@oxidezap/baileyrs 0.3.6 → 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.
Files changed (130) hide show
  1. package/README.md +67 -8
  2. package/lib/Bridge/history-sync-wire.d.ts +2 -2
  3. package/lib/Bridge/history-sync-wire.js +4 -4
  4. package/lib/Bridge/schema.js +7 -1
  5. package/lib/Bridge/types.d.ts +7 -1
  6. package/lib/Compatibility/auth-state.d.ts +30 -0
  7. package/lib/Compatibility/auth-state.js +96 -0
  8. package/lib/Compatibility/encode-proto-core.d.ts +31 -0
  9. package/lib/Compatibility/encode-proto-core.js +51 -0
  10. package/lib/Compatibility/encode-proto.d.ts +0 -19
  11. package/lib/Compatibility/encode-proto.js +3 -35
  12. package/lib/Compatibility/host-auth-state.d.ts +6 -0
  13. package/lib/Compatibility/host-auth-state.js +162 -0
  14. package/lib/Compatibility/internal/auth-state.d.ts +3 -7
  15. package/lib/Compatibility/internal/auth-state.js +34 -1
  16. package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
  17. package/lib/Compatibility/internal/host-auth-state.js +14 -0
  18. package/lib/Compatibility/legacy-store/device.js +5 -5
  19. package/lib/Compatibility/message-ids.d.ts +17 -0
  20. package/lib/Compatibility/message-ids.js +47 -0
  21. package/lib/Compatibility/message-relay.d.ts +2 -2
  22. package/lib/Compatibility/message-relay.js +4 -4
  23. package/lib/Compatibility/proto-runtime.d.ts +5 -0
  24. package/lib/Compatibility/proto-runtime.js +214 -32
  25. package/lib/Compatibility/socket-results.d.ts +1 -1
  26. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  27. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  28. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  29. package/lib/Compatibility/websocket-client.d.ts +11 -3
  30. package/lib/Compatibility/websocket-client.js +84 -11
  31. package/lib/Defaults/index.d.ts +8 -8
  32. package/lib/Defaults/index.js +8 -8
  33. package/lib/Media/content.d.ts +28 -0
  34. package/lib/Media/content.js +129 -0
  35. package/lib/Media/core.d.ts +34 -0
  36. package/lib/Media/core.js +120 -0
  37. package/lib/Media/mutations.d.ts +24 -0
  38. package/lib/Media/mutations.js +38 -0
  39. package/lib/Runtime/aes-gcm.d.ts +4 -0
  40. package/lib/Runtime/aes-gcm.js +11 -0
  41. package/lib/Runtime/bridge.d.ts +44 -0
  42. package/lib/Runtime/bridge.js +76 -0
  43. package/lib/Runtime/buffer.d.ts +9 -0
  44. package/lib/Runtime/buffer.js +22 -0
  45. package/lib/Runtime/bytes.d.ts +61 -0
  46. package/lib/Runtime/bytes.js +270 -0
  47. package/lib/Runtime/host.d.ts +22 -0
  48. package/lib/Runtime/host.js +43 -0
  49. package/lib/Runtime/long.d.ts +33 -0
  50. package/lib/Runtime/long.js +64 -0
  51. package/lib/Runtime/node-media-processors.d.ts +4 -0
  52. package/lib/Runtime/node-media-processors.js +29 -0
  53. package/lib/Runtime/node-media.d.ts +28 -0
  54. package/lib/Runtime/node-media.js +115 -0
  55. package/lib/Runtime/node.d.ts +14 -0
  56. package/lib/Runtime/node.js +81 -0
  57. package/lib/Runtime/paths.d.ts +4 -0
  58. package/lib/Runtime/paths.js +7 -0
  59. package/lib/Runtime/stream.d.ts +11 -0
  60. package/lib/Runtime/stream.js +25 -0
  61. package/lib/Runtime/types.d.ts +98 -0
  62. package/lib/Runtime/types.js +13 -0
  63. package/lib/Socket/core.d.ts +312 -0
  64. package/lib/Socket/core.js +1122 -0
  65. package/lib/Socket/events-core.d.ts +75 -0
  66. package/lib/Socket/events-core.js +1058 -0
  67. package/lib/Socket/events.d.ts +1 -63
  68. package/lib/Socket/events.js +4 -1047
  69. package/lib/Socket/groups.js +4 -3
  70. package/lib/Socket/index.d.ts +521 -103
  71. package/lib/Socket/index.js +10 -1007
  72. package/lib/Socket/messages-core.d.ts +41 -0
  73. package/lib/Socket/messages-core.js +270 -0
  74. package/lib/Socket/messages.d.ts +9 -36
  75. package/lib/Socket/messages.js +3 -260
  76. package/lib/Socket/newsletter.js +3 -3
  77. package/lib/Socket/profile.js +1 -1
  78. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  79. package/lib/Socket/terminal-close-reporter.js +3 -3
  80. package/lib/Socket/transport.d.ts +2 -0
  81. package/lib/Socket/transport.js +16 -1
  82. package/lib/Socket/types.d.ts +2 -0
  83. package/lib/Types/Auth.d.ts +11 -0
  84. package/lib/Types/Message.d.ts +1 -1
  85. package/lib/Types/Socket.d.ts +2 -2
  86. package/lib/Types/index.d.ts +6 -1
  87. package/lib/Utils/browser-utils.d.ts +4 -0
  88. package/lib/Utils/browser-utils.js +53 -2
  89. package/lib/Utils/crypto.d.ts +1 -0
  90. package/lib/Utils/crypto.js +1 -0
  91. package/lib/Utils/event-buffer.d.ts +6 -1
  92. package/lib/Utils/event-buffer.js +28 -27
  93. package/lib/Utils/link-preview.d.ts +4 -3
  94. package/lib/Utils/logger.d.ts +3 -0
  95. package/lib/Utils/logger.js +35 -6
  96. package/lib/Utils/messages-core.d.ts +174 -0
  97. package/lib/Utils/messages-core.js +1042 -0
  98. package/lib/Utils/messages-media-core.d.ts +73 -0
  99. package/lib/Utils/messages-media-core.js +319 -0
  100. package/lib/Utils/messages-media.d.ts +1 -72
  101. package/lib/Utils/messages-media.js +9 -358
  102. package/lib/Utils/messages.d.ts +1 -166
  103. package/lib/Utils/messages.js +7 -1040
  104. package/lib/Utils/optional-peer.js +14 -5
  105. package/lib/Utils/process-history-message-core.d.ts +36 -0
  106. package/lib/Utils/process-history-message-core.js +187 -0
  107. package/lib/Utils/process-history-message.d.ts +5 -43
  108. package/lib/Utils/process-history-message.js +11 -197
  109. package/lib/Utils/process-message-core.d.ts +29 -0
  110. package/lib/Utils/process-message-core.js +112 -0
  111. package/lib/Utils/process-message.d.ts +4 -24
  112. package/lib/Utils/process-message.js +6 -111
  113. package/lib/WABinary/generic-utils.js +7 -5
  114. package/lib/host-shared.d.ts +74 -0
  115. package/lib/host-shared.js +15 -0
  116. package/lib/host-socket-operations.d.ts +3 -0
  117. package/lib/host-socket-operations.js +2 -0
  118. package/lib/host-surface.d.ts +21 -0
  119. package/lib/host-surface.js +35 -0
  120. package/lib/host-types.d.ts +356 -0
  121. package/lib/host-types.js +2 -0
  122. package/lib/host.d.ts +33 -0
  123. package/lib/host.js +31 -0
  124. package/lib/node-surface.d.ts +9 -0
  125. package/lib/node-surface.js +15 -0
  126. package/lib/surface.d.ts +5 -0
  127. package/lib/surface.js +6 -0
  128. package/lib/wasm.d.ts +27 -0
  129. package/lib/wasm.js +27 -0
  130. package/package.json +18 -6
