jagproject 26.3.22 → 26.3.25

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 (206) hide show
  1. package/WAProto/GenerateStatics.sh +3 -4
  2. package/WAProto/WAProto.proto +1215 -511
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +64857 -145167
  6. package/engine-requirements.js +4 -7
  7. package/lib/Defaults/index.d.ts +74 -0
  8. package/lib/Defaults/index.js +51 -33
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/wileys-version.json +2 -2
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +5 -3
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +35 -46
  16. package/lib/Signal/Group/index.d.ts +12 -0
  17. package/lib/Signal/Group/index.js +21 -21
  18. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  19. package/lib/Signal/Group/keyhelper.js +2 -2
  20. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  21. package/lib/Signal/Group/sender-chain-key.js +5 -10
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  24. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  25. package/lib/Signal/Group/sender-key-message.js +8 -8
  26. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +7 -16
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +25 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +2 -2
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +358 -54
  35. package/lib/Signal/lid-mapping.d.ts +19 -0
  36. package/lib/Signal/lid-mapping.js +274 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +2 -2
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +1 -0
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +18 -30
  43. package/lib/Socket/business.d.ts +202 -0
  44. package/lib/Socket/business.js +160 -38
  45. package/lib/Socket/chats.d.ts +111 -0
  46. package/lib/Socket/chats.js +497 -314
  47. package/lib/Socket/communities.d.ts +258 -0
  48. package/lib/Socket/communities.js +438 -0
  49. package/lib/Socket/community.js +333 -0
  50. package/lib/Socket/groups.d.ts +150 -0
  51. package/lib/Socket/groups.js +229 -91
  52. package/lib/Socket/index.d.ts +245 -0
  53. package/lib/Socket/index.js +9 -6
  54. package/lib/Socket/messages-recv.d.ts +187 -0
  55. package/lib/Socket/messages-recv.js +1105 -501
  56. package/lib/Socket/messages-send.d.ts +183 -0
  57. package/lib/Socket/messages-send.js +1184 -501
  58. package/lib/Socket/mex.d.ts +3 -0
  59. package/lib/Socket/mex.js +45 -0
  60. package/lib/Socket/newsletter.d.ts +160 -0
  61. package/lib/Socket/newsletter.js +227 -200
  62. package/lib/Socket/socket.d.ts +55 -0
  63. package/lib/Socket/socket.js +507 -206
  64. package/lib/Socket/usync.js +6 -6
  65. package/lib/Store/index.js +17 -5
  66. package/lib/Store/make-cache-manager-store.js +83 -0
  67. package/lib/Store/make-in-memory-store.js +48 -89
  68. package/lib/Store/make-ordered-dictionary.js +1 -1
  69. package/lib/Types/Auth.d.ts +116 -0
  70. package/lib/Types/Bussines.d.ts +25 -0
  71. package/lib/Types/Bussines.js +2 -0
  72. package/lib/Types/Call.d.ts +15 -0
  73. package/lib/Types/Chat.d.ts +123 -0
  74. package/lib/Types/Chat.js +7 -1
  75. package/lib/Types/Contact.d.ts +24 -0
  76. package/lib/Types/Events.d.ts +237 -0
  77. package/lib/Types/Events.js +1 -0
  78. package/lib/Types/GroupMetadata.d.ts +67 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +1 -3
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +1 -3
  83. package/lib/Types/Message.d.ts +305 -0
  84. package/lib/Types/Message.js +9 -5
  85. package/lib/Types/MexUpdates.js +11 -0
  86. package/lib/Types/Newsletter.d.ts +135 -0
  87. package/lib/Types/Newsletter.js +36 -11
  88. package/lib/Types/Product.d.ts +79 -0
  89. package/lib/Types/Signal.d.ts +76 -0
  90. package/lib/Types/Signal.js +1 -0
  91. package/lib/Types/Socket.d.ts +133 -0
  92. package/lib/Types/Socket.js +1 -0
  93. package/lib/Types/State.d.ts +39 -0
  94. package/lib/Types/State.js +12 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +1 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +14 -14
  99. package/lib/Utils/audioToBuffer.js +31 -0
  100. package/lib/Utils/auth-utils.d.ts +19 -0
  101. package/lib/Utils/auth-utils.js +222 -123
  102. package/lib/Utils/baileys-event-stream.js +60 -0
  103. package/lib/Utils/browser-utils.d.ts +4 -0
  104. package/lib/Utils/browser-utils.js +38 -29
  105. package/lib/Utils/business.d.ts +23 -0
  106. package/lib/Utils/business.js +54 -48
  107. package/lib/Utils/chat-utils.d.ts +70 -0
  108. package/lib/Utils/chat-utils.js +284 -189
  109. package/lib/Utils/crypto.d.ts +37 -0
  110. package/lib/Utils/crypto.js +16 -41
  111. package/lib/Utils/decode-wa-message.d.ts +48 -0
  112. package/lib/Utils/decode-wa-message.js +128 -48
  113. package/lib/Utils/event-buffer.d.ts +34 -0
  114. package/lib/Utils/event-buffer.js +124 -62
  115. package/lib/Utils/generics.d.ts +91 -0
  116. package/lib/Utils/generics.js +154 -138
  117. package/lib/Utils/history.d.ts +22 -0
  118. package/lib/Utils/history.js +77 -34
  119. package/lib/Utils/identity-change-handler.d.ts +37 -0
  120. package/lib/Utils/identity-change-handler.js +54 -0
  121. package/lib/Utils/index.d.ts +22 -0
  122. package/lib/Utils/index.js +32 -19
  123. package/lib/Utils/link-preview.d.ts +21 -0
  124. package/lib/Utils/link-preview.js +12 -17
  125. package/lib/Utils/logger.d.ts +13 -0
  126. package/lib/Utils/lt-hash.d.ts +8 -0
  127. package/lib/Utils/lt-hash.js +2 -43
  128. package/lib/Utils/make-mutex.d.ts +9 -0
  129. package/lib/Utils/make-mutex.js +21 -27
  130. package/lib/Utils/message-retry-manager.d.ts +110 -0
  131. package/lib/Utils/message-retry-manager.js +143 -45
  132. package/lib/Utils/messages-media.d.ts +130 -0
  133. package/lib/Utils/messages-media.js +429 -502
  134. package/lib/Utils/messages-newsletter.d.ts +84 -0
  135. package/lib/Utils/messages-newsletter.js +295 -0
  136. package/lib/Utils/messages.d.ts +92 -0
  137. package/lib/Utils/messages.js +1099 -400
  138. package/lib/Utils/noise-handler.d.ts +20 -0
  139. package/lib/Utils/noise-handler.js +145 -91
  140. package/lib/Utils/pre-key-manager.d.ts +28 -0
  141. package/lib/Utils/pre-key-manager.js +112 -0
  142. package/lib/Utils/process-message.d.ts +60 -0
  143. package/lib/Utils/process-message.js +316 -184
  144. package/lib/Utils/reporting-utils.d.ts +11 -0
  145. package/lib/Utils/reporting-utils.js +262 -0
  146. package/lib/Utils/resolve-jid.d.ts +43 -0
  147. package/lib/Utils/resolve-jid.js +95 -0
  148. package/lib/Utils/serial-task-queue.js +29 -0
  149. package/lib/Utils/signal.d.ts +34 -0
  150. package/lib/Utils/signal.js +56 -39
  151. package/lib/Utils/streamToBuffer.js +17 -0
  152. package/lib/Utils/sync-action-utils.d.ts +19 -0
  153. package/lib/Utils/sync-action-utils.js +52 -0
  154. package/lib/Utils/tc-token-utils.d.ts +12 -0
  155. package/lib/Utils/tc-token-utils.js +20 -0
  156. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  157. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +11 -12
  159. package/lib/Utils/use-single-file-auth-state.js +73 -0
  160. package/lib/Utils/validate-connection.d.ts +11 -0
  161. package/lib/Utils/validate-connection.js +59 -82
  162. package/lib/Utils/wileys-event-stream.js +1 -61
  163. package/lib/WABinary/constants.d.ts +28 -0
  164. package/lib/WABinary/decode.d.ts +7 -0
  165. package/lib/WABinary/decode.js +39 -4
  166. package/lib/WABinary/encode.d.ts +3 -0
  167. package/lib/WABinary/encode.js +17 -11
  168. package/lib/WABinary/generic-utils.d.ts +15 -0
  169. package/lib/WABinary/generic-utils.js +46 -18
  170. package/lib/WABinary/index.d.ts +6 -0
  171. package/lib/WABinary/index.js +9 -5
  172. package/lib/WABinary/jid-utils.d.ts +48 -0
  173. package/lib/WABinary/jid-utils.js +67 -37
  174. package/lib/WABinary/types.d.ts +19 -0
  175. package/lib/WABinary/types.js +34 -0
  176. package/lib/WAM/BinaryInfo.d.ts +9 -0
  177. package/lib/WAM/constants.d.ts +40 -0
  178. package/lib/WAM/constants.js +19183 -11678
  179. package/lib/WAM/encode.d.ts +3 -0
  180. package/lib/WAM/encode.js +15 -17
  181. package/lib/WAM/index.d.ts +4 -0
  182. package/lib/WAM/index.js +3 -3
  183. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  184. package/lib/WAUSync/Protocols/USyncContactProtocol.js +6 -6
  185. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  186. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +9 -9
  187. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  188. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +6 -6
  189. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -8
  191. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  192. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +18 -17
  193. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  194. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  195. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  196. package/lib/WAUSync/Protocols/index.js +6 -4
  197. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  198. package/lib/WAUSync/USyncQuery.js +38 -30
  199. package/lib/WAUSync/USyncUser.d.ts +13 -0
  200. package/lib/WAUSync/index.d.ts +4 -0
  201. package/lib/WAUSync/index.js +3 -3
  202. package/lib/index.d.ts +12 -0
  203. package/lib/index.js +3 -5
  204. package/package.json +10 -6
  205. package/readme.md +97 -0
  206. package/LICENSE +0 -21
