@celestial-community/baileys 0.0.1-security → 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.

Potentially problematic release.


This version of @celestial-community/baileys might be problematic. Click here for more details.

Files changed (175) hide show
  1. package/WAProto/index.js +138933 -0
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +7 -0
  4. package/lib/Defaults/index.js +157 -0
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +15 -0
  7. package/lib/Signal/Group/group-session-builder.js +94 -0
  8. package/lib/Signal/Group/group_cipher.js +118 -0
  9. package/lib/Signal/Group/index.js +138 -0
  10. package/lib/Signal/Group/keyhelper.js +75 -0
  11. package/lib/Signal/Group/queue-job.js +54 -0
  12. package/lib/Signal/Group/sender-chain-key.js +39 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
  14. package/lib/Signal/Group/sender-key-message.js +76 -0
  15. package/lib/Signal/Group/sender-key-name.js +50 -0
  16. package/lib/Signal/Group/sender-key-record.js +65 -0
  17. package/lib/Signal/Group/sender-key-state.js +114 -0
  18. package/lib/Signal/Group/sender-message-key.js +33 -0
  19. package/lib/Signal/libsignal.js +204 -0
  20. package/lib/Signal/lid-mapping.js +267 -0
  21. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  22. package/lib/Socket/Client/index.js +32 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +82 -0
  24. package/lib/Socket/Client/web-socket-client.js +89 -0
  25. package/lib/Socket/Denzy-ZeroDay.js +805 -0
  26. package/lib/Socket/business.js +279 -0
  27. package/lib/Socket/chats.js +1169 -0
  28. package/lib/Socket/community.d.ts +120 -0
  29. package/lib/Socket/community.js +388 -0
  30. package/lib/Socket/graphql.js +1122 -0
  31. package/lib/Socket/groups.js +345 -0
  32. package/lib/Socket/index.js +22 -0
  33. package/lib/Socket/interop.js +265 -0
  34. package/lib/Socket/lid-mapping.js +111 -0
  35. package/lib/Socket/messages-recv.js +1385 -0
  36. package/lib/Socket/messages-send.js +956 -0
  37. package/lib/Socket/mex.js +69 -0
  38. package/lib/Socket/newsletter.js +424 -0
  39. package/lib/Socket/privacy.js +229 -0
  40. package/lib/Socket/registration.js +190 -0
  41. package/lib/Socket/socket.js +783 -0
  42. package/lib/Socket/username.d.ts +185 -0
  43. package/lib/Socket/username.js +168 -0
  44. package/lib/Socket/usync.js +80 -0
  45. package/lib/Store/index.js +14 -0
  46. package/lib/Store/keyed-db.js +158 -0
  47. package/lib/Store/make-cache-manager-store.js +88 -0
  48. package/lib/Store/make-in-memory-store.js +484 -0
  49. package/lib/Store/make-ordered-dictionary.js +78 -0
  50. package/lib/Store/object-repository.js +27 -0
  51. package/lib/Types/Auth.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +10 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +27 -0
  58. package/lib/Types/LabelAssociation.js +9 -0
  59. package/lib/Types/Message.js +14 -0
  60. package/lib/Types/MexUpdates.js +19 -0
  61. package/lib/Types/Newsletter.js +38 -0
  62. package/lib/Types/Product.js +2 -0
  63. package/lib/Types/RichType.js +30 -0
  64. package/lib/Types/Signal.js +2 -0
  65. package/lib/Types/Socket.js +2 -0
  66. package/lib/Types/State.js +2 -0
  67. package/lib/Types/USync.js +2 -0
  68. package/lib/Types/index.js +58 -0
  69. package/lib/Utils/anti-ban.js +339 -0
  70. package/lib/Utils/anti-delete.d.ts +158 -0
  71. package/lib/Utils/anti-delete.js +293 -0
  72. package/lib/Utils/antiban-presets.js +91 -0
  73. package/lib/Utils/antiban-profiles.js +43 -0
  74. package/lib/Utils/auth-utils.js +210 -0
  75. package/lib/Utils/baileys-event-stream.js +66 -0
  76. package/lib/Utils/browser-utils.js +52 -0
  77. package/lib/Utils/business.js +261 -0
  78. package/lib/Utils/chat-control.d.ts +113 -0
  79. package/lib/Utils/chat-control.js +230 -0
  80. package/lib/Utils/chat-utils.js +922 -0
  81. package/lib/Utils/companion-reg-client-utils.js +37 -0
  82. package/lib/Utils/contact-graph-warmer.js +208 -0
  83. package/lib/Utils/crypto.js +196 -0
  84. package/lib/Utils/decode-wa-message.js +208 -0
  85. package/lib/Utils/delivery-tracker.js +110 -0
  86. package/lib/Utils/device-fingerprint.js +135 -0
  87. package/lib/Utils/event-buffer.js +531 -0
  88. package/lib/Utils/generics.js +571 -0
  89. package/lib/Utils/group-operation-guard.js +147 -0
  90. package/lib/Utils/health-monitor.js +207 -0
  91. package/lib/Utils/history.js +122 -0
  92. package/lib/Utils/human-entropy.js +226 -0
  93. package/lib/Utils/identity-change-handler.js +72 -0
  94. package/lib/Utils/index.js +83 -0
  95. package/lib/Utils/interactive-message.d.ts +139 -0
  96. package/lib/Utils/interactive-message.js +273 -0
  97. package/lib/Utils/legitimacy-signal-injector.js +180 -0
  98. package/lib/Utils/link-preview.js +106 -0
  99. package/lib/Utils/logger.d.ts +13 -0
  100. package/lib/Utils/logger.js +9 -0
  101. package/lib/Utils/lt-hash.js +54 -0
  102. package/lib/Utils/make-mutex.js +41 -0
  103. package/lib/Utils/message-composer.d.ts +106 -0
  104. package/lib/Utils/message-composer.js +721 -0
  105. package/lib/Utils/message-retry-manager.d.ts +88 -0
  106. package/lib/Utils/message-retry-manager.js +160 -0
  107. package/lib/Utils/message-search.d.ts +52 -0
  108. package/lib/Utils/message-search.js +226 -0
  109. package/lib/Utils/messages-media.js +899 -0
  110. package/lib/Utils/messages.js +2698 -0
  111. package/lib/Utils/noise-handler.js +175 -0
  112. package/lib/Utils/offline-node-processor.js +45 -0
  113. package/lib/Utils/pre-key-manager.js +131 -0
  114. package/lib/Utils/presence-choreographer.js +438 -0
  115. package/lib/Utils/process-message.js +423 -0
  116. package/lib/Utils/rate-limiter.js +232 -0
  117. package/lib/Utils/reconnect-throttle.js +157 -0
  118. package/lib/Utils/reply-ratio-guard.js +137 -0
  119. package/lib/Utils/reporting-utils.js +307 -0
  120. package/lib/Utils/retry-reason-tracker.js +140 -0
  121. package/lib/Utils/rich-message-utils.d.ts +48 -0
  122. package/lib/Utils/rich-message-utils.js +400 -0
  123. package/lib/Utils/rich-response-utils.js +461 -0
  124. package/lib/Utils/scheduling.d.ts +135 -0
  125. package/lib/Utils/scheduling.js +246 -0
  126. package/lib/Utils/session-fingerprint.js +226 -0
  127. package/lib/Utils/session-stability.js +224 -0
  128. package/lib/Utils/signal.js +188 -0
  129. package/lib/Utils/stanza-ack.js +38 -0
  130. package/lib/Utils/state-manager.js +91 -0
  131. package/lib/Utils/status-posting.d.ts +81 -0
  132. package/lib/Utils/status-posting.js +187 -0
  133. package/lib/Utils/stealth-connect.js +124 -0
  134. package/lib/Utils/sync-action-utils.js +55 -0
  135. package/lib/Utils/tc-token-utils.js +171 -0
  136. package/lib/Utils/templates.d.ts +54 -0
  137. package/lib/Utils/templates.js +244 -0
  138. package/lib/Utils/timelock-guard.js +162 -0
  139. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  140. package/lib/Utils/use-mongo-file-auth-state.js +81 -0
  141. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  142. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  143. package/lib/Utils/use-single-file-auth-state.js +86 -0
  144. package/lib/Utils/use-sqlite-auth-state.js +187 -0
  145. package/lib/Utils/vCard.d.ts +71 -0
  146. package/lib/Utils/vCard.js +196 -0
  147. package/lib/Utils/validate-connection.js +253 -0
  148. package/lib/Utils/warmup.js +154 -0
  149. package/lib/WABinary/constants.js +1303 -0
  150. package/lib/WABinary/decode.js +270 -0
  151. package/lib/WABinary/encode.js +279 -0
  152. package/lib/WABinary/generic-utils.js +223 -0
  153. package/lib/WABinary/index.js +34 -0
  154. package/lib/WABinary/jid-utils.js +84 -0
  155. package/lib/WABinary/types.js +2 -0
  156. package/lib/WAM/BinaryInfo.js +13 -0
  157. package/lib/WAM/constants.js +15254 -0
  158. package/lib/WAM/encode.js +149 -0
  159. package/lib/WAM/index.js +32 -0
  160. package/lib/WAUSync/Protocols/USyncContactProtocol.js +37 -0
  161. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +71 -0
  162. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +32 -0
  163. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  164. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  165. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +58 -0
  166. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  167. package/lib/WAUSync/Protocols/index.js +34 -0
  168. package/lib/WAUSync/USyncQuery.js +99 -0
  169. package/lib/WAUSync/USyncUser.js +26 -0
  170. package/lib/WAUSync/USyncUsernameProtocol.d.ts +9 -0
  171. package/lib/WAUSync/USyncUsernameProtocol.js +37 -0
  172. package/lib/WAUSync/index.js +32 -0
  173. package/lib/index.js +59 -0
  174. package/package.json +105 -5
  175. package/README.md +0 -5
