@japofc/baileys 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (342) hide show
  1. package/NOTICE.md +111 -0
  2. package/README.md +1254 -0
  3. package/WAProto/index.d.ts +9 -0
  4. package/WAProto/index.js +142276 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Builders/A2UI.d.ts +242 -0
  7. package/lib/Builders/A2UI.js +308 -0
  8. package/lib/Builders/AIRich.d.ts +105 -0
  9. package/lib/Builders/AIRich.js +2286 -0
  10. package/lib/Builders/Button.d.ts +103 -0
  11. package/lib/Builders/Button.js +883 -0
  12. package/lib/Builders/ButtonV2.d.ts +28 -0
  13. package/lib/Builders/ButtonV2.js +144 -0
  14. package/lib/Builders/ButtonV3.d.ts +25 -0
  15. package/lib/Builders/ButtonV3.js +184 -0
  16. package/lib/Builders/Carousel.d.ts +22 -0
  17. package/lib/Builders/Carousel.js +111 -0
  18. package/lib/Builders/JapBaileys.d.ts +34 -0
  19. package/lib/Builders/JapBaileys.js +108 -0
  20. package/lib/Builders/Poll.d.ts +25 -0
  21. package/lib/Builders/Poll.js +128 -0
  22. package/lib/Builders/index.d.ts +17 -0
  23. package/lib/Builders/index.js +11 -0
  24. package/lib/Builders/shared.d.ts +67 -0
  25. package/lib/Builders/shared.js +652 -0
  26. package/lib/Defaults/index.d.ts +154 -0
  27. package/lib/Defaults/index.js +178 -0
  28. package/lib/Framework/Bot.d.ts +61 -0
  29. package/lib/Framework/Bot.js +248 -0
  30. package/lib/Framework/Context.d.ts +21 -0
  31. package/lib/Framework/Context.js +89 -0
  32. package/lib/Framework/MediaManager.d.ts +17 -0
  33. package/lib/Framework/MediaManager.js +151 -0
  34. package/lib/Framework/SessionManager.d.ts +13 -0
  35. package/lib/Framework/SessionManager.js +33 -0
  36. package/lib/Framework/StatsManager.d.ts +26 -0
  37. package/lib/Framework/StatsManager.js +119 -0
  38. package/lib/Framework/Store/SQLiteStore.d.ts +11 -0
  39. package/lib/Framework/Store/SQLiteStore.js +73 -0
  40. package/lib/Framework/index.d.ts +9 -0
  41. package/lib/Framework/index.js +10 -0
  42. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  43. package/lib/Signal/Group/ciphertext-message.js +11 -0
  44. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  45. package/lib/Signal/Group/group-session-builder.js +29 -0
  46. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  47. package/lib/Signal/Group/group_cipher.js +81 -0
  48. package/lib/Signal/Group/index.d.ts +11 -0
  49. package/lib/Signal/Group/index.js +11 -0
  50. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  51. package/lib/Signal/Group/keyhelper.js +17 -0
  52. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  53. package/lib/Signal/Group/sender-chain-key.js +25 -0
  54. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  55. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  56. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  57. package/lib/Signal/Group/sender-key-message.js +65 -0
  58. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  59. package/lib/Signal/Group/sender-key-name.js +47 -0
  60. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  61. package/lib/Signal/Group/sender-key-record.js +40 -0
  62. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  63. package/lib/Signal/Group/sender-key-state.js +83 -0
  64. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  65. package/lib/Signal/Group/sender-message-key.js +25 -0
  66. package/lib/Signal/libsignal.d.ts +54 -0
  67. package/lib/Signal/libsignal.js +430 -0
  68. package/lib/Signal/lid-mapping.d.ts +20 -0
  69. package/lib/Signal/lid-mapping.js +276 -0
  70. package/lib/Socket/Client/index.d.ts +2 -0
  71. package/lib/Socket/Client/index.js +2 -0
  72. package/lib/Socket/Client/types.d.ts +5 -0
  73. package/lib/Socket/Client/types.js +10 -0
  74. package/lib/Socket/Client/websocket.d.ts +12 -0
  75. package/lib/Socket/Client/websocket.js +53 -0
  76. package/lib/Socket/business.d.ts +395 -0
  77. package/lib/Socket/business.js +379 -0
  78. package/lib/Socket/chats.d.ts +136 -0
  79. package/lib/Socket/chats.js +1327 -0
  80. package/lib/Socket/communities.d.ts +562 -0
  81. package/lib/Socket/communities.js +439 -0
  82. package/lib/Socket/dugong.d.ts +117 -0
  83. package/lib/Socket/dugong.js +798 -0
  84. package/lib/Socket/groups.d.ts +285 -0
  85. package/lib/Socket/groups.js +354 -0
  86. package/lib/Socket/index.d.ts +585 -0
  87. package/lib/Socket/index.js +52 -0
  88. package/lib/Socket/messages-recv.d.ts +333 -0
  89. package/lib/Socket/messages-recv.js +1781 -0
  90. package/lib/Socket/messages-send.d.ts +353 -0
  91. package/lib/Socket/messages-send.js +1524 -0
  92. package/lib/Socket/mex.d.ts +1 -0
  93. package/lib/Socket/mex.js +41 -0
  94. package/lib/Socket/newsletter.d.ts +286 -0
  95. package/lib/Socket/newsletter.js +364 -0
  96. package/lib/Socket/socket.d.ts +60 -0
  97. package/lib/Socket/socket.js +1012 -0
  98. package/lib/Socket/username.d.ts +82 -0
  99. package/lib/Socket/username.js +159 -0
  100. package/lib/Store/index.d.ts +3 -0
  101. package/lib/Store/index.js +3 -0
  102. package/lib/Store/make-in-memory-store.d.ts +62 -0
  103. package/lib/Store/make-in-memory-store.js +428 -0
  104. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  105. package/lib/Store/make-ordered-dictionary.js +78 -0
  106. package/lib/Store/object-repository.d.ts +10 -0
  107. package/lib/Store/object-repository.js +23 -0
  108. package/lib/Types/Auth.d.ts +117 -0
  109. package/lib/Types/Auth.js +1 -0
  110. package/lib/Types/Bussines.d.ts +25 -0
  111. package/lib/Types/Call.d.ts +15 -0
  112. package/lib/Types/Call.js +1 -0
  113. package/lib/Types/Chat.d.ts +124 -0
  114. package/lib/Types/Chat.js +7 -0
  115. package/lib/Types/Contact.d.ts +26 -0
  116. package/lib/Types/Contact.js +1 -0
  117. package/lib/Types/Events.d.ts +256 -0
  118. package/lib/Types/Events.js +1 -0
  119. package/lib/Types/GroupMetadata.d.ts +71 -0
  120. package/lib/Types/GroupMetadata.js +1 -0
  121. package/lib/Types/Label.d.ts +5 -0
  122. package/lib/Types/Label.js +24 -0
  123. package/lib/Types/LabelAssociation.d.ts +6 -0
  124. package/lib/Types/LabelAssociation.js +6 -0
  125. package/lib/Types/Message.d.ts +62 -0
  126. package/lib/Types/Message.js +17 -0
  127. package/lib/Types/Mex.d.ts +2 -0
  128. package/lib/Types/Mex.js +38 -0
  129. package/lib/Types/Product.d.ts +79 -0
  130. package/lib/Types/Product.js +1 -0
  131. package/lib/Types/RichType.d.ts +2 -0
  132. package/lib/Types/RichType.js +22 -0
  133. package/lib/Types/Signal.d.ts +87 -0
  134. package/lib/Types/Signal.js +1 -0
  135. package/lib/Types/Socket.d.ts +138 -0
  136. package/lib/Types/Socket.js +1 -0
  137. package/lib/Types/State.d.ts +8 -0
  138. package/lib/Types/State.js +55 -0
  139. package/lib/Types/USync.d.ts +26 -0
  140. package/lib/Types/index.d.ts +68 -0
  141. package/lib/Types/index.js +27 -0
  142. package/lib/Utils/MessageBuilder.d.ts +2 -0
  143. package/lib/Utils/MessageBuilder.js +2 -0
  144. package/lib/Utils/PersistentStore.d.ts +60 -0
  145. package/lib/Utils/PersistentStore.js +592 -0
  146. package/lib/Utils/anti-delete.d.ts +74 -0
  147. package/lib/Utils/anti-delete.js +221 -0
  148. package/lib/Utils/auth-secure.d.ts +86 -0
  149. package/lib/Utils/auth-secure.js +764 -0
  150. package/lib/Utils/auth-utils.d.ts +57 -0
  151. package/lib/Utils/auth-utils.js +306 -0
  152. package/lib/Utils/auto-reply.d.ts +47 -0
  153. package/lib/Utils/auto-reply.js +157 -0
  154. package/lib/Utils/baileys-event-stream.d.ts +8 -0
  155. package/lib/Utils/baileys-event-stream.js +62 -0
  156. package/lib/Utils/browser-utils.d.ts +8 -0
  157. package/lib/Utils/browser-utils.js +27 -0
  158. package/lib/Utils/business.d.ts +49 -0
  159. package/lib/Utils/business.js +239 -0
  160. package/lib/Utils/button-helper-utils.d.ts +53 -0
  161. package/lib/Utils/button-helper-utils.js +312 -0
  162. package/lib/Utils/button-sender.d.ts +54 -0
  163. package/lib/Utils/button-sender.js +822 -0
  164. package/lib/Utils/chat-control.d.ts +159 -0
  165. package/lib/Utils/chat-control.js +230 -0
  166. package/lib/Utils/chat-history-helpers.d.ts +21 -0
  167. package/lib/Utils/chat-history-helpers.js +70 -0
  168. package/lib/Utils/chat-utils.d.ts +407 -0
  169. package/lib/Utils/chat-utils.js +885 -0
  170. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  171. package/lib/Utils/companion-reg-client-utils.js +39 -0
  172. package/lib/Utils/crypto.d.ts +41 -0
  173. package/lib/Utils/crypto.js +147 -0
  174. package/lib/Utils/decode-wa-message.d.ts +83 -0
  175. package/lib/Utils/decode-wa-message.js +316 -0
  176. package/lib/Utils/event-buffer.d.ts +12 -0
  177. package/lib/Utils/event-buffer.js +635 -0
  178. package/lib/Utils/generics.d.ts +69 -0
  179. package/lib/Utils/generics.js +438 -0
  180. package/lib/Utils/history-share.d.ts +11 -0
  181. package/lib/Utils/history-share.js +70 -0
  182. package/lib/Utils/history.d.ts +90 -0
  183. package/lib/Utils/history.js +146 -0
  184. package/lib/Utils/humanizer.d.ts +12 -0
  185. package/lib/Utils/humanizer.js +73 -0
  186. package/lib/Utils/identity-change-handler.d.ts +13 -0
  187. package/lib/Utils/identity-change-handler.js +49 -0
  188. package/lib/Utils/index.d.ts +57 -0
  189. package/lib/Utils/index.js +56 -0
  190. package/lib/Utils/jid-tools.d.ts +6 -0
  191. package/lib/Utils/jid-tools.js +77 -0
  192. package/lib/Utils/link-preview.d.ts +12 -0
  193. package/lib/Utils/link-preview.js +84 -0
  194. package/lib/Utils/logger.d.ts +4 -0
  195. package/lib/Utils/logger.js +2 -0
  196. package/lib/Utils/lt-hash.d.ts +12 -0
  197. package/lib/Utils/lt-hash.js +26 -0
  198. package/lib/Utils/make-mutex.d.ts +6 -0
  199. package/lib/Utils/make-mutex.js +32 -0
  200. package/lib/Utils/media-messages.d.ts +18 -0
  201. package/lib/Utils/media-messages.js +70 -0
  202. package/lib/Utils/media-set.d.ts +13 -0
  203. package/lib/Utils/media-set.js +171 -0
  204. package/lib/Utils/message-kind.d.ts +32 -0
  205. package/lib/Utils/message-kind.js +136 -0
  206. package/lib/Utils/message-retry-manager.d.ts +79 -0
  207. package/lib/Utils/message-retry-manager.js +264 -0
  208. package/lib/Utils/message-search.d.ts +44 -0
  209. package/lib/Utils/message-search.js +188 -0
  210. package/lib/Utils/messages-media.d.ts +135 -0
  211. package/lib/Utils/messages-media.js +868 -0
  212. package/lib/Utils/messages.d.ts +44 -0
  213. package/lib/Utils/messages.js +2326 -0
  214. package/lib/Utils/meta-ai.d.ts +13 -0
  215. package/lib/Utils/meta-ai.js +74 -0
  216. package/lib/Utils/mini-app.d.ts +35 -0
  217. package/lib/Utils/mini-app.js +213 -0
  218. package/lib/Utils/noise-handler.d.ts +20 -0
  219. package/lib/Utils/noise-handler.js +200 -0
  220. package/lib/Utils/offline-node-processor.d.ts +9 -0
  221. package/lib/Utils/offline-node-processor.js +39 -0
  222. package/lib/Utils/past-participants.d.ts +14 -0
  223. package/lib/Utils/past-participants.js +40 -0
  224. package/lib/Utils/pre-key-manager.d.ts +25 -0
  225. package/lib/Utils/pre-key-manager.js +105 -0
  226. package/lib/Utils/process-message.d.ts +82 -0
  227. package/lib/Utils/process-message.js +808 -0
  228. package/lib/Utils/qr-render.d.ts +59 -0
  229. package/lib/Utils/qr-render.js +179 -0
  230. package/lib/Utils/qrcodegen.d.ts +79 -0
  231. package/lib/Utils/qrcodegen.js +848 -0
  232. package/lib/Utils/reporting-utils.d.ts +12 -0
  233. package/lib/Utils/reporting-utils.js +257 -0
  234. package/lib/Utils/rich-message-utils.d.ts +48 -0
  235. package/lib/Utils/rich-message-utils.js +444 -0
  236. package/lib/Utils/router.d.ts +37 -0
  237. package/lib/Utils/router.js +165 -0
  238. package/lib/Utils/scheduled-posts.d.ts +30 -0
  239. package/lib/Utils/scheduled-posts.js +110 -0
  240. package/lib/Utils/scheduling.d.ts +42 -0
  241. package/lib/Utils/scheduling.js +139 -0
  242. package/lib/Utils/signal.d.ts +82 -0
  243. package/lib/Utils/signal.js +200 -0
  244. package/lib/Utils/stanza-ack.d.ts +16 -0
  245. package/lib/Utils/stanza-ack.js +37 -0
  246. package/lib/Utils/status.d.ts +50 -0
  247. package/lib/Utils/status.js +107 -0
  248. package/lib/Utils/stickerpack.d.ts +51 -0
  249. package/lib/Utils/stickerpack.js +274 -0
  250. package/lib/Utils/sync-action-utils.d.ts +2 -0
  251. package/lib/Utils/sync-action-utils.js +48 -0
  252. package/lib/Utils/tag.d.ts +12 -0
  253. package/lib/Utils/tag.js +44 -0
  254. package/lib/Utils/tc-token-utils.d.ts +29 -0
  255. package/lib/Utils/tc-token-utils.js +162 -0
  256. package/lib/Utils/templates.d.ts +76 -0
  257. package/lib/Utils/templates.js +150 -0
  258. package/lib/Utils/transcribe.d.ts +12 -0
  259. package/lib/Utils/transcribe.js +107 -0
  260. package/lib/Utils/use-cache-manager-auth-state.d.ts +13 -0
  261. package/lib/Utils/use-cache-manager-auth-state.js +81 -0
  262. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  263. package/lib/Utils/use-multi-file-auth-state.js +166 -0
  264. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  265. package/lib/Utils/use-single-file-auth-state.js +113 -0
  266. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  267. package/lib/Utils/use-sqlite-auth-state.js +169 -0
  268. package/lib/Utils/validate-connection.d.ts +42 -0
  269. package/lib/Utils/validate-connection.js +198 -0
  270. package/lib/Utils/vcard.d.ts +58 -0
  271. package/lib/Utils/vcard.js +104 -0
  272. package/lib/Utils/voice-note.d.ts +15 -0
  273. package/lib/Utils/voice-note.js +63 -0
  274. package/lib/VoIP/audio-feeder.d.ts +18 -0
  275. package/lib/VoIP/audio-feeder.js +160 -0
  276. package/lib/VoIP/call-recorder.d.ts +13 -0
  277. package/lib/VoIP/call-recorder.js +73 -0
  278. package/lib/VoIP/index.d.ts +86 -0
  279. package/lib/VoIP/index.js +611 -0
  280. package/lib/VoIP/relay-transport.d.ts +43 -0
  281. package/lib/VoIP/relay-transport.js +563 -0
  282. package/lib/VoIP/signaling.d.ts +26 -0
  283. package/lib/VoIP/signaling.js +662 -0
  284. package/lib/VoIP/types.d.ts +69 -0
  285. package/lib/VoIP/types.js +17 -0
  286. package/lib/VoIP/wasm-engine.d.ts +120 -0
  287. package/lib/VoIP/wasm-engine.js +1358 -0
  288. package/lib/VoIP/worker-bootstrap.d.ts +4 -0
  289. package/lib/VoIP/worker-bootstrap.js +1046 -0
  290. package/lib/WABinary/constants.d.ts +61 -0
  291. package/lib/WABinary/constants.js +1466 -0
  292. package/lib/WABinary/decode.d.ts +9 -0
  293. package/lib/WABinary/decode.js +261 -0
  294. package/lib/WABinary/encode.d.ts +2 -0
  295. package/lib/WABinary/encode.js +219 -0
  296. package/lib/WABinary/generic-utils.d.ts +74 -0
  297. package/lib/WABinary/generic-utils.js +276 -0
  298. package/lib/WABinary/index.d.ts +5 -0
  299. package/lib/WABinary/index.js +5 -0
  300. package/lib/WABinary/jid-utils.d.ts +28 -0
  301. package/lib/WABinary/jid-utils.js +95 -0
  302. package/lib/WABinary/types.d.ts +19 -0
  303. package/lib/WABinary/types.js +1 -0
  304. package/lib/WAM/BinaryInfo.d.ts +7 -0
  305. package/lib/WAM/BinaryInfo.js +9 -0
  306. package/lib/WAM/constants.d.ts +34926 -0
  307. package/lib/WAM/constants.js +22852 -0
  308. package/lib/WAM/encode.d.ts +1 -0
  309. package/lib/WAM/encode.js +149 -0
  310. package/lib/WAM/index.d.ts +3 -0
  311. package/lib/WAM/index.js +3 -0
  312. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  313. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  314. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  315. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  316. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  317. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  318. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  319. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  320. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  321. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  322. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  323. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  324. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  325. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  326. package/lib/WAUSync/Protocols/index.d.ts +7 -0
  327. package/lib/WAUSync/Protocols/index.js +7 -0
  328. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  329. package/lib/WAUSync/USyncQuery.js +121 -0
  330. package/lib/WAUSync/USyncUser.d.ts +16 -0
  331. package/lib/WAUSync/USyncUser.js +30 -0
  332. package/lib/WAUSync/index.d.ts +3 -0
  333. package/lib/WAUSync/index.js +3 -0
  334. package/lib/assets/wasm/loader.d.ts +5 -0
  335. package/lib/assets/wasm/loader.js +5 -0
  336. package/lib/assets/wasm/whatsapp.wasm +0 -0
  337. package/lib/assets/wasm/worker-modules.d.ts +5 -0
  338. package/lib/assets/wasm/worker-modules.js +273 -0
  339. package/lib/index.d.ts +18 -0
  340. package/lib/index.js +23 -0
  341. package/package.json +180 -0
  342. package/postinstall-banner.js +82 -0
