kage-baileys 3.0.6 → 3.2.3

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 (216) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/WAProto/WAProto.proto +3395 -415
  4. package/WAProto/compat.cjs +12 -0
  5. package/WAProto/index.d.ts +47104 -19888
  6. package/WAProto/index.js +131979 -57361
  7. package/lib/Addon/http-error.js +43 -0
  8. package/lib/Addon/index.js +32 -0
  9. package/lib/Addon/keyed-db.js +250 -0
  10. package/lib/Addon/link-preview.js +82 -0
  11. package/lib/Defaults/baileys-version.json +3 -0
  12. package/lib/Defaults/connection.js +110 -0
  13. package/lib/Defaults/constants.js +156 -0
  14. package/lib/Defaults/history.js +46 -0
  15. package/lib/Defaults/index.js +230 -0
  16. package/lib/Defaults/media.js +104 -0
  17. package/lib/Defaults/phonenumber-mcc.json +223 -0
  18. package/lib/Defaults/prefix.js +44 -0
  19. package/lib/Extensions/business-advanced.js +382 -0
  20. package/lib/Extensions/business.js +159 -0
  21. package/lib/Extensions/chats-advanced.js +1106 -0
  22. package/lib/Extensions/chats.js +349 -0
  23. package/lib/Extensions/communities-advanced.js +430 -0
  24. package/lib/Extensions/community.js +94 -0
  25. package/lib/Extensions/groups-advanced.js +343 -0
  26. package/lib/Extensions/index.js +30 -0
  27. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  28. package/lib/Extensions/messages-send-advanced.js +622 -0
  29. package/lib/Extensions/messages-send.js +1380 -0
  30. package/lib/Extensions/newsletter-advanced.js +228 -0
  31. package/lib/Extensions/newsletter.js +72 -0
  32. package/lib/Extensions/socket.js +389 -0
  33. package/lib/Modded/message_builder.js +2084 -4
  34. package/lib/Signal/Group/ciphertext-message.js +54 -0
  35. package/lib/Signal/Group/group-session-builder.js +124 -0
  36. package/lib/Signal/Group/group_cipher.js +216 -0
  37. package/lib/Signal/Group/index.js +124 -0
  38. package/lib/Signal/Group/keyhelper.js +108 -0
  39. package/lib/Signal/Group/sender-chain-key.js +83 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  41. package/lib/Signal/Group/sender-key-message.js +166 -0
  42. package/lib/Signal/Group/sender-key-name.js +130 -0
  43. package/lib/Signal/Group/sender-key-record.js +113 -0
  44. package/lib/Signal/Group/sender-key-state.js +208 -0
  45. package/lib/Signal/Group/sender-message-key.js +82 -0
  46. package/lib/Signal/libsignal.js +935 -0
  47. package/lib/Signal/lid-mapping.js +545 -1
  48. package/lib/Socket/Client/index.js +60 -0
  49. package/lib/Socket/Client/types.js +51 -0
  50. package/lib/Socket/Client/websocket.js +152 -0
  51. package/lib/Socket/business.js +831 -0
  52. package/lib/Socket/chats.js +2535 -49
  53. package/lib/Socket/communities.js +450 -1
  54. package/lib/Socket/community.js +1022 -0
  55. package/lib/Socket/dugong.js +1 -1
  56. package/lib/Socket/groups.js +747 -0
  57. package/lib/Socket/index.js +60 -2
  58. package/lib/Socket/messages-recv.js +3450 -5
  59. package/lib/Socket/messages-send.js +3123 -0
  60. package/lib/Socket/mex.js +126 -1
  61. package/lib/Socket/newsletter.js +465 -0
  62. package/lib/Socket/socket.js +2217 -1
  63. package/lib/Store/index.js +79 -0
  64. package/lib/Store/make-cache-manager-store.js +186 -0
  65. package/lib/Store/make-in-memory-store.js +878 -0
  66. package/lib/Store/make-ordered-dictionary.js +187 -0
  67. package/lib/Store/object-repository.js +78 -0
  68. package/lib/Types/Auth.js +25 -0
  69. package/lib/Types/Bussines.js +25 -1
  70. package/lib/Types/Call.js +25 -0
  71. package/lib/Types/Chat.js +39 -0
  72. package/lib/Types/Contact.js +25 -0
  73. package/lib/Types/Events.js +25 -0
  74. package/lib/Types/GroupMetadata.js +25 -0
  75. package/lib/Types/Label.js +76 -0
  76. package/lib/Types/LabelAssociation.js +40 -0
  77. package/lib/Types/Message.js +57 -0
  78. package/lib/Types/Mex.js +56 -1
  79. package/lib/Types/MexUpdates.js +46 -0
  80. package/lib/Types/Newsletter.js +56 -0
  81. package/lib/Types/Product.js +25 -0
  82. package/lib/Types/RichType.js +23 -0
  83. package/lib/Types/Signal.js +25 -0
  84. package/lib/Types/Socket.js +25 -0
  85. package/lib/Types/State.js +92 -0
  86. package/lib/Types/USync.js +25 -0
  87. package/lib/Types/index.js +133 -0
  88. package/lib/Utils/auth-utils.js +703 -0
  89. package/lib/Utils/automation-tools.js +51 -16
  90. package/lib/Utils/baileys-event-stream.js +146 -0
  91. package/lib/Utils/browser-utils.js +95 -0
  92. package/lib/Utils/business.js +525 -0
  93. package/lib/Utils/chat-utils.js +1861 -0
  94. package/lib/Utils/companion-reg-client-utils.js +55 -1
  95. package/lib/Utils/crypto.js +355 -0
  96. package/lib/Utils/decode-wa-message.js +709 -0
  97. package/lib/Utils/event-buffer.js +1323 -8
  98. package/lib/Utils/generics.js +945 -1
  99. package/lib/Utils/history.js +266 -0
  100. package/lib/Utils/identity-change-handler.js +62 -1
  101. package/lib/Utils/index.js +114 -0
  102. package/lib/Utils/link-preview.js +179 -0
  103. package/lib/Utils/logger.js +42 -0
  104. package/lib/Utils/lt-hash.js +73 -0
  105. package/lib/Utils/make-mutex.js +104 -0
  106. package/lib/Utils/message-inspector.js +110 -0
  107. package/lib/Utils/message-retry-manager.js +507 -2
  108. package/lib/Utils/messages-media.js +1931 -1
  109. package/lib/Utils/messages.js +3748 -0
  110. package/lib/Utils/noise-handler.js +423 -0
  111. package/lib/Utils/offline-node-processor.js +53 -1
  112. package/lib/Utils/pre-key-manager.js +255 -1
  113. package/lib/Utils/process-message.js +1592 -0
  114. package/lib/Utils/reporting-utils.js +272 -1
  115. package/lib/Utils/rich-message-utils.js +377 -0
  116. package/lib/Utils/rich-messages.js +1 -1
  117. package/lib/Utils/signal.js +437 -0
  118. package/lib/Utils/stanza-ack.js +51 -1
  119. package/lib/Utils/status-refresh.js +37 -0
  120. package/lib/Utils/status-tools.js +4 -2
  121. package/lib/Utils/sync-action-utils.js +63 -1
  122. package/lib/Utils/tc-token-utils.js +185 -1
  123. package/lib/Utils/terminal-banner.js +31 -0
  124. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  125. package/lib/Utils/use-single-file-auth-state.js +108 -0
  126. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  127. package/lib/Utils/validate-connection.js +497 -1
  128. package/lib/Utils/view-once-compat.js +13 -5
  129. package/lib/VoIP/audio-feeder.js +150 -0
  130. package/lib/VoIP/index.js +289 -0
  131. package/lib/VoIP/relay-transport.js +608 -0
  132. package/lib/VoIP/signaling.js +583 -0
  133. package/lib/VoIP/types.js +30 -0
  134. package/lib/VoIP/wasm-engine.js +1261 -2
  135. package/lib/VoIP/worker-bootstrap.js +1090 -2
  136. package/lib/WABinary/constants.js +2805 -0
  137. package/lib/WABinary/decode.js +649 -2
  138. package/lib/WABinary/encode.js +564 -2
  139. package/lib/WABinary/generic-utils.js +401 -0
  140. package/lib/WABinary/index.js +82 -0
  141. package/lib/WABinary/jid-utils.js +290 -0
  142. package/lib/WABinary/types.js +25 -0
  143. package/lib/WAM/BinaryInfo.js +50 -0
  144. package/lib/WAM/constants.js +45747 -0
  145. package/lib/WAM/encode.js +393 -0
  146. package/lib/WAM/index.js +78 -0
  147. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  148. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  151. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  153. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  154. package/lib/WAUSync/Protocols/index.js +83 -0
  155. package/lib/WAUSync/USyncQuery.js +241 -2
  156. package/lib/WAUSync/USyncUser.js +86 -0
  157. package/lib/WAUSync/index.js +78 -0
  158. package/lib/assets/wasm/loader.js +1875 -1
  159. package/lib/assets/wasm/worker-modules.js +11047 -1
  160. package/lib/index.d.ts +126 -0
  161. package/lib/index.js +53 -21
  162. package/lib/index.mjs +437 -0
  163. package/licenses/upstream-MIT.txt +22 -0
  164. package/maintenance/api-coverage.json +1642 -0
  165. package/maintenance/archivos-sha256.json +207 -0
  166. package/maintenance/consumer-validation.log +3 -0
  167. package/maintenance/dependency-audit.json +4 -4
  168. package/maintenance/extension-inventory.json +57 -0
  169. package/maintenance/protocol-update.json +1101 -0
  170. package/maintenance/protocol-wire-audit.json +4 -0
  171. package/maintenance/reference-socket-surface.json +209 -0
  172. package/maintenance/resumen-validacion.json +50 -0
  173. package/maintenance/validation.log +2725 -0
  174. package/maintenance/verification.json +566 -0
  175. package/package.json +107 -9
  176. package/scripts/check-imports.cjs +10 -0
  177. package/scripts/check-package.cjs +40 -0
  178. package/scripts/check-syntax.cjs +1 -1
  179. package/scripts/generate-protobuf.cjs +6 -1
  180. package/scripts/generate-public-types.cjs +9 -0
  181. package/scripts/kage-base64-fix.cjs +45 -0
  182. package/scripts/maintenance.cjs +10 -0
  183. package/test/advanced.test.cjs +24 -0
  184. package/test/base64-fix.test.cjs +49 -0
  185. package/test/maintenance.test.cjs +1 -1
  186. package/test/npm-publication.test.cjs +141 -0
  187. package/test/recepcion-reparada.test.cjs +98 -0
  188. package/test/resilience-binary.test.cjs +69 -0
  189. package/test/resilience-transport.test.cjs +34 -0
  190. package/test/types.test.ts +5 -0
  191. package/test/upgrade.test.cjs +104 -0
  192. package/tsconfig.json +20 -0
  193. package/WAProto/p.html +0 -1
  194. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  195. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  196. package/lib/KageExtra/VoIP/index.js +0 -282
  197. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  198. package/lib/KageExtra/VoIP/signaling.js +0 -603
  199. package/lib/KageExtra/VoIP/types.js +0 -17
  200. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  201. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  202. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  203. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  204. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  205. package/lib/KageExtra/index.js +0 -3
  206. package/lib/KageExtra/package.json +0 -1
  207. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  209. package/maintenance/revision-full-check.txt +0 -1097
  210. package/maintenance/revision-library-tests.tap +0 -1088
  211. package/maintenance/revision-protobuf.txt +0 -5
  212. package/maintenance/revision-syntax.txt +0 -5
  213. package/maintenance/schema-coverage.json +0 -23
  214. package/maintenance/schema-merge.json +0 -30
  215. package/maintenance/validation-node20.txt +0 -191
  216. package/maintenance/validation-node22.txt +0 -237
