@hansaka02/baileys 7.3.2 → 7.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/lib/Defaults/baileys-version.json +2 -2
  2. package/lib/Defaults/connection.js +51 -0
  3. package/lib/Defaults/constants.js +74 -0
  4. package/lib/Defaults/history.js +19 -0
  5. package/lib/Defaults/index.js +36 -142
  6. package/lib/Defaults/media.js +48 -0
  7. package/lib/Defaults/prefix.js +18 -0
  8. package/lib/Signal/Group/group-session-builder.js +10 -42
  9. package/lib/Signal/Group/group_cipher.js +9 -6
  10. package/lib/Signal/Group/index.js +39 -53
  11. package/lib/Signal/Group/keyhelper.js +8 -41
  12. package/lib/Signal/Group/sender-chain-key.js +5 -18
  13. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  14. package/lib/Signal/Group/sender-key-message.js +12 -8
  15. package/lib/Signal/Group/sender-key-record.js +7 -16
  16. package/lib/Signal/Group/sender-key-state.js +15 -61
  17. package/lib/Signal/Group/sender-message-key.js +2 -2
  18. package/lib/Signal/libsignal.js +237 -177
  19. package/lib/Signal/lid-mapping.js +128 -71
  20. package/lib/Socket/Client/types.js +2 -2
  21. package/lib/Socket/Client/websocket.js +25 -16
  22. package/lib/Socket/business.js +46 -33
  23. package/lib/Socket/chats.js +286 -170
  24. package/lib/Socket/community.js +215 -77
  25. package/lib/Socket/groups.js +77 -61
  26. package/lib/Socket/index.js +4 -4
  27. package/lib/Socket/messages-recv.js +629 -457
  28. package/lib/Socket/messages-send.js +645 -656
  29. package/lib/Socket/mex.js +61 -0
  30. package/lib/Socket/newsletter.js +166 -245
  31. package/lib/Socket/socket.js +396 -170
  32. package/lib/Store/index.js +27 -11
  33. package/lib/Store/make-cache-manager-store.js +14 -15
  34. package/lib/Store/make-in-memory-store.js +28 -24
  35. package/lib/Types/LabelAssociation.js +2 -2
  36. package/lib/Types/Message.js +6 -6
  37. package/lib/Types/MexUpdates.js +5 -5
  38. package/lib/Types/Newsletter.js +32 -25
  39. package/lib/Types/State.js +4 -4
  40. package/lib/Types/index.js +28 -12
  41. package/lib/Utils/auth-utils.js +212 -375
  42. package/lib/Utils/baileys-event-stream.js +68 -69
  43. package/lib/Utils/browser-utils.js +43 -0
  44. package/lib/Utils/business.js +63 -53
  45. package/lib/Utils/chat-utils.js +241 -106
  46. package/lib/Utils/crypto.js +25 -45
  47. package/lib/Utils/decode-wa-message.js +361 -311
  48. package/lib/Utils/event-buffer.js +97 -42
  49. package/lib/Utils/generics.js +90 -207
  50. package/lib/Utils/history.js +29 -27
  51. package/lib/Utils/index.js +28 -14
  52. package/lib/Utils/link-preview.js +24 -62
  53. package/lib/Utils/logger.js +5 -5
  54. package/lib/Utils/lt-hash.js +29 -23
  55. package/lib/Utils/make-mutex.js +26 -28
  56. package/lib/Utils/message-retry-manager.js +55 -7
  57. package/lib/Utils/messages-media.js +434 -247
  58. package/lib/Utils/messages.js +963 -917
  59. package/lib/Utils/noise-handler.js +60 -20
  60. package/lib/Utils/pre-key-manager.js +126 -0
  61. package/lib/Utils/process-message.js +216 -141
  62. package/lib/Utils/signal.js +75 -37
  63. package/lib/Utils/use-multi-file-auth-state.js +18 -22
  64. package/lib/Utils/validate-connection.js +96 -66
  65. package/lib/WABinary/constants.js +1268 -1268
  66. package/lib/WABinary/decode.js +62 -34
  67. package/lib/WABinary/encode.js +57 -36
  68. package/lib/WABinary/generic-utils.js +4 -4
  69. package/lib/WABinary/index.js +27 -11
  70. package/lib/WABinary/jid-utils.js +58 -11
  71. package/lib/WAM/constants.js +19064 -11563
  72. package/lib/WAM/encode.js +71 -14
  73. package/lib/WAM/index.js +27 -11
  74. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +20 -16
  75. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  76. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +7 -4
  77. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  78. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -2
  79. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +2 -2
  80. package/lib/WAUSync/Protocols/index.js +27 -11
  81. package/lib/WAUSync/USyncQuery.js +51 -28
  82. package/lib/WAUSync/index.js +27 -11
  83. package/lib/index.js +60 -31
  84. package/package.json +12 -17
  85. package/WAProto/AICommon/AICommon.d.ts +0 -11702
  86. package/WAProto/Adv/Adv.d.ts +0 -643
  87. package/WAProto/BotMetadata/BotMetadata.d.ts +0 -5654
  88. package/WAProto/Cert/Cert.d.ts +0 -613
  89. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +0 -476
  90. package/WAProto/CompanionReg/CompanionReg.d.ts +0 -1361
  91. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +0 -577
  92. package/WAProto/E2E/E2E.d.ts +0 -41724
  93. package/WAProto/Ephemeral/Ephemeral.d.ts +0 -114
  94. package/WAProto/HistorySync/HistorySync.d.ts +0 -51700
  95. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +0 -229
  96. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +0 -583
  97. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +0 -42897
  98. package/WAProto/MmsRetry/MmsRetry.d.ts +0 -243
  99. package/WAProto/Protocol/Protocol.d.ts +0 -270
  100. package/WAProto/Reporting/Reporting.d.ts +0 -371
  101. package/WAProto/ServerSync/ServerSync.d.ts +0 -1285
  102. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +0 -1868
  103. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +0 -767
  104. package/WAProto/StatusAttributions/StatusAttributions.d.ts +0 -1027
  105. package/WAProto/SyncAction/SyncAction.d.ts +0 -11193
  106. package/WAProto/UserPassword/UserPassword.d.ts +0 -363
  107. package/WAProto/VnameCert/VnameCert.d.ts +0 -821
  108. package/WAProto/Wa6/Wa6.d.ts +0 -2128
  109. package/WAProto/Web/Web.d.ts +0 -46383
  110. package/WAProto/index.d.ts +0 -55
  111. package/lib/Defaults/index.d.ts +0 -77
  112. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  113. package/lib/Signal/Group/group-session-builder.d.ts +0 -17
  114. package/lib/Signal/Group/group_cipher.d.ts +0 -19
  115. package/lib/Signal/Group/index.d.ts +0 -11
  116. package/lib/Signal/Group/keyhelper.d.ts +0 -16
  117. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  118. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  119. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  120. package/lib/Signal/Group/sender-key-name.d.ts +0 -19
  121. package/lib/Signal/Group/sender-key-record.d.ts +0 -32
  122. package/lib/Signal/Group/sender-key-state.d.ts +0 -44
  123. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  124. package/lib/Signal/libsignal.d.ts +0 -8
  125. package/lib/Signal/lid-mapping.d.ts +0 -28
  126. package/lib/Socket/Client/index.d.ts +0 -2
  127. package/lib/Socket/Client/types.d.ts +0 -16
  128. package/lib/Socket/Client/websocket.d.ts +0 -13
  129. package/lib/Socket/business.d.ts +0 -187
  130. package/lib/Socket/chats.d.ts +0 -97
  131. package/lib/Socket/community.d.ts +0 -129
  132. package/lib/Socket/groups.d.ts +0 -129
  133. package/lib/Socket/index.d.ts +0 -191
  134. package/lib/Socket/messages-recv.d.ts +0 -174
  135. package/lib/Socket/messages-send.d.ts +0 -165
  136. package/lib/Socket/newsletter.d.ts +0 -145
  137. package/lib/Socket/socket.d.ts +0 -45
  138. package/lib/Socket/usync.d.ts +0 -37
  139. package/lib/Socket/usync.js +0 -83
  140. package/lib/Store/index.d.ts +0 -4
  141. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  142. package/lib/Store/make-in-memory-store.d.ts +0 -123
  143. package/lib/Store/make-ordered-dictionary.d.ts +0 -12
  144. package/lib/Store/object-repository.d.ts +0 -10
  145. package/lib/Types/Auth.d.ts +0 -121
  146. package/lib/Types/Bussiness.d.ts +0 -28
  147. package/lib/Types/Call.d.ts +0 -14
  148. package/lib/Types/Chat.d.ts +0 -143
  149. package/lib/Types/Contact.d.ts +0 -23
  150. package/lib/Types/Events.d.ts +0 -226
  151. package/lib/Types/GroupMetadata.d.ts +0 -66
  152. package/lib/Types/Label.d.ts +0 -48
  153. package/lib/Types/LabelAssociation.d.ts +0 -35
  154. package/lib/Types/Message.d.ts +0 -484
  155. package/lib/Types/MexUpdates.d.ts +0 -9
  156. package/lib/Types/Newsletter.d.ts +0 -109
  157. package/lib/Types/Product.d.ts +0 -92
  158. package/lib/Types/Signal.d.ts +0 -98
  159. package/lib/Types/Socket.d.ts +0 -141
  160. package/lib/Types/State.d.ts +0 -41
  161. package/lib/Types/USync.d.ts +0 -26
  162. package/lib/Types/index.d.ts +0 -80
  163. package/lib/Utils/auth-utils.d.ts +0 -21
  164. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  165. package/lib/Utils/business.d.ts +0 -29
  166. package/lib/Utils/chat-utils.d.ts +0 -82
  167. package/lib/Utils/crypto.d.ts +0 -56
  168. package/lib/Utils/decode-wa-message.d.ts +0 -53
  169. package/lib/Utils/event-buffer.d.ts +0 -39
  170. package/lib/Utils/generics.d.ts +0 -117
  171. package/lib/Utils/history.d.ts +0 -23
  172. package/lib/Utils/index.d.ts +0 -20
  173. package/lib/Utils/link-preview.d.ts +0 -23
  174. package/lib/Utils/logger.d.ts +0 -13
  175. package/lib/Utils/lt-hash.d.ts +0 -14
  176. package/lib/Utils/make-mutex.d.ts +0 -9
  177. package/lib/Utils/message-retry-manager.d.ts +0 -88
  178. package/lib/Utils/messages-media.d.ts +0 -135
  179. package/lib/Utils/messages.d.ts +0 -105
  180. package/lib/Utils/noise-handler.d.ts +0 -20
  181. package/lib/Utils/process-message.d.ts +0 -49
  182. package/lib/Utils/signal.d.ts +0 -42
  183. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  184. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  185. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  186. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  187. package/lib/Utils/use-single-file-auth-state.js +0 -80
  188. package/lib/Utils/validate-connection.d.ts +0 -13
  189. package/lib/WABinary/constants.d.ts +0 -30
  190. package/lib/WABinary/decode.d.ts +0 -9
  191. package/lib/WABinary/encode.d.ts +0 -3
  192. package/lib/WABinary/generic-utils.d.ts +0 -28
  193. package/lib/WABinary/index.d.ts +0 -5
  194. package/lib/WABinary/jid-utils.d.ts +0 -58
  195. package/lib/WABinary/types.d.ts +0 -22
  196. package/lib/WAM/BinaryInfo.d.ts +0 -16
  197. package/lib/WAM/constants.d.ts +0 -47
  198. package/lib/WAM/encode.d.ts +0 -3
  199. package/lib/WAM/index.d.ts +0 -3
  200. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +0 -28
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  202. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -26
  203. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -14
  204. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +0 -10
  205. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -14
  206. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  207. package/lib/WAUSync/USyncQuery.d.ts +0 -31
  208. package/lib/WAUSync/USyncUser.d.ts +0 -12
  209. package/lib/WAUSync/index.d.ts +0 -3
  210. package/lib/index.d.ts +0 -13
