@x4r1s3/baileys 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1262 -2
- package/SECURITY.md +47 -0
- package/WAProto/V +1 -0
- package/WAProto/WAProto.proto +8892 -0
- package/WAProto/index.d.ts +104128 -0
- package/WAProto/index.js +334920 -0
- package/assets/rolling-circle.svg +133 -0
- package/assets/x4r1s3-banner.svg +32 -0
- package/engine-requirements.js +27 -0
- package/lib/Builders/A2UI.js +245 -0
- package/lib/Builders/AIRich.js +179 -0
- package/lib/Builders/Button.js +108 -0
- package/lib/Builders/CFC.js +284 -0
- package/lib/Builders/Carousel.js +81 -0
- package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
- package/lib/Call/audio-feeder.mjs +179 -0
- package/lib/Call/audio-recorder.mjs +250 -0
- package/lib/Call/fetch-wasm-resources.mjs +104 -0
- package/lib/Call/index.mjs +680 -0
- package/lib/Call/relay-transport.mjs +563 -0
- package/lib/Call/signaling.mjs +641 -0
- package/lib/Call/types.mjs +17 -0
- package/lib/Call/video-feeder.mjs +94 -0
- package/lib/Call/wasm-engine.mjs +1372 -0
- package/lib/Call/worker-bootstrap.mjs +1042 -0
- package/lib/Defaults/ban-checker.js +56 -0
- package/lib/Defaults/index.js +170 -0
- package/lib/Signal/Group/ciphertext-message.js +23 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +93 -0
- package/lib/Signal/Group/index.js +23 -0
- package/lib/Signal/Group/keyhelper.js +29 -0
- package/lib/Signal/Group/sender-chain-key.js +37 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
- package/lib/Signal/Group/sender-key-message.js +77 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.js +52 -0
- package/lib/Signal/Group/sender-key-state.js +95 -0
- package/lib/Signal/Group/sender-message-key.js +37 -0
- package/lib/Signal/libsignal.js +440 -0
- package/lib/Signal/lid-mapping.js +292 -0
- package/lib/Socket/Client/index.js +14 -0
- package/lib/Socket/Client/types.js +22 -0
- package/lib/Socket/Client/websocket.js +65 -0
- package/lib/Socket/aigroups.js +327 -0
- package/lib/Socket/ban-checker.js +165 -0
- package/lib/Socket/business.js +419 -0
- package/lib/Socket/chats.js +1921 -0
- package/lib/Socket/communities.js +443 -0
- package/lib/Socket/graphql.js +911 -0
- package/lib/Socket/groups.js +561 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interactive-handler.js +612 -0
- package/lib/Socket/interop.js +575 -0
- package/lib/Socket/managed-account.js +220 -0
- package/lib/Socket/messages-recv.js +2191 -0
- package/lib/Socket/messages-send.js +4104 -0
- package/lib/Socket/mex.js +53 -0
- package/lib/Socket/newsletter.js +291 -0
- package/lib/Socket/privacy.js +458 -0
- package/lib/Socket/registration.js +440 -0
- package/lib/Socket/socket.js +1029 -0
- package/lib/Socket/status-actions.js +287 -0
- package/lib/Socket/username.js +241 -0
- package/lib/Store/index.js +16 -0
- package/lib/Store/make-cache-manager-store.js +101 -0
- package/lib/Store/make-in-memory-store.js +432 -0
- package/lib/Store/make-ordered-dictionary.js +90 -0
- package/lib/Store/object-repository.js +35 -0
- package/lib/Types/Auth.js +13 -0
- package/lib/Types/Bussines.js +13 -0
- package/lib/Types/Call.js +13 -0
- package/lib/Types/Chat.js +19 -0
- package/lib/Types/Contact.js +13 -0
- package/lib/Types/Events.js +13 -0
- package/lib/Types/GroupMetadata.js +13 -0
- package/lib/Types/Label.js +36 -0
- package/lib/Types/LabelAssociation.js +18 -0
- package/lib/Types/Message.js +30 -0
- package/lib/Types/Mex.js +53 -0
- package/lib/Types/Product.js +13 -0
- package/lib/Types/RichType.js +34 -0
- package/lib/Types/Signal.js +13 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +60 -0
- package/lib/Types/USync.js +13 -0
- package/lib/Types/index.js +37 -0
- package/lib/Utils/auth-utils.js +313 -0
- package/lib/Utils/ban-checker.js +48 -0
- package/lib/Utils/bot-capabilities.js +96 -0
- package/lib/Utils/bot-planning-replay.js +177 -0
- package/lib/Utils/browser-utils.js +40 -0
- package/lib/Utils/business.js +242 -0
- package/lib/Utils/c2582.js +147 -0
- package/lib/Utils/chat-utils.js +905 -0
- package/lib/Utils/companion-reg-client-utils.js +44 -0
- package/lib/Utils/consumer-application.js +114 -0
- package/lib/Utils/crypto.js +129 -0
- package/lib/Utils/decode-wa-message.js +496 -0
- package/lib/Utils/direct-chat-theme.js +164 -0
- package/lib/Utils/event-buffer.js +601 -0
- package/lib/Utils/experimental-proto.js +206 -0
- package/lib/Utils/games/miniapp.js +17 -0
- package/lib/Utils/games/slot-machine.js +270 -0
- package/lib/Utils/games/website-preview.js +306 -0
- package/lib/Utils/generics.js +402 -0
- package/lib/Utils/group-history.js +68 -0
- package/lib/Utils/group-wallpaper.js +168 -0
- package/lib/Utils/history.js +162 -0
- package/lib/Utils/identity-change-handler.js +60 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/jid-display-normalization.js +221 -0
- package/lib/Utils/link-preview.js +96 -0
- package/lib/Utils/logger.js +14 -0
- package/lib/Utils/lt-hash.js +19 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/message-composer.js +709 -0
- package/lib/Utils/message-inspect.js +79 -0
- package/lib/Utils/message-retry-manager.js +253 -0
- package/lib/Utils/message-security.js +167 -0
- package/lib/Utils/messages-media.js +1027 -0
- package/lib/Utils/messages.js +2467 -0
- package/lib/Utils/meta-ai-msmsg.js +215 -0
- package/lib/Utils/meta-compositing.js +239 -0
- package/lib/Utils/native-flow.js +158 -0
- package/lib/Utils/newsletter-live-update-utils.js +74 -0
- package/lib/Utils/newsletter-status-utils.js +152 -0
- package/lib/Utils/noise-handler.js +212 -0
- package/lib/Utils/offline-node-processor.js +51 -0
- package/lib/Utils/poll-manager.js +206 -0
- package/lib/Utils/portable-compat.js +12 -0
- package/lib/Utils/pre-key-manager.js +117 -0
- package/lib/Utils/process-message.js +610 -0
- package/lib/Utils/reporting-utils.js +269 -0
- package/lib/Utils/rich-message-utils.js +2841 -0
- package/lib/Utils/scheduled-message.js +107 -0
- package/lib/Utils/signal.js +212 -0
- package/lib/Utils/source-grep.js +57 -0
- package/lib/Utils/stanza-ack.js +49 -0
- package/lib/Utils/sticker-annotation.js +87 -0
- package/lib/Utils/sync-action-utils.js +59 -0
- package/lib/Utils/tc-token-utils.js +174 -0
- package/lib/Utils/use-multi-file-auth-state.js +132 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +120 -0
- package/lib/Utils/validate-connection.js +220 -0
- package/lib/Utils/view-once-utils.js +218 -0
- package/lib/Utils/voip-rekey.js +32 -0
- package/lib/Utils/website-preview.js +27 -0
- package/lib/Utils/welcome-flow.js +228 -0
- package/lib/Utils/x4r1s3.js +144 -0
- package/lib/WABinary/constants.js +1475 -0
- package/lib/WABinary/decode.js +273 -0
- package/lib/WABinary/encode.js +231 -0
- package/lib/WABinary/generic-utils.js +242 -0
- package/lib/WABinary/index.js +17 -0
- package/lib/WABinary/jid-utils.js +107 -0
- package/lib/WABinary/types.js +13 -0
- package/lib/WAM/BinaryInfo.js +21 -0
- package/lib/WAM/constants.js +22864 -0
- package/lib/WAM/encode.js +161 -0
- package/lib/WAM/index.js +15 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
- package/lib/WAUSync/Protocols/index.js +24 -0
- package/lib/WAUSync/USyncQuery.js +213 -0
- package/lib/WAUSync/USyncUser.js +66 -0
- package/lib/WAUSync/index.js +15 -0
- package/lib/antiban.cjs +4726 -0
- package/lib/index.d.ts +1285 -0
- package/lib/index.js +30 -0
- package/package.json +125 -4
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/meta-ai-msmsg.js
|
|
5
|
+
* About: Meta ai msmsg module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: decryptMsmsgBotMessage, parseUnifiedResponseData, textFromUnifiedResponse, textFromRichResponse, extractMetaAiText, decodeUnifiedResponseInPlace, decodeDecryptedMsmsgMessage
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { proto } from '../../WAProto/index.js';
|
|
14
|
+
import { aesDecryptGCM, hkdf } from './crypto.js';
|
|
15
|
+
|
|
16
|
+
const BOT_MESSAGE_INFO = 'Bot Message';
|
|
17
|
+
const KEY_LENGTH = 32;
|
|
18
|
+
|
|
19
|
+
const unpadRandomMax16 = (value) => {
|
|
20
|
+
const bytes = new Uint8Array(value);
|
|
21
|
+
if (!bytes.length) {
|
|
22
|
+
throw new Error('unpadPkcs7 given empty bytes');
|
|
23
|
+
}
|
|
24
|
+
const padLength = bytes[bytes.length - 1];
|
|
25
|
+
if (padLength > bytes.length) {
|
|
26
|
+
throw new Error(`unpad given ${bytes.length} bytes, but pad is ${padLength}`);
|
|
27
|
+
}
|
|
28
|
+
return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length - padLength);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const toBuffer = (value) => {
|
|
32
|
+
if (Buffer.isBuffer(value)) return value;
|
|
33
|
+
if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
34
|
+
return Buffer.from(value);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Strips device suffix from LID JIDs: "user:device@lid" → "user@lid".
|
|
38
|
+
// jidEncode includes ":0" even for device=0 (user/non-AD form), so normalize both meId and meLid.
|
|
39
|
+
const normalizeLidJid = (jid) => {
|
|
40
|
+
if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) return jid;
|
|
41
|
+
return `${jid.split(':')[0]}@lid`;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// Ordered msgId candidates per the Rust BotMessageContext:
|
|
45
|
+
// botEditTargetId when editing, stanzaId for the normal full response, metaTargetId as fallback.
|
|
46
|
+
const selectMsgIdCandidates = (messageKey) => {
|
|
47
|
+
const seen = new Set();
|
|
48
|
+
const result = [];
|
|
49
|
+
for (const id of [messageKey?.botEditTargetId, messageKey?.stanzaId, messageKey?.metaTargetId]) {
|
|
50
|
+
const s = id ? String(id) : '';
|
|
51
|
+
if (s && !seen.has(s)) {
|
|
52
|
+
seen.add(s);
|
|
53
|
+
result.push(s);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Ordered target_sender_user_jid candidates per Rust spec (non-AD user JID = no device suffix).
|
|
60
|
+
// jidEncode produces "user:0@lid" for device=0 LID JIDs, so normalize both meId and meLid.
|
|
61
|
+
const selectTargetJidCandidates = (messageKey) => {
|
|
62
|
+
const seen = new Set();
|
|
63
|
+
const result = [];
|
|
64
|
+
for (const jid of [normalizeLidJid(messageKey?.meId), normalizeLidJid(messageKey?.meLid)]) {
|
|
65
|
+
const s = jid ? String(jid) : '';
|
|
66
|
+
if (s && !seen.has(s)) {
|
|
67
|
+
seen.add(s);
|
|
68
|
+
result.push(s);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const decodeDecryptedMsmsgMessage = (decrypted) => {
|
|
75
|
+
const buf = toBuffer(decrypted);
|
|
76
|
+
try {
|
|
77
|
+
const unpadded = Buffer.from(unpadRandomMax16(buf));
|
|
78
|
+
const decoded = proto.Message.decode(unpadded);
|
|
79
|
+
const hasContent = Object.keys(decoded).some(k => k !== 'messageContextInfo' && decoded[k] != null);
|
|
80
|
+
if (hasContent) return decodeUnifiedResponseInPlace(decoded);
|
|
81
|
+
}
|
|
82
|
+
catch {}
|
|
83
|
+
return decodeUnifiedResponseInPlace(proto.Message.decode(buf));
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Decrypts <enc type="msmsg"> bot messages.
|
|
88
|
+
*
|
|
89
|
+
* Two-pass HKDF — algorithm from bot_message.rs (BotMessageContext):
|
|
90
|
+
* k1 = HKDF(messageSecret, salt=∅, info="Bot Message", 32)
|
|
91
|
+
* k2 = HKDF(k1, salt=∅, info=msgID||target_sender_jid||bot_jid, 32)
|
|
92
|
+
* AAD = msgID || 0x00 || bot_user_jid
|
|
93
|
+
* plain = AES-256-GCM.Decrypt(k2, encIv, encPayload, AAD)
|
|
94
|
+
*
|
|
95
|
+
* k1 is shared across all candidates and derived once.
|
|
96
|
+
* AAD always uses bot_user_jid, never target_sender_jid.
|
|
97
|
+
*/
|
|
98
|
+
export const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
|
|
99
|
+
if (!messageSecret || (messageSecret instanceof Uint8Array && !messageSecret.byteLength)) {
|
|
100
|
+
throw new Error('Missing required messageSecret for msmsg decryption');
|
|
101
|
+
}
|
|
102
|
+
if (!messageKey?.participant) throw new Error('Missing required participant for msmsg decryption');
|
|
103
|
+
if (!messageKey?.meId) throw new Error('Missing required meId for msmsg decryption');
|
|
104
|
+
if (!msMsg?.encIv) throw new Error('Missing required encIv for msmsg decryption');
|
|
105
|
+
if (!msMsg?.encPayload) throw new Error('Missing required encPayload for msmsg decryption');
|
|
106
|
+
|
|
107
|
+
const msgIdCandidates = selectMsgIdCandidates(messageKey);
|
|
108
|
+
if (!msgIdCandidates.length) throw new Error('Missing required target message id for msmsg decryption');
|
|
109
|
+
|
|
110
|
+
const targetJidCandidates = selectTargetJidCandidates(messageKey);
|
|
111
|
+
if (!targetJidCandidates.length) throw new Error('Missing required target JID for msmsg decryption');
|
|
112
|
+
|
|
113
|
+
const botJidBuf = Buffer.from(String(messageKey.participant));
|
|
114
|
+
const payload = toBuffer(msMsg.encPayload);
|
|
115
|
+
const iv = toBuffer(msMsg.encIv);
|
|
116
|
+
|
|
117
|
+
// k1 depends only on messageSecret — derive once and reuse across all candidates
|
|
118
|
+
const baseKey = Buffer.from(hkdf(toBuffer(messageSecret), KEY_LENGTH, { info: BOT_MESSAGE_INFO }));
|
|
119
|
+
|
|
120
|
+
let lastError;
|
|
121
|
+
for (const msgId of msgIdCandidates) {
|
|
122
|
+
// msg_id is always passed as ASCII bytes per Rust spec (msg_id.as_bytes())
|
|
123
|
+
const idBuf = Buffer.from(msgId);
|
|
124
|
+
for (const targetJid of targetJidCandidates) {
|
|
125
|
+
const info = Buffer.concat([idBuf, Buffer.from(targetJid), botJidBuf]);
|
|
126
|
+
const key = Buffer.from(hkdf(baseKey, KEY_LENGTH, { info }));
|
|
127
|
+
const aad = Buffer.concat([idBuf, Buffer.from([0x00]), botJidBuf]);
|
|
128
|
+
try {
|
|
129
|
+
return Buffer.from(aesDecryptGCM(payload, key, iv, aad));
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
lastError = e;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const err = new Error('msmsg decryption failed: all key derivation candidates exhausted');
|
|
138
|
+
err.cause = lastError;
|
|
139
|
+
throw err;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// unifiedResponse.data is base64/bytes-wrapped JSON, not encrypted. Keep the
|
|
143
|
+
// original data and expose both the decoded object and flattened text.
|
|
144
|
+
export const parseUnifiedResponseData = (data) => {
|
|
145
|
+
if (!data)
|
|
146
|
+
return null;
|
|
147
|
+
try {
|
|
148
|
+
let buf;
|
|
149
|
+
if (Buffer.isBuffer(data))
|
|
150
|
+
buf = data;
|
|
151
|
+
else if (data instanceof Uint8Array)
|
|
152
|
+
buf = Buffer.from(data);
|
|
153
|
+
else if (typeof data === 'string')
|
|
154
|
+
buf = Buffer.from(data, 'base64');
|
|
155
|
+
else if (data.type === 'Buffer' && Array.isArray(data.data))
|
|
156
|
+
buf = Buffer.from(data.data);
|
|
157
|
+
else
|
|
158
|
+
return null;
|
|
159
|
+
return JSON.parse(buf.toString('utf8'));
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
export const textFromUnifiedResponse = (data) => {
|
|
166
|
+
const json = parseUnifiedResponseData(data);
|
|
167
|
+
if (!json)
|
|
168
|
+
return null;
|
|
169
|
+
const parts = [];
|
|
170
|
+
for (const section of json.sections || []) {
|
|
171
|
+
const text = section?.view_model?.primitive?.text;
|
|
172
|
+
if (text)
|
|
173
|
+
parts.push(text);
|
|
174
|
+
}
|
|
175
|
+
return parts.length ? parts.join('\n') : null;
|
|
176
|
+
};
|
|
177
|
+
export const textFromRichResponse = (richResponse) => {
|
|
178
|
+
if (!richResponse)
|
|
179
|
+
return null;
|
|
180
|
+
if (Array.isArray(richResponse.submessages)) {
|
|
181
|
+
const parts = richResponse.submessages
|
|
182
|
+
.map(submessage => submessage?.messageText)
|
|
183
|
+
.filter(text => typeof text === 'string' && text.length);
|
|
184
|
+
if (parts.length)
|
|
185
|
+
return parts.join('\n');
|
|
186
|
+
}
|
|
187
|
+
return textFromUnifiedResponse(richResponse.unifiedResponse?.data);
|
|
188
|
+
};
|
|
189
|
+
export const extractMetaAiText = (message) => {
|
|
190
|
+
if (!message)
|
|
191
|
+
return null;
|
|
192
|
+
const body = message.protocolMessage?.editedMessage || message;
|
|
193
|
+
return body.extendedTextMessage?.text ?? body.conversation ?? textFromRichResponse(body.richResponseMessage) ?? null;
|
|
194
|
+
};
|
|
195
|
+
export const decodeUnifiedResponseInPlace = (message) => {
|
|
196
|
+
if (!message || typeof message !== 'object')
|
|
197
|
+
return message;
|
|
198
|
+
const bodies = [
|
|
199
|
+
message,
|
|
200
|
+
message.protocolMessage?.editedMessage,
|
|
201
|
+
message.editedMessage
|
|
202
|
+
].filter(Boolean);
|
|
203
|
+
for (const body of bodies) {
|
|
204
|
+
const unifiedResponse = body.richResponseMessage?.unifiedResponse;
|
|
205
|
+
if (unifiedResponse && unifiedResponse.data != null && unifiedResponse.decodedData === undefined) {
|
|
206
|
+
unifiedResponse.decodedData = parseUnifiedResponseData(unifiedResponse.data);
|
|
207
|
+
const text = textFromUnifiedResponse(unifiedResponse.data);
|
|
208
|
+
if (text != null)
|
|
209
|
+
unifiedResponse.text = text;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return message;
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
export { decodeDecryptedMsmsgMessage };
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/meta-compositing.js
|
|
5
|
+
* About: Meta compositing module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: PlanningStepStatus, supportsMetaRendering, buildProgressIndicator, buildCompositingPlaceholder, buildPlainPlaceholder, metaTyping, editMetaMessage, sendMetaComposited; …
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Lia@Changes [WIP]
|
|
15
|
+
* Meta Compositing — send rich messages with Meta AI-style progress indicator.
|
|
16
|
+
*
|
|
17
|
+
* UNIVERSAL VERSION: Works on ALL WhatsApp clients.
|
|
18
|
+
* - Native Meta AI rendering is opt-in and requires caller-supplied verification metadata
|
|
19
|
+
* - Plain text fallback is used unless the native payload can be authenticated
|
|
20
|
+
*
|
|
21
|
+
* metaTyping() — shows the "typing..." / planning steps indicator.
|
|
22
|
+
* sendMetaComposited() — full flow: initial message → streaming MESSAGE_EDIT frames → final edit.
|
|
23
|
+
*
|
|
24
|
+
* If you use or copy this code, please credit @X4R1S3/bailey.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { proto } from '../../WAProto/index.js';
|
|
28
|
+
import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js';
|
|
29
|
+
import { BotCapabilityType, buildBotCapabilityMetadata } from './bot-capabilities.js';
|
|
30
|
+
import { delay } from './generics.js';
|
|
31
|
+
|
|
32
|
+
// ─── Step status enum ───
|
|
33
|
+
export const PlanningStepStatus = {
|
|
34
|
+
IN_PROGRESS: 0,
|
|
35
|
+
DONE: 1,
|
|
36
|
+
FAILED: 2
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Check whether the socket explicitly allows native Meta AI progress rendering.
|
|
41
|
+
* WhatsApp validates bot verification metadata on these messages. The library
|
|
42
|
+
* therefore refuses to fabricate certificates or signatures: native rendering
|
|
43
|
+
* requires both an explicit socket opt-in and verification metadata obtained from
|
|
44
|
+
* a compatible, trusted Meta AI message/session.
|
|
45
|
+
*/
|
|
46
|
+
export const supportsMetaRendering = (_jid, config = {}) => {
|
|
47
|
+
return config.forceMetaRendering === true &&
|
|
48
|
+
config.metaAiRendering?.verificationMetadata?.proofs?.length > 0;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Build a BotProgressIndicatorMetadata object.
|
|
53
|
+
*/
|
|
54
|
+
export const buildProgressIndicator = (description, steps = [], estimatedMs) => {
|
|
55
|
+
const stepsMetadata = steps.map(step => {
|
|
56
|
+
const s = {
|
|
57
|
+
statusTitle: step.title,
|
|
58
|
+
status: step.status ?? PlanningStepStatus.IN_PROGRESS
|
|
59
|
+
};
|
|
60
|
+
if (step.body) s.statusBody = step.body;
|
|
61
|
+
if (step.isReasoning) s.isReasoning = true;
|
|
62
|
+
if (step.isEnhancedSearch) s.isEnhancedSearch = true;
|
|
63
|
+
return s;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const indicator = { stepsMetadata };
|
|
67
|
+
if (description) indicator.progressDescription = description;
|
|
68
|
+
if (estimatedMs != null) indicator.estimatedCompletionTime = estimatedMs;
|
|
69
|
+
return indicator;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build the native Meta AI compositing placeholder (for compatible clients only).
|
|
74
|
+
*/
|
|
75
|
+
export const buildCompositingPlaceholder = ({
|
|
76
|
+
description = 'Thinking…',
|
|
77
|
+
steps = [],
|
|
78
|
+
estimatedMs,
|
|
79
|
+
placeholderText = '',
|
|
80
|
+
verificationMetadata
|
|
81
|
+
} = {}) => {
|
|
82
|
+
const progressIndicatorMetadata = buildProgressIndicator(description, steps, estimatedMs);
|
|
83
|
+
|
|
84
|
+
const textEncoder = new TextEncoder();
|
|
85
|
+
const unifiedData = textEncoder.encode(JSON.stringify({
|
|
86
|
+
response_id: crypto.randomUUID(),
|
|
87
|
+
sections: placeholderText ? [{
|
|
88
|
+
view_model: {
|
|
89
|
+
primitive: {
|
|
90
|
+
text: placeholderText,
|
|
91
|
+
inline_entities: [],
|
|
92
|
+
__typename: 'GenAIMarkdownTextUXPrimitive'
|
|
93
|
+
},
|
|
94
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
95
|
+
}
|
|
96
|
+
}] : []
|
|
97
|
+
}));
|
|
98
|
+
|
|
99
|
+
const richResponseMessage = {
|
|
100
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
101
|
+
unifiedResponse: { data: unifiedData },
|
|
102
|
+
submessages: []
|
|
103
|
+
};
|
|
104
|
+
const capabilities = [
|
|
105
|
+
BotCapabilityType.PROGRESS_INDICATOR,
|
|
106
|
+
...(steps.length ? [BotCapabilityType.AGENTIC_PLANNING] : []),
|
|
107
|
+
...(steps.some(step => step.queryPlan || step.type === 'query') ? [BotCapabilityType.QUERY_PLAN] : [])
|
|
108
|
+
];
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
messageContextInfo: {
|
|
112
|
+
botMetadata: {
|
|
113
|
+
capabilityMetadata: buildBotCapabilityMetadata(capabilities),
|
|
114
|
+
pluginMetadata: {},
|
|
115
|
+
progressIndicatorMetadata,
|
|
116
|
+
botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA,
|
|
117
|
+
...(verificationMetadata ? { verificationMetadata } : {})
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
botForwardedMessage: {
|
|
121
|
+
message: { richResponseMessage }
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Build a plain-text placeholder that works on ALL WhatsApp clients.
|
|
128
|
+
*/
|
|
129
|
+
export const buildPlainPlaceholder = (description = 'Thinking…', steps = [], placeholderText = '') => {
|
|
130
|
+
const stepLines = steps.map(step => {
|
|
131
|
+
const icon = step.status === PlanningStepStatus.DONE ? '✓' :
|
|
132
|
+
step.status === PlanningStepStatus.FAILED ? '✗' : '○';
|
|
133
|
+
return `${icon} ${step.title}`;
|
|
134
|
+
}).join('\n');
|
|
135
|
+
|
|
136
|
+
let text = `_${description}_`;
|
|
137
|
+
if (stepLines) text += `\n\n${stepLines}`;
|
|
138
|
+
if (placeholderText) text += `\n\n${placeholderText}`;
|
|
139
|
+
|
|
140
|
+
return { text };
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* metaTyping — sends the progress/compositing indicator.
|
|
145
|
+
* UNIVERSAL: plain text is the default. Native Meta progress is sent only when
|
|
146
|
+
* useNativeMeta is true, forceMetaRendering is enabled, and trusted verification
|
|
147
|
+
* metadata is supplied in socket.config.metaAiRendering.
|
|
148
|
+
*/
|
|
149
|
+
export const metaTyping = async (sock, jid, {
|
|
150
|
+
description = 'Thinking…',
|
|
151
|
+
steps = [],
|
|
152
|
+
estimatedMs,
|
|
153
|
+
placeholderText = '',
|
|
154
|
+
useNativeMeta = false
|
|
155
|
+
} = {}) => {
|
|
156
|
+
// Show typing indicator
|
|
157
|
+
await sock.sendPresenceUpdate('composing', jid);
|
|
158
|
+
|
|
159
|
+
if (useNativeMeta && supportsMetaRendering(jid, sock.config)) {
|
|
160
|
+
const placeholder = buildCompositingPlaceholder({
|
|
161
|
+
description,
|
|
162
|
+
steps,
|
|
163
|
+
estimatedMs,
|
|
164
|
+
placeholderText,
|
|
165
|
+
verificationMetadata: sock.config?.metaAiRendering?.verificationMetadata
|
|
166
|
+
});
|
|
167
|
+
return sock.sendMessage(jid, { raw: true, ...placeholder });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Universal fallback: plain text placeholder
|
|
171
|
+
const plainSteps = steps.map(s => ({ ...s, status: PlanningStepStatus.IN_PROGRESS }));
|
|
172
|
+
const placeholder = buildPlainPlaceholder(description, plainSteps, placeholderText);
|
|
173
|
+
return sock.sendMessage(jid, placeholder);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** Send a streaming MESSAGE_EDIT frame without changing the original key. */
|
|
177
|
+
export const editMetaMessage = async (sock, jid, key, content, sendOptions = {}, streamContext) => {
|
|
178
|
+
if (!key)
|
|
179
|
+
return undefined;
|
|
180
|
+
const frame = streamContext
|
|
181
|
+
? { ...content, messageContextInfo: { ...streamContext, ...content.messageContextInfo } }
|
|
182
|
+
: content;
|
|
183
|
+
return sock.sendMessage(jid, { ...frame, edit: key }, sendOptions);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* sendMetaComposited — full Meta AI-style flow (UNIVERSAL).
|
|
188
|
+
* 1. Send initial progress indicator
|
|
189
|
+
* 2. Optionally emit streamUpdates as MESSAGE_EDIT frames
|
|
190
|
+
* 3. Edit the same message into the final response
|
|
191
|
+
*/
|
|
192
|
+
export const sendMetaComposited = async (sock, jid, content, {
|
|
193
|
+
thinkingMs = 2000,
|
|
194
|
+
description = 'Thinking…',
|
|
195
|
+
steps = [],
|
|
196
|
+
placeholderText = '',
|
|
197
|
+
sendOptions = {},
|
|
198
|
+
useNativeMeta = false,
|
|
199
|
+
streamUpdates = [],
|
|
200
|
+
streamUpdateDelayMs = 0,
|
|
201
|
+
streamContext
|
|
202
|
+
} = {}) => {
|
|
203
|
+
const placeholder = await metaTyping(sock, jid, {
|
|
204
|
+
description, steps, estimatedMs: thinkingMs, placeholderText, useNativeMeta
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
await delay(thinkingMs);
|
|
209
|
+
if (placeholder?.key) {
|
|
210
|
+
for (const update of streamUpdates) {
|
|
211
|
+
const frame = typeof update === 'string' ? { text: update } : update;
|
|
212
|
+
try {
|
|
213
|
+
await editMetaMessage(sock, jid, placeholder.key, frame, sendOptions, streamContext);
|
|
214
|
+
}
|
|
215
|
+
catch (_) {}
|
|
216
|
+
if (streamUpdateDelayMs > 0)
|
|
217
|
+
await delay(streamUpdateDelayMs);
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
await editMetaMessage(sock, jid, placeholder.key, content, sendOptions, streamContext);
|
|
221
|
+
}
|
|
222
|
+
catch (_) {
|
|
223
|
+
await sock.sendMessage(jid, content, sendOptions);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
await sock.sendMessage(jid, content, sendOptions);
|
|
228
|
+
}
|
|
229
|
+
} catch (_) {}
|
|
230
|
+
|
|
231
|
+
await sock.sendPresenceUpdate('paused', jid);
|
|
232
|
+
return placeholder;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Convenience: build a steps array from plain strings.
|
|
237
|
+
*/
|
|
238
|
+
export const buildSteps = (titles, status = PlanningStepStatus.IN_PROGRESS) =>
|
|
239
|
+
titles.map(title => ({ title, status }));
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/native-flow.js
|
|
5
|
+
* About: Native flow module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: parseNativeFlowResponse, parseWhatsAppFlowResponse, buildWhatsAppFlowButton, makeWhatsAppFlowButton
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
const parseJsonObject = (value) => {
|
|
14
|
+
if (!value) {
|
|
15
|
+
return {};
|
|
16
|
+
}
|
|
17
|
+
if (typeof value === 'object') {
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(value);
|
|
22
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Extracts a native-flow response from an incoming WhatsApp message.
|
|
31
|
+
* Supports ordinary quick replies, single-select responses, and WhatsApp Flow
|
|
32
|
+
* form responses carried by nativeFlowResponseMessage.paramsJson.
|
|
33
|
+
*/
|
|
34
|
+
export const parseNativeFlowResponse = (message) => {
|
|
35
|
+
const content = message?.message || message;
|
|
36
|
+
const response = content?.interactiveResponseMessage?.nativeFlowResponseMessage ||
|
|
37
|
+
content?.nativeFlowResponseMessage;
|
|
38
|
+
if (!response) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const params = parseJsonObject(response.paramsJson);
|
|
42
|
+
const actionPayload = params.flow_action_payload || params.flowActionPayload || {};
|
|
43
|
+
const data = params.data || params.response || params.form_data || params.formData || actionPayload.data || {};
|
|
44
|
+
return {
|
|
45
|
+
name: response.name || '',
|
|
46
|
+
version: response.version,
|
|
47
|
+
paramsJson: response.paramsJson || '',
|
|
48
|
+
params,
|
|
49
|
+
isFlow: response.name === 'galaxy_message' || response.name === 'flow' ||
|
|
50
|
+
!!(params.flow_id || params.flow_token || params.flow_message_version),
|
|
51
|
+
flowId: params.flow_id || params.flowId,
|
|
52
|
+
flowToken: params.flow_token || params.flowToken,
|
|
53
|
+
screen: params.screen || actionPayload.screen,
|
|
54
|
+
action: params.flow_action || params.flowAction || actionPayload.action,
|
|
55
|
+
actionPayload,
|
|
56
|
+
data,
|
|
57
|
+
buttonId: params.id || params.button_id || params.buttonId,
|
|
58
|
+
displayText: params.display_text || params.displayText,
|
|
59
|
+
raw: response
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Extracts only completed or navigated WhatsApp Flow data from a message.
|
|
65
|
+
* Returns null for ordinary native-flow buttons.
|
|
66
|
+
*/
|
|
67
|
+
export const parseWhatsAppFlowResponse = (message) => {
|
|
68
|
+
const response = parseNativeFlowResponse(message);
|
|
69
|
+
if (!response?.isFlow) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return response;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Builds the native-flow button payload used to launch a published WhatsApp Flow.
|
|
77
|
+
* The caller must own the Flow ID/token and publish the Flow through Meta's
|
|
78
|
+
* WhatsApp Flows API or Flow Builder.
|
|
79
|
+
*/
|
|
80
|
+
export const buildWhatsAppFlowButton = ({
|
|
81
|
+
flowId,
|
|
82
|
+
flowToken,
|
|
83
|
+
cta = 'Open form',
|
|
84
|
+
action = 'navigate',
|
|
85
|
+
actionPayload,
|
|
86
|
+
mode = 'published',
|
|
87
|
+
flowMessageVersion = '3',
|
|
88
|
+
metadata,
|
|
89
|
+
name = 'galaxy_message'
|
|
90
|
+
} = {}) => {
|
|
91
|
+
if (!flowId) {
|
|
92
|
+
throw new TypeError('flowId is required to launch a WhatsApp Flow');
|
|
93
|
+
}
|
|
94
|
+
if (!flowToken) {
|
|
95
|
+
throw new TypeError('flowToken is required to launch a WhatsApp Flow');
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
name,
|
|
99
|
+
flow_message_version: String(flowMessageVersion),
|
|
100
|
+
flow_token: String(flowToken),
|
|
101
|
+
flow_id: String(flowId),
|
|
102
|
+
flow_cta: String(cta),
|
|
103
|
+
flow_action: action,
|
|
104
|
+
...(actionPayload ? { flow_action_payload: actionPayload } : {}),
|
|
105
|
+
...(metadata ? { flow_metadata: metadata } : {})
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export const makeWhatsAppFlowButton = (flow) => ({
|
|
110
|
+
name: flow?.nativeFlowName || 'galaxy_message',
|
|
111
|
+
buttonParamsJson: JSON.stringify(buildWhatsAppFlowButton(flow))
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/** Decode a submitted WhatsApp support/CSAT feedback Flow. */
|
|
115
|
+
export const parseWhatsAppFeedbackResponse = (message) => {
|
|
116
|
+
const response = parseWhatsAppFlowResponse(message);
|
|
117
|
+
if (!response) return null;
|
|
118
|
+
const { satisfaction_level, question_answered, improvement_suggestion } = response.data || {};
|
|
119
|
+
if (satisfaction_level === undefined && question_answered === undefined && improvement_suggestion === undefined) return null;
|
|
120
|
+
return {
|
|
121
|
+
...response,
|
|
122
|
+
feedback: {
|
|
123
|
+
satisfactionLevel: satisfaction_level,
|
|
124
|
+
questionAnswered: question_answered,
|
|
125
|
+
improvementSuggestion: improvement_suggestion
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** Build WhatsApp's native appointment-booking confirmation button. */
|
|
131
|
+
export const buildBookingConfirmationButton = ({ location, startDatetime, endDatetime, email } = {}) => {
|
|
132
|
+
if (typeof location !== 'string' || !location.trim()) throw new TypeError('location is required for a booking confirmation');
|
|
133
|
+
for (const [name, value] of [['startDatetime', startDatetime], ['endDatetime', endDatetime]]) {
|
|
134
|
+
if (typeof value !== 'string' || !value.trim() || Number.isNaN(Date.parse(value)) || !/(Z|[+-]\d{2}:\d{2})$/i.test(value)) {
|
|
135
|
+
throw new TypeError(`${name} must be a valid ISO-8601 datetime with an explicit timezone`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (Date.parse(endDatetime) <= Date.parse(startDatetime)) throw new TypeError('endDatetime must be later than startDatetime');
|
|
139
|
+
if (email !== undefined && typeof email !== 'string') throw new TypeError('email must be a string when provided');
|
|
140
|
+
return {
|
|
141
|
+
name: 'booking_confirmation',
|
|
142
|
+
buttonParamsJson: JSON.stringify({ location, start_datetime: startDatetime, end_datetime: endDatetime, ...(email ? { email } : {}) })
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** Build WhatsApp's native request_contact_info button payload. */
|
|
147
|
+
export const buildRequestContactInfoButton = ({ buttonParams } = {}) => {
|
|
148
|
+
if (buttonParams === undefined) {
|
|
149
|
+
return { name: 'request_contact_info' };
|
|
150
|
+
}
|
|
151
|
+
if (!buttonParams || typeof buttonParams !== 'object' || Array.isArray(buttonParams)) {
|
|
152
|
+
throw new TypeError('buttonParams must be an object when provided');
|
|
153
|
+
}
|
|
154
|
+
const serialized = JSON.stringify(buttonParams);
|
|
155
|
+
return serialized === '{}'
|
|
156
|
+
? { name: 'request_contact_info' }
|
|
157
|
+
: { name: 'request_contact_info', buttonParamsJson: serialized };
|
|
158
|
+
};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Based on velowa (https://github.com/7ucg/velowa) by Baron - velowa License; see THIRD_PARTY_NOTICES.md.
|
|
2
|
+
import { getBinaryNodeChild, getBinaryNodeChildren } from '../WABinary/index.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Parse live counters from a newsletter notification. The first update after a
|
|
6
|
+
* subscription is a snapshot; later updates contain only changed messages.
|
|
7
|
+
* Missing messages in a delta therefore mean "unchanged", not zeroed.
|
|
8
|
+
*/
|
|
9
|
+
export const parseNewsletterLiveUpdate = node => {
|
|
10
|
+
const newsletter = node?.attrs?.from;
|
|
11
|
+
if (!newsletter) {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const liveUpdatesNode = getBinaryNodeChild(node, 'live_updates');
|
|
16
|
+
const messagesNode = getBinaryNodeChild(liveUpdatesNode, 'messages');
|
|
17
|
+
const messages = getBinaryNodeChildren(messagesNode, 'message')
|
|
18
|
+
.map(messageNode => {
|
|
19
|
+
const serverId = Number(messageNode.attrs?.server_id);
|
|
20
|
+
if (!serverId) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const reactionsNode = getBinaryNodeChild(messageNode, 'reactions');
|
|
25
|
+
const votesNode = getBinaryNodeChild(messageNode, 'votes');
|
|
26
|
+
const forwardsNode = getBinaryNodeChild(messageNode, 'forwards_count');
|
|
27
|
+
const forwardsCount = forwardsNode?.attrs?.count;
|
|
28
|
+
|
|
29
|
+
return {
|
|
30
|
+
serverId,
|
|
31
|
+
...(forwardsCount !== undefined ? { forwardsCount: Number(forwardsCount) } : {}),
|
|
32
|
+
...(Array.isArray(reactionsNode?.content)
|
|
33
|
+
? {
|
|
34
|
+
reactions: getBinaryNodeChildren(reactionsNode, 'reaction')
|
|
35
|
+
.filter(reaction => reaction.attrs?.code)
|
|
36
|
+
.map(reaction => ({
|
|
37
|
+
code: reaction.attrs.code,
|
|
38
|
+
count: Number(reaction.attrs.count ?? 0)
|
|
39
|
+
}))
|
|
40
|
+
}
|
|
41
|
+
: {}),
|
|
42
|
+
...(Array.isArray(votesNode?.content)
|
|
43
|
+
? {
|
|
44
|
+
votes: getBinaryNodeChildren(votesNode, 'vote')
|
|
45
|
+
.filter(vote =>
|
|
46
|
+
(Buffer.isBuffer(vote.content) || vote.content instanceof Uint8Array) &&
|
|
47
|
+
vote.attrs?.count !== undefined
|
|
48
|
+
)
|
|
49
|
+
.map(vote => ({
|
|
50
|
+
optionHash: Buffer.from(vote.content).toString('hex'),
|
|
51
|
+
count: Number(vote.attrs.count)
|
|
52
|
+
}))
|
|
53
|
+
}
|
|
54
|
+
: {})
|
|
55
|
+
};
|
|
56
|
+
})
|
|
57
|
+
.filter(message => message !== undefined);
|
|
58
|
+
|
|
59
|
+
if (!messages.length) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return { newsletter, messages };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const emitNewsletterLiveUpdate = (ev, node) => {
|
|
67
|
+
const update = parseNewsletterLiveUpdate(node);
|
|
68
|
+
if (!update) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
ev.emit('newsletter.live-update', update);
|
|
73
|
+
return update;
|
|
74
|
+
};
|