@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

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 (431) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +25 -0
  3. package/NOTICE.md +158 -0
  4. package/README.md +5294 -2
  5. package/VanzxyBanner.js +134 -0
  6. package/WAProto/index.d.ts +13317 -0
  7. package/WAProto/index.js +147553 -0
  8. package/lib/Builders/A2UI.d.ts +131 -0
  9. package/lib/Builders/A2UI.js +343 -0
  10. package/lib/Builders/AIRich.d.ts +1021 -0
  11. package/lib/Builders/AIRich.js +2889 -0
  12. package/lib/Builders/Album.d.ts +51 -0
  13. package/lib/Builders/Album.js +99 -0
  14. package/lib/Builders/Button.d.ts +137449 -0
  15. package/lib/Builders/Button.js +1054 -0
  16. package/lib/Builders/ButtonV2.d.ts +43 -0
  17. package/lib/Builders/ButtonV2.js +175 -0
  18. package/lib/Builders/ButtonV3.d.ts +35 -0
  19. package/lib/Builders/ButtonV3.js +189 -0
  20. package/lib/Builders/Carousel.d.ts +68 -0
  21. package/lib/Builders/Carousel.js +161 -0
  22. package/lib/Builders/Event.d.ts +61 -0
  23. package/lib/Builders/Event.js +118 -0
  24. package/lib/Builders/Expiring.d.ts +17 -0
  25. package/lib/Builders/Expiring.js +27 -0
  26. package/lib/Builders/Poll.d.ts +63 -0
  27. package/lib/Builders/Poll.js +139 -0
  28. package/lib/Builders/VanzxyBaileys.d.ts +42 -0
  29. package/lib/Builders/VanzxyBaileys.js +110 -0
  30. package/lib/Builders/errors.d.ts +25 -0
  31. package/lib/Builders/errors.js +29 -0
  32. package/lib/Builders/index.d.ts +14 -0
  33. package/lib/Builders/index.js +23 -0
  34. package/lib/Builders/shared.d.ts +395 -0
  35. package/lib/Builders/shared.js +738 -0
  36. package/lib/Defaults/bot-jid.d.ts +1 -0
  37. package/lib/Defaults/bot-jid.js +1 -0
  38. package/lib/Defaults/index.d.ts +161 -0
  39. package/lib/Defaults/index.js +165 -0
  40. package/lib/Defaults/version.d.ts +1 -0
  41. package/lib/Defaults/version.js +1 -0
  42. package/lib/Framework/Bot.d.ts +865 -0
  43. package/lib/Framework/Bot.js +230 -0
  44. package/lib/Framework/Context.d.ts +17 -0
  45. package/lib/Framework/Context.js +90 -0
  46. package/lib/Framework/MediaManager.d.ts +15 -0
  47. package/lib/Framework/MediaManager.js +154 -0
  48. package/lib/Framework/SessionManager.d.ts +10 -0
  49. package/lib/Framework/SessionManager.js +34 -0
  50. package/lib/Framework/StatsManager.d.ts +20 -0
  51. package/lib/Framework/StatsManager.js +117 -0
  52. package/lib/Framework/Store/SQLiteStore.d.ts +13 -0
  53. package/lib/Framework/Store/SQLiteStore.js +68 -0
  54. package/lib/Framework/index.d.ts +6 -0
  55. package/lib/Framework/index.js +11 -0
  56. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  57. package/lib/Signal/Group/ciphertext-message.js +11 -0
  58. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  59. package/lib/Signal/Group/group-session-builder.js +29 -0
  60. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  61. package/lib/Signal/Group/group_cipher.js +81 -0
  62. package/lib/Signal/Group/index.d.ts +11 -0
  63. package/lib/Signal/Group/index.js +11 -0
  64. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  65. package/lib/Signal/Group/keyhelper.js +17 -0
  66. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  67. package/lib/Signal/Group/sender-chain-key.js +25 -0
  68. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  69. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  70. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  71. package/lib/Signal/Group/sender-key-message.js +65 -0
  72. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  73. package/lib/Signal/Group/sender-key-name.js +47 -0
  74. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  75. package/lib/Signal/Group/sender-key-record.js +40 -0
  76. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  77. package/lib/Signal/Group/sender-key-state.js +83 -0
  78. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  79. package/lib/Signal/Group/sender-message-key.js +25 -0
  80. package/lib/Signal/libsignal.d.ts +58 -0
  81. package/lib/Signal/libsignal.js +436 -0
  82. package/lib/Signal/lid-mapping.d.ts +20 -0
  83. package/lib/Signal/lid-mapping.js +276 -0
  84. package/lib/Socket/Client/index.d.ts +2 -0
  85. package/lib/Socket/Client/index.js +2 -0
  86. package/lib/Socket/Client/types.d.ts +5 -0
  87. package/lib/Socket/Client/types.js +10 -0
  88. package/lib/Socket/Client/websocket.d.ts +12 -0
  89. package/lib/Socket/Client/websocket.js +53 -0
  90. package/lib/Socket/business.d.ts +674 -0
  91. package/lib/Socket/business.js +379 -0
  92. package/lib/Socket/chats.d.ts +137 -0
  93. package/lib/Socket/chats.js +1299 -0
  94. package/lib/Socket/communities.d.ts +805 -0
  95. package/lib/Socket/communities.js +454 -0
  96. package/lib/Socket/dugong.d.ts +118 -0
  97. package/lib/Socket/dugong.js +810 -0
  98. package/lib/Socket/groups.d.ts +287 -0
  99. package/lib/Socket/groups.js +386 -0
  100. package/lib/Socket/index.d.ts +826 -0
  101. package/lib/Socket/index.js +35 -0
  102. package/lib/Socket/messages-recv.d.ts +613 -0
  103. package/lib/Socket/messages-recv.js +1851 -0
  104. package/lib/Socket/messages-send.d.ts +608 -0
  105. package/lib/Socket/messages-send.js +1574 -0
  106. package/lib/Socket/mex-fallback.d.ts +51 -0
  107. package/lib/Socket/mex-fallback.js +97 -0
  108. package/lib/Socket/mex.d.ts +1 -0
  109. package/lib/Socket/mex.js +41 -0
  110. package/lib/Socket/newsletter-ext.d.ts +47 -0
  111. package/lib/Socket/newsletter-ext.js +262 -0
  112. package/lib/Socket/newsletter.d.ts +285 -0
  113. package/lib/Socket/newsletter.js +223 -0
  114. package/lib/Socket/socket.d.ts +60 -0
  115. package/lib/Socket/socket.js +1001 -0
  116. package/lib/Socket/username.d.ts +842 -0
  117. package/lib/Socket/username.js +156 -0
  118. package/lib/Store/index.d.ts +3 -0
  119. package/lib/Store/index.js +3 -0
  120. package/lib/Store/make-in-memory-store.d.ts +62 -0
  121. package/lib/Store/make-in-memory-store.js +425 -0
  122. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  123. package/lib/Store/make-ordered-dictionary.js +78 -0
  124. package/lib/Store/object-repository.d.ts +10 -0
  125. package/lib/Store/object-repository.js +23 -0
  126. package/lib/Types/Auth.d.ts +1 -0
  127. package/lib/Types/Auth.js +1 -0
  128. package/lib/Types/Bussines.d.ts +1 -0
  129. package/lib/Types/Bussines.js +1 -0
  130. package/lib/Types/Call.d.ts +1 -0
  131. package/lib/Types/Call.js +1 -0
  132. package/lib/Types/Chat.d.ts +1 -0
  133. package/lib/Types/Chat.js +7 -0
  134. package/lib/Types/Contact.d.ts +1 -0
  135. package/lib/Types/Contact.js +1 -0
  136. package/lib/Types/Events.d.ts +1 -0
  137. package/lib/Types/Events.js +1 -0
  138. package/lib/Types/GroupMetadata.d.ts +1 -0
  139. package/lib/Types/GroupMetadata.js +1 -0
  140. package/lib/Types/Label.d.ts +2 -0
  141. package/lib/Types/Label.js +24 -0
  142. package/lib/Types/LabelAssociation.d.ts +2 -0
  143. package/lib/Types/LabelAssociation.js +6 -0
  144. package/lib/Types/Message.d.ts +11 -0
  145. package/lib/Types/Message.js +17 -0
  146. package/lib/Types/Mex.d.ts +2 -0
  147. package/lib/Types/Mex.js +38 -0
  148. package/lib/Types/Product.d.ts +1 -0
  149. package/lib/Types/Product.js +1 -0
  150. package/lib/Types/RichType.d.ts +2 -0
  151. package/lib/Types/RichType.js +22 -0
  152. package/lib/Types/Signal.d.ts +1 -0
  153. package/lib/Types/Signal.js +1 -0
  154. package/lib/Types/Socket.d.ts +1 -0
  155. package/lib/Types/Socket.js +1 -0
  156. package/lib/Types/State.d.ts +5 -0
  157. package/lib/Types/State.js +55 -0
  158. package/lib/Types/USync.d.ts +1 -0
  159. package/lib/Types/USync.js +1 -0
  160. package/lib/Types/index.d.ts +15 -0
  161. package/lib/Types/index.js +27 -0
  162. package/lib/Utils/PersistentStore.d.ts +83 -0
  163. package/lib/Utils/PersistentStore.js +592 -0
  164. package/lib/Utils/anchor-guard.d.ts +31 -0
  165. package/lib/Utils/anchor-guard.js +329 -0
  166. package/lib/Utils/android-stanza-id.d.ts +4 -0
  167. package/lib/Utils/android-stanza-id.js +21 -0
  168. package/lib/Utils/anti-delete.d.ts +62 -0
  169. package/lib/Utils/anti-delete.js +212 -0
  170. package/lib/Utils/auth-secure.d.ts +180 -0
  171. package/lib/Utils/auth-secure.js +791 -0
  172. package/lib/Utils/auth-utils.d.ts +59 -0
  173. package/lib/Utils/auth-utils.js +326 -0
  174. package/lib/Utils/auto-reconnect.d.ts +8 -0
  175. package/lib/Utils/auto-reconnect.js +204 -0
  176. package/lib/Utils/auto-reply.d.ts +35 -0
  177. package/lib/Utils/auto-reply.js +152 -0
  178. package/lib/Utils/bad-mac-handler.d.ts +59 -0
  179. package/lib/Utils/bad-mac-handler.js +119 -0
  180. package/lib/Utils/baileys-event-stream.d.ts +5 -0
  181. package/lib/Utils/baileys-event-stream.js +62 -0
  182. package/lib/Utils/browser-utils.d.ts +9 -0
  183. package/lib/Utils/browser-utils.js +29 -0
  184. package/lib/Utils/business.d.ts +49 -0
  185. package/lib/Utils/business.js +236 -0
  186. package/lib/Utils/button-helper-utils.d.ts +59 -0
  187. package/lib/Utils/button-helper-utils.js +266 -0
  188. package/lib/Utils/button-sender.d.ts +164 -0
  189. package/lib/Utils/button-sender.js +845 -0
  190. package/lib/Utils/chat-control.d.ts +98 -0
  191. package/lib/Utils/chat-control.js +231 -0
  192. package/lib/Utils/chat-history-helpers.d.ts +4 -0
  193. package/lib/Utils/chat-history-helpers.js +70 -0
  194. package/lib/Utils/chat-utils.d.ts +408 -0
  195. package/lib/Utils/chat-utils.js +879 -0
  196. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  197. package/lib/Utils/companion-reg-client-utils.js +39 -0
  198. package/lib/Utils/connection-watchdog.d.ts +10 -0
  199. package/lib/Utils/connection-watchdog.js +74 -0
  200. package/lib/Utils/crypto.d.ts +41 -0
  201. package/lib/Utils/crypto.js +145 -0
  202. package/lib/Utils/decode-wa-message.d.ts +83 -0
  203. package/lib/Utils/decode-wa-message.js +315 -0
  204. package/lib/Utils/disconnect-reason.d.ts +13 -0
  205. package/lib/Utils/disconnect-reason.js +36 -0
  206. package/lib/Utils/event-buffer.d.ts +12 -0
  207. package/lib/Utils/event-buffer.js +640 -0
  208. package/lib/Utils/fetch-timeout.d.ts +4 -0
  209. package/lib/Utils/fetch-timeout.js +14 -0
  210. package/lib/Utils/ffmpeg-path.d.ts +5 -0
  211. package/lib/Utils/ffmpeg-path.js +130 -0
  212. package/lib/Utils/generics.d.ts +79 -0
  213. package/lib/Utils/generics.js +426 -0
  214. package/lib/Utils/group-metadata-cache.d.ts +3 -0
  215. package/lib/Utils/group-metadata-cache.js +25 -0
  216. package/lib/Utils/group-status-detection.d.ts +5 -0
  217. package/lib/Utils/group-status-detection.js +114 -0
  218. package/lib/Utils/history.d.ts +91 -0
  219. package/lib/Utils/history.js +144 -0
  220. package/lib/Utils/html-app.d.ts +14 -0
  221. package/lib/Utils/html-app.js +97 -0
  222. package/lib/Utils/html-multiplayer.d.ts +8 -0
  223. package/lib/Utils/html-multiplayer.js +90 -0
  224. package/lib/Utils/humanizer.d.ts +8 -0
  225. package/lib/Utils/humanizer.js +74 -0
  226. package/lib/Utils/identity-change-handler.d.ts +13 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/index.d.ts +88 -0
  229. package/lib/Utils/index.js +93 -0
  230. package/lib/Utils/jid-tools.d.ts +3 -0
  231. package/lib/Utils/jid-tools.js +78 -0
  232. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  233. package/lib/Utils/link-preview-metadata.js +90 -0
  234. package/lib/Utils/link-preview.d.ts +12 -0
  235. package/lib/Utils/link-preview.js +84 -0
  236. package/lib/Utils/lock-manager.d.ts +5 -0
  237. package/lib/Utils/lock-manager.js +50 -0
  238. package/lib/Utils/logger.d.ts +2 -0
  239. package/lib/Utils/logger.js +2 -0
  240. package/lib/Utils/lt-hash.d.ts +12 -0
  241. package/lib/Utils/lt-hash.js +26 -0
  242. package/lib/Utils/make-mutex.d.ts +6 -0
  243. package/lib/Utils/make-mutex.js +32 -0
  244. package/lib/Utils/media-messages.d.ts +35 -0
  245. package/lib/Utils/media-messages.js +70 -0
  246. package/lib/Utils/media-processor.d.ts +6 -0
  247. package/lib/Utils/media-processor.js +174 -0
  248. package/lib/Utils/media-set.d.ts +6 -0
  249. package/lib/Utils/media-set.js +169 -0
  250. package/lib/Utils/message-kind.d.ts +26 -0
  251. package/lib/Utils/message-kind.js +138 -0
  252. package/lib/Utils/message-retry-manager.d.ts +79 -0
  253. package/lib/Utils/message-retry-manager.js +264 -0
  254. package/lib/Utils/message-search.d.ts +40 -0
  255. package/lib/Utils/message-search.js +181 -0
  256. package/lib/Utils/messages-media.d.ts +136 -0
  257. package/lib/Utils/messages-media.js +867 -0
  258. package/lib/Utils/messages.d.ts +66 -0
  259. package/lib/Utils/messages.js +2271 -0
  260. package/lib/Utils/meta-ai-msmsg.d.ts +3 -0
  261. package/lib/Utils/meta-ai-msmsg.js +132 -0
  262. package/lib/Utils/meta-ai.d.ts +4 -0
  263. package/lib/Utils/meta-ai.js +75 -0
  264. package/lib/Utils/migrate-auth-state.d.ts +23 -0
  265. package/lib/Utils/migrate-auth-state.js +126 -0
  266. package/lib/Utils/mini-app.d.ts +20 -0
  267. package/lib/Utils/mini-app.js +215 -0
  268. package/lib/Utils/mock-socket.d.ts +67 -0
  269. package/lib/Utils/mock-socket.js +254 -0
  270. package/lib/Utils/modern-messages.d.ts +64 -0
  271. package/lib/Utils/modern-messages.js +497 -0
  272. package/lib/Utils/native-flow.d.ts +19 -0
  273. package/lib/Utils/native-flow.js +112 -0
  274. package/lib/Utils/newsletter-status.d.ts +157 -0
  275. package/lib/Utils/newsletter-status.js +652 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.js +200 -0
  278. package/lib/Utils/offline-node-processor.d.ts +9 -0
  279. package/lib/Utils/offline-node-processor.js +39 -0
  280. package/lib/Utils/pairing-utils.d.ts +5 -0
  281. package/lib/Utils/pairing-utils.js +29 -0
  282. package/lib/Utils/passkey.d.ts +4 -0
  283. package/lib/Utils/passkey.js +11 -0
  284. package/lib/Utils/past-participants.d.ts +2 -0
  285. package/lib/Utils/past-participants.js +40 -0
  286. package/lib/Utils/payment-detection.d.ts +40 -0
  287. package/lib/Utils/payment-detection.js +213 -0
  288. package/lib/Utils/payment-guard.d.ts +28 -0
  289. package/lib/Utils/payment-guard.js +143 -0
  290. package/lib/Utils/payment-messages.d.ts +42 -0
  291. package/lib/Utils/payment-messages.js +161 -0
  292. package/lib/Utils/payment-utils.d.ts +75 -0
  293. package/lib/Utils/payment-utils.js +145 -0
  294. package/lib/Utils/phone-utils.d.ts +3 -0
  295. package/lib/Utils/phone-utils.js +29 -0
  296. package/lib/Utils/pre-key-manager.d.ts +25 -0
  297. package/lib/Utils/pre-key-manager.js +105 -0
  298. package/lib/Utils/process-message.d.ts +103 -0
  299. package/lib/Utils/process-message.js +868 -0
  300. package/lib/Utils/qr-terminal.d.ts +1 -0
  301. package/lib/Utils/qr-terminal.js +16 -0
  302. package/lib/Utils/reconnect-backoff.d.ts +25 -0
  303. package/lib/Utils/reconnect-backoff.js +47 -0
  304. package/lib/Utils/reporting-utils.d.ts +12 -0
  305. package/lib/Utils/reporting-utils.js +257 -0
  306. package/lib/Utils/rich-message-utils.d.ts +54 -0
  307. package/lib/Utils/rich-message-utils.js +435 -0
  308. package/lib/Utils/rich-messages.d.ts +298 -0
  309. package/lib/Utils/rich-messages.js +1145 -0
  310. package/lib/Utils/scheduled-message.d.ts +81 -0
  311. package/lib/Utils/scheduled-message.js +101 -0
  312. package/lib/Utils/scheduling.d.ts +59 -0
  313. package/lib/Utils/scheduling.js +139 -0
  314. package/lib/Utils/signal.d.ts +82 -0
  315. package/lib/Utils/signal.js +200 -0
  316. package/lib/Utils/stanza-ack.d.ts +16 -0
  317. package/lib/Utils/stanza-ack.js +37 -0
  318. package/lib/Utils/status-stickers.d.ts +79 -0
  319. package/lib/Utils/status-stickers.js +261 -0
  320. package/lib/Utils/status.d.ts +107 -0
  321. package/lib/Utils/status.js +131 -0
  322. package/lib/Utils/sticker-pack-maker.d.ts +20 -0
  323. package/lib/Utils/sticker-pack-maker.js +112 -0
  324. package/lib/Utils/stickerpack.d.ts +18 -0
  325. package/lib/Utils/stickerpack.js +316 -0
  326. package/lib/Utils/sync-action-utils.d.ts +2 -0
  327. package/lib/Utils/sync-action-utils.js +48 -0
  328. package/lib/Utils/tag.d.ts +8 -0
  329. package/lib/Utils/tag.js +45 -0
  330. package/lib/Utils/tc-token-utils.d.ts +29 -0
  331. package/lib/Utils/tc-token-utils.js +162 -0
  332. package/lib/Utils/templates.d.ts +86 -0
  333. package/lib/Utils/templates.js +148 -0
  334. package/lib/Utils/text-format.d.ts +13 -0
  335. package/lib/Utils/text-format.js +81 -0
  336. package/lib/Utils/text-tools.d.ts +3 -0
  337. package/lib/Utils/text-tools.js +38 -0
  338. package/lib/Utils/ttl-cache.d.ts +29 -0
  339. package/lib/Utils/ttl-cache.js +123 -0
  340. package/lib/Utils/use-cache-manager-auth-state.d.ts +22 -0
  341. package/lib/Utils/use-cache-manager-auth-state.js +86 -0
  342. package/lib/Utils/use-multi-file-auth-state.d.ts +20 -0
  343. package/lib/Utils/use-multi-file-auth-state.js +201 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  345. package/lib/Utils/use-single-file-auth-state.js +111 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  347. package/lib/Utils/use-sqlite-auth-state.js +171 -0
  348. package/lib/Utils/username.d.ts +22 -0
  349. package/lib/Utils/username.js +59 -0
  350. package/lib/Utils/validate-connection.d.ts +43 -0
  351. package/lib/Utils/validate-connection.js +197 -0
  352. package/lib/Utils/vcard.d.ts +40 -0
  353. package/lib/Utils/vcard.js +92 -0
  354. package/lib/Utils/voice-note.d.ts +13 -0
  355. package/lib/Utils/voice-note.js +47 -0
  356. package/lib/VoIP/audio-feeder.d.ts +15 -0
  357. package/lib/VoIP/audio-feeder.js +132 -0
  358. package/lib/VoIP/index.d.ts +22 -0
  359. package/lib/VoIP/index.js +277 -0
  360. package/lib/VoIP/relay-transport.d.ts +16 -0
  361. package/lib/VoIP/relay-transport.js +559 -0
  362. package/lib/VoIP/signaling.d.ts +16 -0
  363. package/lib/VoIP/signaling.js +624 -0
  364. package/lib/VoIP/types.d.ts +11 -0
  365. package/lib/VoIP/types.js +17 -0
  366. package/lib/VoIP/wasm-engine.d.ts +28 -0
  367. package/lib/VoIP/wasm-engine.js +1214 -0
  368. package/lib/VoIP/worker-bootstrap.d.ts +1 -0
  369. package/lib/VoIP/worker-bootstrap.js +1042 -0
  370. package/lib/WABinary/constants.d.ts +61 -0
  371. package/lib/WABinary/constants.js +1466 -0
  372. package/lib/WABinary/decode.d.ts +9 -0
  373. package/lib/WABinary/decode.js +261 -0
  374. package/lib/WABinary/encode.d.ts +2 -0
  375. package/lib/WABinary/encode.js +219 -0
  376. package/lib/WABinary/generic-utils.d.ts +45 -0
  377. package/lib/WABinary/generic-utils.js +285 -0
  378. package/lib/WABinary/index.d.ts +5 -0
  379. package/lib/WABinary/index.js +5 -0
  380. package/lib/WABinary/jid-utils.d.ts +32 -0
  381. package/lib/WABinary/jid-utils.js +102 -0
  382. package/lib/WABinary/types.d.ts +1 -0
  383. package/lib/WABinary/types.js +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +7 -0
  385. package/lib/WAM/BinaryInfo.js +9 -0
  386. package/lib/WAM/constants.d.ts +34926 -0
  387. package/lib/WAM/constants.js +22852 -0
  388. package/lib/WAM/encode.d.ts +1 -0
  389. package/lib/WAM/encode.js +149 -0
  390. package/lib/WAM/index.d.ts +3 -0
  391. package/lib/WAM/index.js +3 -0
  392. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +43 -0
  393. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  395. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  396. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  397. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +60 -0
  398. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  399. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  400. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +13 -0
  401. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +28 -0
  402. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +22 -0
  403. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  404. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +20 -0
  405. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +23 -0
  406. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  407. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  408. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +14 -0
  409. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +24 -0
  410. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  411. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  412. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  413. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  414. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  415. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  416. package/lib/WAUSync/Protocols/index.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/index.js +12 -0
  418. package/lib/WAUSync/USyncQuery.d.ts +25 -0
  419. package/lib/WAUSync/USyncQuery.js +140 -0
  420. package/lib/WAUSync/USyncUser.d.ts +24 -0
  421. package/lib/WAUSync/USyncUser.js +47 -0
  422. package/lib/WAUSync/index.d.ts +3 -0
  423. package/lib/WAUSync/index.js +3 -0
  424. package/lib/assets/wasm/loader.js +5 -0
  425. package/lib/assets/wasm/whatsapp.wasm +0 -0
  426. package/lib/assets/wasm/worker-modules.js +273 -0
  427. package/lib/exports-extra.d.ts +45 -0
  428. package/lib/exports-extra.js +47 -0
  429. package/lib/index.d.ts +16 -0
  430. package/lib/index.js +24 -0
  431. package/package.json +161 -4
