@hbmodsofc/baileys 1.7.7 → 2.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.
Files changed (155) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/index.js +157084 -24729
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +8 -12
  5. package/lib/Defaults/index.js +124 -90
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/group_cipher.d.ts +1 -0
  8. package/lib/Signal/Group/group_cipher.js +39 -28
  9. package/lib/Signal/Group/queue-job.d.ts +1 -0
  10. package/lib/Signal/Group/queue-job.js +57 -0
  11. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  12. package/lib/Signal/Group/sender-chain-key.js +2 -9
  13. package/lib/Signal/Group/sender-key-distribution-message.js +3 -3
  14. package/lib/Signal/Group/sender-key-message.js +3 -3
  15. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  16. package/lib/Signal/Group/sender-key-state.js +16 -47
  17. package/lib/Signal/libsignal.d.ts +3 -7
  18. package/lib/Signal/libsignal.js +39 -224
  19. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +3 -1
  20. package/lib/Socket/Client/index.d.ts +3 -2
  21. package/lib/Socket/Client/index.js +3 -2
  22. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  24. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  25. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +16 -10
  26. package/lib/Socket/business.d.ts +78 -94
  27. package/lib/Socket/business.js +11 -130
  28. package/lib/Socket/chats.d.ts +233 -63
  29. package/lib/Socket/chats.js +184 -234
  30. package/lib/Socket/groups.d.ts +41 -62
  31. package/lib/Socket/groups.js +64 -76
  32. package/lib/Socket/hbmods.d.ts +253 -0
  33. package/lib/Socket/hbmods.js +1 -0
  34. package/lib/Socket/index.d.ts +83 -129
  35. package/lib/Socket/index.js +6 -13
  36. package/lib/Socket/messages-recv.d.ts +48 -59
  37. package/lib/Socket/messages-recv.js +371 -516
  38. package/lib/Socket/messages-send.d.ts +67 -86
  39. package/lib/Socket/messages-send.js +1 -1091
  40. package/lib/Socket/newsletter.d.ts +64 -76
  41. package/lib/Socket/newsletter.js +1 -184
  42. package/lib/Socket/registration.d.ts +267 -0
  43. package/lib/Socket/registration.js +166 -0
  44. package/lib/Socket/socket.d.ts +13 -19
  45. package/lib/Socket/socket.js +1 -805
  46. package/lib/Socket/usync.d.ts +36 -0
  47. package/lib/Socket/usync.js +70 -0
  48. package/lib/Types/Auth.d.ts +10 -4
  49. package/lib/Types/Call.d.ts +1 -1
  50. package/lib/Types/Chat.d.ts +9 -29
  51. package/lib/Types/Chat.js +1 -7
  52. package/lib/Types/Contact.d.ts +1 -5
  53. package/lib/Types/Events.d.ts +14 -55
  54. package/lib/Types/GroupMetadata.d.ts +5 -15
  55. package/lib/Types/Label.d.ts +0 -11
  56. package/lib/Types/Label.js +1 -1
  57. package/lib/Types/LabelAssociation.js +1 -1
  58. package/lib/Types/Message.d.ts +49 -75
  59. package/lib/Types/Message.js +7 -10
  60. package/lib/Types/Newsletter.d.ts +98 -129
  61. package/lib/Types/Newsletter.js +38 -33
  62. package/lib/Types/Product.d.ts +1 -1
  63. package/lib/Types/Signal.d.ts +1 -29
  64. package/lib/Types/Socket.d.ts +22 -48
  65. package/lib/Types/State.d.ts +2 -13
  66. package/lib/Types/State.js +0 -12
  67. package/lib/Types/USync.d.ts +1 -1
  68. package/lib/Types/index.d.ts +3 -10
  69. package/lib/Types/index.js +2 -2
  70. package/lib/Utils/auth-utils.d.ts +3 -3
  71. package/lib/Utils/auth-utils.js +102 -378
  72. package/lib/Utils/baileys-event-stream.js +1 -1
  73. package/lib/Utils/business.d.ts +2 -2
  74. package/lib/Utils/business.js +13 -19
  75. package/lib/Utils/chat-utils.d.ts +22 -21
  76. package/lib/Utils/chat-utils.js +154 -201
  77. package/lib/Utils/crypto.d.ts +19 -18
  78. package/lib/Utils/crypto.js +37 -78
  79. package/lib/Utils/decode-wa-message.d.ts +7 -34
  80. package/lib/Utils/decode-wa-message.js +66 -138
  81. package/lib/Utils/event-buffer.d.ts +8 -6
  82. package/lib/Utils/event-buffer.js +43 -81
  83. package/lib/Utils/generics.d.ts +27 -27
  84. package/lib/Utils/generics.js +133 -128
  85. package/lib/Utils/history.d.ts +5 -9
  86. package/lib/Utils/history.js +23 -17
  87. package/lib/Utils/index.d.ts +0 -2
  88. package/lib/Utils/index.js +0 -2
  89. package/lib/Utils/link-preview.d.ts +4 -4
  90. package/lib/Utils/link-preview.js +12 -40
  91. package/lib/Utils/logger.d.ts +3 -11
  92. package/lib/Utils/lt-hash.d.ts +8 -8
  93. package/lib/Utils/lt-hash.js +24 -23
  94. package/lib/Utils/make-mutex.d.ts +2 -2
  95. package/lib/Utils/make-mutex.js +2 -3
  96. package/lib/Utils/messages-media.d.ts +41 -37
  97. package/lib/Utils/messages-media.js +368 -252
  98. package/lib/Utils/messages.d.ts +15 -13
  99. package/lib/Utils/messages.js +261 -274
  100. package/lib/Utils/noise-handler.d.ts +15 -13
  101. package/lib/Utils/noise-handler.js +26 -20
  102. package/lib/Utils/process-message.d.ts +8 -9
  103. package/lib/Utils/process-message.js +93 -157
  104. package/lib/Utils/signal.d.ts +5 -6
  105. package/lib/Utils/signal.js +29 -37
  106. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  107. package/lib/Utils/use-multi-file-auth-state.js +7 -12
  108. package/lib/Utils/validate-connection.d.ts +6 -5
  109. package/lib/Utils/validate-connection.js +97 -39
  110. package/lib/WABinary/constants.d.ts +27 -24
  111. package/lib/WABinary/constants.js +13 -1276
  112. package/lib/WABinary/decode.d.ts +4 -3
  113. package/lib/WABinary/decode.js +14 -28
  114. package/lib/WABinary/encode.d.ts +2 -1
  115. package/lib/WABinary/encode.js +147 -134
  116. package/lib/WABinary/generic-utils.d.ts +7 -4
  117. package/lib/WABinary/generic-utils.js +125 -40
  118. package/lib/WABinary/jid-utils.d.ts +8 -13
  119. package/lib/WABinary/jid-utils.js +16 -27
  120. package/lib/WAM/BinaryInfo.d.ts +11 -2
  121. package/lib/WAM/constants.d.ts +2 -3
  122. package/lib/WAM/constants.js +2359 -2252
  123. package/lib/WAM/encode.d.ts +2 -1
  124. package/lib/WAM/encode.js +11 -8
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +2 -2
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +4 -3
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  128. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +5 -5
  129. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +5 -5
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +6 -5
  133. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +2 -2
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -4
  136. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +3 -11
  137. package/lib/WAUSync/USyncQuery.d.ts +2 -2
  138. package/lib/WAUSync/USyncQuery.js +15 -19
  139. package/lib/WAUSync/USyncUser.d.ts +5 -5
  140. package/lib/WAUSync/index.d.ts +1 -1
  141. package/lib/WAUSync/index.js +1 -1
  142. package/package.json +102 -102
  143. package/lib/Signal/lid-mapping.d.ts +0 -26
  144. package/lib/Signal/lid-mapping.js +0 -146
  145. package/lib/Socket/communities.d.ts +0 -232
  146. package/lib/Socket/communities.js +0 -402
  147. package/lib/Socket/mex.d.ts +0 -2
  148. package/lib/Socket/mex.js +0 -45
  149. package/lib/Types/Bussines.d.ts +0 -24
  150. package/lib/Types/Bussines.js +0 -2
  151. package/lib/Utils/lidToJid-test.d.ts +0 -11
  152. package/lib/Utils/lidToJid-test.js +0 -27
  153. package/lib/Utils/message-retry-manager.d.ts +0 -81
  154. package/lib/Utils/message-retry-manager.js +0 -152
  155. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -3,12 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initAuthCreds = exports.addTransactionCapability = void 0;
