@badzz88/baileys 8.5.5 → 8.5.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 (282) hide show
  1. package/README.md +2 -2
  2. package/WAProto/WAProto.proto +1256 -75
  3. package/WAProto/fix-imports.js +69 -79
  4. package/WAProto/index.d.ts +15254 -71491
  5. package/WAProto/index.js +19816 -126438
  6. package/engine-requirements.js +3 -4
  7. package/package.json +4 -4
  8. package/src/Defaults/index.js +186 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +86 -0
  11. package/src/Signal/Group/group_cipher.js +82 -0
  12. package/src/Signal/Group/index.js +140 -0
  13. package/src/Signal/Group/keyhelper.js +77 -0
  14. package/src/Signal/Group/sender-chain-key.js +29 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +51 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +87 -0
  20. package/src/Signal/Group/sender-message-key.js +29 -0
  21. package/src/Signal/libsignal.js +455 -0
  22. package/src/Signal/lid-mapping.js +273 -0
  23. package/src/Socket/Client/index.js +31 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +61 -0
  26. package/src/Socket/aigroups.js +221 -0
  27. package/src/Socket/business.js +411 -0
  28. package/src/Socket/chats.js +1449 -0
  29. package/src/Socket/communities.js +463 -0
  30. package/src/Socket/graphql.js +523 -0
  31. package/src/Socket/groups.js +516 -0
  32. package/src/Socket/index.js +31 -0
  33. package/src/Socket/interactive-handler.js +527 -0
  34. package/src/Socket/interop.js +339 -0
  35. package/{lib → src}/Socket/luxu.js +82 -120
  36. package/src/Socket/managed-account.js +98 -0
  37. package/src/Socket/messages-recv.js +2685 -0
  38. package/src/Socket/messages-send.js +2047 -0
  39. package/src/Socket/mex.js +57 -0
  40. package/src/Socket/newsletter.js +455 -0
  41. package/src/Socket/privacy.js +125 -0
  42. package/src/Socket/registration.js +236 -0
  43. package/src/Socket/socket.js +983 -0
  44. package/src/Socket/text-router.js +65 -0
  45. package/src/Socket/username.js +130 -0
  46. package/src/Store/index.js +33 -0
  47. package/{lib → src}/Store/keyed-db.js +21 -11
  48. package/src/Store/make-cache-manager-store.js +84 -0
  49. package/src/Store/make-in-memory-store.js +551 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +26 -0
  52. package/src/Types/Auth.js +31 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +26 -0
  60. package/src/Types/LabelAssociation.js +8 -0
  61. package/src/Types/Message.js +93 -0
  62. package/src/Types/Mex.js +112 -0
  63. package/src/Types/Newsletter.js +109 -0
  64. package/src/Types/Product.js +2 -0
  65. package/src/Types/Signal.js +2 -0
  66. package/src/Types/Socket.js +2 -0
  67. package/src/Types/State.js +62 -0
  68. package/src/Types/USync.js +2 -0
  69. package/src/Types/index.js +56 -0
  70. package/src/Utils/auth-utils.js +254 -0
  71. package/src/Utils/browser-utils.js +112 -0
  72. package/src/Utils/business.js +240 -0
  73. package/src/Utils/chat-utils.js +1230 -0
  74. package/src/Utils/command-loader.d.ts +27 -0
  75. package/src/Utils/command-loader.js +89 -0
  76. package/src/Utils/companion-reg-client-utils.js +40 -0
  77. package/src/Utils/consumer-application.js +105 -0
  78. package/src/Utils/crypto.js +118 -0
  79. package/src/Utils/curve25519-js.js +242 -0
  80. package/src/Utils/decode-wa-message.js +529 -0
  81. package/src/Utils/event-buffer.js +580 -0
  82. package/src/Utils/generics.js +483 -0
  83. package/src/Utils/group-history.js +44 -0
  84. package/src/Utils/history.js +232 -0
  85. package/src/Utils/identity-change-handler.js +52 -0
  86. package/src/Utils/index.js +58 -0
  87. package/src/Utils/jid-display-normalization.js +195 -0
  88. package/src/Utils/link-preview.js +135 -0
  89. package/src/Utils/logger.js +8 -0
  90. package/src/Utils/lt-hash.js +25 -0
  91. package/src/Utils/make-mutex.js +36 -0
  92. package/src/Utils/message-composer.js +471 -0
  93. package/src/Utils/message-retry-manager.js +217 -0
  94. package/src/Utils/messages-media.js +843 -0
  95. package/src/Utils/messages.js +2817 -0
  96. package/src/Utils/meta-ai-msmsg.js +222 -0
  97. package/src/Utils/native-bridge.js +68 -0
  98. package/src/Utils/noise-handler.js +169 -0
  99. package/src/Utils/offline-node-processor.js +34 -0
  100. package/src/Utils/pre-key-manager.js +90 -0
  101. package/src/Utils/process-message.js +950 -0
  102. package/src/Utils/reporting-utils.js +261 -0
  103. package/src/Utils/session-pool.d.ts +14 -0
  104. package/src/Utils/session-pool.js +70 -0
  105. package/src/Utils/signal.js +217 -0
  106. package/src/Utils/stanza-ack.js +30 -0
  107. package/src/Utils/sticker.d.ts +13 -0
  108. package/src/Utils/sticker.js +123 -0
  109. package/src/Utils/sync-action-utils.js +45 -0
  110. package/src/Utils/tc-token-utils.js +158 -0
  111. package/src/Utils/use-multi-file-auth-state.js +111 -0
  112. package/src/Utils/validate-connection.js +209 -0
  113. package/src/Utils/view-once-cache.d.ts +12 -0
  114. package/src/Utils/view-once-cache.js +63 -0
  115. package/src/Utils/voip-rekey.js +22 -0
  116. package/src/WABinary/constants.js +1304 -0
  117. package/src/WABinary/decode.js +342 -0
  118. package/{lib → src}/WABinary/encode.js +9 -12
  119. package/src/WABinary/generic-utils.js +238 -0
  120. package/src/WABinary/index.js +34 -0
  121. package/src/WABinary/jid-utils.js +351 -0
  122. package/src/WABinary/types.js +2 -0
  123. package/src/WAM/BinaryInfo.js +13 -0
  124. package/src/WAM/constants.js +39484 -0
  125. package/src/WAM/encode.js +149 -0
  126. package/src/WAM/index.js +32 -0
  127. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  128. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
  129. package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  130. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
  131. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  132. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
  133. package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
  134. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +473 -0
  135. package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
  136. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  137. package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  138. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  139. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  140. package/src/WAUSync/Protocols/index.js +40 -0
  141. package/src/WAUSync/USyncQuery.js +126 -0
  142. package/src/WAUSync/USyncUser.js +50 -0
  143. package/src/WAUSync/index.js +32 -0
  144. package/src/antiban.js +4152 -0
  145. package/{lib → src}/index.js +51 -49
  146. package/lib/Defaults/index.js +0 -187
  147. package/lib/Signal/Group/ciphertext-message.js +0 -15
  148. package/lib/Signal/Group/group-session-builder.js +0 -92
  149. package/lib/Signal/Group/group_cipher.js +0 -89
  150. package/lib/Signal/Group/index.js +0 -136
  151. package/lib/Signal/Group/keyhelper.js +0 -73
  152. package/lib/Signal/Group/sender-chain-key.js +0 -32
  153. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  154. package/lib/Signal/Group/sender-key-message.js +0 -69
  155. package/lib/Signal/Group/sender-key-name.js +0 -50
  156. package/lib/Signal/Group/sender-key-record.js +0 -44
  157. package/lib/Signal/Group/sender-key-state.js +0 -97
  158. package/lib/Signal/Group/sender-message-key.js +0 -30
  159. package/lib/Signal/libsignal.js +0 -459
  160. package/lib/Signal/lid-mapping.js +0 -260
  161. package/lib/Socket/Client/index.js +0 -30
  162. package/lib/Socket/Client/types.js +0 -13
  163. package/lib/Socket/Client/websocket.js +0 -62
  164. package/lib/Socket/aigroups.js +0 -240
  165. package/lib/Socket/business.js +0 -422
  166. package/lib/Socket/chats.js +0 -1816
  167. package/lib/Socket/communities.js +0 -549
  168. package/lib/Socket/graphql.js +0 -656
  169. package/lib/Socket/groups.js +0 -764
  170. package/lib/Socket/index.js +0 -39
  171. package/lib/Socket/interactive-handler.js +0 -522
  172. package/lib/Socket/interop.js +0 -549
  173. package/lib/Socket/managed-account.js +0 -183
  174. package/lib/Socket/messages-recv.js +0 -2442
  175. package/lib/Socket/messages-send.js +0 -1853
  176. package/lib/Socket/mex.js +0 -60
  177. package/lib/Socket/newsletter.js +0 -818
  178. package/lib/Socket/privacy.js +0 -449
  179. package/lib/Socket/registration.js +0 -427
  180. package/lib/Socket/socket.js +0 -1092
  181. package/lib/Socket/text-router.js +0 -83
  182. package/lib/Socket/username.js +0 -243
  183. package/lib/Store/index.js +0 -36
  184. package/lib/Store/make-cache-manager-store.js +0 -90
  185. package/lib/Store/make-in-memory-store.js +0 -604
  186. package/lib/Store/make-ordered-dictionary.js +0 -81
  187. package/lib/Store/object-repository.js +0 -29
  188. package/lib/Types/Auth.js +0 -38
  189. package/lib/Types/Bussines.js +0 -2
  190. package/lib/Types/Call.js +0 -2
  191. package/lib/Types/Chat.js +0 -4
  192. package/lib/Types/Contact.js +0 -2
  193. package/lib/Types/Events.js +0 -2
  194. package/lib/Types/GroupMetadata.js +0 -2
  195. package/lib/Types/Label.js +0 -27
  196. package/lib/Types/LabelAssociation.js +0 -9
  197. package/lib/Types/Message.js +0 -95
  198. package/lib/Types/Mex.js +0 -112
  199. package/lib/Types/Newsletter.js +0 -121
  200. package/lib/Types/Product.js +0 -2
  201. package/lib/Types/Signal.js +0 -2
  202. package/lib/Types/Socket.js +0 -2
  203. package/lib/Types/State.js +0 -70
  204. package/lib/Types/USync.js +0 -2
  205. package/lib/Types/index.js +0 -55
  206. package/lib/Utils/auth-utils.js +0 -306
  207. package/lib/Utils/browser-utils.js +0 -114
  208. package/lib/Utils/business.js +0 -247
  209. package/lib/Utils/chat-utils.js +0 -1208
  210. package/lib/Utils/command-loader.d.ts +0 -31
  211. package/lib/Utils/command-loader.js +0 -100
  212. package/lib/Utils/companion-reg-client-utils.js +0 -42
  213. package/lib/Utils/consumer-application.js +0 -107
  214. package/lib/Utils/crypto.js +0 -155
  215. package/lib/Utils/curve25519-js.js +0 -275
  216. package/lib/Utils/decode-wa-message.js +0 -560
  217. package/lib/Utils/event-buffer.js +0 -607
  218. package/lib/Utils/generics.js +0 -563
  219. package/lib/Utils/group-history.js +0 -60
  220. package/lib/Utils/history.js +0 -244
  221. package/lib/Utils/identity-change-handler.js +0 -52
  222. package/lib/Utils/index.js +0 -57
  223. package/lib/Utils/jid-display-normalization.js +0 -218
  224. package/lib/Utils/link-preview.js +0 -143
  225. package/lib/Utils/logger.js +0 -9
  226. package/lib/Utils/lt-hash.js +0 -39
  227. package/lib/Utils/make-mutex.js +0 -36
  228. package/lib/Utils/message-composer.js +0 -479
  229. package/lib/Utils/message-inspect.js +0 -393
  230. package/lib/Utils/message-retry-manager.js +0 -270
  231. package/lib/Utils/messages-media.js +0 -896
  232. package/lib/Utils/messages.js +0 -2904
  233. package/lib/Utils/meta-ai-msmsg.js +0 -262
  234. package/lib/Utils/native-bridge.js +0 -82
  235. package/lib/Utils/noise-handler.js +0 -196
  236. package/lib/Utils/offline-node-processor.js +0 -42
  237. package/lib/Utils/pre-key-manager.js +0 -107
  238. package/lib/Utils/process-message.js +0 -1048
  239. package/lib/Utils/reporting-utils.js +0 -262
  240. package/lib/Utils/session-pool.d.ts +0 -16
  241. package/lib/Utils/session-pool.js +0 -94
  242. package/lib/Utils/signal.js +0 -224
  243. package/lib/Utils/stanza-ack.js +0 -40
  244. package/lib/Utils/sticker.d.ts +0 -17
  245. package/lib/Utils/sticker.js +0 -145
  246. package/lib/Utils/sync-action-utils.js +0 -54
  247. package/lib/Utils/tc-token-utils.js +0 -161
  248. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  249. package/lib/Utils/validate-connection.js +0 -219
  250. package/lib/Utils/view-once-cache.d.ts +0 -9
  251. package/lib/Utils/view-once-cache.js +0 -79
  252. package/lib/Utils/voip-rekey.js +0 -22
  253. package/lib/WABinary/constants.js +0 -1304
  254. package/lib/WABinary/decode.js +0 -343
  255. package/lib/WABinary/generic-utils.js +0 -240
  256. package/lib/WABinary/index.js +0 -33
  257. package/lib/WABinary/jid-utils.js +0 -361
  258. package/lib/WABinary/types.js +0 -2
  259. package/lib/WAM/BinaryInfo.js +0 -13
  260. package/lib/WAM/constants.js +0 -39486
  261. package/lib/WAM/encode.js +0 -142
  262. package/lib/WAM/index.js +0 -31
  263. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -55
  264. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +0 -43
  265. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -54
  266. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  267. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  268. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +0 -59
  269. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -31
  270. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -865
  271. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +0 -32
  272. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  273. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -39
  274. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  275. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -27
  276. package/lib/WAUSync/Protocols/index.js +0 -39
  277. package/lib/WAUSync/USyncBackoff.js +0 -26
  278. package/lib/WAUSync/USyncQuery.js +0 -133
  279. package/lib/WAUSync/USyncUser.js +0 -50
  280. package/lib/WAUSync/index.js +0 -31
  281. package/lib/antiban.js +0 -4637
  282. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