@@ -5,11 +5,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.initAuthCreds = exports.addTransactionCapability = void 0;
7
7
  exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
- const crypto_1 = require("crypto");
9
8
  const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
- const Defaults_1 = require("../Defaults");
11
- const crypto_2 = require("./crypto");
12
- const generics_1 = require("./generics");
9
+ const async_hooks_1 = require("async_hooks");
10
+ const async_mutex_1 = require("async-mutex");
11
+ const crypto_1 = require("crypto");
12
+ const serial_task_queue_js_1 = __importDefault(require("./serial-task-queue.js"));
13
+ const index_js_1 = require("../Defaults/index.js");
14
+ const crypto_js_1 = require("./crypto.js");
15
+ const generics_js_1 = require("./generics.js");
16
+ const pre_key_manager_js_1 = require("./pre-key-manager.js");
13
17
  /**
14
18
  * Adds caching capability to a SignalKeyStore
15
19
  * @param store the store to add caching to
@@ -17,171 +21,265 @@ const generics_1 = require("./generics");
17
21
  * @param _cache cache store to use
18
22
  */
19
23
  function makeCacheableSignalKeyStore(store, logger, _cache) {
20
- const cache = _cache || new node_cache_1.default({
21
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
22
- useClones: false,
23
- deleteOnExpire: true,
24
- });
24
+ const cache = _cache ||
25
+ new node_cache_1.default({
26
+ stdTTL: index_js_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
27
+ useClones: false,
28
+ deleteOnExpire: true
29
+ });
30
+ // Mutex for protecting cache operations
31
+ const cacheMutex = new async_mutex_1.Mutex();
25
32
  function getUniqueId(type, id) {
26
33
  return `${type}.${id}`;
27
34
  }
28
35
  return {
29
36
  async get(type, ids) {
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;
36
- }
37
- else {
38
- idsToFetch.push(id);
39
- }
40
- }
41
- if (idsToFetch.length) {
42
- logger === null || logger === void 0 ? void 0 : 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) {
37
+ return cacheMutex.runExclusive(async () => {
38
+ const data = {};
39
+ const idsToFetch = [];
40
+ for (const id of ids) {
41
+ const item = (await cache.get(getUniqueId(type, id)));
42
+ if (typeof item !== 'undefined') {
47
43
  data[id] = item;
48
- cache.set(getUniqueId(type, id), item);
44
+ }
45
+ else {
46
+ idsToFetch.push(id);
49
47
  }
50
48
  }
51
- }
52
- return data;
49
+ if (idsToFetch.length) {
50
+ logger?.trace({ items: idsToFetch.length }, 'loading from store');
51
+ const fetched = await store.get(type, idsToFetch);
52
+ for (const id of idsToFetch) {
53
+ const item = fetched[id];
54
+ if (item) {
55
+ data[id] = item;
56
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
57
+ await cache.set(getUniqueId(type, id), item);
58
+ }
59
+ }
60
+ }
61
+ return data;
62
+ });
53
63
  },
