@vanzxy/baileys 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/NOTICE.md +111 -0
  2. package/README.md +830 -0
  3. package/WAProto/index.d.ts +9 -0
  4. package/WAProto/index.js +142036 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.d.ts +152 -0
  7. package/lib/Defaults/index.js +179 -0
  8. package/lib/Framework/Bot.js +209 -0
  9. package/lib/Framework/Context.js +90 -0
  10. package/lib/Framework/MediaManager.js +152 -0
  11. package/lib/Framework/SessionManager.js +34 -0
  12. package/lib/Framework/StatsManager.js +120 -0
  13. package/lib/Framework/Store/SQLiteStore.js +74 -0
  14. package/lib/Framework/index.js +11 -0
  15. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  16. package/lib/Signal/Group/ciphertext-message.js +12 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  20. package/lib/Signal/Group/group_cipher.js +82 -0
  21. package/lib/Signal/Group/index.d.ts +11 -0
  22. package/lib/Signal/Group/index.js +12 -0
  23. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  24. package/lib/Signal/Group/keyhelper.js +18 -0
  25. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  26. package/lib/Signal/Group/sender-chain-key.js +26 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  29. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-message.js +66 -0
  31. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  32. package/lib/Signal/Group/sender-key-name.js +48 -0
  33. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  34. package/lib/Signal/Group/sender-key-record.js +41 -0
  35. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  36. package/lib/Signal/Group/sender-key-state.js +84 -0
  37. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  38. package/lib/Signal/Group/sender-message-key.js +26 -0
  39. package/lib/Signal/libsignal.d.ts +54 -0
  40. package/lib/Signal/libsignal.js +431 -0
  41. package/lib/Signal/lid-mapping.d.ts +20 -0
  42. package/lib/Signal/lid-mapping.js +277 -0
  43. package/lib/Socket/Client/index.d.ts +2 -0
  44. package/lib/Socket/Client/index.js +3 -0
  45. package/lib/Socket/Client/types.d.ts +5 -0
  46. package/lib/Socket/Client/types.js +11 -0
  47. package/lib/Socket/Client/websocket.d.ts +12 -0
  48. package/lib/Socket/Client/websocket.js +54 -0
  49. package/lib/Socket/business.d.ts +395 -0
  50. package/lib/Socket/business.js +380 -0
  51. package/lib/Socket/chats.d.ts +136 -0
  52. package/lib/Socket/chats.js +1328 -0
  53. package/lib/Socket/communities.d.ts +561 -0
  54. package/lib/Socket/communities.js +434 -0
  55. package/lib/Socket/dugong.d.ts +117 -0
  56. package/lib/Socket/dugong.js +799 -0
  57. package/lib/Socket/groups.d.ts +285 -0
  58. package/lib/Socket/groups.js +355 -0
  59. package/lib/Socket/index.d.ts +531 -0
  60. package/lib/Socket/index.js +34 -0
  61. package/lib/Socket/messages-recv.d.ts +333 -0
  62. package/lib/Socket/messages-recv.js +1782 -0
  63. package/lib/Socket/messages-send.d.ts +329 -0
  64. package/lib/Socket/messages-send.js +1383 -0
  65. package/lib/Socket/mex.d.ts +1 -0
  66. package/lib/Socket/mex.js +42 -0
  67. package/lib/Socket/newsletter.d.ts +281 -0
  68. package/lib/Socket/newsletter.js +321 -0
  69. package/lib/Socket/socket.d.ts +60 -0
  70. package/lib/Socket/socket.js +1001 -0
  71. package/lib/Socket/username.js +153 -0
  72. package/lib/Store/index.d.ts +3 -0
  73. package/lib/Store/index.js +4 -0
  74. package/lib/Store/make-in-memory-store.d.ts +62 -0
  75. package/lib/Store/make-in-memory-store.js +429 -0
  76. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  77. package/lib/Store/make-ordered-dictionary.js +79 -0
  78. package/lib/Store/object-repository.d.ts +10 -0
  79. package/lib/Store/object-repository.js +24 -0
  80. package/lib/Types/Auth.d.ts +117 -0
  81. package/lib/Types/Auth.js +2 -0
  82. package/lib/Types/Bussines.d.ts +25 -0
  83. package/lib/Types/Bussines.js +2 -0
  84. package/lib/Types/Call.d.ts +15 -0
  85. package/lib/Types/Call.js +2 -0
  86. package/lib/Types/Chat.d.ts +124 -0
  87. package/lib/Types/Chat.js +8 -0
  88. package/lib/Types/Contact.d.ts +26 -0
  89. package/lib/Types/Contact.js +2 -0
  90. package/lib/Types/Events.d.ts +256 -0
  91. package/lib/Types/Events.js +2 -0
  92. package/lib/Types/GroupMetadata.d.ts +71 -0
  93. package/lib/Types/GroupMetadata.js +2 -0
  94. package/lib/Types/Label.d.ts +2 -0
  95. package/lib/Types/Label.js +25 -0
  96. package/lib/Types/LabelAssociation.d.ts +2 -0
  97. package/lib/Types/LabelAssociation.js +7 -0
  98. package/lib/Types/Message.d.ts +11 -0
  99. package/lib/Types/Message.js +18 -0
  100. package/lib/Types/Mex.d.ts +2 -0
  101. package/lib/Types/Mex.js +39 -0
  102. package/lib/Types/Product.d.ts +79 -0
  103. package/lib/Types/Product.js +2 -0
  104. package/lib/Types/RichType.d.ts +2 -0
  105. package/lib/Types/RichType.js +23 -0
  106. package/lib/Types/Signal.d.ts +87 -0
  107. package/lib/Types/Signal.js +2 -0
  108. package/lib/Types/Socket.d.ts +136 -0
  109. package/lib/Types/Socket.js +2 -0
  110. package/lib/Types/State.d.ts +5 -0
  111. package/lib/Types/State.js +56 -0
  112. package/lib/Types/USync.d.ts +26 -0
  113. package/lib/Types/USync.js +2 -0
  114. package/lib/Types/index.d.ts +66 -0
  115. package/lib/Types/index.js +26 -0
  116. package/lib/Utils/A2UI.js +277 -0
  117. package/lib/Utils/MessageBuilder.js +4405 -0
  118. package/lib/Utils/MessageBuilder_d.ts +411 -0
  119. package/lib/Utils/PersistentStore.js +592 -0
  120. package/lib/Utils/PersistentStore_d.ts +60 -0
  121. package/lib/Utils/anti-delete.d.ts +74 -0
  122. package/lib/Utils/anti-delete.js +222 -0
  123. package/lib/Utils/auth-utils.d.ts +57 -0
  124. package/lib/Utils/auth-utils.js +307 -0
  125. package/lib/Utils/auto-reply.d.ts +47 -0
  126. package/lib/Utils/auto-reply.js +158 -0
  127. package/lib/Utils/baileys-event-stream.d.ts +8 -0
  128. package/lib/Utils/baileys-event-stream.js +62 -0
  129. package/lib/Utils/browser-utils.d.ts +8 -0
  130. package/lib/Utils/browser-utils.js +28 -0
  131. package/lib/Utils/business.d.ts +49 -0
  132. package/lib/Utils/business.js +240 -0
  133. package/lib/Utils/button-helper-utils.js +314 -0
  134. package/lib/Utils/button-sender.js +824 -0
  135. package/lib/Utils/chat-control.d.ts +159 -0
  136. package/lib/Utils/chat-control.js +232 -0
  137. package/lib/Utils/chat-history-helpers.d.ts +21 -0
  138. package/lib/Utils/chat-history-helpers.js +71 -0
  139. package/lib/Utils/chat-utils.d.ts +407 -0
  140. package/lib/Utils/chat-utils.js +886 -0
  141. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  142. package/lib/Utils/companion-reg-client-utils.js +40 -0
  143. package/lib/Utils/crypto.d.ts +41 -0
  144. package/lib/Utils/crypto.js +148 -0
  145. package/lib/Utils/decode-wa-message.d.ts +83 -0
  146. package/lib/Utils/decode-wa-message.js +317 -0
  147. package/lib/Utils/event-buffer.d.ts +12 -0
  148. package/lib/Utils/event-buffer.js +636 -0
  149. package/lib/Utils/generics.d.ts +69 -0
  150. package/lib/Utils/generics.js +439 -0
  151. package/lib/Utils/history.d.ts +90 -0
  152. package/lib/Utils/history.js +147 -0
  153. package/lib/Utils/identity-change-handler.d.ts +13 -0
  154. package/lib/Utils/identity-change-handler.js +50 -0
  155. package/lib/Utils/index.d.ts +39 -0
  156. package/lib/Utils/index.js +46 -0
  157. package/lib/Utils/link-preview.d.ts +12 -0
  158. package/lib/Utils/link-preview.js +85 -0
  159. package/lib/Utils/logger.d.ts +2 -0
  160. package/lib/Utils/logger.js +3 -0
  161. package/lib/Utils/lt-hash.d.ts +12 -0
  162. package/lib/Utils/lt-hash.js +27 -0
  163. package/lib/Utils/make-mutex.d.ts +6 -0
  164. package/lib/Utils/make-mutex.js +33 -0
  165. package/lib/Utils/media-messages.d.ts +18 -0
  166. package/lib/Utils/media-messages.js +71 -0
  167. package/lib/Utils/media-set.d.ts +13 -0
  168. package/lib/Utils/media-set.js +172 -0
  169. package/lib/Utils/message-kind.js +139 -0
  170. package/lib/Utils/message-retry-manager.d.ts +79 -0
  171. package/lib/Utils/message-retry-manager.js +265 -0
  172. package/lib/Utils/message-search.d.ts +44 -0
  173. package/lib/Utils/message-search.js +189 -0
  174. package/lib/Utils/messages-media.d.ts +135 -0
  175. package/lib/Utils/messages-media.js +869 -0
  176. package/lib/Utils/messages.d.ts +44 -0
  177. package/lib/Utils/messages.js +2155 -0
  178. package/lib/Utils/noise-handler.d.ts +20 -0
  179. package/lib/Utils/noise-handler.js +201 -0
  180. package/lib/Utils/offline-node-processor.d.ts +9 -0
  181. package/lib/Utils/offline-node-processor.js +40 -0
  182. package/lib/Utils/past-participants.d.ts +14 -0
  183. package/lib/Utils/past-participants.js +40 -0
  184. package/lib/Utils/pre-key-manager.d.ts +25 -0
  185. package/lib/Utils/pre-key-manager.js +106 -0
  186. package/lib/Utils/process-message.d.ts +82 -0
  187. package/lib/Utils/process-message.js +809 -0
  188. package/lib/Utils/reporting-utils.d.ts +12 -0
  189. package/lib/Utils/reporting-utils.js +258 -0
  190. package/lib/Utils/rich-message-utils.d.ts +48 -0
  191. package/lib/Utils/rich-message-utils.js +445 -0
  192. package/lib/Utils/scheduling.d.ts +42 -0
  193. package/lib/Utils/scheduling.js +140 -0
  194. package/lib/Utils/signal.d.ts +82 -0
  195. package/lib/Utils/signal.js +201 -0
  196. package/lib/Utils/stanza-ack.d.ts +16 -0
  197. package/lib/Utils/stanza-ack.js +38 -0
  198. package/lib/Utils/status.d.ts +50 -0
  199. package/lib/Utils/status.js +108 -0
  200. package/lib/Utils/stickerpack.d.ts +51 -0
  201. package/lib/Utils/stickerpack.js +275 -0
  202. package/lib/Utils/sync-action-utils.d.ts +2 -0
  203. package/lib/Utils/sync-action-utils.js +49 -0
  204. package/lib/Utils/tc-token-utils.d.ts +29 -0
  205. package/lib/Utils/tc-token-utils.js +163 -0
  206. package/lib/Utils/templates.d.ts +76 -0
  207. package/lib/Utils/templates.js +151 -0
  208. package/lib/Utils/use-cache-manager-auth-state.d.ts +13 -0
  209. package/lib/Utils/use-cache-manager-auth-state.js +82 -0
  210. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  211. package/lib/Utils/use-multi-file-auth-state.js +167 -0
  212. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  213. package/lib/Utils/use-single-file-auth-state.js +114 -0
  214. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  215. package/lib/Utils/use-sqlite-auth-state.js +170 -0
  216. package/lib/Utils/validate-connection.d.ts +42 -0
  217. package/lib/Utils/validate-connection.js +199 -0
  218. package/lib/Utils/vcard.d.ts +58 -0
  219. package/lib/Utils/vcard.js +105 -0
  220. package/lib/VoIP/audio-feeder.d.ts +15 -0
  221. package/lib/VoIP/audio-feeder.js +132 -0
  222. package/lib/VoIP/index.js +277 -0
  223. package/lib/VoIP/relay-transport.d.ts +43 -0
  224. package/lib/VoIP/relay-transport.js +559 -0
  225. package/lib/VoIP/signaling.js +624 -0
  226. package/lib/VoIP/types.d.ts +69 -0
  227. package/lib/VoIP/types.js +17 -0
  228. package/lib/VoIP/wasm-engine.d.ts +103 -0
  229. package/lib/VoIP/wasm-engine.js +1214 -0
  230. package/lib/VoIP/worker-bootstrap.js +1042 -0
  231. package/lib/WABinary/constants.d.ts +61 -0
  232. package/lib/WABinary/constants.js +1467 -0
  233. package/lib/WABinary/decode.d.ts +9 -0
  234. package/lib/WABinary/decode.js +262 -0
  235. package/lib/WABinary/encode.d.ts +2 -0
  236. package/lib/WABinary/encode.js +220 -0
  237. package/lib/WABinary/generic-utils.d.ts +74 -0
  238. package/lib/WABinary/generic-utils.js +277 -0
  239. package/lib/WABinary/index.d.ts +5 -0
  240. package/lib/WABinary/index.js +6 -0
  241. package/lib/WABinary/jid-utils.d.ts +28 -0
  242. package/lib/WABinary/jid-utils.js +96 -0
  243. package/lib/WABinary/types.d.ts +19 -0
  244. package/lib/WABinary/types.js +2 -0
  245. package/lib/WAM/BinaryInfo.d.ts +7 -0
  246. package/lib/WAM/BinaryInfo.js +10 -0
  247. package/lib/WAM/constants.d.ts +34926 -0
  248. package/lib/WAM/constants.js +22853 -0
  249. package/lib/WAM/encode.d.ts +1 -0
  250. package/lib/WAM/encode.js +150 -0
  251. package/lib/WAM/index.d.ts +3 -0
  252. package/lib/WAM/index.js +4 -0
  253. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  254. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  255. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  256. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +63 -0
  257. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  258. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  259. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  260. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  261. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  262. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  263. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  264. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  265. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  266. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  267. package/lib/WAUSync/Protocols/index.d.ts +7 -0
  268. package/lib/WAUSync/Protocols/index.js +8 -0
  269. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  270. package/lib/WAUSync/USyncQuery.js +122 -0
  271. package/lib/WAUSync/USyncUser.d.ts +16 -0
  272. package/lib/WAUSync/USyncUser.js +31 -0
  273. package/lib/WAUSync/index.d.ts +3 -0
  274. package/lib/WAUSync/index.js +4 -0
  275. package/lib/assets/wasm/loader.js +5 -0
  276. package/lib/assets/wasm/whatsapp.wasm +0 -0
  277. package/lib/assets/wasm/worker-modules.js +273 -0
  278. package/lib/index.d.ts +12 -0
  279. package/lib/index.js +20 -0
  280. package/package.json +175 -0
  281. package/postinstall-banner.js +56 -0
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Vanz@Add --- ported from Bail-master addons/media-set.ts.
3
+ * Profile-picture setters (full/panoramic variants) and group-status /
4
+ * member-label senders. Depends on this fork's own media-messages.js
5
+ * (also ported this batch) and its existing generateWAMessageContent /
6
+ * generateWAMessageFromContent / unixTimestampSeconds / S_WHATSAPP_NET.
7
+ *
8
+ * NOTE ON DUPLICATE-LOOKING SETTERS: `updateProfilePictureFull` and
9
+ * `updateProfilePictureFull2` are genuinely different, not duplicates —
10
+ * the first sends the `img` buffer from `generateProfilePictureFP`
11
+ * (scaled-to-fit 720x720 main image), the second sends the `preview`
12
+ * buffer from `generatePP` (normalized preview). Both are kept.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ // Vanz@Fix: unixTimestampSeconds is not re-exported by messages.js (it only imports
16
+ // it internally from generics.js for its own use) — pull it from generics.js directly.
17
+ import { generateWAMessageContent, generateWAMessageFromContent } from './messages.js';
18
+ import { unixTimestampSeconds } from './generics.js';
19
+ import { S_WHATSAPP_NET } from '../WABinary/index.js';
20
+ import { generatePP, generateProfilePictureFP } from './media-messages.js';
21
+ /** Update the profile picture for yourself or a group — sends the main (scaled-to-fit) image. */
22
+ export const updateProfilePictureFull = async (jid, content, sock) => {
23
+ const { query } = sock;
24
+ const { img } = await generateProfilePictureFP(content);
25
+ const media = await query({
26
+ tag: 'iq',
27
+ attrs: {
28
+ target: jid,
29
+ to: S_WHATSAPP_NET,
30
+ type: 'set',
31
+ xmlns: 'w:profile:picture'
32
+ },
33
+ content: [
34
+ {
35
+ tag: 'picture',
36
+ attrs: { type: 'image' },
37
+ content: img
38
+ }
39
+ ]
40
+ });
41
+ return media;
42
+ };
43
+ /** Update the profile picture for yourself or a group — sends the normalized preview image. */
44
+ export const updateProfilePictureFull2 = async (jid, content, sock) => {
45
+ const { query } = sock;
46
+ const { preview } = await generatePP(content);
47
+ const media = await query({
48
+ tag: 'iq',
49
+ attrs: {
50
+ target: jid,
51
+ to: S_WHATSAPP_NET,
52
+ type: 'set',
53
+ xmlns: 'w:profile:picture'
54
+ },
55
+ content: [
56
+ {
57
+ tag: 'picture',
58
+ attrs: { type: 'image' },
59
+ content: preview
60
+ }
61
+ ]
62
+ });
63
+ return media;
64
+ };
65
+ /** Send a group status (status update visible only within a group's members). */
66
+ export const groupStatus = async (jid, content, sock) => {
67
+ const { backgroundColor, ...rest } = content;
68
+ const inside = await generateWAMessageContent(rest, {
69
+ upload: sock.waUploadToServer,
70
+ backgroundColor
71
+ });
72
+ const messageSecret = randomBytes(32);
73
+ const m = generateWAMessageFromContent(jid, {
74
+ messageContextInfo: { messageSecret },
75
+ groupStatusMessageV2: {
76
+ message: {
77
+ ...inside,
78
+ messageContextInfo: { messageSecret }
79
+ }
80
+ }
81
+ }, {});
82
+ await sock.relayMessage(jid, m.message, { messageId: m.key.id });
83
+ return m;
84
+ };
85
+ /** Send the same group status to multiple groups at once. */
86
+ export const groupStatusV2 = async (jids, content, sock) => {
87
+ const { backgroundColor, ...rest } = content;
88
+ const inside = await generateWAMessageContent(rest, {
89
+ upload: sock.waUploadToServer,
90
+ backgroundColor
91
+ });
92
+ const messageSecret = randomBytes(32);
93
+ const results = [];
94
+ for (const id of jids) {
95
+ const m = generateWAMessageFromContent(id, {
96
+ messageContextInfo: { messageSecret },
97
+ groupStatusMessageV2: {
98
+ message: {
99
+ ...inside,
100
+ messageContextInfo: { messageSecret }
101
+ }
102
+ }
103
+ }, {});
104
+ await sock.relayMessage(id, m.message, { messageId: m.key.id });
105
+ results.push(m);
106
+ }
107
+ return results;
108
+ };
109
+ /**
110
+ * Set/update a member's label in a group (awaits the relay and returns the result).
111
+ * Label is truncated to 30 characters (WA's limit).
112
+ */
113
+ export const groupSetMemberLabel = async (jid, memberLabel, sock) => {
114
+ const result = await sock.relayMessage(jid, {
115
+ protocolMessage: {
116
+ type: 30,
117
+ memberLabel: {
118
+ label: memberLabel.slice(0, 30),
119
+ labelTimestamp: unixTimestampSeconds() || Date.now()
120
+ }
121
+ }
122
+ }, {
123
+ additionalNodes: [
124
+ {
125
+ tag: 'meta',
126
+ attrs: {
127
+ tag_reason: 'user_update',
128
+ appdata: 'member_tag'
129
+ },
130
+ content: undefined
131
+ }
132
+ ]
133
+ });
134
+ return result;
135
+ };
136
+ /**
137
+ * Set/update a member's label in a group — fire-and-forget variant (errors
138
+ * are swallowed, matching the source's behavior; prefer
139
+ * `groupSetMemberLabel` if you need to await/observe failures).
140
+ */
141
+ export const groupLabel = async (jid, text, sock) => {
142
+ try {
143
+ void sock.relayMessage(jid, {
144
+ protocolMessage: {
145
+ type: 30,
146
+ memberLabel: {
147
+ label: text.slice(0, 30),
148
+ // Vanz@Fix (bug 67): this used Date.now() (milliseconds) while the
149
+ // sibling groupSetMemberLabel() correctly uses unixTimestampSeconds()
150
+ // for the same proto field — WA's *Timestamp fields are unix-seconds,
151
+ // so this was sending a timestamp ~1000x too large.
152
+ labelTimestamp: unixTimestampSeconds() || Date.now()
153
+ }
154
+ }
155
+ }, {
156
+ additionalNodes: [
157
+ {
158
+ tag: 'meta',
159
+ attrs: {
160
+ tag_reason: 'user_update',
161
+ appdata: 'member_tag'
162
+ },
163
+ content: undefined
164
+ }
165
+ ]
166
+ });
167
+ }
168
+ catch {
169
+ // intentionally swallowed — matches source behavior
170
+ }
171
+ };
172
+ //# sourceMappingURL=media-set.js.map
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Evernight AI — lib/Utils/message-kind.js / Creator : Vanzxy🍃
3
+ *
4
+ * Addon-kind resolution logic adapted from zapo-js (MIT, © vinikjkkj)
5
+ * <https://github.com/vinikjkkj/zapo>, ported to this Baileys fork's
6
+ * message-content shape. The normalized reply parser below is original,
7
+ * written to cover this fork's own buttonsResponseMessage /
8
+ * listResponseMessage / interactiveResponseMessage / templateButtonReplyMessage
9
+ * send-side shapes (see messages.js).
10
+ */
11
+
12
+ /**
13
+ * Unwraps ephemeral/viewOnce/edited wrappers to get at the real content.
14
+ * Mirrors the wrapper set already handled by normalizeMessageContent()
15
+ * in messages.js, kept local here to avoid a circular import.
16
+ */
17
+ const unwrapMessage = (message) => {
18
+ let content = message;
19
+ for (let i = 0; i < 5; i++) {
20
+ const inner = content?.ephemeralMessage?.message ||
21
+ content?.viewOnceMessage?.message ||
22
+ content?.viewOnceMessageV2?.message ||
23
+ content?.viewOnceMessageV2Extension?.message ||
24
+ content?.documentWithCaptionMessage?.message ||
25
+ content?.editedMessage?.message;
26
+ if (!inner) {
27
+ break;
28
+ }
29
+ content = inner;
30
+ }
31
+ return content;
32
+ };
33
+
34
+ /**
35
+ * Companion "addon kind" for list / native-flow style messages.
36
+ * Ported from zapo-js's resolveButtonAddonKind (src/message/encode/content.ts).
37
+ * @typedef {'list' | 'interactive' | 'payment_info' | 'order_details'} WaButtonAddonKind
38
+ */
39
+
40
+ const resolveNativeFlowAddonKind = (nativeFlow) => {
41
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name;
42
+ if (firstButtonName === 'payment_info')
43
+ return 'payment_info';
44
+ if (firstButtonName === 'review_and_pay')
45
+ return 'order_details';
46
+ return 'interactive';
47
+ };
48
+
49
+ /**
50
+ * Resolves which kind of button/list addon an outgoing message carries.
51
+ * Returns null if the message has no button/list/native-flow content.
52
+ * @param {import('../../WAProto').proto.IMessage} message
53
+ * @returns {WaButtonAddonKind | null}
54
+ */
55
+ export const resolveButtonAddonKind = (message) => {
56
+ const msg = unwrapMessage(message);
57
+ if (!msg)
58
+ return null;
59
+ if (msg.listMessage)
60
+ return 'list';
61
+ if (msg.buttonsMessage)
62
+ return 'interactive';
63
+ const nativeFlow = msg.interactiveMessage?.nativeFlowMessage;
64
+ if (nativeFlow)
65
+ return resolveNativeFlowAddonKind(nativeFlow);
66
+ return null;
67
+ };
68
+
69
+ /**
70
+ * Normalized shape returned by parseInteractiveReply, regardless of which
71
+ * underlying WhatsApp reply type produced it.
72
+ * @typedef {Object} NormalizedInteractiveReply
73
+ * @property {'buttons_response'|'list_response'|'native_flow_response'|'template_button_reply'|null} kind
74
+ * @property {string|null} id - the button/row/native-flow id the user selected
75
+ * @property {string|null} displayText - visible text of the selection, if present
76
+ * @property {Object|null} params - parsed paramsJson for native-flow responses, or null
77
+ */
78
+
79
+ /**
80
+ * Reads whatever a user tapped (button, list row, or native-flow reply) and
81
+ * returns one consistent shape, so plugin authors don't need a different
82
+ * branch per response type. Safe against malformed paramsJson (returns null
83
+ * instead of throwing).
84
+ * @param {import('../../WAProto').proto.IMessage} message
85
+ * @returns {NormalizedInteractiveReply}
86
+ */
87
+ export const parseInteractiveReply = (message) => {
88
+ const msg = unwrapMessage(message);
89
+ const empty = { kind: null, id: null, displayText: null, params: null };
90
+ if (!msg)
91
+ return empty;
92
+ if (msg.buttonsResponseMessage) {
93
+ const r = msg.buttonsResponseMessage;
94
+ return {
95
+ kind: 'buttons_response',
96
+ id: r.selectedButtonId || null,
97
+ displayText: r.selectedDisplayText || null,
98
+ params: null
99
+ };
100
+ }
101
+ if (msg.listResponseMessage) {
102
+ const r = msg.listResponseMessage;
103
+ return {
104
+ kind: 'list_response',
105
+ id: r.singleSelectReply?.selectedRowId || null,
106
+ displayText: r.title || r.description || null,
107
+ params: null
108
+ };
109
+ }
110
+ if (msg.interactiveResponseMessage) {
111
+ const r = msg.interactiveResponseMessage;
112
+ let params = null;
113
+ if (r.nativeFlowResponseMessage?.paramsJson) {
114
+ try {
115
+ params = JSON.parse(r.nativeFlowResponseMessage.paramsJson);
116
+ }
117
+ catch {
118
+ params = null;
119
+ }
120
+ }
121
+ return {
122
+ kind: 'native_flow_response',
123
+ id: params?.id ?? r.nativeFlowResponseMessage?.name ?? null,
124
+ displayText: r.body?.text || null,
125
+ params
126
+ };
127
+ }
128
+ if (msg.templateButtonReplyMessage) {
129
+ const r = msg.templateButtonReplyMessage;
130
+ return {
131
+ kind: 'template_button_reply',
132
+ id: r.selectedId || null,
133
+ displayText: r.selectedDisplayText || null,
134
+ params: null
135
+ };
136
+ }
137
+ return empty;
138
+ };
139
+ //# sourceMappingURL=message-kind.js.map
@@ -0,0 +1,79 @@
1
+ export const RetryReason: any;
2
+ export class MessageRetryManager {
3
+ constructor(logger: any, maxMsgRetryCount: any);
4
+ logger: any;
5
+ recentMessagesMap: any;
6
+ messageKeyIndex: Map<any, any>;
7
+ sessionRecreateHistory: any;
8
+ retryCounters: any;
9
+ baseKeys: any;
10
+ pendingPhoneRequests: {};
11
+ maxMsgRetryCount: any;
12
+ statistics: {
13
+ totalRetries: number;
14
+ successfulRetries: number;
15
+ failedRetries: number;
16
+ mediaRetries: number;
17
+ sessionRecreations: number;
18
+ phoneRequests: number;
19
+ };
20
+ /**
21
+ * Add a recent message to the cache for retry handling
22
+ */
23
+ addRecentMessage(to: any, id: any, message: any): void;
24
+ /**
25
+ * Get a recent message from the cache
26
+ */
27
+ getRecentMessage(to: any, id: any): any;
28
+ /**
29
+ * Check if a session should be recreated based on retry count, history, and error code.
30
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
31
+ */
32
+ shouldRecreateSession(jid: any, hasSession: any, errorCode: any): {
33
+ reason: string;
34
+ recreate: boolean;
35
+ };
36
+ /**
37
+ * Parse error code from retry receipt's retry node.
38
+ * Returns undefined if no error code is present.
39
+ */
40
+ parseRetryErrorCode(errorAttr: any): any;
41
+ /**
42
+ * Check if an error code indicates a MAC failure
43
+ */
44
+ isMacError(errorCode: any): boolean;
45
+ /**
46
+ * Increment retry counter for a message
47
+ */
48
+ incrementRetryCount(messageId: any): any;
49
+ /**
50
+ * Get retry count for a message
51
+ */
52
+ getRetryCount(messageId: any): any;
53
+ /**
54
+ * Check if message has exceeded maximum retry attempts
55
+ */
56
+ hasExceededMaxRetries(messageId: any): boolean;
57
+ /**
58
+ * Mark retry as successful
59
+ */
60
+ markRetrySuccess(messageId: any): void;
61
+ /**
62
+ * Mark retry as failed
63
+ */
64
+ markRetryFailed(messageId: any): void;
65
+ /**
66
+ * Schedule a phone request with delay
67
+ */
68
+ schedulePhoneRequest(messageId: any, callback: any, delay?: number): void;
69
+ /**
70
+ * Cancel pending phone request
71
+ */
72
+ cancelPendingPhoneRequest(messageId: any): void;
73
+ clear(): void;
74
+ saveBaseKey(addr: any, msgId: any, baseKey: any): void;
75
+ hasSameBaseKey(addr: any, msgId: any, baseKey: any): boolean;
76
+ deleteBaseKey(addr: any, msgId: any): void;
77
+ keyToString(key: any): string;
78
+ removeRecentMessage(messageId: any): void;
79
+ }
@@ -0,0 +1,265 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ /** Number of sent messages to cache in memory for handling retry receipts */
3
+ const RECENT_MESSAGES_SIZE = 1024;
4
+ const MESSAGE_KEY_SEPARATOR = '\u0000';
5
+ /** Timeout for session recreation - 1 hour */
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
7
+ const PHONE_REQUEST_DELAY = 3000;
8
+ // Retry reason codes matching WhatsApp Web's Signal error codes.
9
+ export var RetryReason;
10
+ (function (RetryReason) {
11
+ RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
12
+ RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
13
+ RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
14
+ RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
15
+ /** MAC verification failed - most common cause of decryption failures */
16
+ RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
17
+ RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
18
+ RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
19
+ /** Explicit MAC failure - session is definitely out of sync */
20
+ RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
21
+ RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
22
+ RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
23
+ RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
24
+ RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
25
+ RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
26
+ RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
27
+ })(RetryReason || (RetryReason = {}));
28
+ /** Error codes that indicate a MAC failure and require immediate session recreation */
29
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
30
+ export class MessageRetryManager {
31
+ constructor(logger, maxMsgRetryCount) {
32
+ this.logger = logger;
33
+ this.recentMessagesMap = new LRUCache({
34
+ max: RECENT_MESSAGES_SIZE,
35
+ ttl: 5 * 60 * 1000,
36
+ ttlAutopurge: true,
37
+ dispose: (_value, key) => {
38
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
39
+ if (separatorIndex > -1) {
40
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
41
+ this.messageKeyIndex.delete(messageId);
42
+ }
43
+ }
44
+ });
45
+ this.messageKeyIndex = new Map();
46
+ this.sessionRecreateHistory = new LRUCache({
47
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
48
+ ttlAutopurge: true
49
+ });
50
+ this.retryCounters = new LRUCache({
51
+ ttl: 15 * 60 * 1000,
52
+ ttlAutopurge: true,
53
+ updateAgeOnGet: true
54
+ }); // 15 minutes TTL
55
+ this.baseKeys = new LRUCache({
56
+ max: 1024,
57
+ ttl: 15 * 60 * 1000,
58
+ ttlAutopurge: true
59
+ });
60
+ this.pendingPhoneRequests = {};
61
+ this.maxMsgRetryCount = 5;
62
+ this.statistics = {
63
+ totalRetries: 0,
64
+ successfulRetries: 0,
65
+ failedRetries: 0,
66
+ mediaRetries: 0,
67
+ sessionRecreations: 0,
68
+ phoneRequests: 0
69
+ };
70
+ this.maxMsgRetryCount = maxMsgRetryCount;
71
+ }
72
+ /**
73
+ * Add a recent message to the cache for retry handling
74
+ */
75
+ addRecentMessage(to, id, message) {
76
+ const key = { to, id };
77
+ const keyStr = this.keyToString(key);
78
+ // Add new message
79
+ this.recentMessagesMap.set(keyStr, {
80
+ message,
81
+ timestamp: Date.now()
82
+ });
83
+ this.messageKeyIndex.set(id, keyStr);
84
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
85
+ }
86
+ /**
87
+ * Get a recent message from the cache
88
+ */
89
+ getRecentMessage(to, id) {
90
+ const key = { to, id };
91
+ const keyStr = this.keyToString(key);
92
+ return this.recentMessagesMap.get(keyStr);
93
+ }
94
+ /**
95
+ * Check if a session should be recreated based on retry count, history, and error code.
96
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
97
+ */
98
+ shouldRecreateSession(jid, hasSession, errorCode) {
99
+ // If we don't have a session, always recreate
100
+ if (!hasSession) {
101
+ this.sessionRecreateHistory.set(jid, Date.now());
102
+ this.statistics.sessionRecreations++;
103
+ return {
104
+ reason: "we don't have a Signal session with them",
105
+ recreate: true
106
+ };
107
+ }
108
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
109
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
110
+ this.sessionRecreateHistory.set(jid, Date.now());
111
+ this.statistics.sessionRecreations++;
112
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
113
+ return {
114
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
115
+ recreate: true
116
+ };
117
+ }
118
+ const now = Date.now();
119
+ const prevTime = this.sessionRecreateHistory.get(jid);
120
+ // If no previous recreation or it's been more than an hour
121
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
122
+ this.sessionRecreateHistory.set(jid, now);
123
+ this.statistics.sessionRecreations++;
124
+ return {
125
+ reason: 'retry count > 1 and over an hour since last recreation',
126
+ recreate: true
127
+ };
128
+ }
129
+ return { reason: '', recreate: false };
130
+ }
131
+ /**
132
+ * Parse error code from retry receipt's retry node.
133
+ * Returns undefined if no error code is present.
134
+ */
135
+ parseRetryErrorCode(errorAttr) {
136
+ if (errorAttr === undefined || errorAttr === '') {
137
+ return undefined;
138
+ }
139
+ const code = parseInt(errorAttr, 10);
140
+ if (Number.isNaN(code)) {
141
+ return undefined;
142
+ }
143
+ // Validate it's a known RetryReason
144
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
145
+ return code;
146
+ }
147
+ return RetryReason.UnknownError;
148
+ }
149
+ /**
150
+ * Check if an error code indicates a MAC failure
151
+ */
152
+ isMacError(errorCode) {
153
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
154
+ }
155
+ /**
156
+ * Increment retry counter for a message
157
+ */
158
+ incrementRetryCount(messageId) {
159
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
160
+ this.statistics.totalRetries++;
161
+ return this.retryCounters.get(messageId);
162
+ }
163
+ /**
164
+ * Get retry count for a message
165
+ */
166
+ getRetryCount(messageId) {
167
+ return this.retryCounters.get(messageId) || 0;
168
+ }
169
+ /**
170
+ * Check if message has exceeded maximum retry attempts
171
+ */
172
+ hasExceededMaxRetries(messageId) {
173
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
174
+ }
175
+ /**
176
+ * Mark retry as successful
177
+ */
178
+ markRetrySuccess(messageId) {
179
+ this.statistics.successfulRetries++;
180
+ // Clean up retry counter for successful message
181
+ this.retryCounters.delete(messageId);
182
+ this.cancelPendingPhoneRequest(messageId);
183
+ this.removeRecentMessage(messageId);
184
+ }
185
+ /**
186
+ * Mark retry as failed
187
+ */
188
+ markRetryFailed(messageId) {
189
+ this.statistics.failedRetries++;
190
+ this.retryCounters.delete(messageId);
191
+ this.cancelPendingPhoneRequest(messageId);
192
+ this.removeRecentMessage(messageId);
193
+ }
194
+ /**
195
+ * Schedule a phone request with delay
196
+ */
197
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
198
+ // Cancel any existing request for this message
199
+ this.cancelPendingPhoneRequest(messageId);
200
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
201
+ delete this.pendingPhoneRequests[messageId];
202
+ this.statistics.phoneRequests++;
203
+ callback();
204
+ }, delay);
205
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
206
+ }
207
+ /**
208
+ * Cancel pending phone request
209
+ */
210
+ cancelPendingPhoneRequest(messageId) {
211
+ const timeout = this.pendingPhoneRequests[messageId];
212
+ if (timeout) {
213
+ clearTimeout(timeout);
214
+ delete this.pendingPhoneRequests[messageId];
215
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
216
+ }
217
+ }
218
+ clear() {
219
+ this.recentMessagesMap.clear();
220
+ this.messageKeyIndex.clear();
221
+ this.sessionRecreateHistory.clear();
222
+ this.retryCounters.clear();
223
+ this.baseKeys.clear();
224
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) {
225
+ this.cancelPendingPhoneRequest(messageId);
226
+ }
227
+ this.statistics = {
228
+ totalRetries: 0,
229
+ successfulRetries: 0,
230
+ failedRetries: 0,
231
+ mediaRetries: 0,
232
+ sessionRecreations: 0,
233
+ phoneRequests: 0
234
+ };
235
+ }
236
+ saveBaseKey(addr, msgId, baseKey) {
237
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey);
238
+ }
239
+ hasSameBaseKey(addr, msgId, baseKey) {
240
+ const stored = this.baseKeys.get(`${addr}:${msgId}`);
241
+ if (!stored || stored.length !== baseKey.length) {
242
+ return false;
243
+ }
244
+ for (let i = 0; i < stored.length; i++) {
245
+ if (stored[i] !== baseKey[i])
246
+ return false;
247
+ }
248
+ return true;
249
+ }
250
+ deleteBaseKey(addr, msgId) {
251
+ this.baseKeys.delete(`${addr}:${msgId}`);
252
+ }
253
+ keyToString(key) {
254
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
255
+ }
256
+ removeRecentMessage(messageId) {
257
+ const keyStr = this.messageKeyIndex.get(messageId);
258
+ if (!keyStr) {
259
+ return;
260
+ }
261
+ this.recentMessagesMap.delete(keyStr);
262
+ this.messageKeyIndex.delete(messageId);
263
+ }
264
+ }
265
+ //# sourceMappingURL=message-retry-manager.js.map
@@ -0,0 +1,44 @@
1
+ import type { WAMessage } from '../Types/index.js';
2
+ export type SearchMessageType = 'text' | 'image' | 'video' | 'document' | 'audio' | 'sticker' | 'location' | 'contact' | 'other';
3
+ export interface SearchOptions {
4
+ jid?: string;
5
+ fromDate?: Date;
6
+ toDate?: Date;
7
+ fromSender?: string;
8
+ fromMe?: boolean;
9
+ messageTypes?: SearchMessageType[];
10
+ limit?: number;
11
+ caseSensitive?: boolean;
12
+ }
13
+ export interface SearchResult {
14
+ message: WAMessage;
15
+ matchedText: string;
16
+ matchPosition: number;
17
+ relevanceScore: number;
18
+ }
19
+ export interface RegexSearchOptions {
20
+ jid?: string;
21
+ fromSender?: string;
22
+ fromMe?: boolean;
23
+ messageTypes?: SearchMessageType[];
24
+ limit?: number;
25
+ }
26
+ export declare const extractMessageText: (message: WAMessage) => string;
27
+ export declare const calculateRelevance: (query: string, text: string, position: number) => number;
28
+ export declare const searchMessages: (messages: WAMessage[], query: string, options?: SearchOptions) => SearchResult[];
29
+ export declare const searchMessagesRegex: (messages: WAMessage[], pattern: RegExp, options?: RegexSearchOptions) => SearchResult[];
30
+ export declare class MessageSearchManager {
31
+ private messages;
32
+ private messageIndex;
33
+ addMessages(messages: WAMessage[]): void;
34
+ removeMessages(messageIds: string[]): void;
35
+ clear(): void;
36
+ get count(): number;
37
+ search(query: string, options?: SearchOptions): SearchResult[];
38
+ searchRegex(pattern: RegExp, options?: RegexSearchOptions): SearchResult[];
39
+ getByJid(jid: string): WAMessage[];
40
+ getBySender(sender: string): WAMessage[];
41
+ getByType(type: SearchMessageType): WAMessage[];
42
+ getById(id: string): WAMessage | undefined;
43
+ }
44
+ export declare const createMessageSearch: () => MessageSearchManager;