@pontalabs/baileys 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +839 -267
  3. package/WAProto/GenerateStatics.sh +4 -3
  4. package/WAProto/WAProto.proto +511 -1215
  5. package/WAProto/index.d.ts +55 -14017
  6. package/WAProto/index.js +29 -97689
  7. package/lib/Defaults/index.d.ts +74 -72
  8. package/lib/Defaults/index.js +108 -94
  9. package/lib/Signal/Group/ciphertext-message.d.ts +7 -8
  10. package/lib/Signal/Group/ciphertext-message.js +16 -9
  11. package/lib/Signal/Group/group-session-builder.d.ts +13 -11
  12. package/lib/Signal/Group/group-session-builder.js +61 -19
  13. package/lib/Signal/Group/group_cipher.d.ts +16 -14
  14. package/lib/Signal/Group/group_cipher.js +70 -41
  15. package/lib/Signal/Group/index.d.ts +11 -12
  16. package/lib/Signal/Group/index.js +61 -12
  17. package/lib/Signal/Group/keyhelper.d.ts +14 -9
  18. package/lib/Signal/Group/keyhelper.js +58 -10
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -13
  20. package/lib/Signal/Group/sender-chain-key.js +34 -13
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -16
  22. package/lib/Signal/Group/sender-key-distribution-message.js +36 -28
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -18
  24. package/lib/Signal/Group/sender-key-message.js +45 -38
  25. package/lib/Signal/Group/sender-key-name.d.ts +15 -14
  26. package/lib/Signal/Group/sender-key-name.js +31 -20
  27. package/lib/Signal/Group/sender-key-record.d.ts +25 -24
  28. package/lib/Signal/Group/sender-key-record.js +35 -18
  29. package/lib/Signal/Group/sender-key-state.d.ts +34 -29
  30. package/lib/Signal/Group/sender-key-state.js +100 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +10 -11
  32. package/lib/Signal/Group/sender-message-key.js +22 -15
  33. package/lib/Signal/libsignal.d.ts +8 -5
  34. package/lib/Signal/libsignal.js +142 -288
  35. package/lib/Signal/lid-mapping.d.ts +28 -23
  36. package/lib/Signal/lid-mapping.js +184 -277
  37. package/lib/Socket/Client/index.d.ts +2 -3
  38. package/lib/Socket/Client/index.js +22 -3
  39. package/lib/Socket/Client/types.d.ts +15 -15
  40. package/lib/Socket/Client/types.js +15 -8
  41. package/lib/Socket/Client/websocket.d.ts +12 -12
  42. package/lib/Socket/Client/websocket.js +37 -29
  43. package/lib/Socket/business.d.ts +178 -208
  44. package/lib/Socket/business.js +127 -91
  45. package/lib/Socket/chats.d.ts +93 -120
  46. package/lib/Socket/chats.js +652 -727
  47. package/lib/Socket/community.js +10 -2
  48. package/lib/Socket/groups.d.ts +111 -143
  49. package/lib/Socket/groups.js +186 -165
  50. package/lib/Socket/index.d.ts +183 -252
  51. package/lib/Socket/index.js +18 -38
  52. package/lib/Socket/messages-recv.d.ts +167 -196
  53. package/lib/Socket/messages-recv.js +1567 -1443
  54. package/lib/Socket/messages-send.d.ts +158 -192
  55. package/lib/Socket/messages-send.js +1208 -1102
  56. package/lib/Socket/newsletter.d.ts +138 -163
  57. package/lib/Socket/newsletter.js +249 -153
  58. package/lib/Socket/socket.d.ts +36 -50
  59. package/lib/Socket/socket.js +820 -749
  60. package/lib/Store/index.d.ts +4 -4
  61. package/lib/Store/index.js +24 -4
  62. package/lib/Store/make-in-memory-store.d.ts +104 -44
  63. package/lib/Store/make-in-memory-store.js +213 -199
  64. package/lib/Store/make-ordered-dictionary.d.ts +12 -13
  65. package/lib/Store/make-ordered-dictionary.js +45 -38
  66. package/lib/Store/object-repository.d.ts +10 -11
  67. package/lib/Store/object-repository.js +16 -9
  68. package/lib/Types/Auth.d.ts +97 -93
  69. package/lib/Types/Auth.js +3 -2
  70. package/lib/Types/Bussines.js +3 -2
  71. package/lib/Types/Call.d.ts +13 -14
  72. package/lib/Types/Call.js +3 -2
  73. package/lib/Types/Chat.d.ts +97 -78
  74. package/lib/Types/Chat.js +9 -8
  75. package/lib/Types/Contact.d.ts +9 -12
  76. package/lib/Types/Contact.js +3 -2
  77. package/lib/Types/Events.d.ts +176 -206
  78. package/lib/Types/Events.js +3 -2
  79. package/lib/Types/GroupMetadata.d.ts +48 -53
  80. package/lib/Types/GroupMetadata.js +3 -2
  81. package/lib/Types/Label.d.ts +14 -13
  82. package/lib/Types/Label.js +30 -24
  83. package/lib/Types/LabelAssociation.d.ts +20 -15
  84. package/lib/Types/LabelAssociation.js +12 -6
  85. package/lib/Types/Message.d.ts +412 -248
  86. package/lib/Types/Message.js +19 -17
  87. package/lib/Types/Product.d.ts +71 -58
  88. package/lib/Types/Product.js +3 -2
  89. package/lib/Types/Signal.d.ts +82 -71
  90. package/lib/Types/Signal.js +3 -2
  91. package/lib/Types/Socket.d.ts +81 -76
  92. package/lib/Types/Socket.js +3 -3
  93. package/lib/Types/State.d.ts +19 -75
  94. package/lib/Types/State.js +14 -56
  95. package/lib/Types/USync.d.ts +8 -8
  96. package/lib/Types/USync.js +3 -2
  97. package/lib/Types/index.d.ts +62 -47
  98. package/lib/Types/index.js +50 -26
  99. package/lib/Utils/auth-utils.d.ts +10 -13
  100. package/lib/Utils/auth-utils.js +472 -213
  101. package/lib/Utils/business.d.ts +20 -14
  102. package/lib/Utils/business.js +134 -110
  103. package/lib/Utils/chat-utils.d.ts +70 -88
  104. package/lib/Utils/chat-utils.js +403 -466
  105. package/lib/Utils/crypto.d.ts +46 -27
  106. package/lib/Utils/crypto.js +188 -117
  107. package/lib/Utils/decode-wa-message.d.ts +45 -58
  108. package/lib/Utils/decode-wa-message.js +311 -212
  109. package/lib/Utils/event-buffer.d.ts +17 -14
  110. package/lib/Utils/event-buffer.js +296 -321
  111. package/lib/Utils/generics.d.ts +92 -66
  112. package/lib/Utils/generics.js +436 -270
  113. package/lib/Utils/history.d.ts +23 -24
  114. package/lib/Utils/history.js +76 -106
  115. package/lib/Utils/index.d.ts +21 -24
  116. package/lib/Utils/index.js +41 -24
  117. package/lib/Utils/link-preview.d.ts +14 -12
  118. package/lib/Utils/link-preview.js +75 -40
  119. package/lib/Utils/logger.d.ts +11 -10
  120. package/lib/Utils/logger.js +7 -3
  121. package/lib/Utils/lt-hash.d.ts +14 -8
  122. package/lib/Utils/lt-hash.js +53 -3
  123. package/lib/Utils/make-mutex.d.ts +7 -7
  124. package/lib/Utils/make-mutex.js +44 -28
  125. package/lib/Utils/message-retry-manager.d.ts +88 -115
  126. package/lib/Utils/message-retry-manager.js +160 -265
  127. package/lib/Utils/messages-media.d.ts +107 -105
  128. package/lib/Utils/messages-media.js +619 -548
  129. package/lib/Utils/messages.d.ts +66 -52
  130. package/lib/Utils/messages.js +1558 -1730
  131. package/lib/Utils/noise-handler.d.ts +18 -18
  132. package/lib/Utils/noise-handler.js +130 -176
  133. package/lib/Utils/process-message.d.ts +32 -43
  134. package/lib/Utils/process-message.js +282 -484
  135. package/lib/Utils/rich-message-utils.js +724 -1220
  136. package/lib/Utils/signal.d.ts +32 -37
  137. package/lib/Utils/signal.js +105 -140
  138. package/lib/Utils/use-multi-file-auth-state.d.ts +5 -5
  139. package/lib/Utils/use-multi-file-auth-state.js +120 -70
  140. package/lib/Utils/use-single-file-auth-state.d.ts +13 -11
  141. package/lib/Utils/use-single-file-auth-state.js +66 -92
  142. package/lib/Utils/validate-connection.d.ts +13 -11
  143. package/lib/Utils/validate-connection.js +113 -128
  144. package/lib/WABinary/constants.d.ts +27 -25
  145. package/lib/WABinary/constants.js +1292 -1451
  146. package/lib/WABinary/decode.d.ts +9 -7
  147. package/lib/WABinary/decode.js +189 -163
  148. package/lib/WABinary/encode.d.ts +3 -3
  149. package/lib/WABinary/encode.js +155 -110
  150. package/lib/WABinary/generic-utils.d.ts +27 -14
  151. package/lib/WABinary/generic-utils.js +105 -177
  152. package/lib/WABinary/index.d.ts +5 -6
  153. package/lib/WABinary/index.js +25 -6
  154. package/lib/WABinary/jid-utils.d.ts +54 -41
  155. package/lib/WABinary/jid-utils.js +152 -83
  156. package/lib/WABinary/types.d.ts +13 -10
  157. package/lib/WABinary/types.js +3 -2
  158. package/lib/WAM/BinaryInfo.d.ts +15 -8
  159. package/lib/WAM/BinaryInfo.js +14 -7
  160. package/lib/WAM/constants.d.ts +37 -30
  161. package/lib/WAM/constants.js +11983 -19465
  162. package/lib/WAM/encode.d.ts +3 -3
  163. package/lib/WAM/encode.js +109 -95
  164. package/lib/WAM/index.d.ts +3 -4
  165. package/lib/WAM/index.js +23 -4
  166. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -37
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -19
  169. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +26 -18
  170. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -11
  171. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -12
  172. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -11
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +24 -16
  174. package/lib/WAUSync/Protocols/index.d.ts +6 -6
  175. package/lib/WAUSync/Protocols/index.js +26 -6
  176. package/lib/WAUSync/USyncQuery.d.ts +28 -27
  177. package/lib/WAUSync/USyncQuery.js +62 -68
  178. package/lib/WAUSync/USyncUser.d.ts +10 -15
  179. package/lib/WAUSync/USyncUser.js +19 -20
  180. package/lib/WAUSync/index.d.ts +3 -4
  181. package/lib/WAUSync/index.js +23 -4
  182. package/lib/index.d.ts +12 -11
  183. package/lib/index.js +39 -12
  184. package/package.json +42 -86
  185. package/engine-requirements.js +0 -10
