@x4r1s3/baileys 0.0.0-stage → 1.0.1

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1245 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/astralena-v3.mjs +96 -0
  18. package/lib/Call/audio-feeder.mjs +201 -0
  19. package/lib/Call/audio-recorder.mjs +250 -0
  20. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  21. package/lib/Call/index.mjs +707 -0
  22. package/lib/Call/relay-transport.mjs +563 -0
  23. package/lib/Call/signaling.mjs +660 -0
  24. package/lib/Call/types.mjs +17 -0
  25. package/lib/Call/video-feeder.mjs +94 -0
  26. package/lib/Call/voip-resources.mjs +259 -0
  27. package/lib/Call/wasm-engine.mjs +1372 -0
  28. package/lib/Call/worker-bootstrap.mjs +1042 -0
  29. package/lib/Defaults/ban-checker.js +56 -0
  30. package/lib/Defaults/index.js +170 -0
  31. package/lib/Signal/Group/ciphertext-message.js +23 -0
  32. package/lib/Signal/Group/group-session-builder.js +41 -0
  33. package/lib/Signal/Group/group_cipher.js +93 -0
  34. package/lib/Signal/Group/index.js +23 -0
  35. package/lib/Signal/Group/keyhelper.js +29 -0
  36. package/lib/Signal/Group/sender-chain-key.js +37 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  38. package/lib/Signal/Group/sender-key-message.js +77 -0
  39. package/lib/Signal/Group/sender-key-name.js +59 -0
  40. package/lib/Signal/Group/sender-key-record.js +52 -0
  41. package/lib/Signal/Group/sender-key-state.js +95 -0
  42. package/lib/Signal/Group/sender-message-key.js +37 -0
  43. package/lib/Signal/libsignal.js +440 -0
  44. package/lib/Signal/lid-mapping.js +292 -0
  45. package/lib/Socket/Client/index.js +14 -0
  46. package/lib/Socket/Client/types.js +22 -0
  47. package/lib/Socket/Client/websocket.js +65 -0
  48. package/lib/Socket/aigroups.js +327 -0
  49. package/lib/Socket/ban-checker.js +165 -0
  50. package/lib/Socket/business.js +419 -0
  51. package/lib/Socket/chats.js +1921 -0
  52. package/lib/Socket/communities.js +443 -0
  53. package/lib/Socket/graphql.js +911 -0
  54. package/lib/Socket/groups.js +561 -0
  55. package/lib/Socket/index.js +49 -0
  56. package/lib/Socket/interactive-handler.js +612 -0
  57. package/lib/Socket/interop.js +575 -0
  58. package/lib/Socket/managed-account.js +220 -0
  59. package/lib/Socket/messages-recv.js +2193 -0
  60. package/lib/Socket/messages-send.js +4141 -0
  61. package/lib/Socket/mex.js +53 -0
  62. package/lib/Socket/newsletter.js +291 -0
  63. package/lib/Socket/privacy.js +458 -0
  64. package/lib/Socket/registration.js +440 -0
  65. package/lib/Socket/socket.js +1042 -0
  66. package/lib/Socket/status-actions.js +287 -0
  67. package/lib/Socket/username.js +241 -0
  68. package/lib/Store/index.js +16 -0
  69. package/lib/Store/make-cache-manager-store.js +101 -0
  70. package/lib/Store/make-in-memory-store.js +432 -0
  71. package/lib/Store/make-ordered-dictionary.js +90 -0
  72. package/lib/Store/object-repository.js +35 -0
  73. package/lib/Types/Auth.js +13 -0
  74. package/lib/Types/Bussines.js +13 -0
  75. package/lib/Types/Call.js +13 -0
  76. package/lib/Types/Chat.js +19 -0
  77. package/lib/Types/Contact.js +13 -0
  78. package/lib/Types/Events.js +13 -0
  79. package/lib/Types/GroupMetadata.js +13 -0
  80. package/lib/Types/Label.js +36 -0
  81. package/lib/Types/LabelAssociation.js +18 -0
  82. package/lib/Types/Message.js +30 -0
  83. package/lib/Types/Mex.js +53 -0
  84. package/lib/Types/Product.js +13 -0
  85. package/lib/Types/RichType.js +34 -0
  86. package/lib/Types/Signal.js +13 -0
  87. package/lib/Types/Socket.js +14 -0
  88. package/lib/Types/State.js +60 -0
  89. package/lib/Types/USync.js +13 -0
  90. package/lib/Types/index.js +37 -0
  91. package/lib/Utils/auth-utils.js +313 -0
  92. package/lib/Utils/ban-checker.js +48 -0
  93. package/lib/Utils/bot-capabilities.js +96 -0
  94. package/lib/Utils/bot-planning-replay.js +177 -0
  95. package/lib/Utils/browser-utils.js +40 -0
  96. package/lib/Utils/business.js +242 -0
  97. package/lib/Utils/c2582.js +147 -0
  98. package/lib/Utils/chat-utils.js +905 -0
  99. package/lib/Utils/companion-reg-client-utils.js +104 -0
  100. package/lib/Utils/consumer-application.js +114 -0
  101. package/lib/Utils/crypto.js +129 -0
  102. package/lib/Utils/decode-wa-message.js +496 -0
  103. package/lib/Utils/direct-chat-theme.js +164 -0
  104. package/lib/Utils/event-buffer.js +601 -0
  105. package/lib/Utils/experimental-proto.js +206 -0
  106. package/lib/Utils/games/miniapp.js +17 -0
  107. package/lib/Utils/games/slot-machine.js +270 -0
  108. package/lib/Utils/games/website-preview.js +306 -0
  109. package/lib/Utils/generics.js +402 -0
  110. package/lib/Utils/group-history.js +68 -0
  111. package/lib/Utils/group-wallpaper.js +168 -0
  112. package/lib/Utils/history.js +162 -0
  113. package/lib/Utils/identity-change-handler.js +60 -0
  114. package/lib/Utils/index.js +61 -0
  115. package/lib/Utils/jid-display-normalization.js +221 -0
  116. package/lib/Utils/link-preview.js +96 -0
  117. package/lib/Utils/logger.js +14 -0
  118. package/lib/Utils/lt-hash.js +19 -0
  119. package/lib/Utils/make-mutex.js +44 -0
  120. package/lib/Utils/message-composer.js +709 -0
  121. package/lib/Utils/message-inspect.js +79 -0
  122. package/lib/Utils/message-retry-manager.js +253 -0
  123. package/lib/Utils/message-security.js +167 -0
  124. package/lib/Utils/messages-media.js +1027 -0
  125. package/lib/Utils/messages.js +2467 -0
  126. package/lib/Utils/meta-ai-msmsg.js +215 -0
  127. package/lib/Utils/meta-compositing.js +239 -0
  128. package/lib/Utils/native-flow.js +158 -0
  129. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  130. package/lib/Utils/newsletter-status-utils.js +152 -0
  131. package/lib/Utils/noise-handler.js +212 -0
  132. package/lib/Utils/offline-node-processor.js +51 -0
  133. package/lib/Utils/poll-manager.js +206 -0
  134. package/lib/Utils/portable-compat.js +12 -0
  135. package/lib/Utils/pre-key-manager.js +117 -0
  136. package/lib/Utils/process-message.js +610 -0
  137. package/lib/Utils/reporting-utils.js +269 -0
  138. package/lib/Utils/rich-message-utils.js +2841 -0
  139. package/lib/Utils/scheduled-message.js +107 -0
  140. package/lib/Utils/signal.js +212 -0
  141. package/lib/Utils/source-grep.js +57 -0
  142. package/lib/Utils/stanza-ack.js +49 -0
  143. package/lib/Utils/sticker-annotation.js +87 -0
  144. package/lib/Utils/sync-action-utils.js +59 -0
  145. package/lib/Utils/tc-token-utils.js +174 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  147. package/lib/Utils/use-single-file-auth-state.js +108 -0
  148. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  149. package/lib/Utils/validate-connection.js +221 -0
  150. package/lib/Utils/view-once-utils.js +218 -0
  151. package/lib/Utils/voip-rekey.js +32 -0
  152. package/lib/Utils/website-preview.js +27 -0
  153. package/lib/Utils/welcome-flow.js +228 -0
  154. package/lib/Utils/x4r1s3.js +144 -0
  155. package/lib/WABinary/constants.js +1475 -0
  156. package/lib/WABinary/decode.js +273 -0
  157. package/lib/WABinary/encode.js +231 -0
  158. package/lib/WABinary/generic-utils.js +242 -0
  159. package/lib/WABinary/index.js +17 -0
  160. package/lib/WABinary/jid-utils.js +107 -0
  161. package/lib/WABinary/types.js +13 -0
  162. package/lib/WAM/BinaryInfo.js +21 -0
  163. package/lib/WAM/constants.js +22864 -0
  164. package/lib/WAM/encode.js +161 -0
  165. package/lib/WAM/index.js +15 -0
  166. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  170. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  171. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  172. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  174. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  175. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  176. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  177. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  178. package/lib/WAUSync/Protocols/index.js +24 -0
  179. package/lib/WAUSync/USyncQuery.js +213 -0
  180. package/lib/WAUSync/USyncUser.js +66 -0
  181. package/lib/WAUSync/index.js +15 -0
  182. package/lib/antiban.cjs +4726 -0
  183. package/lib/index.d.ts +1895 -0
  184. package/lib/index.js +41 -0
  185. package/package.json +125 -4