7
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const async_mutex_1 = require("async-mutex");
6
+ exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
10
7
  const crypto_1 = require("crypto");
11
- const lru_cache_1 = require("lru-cache");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const uuid_1 = require("uuid");
12
10
  const Defaults_1 = require("../Defaults");
13
11
  const crypto_2 = require("./crypto");
14
12
  const generics_1 = require("./generics");
@@ -19,203 +17,59 @@ const generics_1 = require("./generics");
19
17
  * @param _cache cache store to use
20
18
  */
21
19
  function makeCacheableSignalKeyStore(store, logger, _cache) {
22
- const cache = _cache ||
23
- new node_cache_1.default({
24
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
25
- useClones: false,
26
- deleteOnExpire: true
27
- });
28
- // Mutex for protecting cache operations
29
- const cacheMutex = new async_mutex_1.Mutex();
20
+ const cache = _cache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
22
+ useClones: false,
23
+ deleteOnExpire: true,
24
+ });
30
25
  function getUniqueId(type, id) {
31
26
  return `${type}.${id}`;
32
27
  }
33
28
  return {
34
29
  async get(type, ids) {
35
- return cacheMutex.runExclusive(async () => {
36
- const data = {};
37
- const idsToFetch = [];
38
- for (const id of ids) {
39
- const item = cache.get(getUniqueId(type, id));
40
- if (typeof item !== 'undefined') {
41
- data[id] = item;
42
- }
43
- else {
44
- idsToFetch.push(id);
45
- }
30
+ const data = {};
31
+ const idsToFetch = [];
32
+ for (const id of ids) {
33
+ const item = cache.get(getUniqueId(type, id));
34
+ if (typeof item !== 'undefined') {
35
+ data[id] = item;
46
36
  }
47
- if (idsToFetch.length) {
48
- logger?.trace({ items: idsToFetch.length }, 'loading from store');
49
- const fetched = await store.get(type, idsToFetch);
50
- for (const id of idsToFetch) {
51
- const item = fetched[id];
52
- if (item) {
53
- data[id] = item;
54
- cache.set(getUniqueId(type, id), item);
55
- }
37
+ else {
38
+ idsToFetch.push(id);
39
+ }
40
+ }
41
+ if (idsToFetch.length) {
42
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
43
+ const fetched = await store.get(type, idsToFetch);
44
+ for (const id of idsToFetch) {
45
+ const item = fetched[id];
46
+ if (item) {
47
+ data[id] = item;
48
+ cache.set(getUniqueId(type, id), item);
56
49
  }
57
50
  }
58
- return data;
59
- });
51
+ }
52
+ return data;
60
53
  },
61
54
  async set(data) {
62
- return cacheMutex.runExclusive(async () => {
63
- let keys = 0;
64
- for (const type in data) {
65
- for (const id in data[type]) {
66
- await cache.set(getUniqueId(type, id), data[type][id]);
67
- keys += 1;
68
- }
55
+ let keys = 0;
56
+ for (const type in data) {
57
+ for (const id in data[type]) {
58
+ cache.set(getUniqueId(type, id), data[type][id]);
59
+ keys += 1;
69
60
  }
70
- logger?.trace({ keys }, 'updated cache');
71
- await store.set(data);
72
- });
61
+ }
62
+ logger.trace({ keys }, 'updated cache');
63
+ await store.set(data);
73
64
  },
74
65
  async clear() {
75
- await cache.flushAll();
76
- await store.clear?.();
66
+ var _a;
67
+ cache.flushAll();
68
+ await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
77
69
  }
78
70
  };
79
71
  }
80
- // Module-level specialized mutexes for pre-key operations
81
- const preKeyMutex = new async_mutex_1.Mutex();
82
- const signedPreKeyMutex = new async_mutex_1.Mutex();
83
- /**
84
- * Get the appropriate mutex for the key type
85
- */
86
- const getPreKeyMutex = (keyType) => {
87
- return keyType === 'signed-pre-key' ? signedPreKeyMutex : preKeyMutex;
88
- };
89
- /**
90
- * Handles pre-key operations with mutex protection
91
- */
92
- async function handlePreKeyOperations(data, keyType, transactionCache, mutations, logger, isInTransaction, state) {
93
- const mutex = getPreKeyMutex(keyType);
94
- await mutex.runExclusive(async () => {
95
- const keyData = data[keyType];
96
- if (!keyData)
97
- return;
98
- // Ensure structures exist
99
- transactionCache[keyType] = transactionCache[keyType] || {};
100
- mutations[keyType] = mutations[keyType] || {};
101
- // Separate deletions from updates for batch processing
102
- const deletionKeys = [];
103
- const updateKeys = [];
104
- for (const keyId in keyData) {
105
- if (keyData[keyId] === null) {
106
- deletionKeys.push(keyId);
107
- }
108
- else {
109
- updateKeys.push(keyId);
110
- }
111
- }
112
- // Process updates first (no validation needed)
113
- for (const keyId of updateKeys) {
114
- if (transactionCache[keyType]) {
115
- transactionCache[keyType][keyId] = keyData[keyId];
116
- }
117
- if (mutations[keyType]) {
118
- mutations[keyType][keyId] = keyData[keyId];
119
- }
120
- }
121
- // Process deletions with validation
122
- if (deletionKeys.length === 0)
123
- return;
124
- if (isInTransaction) {
125
- // In transaction, only allow deletion if key exists in cache
126
- for (const keyId of deletionKeys) {
127
- if (transactionCache[keyType]) {
128
- transactionCache[keyType][keyId] = null;
129
- if (mutations[keyType]) {
130
- // Mark for deletion in mutations
131
- mutations[keyType][keyId] = null;
132
- }
133
- }
134
- else {
135
- logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
136
- }
137
- }
138
- return;
139
- }
140
- // Outside transaction, batch validate all deletions
141
- if (!state)
142
- return;
143
- const existingKeys = await state.get(keyType, deletionKeys);
144
- for (const keyId of deletionKeys) {
145
- if (existingKeys[keyId]) {
146
- if (transactionCache[keyType])
147
- transactionCache[keyType][keyId] = null;
148
- if (mutations[keyType])
149
- mutations[keyType][keyId] = null;
150
- }
151
- else {
152
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
153
- }
154
- }
155
- });
156
- }
157
- /**
158
- * Handles normal key operations for transactions
159
- */
160
- function handleNormalKeyOperations(data, key, transactionCache, mutations) {
161
- Object.assign(transactionCache[key], data[key]);
162
- mutations[key] = mutations[key] || {};
163
- Object.assign(mutations[key], data[key]);
164
- }
165
- /**
166
- * Process pre-key deletions with validation
167
- */
168
- async function processPreKeyDeletions(data, keyType, state, logger) {
169
- const mutex = getPreKeyMutex(keyType);
170
- await mutex.runExclusive(async () => {
171
- const keyData = data[keyType];
172
- if (!keyData)
173
- return;
174
- // Validate deletions
175
- for (const keyId in keyData) {
176
- if (keyData[keyId] === null) {
177
- const existingKeys = await state.get(keyType, [keyId]);
178
- if (!existingKeys[keyId]) {
179
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
180
- if (data[keyType])
181
- delete data[keyType][keyId];
182
- }
183
- }
184
- }
185
- });
186
- }
187
- /**
188
- * Executes a function with mutexes acquired for given key types
189
- * Uses async-mutex's runExclusive with efficient batching
190
- */
191
- async function withMutexes(keyTypes, getKeyTypeMutex, fn) {
192
- if (keyTypes.length === 0) {
193
- return fn();
194
- }
195
- if (keyTypes.length === 1) {
196
- return getKeyTypeMutex(keyTypes[0]).runExclusive(fn);
197
- }
198
- // For multiple mutexes, sort by key type to prevent deadlocks
199
- // Then acquire all mutexes in order using Promise.all for better efficiency
200
- const sortedKeyTypes = [...keyTypes].sort();
201
- const mutexes = sortedKeyTypes.map(getKeyTypeMutex);
202
- // Acquire all mutexes in order to prevent deadlocks
203
- const releases = [];
204
- try {
205
- for (const mutex of mutexes) {
206
- releases.push(await mutex.acquire());
207
- }
208
- return await fn();
209
- }
210
- finally {
211
- // Release in reverse order
212
- while (releases.length > 0) {
213
- const release = releases.pop();
214
- if (release)
215
- release();
216
- }
217
- }
218
- }
72
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
219
73
  /**
220
74
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
221
75
  * this allows batch read & write operations & improves the performance of the lib
@@ -229,116 +83,24 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
229
83
  let dbQueriesInTransaction = 0;
230
84
  let transactionCache = {};
231
85
  let mutations = {};
232
- // LRU Cache to hold mutexes for different key types
233
- const mutexCache = new lru_cache_1.LRUCache({
234
- ttl: 60 * 60 * 1000, // 1 hour
235
- ttlAutopurge: true,
236
- updateAgeOnGet: true
237
- });
238
86
  let transactionsInProgress = 0;
239
- function getKeyTypeMutex(type) {
240
- return getMutex(`keytype:${type}`);
241
- }
242
- function getSenderKeyMutex(senderKeyName) {
243
- return getMutex(`senderkey:${senderKeyName}`);
244
- }
245
- function getTransactionMutex(key) {
246
- return getMutex(`transaction:${key}`);
247
- }
248
- // Get or create a mutex for a specific key name
249
- function getMutex(key) {
250
- let mutex = mutexCache.get(key);
251
- if (!mutex) {
252
- mutex = new async_mutex_1.Mutex();
253
- mutexCache.set(key, mutex);
254
- logger.info({ key }, 'created new mutex');
255
- }
256
- return mutex;
257
- }
258
- // Sender key operations with proper mutex sequencing
259
- function queueSenderKeyOperation(senderKeyName, operation) {
260
- return getSenderKeyMutex(senderKeyName).runExclusive(operation);
261
- }
262
- // Check if we are currently in a transaction
263
- function isInTransaction() {
264
- return transactionsInProgress > 0;
265
- }
266
- // Helper function to handle transaction commit with retries
267
- async function commitTransaction() {
268
- if (!Object.keys(mutations).length) {
269
- logger.trace('no mutations in transaction');
270
- return;
271
- }
272
- logger.trace('committing transaction');
273
- let tries = maxCommitRetries;
274
- while (tries > 0) {
275
- tries -= 1;
276
- try {
277
- await state.set(mutations);
278
- logger.trace({ dbQueriesInTransaction }, 'committed transaction');
279
- return;
280
- }
281
- catch (error) {
282
- logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
283
- if (tries > 0) {
284
- await (0, generics_1.delay)(delayBetweenTriesMs);
285
- }
286
- }
287
- }
288
- }
289
- // Helper function to clean up transaction state
290
- function cleanupTransactionState() {
291
- transactionsInProgress -= 1;
292
- if (transactionsInProgress === 0) {
293
- transactionCache = {};
294
- mutations = {};
295
- dbQueriesInTransaction = 0;
296
- }
297
- }
298
- // Helper function to execute work within transaction
299
- async function executeTransactionWork(work) {
300
- const result = await work();
301
- // commit if this is the outermost transaction
302
- if (transactionsInProgress === 1) {
303
- await commitTransaction();
304
- }
305
- return result;
306
- }
307
87
  return {
308
88
  get: async (type, ids) => {
309
89
  if (isInTransaction()) {
310
90
  const dict = transactionCache[type];
311
- const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids;
91
+ const idsRequiringFetch = dict
92
+ ? ids.filter(item => typeof dict[item] === 'undefined')
93
+ : ids;
312
94
  // only fetch if there are any items to fetch
313
95
  if (idsRequiringFetch.length) {
314
96
  dbQueriesInTransaction += 1;
315
- // Use per-sender-key queue for sender-key operations when possible
316
- if (type === 'sender-key') {
317
- logger.info({ idsRequiringFetch }, 'processing sender keys in transaction');
318
- // For sender keys, process each one with queued operations to maintain serialization
319
- for (const senderKeyName of idsRequiringFetch) {
320
- await queueSenderKeyOperation(senderKeyName, async () => {
321
- logger.info({ senderKeyName }, 'fetching sender key in transaction');
322
- const result = await state.get(type, [senderKeyName]);
323
- // Update transaction cache
324
- transactionCache[type] || (transactionCache[type] = {});
325
- Object.assign(transactionCache[type], result);
326
- logger.info({ senderKeyName, hasResult: !!result[senderKeyName] }, 'sender key fetch complete');
327
- });
328
- }
329
- }
330
- else {
331
- // Use runExclusive for cleaner mutex handling
332
- await getKeyTypeMutex(type).runExclusive(async () => {
333
- const result = await state.get(type, idsRequiringFetch);
334
- // Update transaction cache
335
- transactionCache[type] || (transactionCache[type] = {});
336
- Object.assign(transactionCache[type], result);
337
- });
338
- }
97
+ const result = await state.get(type, idsRequiringFetch);
98
+ transactionCache[type] || (transactionCache[type] = {});
99
+ Object.assign(transactionCache[type], result);
339
100
  }
340
101
  return ids.reduce((dict, id) => {
341
- const value = transactionCache[type]?.[id];
102
+ var _a;
103
+ const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
342
104
  if (value) {
343
105
  dict[id] = value;
344
106
  }
@@ -346,115 +108,71 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
346
108
  }, {});
347
109
  }
348
110
  else {
349
- // Not in transaction, fetch directly with queue protection
350
- if (type === 'sender-key') {
351
- // For sender keys, use individual queues to maintain per-key serialization
352
- const results = {};
353
- for (const senderKeyName of ids) {
354
- const result = await queueSenderKeyOperation(senderKeyName, async () => await state.get(type, [senderKeyName]));
355
- Object.assign(results, result);
356
- }
357
- return results;
358
- }
359
- else {
360
- return await getKeyTypeMutex(type).runExclusive(() => state.get(type, ids));
361
- }
111
+ return state.get(type, ids);
362
112
  }
363
113
  },
364
- set: async (data) => {
114
+ set: data => {
365
115
  if (isInTransaction()) {
366
116
  logger.trace({ types: Object.keys(data) }, 'caching in transaction');
367
- for (const key_ in data) {
368
- const key = key_;
117
+ for (const key in data) {
369
118
  transactionCache[key] = transactionCache[key] || {};
370
- // Special handling for pre-keys and signed-pre-keys
371
- if (key === 'pre-key') {
372
- await handlePreKeyOperations(data, key, transactionCache, mutations, logger, true);
373
- }
374
- else {
375
- // Normal handling for other key types
376
- handleNormalKeyOperations(data, key, transactionCache, mutations);
377
- }
119
+ Object.assign(transactionCache[key], data[key]);
120
+ mutations[key] = mutations[key] || {};
121
+ Object.assign(mutations[key], data[key]);
378
122
  }
379
123
  }
380
124
  else {
381
- // Not in transaction, apply directly with mutex protection
382
- const hasSenderKeys = 'sender-key' in data;
383
- const senderKeyNames = hasSenderKeys ? Object.keys(data['sender-key'] || {}) : [];
384
- if (hasSenderKeys) {
385
- logger.info({ senderKeyNames }, 'processing sender key set operations');
386
- // Handle sender key operations with per-key queues
387
- for (const senderKeyName of senderKeyNames) {
388
- await queueSenderKeyOperation(senderKeyName, async () => {
389
- // Create data subset for this specific sender key
390
- const senderKeyData = {
391
- 'sender-key': {
392
- [senderKeyName]: data['sender-key'][senderKeyName]
393
- }
394
- };
395
- logger.trace({ senderKeyName }, 'storing sender key');
396
- // Apply changes to the store
397
- await state.set(senderKeyData);
398
- logger.trace({ senderKeyName }, 'sender key stored');
399
- });
400
- }
401
- // Handle any non-sender-key data with regular mutexes
402
- const nonSenderKeyData = { ...data };
403
- delete nonSenderKeyData['sender-key'];
404
- if (Object.keys(nonSenderKeyData).length > 0) {
405
- await withMutexes(Object.keys(nonSenderKeyData), getKeyTypeMutex, async () => {
406
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
407
- for (const key_ in nonSenderKeyData) {
408
- const keyType = key_;
409
- if (keyType === 'pre-key') {
410
- await processPreKeyDeletions(nonSenderKeyData, keyType, state, logger);
411
- }
412
- }
413
- // Apply changes to the store
414
- await state.set(nonSenderKeyData);
415
- });
416
- }
417
- }
418
- else {
419
- // No sender keys - use original logic
420
- await withMutexes(Object.keys(data), getKeyTypeMutex, async () => {
421
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
422
- for (const key_ in data) {
423
- const keyType = key_;
424
- if (keyType === 'pre-key') {
425
- await processPreKeyDeletions(data, keyType, state, logger);
426
- }
427
- }
428
- // Apply changes to the store
429
- await state.set(data);
430
- });
431
- }
125
+ return state.set(data);
432
126
  }
433
127
  },
434
128
  isInTransaction,
435
- async transaction(work, key) {
436
- const releaseTxMutex = await getTransactionMutex(key).acquire();
129
+ async transaction(work) {
130
+ let result;
131
+ transactionsInProgress += 1;
132
+ if (transactionsInProgress === 1) {
133
+ logger.trace('entering transaction');
134
+ }
437
135
  try {
438
- transactionsInProgress += 1;
136
+ result = await work();
137
+ // commit if this is the outermost transaction
439
138
  if (transactionsInProgress === 1) {
440
- logger.trace('entering transaction');
441
- }
442
- // Release the transaction mutex now that we've updated the counter
443
- // This allows other transactions to start preparing
444
- releaseTxMutex();
445
- try {
446
- return await executeTransactionWork(work);
447
- }
448
- finally {
449
- cleanupTransactionState();
139
+ if (Object.keys(mutations).length) {
140
+ logger.trace('committing transaction');
141
+ // retry mechanism to ensure we've some recovery
142
+ // in case a transaction fails in the first attempt
143
+ let tries = maxCommitRetries;
144
+ while (tries) {
145
+ tries -= 1;
146
+ try {
147
+ await state.set(mutations);
148
+ logger.trace({ dbQueriesInTransaction }, 'committed transaction');
149
+ break;
150
+ }
151
+ catch (error) {
152
+ logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
153
+ await (0, generics_1.delay)(delayBetweenTriesMs);
154
+ }
155
+ }
156
+ }
157
+ else {
158
+ logger.trace('no mutations in transaction');
159
+ }
450
160
  }
451
161
  }
452
- catch (error) {
453
- releaseTxMutex();
454
- throw error;
162
+ finally {
163
+ transactionsInProgress -= 1;
164
+ if (transactionsInProgress === 0) {
165
+ transactionCache = {};
166
+ mutations = {};
167
+ dbQueriesInTransaction = 0;
168
+ }
455
169
  }
170
+ return result;
456
171
  }
457
172
  };
173
+ function isInTransaction() {
174
+ return transactionsInProgress > 0;
175
+ }
458
176
  };
459
177
  exports.addTransactionCapability = addTransactionCapability;
460
178
  const initAuthCreds = () => {
@@ -473,10 +191,16 @@ const initAuthCreds = () => {
473
191
  accountSettings: {
474
192
  unarchiveChats: false
475
193
  },
194
+ // mobile creds
195
+ deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
+ phoneId: (0, uuid_1.v4)(),
197
+ identityId: (0, crypto_1.randomBytes)(20),
476
198
  registered: false,
199
+ backupToken: (0, crypto_1.randomBytes)(20),
200
+ registration: {},
477
201
  pairingCode: undefined,
478
202
  lastPropHash: undefined,
479
- routingInfo: undefined
203
+ routingInfo: undefined,
480
204
  };
481
205
  };
482
206
  exports.initAuthCreds = initAuthCreds;
@@ -50,7 +50,7 @@ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
50
50
  if (line) {
51
51
  const { event, data } = JSON.parse(line);
52
52
  ev.emit(event, data);
53
- delayIntervalMs && (await (0, generics_1.delay)(delayIntervalMs));
53
+ delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
54
54
  }
55
55
  }
56
56
  fileStream.close();
@@ -1,5 +1,5 @@
1
- import type { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
- import { type BinaryNode } from '../WABinary';
1
+ import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
+ import { BinaryNode } from '../WABinary';
3
3
  export declare const parseCatalogNode: (node: BinaryNode) => {
4
4
  products: Product[];
5
5
  nextPageCursor: string | undefined;