@@ -268,4 +268,548 @@ var _indexjs = require('../WABinary/index.js');
268
268
  return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
269
269
  }
270
270
  } exports.LIDMappingStore = LIDMappingStore;
271
- //# sourceMappingURL=lid-mapping.js.map
271
+ //#
272
+ // Kage: compatibilidad de API.
273
+ const __kageModule20 = (() => {
274
+ const module = { exports: {} }; const exports = module.exports;
275
+ "use strict"
276
+
277
+ Object.defineProperty(exports, "__esModule", { value: true })
278
+
279
+ const { LRUCache } = require("lru-cache")
280
+ const {
281
+ isHostedPnUser,
282
+ isLidUser,
283
+ isPnUser,
284
+ jidDecode,
285
+ jidNormalizedUser,
286
+ WAJIDDomains
287
+ } = require("../WABinary")
288
+
289
+ class LIDMappingStore {
290
+ constructor(keys, logger, pnToLIDFunc) {
291
+ this.mappingCache = new LRUCache({
292
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
293
+ ttlAutopurge: true,
294
+ updateAgeOnGet: true
295
+ })
296
+ this.keys = keys
297
+ this.pnToLIDFunc = pnToLIDFunc
298
+ this.logger = logger
299
+ }
300
+
301
+ /**
302
+ * Store LID-PN mapping - USER LEVEL
303
+ */
304
+ async storeLIDPNMappings(pairs) {
305
+ // Validate inputs
306
+ const pairMap = {}
307
+
308
+ for (const { lid, pn } of pairs) {
309
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
310
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
311
+ continue
312
+ }
313
+
314
+ const lidDecoded = jidDecode(lid)
315
+ const pnDecoded = jidDecode(pn)
316
+
317
+ if (!lidDecoded || !pnDecoded) return
318
+
319
+ const pnUser = pnDecoded.user
320
+ const lidUser = lidDecoded.user
321
+
322
+ let existingLidUser = this.mappingCache.get(`pn:${pnUser}`)
323
+
324
+ if (!existingLidUser) {
325
+ this.logger.trace(`Cache miss for PN user ${pnUser}; checking database`)
326
+
327
+ const stored = await this.keys.get('lid-mapping', [pnUser])
328
+
329
+ existingLidUser = stored[pnUser]
330
+
331
+ if (existingLidUser) {
332
+ // Update cache with database value
333
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser)
334
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser)
335
+ }
336
+ }
337
+
338
+ if (existingLidUser === lidUser) {
339
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping')
340
+ continue
341
+ }
342
+
343
+ pairMap[pnUser] = lidUser
344
+ }
345
+
346
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
347
+
348
+ await this.keys.transaction(async () => {
349
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
350
+ await this.keys.set({
351
+ 'lid-mapping': {
352
+ [pnUser]: lidUser,
353
+ [`${lidUser}_reverse`]: pnUser
354
+ }
355
+ })
356
+
357
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
358
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
359
+ }
360
+ }, 'lid-mapping')
361
+ }
362
+
363
+ /**
364
+ * Get LID for PN - Returns device-specific LID based on user mapping
365
+ */
366
+ async getLIDForPN(pn) {
367
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null
368
+ }
369
+
370
+ async getLIDsForPNs(pns) {
371
+ const usyncFetch = {}
372
+
373
+ // mapped from pn to lid mapping to prevent duplication in results later
374
+ const successfulPairs = {}
375
+
376
+ for (const pn of pns) {
377
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue
378
+
379
+ const decoded = jidDecode(pn)
380
+ if (!decoded) continue
381
+
382
+ // Check cache first for PN → LID mapping
383
+ const pnUser = decoded.user
384
+
385
+ let lidUser = this.mappingCache.get(`pn:${pnUser}`)
386
+
387
+ if (!lidUser) {
388
+ // Cache miss - check database
389
+ const stored = await this.keys.get('lid-mapping', [pnUser])
390
+
391
+ lidUser = stored[pnUser]
392
+
393
+ if (lidUser) {
394
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
395
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
396
+ }
397
+
398
+ else {
399
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`)
400
+
401
+ const device = decoded.device || 0
402
+
403
+ let normalizedPn = jidNormalizedUser(pn)
404
+
405
+ if (isHostedPnUser(normalizedPn)) {
406
+ normalizedPn = `${pnUser}@s.whatsapp.net`
407
+ }
408
+
409
+ if (!usyncFetch[normalizedPn]) {
410
+ usyncFetch[normalizedPn] = [device]
411
+ }
412
+
413
+ else {
414
+ usyncFetch[normalizedPn]?.push(device)
415
+ }
416
+
417
+ continue
418
+ }
419
+ }
420
+
421
+ lidUser = lidUser.toString()
422
+
423
+ if (!lidUser) {
424
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
425
+ return null
426
+ }
427
+
428
+ // Push the PN device ID to the LID to maintain device separation
429
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0
430
+ const deviceSpecificLid = `${lidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`
431
+
432
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
433
+
434
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn }
435
+ }
436
+
437
+ if (Object.keys(usyncFetch).length > 0) {
438
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)) // this function already adds LIDs to mapping
439
+
440
+ if (result && result.length > 0) {
441
+ await this.storeLIDPNMappings(result)
442
+
443
+ for (const pair of result) {
444
+ const pnDecoded = jidDecode(pair.pn)
445
+ const pnUser = pnDecoded?.user
446
+
447
+ if (!pnUser) continue
448
+
449
+ const lidUser = jidDecode(pair.lid)?.user
450
+
451
+ if (!lidUser) continue
452
+
453
+ for (const device of usyncFetch[pair.pn]) {
454
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`
455
+
456
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`)
457
+
458
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`
459
+
460
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn }
461
+ }
462
+ }
463
+ }
464
+
465
+ else {
466
+ return null
467
+ }
468
+ }
469
+
470
+ return Object.values(successfulPairs)
471
+ }
472
+
473
+ /**
474
+ * Get PN for LID - USER LEVEL with device construction
475
+ */
476
+ async getPNForLID(lid) {
477
+ if (!isLidUser(lid)) return null
478
+
479
+ const decoded = jidDecode(lid)
480
+
481
+ if (!decoded) return null
482
+
483
+ // Check cache first for LID → PN mapping
484
+ const lidUser = decoded.user
485
+
486
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`)
487
+
488
+ if (!pnUser || typeof pnUser !== 'string') {
489
+ // Cache miss - check database
490
+ const stored = await this.keys.get('lid-mapping', [`${lidUser}_reverse`])
491
+
492
+ pnUser = stored[`${lidUser}_reverse`]
493
+
494
+ if (!pnUser || typeof pnUser !== 'string') {
495
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
496
+ return null
497
+ }
498
+
499
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
500
+ }
501
+
502
+ // Construct device-specific PN JID
503
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0
504
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`
505
+
506
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
507
+
508
+ return pnJid
509
+ }
510
+ }
511
+
512
+ module.exports = {
513
+ LIDMappingStore
514
+ }
515
+ return module.exports;
516
+ })();
517
+ for (const key of Object.keys(__kageModule20)) {
518
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule20[key]});
519
+ }
520
+
521
+ // Kage: funciones avanzadas.
522
+ const __kageModule126 = (() => {
523
+ const module = { exports: {} }; const exports = module.exports;
524
+ "use strict";
525
+ Object.defineProperty(exports, "__esModule", { value: true });
526
+ exports.LIDMappingStore = void 0;
527
+ const index_js_1 = require("../Addon/index.js");
528
+ const index_js_2 = require("../WABinary/index.js");
529
+ class LIDMappingStore {
530
+ constructor(keys, logger, pnToLIDFunc) {
531
+ this.mappingCache = (0, index_js_1.createCache)({
532
+ ttl: 3 * 24 * 60 * 60 // 3 days
533
+ });
534
+ this.inflightLIDLookups = new Map();
535
+ this.inflightPNLookups = new Map();
536
+ this.keys = keys;
537
+ this.pnToLIDFunc = pnToLIDFunc;
538
+ this.logger = logger;
539
+ }
540
+ async storeLIDPNMappings(pairs) {
541
+ if (pairs.length === 0)
542
+ return;
543
+ const validatedPairs = [];
544
+ for (const { lid, pn } of pairs) {
545
+ if (!(((0, index_js_2.isLidUser)(lid) && (0, index_js_2.isPnUser)(pn)) || ((0, index_js_2.isPnUser)(lid) && (0, index_js_2.isLidUser)(pn)))) {
546
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
547
+ continue;
548
+ }
549
+ const lidDecoded = (0, index_js_2.jidDecode)(lid);
550
+ const pnDecoded = (0, index_js_2.jidDecode)(pn);
551
+ if (!lidDecoded || !pnDecoded)
552
+ continue;
553
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
554
+ }
555
+ if (validatedPairs.length === 0)
556
+ return;
557
+ const cacheMissSet = new Set();
558
+ const existingMappings = new Map();
559
+ for (const { pnUser } of validatedPairs) {
560
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
561
+ if (cached) {
562
+ existingMappings.set(pnUser, cached);
563
+ }
564
+ else {
565
+ cacheMissSet.add(pnUser);
566
+ }
567
+ }
568
+ if (cacheMissSet.size > 0) {
569
+ const cacheMisses = [...cacheMissSet];
570
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
571
+ const stored = await this.keys.get('lid-mapping', cacheMisses);
572
+ for (const pnUser of cacheMisses) {
573
+ const existingLidUser = stored[pnUser];
574
+ if (existingLidUser) {
575
+ existingMappings.set(pnUser, existingLidUser);
576
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
577
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
578
+ }
579
+ }
580
+ }
581
+ const pairMap = {};
582
+ for (const { pnUser, lidUser } of validatedPairs) {
583
+ const existingLidUser = existingMappings.get(pnUser);
584
+ if (existingLidUser === lidUser) {
585
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
586
+ continue;
587
+ }
588
+ pairMap[pnUser] = lidUser;
589
+ }
590
+ if (Object.keys(pairMap).length === 0)
591
+ return;
592
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
593
+ const batchData = {};
594
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
595
+ batchData[pnUser] = lidUser;
596
+ batchData[`${lidUser}_reverse`] = pnUser;
597
+ }
598
+ await this.keys.transaction(async () => {
599
+ await this.keys.set({ 'lid-mapping': batchData });
600
+ }, 'lid-mapping');
601
+ // Update cache after successful DB write
602
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
603
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
604
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
605
+ }
606
+ }
607
+ async getLIDForPN(pn) {
608
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
609
+ }
610
+ async getLIDsForPNs(pns) {
611
+ if (pns.length === 0)
612
+ return null;
613
+ const sortedPns = [...new Set(pns)].sort();
614
+ const cacheKey = sortedPns.join(',');
615
+ const inflight = this.inflightLIDLookups.get(cacheKey);
616
+ if (inflight) {
617
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
618
+ return inflight;
619
+ }
620
+ const promise = this._getLIDsForPNsImpl(pns);
621
+ this.inflightLIDLookups.set(cacheKey, promise);
622
+ try {
623
+ return await promise;
624
+ }
625
+ finally {
626
+ this.inflightLIDLookups.delete(cacheKey);
627
+ }
628
+ }
629
+ async _getLIDsForPNsImpl(pns) {
630
+ const usyncFetch = {};
631
+ const successfulPairs = {};
632
+ const pending = [];
633
+ const addResolvedPair = (pn, decoded, lidUser) => {
634
+ const normalizedLidUser = lidUser.toString();
635
+ if (!normalizedLidUser) {
636
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
637
+ return false;
638
+ }
639
+ // Push the PN device ID to the LID to maintain device separation
640
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
641
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
642
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
643
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
644
+ return true;
645
+ };
646
+ for (const pn of pns) {
647
+ if (!(0, index_js_2.isPnUser)(pn) && !(0, index_js_2.isHostedPnUser)(pn))
648
+ continue;
649
+ const decoded = (0, index_js_2.jidDecode)(pn);
650
+ if (!decoded)
651
+ continue;
652
+ const pnUser = decoded.user;
653
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
654
+ if (cached && typeof cached === 'string') {
655
+ if (!addResolvedPair(pn, decoded, cached)) {
656
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
657
+ continue;
658
+ }
659
+ continue;
660
+ }
661
+ pending.push({ pn, pnUser, decoded });
662
+ }
663
+ if (pending.length) {
664
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))];
665
+ const stored = await this.keys.get('lid-mapping', pnUsers);
666
+ for (const pnUser of pnUsers) {
667
+ const lidUser = stored[pnUser];
668
+ if (lidUser && typeof lidUser === 'string') {
669
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
670
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
671
+ }
672
+ }
673
+ for (const { pn, pnUser, decoded } of pending) {
674
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
675
+ if (cached && typeof cached === 'string') {
676
+ if (!addResolvedPair(pn, decoded, cached)) {
677
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
678
+ continue;
679
+ }
680
+ }
681
+ else {
682
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
683
+ const device = decoded.device || 0;
684
+ let normalizedPn = (0, index_js_2.jidNormalizedUser)(pn);
685
+ if ((0, index_js_2.isHostedPnUser)(normalizedPn)) {
686
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
687
+ }
688
+ if (!usyncFetch[normalizedPn]) {
689
+ usyncFetch[normalizedPn] = [device];
690
+ }
691
+ else {
692
+ usyncFetch[normalizedPn]?.push(device);
693
+ }
694
+ }
695
+ }
696
+ }
697
+ if (Object.keys(usyncFetch).length > 0) {
698
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)); // this function already adds LIDs to mapping
699
+ if (result && result.length > 0) {
700
+ await this.storeLIDPNMappings(result);
701
+ for (const pair of result) {
702
+ const pnDecoded = (0, index_js_2.jidDecode)(pair.pn);
703
+ const pnUser = pnDecoded?.user;
704
+ if (!pnUser)
705
+ continue;
706
+ const lidUser = (0, index_js_2.jidDecode)(pair.lid)?.user;
707
+ if (!lidUser)
708
+ continue;
709
+ for (const device of usyncFetch[pair.pn]) {
710
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
711
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
712
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
713
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
714
+ }
715
+ }
716
+ }
717
+ else {
718
+ this.logger.warn('USync fetch yielded no results for pending PNs');
719
+ }
720
+ }
721
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
722
+ }
723
+ async getPNForLID(lid) {
724
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
725
+ }
726
+ async getPNsForLIDs(lids) {
727
+ if (lids.length === 0)
728
+ return null;
729
+ const sortedLids = [...new Set(lids)].sort();
730
+ const cacheKey = sortedLids.join(',');
731
+ const inflight = this.inflightPNLookups.get(cacheKey);
732
+ if (inflight) {
733
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
734
+ return inflight;
735
+ }
736
+ const promise = this._getPNsForLIDsImpl(lids);
737
+ this.inflightPNLookups.set(cacheKey, promise);
738
+ try {
739
+ return await promise;
740
+ }
741
+ finally {
742
+ this.inflightPNLookups.delete(cacheKey);
743
+ }
744
+ }
745
+ async _getPNsForLIDsImpl(lids) {
746
+ const successfulPairs = {};
747
+ const pending = [];
748
+ const addResolvedPair = (lid, decoded, pnUser) => {
749
+ if (!pnUser || typeof pnUser !== 'string') {
750
+ return false;
751
+ }
752
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
753
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === index_js_2.WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
754
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
755
+ successfulPairs[lid] = { lid, pn: pnJid };
756
+ return true;
757
+ };
758
+ for (const lid of lids) {
759
+ if (!(0, index_js_2.isLidUser)(lid))
760
+ continue;
761
+ const decoded = (0, index_js_2.jidDecode)(lid);
762
+ if (!decoded)
763
+ continue;
764
+ const lidUser = decoded.user;
765
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
766
+ if (cached && typeof cached === 'string') {
767
+ addResolvedPair(lid, decoded, cached);
768
+ continue;
769
+ }
770
+ pending.push({ lid, lidUser, decoded });
771
+ }
772
+ if (pending.length) {
773
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
774
+ const stored = await this.keys.get('lid-mapping', reverseKeys);
775
+ for (const { lid, lidUser, decoded } of pending) {
776
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
777
+ if (!pnUser || typeof pnUser !== 'string') {
778
+ pnUser = stored[`${lidUser}_reverse`];
779
+ if (pnUser && typeof pnUser === 'string') {
780
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
781
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
782
+ }
783
+ }
784
+ if (pnUser && typeof pnUser === 'string') {
785
+ addResolvedPair(lid, decoded, pnUser);
786
+ }
787
+ else {
788
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
789
+ }
790
+ }
791
+ }
792
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
793
+ }
794
+ /**
795
+ * Close the cache and release resources
796
+ */
797
+ close() {
798
+ this.mappingCache.flushAll();
799
+ }
800
+ }
801
+ exports.LIDMappingStore = LIDMappingStore;
802
+
803
+ return module.exports;
804
+ })();
805
+ for (const key of Object.keys(__kageModule126)) {
806
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule126[key]});
807
+ }
808
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule126, configurable:true});
809
+
810
+ // Kage: superficie pública completa.
811
+ exports.LIDMappingStore.prototype.close = function () {
812
+ this.mappingCache.clear();
813
+ this.inflightLIDLookups.clear();
814
+ this.inflightPNLookups.clear();
815
+ };
@@ -16,3 +16,63 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./types"), exports);
18
18
  __exportStar(require("./websocket"), exports);