@@ -1,41 +1,19 @@
1
1
  "use strict"
2
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v })
17
- }) : function(o, v) {
18
- o["default"] = v
19
- })
20
-
21
- var __importStar = (this && this.__importStar) || function (mod) {
22
- if (mod && mod.__esModule) return mod
23
- var result = {}
24
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
25
- __setModuleDefault(result, mod)
26
- return result
27
- }
28
-
29
3
  Object.defineProperty(exports, "__esModule", { value: true })
30
4
 
31
- const messages_1 = require("./messages")
32
- const messages_media_1 = require("./messages-media")
5
+ const { unfurl } = require('unfurl.js')
6
+ const { prepareWAMessageMedia } = require("./messages")
7
+ const {
8
+ getHttpStream,
9
+ extractImageThumb
10
+ } = require("./messages-media")
33
11
  const THUMBNAIL_WIDTH_PX = 192
34
12
 
35
13
  /** Fetches an image and generates a thumbnail for it */
36
14
  const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
37
- const stream = await messages_media_1.getHttpStream(url, fetchOpts)
38
- const result = await messages_media_1.extractImageThumb(stream, thumbnailWidth)
15
+ const stream = await getHttpStream(url, fetchOpts)
16
+ const result = await extractImageThumb(stream, thumbnailWidth)
39
17
  return result