@@ -0,0 +1,2326 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
4
+ import { promises as fs } from 'fs';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
+ import { sha256 } from './crypto.js';
10
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
12
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
13
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
14
+ const CONCURRENCY_LIMIT = 15;
15
+ const MIMETYPE_MAP = {
16
+ image: 'image/jpeg',
17
+ video: 'video/mp4',
18
+ document: 'application/pdf',
19
+ audio: 'audio/ogg; codecs=opus',
20
+ sticker: 'image/webp',
21
+ 'product-catalog-image': 'image/jpeg'
22
+ };
23
+ const MessageTypeProto = {
24
+ image: WAProto.Message.ImageMessage,
25
+ video: WAProto.Message.VideoMessage,
26
+ audio: WAProto.Message.AudioMessage,
27
+ sticker: WAProto.Message.StickerMessage,
28
+ document: WAProto.Message.DocumentMessage
29
+ };
30
+ const mediaAnnotation = [
31
+ {
32
+ polygonVertices: [
33
+ { x: 60.71664810180664, y: -36.39784622192383 },
34
+ { x: -16.710189819335938, y: 49.263675689697266 },
35
+ { x: -56.585853576660156, y: 37.85963439941406 },
36
+ { x: 20.840980529785156, y: -47.80188751220703 }
37
+ ],
38
+ newsletter: {
39
+ // JAP@Note 03-02-26 --- You can change jid, message id, and name via .env (⁠≧⁠▽⁠≦⁠)
40
+ newsletterJid: process.env.NEWSLETTER_ID ||
41
+ Buffer.from('313230333633343034303036363434313339406e6577736c6574746572', 'hex').toString(),
42
+ newsletterName: process.env.NEWSLETTER_NAME ||
43
+ Buffer.from('f09d96b2f09d978df09d96baf09d978bf09d96bff09d96baf09d9785f09d9785', 'hex').toString(),
44
+ contentType: proto.ContextInfo.ForwardedNewsletterMessageInfo.ContentType.UPDATE,
45
+ accessibilityText: process.env.NEWSLETTER_ACCESSIBILITY_TEXT ||
46
+ '@japofc/baileys'
47
+ }
48
+ }
49
+ ];
50
+ /**
51
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
52
+ * @param text eg. hello https://google.com
53
+ * @returns the URL, eg. https://google.com
54
+ */
55
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
56
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
57
+ const url = extractUrlFromText(text);
58
+ if (!!getUrlInfo && url) {
59
+ try {
60
+ const urlInfo = await getUrlInfo(url);
61
+ return urlInfo;
62
+ }
63
+ catch (error) {
64
+ // ignore if fails
65
+ logger?.warn({ trace: error.stack }, 'url generation failed');
66
+ }
67
+ }
68
+ };
69
+ const assertColor = async (color) => {
70
+ let assertedColor;
71
+ if (typeof color === 'number') {
72
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
73
+ }
74
+ else {
75
+ let hex = color.trim().replace('#', '');
76
+ if (hex.length <= 6) {
77
+ hex = 'FF' + hex.padStart(6, '0');
78
+ }
79
+ assertedColor = parseInt(hex, 16);
80
+ return assertedColor;
81
+ }
82
+ };
83
+ export const prepareWAMessageMedia = async (message, options) => {
84
+ const logger = options.logger;
85
+ let mediaType;
86
+ for (const key of MEDIA_KEYS) {
87
+ if (key in message) {
88
+ mediaType = key;
89
+ }
90
+ }
91
+ if (!mediaType) {
92
+ throw new Boom('Invalid media type', { statusCode: 400 });
93
+ }
94
+ const uploadData = {
95
+ ...message,
96
+ media: message[mediaType]
97
+ };
98
+ // JAP@Fix: Removed mediaAnnotation injection that caused "Lihat saluran" (newsletter) button
99
+ // to appear on every image/video sent. Original itslia code injected newsletter contextInfo
100
+ // into all media uploads which is unnecessary and annoying for regular bot usage.
101
+ delete uploadData[mediaType];
102
+ // check if cacheable + generate cache key
103
+ const cacheableKey = typeof uploadData.media === 'object' &&
104
+ 'url' in uploadData.media &&
105
+ !!uploadData.media.url &&
106
+ !!options.mediaCache &&
107
+ mediaType + ':' + uploadData.media.url.toString();
108
+ if (mediaType === 'document' && !uploadData.fileName) {
109
+ uploadData.fileName = 'file';
110
+ }
111
+ if (!uploadData.mimetype) {
112
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
113
+ }
114
+ if (cacheableKey) {
115
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
116
+ if (mediaBuff) {
117
+ logger?.debug({ cacheableKey }, 'got media cache hit');
118
+ const obj = proto.Message.decode(mediaBuff);
119
+ const key = `${mediaType}Message`;
120
+ Object.assign(obj[key], { ...uploadData, media: undefined });
121
+ return obj;
122
+ }
123
+ }
124
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
125
+ if (isNewsletter) {
126
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
127
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
128
+ const fileSha256B64 = fileSha256.toString('base64');
129
+ const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
130
+ fileEncSha256B64: fileSha256B64,
131
+ mediaType: mediaType,
132
+ timeoutMs: options.mediaUploadTimeoutMs,
133
+ newsletter: isNewsletter
134
+ });
135
+ await fs.unlink(filePath);
136
+ const obj = WAProto.Message.fromObject({
137
+ // todo: add more support here
138
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
139
+ url: mediaUrl,
140
+ directPath,
141
+ fileSha256,
142
+ fileLength,
143
+ thumbnailDirectPath,
144
+ thumbnailSha256,
145
+ ...uploadData,
146
+ media: undefined
147
+ })
148
+ });
149
+ if (uploadData.ptv) {
150
+ obj.ptvMessage = obj.videoMessage;
151
+ delete obj.videoMessage;
152
+ }
153
+ if (obj.stickerMessage) {
154
+ obj.stickerMessage.stickerSentTs = Date.now();
155
+ }
156
+ if (cacheableKey) {
157
+ logger?.debug({ cacheableKey }, 'set cache');
158
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
159
+ }
160
+ return obj;
161
+ }
162
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
163
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
164
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
165
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
166
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
167
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
168
+ logger,
169
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
170
+ opts: options.options
171
+ });
172
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
173
+ const [{ mediaUrl, directPath }] = await Promise.all([
174
+ (async () => {
175
+ const result = await options.upload(encFilePath, {
176
+ fileEncSha256B64,
177
+ mediaType,
178
+ timeoutMs: options.mediaUploadTimeoutMs
179
+ });
180
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
181
+ return result;
182
+ })(),
183
+ (async () => {
184
+ try {
185
+ if (requiresThumbnailComputation) {
186
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
187
+ uploadData.jpegThumbnail = thumbnail;
188
+ if (!uploadData.width && originalImageDimensions) {
189
+ uploadData.width = originalImageDimensions.width;
190
+ uploadData.height = originalImageDimensions.height;
191
+ logger?.debug('set dimensions');
192
+ }
193
+ logger?.debug('generated thumbnail');
194
+ }
195
+ if (requiresDurationComputation) {
196
+ uploadData.seconds = await getAudioDuration(originalFilePath);
197
+ logger?.debug('computed audio duration');
198
+ }
199
+ if (requiresWaveformProcessing) {
200
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
201
+ logger?.debug('processed waveform');
202
+ }
203
+ if (requiresAudioBackground) {
204
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
205
+ logger?.debug('computed backgroundColor audio status');
206
+ }
207
+ }
208
+ catch (error) {
209
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
210
+ }
211
+ })()
212
+ ]).finally(async () => {
213
+ try {
214
+ await fs.unlink(encFilePath);
215
+ if (originalFilePath) {
216
+ await fs.unlink(originalFilePath);
217
+ }
218
+ logger?.debug('removed tmp files');
219
+ }
220
+ catch (error) {
221
+ logger?.warn('failed to remove tmp file');
222
+ }
223
+ });
224
+ const obj = WAProto.Message.fromObject({
225
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
226
+ url: mediaUrl,
227
+ directPath,
228
+ mediaKey,
229
+ fileEncSha256,
230
+ fileSha256,
231
+ fileLength,
232
+ mediaKeyTimestamp: unixTimestampSeconds(),
233
+ ...uploadData,
234
+ media: undefined
235
+ })
236
+ });
237
+ if (uploadData.ptv) {
238
+ obj.ptvMessage = obj.videoMessage;
239
+ delete obj.videoMessage;
240
+ }
241
+ if (cacheableKey) {
242
+ logger?.debug({ cacheableKey }, 'set cache');
243
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
244
+ }
245
+ return obj;
246
+ };
247
+ // JAP@Changes 31-01-26 --- Extract product message into a standalone function so it can also be reused as the header for interactive messages
248
+ const prepareProductMessage = async (message, options) => {
249
+ if (!message.businessOwnerJid) {
250
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
251
+ }
252
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
253
+ // JAP@Changes 01-02-26 --- Add product message default value
254
+ const { image, ...content } = message;
255
+ content.product = {
256
+ currencyCode: 'IDR',
257
+ priceAmount1000: 1000,
258
+ title: LIBRARY_NAME,
259
+ ...message.product,
260
+ productImage: imageMessage
261
+ };
262
+ return content;
263
+ };
264
+ /**
265
+ * JAP@Note 30-01-26
266
+ * ---
267
+ * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
268
+ * based on upstream Baileys PR #1561
269
+ */
270
+ // JAP@Changes 21-04-26 --- Enhanced prepareStickerPackMessage
271
+ const prepareStickerPackMessage = async (message, options) => {
272
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: JAPofc', description = '🏷️ japofc/baileys' } = message;
273
+ if (stickers.length > 60) {
274
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
275
+ }
276
+ if (stickers.length === 0) {
277
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
278
+ }
279
+ if (!cover) {
280
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
281
+ }
282
+ const logger = options.logger;
283
+ // JAP@Changes 01-02-26 --- Add caching for sticker pack
284
+ let cacheableKey = false;
285
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
286
+ const urls = [];
287
+ for (let i = 0; i < stickers.length; i++) {
288
+ const data = stickers[i].data;
289
+ if (typeof data === 'object' && data?.url) {
290
+ urls.push(data.url);
291
+ }
292
+ }
293
+ if (urls.length > 0) {
294
+ cacheableKey = 'sticker:' + urls.join('@');
295
+ }
296
+ }
297
+ if (cacheableKey) {
298
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
299
+ if (mediaBuff) {
300
+ logger?.debug({ cacheableKey }, 'got media cache hit');
301
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
302
+ }
303
+ }
304
+ const lib = await getImageProcessingLibrary();
305
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
306
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
307
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
308
+ if (!hasSharp && !hasImage) {
309
+ throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
310
+ }
311
+ const stickerPackIdValue = generateMessageIDV2();
312
+ const stickerData = {};
313
+ const stickerMetadata = new Array(stickers.length);
314
+ for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
315
+ const promises = [];
316
+ const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length);
317
+ for (let j = i; j < chunkEnd; j++) {
318
+ promises.push((async (index) => {
319
+ const sticker = stickers[index];
320
+ const { stream } = await getStream(sticker.data);
321
+ const buffer = await toBuffer(stream);
322
+ let webpBuffer;
323
+ let isAnimated = false;
324
+ if (isWebPBuffer(buffer)) {
325
+ webpBuffer = buffer;
326
+ isAnimated = isAnimatedWebP(buffer);
327
+ }
328
+ else if (hasSharp) {
329
+ webpBuffer = await lib.sharp.default(buffer)
330
+ .resize(512, 512, { fit: 'inside' })
331
+ .webp({ quality: 80 })
332
+ .toBuffer();
333
+ }
334
+ else {
335
+ webpBuffer = await new lib.image.Transformer(buffer)
336
+ .resize(512, 512)
337
+ .webp(80);
338
+ }
339
+ if (webpBuffer.length > 1024 * 1024) {
340
+ throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
341
+ }
342
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
343
+ const fileName = `${hash}.webp`;
344
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
345
+ stickerMetadata[index] = {
346
+ fileName,
347
+ mimetype: 'image/webp',
348
+ isAnimated,
349
+ emojis: sticker.emojis || ['✨'],
350
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
351
+ };
352
+ })(j));
353
+ }
354
+ await Promise.all(promises);
355
+ }
356
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
357
+ const { stream: coverStream } = await getStream(cover);
358
+ const coverBuffer = await toBuffer(coverStream);
359
+ let coverWebpBuffer;
360
+ if (isWebPBuffer(coverBuffer)) {
361
+ coverWebpBuffer = coverBuffer;
362
+ }
363
+ else if (hasSharp) {
364
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
365
+ .resize(512, 512, { fit: 'inside' })
366
+ .webp({ quality: 80 })
367
+ .toBuffer();
368
+ }
369
+ else {
370
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
371
+ .resize(512, 512)
372
+ .webp(80);
373
+ }
374
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
375
+ const zipBuffer = await new Promise((resolve, reject) => {
376
+ zip(stickerData, (error, data) => error ? reject(error) : resolve(Buffer.from(data)));
377
+ });
378
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
379
+ logger,
380
+ opts: options.options
381
+ });
382
+ let stickerPackUploadResult;
383
+ try {
384
+ stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
385
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
386
+ mediaType: 'sticker-pack',
387
+ timeoutMs: options.mediaUploadTimeoutMs
388
+ });
389
+ }
390
+ finally {
391
+ fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
392
+ }
393
+ const obj = {
394
+ name,
395
+ publisher,
396
+ stickerPackId: stickerPackIdValue,
397
+ packDescription: description,
398
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
399
+ stickerPackSize: zipBuffer.length,
400
+ stickers: stickerMetadata,
401
+ fileSha256: stickerPackUpload.fileSha256,
402
+ fileEncSha256: stickerPackUpload.fileEncSha256,
403
+ mediaKey: stickerPackUpload.mediaKey,
404
+ directPath: stickerPackUploadResult.directPath,
405
+ fileLength: stickerPackUpload.fileLength,
406
+ mediaKeyTimestamp: unixTimestampSeconds(),
407
+ trayIconFileName
408
+ };
409
+ try {
410
+ let thumbnailBuffer;
411
+ if (hasSharp) {
412
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
413
+ }
414
+ else if (hasImage) {
415
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
416
+ }
417
+ else if (hasJimp) {
418
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
419
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
420
+ }
421
+ else {
422
+ throw new Error('No image processing library available for thumbnail generation');
423
+ }
424
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
425
+ throw new Error('Failed to generate thumbnail buffer');
426
+ }
427
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
428
+ logger,
429
+ opts: options.options,
430
+ mediaKey: stickerPackUpload.mediaKey
431
+ });
432
+ let thumbUploadResult;
433
+ try {
434
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
435
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
436
+ mediaType: 'thumbnail-sticker-pack',
437
+ timeoutMs: options.mediaUploadTimeoutMs
438
+ });
439
+ }
440
+ finally {
441
+ fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
442
+ }
443
+ Object.assign(obj, {
444
+ thumbnailDirectPath: thumbUploadResult.directPath,
445
+ thumbnailSha256: thumbUpload.fileSha256,
446
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
447
+ thumbnailHeight: 252,
448
+ thumbnailWidth: 252,
449
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
450
+ });
451
+ }
452
+ catch (error) {
453
+ logger?.warn(`Thumbnail generation failed: ${error}`);
454
+ }
455
+ if (cacheableKey) {
456
+ logger?.debug({ cacheableKey }, 'set cache (background)');
457
+ options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish());
458
+ }
459
+ return WAProto.Message.StickerPackMessage.fromObject(obj);
460
+ };
461
+ // JAP@Changes 30-01-26 --- Add native flow button helper for interactive message
462
+ const prepareNativeFlowButtons = (message) => {
463
+ const buttons = message.nativeFlow;
464
+ const isButtonsFieldArray = Array.isArray(buttons);
465
+ // JAP@Fix (bug 7): buttons can be undefined here (e.g. cards shorthand passes `[]`
466
+ // for a card with no nativeFlow, so `[].nativeFlow` is undefined) — fall back to an
467
+ // empty button list instead of crashing on `undefined.buttons`.
468
+ const correctedField = isButtonsFieldArray ? buttons : (buttons?.buttons ?? []);
469
+ const messageParamsJson = {};
470
+ // JAP@Changes 31-01-26 --- Add offer and options inside interactive message
471
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
472
+ Object.assign(messageParamsJson, {
473
+ limited_time_offer: {
474
+ text: message.offerText || LIBRARY_NAME,
475
+ url: message.offerUrl || DONATE_URL || undefined, // JAP@Fix (bug 10): DONATE_URL now empty — don't inject fallback link
476
+ copy_code: message.offerCode,
477
+ expiration_time: message.offerExpiration
478
+ }
479
+ });
480
+ }
481
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
482
+ Object.assign(messageParamsJson, {
483
+ bottom_sheet: {
484
+ in_thread_buttons_limit: 1,
485
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
486
+ list_title: message.optionTitle || '📄 Select Options',
487
+ button_title: message.optionText
488
+ }
489
+ });
490
+ }
491
+ return {
492
+ buttons: correctedField.map(button => {
493
+ const buttonText = button.text || button.buttonText;
494
+ const buttonIcon = button.icon?.toUpperCase();
495
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
496
+ return {
497
+ name: 'quick_reply',
498
+ buttonParamsJson: JSON.stringify({
499
+ display_text: buttonText || '👉🏻 Click',
500
+ id: button.id,
501
+ icon: buttonIcon
502
+ })
503
+ };
504
+ }
505
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
506
+ return {
507
+ name: 'cta_copy',
508
+ buttonParamsJson: JSON.stringify({
509
+ display_text: buttonText || '📋 Copy',
510
+ copy_code: button.copy,
511
+ icon: buttonIcon
512
+ })
513
+ };
514
+ }
515
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
516
+ return {
517
+ name: 'cta_url',
518
+ buttonParamsJson: JSON.stringify({
519
+ display_text: buttonText || '🌐 Visit',
520
+ url: button.url,
521
+ merchant_url: button.url,
522
+ webview_interaction: button.useWebview,
523
+ icon: buttonIcon
524
+ })
525
+ };
526
+ }
527
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
528
+ return {
529
+ name: 'cta_call',
530
+ buttonParamsJson: JSON.stringify({
531
+ display_text: buttonText || '📞 Call',
532
+ phone_number: button.call,
533
+ icon: buttonIcon
534
+ })
535
+ };
536
+ }
537
+ // JAP@Changes 12-03-26 --- Add "single_select" shortcut \⁠(⁠°⁠o⁠°⁠)⁠/
538
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
539
+ return {
540
+ name: 'single_select',
541
+ buttonParamsJson: JSON.stringify({
542
+ title: buttonText || '📋 Select',
543
+ sections: button.sections,
544
+ icon: buttonIcon
545
+ })
546
+ };
547
+ }
548
+ // JAP@Changes --- Add "cta_reminder" shortcut
549
+ else if (hasOptionalProperty(button, 'reminder') && !!button.reminder) {
550
+ return {
551
+ name: 'cta_reminder',
552
+ buttonParamsJson: JSON.stringify({
553
+ display_text: buttonText || '⏰ Remind me',
554
+ id: button.id || button.reminder,
555
+ icon: buttonIcon
556
+ })
557
+ };
558
+ }
559
+ // JAP@Changes --- Add "cta_cancel_reminder" shortcut
560
+ else if (hasOptionalProperty(button, 'cancelReminder') && !!button.cancelReminder) {
561
+ return {
562
+ name: 'cta_cancel_reminder',
563
+ buttonParamsJson: JSON.stringify({
564
+ display_text: buttonText || '🔕 Cancel reminder',
565
+ id: button.id || button.cancelReminder,
566
+ icon: buttonIcon
567
+ })
568
+ };
569
+ }
570
+ // JAP@Changes --- Add "address_message" / send_location shortcut
571
+ else if (hasOptionalProperty(button, 'address') && !!button.address) {
572
+ return {
573
+ name: 'address_message',
574
+ buttonParamsJson: JSON.stringify({
575
+ display_text: buttonText || '📍 Send address',
576
+ id: button.id || 'address_message'
577
+ })
578
+ };
579
+ }
580
+ else if (hasOptionalProperty(button, 'location') && button.location === true) {
581
+ return {
582
+ name: 'send_location',
583
+ buttonParamsJson: JSON.stringify({})
584
+ };
585
+ }
586
+ // JAP@Changes --- Add "view_catalog" / catalog_message / mpm shortcut
587
+ else if (hasOptionalProperty(button, 'catalog') && !!button.catalog) {
588
+ return {
589
+ name: 'catalog_message',
590
+ buttonParamsJson: JSON.stringify({
591
+ business_phone_number: button.catalog.bizJid || button.catalog,
592
+ display_text: buttonText || '🛍️ View catalog',
593
+ id: button.id || 'catalog_message'
594
+ })
595
+ };
596
+ }
597
+ else if (hasOptionalProperty(button, 'products') && !!button.products) {
598
+ return {
599
+ name: 'mpm',
600
+ buttonParamsJson: JSON.stringify({
601
+ business_phone_number: button.bizJid || button.products.bizJid,
602
+ product_ids: Array.isArray(button.products) ? button.products : button.products.ids
603
+ })
604
+ };
605
+ }
606
+ // JAP@Fix (bug 12): otp_button/authentication_button removed entirely.
607
+ // These are WhatsApp Business Platform (Cloud API) authentication template
608
+ // buttons, gated behind Meta template approval — they cannot be produced
609
+ // by any MD-protocol client library, Baileys included. Not a bug to fix,
610
+ // just an unsupported surface; unrecognized `otp`/`oneTapOtp` fields now
611
+ // fall through untouched instead of building a doomed-to-fail button.
612
+
613
+ // JAP@Fix (bug 11): 'call_button'/'url_button'/'reply_button' were invalid
614
+ // native-flow type names (leftover from the deprecated buttonsMessage system,
615
+ // which modern WA clients no longer render — that's why they silent-failed).
616
+ // Aliased to the real, currently-supported native-flow equivalents instead.
617
+ else if (hasOptionalProperty(button, 'phoneNumber') && !!button.phoneNumber) {
618
+ return {
619
+ name: 'cta_call',
620
+ buttonParamsJson: JSON.stringify({
621
+ display_text: buttonText || '📞 Call',
622
+ phone_number: button.phoneNumber,
623
+ icon: buttonIcon
624
+ })
625
+ };
626
+ }
627
+ else if (hasOptionalProperty(button, 'urlBtn') && !!button.urlBtn) {
628
+ return {
629
+ name: 'cta_url',
630
+ buttonParamsJson: JSON.stringify({
631
+ display_text: buttonText || '🌐 Open',
632
+ url: button.urlBtn,
633
+ merchant_url: button.urlBtn,
634
+ webview_interaction: button.useWebview,
635
+ icon: buttonIcon
636
+ })
637
+ };
638
+ }
639
+ else if (hasOptionalProperty(button, 'reply') && !!button.reply) {
640
+ return {
641
+ name: 'quick_reply',
642
+ buttonParamsJson: JSON.stringify({
643
+ display_text: buttonText || button.reply,
644
+ id: button.id || button.reply,
645
+ icon: buttonIcon
646
+ })
647
+ };
648
+ }
649
+ // JAP@Changes --- Add order/payment lifecycle button shortcuts
650
+ // ⚠️ NOTE: card_message/order_details/order_status/review_and_pay/
651
+ // payment_status/payment_method are valid native-flow types, BUT WA only
652
+ // renders them when order_id/product data resolves to a real Commerce
653
+ // order tied to your catalog/business account. Fake/test IDs will always
654
+ // silently fail — this is server-side validation, not a Baileys bug.
655
+ else if (hasOptionalProperty(button, 'card') && !!button.card) {
656
+ return {
657
+ name: 'card_message',
658
+ buttonParamsJson: JSON.stringify(button.card)
659
+ };
660
+ }
661
+ else if (hasOptionalProperty(button, 'orderDetails') && !!button.orderDetails) {
662
+ return {
663
+ name: 'order_details',
664
+ buttonParamsJson: JSON.stringify(button.orderDetails)
665
+ };
666
+ }
667
+ else if (hasOptionalProperty(button, 'orderStatus') && !!button.orderStatus) {
668
+ return {
669
+ name: 'order_status',
670
+ buttonParamsJson: JSON.stringify(button.orderStatus)
671
+ };
672
+ }
673
+ else if (hasOptionalProperty(button, 'reviewAndPay') && !!button.reviewAndPay) {
674
+ return {
675
+ name: 'review_and_pay',
676
+ buttonParamsJson: JSON.stringify(button.reviewAndPay)
677
+ };
678
+ }
679
+ else if (hasOptionalProperty(button, 'paymentStatus') && !!button.paymentStatus) {
680
+ return {
681
+ name: 'payment_status',
682
+ buttonParamsJson: JSON.stringify(button.paymentStatus)
683
+ };
684
+ }
685
+ else if (hasOptionalProperty(button, 'paymentMethod') && !!button.paymentMethod) {
686
+ return {
687
+ name: 'payment_method',
688
+ buttonParamsJson: JSON.stringify(button.paymentMethod)
689
+ };
690
+ }
691
+ else if (hasOptionalProperty(button, 'trackOrder') && !!button.trackOrder) {
692
+ return {
693
+ name: 'track_order',
694
+ buttonParamsJson: JSON.stringify({
695
+ id: button.id || button.trackOrder,
696
+ display_text: buttonText || '🚚 Track order'
697
+ })
698
+ };
699
+ }
700
+ else if (hasOptionalProperty(button, 'reorder') && !!button.reorder) {
701
+ return {
702
+ name: 'reorder',
703
+ buttonParamsJson: JSON.stringify({
704
+ id: button.id || button.reorder,
705
+ display_text: buttonText || '🔁 Reorder'
706
+ })
707
+ };
708
+ }
709
+ else if (hasOptionalProperty(button, 'cancelOrder') && !!button.cancelOrder) {
710
+ return {
711
+ name: 'cancel_order',
712
+ buttonParamsJson: JSON.stringify({
713
+ id: button.id || button.cancelOrder,
714
+ display_text: buttonText || '❌ Cancel order'
715
+ })
716
+ };
717
+ }
718
+ // JAP@Changes --- Add navigation / utility button shortcuts
719
+ else if (hasOptionalProperty(button, 'clearChat') && button.clearChat === true) {
720
+ return {
721
+ name: 'clear_chat',
722
+ buttonParamsJson: JSON.stringify({})
723
+ };
724
+ }
725
+ else if (hasOptionalProperty(button, 'screen') && !!button.screen) {
726
+ return {
727
+ name: 'navigateToScreen',
728
+ buttonParamsJson: JSON.stringify({
729
+ screen_name: button.screen,
730
+ data: button.data || {}
731
+ })
732
+ };
733
+ }
734
+ // JAP@Changes --- Add "flow_action" shortcut (WhatsApp Flows form)
735
+ // ⚠️ NOTE: requires a flow_id actually registered & published in the
736
+ // WhatsApp Flows Manager for your business account. A fictitious ID
737
+ // (like 'flow_test_id') will always fail — server-side, not fixable here.
738
+ else if (hasOptionalProperty(button, 'flow') && !!button.flow) {
739
+ return {
740
+ name: 'flow_action',
741
+ buttonParamsJson: JSON.stringify({
742
+ flow_message_version: button.flow.version || '3',
743
+ flow_id: button.flow.id,
744
+ flow_cta: buttonText || button.flow.cta || 'Continue',
745
+ flow_token: button.flow.token || undefined, // JAP@Add --- endpoint/data-channel flows need this
746
+ flow_action: button.flow.action || 'navigate',
747
+ flow_action_payload: button.flow.actionPayload || {
748
+ screen: button.flow.screen || 'WELCOME',
749
+ data: button.flow.data || {}
750
+ }
751
+ })
752
+ };
753
+ }
754
+ // JAP@Changes --- Add "voice_call" / "video_call_button" shortcuts
755
+ else if (hasOptionalProperty(button, 'voiceCall') && !!button.voiceCall) {
756
+ return {
757
+ name: 'voice_call',
758
+ buttonParamsJson: JSON.stringify({
759
+ display_text: buttonText || '📞 Voice call',
760
+ id: button.id || button.voiceCall
761
+ })
762
+ };
763
+ }
764
+ else if (hasOptionalProperty(button, 'videoCall') && !!button.videoCall) {
765
+ return {
766
+ name: 'video_call_button',
767
+ buttonParamsJson: JSON.stringify({
768
+ display_text: buttonText || '🎥 Video call',
769
+ id: button.id || button.videoCall
770
+ })
771
+ };
772
+ }
773
+ return button;
774
+ }),
775
+ messageParamsJson: JSON.stringify(messageParamsJson)
776
+ };
777
+ };
778
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
779
+ ephemeralExpiration = ephemeralExpiration || 0;
780
+ const content = {
781
+ ephemeralMessage: {
782
+ message: {
783
+ protocolMessage: {
784
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
785
+ ephemeralExpiration
786
+ }
787
+ }
788
+ }
789
+ };
790
+ return WAProto.Message.fromObject(content);
791
+ };
792
+ /**
793
+ * Generate forwarded message content like WA does
794
+ * @param message the message to forward
795
+ * @param options.forceForward will show the message as forwarded even if it is from you
796
+ */
797
+ export const generateForwardMessageContent = (message, forceForward) => {
798
+ let content = message.message;
799
+ if (!content) {
800
+ throw new Boom('no content in message', { statusCode: 400 });
801
+ }
802
+ // hacky copy
803
+ content = normalizeMessageContent(content);
804
+ content = proto.Message.decode(proto.Message.encode(content).finish());
805
+ let key = Object.keys(content)[0];
806
+ // JAP@Fix (bug 27): viewOnce/ephemeral messages wrap content in an outer key.
807
+ // Must unwrap first before reading forwardingScore, otherwise score stays 0.
808
+ let innerContent = content?.[key];
809
+ if (key === 'viewOnceMessage' || key === 'ephemeralMessage') {
810
+ const innerKey = innerContent?.message ? Object.keys(innerContent.message)[0] : null;
811
+ if (innerKey) {
812
+ innerContent = innerContent.message[innerKey];
813
+ }
814
+ }
815
+ let score = innerContent?.contextInfo?.forwardingScore || 0;
816
+ score += message.key.fromMe && !forceForward ? 0 : 1;
817
+ if (key === 'conversation') {
818
+ content.extendedTextMessage = { text: content[key] };
819
+ delete content.conversation;
820
+ key = 'extendedTextMessage';
821
+ }
822
+ const key_ = content?.[key];
823
+ if (score > 0) {
824
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
825
+ }
826
+ else {
827
+ key_.contextInfo = {};
828
+ }
829
+ return content;
830
+ };
831
+ export const hasNonNullishProperty = (message, key) => {
832
+ return message != null &&
833
+ typeof message === 'object' &&
834
+ key in message &&
835
+ message[key] != null;
836
+ };
837
+ export const hasOptionalProperty = (obj, key) => {
838
+ return obj != null &&
839
+ typeof obj === 'object' &&
840
+ key in obj &&
841
+ obj[key] != null;
842
+ };
843
+ // JAP@Changes 06-02-26 --- Validate album message media to avoid bug 👀
844
+ export const hasValidAlbumMedia = (message) => {
845
+ return !!(message.imageMessage ||
846
+ message.videoMessage);
847
+ };
848
+ export const hasValidInteractiveHeader = (message) => {
849
+ return !!(message.imageMessage ||
850
+ message.videoMessage ||
851
+ message.documentMessage ||
852
+ message.productMessage ||
853
+ message.locationMessage);
854
+ };
855
+ // JAP@Changes 30-01-26 --- Validate carousel cards header to avoid bug 👀
856
+ export const hasValidCarouselHeader = (message) => {
857
+ return !!(message.imageMessage ||
858
+ message.videoMessage ||
859
+ message.productMessage);
860
+ };
861
+ export const generateWAMessageContent = async (message, options) => {
862
+ var _a, _b;
863
+ let m = {};
864
+ // JAP@Changes 30-01-26 --- Add "raw" boolean to send raw messages directly via generateWAMessage()
865
+ if (hasNonNullishProperty(message, 'raw')) {
866
+ delete message.raw;
867
+ return message;
868
+ }
869
+ // JAP@Changes 09-04-26 --- Add support for code block and table with richResponseMessage
870
+ // JAP@Fix (bug 41 / inline image standalone): gate only checked code/links/table/richResponse,
871
+ // so sending { inlineImage } alone (or headerText/contentText/latex/items/etc standalone) never
872
+ // reached prepareRichResponseMessage and silently fell through to another branch. Added every
873
+ // key that prepareRichResponseMessage actually destructures.
874
+ else if (hasNonNullishProperty(message, 'code') ||
875
+ hasNonNullishProperty(message, 'links') ||
876
+ hasNonNullishProperty(message, 'table') ||
877
+ hasNonNullishProperty(message, 'richResponse') ||
878
+ hasNonNullishProperty(message, 'inlineImage') ||
879
+ hasNonNullishProperty(message, 'inlineVideo') ||
880
+ hasNonNullishProperty(message, 'headerText') ||
881
+ hasNonNullishProperty(message, 'contentText') ||
882
+ hasNonNullishProperty(message, 'footerText') ||
883
+ hasNonNullishProperty(message, 'latex') ||
884
+ hasNonNullishProperty(message, 'items') ||
885
+ hasNonNullishProperty(message, 'posts') ||
886
+ hasNonNullishProperty(message, 'products') ||
887
+ hasNonNullishProperty(message, 'suggested')) {
888
+ m = prepareRichResponseMessage(message);
889
+ }
890
+ else if (hasNonNullishProperty(message, 'text')) {
891
+ const extContent = { text: message.text };
892
+ let urlInfo = message.linkPreview;
893
+ if (typeof urlInfo === 'undefined') {
894
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
895
+ }
896
+ if (urlInfo) {
897
+ extContent.matchedText = urlInfo['matched-text'];
898
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
899
+ extContent.description = urlInfo.description;
900
+ extContent.title = urlInfo.title;
901
+ extContent.previewType = urlInfo.previewType ?? 0;
902
+ extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
903
+ const img = urlInfo.highQualityThumbnail;
904
+ if (img) {
905
+ extContent.thumbnailDirectPath = img.directPath;
906
+ extContent.mediaKey = img.mediaKey;
907
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
908
+ extContent.thumbnailWidth = img.width;
909
+ extContent.thumbnailHeight = img.height;
910
+ extContent.thumbnailSha256 = img.fileSha256;
911
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
912
+ }
913
+ }
914
+ const faviconData = message.favicon;
915
+ if (faviconData && typeof options.upload === 'function') {
916
+ const { imageMessage } = await prepareWAMessageMedia({
917
+ image: faviconData
918
+ }, options);
919
+ extContent.faviconMMSMetadata = {
920
+ thumbnailDirectPath: imageMessage.directPath,
921
+ mediaKey: imageMessage.mediaKey,
922
+ mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
923
+ thumbnailWidth: 32,
924
+ thumbnailHeight: 32,
925
+ thumbnailSha256: imageMessage.fileSha256,
926
+ thumbnailEncSha256: imageMessage.fileEncSha256
927
+ };
928
+ }
929
+ if (options.backgroundColor) {
930
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
931
+ }
932
+ if (options.font) {
933
+ extContent.font = options.font;
934
+ }
935
+ m.extendedTextMessage = extContent;
936
+ }
937
+ else if (hasNonNullishProperty(message, 'contacts')) {
938
+ const contactLen = message.contacts.contacts.length;
939
+ if (!contactLen) {
940
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
941
+ }
942
+ if (contactLen === 1) {
943
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
944
+ }
945
+ else {
946
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
947
+ }
948
+ }
949
+ else if (hasNonNullishProperty(message, 'location')) {
950
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
951
+ }
952
+ else if (hasNonNullishProperty(message, 'react')) {
953
+ if (!message.react.senderTimestampMs) {
954
+ message.react.senderTimestampMs = Date.now();
955
+ }
956
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
957
+ }
958
+ else if (hasNonNullishProperty(message, 'delete')) {
959
+ m.protocolMessage = {
960
+ key: message.delete,
961
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
962
+ };
963
+ }
964
+ else if (hasNonNullishProperty(message, 'forward')) {
965
+ m = generateForwardMessageContent(message.forward, message.force);
966
+ }
967
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
968
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
969
+ ? message.disappearingMessagesInChat
970
+ ? WA_DEFAULT_EPHEMERAL
971
+ : 0
972
+ : message.disappearingMessagesInChat;
973
+ m = prepareDisappearingMessageSettingContent(exp);
974
+ }
975
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
976
+ m.groupInviteMessage = {};
977
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
978
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration ?? 0; // JAP@Fix: default 0 (no expiry) instead of undefined
979
+ m.groupInviteMessage.caption = message.groupInvite.text;
980
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
981
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
982
+ //TODO: use built-in interface and get disappearing mode info etc.
983
+ //TODO: cache / use store!?
984
+ if (options.getProfilePicUrl) {
985
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
986
+ if (pfpUrl) {
987
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
988
+ if (resp.ok) {
989
+ const buf = Buffer.from(await resp.arrayBuffer());
990
+ // JAP@Fix: upload thumbnail to WA server so thumbnailDirectPath/mediaKey are set properly
991
+ if (options.upload) {
992
+ try {
993
+ const uploaded = await prepareWAMessageMedia({ image: buf }, { upload: options.upload });
994
+ if (uploaded.imageMessage) {
995
+ m.groupInviteMessage.jpegThumbnail = buf;
996
+ m.groupInviteMessage.thumbnailDirectPath = uploaded.imageMessage.directPath;
997
+ m.groupInviteMessage.thumbnailSha256 = uploaded.imageMessage.fileSha256;
998
+ m.groupInviteMessage.thumbnailEncSha256 = uploaded.imageMessage.fileEncSha256;
999
+ m.groupInviteMessage.mediaKey = uploaded.imageMessage.mediaKey;
1000
+ }
1001
+ } catch {
1002
+ // fallback: at least attach raw jpeg
1003
+ m.groupInviteMessage.jpegThumbnail = buf;
1004
+ }
1005
+ } else {
1006
+ m.groupInviteMessage.jpegThumbnail = buf;
1007
+ }
1008
+ }
1009
+ }
1010
+ }
1011
+ }
1012
+ else if (hasNonNullishProperty(message, 'stickers')) {
1013
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
1014
+ }
1015
+ else if (hasNonNullishProperty(message, 'pin')) {
1016
+ m.pinInChatMessage = {};
1017
+ m.messageContextInfo = {};
1018
+ m.pinInChatMessage.key = message.pin;
1019
+ m.pinInChatMessage.type = message.type;
1020
+ m.pinInChatMessage.senderTimestampMs = Date.now();
1021
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
1022
+ }
1023
+ else if (hasNonNullishProperty(message, 'keep')) {
1024
+ m.keepInChatMessage = {};
1025
+ m.keepInChatMessage.key = message.keep;
1026
+ m.keepInChatMessage.keepType = message.type;
1027
+ m.keepInChatMessage.timestampMs = Date.now();
1028
+ }
1029
+ else if (hasNonNullishProperty(message, 'flowReply')) {
1030
+ m.interactiveResponseMessage = {
1031
+ body: {
1032
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
1033
+ text: message.flowReply.text
1034
+ },
1035
+ nativeFlowResponseMessage: {
1036
+ name: message.flowReply.name,
1037
+ paramsJson: message.flowReply.paramsJson || '{}',
1038
+ version: message.flowReply.version || 1
1039
+ }
1040
+ };
1041
+ }
1042
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
1043
+ switch (message.type) {
1044
+ case 'template':
1045
+ m.templateButtonReplyMessage = {
1046
+ selectedDisplayText: message.buttonReply.displayText,
1047
+ selectedId: message.buttonReply.id,
1048
+ selectedIndex: message.buttonReply.index
1049
+ };
1050
+ break;
1051
+ case 'plain':
1052
+ m.buttonsResponseMessage = {
1053
+ selectedButtonId: message.buttonReply.id,
1054
+ selectedDisplayText: message.buttonReply.displayText,
1055
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
1056
+ };
1057
+ break;
1058
+ }
1059
+ }
1060
+ else if (hasNonNullishProperty(message, 'listReply')) {
1061
+ m.listResponseMessage = {
1062
+ description: message.listReply.description,
1063
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
1064
+ singleSelectReply: {
1065
+ selectedRowId: message.listReply.id
1066
+ },
1067
+ title: message.listReply.title
1068
+ };
1069
+ }
1070
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
1071
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
1072
+ m.ptvMessage = videoMessage;
1073
+ }
1074
+ else if (hasNonNullishProperty(message, 'product')) {
1075
+ m.productMessage = await prepareProductMessage(message, options);
1076
+ }
1077
+ else if (hasNonNullishProperty(message, 'event')) {
1078
+ m.eventMessage = {};
1079
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
1080
+ if (message.event.call && options.getCallLink) {
1081
+ const token = await options.getCallLink(message.event.call, { startTime });
1082
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
1083
+ }
1084
+ m.messageContextInfo = {
1085
+ // encKey
1086
+ messageSecret: message.event.messageSecret || randomBytes(32)
1087
+ };
1088
+ m.eventMessage.name = message.event.name;
1089
+ m.eventMessage.description = message.event.description;
1090
+ m.eventMessage.startTime = startTime;
1091
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
1092
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
1093
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
1094
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
1095
+ // JAP@Add --- WA 2026 event reminders (hasReminder + seconds-before-start offset)
1096
+ m.eventMessage.hasReminder = message.event.reminder ?? message.event.hasReminder ?? false;
1097
+ m.eventMessage.reminderOffsetSec = message.event.reminderOffsetSec;
1098
+ m.eventMessage.location = message.event.location;
1099
+ }
1100
+ // JAP@Add --- scheduled-call primitive (ScheduledCallCreationMessage).
1101
+ // CallType enum: VOICE = 1, VIDEO = 2.
1102
+ else if (hasNonNullishProperty(message, 'scheduledCall')) {
1103
+ const sc = message.scheduledCall;
1104
+ const ts = sc.scheduledAt instanceof Date ? sc.scheduledAt.getTime() : Number(sc.scheduledAt);
1105
+ if (!Number.isFinite(ts) || ts <= 0) {
1106
+ throw new Boom('Invalid scheduledCall.scheduledAt (expected a Date or epoch-ms number)', { statusCode: 400 });
1107
+ }
1108
+ m.scheduledCallCreationMessage = {
1109
+ scheduledTimestampMs: ts,
1110
+ callType: sc.callType === 'video' ? 2 : 1,
1111
+ title: sc.title
1112
+ };
1113
+ }
1114
+ // JAP@Add --- scheduled-call edit/cancel (ScheduledCallEditMessage; CANCEL = 1 is the only edit type WA defines).
1115
+ else if (hasNonNullishProperty(message, 'scheduledCallEdit')) {
1116
+ m.scheduledCallEditMessage = {
1117
+ key: message.scheduledCallEdit.key,
1118
+ editType: 1
1119
+ };
1120
+ }
1121
+ else if (hasNonNullishProperty(message, 'poll')) {
1122
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
1123
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
1124
+ if (!Array.isArray(message.poll.values)) {
1125
+ throw new Boom('Invalid poll values', { statusCode: 400 });
1126
+ }
1127
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
1128
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
1129
+ statusCode: 400
1130
+ });
1131
+ }
1132
+ const pollCreationMessage = {
1133
+ name: message.poll.name,
1134
+ selectableOptionsCount: message.poll.selectableCount,
1135
+ options: message.poll.values.map(optionName => ({ optionName })),
1136
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
1137
+ hideParticipantName: message.poll.hideVoter ?? false,
1138
+ allowAddOption: message.poll.canAddOption ?? false
1139
+ };
1140
+ if (message.poll.toAnnouncementGroup) {
1141
+ // poll v2 is for community announcement groups (single select and multiple)
1142
+ m.pollCreationMessageV2 = pollCreationMessage;
1143
+ }
1144
+ else {
1145
+ // JAP@Changes 08-02-26 --- Add quiz message support
1146
+ if (message.poll.pollType === 1) {
1147
+ if (!message.poll.correctAnswer) {
1148
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
1149
+ }
1150
+ m.pollCreationMessageV5 = {
1151
+ // JAP@Note 08-02-26 --- quiz for newsletter only
1152
+ ...pollCreationMessage,
1153
+ correctAnswer: {
1154
+ optionName: message.poll.correctAnswer.toString()
1155
+ },
1156
+ pollType: 1,
1157
+ selectableOptionsCount: 1
1158
+ };
1159
+ }
1160
+ else if (message.poll.selectableCount === 1) {
1161
+ //poll v3 is for single select polls
1162
+ m.pollCreationMessageV3 = pollCreationMessage;
1163
+ }
1164
+ else {
1165
+ // poll for multiple choice polls
1166
+ m.pollCreationMessage = pollCreationMessage;
1167
+ }
1168
+ }
1169
+ m.messageContextInfo = {
1170
+ // encKey
1171
+ messageSecret: message.poll.messageSecret || randomBytes(32)
1172
+ };
1173
+ }
1174
+ // JAP@Changes 08-02-26 --- Add poll result snapshot message
1175
+ else if (hasNonNullishProperty(message, 'pollResult')) {
1176
+ const pollResultSnapshotMessage = {
1177
+ name: message.pollResult.name,
1178
+ pollVotes: message.pollResult.votes.map(vote => ({
1179
+ optionName: vote.name,
1180
+ optionVoteCount: parseInt(vote.voteCount)
1181
+ }))
1182
+ };
1183
+ if (message.pollResult.pollType === 1) {
1184
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
1185
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
1186
+ }
1187
+ else {
1188
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
1189
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
1190
+ }
1191
+ }
1192
+ // JAP@Changes 08-02-26 --- Add poll update message
1193
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
1194
+ if (!message.pollUpdate.key) {
1195
+ throw new Boom('Message key is required', { statusCode: 400 });
1196
+ }
1197
+ if (!message.pollUpdate.vote) {
1198
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
1199
+ }
1200
+ m.pollUpdateMessage = {
1201
+ metadata: message.pollUpdate.metadata,
1202
+ pollCreationMessageKey: message.pollUpdate.key,
1203
+ senderTimestampMs: Date.now(),
1204
+ vote: message.pollUpdate.vote
1205
+ };
1206
+ }
1207
+ // JAP@Changes 01-02-26 --- Add payment invite message
1208
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
1209
+ m.paymentInviteMessage = {
1210
+ expiryTimestamp: Date.now(),
1211
+ serviceType: message.paymentInviteServiceType
1212
+ };
1213
+ }
1214
+ // JAP@Changes 01-02-26 --- Add order message
1215
+ else if (hasNonNullishProperty(message, 'orderText')) {
1216
+ if (!Buffer.isBuffer(message.thumbnail)) {
1217
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
1218
+ }
1219
+ m.orderMessage = {
1220
+ itemCount: 1,
1221
+ messageVersion: 1,
1222
+ orderTitle: LIBRARY_NAME,
1223
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
1224
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
1225
+ token: generateMessageIDV2(),
1226
+ totalAmount1000: 1000,
1227
+ totalCurrencyCode: 'IDR',
1228
+ ...message,
1229
+ message: message.orderText
1230
+ };
1231
+ delete m.orderMessage.orderText;
1232
+ }
1233
+ // JAP@Changes 31-01-26 --- Add support for album messages
1234
+ else if (hasNonNullishProperty(message, 'album')) {
1235
+ if (!Array.isArray(message.album)) {
1236
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
1237
+ }
1238
+ let videoCount = 0;
1239
+ for (let i = 0; i < message.album.length; i++) {
1240
+ if (message.album[i].video)
1241
+ videoCount++;
1242
+ }
1243
+ ;
1244
+ let imageCount = 0;
1245
+ for (let i = 0; i < message.album.length; i++) {
1246
+ if (message.album[i].image)
1247
+ imageCount++;
1248
+ }
1249
+ ;
1250
+ if ((videoCount + imageCount) < 2) {
1251
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
1252
+ }
1253
+ m.albumMessage = {
1254
+ expectedImageCount: imageCount,
1255
+ expectedVideoCount: videoCount
1256
+ };
1257
+ }
1258
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
1259
+ m.protocolMessage = {
1260
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
1261
+ };
1262
+ }
1263
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
1264
+ m.requestPhoneNumberMessage = {};
1265
+ }
1266
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
1267
+ m.protocolMessage = {
1268
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
1269
+ limitSharing: {
1270
+ sharingLimited: message.limitSharing === true,
1271
+ trigger: 1,
1272
+ limitSharingSettingTimestamp: Date.now(),
1273
+ initiatedByMe: true
1274
+ }
1275
+ };
1276
+ }
1277
+ else if (hasNonNullishProperty(message, 'music')) {
1278
+ // JAP@Add --- Music message (experimental: needs real provider catalog IDs)
1279
+ const { songUri, artworkUri, style, embeddedMusic } = message.music || {};
1280
+ if (!songUri && !embeddedMusic) {
1281
+ throw new Boom('music needs { songUri } and/or { embeddedMusic }', { statusCode: 400 });
1282
+ }
1283
+ m.musicMessage = {
1284
+ ...(songUri ? { songUri } : {}),
1285
+ ...(artworkUri ? { artworkUri } : {}),
1286
+ ...(style ? { style } : {}),
1287
+ ...(embeddedMusic ? { embeddedMusic } : {})
1288
+ };
1289
+ }
1290
+ else if (hasNonNullishProperty(message, 'requestPayment')) {
1291
+ // JAP@Add --- payment request (UPI-style requestPaymentMessage)
1292
+ const req = message.requestPayment || {};
1293
+ const currencyCodeIso4217 = req.currency || req.currencyCode || req.currencyCodeIso4217;
1294
+ const amount1000 = req.amount1000 ?? (req.amount != null ? Math.round(Number(req.amount) * 1000) : undefined);
1295
+ if (!currencyCodeIso4217 || typeof currencyCodeIso4217 !== 'string') {
1296
+ throw new Boom('requestPayment needs { currency } (ISO-4217, e.g. IDR)', { statusCode: 400 });
1297
+ }
1298
+ if (amount1000 == null || !Number.isFinite(amount1000) || amount1000 <= 0) {
1299
+ throw new Boom('requestPayment needs { amount } (> 0) or { amount1000 }', { statusCode: 400 });
1300
+ }
1301
+ m.requestPaymentMessage = {
1302
+ currencyCodeIso4217,
1303
+ amount1000,
1304
+ ...(req.note ? { noteMessage: { conversation: req.note } } : {}),
1305
+ ...(req.requestFrom ? { requestFrom: req.requestFrom } : {}),
1306
+ ...(req.expiry ? { expiryTimestamp: req.expiry instanceof Date ? Math.floor(req.expiry.getTime() / 1000) : req.expiry } : {})
1307
+ };
1308
+ }
1309
+ else if (hasNonNullishProperty(message, 'sendPayment')) {
1310
+ // JAP@Add --- pay an incoming request (sendPaymentMessage)
1311
+ const pay = message.sendPayment || {};
1312
+ if (!pay.requestKey && !pay.key) {
1313
+ throw new Boom('sendPayment needs { requestKey } (key of the request message)', { statusCode: 400 });
1314
+ }
1315
+ m.sendPaymentMessage = {
1316
+ requestMessageKey: pay.requestKey || pay.key,
1317
+ ...(pay.note ? { noteMessage: { conversation: pay.note } } : {}),
1318
+ ...(pay.transactionData ? { transactionData: pay.transactionData } : {})
1319
+ };
1320
+ }
1321
+ else if (hasNonNullishProperty(message, 'cancelPayment')) {
1322
+ // JAP@Add --- cancel your own payment request
1323
+ const key = message.cancelPayment?.key || message.cancelPayment;
1324
+ if (!key || typeof key !== 'object') {
1325
+ throw new Boom('cancelPayment needs { key } (key of your request message)', { statusCode: 400 });
1326
+ }
1327
+ m.cancelPaymentRequestMessage = { key };
1328
+ }
1329
+ else if (hasNonNullishProperty(message, 'declinePayment')) {
1330
+ // JAP@Add --- decline an incoming payment request
1331
+ const key = message.declinePayment?.key || message.declinePayment;
1332
+ if (!key || typeof key !== 'object') {
1333
+ throw new Boom('declinePayment needs { key } (key of the request message)', { statusCode: 400 });
1334
+ }
1335
+ m.declinePaymentRequestMessage = { key };
1336
+ }
1337
+ else if (hasNonNullishProperty(message, 'invoice')) {
1338
+ // JAP@Add --- invoice attachment message
1339
+ const inv = message.invoice || {};
1340
+ if (!inv.note || typeof inv.note !== 'string') {
1341
+ throw new Boom('invoice needs { note }', { statusCode: 400 });
1342
+ }
1343
+ m.invoiceMessage = {
1344
+ note: inv.note,
1345
+ ...(inv.token ? { token: inv.token } : {}),
1346
+ ...(inv.attachmentType ? { attachmentType: inv.attachmentType } : {}),
1347
+ ...(inv.attachmentMimetype ? { attachmentMimetype: inv.attachmentMimetype } : {}),
1348
+ ...(inv.attachmentDirectPath ? { attachmentDirectPath: inv.attachmentDirectPath } : {})
1349
+ };
1350
+ }
1351
+ else if (hasNonNullishProperty(message, 'pollAddOption')) {
1352
+ // JAP@Add --- WA 2026: add options to a live poll
1353
+ const { pollKey, key, options } = message.pollAddOption || {};
1354
+ const pollCreationMessageKey = pollKey || key;
1355
+ if (!pollCreationMessageKey || typeof pollCreationMessageKey !== 'object') {
1356
+ throw new Boom('pollAddOption needs { pollKey } (key of the poll message)', { statusCode: 400 });
1357
+ }
1358
+ if (!Array.isArray(options) || !options.length) {
1359
+ throw new Boom('pollAddOption needs a non-empty { options } array', { statusCode: 400 });
1360
+ }
1361
+ m.pollAddOptionMessage = {
1362
+ pollCreationMessageKey,
1363
+ addOption: options.map((o) => (typeof o === 'string' ? { optionName: o } : o))
1364
+ };
1365
+ }
1366
+ else if (hasNonNullishProperty(message, 'eventInvite')) {
1367
+ // JAP@Add --- event invitation card (eventInviteMessage)
1368
+ const inv = message.eventInvite || {};
1369
+ if (!inv.eventTitle || typeof inv.eventTitle !== 'string') {
1370
+ throw new Boom('eventInvite needs { eventTitle }', { statusCode: 400 });
1371
+ }
1372
+ const toSec = (v) => (v instanceof Date ? Math.floor(v.getTime() / 1000) : v);
1373
+ m.eventInviteMessage = {
1374
+ eventTitle: inv.eventTitle,
1375
+ ...(inv.eventId ? { eventId: inv.eventId } : {}),
1376
+ ...(inv.startTime ? { startTime: toSec(inv.startTime) } : {}),
1377
+ ...(inv.endTime ? { endTime: toSec(inv.endTime) } : {}),
1378
+ ...(inv.caption ? { caption: inv.caption } : {}),
1379
+ ...(inv.isCanceled != null ? { isCanceled: inv.isCanceled } : {}),
1380
+ ...(inv.callLink ? { callLink: inv.callLink } : {})
1381
+ };
1382
+ }
1383
+ else if (hasNonNullishProperty(message, 'newsletterInvite')) {
1384
+ // JAP@Add --- channel invite card (newsletterAdminInviteMessage)
1385
+ const inv = message.newsletterInvite || {};
1386
+ if (!inv.newsletterJid || !inv.newsletterName) {
1387
+ throw new Boom('newsletterInvite needs { newsletterJid, newsletterName }', { statusCode: 400 });
1388
+ }
1389
+ m.newsletterAdminInviteMessage = {
1390
+ newsletterJid: inv.newsletterJid,
1391
+ newsletterName: inv.newsletterName,
1392
+ ...(inv.caption ? { caption: inv.caption } : {}),
1393
+ ...(inv.inviteExpiration ? { inviteExpiration: inv.inviteExpiration } : {})
1394
+ };
1395
+ }
1396
+ else if (hasNonNullishProperty(message, 'comment')) {
1397
+ // JAP@Add --- comment attached to another message (channels/posts)
1398
+ const c = message.comment || {};
1399
+ if (!c.text || !c.targetKey) {
1400
+ throw new Boom('comment needs { text, targetKey }', { statusCode: 400 });
1401
+ }
1402
+ m.commentMessage = { message: { conversation: c.text }, targetMessageKey: c.targetKey };
1403
+ }
1404
+ else if (hasNonNullishProperty(message, 'statusQuote')) {
1405
+ // JAP@Add --- quote a status update
1406
+ const q = message.statusQuote || {};
1407
+ if (!q.text || !q.originalStatusId) {
1408
+ throw new Boom('statusQuote needs { text, originalStatusId }', { statusCode: 400 });
1409
+ }
1410
+ m.statusQuotedMessage = {
1411
+ text: q.text,
1412
+ originalStatusId: q.originalStatusId,
1413
+ ...(q.type != null ? { type: q.type } : {})
1414
+ };
1415
+ }
1416
+ else {
1417
+ m = await prepareWAMessageMedia(message, options);
1418
+ // JAP@Add: MediaKeyDomain passthrough (WA 2026; unset by default — server labels it)
1419
+ if (message.mediaKeyDomain != null) {
1420
+ for (const k of ['audioMessage', 'documentMessage', 'imageMessage', 'stickerMessage', 'videoMessage']) {
1421
+ if (m[k]) {
1422
+ m[k].mediaKeyDomain = message.mediaKeyDomain;
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ // JAP@Changes 30-01-26 --- Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
1428
+ if (hasNonNullishProperty(message, 'buttons')) {
1429
+ const buttonsMessage = {
1430
+ buttons: message.buttons.map(button => {
1431
+ // JAP@Changes 12-03-26 --- Add "single_select" shortcut!
1432
+ const buttonText = button.text || button.buttonText;
1433
+ if (hasOptionalProperty(button, 'sections')) {
1434
+ return {
1435
+ nativeFlowInfo: {
1436
+ name: 'single_select',
1437
+ paramsJson: JSON.stringify({
1438
+ title: buttonText,
1439
+ sections: button.sections
1440
+ })
1441
+ },
1442
+ type: ButtonType.NATIVE_FLOW
1443
+ };
1444
+ }
1445
+ else if (hasOptionalProperty(button, 'name')) {
1446
+ return {
1447
+ nativeFlowInfo: {
1448
+ name: button.name,
1449
+ paramsJson: button.paramsJson
1450
+ },
1451
+ type: ButtonType.NATIVE_FLOW
1452
+ };
1453
+ }
1454
+ return {
1455
+ buttonId: button.id || button.buttonId,
1456
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1457
+ type: button.type || ButtonType.RESPONSE
1458
+ };
1459
+ })
1460
+ };
1461
+ if (hasOptionalProperty(message, 'text')) {
1462
+ buttonsMessage.contentText = message.text;
1463
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
1464
+ }
1465
+ else {
1466
+ if (hasOptionalProperty(message, 'caption')) {
1467
+ buttonsMessage.contentText = message.caption;
1468
+ }
1469
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1470
+ buttonsMessage.headerType = ButtonHeaderType[type];
1471
+ Object.assign(buttonsMessage, m);
1472
+ }
1473
+ if (hasOptionalProperty(message, 'footer')) {
1474
+ buttonsMessage.footerText = message.footer;
1475
+ }
1476
+ m = { buttonsMessage };
1477
+ }
1478
+ else if (hasNonNullishProperty(message, 'sections')) {
1479
+ const listMessage = {
1480
+ sections: message.sections,
1481
+ buttonText: message.buttonText,
1482
+ title: message.title,
1483
+ footerText: message.footer,
1484
+ description: message.text,
1485
+ listType: ListType.SINGLE_SELECT
1486
+ };
1487
+ m = { listMessage };
1488
+ }
1489
+ // JAP@Note 03-02-26 --- This message type is shown on WhatsApp Web/Desktop and iOS (I guess 。⁠◕⁠‿⁠◕⁠。). On Android, it only appears in newsletter (so far ಥ⁠‿⁠ಥ)
1490
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1491
+ const hydratedTemplate = {
1492
+ hydratedButtons: message.templateButtons.map((button, i) => {
1493
+ const buttonText = button.text || button.buttonText;
1494
+ if (hasOptionalProperty(button, 'id')) {
1495
+ return {
1496
+ index: i,
1497
+ quickReplyButton: {
1498
+ displayText: buttonText || '👉🏻 Click',
1499
+ id: button.id
1500
+ }
1501
+ };
1502
+ }
1503
+ else if (hasOptionalProperty(button, 'url')) {
1504
+ return {
1505
+ index: i,
1506
+ urlButton: {
1507
+ displayText: buttonText || '🌐 Visit',
1508
+ url: button.url
1509
+ }
1510
+ };
1511
+ }
1512
+ else if (hasOptionalProperty(button, 'call')) {
1513
+ return {
1514
+ index: i,
1515
+ callButton: {
1516
+ displayText: buttonText || '📞 Call',
1517
+ phoneNumber: button.call
1518
+ }
1519
+ };
1520
+ }
1521
+ button.index = button.index || i;
1522
+ return button;
1523
+ })
1524
+ };
1525
+ if (hasOptionalProperty(message, 'text')) {
1526
+ hydratedTemplate.hydratedContentText = message.text;
1527
+ }
1528
+ else {
1529
+ if (hasOptionalProperty(message, 'caption')) {
1530
+ hydratedTemplate.hydratedTitleText = message.title;
1531
+ hydratedTemplate.hydratedContentText = message.caption;
1532
+ }
1533
+ ;
1534
+ Object.assign(hydratedTemplate, m);
1535
+ }
1536
+ if (hasOptionalProperty(message, 'footer')) {
1537
+ hydratedTemplate.hydratedFooterText = message.footer;
1538
+ }
1539
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // JAP@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1540
+ m = {
1541
+ templateMessage: {
1542
+ hydratedFourRowTemplate: hydratedTemplate,
1543
+ hydratedTemplate: hydratedTemplate
1544
+ }
1545
+ };
1546
+ }
1547
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1548
+ const interactiveMessage = {
1549
+ nativeFlowMessage: prepareNativeFlowButtons(message)
1550
+ };
1551
+ if (hasOptionalProperty(message, 'bizJid')) {
1552
+ interactiveMessage.collectionMessage = {
1553
+ bizJid: message.bizJid,
1554
+ id: message.id,
1555
+ messageVersion: 1
1556
+ };
1557
+ }
1558
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1559
+ interactiveMessage.shopStorefrontMessage = {
1560
+ surface: message.shopSurface,
1561
+ id: message.id,
1562
+ messageVersion: 1
1563
+ };
1564
+ }
1565
+ if (hasOptionalProperty(message, 'text')) {
1566
+ interactiveMessage.body = { text: message.text };
1567
+ }
1568
+ else {
1569
+ if (hasOptionalProperty(message, 'caption')) {
1570
+ const isValidHeader = hasValidInteractiveHeader(m);
1571
+ if (!isValidHeader) {
1572
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1573
+ }
1574
+ interactiveMessage.header = {
1575
+ title: message.title || '',
1576
+ subtitle: message.subtitle || '',
1577
+ hasMediaAttachment: isValidHeader
1578
+ };
1579
+ interactiveMessage.body = { text: message.caption };
1580
+ }
1581
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1582
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1583
+ }
1584
+ Object.assign(interactiveMessage.header, m);
1585
+ }
1586
+ if (hasOptionalProperty(message, 'audioFooter')) {
1587
+ const { audioMessage } = await prepareWAMessageMedia({
1588
+ audio: message.audioFooter
1589
+ }, options);
1590
+ interactiveMessage.footer = {
1591
+ audioMessage,
1592
+ hasMediaAttachment: true
1593
+ };
1594
+ }
1595
+ else if (hasOptionalProperty(message, 'footer')) {
1596
+ interactiveMessage.footer = { text: message.footer };
1597
+ }
1598
+ m = { interactiveMessage };
1599
+ }
1600
+ else if (hasNonNullishProperty(message, 'cards')) {
1601
+ const interactiveMessage = {
1602
+ carouselMessage: {
1603
+ cards: await Promise.all(message.cards.map(async (card) => {
1604
+ let carouselHeader = {};
1605
+ if (hasNonNullishProperty(card, 'product')) {
1606
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1607
+ }
1608
+ else {
1609
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1610
+ }
1611
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1612
+ if (!isValidHeader) {
1613
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1614
+ }
1615
+ const carouselCard = {
1616
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1617
+ };
1618
+ if (hasOptionalProperty(card, 'text')) {
1619
+ carouselCard.body = { text: card.text };
1620
+ }
1621
+ else {
1622
+ if (hasOptionalProperty(card, 'caption')) {
1623
+ carouselCard.header = {
1624
+ title: card.title || '',
1625
+ subtitle: card.subtitle || '',
1626
+ hasMediaAttachment: isValidHeader
1627
+ };
1628
+ carouselCard.body = { text: card.caption };
1629
+ }
1630
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1631
+ carouselCard.jpegThumbnail = card.thumbnail;
1632
+ }
1633
+ Object.assign(carouselCard.header, carouselHeader);
1634
+ }
1635
+ if (hasOptionalProperty(card, 'audioFooter')) {
1636
+ const { audioMessage } = await prepareWAMessageMedia({
1637
+ audio: card.audioFooter
1638
+ }, options);
1639
+ carouselCard.footer = {
1640
+ audioMessage,
1641
+ hasMediaAttachment: true
1642
+ };
1643
+ }
1644
+ else if (hasOptionalProperty(card, 'footer')) {
1645
+ carouselCard.footer = { text: card.footer };
1646
+ }
1647
+ // JAP@Fix (bug 20): add per-card contextInfo support
1648
+ // Allows each carousel card to have its own reply context, forward info, etc.
1649
+ if (hasNonNullishProperty(card, 'contextInfo')) {
1650
+ carouselCard.contextInfo = card.contextInfo;
1651
+ }
1652
+ return carouselCard;
1653
+ })),
1654
+ carouselCardType: CarouselCardType.UNKNOWN,
1655
+ messageVersion: 1
1656
+ }
1657
+ };
1658
+ if (hasOptionalProperty(message, 'text')) {
1659
+ interactiveMessage.body = { text: message.text };
1660
+ }
1661
+ if (hasOptionalProperty(message, 'footer')) {
1662
+ interactiveMessage.footer = { text: message.footer };
1663
+ }
1664
+ m = { interactiveMessage };
1665
+ }
1666
+ // JAP@Changes 01-02-26 --- Add request payment message
1667
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1668
+ const requestPaymentMessage = {
1669
+ amount: {
1670
+ currencyCode: 'IDR',
1671
+ offset: 1000,
1672
+ value: 1000
1673
+ },
1674
+ amount1000: 1000,
1675
+ currencyCodeIso4217: 'IDR',
1676
+ expiryTimestamp: Date.now(),
1677
+ noteMessage: m,
1678
+ requestFrom: message.requestPaymentFrom,
1679
+ ...message
1680
+ };
1681
+ delete requestPaymentMessage.requestPaymentFrom;
1682
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1683
+ Object.assign(requestPaymentMessage.noteMessage, m);
1684
+ }
1685
+ else {
1686
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1687
+ }
1688
+ m = { requestPaymentMessage };
1689
+ }
1690
+ // JAP@Changes 01-02-26 --- Add invoice message
1691
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1692
+ const attachment = m.imageMessage || m.documentMessage;
1693
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1694
+ const invoiceMessage = {
1695
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1696
+ note: message.invoiceNote
1697
+ };
1698
+ if (attachment) {
1699
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1700
+ Object.assign(invoiceMessage, {
1701
+ attachmentDirectPath: directPath,
1702
+ attachmentFileEncSha256: fileEncSha256,
1703
+ attachmentFileSha256: fileSha256,
1704
+ attachmentJpegThumbnail: jpegThumbnail,
1705
+ attachmentMediaKey: mediaKey,
1706
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1707
+ attachmentMimetype: mimetype,
1708
+ token: generateMessageIDV2()
1709
+ });
1710
+ }
1711
+ else {
1712
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1713
+ }
1714
+ m = { invoiceMessage };
1715
+ }
1716
+ // JAP@Changes 31-01-26 --- Add direct externalAdReply access (no need to create contextInfo first)
1717
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1718
+ const messageType = Object.keys(m)[0];
1719
+ const key = m[messageType];
1720
+ const content = message.externalAdReply;
1721
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1722
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1723
+ }
1724
+ if (!content.url || typeof content.url !== 'string') {
1725
+ content.url = DONATE_URL || ''; // JAP@Fix (bug 10): DONATE_URL now empty — use empty string as safe fallback
1726
+ }
1727
+ const externalAdReply = {
1728
+ ...content,
1729
+ body: content.body,
1730
+ mediaType: content.mediaType || 1,
1731
+ mediaUrl: content.url,
1732
+ renderLargerThumbnail: content.largeThumbnail,
1733
+ sourceUrl: content.url,
1734
+ thumbnail: content.thumbnail,
1735
+ thumbnailUrl: content.url + '?update=' + Date.now(),
1736
+ title: content.title || LIBRARY_NAME
1737
+ };
1738
+ delete externalAdReply.subTitle;
1739
+ delete externalAdReply.largeThumbnail;
1740
+ delete externalAdReply.url;
1741
+ if ('contextInfo' in key && !!key.contextInfo) {
1742
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1743
+ }
1744
+ else if (key) {
1745
+ key.contextInfo = { externalAdReply };
1746
+ }
1747
+ }
1748
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1749
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1750
+ const messageType = Object.keys(m)[0];
1751
+ const key = m[messageType];
1752
+ if (key && 'contextInfo' in key) {
1753
+ key.contextInfo = key.contextInfo || {};
1754
+ if (message.mentions?.length) {
1755
+ key.contextInfo.mentionedJid = message.mentions;
1756
+ }
1757
+ if (message.mentionAll) {
1758
+ key.contextInfo.nonJidMentions = 1;
1759
+ }
1760
+ }
1761
+ else if (key) {
1762
+ key.contextInfo = {
1763
+ mentionedJid: message.mentions,
1764
+ nonJidMentions: message.mentionAll ? 1 : 0
1765
+ };
1766
+ }
1767
+ }
1768
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1769
+ const messageType = Object.keys(m)[0];
1770
+ const key = m[messageType];
1771
+ if ('contextInfo' in key && !!key.contextInfo) {
1772
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1773
+ }
1774
+ else if (key) {
1775
+ key.contextInfo = message.contextInfo;
1776
+ }
1777
+ }
1778
+ // JAP@Fix: groupStatus wrapping — audio uses groupStatusMessage (v1) for compatibility
1779
+ // with older WA versions. groupStatusMessageV2 causes black screen ("versi tidak mendukung")
1780
+ // on recipients with older WhatsApp. Only non-audio media uses V2.
1781
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1782
+ const messageType = Object.keys(m)[0];
1783
+ const key = m[messageType];
1784
+ if ('contextInfo' in key && !!key.contextInfo) {
1785
+ key.contextInfo.isGroupStatus = message.groupStatus;
1786
+ }
1787
+ else if (key) {
1788
+ key.contextInfo = {
1789
+ isGroupStatus: message.groupStatus
1790
+ };
1791
+ }
1792
+ // JAP@Fix: audio must use groupStatusMessage (v1), not V2
1793
+ // V2 is not supported by older WA clients causing black screen for audio
1794
+ if (messageType === 'audioMessage') {
1795
+ m = { groupStatusMessage: { message: m } };
1796
+ } else {
1797
+ m = { groupStatusMessageV2: { message: m } };
1798
+ }
1799
+ delete message.groupStatus;
1800
+ }
1801
+ // JAP@Changes 06-05-26 --- Add "spoiler" boolean to set contextInfo.isSpoiler and wrap message into spoilerMessage
1802
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1803
+ const messageType = Object.keys(m)[0];
1804
+ const key = m[messageType];
1805
+ if ('contextInfo' in key && !!key.contextInfo) {
1806
+ key.contextInfo.isSpoiler = message.spoiler;
1807
+ }
1808
+ else if (key) {
1809
+ key.contextInfo = {
1810
+ isSpoiler: message.spoiler
1811
+ };
1812
+ }
1813
+ m = { spoilerMessage: { message: m } };
1814
+ delete message.spoiler;
1815
+ }
1816
+ // JAP@Changes 02-02-26 --- Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
1817
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1818
+ if (!m.interactiveMessage) {
1819
+ throw new Boom('Invalid message type for template', { statusCode: 400 }); // JAP@Note 02-02-26 --- To avoid bug 👀
1820
+ }
1821
+ m = {
1822
+ templateMessage: {
1823
+ interactiveMessageTemplate: m.interactiveMessage,
1824
+ templateId: message.id || 'template-' + Date.now() // JAP@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1825
+ }
1826
+ };
1827
+ delete message.interactiveAsTemplate;
1828
+ }
1829
+ // JAP@Changes 30-01-26 --- Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
1830
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1831
+ m = { ephemeralMessage: { message: m } };
1832
+ delete message.ephemeral;
1833
+ }
1834
+ // JAP@Changes 16-05-26 --- Add wrap message into lottieStickerMessage by isLottie boolean
1835
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1836
+ m = { lottieStickerMessage: { message: m } };
1837
+ }
1838
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1839
+ m = { viewOnceMessage: { message: m } };
1840
+ }
1841
+ // JAP@Changes 03-02-26 --- Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
1842
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1843
+ m = { viewOnceMessageV2: { message: m } };
1844
+ delete message.viewOnceV2;
1845
+ }
1846
+ // JAP@Changes 03-02-26 --- Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
1847
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1848
+ m = { viewOnceMessageV2Extension: { message: m } };
1849
+ delete message.viewOnceV2Extension;
1850
+ }
1851
+ if (hasOptionalProperty(message, 'edit')) {
1852
+ m = {
1853
+ protocolMessage: {
1854
+ key: message.edit,
1855
+ editedMessage: m,
1856
+ timestampMs: Date.now(),
1857
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1858
+ }
1859
+ };
1860
+ }
1861
+ if (shouldIncludeReportingToken(m)) {
1862
+ m.messageContextInfo = m.messageContextInfo || {};
1863
+ if (!m.messageContextInfo.messageSecret) {
1864
+ m.messageContextInfo.messageSecret = randomBytes(32);
1865
+ }
1866
+ }
1867
+ return WAProto.Message.create(m);
1868
+ };
1869
+ export const generateWAMessageFromContent = (jid, message, options) => {
1870
+ // set timestamp to now
1871
+ // if not specified
1872
+ if (!options.timestamp) {
1873
+ options.timestamp = new Date();
1874
+ }
1875
+ const innerMessage = normalizeMessageContent(message);
1876
+ const messageContextInfo = message.messageContextInfo;
1877
+ const key = getContentType(innerMessage);
1878
+ const timestamp = unixTimestampSeconds(options.timestamp);
1879
+ const isNewsletter = isJidNewsletter(jid);
1880
+ const { quoted, userJid } = options;
1881
+ if (quoted) {
1882
+ const participant = quoted.key.fromMe
1883
+ ? userJid // TODO: Add support for LIDs
1884
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1885
+ let quotedMsg = normalizeMessageContent(quoted.message);
1886
+ const msgType = getContentType(quotedMsg);
1887
+ // strip any redundant properties
1888
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1889
+ const quotedContent = quotedMsg[msgType];
1890
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1891
+ delete quotedContent.contextInfo;
1892
+ }
1893
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1894
+ contextInfo.participant = jidNormalizedUser(participant);
1895
+ contextInfo.stanzaId = quoted.key.id;
1896
+ contextInfo.quotedMessage = quotedMsg;
1897
+ // if a participant is quoted, then it must be a group
1898
+ // hence, remoteJid of group must also be entered
1899
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
1900
+ contextInfo.remoteJid = quoted.key.remoteJid;
1901
+ }
1902
+ if (contextInfo && innerMessage[key]) {
1903
+ /* @ts-ignore */
1904
+ innerMessage[key].contextInfo = contextInfo;
1905
+ }
1906
+ }
1907
+ if (
1908
+ // if we want to send a disappearing message
1909
+ !!options?.ephemeralExpiration &&
1910
+ // and it's not a protocol message -- delete, toggle disappear message
1911
+ key !== 'protocolMessage' &&
1912
+ // already not converted to disappearing message
1913
+ key !== 'ephemeralMessage' &&
1914
+ // newsletters don't support ephemeral messages
1915
+ !isNewsletter) {
1916
+ /* @ts-ignore */
1917
+ innerMessage[key].contextInfo = {
1918
+ ...(innerMessage[key].contextInfo || {}),
1919
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1920
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1921
+ };
1922
+ }
1923
+ // JAP@Changes 30-01-26 --- Add deviceListMetadata inside messageContextInfo for private chat
1924
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1925
+ messageContextInfo.deviceListMetadata = {
1926
+ recipientKeyHash: randomBytes(10),
1927
+ recipientTimestamp: unixTimestampSeconds()
1928
+ };
1929
+ messageContextInfo.deviceListMetadataVersion = 2;
1930
+ }
1931
+ message = WAProto.Message.create(message);
1932
+ const messageJSON = {
1933
+ key: {
1934
+ remoteJid: jid,
1935
+ fromMe: true,
1936
+ id: options?.messageId || generateMessageIDV2()
1937
+ },
1938
+ message: message,
1939
+ messageTimestamp: timestamp,
1940
+ messageStubParameters: [],
1941
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
1942
+ status: WAMessageStatus.PENDING
1943
+ };
1944
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1945
+ };
1946
+ /**
1947
+ * JAP@Compat 1.4.2 --- Legacy alias for generateWAMessageFromContent.
1948
+ * Older Baileys forks exposed this exact signature (jid, message, options) => WebMessageInfo
1949
+ * as "prepareMessageFromContent". It was never replaced with a different implementation,
1950
+ * just renamed upstream — so this is a direct alias, not a stub.
1951
+ */
1952
+ export const prepareMessageFromContent = generateWAMessageFromContent;
1953
+ export const generateWAMessage = async (jid, content, options) => {
1954
+ // ensure msg ID is with every log
1955
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1956
+ // Pass jid in the options to generateWAMessageContent
1957
+ if (jid) {
1958
+ options.jid = jid;
1959
+ }
1960
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1961
+ };
1962
+ /** Get the key to access the true type of content */
1963
+ export const getContentType = (content) => {
1964
+ if (content) {
1965
+ const keys = Object.keys(content);
1966
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1967
+ return key;
1968
+ }
1969
+ };
1970
+ /**
1971
+ * Normalizes ephemeral, view once messages to regular message content
1972
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1973
+ * @param content
1974
+ * @returns
1975
+ */
1976
+ export const normalizeMessageContent = (content) => {
1977
+ if (!content) {
1978
+ return undefined;
1979
+ }
1980
+ // set max iterations to prevent an infinite loop
1981
+ for (let i = 0; i < 5; i++) {
1982
+ const inner = getFutureProofMessage(content);
1983
+ if (!inner) {
1984
+ break;
1985
+ }
1986
+ content = inner.message;
1987
+ }
1988
+ return content;
1989
+ // JAP@Changes 03-02-26 --- Add all futureProofMessage into getFutureProofMessage()
1990
+ // JAP@Fix 29-08-26 --- whitelist was missing 2 FutureProofMessage-typed fields added to
1991
+ // WAProto this session: botPlatformRegistrationSuccessMessage (131) and
1992
+ // newsletterScheduledMessage (132) — both would've silently failed to unwrap.
1993
+ function getFutureProofMessage(message) {
1994
+ return (message?.associatedChildMessage ||
1995
+ message?.botForwardedMessage ||
1996
+ message?.botInvokeMessage ||
1997
+ message?.botPlatformRegistrationSuccessMessage ||
1998
+ message?.botTaskMessage ||
1999
+ message?.documentWithCaptionMessage ||
2000
+ message?.editedMessage ||
2001
+ message?.ephemeralMessage ||
2002
+ message?.eventCoverImage ||
2003
+ message?.groupMentionedMessage ||
2004
+ message?.groupStatusMentionMessage ||
2005
+ message?.groupStatusMessage ||
2006
+ message?.groupStatusMessageV2 ||
2007
+ message?.limitSharingMessage ||
2008
+ message?.lottieStickerMessage ||
2009
+ message?.newsletterAdminProfileMessage ||
2010
+ message?.newsletterAdminProfileMessageV2 ||
2011
+ message?.newsletterAdminProfileStatusMessage ||
2012
+ message?.newsletterScheduledMessage ||
2013
+ message?.pollCreationMessageV4 ||
2014
+ message?.pollCreationOptionImageMessage ||
2015
+ message?.questionMessage ||
2016
+ message?.questionReplyMessage ||
2017
+ message?.spoilerMessage ||
2018
+ message?.statusAddYours ||
2019
+ message?.statusMentionMessage ||
2020
+ message?.viewOnceMessage ||
2021
+ message?.viewOnceMessageV2 ||
2022
+ message?.viewOnceMessageV2Extension);
2023
+ }
2024
+ };
2025
+ /**
2026
+ * Extract the true message content from a message
2027
+ * Eg. extracts the inner message from a disappearing message/view once message
2028
+ */
2029
+ export const extractMessageContent = (content) => {
2030
+ const extractFromTemplateMessage = (msg) => {
2031
+ if (msg.imageMessage) {
2032
+ return { imageMessage: msg.imageMessage };
2033
+ }
2034
+ else if (msg.documentMessage) {
2035
+ return { documentMessage: msg.documentMessage };
2036
+ }
2037
+ else if (msg.videoMessage) {
2038
+ return { videoMessage: msg.videoMessage };
2039
+ }
2040
+ else if (msg.locationMessage) {
2041
+ return { locationMessage: msg.locationMessage };
2042
+ }
2043
+ else {
2044
+ return {
2045
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
2046
+ };
2047
+ }
2048
+ };
2049
+ content = normalizeMessageContent(content);
2050
+ if (content?.buttonsMessage) {
2051
+ return extractFromTemplateMessage(content.buttonsMessage);
2052
+ }
2053
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
2054
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
2055
+ }
2056
+ if (content?.templateMessage?.hydratedTemplate) {
2057
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
2058
+ }
2059
+ if (content?.templateMessage?.fourRowTemplate) {
2060
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
2061
+ }
2062
+ return content;
2063
+ };
2064
+ /**
2065
+ * Returns the device predicted by message ID
2066
+ */
2067
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
2068
+ ? 'ios'
2069
+ : /^3E.{20}$/.test(id)
2070
+ ? 'web'
2071
+ : /^(.{21}|.{32})$/.test(id)
2072
+ ? 'android'
2073
+ : /^(3F|.{18}$)/.test(id)
2074
+ ? 'desktop'
2075
+ : 'unknown';
2076
+ /** Upserts a receipt in the message */
2077
+ export const updateMessageWithReceipt = (msg, receipt) => {
2078
+ msg.userReceipt = msg.userReceipt || [];
2079
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
2080
+ if (recp) {
2081
+ Object.assign(recp, receipt);
2082
+ }
2083
+ else {
2084
+ msg.userReceipt.push(receipt);
2085
+ }
2086
+ };
2087
+ /** Update the message with a new reaction */
2088
+ export const updateMessageWithReaction = (msg, reaction) => {
2089
+ const authorID = getKeyAuthor(reaction.key);
2090
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
2091
+ reaction.text = reaction.text || '';
2092
+ reactions.push(reaction);
2093
+ msg.reactions = reactions;
2094
+ };
2095
+ /** Update the message with a new poll update */
2096
+ export const updateMessageWithPollUpdate = (msg, update) => {
2097
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
2098
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
2099
+ if (update.vote?.selectedOptions?.length) {
2100
+ reactions.push(update);
2101
+ }
2102
+ msg.pollUpdates = reactions;
2103
+ };
2104
+ /** Update the message with a new event response */
2105
+ export const updateMessageWithEventResponse = (msg, update) => {
2106
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
2107
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
2108
+ responses.push(update);
2109
+ msg.eventResponses = responses;
2110
+ };
2111
+ /**
2112
+ * Aggregates all poll updates in a poll.
2113
+ * @param msg the poll creation message
2114
+ * @param meId your jid
2115
+ * @returns A list of options & their voters
2116
+ */
2117
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
2118
+ const opts = message?.pollCreationMessage?.options ||
2119
+ message?.pollCreationMessageV2?.options ||
2120
+ message?.pollCreationMessageV3?.options ||
2121
+ [];
2122
+ const voteHashMap = opts.reduce((acc, opt) => {
2123
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
2124
+ acc[hash] = {
2125
+ name: opt.optionName || '',
2126
+ voters: []
2127
+ };
2128
+ return acc;
2129
+ }, {});
2130
+ for (const update of pollUpdates || []) {
2131
+ const { vote } = update;
2132
+ if (!vote) {
2133
+ continue;
2134
+ }
2135
+ for (const option of vote.selectedOptions || []) {
2136
+ const hash = option.toString();
2137
+ let data = voteHashMap[hash];
2138
+ if (!data) {
2139
+ voteHashMap[hash] = {
2140
+ name: 'Unknown',
2141
+ voters: []
2142
+ };
2143
+ data = voteHashMap[hash];
2144
+ }
2145
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
2146
+ }
2147
+ }
2148
+ return Object.values(voteHashMap);
2149
+ }
2150
+ /**
2151
+ * Aggregates all event responses in an event message.
2152
+ * @param msg the event creation message
2153
+ * @param meId your jid
2154
+ * @returns A list of response types & their responders
2155
+ */
2156
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
2157
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
2158
+ const responseMap = {};
2159
+ for (const type of responseTypes) {
2160
+ responseMap[type] = {
2161
+ response: type,
2162
+ responders: []
2163
+ };
2164
+ }
2165
+ for (const update of eventResponses || []) {
2166
+ const responseType = update.eventResponse || 'UNKNOWN';
2167
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
2168
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
2169
+ }
2170
+ }
2171
+ return Object.values(responseMap);
2172
+ }
2173
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
2174
+ export const aggregateMessageKeysNotFromMe = (keys) => {
2175
+ const keyMap = {};
2176
+ for (const { remoteJid, id, participant, fromMe } of keys) {
2177
+ if (!fromMe) {
2178
+ const uqKey = `${remoteJid}:${participant || ''}`;
2179
+ if (!keyMap[uqKey]) {
2180
+ keyMap[uqKey] = {
2181
+ jid: remoteJid,
2182
+ participant: participant,
2183
+ messageIds: []
2184
+ };
2185
+ }
2186
+ keyMap[uqKey].messageIds.push(id);
2187
+ }
2188
+ }
2189
+ return Object.values(keyMap);
2190
+ };
2191
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
2192
+ /**
2193
+ * Downloads the given message. Throws an error if it's not a media message
2194
+ */
2195
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
2196
+ const result = await downloadMsg().catch(async (error) => {
2197
+ if (ctx &&
2198
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
2199
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
2200
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
2201
+ // request reupload
2202
+ message = await ctx.reuploadRequest(message);
2203
+ const result = await downloadMsg();
2204
+ return result;
2205
+ }
2206
+ throw error;
2207
+ });
2208
+ return result;
2209
+ async function downloadMsg() {
2210
+ const mContent = extractMessageContent(message.message);
2211
+ if (!mContent) {
2212
+ throw new Boom('No message present', { statusCode: 400, data: message });
2213
+ }
2214
+ const contentType = getContentType(mContent);
2215
+ let mediaType = contentType?.replace('Message', '');
2216
+ const media = mContent[contentType];
2217
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
2218
+ throw new Boom(`"${contentType}" message is not a media message`);
2219
+ }
2220
+ let download;
2221
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
2222
+ download = {
2223
+ directPath: media.thumbnailDirectPath,
2224
+ mediaKey: media.mediaKey
2225
+ };
2226
+ mediaType = 'thumbnail-link';
2227
+ }
2228
+ else {
2229
+ download = media;
2230
+ }
2231
+ const stream = await downloadContentFromMessage(download, mediaType, options);
2232
+ if (type === 'buffer') {
2233
+ const bufferArray = [];
2234
+ for await (const chunk of stream) {
2235
+ bufferArray.push(chunk);
2236
+ }
2237
+ return Buffer.concat(bufferArray);
2238
+ }
2239
+ return stream;
2240
+ }
2241
+ };
2242
+ /** Checks whether the given message is a media message; if it is returns the inner content */
2243
+ export const assertMediaContent = (content) => {
2244
+ content = extractMessageContent(content);
2245
+ const mediaContent = content?.documentMessage ||
2246
+ content?.imageMessage ||
2247
+ content?.videoMessage ||
2248
+ content?.audioMessage ||
2249
+ content?.stickerMessage;
2250
+ if (!mediaContent) {
2251
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
2252
+ }
2253
+ return mediaContent;
2254
+ };
2255
+ /**
2256
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
2257
+ * or ANIM/ANMF chunks
2258
+ */
2259
+ const isAnimatedWebP = (buffer) => {
2260
+ // WebP must start with RIFF....WEBP
2261
+ if (buffer.length < 12 ||
2262
+ buffer[0] !== 0x52 ||
2263
+ buffer[1] !== 0x49 ||
2264
+ buffer[2] !== 0x46 ||
2265
+ buffer[3] !== 0x46 ||
2266
+ buffer[8] !== 0x57 ||
2267
+ buffer[9] !== 0x45 ||
2268
+ buffer[10] !== 0x42 ||
2269
+ buffer[11] !== 0x50) {
2270
+ return false;
2271
+ }
2272
+ ;
2273
+ // Parse chunks starting after RIFF header (12 bytes)
2274
+ let offset = 12;
2275
+ while (offset < buffer.length - 8) {
2276
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
2277
+ const chunkSize = buffer.readUInt32LE(offset + 4);
2278
+ if (chunkFourCC === 'VP8X') {
2279
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
2280
+ const flagsOffset = offset + 8;
2281
+ if (flagsOffset < buffer.length) {
2282
+ const flags = buffer[flagsOffset];
2283
+ if (flags & 0x02) {
2284
+ return true;
2285
+ }
2286
+ ;
2287
+ }
2288
+ ;
2289
+ }
2290
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
2291
+ // ANIM or ANMF chunks indicate animation
2292
+ return true;
2293
+ }
2294
+ ;
2295
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
2296
+ offset += 8 + chunkSize + (chunkSize % 2);
2297
+ }
2298
+ ;
2299
+ return false;
2300
+ };
2301
+ /**
2302
+ * Checks if a buffer is a WebP file
2303
+ */
2304
+ const isWebPBuffer = (buffer) => {
2305
+ return (buffer.length >= 12 &&
2306
+ buffer[0] === 0x52 &&
2307
+ buffer[1] === 0x49 &&
2308
+ buffer[2] === 0x46 &&
2309
+ buffer[3] === 0x46 &&
2310
+ buffer[8] === 0x57 &&
2311
+ buffer[9] === 0x45 &&
2312
+ buffer[10] === 0x42 &&
2313
+ buffer[11] === 0x50);
2314
+ };
2315
+ /**
2316
+ * JAP@Changes 30-01-26
2317
+ * ---
2318
+ * Determines whether a message should include a Biz Binary Node.
2319
+ * A Biz Binary Node is added only for interactive messages
2320
+ * such as buttons or other supported interactive types.
2321
+ */
2322
+ export const shouldIncludeBizBinaryNode = (message) => !!(message.buttonsMessage ||
2323
+ message.listMessage ||
2324
+ message.templateMessage ||
2325
+ (message.interactiveMessage &&
2326
+ message.interactiveMessage.nativeFlowMessage));