19
+
20
+ // Kage: compatibilidad de API.
21
+ const __kageModule21 = (() => {
22
+ const module = { exports: {} }; const exports = module.exports;
23
+ "use strict"
24
+
25
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k
27
+ var desc = Object.getOwnPropertyDescriptor(m, k)
28
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
29
+ desc = { enumerable: true, get: function() { return m[k] } }
30
+ }
31
+ Object.defineProperty(o, k2, desc)
32
+ }) : (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k
34
+ o[k2] = m[k]
35
+ }))
36
+
37
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
38
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p)
39
+ }
40
+
41
+ Object.defineProperty(exports, "__esModule", { value: true })
42
+
43
+ __exportStar(require("./types"), exports)
44
+ __exportStar(require("./websocket"), exports)
45
+ return module.exports;
46
+ })();
47
+ for (const key of Object.keys(__kageModule21)) {
48
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule21[key]});
49
+ }
50
+
51
+ // Kage: funciones avanzadas.
52
+ const __kageModule127 = (() => {
53
+ const module = { exports: {} }; const exports = module.exports;
54
+ "use strict";
55
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
56
+ if (k2 === undefined) k2 = k;
57
+ var desc = Object.getOwnPropertyDescriptor(m, k);
58
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
59
+ desc = { enumerable: true, get: function() { return m[k]; } };
60
+ }
61
+ Object.defineProperty(o, k2, desc);
62
+ }) : (function(o, m, k, k2) {
63
+ if (k2 === undefined) k2 = k;
64
+ o[k2] = m[k];
65
+ }));
66
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
67
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
68
+ };
69
+ Object.defineProperty(exports, "__esModule", { value: true });
70
+ __exportStar(require("./types.js"), exports);
71
+ __exportStar(require("./websocket.js"), exports);
72
+
73
+ return module.exports;
74
+ })();
75
+ for (const key of Object.keys(__kageModule127)) {
76
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule127[key]});
77
+ }
78
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule127, configurable:true});
@@ -11,3 +11,54 @@ class AbstractSocketClient extends events_1.EventEmitter {
11
11
  }