@@ -0,0 +1,41 @@
1
+ import type { AnyMessageContent, MessageGenerationOptions, MessageReceiptType, MessageRelayOptions, WAMessage, WAMessageKey } from '../Types/index.js';
2
+ import { WAProto } from '../Types/index.js';
3
+ import type { BaileysRuntime } from '../Runtime/types.js';
4
+ import type { SocketContext } from './types.js';
5
+ export type EncodeProto = (path: string, message: unknown) => Uint8Array;
6
+ export declare const makeMessageMethodsCore: (ctx: SocketContext, encode: EncodeProto, runtimeLong?: Pick<BaileysRuntime['Long'], 'fromValue'>) => {
7
+ sendMessage: (jid: string, content: AnyMessageContent, options?: Omit<MessageGenerationOptions, 'waClient' | 'logger' | 'userJid' | 'mediaInNote'>) => Promise<WAMessage>;
8
+ updateMediaMessage: (message: WAMessage) => Promise<WAMessage>;
9
+ /**
10
+ * Low-level message relay — sends a raw proto.IMessage with full control
11
+ * over the message ID. Use `sendMessage` for the high-level API that handles
12
+ * media upload, message generation, link previews, etc.
13
+ *
14
+ * Returns the message ID used on the wire.
15
+ *
16
+ * @param jid Recipient JID
17
+ * @param message Raw protobuf Message (snake_case keys)
18
+ * @param options Relay options
19
+ */
20
+ relayMessage: (jid: string, message: WAProto.IMessage, options: MessageRelayOptions) => Promise<string>;
21
+ readMessages: (keys: WAMessageKey[]) => Promise<void>;
22
+ /**
23
+ * Send a receipt for messages. The bridge handles most receipt types automatically
24
+ * (delivered, sender). Use `readMessages` for the common case of sending read receipts.
25
+ *
26
+ * Supported types via bridge: 'read', 'read-self', 'played'
27
+ * Auto-handled by bridge: 'sender', 'inactive', undefined (delivered)
28
+ * Not supported: 'hist_sync', 'peer_msg' (logged as warning)
29
+ */
30
+ sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: MessageReceiptType) => Promise<void>;
31
+ /**
32
+ * Send receipts for multiple message keys, grouped by JID and participant.
33
+ */
34
+ sendReceipts: (keys: WAMessageKey[], type: MessageReceiptType) => Promise<void>;
35
+ /**
36
+ * Request resend of a placeholder message via PeerDataOperationRequest.
37
+ * Wraps the request in a protocolMessage and relays it to the chat.
38
+ */
39
+ requestPlaceholderResend: (messageKey: WAMessageKey, msgData?: Partial<WAMessage>) => Promise<string | undefined>;
40
+ };
41
+ //# sourceMappingURL=messages-core.d.ts.map
@@ -0,0 +1,270 @@
1
+ import { sendReportingUpstreamFailure } from '../Compatibility/all-encryptions-failed.js';
2
+ import { sendDroppingDerivedNodes } from '../Compatibility/derived-stanza-nodes.js';
3
+ import { EMPTY_RELAY_NODES, planMessageRelay, resolveMessageId } from '../Compatibility/message-relay.js';
4
+ import { receiptMessageKeys } from '../Compatibility/message-keys.js';
5
+ import { MESSAGE_RECEIPT_TYPES, WAProto } from '../Types/index.js';
6
+ import { randomBytes } from '../Runtime/bytes.js';
7
+ import { assertArgumentDomain } from '../Utils/argument-domain.js';
8
+ import { Boom } from '../Utils/boom.js';
9
+ import { generateWAMessage, getContentType, normalizeMessageContent } from '../Utils/messages-core.js';
10
+ import { jidNormalizedUser } from '../WABinary/index.js';
11
+ /** Extract the media content from a WAMessage (image, video, audio, document, sticker) */
12
+ function getMediaContent(content) {
13
+ return (content?.imageMessage ||
14
+ content?.videoMessage ||
15
+ content?.audioMessage ||
16
+ content?.documentMessage ||
17
+ content?.stickerMessage);
18
+ }
19
+ const normalizedUserJids = new WeakMap();
20
+ const getNormalizedUserJid = (ctx) => {
21
+ const userId = ctx.getUser()?.id;
22
+ if (!userId)
23
+ return undefined;
24
+ const cached = normalizedUserJids.get(ctx);
25
+ if (cached?.userId === userId)
26
+ return cached.jid;
27
+ const jid = jidNormalizedUser(userId);
28
+ normalizedUserJids.set(ctx, { userId, jid });
29
+ return jid;
30
+ };
31
+ export const makeMessageMethodsCore = (ctx, encode, runtimeLong) => {
32
+ const randomSource = ctx.randomBytes ?? randomBytes;
33
+ return {
34
+ sendMessage: async (jid, content, options) => {
35
+ return ctx.withClient(async (client) => {
36
+ const userJid = getNormalizedUserJid(ctx) ?? '';
37
+ // SocketConfig contains transport/auth/cache state that message
38
+ // generation neither reads nor owns. Copying all of it here retained a
39
+ // large object graph and repeated dozens of property writes per send.
40
+ // `options` is the one generation default shared with the socket; every
41
+ // other generation knob belongs to this call's typed options.
42
+ const generationOptions = {
43
+ ...options,
44
+ runtimeRandomBytes: randomSource,
45
+ ...(runtimeLong ? { runtimeLong } : {}),
46
+ options: options?.options ?? ctx.fullConfig.options,
47
+ logger: ctx.logger,
48
+ userJid,
49
+ waClient: client
50
+ };
51
+ const fullMsg = await generateWAMessage(jid, content, generationOptions);
52
+ const msg = normalizeMessageContent(fullMsg.message);
53
+ if (!msg)
54
+ throw new Boom('Failed to generate message content', { statusCode: 400 });
55
+ const contentType = getContentType(msg);
56
+ if (contentType === 'protocolMessage') {
57
+ const protoMsg = msg.protocolMessage;
58
+ if (protoMsg?.type === WAProto.Message.ProtocolMessage.Type.REVOKE && protoMsg?.key?.id) {
59
+ if (options?.messageId) {
60
+ // The core has no revoke variant that takes a stanza id, so
61
+ // the option cannot be honoured here. Saying so beats the
62
+ // silent drop this option used to get on every path.
63
+ ctx.logger.warn({ jid, messageId: options.messageId }, 'messageId option cannot be honoured for a revoke: the core assigns the stanza id itself');
64
+ }
65
+ // Group revokes need the original sender's participant JID —
66
+ // without it the server rejects the revoke. The bridge
67
+ // signature is `revokeMessage(jid, message_id, participant?)`.
68
+ // Caller passes participant via `message.delete.participant`
69
+ // which lands on `protoMsg.key.participant` in the generated
70
+ // proto.
71
+ await client.revokeMessage(jid, protoMsg.key.id, protoMsg.key.participant ?? null);
72
+ return fullMsg;
73
+ }
74
+ if (protoMsg?.type === WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT &&
75
+ protoMsg?.key?.id &&
76
+ protoMsg?.editedMessage) {
77
+ const editBytes = WAProto.Message.encode(protoMsg.editedMessage).finish();
78
+ // Edit-path counterpart of `options.messageId` on a plain send, and
79
+ // deliberately not `resolveMessageId`: the engine treats any supplied
80
+ // stanza id as borrowed and binds no id-keyed state to it, so an edit
81
+ // nobody asked to pin would silently lose its retry-cache entry and
82
+ // outbound secret. Absent stays absent. `||` and not `??` because an
83
+ // empty id means unspecified everywhere else in this API.
84
+ const editStanzaId = options?.messageId || undefined;
85
+ const newMsgId = await client.editMessageBytes(jid, protoMsg.key.id, editBytes, editStanzaId);
86
+ fullMsg.key.id = newMsgId || fullMsg.key.id;
87
+ return fullMsg;
88
+ }
89
+ }
90
+ const msgBytes = encode('Message', msg);
91
+ // The with-options sends are the same core send as the plain ones, with
92
+ // the stanza id supplied by the caller instead of drawn by the engine.
93
+ // The id resolves through the same place `relayMessage` resolves it.
94
+ const messageId = resolveMessageId(ctx.getUser(), options?.messageId, randomSource);
95
+ const msgId = await sendReportingUpstreamFailure(() => jid === 'status@broadcast' && options?.statusJidList?.length
96
+ ? client.sendStatusMessageBytesWithOptions(msgBytes, options.statusJidList, messageId, EMPTY_RELAY_NODES, false)
97
+ : client.relayMessageBytesWithOptions(jid, msgBytes, messageId, EMPTY_RELAY_NODES, false, false));
98
+ fullMsg.key.id = msgId || fullMsg.key.id;
99
+ // Local echo of the message we just sent. Suppressed when
100
+ // `emitOwnEvents=false` so callers that explicitly opted out of seeing
101
+ // their own outbound messages don't get them looped back. This is the
102
+ // upstream-Baileys semantics of `emitOwnEvents` — it controls THIS
103
+ // echo, not inbound `fromMe` messages from other linked devices.
104
+ if (ctx.fullConfig.emitOwnEvents !== false) {
105
+ ctx.ev.emit('messages.upsert', {
106
+ messages: [fullMsg],
107
+ type: 'append'
108
+ });
109
+ }
110
+ return fullMsg;
111
+ });
112
+ },
113
+ updateMediaMessage: async (message) => {
114
+ return ctx.withClient(async (client) => {
115
+ const content = normalizeMessageContent(message.message);
116
+ const mediaContent = getMediaContent(content);
117
+ if (!mediaContent) {
118
+ throw new Boom('Not a media message', { statusCode: 400 });
119
+ }
120
+ const mediaKey = mediaContent.mediaKey;
121
+ if (!mediaKey) {
122
+ throw new Boom('Message has no media key', { statusCode: 400 });
123
+ }
124
+ const key = message.key;
125
+ if (!key.id || !key.remoteJid)
126
+ throw new Boom('Media message key requires id and remoteJid', { statusCode: 400 });
127
+ const newDirectPath = await client.requestMediaReupload(key.id, key.remoteJid, mediaKey instanceof Uint8Array ? mediaKey : new Uint8Array(mediaKey), !!key.fromMe, key.participant ?? null);
128
+ // Update the message with the new direct path
129
+ // (download uses directPath via Rust bridge, url is informational)
130
+ mediaContent.directPath = newDirectPath;
131
+ ctx.logger.debug({ directPath: newDirectPath, msgId: key.id }, 'media reupload successful');
132
+ ctx.ev.emit('messages.update', [
133
+ {
134
+ key: message.key,
135
+ update: { message: message.message }
136
+ }
137
+ ]);
138
+ return message;
139
+ });
140
+ },
141
+ /**
142
+ * Low-level message relay — sends a raw proto.IMessage with full control
143
+ * over the message ID. Use `sendMessage` for the high-level API that handles
144
+ * media upload, message generation, link previews, etc.
145
+ *
146
+ * Returns the message ID used on the wire.
147
+ *
148
+ * @param jid Recipient JID
149
+ * @param message Raw protobuf Message (snake_case keys)
150
+ * @param options Relay options
151
+ */
152
+ relayMessage: async (jid, message, options) => {
153
+ return ctx.withClient(async (client) => {
154
+ const plan = planMessageRelay(jid, options, ctx.getUser(), randomSource);
155
+ ctx.logger.debug({
156
+ jid,
157
+ kind: plan.kind,
158
+ messageId: plan.messageId,
159
+ extraNodes: plan.kind === 'retransmission' ? 0 : plan.nodes.length
160
+ }, 'relayMessage compatibility plan');
161
+ // The message goes to the bridge as the caller built it: the core settles
162
+ // messageSecret / reportingTokenVersion itself, reusing a caller-set secret
163
+ // rather than replacing it, so nothing here has to be dropped.
164
+ const bytes = encode('Message', message);
165
+ if (plan.kind === 'retransmission') {
166
+ await client.retransmitMessageBytes(jid, bytes, plan.input);
167
+ return plan.messageId;
168
+ }
169
+ // Both sends go through the same retry: a caller node the engine derives
170
+ // is refused the same way whether the message is bound for a chat or for
171
+ // status, and the escape hatch — a node it does not derive — survives
172
+ // either way.
173
+ const drop = (tag) => ctx.logger.debug({ jid, messageId: plan.messageId, tag }, 'dropped an additionalNodes entry the engine derives from the message');
174
+ if (plan.kind === 'status') {
175
+ return sendReportingUpstreamFailure(() => sendDroppingDerivedNodes(plan.nodes, nodes => client.sendStatusMessageBytesWithOptions(bytes, plan.recipients, plan.messageId, nodes, plan.refreshDevices), drop));
176
+ }
177
+ return sendReportingUpstreamFailure(() => sendDroppingDerivedNodes(plan.nodes, nodes => client.relayMessageBytesWithOptions(jid, bytes, plan.messageId, nodes, plan.refreshGroupMetadata, plan.refreshDevices), drop));
178
+ });
179
+ },
180
+ readMessages: async (keys) => {
181
+ const receiptKeys = receiptMessageKeys(keys);
182
+ if (receiptKeys.length)
183
+ await ctx.withClient(client => client.readMessages(receiptKeys));
184
+ },
185
+ /**
186
+ * Send a receipt for messages. The bridge handles most receipt types automatically
187
+ * (delivered, sender). Use `readMessages` for the common case of sending read receipts.
188
+ *
189
+ * Supported types via bridge: 'read', 'read-self', 'played'
190
+ * Auto-handled by bridge: 'sender', 'inactive', undefined (delivered)
191
+ * Not supported: 'hist_sync', 'peer_msg' (logged as warning)
192
+ */
193
+ sendReceipt: async (jid, participant, messageIds, type) => {
194
+ // Ahead of the empty-list exit: the types this method handles elsewhere
195
+ // resolve without sending anything, so a typo looked like a no-op.
196
+ assertArgumentDomain('sendReceipt', 'type', type, MESSAGE_RECEIPT_TYPES);
197
+ if (!messageIds.length)
198
+ return;
199
+ if (type === 'read' || type === 'read-self') {
200
+ const keys = messageIds.map(id => ({
201
+ remoteJid: jid,
202
+ id,
203
+ ...(participant ? { participant } : {})
204
+ }));
205
+ await ctx.withClient(client => client.readMessages(keys));
206
+ }
207
+ else if (type === 'played') {
208
+ // Voice/video-note played receipts. The bridge (and core) pick the wire
209
+ // type (`played` vs `played-self` for newsletters) and the `participant`
210
+ // attr from the chat jid, so we just hand over the keys — same shape as
211
+ // readMessages.
212
+ const keys = messageIds.map(id => ({
213
+ remoteJid: jid,
214
+ id,
215
+ ...(participant ? { participant } : {})
216
+ }));
217
+ await ctx.withClient(client => client.markPlayed(keys));
218
+ }
219
+ else {
220
+ // delivered/sender/inactive receipts are sent automatically by the Rust bridge
221
+ // hist_sync/peer_msg require bridge-side support
222
+ ctx.logger.debug({ type, jid, count: messageIds.length }, 'sendReceipt: type handled automatically by bridge or not yet supported');
223
+ }
224
+ },
225
+ /**
226
+ * Send receipts for multiple message keys, grouped by JID and participant.
227
+ */
228
+ sendReceipts: async (keys, type) => {
229
+ assertArgumentDomain('sendReceipts', 'type', type, MESSAGE_RECEIPT_TYPES);
230
+ return ctx.withClient(async (client) => {
231
+ const receiptKeys = receiptMessageKeys(keys);
232
+ if (type === 'read' || type === 'read-self') {
233
+ if (receiptKeys.length) {
234
+ await client.readMessages(receiptKeys);
235
+ }
236
+ }
237
+ else if (type === 'played') {
238
+ if (receiptKeys.length) {
239
+ await client.markPlayed(receiptKeys);
240
+ }
241
+ }
242
+ else {
243
+ ctx.logger.debug({ type, count: keys.length }, 'sendReceipts: type handled automatically by bridge or not yet supported');
244
+ }
245
+ });
246
+ },
247
+ /**
248
+ * Request resend of a placeholder message via PeerDataOperationRequest.
249
+ * Wraps the request in a protocolMessage and relays it to the chat.
250
+ */
251
+ requestPlaceholderResend: async (messageKey, msgData) => {
252
+ void msgData;
253
+ const message = {
254
+ protocolMessage: {
255
+ peerDataOperationRequestMessage: {
256
+ peerDataOperationRequestType: WAProto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND,
257
+ placeholderMessageResendRequest: [{ messageKey }]
258
+ },
259
+ type: WAProto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
260
+ }
261
+ };
262
+ const remoteJid = messageKey.remoteJid;
263
+ if (!remoteJid)
264
+ throw new Boom('Placeholder resend requires remoteJid', { statusCode: 400 });
265
+ const bytes = encode('Message', message);
266
+ return ctx.withClient(client => client.relayMessageBytes(remoteJid, bytes, null));
267
+ }
268
+ };
269
+ };
270
+ //# sourceMappingURL=messages-core.js.map
@@ -1,39 +1,12 @@
1
- import type { AnyMessageContent, MessageGenerationOptions, MessageReceiptType, MessageRelayOptions, WAMessage, WAMessageKey } from '../Types/index.js';
2
- import { WAProto } from '../Types/index.js';
1
+ import { type EncodeProto } from './messages-core.js';
3
2
  import type { SocketContext } from './types.js';