@@ -0,0 +1,2817 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.assertMediaContent =
4
+ exports.downloadMediaMessage =
5
+ exports.aggregateMessageKeysNotFromMe =
6
+ exports.updateMessageWithEventResponse =
7
+ exports.updateMessageWithPollUpdate =
8
+ exports.updateMessageWithReaction =
9
+ exports.updateMessageWithReceipt =
10
+ exports.getDevice =
11
+ exports.extractMessageContent =
12
+ exports.normalizeMessageContent =
13
+ exports.getContentType =
14
+ exports.generateWAMessage =
15
+ exports.generateWAMessageFromContent =
16
+ exports.generateWAMessageContent =
17
+ exports.hasNonNullishProperty =
18
+ exports.generateForwardMessageContent =
19
+ exports.prepareDisappearingMessageSettingContent =
20
+ exports.prepareWAMessageMedia =
21
+ exports.generateLinkPreviewIfRequired =
22
+ exports.extractUrlFromText =
23
+ void 0;
24
+ exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
25
+ exports.getAggregateResponsesInEventMessage = getAggregateResponsesInEventMessage;
26
+ const boom_1 = require('@hapi/boom');
27
+ const crypto_1 = require('crypto');
28
+ const fs_1 = require('fs');
29
+ const index_js_1 = require('../../WAProto/index.js');
30
+ const WAProto_1 = require('../../WAProto/index.js');
31
+ const Defaults_1 = require('../Defaults');
32
+ const Types_1 = require('../Types');
33
+ const WABinary_1 = require('../WABinary');
34
+ const crypto_2 = require('./crypto');
35
+ const generics_1 = require('./generics');
36
+ const messages_media_1 = require('./messages-media');
37
+ const reporting_utils_1 = require('./reporting-utils');
38
+ const jid_display_normalization_1 = require('./jid-display-normalization');
39
+ const MIMETYPE_MAP = {
40
+ image: 'image/jpeg',
41
+ video: 'video/mp4',
42
+ document: 'application/pdf',
43
+ audio: 'audio/ogg; codecs=opus',
44
+ sticker: 'image/webp',
45
+ 'product-catalog-image': 'image/jpeg'
46
+ };
47
+ const MessageTypeProto = {
48
+ image: WAProto_1.proto.Message.ImageMessage,
49
+ video: WAProto_1.proto.Message.VideoMessage,
50
+ audio: WAProto_1.proto.Message.AudioMessage,
51
+ sticker: WAProto_1.proto.Message.StickerMessage,
52
+ document: WAProto_1.proto.Message.DocumentMessage
53
+ };
54
+ const MEDIA_MESSAGE_TYPE_ALIASES = {
55
+ imageMessage: 'image',
56
+ videoMessage: 'video',
57
+ audioMessage: 'audio',
58
+ documentMessage: 'document',
59
+ stickerMessage: 'sticker',
60
+ ptvMessage: 'video'
61
+ };
62
+ const MEDIA_MESSAGE_TYPE_ALIAS_KEYS = Object.keys(MEDIA_MESSAGE_TYPE_ALIASES);
63
+ const hasMediaPayload = message => Defaults_1.MEDIA_KEYS.some(key => key in message) || MEDIA_MESSAGE_TYPE_ALIAS_KEYS.some(key => key in message);
64
+ const ButtonType = WAProto_1.proto.Message.ButtonsMessage.HeaderType;
65
+ const RICH_RESPONSE_CODE_KEYWORDS = new Set([
66
+ 'break',
67
+ 'case',
68
+ 'catch',
69
+ 'continue',
70
+ 'debugger',
71
+ 'default',
72
+ 'delete',
73
+ 'do',
74
+ 'else',
75
+ 'finally',
76
+ 'for',
77
+ 'function',
78
+ 'if',
79
+ 'in',
80
+ 'instanceof',
81
+ 'new',
82
+ 'return',
83
+ 'switch',
84
+ 'this',
85
+ 'throw',
86
+ 'try',
87
+ 'typeof',
88
+ 'var',
89
+ 'void',
90
+ 'while',
91
+ 'with',
92
+ 'true',
93
+ 'false',
94
+ 'null',
95
+ 'undefined',
96
+ 'NaN',
97
+ 'Infinity',
98
+ 'class',
99
+ 'const',
100
+ 'let',
101
+ 'super',
102
+ 'extends',
103
+ 'export',
104
+ 'import',
105
+ 'yield',
106
+ 'static',
107
+ 'constructor',
108
+ 'of',
109
+ 'async',
110
+ 'await',
111
+ 'get',
112
+ 'set',
113
+ 'implements',
114
+ 'interface',
115
+ 'package',
116
+ 'private',
117
+ 'protected',
118
+ 'public',
119
+ 'enum',
120
+ 'throws',
121
+ 'transient'
122
+ ]);
123
+ const tokenizeCode = code => {
124
+ const tokens = [];
125
+ let i = 0;
126
+ const len = code.length;
127
+ while (i < len) {
128
+ if (/\s/.test(code[i])) {
129
+ const start = i;
130
+ while (i < len && /\s/.test(code[i]))
131
+ i++;
132
+ tokens.push({ content: code.slice(start, i), type: 'DEFAULT' });
133
+ continue;
134
+ }
135
+ if (code[i] === '"' || code[i] === "'" || code[i] === '`') {
136
+ const start = i;
137
+ const quote = code[i];
138
+ i++;
139
+ while (i < len && code[i] !== quote) {
140
+ if (code[i] === '\\')
141
+ i++;
142
+ i++;
143
+ }
144
+ i++;
145
+ tokens.push({ content: code.slice(start, i), type: 'STR' });
146
+ continue;
147
+ }
148
+ if (code[i] === '/' && i + 1 < len && code[i + 1] === '/') {
149
+ const start = i;
150
+ while (i < len && code[i] !== '\n')
151
+ i++;
152
+ tokens.push({ content: code.slice(start, i), type: 'COMMENT' });
153
+ continue;
154
+ }
155
+ if (code[i] === '/' && i + 1 < len && code[i + 1] === '*') {
156
+ const start = i;
157
+ i += 2;
158
+ while (i + 1 < len && !(code[i] === '*' && code[i + 1] === '/'))
159
+ i++;
160
+ i += 2;
161
+ tokens.push({ content: code.slice(start, i), type: 'COMMENT' });
162
+ continue;
163
+ }
164
+ if (/[0-9]/.test(code[i])) {
165
+ const start = i;
166
+ while (i < len && /[0-9.]/.test(code[i]))
167
+ i++;
168
+ tokens.push({ content: code.slice(start, i), type: 'NUMBER' });
169
+ continue;
170
+ }
171
+ if (/[a-zA-Z_$]/.test(code[i])) {
172
+ const start = i;
173
+ while (i < len && /[a-zA-Z0-9_$]/.test(code[i]))
174
+ i++;
175
+ const word = code.slice(start, i);
176
+ if (RICH_RESPONSE_CODE_KEYWORDS.has(word)) {
177
+ tokens.push({ content: word, type: 'KEYWORD' });
178
+ }
179
+ else {
180
+ let j = i;
181
+ while (j < len && /\s/.test(code[j]))
182
+ j++;
183
+ tokens.push({ content: word, type: j < len && code[j] === '(' ? 'METHOD' : 'DEFAULT' });
184
+ }
185
+ continue;
186
+ }
187
+ tokens.push({ content: code[i], type: 'DEFAULT' });
188
+ i++;
189
+ }
190
+ const merged = [];
191
+ for (const t of tokens) {
192
+ if (merged.length && merged[merged.length - 1].type === 'DEFAULT' && t.type === 'DEFAULT') {
193
+ merged[merged.length - 1].content += t.content;
194
+ }
195
+ else {
196
+ merged.push(t);
197
+ }
198
+ }
199
+ return merged;
200
+ };
201
+ const extractUrlFromText = text => text.match(Defaults_1.URL_REGEX)?.[0];
202
+ exports.extractUrlFromText = extractUrlFromText;
203
+ const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
204
+ const url = (0, exports.extractUrlFromText)(text);
205
+ if (!!getUrlInfo && url) {
206
+ try {
207
+ const urlInfo = await getUrlInfo(url);
208
+ return urlInfo;
209
+ }
210
+ catch (error) {
211
+ logger?.warn({ trace: error.stack }, 'url generation failed');
212
+ }
213
+ }
214
+ };
215
+ exports.generateLinkPreviewIfRequired = generateLinkPreviewIfRequired;
216
+ const assertColor = async (color) => {
217
+ let assertedColor;
218
+ if (typeof color === 'number') {
219
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
220
+ }
221
+ else {
222
+ let hex = color.trim().replace('#', '');
223
+ if (hex.length <= 6) {
224
+ hex = 'FF' + hex.padStart(6, '0');
225
+ }
226
+ assertedColor = parseInt(hex, 16);
227
+ return assertedColor;
228
+ }
229
+ };
230
+ const prepareWAMessageMedia = async (message, options) => {
231
+ const logger = options.logger;
232
+ let mediaType;
233
+ for (const key of Defaults_1.MEDIA_KEYS) {
234
+ if (key in message) {
235
+ mediaType = key;
236
+ }
237
+ }
238
+ if (!mediaType) {
239
+ throw new boom_1.Boom('Invalid media type', { statusCode: 400 });
240
+ }
241
+ const uploadData = {
242
+ ...message,
243
+ media: message[mediaType]
244
+ };
245
+ delete uploadData[mediaType];
246
+ const cacheableKey = typeof uploadData.media === 'object' &&
247
+ 'url' in uploadData.media &&
248
+ !!uploadData.media.url &&
249
+ !!options.mediaCache &&
250
+ mediaType + ':' + uploadData.media.url.toString();
251
+ if (mediaType === 'document' && !uploadData.fileName) {
252
+ uploadData.fileName = 'file';
253
+ }
254
+ if (!uploadData.mimetype) {
255
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
256
+ }
257
+ if (cacheableKey) {
258
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
259
+ if (mediaBuff) {
260
+ logger?.debug({ cacheableKey }, 'got media cache hit');
261
+ const obj = index_js_1.proto.Message.decode(mediaBuff);
262
+ const key = `${mediaType}Message`;
263
+ Object.assign(obj[key], { ...uploadData, media: undefined });
264
+ return obj;
265
+ }
266
+ }
267
+ const isNewsletter = !!options.jid && (0, WABinary_1.isJidNewsletter)(options.jid);
268
+ if (isNewsletter) {
269
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
270
+ const { filePath, fileSha256, fileLength } = await (0, messages_media_1.getRawMediaUploadData)(uploadData.media, options.mediaTypeOverride || mediaType, logger);
271
+ const fileSha256B64 = fileSha256.toString('base64');
272
+ const { mediaUrl, directPath } = await options.upload(filePath, {
273
+ fileEncSha256B64: fileSha256B64,
274
+ mediaType: mediaType,
275
+ timeoutMs: options.mediaUploadTimeoutMs
276
+ });
277
+ await fs_1.promises.unlink(filePath);
278
+ const obj = WAProto_1.proto.Message.fromObject({
279
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
280
+ url: mediaUrl,
281
+ directPath,
282
+ fileSha256,
283
+ fileLength,
284
+ ...uploadData,
285
+ media: undefined
286
+ })
287
+ });
288
+ if (uploadData.ptv) {
289
+ obj.ptvMessage = obj.videoMessage;
290
+ delete obj.videoMessage;
291
+ }
292
+ if (obj.stickerMessage) {
293
+ obj.stickerMessage.stickerSentTs = Date.now();
294
+ }
295
+ if (cacheableKey) {
296
+ logger?.debug({ cacheableKey }, 'set cache');
297
+ await options.mediaCache.set(cacheableKey, WAProto_1.proto.Message.encode(obj).finish());
298
+ }
299
+ return obj;
300
+ }
301
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
302
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
303
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
304
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
305
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
306
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await (0,
307
+ messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
308
+ logger,
309
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
310
+ opts: options.options
311
+ });
312
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
313
+ const [{ mediaUrl, directPath }] = await Promise.all([
314
+ (async () => {
315
+ const result = await options.upload(encFilePath, {
316
+ fileEncSha256B64,
317
+ mediaType,
318
+ timeoutMs: options.mediaUploadTimeoutMs
319
+ });
320
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
321
+ return result;
322
+ })(),
323
+ (async () => {
324
+ try {
325
+ if (requiresThumbnailComputation) {
326
+ const { thumbnail, originalImageDimensions } = await (0, messages_media_1.generateThumbnail)(originalFilePath, mediaType, options);
327
+ uploadData.jpegThumbnail = thumbnail;
328
+ if (!uploadData.width && originalImageDimensions) {
329
+ uploadData.width = originalImageDimensions.width;
330
+ uploadData.height = originalImageDimensions.height;
331
+ logger?.debug('set dimensions');
332
+ }
333
+ logger?.debug('generated thumbnail');
334
+ }
335
+ if (requiresDurationComputation) {
336
+ uploadData.seconds = await (0, messages_media_1.getAudioDuration)(originalFilePath);
337
+ logger?.debug('computed audio duration');
338
+ }
339
+ if (requiresWaveformProcessing) {
340
+ uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(originalFilePath, logger);
341
+ logger?.debug('processed waveform');
342
+ }
343
+ if (requiresAudioBackground) {
344
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
345
+ logger?.debug('computed backgroundColor audio status');
346
+ }
347
+ }
348
+ catch (error) {
349
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
350
+ }
351
+ })()
352
+ ]).finally(async () => {
353
+ try {
354
+ await fs_1.promises.unlink(encFilePath);
355
+ if (originalFilePath) {
356
+ await fs_1.promises.unlink(originalFilePath);
357
+ }
358
+ logger?.debug('removed tmp files');
359
+ }
360
+ catch (error) {
361
+ logger?.warn('failed to remove tmp file');
362
+ }
363
+ });
364
+ const obj = WAProto_1.proto.Message.fromObject({
365
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
366
+ url: mediaUrl,
367
+ directPath,
368
+ mediaKey,
369
+ fileEncSha256,
370
+ fileSha256,
371
+ fileLength,
372
+ mediaKeyTimestamp: (0, generics_1.unixTimestampSeconds)(),
373
+ ...uploadData,
374
+ media: undefined
375
+ })
376
+ });
377
+ if (uploadData.ptv) {
378
+ obj.ptvMessage = obj.videoMessage;
379
+ delete obj.videoMessage;
380
+ }
381
+ if (cacheableKey) {
382
+ logger?.debug({ cacheableKey }, 'set cache');
383
+ await options.mediaCache.set(cacheableKey, WAProto_1.proto.Message.encode(obj).finish());
384
+ }
385
+ return obj;
386
+ };
387
+ exports.prepareWAMessageMedia = prepareWAMessageMedia;
388
+ const prepareDisappearingMessageSettingContent = ephemeralExpiration => {
389
+ ephemeralExpiration = ephemeralExpiration || 0;
390
+ const content = {
391
+ ephemeralMessage: {
392
+ message: {
393
+ protocolMessage: {
394
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
395
+ ephemeralExpiration
396
+ }
397
+ }
398
+ }
399
+ };
400
+ return WAProto_1.proto.Message.fromObject(content);
401
+ };
402
+ exports.prepareDisappearingMessageSettingContent = prepareDisappearingMessageSettingContent;
403
+ const generateForwardMessageContent = (message, forceForward) => {
404
+ let content = message.message;
405
+ if (!content) {
406
+ throw new boom_1.Boom('no content in message', { statusCode: 400 });
407
+ }
408
+ content = (0, exports.normalizeMessageContent)(content);
409
+ content = index_js_1.proto.Message.decode(index_js_1.proto.Message.encode(content).finish());
410
+ let key = Object.keys(content)[0];
411
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
412
+ score += message.key.fromMe && !forceForward ? 0 : 1;
413
+ if (key === 'conversation') {
414
+ content.extendedTextMessage = { text: content[key] };
415
+ delete content.conversation;
416
+ key = 'extendedTextMessage';
417
+ }
418
+ const key_ = content?.[key];
419
+ if (score > 0) {
420
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
421
+ }
422
+ else {
423
+ key_.contextInfo = {};
424
+ }
425
+ return content;
426
+ };
427
+ exports.generateForwardMessageContent = generateForwardMessageContent;
428
+ const hasNonNullishProperty = (message, key) => {
429
+ return (typeof message === 'object' &&
430
+ message !== null &&
431
+ key in message &&
432
+ message[key] !== null &&
433
+ message[key] !== undefined);
434
+ };
435
+ exports.hasNonNullishProperty = hasNonNullishProperty;
436
+ function hasOptionalProperty(obj, key) {
437
+ return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
438
+ }
439
+ const normalizeEarFields = ear => {
440
+ const result = { ...ear };
441
+ const applyAlias = (fromKey, toKey) => {
442
+ if (result[fromKey] !== undefined && result[toKey] === undefined)
443
+ result[toKey] = result[fromKey];
444
+ };
445
+ applyAlias('thumbnail_url', 'thumbnailUrl');
446
+ applyAlias('thumbnailUrl', 'thumbnail');
447
+ applyAlias('source_url', 'sourceUrl');
448
+ applyAlias('media_type', 'mediaType');
449
+ applyAlias('show_ad_attribution', 'showAdAttribution');
450
+ applyAlias('render_larger_thumbnail', 'renderLargerThumbnail');
451
+ if (result.thumbnail && !result.jpegThumbnail)
452
+ result.jpegThumbnail = result.thumbnail;
453
+ if (result.largeThumbnail !== undefined && result.renderLargerThumbnail === undefined)
454
+ result.renderLargerThumbnail = result.largeThumbnail;
455
+ if (result.url && !result.sourceUrl)
456
+ result.sourceUrl = result.url;
457
+ delete result.thumbnail;
458
+ delete result.largeThumbnail;
459
+ delete result.url;
460
+ delete result.thumbnail_url;
461
+ delete result.source_url;
462
+ delete result.media_type;
463
+ delete result.show_ad_attribution;
464
+ delete result.render_larger_thumbnail;
465
+ return result;
466
+ };
467
+ const normalizeQuickReplyButton = button => {
468
+ var _a;
469
+ if (button.name && typeof button.name === 'string') {
470
+ return {
471
+ name: button.name,
472
+ buttonParamsJson: typeof button.buttonParamsJson === 'string'
473
+ ? button.buttonParamsJson
474
+ : JSON.stringify(button.buttonParamsJson || {})
475
+ };
476
+ }
477
+ if (button.type === 4 && button.nativeFlowInfo) {
478
+ const { name, paramsJson } = button.nativeFlowInfo;
479
+ return {
480
+ name: name || 'quick_reply',
481
+ buttonParamsJson: typeof paramsJson === 'string' ? paramsJson : JSON.stringify(paramsJson || {})
482
+ };
483
+ }
484
+ const buttonTextObject = button.buttonText && typeof button.buttonText === 'object' ? button.buttonText : undefined;
485
+ const displayTextCandidates = [
486
+ button.text,
487
+ button.displayText,
488
+ button.display_text,
489
+ typeof button.buttonText === 'string' ? button.buttonText : undefined,
490
+ buttonTextObject === null || buttonTextObject === void 0 ? void 0 : buttonTextObject.displayText,
491
+ buttonTextObject === null || buttonTextObject === void 0 ? void 0 : buttonTextObject.display_text
492
+ ];
493
+ const displayText = displayTextCandidates.find(value => typeof value === 'string' && value.length > 0) || '';
494
+ const id = button.buttonId || button.id || ((_a = button.buttonParamsJson) === null || _a === void 0 ? void 0 : _a.id) || '';
495
+ return {
496
+ name: 'quick_reply',
497
+ buttonParamsJson: JSON.stringify({
498
+ display_text: displayText,
499
+ id
500
+ })
501
+ };
502
+ };
503
+ const asciiDecode = arr => arr.map(e => String.fromCharCode(e)).join('');
504
+ const applyContextInfoAndMentions = (interactiveMessage, message) => {
505
+ if ('contextInfo' in message && !!message.contextInfo) {
506
+ interactiveMessage.contextInfo = message.contextInfo;
507
+ }
508
+ if ('mentions' in message && !!message.mentions) {
509
+ interactiveMessage.contextInfo = {
510
+ ...(interactiveMessage.contextInfo || {}),
511
+ mentionedJid: message.mentions
512
+ };
513
+ }
514
+ };
515
+ const buildPaymentNoteMessage = async (paymentPayload, options, fallbackText = '') => {
516
+ let notes;
517
+ if (paymentPayload === null || paymentPayload === void 0 ? void 0 : paymentPayload.sticker) {
518
+ const stickerPrep = await (0, exports.prepareWAMessageMedia)({ sticker: paymentPayload.sticker }, options);
519
+ notes = {
520
+ stickerMessage: {
521
+ ...(stickerPrep === null || stickerPrep === void 0 ? void 0 : stickerPrep.stickerMessage),
522
+ contextInfo: paymentPayload === null || paymentPayload === void 0 ? void 0 : paymentPayload.contextInfo
523
+ }
524
+ };
525
+ }
526
+ else if (typeof (paymentPayload === null || paymentPayload === void 0 ? void 0 : paymentPayload.note) === 'string') {
527
+ notes = {
528
+ extendedTextMessage: {
529
+ text: paymentPayload.note,
530
+ contextInfo: paymentPayload === null || paymentPayload === void 0 ? void 0 : paymentPayload.contextInfo
531
+ }
532
+ };
533
+ }
534
+ else if ((paymentPayload === null || paymentPayload === void 0 ? void 0 : paymentPayload.noteMessage) &&
535
+ typeof paymentPayload.noteMessage === 'object') {
536
+ const noteKeys = Object.keys(paymentPayload.noteMessage);
537
+ const allowedNoteMessageKeys = ['extendedTextMessage', 'stickerMessage'];
538
+ const hasOnlyAllowedKeys = noteKeys.length > 0 && noteKeys.every(key => allowedNoteMessageKeys.includes(key));
539
+ if (!noteKeys.length || !hasOnlyAllowedKeys) {
540
+ throw new boom_1.Boom('Invalid payment noteMessage', { statusCode: 400 });
541
+ }
542
+ notes = paymentPayload.noteMessage;
543
+ }
544
+ else {
545
+ notes = { extendedTextMessage: { text: fallbackText } };
546
+ }
547
+ return notes;
548
+ };
549
+ const generateWAMessageContent = async (message, options) => {
550
+ var _a, _b;
551
+ let m = {};
552
+ const hasCaptionWithoutMedia = 'caption' in message && !hasMediaPayload(message);
553
+ const hasCaptionContainer = ('groupStatus' in message && !!message.groupStatus) || ('viewOnce' in message && !!message.viewOnce);
554
+ if ((0, exports.hasNonNullishProperty)(message, 'text')) {
555
+ const extContent = { text: message.text };
556
+ let urlInfo = message.linkPreview;
557
+ if (typeof urlInfo === 'undefined') {
558
+ urlInfo = await (0, exports.generateLinkPreviewIfRequired)(message.text, options.getUrlInfo, options.logger);
559
+ }
560
+ if (urlInfo) {
561
+ extContent.matchedText = urlInfo['matched-text'];
562
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
563
+ extContent.description = urlInfo.description;
564
+ extContent.title = urlInfo.title;
565
+ extContent.previewType = 0;
566
+ const img = urlInfo.highQualityThumbnail;
567
+ if (img) {
568
+ extContent.thumbnailDirectPath = img.directPath;
569
+ extContent.mediaKey = img.mediaKey;
570
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
571
+ extContent.thumbnailWidth = img.width;
572
+ extContent.thumbnailHeight = img.height;
573
+ extContent.thumbnailSha256 = img.fileSha256;
574
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
575
+ }
576
+ }
577
+ if (options.backgroundColor) {
578
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
579
+ }
580
+ if (options.font) {
581
+ extContent.font = options.font;
582
+ }
583
+ if (options.jid &&
584
+ (0, WABinary_1.isInteropUser)(options.jid) &&
585
+ !options.backgroundColor &&
586
+ !options.font &&
587
+ !urlInfo) {
588
+ m.conversation = message.text;
589
+ }
590
+ else {
591
+ m.extendedTextMessage = extContent;
592
+ }
593
+ }
594
+ else if ((0, exports.hasNonNullishProperty)(message, 'contacts')) {
595
+ const contactLen = message.contacts.contacts.length;
596
+ if (!contactLen) {
597
+ throw new boom_1.Boom('require atleast 1 contact', { statusCode: 400 });
598
+ }
599
+ if (contactLen === 1) {
600
+ m.contactMessage = WAProto_1.proto.Message.ContactMessage.create(message.contacts.contacts[0]);
601
+ }
602
+ else {
603
+ m.contactsArrayMessage = WAProto_1.proto.Message.ContactsArrayMessage.create(message.contacts);
604
+ }
605
+ }
606
+ else if ((0, exports.hasNonNullishProperty)(message, 'location')) {
607
+ m.locationMessage = WAProto_1.proto.Message.LocationMessage.create(message.location);
608
+ }
609
+ else if ((0, exports.hasNonNullishProperty)(message, 'react')) {
610
+ if (!message.react.senderTimestampMs) {
611
+ message.react.senderTimestampMs = Date.now();
612
+ }
613
+ m.reactionMessage = WAProto_1.proto.Message.ReactionMessage.create(message.react);
614
+ }
615
+ else if ((0, exports.hasNonNullishProperty)(message, 'delete')) {
616
+ m.protocolMessage = {
617
+ key: message.delete,
618
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE
619
+ };
620
+ }
621
+ else if ((0, exports.hasNonNullishProperty)(message, 'forward')) {
622
+ m = (0, exports.generateForwardMessageContent)(message.forward, message.force);
623
+ }
624
+ else if ((0, exports.hasNonNullishProperty)(message, 'disappearingMessagesInChat')) {
625
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
626
+ ? message.disappearingMessagesInChat
627
+ ? Defaults_1.WA_DEFAULT_EPHEMERAL
628
+ : 0
629
+ : message.disappearingMessagesInChat;
630
+ m = (0, exports.prepareDisappearingMessageSettingContent)(exp);
631
+ }
632
+ else if ((0, exports.hasNonNullishProperty)(message, 'groupInvite')) {
633
+ m.groupInviteMessage = {};
634
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
635
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
636
+ m.groupInviteMessage.caption = message.groupInvite.text;
637
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
638
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
639
+ if (options.getProfilePicUrl) {
640
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
641
+ if (pfpUrl) {
642
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
643
+ if (resp.ok) {
644
+ const buf = Buffer.from(await resp.arrayBuffer());
645
+ m.groupInviteMessage.jpegThumbnail = buf;
646
+ }
647
+ }
648
+ }
649
+ }
650
+ else if ((0, exports.hasNonNullishProperty)(message, 'pin')) {
651
+ m.pinInChatMessage = {};
652
+ m.messageContextInfo = {};
653
+ m.pinInChatMessage.key = message.pin;
654
+ m.pinInChatMessage.type = message.type;
655
+ m.pinInChatMessage.senderTimestampMs = Date.now();
656
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
657
+ }
658
+ else if ((0, exports.hasNonNullishProperty)(message, 'buttonReply')) {
659
+ switch (message.type) {
660
+ case 'template':
661
+ m.templateButtonReplyMessage = {
662
+ selectedDisplayText: message.buttonReply.displayText,
663
+ selectedId: message.buttonReply.id,
664
+ selectedIndex: message.buttonReply.index
665
+ };
666
+ break;
667
+ case 'plain':
668
+ m.buttonsResponseMessage = {
669
+ selectedButtonId: message.buttonReply.id,
670
+ selectedDisplayText: message.buttonReply.displayText,
671
+ type: index_js_1.proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
672
+ };
673
+ break;
674
+ case 'interactive':
675
+ m.interactiveResponseMessage = {
676
+ body: {
677
+ text: message.buttonReply.displayText,
678
+ format: WAProto_1.proto.Message.InteractiveResponseMessage.Body.Format.EXTENSIONS_1
679
+ },
680
+ nativeFlowResponseMessage: {
681
+ name: message.buttonReply.nativeFlows.name,
682
+ paramsJson: message.buttonReply.nativeFlows.paramsJson,
683
+ version: message.buttonReply.nativeFlows.version
684
+ }
685
+ };
686
+ break;
687
+ case 'list':
688
+ m.listResponseMessage = {
689
+ title: message.buttonReply.title,
690
+ description: message.buttonReply.description,
691
+ singleSelectReply: {
692
+ selectedRowId: message.buttonReply.rowId
693
+ },
694
+ listType: WAProto_1.proto.Message.ListResponseMessage.ListType.SINGLE_SELECT
695
+ };
696
+ break;
697
+ }
698
+ }
699
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
700
+ const { videoMessage } = await (0, exports.prepareWAMessageMedia)({ video: message.video }, options);
701
+ m.ptvMessage = videoMessage;
702
+ }
703
+ else if ((0, exports.hasNonNullishProperty)(message, 'product')) {
704
+ const { imageMessage } = await (0, exports.prepareWAMessageMedia)({ image: message.product.productImage }, options);
705
+ m.productMessage = WAProto_1.proto.Message.ProductMessage.create({
706
+ ...message,
707
+ product: {
708
+ ...message.product,
709
+ productImage: imageMessage
710
+ }
711
+ });
712
+ }
713
+ else if ((0, exports.hasNonNullishProperty)(message, 'listReply')) {
714
+ m.listResponseMessage = { ...message.listReply };
715
+ }
716
+ else if ((0, exports.hasNonNullishProperty)(message, 'event')) {
717
+ m.eventMessage = {};
718
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
719
+ if (message.event.call && options.getCallLink) {
720
+ const token = await options.getCallLink(message.event.call, { startTime });
721
+ m.eventMessage.joinLink =
722
+ (message.event.call === 'audio' ? Defaults_1.CALL_AUDIO_PREFIX : Defaults_1.CALL_VIDEO_PREFIX) + token;
723
+ }
724
+ m.messageContextInfo = {
725
+ messageSecret: message.event.messageSecret || (0, crypto_1.randomBytes)(32)
726
+ };
727
+ m.eventMessage.name = message.event.name;
728
+ m.eventMessage.description = message.event.description;
729
+ m.eventMessage.startTime = startTime;
730
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
731
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
732
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
733
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
734
+ m.eventMessage.location = message.event.location;
735
+ }
736
+ else if ((0, exports.hasNonNullishProperty)(message, 'poll')) {
737
+ ;
738
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
739
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
740
+ if (!Array.isArray(message.poll.values)) {
741
+ throw new boom_1.Boom('Invalid poll values', { statusCode: 400 });
742
+ }
743
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
744
+ throw new boom_1.Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
745
+ statusCode: 400
746
+ });
747
+ }
748
+ m.messageContextInfo = {
749
+ messageSecret: message.poll.messageSecret || (0, crypto_1.randomBytes)(32)
750
+ };
751
+ const isQuiz = message.poll.type === 'quiz' || message.poll.pollType === WAProto_1.proto.Message.PollType.QUIZ;
752
+ const pollTypeEnum = WAProto_1.proto.Message.PollType;
753
+ const pollCreationMessage = {
754
+ name: message.poll.name,
755
+ selectableOptionsCount: message.poll.selectableCount,
756
+ options: message.poll.values.map(optionName => ({ optionName })),
757
+ pollType: isQuiz ? pollTypeEnum.QUIZ : pollTypeEnum.POLL,
758
+ ...(isQuiz && message.poll.correctAnswer ? { correctAnswer: { optionName: message.poll.correctAnswer } } : {}),
759
+ ...(message.poll.endTime
760
+ ? {
761
+ endTime: message.poll.endTime instanceof Date
762
+ ? Math.floor(message.poll.endTime.getTime() / 1000)
763
+ : Number(message.poll.endTime)
764
+ }
765
+ : {}),
766
+ ...(message.poll.hideParticipantName !== undefined
767
+ ? { hideParticipantName: !!message.poll.hideParticipantName }
768
+ : {}),
769
+ ...(message.poll.allowAddOption !== undefined ? { allowAddOption: !!message.poll.allowAddOption } : {})
770
+ };
771
+ if (message.poll.version === 6 || message.poll.v6) {
772
+ m.pollCreationMessageV6 = pollCreationMessage;
773
+ }
774
+ else if (message.poll.version === 5 || message.poll.v5) {
775
+ m.pollCreationMessageV5 = pollCreationMessage;
776
+ }
777
+ else if (message.poll.toAnnouncementGroup) {
778
+ m.pollCreationMessageV2 = pollCreationMessage;
779
+ }
780
+ else {
781
+ if (message.poll.selectableCount === 1) {
782
+ m.pollCreationMessageV3 = pollCreationMessage;
783
+ }
784
+ else {
785
+ m.pollCreationMessage = pollCreationMessage;
786
+ }
787
+ }
788
+ }
789
+ else if ('inviteAdmin' in message) {
790
+ m.newsletterAdminInviteMessage = {};
791
+ m.newsletterAdminInviteMessage.inviteExpiration = message.inviteAdmin.inviteExpiration;
792
+ m.newsletterAdminInviteMessage.caption = message.inviteAdmin.text;
793
+ m.newsletterAdminInviteMessage.newsletterJid = message.inviteAdmin.jid;
794
+ m.newsletterAdminInviteMessage.newsletterName = message.inviteAdmin.subject;
795
+ m.newsletterAdminInviteMessage.jpegThumbnail = message.inviteAdmin.thumbnail;
796
+ }
797
+ else if ('requestPayment' in message || 'requestPaymentMessage' in message) {
798
+ if ('requestPayment' in message && 'requestPaymentMessage' in message) {
799
+ throw new boom_1.Boom('Use either requestPayment or requestPaymentMessage, not both', { statusCode: 400 });
800
+ }
801
+ const requestPayment = message.requestPayment || message.requestPaymentMessage;
802
+ const notes = await buildPaymentNoteMessage(requestPayment, options);
803
+ const amountValue = requestPayment.amount ?? requestPayment.amount1000;
804
+ const amount1000Raw = typeof (amountValue === null || amountValue === void 0 ? void 0 : amountValue.toNumber) === 'function'
805
+ ? amountValue.toNumber()
806
+ : Number(amountValue);
807
+ const amount1000 = Number.isFinite(amount1000Raw) ? Math.round(amount1000Raw) : amount1000Raw;
808
+ const currencyCodeIso4217 = requestPayment.currency ?? requestPayment.currencyCodeIso4217;
809
+ const requestFrom = requestPayment.from ?? requestPayment.requestFrom ?? options.recipientJid;
810
+ const missingFields = [];
811
+ if (amountValue === undefined)
812
+ missingFields.push('amount/amount1000');
813
+ if (currencyCodeIso4217 === undefined)
814
+ missingFields.push('currency/currencyCodeIso4217');
815
+ if (requestFrom === undefined)
816
+ missingFields.push('from/requestFrom');
817
+ if (missingFields.length) {
818
+ throw new boom_1.Boom(`Invalid requestPayment fields: missing ${missingFields.join(', ')}`, { statusCode: 400 });
819
+ }
820
+ if (typeof amount1000 !== 'number' ||
821
+ !Number.isFinite(amount1000) ||
822
+ !Number.isInteger(amount1000) ||
823
+ amount1000 <= 0) {
824
+ throw new boom_1.Boom('Invalid requestPayment fields: amount/amount1000 must be a positive integer', {
825
+ statusCode: 400
826
+ });
827
+ }
828
+ const bg = requestPayment.background;
829
+ m.requestPaymentMessage = WAProto_1.proto.Message.RequestPaymentMessage.fromObject({
830
+ expiryTimestamp: requestPayment.expiry ?? requestPayment.expiryTimestamp,
831
+ amount1000,
832
+ currencyCodeIso4217,
833
+ requestFrom,
834
+ noteMessage: notes,
835
+ ...(bg != null ? { background: bg } : {})
836
+ });
837
+ }
838
+ else if ('sendPayment' in message || 'sendPaymentMessage' in message) {
839
+ if ('sendPayment' in message && 'sendPaymentMessage' in message) {
840
+ throw new boom_1.Boom('Use either sendPayment or sendPaymentMessage, not both', { statusCode: 400 });
841
+ }
842
+ const sendPayment = message.sendPayment || message.sendPaymentMessage;
843
+ const notes = await buildPaymentNoteMessage(sendPayment, options, message.text || '');
844
+ const requestMessageKey = sendPayment.requestMessageKey ?? sendPayment.requestKey ?? sendPayment.request;
845
+ if (!requestMessageKey) {
846
+ throw new boom_1.Boom('Invalid sendPayment fields: missing requestMessageKey/requestKey/request', {
847
+ statusCode: 400
848
+ });
849
+ }
850
+ m.sendPaymentMessage = WAProto_1.proto.Message.SendPaymentMessage.fromObject({
851
+ noteMessage: notes,
852
+ requestMessageKey,
853
+ ...(sendPayment.background != null ? { background: sendPayment.background } : {}),
854
+ ...(sendPayment.transactionData != null ? { transactionData: sendPayment.transactionData } : {})
855
+ });
856
+ }
857
+ else if ('declinePaymentRequest' in message || 'declinePaymentRequestMessage' in message) {
858
+ if ('declinePaymentRequest' in message && 'declinePaymentRequestMessage' in message) {
859
+ throw new boom_1.Boom('Use either declinePaymentRequest or declinePaymentRequestMessage, not both', {
860
+ statusCode: 400
861
+ });
862
+ }
863
+ const declinePayment = message.declinePaymentRequest || message.declinePaymentRequestMessage;
864
+ const key = (declinePayment === null || declinePayment === void 0 ? void 0 : declinePayment.key) || declinePayment;
865
+ if (!key) {
866
+ throw new boom_1.Boom('Invalid declinePaymentRequest fields: missing key', { statusCode: 400 });
867
+ }
868
+ m.declinePaymentRequestMessage = WAProto_1.proto.Message.DeclinePaymentRequestMessage.fromObject({ key });
869
+ }
870
+ else if ('cancelPaymentRequest' in message || 'cancelPaymentRequestMessage' in message) {
871
+ if ('cancelPaymentRequest' in message && 'cancelPaymentRequestMessage' in message) {
872
+ throw new boom_1.Boom('Use either cancelPaymentRequest or cancelPaymentRequestMessage, not both', {
873
+ statusCode: 400
874
+ });
875
+ }
876
+ const cancelPayment = message.cancelPaymentRequest || message.cancelPaymentRequestMessage;
877
+ const key = (cancelPayment === null || cancelPayment === void 0 ? void 0 : cancelPayment.key) || cancelPayment;
878
+ if (!key) {
879
+ throw new boom_1.Boom('Invalid cancelPaymentRequest fields: missing key', { statusCode: 400 });
880
+ }
881
+ m.cancelPaymentRequestMessage = WAProto_1.proto.Message.CancelPaymentRequestMessage.fromObject({ key });
882
+ }
883
+ else if ('requestPaymentFrom' in message && !!message.requestPaymentFrom) {
884
+ const noteText = message.text || '';
885
+ m.requestPaymentMessage = WAProto_1.proto.Message.RequestPaymentMessage.fromObject({
886
+ requestFrom: message.requestPaymentFrom,
887
+ noteMessage: { extendedTextMessage: { text: noteText } }
888
+ });
889
+ }
890
+ else if ('invoiceNote' in message) {
891
+ const preparedInvoice = await (0, exports.prepareWAMessageMedia)(message, options);
892
+ const mediaType = Object.keys(preparedInvoice)[0];
893
+ const mediaMsg = preparedInvoice[mediaType] || {};
894
+ m.invoiceMessage = WAProto_1.proto.Message.InvoiceMessage.fromObject({
895
+ note: message.invoiceNote,
896
+ token: message.invoiceToken || '',
897
+ attachmentType: mediaType === 'imageMessage' ? 1 : 0,
898
+ attachmentMimetype: mediaMsg.mimetype,
899
+ attachmentMediaKey: mediaMsg.mediaKey,
900
+ attachmentMediaKeyTimestamp: mediaMsg.mediaKeyTimestamp,
901
+ attachmentFileSha256: mediaMsg.fileSha256,
902
+ attachmentFileEncSha256: mediaMsg.fileEncSha256,
903
+ attachmentDirectPath: mediaMsg.directPath,
904
+ attachmentJpegThumbnail: mediaMsg.jpegThumbnail
905
+ });
906
+ }
907
+ else if ('orderText' in message) {
908
+ m.orderMessage = WAProto_1.proto.Message.OrderMessage.fromObject({
909
+ message: message.orderText,
910
+ thumbnail: message.thumbnail,
911
+ status: message.orderStatus || 1,
912
+ surface: message.orderSurface || 1
913
+ });
914
+ }
915
+ else if ('paymentInviteServiceType' in message) {
916
+ m.paymentInviteMessage = {
917
+ serviceType: message.paymentInviteServiceType,
918
+ expiryTimestamp: message.paymentInviteExpiry
919
+ };
920
+ }
921
+ else if ((0, exports.hasNonNullishProperty)(message, 'sharePhoneNumber')) {
922
+ m.protocolMessage = {
923
+ type: index_js_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
924
+ };
925
+ }
926
+ else if ((0, exports.hasNonNullishProperty)(message, 'requestPhoneNumber')) {
927
+ m.requestPhoneNumberMessage = {};
928
+ }
929
+ else if ((0, exports.hasNonNullishProperty)(message, 'limitSharing')) {
930
+ m.protocolMessage = {
931
+ type: index_js_1.proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
932
+ limitSharing: {
933
+ sharingLimited: message.limitSharing === true,
934
+ trigger: 1,
935
+ limitSharingSettingTimestamp: Date.now(),
936
+ initiatedByMe: true
937
+ }
938
+ };
939
+ }
940
+ else if ('album' in message) {
941
+ const imageMessages = message.album.filter(item => 'image' in item);
942
+ const videoMessages = message.album.filter(item => 'video' in item);
943
+ m.albumMessage = WAProto_1.proto.Message.AlbumMessage.fromObject({
944
+ expectedImageCount: imageMessages.length,
945
+ expectedVideoCount: videoMessages.length
946
+ });
947
+ }
948
+ else if ('pollResult' in message) {
949
+ if (!Array.isArray(message.pollResult.values)) {
950
+ throw new boom_1.Boom('Invalid pollResult values', { statusCode: 400 });
951
+ }
952
+ const isQuizResult = message.pollResult.type === 'quiz' || message.pollResult.pollType === WAProto_1.proto.Message.PollType.QUIZ;
953
+ const pollVotes = message.pollResult.values.map(([optionName, optionVoteCount]) => ({
954
+ optionName,
955
+ optionVoteCount
956
+ }));
957
+ const snapshotPayload = {
958
+ name: message.pollResult.name,
959
+ pollVotes,
960
+ pollType: isQuizResult ? WAProto_1.proto.Message.PollType.QUIZ : WAProto_1.proto.Message.PollType.POLL
961
+ };
962
+ if (message.pollResult.version === 3 || message.pollResult.v3) {
963
+ m.pollResultSnapshotMessageV3 = WAProto_1.proto.Message.PollResultSnapshotMessage.fromObject(snapshotPayload);
964
+ }
965
+ else {
966
+ m.pollResultSnapshotMessage = snapshotPayload;
967
+ }
968
+ }
969
+ else if ('stickerPack' in message || 'stickerPackMessage' in message) {
970
+ if ('stickerPack' in message && 'stickerPackMessage' in message) {
971
+ throw new boom_1.Boom('Cannot specify both stickerPack and stickerPackMessage; use only one property.', {
972
+ statusCode: 400
973
+ });
974
+ }
975
+ const stickerPackMessage = 'stickerPack' in message ? message.stickerPack : message.stickerPackMessage;
976
+ m.stickerPackMessage = WAProto_1.proto.Message.StickerPackMessage.fromObject(stickerPackMessage);
977
+ }
978
+ else if ('listMessage' in message) {
979
+ const lm = { ...message.listMessage };
980
+ if (lm.text !== undefined && lm.description === undefined) {
981
+ lm.description = lm.text;
982
+ delete lm.text;
983
+ }
984
+ m = { listMessage: lm };
985
+ }
986
+ else if ('buttonsMessage' in message) {
987
+ m = {
988
+ buttonsMessage: WAProto_1.proto.Message.ButtonsMessage.fromObject(message.buttonsMessage)
989
+ };
990
+ }
991
+ else if ('interactiveMessage' in message) {
992
+ m = { interactiveMessage: message.interactiveMessage };
993
+ }
994
+ else if ('richResponse' in message) {
995
+ }
996
+ else if ('groupStatusMessage' in message) {
997
+ m = { groupStatusMessage: WAProto_1.proto.Message.GroupStatusMessage.fromObject(message.groupStatusMessage) };
998
+ }
999
+ else if (hasCaptionWithoutMedia && !hasCaptionContainer) {
1000
+ m.extendedTextMessage = { text: message.caption };
1001
+ }
1002
+ else if (hasCaptionWithoutMedia && hasCaptionContainer) {
1003
+ m = {};
1004
+ }
1005
+ else if (!hasCaptionWithoutMedia && hasMediaPayload(message)) {
1006
+ m = await (0, exports.prepareWAMessageMedia)(message, options);
1007
+ }
1008
+ if ('buttons' in message && !!message.buttons) {
1009
+ const interactiveMessage = {
1010
+ nativeFlowMessage: WAProto_1.proto.Message.InteractiveMessage.NativeFlowMessage.fromObject({
1011
+ buttons: message.buttons.map(normalizeQuickReplyButton)
1012
+ })
1013
+ };
1014
+ if ('text' in message) {
1015
+ interactiveMessage.body = { text: message.text };
1016
+ }
1017
+ else if ('caption' in message) {
1018
+ interactiveMessage.body = { text: message.caption };
1019
+ interactiveMessage.header = {
1020
+ title: message.title || '',
1021
+ subtitle: message.subtitle,
1022
+ hasMediaAttachment: Boolean(message.hasMediaAttachment)
1023
+ };
1024
+ Object.assign(interactiveMessage.header, m);
1025
+ }
1026
+ if ('title' in message && !!message.title && !interactiveMessage.header) {
1027
+ interactiveMessage.header = {
1028
+ title: message.title,
1029
+ subtitle: message.subtitle,
1030
+ hasMediaAttachment: Boolean(message.hasMediaAttachment)
1031
+ };
1032
+ }
1033
+ else if ('title' in message && !!message.title && interactiveMessage.header) {
1034
+ interactiveMessage.header.title = message.title;
1035
+ if (message.subtitle !== undefined) {
1036
+ interactiveMessage.header.subtitle = message.subtitle;
1037
+ }
1038
+ }
1039
+ if ('footer' in message && !!message.footer) {
1040
+ interactiveMessage.footer = { text: message.footer };
1041
+ }
1042
+ applyContextInfoAndMentions(interactiveMessage, message);
1043
+ m = { interactiveMessage };
1044
+ }
1045
+ else if ('templateButtons' in message && !!message.templateButtons) {
1046
+ const msg = {
1047
+ hydratedButtons: message.hasOwnProperty('templateButtons') ? message.templateButtons : message.templateButtons
1048
+ };
1049
+ if ('text' in message) {
1050
+ msg.hydratedContentText = message.text;
1051
+ }
1052
+ else {
1053
+ if ('caption' in message) {
1054
+ msg.hydratedContentText = message.caption;
1055
+ }
1056
+ Object.assign(msg, m);
1057
+ }
1058
+ if ('footer' in message && !!message.footer) {
1059
+ msg.hydratedFooterText = message.footer;
1060
+ }
1061
+ m = {
1062
+ templateMessage: {
1063
+ fourRowTemplate: msg,
1064
+ hydratedTemplate: msg
1065
+ }
1066
+ };
1067
+ }
1068
+ if ('sections' in message && !!message.sections) {
1069
+ const listMessage = {
1070
+ sections: message.sections,
1071
+ buttonText: message.buttonText,
1072
+ title: message.title,
1073
+ footerText: message.footer,
1074
+ description: message.text,
1075
+ listType: WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT
1076
+ };
1077
+ m = { listMessage };
1078
+ }
1079
+ else if ('productList' in message && !!message.productList) {
1080
+ if (!Array.isArray(message.productList) ||
1081
+ message.productList.length === 0 ||
1082
+ !Array.isArray(message.productList[0].products) ||
1083
+ message.productList[0].products.length === 0) {
1084
+ throw new boom_1.Boom('Invalid productList: must contain at least one section with one product', {
1085
+ statusCode: 400
1086
+ });
1087
+ }
1088
+ m.listMessage = {
1089
+ title: message.title,
1090
+ buttonText: message.buttonText,
1091
+ footerText: message.footer,
1092
+ description: message.text,
1093
+ productListInfo: {
1094
+ productSections: message.productList,
1095
+ headerImage: {
1096
+ productId: message.productList[0].products[0].productId
1097
+ },
1098
+ businessOwnerJid: message.businessOwnerJid
1099
+ },
1100
+ listType: WAProto_1.proto.Message.ListMessage.ListType.PRODUCT_LIST
1101
+ };
1102
+ }
1103
+ if ('interactiveButtons' in message && !!message.interactiveButtons) {
1104
+ const nativeFlow = WAProto_1.proto.Message.InteractiveMessage.NativeFlowMessage.fromObject({
1105
+ buttons: message.interactiveButtons,
1106
+ messageParamsJson: message.messageParams ?? "{}"
1107
+ });
1108
+ let interactiveMessage = { nativeFlowMessage: nativeFlow };
1109
+ if ('text' in message) {
1110
+ interactiveMessage.body = { text: message.text };
1111
+ }
1112
+ else if ('caption' in message) {
1113
+ interactiveMessage.body = { text: message.caption };
1114
+ }
1115
+ if ('title' in message && !!message.title) {
1116
+ interactiveMessage.header = {
1117
+ title: message.title,
1118
+ subtitle: message.subtitle || "",
1119
+ hasMediaAttachment: false
1120
+ };
1121
+ let media = null;
1122
+ if ('image' in message && !!message.image) {
1123
+ media = await prepareWAMessageMedia({ image: message.image }, options);
1124
+ interactiveMessage.header.imageMessage = media.imageMessage;
1125
+ if (message.image.caption) {
1126
+ interactiveMessage.header.imageMessage.caption = message.image.caption;
1127
+ }
1128
+ }
1129
+ else if ('video' in message && !!message.video) {
1130
+ media = await prepareWAMessageMedia({ video: message.video }, options);
1131
+ interactiveMessage.header.videoMessage = media.videoMessage;
1132
+ if (message.video.caption) {
1133
+ interactiveMessage.header.videoMessage.caption = message.video.caption;
1134
+ }
1135
+ }
1136
+ else if ('gif' in message && !!message.gif) {
1137
+ media = await prepareWAMessageMedia({ video: message.gif }, options);
1138
+ interactiveMessage.header.videoMessage = media.videoMessage;
1139
+ interactiveMessage.header.videoMessage.gifPlayback = true;
1140
+ if (message.gif.caption) {
1141
+ interactiveMessage.header.videoMessage.caption = message.gif.caption;
1142
+ }
1143
+ }
1144
+ else if ('document' in message && !!message.document) {
1145
+ media = await prepareWAMessageMedia({ document: message.document }, options);
1146
+ interactiveMessage.header.documentMessage = media.documentMessage;
1147
+ let docuR = interactiveMessage.header.documentMessage;
1148
+ docuR.fileName = message.document.fileName || "Document";
1149
+ docuR.mimetype = message.document.mimetype || docuR.mimetype;
1150
+ if (message.document.caption)
1151
+ docuR.caption = message.document.caption;
1152
+ if (message.document.jpegThumbnail)
1153
+ docuR.jpegThumbnail = message.document.jpegThumbnail;
1154
+ }
1155
+ else if ('location' in message && !!message.location) {
1156
+ let mLoc = message.location;
1157
+ interactiveMessage.header.locationMessage = {
1158
+ degreesLongitude: mLoc.longitude || 0,
1159
+ degreesLatitude: mLoc.latitude || 0,
1160
+ name: mLoc.name || null,
1161
+ address: mLoc.address || null,
1162
+ url: mLoc.url || null
1163
+ };
1164
+ media = true;
1165
+ }
1166
+ else if ('thumbnail' in message && !!message.thumbnail) {
1167
+ interactiveMessage.header.jpegThumbnail = message.thumbnail;
1168
+ }
1169
+ if (media || ('thumbnail' in message && !!message.thumbnail)) {
1170
+ interactiveMessage.header.hasMediaAttachment = true;
1171
+ }
1172
+ }
1173
+ if ('footer' in message && !!message.footer) {
1174
+ interactiveMessage.footer = { text: message.footer };
1175
+ }
1176
+ applyContextInfoAndMentions(interactiveMessage, message);
1177
+ m = { interactiveMessage };
1178
+ }
1179
+ if ('shop' in message && !!message.shop) {
1180
+ const interactiveMessage = {
1181
+ shopStorefrontMessage: WAProto_1.proto.Message.InteractiveMessage.ShopMessage.fromObject({
1182
+ surface: (_l = message.shop) === null || _l === void 0 ? void 0 : _l.surface,
1183
+ id: (_m = message.shop) === null || _m === void 0 ? void 0 : _m.id
1184
+ })
1185
+ };
1186
+ if ('text' in message) {
1187
+ interactiveMessage.body = {
1188
+ text: message.text
1189
+ };
1190
+ }
1191
+ else if ('caption' in message) {
1192
+ interactiveMessage.body = {
1193
+ text: message.caption
1194
+ };
1195
+ interactiveMessage.header = {
1196
+ title: message.title,
1197
+ subtitle: message.subtitle,
1198
+ hasMediaAttachment: Boolean(message.hasMediaAttachment)
1199
+ };
1200
+ Object.assign(interactiveMessage.header, m);
1201
+ }
1202
+ if ('footer' in message && !!message.footer) {
1203
+ interactiveMessage.footer = {
1204
+ text: message.footer
1205
+ };
1206
+ }
1207
+ if ('title' in message && !!message.title) {
1208
+ interactiveMessage.header = {
1209
+ title: message.title,
1210
+ subtitle: message.subtitle,
1211
+ hasMediaAttachment: Boolean(message.hasMediaAttachment)
1212
+ };
1213
+ Object.assign(interactiveMessage.header, m);
1214
+ }
1215
+ applyContextInfoAndMentions(interactiveMessage, message);
1216
+ m = { interactiveMessage };
1217
+ if ('interactiveAsTemplate' in message && message.interactiveAsTemplate !== false) {
1218
+ m = { templateMessage: { interactiveMessageTemplate: interactiveMessage } };
1219
+ }
1220
+ }
1221
+ if ('richResponse' in message) {
1222
+ const { text, code, language = 'javascript', botJid = '259786046210223@bot', table, latex, map, imageUrl, imageUrls, responseId, messageSecret: richSecret } = message.richResponse;
1223
+ const sections = [];
1224
+ if (text) {
1225
+ sections.push({
1226
+ view_model: {
1227
+ primitive: { text, __typename: 'GenAIMarkdownTextUXPrimitive' },
1228
+ __typename: 'GenAISingleLayoutViewModel'
1229
+ }
1230
+ });
1231
+ }
1232
+ if (code) {
1233
+ sections.push({
1234
+ view_model: {
1235
+ primitive: {
1236
+ language,
1237
+ code_blocks: tokenizeCode(String(code)),
1238
+ __typename: 'GenAICodeUXPrimitive'
1239
+ },
1240
+ __typename: 'GenAISingleLayoutViewModel'
1241
+ }
1242
+ });
1243
+ }
1244
+ if (table) {
1245
+ const isPlainArrayTable = Array.isArray(table);
1246
+ const rows = isPlainArrayTable ? table : table.rows;
1247
+ if (!Array.isArray(rows)) {
1248
+ throw new boom_1.Boom('richResponse.table must be an array of rows (e.g. [["h1","h2"],["a","b"]]) or { rows: [...] }', { statusCode: 400 });
1249
+ }
1250
+ sections.push({
1251
+ view_model: {
1252
+ primitive: {
1253
+ rows: rows.map((row, idx) => ({
1254
+ cells: Array.isArray(row) ? row.map(c => ({ text: String(c) })) : row.cells,
1255
+ isHeading: Array.isArray(row) ? isPlainArrayTable && idx === 0 : row.isHeading
1256
+ })),
1257
+ __typename: 'GenAITableUXPrimitive'
1258
+ },
1259
+ __typename: 'GenAISingleLayoutViewModel'
1260
+ }
1261
+ });
1262
+ }
1263
+ if (latex) {
1264
+ const expressions = Array.isArray(latex)
1265
+ ? latex.map(e => (typeof e === 'string' ? { expression: e } : e))
1266
+ : [{ expression: String(latex) }];
1267
+ sections.push({
1268
+ view_model: {
1269
+ primitive: { expressions, __typename: 'GenAILatexUXPrimitive' },
1270
+ __typename: 'GenAISingleLayoutViewModel'
1271
+ }
1272
+ });
1273
+ }
1274
+ if (map) {
1275
+ sections.push({
1276
+ view_model: {
1277
+ primitive: {
1278
+ latitude: map.latitude,
1279
+ longitude: map.longitude,
1280
+ zoom: map.zoom,
1281
+ title: map.title,
1282
+ annotations: map.annotations || [],
1283
+ __typename: 'GenAIMapUXPrimitive'
1284
+ },
1285
+ __typename: 'GenAISingleLayoutViewModel'
1286
+ }
1287
+ });
1288
+ }
1289
+ if (imageUrl) {
1290
+ sections.push({
1291
+ view_model: {
1292
+ primitive: { url: imageUrl, __typename: 'GenAIInlineImageUXPrimitive' },
1293
+ __typename: 'GenAISingleLayoutViewModel'
1294
+ }
1295
+ });
1296
+ }
1297
+ if (imageUrls && Array.isArray(imageUrls) && imageUrls.length > 0) {
1298
+ sections.push({
1299
+ view_model: {
1300
+ primitive: {
1301
+ urls: imageUrls.map(u => (typeof u === 'string' ? { url: u } : u)),
1302
+ __typename: 'GenAIGridImageUXPrimitive'
1303
+ },
1304
+ __typename: 'GenAISingleLayoutViewModel'
1305
+ }
1306
+ });
1307
+ }
1308
+ if (!sections.length && !text) {
1309
+ sections.push({
1310
+ view_model: {
1311
+ primitive: { text: '', __typename: 'GenAIMarkdownTextUXPrimitive' },
1312
+ __typename: 'GenAISingleLayoutViewModel'
1313
+ }
1314
+ });
1315
+ }
1316
+ const unifiedData = {
1317
+ response_id: responseId || (0, crypto_1.randomUUID)(),
1318
+ sections
1319
+ };
1320
+ return WAProto_1.proto.Message.fromObject({
1321
+ messageContextInfo: {
1322
+ deviceListMetadata: {},
1323
+ deviceListMetadataVersion: 2,
1324
+ messageSecret: richSecret || (0, crypto_1.randomBytes)(32)
1325
+ },
1326
+ botForwardedMessage: {
1327
+ message: {
1328
+ richResponseMessage: {
1329
+ submessages: [],
1330
+ messageType: 1,
1331
+ unifiedResponse: { data: Buffer.from(JSON.stringify(unifiedData)) },
1332
+ contextInfo: {
1333
+ forwardingScore: 2,
1334
+ isForwarded: true,
1335
+ forwardedAiBotMessageInfo: { botJid },
1336
+ botMessageSharingInfo: {
1337
+ botEntryPointOrigin: 1,
1338
+ forwardScore: 2
1339
+ }
1340
+ }
1341
+ }
1342
+ }
1343
+ }
1344
+ });
1345
+ }
1346
+ if ('statusNotification' in message || 'statusNotificationMessage' in message) {
1347
+ const notifData = 'statusNotification' in message ? message.statusNotification : message.statusNotificationMessage;
1348
+ m = { statusNotificationMessage: WAProto_1.proto.Message.StatusNotificationMessage.fromObject(notifData) };
1349
+ }
1350
+ else if ('statusQuestionAnswer' in message || 'statusQuestionAnswerMessage' in message) {
1351
+ const qaData = 'statusQuestionAnswer' in message ? message.statusQuestionAnswer : message.statusQuestionAnswerMessage;
1352
+ m = { statusQuestionAnswerMessage: WAProto_1.proto.Message.StatusQuestionAnswerMessage.fromObject(qaData) };
1353
+ }
1354
+ else if ('questionResponse' in message || 'questionResponseMessage' in message) {
1355
+ const qrData = 'questionResponse' in message ? message.questionResponse : message.questionResponseMessage;
1356
+ m = { questionResponseMessage: WAProto_1.proto.Message.QuestionResponseMessage.fromObject(qrData) };
1357
+ }
1358
+ else if ('statusQuoted' in message || 'statusQuotedMessage' in message) {
1359
+ const sqData = 'statusQuoted' in message ? message.statusQuoted : message.statusQuotedMessage;
1360
+ m = { statusQuotedMessage: WAProto_1.proto.Message.StatusQuotedMessage.fromObject(sqData) };
1361
+ }
1362
+ else if ('statusStickerInteraction' in message || 'statusStickerInteractionMessage' in message) {
1363
+ const ssiData = 'statusStickerInteraction' in message ? message.statusStickerInteraction : message.statusStickerInteractionMessage;
1364
+ m = { statusStickerInteractionMessage: WAProto_1.proto.Message.StatusStickerInteractionMessage.fromObject(ssiData) };
1365
+ }
1366
+ else if ('newsletterFollowerInvite' in message || 'newsletterFollowerInviteMessageV2' in message) {
1367
+ const nfiData = 'newsletterFollowerInvite' in message
1368
+ ? message.newsletterFollowerInvite
1369
+ : message.newsletterFollowerInviteMessageV2;
1370
+ m = {
1371
+ newsletterFollowerInviteMessageV2: WAProto_1.proto.Message.NewsletterFollowerInviteMessage.fromObject(nfiData)
1372
+ };
1373
+ }
1374
+ else if ('messageHistoryNotice' in message) {
1375
+ m = { messageHistoryNotice: WAProto_1.proto.Message.MessageHistoryNotice.fromObject(message.messageHistoryNotice) };
1376
+ }
1377
+ else if ('scheduledCall' in message || 'scheduledCallCreationMessage' in message) {
1378
+ if ('scheduledCall' in message && 'scheduledCallCreationMessage' in message) {
1379
+ throw new boom_1.Boom('Use either scheduledCall or scheduledCallCreationMessage, not both', { statusCode: 400 });
1380
+ }
1381
+ const sc = message.scheduledCall || message.scheduledCallCreationMessage;
1382
+ const scheduledTs = sc.scheduledAt instanceof Date
1383
+ ? sc.scheduledAt.getTime()
1384
+ : sc.scheduledAt
1385
+ ? Number(sc.scheduledAt)
1386
+ : sc.scheduledTimestampMs
1387
+ ? Number(sc.scheduledTimestampMs)
1388
+ : Date.now() + 3600000;
1389
+ const callTypeEnum = WAProto_1.proto.Message.ScheduledCallCreationMessage.CallType;
1390
+ let callType = callTypeEnum.UNKNOWN;
1391
+ if (sc.isVideo || sc.callType === 'video' || sc.callType === callTypeEnum.VIDEO) {
1392
+ callType = callTypeEnum.VIDEO;
1393
+ }
1394
+ else if (sc.callType === 'voice' || sc.callType === callTypeEnum.VOICE || sc.callType === undefined) {
1395
+ callType = callTypeEnum.VOICE;
1396
+ }
1397
+ else {
1398
+ callType = sc.callType ?? callTypeEnum.VOICE;
1399
+ }
1400
+ m.scheduledCallCreationMessage = WAProto_1.proto.Message.ScheduledCallCreationMessage.fromObject({
1401
+ scheduledTimestampMs: scheduledTs,
1402
+ callType,
1403
+ title: sc.title || ''
1404
+ });
1405
+ }
1406
+ else if ('editScheduledCall' in message || 'scheduledCallEditMessage' in message) {
1407
+ if ('editScheduledCall' in message && 'scheduledCallEditMessage' in message) {
1408
+ throw new boom_1.Boom('Use either editScheduledCall or scheduledCallEditMessage, not both', { statusCode: 400 });
1409
+ }
1410
+ const esc = message.editScheduledCall || message.scheduledCallEditMessage;
1411
+ const key = esc.key || esc;
1412
+ if (!key || typeof key !== 'object' || !key.id) {
1413
+ throw new boom_1.Boom('editScheduledCall requires a valid message key with id', { statusCode: 400 });
1414
+ }
1415
+ m.scheduledCallEditMessage = WAProto_1.proto.Message.ScheduledCallEditMessage.fromObject({
1416
+ key,
1417
+ editType: WAProto_1.proto.Message.ScheduledCallEditMessage.EditType.CANCEL
1418
+ });
1419
+ }
1420
+ else if ('eventInvite' in message || 'eventInviteMessage' in message) {
1421
+ if ('eventInvite' in message && 'eventInviteMessage' in message) {
1422
+ throw new boom_1.Boom('Use either eventInvite or eventInviteMessage, not both', { statusCode: 400 });
1423
+ }
1424
+ const ei = message.eventInvite || message.eventInviteMessage;
1425
+ const startTime = ei.startDate instanceof Date
1426
+ ? Math.floor(ei.startDate.getTime() / 1000)
1427
+ : ei.startTime
1428
+ ? Number(ei.startTime)
1429
+ : undefined;
1430
+ const endTime = ei.endDate instanceof Date ? Math.floor(ei.endDate.getTime() / 1000) : ei.endTime ? Number(ei.endTime) : undefined;
1431
+ if (!ei.eventId && !ei.id) {
1432
+ throw new boom_1.Boom('eventInvite requires an eventId', { statusCode: 400 });
1433
+ }
1434
+ m.eventInviteMessage = WAProto_1.proto.Message.EventInviteMessage.fromObject({
1435
+ eventId: ei.eventId || ei.id,
1436
+ eventTitle: ei.title || ei.eventTitle || '',
1437
+ caption: ei.text || ei.caption || '',
1438
+ startTime,
1439
+ endTime,
1440
+ isCanceled: ei.isCancelled ?? ei.isCanceled ?? false,
1441
+ jpegThumbnail: ei.thumbnail || ei.jpegThumbnail,
1442
+ contextInfo: ei.contextInfo
1443
+ });
1444
+ }
1445
+ else if ('comment' in message || 'commentMessage' in message) {
1446
+ if ('comment' in message && 'commentMessage' in message) {
1447
+ throw new boom_1.Boom('Use either comment or commentMessage, not both', { statusCode: 400 });
1448
+ }
1449
+ const cm = message.comment || message.commentMessage;
1450
+ if (!cm.targetMessageKey && !cm.key) {
1451
+ throw new boom_1.Boom('comment requires a targetMessageKey', { statusCode: 400 });
1452
+ }
1453
+ m.commentMessage = WAProto_1.proto.Message.CommentMessage.fromObject({
1454
+ message: cm.message || cm.replyMessage,
1455
+ targetMessageKey: cm.targetMessageKey || cm.key
1456
+ });
1457
+ }
1458
+ else if ('splitPayment' in message || 'splitPaymentMessage' in message) {
1459
+ if ('splitPayment' in message && 'splitPaymentMessage' in message) {
1460
+ throw new boom_1.Boom('Use either splitPayment or splitPaymentMessage, not both', { statusCode: 400 });
1461
+ }
1462
+ const sp = message.splitPayment || message.splitPaymentMessage;
1463
+ if (!sp.totalAmount || !sp.participants?.length) {
1464
+ throw new boom_1.Boom('splitPayment requires totalAmount and at least one participant', { statusCode: 400 });
1465
+ }
1466
+ m.splitPaymentMessage = WAProto_1.proto.Message.SplitPaymentMessage.fromObject({
1467
+ splitId: sp.splitId || (0, crypto_1.randomUUID)(),
1468
+ totalAmount: sp.totalAmount,
1469
+ description: sp.description || '',
1470
+ requesterJid: sp.requesterJid || options.userJid,
1471
+ participants: sp.participants.map(p => ({
1472
+ jid: p.jid,
1473
+ amount: p.amount,
1474
+ status: p.status ?? WAProto_1.proto.Message.SplitPaymentParticipant.SplitPaymentStatus.PENDING
1475
+ })),
1476
+ createdAtMs: sp.createdAtMs || Date.now(),
1477
+ contextInfo: sp.contextInfo
1478
+ });
1479
+ }
1480
+ else if ('p2pPaymentReminder' in message || 'p2PPaymentReminderNotification' in message) {
1481
+ if ('p2pPaymentReminder' in message && 'p2PPaymentReminderNotification' in message) {
1482
+ throw new boom_1.Boom('Use either p2pPaymentReminder or p2PPaymentReminderNotification, not both', {
1483
+ statusCode: 400
1484
+ });
1485
+ }
1486
+ const pr = message.p2pPaymentReminder || message.p2PPaymentReminderNotification;
1487
+ const freqEnum = WAProto_1.proto.Message.P2PPaymentReminderNotification.ReminderFrequency;
1488
+ const stateEnum = WAProto_1.proto.Message.P2PPaymentReminderNotification.ReminderState;
1489
+ const freqMap = {
1490
+ weekly: freqEnum.WEEKLY,
1491
+ biweekly: freqEnum.BIWEEKLY,
1492
+ monthly: freqEnum.MONTHLY,
1493
+ custom: freqEnum.CUSTOM
1494
+ };
1495
+ const stateMap = {
1496
+ active: stateEnum.ACTIVE,
1497
+ paused: stateEnum.PAUSED,
1498
+ stopped: stateEnum.STOPPED,
1499
+ expired: stateEnum.EXPIRED,
1500
+ cancelled: stateEnum.CANCELLED
1501
+ };
1502
+ m.p2PPaymentReminderNotification = WAProto_1.proto.Message.P2PPaymentReminderNotification.fromObject({
1503
+ reminderId: pr.reminderId || (0, crypto_1.randomUUID)(),
1504
+ amount: pr.amount,
1505
+ frequency: typeof pr.frequency === 'string'
1506
+ ? (freqMap[pr.frequency.toLowerCase()] ?? freqEnum.UNKNOWN_FREQUENCY)
1507
+ : (pr.frequency ?? freqEnum.UNKNOWN_FREQUENCY),
1508
+ nextReminderTimestamp: pr.nextReminderTimestamp,
1509
+ expiryTimestamp: pr.expiryTimestamp,
1510
+ state: typeof pr.state === 'string'
1511
+ ? (stateMap[pr.state.toLowerCase()] ?? stateEnum.ACTIVE)
1512
+ : (pr.state ?? stateEnum.ACTIVE),
1513
+ description: pr.description || '',
1514
+ creatorJid: pr.creatorJid || options.userJid,
1515
+ receiverJid: pr.receiverJid,
1516
+ upiId: pr.upiId,
1517
+ createdTimestamp: pr.createdTimestamp || Date.now()
1518
+ });
1519
+ }
1520
+ else if ('conditionalReveal' in message || 'conditionalRevealMessage' in message) {
1521
+ if ('conditionalReveal' in message && 'conditionalRevealMessage' in message) {
1522
+ throw new boom_1.Boom('Use either conditionalReveal or conditionalRevealMessage, not both', { statusCode: 400 });
1523
+ }
1524
+ const cr = message.conditionalReveal || message.conditionalRevealMessage;
1525
+ m.conditionalRevealMessage = WAProto_1.proto.Message.ConditionalRevealMessage.fromObject({
1526
+ conditionalRevealMessageType: WAProto_1.proto.Message.ConditionalRevealMessage.ConditionalRevealMessageType.SCHEDULED_MESSAGE,
1527
+ revealKeyId: cr.revealKeyId || (0, crypto_1.randomUUID)()
1528
+ });
1529
+ m.messageContextInfo = {
1530
+ messageSecret: cr.messageSecret || (0, crypto_1.randomBytes)(32)
1531
+ };
1532
+ }
1533
+ else if ('callLog' in message || 'callLogMessage' in message) {
1534
+ if ('callLog' in message && 'callLogMessage' in message) {
1535
+ throw new boom_1.Boom('Use either callLog or callLogMessage, not both', { statusCode: 400 });
1536
+ }
1537
+ const cl = message.callLog || message.callLogMessage;
1538
+ const outcomeEnum = WAProto_1.proto.Message.CallLogMessage.CallOutcome;
1539
+ const callTypeEnum = WAProto_1.proto.Message.CallLogMessage.CallType;
1540
+ const outcomeMap = {
1541
+ connected: outcomeEnum.CONNECTED,
1542
+ missed: outcomeEnum.MISSED,
1543
+ failed: outcomeEnum.FAILED,
1544
+ rejected: outcomeEnum.REJECTED,
1545
+ accepted_elsewhere: outcomeEnum.ACCEPTED_ELSEWHERE,
1546
+ ongoing: outcomeEnum.ONGOING,
1547
+ silenced_by_dnd: outcomeEnum.SILENCED_BY_DND,
1548
+ silenced_unknown_caller: outcomeEnum.SILENCED_UNKNOWN_CALLER
1549
+ };
1550
+ const callTypeMap = {
1551
+ regular: callTypeEnum.REGULAR,
1552
+ scheduled_call: callTypeEnum.SCHEDULED_CALL,
1553
+ voice_chat: callTypeEnum.VOICE_CHAT
1554
+ };
1555
+ m.callLogMesssage = WAProto_1.proto.Message.CallLogMessage.fromObject({
1556
+ isVideo: cl.isVideo ?? false,
1557
+ callOutcome: typeof cl.outcome === 'string'
1558
+ ? (outcomeMap[cl.outcome.toLowerCase()] ?? outcomeEnum.CONNECTED)
1559
+ : (cl.outcome ?? outcomeEnum.CONNECTED),
1560
+ durationSecs: cl.durationSecs || 0,
1561
+ callType: typeof cl.callType === 'string'
1562
+ ? (callTypeMap[cl.callType.toLowerCase()] ?? callTypeEnum.REGULAR)
1563
+ : (cl.callType ?? callTypeEnum.REGULAR),
1564
+ participants: (cl.participants || []).map(p => ({
1565
+ jid: p.jid,
1566
+ callOutcome: typeof p.outcome === 'string'
1567
+ ? (outcomeMap[p.outcome.toLowerCase()] ?? outcomeEnum.CONNECTED)
1568
+ : (p.outcome ?? p.callOutcome ?? outcomeEnum.CONNECTED)
1569
+ }))
1570
+ });
1571
+ }
1572
+ else if ('statusMention' in message || 'statusMentionMsg' in message) {
1573
+ const sm = message.statusMention || message.statusMentionMsg;
1574
+ if (!sm || typeof sm !== 'object') {
1575
+ throw new boom_1.Boom('statusMention must be an object with a message property', { statusCode: 400 });
1576
+ }
1577
+ m.statusMentionMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1578
+ message: sm.message || sm
1579
+ });
1580
+ }
1581
+ else if ('question' in message || 'questionMessage' in message) {
1582
+ const q = message.question || message.questionMessage;
1583
+ m.questionMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1584
+ message: q.message || (typeof q === 'object' && 'conversation' in q ? q : { conversation: String(q) })
1585
+ });
1586
+ }
1587
+ else if ('questionReply' in message || 'questionReplyMessage' in message) {
1588
+ const qr = message.questionReply || message.questionReplyMessage;
1589
+ m.questionReplyMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1590
+ message: qr.message || (typeof qr === 'object' && 'conversation' in qr ? qr : { conversation: String(qr) })
1591
+ });
1592
+ }
1593
+ else if ('statusAddYours' in message) {
1594
+ const say = message.statusAddYours;
1595
+ m.statusAddYours = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1596
+ message: say.message || say
1597
+ });
1598
+ }
1599
+ else if ('eventCoverImage' in message) {
1600
+ const eci = message.eventCoverImage;
1601
+ m.eventCoverImage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1602
+ message: eci.message || eci
1603
+ });
1604
+ }
1605
+ else if ('spoilerMessage' in message || 'spoiler' in message) {
1606
+ const sp = message.spoilerMessage || message.spoiler;
1607
+ m.spoilerMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1608
+ message: sp.message || sp
1609
+ });
1610
+ }
1611
+ else if ('lottieStickerMessage' in message || 'lottieSticker' in message) {
1612
+ const ls = message.lottieStickerMessage || message.lottieSticker;
1613
+ m.lottieStickerMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1614
+ message: ls.message || ls
1615
+ });
1616
+ }
1617
+ else if ('groupStatusV2' in message || 'groupStatusMessageV2' in message) {
1618
+ const gsv2 = message.groupStatusV2 || message.groupStatusMessageV2;
1619
+ m.groupStatusMessageV2 = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1620
+ message: gsv2.message || gsv2
1621
+ });
1622
+ }
1623
+ else if ('newsletterAdminProfile' in message || 'newsletterAdminProfileMessage' in message) {
1624
+ const nap = message.newsletterAdminProfile || message.newsletterAdminProfileMessage;
1625
+ m.newsletterAdminProfileMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1626
+ message: nap.message || nap
1627
+ });
1628
+ }
1629
+ else if ('newsletterAdminProfileV2' in message || 'newsletterAdminProfileMessageV2' in message) {
1630
+ const nap2 = message.newsletterAdminProfileV2 || message.newsletterAdminProfileMessageV2;
1631
+ m.newsletterAdminProfileMessageV2 = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1632
+ message: nap2.message || nap2
1633
+ });
1634
+ }
1635
+ else if ('botTask' in message || 'botTaskMessage' in message) {
1636
+ const bt = message.botTask || message.botTaskMessage;
1637
+ m.botTaskMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1638
+ message: bt.message || bt
1639
+ });
1640
+ }
1641
+ else if ('botInvoke' in message || 'botInvokeMessage' in message) {
1642
+ const bi = message.botInvoke || message.botInvokeMessage;
1643
+ m.botInvokeMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1644
+ message: bi.message || bi
1645
+ });
1646
+ }
1647
+ else if ('associatedChild' in message || 'associatedChildMessage' in message) {
1648
+ const ac = message.associatedChild || message.associatedChildMessage;
1649
+ m.associatedChildMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1650
+ message: ac.message || ac
1651
+ });
1652
+ }
1653
+ else if ('groupStatusMention' in message || 'groupStatusMentionMessage' in message) {
1654
+ const gsm = message.groupStatusMention || message.groupStatusMentionMessage;
1655
+ m.groupStatusMentionMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1656
+ message: gsm.message || gsm
1657
+ });
1658
+ }
1659
+ else if ('pollCreationOptionImage' in message || 'pollCreationOptionImageMessage' in message) {
1660
+ const pcoi = message.pollCreationOptionImage || message.pollCreationOptionImageMessage;
1661
+ m.pollCreationOptionImageMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1662
+ message: pcoi.message || pcoi
1663
+ });
1664
+ }
1665
+ else if ('newsletterAdminProfileStatus' in message || 'newsletterAdminProfileStatusMessage' in message) {
1666
+ const naps = message.newsletterAdminProfileStatus || message.newsletterAdminProfileStatusMessage;
1667
+ m.newsletterAdminProfileStatusMessage = WAProto_1.proto.Message.FutureProofMessage.fromObject({
1668
+ message: naps.message || naps
1669
+ });
1670
+ }
1671
+ else if ('placeholder' in message || 'placeholderMessage' in message) {
1672
+ const ph = message.placeholder || message.placeholderMessage;
1673
+ const phTypeEnum = WAProto_1.proto.Message.PlaceholderMessage.PlaceholderType;
1674
+ const phTypeMap = {
1675
+ e2e_reenable: phTypeEnum.PLACEHOLDER_MESSAGE_TYPE_E2E_REENABLE_MSG,
1676
+ linked_devices: phTypeEnum.PLACEHOLDER_MESSAGE_TYPE_LINKED_DEVICES_MESSAGE
1677
+ };
1678
+ m.placeholderMessage = WAProto_1.proto.Message.PlaceholderMessage.fromObject({
1679
+ type: typeof ph.type === 'string'
1680
+ ? (phTypeMap[ph.type.toLowerCase()] ?? phTypeEnum.PLACEHOLDER_MESSAGE_TYPE_E2E_REENABLE_MSG)
1681
+ : (ph.type ?? phTypeEnum.PLACEHOLDER_MESSAGE_TYPE_E2E_REENABLE_MSG)
1682
+ });
1683
+ }
1684
+ else if ('tapLink' in message || 'tapLinkMessage' in message) {
1685
+ const tl = message.tapLink || message.tapLinkMessage;
1686
+ const inner = {
1687
+ extendedTextMessage: {
1688
+ text: tl.text || tl.title || '',
1689
+ matchedText: tl.url || tl.tapUrl,
1690
+ title: tl.title || tl.text || '',
1691
+ contextInfo: {
1692
+ actionLink: {
1693
+ url: tl.url || tl.tapUrl || '',
1694
+ buttonTitle: tl.buttonTitle || 'Open'
1695
+ }
1696
+ }
1697
+ }
1698
+ };
1699
+ Object.assign(m, inner);
1700
+ }
1701
+ else if ('citation' in message) {
1702
+ const cit = message.citation;
1703
+ m.extendedTextMessage = {
1704
+ text: cit.text || cit.title || '',
1705
+ title: cit.title || '',
1706
+ description: cit.subtitle || cit.description || '',
1707
+ ...(cit.imageUrl ? { jpegThumbnail: undefined, previewType: 0 } : {})
1708
+ };
1709
+ }
1710
+ else if ('embeddedMusic' in message) {
1711
+ const em = message.embeddedMusic;
1712
+ m.extendedTextMessage = {
1713
+ text: em.text || `🎵 ${em.title || ''} — ${em.author || ''}`,
1714
+ title: em.title || '',
1715
+ description: em.author || em.artistAttribution || '',
1716
+ previewType: 0
1717
+ };
1718
+ }
1719
+ if ('keepInChat' in message || 'keepInChatMessage' in message) {
1720
+ const kic = message.keepInChat || message.keepInChatMessage;
1721
+ const keepTypeEnum = WAProto_1.proto.KeepType;
1722
+ const keepTypeMap = { keep: keepTypeEnum.KEEP_FOR_ALL, undo: keepTypeEnum.UNDO_KEEP_FOR_ALL };
1723
+ m.keepInChatMessage = WAProto_1.proto.Message.KeepInChatMessage.fromObject({
1724
+ key: kic.key || kic,
1725
+ keepType: typeof kic.keepType === 'string'
1726
+ ? (keepTypeMap[kic.keepType.toLowerCase()] ?? keepTypeEnum.KEEP_FOR_ALL)
1727
+ : (kic.keepType ?? keepTypeEnum.KEEP_FOR_ALL),
1728
+ timestampMs: kic.timestampMs || Date.now()
1729
+ });
1730
+ }
1731
+ if ('botFeedback' in message || 'botFeedbackMessage' in message) {
1732
+ const bf = message.botFeedback || message.botFeedbackMessage;
1733
+ const kindEnum = WAProto_1.proto.BotFeedbackMessage.BotFeedbackKind;
1734
+ const kindMap = {
1735
+ positive: kindEnum.BOT_FEEDBACK_POSITIVE,
1736
+ negative: kindEnum.BOT_FEEDBACK_NEGATIVE,
1737
+ negative_generic: kindEnum.BOT_FEEDBACK_NEGATIVE_GENERIC,
1738
+ negative_helpful: kindEnum.BOT_FEEDBACK_NEGATIVE_HELPFUL,
1739
+ negative_interesting: kindEnum.BOT_FEEDBACK_NEGATIVE_INTERESTING,
1740
+ negative_accurate: kindEnum.BOT_FEEDBACK_NEGATIVE_ACCURATE,
1741
+ negative_safe: kindEnum.BOT_FEEDBACK_NEGATIVE_SAFE,
1742
+ negative_other: kindEnum.BOT_FEEDBACK_NEGATIVE_OTHER
1743
+ };
1744
+ m.protocolMessage = {
1745
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.BOT_FEEDBACK_MESSAGE,
1746
+ key: bf.key,
1747
+ botFeedbackMessage: WAProto_1.proto.BotFeedbackMessage.fromObject({
1748
+ feedbackId: bf.feedbackId || bf.key?.id || '',
1749
+ kind: typeof bf.kind === 'string'
1750
+ ? (kindMap[bf.kind.toLowerCase()] ?? kindEnum.BOT_FEEDBACK_POSITIVE)
1751
+ : (bf.kind ?? kindEnum.BOT_FEEDBACK_POSITIVE)
1752
+ })
1753
+ };
1754
+ }
1755
+ if ('pollAddOption' in message || 'pollAddOptionMessage' in message) {
1756
+ const pao = message.pollAddOption || message.pollAddOptionMessage;
1757
+ if (!pao.pollCreationMessageKey && !pao.key) {
1758
+ throw new boom_1.Boom('pollAddOption requires a pollCreationMessageKey', { statusCode: 400 });
1759
+ }
1760
+ m.pollAddOptionMessage = WAProto_1.proto.Message.PollAddOptionMessage.fromObject({
1761
+ pollCreationMessageKey: pao.pollCreationMessageKey || pao.key,
1762
+ addOption: { optionName: pao.optionName || pao.option }
1763
+ });
1764
+ }
1765
+ if ('chatTheme' in message || 'chatThemeMessage' in message) {
1766
+ const ct = message.chatTheme || message.chatThemeMessage;
1767
+ const themeSetting = {
1768
+ settingTimestampMs: Date.now(),
1769
+ clearTheme: ct.clear ?? false,
1770
+ colorSchemeId: ct.colorSchemeId
1771
+ };
1772
+ if (ct.solidColor) {
1773
+ const sc = typeof ct.solidColor === 'object' ? ct.solidColor : {};
1774
+ themeSetting.solidColor = WAProto_1.proto.Message.ChatSolidColorWallpaper.fromObject({
1775
+ colorLight: sc.colorLight || sc.color || '#FFFFFF',
1776
+ colorDark: sc.colorDark || sc.color || '#000000',
1777
+ isDoodleEnabled: sc.isDoodleEnabled ?? false
1778
+ });
1779
+ }
1780
+ else if (ct.stockImage) {
1781
+ const si = typeof ct.stockImage === 'object' ? ct.stockImage : {};
1782
+ themeSetting.stockImage = WAProto_1.proto.Message.ChatStockImageWallpaper.fromObject({
1783
+ stockImageId: si.id || si.stockImageId || String(ct.stockImage),
1784
+ dimLevel: (si.dimLevel ?? si.opacity != null) ? (si.opacity ?? 100) / 100 : 0
1785
+ });
1786
+ }
1787
+ else if (ct.defaultWallpaper) {
1788
+ themeSetting.defaultWallpaper = WAProto_1.proto.Message.ChatDefaultWallpaper.fromObject({
1789
+ isDoodleEnabled: ct.defaultWallpaper.isDoodleEnabled ?? false
1790
+ });
1791
+ }
1792
+ else if (ct.customImage) {
1793
+ themeSetting.customImage = WAProto_1.proto.Message.ChatCustomImageWallpaper.fromObject({
1794
+ directPath: ct.customImage.directPath,
1795
+ mediaKey: ct.customImage.mediaKey,
1796
+ fileEncSha256: ct.customImage.fileEncSha256,
1797
+ fileSha256: ct.customImage.fileSha256,
1798
+ dimLevel: ct.customImage.dimLevel ?? 0
1799
+ });
1800
+ }
1801
+ m.protocolMessage = {
1802
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.CHAT_THEME_SETTING,
1803
+ chatThemeSetting: WAProto_1.proto.Message.ChatThemeSetting.fromObject(themeSetting)
1804
+ };
1805
+ }
1806
+ if ('stopGeneration' in message) {
1807
+ const sg = message.stopGeneration;
1808
+ m.protocolMessage = {
1809
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.STOP_GENERATION_MESSAGE,
1810
+ key: sg.key || sg
1811
+ };
1812
+ }
1813
+ if ('unscheduleMessage' in message) {
1814
+ const us = message.unscheduleMessage;
1815
+ m.protocolMessage = {
1816
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_UNSCHEDULE,
1817
+ key: us.key || us
1818
+ };
1819
+ }
1820
+ if ('bcall' in message || 'bcallMessage' in message) {
1821
+ const bc = message.bcall || message.bcallMessage;
1822
+ const mediaTypeEnum = WAProto_1.proto.Message.BCallMessage.MediaType;
1823
+ const mediaTypeMap = { audio: mediaTypeEnum.AUDIO, video: mediaTypeEnum.VIDEO };
1824
+ m.bcallMessage = WAProto_1.proto.Message.BCallMessage.fromObject({
1825
+ sessionId: bc.sessionId || (0, crypto_1.randomUUID)(),
1826
+ mediaType: typeof bc.mediaType === 'string'
1827
+ ? (mediaTypeMap[bc.mediaType.toLowerCase()] ?? mediaTypeEnum.AUDIO)
1828
+ : (bc.mediaType ?? mediaTypeEnum.AUDIO),
1829
+ masterKey: bc.masterKey || (0, crypto_1.randomBytes)(32),
1830
+ caption: bc.caption || ''
1831
+ });
1832
+ }
1833
+ if ('liveLocationUpdate' in message) {
1834
+ const llu = message.liveLocationUpdate;
1835
+ m.liveLocationMessage = WAProto_1.proto.Message.LiveLocationMessage.fromObject({
1836
+ degreesLatitude: llu.latitude,
1837
+ degreesLongitude: llu.longitude,
1838
+ accuracyInMeters: llu.accuracy,
1839
+ speedInMps: llu.speed,
1840
+ degreesClockwiseFromMagneticNorth: llu.heading,
1841
+ sequenceNumber: llu.sequence || 1,
1842
+ timeOffset: llu.timeOffset || 0,
1843
+ jpegThumbnail: llu.thumbnail
1844
+ });
1845
+ }
1846
+ if ('stopLiveLocation' in message) {
1847
+ const sll = message.stopLiveLocation;
1848
+ m.protocolMessage = {
1849
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE,
1850
+ key: sll.key || sll
1851
+ };
1852
+ }
1853
+ if ('carousel' in message || 'carouselMessage' in message) {
1854
+ const c = message.carousel || message.carouselMessage;
1855
+ if (!Array.isArray(c.cards) || !c.cards.length) {
1856
+ throw new boom_1.Boom('carousel requires at least one card', { statusCode: 400 });
1857
+ }
1858
+ const cardTypeEnum = WAProto_1.proto.Message.InteractiveMessage.CarouselMessage.CarouselCardType;
1859
+ const cardTypeMap = {
1860
+ horizontal: cardTypeEnum.HSCROLL_CARDS,
1861
+ album: cardTypeEnum.ALBUM_IMAGE,
1862
+ hscroll: cardTypeEnum.HSCROLL_CARDS
1863
+ };
1864
+ m.interactiveMessage = {
1865
+ carouselMessage: WAProto_1.proto.Message.InteractiveMessage.CarouselMessage.fromObject({
1866
+ cards: c.cards.map(card => card.interactiveMessage || card),
1867
+ messageVersion: c.messageVersion || 1,
1868
+ carouselCardType: typeof c.cardType === 'string'
1869
+ ? (cardTypeMap[c.cardType.toLowerCase()] ?? cardTypeEnum.HSCROLL_CARDS)
1870
+ : (c.carouselCardType ?? cardTypeEnum.HSCROLL_CARDS)
1871
+ })
1872
+ };
1873
+ }
1874
+ if ('aiMediaCollection' in message || 'aiMediaCollectionMessage' in message) {
1875
+ const amc = message.aiMediaCollection || message.aiMediaCollectionMessage;
1876
+ m.protocolMessage = {
1877
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.AI_MEDIA_COLLECTION_MESSAGE,
1878
+ aiMediaCollectionMessage: WAProto_1.proto.AIMediaCollectionMessage.fromObject({
1879
+ collectionId: amc.collectionId || (0, crypto_1.randomUUID)(),
1880
+ expectedMediaCount: amc.expectedMediaCount || amc.count || 1,
1881
+ hasGlobalCaption: amc.hasGlobalCaption ?? false
1882
+ })
1883
+ };
1884
+ }
1885
+ if ('botCapabilities' in message && Array.isArray(message.botCapabilities) && message.botCapabilities.length) {
1886
+ const capEnum = WAProto_1.proto.BotCapabilityMetadata.BotCapabilityType;
1887
+ const capStrMap = Object.fromEntries(Object.entries(capEnum).map(([k, v]) => [k.toLowerCase(), v]));
1888
+ const caps = message.botCapabilities
1889
+ .map(c => (typeof c === 'string' ? (capStrMap[c.toLowerCase()] ?? capEnum.UNKNOWN) : c))
1890
+ .filter(c => typeof c === 'number' && c !== capEnum.UNKNOWN);
1891
+ m.messageContextInfo = m.messageContextInfo || {};
1892
+ m.messageContextInfo.botMetadata = WAProto_1.proto.BotMetadata.fromObject({
1893
+ capabilityMetadata: { capabilities: caps }
1894
+ });
1895
+ }
1896
+ if ('botThreadInfo' in message && message.botThreadInfo) {
1897
+ const bt = message.botThreadInfo;
1898
+ const threadTypeEnum = WAProto_1.proto.AIThreadInfo.AIThreadClientInfo.AIThreadType;
1899
+ const threadTypeMap = Object.fromEntries(Object.entries(threadTypeEnum).map(([k, v]) => [k.toLowerCase(), v]));
1900
+ const existing = m.messageContextInfo?.botMetadata
1901
+ ? WAProto_1.proto.BotMetadata.toObject(m.messageContextInfo.botMetadata)
1902
+ : {};
1903
+ m.messageContextInfo = m.messageContextInfo || {};
1904
+ m.messageContextInfo.botMetadata = WAProto_1.proto.BotMetadata.fromObject({
1905
+ ...existing,
1906
+ botThreadInfo: {
1907
+ clientInfo: {
1908
+ type: typeof bt.type === 'string'
1909
+ ? (threadTypeMap[bt.type.toLowerCase()] ?? threadTypeEnum.UNKNOWN)
1910
+ : (bt.type ?? threadTypeEnum.UNKNOWN),
1911
+ sourceChatJid: bt.sourceChatJid || ''
1912
+ }
1913
+ }
1914
+ });
1915
+ }
1916
+ if ('messageAssociation' in message && message.messageAssociation) {
1917
+ const ma = message.messageAssociation;
1918
+ const assocTypeEnum = WAProto_1.proto.MessageAssociation.AssociationType;
1919
+ const assocTypeMap = Object.fromEntries(Object.entries(assocTypeEnum).map(([k, v]) => [k.toLowerCase(), v]));
1920
+ m.messageContextInfo = m.messageContextInfo || {};
1921
+ m.messageContextInfo.messageAssociation = WAProto_1.proto.MessageAssociation.fromObject({
1922
+ associationType: typeof ma.type === 'string'
1923
+ ? (assocTypeMap[ma.type.toLowerCase()] ?? assocTypeEnum.UNKNOWN)
1924
+ : (ma.associationType ?? ma.type ?? assocTypeEnum.UNKNOWN),
1925
+ parentMessageKey: ma.parentMessageKey || ma.parentKey,
1926
+ messageIndex: ma.messageIndex || 0
1927
+ });
1928
+ }
1929
+ if ('threadId' in message && message.threadId) {
1930
+ const tid = message.threadId;
1931
+ const threadTypeEnum = WAProto_1.proto.ThreadID.ThreadType;
1932
+ m.messageContextInfo = m.messageContextInfo || {};
1933
+ m.messageContextInfo.threadId = [
1934
+ WAProto_1.proto.ThreadID.fromObject({
1935
+ threadType: tid.type === 'ai'
1936
+ ? threadTypeEnum.AI_THREAD
1937
+ : tid.type === 'replies'
1938
+ ? threadTypeEnum.VIEW_REPLIES
1939
+ : (tid.threadType ?? threadTypeEnum.UNKNOWN),
1940
+ threadKey: tid.key || tid.threadKey
1941
+ })
1942
+ ];
1943
+ }
1944
+ if ('featureEligibilities' in message && message.featureEligibilities) {
1945
+ const fe = message.featureEligibilities;
1946
+ const [msgType] = Object.keys(m);
1947
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
1948
+ m[msgType].contextInfo = {
1949
+ ...(m[msgType].contextInfo || {}),
1950
+ featureEligibilities: {
1951
+ cannotBeReactedTo: fe.cannotBeReactedTo ?? false,
1952
+ cannotBeRanked: fe.cannotBeRanked ?? false,
1953
+ canRequestFeedback: fe.canRequestFeedback ?? false,
1954
+ canBeReshared: fe.canBeReshared ?? true,
1955
+ canReceiveMultiReact: fe.canReceiveMultiReact ?? true
1956
+ }
1957
+ };
1958
+ }
1959
+ }
1960
+ if ('forwardOrigin' in message) {
1961
+ const [msgType] = Object.keys(m);
1962
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
1963
+ const foEnum = WAProto_1.proto.ContextInfo.ForwardOrigin;
1964
+ const foMap = {
1965
+ chat: foEnum.CHAT,
1966
+ status: foEnum.STATUS,
1967
+ channels: foEnum.CHANNELS,
1968
+ meta_ai: foEnum.META_AI,
1969
+ ugc: foEnum.UGC
1970
+ };
1971
+ m[msgType].contextInfo = {
1972
+ ...(m[msgType].contextInfo || {}),
1973
+ forwardOrigin: typeof message.forwardOrigin === 'string'
1974
+ ? (foMap[message.forwardOrigin.toLowerCase()] ?? foEnum.CHAT)
1975
+ : (message.forwardOrigin ?? foEnum.CHAT)
1976
+ };
1977
+ }
1978
+ }
1979
+ if ('statusAudienceMetadata' in message && message.statusAudienceMetadata) {
1980
+ const [msgType] = Object.keys(m);
1981
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
1982
+ const audType = WAProto_1.proto.ContextInfo.StatusAudienceMetadata.AudienceType;
1983
+ const sam = message.statusAudienceMetadata;
1984
+ m[msgType].contextInfo = {
1985
+ ...(m[msgType].contextInfo || {}),
1986
+ statusAudienceMetadata: {
1987
+ audienceType: sam.closeFriends ? audType.CLOSE_FRIENDS : audType.UNKNOWN,
1988
+ listName: sam.listName,
1989
+ listEmoji: sam.listEmoji
1990
+ }
1991
+ };
1992
+ }
1993
+ }
1994
+ if ('aiGenerated' in message && message.aiGenerated === true) {
1995
+ if (m.videoMessage) {
1996
+ m.videoMessage.videoSourceType = WAProto_1.proto.Message.VideoMessage.VideoSourceType.AI_GENERATED;
1997
+ }
1998
+ if (m.imageMessage) {
1999
+ m.imageMessage.imageSourceType = WAProto_1.proto.Message.ImageMessage.ImageSourceType.AI_GENERATED;
2000
+ }
2001
+ }
2002
+ if ('aiModified' in message && message.aiModified === true) {
2003
+ if (m.imageMessage) {
2004
+ m.imageMessage.imageSourceType = WAProto_1.proto.Message.ImageMessage.ImageSourceType.AI_MODIFIED;
2005
+ }
2006
+ }
2007
+ if ('imageSourceType' in message) {
2008
+ if (m.imageMessage) {
2009
+ const istEnum = WAProto_1.proto.Message.ImageMessage.ImageSourceType;
2010
+ const istMap = {
2011
+ user: istEnum.USER_IMAGE,
2012
+ ai_generated: istEnum.AI_GENERATED,
2013
+ ai_modified: istEnum.AI_MODIFIED,
2014
+ rasterized: istEnum.RASTERIZED_TEXT_STATUS
2015
+ };
2016
+ m.imageMessage.imageSourceType =
2017
+ typeof message.imageSourceType === 'string'
2018
+ ? (istMap[message.imageSourceType.toLowerCase()] ?? istEnum.USER_IMAGE)
2019
+ : (message.imageSourceType ?? istEnum.USER_IMAGE);
2020
+ }
2021
+ }
2022
+ if ('qrUrl' in message && message.qrUrl && m.imageMessage) {
2023
+ m.imageMessage.qrUrl = message.qrUrl;
2024
+ }
2025
+ if ('videoContentUrl' in message && message.videoContentUrl && m.extendedTextMessage) {
2026
+ m.extendedTextMessage.videoContentUrl = message.videoContentUrl;
2027
+ }
2028
+ if ('endCardTiles' in message && Array.isArray(message.endCardTiles) && m.extendedTextMessage) {
2029
+ m.extendedTextMessage.endCardTiles = message.endCardTiles.map(tile => WAProto_1.proto.Message.VideoEndCard.fromObject({
2030
+ username: tile.username || tile.user,
2031
+ caption: tile.caption || tile.text,
2032
+ thumbnailImageUrl: tile.thumbnailUrl || tile.thumbnail,
2033
+ profilePictureUrl: tile.profilePictureUrl || tile.avatar
2034
+ }));
2035
+ }
2036
+ if ('musicMetadata' in message && message.musicMetadata && m.extendedTextMessage) {
2037
+ const mm = message.musicMetadata;
2038
+ m.extendedTextMessage.musicMetadata = WAProto_1.proto.EmbeddedMusic.fromObject({
2039
+ songId: mm.songId,
2040
+ author: mm.author || mm.artist,
2041
+ title: mm.title,
2042
+ artistAttribution: mm.artistAttribution,
2043
+ isExplicit: mm.isExplicit ?? false,
2044
+ musicSongStartTimeInMs: mm.startTimeMs || 0,
2045
+ derivedContentStartTimeInMs: mm.derivedStartTimeMs || 0,
2046
+ overlapDurationInMs: mm.overlapDurationMs || 0
2047
+ });
2048
+ }
2049
+ if ('businessInteractionPills' in message && message.businessInteractionPills) {
2050
+ const bip = message.businessInteractionPills;
2051
+ const pillTypeEnum = WAProto_1.proto.ContextInfo.BusinessInteractionPills.PillType;
2052
+ const entryEnum = WAProto_1.proto.ContextInfo.BusinessInteractionPills.EntryPoint;
2053
+ const pillMap = Object.fromEntries(Object.entries(pillTypeEnum).map(([k, v]) => [k.toLowerCase(), v]));
2054
+ const entryMap = Object.fromEntries(Object.entries(entryEnum).map(([k, v]) => [k.toLowerCase(), v]));
2055
+ const [msgType] = Object.keys(m);
2056
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2057
+ m[msgType].contextInfo = {
2058
+ ...(m[msgType].contextInfo || {}),
2059
+ businessInteractionPills: WAProto_1.proto.ContextInfo.BusinessInteractionPills.fromObject({
2060
+ businessJid: bip.businessJid,
2061
+ entryPoint: typeof bip.entryPoint === 'string'
2062
+ ? (entryMap[bip.entryPoint.toLowerCase()] ?? entryEnum.ENTRY_POINT_UNKNOWN)
2063
+ : bip.entryPoint,
2064
+ pills: (bip.pills || []).map(p => ({
2065
+ pillType: typeof p.type === 'string'
2066
+ ? (pillMap[p.type.toLowerCase()] ?? pillTypeEnum.UNKNOWN)
2067
+ : (p.pillType ?? pillTypeEnum.UNKNOWN),
2068
+ actionUrl: p.url || p.actionUrl
2069
+ }))
2070
+ })
2071
+ };
2072
+ }
2073
+ }
2074
+ if ('dataSharingContext' in message && message.dataSharingContext) {
2075
+ const dsc = message.dataSharingContext;
2076
+ const [msgType] = Object.keys(m);
2077
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2078
+ m[msgType].contextInfo = {
2079
+ ...(m[msgType].contextInfo || {}),
2080
+ dataSharingContext: WAProto_1.proto.ContextInfo.DataSharingContext.fromObject({
2081
+ showMmDisclosure: dsc.showMmDisclosure ?? false,
2082
+ encryptedSignalTokenConsented: dsc.encryptedToken,
2083
+ dataSharingFlags: dsc.flags || 0
2084
+ })
2085
+ };
2086
+ }
2087
+ }
2088
+ if ('botSession' in message && message.botSession) {
2089
+ const bs = message.botSession;
2090
+ const srcEnum = WAProto_1.proto.BotSessionSource;
2091
+ const srcMap = Object.fromEntries(Object.entries(srcEnum).map(([k, v]) => [k.toLowerCase(), v]));
2092
+ m.messageContextInfo = m.messageContextInfo || {};
2093
+ const existing = m.messageContextInfo.botMetadata
2094
+ ? WAProto_1.proto.BotMetadata.toObject(m.messageContextInfo.botMetadata)
2095
+ : {};
2096
+ m.messageContextInfo.botMetadata = WAProto_1.proto.BotMetadata.fromObject({
2097
+ ...existing,
2098
+ sessionMetadata: {
2099
+ sessionId: bs.sessionId,
2100
+ sessionSource: typeof bs.source === 'string'
2101
+ ? (srcMap[bs.source.toLowerCase()] ?? srcEnum.NONE)
2102
+ : (bs.sessionSource ?? srcEnum.NONE)
2103
+ }
2104
+ });
2105
+ }
2106
+ if ('botReminder' in message && message.botReminder) {
2107
+ const br = message.botReminder;
2108
+ const actionEnum = WAProto_1.proto.BotReminderMetadata.ReminderAction;
2109
+ const freqEnum = WAProto_1.proto.BotReminderMetadata.ReminderFrequency;
2110
+ const actionMap = {
2111
+ notify: actionEnum.NOTIFY,
2112
+ create: actionEnum.CREATE,
2113
+ delete: actionEnum.DELETE,
2114
+ update: actionEnum.UPDATE
2115
+ };
2116
+ const freqMap = {
2117
+ once: freqEnum.ONCE,
2118
+ daily: freqEnum.DAILY,
2119
+ weekly: freqEnum.WEEKLY,
2120
+ biweekly: freqEnum.BIWEEKLY,
2121
+ monthly: freqEnum.MONTHLY
2122
+ };
2123
+ m.messageContextInfo = m.messageContextInfo || {};
2124
+ const existing = m.messageContextInfo.botMetadata
2125
+ ? WAProto_1.proto.BotMetadata.toObject(m.messageContextInfo.botMetadata)
2126
+ : {};
2127
+ m.messageContextInfo.botMetadata = WAProto_1.proto.BotMetadata.fromObject({
2128
+ ...existing,
2129
+ reminderMetadata: {
2130
+ requestMessageKey: br.requestMessageKey || br.key,
2131
+ action: typeof br.action === 'string'
2132
+ ? (actionMap[br.action.toLowerCase()] ?? actionEnum.NOTIFY)
2133
+ : (br.action ?? actionEnum.NOTIFY),
2134
+ name: br.name,
2135
+ nextTriggerTimestamp: br.nextTriggerTimestamp || br.timestamp,
2136
+ frequency: typeof br.frequency === 'string'
2137
+ ? (freqMap[br.frequency.toLowerCase()] ?? freqEnum.ONCE)
2138
+ : (br.frequency ?? freqEnum.ONCE)
2139
+ }
2140
+ });
2141
+ }
2142
+ if ('botPlugin' in message && message.botPlugin) {
2143
+ const bp = message.botPlugin;
2144
+ const ptEnum = WAProto_1.proto.BotPluginMetadata.PluginType;
2145
+ const spEnum = WAProto_1.proto.BotPluginMetadata.SearchProvider;
2146
+ const ptMap = { reels: ptEnum.REELS, search: ptEnum.SEARCH };
2147
+ const spMap = { bing: spEnum.BING, google: spEnum.GOOGLE, support: spEnum.SUPPORT };
2148
+ m.messageContextInfo = m.messageContextInfo || {};
2149
+ const existing = m.messageContextInfo.botMetadata
2150
+ ? WAProto_1.proto.BotMetadata.toObject(m.messageContextInfo.botMetadata)
2151
+ : {};
2152
+ m.messageContextInfo.botMetadata = WAProto_1.proto.BotMetadata.fromObject({
2153
+ ...existing,
2154
+ pluginMetadata: WAProto_1.proto.BotPluginMetadata.fromObject({
2155
+ provider: typeof bp.provider === 'string'
2156
+ ? (spMap[bp.provider.toLowerCase()] ?? spEnum.UNKNOWN)
2157
+ : (bp.provider ?? spEnum.UNKNOWN),
2158
+ pluginType: typeof bp.pluginType === 'string'
2159
+ ? (ptMap[bp.pluginType.toLowerCase()] ?? ptEnum.UNKNOWN_PLUGIN)
2160
+ : (bp.pluginType ?? ptEnum.UNKNOWN_PLUGIN),
2161
+ searchProviderUrl: bp.searchProviderUrl,
2162
+ searchQuery: bp.searchQuery,
2163
+ thumbnailCdnUrl: bp.thumbnailCdnUrl,
2164
+ profilePhotoCdnUrl: bp.profilePhotoCdnUrl,
2165
+ expectedLinksCount: bp.expectedLinksCount || 0,
2166
+ referenceIndex: bp.referenceIndex || 0
2167
+ })
2168
+ });
2169
+ }
2170
+ if ('isSpoiler' in message && message.isSpoiler === true) {
2171
+ const [msgType] = Object.keys(m);
2172
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2173
+ m[msgType].contextInfo = {
2174
+ ...(m[msgType].contextInfo || {}),
2175
+ isSpoiler: true
2176
+ };
2177
+ }
2178
+ }
2179
+ if ('expiration' in message && typeof message.expiration === 'number') {
2180
+ const [msgType] = Object.keys(m);
2181
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2182
+ m[msgType].contextInfo = {
2183
+ ...(m[msgType].contextInfo || {}),
2184
+ expiration: message.expiration
2185
+ };
2186
+ }
2187
+ }
2188
+ if ('ephemeralSettingTimestamp' in message) {
2189
+ const [msgType] = Object.keys(m);
2190
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2191
+ m[msgType].contextInfo = {
2192
+ ...(m[msgType].contextInfo || {}),
2193
+ ephemeralSettingTimestamp: message.ephemeralSettingTimestamp
2194
+ };
2195
+ }
2196
+ }
2197
+ if ('groupSubject' in message && message.groupSubject) {
2198
+ const [msgType] = Object.keys(m);
2199
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2200
+ m[msgType].contextInfo = {
2201
+ ...(m[msgType].contextInfo || {}),
2202
+ groupSubject: message.groupSubject
2203
+ };
2204
+ }
2205
+ }
2206
+ if ('parentGroupJid' in message && message.parentGroupJid) {
2207
+ const [msgType] = Object.keys(m);
2208
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2209
+ m[msgType].contextInfo = {
2210
+ ...(m[msgType].contextInfo || {}),
2211
+ parentGroupJid: message.parentGroupJid
2212
+ };
2213
+ }
2214
+ }
2215
+ if ('memberLabel' in message && message.memberLabel) {
2216
+ const [msgType] = Object.keys(m);
2217
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2218
+ m[msgType].contextInfo = {
2219
+ ...(m[msgType].contextInfo || {}),
2220
+ memberLabel: message.memberLabel
2221
+ };
2222
+ }
2223
+ }
2224
+ if ('trustBanner' in message && message.trustBanner) {
2225
+ const tb = message.trustBanner;
2226
+ const [msgType] = Object.keys(m);
2227
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2228
+ m[msgType].contextInfo = {
2229
+ ...(m[msgType].contextInfo || {}),
2230
+ ...(tb.type != null ? { trustBannerType: tb.type } : {}),
2231
+ ...(tb.action != null ? { trustBannerAction: tb.action } : {})
2232
+ };
2233
+ }
2234
+ }
2235
+ if ('entryPoint' in message && message.entryPoint) {
2236
+ const ep = message.entryPoint;
2237
+ const [msgType] = Object.keys(m);
2238
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2239
+ m[msgType].contextInfo = {
2240
+ ...(m[msgType].contextInfo || {}),
2241
+ ...(ep.source ? { entryPointConversionSource: ep.source } : {}),
2242
+ ...(ep.app ? { entryPointConversionApp: ep.app } : {}),
2243
+ ...(ep.delaySecs != null ? { entryPointConversionDelaySeconds: ep.delaySecs } : {}),
2244
+ ...(ep.externalSource ? { entryPointConversionExternalSource: ep.externalSource } : {}),
2245
+ ...(ep.externalMedium ? { entryPointConversionExternalMedium: ep.externalMedium } : {})
2246
+ };
2247
+ }
2248
+ }
2249
+ if ('utm' in message && message.utm) {
2250
+ const [msgType] = Object.keys(m);
2251
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2252
+ m[msgType].contextInfo = {
2253
+ ...(m[msgType].contextInfo || {}),
2254
+ utm: WAProto_1.proto.ContextInfo.UTMInfo.fromObject({
2255
+ utmSource: message.utm.source,
2256
+ utmCampaign: message.utm.campaign
2257
+ })
2258
+ };
2259
+ }
2260
+ }
2261
+ if ('partiallySelectedContent' in message && message.partiallySelectedContent) {
2262
+ const [msgType] = Object.keys(m);
2263
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2264
+ m[msgType].contextInfo = {
2265
+ ...(m[msgType].contextInfo || {}),
2266
+ partiallySelectedContent: message.partiallySelectedContent
2267
+ };
2268
+ }
2269
+ }
2270
+ if ('crossAppSource' in message && message.crossAppSource) {
2271
+ const [msgType] = Object.keys(m);
2272
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2273
+ m[msgType].contextInfo = {
2274
+ ...(m[msgType].contextInfo || {}),
2275
+ crossAppSource: message.crossAppSource
2276
+ };
2277
+ }
2278
+ }
2279
+ if ('isQuestion' in message && message.isQuestion === true) {
2280
+ const [msgType] = Object.keys(m);
2281
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2282
+ m[msgType].contextInfo = {
2283
+ ...(m[msgType].contextInfo || {}),
2284
+ isQuestion: true
2285
+ };
2286
+ }
2287
+ }
2288
+ if ('afterReadDuration' in message && typeof message.afterReadDuration === 'number') {
2289
+ const [msgType] = Object.keys(m);
2290
+ if (msgType && m[msgType] && typeof m[msgType] === 'object') {
2291
+ m[msgType].contextInfo = {
2292
+ ...(m[msgType].contextInfo || {}),
2293
+ afterReadDuration: message.afterReadDuration
2294
+ };
2295
+ }
2296
+ m.messageContextInfo = {
2297
+ ...(m.messageContextInfo || {}),
2298
+ messageAddOnDurationInSecs: message.afterReadDuration,
2299
+ messageAddOnExpiryType: index_js_1.proto.MessageContextInfo.MessageAddonExpiryType.DEPENDENT_ON_PARENT
2300
+ };
2301
+ }
2302
+ if ('raw' in message && !!message.raw) {
2303
+ const { raw: _, externalAdReply: _ear, ...rawMsg } = message;
2304
+ if ('externalAdReply' in message && !!message.externalAdReply) {
2305
+ const ear = normalizeEarFields(message.externalAdReply);
2306
+ const [rawType] = Object.keys(rawMsg);
2307
+ if (rawType && rawMsg[rawType]) {
2308
+ rawMsg[rawType].contextInfo = {
2309
+ ...(rawMsg[rawType].contextInfo || {}),
2310
+ externalAdReply: ear
2311
+ };
2312
+ }
2313
+ }
2314
+ return WAProto_1.proto.Message.fromObject(rawMsg);
2315
+ }
2316
+ else if (Object.keys(m).length === 0) {
2317
+ m = await (0, exports.prepareWAMessageMedia)(message, options);
2318
+ }
2319
+ if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
2320
+ const viewOnceVersion = message.viewOnceVersion || message.viewOnce;
2321
+ if (viewOnceVersion === 'v2' || viewOnceVersion === 2) {
2322
+ m = { viewOnceMessageV2: { message: m } };
2323
+ }
2324
+ else if (viewOnceVersion === 'v2ext' || viewOnceVersion === 'v2extension') {
2325
+ m = { viewOnceMessageV2Extension: { message: m } };
2326
+ }
2327
+ else {
2328
+ m = { viewOnceMessage: { message: m } };
2329
+ }
2330
+ }
2331
+ if (hasOptionalProperty(message, 'documentWithCaption') && !!message.documentWithCaption) {
2332
+ m = { documentWithCaptionMessage: { message: m } };
2333
+ }
2334
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
2335
+ m = { ephemeralMessage: { message: m } };
2336
+ }
2337
+ if (hasOptionalProperty(message, 'groupMentioned') && !!message.groupMentioned) {
2338
+ m = { groupMentionedMessage: { message: m } };
2339
+ }
2340
+ if ('groupStatus' in message && !!message.groupStatus) {
2341
+ m = { groupStatusMessage: { message: m } };
2342
+ }
2343
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
2344
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
2345
+ const normalizedMentions = await (0, jid_display_normalization_1.normalizeMentionedJidsForSend)(message.mentions, options.groupData, options.signalRepository, options.logger);
2346
+ const messageType = Object.keys(m)[0];
2347
+ const key = m[messageType];
2348
+ if (key && 'contextInfo' in key) {
2349
+ key.contextInfo = key.contextInfo || {};
2350
+ if (normalizedMentions?.length) {
2351
+ key.contextInfo.mentionedJid = normalizedMentions;
2352
+ }
2353
+ if (message.mentionAll) {
2354
+ key.contextInfo.nonJidMentions = 1;
2355
+ }
2356
+ else if (!key) {
2357
+ key.contextInfo = {
2358
+ mentionedJid: normalizedMentions,
2359
+ nonJidMentions: message.mentionAll ? 1 : 0
2360
+ };
2361
+ }
2362
+ }
2363
+ }
2364
+ if (hasOptionalProperty(message, 'edit')) {
2365
+ m = {
2366
+ protocolMessage: {
2367
+ key: message.edit,
2368
+ editedMessage: m,
2369
+ timestampMs: Date.now(),
2370
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT
2371
+ }
2372
+ };
2373
+ }
2374
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
2375
+ const messageType = Object.keys(m)[0];
2376
+ const key = m[messageType];
2377
+ if ('contextInfo' in key && !!key.contextInfo) {
2378
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
2379
+ }
2380
+ else if (key) {
2381
+ key.contextInfo = message.contextInfo;
2382
+ }
2383
+ }
2384
+ if ((0, reporting_utils_1.shouldIncludeReportingToken)(m) && !(0, WABinary_1.isInteropUser)(options.jid)) {
2385
+ m.messageContextInfo = m.messageContextInfo || {};
2386
+ if (!m.messageContextInfo.messageSecret) {
2387
+ m.messageContextInfo.messageSecret = (0, crypto_1.randomBytes)(32);
2388
+ }
2389
+ }
2390
+ if ('externalAdReply' in message && !!message.externalAdReply) {
2391
+ const wrappers = [
2392
+ 'viewOnceMessage',
2393
+ 'viewOnceMessageV2',
2394
+ 'viewOnceMessageV2Extension',
2395
+ 'ephemeralMessage',
2396
+ 'groupStatusMessage',
2397
+ 'templateMessage'
2398
+ ];
2399
+ const [outerType] = Object.keys(m);
2400
+ const inner = wrappers.includes(outerType) ? m[outerType].message : m;
2401
+ const [innerType] = Object.keys(inner);
2402
+ const innerPayload = innerType ? inner[innerType] : undefined;
2403
+ if (innerType && innerType !== 'carouselMessage' && innerPayload && typeof innerPayload === 'object') {
2404
+ const ear = normalizeEarFields(message.externalAdReply);
2405
+ innerPayload.contextInfo = {
2406
+ ...(innerPayload.contextInfo || {}),
2407
+ externalAdReply: ear
2408
+ };
2409
+ }
2410
+ }
2411
+ if ('secureMetaServiceLabel' in message && !!message.secureMetaServiceLabel) {
2412
+ const [messageType] = Object.keys(m);
2413
+ m[messageType] = m[messageType] || {};
2414
+ m[messageType].contextInfo = {
2415
+ ...(m[messageType].contextInfo || {}),
2416
+ secureMetaServiceLabel: 1
2417
+ };
2418
+ }
2419
+ return WAProto_1.proto.Message.create(m);
2420
+ };
2421
+ exports.generateWAMessageContent = generateWAMessageContent;
2422
+ const generateWAMessageFromContent = (jid, message, options) => {
2423
+ if (!options.timestamp) {
2424
+ options.timestamp = new Date();
2425
+ }
2426
+ const innerMessage = (0, exports.normalizeMessageContent)(message);
2427
+ const key = (0, exports.getContentType)(innerMessage);
2428
+ const timestamp = (0, generics_1.unixTimestampSeconds)(options.timestamp);
2429
+ const { quoted, userJid } = options;
2430
+ if (quoted && !(0, WABinary_1.isJidNewsletter)(jid)) {
2431
+ const participant = quoted.key.fromMe
2432
+ ? userJid
2433
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
2434
+ let quotedMsg = (0, exports.normalizeMessageContent)(quoted.message);
2435
+ const msgType = (0, exports.getContentType)(quotedMsg);
2436
+ quotedMsg = index_js_1.proto.Message.create({ [msgType]: quotedMsg[msgType] });
2437
+ const quotedContent = quotedMsg[msgType];
2438
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
2439
+ delete quotedContent.contextInfo;
2440
+ }
2441
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
2442
+ contextInfo.participant = (0, WABinary_1.jidNormalizedUser)(participant);
2443
+ contextInfo.stanzaId = quoted.key.id;
2444
+ contextInfo.quotedMessage = quotedMsg;
2445
+ if (jid !== quoted.key.remoteJid) {
2446
+ contextInfo.remoteJid = quoted.key.remoteJid;
2447
+ }
2448
+ if (contextInfo && innerMessage[key]) {
2449
+ innerMessage[key].contextInfo = contextInfo;
2450
+ }
2451
+ }
2452
+ if (!!options.ephemeralExpiration &&
2453
+ key !== 'protocolMessage' &&
2454
+ key !== 'ephemeralMessage' &&
2455
+ !(0, WABinary_1.isJidNewsletter)(jid)) {
2456
+ innerMessage[key].contextInfo = {
2457
+ ...(innerMessage[key].contextInfo || {}),
2458
+ expiration: options.ephemeralExpiration || Defaults_1.WA_DEFAULT_EPHEMERAL
2459
+ };
2460
+ }
2461
+ message = WAProto_1.proto.Message.create(message);
2462
+ const iosBros = options?.browser?.[0] === 'iOS' || options?.browser?.[1] === 'Safari';
2463
+ const androidBros = options?.browser?.[0] === 'Android';
2464
+ const pickedMessageId = options?.messageId ||
2465
+ (iosBros
2466
+ ? (0, generics_1.generateIOSMessageID)()
2467
+ : androidBros
2468
+ ? (0, generics_1.generateAndroMessageID)()
2469
+ : (0, generics_1.generateMessageIDV2)(userJid));
2470
+ const messageJSON = {
2471
+ key: {
2472
+ remoteJid: jid,
2473
+ fromMe: true,
2474
+ id: pickedMessageId
2475
+ },
2476
+ message: message,
2477
+ messageTimestamp: timestamp,
2478
+ messageStubParameters: [],
2479
+ participant: (0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidStatusBroadcast)(jid) ? userJid : undefined,
2480
+ status: Types_1.WAMessageStatus.PENDING
2481
+ };
2482
+ return WAProto_1.proto.WebMessageInfo.fromObject(messageJSON);
2483
+ };
2484
+ exports.generateWAMessageFromContent = generateWAMessageFromContent;
2485
+ const generateWAMessage = async (jid, content, options) => {
2486
+ options.logger = options?.logger?.child({ msgId: options.messageId });
2487
+ return (0, exports.generateWAMessageFromContent)(jid, await (0, exports.generateWAMessageContent)(content, { ...options, jid }), options);
2488
+ };
2489
+ exports.generateWAMessage = generateWAMessage;
2490
+ const getContentType = content => {
2491
+ if (content) {
2492
+ const keys = Object.keys(content);
2493
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
2494
+ return key;
2495
+ }
2496
+ };
2497
+ exports.getContentType = getContentType;
2498
+ const normalizeMessageContent = content => {
2499
+ if (!content) {
2500
+ return undefined;
2501
+ }
2502
+ for (let i = 0; i < 5; i++) {
2503
+ const inner = getFutureProofMessage(content);
2504
+ if (!inner) {
2505
+ break;
2506
+ }
2507
+ content = inner.message;
2508
+ }
2509
+ return content;
2510
+ function getFutureProofMessage(message) {
2511
+ return (message.ephemeralMessage ||
2512
+ message.viewOnceMessage ||
2513
+ message.documentWithCaptionMessage ||
2514
+ message.viewOnceMessageV2 ||
2515
+ message.viewOnceMessageV2Extension ||
2516
+ message.editedMessage ||
2517
+ message.groupMentionedMessage ||
2518
+ message.botInvokeMessage ||
2519
+ message.lottieStickerMessage ||
2520
+ message.eventCoverImage ||
2521
+ message.statusMentionMessage ||
2522
+ message.pollCreationOptionImageMessage ||
2523
+ message.associatedChildMessage ||
2524
+ message.groupStatusMentionMessage ||
2525
+ message.pollCreationMessageV4 ||
2526
+ message.pollCreationMessageV5 ||
2527
+ message.statusAddYours ||
2528
+ message.groupStatusMessage ||
2529
+ message.limitSharingMessage ||
2530
+ message.botTaskMessage ||
2531
+ message.questionMessage ||
2532
+ message.groupStatusMessageV2 ||
2533
+ message.botForwardedMessage ||
2534
+ message.questionReplyMessage ||
2535
+ message.newsletterAdminProfileMessage ||
2536
+ message.newsletterAdminProfileMessageV2 ||
2537
+ message.newsletterAdminProfileStatusMessage ||
2538
+ message.spoilerMessage ||
2539
+ message.groupStatusV3Message ||
2540
+ message.pollCreationMessageV6);
2541
+ }
2542
+ };
2543
+ exports.normalizeMessageContent = normalizeMessageContent;
2544
+ const extractMessageContent = content => {
2545
+ const extractFromTemplateMessage = msg => {
2546
+ if (msg.imageMessage) {
2547
+ return { imageMessage: msg.imageMessage };
2548
+ }
2549
+ else if (msg.documentMessage) {
2550
+ return { documentMessage: msg.documentMessage };
2551
+ }
2552
+ else if (msg.videoMessage) {
2553
+ return { videoMessage: msg.videoMessage };
2554
+ }
2555
+ else if (msg.locationMessage) {
2556
+ return { locationMessage: msg.locationMessage };
2557
+ }
2558
+ else {
2559
+ return {
2560
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
2561
+ };
2562
+ }
2563
+ };
2564
+ content = (0, exports.normalizeMessageContent)(content);
2565
+ if (content?.buttonsMessage) {
2566
+ return extractFromTemplateMessage(content.buttonsMessage);
2567
+ }
2568
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
2569
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
2570
+ }
2571
+ if (content?.templateMessage?.hydratedTemplate) {
2572
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
2573
+ }
2574
+ if (content?.templateMessage?.fourRowTemplate) {
2575
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
2576
+ }
2577
+ return content;
2578
+ };
2579
+ exports.extractMessageContent = extractMessageContent;
2580
+ const getDevice = id => /^3A.{18}$/.test(id)
2581
+ ? 'ios'
2582
+ : /^3E.{20}$/.test(id)
2583
+ ? 'web'
2584
+ : /^(.{21}|.{32})$/.test(id)
2585
+ ? 'android'
2586
+ : /^(3F|.{18}$)/.test(id)
2587
+ ? 'desktop'
2588
+ : 'api/baileys';
2589
+ exports.getDevice = getDevice;
2590
+ const updateMessageWithReceipt = (msg, receipt) => {
2591
+ msg.userReceipt = msg.userReceipt || [];
2592
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
2593
+ if (recp) {
2594
+ Object.assign(recp, receipt);
2595
+ }
2596
+ else {
2597
+ msg.userReceipt.push(receipt);
2598
+ }
2599
+ };
2600
+ exports.updateMessageWithReceipt = updateMessageWithReceipt;
2601
+ const updateMessageWithReaction = (msg, reaction) => {
2602
+ const authorID = (0, generics_1.getKeyAuthor)(reaction.key);
2603
+ const reactions = (msg.reactions || []).filter(r => (0, generics_1.getKeyAuthor)(r.key) !== authorID);
2604
+ reaction.text = reaction.text || '';
2605
+ reactions.push(reaction);
2606
+ msg.reactions = reactions;
2607
+ };
2608
+ exports.updateMessageWithReaction = updateMessageWithReaction;
2609
+ const updateMessageWithPollUpdate = (msg, update) => {
2610
+ const authorID = (0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey);
2611
+ const reactions = (msg.pollUpdates || []).filter(r => (0, generics_1.getKeyAuthor)(r.pollUpdateMessageKey) !== authorID);
2612
+ if (update.vote?.selectedOptions?.length) {
2613
+ reactions.push(update);
2614
+ }
2615
+ msg.pollUpdates = reactions;
2616
+ };
2617
+ exports.updateMessageWithPollUpdate = updateMessageWithPollUpdate;
2618
+ const updateMessageWithEventResponse = (msg, update) => {
2619
+ const authorID = (0, generics_1.getKeyAuthor)(update.eventResponseMessageKey);
2620
+ const responses = (msg.eventResponses || []).filter(r => (0, generics_1.getKeyAuthor)(r.eventResponseMessageKey) !== authorID);
2621
+ responses.push(update);
2622
+ msg.eventResponses = responses;
2623
+ };
2624
+ exports.updateMessageWithEventResponse = updateMessageWithEventResponse;
2625
+ function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
2626
+ const opts = message?.pollCreationMessage?.options ||
2627
+ message?.pollCreationMessageV2?.options ||
2628
+ message?.pollCreationMessageV3?.options ||
2629
+ message?.pollCreationMessageV5?.options ||
2630
+ message?.pollCreationMessageV6?.options ||
2631
+ message?.pollCreationMessageV4?.message?.pollCreationMessage?.options ||
2632
+ message?.pollCreationMessageV4?.message?.pollCreationMessageV3?.options ||
2633
+ [];
2634
+ const voteHashMap = opts.reduce((acc, opt) => {
2635
+ const hash = (0, crypto_2.sha256)(Buffer.from(opt.optionName || '')).toString();
2636
+ acc[hash] = {
2637
+ name: opt.optionName || '',
2638
+ voters: []
2639
+ };
2640
+ return acc;
2641
+ }, {});
2642
+ for (const update of pollUpdates || []) {
2643
+ const { vote } = update;
2644
+ if (!vote) {
2645
+ continue;
2646
+ }
2647
+ for (const option of vote.selectedOptions || []) {
2648
+ const hash = option.toString();
2649
+ let data = voteHashMap[hash];
2650
+ if (!data) {
2651
+ voteHashMap[hash] = {
2652
+ name: 'Unknown',
2653
+ voters: []
2654
+ };
2655
+ data = voteHashMap[hash];
2656
+ }
2657
+ voteHashMap[hash].voters.push((0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey, meId));
2658
+ }
2659
+ }
2660
+ return Object.values(voteHashMap);
2661
+ }
2662
+ const aggregateMessageKeysNotFromMe = keys => {
2663
+ const keyMap = {};
2664
+ for (const { remoteJid, id, participant, fromMe, sts } of keys) {
2665
+ if (!fromMe) {
2666
+ const uqKey = `${remoteJid}:${participant || ''}`;
2667
+ if (!keyMap[uqKey]) {
2668
+ keyMap[uqKey] = {
2669
+ jid: remoteJid,
2670
+ participant: participant,
2671
+ messageIds: [],
2672
+ sts: sts
2673
+ };
2674
+ }
2675
+ else if (keyMap[uqKey].sts !== sts) {
2676
+ keyMap[uqKey].sts = undefined;
2677
+ }
2678
+ keyMap[uqKey].messageIds.push(id);
2679
+ }
2680
+ }
2681
+ return Object.values(keyMap);
2682
+ };
2683
+ exports.aggregateMessageKeysNotFromMe = aggregateMessageKeysNotFromMe;
2684
+ const isScheduledMessage = msg => !!msg?.scheduledMessageMetadata?.scheduledTime;
2685
+ exports.isScheduledMessage = isScheduledMessage;
2686
+ const getScheduledMessageTime = msg => {
2687
+ const t = msg?.scheduledMessageMetadata?.scheduledTime;
2688
+ if (!t)
2689
+ return null;
2690
+ return new Date(Number(t) * 1000);
2691
+ };
2692
+ exports.getScheduledMessageTime = getScheduledMessageTime;
2693
+ const getMessagePaymentInfo = msg => msg?.paymentInfo || msg?.quotedPaymentInfo || null;
2694
+ exports.getMessagePaymentInfo = getMessagePaymentInfo;
2695
+ const getMessageCommentMetadata = msg => msg?.commentMetadata || null;
2696
+ exports.getMessageCommentMetadata = getMessageCommentMetadata;
2697
+ const getMessageAddOns = msg => msg?.messageAddOns || [];
2698
+ exports.getMessageAddOns = getMessageAddOns;
2699
+ const getPollCorrectAnswer = pollMsg => {
2700
+ const poll = pollMsg?.pollCreationMessage ||
2701
+ pollMsg?.pollCreationMessageV2 ||
2702
+ pollMsg?.pollCreationMessageV3 ||
2703
+ pollMsg?.pollCreationMessageV5 ||
2704
+ pollMsg?.pollCreationMessageV6;
2705
+ if (!poll)
2706
+ return null;
2707
+ const isQuiz = poll.pollType === WAProto_1.proto.Message.PollType?.QUIZ || poll.pollType === 1;
2708
+ return isQuiz ? poll.correctAnswer?.optionName || null : null;
2709
+ };
2710
+ exports.getPollCorrectAnswer = getPollCorrectAnswer;
2711
+ function getAggregateResponsesInEventMessage({ eventResponses }, meLid) {
2712
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
2713
+ const responseMap = {};
2714
+ for (const type of responseTypes) {
2715
+ responseMap[type] = {
2716
+ response: type,
2717
+ responders: []
2718
+ };
2719
+ }
2720
+ for (const update of eventResponses) {
2721
+ const { response } = update.response || {};
2722
+ const responseType = index_js_1.proto.Message.EventResponseMessage.EventResponseType[response];
2723
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
2724
+ responseMap[responseType].responders.push(generics_1.getKeyAuthor(update.eventResponseMessageKey, meLid));
2725
+ }
2726
+ }
2727
+ return Object.values(responseMap);
2728
+ }
2729
+ exports.getAggregateResponsesInEventMessage = getAggregateResponsesInEventMessage;
2730
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
2731
+ const downloadMediaMessage = async (message, type, options, ctx) => {
2732
+ const result = await downloadMsg().catch(async (error) => {
2733
+ if (ctx &&
2734
+ typeof error?.status === 'number' &&
2735
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
2736
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
2737
+ message = await ctx.reuploadRequest(message);
2738
+ const result = await downloadMsg();
2739
+ return result;
2740
+ }
2741
+ throw error;
2742
+ });
2743
+ return result;
2744
+ async function downloadMsg() {
2745
+ const mContent = (0, exports.extractMessageContent)(message.message);
2746
+ if (!mContent) {
2747
+ throw new boom_1.Boom('No message present', { statusCode: 400, data: message });
2748
+ }
2749
+ const contentType = (0, exports.getContentType)(mContent);
2750
+ let mediaType = contentType?.replace('Message', '');
2751
+ const media = mContent[contentType];
2752
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
2753
+ throw new boom_1.Boom(`"${contentType}" message is not a media message`);
2754
+ }
2755
+ let download;
2756
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
2757
+ download = {
2758
+ directPath: media.thumbnailDirectPath,
2759
+ mediaKey: media.mediaKey
2760
+ };
2761
+ mediaType = 'thumbnail-link';
2762
+ }
2763
+ else {
2764
+ download = media;
2765
+ }
2766
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(download, mediaType, options);
2767
+ if (type === 'buffer') {
2768
+ const bufferArray = [];
2769
+ for await (const chunk of stream) {
2770
+ bufferArray.push(chunk);
2771
+ }
2772
+ return Buffer.concat(bufferArray);
2773
+ }
2774
+ return stream;
2775
+ }
2776
+ };
2777
+ exports.downloadMediaMessage = downloadMediaMessage;
2778
+ const assertMediaContent = content => {
2779
+ content = (0, exports.extractMessageContent)(content);
2780
+ const mediaContent = content?.documentMessage ||
2781
+ content?.imageMessage ||
2782
+ content?.videoMessage ||
2783
+ content?.audioMessage ||
2784
+ content?.stickerMessage;
2785
+ if (!mediaContent) {
2786
+ throw new boom_1.Boom('given message is not a media message', { statusCode: 400, data: content });
2787
+ }
2788
+ return mediaContent;
2789
+ };
2790
+ exports.assertMediaContent = assertMediaContent;
2791
+ const toJid = id => {
2792
+ if (!id)
2793
+ return '';
2794
+ if (id.includes('@'))
2795
+ return id;
2796
+ return `${id}@s.whatsapp.net`;
2797
+ };
2798
+ exports.toJid = toJid;
2799
+ const getSenderLid = message => {
2800
+ const k = message.key;
2801
+ if (!k) {
2802
+ return { jid: '', lid: '' };
2803
+ }
2804
+ const jid = k.participant || k.remoteJid || '';
2805
+ if (jid.endsWith('@lid') || jid.endsWith('@hosted.lid')) {
2806
+ return { jid, lid: jid };
2807
+ }
2808
+ if (k.lid && typeof k.lid === 'string') {
2809
+ const lid = k.lid.includes('@') ? k.lid : (0, WABinary_1.jidEncode)(k.lid, 'lid');
2810
+ return { jid, lid };
2811
+ }
2812
+ if (k.participantLid && (0, WABinary_1.isLidUser)(k.participantLid)) {
2813
+ return { jid, lid: k.participantLid };
2814
+ }
2815
+ return { jid, lid: '' };
2816
+ };
2817
+ exports.getSenderLid = getSenderLid;