@@ -0,0 +1,1054 @@
1
+ import { buildPaymentParams } from '../Utils/payment-utils.js';
2
+ import { BaseBuilder, Toolkit, generateWAMessageFromContent, prepareWAMessageMedia, generateMessageIDV2, getBizBinaryNode, crypto } from './shared.js';
3
+ /**
4
+ * `interactiveMessage`/nativeFlow builder — the current-generation button protocol (32
5
+ * native-flow button types: quick replies, URL/call/copy/location/catalog CTAs, payment and
6
+ * order-tracking flows, WhatsApp Flows launches, a `single_select` list, and a raw
7
+ * `setBloksWidget()` escape hatch). See `ButtonV2` (legacy `buttonsMessage`) and `ButtonV3`
8
+ * (legacy `templateMessage`) for the two older button protocols this fork also supports.
9
+ */
10
+ class Button extends BaseBuilder {
11
+ #client;
12
+
13
+ /** @param {import('../../WAProto/index.js').WASocket} client Active Baileys socket (must expose `relayMessage`). */
14
+ constructor(client) {
15
+ super();
16
+ if (!client) {
17
+ throw new Error('Socket is required');
18
+ }
19
+ this.#client = client;
20
+
21
+ this._buttons = [];
22
+ this._data = null;
23
+ this._currentSelectionIndex = -1;
24
+ this._currentSectionIndex = -1;
25
+ this._params = {};
26
+ this._gifPlayback = false;
27
+ this._locationHeader = null;
28
+ }
29
+
30
+ /**
31
+ * Reconstruct this builder's state from an already-built/sent interactiveMessage.
32
+ * @param {object} msg A raw message object containing `interactiveMessage` (e.g. `oldMsg.message`).
33
+ */
34
+ loadFrom(msg) {
35
+ if (!msg) throw new Error('loadFrom(msg): interactiveMessage needed');
36
+ if (!msg.interactiveMessage) throw new Error('loadFrom(msg): interactiveMessage not found');
37
+
38
+ const { interactiveMessage, ...extraPayload } = msg;
39
+ const iM = interactiveMessage;
40
+ const header = iM.header || {};
41
+ const nativeFlow = iM.nativeFlowMessage || {};
42
+
43
+ this._title = header.title || '';
44
+ this._subtitle = header.subtitle || '';
45
+ this._body = iM.body?.text || '';
46
+ this._footer = iM.footer?.text || '';
47
+ this._contextInfo = iM.contextInfo || {};
48
+ this._extraPayload = extraPayload;
49
+
50
+ this._buttons = Array.isArray(nativeFlow.buttons)
51
+ ? nativeFlow.buttons.map((button) => ({
52
+ ...button,
53
+ buttonParamsJson: typeof button.buttonParamsJson === 'string' ? button.buttonParamsJson : JSON.stringify(button.buttonParamsJson || {}),
54
+ }))
55
+ : [];
56
+
57
+ this._data = header.imageMessage
58
+ ? { imageMessage: header.imageMessage }
59
+ : header.videoMessage
60
+ ? { videoMessage: header.videoMessage }
61
+ : header.documentMessage
62
+ ? { documentMessage: header.documentMessage }
63
+ : header.productMessage
64
+ ? { productMessage: header.productMessage }
65
+ : null;
66
+
67
+ this._gifPlayback = !!header.videoMessage?.gifPlayback;
68
+ this._locationHeader = header.locationMessage ? { thumbnailUrl: '' } : null;
69
+
70
+ this._params = {};
71
+ if (typeof nativeFlow.messageParamsJson === 'string') {
72
+ try {
73
+ this._params = JSON.parse(nativeFlow.messageParamsJson || '{}');
74
+ } catch {
75
+ this._params = {};
76
+ }
77
+ } else if (nativeFlow.messageParamsJson && typeof nativeFlow.messageParamsJson === 'object') {
78
+ this._params = { ...nativeFlow.messageParamsJson };
79
+ }
80
+
81
+ this._currentSelectionIndex = this._buttons.findLastIndex((button) => button.name === 'single_select');
82
+ this._currentSectionIndex = -1;
83
+
84
+ if (this._currentSelectionIndex !== -1) {
85
+ try {
86
+ const button = this._buttons[this._currentSelectionIndex];
87
+ const params = JSON.parse(button.buttonParamsJson || '{}');
88
+ if (Array.isArray(params.sections) && params.sections.length) {
89
+ this._currentSectionIndex = params.sections.length - 1;
90
+ }
91
+ } catch {
92
+ this._currentSelectionIndex = -1;
93
+ this._currentSectionIndex = -1;
94
+ }
95
+ }
96
+
97
+ return this;
98
+ }
99
+
100
+ /** Attach a video as the interactive header. @param {string|Buffer} path Url or buffer. */
101
+ setVideo(path, options = {}) {
102
+ if (!path) throw new Error('Url or buffer needed');
103
+ Buffer.isBuffer(path) ? (this._data = { video: path, ...options }) : (this._data = { video: { url: path }, ...options });
104
+ this._gifPlayback = false;
105
+ return this;
106
+ }
107
+
108
+ /** Attach an image as the interactive header. @param {string|Buffer} path Url or buffer. */
109
+ setImage(path, options = {}) {
110
+ if (!path) throw new Error('Url or buffer needed');
111
+ Buffer.isBuffer(path) ? (this._data = { image: path, ...options }) : (this._data = { image: { url: path }, ...options });
112
+ this._gifPlayback = false;
113
+ return this;
114
+ }
115
+
116
+ /** Attach a document as the interactive header. @param {string|Buffer} path Url or buffer. */
117
+ setDocument(path, options = {}) {
118
+ if (!path) throw new Error('Url or buffer needed');
119
+ Buffer.isBuffer(path) ? (this._data = { document: path, ...options }) : (this._data = { document: { url: path }, ...options });
120
+ this._gifPlayback = false;
121
+ return this;
122
+ }
123
+
124
+ /** Set a raw pre-built header media object (bypasses setVideo/setImage/setDocument shorthands). */
125
+ setMedia(obj) {
126
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
127
+ throw new TypeError('Media must be a plain object');
128
+ }
129
+
130
+ this._data = obj;
131
+ this._gifPlayback = false;
132
+ return this;
133
+ }
134
+
135
+ /**
136
+ * video header that autoplays muted & looped (gifPlayback).
137
+ * gifPlayback is injected into the uploaded `videoMessage` after upload, not passed to the uploader.
138
+ * @param {string|Buffer} path Url or buffer.
139
+ */
140
+ setVideoGif(path, options = {}) {
141
+ if (!path) throw new Error('Url or buffer needed');
142
+ this._data = Buffer.isBuffer(path) ? { video: path, gifPlayback: true, ...options } : { video: { url: path }, gifPlayback: true, ...options };
143
+ this._gifPlayback = true;
144
+ return this;
145
+ }
146
+
147
+ /**
148
+ * location-style header: title -> location name, subtitle -> address,
149
+ * optional thumbnail (url or Buffer, resized to 300x300). Takes priority over any image/video/document header.
150
+ * @param {string|Buffer} [thumbnail]
151
+ */
152
+ setLocationHeader(thumbnail = '') {
153
+ this._locationHeader = { thumbnailUrl: thumbnail };
154
+ return this;
155
+ }
156
+
157
+ /** Remove every button added so far (keeps title/body/footer/media). */
158
+ clearButtons() {
159
+ this._buttons = [];
160
+ return this;
161
+ }
162
+
163
+ /** Overwrite the message-level `nativeFlowMessage.messageParamsJson` payload wholesale. */
164
+ setParams(obj) {
165
+ this._params = obj;
166
+ return this;
167
+ }
168
+
169
+ /**
170
+ * @typedef {{ $ref: string }} BloksRef
171
+ * Points back at a sibling node tagged `ref: 'name'` elsewhere in the same tree (currently
172
+ * only needed for `Modal.trigger`/`Modal.content` — everything else nests directly).
173
+ */
174
+ /**
175
+ * @typedef {Object} BloksNodeBase
176
+ * @property {string} [ref] Builder-only tag so another node can reference this one via `{ $ref: ref }`. Stripped before send.
177
+ */
178
+ /**
179
+ * @typedef {BloksNodeBase & { component: 'Column'|'Row', weight?: number, justify?: string, children?: BloksNode[] }} ColumnRowNode
180
+ * @typedef {BloksNodeBase & { component: 'Text', text: string, variant?: string }} TextNode
181
+ * @typedef {BloksNodeBase & { component: 'Icon', name: string }} IconNode
182
+ * @typedef {BloksNodeBase & { component: 'Divider' }} DividerNode
183
+ * @typedef {BloksNodeBase & { component: 'Image', url: string, variant?: string, fit?: string }} ImageNode
184
+ * @typedef {BloksNodeBase & { component: 'Video', url: string }} VideoNode
185
+ * @typedef {BloksNodeBase & { component: 'List', children?: BloksNode[] }} ListNode
186
+ * @typedef {BloksNodeBase & { component: 'TextField', label?: string, value?: string, variant?: string }} TextFieldNode
187
+ * @typedef {BloksNodeBase & { component: 'DateTimeInput', label?: string, value?: string, enableDate?: boolean, enableTime?: boolean }} DateTimeInputNode
188
+ * @typedef {BloksNodeBase & { component: 'Slider', label?: string, min?: number, max?: number, value?: number }} SliderNode
189
+ * @typedef {BloksNodeBase & { component: 'CheckBox', label?: string, value?: boolean }} CheckBoxNode
190
+ * @typedef {BloksNodeBase & { component: 'ChoicePicker', label?: string, variant?: string, displayStyle?: string, options?: Array<{label: string, value: string}>, value?: string }} ChoicePickerNode
191
+ * @typedef {BloksNodeBase & { component: 'Button', child?: BloksNode, variant?: string, action?: { call: string, args?: Record<string, any> } }} BloksButtonNode
192
+ * Note: unlike the CTA/native-flow `Button` class elsewhere in this file, an A2UI Button node
193
+ * has no `label`/`type`+`name` — its label comes from a nested `child` (usually a `Text` node),
194
+ * and tapping it fires `action.call` (with `action.args`), not a native-flow button name.
195
+ * @typedef {BloksNodeBase & { component: 'Modal', trigger: string|BloksRef, content: BloksNode|string|BloksRef }} ModalNode
196
+ * @typedef {BloksNodeBase & { component: 'Tabs', tabs: Array<{title: string, child: BloksNode}> }} TabsNode
197
+ * @typedef {BloksNodeBase & { component: 'Card', child?: BloksNode }} CardNode
198
+ * @typedef {BloksNodeBase & { component: 'AudioPlayer', url: string, description?: string }} AudioPlayerNode
199
+ * @typedef {BloksNodeBase & { component: string, [key: string]: any }} AnyBloksNode Fallback for components not yet confirmed on the wire — still works, just no prop-level autocomplete.
200
+ * @typedef {ColumnRowNode|TextNode|IconNode|DividerNode|ImageNode|VideoNode|ListNode|TextFieldNode|DateTimeInputNode|SliderNode|CheckBoxNode|ChoicePickerNode|BloksButtonNode|ModalNode|TabsNode|CardNode|AudioPlayerNode|AnyBloksNode} BloksNode
201
+ */
202
+ #flattenBloks(tree, out, ctx = { n: 0, refs: new Map(), pending: [] }, id = 'root') {
203
+ if (!tree || typeof tree !== 'object') throw new TypeError('setBloksWidget: every node needs a "component" type');
204
+ const { component, children, child, ref, ...rest } = tree;
205
+ if (typeof component !== 'string' || !component) throw new TypeError('setBloksWidget: every node needs a "component" type');
206
+
207
+ const isTreeNode = (v) => v && typeof v === 'object' && !Array.isArray(v) && typeof v.component === 'string';
208
+ const isRefMarker = (v) => v && typeof v === 'object' && !Array.isArray(v) && typeof v.$ref === 'string' && Object.keys(v).length === 1;
209
+
210
+ const node = { id, component };
211
+ for (const [k, v] of Object.entries(rest)) {
212
+ if (isRefMarker(v)) {
213
+ node[k] = null; // resolved once the full tree (and its `ref` tags) has been walked
214
+ ctx.pending.push({ node, key: k, refName: v.$ref });
215
+ } else if (isTreeNode(v)) {
216
+ node[k] = this.#flattenBloks(v, out, ctx, `n${ctx.n++}`);
217
+ } else {
218
+ node[k] = v;
219
+ }
220
+ }
221
+
222
+ if (Array.isArray(children)) {
223
+ node.children = children.map((c) => this.#flattenBloks(c, out, ctx, `n${ctx.n++}`));
224
+ } else if (child) {
225
+ node.child = this.#flattenBloks(child, out, ctx, `n${ctx.n++}`);
226
+ }
227
+
228
+ if (ref) ctx.refs.set(ref, id);
229
+
230
+ out.push(node);
231
+ return id;
232
+ }
233
+
234
+ /**
235
+ * Set a Bloks/A2UI native widget (`bloksWidget`, `type: "im_a2ui"`) — a real interactive
236
+ * screen (images, video, checkboxes, text fields, buttons that fire an `action`), not a
237
+ * static card. Pass a nested tree; ids are assigned automatically.
238
+ *
239
+ * For components that reference a SIBLING node instead of nesting one — currently just
240
+ * `Modal.trigger` — tag the source node with `ref: 'someName'` and point at it with
241
+ * `{ $ref: 'someName' }`. Everything else (including `Modal.content`) can just be nested
242
+ * directly, no special key needed.
243
+ * @param {BloksNode} tree Root node, e.g. `{ component: 'Column', children: [...] }`.
244
+ * @param {{uuid?: string, catalogId?: string, surfaceId?: string, version?: string}} [options]
245
+ */
246
+ setBloksWidget(tree, { uuid = crypto.randomUUID(), catalogId = 'https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json', surfaceId, version = 'v0.9' } = {}) {
247
+ const components = [];
248
+ const ctx = { n: 0, refs: new Map(), pending: [] };
249
+ this.#flattenBloks(tree, components, ctx);
250
+ for (const { node, key, refName } of ctx.pending) {
251
+ const resolved = ctx.refs.get(refName);
252
+ if (!resolved) throw new Error(`setBloksWidget: ref "${refName}" (used on "${key}") was never declared with ref: "${refName}" on any node`);
253
+ node[key] = resolved;
254
+ }
255
+
256
+ this._bloksWidget = {
257
+ uuid,
258
+ data: JSON.stringify({
259
+ version,
260
+ createSurface: {
261
+ surfaceId: surfaceId ?? `starcore-widget=${uuid}`,
262
+ catalogId,
263
+ components,
264
+ },
265
+ }),
266
+ type: 'im_a2ui',
267
+ };
268
+
269
+ return this;
270
+ }
271
+
272
+ /**
273
+ * Low-level escape hatch: push a raw native-flow button by name. Prefer the
274
+ * dedicated `add*()` helpers below when one exists — they validate the
275
+ * required keys for that button type.
276
+ * @param {string} name Native-flow button name, e.g. 'quick_reply', 'cta_url'.
277
+ * @param {string|Record<string, any>} params Either a pre-stringified JSON payload or a plain object.
278
+ */
279
+ addButton(name, params) {
280
+ if (typeof name !== 'string' || !name.trim()) {
281
+ throw new TypeError('addButton(name, params) requires a non-empty string name');
282
+ }
283
+
284
+ this._buttons.push({
285
+ name,
286
+ buttonParamsJson: typeof params === 'string' ? params : JSON.stringify(params),
287
+ });
288
+
289
+ return this;
290
+ }
291
+
292
+ /** Append a row to the section currently open on the last `addSelection()` (call `makeSection()` first). */
293
+ makeRow(header = '', title = '', description = '', id = '') {
294
+ if (this._currentSelectionIndex === -1 || this._currentSectionIndex === -1) {
295
+ throw new Error('You need to create a selection and a section first');
296
+ }
297
+ if (!title || !id) {
298
+ throw new TypeError('makeRow() requires both a title and an id');
299
+ }
300
+ const buttonParams = JSON.parse(this._buttons[this._currentSelectionIndex].buttonParamsJson);
301
+ buttonParams.sections[this._currentSectionIndex].rows.push({ header, title, description, id });
302
+ this._buttons[this._currentSelectionIndex].buttonParamsJson = JSON.stringify(buttonParams);
303
+ return this;
304
+ }
305
+
306
+ /** Open a new section on the `single_select` button added by the last `addSelection()` call. */
307
+ makeSection(title = '', highlight_label = '') {
308
+ if (this._currentSelectionIndex === -1) {
309
+ throw new Error('You need to create a selection first');
310
+ }
311
+ const buttonParams = JSON.parse(this._buttons[this._currentSelectionIndex].buttonParamsJson);
312
+ buttonParams.sections.push({ title, highlight_label, rows: [] });
313
+ this._currentSectionIndex = buttonParams.sections.length - 1;
314
+ this._buttons[this._currentSelectionIndex].buttonParamsJson = JSON.stringify(buttonParams);
315
+ return this;
316
+ }
317
+
318
+ /** Start a `single_select` (in-button picker list) button. Follow with `makeSection()` + `makeRow()`. */
319
+ addSelection(title, options = {}) {
320
+ if (!title) throw new TypeError('addSelection(title) requires a non-empty title');
321
+ this._buttons.push({ ...options, name: 'single_select', buttonParamsJson: JSON.stringify({ title, sections: [] }) });
322
+ this._currentSelectionIndex = this._buttons.length - 1;
323
+ this._currentSectionIndex = -1;
324
+ return this;
325
+ }
326
+
327
+ /**
328
+ * Add a `quick_reply` button — sends `id` back as the interactive-response id when tapped.
329
+ * @param {string} display_text Button label.
330
+ * @param {string} id Unique id returned on tap; required, WA silently drops replies without one.
331
+ */
332
+ addReply(display_text = '', id = '', options = {}) {
333
+ if (!display_text || !id) {
334
+ throw new TypeError('addReply(display_text, id) requires both a label and a unique id');
335
+ }
336
+ this._buttons.push({
337
+ name: 'quick_reply',
338
+ buttonParamsJson: JSON.stringify({
339
+ display_text,
340
+ id,
341
+ ...options,
342
+ }),
343
+ });
344
+ return this;
345
+ }
346
+
347
+ /**
348
+ * Add a `cta_call` (tap-to-dial) button.
349
+ * @param {string} display_text Button label.
350
+ * @param {string} phone_number Phone number to dial, e.g. '+15551234567'.
351
+ */
352
+ addCall(display_text = '', phone_number = '', options = {}) {
353
+ if (!display_text || !phone_number) {
354
+ throw new TypeError('addCall(display_text, phone_number) requires both a label and a phone number');
355
+ }
356
+ this._buttons.push({
357
+ name: 'cta_call',
358
+ buttonParamsJson: JSON.stringify({
359
+ display_text,
360
+ phone_number,
361
+ ...options,
362
+ }),
363
+ });
364
+ return this;
365
+ }
366
+
367
+ /** Add a `cta_reminder` button (schedules an in-chat reminder chip). */
368
+ addReminder(display_text = '', id = '', options = {}) {
369
+ if (!display_text || !id) {
370
+ throw new TypeError('addReminder(display_text, id) requires both a label and a unique id');
371
+ }
372
+ this._buttons.push({
373
+ name: 'cta_reminder',
374
+ buttonParamsJson: JSON.stringify({
375
+ display_text,
376
+ id,
377
+ ...options,
378
+ }),
379
+ });
380
+ return this;
381
+ }
382
+
383
+ /** Add a `cta_cancel_reminder` button, pairs with `addReminder()`. */
384
+ addCancelReminder(display_text = '', id = '', options = {}) {
385
+ if (!display_text || !id) {
386
+ throw new TypeError('addCancelReminder(display_text, id) requires both a label and a unique id');
387
+ }
388
+ this._buttons.push({
389
+ name: 'cta_cancel_reminder',
390
+ buttonParamsJson: JSON.stringify({
391
+ display_text,
392
+ id,
393
+ ...options,
394
+ }),
395
+ });
396
+ return this;
397
+ }
398
+
399
+ /** Add an `address_message` button (prompts the user's saved-address picker). */
400
+ addAddress(display_text = '', id = '', options = {}) {
401
+ if (!display_text || !id) {
402
+ throw new TypeError('addAddress(display_text, id) requires both a label and a unique id');
403
+ }
404
+ this._buttons.push({
405
+ name: 'address_message',
406
+ buttonParamsJson: JSON.stringify({
407
+ display_text,
408
+ id,
409
+ ...options,
410
+ }),
411
+ });
412
+ return this;
413
+ }
414
+
415
+ /** Add a `send_location` button (requests the user's live location). */
416
+ addLocation(options = {}) {
417
+ this._buttons.push({
418
+ name: 'send_location',
419
+ buttonParamsJson: JSON.stringify(options),
420
+ });
421
+ return this;
422
+ }
423
+
424
+ /**
425
+ * Add a `cta_url` button.
426
+ * @param {string} display_text Button label.
427
+ * @param {string} url Url opened on tap.
428
+ * @param {boolean} webview_interaction Open inside WhatsApp's in-app webview instead of the system browser.
429
+ */
430
+ addUrl(display_text = '', url = '', webview_interaction = false, options = {}) {
431
+ if (!display_text || !url) {
432
+ throw new TypeError('addUrl(display_text, url) requires both a label and a url');
433
+ }
434
+ this._buttons.push({
435
+ ...options,
436
+ name: 'cta_url',
437
+ buttonParamsJson: JSON.stringify({
438
+ display_text,
439
+ url,
440
+ merchant_url: url,
441
+ webview_interaction,
442
+ ...options,
443
+ }),
444
+ });
445
+ return this;
446
+ }
447
+
448
+ /** Add a `cta_copy` button (copies `copy_code` to the user's clipboard on tap). */
449
+ addCopy(display_text = '', copy_code = '', options = {}) {
450
+ if (!display_text || !copy_code) {
451
+ throw new TypeError('addCopy(display_text, copy_code) requires both a label and the text to copy');
452
+ }
453
+ this._buttons.push({
454
+ name: 'cta_copy',
455
+ buttonParamsJson: JSON.stringify({
456
+ display_text,
457
+ copy_code,
458
+ ...options,
459
+ }),
460
+ });
461
+ return this;
462
+ }
463
+
464
+ /**
465
+ * Add an `open_webview` button — opens a titled in-app webview (distinct from
466
+ * `cta_url`'s `webview_interaction` flag: this is its own native-flow name).
467
+ * @param {string} title Webview title shown in the header bar.
468
+ * @param {string} url Url loaded inside the webview.
469
+ */
470
+ addOpenWebview(title = '', url = '', options = {}) {
471
+ if (!title || !url) {
472
+ throw new TypeError('addOpenWebview(title, url) requires both a title and a url');
473
+ }
474
+ this._buttons.push({
475
+ name: 'open_webview',
476
+ buttonParamsJson: JSON.stringify({
477
+ title,
478
+ link: { url },
479
+ ...options,
480
+ }),
481
+ });
482
+ return this;
483
+ }
484
+
485
+ /**
486
+ * Add a `cta_catalog` button (opens the sender's WhatsApp Business catalog).
487
+ * WA only shows the catalog action for accounts
488
+ * that actually have a catalog attached; on regular accounts the button may
489
+ * render inert. See Button.#SPECIAL_FLOW for the native-flow node this name requires.
490
+ */
491
+ addCatalog(display_text = '', options = {}) {
492
+ this._buttons.push({
493
+ name: 'cta_catalog',
494
+ buttonParamsJson: JSON.stringify({
495
+ ...(display_text ? { display_text } : {}),
496
+ ...options,
497
+ }),
498
+ });
499
+ return this;
500
+ }
501
+
502
+ /**
503
+ * Add an `automated_greeting_message_view_catalog` button — the "View catalog"
504
+ * action WhatsApp Business shows on the automated greeting message.
505
+ * Business-account only; see Button.#SPECIAL_FLOW.
506
+ */
507
+ addViewCatalog(options = {}) {
508
+ this._buttons.push({
509
+ name: 'automated_greeting_message_view_catalog',
510
+ buttonParamsJson: JSON.stringify(options),
511
+ });
512
+ return this;
513
+ }
514
+
515
+ /**
516
+ * Add a `call_permission_request` button — asks the user to grant call
517
+ * permission before a voice/video call can be placed.
518
+ * See Button.#SPECIAL_FLOW.
519
+ */
520
+ addCallPermission(display_text = '', options = {}) {
521
+ this._buttons.push({
522
+ name: 'call_permission_request',
523
+ buttonParamsJson: JSON.stringify({
524
+ ...(display_text ? { display_text } : {}),
525
+ ...options,
526
+ }),
527
+ });
528
+ return this;
529
+ }
530
+
531
+ /**
532
+ * `request_contact_info` native-flow button (asks the recipient to share their contact info).
533
+ * Captured from official-client traffic: the button carries NO params (no buttonParamsJson at all) and the message has
534
+ * `messageParamsJson: "{}"`. It is deliberately NOT in FLOWS_MAP / #SPECIAL_FLOW: the client sends it inside the generic
535
+ * `<native_flow v='9' name='mixed'>` biz node, which is exactly what getBizBinaryNode() already emits for unlisted names.
536
+ * Pass `display_text` only if you want to override the client's own label (unverified).
537
+ */
538
+ addRequestContactInfo(display_text = '') {
539
+ this._buttons.push({
540
+ name: 'request_contact_info',
541
+ ...(display_text ? { buttonParamsJson: JSON.stringify({ display_text }) } : {}),
542
+ });
543
+ return this;
544
+ }
545
+
546
+ /**
547
+ * Add a `payment_info` button carrying a structured payment-settings payload
548
+ * (e.g. a PIX static-code block). Payload shape is dictated by WhatsApp's
549
+ * payment flows and is passed through as given — validate it yourself.
550
+ * Business/payment-enabled accounts only.
551
+ * @param {Record<string, any>} payload e.g. `{ payment_settings: [{ type: 'pix_static_code', pix_static_code: {...} }] }`.
552
+ */
553
+ addPaymentInfo(payload = {}) {
554
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
555
+ throw new TypeError('addPaymentInfo(payload) requires a plain object');
556
+ }
557
+ this._buttons.push({
558
+ name: 'payment_info',
559
+ buttonParamsJson: JSON.stringify(payload),
560
+ });
561
+ return this;
562
+ }
563
+
564
+ /**
565
+ * Add a `review_and_pay` button (order/payment summary flow).
566
+ * Server-validated by WhatsApp; malformed or
567
+ * unauthorized payloads are typically ignored rather than erroring locally.
568
+ * @param {Record<string, any>} payload Order/payment summary payload.
569
+ */
570
+ addReviewAndPay(payload = {}) {
571
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
572
+ throw new TypeError('addReviewAndPay(payload) requires a plain object');
573
+ }
574
+ this._buttons.push({
575
+ name: 'review_and_pay',
576
+ buttonParamsJson: JSON.stringify(payload),
577
+ });
578
+ return this;
579
+ }
580
+
581
+ /**
582
+ * add a `review_and_pay` button from a short spec -- shorthand for
583
+ * `addButton('review_and_pay', buildPaymentParams(spec))`. `done: false` (default) = pending request card listing
584
+ * `spec.accounts`; `done: true` = already-paid order card. See `buildPaymentParams()` for the spec.
585
+ * @param {{amount: number, item: string, note?: string, done?: boolean, accounts?: object[]}} spec
586
+ */
587
+ addPay(spec) {
588
+ this._buttons.push({ name: 'review_and_pay', buttonParamsJson: buildPaymentParams(spec) });
589
+ return this;
590
+ }
591
+
592
+ /** Go-name alias of `addPay()`. */
593
+ pay(spec) {
594
+ return this.addPay(spec);
595
+ }
596
+
597
+ #simple(name, display_text, id, options) {
598
+ if (!display_text || !id) throw new TypeError(`${name} button requires both a label and an id`);
599
+ return this.addButton(name, { display_text, id, ...options });
600
+ }
601
+
602
+ /** `mpm` (multi-product message) button. */
603
+ addMPM(display_text = '', id = '', options = {}) {
604
+ return this.#simple('mpm', display_text, id, options);
605
+ }
606
+
607
+ /** `payment_info` button in (label, id) form -- see addPaymentInfo(payload) for the raw-payload form. */
608
+ addPayment(display_text = '', id = '', options = {}) {
609
+ return this.#simple('payment_info', display_text, id, options);
610
+ }
611
+
612
+ /** `galaxy_message` (agent transfer) button. */
613
+ addAgentTransfer(display_text = '', id = '', options = {}) {
614
+ return this.#simple('galaxy_message', display_text, id, options);
615
+ }
616
+
617
+ /** `review_order` button. */
618
+ addReviewOrder(display_text = '', id = '', options = {}) {
619
+ return this.#simple('review_order', display_text, id, options);
620
+ }
621
+
622
+ // -- Split buttons (two buttons side by side). Wire format: an empty-name marker button followed by the
623
+ // left and right buttons. Ported from betton Button; rendering is decided by the WhatsApp client.
624
+ #pushSplit(leftName, leftParams, rightName, rightParams) {
625
+ for (const [n, p] of [[leftName, leftParams], [rightName, rightParams]]) {
626
+ if (typeof n !== 'string' || !n.trim()) throw new TypeError('split button sides need a non-empty button name');
627
+ if (p === undefined || p === null) throw new TypeError(`split button side "${n}" needs params`);
628
+ }
629
+ this._buttons.push({ name: '', buttonParamsJson: '' });
630
+ this._buttons.push({ name: leftName, buttonParamsJson: typeof leftParams === 'string' ? leftParams : JSON.stringify(leftParams) });
631
+ this._buttons.push({ name: rightName, buttonParamsJson: typeof rightParams === 'string' ? rightParams : JSON.stringify(rightParams) });
632
+ return this;
633
+ }
634
+
635
+ /** Two quick-reply buttons side by side. */
636
+ addSplitReply(leftText = '', leftId = '', rightText = '', rightId = '') {
637
+ return this.#pushSplit('quick_reply', { display_text: leftText, id: leftId }, 'quick_reply', { display_text: rightText, id: rightId });
638
+ }
639
+
640
+ /** Two URL buttons side by side. */
641
+ addSplitUrl(leftText = '', leftUrl = '', rightText = '', rightUrl = '') {
642
+ return this.#pushSplit('cta_url', { display_text: leftText, url: leftUrl, webview_interaction: false }, 'cta_url', { display_text: rightText, url: rightUrl, webview_interaction: false });
643
+ }
644
+
645
+ /** Quick-reply (left) + URL (right) side by side. */
646
+ addSplitReplyUrl(replyText = '', replyId = '', urlText = '', url = '') {
647
+ return this.#pushSplit('quick_reply', { display_text: replyText, id: replyId }, 'cta_url', { display_text: urlText, url, webview_interaction: false });
648
+ }
649
+
650
+ /** Quick-reply (left) + copy (right) side by side. */
651
+ addSplitReplyCopy(replyText = '', replyId = '', copyText = '', copyCode = '') {
652
+ return this.#pushSplit('quick_reply', { display_text: replyText, id: replyId }, 'cta_copy', { display_text: copyText, copy_code: copyCode, id: `${replyId}_copy` });
653
+ }
654
+
655
+ /** URL (left) + copy (right) side by side. */
656
+ addSplitUrlCopy(urlText = '', url = '', copyText = '', copyCode = '') {
657
+ return this.#pushSplit('cta_url', { display_text: urlText, url, webview_interaction: false }, 'cta_copy', { display_text: copyText, copy_code: copyCode, id: `copy_${Date.now()}` });
658
+ }
659
+
660
+ /** Generic split: `{ name, params }` on each side. */
661
+ addSplit(left = {}, right = {}) {
662
+ return this.#pushSplit(left.name, left.params, right.name, right.params);
663
+ }
664
+
665
+ /** `single_select` (left) + quick-reply (right) side by side. */
666
+ addSplitSelectReply(selectTitle, sections = [], replyText = '', replyId = '') {
667
+ return this.#pushSplit('single_select', { title: selectTitle, sections }, 'quick_reply', { display_text: replyText, id: replyId });
668
+ }
669
+
670
+ /**
671
+ * Send an audio clip (e.g. a menu jingle) alongside a button message.
672
+ * @param {object} sock Active socket. @param {string} jid Chat jid. @param {string|Buffer} audioSrc Url, file path or Buffer.
673
+ */
674
+ static async sendAudio(sock, jid, audioSrc, { quoted, ptt = false, mimetype = 'audio/mpeg' } = {}) {
675
+ const { readFileSync } = await import('node:fs');
676
+ const audio = Buffer.isBuffer(audioSrc) ? audioSrc : /^https?:\/\//i.test(audioSrc) ? { url: audioSrc } : readFileSync(audioSrc);
677
+ return sock.sendMessage(jid, { audio, ptt, mimetype }, { quoted });
678
+ }
679
+
680
+ /**
681
+ * Add a `wa_payment_transaction_details` button referencing a prior transaction.
682
+ * See Button.#SPECIAL_FLOW.
683
+ */
684
+ addTransactionDetails(payload = {}) {
685
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
686
+ throw new TypeError('addTransactionDetails(payload) requires a plain object');
687
+ }
688
+ this._buttons.push({
689
+ name: 'wa_payment_transaction_details',
690
+ buttonParamsJson: JSON.stringify(payload),
691
+ });
692
+ return this;
693
+ }
694
+
695
+ /**
696
+ * Add an `mpm` (multi-product message) button referencing a set of catalog items.
697
+ * Business-catalog accounts only; see Button.#SPECIAL_FLOW.
698
+ */
699
+ addMultiProduct(payload = {}) {
700
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
701
+ throw new TypeError('addMultiProduct(payload) requires a plain object');
702
+ }
703
+ this._buttons.push({
704
+ name: 'mpm',
705
+ buttonParamsJson: JSON.stringify(payload),
706
+ });
707
+ return this;
708
+ }
709
+
710
+
711
+ /** Native-flow `payment_key_info` shortcut. Payload is passed through unchanged. */
712
+ addPaymentKeyInfo(payload = {}) {
713
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addPaymentKeyInfo(payload) requires a plain object');
714
+ this._buttons.push({ name: 'payment_key_info', buttonParamsJson: JSON.stringify(payload) });
715
+ return this;
716
+ }
717
+
718
+ /** Native-flow `booking_confirmation` shortcut. Payload is passed through unchanged. */
719
+ addBookingConfirmation(payload = {}) {
720
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addBookingConfirmation(payload) requires a plain object');
721
+ this._buttons.push({ name: 'booking_confirmation', buttonParamsJson: JSON.stringify(payload) });
722
+ return this;
723
+ }
724
+
725
+ /** Native-flow `card_message` shortcut, matching this fork's prepareNativeFlowButtons(). */
726
+ addCardMessage(payload = {}) {
727
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addCardMessage(payload) requires a plain object');
728
+ this._buttons.push({ name: 'card_message', buttonParamsJson: JSON.stringify(payload) });
729
+ return this;
730
+ }
731
+
732
+ /** Native-flow `order_details` shortcut. */
733
+ addOrderDetails(payload = {}) {
734
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addOrderDetails(payload) requires a plain object');
735
+ this._buttons.push({ name: 'order_details', buttonParamsJson: JSON.stringify(payload) });
736
+ return this;
737
+ }
738
+
739
+ /** Native-flow `order_status` shortcut. */
740
+ addOrderStatus(payload = {}) {
741
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addOrderStatus(payload) requires a plain object');
742
+ this._buttons.push({ name: 'order_status', buttonParamsJson: JSON.stringify(payload) });
743
+ return this;
744
+ }
745
+
746
+ /** Native-flow `payment_status` shortcut. */
747
+ addPaymentStatus(payload = {}) {
748
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addPaymentStatus(payload) requires a plain object');
749
+ this._buttons.push({ name: 'payment_status', buttonParamsJson: JSON.stringify(payload) });
750
+ return this;
751
+ }
752
+
753
+ /** Native-flow `payment_method` shortcut. */
754
+ addPaymentMethod(payload = {}) {
755
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) throw new TypeError('addPaymentMethod(payload) requires a plain object');
756
+ this._buttons.push({ name: 'payment_method', buttonParamsJson: JSON.stringify(payload) });
757
+ return this;
758
+ }
759
+
760
+ /** Native-flow `track_order` shortcut. */
761
+ addTrackOrder(id, display_text = '🚚 Track order') {
762
+ if (!id) throw new TypeError('addTrackOrder(id) requires a non-empty id');
763
+ this._buttons.push({ name: 'track_order', buttonParamsJson: JSON.stringify({ id, display_text }) });
764
+ return this;
765
+ }
766
+
767
+ /** Native-flow `reorder` shortcut. */
768
+ addReorder(id, display_text = '🔁 Reorder') {
769
+ if (!id) throw new TypeError('addReorder(id) requires a non-empty id');
770
+ this._buttons.push({ name: 'reorder', buttonParamsJson: JSON.stringify({ id, display_text }) });
771
+ return this;
772
+ }
773
+
774
+ /** Native-flow `cancel_order` shortcut. */
775
+ addCancelOrder(id, display_text = '❌ Cancel order') {
776
+ if (!id) throw new TypeError('addCancelOrder(id) requires a non-empty id');
777
+ this._buttons.push({ name: 'cancel_order', buttonParamsJson: JSON.stringify({ id, display_text }) });
778
+ return this;
779
+ }
780
+
781
+ /** Native-flow `clear_chat` shortcut. */
782
+ addClearChat() {
783
+ this._buttons.push({ name: 'clear_chat', buttonParamsJson: '{}' });
784
+ return this;
785
+ }
786
+
787
+ /** Native-flow `navigateToScreen` shortcut. */
788
+ addNavigateToScreen(screen, data = {}) {
789
+ if (!screen) throw new TypeError('addNavigateToScreen(screen) requires a non-empty screen');
790
+ this._buttons.push({ name: 'navigateToScreen', buttonParamsJson: JSON.stringify({ screen_name: screen, data }) });
791
+ return this;
792
+ }
793
+
794
+ /** WhatsApp Flows shortcut. Requires a real registered Flow. */
795
+ addFlow(flow = {}, display_text = '') {
796
+ if (typeof flow !== 'object' || flow === null || Array.isArray(flow) || !flow.id) throw new TypeError('addFlow(flow) requires a plain object with flow.id');
797
+ this._buttons.push({
798
+ name: 'flow',
799
+ buttonParamsJson: JSON.stringify({
800
+ flow_message_version: flow.version || '3',
801
+ // flow_token: unique per-send session token WhatsApp Flows requires to
802
+ // correlate a flow_action data-exchange callback with this specific
803
+ // message. Was missing entirely -- without it the client can accept the
804
+ // message but has nothing to key the flow session on.
805
+ flow_token: flow.token || generateMessageIDV2(),
806
+ flow_id: flow.id,
807
+ flow_cta: display_text || flow.cta || 'Continue',
808
+ flow_action: flow.action || 'navigate',
809
+ flow_action_payload: flow.actionPayload || { screen: flow.screen || 'WELCOME', data: flow.data || {} },
810
+ }),
811
+ });
812
+ return this;
813
+ }
814
+
815
+ /** Native-flow `voice_call` shortcut. */
816
+ addVoiceCall(id, display_text = '📞 Voice call') {
817
+ if (!id) throw new TypeError('addVoiceCall(id) requires a non-empty id');
818
+ this._buttons.push({ name: 'voice_call', buttonParamsJson: JSON.stringify({ display_text, id }) });
819
+ return this;
820
+ }
821
+
822
+ /** Native-flow `video_call_button` shortcut. */
823
+ addVideoCall(id, display_text = '🎥 Video call') {
824
+ if (!id) throw new TypeError('addVideoCall(id) requires a non-empty id');
825
+ this._buttons.push({ name: 'video_call_button', buttonParamsJson: JSON.stringify({ display_text, id }) });
826
+ return this;
827
+ }
828
+
829
+ static #validateAgainstSchema(schema, data, label) {
830
+ for (const [key, type] of Object.entries(schema)) {
831
+ if (data[key] === undefined) continue;
832
+ const expectsArray = Array.isArray(type);
833
+ if (expectsArray) {
834
+ if (!Array.isArray(data[key]) || !data[key].every((v) => typeof v === type[0])) {
835
+ throw new TypeError(`${label}.${key} must be an array of ${type[0]}`);
836
+ }
837
+ } else if (typeof data[key] !== type) {
838
+ throw new TypeError(`${label}.${key} must be a ${type}`);
839
+ }
840
+ }
841
+ }
842
+
843
+ /** Set the message-level "limited time offer" strip (countdown banner above the buttons). */
844
+ setLimitedTimeOffer({ text = '', url = '', copy_code = '', expiration_time } = {}) {
845
+ const data = { text, url, copy_code, expiration_time };
846
+ Button.#validateAgainstSchema(Button.paramsList.limited_time_offer, data, 'limited_time_offer');
847
+ this._params = { ...this._params, limited_time_offer: data };
848
+ return this;
849
+ }
850
+
851
+ /** Configure how many buttons show inline before the rest collapse into a bottom sheet. */
852
+ setBottomSheet({ in_thread_buttons_limit, divider_indices = [], list_title = '', button_title = '' } = {}) {
853
+ const data = { in_thread_buttons_limit, divider_indices, list_title, button_title };
854
+ Button.#validateAgainstSchema(Button.paramsList.bottom_sheet, data, 'bottom_sheet');
855
+ this._params = { ...this._params, bottom_sheet: data };
856
+ return this;
857
+ }
858
+
859
+ /** Configure the tap-target callout shown pointing at a specific button by index. */
860
+ setTapTargetConfiguration({ title = '', description = '', canonical_url = '', domain = '', buttonIndex = 0 } = {}) {
861
+ const data = { title, description, canonical_url, domain, buttonIndex };
862
+ Button.#validateAgainstSchema(Button.paramsList.tap_target_configuration, data, 'tap_target_configuration');
863
+ this._params = { ...this._params, tap_target_configuration: data };
864
+ return this;
865
+ }
866
+
867
+ static paramsList = {
868
+ limited_time_offer: {
869
+ text: 'string',
870
+ url: 'string',
871
+ copy_code: 'string',
872
+ expiration_time: 'number',
873
+ },
874
+ bottom_sheet: {
875
+ in_thread_buttons_limit: 'number',
876
+ divider_indices: ['number'],
877
+ list_title: 'string',
878
+ button_title: 'string',
879
+ },
880
+ tap_target_configuration: {
881
+ title: 'string',
882
+ description: 'string',
883
+ canonical_url: 'string',
884
+ domain: 'string',
885
+ buttonIndex: 'number',
886
+ },
887
+ };
888
+
889
+ static #SPECIAL_FLOW = {
890
+ review_and_pay: { v: '1', name: 'order_details' },
891
+ payment_info: { v: '1', name: 'payment_info' },
892
+ mpm: { v: '2', name: 'mpm' },
893
+ cta_catalog: { v: '2', name: 'cta_catalog' },
894
+ send_location: { v: '2', name: 'send_location' },
895
+ call_permission_request: { v: '2', name: 'call_permission_request' },
896
+ wa_payment_transaction_details: { v: '2', name: 'wa_payment_transaction_details' },
897
+ payment_key_info: { v: '1', name: 'payment_key_info' },
898
+ booking_confirmation: { v: '1', name: 'booking_confirmation' },
899
+ automated_greeting_message_view_catalog: { v: '2', name: 'automated_greeting_message_view_catalog' },
900
+ };
901
+
902
+ /** Render this builder's header/body/footer/media/buttons/params into an `interactiveMessage`-shaped card (without the outer `interactiveMessage` wrapper or contextInfo). */
903
+ async toCard() {
904
+ let header;
905
+ if (this._locationHeader) {
906
+ let jpegThumbnail = null;
907
+ const thumb = this._locationHeader.thumbnailUrl;
908
+ try {
909
+ const buf = Buffer.isBuffer(thumb) ? thumb : thumb ? await Toolkit.fetchBuffer(thumb, {}, { silent: true }) : null;
910
+ if (buf?.length) jpegThumbnail = await Toolkit.resize(buf, 300, 300);
911
+ } catch {
912
+ jpegThumbnail = null;
913
+ }
914
+ header = {
915
+ hasMediaAttachment: false,
916
+ locationMessage: { degreesLatitude: 0, degreesLongitude: 0, name: this._title, address: this._subtitle, jpegThumbnail },
917
+ };
918
+ } else {
919
+ // gifPlayback is applied to the uploaded videoMessage afterwards, so it is stripped from the upload input.
920
+ const { gifPlayback, ...upload } = this._gifPlayback && this._data ? this._data : { ...this._data };
921
+ const source = this._gifPlayback ? upload : this._data;
922
+ let media = {};
923
+ if (this._data) {
924
+ media = await prepareWAMessageMedia(source, { upload: this.#client.waUploadToServer }).catch((e) => {
925
+ if (String(e).includes('Invalid media type')) return source;
926
+ throw e;
927
+ });
928
+ if (this._gifPlayback && media.videoMessage) media = { ...media, videoMessage: { ...media.videoMessage, gifPlayback: true } };
929
+ }
930
+ header = { title: this._title, subtitle: this._subtitle, hasMediaAttachment: !!this._data, ...media };
931
+ }
932
+
933
+ return {
934
+ body: {
935
+ text: this._body,
936
+ },
937
+ footer: {
938
+ text: this._footer,
939
+ },
940
+ header,
941
+ nativeFlowMessage: {
942
+ messageParamsJson: JSON.stringify(this._params),
943
+ buttons: this._buttons,
944
+ },
945
+ };
946
+ }
947
+
948
+ #isLoneSingleSelect() {
949
+ return this._buttons.length === 1 && this._buttons[0].name === 'single_select';
950
+ }
951
+
952
+ #toListMessage() {
953
+ const { title: buttonText, sections } = JSON.parse(this._buttons[0].buttonParamsJson);
954
+ return {
955
+ listMessage: {
956
+ title: this._title || undefined,
957
+ description: this._body || undefined,
958
+ footerText: this._footer || undefined,
959
+ buttonText: buttonText || undefined,
960
+ listType: 1,
961
+ sections: (sections || []).map((s) => ({
962
+ title: s.title,
963
+ rows: (s.rows || []).map((r) => ({
964
+ title: r.title || r.header || '',
965
+ description: r.description || '',
966
+ rowId: r.id || '',
967
+ })),
968
+ })),
969
+ contextInfo: this._contextInfo,
970
+ },
971
+ };
972
+ }
973
+
974
+ /** @returns {Record<string, any>} The final content object, without generating/wrapping a WAMessage. Useful when composing this interactive card into something else (e.g. Carousel). */
975
+ async build(jid, { ...options } = {}) {
976
+ if (this._buttons.length === 0 && !this._bloksWidget) {
977
+ throw new Error('Button requires at least one button (use addReply/addUrl/addCall/addSelection/addButton/...) or a Bloks widget (setBloksWidget())');
978
+ }
979
+
980
+ const extra = this._extraPayload?.messageContextInfo && !this._extraPayload.messageContextInfo.messageSecret
981
+ ? { ...this._extraPayload, messageContextInfo: { ...this._extraPayload.messageContextInfo, messageSecret: crypto.randomBytes(32) } }
982
+ : this._extraPayload;
983
+
984
+ if (this._buttons.length > 0 && this.#isLoneSingleSelect()) {
985
+ return generateWAMessageFromContent(jid, { ...extra, ...this.#toListMessage() }, { ...options });
986
+ }
987
+
988
+ const message = this._buttons.length > 0 ? await this.toCard() : {};
989
+
990
+ return generateWAMessageFromContent(
991
+ jid,
992
+ {
993
+ ...(this._bloksWidget && {
994
+ messageContextInfo: { messageSecret: crypto.randomBytes(32) },
995
+ }),
996
+ ...extra,
997
+ interactiveMessage: {
998
+ ...message,
999
+ ...(this._bloksWidget && { bloksWidget: this._bloksWidget }),
1000
+ contextInfo: this._contextInfo,
1001
+ },
1002
+ },
1003
+ { ...options }
1004
+ );
1005
+ }
1006
+
1007
+ /** Build and send this interactive message. @param {string} jid Destination chat/group jid. */
1008
+ async send(jid, { ...options } = {}) {
1009
+ const msg = await this.build(jid, options);
1010
+
1011
+ const bizNode = getBizBinaryNode(msg.message);
1012
+
1013
+ await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
1014
+ messageId: msg.key.id,
1015
+ additionalNodes: [bizNode],
1016
+ ...options,
1017
+ });
1018
+ return msg;
1019
+ }
1020
+ }
1021
+
1022
+ /**
1023
+ * Legacy `buttonsMessage` builder (up to 3 simple quick-reply buttons under a
1024
+ * media/location header). Simpler and more universally supported than
1025
+ * `Button`'s native-flow messages, but capped to `type: 1` quick replies.
1026
+ */
1027
+ class CardBuilder {
1028
+ /** @param {import('../../WAProto/index.js').WASocket} client Active Baileys socket. */
1029
+ constructor(client) {
1030
+ this._card = new Button(client);
1031
+ }
1032
+
1033
+ image(url) {
1034
+ this._card.setImage(url);
1035
+ return this;
1036
+ }
1037
+
1038
+ title(t) {
1039
+ this._card.setTitle(t);
1040
+ return this;
1041
+ }
1042
+
1043
+ text(t) {
1044
+ this._card.setBody(t);
1045
+ return this;
1046
+ }
1047
+
1048
+ button(displayText, id) {
1049
+ this._card.addReply(displayText, id);
1050
+ return this;
1051
+ }
1052
+ }
1053
+
1054
+ export { Button, CardBuilder };