@@ -0,0 +1,432 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Store/make-in-memory-store.js
5
+ * About: Make in memory store module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: waChatKey, waMessageID, waLabelAssociationKey, makeInMemoryStore
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@Note 03-02-26 [WIP]
15
+ * Manually converted to ESM and modified by me
16
+ * Originally based on @whiskeysockets/baileys v6.7.16
17
+ * Minor adjustments for compatibility with baileys v7 (⁠つ⁠≧⁠▽⁠≦⁠)⁠つ
18
+ */
19
+ import keyedDB from '@adiwajshing/keyed-db';
20
+ import { writeFileSync, readFileSync, existsSync } from 'fs';
21
+ import { WAProto } from '../Types/index.js';
22
+ import { LabelAssociationType } from '../Types/LabelAssociation.js';
23
+ import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
24
+ import { md5, toNumber, updateMessageWithReceipt, updateMessageWithReaction } from '../Utils/index.js';
25
+ import { jidDecode, jidNormalizedUser } from '../WABinary/index.js';
26
+ import { makeOrderedDictionary } from './make-ordered-dictionary.js';
27
+ import { ObjectRepository } from './object-repository.js';
28
+ export const waChatKey = (pin) => ({
29
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
30
+ compare: (k1, k2) => k2.localeCompare(k1)
31
+ });
32
+ export const waMessageID = (m) => m.key.id || '';
33
+ export const waLabelAssociationKey = {
34
+ key: (la) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
35
+ compare: (k1, k2) => k2.localeCompare(k1)
36
+ };
37
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
38
+ export const makeInMemoryStore = (config = {}) => {
39
+ const socket = config.socket;
40
+ const chatKey = config.chatKey || waChatKey(true);
41
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
42
+ const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
43
+ const KeyedDB = keyedDB?.default ?? keyedDB; // Lia@Note 03-02-26 --- Handle CJS ↔ ESM default export differences ⊂⁠(⁠・⁠ω⁠・⁠*⁠⊂⁠)
44
+ const chats = new KeyedDB(chatKey, c => c.id);
45
+ const messages = {};
46
+ const contacts = {};
47
+ const groupMetadata = {};
48
+ const presences = {};
49
+ const state = { connection: 'close' };
50
+ const labels = new ObjectRepository();
51
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
52
+ const assertMessageList = (jid) => {
53
+ if (!messages[jid]) {
54
+ messages[jid] = makeMessagesDictionary();
55
+ }
56
+ return messages[jid];
57
+ };
58
+ const contactsUpsert = (newContacts) => {
59
+ const oldContacts = new Set(Object.keys(contacts));
60
+ for (const contact of newContacts) {
61
+ oldContacts.delete(contact.id);
62
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
63
+ }
64
+ return oldContacts;
65
+ };
66
+ const labelsUpsert = (newLabels) => {
67
+ for (const label of newLabels) {
68
+ labels.upsertById(label.id, label);
69
+ }
70
+ };
71
+ /**
72
+ * binds to a BaileysEventEmitter.
73
+ * It listens to all events and constructs a state that you can query accurate data from.
74
+ * Eg. can use the store to fetch chats, contacts, messages etc.
75
+ * @param ev typically the event emitter from the socket connection
76
+ */
77
+ const bind = (ev) => {
78
+ ev.on('connection.update', update => {
79
+ Object.assign(state, update);
80
+ });
81
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
82
+ if (syncType === WAProto.HistorySync.HistorySyncType.ON_DEMAND) {
83
+ return; // FOR NOW,
84
+ //TODO: HANDLE
85
+ }
86
+ if (isLatest) {
87
+ chats.clear();
88
+ for (const id in messages) {
89
+ delete messages[id];
90
+ }
91
+ }
92
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
93
+ logger.debug({ chatsAdded }, 'synced chats');
94
+ const oldContacts = contactsUpsert(newContacts);
95
+ if (isLatest) {
96
+ for (const jid of oldContacts) {
97
+ delete contacts[jid];
98
+ }
99
+ }
100
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
101
+ for (const msg of newMessages) {
102
+ const jid = msg.key.remoteJidAlt || msg.key.remoteJid;
103
+ const list = assertMessageList(jid);
104
+ list.upsert(msg, 'prepend');
105
+ }
106
+ logger.debug({ messages: newMessages.length }, 'synced messages');
107
+ });
108
+ ev.on('contacts.upsert', contacts => {
109
+ contactsUpsert(contacts);
110
+ });
111
+ ev.on('contacts.update', async (updates) => {
112
+ var _a;
113
+ for (const update of updates) {
114
+ let contact;
115
+ if (contacts[update.id]) {
116
+ contact = contacts[update.id];
117
+ }
118
+ else {
119
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
120
+ const { user } = jidDecode(contactId);
121
+ return [contactId, (await md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
122
+ }));
123
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
124
+ }
125
+ if (contact) {
126
+ if (update.imgUrl === 'changed') {
127
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
128
+ }
129
+ else if (update.imgUrl === 'removed') {
130
+ delete contact.imgUrl;
131
+ }
132
+ }
133
+ else {
134
+ return logger.debug({ update }, 'got update for non-existant contact');
135
+ }
136
+ Object.assign(contacts[contact.id], contact);
137
+ }
138
+ });
139
+ ev.on('chats.upsert', newChats => {
140
+ chats.upsert(...newChats);
141
+ });
142
+ ev.on('chats.update', updates => {
143
+ for (let update of updates) {
144
+ const result = chats.update(update.id, chat => {
145
+ if (update.unreadCount > 0) {
146
+ update = { ...update };
147
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
148
+ }
149
+ Object.assign(chat, update);
150
+ });
151
+ if (!result) {
152
+ logger.debug({ update }, 'got update for non-existant chat');
153
+ }
154
+ }
155
+ });
156
+ ev.on('labels.edit', (label) => {
157
+ if (label.deleted) {
158
+ return labels.deleteById(label.id);
159
+ }
160
+ // WhatsApp can store only up to 20 labels
161
+ if (labels.count() < 20) {
162
+ return labels.upsertById(label.id, label);
163
+ }
164
+ logger.error('Labels count exceed');
165
+ });
166
+ ev.on('labels.association', ({ type, association }) => {
167
+ switch (type) {
168
+ case 'add':
169
+ labelAssociations.upsert(association);
170
+ break;
171
+ case 'remove':
172
+ labelAssociations.delete(association);
173
+ break;
174
+ default:
175
+ console.error(`unknown operation type [${type}]`);
176
+ }
177
+ });
178
+ ev.on('presence.update', ({ id, presences: update }) => {
179
+ presences[id] = presences[id] || {};
180
+ Object.assign(presences[id], update);
181
+ });
182
+ ev.on('chats.delete', deletions => {
183
+ for (const item of deletions) {
184
+ if (chats.get(item)) {
185
+ chats.deleteById(item);
186
+ }
187
+ }
188
+ });
189
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
190
+ switch (type) {
191
+ case 'append':
192
+ case 'notify':
193
+ for (const msg of newMessages) {
194
+ const jid = jidNormalizedUser(msg.key.remoteJidAlt || msg.key.remoteJid);
195
+ const list = assertMessageList(jid);
196
+ list.upsert(msg, 'append');
197
+ if (type === 'notify' && !chats.get(jid)) {
198
+ ev.emit('chats.upsert', [
199
+ {
200
+ id: jid,
201
+ conversationTimestamp: toNumber(msg.messageTimestamp),
202
+ unreadCount: 1
203
+ }
204
+ ]);
205
+ }
206
+ }
207
+ break;
208
+ }
209
+ });
210
+ ev.on('messages.update', updates => {
211
+ var _a;
212
+ for (const { update, key } of updates) {
213
+ const list = assertMessageList(jidNormalizedUser(key.remoteJid));
214
+ if (update === null || update === void 0 ? void 0 : update.status) {
215
+ const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
216
+ if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
217
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
218
+ delete update.status;
219
+ logger.debug({ update }, 'new update object');
220
+ }
221
+ }
222
+ const result = list.updateAssign(key.id, update);
223
+ if (!result) {
224
+ logger.debug({ update }, 'got update for non-existent message');
225
+ }
226
+ }
227
+ });
228
+ ev.on('messages.delete', item => {
229
+ if ('all' in item) {
230
+ const list = messages[item.jid];
231
+ list === null || list === void 0 ? void 0 : list.clear();
232
+ }
233
+ else {
234
+ const jid = item.keys[0].remoteJidAlt || item.keys[0].remoteJid;
235
+ const list = messages[jid];
236
+ if (list) {
237
+ const idSet = new Set(item.keys.map(k => k.id));
238
+ list.filter(m => !idSet.has(m.key.id));
239
+ }
240
+ }
241
+ });
242
+ ev.on('groups.update', updates => {
243
+ for (const update of updates) {
244
+ const id = update.id;
245
+ if (groupMetadata[id]) {
246
+ Object.assign(groupMetadata[id], update);
247
+ }
248
+ else {
249
+ logger.debug({ update }, 'got update for non-existant group metadata');
250
+ }
251
+ }
252
+ });
253
+ ev.on('group-participants.update', ({ id, participants, action }) => {
254
+ const metadata = groupMetadata[id];
255
+ if (metadata) {
256
+ switch (action) {
257
+ case 'add':
258
+ metadata.participants.push(...participants.map(participant => ({ id: participant.id, phoneNumber: participant.phoneNumber, admin: participant.admin })));
259
+ break;
260
+ case 'demote':
261
+ case 'promote':
262
+ for (const participant of metadata.participants) {
263
+ for (const participantData of participants) {
264
+ if (participantData.id === participant.id || participantData.phoneNumber === participant.phoneNumber) {
265
+ participant.admin = action === 'promote' && 'admin';
266
+ }
267
+ }
268
+ }
269
+ break;
270
+ case 'remove':
271
+ const removeSet = new Set();
272
+ for (const p of participants) {
273
+ if (p.id)
274
+ removeSet.add(p.id);
275
+ if (p.phoneNumber)
276
+ removeSet.add(p.phoneNumber);
277
+ }
278
+ metadata.participants = metadata.participants.reduce((acc, p) => {
279
+ if (!removeSet.has(p.id) && !removeSet.has(p.phoneNumber))
280
+ acc.push(p);
281
+ return acc;
282
+ }, []);
283
+ break;
284
+ }
285
+ }
286
+ });
287
+ ev.on('message-receipt.update', updates => {
288
+ for (const { key, receipt } of updates) {
289
+ const obj = messages[key.remoteJidAlt || key.remoteJid];
290
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
291
+ if (msg) {
292
+ updateMessageWithReceipt(msg, receipt);
293
+ }
294
+ }
295
+ });
296
+ ev.on('messages.reaction', (reactions) => {
297
+ for (const { key, reaction } of reactions) {
298
+ const obj = messages[key.remoteJidAlt || key.remoteJid];
299
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
300
+ if (msg) {
301
+ updateMessageWithReaction(msg, reaction);
302
+ }
303
+ }
304
+ });
305
+ };
306
+ const toJSON = () => ({
307
+ chats,
308
+ contacts,
309
+ messages,
310
+ labels,
311
+ labelAssociations
312
+ });
313
+ const fromJSON = (json) => {
314
+ chats.upsert(...json.chats);
315
+ labelAssociations.upsert(...json.labelAssociations || []);
316
+ contactsUpsert(Object.values(json.contacts));
317
+ labelsUpsert(Object.values(json.labels || {}));
318
+ for (const jid in json.messages) {
319
+ const list = assertMessageList(jid);
320
+ for (const msg of json.messages[jid]) {
321
+ list.upsert(WAProto.WebMessageInfo.fromObject(msg), 'append');
322
+ }
323
+ }
324
+ };
325
+ return {
326
+ chats,
327
+ contacts,
328
+ messages,
329
+ groupMetadata,
330
+ state,
331
+ presences,
332
+ labels,
333
+ labelAssociations,
334
+ bind,
335
+ /** loads messages from the store, if not found -- uses the legacy connection */
336
+ loadMessages: async (jid, count, cursor) => {
337
+ const list = assertMessageList(jid);
338
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
339
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
340
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
341
+ let messages;
342
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
343
+ if (cursorValue) {
344
+ const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
345
+ messages = list.array.slice(0, msgIdx);
346
+ }
347
+ else {
348
+ messages = list.array;
349
+ }
350
+ const diff = count - messages.length;
351
+ if (diff < 0) {
352
+ messages = messages.slice(-count); // get the last X messages
353
+ }
354
+ }
355
+ else {
356
+ messages = [];
357
+ }
358
+ return messages;
359
+ },
360
+ /**
361
+ * Get all available labels for profile
362
+ *
363
+ * Keep in mind that the list is formed from predefined tags and tags
364
+ * that were "caught" during their editing.
365
+ */
366
+ getLabels: () => {
367
+ return labels;
368
+ },
369
+ /**
370
+ * Get labels for chat
371
+ *
372
+ * @returns Label IDs
373
+ **/
374
+ getChatLabels: (chatId) => {
375
+ return labelAssociations.filter((la) => la.chatId === chatId).all();
376
+ },
377
+ /**
378
+ * Get labels for message
379
+ *
380
+ * @returns Label IDs
381
+ **/
382
+ getMessageLabels: (messageId) => {
383
+ const associations = labelAssociations
384
+ .filter((la) => la.messageId === messageId)
385
+ .all();
386
+ return associations.map(({ labelId }) => labelId);
387
+ },
388
+ loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
389
+ mostRecentMessage: async (jid) => {
390
+ var _a;
391
+ const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
392
+ return message;
393
+ },
394
+ fetchImageUrl: async (jid, sock) => {
395
+ const contact = contacts[jid];
396
+ if (!contact) {
397
+ return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
398
+ }
399
+ if (typeof contact.imgUrl === 'undefined') {
400
+ contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
401
+ }
402
+ return contact.imgUrl;
403
+ },
404
+ fetchGroupMetadata: async (jid, sock) => {
405
+ if (!groupMetadata[jid]) {
406
+ const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
407
+ if (metadata) {
408
+ groupMetadata[jid] = metadata;
409
+ }
410
+ }
411
+ return groupMetadata[jid];
412
+ },
413
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
414
+ const list = messages[remoteJid];
415
+ const msg = list === null || list === void 0 ? void 0 : list.get(id);
416
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
417
+ },
418
+ toJSON,
419
+ fromJSON,
420
+ writeToFile: (path) => {
421
+ writeFileSync(path, JSON.stringify(toJSON()));
422
+ },
423
+ readFromFile: (path) => {
424
+ if (existsSync(path)) {
425
+ logger.debug({ path }, 'reading from file');
426
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' });
427
+ const json = JSON.parse(jsonStr);
428
+ fromJSON(json);
429
+ }
430
+ }
431
+ };
432
+ };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Store/make-ordered-dictionary.js
5
+ * About: Make ordered dictionary module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeOrderedDictionary
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
+ export function makeOrderedDictionary(idGetter) {
14
+ const array = [];
15
+ const dict = {};
16
+ const get = (id) => dict[id];
17
+ const update = (item) => {
18
+ const id = idGetter(item);
19
+ const idx = array.findIndex(i => idGetter(i) === id);
20
+ if (idx >= 0) {
21
+ array[idx] = item;
22
+ dict[id] = item;
23
+ }
24
+ return false;
25
+ };
26
+ const upsert = (item, mode) => {
27
+ const id = idGetter(item);
28
+ if (get(id)) {
29
+ update(item);
30
+ }
31
+ else {
32
+ if (mode === 'append') {
33
+ array.push(item);
34
+ }
35
+ else {
36
+ array.splice(0, 0, item);
37
+ }
38
+ dict[id] = item;
39
+ }
40
+ };
41
+ const remove = (item) => {
42
+ const id = idGetter(item);
43
+ const idx = array.findIndex(i => idGetter(i) === id);
44
+ if (idx >= 0) {
45
+ array.splice(idx, 1);
46
+ delete dict[id];
47
+ return true;
48
+ }
49
+ return false;
50
+ };
51
+ return {
52
+ array,
53
+ get,
54
+ upsert,
55
+ update,
56
+ remove,
57
+ updateAssign: (id, update) => {
58
+ const item = get(id);
59
+ if (item) {
60
+ Object.assign(item, update);
61
+ delete dict[id];
62
+ dict[idGetter(item)] = item;
63
+ return true;
64
+ }
65
+ return false;
66
+ },
67
+ clear: () => {
68
+ array.splice(0, array.length);
69
+ for (const key of Object.keys(dict)) {
70
+ delete dict[key];
71
+ }
72
+ },
73
+ filter: (contain) => {
74
+ let i = 0;
75
+ while (i < array.length) {
76
+ if (!contain(array[i])) {
77
+ delete dict[idGetter(array[i])];
78
+ array.splice(i, 1);
79
+ }
80
+ else {
81
+ i += 1;
82
+ }
83
+ }
84
+ },
85
+ toJSON: () => array,
86
+ fromJSON: (newItems) => {
87
+ array.splice(0, array.length, ...newItems);
88
+ }
89
+ };
90
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Store/object-repository.js
5
+ * About: Object repository module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: ObjectRepository
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
+ export class ObjectRepository {
14
+ constructor(entities = {}) {
15
+ this.entityMap = new Map(Object.entries(entities));
16
+ }
17
+ findById(id) {
18
+ return this.entityMap.get(id);
19
+ }
20
+ findAll() {
21
+ return Array.from(this.entityMap.values());
22
+ }
23
+ upsertById(id, entity) {
24
+ return this.entityMap.set(id, { ...entity });
25
+ }
26
+ deleteById(id) {
27
+ return this.entityMap.delete(id);
28
+ }
29
+ count() {
30
+ return this.entityMap.size;
31
+ }
32
+ toJSON() {
33
+ return this.findAll();
34
+ }
35
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Auth.js
5
+ * About: Auth module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Bussines.js
5
+ * About: Bussines module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Call.js
5
+ * About: Call module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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
+ export {};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Chat.js
5
+ * About: Chat module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: ALL_WA_PATCH_NAMES
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
+ export const ALL_WA_PATCH_NAMES = [
14
+ 'critical_block',
15
+ 'critical_unblock_low',
16
+ 'regular_high',
17
+ 'regular_low',
18
+ 'regular'
19
+ ];
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Contact.js
5
+ * About: Contact module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/Events.js
5
+ * About: Events module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Types/GroupMetadata.js
5
+ * About: GroupMetadata module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: No public exports detected; module side effects or declarations are local.
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
+ export {};