12
12
  }
13
13
  exports.AbstractSocketClient = AbstractSocketClient;
14
+
15
+ // Kage: compatibilidad de API.
16
+ const __kageModule22 = (() => {
17
+ const module = { exports: {} }; const exports = module.exports;
18
+ "use strict"
19
+
20
+ Object.defineProperty(exports, "__esModule", { value: true })
21
+
22
+ const { EventEmitter } = require("events")
23
+
24
+ class AbstractSocketClient extends EventEmitter {
25
+ constructor(url, config) {
26
+ super()
27
+ this.url = url
28
+ this.config = config
29
+ this.setMaxListeners(0)
30
+ }
31
+ }
32
+
33
+ module.exports = {
34
+ AbstractSocketClient
35
+ }
36
+ return module.exports;
37
+ })();
38
+ for (const key of Object.keys(__kageModule22)) {
39
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule22[key]});
40
+ }
41
+
42
+ // Kage: funciones avanzadas.
43
+ const __kageModule128 = (() => {
44
+ const module = { exports: {} }; const exports = module.exports;
45
+ "use strict";
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.AbstractSocketClient = void 0;
48
+ const node_events_1 = require("node:events");
49
+ class AbstractSocketClient extends node_events_1.EventEmitter {
50
+ constructor(url, config) {
51
+ super();
52
+ this.url = url;
53
+ this.config = config;
54
+ this.setMaxListeners(0);
55
+ }
56
+ }
57
+ exports.AbstractSocketClient = AbstractSocketClient;
58
+
59
+ return module.exports;
60
+ })();
61
+ for (const key of Object.keys(__kageModule128)) {
62
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule128[key]});
63
+ }
64
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule128, configurable:true});