@deffa5556/bail 1.0.6 → 1.0.7

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 (314) hide show
  1. package/cjs/WAProto/index.cjs +106053 -0
  2. package/cjs/deffa/config.cjs +14 -0
  3. package/cjs/deffa/plugins/ai/deepseekr1.cjs +35 -0
  4. package/cjs/deffa/plugins/ai/gita.cjs +26 -0
  5. package/cjs/deffa/plugins/ai/glm47flash.cjs +35 -0
  6. package/cjs/deffa/plugins/ai/gptoss120b.cjs +35 -0
  7. package/cjs/deffa/plugins/ai/qwq32b.cjs +35 -0
  8. package/cjs/deffa/plugins/berita/antara.cjs +25 -0
  9. package/cjs/deffa/plugins/berita/cnbcindonesia.cjs +25 -0
  10. package/cjs/deffa/plugins/berita/cnn.cjs +25 -0
  11. package/cjs/deffa/plugins/berita/kompas.cjs +25 -0
  12. package/cjs/deffa/plugins/berita/liputan6.cjs +25 -0
  13. package/cjs/deffa/plugins/berita/merdeka.cjs +25 -0
  14. package/cjs/deffa/plugins/berita/sindonews.cjs +25 -0
  15. package/cjs/deffa/plugins/berita/tribunnews.cjs +25 -0
  16. package/cjs/deffa/plugins/downloader/douyin.cjs +30 -0
  17. package/cjs/deffa/plugins/downloader/facebook.cjs +30 -0
  18. package/cjs/deffa/plugins/downloader/github.cjs +35 -0
  19. package/cjs/deffa/plugins/downloader/lahelu.cjs +30 -0
  20. package/cjs/deffa/plugins/downloader/snackvideo.cjs +30 -0
  21. package/cjs/deffa/plugins/downloader/soundcloud.cjs +30 -0
  22. package/cjs/deffa/plugins/downloader/tiktok.cjs +30 -0
  23. package/cjs/deffa/plugins/downloader/tiktokhd.cjs +30 -0
  24. package/cjs/deffa/plugins/downloader/twitter.cjs +30 -0
  25. package/cjs/deffa/plugins/downloader/ummy.cjs +36 -0
  26. package/cjs/deffa/plugins/index.cjs +213 -0
  27. package/cjs/deffa/plugins/info/bmkg.cjs +34 -0
  28. package/cjs/deffa/plugins/info/cuaca.cjs +31 -0
  29. package/cjs/deffa/plugins/info/jadwaltv.cjs +29 -0
  30. package/cjs/deffa/plugins/maker/brat.cjs +45 -0
  31. package/cjs/deffa/plugins/maker/bratvid.cjs +52 -0
  32. package/cjs/deffa/plugins/search/8font.cjs +28 -0
  33. package/cjs/deffa/plugins/search/applemusic.cjs +28 -0
  34. package/cjs/deffa/plugins/search/bimg.cjs +30 -0
  35. package/cjs/deffa/plugins/search/brave.cjs +34 -0
  36. package/cjs/deffa/plugins/search/duckduckgo.cjs +28 -0
  37. package/cjs/deffa/plugins/search/lahelu.cjs +28 -0
  38. package/cjs/deffa/plugins/search/mangatoon.cjs +28 -0
  39. package/cjs/deffa/plugins/search/mcpedl.cjs +28 -0
  40. package/cjs/deffa/plugins/search/myinstants.cjs +28 -0
  41. package/cjs/deffa/plugins/search/otakotaku.cjs +28 -0
  42. package/cjs/deffa/plugins/search/pinterest.cjs +30 -0
  43. package/cjs/deffa/plugins/search/resep.cjs +28 -0
  44. package/cjs/deffa/plugins/search/seegore.cjs +30 -0
  45. package/cjs/deffa/plugins/search/soundcloud.cjs +28 -0
  46. package/cjs/deffa/plugins/search/youtube.cjs +28 -0
  47. package/cjs/deffa/plugins/stalk/github.cjs +38 -0
  48. package/cjs/deffa/plugins/stalk/pinterest.cjs +37 -0
  49. package/cjs/deffa/plugins/stalk/threads.cjs +34 -0
  50. package/cjs/deffa/plugins/stalk/tiktok.cjs +37 -0
  51. package/cjs/deffa/plugins/stalk/twitter.cjs +37 -0
  52. package/cjs/deffa/plugins/stalk/youtube.cjs +37 -0
  53. package/cjs/lib/Defaults/index.cjs +158 -0
  54. package/cjs/lib/Discord/Client.cjs +263 -0
  55. package/cjs/lib/Discord/Constants.cjs +1842 -0
  56. package/cjs/lib/Discord/connect-dc.cjs +11 -0
  57. package/cjs/lib/Discord/esm-bridge.cjs +136 -0
  58. package/cjs/lib/Discord/gateway/Dispatcher.cjs +93 -0
  59. package/cjs/lib/Discord/gateway/Shard.cjs +695 -0
  60. package/cjs/lib/Discord/gateway/ShardManager.cjs +344 -0
  61. package/cjs/lib/Discord/gateway/compression/base.cjs +13 -0
  62. package/cjs/lib/Discord/gateway/compression/config.cjs +47 -0
  63. package/cjs/lib/Discord/gateway/compression/pako.cjs +44 -0
  64. package/cjs/lib/Discord/gateway/compression/zlib-native.cjs +47 -0
  65. package/cjs/lib/Discord/gateway/compression/zlib-sync.cjs +31 -0
  66. package/cjs/lib/Discord/gateway/compression/zstd-napi.cjs +80 -0
  67. package/cjs/lib/Discord/gateway/compression/zstd-native.cjs +46 -0
  68. package/cjs/lib/Discord/gateway/events.cjs +956 -0
  69. package/cjs/lib/Discord/index.cjs +238 -0
  70. package/cjs/lib/Discord/rest/Bucket.cjs +69 -0
  71. package/cjs/lib/Discord/rest/DiscordHTTPError.cjs +63 -0
  72. package/cjs/lib/Discord/rest/DiscordRESTError.cjs +84 -0
  73. package/cjs/lib/Discord/rest/OAuthHelper.cjs +226 -0
  74. package/cjs/lib/Discord/rest/RESTManager.cjs +116 -0
  75. package/cjs/lib/Discord/rest/RequestHandler.cjs +320 -0
  76. package/cjs/lib/Discord/rest/SequentialBucket.cjs +69 -0
  77. package/cjs/lib/Discord/routes/Applications.cjs +625 -0
  78. package/cjs/lib/Discord/routes/Channels.cjs +1199 -0
  79. package/cjs/lib/Discord/routes/Guilds.cjs +1792 -0
  80. package/cjs/lib/Discord/routes/Interactions.cjs +212 -0
  81. package/cjs/lib/Discord/routes/Lobbies.cjs +197 -0
  82. package/cjs/lib/Discord/routes/Miscellaneous.cjs +120 -0
  83. package/cjs/lib/Discord/routes/OAuth.cjs +350 -0
  84. package/cjs/lib/Discord/routes/Users.cjs +107 -0
  85. package/cjs/lib/Discord/routes/Webhooks.cjs +308 -0
  86. package/cjs/lib/Discord/structures/AnnouncementChannel.cjs +46 -0
  87. package/cjs/lib/Discord/structures/AnnouncementThreadChannel.cjs +28 -0
  88. package/cjs/lib/Discord/structures/Application.cjs +345 -0
  89. package/cjs/lib/Discord/structures/ApplicationCommand.cjs +109 -0
  90. package/cjs/lib/Discord/structures/Attachment.cjs +46 -0
  91. package/cjs/lib/Discord/structures/AuditLogEntry.cjs +41 -0
  92. package/cjs/lib/Discord/structures/AutoModerationRule.cjs +117 -0
  93. package/cjs/lib/Discord/structures/AutocompleteInteraction.cjs +90 -0
  94. package/cjs/lib/Discord/structures/Base.cjs +56 -0
  95. package/cjs/lib/Discord/structures/BaseEntitlement.cjs +40 -0
  96. package/cjs/lib/Discord/structures/CategoryChannel.cjs +102 -0
  97. package/cjs/lib/Discord/structures/Channel.cjs +89 -0
  98. package/cjs/lib/Discord/structures/ClientApplication.cjs +269 -0
  99. package/cjs/lib/Discord/structures/CommandInteraction.cjs +294 -0
  100. package/cjs/lib/Discord/structures/ComponentInteraction.cjs +306 -0
  101. package/cjs/lib/Discord/structures/Entitlement.cjs +24 -0
  102. package/cjs/lib/Discord/structures/ExtendedUser.cjs +48 -0
  103. package/cjs/lib/Discord/structures/ForumChannel.cjs +20 -0
  104. package/cjs/lib/Discord/structures/GroupChannel.cjs +160 -0
  105. package/cjs/lib/Discord/structures/Guild.cjs +1289 -0
  106. package/cjs/lib/Discord/structures/GuildChannel.cjs +82 -0
  107. package/cjs/lib/Discord/structures/GuildPreview.cjs +141 -0
  108. package/cjs/lib/Discord/structures/GuildScheduledEvent.cjs +166 -0
  109. package/cjs/lib/Discord/structures/GuildTemplate.cjs +96 -0
  110. package/cjs/lib/Discord/structures/Integration.cjs +123 -0
  111. package/cjs/lib/Discord/structures/Interaction.cjs +78 -0
  112. package/cjs/lib/Discord/structures/InteractionResolvedChannel.cjs +36 -0
  113. package/cjs/lib/Discord/structures/Invite.cjs +196 -0
  114. package/cjs/lib/Discord/structures/InviteGuild.cjs +117 -0
  115. package/cjs/lib/Discord/structures/InviteRole.cjs +88 -0
  116. package/cjs/lib/Discord/structures/Lobby.cjs +84 -0
  117. package/cjs/lib/Discord/structures/LobbyMember.cjs +30 -0
  118. package/cjs/lib/Discord/structures/MediaChannel.cjs +20 -0
  119. package/cjs/lib/Discord/structures/Member.cjs +300 -0
  120. package/cjs/lib/Discord/structures/Message.cjs +553 -0
  121. package/cjs/lib/Discord/structures/ModalSubmitInteraction.cjs +263 -0
  122. package/cjs/lib/Discord/structures/OAuthApplication.cjs +203 -0
  123. package/cjs/lib/Discord/structures/OAuthGuild.cjs +98 -0
  124. package/cjs/lib/Discord/structures/PartialApplication.cjs +97 -0
  125. package/cjs/lib/Discord/structures/Permission.cjs +61 -0
  126. package/cjs/lib/Discord/structures/PermissionOverwrite.cjs +46 -0
  127. package/cjs/lib/Discord/structures/PingInteraction.cjs +27 -0
  128. package/cjs/lib/Discord/structures/Poll.cjs +69 -0
  129. package/cjs/lib/Discord/structures/PrimaryGuild.cjs +93 -0
  130. package/cjs/lib/Discord/structures/PrivateChannel.cjs +131 -0
  131. package/cjs/lib/Discord/structures/PrivateThreadChannel.cjs +28 -0
  132. package/cjs/lib/Discord/structures/PublicThreadChannel.cjs +36 -0
  133. package/cjs/lib/Discord/structures/Role.cjs +126 -0
  134. package/cjs/lib/Discord/structures/SKU.cjs +58 -0
  135. package/cjs/lib/Discord/structures/Soundboard.cjs +58 -0
  136. package/cjs/lib/Discord/structures/StageChannel.cjs +45 -0
  137. package/cjs/lib/Discord/structures/StageInstance.cjs +80 -0
  138. package/cjs/lib/Discord/structures/Subscription.cjs +21 -0
  139. package/cjs/lib/Discord/structures/Team.cjs +70 -0
  140. package/cjs/lib/Discord/structures/TestEntitlement.cjs +22 -0
  141. package/cjs/lib/Discord/structures/TextChannel.cjs +48 -0
  142. package/cjs/lib/Discord/structures/TextableChannel.cjs +265 -0
  143. package/cjs/lib/Discord/structures/TextableVoiceChannel.cjs +70 -0
  144. package/cjs/lib/Discord/structures/ThreadChannel.cjs +276 -0
  145. package/cjs/lib/Discord/structures/ThreadOnlyChannel.cjs +205 -0
  146. package/cjs/lib/Discord/structures/ThreadableChannel.cjs +57 -0
  147. package/cjs/lib/Discord/structures/UnavailableGuild.cjs +21 -0
  148. package/cjs/lib/Discord/structures/User.cjs +223 -0
  149. package/cjs/lib/Discord/structures/VoiceChannel.cjs +34 -0
  150. package/cjs/lib/Discord/structures/VoiceState.cjs +113 -0
  151. package/cjs/lib/Discord/structures/Webhook.cjs +224 -0
  152. package/cjs/lib/Discord/util/Collection.cjs +77 -0
  153. package/cjs/lib/Discord/util/Errors.cjs +81 -0
  154. package/cjs/lib/Discord/util/QueryBuilder.cjs +20 -0
  155. package/cjs/lib/Discord/util/Routes.cjs +293 -0
  156. package/cjs/lib/Discord/util/SimpleCollection.cjs +78 -0
  157. package/cjs/lib/Discord/util/Time.cjs +92 -0
  158. package/cjs/lib/Discord/util/TypedCollection.cjs +78 -0
  159. package/cjs/lib/Discord/util/TypedEmitter.cjs +20 -0
  160. package/cjs/lib/Discord/util/Util.cjs +906 -0
  161. package/cjs/lib/Discord/util/interactions/InteractionOptionsWrapper.cjs +207 -0
  162. package/cjs/lib/Discord/util/interactions/MessageInteractionResponse.cjs +26 -0
  163. package/cjs/lib/Discord/util/interactions/ModalSubmitInteractionComponentsWrapper.cjs +98 -0
  164. package/cjs/lib/Discord/util/interactions/SelectMenuValuesWrapper.cjs +77 -0
  165. package/cjs/lib/Discord/util/interactions/shared.cjs +20 -0
  166. package/cjs/lib/Discord/util/warning.cjs +34 -0
  167. package/cjs/lib/Signal/Group/ciphertext-message.cjs +16 -0
  168. package/cjs/lib/Signal/Group/group-session-builder.cjs +67 -0
  169. package/cjs/lib/Signal/Group/group_cipher.cjs +86 -0
  170. package/cjs/lib/Signal/Group/index.cjs +58 -0
  171. package/cjs/lib/Signal/Group/keyhelper.cjs +56 -0
  172. package/cjs/lib/Signal/Group/sender-chain-key.cjs +30 -0
  173. package/cjs/lib/Signal/Group/sender-key-distribution-message.cjs +67 -0
  174. package/cjs/lib/Signal/Group/sender-key-message.cjs +70 -0
  175. package/cjs/lib/Signal/Group/sender-key-name.cjs +52 -0
  176. package/cjs/lib/Signal/Group/sender-key-record.cjs +45 -0
  177. package/cjs/lib/Signal/Group/sender-key-state.cjs +88 -0
  178. package/cjs/lib/Signal/Group/sender-message-key.cjs +30 -0
  179. package/cjs/lib/Signal/libsignal.cjs +467 -0
  180. package/cjs/lib/Signal/lid-mapping.cjs +281 -0
  181. package/cjs/lib/Socket/Client/index.cjs +19 -0
  182. package/cjs/lib/Socket/Client/types.cjs +15 -0
  183. package/cjs/lib/Socket/Client/websocket.cjs +61 -0
  184. package/cjs/lib/Socket/business.cjs +384 -0
  185. package/cjs/lib/Socket/chats.cjs +1221 -0
  186. package/cjs/lib/Socket/communities.cjs +440 -0
  187. package/cjs/lib/Socket/groups.cjs +353 -0
  188. package/cjs/lib/Socket/index.cjs +14 -0
  189. package/cjs/lib/Socket/messages-recv.cjs +1772 -0
  190. package/cjs/lib/Socket/messages-send.cjs +1376 -0
  191. package/cjs/lib/Socket/mex.cjs +46 -0
  192. package/cjs/lib/Socket/newsletter.cjs +230 -0
  193. package/cjs/lib/Socket/socket.cjs +976 -0
  194. package/cjs/lib/Store/index.cjs +20 -0
  195. package/cjs/lib/Store/make-in-memory-store.cjs +470 -0
  196. package/cjs/lib/Store/make-ordered-dictionary.cjs +82 -0
  197. package/cjs/lib/Store/object-repository.cjs +28 -0
  198. package/cjs/lib/Telegram/button.cjs +147 -0
  199. package/cjs/lib/Telegram/composer.cjs +582 -0
  200. package/cjs/lib/Telegram/context.cjs +853 -0
  201. package/cjs/lib/Telegram/core/helpers/args.cjs +57 -0
  202. package/cjs/lib/Telegram/core/helpers/check.cjs +55 -0
  203. package/cjs/lib/Telegram/core/helpers/compact.cjs +16 -0
  204. package/cjs/lib/Telegram/core/helpers/deunionize.cjs +12 -0
  205. package/cjs/lib/Telegram/core/helpers/formatting.cjs +91 -0
  206. package/cjs/lib/Telegram/core/helpers/util.cjs +50 -0
  207. package/cjs/lib/Telegram/core/network/client.cjs +338 -0
  208. package/cjs/lib/Telegram/core/network/error.cjs +21 -0
  209. package/cjs/lib/Telegram/core/network/multipart-stream.cjs +79 -0
  210. package/cjs/lib/Telegram/core/network/polling.cjs +87 -0
  211. package/cjs/lib/Telegram/core/network/webhook.cjs +54 -0
  212. package/cjs/lib/Telegram/core/types/typegram.cjs +31 -0
  213. package/cjs/lib/Telegram/deffa-telegraf.cjs +264 -0
  214. package/cjs/lib/Telegram/esm-bridge.cjs +20 -0
  215. package/cjs/lib/Telegram/filters.cjs +69 -0
  216. package/cjs/lib/Telegram/format.cjs +58 -0
  217. package/cjs/lib/Telegram/future.cjs +140 -0
  218. package/cjs/lib/Telegram/index.cjs +67 -0
  219. package/cjs/lib/Telegram/input.cjs +61 -0
  220. package/cjs/lib/Telegram/markup.cjs +129 -0
  221. package/cjs/lib/Telegram/middleware.cjs +2 -0
  222. package/cjs/lib/Telegram/reactions.cjs +84 -0
  223. package/cjs/lib/Telegram/router.cjs +46 -0
  224. package/cjs/lib/Telegram/scenes/base.cjs +39 -0
  225. package/cjs/lib/Telegram/scenes/context.cjs +104 -0
  226. package/cjs/lib/Telegram/scenes/index.cjs +21 -0
  227. package/cjs/lib/Telegram/scenes/stage.cjs +49 -0
  228. package/cjs/lib/Telegram/scenes/wizard/context.cjs +31 -0
  229. package/cjs/lib/Telegram/scenes/wizard/index.cjs +45 -0
  230. package/cjs/lib/Telegram/scenes.cjs +21 -0
  231. package/cjs/lib/Telegram/session.cjs +166 -0
  232. package/cjs/lib/Telegram/telegram-types.cjs +6 -0
  233. package/cjs/lib/Telegram/telegram.cjs +945 -0
  234. package/cjs/lib/Telegram/types.cjs +2 -0
  235. package/cjs/lib/Telegram/utils.cjs +5 -0
  236. package/cjs/lib/Types/Auth.cjs +3 -0
  237. package/cjs/lib/Types/Bussines.cjs +3 -0
  238. package/cjs/lib/Types/Call.cjs +3 -0
  239. package/cjs/lib/Types/Chat.cjs +11 -0
  240. package/cjs/lib/Types/Contact.cjs +3 -0
  241. package/cjs/lib/Types/Events.cjs +4 -0
  242. package/cjs/lib/Types/GroupMetadata.cjs +3 -0
  243. package/cjs/lib/Types/Label.cjs +26 -0
  244. package/cjs/lib/Types/LabelAssociation.cjs +8 -0
  245. package/cjs/lib/Types/Message.cjs +19 -0
  246. package/cjs/lib/Types/Mex.cjs +40 -0
  247. package/cjs/lib/Types/Product.cjs +3 -0
  248. package/cjs/lib/Types/RichType.cjs +24 -0
  249. package/cjs/lib/Types/Signal.cjs +4 -0
  250. package/cjs/lib/Types/Socket.cjs +4 -0
  251. package/cjs/lib/Types/State.cjs +54 -0
  252. package/cjs/lib/Types/USync.cjs +4 -0
  253. package/cjs/lib/Types/index.cjs +42 -0
  254. package/cjs/lib/Utils/auth-utils.cjs +312 -0
  255. package/cjs/lib/Utils/browser-utils.cjs +39 -0
  256. package/cjs/lib/Utils/business.cjs +241 -0
  257. package/cjs/lib/Utils/chat-utils.cjs +890 -0
  258. package/cjs/lib/Utils/companion-reg-client-utils.cjs +51 -0
  259. package/cjs/lib/Utils/crypto.cjs +170 -0
  260. package/cjs/lib/Utils/decode-wa-message.cjs +330 -0
  261. package/cjs/lib/Utils/event-buffer.cjs +629 -0
  262. package/cjs/lib/Utils/generics.cjs +427 -0
  263. package/cjs/lib/Utils/history.cjs +141 -0
  264. package/cjs/lib/Utils/identity-change-handler.cjs +56 -0
  265. package/cjs/lib/Utils/index.cjs +43 -0
  266. package/cjs/lib/Utils/link-preview.cjs +122 -0
  267. package/cjs/lib/Utils/logger.cjs +8 -0
  268. package/cjs/lib/Utils/lt-hash.cjs +11 -0
  269. package/cjs/lib/Utils/make-mutex.cjs +38 -0
  270. package/cjs/lib/Utils/message-retry-manager.cjs +267 -0
  271. package/cjs/lib/Utils/messages-media.cjs +906 -0
  272. package/cjs/lib/Utils/messages.cjs +1909 -0
  273. package/cjs/lib/Utils/noise-handler.cjs +205 -0
  274. package/cjs/lib/Utils/offline-node-processor.cjs +43 -0
  275. package/cjs/lib/Utils/pre-key-manager.cjs +113 -0
  276. package/cjs/lib/Utils/process-message.cjs +755 -0
  277. package/cjs/lib/Utils/reporting-utils.cjs +263 -0
  278. package/cjs/lib/Utils/rich-message-utils.cjs +434 -0
  279. package/cjs/lib/Utils/session-guard.cjs +163 -0
  280. package/cjs/lib/Utils/signal.cjs +214 -0
  281. package/cjs/lib/Utils/stanza-ack.cjs +41 -0
  282. package/cjs/lib/Utils/sync-action-utils.cjs +54 -0
  283. package/cjs/lib/Utils/tc-token-utils.cjs +174 -0
  284. package/cjs/lib/Utils/text-sticker.cjs +174 -0
  285. package/cjs/lib/Utils/use-multi-file-auth-state.cjs +125 -0
  286. package/cjs/lib/Utils/use-single-file-auth-state.cjs +113 -0
  287. package/cjs/lib/Utils/use-sqlite-auth-state.cjs +145 -0
  288. package/cjs/lib/Utils/validate-connection.cjs +210 -0
  289. package/cjs/lib/WABinary/constants.cjs +1470 -0
  290. package/cjs/lib/WABinary/decode.cjs +301 -0
  291. package/cjs/lib/WABinary/encode.cjs +257 -0
  292. package/cjs/lib/WABinary/generic-utils.cjs +240 -0
  293. package/cjs/lib/WABinary/index.cjs +22 -0
  294. package/cjs/lib/WABinary/jid-utils.cjs +114 -0
  295. package/cjs/lib/WABinary/types.cjs +37 -0
  296. package/cjs/lib/WAM/BinaryInfo.cjs +14 -0
  297. package/cjs/lib/WAM/constants.cjs +22856 -0
  298. package/cjs/lib/WAM/encode.cjs +154 -0
  299. package/cjs/lib/WAM/index.cjs +20 -0
  300. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.cjs +56 -0
  301. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.cjs +58 -0
  302. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.cjs +31 -0
  303. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.cjs +42 -0
  304. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.cjs +29 -0
  305. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.cjs +55 -0
  306. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.cjs +33 -0
  307. package/cjs/lib/WAUSync/Protocols/index.cjs +22 -0
  308. package/cjs/lib/WAUSync/USyncQuery.cjs +102 -0
  309. package/cjs/lib/WAUSync/USyncUser.cjs +35 -0
  310. package/cjs/lib/WAUSync/index.cjs +20 -0
  311. package/cjs/lib/index.cjs +372 -0
  312. package/cjs/lib/plugins/loader.cjs +117 -0
  313. package/lib/Defaults/index.js +1 -1
  314. package/package.json +11 -6