40
18
  }
41
19
 
@@ -45,38 +23,24 @@ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) =>
45
23
  * @param text first matched URL in text
46
24
  * @returns the URL info required to generate link preview
47
25
  */
48
- const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3000 }}) => {
26
+ const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3000 } }) => {
49
27
  try {
50
- const retries = 0
51
- const maxRetry = 5
52
- const { getLinkPreview } = await Promise.resolve().then(() => __importStar(require('link-preview-js')))
53
28
  let previewLink = text
29
+
54
30
  if (!text.startsWith('https://') && !text.startsWith('http://')) {
55
31
  previewLink = 'https://' + previewLink
56
32
  }
57
- const info = await getLinkPreview(previewLink, {
33
+
34
+ const { open_graph: info } = await unfurl(previewLink, {
58
35
  ...opts.fetchOpts,
59
- followRedirects: 'follow',
60
- handleRedirects: (baseURL, forwardedURL) => {
61
- const urlObj = new URL(baseURL)
62
- const forwardedURLObj = new URL(forwardedURL)
63
- if (retries >= maxRetry) {
64
- return false
65
- }
66
- if (forwardedURLObj.hostname === urlObj.hostname
67
- || forwardedURLObj.hostname === 'www.' + urlObj.hostname
68
- || 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
69
- retries + 1
70
- return true
71
- }
72
- else {
73
- return false
74
- }
75
- },
76
- headers: opts.fetchOpts
77
- })
36
+ oembed: false,
37
+ compress: true,
38
+ size: 0,
39
+ follow: 50
40
+ })
41
+
78
42
  if (info && 'title' in info && info.title) {
79
- const [image] = info.images
43
+ const image = info.images?.[0]?.url
80
44
  const urlInfo = {
81
45
  'canonical-url': info.url,
82
46
  'matched-text': text,
@@ -84,22 +48,20 @@ const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fet
84
48
  description: info.description,
85
49
  originalThumbnailUrl: image
86
50
  }
51
+
87
52
  if (opts.uploadImage) {
88
- const { imageMessage } = await messages_1.prepareWAMessageMedia({ image: { url: image } }, {
53
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
89
54
  upload: opts.uploadImage,
90
55
  mediaTypeOverride: 'thumbnail-link',
91
56
  options: opts.fetchOpts
92
57
  })
93
- urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
94
- ? Buffer.from(imageMessage.jpegThumbnail)
95
- : undefined
58
+
59
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
96
60
  urlInfo.highQualityThumbnail = imageMessage || undefined
97
61
  }
98
62
  else {
99
63
  try {
100
- urlInfo.jpegThumbnail = image
101
- ? (await getCompressedJpegThumbnail(image, opts)).buffer
102
- : undefined
64
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
103
65
  }
104
66
  catch (error) {
105
67
  opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
@@ -1,7 +1,7 @@
1
1
  "use strict"
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod }
4
- }
2
+
5
3
  Object.defineProperty(exports, "__esModule", { value: true })
6
- const pino_1 = __importDefault(require("pino"))
7
- exports.default = pino_1.default({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
4
+
5
+ const pino = require("pino")
6
+
7
+ exports.default = pino({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, "__esModule", { value: true })
4
4
 
5
- const crypto_1 = require("./crypto")
5
+ const { hkdf } = require("./crypto")
6
6
 
7
7
  /**
8
8
  * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
@@ -10,48 +10,54 @@ const crypto_1 = require("./crypto")
10
10
  * if the same series of mutations was made sequentially.
11
11
  */
12
12
  const o = 128
13
- class d {
13
+
14
+ class LTHash {
14
15
  constructor(e) {
15
16
  this.salt = e
16
17
  }
17
- add(e, t) {
18
- var r = this
18
+
19
+ async add(e, t) {
19
20
  for (const item of t) {
20
- e = r._addSingle(e, item)
21
+ e = await this._addSingle(e, item)
21
22
  }
22
23
  return e
23
24
  }
24
- subtract(e, t) {
25
- var r = this
25
+
26
+ async subtract(e, t) {
26
27
  for (const item of t) {
27
- e = r._subtractSingle(e, item)
28
+ e = await this._subtractSingle(e, item)
28
29
  }
29
30
  return e
30
31
  }
31
- subtractThenAdd(e, t, r) {
32
- var n = this
33
- return n.add(n.subtract(e, r), t)
32
+
33
+ async subtractThenAdd(e, addList, subtractList) {
34
+ const subtracted = await this.subtract(e, subtractList)
35
+ return this.add(subtracted, addList)
34
36
  }
37
+
35
38
  async _addSingle(e, t) {
36
- var r = this
37
- const n = new Uint8Array(await crypto_1.hkdf(Buffer.from(t), o, { info: r.salt })).buffer
38
- return r.performPointwiseWithOverflow(await e, n, ((e, t) => e + t))
39
+ const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer
40
+ return this.performPointwiseWithOverflow(e, derived, (a, b) => a + b)
39
41
  }
42
+
40
43
  async _subtractSingle(e, t) {
41
- var r = this
42
- const n = new Uint8Array(await crypto_1.hkdf(Buffer.from(t), o, { info: r.salt })).buffer
43
- return r.performPointwiseWithOverflow(await e, n, ((e, t) => e - t))
44
+ const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer
45
+ return this.performPointwiseWithOverflow(e, derived, (a, b) => a - b)
44
46
  }
45
- performPointwiseWithOverflow(e, t, r) {
46
- const n = new DataView(e), i = new DataView(t), a = new ArrayBuffer(n.byteLength), s = new DataView(a)
47
- for (let e = 0; e < n.byteLength; e += 2) {
48
- s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0)
47
+
48
+ performPointwiseWithOverflow(e, t, op) {
49
+ const n = new DataView(e)
50
+ const i = new DataView(t)
51
+ const out = new ArrayBuffer(n.byteLength)
52
+ const s = new DataView(out)
53
+ for (let offset = 0; offset < n.byteLength; offset += 2) {
54
+ s.setUint16(offset, op(n.getUint16(offset, true), i.getUint16(offset, true)), true)
49
55
  }
50
- return a
56
+ return out
51
57
  }
52
58
  }
53
59
 
54
- const LT_HASH_ANTI_TAMPERING = new d('WhatsApp Patch Integrity')
60
+ const LT_HASH_ANTI_TAMPERING = new LTHash('WhatsApp Patch Integrity')
55
61
 
56
62
  module.exports = {
57
63
  LT_HASH_ANTI_TAMPERING
@@ -2,43 +2,41 @@
2
2
 
3
3
  Object.defineProperty(exports, "__esModule", { value: true })
4
4
 
5
+ const { Mutex: AsyncMutex } = require("async-mutex")
6
+
5
7
  const makeMutex = () => {
6
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
- let task = Promise.resolve()
8
- let taskTimeout
8
+ const mutex = new AsyncMutex()
9
9
  return {
10
10
  mutex(code) {
11
- task = (async () => {
12
- // wait for the previous task to complete
13
- // if there is an error, we swallow so as to not block the queue
14
- try {
15
- await task
16
- }
17
- catch (_a) { }
18
- try {
19
- // execute the current task
20
- const result = await code()
21
- return result
22
- }
23
- finally {
24
- clearTimeout(taskTimeout)
25
- }
26
- })()
27
- // we replace the existing task, appending the new piece of execution to it
28
- // so the next task will have to wait for this one to finish
29
- return task
30
- },
11
+ return mutex.runExclusive(code)
12
+ }
31
13
  }
32
14
  }
33
15
 
34
16
  const makeKeyedMutex = () => {
35
- const map = {}
17
+ const map = new Map()
36
18
  return {
37
- mutex(key, task) {
38
- if (!map[key]) {
39
- map[key] = makeMutex()
19
+ async mutex(key, task) {
20
+ let entry = map.get(key)
21
+
22
+ if (!entry) {
23
+ entry = { mutex: new AsyncMutex(), refCount: 0 }
24
+ map.set(key, entry)
25
+ }
26
+
27
+ entry.refCount++
28
+
29
+ try {
30
+ return await entry.mutex.runExclusive(task)
31
+ }
32
+ finally {
33
+ entry.refCount--
34
+
35
+ // only delete it if this is still the current entry
36
+ if (entry.refCount === 0 && map.get(key) === entry) {
37
+ map.delete(key)
38
+ }
40
39
  }
41
- return map[key].mutex(task)
42
40
  }
43
41
  }
44
42
  }
@@ -2,11 +2,13 @@
2
2
 
3
3
  Object.defineProperty(exports, "__esModule", { value: true })
4
4
 
5
- const LRUCache_1 = require("lru-cache")
5
+ const { LRUCache } = require("lru-cache")
6
6
 
7
7
  /** Number of sent messages to cache in memory for handling retry receipts */
8
8
  const RECENT_MESSAGES_SIZE = 512
9
9
 
10
+ const MESSAGE_KEY_SEPARATOR = '\u0000'
11
+
10
12
  /** Timeout for session recreation - 1 hour */
11
13
  const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000 // 1 hour in milliseconds
12
14
 
@@ -15,14 +17,24 @@ const PHONE_REQUEST_DELAY = 3000
15
17
  class MessageRetryManager {
16
18
  constructor(logger, maxMsgRetryCount) {
17
19
  this.logger = logger
18
- this.recentMessagesMap = new LRUCache_1.LRUCache({
19
- max: RECENT_MESSAGES_SIZE
20
+ this.recentMessagesMap = new LRUCache({
21
+ max: RECENT_MESSAGES_SIZE,
22
+ ttl: 5 * 60 * 1000,
23
+ ttlAutopurge: true,
24
+ dispose: (_value, key) => {
25
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
26
+ if (separatorIndex > -1) {
27
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length)
28
+ this.messageKeyIndex.delete(messageId)
29
+ }
30
+ }
20
31
  })
21
- this.sessionRecreateHistory = new LRUCache_1.LRUCache({
32
+ this.messageKeyIndex = new Map()
33
+ this.sessionRecreateHistory = new LRUCache({
22
34
  ttl: RECREATE_SESSION_TIMEOUT * 2,
23
35
  ttlAutopurge: true
24
36
  })
25
- this.retryCounters = new LRUCache_1.LRUCache({
37
+ this.retryCounters = new LRUCache({
26
38
  ttl: 15 * 60 * 1000,
27
39
  ttlAutopurge: true,
28
40
  updateAgeOnGet: true
@@ -39,27 +51,33 @@ class MessageRetryManager {
39
51
  }
40
52
  this.maxMsgRetryCount = maxMsgRetryCount
41
53
  }
54
+
42
55
  /**
43
56
  * Add a recent message to the cache for retry handling
44
57
  */
45
58
  addRecentMessage(to, id, message) {
46
59
  const key = { to, id }
47
60
  const keyStr = this.keyToString(key)
61
+
48
62
  // Add new message
49
63
  this.recentMessagesMap.set(keyStr, {
50
64
  message,
51
65
  timestamp: Date.now()
52
66
  })
67
+ this.messageKeyIndex.set(id, keyStr)
53
68
  this.logger.debug(`Added message to retry cache: ${to}/${id}`)
54
69
  }
70
+
55
71
  /**
56
72
  * Get a recent message from the cache
57
73
  */
58
74
  getRecentMessage(to, id) {
59
75
  const key = { to, id }
60
76
  const keyStr = this.keyToString(key)
77
+
61
78
  return this.recentMessagesMap.get(keyStr)
62
79
  }
80
+
63
81
  /**
64
82
  * Check if a session should be recreated based on retry count and history
65
83
  */
@@ -73,16 +91,20 @@ class MessageRetryManager {
73
91
  recreate: true
74
92
  }
75
93
  }
94
+
76
95
  // Only consider recreation if retry count > 1
77
96
  if (retryCount < 2) {
78
97
  return { reason: '', recreate: false }
79
98
  }
99
+
80
100
  const now = Date.now()
81
101
  const prevTime = this.sessionRecreateHistory.get(jid)
102
+
82
103
  // If no previous recreation or it's been more than an hour
83
104
  if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
84
105
  this.sessionRecreateHistory.set(jid, now)
85
106
  this.statistics.sessionRecreations++
107
+
86
108
  return {
87
109
  reason: 'retry count > 1 and over an hour since last recreation',
88
110
  recreate: true
@@ -90,26 +112,31 @@ class MessageRetryManager {
90
112
  }
91
113
  return { reason: '', recreate: false }
92
114
  }
115
+
93
116
  /**
94
117
  * Increment retry counter for a message
95
118
  */
96
119
  incrementRetryCount(messageId) {
97
120
  this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1)
98
121
  this.statistics.totalRetries++
122
+
99
123
  return this.retryCounters.get(messageId)
100
124
  }
125
+
101
126
  /**
102
127
  * Get retry count for a message
103
128
  */
104
129
  getRetryCount(messageId) {
105
130
  return this.retryCounters.get(messageId) || 0
106
131
  }
132
+
107
133
  /**
108
134
  * Check if message has exceeded maximum retry attempts
109
135
  */
110
136
  hasExceededMaxRetries(messageId) {
111
137
  return this.getRetryCount(messageId) >= this.maxMsgRetryCount
112
138
  }
139
+
113
140
  /**
114
141
  * Mark retry as successful
115
142
  */
@@ -118,14 +145,19 @@ class MessageRetryManager {
118
145
  // Clean up retry counter for successful message
119
146
  this.retryCounters.delete(messageId)
120
147
  this.cancelPendingPhoneRequest(messageId)
148
+ this.removeRecentMessage(messageId)
121
149
  }
150
+
122
151
  /**
123
152
  * Mark retry as failed
124
153
  */
125
154
  markRetryFailed(messageId) {
126
155
  this.statistics.failedRetries++
127
156
  this.retryCounters.delete(messageId)
157
+ this.cancelPendingPhoneRequest(messageId)
158
+ this.removeRecentMessage(messageId)
128
159
  }
160
+
129
161
  /**
130
162
  * Schedule a phone request with delay
131
163
  */
@@ -134,24 +166,40 @@ class MessageRetryManager {
134
166
  this.cancelPendingPhoneRequest(messageId)
135
167
  this.pendingPhoneRequests[messageId] = setTimeout(() => {
136
168
  delete this.pendingPhoneRequests[messageId]
169
+
137
170
  this.statistics.phoneRequests++
171
+
138
172
  callback()
139
173
  }, delay)
140
- this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`)
174
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
141
175
  }
176
+
142
177
  /**
143
178
  * Cancel pending phone request
144
179
  */
145
180
  cancelPendingPhoneRequest(messageId) {
146
181
  const timeout = this.pendingPhoneRequests[messageId]
182
+
147
183
  if (timeout) {
148
184
  clearTimeout(timeout)
185
+
149
186
  delete this.pendingPhoneRequests[messageId]
187
+
150
188
  this.logger.debug(`Cancelled pending phone request for message ${messageId}`)
151
189
  }
152
190
  }
191
+
153
192
  keyToString(key) {
154
- return `${key.to}:${key.id}`
193
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`
194
+ }
195
+
196
+ removeRecentMessage(messageId) {
197
+ const keyStr = this.messageKeyIndex.get(messageId)
198
+
199
+ if (!keyStr) return
200
+
201
+ this.recentMessagesMap.delete(keyStr)
202
+ this.messageKeyIndex.delete(messageId)
155
203
  }
156
204
  }
157
205