4
- export declare const makeMessageMethods: (ctx: SocketContext) => {
5
- sendMessage: (jid: string, content: AnyMessageContent, options?: Omit<MessageGenerationOptions, 'waClient' | 'logger' | 'userJid' | 'mediaInNote'>) => Promise<WAMessage>;
6
- updateMediaMessage: (message: WAMessage) => Promise<WAMessage>;
7
- /**
8
- * Low-level message relay — sends a raw proto.IMessage with full control
9
- * over the message ID. Use `sendMessage` for the high-level API that handles
10
- * media upload, message generation, link previews, etc.
11
- *
12
- * Returns the message ID used on the wire.
13
- *
14
- * @param jid Recipient JID
15
- * @param message Raw protobuf Message (snake_case keys)
16
- * @param options Relay options
17
- */
18
- relayMessage: (jid: string, message: WAProto.IMessage, options: MessageRelayOptions) => Promise<string>;
19
- readMessages: (keys: WAMessageKey[]) => Promise<void>;
20
- /**
21
- * Send a receipt for messages. The bridge handles most receipt types automatically
22
- * (delivered, sender). Use `readMessages` for the common case of sending read receipts.
23
- *
24
- * Supported types via bridge: 'read', 'read-self', 'played'
25
- * Auto-handled by bridge: 'sender', 'inactive', undefined (delivered)
26
- * Not supported: 'hist_sync', 'peer_msg' (logged as warning)
27
- */
28
- sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: MessageReceiptType) => Promise<void>;
29
- /**
30
- * Send receipts for multiple message keys, grouped by JID and participant.
31
- */
32
- sendReceipts: (keys: WAMessageKey[], type: MessageReceiptType) => Promise<void>;
33
- /**
34
- * Request resend of a placeholder message via PeerDataOperationRequest.
35
- * Wraps the request in a protocolMessage and relays it to the chat.
36
- */
37
- requestPlaceholderResend: (messageKey: WAMessageKey, msgData?: Partial<WAMessage>) => Promise<string | undefined>;
3
+ export declare const makeMessageMethods: (ctx: SocketContext, encode?: EncodeProto) => {
4
+ sendMessage: (jid: string, content: import("../index.js").AnyMessageContent, options?: Omit<import("../index.js").MessageGenerationOptions, 'waClient' | 'logger' | 'userJid' | 'mediaInNote'>) => Promise<import("../index.js").WAMessage>;
5
+ updateMediaMessage: (message: import("../index.js").WAMessage) => Promise<import("../index.js").WAMessage>;
6
+ relayMessage: (jid: string, message: import("@oxidezap/whatsapp-rust-bridge/proto-types").proto.IMessage, options: import("../index.js").MessageRelayOptions) => Promise<string>;
7
+ readMessages: (keys: import("../index.js").WAMessageKey[]) => Promise<void>;
8
+ sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: import("../index.js").MessageReceiptType) => Promise<void>;
9
+ sendReceipts: (keys: import("../index.js").WAMessageKey[], type: import("../index.js").MessageReceiptType) => Promise<void>;
10
+ requestPlaceholderResend: (messageKey: import("../index.js").WAMessageKey, msgData?: Partial<import("../index.js").WAMessage>) => Promise<string | undefined>;
38
11
  };