54
64
  async set(data) {
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;
65
+ return cacheMutex.runExclusive(async () => {
66
+ let keys = 0;
67
+ for (const type in data) {
68
+ for (const id in data[type]) {
69
+ await cache.set(getUniqueId(type, id), data[type][id]);
70
+ keys += 1;
71
+ }
60
72
  }
61
- }
62
- logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
63
- await store.set(data);
73
+ logger?.trace({ keys }, 'updated cache');
74
+ await store.set(data);
75
+ });
64
76
  },
65
77
  async clear() {
66
- var _a;
67
- cache.flushAll();
68
- await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
78
+ await cache.flushAll();
79
+ await store.clear?.();
69
80
  }
70
81
  };
71
82
  }
72
83
  /**
73
- * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
74
- * this allows batch read & write operations & improves the performance of the lib
84
+ * Adds DB-like transaction capability to the SignalKeyStore
85
+ * Uses AsyncLocalStorage for automatic context management
75
86
  * @param state the key store to apply this capability to
76
87
  * @param logger logger to log events
77
88
  * @returns SignalKeyStore with transaction capability
78
89
  */
79
90
  const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
80
- // number of queries made to the DB during the transaction
81
- // only there for logging purposes
82
- let dbQueriesInTransaction = 0;
83
- let transactionCache = {};
84
- let mutations = {};
85
- let transactionsInProgress = 0;
86
- return {
87
- get: async (type, ids) => {
88
- if (isInTransaction()) {
89
- const dict = transactionCache[type];
90
- const idsRequiringFetch = dict
91
- ? ids.filter(item => typeof dict[item] === 'undefined')
92
- : ids;
93
- // only fetch if there are any items to fetch
94
- if (idsRequiringFetch.length) {
95
- dbQueriesInTransaction += 1;
96
- const result = await state.get(type, idsRequiringFetch);
97
- transactionCache[type] || (transactionCache[type] = {});
98
- Object.assign(transactionCache[type], result);
91
+ const txStorage = new async_hooks_1.AsyncLocalStorage();
92
+ // Queues for concurrency control (keyed by signal data type - bounded set)
93
+ const keyQueues = new Map();
94
+ // Transaction mutexes with reference counting for cleanup
95
+ const txMutexes = new Map();
96
+ const txMutexRefCounts = new Map();
97
+ // Pre-key manager for specialized operations
98
+ const preKeyManager = new pre_key_manager_js_1.PreKeyManager(state, logger);
99
+ /**
100
+ * Get or create a queue for a specific key type
101
+ */
102
+ function getQueue(key) {
103
+ if (!keyQueues.has(key)) {
104
+ keyQueues.set(key, new serial_task_queue_js_1.default({ concurrency: 1 }));
105
+ }
106
+ return keyQueues.get(key);
107
+ }
108
+ /**
109
+ * Get or create a transaction mutex
110
+ */
111
+ function getTxMutex(key) {
112
+ if (!txMutexes.has(key)) {
113
+ txMutexes.set(key, new async_mutex_1.Mutex());
114
+ txMutexRefCounts.set(key, 0);
115
+ }
116
+ return txMutexes.get(key);
117
+ }
118
+ /**
119
+ * Acquire a reference to a transaction mutex
120
+ */
121
+ function acquireTxMutexRef(key) {
122
+ const count = txMutexRefCounts.get(key) ?? 0;
123
+ txMutexRefCounts.set(key, count + 1);
124
+ }
125
+ /**
126
+ * Release a reference to a transaction mutex and cleanup if no longer needed
127
+ */
128
+ function releaseTxMutexRef(key) {
129
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
130
+ txMutexRefCounts.set(key, count);
131
+ // Cleanup if no more references and mutex is not locked
132
+ if (count <= 0) {
133
+ const mutex = txMutexes.get(key);
134
+ if (mutex && !mutex.isLocked()) {
135
+ txMutexes.delete(key);
136
+ txMutexRefCounts.delete(key);
137
+ }
138
+ }
139
+ }
140
+ /**
141
+ * Check if currently in a transaction
142
+ */
143
+ function isInTransaction() {
144
+ return !!txStorage.getStore();
145
+ }
146
+ /**
147
+ * Commit transaction with retries
148
+ */
149
+ async function commitWithRetry(mutations) {
150
+ if (Object.keys(mutations).length === 0) {
151
+ logger.trace('no mutations in transaction');
152
+ return;
153
+ }
154
+ logger.trace('committing transaction');
155
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
156
+ try {
157
+ await state.set(mutations);
158
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
159
+ return;
160
+ }
161
+ catch (error) {
162
+ const retriesLeft = maxCommitRetries - attempt - 1;
163
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
164
+ if (retriesLeft === 0) {
165
+ throw error;
99
166
  }
100
- return ids.reduce((dict, id) => {
101
- var _a;
102
- const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
103
- if (value) {
104
- dict[id] = value;
105
- }
106
- return dict;
107
- }, {});
167
+ await (0, generics_js_1.delay)(delayBetweenTriesMs);
108
168
  }
109
- else {
169
+ }
170
+ }
171
+ return {
172
+ get: async (type, ids) => {
173
+ const ctx = txStorage.getStore();
174
+ if (!ctx) {
175
+ // No transaction - direct read without exclusive lock for concurrency
110
176
  return state.get(type, ids);
111
177
  }
178
+ // In transaction - check cache first
179
+ const cached = ctx.cache[type] || {};
180
+ const missing = ids.filter(id => !(id in cached));
181
+ if (missing.length > 0) {
182
+ ctx.dbQueries++;
183
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
184
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
185
+ // Update cache
186
+ ctx.cache[type] = ctx.cache[type] || {};
187
+ Object.assign(ctx.cache[type], fetched);
188
+ }
189
+ // Return requested ids from cache
190
+ const result = {};
191
+ for (const id of ids) {
192
+ const value = ctx.cache[type]?.[id];
193
+ if (value !== undefined && value !== null) {
194
+ result[id] = value;
195
+ }
196
+ }
197
+ return result;
112
198
  },
113
- set: data => {
114
- if (isInTransaction()) {
115
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
116
- for (const key in data) {
117
- transactionCache[key] = transactionCache[key] || {};
118
- Object.assign(transactionCache[key], data[key]);
119
- mutations[key] = mutations[key] || {};
120
- Object.assign(mutations[key], data[key]);
199
+ set: async (data) => {
200
+ const ctx = txStorage.getStore();
201
+ if (!ctx) {
202
+ // No transaction - direct write with queue protection
203
+ const types = Object.keys(data);
204
+ // Process pre-keys with validation
205
+ for (const type_ of types) {
206
+ const type = type_;
207
+ if (type === 'pre-key') {
208
+ await preKeyManager.validateDeletions(data, type);
209
+ }
121
210
  }
211
+ // Write all data in parallel
212
+ await Promise.all(types.map(type => getQueue(type).add(async () => {
213
+ const typeData = { [type]: data[type] };
214
+ await state.set(typeData);
215
+ })));
216
+ return;
122
217
  }
123
- else {
124
- return state.set(data);
218
+ // In transaction - update cache and mutations
219
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
220
+ for (const key_ in data) {
221
+ const key = key_;
222
+ // Ensure structures exist
223
+ ctx.cache[key] = ctx.cache[key] || {};
224
+ ctx.mutations[key] = ctx.mutations[key] || {};
225
+ // Special handling for pre-keys
226
+ if (key === 'pre-key') {
227
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
228
+ }
229
+ else {
230
+ // Normal key types
231
+ Object.assign(ctx.cache[key], data[key]);
232
+ Object.assign(ctx.mutations[key], data[key]);
233
+ }
125
234
  }
126
235
  },
127
236
  isInTransaction,
128
- async transaction(work) {
129
- let result;
130
- transactionsInProgress += 1;
131
- if (transactionsInProgress === 1) {
132
- logger.trace('entering transaction');
237
+ transaction: async (work, key) => {
238
+ const existing = txStorage.getStore();
239
+ // Nested transaction - reuse existing context
240
+ if (existing) {
241
+ logger.trace('reusing existing transaction context');
242
+ return work();
133
243
  }
244
+ // New transaction - acquire mutex and create context
245
+ const mutex = getTxMutex(key);
246
+ acquireTxMutexRef(key);
134
247
  try {
135
- result = await work();
136
- // commit if this is the outermost transaction
137
- if (transactionsInProgress === 1) {
138
- if (Object.keys(mutations).length) {
139
- logger.trace('committing transaction');
140
- // retry mechanism to ensure we've some recovery
141
- // in case a transaction fails in the first attempt
142
- let tries = maxCommitRetries;
143
- while (tries) {
144
- tries -= 1;
145
- try {
146
- await state.set(mutations);
147
- logger.trace({ dbQueriesInTransaction }, 'committed transaction');
148
- break;
149
- }
150
- catch (error) {
151
- logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
152
- await (0, generics_1.delay)(delayBetweenTriesMs);
153
- }
154
- }
248
+ return await mutex.runExclusive(async () => {
249
+ const ctx = {
250
+ cache: {},
251
+ mutations: {},
252
+ dbQueries: 0
253
+ };
254
+ logger.trace('entering transaction');
255
+ try {
256
+ const result = await txStorage.run(ctx, work);
257
+ // Commit mutations
258
+ await commitWithRetry(ctx.mutations);
259
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
260
+ return result;
155
261
  }
156
- else {
157
- logger.trace('no mutations in transaction');
262
+ catch (error) {
263
+ logger.error({ error }, 'transaction failed, rolling back');
264
+ throw error;
158
265
  }
159
- }
266
+ });
160
267
  }
161
268
  finally {
162
- transactionsInProgress -= 1;
163
- if (transactionsInProgress === 0) {
164
- transactionCache = {};
165
- mutations = {};
166
- dbQueriesInTransaction = 0;
167
- }
269
+ releaseTxMutexRef(key);
168
270
  }
169
- return result;
170
271
  }
171
272
  };
172
- function isInTransaction() {
173
- return transactionsInProgress > 0;
174
- }
175
273
  };
176
274
  exports.addTransactionCapability = addTransactionCapability;
177
275
  const initAuthCreds = () => {
178
- const identityKey = crypto_2.Curve.generateKeyPair();
276
+ const identityKey = crypto_js_1.Curve.generateKeyPair();
179
277
  return {
180
- noiseKey: crypto_2.Curve.generateKeyPair(),
181
- pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
278
+ noiseKey: crypto_js_1.Curve.generateKeyPair(),
279
+ pairingEphemeralKeyPair: crypto_js_1.Curve.generateKeyPair(),
182
280
  signedIdentityKey: identityKey,
183
- signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
184
- registrationId: (0, generics_1.generateRegistrationId)(),
281
+ signedPreKey: (0, crypto_js_1.signedKeyPair)(identityKey, 1),
282
+ registrationId: (0, generics_js_1.generateRegistrationId)(),
185
283
  advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
186
284
  processedHistoryMessages: [],
187
285
  nextPreKeyId: 1,
@@ -194,6 +292,7 @@ const initAuthCreds = () => {
194
292
  pairingCode: undefined,
195
293
  lastPropHash: undefined,
196
294
  routingInfo: undefined,
295
+ additionalData: undefined
197
296
  };
198
297
  };
199
298
  exports.initAuthCreds = initAuthCreds;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readAndEmitEventStream = exports.captureEventStream = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const fs_1 = require("fs");
9
+ const promises_1 = require("fs/promises");
10
+ const readline_1 = require("readline");
11
+ const generics_js_1 = require("./generics.js");
12
+ const make_mutex_js_1 = require("./make-mutex.js");
13
+ /**
14
+ * Captures events from a baileys event emitter & stores them in a file
15
+ * @param ev The event emitter to read events from
16
+ * @param filename File to save to
17
+ */
18
+ const captureEventStream = (ev, filename) => {
19
+ const oldEmit = ev.emit;
20
+ // write mutex so data is appended in order
21
+ const writeMutex = (0, make_mutex_js_1.makeMutex)();
22
+ // monkey patch eventemitter to capture all events
23
+ ev.emit = function (...args) {
24
+ const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
+ const result = oldEmit.apply(ev, args);
26
+ writeMutex.mutex(async () => {
27
+ await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
28
+ });
29
+ return result;
30
+ };
31
+ };
32
+ exports.captureEventStream = captureEventStream;
33
+ /**
34
+ * Read event file and emit events from there
35
+ * @param filename filename containing event data
36
+ * @param delayIntervalMs delay between each event emit
37
+ */
38
+ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
+ const ev = new events_1.default();
40
+ const fireEvents = async () => {
41
+ const fileStream = (0, fs_1.createReadStream)(filename);
42
+ const rl = (0, readline_1.createInterface)({
43
+ input: fileStream,
44
+ crlfDelay: Infinity
45
+ });
46
+ for await (const line of rl) {
47
+ if (line) {
48
+ const { event, data } = JSON.parse(line);
49
+ ev.emit(event, data);
50
+ delayIntervalMs && await (0, generics_js_1.delay)(delayIntervalMs);
51
+ }
52
+ }
53
+ fileStream.close();
54
+ };
55
+ return {
56
+ ev,
57
+ task: fireEvents()
58
+ };
59
+ };
60
+ exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -0,0 +1,4 @@
1
+ import type { BrowsersMap } from '../Types/index.js';
2
+ export declare const Browsers: BrowsersMap;
3
+ export declare const getPlatformId: (browser: string) => string;
4
+ //# sourceMappingURL=browser-utils.d.ts.map
@@ -1,35 +1,44 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPlatformId = exports.Browsers = void 0;
4
-
5
- const os = require("os");
6
- const { proto } = require("../../WAProto/index.js");
7
-
8
- const PLATFORM_MAP = {
9
- 'aix': 'AIX',
10
- 'darwin': 'Mac OS',
11
- 'win32': 'Windows',
12
- 'android': 'Android',
13
- 'freebsd': 'FreeBSD',
14
- 'openbsd': 'OpenBSD',
15
- 'sunos': 'Solaris',
16
- 'linux': undefined, // Default ke Ubuntu untuk Linux
17
- 'haiku': undefined,
18
- 'cygwin': undefined,
19
- 'netbsd': undefined
3
+ exports.getPlatformId = exports.Browsers = exports.PLATFORM_VERSIONS = exports.PLATFORM_MAP = void 0;
4
+ const os_1 = require("os");
5
+ const index_js_1 = require("../../WAProto/index.js");
6
+ exports.PLATFORM_MAP = {
7
+ 'aix': 'AIX', 'darwin': 'Mac OS', 'win32': 'Windows', 'android': 'Android',
8
+ 'freebsd': 'FreeBSD', 'openbsd': 'OpenBSD', 'sunos': 'Solaris', 'linux': 'Linux',
9
+ 'ubuntu': 'Ubuntu', 'ios': 'iOS', 'baileys': 'Baileys', 'chromeos': 'Chrome OS',
10
+ 'tizen': 'Tizen', 'watchos': 'watchOS', 'wearos': 'Wear OS', 'harmonyos': 'HarmonyOS',
11
+ 'kaios': 'KaiOS', 'smarttv': 'Smart TV', 'raspberrypi': 'Raspberry Pi OS',
12
+ 'symbian': 'Symbian', 'blackberry': 'Blackberry OS', 'windowsphone': 'Windows Phone'
20
13
  };
21
-
22
- // Fixed: Browsers sekarang fungsi yang return array [platform, browser, version]
23
- // Ini kompatibel dengan pemanggilan Browsers('Chrome') di Defaults/index.js
24
- exports.Browsers = (browser) => {
25
- const osName = PLATFORM_MAP[os.platform()] || 'Ubuntu'; // Default Ubuntu kalau undefined
26
- const osRelease = os.release(); // Ambil versi OS real-time
27
- return [osName, browser, osRelease];
14
+ exports.PLATFORM_VERSIONS = {
15
+ 'ubuntu': '22.04.4', 'darwin': '18.5', 'win32': '10.0.22631', 'android': '14.0.0',
16
+ 'freebsd': '13.2', 'openbsd': '7.3', 'sunos': '11', 'linux': '6.5', 'ios': '18.2',
17
+ 'baileys': '6.5.0', 'chromeos': '117.0.5938.132', 'tizen': '6.5', 'watchos': '10.1',
18
+ 'wearos': '4.1', 'harmonyos': '4.0.0', 'kaios': '3.1', 'smarttv': '23.3.1',
19
+ 'raspberrypi': '11 (Bullseye)', 'symbian': '3', 'blackberry': '10.3.3', 'windowsphone': '8.1'
20
+ };
21
+ exports.Browsers = {
22
+ ubuntu: (browser) => [exports.PLATFORM_MAP['ubuntu'], browser, exports.PLATFORM_VERSIONS['ubuntu']],
23
+ macOS: (browser) => [exports.PLATFORM_MAP['darwin'], browser, exports.PLATFORM_VERSIONS['darwin']],
24
+ windows: (browser) => [exports.PLATFORM_MAP['win32'], browser, exports.PLATFORM_VERSIONS['win32']],
25
+ linux: (browser) => [exports.PLATFORM_MAP['linux'], browser, exports.PLATFORM_VERSIONS['linux']],
26
+ solaris: (browser) => [exports.PLATFORM_MAP['sunos'], browser, exports.PLATFORM_VERSIONS['sunos']],
27
+ baileys: (browser) => [exports.PLATFORM_MAP['baileys'], browser, exports.PLATFORM_VERSIONS['baileys']],
28
+ android: (browser) => [exports.PLATFORM_MAP['android'], browser, exports.PLATFORM_VERSIONS['android']],
29
+ iOS: (browser) => [exports.PLATFORM_MAP['ios'], browser, exports.PLATFORM_VERSIONS['ios']],
30
+ kaiOS: (browser) => [exports.PLATFORM_MAP['kaios'], browser, exports.PLATFORM_VERSIONS['kaios']],
31
+ chromeOS: (browser) => [exports.PLATFORM_MAP['chromeos'], browser, exports.PLATFORM_VERSIONS['chromeos']],
32
+ appropriate: (browser) => {
33
+ const p = (0, os_1.platform)();
34
+ return [exports.PLATFORM_MAP[p] || 'Unknown OS', browser, exports.PLATFORM_VERSIONS[p] || 'latest'];
35
+ },
36
+ custom: (p, browser, version) => {
37
+ return [exports.PLATFORM_MAP[p.toLowerCase()] || p, browser, version || exports.PLATFORM_VERSIONS[p] || 'latest'];
38
+ }
28
39
  };
29
-
30
40
  const getPlatformId = (browser) => {
31
- const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
32
- return platformType ? platformType.toString() : '1'; // Default Chrome
41
+ const platformType = index_js_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
42
+ return platformType ? platformType.toString() : '1';
33
43
  };
34
-
35
- exports.getPlatformId = getPlatformId;
44
+ exports.getPlatformId = getPlatformId;
@@ -0,0 +1,23 @@
1
+ import type { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types/index.js';
2
+ import { type BinaryNode } from '../WABinary/index.js';
3
+ export declare const parseCatalogNode: (node: BinaryNode) => {
4
+ products: Product[];
5
+ nextPageCursor: string | undefined;
6
+ };
7
+ export declare const parseCollectionsNode: (node: BinaryNode) => {
8
+ collections: CatalogCollection[];
9
+ };
10
+ export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
11
+ export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
12
+ export declare const parseProductNode: (productNode: BinaryNode) => Product;
13
+ /**
14
+ * Uploads images not already uploaded to WA's servers
15
+ */
16
+ export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
17
+ /**
18
+ * Uploads images not already uploaded to WA's servers
19
+ */
20
+ export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
+ url: string;
22
+ }[]>;
23
+ //# sourceMappingURL=business.d.ts.map