@@ -0,0 +1,906 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.uploadWithNodeHttp = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.DEF_MEDIA_HOST = exports.encryptedStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.extractVideoThumb = exports.getRawMediaUploadData = exports.hkdfInfoKey = exports.getImageProcessingLibrary = void 0;
37
+ exports.getMediaKeys = getMediaKeys;
38
+ exports.getAudioDuration = getAudioDuration;
39
+ exports.getAudioWaveform = getAudioWaveform;
40
+ exports.generateThumbnail = generateThumbnail;
41
+ exports.extensionForMediaMessage = extensionForMediaMessage;
42
+ const boom_1 = require("@hapi/boom");
43
+ const child_process_1 = require("child_process");
44
+ const Crypto = __importStar(require("crypto"));
45
+ const events_1 = require("events");
46
+ const fs_1 = require("fs");
47
+ const os_1 = require("os");
48
+ const path_1 = require("path");
49
+ const stream_1 = require("stream");
50
+ const url_1 = require("url");
51
+ const index_js_1 = require("../../WAProto/index.cjs");
52
+ const index_js_2 = require("../Defaults/index.cjs");
53
+ const index_js_3 = require("../WABinary/index.cjs");
54
+ const crypto_js_1 = require("./crypto.cjs");
55
+ const generics_js_1 = require("./generics.cjs");
56
+ const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
57
+ let imageProcessingLibrary;
58
+ const getImageProcessingLibrary = async () => {
59
+ if (imageProcessingLibrary) {
60
+ return imageProcessingLibrary;
61
+ }
62
+ //@ts-ignore
63
+ const [sharp, image, jimp] = await Promise.all([
64
+ Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }),
65
+ Promise.resolve().then(() => __importStar(require('@napi-rs/image'))).catch(() => { }),
66
+ Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { })
67
+ ]);
68
+ if (sharp) {
69
+ imageProcessingLibrary = { sharp };
70
+ }
71
+ else if (image) {
72
+ imageProcessingLibrary = { image };
73
+ }
74
+ else if (jimp) {
75
+ imageProcessingLibrary = { jimp };
76
+ }
77
+ else {
78
+ throw new boom_1.Boom('No image processing library available');
79
+ }
80
+ return imageProcessingLibrary;
81
+ };
82
+ exports.getImageProcessingLibrary = getImageProcessingLibrary;
83
+ const hkdfInfoKey = (type) => {
84
+ const hkdfInfo = index_js_2.MEDIA_HKDF_KEY_MAPPING[type];
85
+ return `WhatsApp ${hkdfInfo} Keys`;
86
+ };
87
+ exports.hkdfInfoKey = hkdfInfoKey;
88
+ const getRawMediaUploadData = async (media, mediaType, logger) => {
89
+ const { stream } = await (0, exports.getStream)(media);
90
+ logger?.debug('got stream for raw upload');
91
+ const hasher = Crypto.createHash('sha256');
92
+ const filePath = (0, path_1.join)((0, os_1.tmpdir)(), mediaType + (0, generics_js_1.generateMessageIDV2)());
93
+ const fileWriteStream = (0, fs_1.createWriteStream)(filePath);
94
+ let fileLength = 0;
95
+ try {
96
+ for await (const data of stream) {
97
+ fileLength += data.length;
98
+ hasher.update(data);
99
+ if (!fileWriteStream.write(data)) {
100
+ await (0, events_1.once)(fileWriteStream, 'drain');
101
+ }
102
+ }
103
+ fileWriteStream.end();
104
+ await (0, events_1.once)(fileWriteStream, 'finish');
105
+ stream.destroy();
106
+ const fileSha256 = hasher.digest();
107
+ logger?.debug('hashed data for raw upload');
108
+ return {
109
+ filePath: filePath,
110
+ fileSha256,
111
+ fileLength
112
+ };
113
+ }
114
+ catch (error) {
115
+ fileWriteStream.destroy();
116
+ stream.destroy();
117
+ try {
118
+ await fs_1.promises.unlink(filePath);
119
+ }
120
+ catch {
121
+ //
122
+ }
123
+ throw error;
124
+ }
125
+ };
126
+ exports.getRawMediaUploadData = getRawMediaUploadData;
127
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
128
+ async function getMediaKeys(buffer, mediaType) {
129
+ if (!buffer) {
130
+ throw new boom_1.Boom('Cannot derive from empty media key');
131
+ }
132
+ if (typeof buffer === 'string') {
133
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
134
+ }
135
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
136
+ const expandedMediaKey = (0, crypto_js_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
137
+ return {
138
+ iv: expandedMediaKey.slice(0, 16),
139
+ cipherKey: expandedMediaKey.slice(16, 48),
140
+ macKey: expandedMediaKey.slice(48, 80)
141
+ };
142
+ }
143
+ /** Extracts video thumb using FFMPEG */
144
+ const extractVideoThumb = async (path, time, size) => {
145
+ const ffmpeg = (0, child_process_1.spawn)('ffmpeg', [
146
+ '-loglevel', 'error',
147
+ '-ss', String(time),
148
+ '-i', path,
149
+ '-an', '-sn', '-dn',
150
+ '-map_metadata', '-1',
151
+ '-vf', `scale=${size.width}:-1`,
152
+ '-frames:v', '1',
153
+ '-c:v', 'mjpeg',
154
+ '-f', 'image2pipe',
155
+ 'pipe:1'
156
+ ], {
157
+ stdio: ['ignore', 'pipe', 'pipe']
158
+ });
159
+ let buffer = Buffer.alloc(0);
160
+ const stderrChunks = [];
161
+ ffmpeg.stdout.on('data', (chunk) => {
162
+ buffer = Buffer.concat([buffer, chunk]);
163
+ });
164
+ ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
165
+ const [code] = await (0, events_1.once)(ffmpeg, 'close');
166
+ if (code !== 0) {
167
+ throw new boom_1.Boom(`FFmpeg failed (code ${code}):\n` +
168
+ Buffer.concat(stderrChunks).toString('utf8'));
169
+ }
170
+ return buffer;
171
+ };
172
+ exports.extractVideoThumb = extractVideoThumb;
173
+ const extractImageThumb = async (bufferOrFilePath, width = 32) => {
174
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
175
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
176
+ if (bufferOrFilePath instanceof stream_1.Readable) {
177
+ bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
178
+ }
179
+ const lib = await (0, exports.getImageProcessingLibrary)();
180
+ if ('sharp' in lib && lib.sharp?.default) {
181
+ const img = lib.sharp.default(bufferOrFilePath);
182
+ const dimensions = await img.metadata();
183
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
184
+ return {
185
+ buffer,
186
+ original: {
187
+ width: dimensions.width,
188
+ height: dimensions.height
189
+ }
190
+ };
191
+ }
192
+ else if ('image' in lib && lib.image?.Transformer) {
193
+ if (!Buffer.isBuffer(bufferOrFilePath)) {
194
+ bufferOrFilePath = await fs_1.promises.readFile(bufferOrFilePath);
195
+ }
196
+ const img = new lib.image.Transformer(bufferOrFilePath);
197
+ const dimensions = await img.metadata();
198
+ const buffer = await img.resize(width, undefined, 0).jpeg(50);
199
+ return {
200
+ buffer,
201
+ original: {
202
+ width: dimensions.width,
203
+ height: dimensions.height
204
+ }
205
+ };
206
+ }
207
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
208
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
209
+ const dimensions = {
210
+ width: jimp.width,
211
+ height: jimp.height
212
+ };
213
+ const buffer = await jimp
214
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
215
+ .getBuffer('image/jpeg', { quality: 50 });
216
+ return {
217
+ buffer,
218
+ original: dimensions
219
+ };
220
+ }
221
+ else {
222
+ throw new boom_1.Boom('No image processing library available');
223
+ }
224
+ };
225
+ exports.extractImageThumb = extractImageThumb;
226
+ const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
227
+ exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
228
+ const generateProfilePicture = async (mediaUpload, dimensions) => {
229
+ let buffer;
230
+ const { width: w = 720, height: h = 720 } = dimensions || {};
231
+ if (Buffer.isBuffer(mediaUpload)) {
232
+ buffer = mediaUpload;
233
+ }
234
+ else {
235
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
236
+ const { stream } = await (0, exports.getStream)(mediaUpload);
237
+ // Convert the resulting stream to a buffer
238
+ buffer = await (0, exports.toBuffer)(stream);
239
+ }
240
+ const lib = await (0, exports.getImageProcessingLibrary)();
241
+ let img;
242
+ if ('sharp' in lib && lib.sharp?.default) {
243
+ img = lib.sharp
244
+ .default(buffer)
245
+ .resize(w, h)
246
+ .jpeg({
247
+ quality: 80
248
+ })
249
+ .toBuffer();
250
+ }
251
+ else if ('image' in lib && lib.image?.Transformer) {
252
+ img = new lib.image
253
+ .Transformer(buffer)
254
+ .resize(w, h, 0)
255
+ .jpeg(80);
256
+ }
257
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
258
+ const jimp = await lib.jimp.Jimp.read(buffer);
259
+ const min = Math.min(jimp.width, jimp.height);
260
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
261
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
262
+ }
263
+ else {
264
+ throw new boom_1.Boom('No image processing library available');
265
+ }
266
+ return {
267
+ img: await img
268
+ };
269
+ };
270
+ exports.generateProfilePicture = generateProfilePicture;
271
+ /** gets the SHA256 of the given media message */
272
+ const mediaMessageSHA256B64 = (message) => {
273
+ const media = Object.values(message)[0];
274
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
275
+ };
276
+ exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
277
+ async function getAudioDuration(buffer) {
278
+ const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
279
+ let metadata;
280
+ const options = {
281
+ duration: true
282
+ };
283
+ if (Buffer.isBuffer(buffer)) {
284
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
285
+ }
286
+ else if (typeof buffer === 'string') {
287
+ metadata = await musicMetadata.parseFile(buffer, options);
288
+ }
289
+ else {
290
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
291
+ }
292
+ return metadata.format.duration;
293
+ }
294
+ /**
295
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
296
+ */
297
+ async function getAudioWaveform(buffer, logger) {
298
+ try {
299
+ // @ts-ignore
300
+ const { default: decoder } = await Promise.resolve().then(() => __importStar(require('audio-decode')));
301
+ let audioData;
302
+ if (Buffer.isBuffer(buffer)) {
303
+ audioData = buffer;
304
+ }
305
+ else if (typeof buffer === 'string') {
306
+ const rStream = (0, fs_1.createReadStream)(buffer);
307
+ audioData = await (0, exports.toBuffer)(rStream);
308
+ }
309
+ else {
310
+ audioData = await (0, exports.toBuffer)(buffer);
311
+ }
312
+ const audioBuffer = await decoder(audioData);
313
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
314
+ const samples = 64; // Number of samples we want to have in our final data set
315
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
316
+ const filteredData = [];
317
+ for (let i = 0; i < samples; i++) {
318
+ const blockStart = blockSize * i; // the location of the first sample in the block
319
+ let sum = 0;
320
+ for (let j = 0; j < blockSize; j++) {
321
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
322
+ }
323
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
324
+ }
325
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
326
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
327
+ const normalizedData = filteredData.map(n => n * multiplier);
328
+ // Generate waveform like WhatsApp
329
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
330
+ return waveform;
331
+ }
332
+ catch (e) {
333
+ logger?.debug('Failed to generate waveform: ' + e);
334
+ }
335
+ }
336
+ const toReadable = (buffer) => {
337
+ const readable = new stream_1.Readable({ read: () => { } });
338
+ readable.push(buffer);
339
+ readable.push(null);
340
+ return readable;
341
+ };
342
+ exports.toReadable = toReadable;
343
+ const toBuffer = async (stream) => {
344
+ const chunks = [];
345
+ for await (const chunk of stream) {
346
+ chunks.push(chunk);
347
+ }
348
+ stream.destroy();
349
+ return Buffer.concat(chunks);
350
+ };
351
+ exports.toBuffer = toBuffer;
352
+ const getStream = async (item, opts) => {
353
+ if (Buffer.isBuffer(item)) {
354
+ return { stream: (0, exports.toReadable)(item), type: 'buffer' };
355
+ }
356
+ if ('stream' in item) {
357
+ return { stream: item.stream, type: 'readable' };
358
+ }
359
+ const urlStr = item.url.toString();
360
+ if (urlStr.startsWith('data:')) {
361
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
362
+ return { stream: (0, exports.toReadable)(buffer), type: 'buffer' };
363
+ }
364
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
365
+ return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
366
+ }
367
+ return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
368
+ };
369
+ exports.getStream = getStream;
370
+ /** generates a thumbnail for a given media, if required */
371
+ async function generateThumbnail(file, mediaType, options) {
372
+ let thumbnail;
373
+ let originalImageDimensions;
374
+ if (mediaType === 'image') {
375
+ const { buffer, original } = await (0, exports.extractImageThumb)(file);
376
+ thumbnail = buffer.toString('base64');
377
+ if (original.width && original.height) {
378
+ originalImageDimensions = {
379
+ width: original.width,
380
+ height: original.height
381
+ };
382
+ }
383
+ }
384
+ else if (mediaType === 'video') {
385
+ try {
386
+ const buff = await (0, exports.extractVideoThumb)(file, '00:00:00', { width: 32, height: 32 });
387
+ thumbnail = buff.toString('base64');
388
+ }
389
+ catch (err) {
390
+ options.logger?.debug('could not generate video thumb: ' + err);
391
+ }
392
+ }
393
+ return {
394
+ thumbnail,
395
+ originalImageDimensions
396
+ };
397
+ }
398
+ const getHttpStream = async (url, options = {}) => {
399
+ const response = await fetch(url.toString(), {
400
+ dispatcher: options.dispatcher,
401
+ method: 'GET',
402
+ headers: options.headers
403
+ });
404
+ if (!response.ok) {
405
+ throw new boom_1.Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
406
+ }
407
+ // @ts-ignore Node18+ Readable.fromWeb exists
408
+ return response.body instanceof stream_1.Readable ? response.body : stream_1.Readable.fromWeb(response.body);
409
+ };
410
+ exports.getHttpStream = getHttpStream;
411
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
412
+ const { stream, type } = await (0, exports.getStream)(media, opts);
413
+ logger?.debug('fetched media stream');
414
+ const mediaKey = Crypto.randomBytes(32);
415
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
416
+ const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)() + '-enc');
417
+ const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
418
+ let originalFileStream;
419
+ let originalFilePath;
420
+ if (saveOriginalFileIfRequired) {
421
+ originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)() + '-original');
422
+ originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
423
+ }
424
+ let fileLength = 0;
425
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
426
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
427
+ const sha256Plain = Crypto.createHash('sha256');
428
+ const sha256Enc = Crypto.createHash('sha256');
429
+ const onChunk = async (buff) => {
430
+ sha256Enc.update(buff);
431
+ hmac.update(buff);
432
+ // Handle backpressure: if write returns false, wait for drain
433
+ if (!encFileWriteStream.write(buff)) {
434
+ await (0, events_1.once)(encFileWriteStream, 'drain');
435
+ }
436
+ };
437
+ try {
438
+ for await (const data of stream) {
439
+ fileLength += data.length;
440
+ if (type === 'remote' &&
441
+ opts?.maxContentLength &&
442
+ fileLength + data.length > opts.maxContentLength) {
443
+ throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
444
+ data: { media, type }
445
+ });
446
+ }
447
+ if (originalFileStream) {
448
+ if (!originalFileStream.write(data)) {
449
+ await (0, events_1.once)(originalFileStream, 'drain');
450
+ }
451
+ }
452
+ sha256Plain.update(data);
453
+ await onChunk(aes.update(data));
454
+ }
455
+ await onChunk(aes.final());
456
+ const mac = hmac.digest().slice(0, 10);
457
+ sha256Enc.update(mac);
458
+ const fileSha256 = sha256Plain.digest();
459
+ const fileEncSha256 = sha256Enc.digest();
460
+ encFileWriteStream.write(mac);
461
+ const encFinishPromise = (0, events_1.once)(encFileWriteStream, 'finish');
462
+ const originalFinishPromise = originalFileStream ? (0, events_1.once)(originalFileStream, 'finish') : Promise.resolve();
463
+ encFileWriteStream.end();
464
+ originalFileStream?.end?.();
465
+ stream.destroy();
466
+ // Wait for write streams to fully flush to disk
467
+ // This helps reduce memory pressure by allowing OS to release buffers
468
+ await encFinishPromise;
469
+ await originalFinishPromise;
470
+ logger?.debug('encrypted data successfully');
471
+ return {
472
+ mediaKey,
473
+ originalFilePath,
474
+ encFilePath,
475
+ mac,
476
+ fileEncSha256,
477
+ fileSha256,
478
+ fileLength
479
+ };
480
+ }
481
+ catch (error) {
482
+ // destroy all streams with error
483
+ encFileWriteStream.destroy();
484
+ originalFileStream?.destroy?.();
485
+ aes.destroy();
486
+ hmac.destroy();
487
+ sha256Plain.destroy();
488
+ sha256Enc.destroy();
489
+ stream.destroy();
490
+ try {
491
+ await fs_1.promises.unlink(encFilePath);
492
+ if (originalFilePath) {
493
+ await fs_1.promises.unlink(originalFilePath);
494
+ }
495
+ }
496
+ catch (err) {
497
+ logger?.error({ err }, 'failed deleting tmp files');
498
+ }
499
+ throw error;
500
+ }
501
+ };
502
+ exports.encryptedStream = encryptedStream;
503
+ exports.DEF_MEDIA_HOST = 'mmg.whatsapp.net';
504
+ const AES_CHUNK_SIZE = 16;
505
+ const toSmallestChunkSize = (num) => {
506
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
507
+ };
508
+ const getUrlFromDirectPath = (directPath, host = exports.DEF_MEDIA_HOST) => `https://${host}${directPath}`;
509
+ exports.getUrlFromDirectPath = getUrlFromDirectPath;
510
+ const extractHost = (url) => {
511
+ if (!url)
512
+ return undefined;
513
+ try {
514
+ return new url_1.URL(url).host;
515
+ }
516
+ catch {
517
+ return undefined;
518
+ }
519
+ };
520
+ const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
521
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
522
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
523
+ const fallbackHost = opts.host ?? extractHost(url);
524
+ const downloadUrl = directPath ? (0, exports.getUrlFromDirectPath)(directPath, fallbackHost) : url;
525
+ if (!downloadUrl) {
526
+ throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
527
+ }
528
+ const keys = await getMediaKeys(mediaKey, type);
529
+ return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
530
+ };
531
+ exports.downloadContentFromMessage = downloadContentFromMessage;
532
+ /**
533
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
534
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
535
+ * */
536
+ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
537
+ let bytesFetched = 0;
538
+ let startChunk = 0;
539
+ let firstBlockIsIV = false;
540
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
541
+ if (startByte) {
542
+ const chunk = toSmallestChunkSize(startByte || 0);
543
+ if (chunk) {
544
+ startChunk = chunk - AES_CHUNK_SIZE;
545
+ bytesFetched = chunk;
546
+ firstBlockIsIV = true;
547
+ }
548
+ }
549
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
550
+ const headersInit = options?.headers ? options.headers : undefined;
551
+ const headers = {
552
+ ...(headersInit
553
+ ? Array.isArray(headersInit)
554
+ ? Object.fromEntries(headersInit)
555
+ : headersInit
556
+ : {}),
557
+ Origin: index_js_2.DEFAULT_ORIGIN
558
+ };
559
+ if (startChunk || endChunk) {
560
+ headers.Range = `bytes=${startChunk}-`;
561
+ if (endChunk) {
562
+ headers.Range += endChunk;
563
+ }
564
+ }
565
+ // download the message
566
+ const fetched = await (0, exports.getHttpStream)(downloadUrl, {
567
+ ...(options || {}),
568
+ headers
569
+ });
570
+ let remainingBytes = Buffer.from([]);
571
+ let aes;
572
+ const pushBytes = (bytes, push) => {
573
+ if (startByte || endByte) {
574
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
575
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
576
+ push(bytes.slice(start, end));
577
+ bytesFetched += bytes.length;
578
+ }
579
+ else {
580
+ push(bytes);
581
+ }
582
+ };
583
+ const output = new stream_1.Transform({
584
+ transform(chunk, _, callback) {
585
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
586
+ const decryptLength = toSmallestChunkSize(data.length);
587
+ remainingBytes = data.slice(decryptLength);
588
+ data = data.slice(0, decryptLength);
589
+ if (!aes) {
590
+ let ivValue = iv;
591
+ if (firstBlockIsIV) {
592
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
593
+ data = data.slice(AES_CHUNK_SIZE);
594
+ }
595
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
596
+ // if an end byte that is not EOF is specified
597
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
598
+ if (endByte) {
599
+ aes.setAutoPadding(false);
600
+ }
601
+ }
602
+ try {
603
+ pushBytes(aes.update(data), b => this.push(b));
604
+ callback();
605
+ }
606
+ catch (error) {
607
+ callback(error);
608
+ }
609
+ },
610
+ final(callback) {
611
+ try {
612
+ pushBytes(aes.final(), b => this.push(b));
613
+ callback();
614
+ }
615
+ catch (error) {
616
+ callback(error);
617
+ }
618
+ }
619
+ });
620
+ return fetched.pipe(output, { end: true });
621
+ };
622
+ exports.downloadEncryptedContent = downloadEncryptedContent;
623
+ function extensionForMediaMessage(message) {
624
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
625
+ const type = Object.keys(message)[0];
626
+ let extension;
627
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
628
+ extension = '.jpeg';
629
+ }
630
+ else {
631
+ const messageContent = message[type];
632
+ extension = getExtension(messageContent.mimetype);
633
+ }
634
+ return extension;
635
+ }
636
+ const isNodeRuntime = () => {
637
+ return (typeof process !== 'undefined' &&
638
+ process.versions?.node !== null &&
639
+ typeof process.versions.bun === 'undefined' &&
640
+ typeof globalThis.Deno === 'undefined');
641
+ };
642
+ const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
643
+ if (redirectCount > 5) {
644
+ throw new Error('Too many redirects');
645
+ }
646
+ const parsedUrl = new url_1.URL(url);
647
+ const httpModule = parsedUrl.protocol === 'https:' ? await Promise.resolve().then(() => __importStar(require('https'))) : await Promise.resolve().then(() => __importStar(require('http')));
648
+ // Get file size for Content-Length header (required for Node.js streaming)
649
+ const fileStats = await fs_1.promises.stat(filePath);
650
+ const fileSize = fileStats.size;
651
+ return new Promise((resolve, reject) => {
652
+ const req = httpModule.request({
653
+ hostname: parsedUrl.hostname,
654
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
655
+ path: parsedUrl.pathname + parsedUrl.search,
656
+ method: 'POST',
657
+ headers: {
658
+ ...headers,
659
+ 'Content-Length': fileSize
660
+ },
661
+ agent,
662
+ timeout: timeoutMs
663
+ }, res => {
664
+ // Handle redirects (3xx)
665
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
666
+ res.resume(); // Consume response to free resources
667
+ const newUrl = new url_1.URL(res.headers.location, url).toString();
668
+ resolve((0, exports.uploadWithNodeHttp)({
669
+ url: newUrl,
670
+ filePath,
671
+ headers,
672
+ timeoutMs,
673
+ agent
674
+ }, redirectCount + 1));
675
+ return;
676
+ }
677
+ let body = '';
678
+ res.on('data', chunk => (body += chunk));
679
+ res.on('end', () => {
680
+ try {
681
+ resolve(JSON.parse(body));
682
+ }
683
+ catch {
684
+ resolve(undefined);
685
+ }
686
+ });
687
+ });
688
+ req.on('error', reject);
689
+ req.on('timeout', () => {
690
+ req.destroy();
691
+ reject(new Error('Upload timeout'));
692
+ });
693
+ const stream = (0, fs_1.createReadStream)(filePath);
694
+ stream.pipe(req);
695
+ stream.on('error', err => {
696
+ req.destroy();
697
+ reject(err);
698
+ });
699
+ });
700
+ };
701
+ exports.uploadWithNodeHttp = uploadWithNodeHttp;
702
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
703
+ // Convert Node.js Readable to Web ReadableStream
704
+ const nodeStream = (0, fs_1.createReadStream)(filePath);
705
+ const webStream = stream_1.Readable.toWeb(nodeStream);
706
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
707
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
708
+ const response = await fetch(url, {
709
+ ...(dispatcher ? { dispatcher } : {}),
710
+ method: 'POST',
711
+ body: webStream,
712
+ headers,
713
+ duplex: 'half',
714
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
715
+ });
716
+ try {
717
+ return (await response.json());
718
+ }
719
+ catch {
720
+ return undefined;
721
+ }
722
+ };
723
+ /**
724
+ * Uploads media to WhatsApp servers.
725
+ *
726
+ * ## Why we have two upload implementations:
727
+ *
728
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
729
+ * the entire request body in memory before sending, even when using streams.
730
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
731
+ * See: https://github.com/nodejs/undici/issues/4058
732
+ *
733
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
734
+ * buffering, so we can use the web-standard Fetch API there.
735
+ *
736
+ * ## Future considerations:
737
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
738
+ * across all runtimes. Monitor the GitHub issue for updates.
739
+ */
740
+ const uploadMedia = async (params, logger) => {
741
+ if (isNodeRuntime()) {
742
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
743
+ return (0, exports.uploadWithNodeHttp)(params);
744
+ }
745
+ else {
746
+ logger?.debug('Using web-standard Fetch API for upload');
747
+ return uploadWithFetch(params);
748
+ }
749
+ };
750
+ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
751
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
752
+ // send a query JSON to obtain the url & auth token to upload our media
753
+ let uploadInfo = await refreshMediaConn(false);
754
+ let urls;
755
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
756
+ fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
757
+ // Prepare common headers
758
+ const customHeaders = (() => {
759
+ const hdrs = options?.headers;
760
+ if (!hdrs)
761
+ return {};
762
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
763
+ })();
764
+ const headers = {
765
+ ...customHeaders,
766
+ 'Content-Type': 'application/octet-stream',
767
+ Origin: index_js_2.DEFAULT_ORIGIN
768
+ };
769
+ for (const { hostname } of hosts) {
770
+ logger.debug(`uploading to "${hostname}"`);
771
+ const auth = encodeURIComponent(uploadInfo.auth);
772
+ // Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
773
+ const mediaPathMap = newsletter ? index_js_2.NEWSLETTER_MEDIA_PATH_MAP : index_js_2.MEDIA_PATH_MAP;
774
+ // Lia@Changes 20-03-26 --- Add server thumb for newsletter media
775
+ const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
776
+ const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
777
+ let result;
778
+ try {
779
+ result = await uploadMedia({
780
+ url,
781
+ filePath,
782
+ headers,
783
+ timeoutMs,
784
+ agent: fetchAgent
785
+ }, logger);
786
+ if (result?.url || result?.direct_path) {
787
+ urls = {
788
+ mediaUrl: result.url,
789
+ directPath: result.direct_path,
790
+ meta_hmac: result.meta_hmac,
791
+ fbid: result.fbid,
792
+ ts: result.ts,
793
+ thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
794
+ thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
795
+ };
796
+ break;
797
+ }
798
+ else {
799
+ uploadInfo = await refreshMediaConn(true);
800
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
801
+ }
802
+ }
803
+ catch (error) {
804
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
805
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
806
+ }
807
+ }
808
+ if (!urls) {
809
+ throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
810
+ }
811
+ return urls;
812
+ };
813
+ };
814
+ exports.getWAUploadToServer = getWAUploadToServer;
815
+ const getMediaRetryKey = (mediaKey) => {
816
+ return (0, crypto_js_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
817
+ };
818
+ /**
819
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
820
+ */
821
+ const encryptMediaRetryRequest = (key, mediaKey, meId) => {
822
+ const recp = { stanzaId: key.id };
823
+ const recpBuffer = index_js_1.proto.ServerErrorReceipt.encode(recp).finish();
824
+ const iv = Crypto.randomBytes(12);
825
+ const retryKey = getMediaRetryKey(mediaKey);
826
+ const ciphertext = (0, crypto_js_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
827
+ const req = {
828
+ tag: 'receipt',
829
+ attrs: {
830
+ id: key.id,
831
+ to: (0, index_js_3.jidNormalizedUser)(meId),
832
+ type: 'server-error'
833
+ },
834
+ content: [
835
+ // this encrypt node is actually pretty useless
836
+ // the media is returned even without this node
837
+ // keeping it here to maintain parity with WA Web
838
+ {
839
+ tag: 'encrypt',
840
+ attrs: {},
841
+ content: [
842
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
843
+ { tag: 'enc_iv', attrs: {}, content: iv }
844
+ ]
845
+ },
846
+ {
847
+ tag: 'rmr',
848
+ attrs: {
849
+ jid: key.remoteJid,
850
+ from_me: (!!key.fromMe).toString(),
851
+ // @ts-ignore
852
+ participant: key.participant || undefined
853
+ }
854
+ }
855
+ ]
856
+ };
857
+ return req;
858
+ };
859
+ exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
860
+ const decodeMediaRetryNode = (node) => {
861
+ const rmrNode = (0, index_js_3.getBinaryNodeChild)(node, 'rmr');
862
+ const event = {
863
+ key: {
864
+ id: node.attrs.id,
865
+ remoteJid: rmrNode.attrs.jid,
866
+ fromMe: rmrNode.attrs.from_me === 'true',
867
+ participant: rmrNode.attrs.participant
868
+ }
869
+ };
870
+ const errorNode = (0, index_js_3.getBinaryNodeChild)(node, 'error');
871
+ if (errorNode) {
872
+ const errorCode = +errorNode.attrs.code;
873
+ event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
874
+ data: errorNode.attrs,
875
+ statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
876
+ });
877
+ }
878
+ else {
879
+ const encryptedInfoNode = (0, index_js_3.getBinaryNodeChild)(node, 'encrypt');
880
+ const ciphertext = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
881
+ const iv = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
882
+ if (ciphertext && iv) {
883
+ event.media = { ciphertext, iv };
884
+ }
885
+ else {
886
+ event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
887
+ }
888
+ }
889
+ return event;
890
+ };
891
+ exports.decodeMediaRetryNode = decodeMediaRetryNode;
892
+ const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
893
+ const retryKey = getMediaRetryKey(mediaKey);
894
+ const plaintext = (0, crypto_js_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
895
+ return index_js_1.proto.MediaRetryNotification.decode(plaintext);
896
+ };
897
+ exports.decryptMediaRetryData = decryptMediaRetryData;
898
+ const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
899
+ exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
900
+ const MEDIA_RETRY_STATUS_MAP = {
901
+ [index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
902
+ [index_js_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
903
+ [index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
904
+ [index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
905
+ };
906
+ //# sourceMappingURL=messages-media.js.map