39
12
  //# sourceMappingURL=messages.d.ts.map
@@ -1,262 +1,5 @@
1
- import { sendReportingUpstreamFailure } from '../Compatibility/all-encryptions-failed.js';
2
- import { sendDroppingDerivedNodes } from '../Compatibility/derived-stanza-nodes.js';
1
+ /** Node-facing socket message methods; preserves the historical deep-import default codec. */
3
2
  import { encodeProtoCompat } from '../Compatibility/encode-proto.js';
4
- import { EMPTY_RELAY_NODES, planMessageRelay, resolveMessageId } from '../Compatibility/message-relay.js';
5
- import { receiptMessageKeys } from '../Compatibility/message-keys.js';
6
- import { MESSAGE_RECEIPT_TYPES, WAProto } from '../Types/index.js';
7
- import { assertArgumentDomain } from '../Utils/argument-domain.js';
8
- import { Boom } from '../Utils/boom.js';
9
- import { generateWAMessage, getContentType, normalizeMessageContent } from '../Utils/messages.js';
10
- import { jidNormalizedUser } from '../WABinary/index.js';
11
- /** Extract the media content from a WAMessage (image, video, audio, document, sticker) */
12
- function getMediaContent(content) {
13
- return (content?.imageMessage ||
14
- content?.videoMessage ||
15
- content?.audioMessage ||
16
- content?.documentMessage ||
17
- content?.stickerMessage);
18
- }
19
- const normalizedUserJids = new WeakMap();
20
- const getNormalizedUserJid = (ctx) => {
21
- const userId = ctx.getUser()?.id;
22
- if (!userId)
23
- return undefined;
24
- const cached = normalizedUserJids.get(ctx);
25
- if (cached?.userId === userId)
26
- return cached.jid;
27
- const jid = jidNormalizedUser(userId);
28
- normalizedUserJids.set(ctx, { userId, jid });
29
- return jid;
30
- };
31
- export const makeMessageMethods = (ctx) => {
32
- return {
33
- sendMessage: async (jid, content, options) => {
34
- return ctx.withClient(async (client) => {
35
- const userJid = getNormalizedUserJid(ctx) ?? '';
36
- // SocketConfig contains transport/auth/cache state that message
37
- // generation neither reads nor owns. Copying all of it here retained a
38
- // large object graph and repeated dozens of property writes per send.
39
- // `options` is the one generation default shared with the socket; every
40
- // other generation knob belongs to this call's typed options.
41
- const generationOptions = {
42
- ...options,
43
- options: options?.options ?? ctx.fullConfig.options,
44
- logger: ctx.logger,
45
- userJid,
46
- waClient: client
47
- };
48
- const fullMsg = await generateWAMessage(jid, content, generationOptions);
49
- const msg = normalizeMessageContent(fullMsg.message);
50
- if (!msg)
51
- throw new Boom('Failed to generate message content', { statusCode: 400 });
52
- const contentType = getContentType(msg);
53
- if (contentType === 'protocolMessage') {
54
- const protoMsg = msg.protocolMessage;
55
- if (protoMsg?.type === WAProto.Message.ProtocolMessage.Type.REVOKE && protoMsg?.key?.id) {
56
- if (options?.messageId) {
57
- // The core has no revoke variant that takes a stanza id, so
58
- // the option cannot be honoured here. Saying so beats the
59
- // silent drop this option used to get on every path.
60
- ctx.logger.warn({ jid, messageId: options.messageId }, 'messageId option cannot be honoured for a revoke: the core assigns the stanza id itself');
61
- }
62
- // Group revokes need the original sender's participant JID —
63
- // without it the server rejects the revoke. The bridge
64
- // signature is `revokeMessage(jid, message_id, participant?)`.
65
- // Caller passes participant via `message.delete.participant`
66
- // which lands on `protoMsg.key.participant` in the generated
67
- // proto.
68
- await client.revokeMessage(jid, protoMsg.key.id, protoMsg.key.participant ?? null);
69
- return fullMsg;
70
- }
71
- if (protoMsg?.type === WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT &&
72
- protoMsg?.key?.id &&
73
- protoMsg?.editedMessage) {
74
- const editBytes = WAProto.Message.encode(protoMsg.editedMessage).finish();
75
- // Edit-path counterpart of `options.messageId` on a plain send, and
76
- // deliberately not `resolveMessageId`: the engine treats any supplied
77
- // stanza id as borrowed and binds no id-keyed state to it, so an edit
78
- // nobody asked to pin would silently lose its retry-cache entry and
79
- // outbound secret. Absent stays absent. `||` and not `??` because an
80
- // empty id means unspecified everywhere else in this API.
81
- const editStanzaId = options?.messageId || undefined;
82
- const newMsgId = await client.editMessageBytes(jid, protoMsg.key.id, editBytes, editStanzaId);
83
- fullMsg.key.id = newMsgId || fullMsg.key.id;
84
- return fullMsg;
85
- }
86
- }
87
- const msgBytes = encodeProtoCompat('Message', msg);
88
- // The with-options sends are the same core send as the plain ones, with
89
- // the stanza id supplied by the caller instead of drawn by the engine.
90
- // The id resolves through the same place `relayMessage` resolves it.
91
- const messageId = resolveMessageId(ctx.getUser(), options?.messageId);
92
- const msgId = await sendReportingUpstreamFailure(() => jid === 'status@broadcast' && options?.statusJidList?.length
93
- ? client.sendStatusMessageBytesWithOptions(msgBytes, options.statusJidList, messageId, EMPTY_RELAY_NODES, false)
94
- : client.relayMessageBytesWithOptions(jid, msgBytes, messageId, EMPTY_RELAY_NODES, false, false));
95
- fullMsg.key.id = msgId || fullMsg.key.id;
96
- // Local echo of the message we just sent. Suppressed when
97
- // `emitOwnEvents=false` so callers that explicitly opted out of seeing
98
- // their own outbound messages don't get them looped back. This is the
99
- // upstream-Baileys semantics of `emitOwnEvents` — it controls THIS
100
- // echo, not inbound `fromMe` messages from other linked devices.
101
- if (ctx.fullConfig.emitOwnEvents !== false) {
102
- ctx.ev.emit('messages.upsert', {
103
- messages: [fullMsg],
104
- type: 'append'
105
- });
106
- }
107
- return fullMsg;
108
- });
109
- },
110
- updateMediaMessage: async (message) => {
111
- return ctx.withClient(async (client) => {
112
- const content = normalizeMessageContent(message.message);
113
- const mediaContent = getMediaContent(content);
114
- if (!mediaContent) {
115
- throw new Boom('Not a media message', { statusCode: 400 });
116
- }
117
- const mediaKey = mediaContent.mediaKey;
118
- if (!mediaKey) {
119
- throw new Boom('Message has no media key', { statusCode: 400 });
120
- }
121
- const key = message.key;
122
- const newDirectPath = await client.requestMediaReupload(key.id, key.remoteJid, mediaKey instanceof Uint8Array ? mediaKey : new Uint8Array(mediaKey), !!key.fromMe, key.participant ?? null);
123
- // Update the message with the new direct path
124
- // (download uses directPath via Rust bridge, url is informational)
125
- mediaContent.directPath = newDirectPath;
126
- ctx.logger.debug({ directPath: newDirectPath, msgId: key.id }, 'media reupload successful');
127
- ctx.ev.emit('messages.update', [
128
- {
129
- key: message.key,
130
- update: { message: message.message }
131
- }
132
- ]);
133
- return message;
134
- });
135
- },
136
- /**
137
- * Low-level message relay — sends a raw proto.IMessage with full control
138
- * over the message ID. Use `sendMessage` for the high-level API that handles
139
- * media upload, message generation, link previews, etc.
140
- *
141
- * Returns the message ID used on the wire.
142
- *
143
- * @param jid Recipient JID
144
- * @param message Raw protobuf Message (snake_case keys)
145
- * @param options Relay options
146
- */
147
- relayMessage: async (jid, message, options) => {
148
- return ctx.withClient(async (client) => {
149
- const plan = planMessageRelay(jid, options, ctx.getUser());
150
- ctx.logger.debug({
151
- jid,
152
- kind: plan.kind,
153
- messageId: plan.messageId,
154
- extraNodes: plan.kind === 'retransmission' ? 0 : plan.nodes.length
155
- }, 'relayMessage compatibility plan');
156
- // The message goes to the bridge as the caller built it: the core settles
157
- // messageSecret / reportingTokenVersion itself, reusing a caller-set secret
158
- // rather than replacing it, so nothing here has to be dropped.
159
- const bytes = encodeProtoCompat('Message', message);
160
- if (plan.kind === 'retransmission') {
161
- await client.retransmitMessageBytes(jid, bytes, plan.input);
162
- return plan.messageId;
163
- }
164
- // Both sends go through the same retry: a caller node the engine derives
165
- // is refused the same way whether the message is bound for a chat or for
166
- // status, and the escape hatch — a node it does not derive — survives
167
- // either way.
168
- const drop = (tag) => ctx.logger.debug({ jid, messageId: plan.messageId, tag }, 'dropped an additionalNodes entry the engine derives from the message');
169
- if (plan.kind === 'status') {
170
- return sendReportingUpstreamFailure(() => sendDroppingDerivedNodes(plan.nodes, nodes => client.sendStatusMessageBytesWithOptions(bytes, plan.recipients, plan.messageId, nodes, plan.refreshDevices), drop));
171
- }
172
- return sendReportingUpstreamFailure(() => sendDroppingDerivedNodes(plan.nodes, nodes => client.relayMessageBytesWithOptions(jid, bytes, plan.messageId, nodes, plan.refreshGroupMetadata, plan.refreshDevices), drop));
173
- });
174
- },
175
- readMessages: async (keys) => {
176
- const receiptKeys = receiptMessageKeys(keys);
177
- if (receiptKeys.length)
178
- await ctx.withClient(client => client.readMessages(receiptKeys));
179
- },
180
- /**
181
- * Send a receipt for messages. The bridge handles most receipt types automatically
182
- * (delivered, sender). Use `readMessages` for the common case of sending read receipts.
183
- *
184
- * Supported types via bridge: 'read', 'read-self', 'played'
185
- * Auto-handled by bridge: 'sender', 'inactive', undefined (delivered)
186
- * Not supported: 'hist_sync', 'peer_msg' (logged as warning)
187
- */
188
- sendReceipt: async (jid, participant, messageIds, type) => {
189
- // Ahead of the empty-list exit: the types this method handles elsewhere
190
- // resolve without sending anything, so a typo looked like a no-op.
191
- assertArgumentDomain('sendReceipt', 'type', type, MESSAGE_RECEIPT_TYPES);
192
- if (!messageIds.length)
193
- return;
194
- if (type === 'read' || type === 'read-self') {
195
- const keys = messageIds.map(id => ({
196
- remoteJid: jid,
197
- id,
198
- ...(participant ? { participant } : {})
199
- }));
200
- await ctx.withClient(client => client.readMessages(keys));
201
- }
202
- else if (type === 'played') {
203
- // Voice/video-note played receipts. The bridge (and core) pick the wire
204
- // type (`played` vs `played-self` for newsletters) and the `participant`
205
- // attr from the chat jid, so we just hand over the keys — same shape as
206
- // readMessages.
207
- const keys = messageIds.map(id => ({
208
- remoteJid: jid,
209
- id,
210
- ...(participant ? { participant } : {})
211
- }));
212
- await ctx.withClient(client => client.markPlayed(keys));
213
- }
214
- else {
215
- // delivered/sender/inactive receipts are sent automatically by the Rust bridge
216
- // hist_sync/peer_msg require bridge-side support
217
- ctx.logger.debug({ type, jid, count: messageIds.length }, 'sendReceipt: type handled automatically by bridge or not yet supported');
218
- }
219
- },
220
- /**
221
- * Send receipts for multiple message keys, grouped by JID and participant.
222
- */
223
- sendReceipts: async (keys, type) => {
224
- assertArgumentDomain('sendReceipts', 'type', type, MESSAGE_RECEIPT_TYPES);
225
- return ctx.withClient(async (client) => {
226
- const receiptKeys = receiptMessageKeys(keys);
227
- if (type === 'read' || type === 'read-self') {
228
- if (receiptKeys.length) {
229
- await client.readMessages(receiptKeys);
230
- }
231
- }
232
- else if (type === 'played') {
233
- if (receiptKeys.length) {
234
- await client.markPlayed(receiptKeys);
235
- }
236
- }
237
- else {
238
- ctx.logger.debug({ type, count: keys.length }, 'sendReceipts: type handled automatically by bridge or not yet supported');
239
- }
240
- });
241
- },
242
- /**
243
- * Request resend of a placeholder message via PeerDataOperationRequest.
244
- * Wraps the request in a protocolMessage and relays it to the chat.
245
- */
246
- requestPlaceholderResend: async (messageKey, msgData) => {
247
- void msgData;
248
- const message = {
249
- protocolMessage: {
250
- peerDataOperationRequestMessage: {
251
- peerDataOperationRequestType: WAProto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND,
252
- placeholderMessageResendRequest: [{ messageKey }]
253
- },
254
- type: WAProto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
255
- }
256
- };
257
- const bytes = encodeProtoCompat('Message', message);
258
- return ctx.withClient(client => client.relayMessageBytes(messageKey.remoteJid, bytes, null));
259
- }
260
- };
261
- };
3
+ import { makeMessageMethodsCore } from './messages-core.js';
4
+ export const makeMessageMethods = (ctx, encode = encodeProtoCompat) => makeMessageMethodsCore(ctx, encode);
262
5
  //# sourceMappingURL=messages.js.map
