@bellaxchuu/flowred 0.8.6

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 (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +214 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +190 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +92 -0
  12. package/lib/Signal/Group/group_cipher.js +89 -0
  13. package/lib/Signal/Group/index.js +136 -0
  14. package/lib/Signal/Group/keyhelper.js +73 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-message.js +69 -0
  18. package/lib/Signal/Group/sender-key-name.js +50 -0
  19. package/lib/Signal/Group/sender-key-record.js +44 -0
  20. package/lib/Signal/Group/sender-key-state.js +97 -0
  21. package/lib/Signal/Group/sender-message-key.js +30 -0
  22. package/lib/Signal/libsignal.js +490 -0
  23. package/lib/Signal/lid-mapping.js +262 -0
  24. package/lib/Socket/Client/index.js +30 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +62 -0
  27. package/lib/Socket/aigroups.js +240 -0
  28. package/lib/Socket/business.js +422 -0
  29. package/lib/Socket/chats.js +1816 -0
  30. package/lib/Socket/communities.js +549 -0
  31. package/lib/Socket/graphql.js +656 -0
  32. package/lib/Socket/groups.js +764 -0
  33. package/lib/Socket/index.js +39 -0
  34. package/lib/Socket/interactive-handler.js +522 -0
  35. package/lib/Socket/interop.js +549 -0
  36. package/lib/Socket/luxu.js +387 -0
  37. package/lib/Socket/managed-account.js +183 -0
  38. package/lib/Socket/messages-recv.js +2440 -0
  39. package/lib/Socket/messages-send.js +1853 -0
  40. package/lib/Socket/mex.js +60 -0
  41. package/lib/Socket/newsletter.js +820 -0
  42. package/lib/Socket/privacy.js +449 -0
  43. package/lib/Socket/registration.js +427 -0
  44. package/lib/Socket/socket.js +1092 -0
  45. package/lib/Socket/text-router.js +83 -0
  46. package/lib/Socket/username.js +243 -0
  47. package/lib/Store/index.js +36 -0
  48. package/lib/Store/keyed-db.js +108 -0
  49. package/lib/Store/make-cache-manager-store.js +90 -0
  50. package/lib/Store/make-in-memory-store.js +604 -0
  51. package/lib/Store/make-ordered-dictionary.js +81 -0
  52. package/lib/Store/object-repository.js +29 -0
  53. package/lib/Types/Auth.js +38 -0
  54. package/lib/Types/Bussines.js +2 -0
  55. package/lib/Types/Call.js +2 -0
  56. package/lib/Types/Chat.js +4 -0
  57. package/lib/Types/Contact.js +2 -0
  58. package/lib/Types/Events.js +2 -0
  59. package/lib/Types/GroupMetadata.js +2 -0
  60. package/lib/Types/Label.js +27 -0
  61. package/lib/Types/LabelAssociation.js +9 -0
  62. package/lib/Types/Message.js +95 -0
  63. package/lib/Types/Mex.js +112 -0
  64. package/lib/Types/Newsletter.js +121 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +70 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +55 -0
  71. package/lib/Utils/auth-utils.js +306 -0
  72. package/lib/Utils/browser-utils.js +114 -0
  73. package/lib/Utils/business.js +247 -0
  74. package/lib/Utils/chat-utils.js +1208 -0
  75. package/lib/Utils/command-loader.js +100 -0
  76. package/lib/Utils/companion-reg-client-utils.js +42 -0
  77. package/lib/Utils/consumer-application.js +107 -0
  78. package/lib/Utils/crypto.js +155 -0
  79. package/lib/Utils/curve25519-js.js +275 -0
  80. package/lib/Utils/decode-wa-message.js +560 -0
  81. package/lib/Utils/event-buffer.js +607 -0
  82. package/lib/Utils/generics.js +563 -0
  83. package/lib/Utils/group-history.js +60 -0
  84. package/lib/Utils/history.js +244 -0
  85. package/lib/Utils/identity-change-handler.js +52 -0
  86. package/lib/Utils/index.js +57 -0
  87. package/lib/Utils/jid-display-normalization.js +218 -0
  88. package/lib/Utils/link-preview.js +143 -0
  89. package/lib/Utils/logger.js +9 -0
  90. package/lib/Utils/lt-hash.js +39 -0
  91. package/lib/Utils/make-mutex.js +36 -0
  92. package/lib/Utils/message-composer.js +479 -0
  93. package/lib/Utils/message-retry-manager.js +270 -0
  94. package/lib/Utils/messages-media.js +896 -0
  95. package/lib/Utils/messages.js +2904 -0
  96. package/lib/Utils/meta-ai-msmsg.js +262 -0
  97. package/lib/Utils/native-bridge.js +82 -0
  98. package/lib/Utils/noise-handler.js +196 -0
  99. package/lib/Utils/offline-node-processor.js +42 -0
  100. package/lib/Utils/pre-key-manager.js +107 -0
  101. package/lib/Utils/process-message.js +1048 -0
  102. package/lib/Utils/reporting-utils.js +262 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.js +145 -0
  107. package/lib/Utils/sync-action-utils.js +54 -0
  108. package/lib/Utils/tc-token-utils.js +161 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/validate-connection.js +219 -0
  111. package/lib/Utils/view-once-cache.js +79 -0
  112. package/lib/Utils/voip-rekey.js +22 -0
  113. package/lib/WABinary/constants.js +1304 -0
  114. package/lib/WABinary/decode.js +343 -0
  115. package/lib/WABinary/encode.js +228 -0
  116. package/lib/WABinary/generic-utils.js +240 -0
  117. package/lib/WABinary/index.js +33 -0
  118. package/lib/WABinary/jid-utils.js +361 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +13 -0
  121. package/lib/WAM/constants.js +39486 -0
  122. package/lib/WAM/encode.js +142 -0
  123. package/lib/WAM/index.js +31 -0
  124. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  125. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  128. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  129. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  130. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  136. package/lib/WAUSync/Protocols/index.js +39 -0
  137. package/lib/WAUSync/USyncQuery.js +133 -0
  138. package/lib/WAUSync/USyncUser.js +50 -0
  139. package/lib/WAUSync/index.js +31 -0
  140. package/lib/antiban.js +4637 -0
  141. package/lib/index.js +45 -0
  142. package/package.json +107 -0
@@ -0,0 +1,83 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.attachTextRouter = void 0
4
+
5
+ const extractText = message => {
6
+ if (!message) return ''
7
+ return (
8
+ message.conversation ||
9
+ message.extendedTextMessage?.text ||
10
+ message.imageMessage?.caption ||
11
+ message.videoMessage?.caption ||
12
+ message.documentMessage?.caption ||
13
+ ''
14
+ )
15
+ }
16
+
17
+ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
18
+
19
+ /**
20
+ * Attaches Telegraf text routing to a socket:
21
+ * `sock.onText(pattern, handler)`, `sock.hears(pattern, handler)` (alias), and
22
+ * `sock.command(name, handler)`, instead of manually parsing every
23
+ * `messages.upsert` event by hand.
24
+ *
25
+ * - `pattern` as a RegExp: handler gets called as `handler(msg, match)` where
26
+ * `match` is the result of `pattern.exec(text)` (or null if only testing).
27
+ * - `pattern` as a string: matched literally (exact match) against the message
28
+ * text; `handler(msg, [text])` is called on match.
29
+ * - `sock.command('start', handler)`: matches `/start`, `/start@BotName`, and
30
+ * `/start extra args`, calling `handler(msg, match)` where `match[1]` is the
31
+ * text after the command (or undefined).
32
+ *
33
+ * All three return an unsubscribe function. Only one `messages.upsert`
34
+ * listener is registered regardless of how many routes are added.
35
+ */
36
+ const attachTextRouter = sock => {
37
+ const routes = []
38
+
39
+ const addRoute = (pattern, handler) => {
40
+ const route = { pattern, handler }
41
+ routes.push(route)
42
+ return () => {
43
+ const idx = routes.indexOf(route)
44
+ if (idx !== -1) routes.splice(idx, 1)
45
+ }
46
+ }
47
+
48
+ const dispatch = async ({ messages, type }) => {
49
+ if (type !== 'notify' && type !== 'append') return
50
+ for (const msg of messages) {
51
+ if (!msg.message || msg.key.fromMe) continue
52
+ const text = extractText(msg.message)
53
+ if (!text) continue
54
+ for (const route of routes.slice()) {
55
+ let match = null
56
+ if (route.pattern instanceof RegExp) {
57
+ route.pattern.lastIndex = 0
58
+ match = route.pattern.exec(text)
59
+ } else if (typeof route.pattern === 'string') {
60
+ match = text === route.pattern ? [text] : null
61
+ }
62
+ if (!match) continue
63
+ try {
64
+ await route.handler(msg, match)
65
+ } catch (error) {
66
+ sock.logger?.error?.({ error, text }, 'onText/hears handler threw')
67
+ }
68
+ }
69
+ }
70
+ }
71
+ sock.ev.on('messages.upsert', dispatch)
72
+
73
+ sock.onText = addRoute
74
+ sock.hears = addRoute
75
+ sock.command = (name, handler) => {
76
+ const names = (Array.isArray(name) ? name : [name]).map(escapeRegExp)
77
+ const pattern = new RegExp(`^/(?:${names.join('|')})(?:@\\S+)?(?:\\s+([\\s\\S]*))?$`, 'i')
78
+ return addRoute(pattern, handler)
79
+ }
80
+
81
+ return sock
82
+ }
83
+ exports.attachTextRouter = attachTextRouter
@@ -0,0 +1,243 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.makeUsernameSocket = void 0
4
+
5
+ const { executeWMexQuery } = require('./mex.js')
6
+ const { USyncQuery, USyncUser } = require('../WAUSync/index.js')
7
+ const { makeNewsletterSocket } = require('./newsletter.js')
8
+ const crypto = require('crypto')
9
+ /**
10
+ * w:mex query IDs for username operations.
11
+ *
12
+ * Source: whatsapp-android-mex_client_persist_ids.json (WA 2.26.26.4 APK assets)
13
+ * Cross-checked: live Frida capture on real device (wa-logger-2.26.26.4.js, 2026-06-30)
14
+ */
15
+ const USERNAME_QUERY_IDS = {
16
+ CHECK: '26124072630599518', // UsernameCheck
17
+ CHECK_MULTI: '27134626522840286', // UsernameCheckMulti
18
+ SET: '27108705368767936', // UsernameSet
19
+ GET: '32618050064506055', // UsernameGet
20
+ GET_RECOMMENDATIONS: '26077456248616957', // UsernameGetRecommendationsQuery
21
+ PIN_SET: '25529696019976770' // UsernamePinSet
22
+ }
23
+
24
+ /**
25
+ * Source enum values from EnumC141106Vn (UsernameCheck result)
26
+ * and EnumC141056Vi (rejection reasons) confirmed via C164057Wg.java
27
+ */
28
+ const USERNAME_CHECK_RESULT = {
29
+ SUCCESS: 'SUCCESS',
30
+ INVALID: 'INVALID'
31
+ }
32
+
33
+ const USERNAME_SOURCE = {
34
+ FB: 'FB',
35
+ IG: 'IG',
36
+ USER_INPUT: 'USER_INPUT',
37
+ SUGGESTION: 'SUGGESTION'
38
+ }
39
+
40
+ const makeUsernameSocket = config => {
41
+ const sock = makeNewsletterSocket(config)
42
+ const { query, generateMessageTag, executeUSyncQuery } = sock
43
+
44
+ const mexQuery = (variables, queryId, dataPath) =>
45
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag)
46
+
47
+ /**
48
+ * Check whether a username is available.
49
+ *
50
+ * @param {string} username - The @username to check (without @)
51
+ * @param {boolean} includeSuggestions - Request alternative suggestions when taken
52
+ * @returns {object}
53
+ * On success: { available: true, username }
54
+ * On taken: { available: false, username, suggestions: string[], rejectionReasons: string[], suggestionsEligible: boolean }
55
+ * On rate-limit: throws Boom with statusCode 429
56
+ *
57
+ * Confirmed fields from C164057Wg.java:
58
+ * data.xwa2_username_check.result → 'SUCCESS' | 'INVALID'
59
+ * data.xwa2_username_check.suggestions
60
+ * data.xwa2_username_check.rejection_reasons
61
+ * data.xwa2_username_check.suggestions_eligible
62
+ */
63
+ const checkUsername = async (username, includeSuggestions = true, sessionId) => {
64
+ // session_id ties this check to the subsequent set step — caller can pass one in
65
+ // so both use the same UUID (confirmed from live WA 2.26.26.4 capture).
66
+ const session_id = sessionId || crypto.randomUUID()
67
+ const data = await mexQuery(
68
+ {
69
+ username,
70
+ include_suggestions: includeSuggestions,
71
+ session_id,
72
+ source: USERNAME_SOURCE.USER_INPUT
73
+ },
74
+ USERNAME_QUERY_IDS.CHECK,
75
+ 'xwa2_username_check'
76
+ )
77
+ if (data?.includes(USERNAME_CHECK_RESULT.SUCCESS) || data?.result === USERNAME_CHECK_RESULT.SUCCESS) {
78
+ return { available: true, username, session_id }
79
+ }
80
+ return {
81
+ available: false,
82
+ username,
83
+ session_id,
84
+ suggestions: data?.suggestions?? [],
85
+ rejectionReasons: data?.rejection_reasons?? [],
86
+ suggestionsEligible: data?.suggestions_eligible?? true
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Set your own username.
92
+ *
93
+ * @param {string} username - The username to set (without @)
94
+ * @param {object} options
95
+ * @param {string} [options.source] - 'USER_INPUT' | 'FB' | 'IG' | 'SUGGESTION'
96
+ * @param {string} [options.sessionId] - Optional session tracking ID
97
+ * @param {string} [options.pin] - Optional PIN for protected usernames
98
+ *
99
+ * Confirmed variables from C1568872p.java A00():
100
+ * username, reserved (bool), session_id, source, pin
101
+ */
102
+ const setUsername = async (username, options = {}) => {
103
+ const { source = USERNAME_SOURCE.USER_INPUT, sessionId, pin } = options
104
+ // session_id links the check and set steps — generate one if caller doesn't supply it.
105
+ // reserved:true confirmed from live WA 2.26.26.4 capture (was wrongly false before).
106
+ const session_id = sessionId || crypto.randomUUID()
107
+ const variables = {
108
+ username,
109
+ reserved: true,
110
+ source,
111
+ session_id,
112
+ ...(pin? { pin } : {})
113
+ }
114
+ return mexQuery(variables, USERNAME_QUERY_IDS.SET, 'xwa2_username_set')
115
+ }
116
+
117
+ const checkAndSetUsername = async (username) => {
118
+ const r = await checkUsername(username)
119
+ if (r.available) {
120
+ return await setUsername(username)
121
+ }
122
+ return r
123
+ }
124
+
125
+ /**
126
+ * Delete (unset) your own username.
127
+ *
128
+ * Confirmed from C1568872p.java:
129
+ * str4 = str == null? "delete" : "set"
130
+ * → sending username=null triggers the delete path on the server.
131
+ */
132
+ const deleteUsername = async () => {
133
+ return mexQuery({ username: null }, USERNAME_QUERY_IDS.SET, 'xwa2_username_delete')
134
+ }
135
+
136
+ /**
137
+ * Get your own current username.
138
+ *
139
+ * Confirmed from C1568872p.java A02():
140
+ * AbstractC41851rT.A0L(AbstractC130045pa.A0T(), C1363664w.class, "UsernameGet", false)
141
+ */
142
+ const getMyUsername = async () => {
143
+ const data = await mexQuery({}, USERNAME_QUERY_IDS.GET, 'xwa2_username_get')
144
+ return data?.username?? null
145
+ }
146
+
147
+ /**
148
+ * Set or delete the PIN that protects your username.
149
+ *
150
+ * @param {string|null} pin - New PIN, or null to delete the PIN
151
+ *
152
+ * Confirmed from MexUsernamePinProtocolApi.java:
153
+ * operation "UsernamePinSet", variable "pin"
154
+ * pin=null triggers the "delete" path on the server.
155
+ */
156
+ const setUsernamePin = async pin => {
157
+ // pin=null → delete PIN (server interprets empty/null variables as delete)
158
+ const variables = pin!= null? { pin } : {}
159
+ return mexQuery(variables, USERNAME_QUERY_IDS.PIN_SET, 'xwa2_username_pin_set')
160
+ }
161
+
162
+ /**
163
+ * Look up a contact by their @username via USync.
164
+ *
165
+ * Confirmed via USyncContactProtocol.getUserElement():
166
+ * { tag: 'contact', attrs: { username, pin? } }
167
+ *
168
+ * @param {string} username - The username to look up (without @)
169
+ * @param {string} [pin] - Optional PIN if the username is PIN-protected
170
+ * @returns {{ jid, lid?, contact: boolean }|null}
171
+ */
172
+ const findUserByUsername = async (username, pin) => {
173
+ const usyncQuery = new USyncQuery().withContactProtocol()
174
+ const user = new USyncUser().withUsername(username)
175
+ if (pin) user.withUsernameKey(pin)
176
+ usyncQuery.withUser(user)
177
+ const result = await executeUSyncQuery(usyncQuery)
178
+ if (!result?.list?.length) return null
179
+ const entry = result.list[0]
180
+ return {
181
+ jid: entry.id,
182
+ contact: entry.contact?? false
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Fetch the username of one or more contacts by their JID.
188
+ * Uses USync with the username protocol.
189
+ *
190
+ * @param {...string} jids - One or more JIDs
191
+ * @returns {Array<{ id, username: string|null }>}
192
+ */
193
+ const fetchContactUsernames = async (...jids) => {
194
+ const usyncQuery = new USyncQuery().withUsernameProtocol()
195
+ for (const jid of jids) {
196
+ usyncQuery.withUser(new USyncUser().withId(jid))
197
+ }
198
+ const result = await executeUSyncQuery(usyncQuery)
199
+ return result?.list?? []
200
+ }
201
+
202
+ /**
203
+ * Check multiple usernames for availability at once.
204
+ * @param {string[]} usernames - Array of usernames (without @)
205
+ */
206
+ const checkUsernameMulti = async usernames => {
207
+ const data = await mexQuery(
208
+ { usernames },
209
+ USERNAME_QUERY_IDS.CHECK_MULTI,
210
+ 'xwa2_username_check_multi'
211
+ )
212
+ return data
213
+ }
214
+
215
+ /**
216
+ * Fetch username recommendations for the current user.
217
+ * @param {string} [source] - Source hint: 'FB' | 'IG' | 'USER_INPUT'
218
+ */
219
+ const getUsernameRecommendations = async (source = null) => {
220
+ const variables = {}
221
+ if (source) variables.source = source
222
+ return mexQuery(variables, USERNAME_QUERY_IDS.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations')
223
+ }
224
+
225
+ return {
226
+ ...sock,
227
+ checkUsername,
228
+ checkUsernameMulti,
229
+ setUsername,
230
+ deleteUsername,
231
+ getMyUsername,
232
+ getUsernameRecommendations,
233
+ setUsernamePin,
234
+ findUserByUsername,
235
+ fetchContactUsernames,
236
+ checkAndSetUsername,
237
+ USERNAME_QUERY_IDS,
238
+ USERNAME_CHECK_RESULT,
239
+ USERNAME_SOURCE
240
+ }
241
+ }
242
+
243
+ exports.makeUsernameSocket = makeUsernameSocket
@@ -0,0 +1,36 @@
1
+ 'use strict'
2
+
3
+ var __createBinding =
4
+ (this && this.__createBinding) ||
5
+ (Object.create
6
+ ? function (o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k
8
+ var desc = Object.getOwnPropertyDescriptor(m, k)
9
+ if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = {
11
+ enumerable: true,
12
+ get: function () {
13
+ return m[k]
14
+ }
15
+ }
16
+ }
17
+ Object.defineProperty(o, k2, desc)
18
+ }
19
+ : function (o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k
21
+ o[k2] = m[k]
22
+ })
23
+
24
+ var __exportStar =
25
+ (this && this.__exportStar) ||
26
+ function (m, exports) {
27
+ for (var p in m)
28
+ if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p)
29
+ }
30
+
31
+ Object.defineProperty(exports, '__esModule', { value: true })
32
+
33
+ __exportStar(require('./make-cache-manager-store'), exports)
34
+ __exportStar(require('./make-in-memory-store'), exports)
35
+ __exportStar(require('./make-ordered-dictionary'), exports)
36
+ __exportStar(require('./object-repository'), exports)
@@ -0,0 +1,108 @@
1
+ export default class KeyedDB {
2
+ constructor(compareFn, idGetter) {
3
+ if (typeof compareFn !== "function" || typeof idGetter !== "function") {
4
+ throw new Error("KeyedDB requires compare and idGetter functions");
5
+ }
6
+ this._compare = compareFn;
7
+ this._idGetter = idGetter;
8
+ this._array = [];
9
+ this._dict = {};
10
+ }
11
+ get length() {
12
+ return this._array.length;
13
+ }
14
+ get(id) {
15
+ return this._dict[id];
16
+ }
17
+ insert(entry, mode = "insert") {
18
+ const id = this._idGetter(entry);
19
+ const existing = this._dict[id];
20
+ if (existing && mode === "insert") {
21
+ return false;
22
+ }
23
+ this._dict[id] = entry;
24
+ let inserted = false;
25
+ for (let i = 0; i < this._array.length; i++) {
26
+ const cmp = this._compare(this._idGetter(this._array[i]), id);
27
+ if (cmp < 0) {
28
+ this._array.splice(i, 0, entry);
29
+ inserted = true;
30
+ break;
31
+ }
32
+ }
33
+ if (!inserted) this._array.push(entry);
34
+ return true;
35
+ }
36
+ insertIfAbsent(...entries) {
37
+ const added = [];
38
+ for (const entry of entries) {
39
+ if (!this._dict[this._idGetter(entry)]) {
40
+ this.insert(entry);
41
+ added.push(entry);
42
+ }
43
+ }
44
+ return added;
45
+ }
46
+ upsert(...entries) {
47
+ const added = [];
48
+ for (const entry of entries) {
49
+ const id = this._idGetter(entry);
50
+ if (this._dict[id]) {
51
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
52
+ if (idx >= 0) this._array[idx] = entry;
53
+ this._dict[id] = entry;
54
+ } else {
55
+ this.insert(entry);
56
+ added.push(entry);
57
+ }
58
+ }
59
+ return added;
60
+ }
61
+ update(id, updater) {
62
+ const item = this._dict[id];
63
+ if (!item) return false;
64
+ updater(item);
65
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
66
+ if (idx >= 0) this._array[idx] = item;
67
+ return true;
68
+ }
69
+ updateAssign(id, update) {
70
+ const item = this._dict[id];
71
+ if (!item) return false;
72
+ Object.assign(item, update);
73
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
74
+ if (idx >= 0) this._array[idx] = item;
75
+ return true;
76
+ }
77
+ deleteById(id) {
78
+ if (!this._dict[id]) return false;
79
+ delete this._dict[id];
80
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
81
+ if (idx >= 0) this._array.splice(idx, 1);
82
+ return true;
83
+ }
84
+ clear() {
85
+ this._array = [];
86
+ this._dict = {};
87
+ }
88
+ all() {
89
+ return [...this._array];
90
+ }
91
+ filter(predicate) {
92
+ this._array = this._array.filter(predicate);
93
+ this._dict = {};
94
+ for (const entry of this._array) {
95
+ this._dict[this._idGetter(entry)] = entry;
96
+ }
97
+ }
98
+ count() {
99
+ return this._array.length;
100
+ }
101
+ toJSON() {
102
+ return this._array;
103
+ }
104
+ fromJSON(array) {
105
+ this.clear();
106
+ for (const entry of array) this.insert(entry);
107
+ }
108
+ }
@@ -0,0 +1,90 @@
1
+ 'use strict'
2
+
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod }
7
+ }
8
+
9
+ Object.defineProperty(exports, '__esModule', { value: true })
10
+
11
+ const cache_manager_1 = require('cache-manager')
12
+ const WAProto_1 = require('../../WAProto')
13
+ const Utils_1 = require('../Utils')
14
+ const logger_1 = __importDefault(require('../Utils/logger'))
15
+
16
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
17
+ const defaultKey = file => `${sessionKey}:${file}`
18
+ const databaseConn = await cache_manager_1.caching(store)
19
+ const writeData = async (file, data) => {
20
+ let ttl = undefined
21
+ if (file === 'creds') {
22
+ ttl = 63115200 // 2 years
23
+ }
24
+ await databaseConn.set(defaultKey(file), JSON.stringify(data, Utils_1.BufferJSON.replacer), ttl)
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 (err) {
42
+ logger_1.default.error({ err }, `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
+ logger_1.default.warn({ err }, 'clearState failed')
51
+ }
52
+ }
53
+ const creds = (await readData('creds')) || (0, Utils_1.initAuthCreds)()
54
+ return {
55
+ clearState,
56
+ saveCreds: () => writeData('creds', creds),
57
+ state: {
58
+ creds,
59
+ keys: {
60
+ get: async (type, ids) => {
61
+ const data = {}
62
+ await Promise.all(
63
+ ids.map(async id => {
64
+ let value = await readData(`${type}-${id}`)
65
+ if (type === 'app-state-sync-key' && value) {
66
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
67
+ }
68
+ data[id] = value
69
+ })
70
+ )
71
+ return data
72
+ },
73
+ set: async data => {
74
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
+ const tasks = []
76
+ for (const category in data) {
77
+ for (const id in data[category]) {
78
+ const value = data[category][id]
79
+ const key = `${category}-${id}`
80
+ tasks.push(value ? writeData(key, value) : removeData(key))
81
+ }
82
+ }
83
+ await Promise.all(tasks)
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ exports.makeCacheManagerAuthState = makeCacheManagerAuthState