@@ -0,0 +1,88 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ const cache_manager_1 = require('cache-manager')
9
+ const WAProto_1 = require('../../WAProto')
10
+ const Utils_1 = require('../Utils')
11
+ const logger_1 = __importDefault(require('../Utils/logger'))
12
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
13
+ const defaultKey = (file) => `${sessionKey}:${file}`
14
+ const databaseConn = await (0, cache_manager_1.caching)(store)
15
+ const writeData = async (file, data) => {
16
+ let ttl = undefined
17
+ if (file === 'creds') {
18
+ ttl = 63115200 // 2 years
19
+ }
20
+ await databaseConn.set(
21
+ defaultKey(file),
22
+ JSON.stringify(data, Utils_1.BufferJSON.replacer),
23
+ ttl
24
+ )
25
+ }
26
+ const readData = async (file) => {
27
+ try {
28
+ const data = await databaseConn.get(defaultKey(file))
29
+ if (data) {
30
+ return JSON.parse(data, Utils_1.BufferJSON.reviver)
31
+ }
32
+ return null
33
+ } catch (error) {
34
+ logger_1.default.error(error)
35
+ return null
36
+ }
37
+ }
38
+ const removeData = async (file) => {
39
+ try {
40
+ return await databaseConn.del(defaultKey(file))
41
+ } catch (_a) {
42
+ logger_1.default.error(`Error removing ${file} from session ${sessionKey}`)
43
+ }
44
+ }
45
+ const clearState = async () => {
46
+ try {
47
+ const result = await databaseConn.store.keys(`${sessionKey}*`)
48
+ await Promise.all(result.map(async (key) => await databaseConn.del(key)))
49
+ } catch (err) {}
50
+ }
51
+ const creds = (await readData('creds')) || (0, Utils_1.initAuthCreds)()
52
+ return {
53
+ clearState,
54
+ saveCreds: () => writeData('creds', creds),
55
+ state: {
56
+ creds,
57
+ keys: {
58
+ get: async (type, ids) => {
59
+ const data = {}
60
+ await Promise.all(
61
+ ids.map(async (id) => {
62
+ let value = await readData(`${type}-${id}`)
63
+ if (type === 'app-state-sync-key' && value) {
64
+ value =
65
+ WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
66
+ }
67
+ data[id] = value
68
+ })
69
+ )
70
+ return data
71
+ },
72
+ set: async (data) => {
73
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
+ const tasks = []
75
+ for (const category in data) {
76
+ for (const id in data[category]) {
77
+ const value = data[category][id]
78
+ const key = `${category}-${id}`
79
+ tasks.push(value ? writeData(key, value) : removeData(key))
80
+ }
81
+ }
82
+ await Promise.all(tasks)
83
+ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ exports.default = makeCacheManagerAuthState
@@ -0,0 +1,484 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.waLabelAssociationKey = exports.waMessageID = exports.waChatKey = void 0
9
+ const WAProto_1 = require('../../WAProto')
10
+ const Defaults_1 = require('../Defaults')
11
+ const LabelAssociation_1 = require('../Types/LabelAssociation')
12
+ const Utils_1 = require('../Utils')
13
+ const WABinary_1 = require('../WABinary')
14
+ const make_ordered_dictionary_1 = __importDefault(require('./make-ordered-dictionary'))
15
+ const object_repository_1 = require('./object-repository')
16
+ const waChatKey = (pin) => ({
17
+ key: (c) =>
18
+ (pin ? (c.pinned ? '1' : '0') : '') +
19
+ (c.archived ? '0' : '1') +
20
+ (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') +
21
+ c.id,
22
+ compare: (k1, k2) => k2.localeCompare(k1)
23
+ })
24
+ exports.waChatKey = waChatKey
25
+ const waMessageID = (m) => m.key.id || ''
26
+ exports.waMessageID = waMessageID
27
+ exports.waLabelAssociationKey = {
28
+ key: (la) =>
29
+ la.type === LabelAssociation_1.LabelAssociationType.Chat
30
+ ? la.chatId + la.labelId
31
+ : la.chatId + la.messageId + la.labelId,
32
+ compare: (k1, k2) => k2.localeCompare(k1)
33
+ }
34
+ const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID)
35
+ exports.default = (config) => {
36
+ const socket = config.socket
37
+ const chatKey = config.chatKey || (0, exports.waChatKey)(true)
38
+ const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey
39
+ const logger =
40
+ config.logger ||
41
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
42
+ const KeyedDB = require('@adiwajshing/keyed-db').default
43
+ const chats = new KeyedDB(chatKey, (c) => c.id)
44
+ const messages = {}
45
+ const contacts = {}
46
+ const groupMetadata = {}
47
+ const presences = {}
48
+ const state = { connection: 'close' }
49
+ const labels = new object_repository_1.ObjectRepository()
50
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
51
+ const assertMessageList = (jid) => {
52
+ if (!messages[jid]) {
53
+ messages[jid] = makeMessagesDictionary()
54
+ }
55
+ return messages[jid]
56
+ }
57
+ const contactsUpsert = (newContacts) => {
58
+ const oldContacts = new Set(Object.keys(contacts))
59
+ for (const contact of newContacts) {
60
+ oldContacts.delete(contact.id)
61
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
62
+ }
63
+ return oldContacts
64
+ }
65
+ const labelsUpsert = (newLabels) => {
66
+ for (const label of newLabels) {
67
+ labels.upsertById(label.id, label)
68
+ }
69
+ }
70
+ const getValidContacts = () => {
71
+ for (const contact of Object.keys(contacts)) {
72
+ if (contact.indexOf('@') < 0) {
73
+ delete contacts[contact]
74
+ }
75
+ }
76
+ return Object.keys(contacts)
77
+ }
78
+ /**
79
+ * binds to a BaileysEventEmitter.
80
+ * It listens to all events and constructs a state that you can query accurate data from.
81
+ * Eg. can use the store to fetch chats, contacts, messages etc.
82
+ * @param ev typically the event emitter from the socket connection
83
+ */
84
+ const bind = (ev) => {
85
+ ev.on('connection.update', (update) => {
86
+ Object.assign(state, update)
87
+ })
88
+ ev.on(
89
+ 'messaging-history.set',
90
+ ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
91
+ if (isLatest) {
92
+ chats.clear()
93
+ for (const id in messages) {
94
+ delete messages[id]
95
+ }
96
+ }
97
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
98
+ logger.debug({ chatsAdded }, 'synced chats')
99
+ const oldContacts = contactsUpsert(newContacts)
100
+ if (isLatest) {
101
+ for (const jid of oldContacts) {
102
+ delete contacts[jid]
103
+ }
104
+ }
105
+ logger.debug(
106
+ { deletedContacts: isLatest ? oldContacts.size : 0, newContacts },
107
+ 'synced contacts'
108
+ )
109
+ for (const msg of newMessages) {
110
+ const jid = msg.key.remoteJid
111
+ const list = assertMessageList(jid)
112
+ list.upsert(msg, 'prepend')
113
+ }
114
+ logger.debug({ messages: newMessages.length }, 'synced messages')
115
+ }
116
+ )
117
+ ev.on('contacts.upsert', (contacts) => {
118
+ contactsUpsert(contacts)
119
+ })
120
+ ev.on('contacts.update', async (updates) => {
121
+ var _a
122
+ for (const update of updates) {
123
+ let contact
124
+ if (contacts[update.id]) {
125
+ contact = contacts[update.id]
126
+ } else {
127
+ const validContacts = getValidContacts()
128
+ const contactHashes = validContacts.map((contactId) => {
129
+ const { user } = (0, WABinary_1.jidDecode)(contactId)
130
+ return [
131
+ contactId,
132
+ (0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))
133
+ .toString('base64')
134
+ .slice(0, 3)
135
+ ]
136
+ })
137
+ contact =
138
+ contacts[
139
+ ((_a = contactHashes.find(([, b]) => b === update.id)) === null ||
140
+ _a === void 0
141
+ ? void 0
142
+ : _a[0]) || ''
143
+ ] // find contact by attrs.hash, when user is not saved as a contact
144
+ }
145
+ if (contact) {
146
+ if (update.imgUrl === 'changed') {
147
+ contact.imgUrl = socket
148
+ ? await (socket === null || socket === void 0
149
+ ? void 0
150
+ : socket.profilePictureUrl(contact.id))
151
+ : undefined
152
+ } else if (update.imgUrl === 'removed') {
153
+ delete contact.imgUrl
154
+ }
155
+ Object.assign(contacts[contact.id], contact)
156
+ } else {
157
+ logger.debug({ update }, 'got update for non-existant contact')
158
+ }
159
+ }
160
+ })
161
+ ev.on('chats.upsert', (newChats) => {
162
+ chats.upsert(...newChats)
163
+ })
164
+ ev.on('chats.update', (updates) => {
165
+ for (let update of updates) {
166
+ const result = chats.update(update.id, (chat) => {
167
+ if (update.unreadCount > 0) {
168
+ update = { ...update }
169
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
170
+ }
171
+ Object.assign(chat, update)
172
+ })
173
+ if (!result) {
174
+ logger.debug({ update }, 'got update for non-existant chat')
175
+ }
176
+ }
177
+ })
178
+ ev.on('labels.edit', (label) => {
179
+ if (label.deleted) {
180
+ return labels.deleteById(label.id)
181
+ }
182
+ // WhatsApp can store only up to 20 labels
183
+ if (labels.count() < 20) {
184
+ return labels.upsertById(label.id, label)
185
+ }
186
+ logger.error('Labels count exceed')
187
+ })
188
+ ev.on('labels.association', ({ type, association }) => {
189
+ switch (type) {
190
+ case 'add':
191
+ labelAssociations.upsert(association)
192
+ break
193
+ case 'remove':
194
+ labelAssociations.delete(association)
195
+ break
196
+ default:
197
+ console.error(`unknown operation type [${type}]`)
198
+ }
199
+ })
200
+ ev.on('presence.update', ({ id, presences: update }) => {
201
+ presences[id] = presences[id] || {}
202
+ Object.assign(presences[id], update)
203
+ })
204
+ ev.on('chats.delete', (deletions) => {
205
+ for (const item of deletions) {
206
+ if (chats.get(item)) {
207
+ chats.deleteById(item)
208
+ }
209
+ }
210
+ })
211
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
212
+ switch (type) {
213
+ case 'append':
214
+ case 'notify':
215
+ for (const msg of newMessages) {
216
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid)
217
+ const list = assertMessageList(jid)
218
+ list.upsert(msg, 'append')
219
+ if (type === 'notify') {
220
+ if (!chats.get(jid)) {
221
+ ev.emit('chats.upsert', [
222
+ {
223
+ id: jid,
224
+ conversationTimestamp: (0, Utils_1.toNumber)(
225
+ msg.messageTimestamp
226
+ ),
227
+ unreadCount: 1
228
+ }
229
+ ])
230
+ }
231
+ }
232
+ }
233
+ break
234
+ }
235
+ })
236
+ ev.on('messages.update', (updates) => {
237
+ var _a
238
+ for (const { update, key } of updates) {
239
+ const list = assertMessageList((0, WABinary_1.jidNormalizedUser)(key.remoteJid))
240
+ if (update === null || update === void 0 ? void 0 : update.status) {
241
+ const listStatus =
242
+ (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status
243
+ if (
244
+ listStatus &&
245
+ (update === null || update === void 0 ? void 0 : update.status) <=
246
+ listStatus
247
+ ) {
248
+ logger.debug(
249
+ { update, storedStatus: listStatus },
250
+ 'status stored newer then update'
251
+ )
252
+ delete update.status
253
+ logger.debug({ update }, 'new update object')
254
+ }
255
+ }
256
+ const result = list.updateAssign(key.id, update)
257
+ if (!result) {
258
+ logger.debug({ update }, 'got update for non-existent message')
259
+ }
260
+ }
261
+ })
262
+ ev.on('messages.delete', (item) => {
263
+ if ('all' in item) {
264
+ const list = messages[item.jid]
265
+ list === null || list === void 0 ? void 0 : list.clear()
266
+ } else {
267
+ const jid = item.keys[0].remoteJid
268
+ const list = messages[jid]
269
+ if (list) {
270
+ const idSet = new Set(item.keys.map((k) => k.id))
271
+ list.filter((m) => !idSet.has(m.key.id))
272
+ }
273
+ }
274
+ })
275
+ ev.on('groups.update', (updates) => {
276
+ for (const update of updates) {
277
+ const id = update.id
278
+ if (groupMetadata[id]) {
279
+ Object.assign(groupMetadata[id], update)
280
+ } else {
281
+ logger.debug({ update }, 'got update for non-existant group metadata')
282
+ }
283
+ }
284
+ })
285
+ ev.on('group-participants.update', ({ id, participants, action }) => {
286
+ const metadata = groupMetadata[id]
287
+ if (metadata) {
288
+ switch (action) {
289
+ case 'add':
290
+ metadata.participants.push(
291
+ ...participants.map((id) => ({
292
+ id,
293
+ isAdmin: false,
294
+ isSuperAdmin: false
295
+ }))
296
+ )
297
+ break
298
+ case 'demote':
299
+ case 'promote':
300
+ for (const participant of metadata.participants) {
301
+ if (participants.includes(participant.id)) {
302
+ participant.isAdmin = action === 'promote'
303
+ }
304
+ }
305
+ break
306
+ case 'remove':
307
+ metadata.participants = metadata.participants.filter(
308
+ (p) => !participants.includes(p.id)
309
+ )
310
+ break
311
+ }
312
+ }
313
+ })
314
+ ev.on('message-receipt.update', (updates) => {
315
+ for (const { key, receipt } of updates) {
316
+ const obj = messages[key.remoteJid]
317
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id)
318
+ if (msg) {
319
+ ;(0, Utils_1.updateMessageWithReceipt)(msg, receipt)
320
+ }
321
+ }
322
+ })
323
+ ev.on('messages.reaction', (reactions) => {
324
+ for (const { key, reaction } of reactions) {
325
+ const obj = messages[key.remoteJid]
326
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id)
327
+ if (msg) {
328
+ ;(0, Utils_1.updateMessageWithReaction)(msg, reaction)
329
+ }
330
+ }
331
+ })
332
+ }
333
+ const toJSON = () => ({
334
+ chats,
335
+ contacts,
336
+ messages,
337
+ labels,
338
+ labelAssociations
339
+ })
340
+ const fromJSON = (json) => {
341
+ chats.upsert(...json.chats)
342
+ labelAssociations.upsert(...(json.labelAssociations || []))
343
+ contactsUpsert(Object.values(json.contacts))
344
+ labelsUpsert(Object.values(json.labels || {}))
345
+ for (const jid in json.messages) {
346
+ const list = assertMessageList(jid)
347
+ for (const msg of json.messages[jid]) {
348
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
349
+ }
350
+ }
351
+ }
352
+ return {
353
+ chats,
354
+ contacts,
355
+ messages,
356
+ groupMetadata,
357
+ state,
358
+ presences,
359
+ labels,
360
+ labelAssociations,
361
+ bind,
362
+ /** loads messages from the store, if not found -- uses the legacy connection */
363
+ loadMessages: async (jid, count, cursor) => {
364
+ const list = assertMessageList(jid)
365
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
366
+ const cursorKey = !!cursor
367
+ ? 'before' in cursor
368
+ ? cursor.before
369
+ : cursor.after
370
+ : undefined
371
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
372
+ let messages
373
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
374
+ if (cursorValue) {
375
+ const msgIdx = list.array.findIndex(
376
+ (m) =>
377
+ m.key.id ===
378
+ (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id)
379
+ )
380
+ messages = list.array.slice(0, msgIdx)
381
+ } else {
382
+ messages = list.array
383
+ }
384
+ const diff = count - messages.length
385
+ if (diff < 0) {
386
+ messages = messages.slice(-count) // get the last X messages
387
+ }
388
+ } else {
389
+ messages = []
390
+ }
391
+ return messages
392
+ },
393
+ /**
394
+ * Get all available labels for profile
395
+ *
396
+ * Keep in mind that the list is formed from predefined tags and tags
397
+ * that were "caught" during their editing.
398
+ */
399
+ getLabels: () => {
400
+ return labels
401
+ },
402
+ /**
403
+ * Get labels for chat
404
+ *
405
+ * @returns Label IDs
406
+ **/
407
+ getChatLabels: (chatId) => {
408
+ return labelAssociations.filter((la) => la.chatId === chatId).all()
409
+ },
410
+ /**
411
+ * Get labels for message
412
+ *
413
+ * @returns Label IDs
414
+ **/
415
+ getMessageLabels: (messageId) => {
416
+ const associations = labelAssociations.filter((la) => la.messageId === messageId).all()
417
+ return associations.map(({ labelId }) => labelId)
418
+ },
419
+ loadMessage: async (jid, id) => {
420
+ var _a
421
+ return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id)
422
+ },
423
+ mostRecentMessage: async (jid) => {
424
+ var _a
425
+ const message =
426
+ (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0]
427
+ return message
428
+ },
429
+ fetchImageUrl: async (jid, sock) => {
430
+ const contact = contacts[jid]
431
+ if (!contact) {
432
+ return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid)
433
+ }
434
+ if (typeof contact.imgUrl === 'undefined') {
435
+ contact.imgUrl = await (sock === null || sock === void 0
436
+ ? void 0
437
+ : sock.profilePictureUrl(jid))
438
+ }
439
+ return contact.imgUrl
440
+ },
441
+ fetchGroupMetadata: async (jid, sock) => {
442
+ if (!groupMetadata[jid]) {
443
+ const metadata = await (sock === null || sock === void 0
444
+ ? void 0
445
+ : sock.groupMetadata(jid))
446
+ if (metadata) {
447
+ groupMetadata[jid] = metadata
448
+ }
449
+ }
450
+ return groupMetadata[jid]
451
+ },
452
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
453
+ // if(!groupMetadata[jid]) {
454
+ // const metadata = await sock?.getBroadcastListInfo(jid)
455
+ // if(metadata) {
456
+ // groupMetadata[jid] = metadata
457
+ // }
458
+ // }
459
+ // return groupMetadata[jid]
460
+ // },
461
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
462
+ const list = messages[remoteJid]
463
+ const msg = list === null || list === void 0 ? void 0 : list.get(id)
464
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt
465
+ },
466
+ toJSON,
467
+ fromJSON,
468
+ writeToFile: (path) => {
469
+ // require fs here so that in case "fs" is not available -- the app does not crash
470
+ const { writeFileSync } = require('fs')
471
+ writeFileSync(path, JSON.stringify(toJSON()))
472
+ },
473
+ readFromFile: (path) => {
474
+ // require fs here so that in case "fs" is not available -- the app does not crash
475
+ const { readFileSync, existsSync } = require('fs')
476
+ if (existsSync(path)) {
477
+ logger.debug({ path }, 'reading from file')
478
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' })
479
+ const json = JSON.parse(jsonStr)
480
+ fromJSON(json)
481
+ }
482
+ }
483
+ }
484
+ }
@@ -0,0 +1,78 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ function makeOrderedDictionary(idGetter) {
4
+ const array = []
5
+ const dict = {}
6
+ const get = (id) => dict[id]
7
+ const update = (item) => {
8
+ const id = idGetter(item)
9
+ const idx = array.findIndex((i) => idGetter(i) === id)
10
+ if (idx >= 0) {
11
+ array[idx] = item
12
+ dict[id] = item
13
+ }
14
+ return false
15
+ }
16
+ const upsert = (item, mode) => {
17
+ const id = idGetter(item)
18
+ if (get(id)) {
19
+ update(item)
20
+ } else {
21
+ if (mode === 'append') {
22
+ array.push(item)
23
+ } else {
24
+ array.splice(0, 0, item)
25
+ }
26
+ dict[id] = item
27
+ }
28
+ }
29
+ const remove = (item) => {
30
+ const id = idGetter(item)
31
+ const idx = array.findIndex((i) => idGetter(i) === id)
32
+ if (idx >= 0) {
33
+ array.splice(idx, 1)
34
+ delete dict[id]
35
+ return true
36
+ }
37
+ return false
38
+ }
39
+ return {
40
+ array,
41
+ get,
42
+ upsert,
43
+ update,
44
+ remove,
45
+ updateAssign: (id, update) => {
46
+ const item = get(id)
47
+ if (item) {
48
+ Object.assign(item, update)
49
+ delete dict[id]
50
+ dict[idGetter(item)] = item
51
+ return true
52
+ }
53
+ return false
54
+ },
55
+ clear: () => {
56
+ array.splice(0, array.length)
57
+ Object.keys(dict).forEach((key) => {
58
+ delete dict[key]
59
+ })
60
+ },
61
+ filter: (contain) => {
62
+ let i = 0
63
+ while (i < array.length) {
64
+ if (!contain(array[i])) {
65
+ delete dict[idGetter(array[i])]
66
+ array.splice(i, 1)
67
+ } else {
68
+ i += 1
69
+ }
70
+ }
71
+ },
72
+ toJSON: () => array,
73
+ fromJSON: (newItems) => {
74
+ array.splice(0, array.length, ...newItems)
75
+ }
76
+ }
77
+ }
78
+ exports.default = makeOrderedDictionary
@@ -0,0 +1,27 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.ObjectRepository = void 0
4
+ class ObjectRepository {
5
+ constructor(entities = {}) {
6
+ this.entityMap = new Map(Object.entries(entities))
7
+ }
8
+ findById(id) {
9
+ return this.entityMap.get(id)
10
+ }
11
+ findAll() {
12
+ return Array.from(this.entityMap.values())
13
+ }
14
+ upsertById(id, entity) {
15
+ return this.entityMap.set(id, { ...entity })
16
+ }
17
+ deleteById(id) {
18
+ return this.entityMap.delete(id)
19
+ }
20
+ count() {
21
+ return this.entityMap.size
22
+ }
23
+ toJSON() {
24
+ return this.findAll()
25
+ }
26
+ }
27
+ exports.ObjectRepository = ObjectRepository
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
@@ -0,0 +1,10 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.ALL_WA_PATCH_NAMES = void 0
4
+ exports.ALL_WA_PATCH_NAMES = [
5
+ 'critical_block',
6
+ 'critical_unblock_low',
7
+ 'regular_high',
8
+ 'regular_low',
9
+ 'regular'
10
+ ]