@@ -1,23 +1,28 @@
1
- import type { LIDMapping, SignalKeyStoreWithTransaction } from '../Types/index.js';
2
- import type { ILogger } from '../Utils/logger.js';
3
- export declare class LIDMappingStore {
4
- private readonly mappingCache;
5
- private readonly keys;
6
- private readonly logger;
7
- private pnToLIDFunc?;
8
- private readonly inflightLIDLookups;
9
- private readonly inflightPNLookups;
10
- constructor(keys: SignalKeyStoreWithTransaction, logger: ILogger, pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>);
11
- storeLIDPNMappings(pairs: LIDMapping[]): Promise<void>;
12
- getLIDForPN(pn: string): Promise<string | null>;
13
- getLIDsForPNs(pns: string[]): Promise<LIDMapping[] | null>;
14
- private _getLIDsForPNsImpl;
15
- getPNForLID(lid: string): Promise<string | null>;
16
- getPNsForLIDs(lids: string[]): Promise<LIDMapping[] | null>;
17
- private _getPNsForLIDsImpl;
18
- /**
19
- * Close the cache and release resources
20
- */
21
- close(): void;
22
- }
23
- //# sourceMappingURL=lid-mapping.d.ts.map
1
+ import { ILogger } from '../Utils/loggerr'
2
+ import { SignalKeyStoreWithTransaction } from '../Types'
3
+
4
+ export declare class LIDMappingStore {
5
+ private readonly mappingCache
6
+ private readonly keys
7
+ private onWhatsAppFunc?
8
+ constructor(keys: SignalKeyStoreWithTransaction, onWhatsAppFunc?: (...jids: string[], logger: ILogger ) => Promise<{
9
+ jid: string
10
+ exists: boolean
11
+ lid: string
12
+ }[] | undefined>)
13
+ /**
14
+ * Store LID-PN mapping - USER LEVEL
15
+ */
16
+ storeLIDPNMappings(pairs: {
17
+ lid: string;
18
+ pn: string;
19
+ }[]): Promise<void>
20
+ /**
21
+ * Get LID for PN - Returns device-specific LID based on user mapping
22
+ */
23
+ getLIDForPN(pn: string): Promise<string | null>
24
+ /**
25
+ * Get PN for LID - USER LEVEL with device construction
26
+ */
27
+ getPNForLID(lid: string): Promise<string | null>
28
+ }
@@ -1,277 +1,184 @@
1
- import { LRUCache } from 'lru-cache';
2
- import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from '../WABinary/index.js';
3
- export class LIDMappingStore {
4
- constructor(keys, logger, pnToLIDFunc) {
5
- this.mappingCache = new LRUCache({
6
- ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
7
- ttlAutopurge: true,
8
- updateAgeOnGet: true
9
- });
10
- this.inflightLIDLookups = new Map();
11
- this.inflightPNLookups = new Map();
12
- this.keys = keys;
13
- this.pnToLIDFunc = pnToLIDFunc;
14
- this.logger = logger;
15
- }
16
- async storeLIDPNMappings(pairs) {
17
- if (pairs.length === 0)
18
- return;
19
- const validatedPairs = [];
20
- for (const { lid, pn } of pairs) {
21
- if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
22
- this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
23
- continue;
24
- }
25
- const lidDecoded = jidDecode(lid);
26
- const pnDecoded = jidDecode(pn);
27
- if (!lidDecoded || !pnDecoded)
28
- continue;
29
- validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
30
- }
31
- if (validatedPairs.length === 0)
32
- return;
33
- const cacheMissSet = new Set();
34
- const existingMappings = new Map();
35
- for (const { pnUser } of validatedPairs) {
36
- const cached = this.mappingCache.get(`pn:${pnUser}`);
37
- if (cached) {
38
- existingMappings.set(pnUser, cached);
39
- }
40
- else {
41
- cacheMissSet.add(pnUser);
42
- }
43
- }
44
- if (cacheMissSet.size > 0) {
45
- const cacheMisses = [...cacheMissSet];
46
- this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
47
- const stored = await this.keys.get('lid-mapping', cacheMisses);
48
- for (const pnUser of cacheMisses) {
49
- const existingLidUser = stored[pnUser];
50
- if (existingLidUser) {
51
- existingMappings.set(pnUser, existingLidUser);
52
- this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
53
- this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
54
- }
55
- }
56
- }
57
- const pairMap = {};
58
- for (const { pnUser, lidUser } of validatedPairs) {
59
- const existingLidUser = existingMappings.get(pnUser);
60
- if (existingLidUser === lidUser) {
61
- this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
62
- continue;
63
- }
64
- pairMap[pnUser] = lidUser;
65
- }
66
- if (Object.keys(pairMap).length === 0)
67
- return;
68
- this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
69
- const batchData = {};
70
- for (const [pnUser, lidUser] of Object.entries(pairMap)) {
71
- batchData[pnUser] = lidUser;
72
- batchData[`${lidUser}_reverse`] = pnUser;
73
- }
74
- await this.keys.transaction(async () => {
75
- await this.keys.set({ 'lid-mapping': batchData });
76
- }, 'lid-mapping');
77
- // Update cache after successful DB write
78
- for (const [pnUser, lidUser] of Object.entries(pairMap)) {
79
- this.mappingCache.set(`pn:${pnUser}`, lidUser);
80
- this.mappingCache.set(`lid:${lidUser}`, pnUser);
81
- }
82
- }
83
- async getLIDForPN(pn) {
84
- return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
85
- }
86
- async getLIDsForPNs(pns) {
87
- if (pns.length === 0)
88
- return null;
89
- const sortedPns = [...new Set(pns)].sort();
90
- const cacheKey = sortedPns.join(',');
91
- const inflight = this.inflightLIDLookups.get(cacheKey);
92
- if (inflight) {
93
- this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
94
- return inflight;
95
- }
96
- const promise = this._getLIDsForPNsImpl(pns);
97
- this.inflightLIDLookups.set(cacheKey, promise);
98
- try {
99
- return await promise;
100
- }
101
- finally {
102
- this.inflightLIDLookups.delete(cacheKey);
103
- }
104
- }
105
- async _getLIDsForPNsImpl(pns) {
106
- const usyncFetch = {};
107
- const successfulPairs = {};
108
- const pending = [];
109
- const addResolvedPair = (pn, decoded, lidUser) => {
110
- const normalizedLidUser = lidUser.toString();
111
- if (!normalizedLidUser) {
112
- this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
113
- return false;
114
- }
115
- // Push the PN device ID to the LID to maintain device separation
116
- const pnDevice = decoded.device !== undefined ? decoded.device : 0;
117
- const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
118
- this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
119
- successfulPairs[pn] = { lid: deviceSpecificLid, pn };
120
- return true;
121
- };
122
- for (const pn of pns) {
123
- if (!isPnUser(pn) && !isHostedPnUser(pn))
124
- continue;
125
- const decoded = jidDecode(pn);
126
- if (!decoded)
127
- continue;
128
- const pnUser = decoded.user;
129
- const cached = this.mappingCache.get(`pn:${pnUser}`);
130
- if (cached && typeof cached === 'string') {
131
- if (!addResolvedPair(pn, decoded, cached)) {
132
- this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
133
- continue;
134
- }
135
- continue;
136
- }
137
- pending.push({ pn, pnUser, decoded });
138
- }
139
- if (pending.length) {
140
- const pnUsers = [...new Set(pending.map(item => item.pnUser))];
141
- const stored = await this.keys.get('lid-mapping', pnUsers);
142
- for (const pnUser of pnUsers) {
143
- const lidUser = stored[pnUser];
144
- if (lidUser && typeof lidUser === 'string') {
145
- this.mappingCache.set(`pn:${pnUser}`, lidUser);
146
- this.mappingCache.set(`lid:${lidUser}`, pnUser);
147
- }
148
- }
149
- for (const { pn, pnUser, decoded } of pending) {
150
- const cached = this.mappingCache.get(`pn:${pnUser}`);
151
- if (cached && typeof cached === 'string') {
152
- if (!addResolvedPair(pn, decoded, cached)) {
153
- this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
154
- continue;
155
- }
156
- }
157
- else {
158
- this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
159
- const device = decoded.device || 0;
160
- let normalizedPn = jidNormalizedUser(pn);
161
- if (isHostedPnUser(normalizedPn)) {
162
- normalizedPn = `${pnUser}@s.whatsapp.net`;
163
- }
164
- if (!usyncFetch[normalizedPn]) {
165
- usyncFetch[normalizedPn] = [device];
166
- }
167
- else {
168
- usyncFetch[normalizedPn]?.push(device);
169
- }
170
- }
171
- }
172
- }
173
- if (Object.keys(usyncFetch).length > 0) {
174
- const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)); // this function already adds LIDs to mapping
175
- if (result && result.length > 0) {
176
- await this.storeLIDPNMappings(result);
177
- for (const pair of result) {
178
- const pnDecoded = jidDecode(pair.pn);
179
- const pnUser = pnDecoded?.user;
180
- if (!pnUser)
181
- continue;
182
- const lidUser = jidDecode(pair.lid)?.user;
183
- if (!lidUser)
184
- continue;
185
- for (const device of usyncFetch[pair.pn]) {
186
- const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
187
- this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
188
- const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
189
- successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
190
- }
191
- }
192
- }
193
- else {
194
- this.logger.warn('USync fetch yielded no results for pending PNs');
195
- }
196
- }
197
- return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
198
- }
199
- async getPNForLID(lid) {
200
- return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
201
- }
202
- async getPNsForLIDs(lids) {
203
- if (lids.length === 0)
204
- return null;
205
- const sortedLids = [...new Set(lids)].sort();
206
- const cacheKey = sortedLids.join(',');
207
- const inflight = this.inflightPNLookups.get(cacheKey);
208
- if (inflight) {
209
- this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
210
- return inflight;
211
- }
212
- const promise = this._getPNsForLIDsImpl(lids);
213
- this.inflightPNLookups.set(cacheKey, promise);
214
- try {
215
- return await promise;
216
- }
217
- finally {
218
- this.inflightPNLookups.delete(cacheKey);
219
- }
220
- }
221
- async _getPNsForLIDsImpl(lids) {
222
- const successfulPairs = {};
223
- const pending = [];
224
- const addResolvedPair = (lid, decoded, pnUser) => {
225
- if (!pnUser || typeof pnUser !== 'string') {
226
- return false;
227
- }
228
- const lidDevice = decoded.device !== undefined ? decoded.device : 0;
229
- const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
230
- this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
231
- successfulPairs[lid] = { lid, pn: pnJid };
232
- return true;
233
- };
234
- for (const lid of lids) {
235
- if (!isLidUser(lid))
236
- continue;
237
- const decoded = jidDecode(lid);
238
- if (!decoded)
239
- continue;
240
- const lidUser = decoded.user;
241
- const cached = this.mappingCache.get(`lid:${lidUser}`);
242
- if (cached && typeof cached === 'string') {
243
- addResolvedPair(lid, decoded, cached);
244
- continue;
245
- }
246
- pending.push({ lid, lidUser, decoded });
247
- }
248
- if (pending.length) {
249
- const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
250
- const stored = await this.keys.get('lid-mapping', reverseKeys);
251
- for (const { lid, lidUser, decoded } of pending) {
252
- let pnUser = this.mappingCache.get(`lid:${lidUser}`);
253
- if (!pnUser || typeof pnUser !== 'string') {
254
- pnUser = stored[`${lidUser}_reverse`];
255
- if (pnUser && typeof pnUser === 'string') {
256
- this.mappingCache.set(`lid:${lidUser}`, pnUser);
257
- this.mappingCache.set(`pn:${pnUser}`, lidUser);
258
- }
259
- }
260
- if (pnUser && typeof pnUser === 'string') {
261
- addResolvedPair(lid, decoded, pnUser);
262
- }
263
- else {
264
- this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
265
- }
266
- }
267
- }
268
- return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
269
- }
270
- /**
271
- * Close the cache and release resources
272
- */
273
- close() {
274
- this.mappingCache.clear();
275
- }
276
- }
277
- //# sourceMappingURL=lid-mapping.js.map
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const lru_cache_1 = require("lru-cache")
6
+ const WABinary_1 = require("../WABinary")
7
+
8
+ class LIDMappingStore {
9
+ constructor(keys, onWhatsAppFunc, logger) {
10
+ this.mappingCache = new lru_cache_1.LRUCache({
11
+ ttl: 7 * 24 * 60 * 60 * 1000, // 7 days
12
+ ttlAutopurge: true,
13
+ updateAgeOnGet: true
14
+ })
15
+ this.keys = keys
16
+ this.logger = logger
17
+ this.onWhatsAppFunc = onWhatsAppFunc // needed to get LID from PN if not found
18
+ }
19
+ /**
20
+ * Store LID-PN mapping - USER LEVEL
21
+ */
22
+ async storeLIDPNMappings(pairs) {
23
+ // Validate inputs
24
+ const pairMap = {}
25
+ const logger = this.logger
26
+
27
+ for (const { lid, pn } of pairs) {
28
+ if (!((WABinary_1.isLidUser(lid) && WABinary_1.isJidUser(pn)) || (WABinary_1.isJidUser(lid) && WABinary_1.isLidUser(pn)))) {
29
+ logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
30
+ continue
31
+ }
32
+
33
+ const [lidJid, pnJid] = WABinary_1.isLidUser(lid) ? [lid, pn] : [pn, lid]
34
+ const lidDecoded = WABinary_1.jidDecode(lidJid)
35
+ const pnDecoded = WABinary_1.jidDecode(pnJid)
36
+
37
+ if (!lidDecoded || !pnDecoded) return
38
+
39
+ const pnUser = pnDecoded.user
40
+ const lidUser = lidDecoded.user
41
+
42
+ // Check if mapping already exists (cache first, then database)
43
+ let existingLidUser = this.mappingCache.get(`pn:${pnUser}`)
44
+
45
+ if (!existingLidUser) {
46
+ // Cache miss - check database
47
+ const stored = await this.keys.get('lid-mapping', [pnUser])
48
+
49
+ existingLidUser = stored[pnUser]
50
+
51
+ if (existingLidUser) {
52
+ // Update cache with database value
53
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser)
54
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser)
55
+ }
56
+ }
57
+
58
+ if (existingLidUser === lidUser) {
59
+ logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping')
60
+ continue
61
+ }
62
+
63
+ pairMap[pnUser] = lidUser
64
+ }
65
+
66
+ logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
67
+
68
+ await this.keys.transaction(async () => {
69
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
70
+ await this.keys.set({
71
+ 'lid-mapping': {
72
+ [pnUser]: lidUser, // "554396160286" -> "102765716062358"
73
+ [`${lidUser}_reverse`]: pnUser // "102765716062358_reverse" -> "554396160286"
74
+ }
75
+ })
76
+
77
+ // Update cache with both directions
78
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
79
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
80
+ }
81
+ }, 'lid-mapping')
82
+ }
83
+ /**
84
+ * Get LID for PN - Returns device-specific LID based on user mapping
85
+ */
86
+ async getLIDForPN(pn) {
87
+ if (!WABinary_1.isJidUser(pn)) return null
88
+
89
+ const logger = this.logger
90
+ const decoded = WABinary_1.jidDecode(pn)
91
+
92
+ if (!decoded) return null
93
+
94
+ // Check cache first for PN → LID mapping
95
+ const pnUser = decoded.user
96
+
97
+ let lidUser = this.mappingCache.get(`pn:${pnUser}`)
98
+
99
+ if (!lidUser) {
100
+ // Cache miss - check database
101
+ const stored = await this.keys.get('lid-mapping', [pnUser])
102
+
103
+ lidUser = stored[pnUser]
104
+
105
+ if (lidUser) {
106
+ // Cache the database result
107
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
108
+ }
109
+
110
+ else {
111
+ // Not in database - try USync
112
+ logger.trace(`No LID mapping found for PN user ${pnUser}; getting from USync`)
113
+
114
+ const { exists, lid } = (await this.onWhatsAppFunc?.(pn))?.[0] // this function already adds LIDs to mapping
115
+
116
+ if (exists && lid) {
117
+ lidUser = WABinary_1.jidDecode(lid)?.user
118
+
119
+ if (lidUser) {
120
+ // Cache the USync result
121
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
122
+ }
123
+ }
124
+
125
+ else {
126
+ return null
127
+ }
128
+ }
129
+ }
130
+
131
+ if (typeof lidUser !== 'string' || !lidUser) {
132
+ logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
133
+ return null
134
+ }
135
+
136
+ // Push the PN device ID to the LID to maintain device separation
137
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0
138
+ const deviceSpecificLid = `${lidUser}:${pnDevice}@lid`
139
+
140
+ logger.trace(`getLIDForPN: ${pn} ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
141
+
142
+ return deviceSpecificLid
143
+ }
144
+ /**
145
+ * Get PN for LID - USER LEVEL with device construction
146
+ */
147
+ async getPNForLID(lid) {
148
+ if (!WABinary_1.isLidUser(lid)) return null
149
+
150
+ const logger = this.logger
151
+ const decoded = WABinary_1.jidDecode(lid)
152
+
153
+ if (!decoded) return null
154
+
155
+ // Check cache first for LID → PN mapping
156
+ const lidUser = decoded.user
157
+
158
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`)
159
+
160
+ if (!pnUser || typeof pnUser !== 'string') {
161
+ // Cache miss - check database
162
+ const stored = await this.keys.get('lid-mapping', [`${lidUser}_reverse`]);
163
+ pnUser = stored[`${lidUser}_reverse`]
164
+
165
+ if (!pnUser || typeof pnUser !== 'string') {
166
+ logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
167
+ return null
168
+ }
169
+
170
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
171
+ }
172
+
173
+ // Construct device-specific PN JID
174
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0
175
+ const pnJid = `${pnUser}:${lidDevice}@s.whatsapp.net`
176
+ logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
177
+
178
+ return pnJid
179
+ }
180
+ }
181
+
182
+ module.exports = {
183
+ LIDMappingStore
184
+ }
@@ -1,3 +1,2 @@
1
- export * from './types.js';
2
- export * from './websocket.js';
3
- //# sourceMappingURL=index.d.ts.map
1
+ export * from './types'
2
+ export * from './websocket'
@@ -1,3 +1,22 @@
1
- export * from './types.js';
2
- export * from './websocket.js';
3
- //# sourceMappingURL=index.js.map
1
+ "use strict"
2
+
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k] } }
8
+ }
9
+ Object.defineProperty(o, k2, desc)
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
13
+ }))
14
+
15
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p)
17
+ }
18
+
19
+ Object.defineProperty(exports, "__esModule", { value: true })
20
+
21
+ __exportStar(require("./types"), exports)
22
+ __exportStar(require("./websocket"), exports)
@@ -1,16 +1,16 @@
1
- import { EventEmitter } from 'events';
2
- import { URL } from 'url';
3
- import type { SocketConfig } from '../../Types/index.js';
1
+ import { EventEmitter } from 'events'
2
+ import { URL } from 'url'
3
+ import { SocketConfig } from '../../Types'
4
+
4
5
  export declare abstract class AbstractSocketClient extends EventEmitter {
5
- url: URL;
6
- config: SocketConfig;
7
- abstract get isOpen(): boolean;
8
- abstract get isClosed(): boolean;
9
- abstract get isClosing(): boolean;
10
- abstract get isConnecting(): boolean;
11
- constructor(url: URL, config: SocketConfig);
12
- abstract connect(): void;
13
- abstract close(): void;
14
- abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
15
- }
16
- //# sourceMappingURL=types.d.ts.map
6
+ url: URL
7
+ config: SocketConfig
8
+ abstract get isOpen(): boolean
9
+ abstract get isClosed(): boolean
10
+ abstract get isClosing(): boolean
11
+ abstract get isConnecting(): boolean
12
+ constructor(url: URL, config: SocketConfig)
13
+ abstract connect(): Promise<void>
14
+ abstract close(): Promise<void>
15
+ abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean
16
+ }
@@ -1,11 +1,18 @@
1
- import { EventEmitter } from 'events';
2
- import { URL } from 'url';
3
- export class AbstractSocketClient extends EventEmitter {
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const events_1 = require("events")
6
+
7
+ class AbstractSocketClient extends events_1.EventEmitter {
4
8
  constructor(url, config) {
5
- super();
6
- this.url = url;
7
- this.config = config;
8
- this.setMaxListeners(0);
9
+ super()
10
+ this.url = url
11
+ this.config = config
12
+ this.setMaxListeners(0)
9
13
  }
10
14
  }
11
- //# sourceMappingURL=types.js.map
15
+
16
+ module.exports = {
17
+ AbstractSocketClient
18
+ }
@@ -1,13 +1,13 @@
1
- import WebSocket from 'ws';
2
- import { AbstractSocketClient } from './types.js';
1
+ import WebSocket from 'ws'
2
+ import { AbstractSocketClient } from './types'
3
+
3
4
  export declare class WebSocketClient extends AbstractSocketClient {
4
- protected socket: WebSocket | null;
5
- get isOpen(): boolean;
6
- get isClosed(): boolean;
7
- get isClosing(): boolean;
8
- get isConnecting(): boolean;
9
- connect(): void;
10
- close(): Promise<void>;
11
- send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean;
12
- }
13
- //# sourceMappingURL=websocket.d.ts.map
5
+ protected socket: WebSocket | null
6
+ get isOpen(): boolean
7
+ get isClosed(): boolean
8
+ get isClosing(): boolean
9
+ get isConnecting(): boolean
10
+ connect(): Promise<void>
11
+ close(): Promise<void>
12
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean
13
+ }