@@ -1,8 +1,8 @@
1
- import { Buffer } from 'node:buffer';
1
+ import { BufferRuntime } from '../Runtime/buffer.js';
2
2
  import { bridgeNewsletterMetadataToBaileys } from '../Compatibility/newsletter-results.js';
3
3
  import { assertArgumentDomain } from '../Utils/argument-domain.js';
4
4
  import { Boom } from '../Utils/boom.js';
5
- import { generateProfilePicture } from '../Utils/messages-media.js';
5
+ import { generateProfilePicture } from '../Utils/messages-media-core.js';
6
6
  export const NEWSLETTER_KEY_TYPES = ['invite', 'jid'];
7
7
  export const makeNewsletterMethods = (ctx) => {
8
8
  return {
@@ -36,7 +36,7 @@ export const makeNewsletterMethods = (ctx) => {
36
36
  result = await client.newsletterRemovePicture(jid);
37
37
  }
38
38
  else if (updates.picture !== undefined) {
39
- result = await client.newsletterSetPicture(jid, new Uint8Array(Buffer.from(updates.picture, 'base64')));
39
+ result = await client.newsletterSetPicture(jid, BufferRuntime.from(updates.picture, 'base64'));
40
40
  }
41
41
  // Only when the delta asked for nothing: every write above already
42
42
  // answers with the refreshed metadata, so reading it would be a round