@awangxcode/qiro-baileys 7.0.0-rc25.5 → 7.0.0-rc26.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 (298) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +1443 -1033
  3. package/WAProto/WAProto.proto +4 -0
  4. package/WAProto/index.d.ts +4067 -243
  5. package/WAProto/index.js +74957 -43330
  6. package/assets/branding/qiro-logo.svg +24 -0
  7. package/assets/branding/qiro-mark.png +0 -0
  8. package/assets/branding/qiro-mark.svg +34 -0
  9. package/assets/branding/qiro-social-preview.png +0 -0
  10. package/lib/Defaults/index.d.ts +16 -1
  11. package/lib/Defaults/index.d.ts.map +1 -1
  12. package/lib/Defaults/index.js +43 -10
  13. package/lib/Defaults/index.js.map +1 -1
  14. package/lib/Extensions/advanced.d.ts +1 -1
  15. package/lib/Extensions/experimental.d.ts +1 -3
  16. package/lib/Extensions/experimental.d.ts.map +1 -1
  17. package/lib/Extensions/experimental.js +0 -2
  18. package/lib/Extensions/experimental.js.map +1 -1
  19. package/lib/MessageBuilder/index.d.ts +5 -5
  20. package/lib/MessageBuilder/index.d.ts.map +1 -1
  21. package/lib/MessageBuilder/index.js +12 -3
  22. package/lib/MessageBuilder/index.js.map +1 -1
  23. package/lib/Signal/Group/group-session-builder.d.ts +3 -3
  24. package/lib/Signal/Group/group-session-builder.js +4 -4
  25. package/lib/Signal/Group/group_cipher.d.ts +2 -2
  26. package/lib/Signal/Group/group_cipher.js +4 -4
  27. package/lib/Signal/Group/index.d.ts +11 -11
  28. package/lib/Signal/Group/index.js +11 -11
  29. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  30. package/lib/Signal/Group/sender-chain-key.js +1 -1
  31. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -1
  32. package/lib/Signal/Group/sender-key-distribution-message.js +1 -1
  33. package/lib/Signal/Group/sender-key-message.d.ts +1 -1
  34. package/lib/Signal/Group/sender-key-message.js +1 -1
  35. package/lib/Signal/Group/sender-key-record.d.ts +1 -1
  36. package/lib/Signal/Group/sender-key-record.js +2 -2
  37. package/lib/Signal/Group/sender-key-state.d.ts +2 -2
  38. package/lib/Signal/Group/sender-key-state.js +2 -2
  39. package/lib/Signal/libsignal.d.ts +3 -3
  40. package/lib/Signal/libsignal.js +6 -6
  41. package/lib/Signal/lid-mapping.d.ts +2 -2
  42. package/lib/Signal/lid-mapping.js +4 -4
  43. package/lib/Signal/lid-mapping.js.map +1 -1
  44. package/lib/Socket/Client/index.d.ts +2 -2
  45. package/lib/Socket/Client/index.js +2 -2
  46. package/lib/Socket/Client/types.d.ts +1 -1
  47. package/lib/Socket/Client/websocket.d.ts +1 -1
  48. package/lib/Socket/Client/websocket.js +2 -2
  49. package/lib/Socket/business.d.ts +347 -65
  50. package/lib/Socket/business.d.ts.map +1 -1
  51. package/lib/Socket/business.js +5 -5
  52. package/lib/Socket/chats.d.ts +129 -16
  53. package/lib/Socket/chats.d.ts.map +1 -1
  54. package/lib/Socket/chats.js +293 -18
  55. package/lib/Socket/chats.js.map +1 -1
  56. package/lib/Socket/communities.d.ts +332 -50
  57. package/lib/Socket/communities.d.ts.map +1 -1
  58. package/lib/Socket/communities.js +5 -5
  59. package/lib/Socket/groups.d.ts +133 -27
  60. package/lib/Socket/groups.d.ts.map +1 -1
  61. package/lib/Socket/groups.js +4 -4
  62. package/lib/Socket/index.d.ts +366 -84
  63. package/lib/Socket/index.d.ts.map +1 -1
  64. package/lib/Socket/index.js +8 -5
  65. package/lib/Socket/index.js.map +1 -1
  66. package/lib/Socket/messages-recv.d.ts +324 -41
  67. package/lib/Socket/messages-recv.d.ts.map +1 -1
  68. package/lib/Socket/messages-recv.js +81 -30
  69. package/lib/Socket/messages-recv.js.map +1 -1
  70. package/lib/Socket/messages-send.d.ts +340 -44
  71. package/lib/Socket/messages-send.d.ts.map +1 -1
  72. package/lib/Socket/messages-send.js +171 -35
  73. package/lib/Socket/messages-send.js.map +1 -1
  74. package/lib/Socket/mex.d.ts +1 -1
  75. package/lib/Socket/mex.js +1 -1
  76. package/lib/Socket/newsletter.d.ts +324 -39
  77. package/lib/Socket/newsletter.d.ts.map +1 -1
  78. package/lib/Socket/newsletter.js +345 -5
  79. package/lib/Socket/newsletter.js.map +1 -1
  80. package/lib/Socket/socket.d.ts +24 -11
  81. package/lib/Socket/socket.d.ts.map +1 -1
  82. package/lib/Socket/socket.js +89 -36
  83. package/lib/Socket/socket.js.map +1 -1
  84. package/lib/Store/index.d.ts +4 -0
  85. package/lib/Store/index.js +4 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +397 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  89. package/lib/Store/make-ordered-dictionary.js +79 -0
  90. package/lib/Store/object-repository.d.ts +11 -0
  91. package/lib/Store/object-repository.js +24 -0
  92. package/lib/Types/Auth.d.ts +2 -2
  93. package/lib/Types/Chat.d.ts +19 -6
  94. package/lib/Types/Chat.d.ts.map +1 -1
  95. package/lib/Types/Chat.js +7 -0
  96. package/lib/Types/Chat.js.map +1 -1
  97. package/lib/Types/Events.d.ts +9 -9
  98. package/lib/Types/GroupMetadata.d.ts +2 -2
  99. package/lib/Types/Message.d.ts +70 -6
  100. package/lib/Types/Message.d.ts.map +1 -1
  101. package/lib/Types/Message.js +11 -0
  102. package/lib/Types/Message.js.map +1 -1
  103. package/lib/Types/Mex.d.ts +68 -39
  104. package/lib/Types/Mex.d.ts.map +1 -1
  105. package/lib/Types/Mex.js +66 -0
  106. package/lib/Types/Mex.js.map +1 -1
  107. package/lib/Types/Product.d.ts +1 -1
  108. package/lib/Types/Signal.d.ts +1 -1
  109. package/lib/Types/Socket.d.ts +50 -5
  110. package/lib/Types/Socket.d.ts.map +1 -1
  111. package/lib/Types/Socket.js +1 -1
  112. package/lib/Types/State.d.ts +1 -1
  113. package/lib/Types/USync.d.ts +2 -2
  114. package/lib/Types/USync.js +1 -1
  115. package/lib/Types/index.d.ts +14 -14
  116. package/lib/Types/index.js +12 -12
  117. package/lib/Utils/audio-sticker.d.ts +14 -0
  118. package/lib/Utils/audio-sticker.js +172 -0
  119. package/lib/Utils/auth-store.d.ts +30 -0
  120. package/lib/Utils/auth-store.js +77 -0
  121. package/lib/Utils/auth-utils.d.ts +2 -2
  122. package/lib/Utils/auth-utils.js +4 -4
  123. package/lib/Utils/browser-utils.d.ts +1 -1
  124. package/lib/Utils/business.d.ts +2 -2
  125. package/lib/Utils/business.js +3 -3
  126. package/lib/Utils/chat-theme.d.ts +34 -0
  127. package/lib/Utils/chat-theme.js +336 -0
  128. package/lib/Utils/chat-utils.d.ts +3 -3
  129. package/lib/Utils/chat-utils.js +9 -9
  130. package/lib/Utils/chat-utils.js.map +1 -1
  131. package/lib/Utils/companion-reg-client-utils.d.ts +3 -3
  132. package/lib/Utils/companion-reg-client-utils.js +1 -1
  133. package/lib/Utils/crypto.d.ts +1 -1
  134. package/lib/Utils/crypto.js +1 -1
  135. package/lib/Utils/decode-wa-message.d.ts +18 -4
  136. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  137. package/lib/Utils/decode-wa-message.js +57 -2
  138. package/lib/Utils/decode-wa-message.js.map +1 -1
  139. package/lib/Utils/event-buffer.d.ts +4 -3
  140. package/lib/Utils/event-buffer.d.ts.map +1 -1
  141. package/lib/Utils/event-buffer.js +7 -8
  142. package/lib/Utils/event-buffer.js.map +1 -1
  143. package/lib/Utils/generics.d.ts +5 -4
  144. package/lib/Utils/generics.d.ts.map +1 -1
  145. package/lib/Utils/generics.js +13 -22
  146. package/lib/Utils/generics.js.map +1 -1
  147. package/lib/Utils/group-metadata-cache.d.ts +4 -0
  148. package/lib/Utils/group-metadata-cache.js +25 -0
  149. package/lib/Utils/history.d.ts +1 -1
  150. package/lib/Utils/history.js +6 -6
  151. package/lib/Utils/history.js.map +1 -1
  152. package/lib/Utils/html-app.d.ts +19 -0
  153. package/lib/Utils/html-app.js +96 -0
  154. package/lib/Utils/html-multiplayer.d.ts +10 -0
  155. package/lib/Utils/html-multiplayer.js +94 -0
  156. package/lib/Utils/identity-change-handler.d.ts +2 -2
  157. package/lib/Utils/identity-change-handler.js +2 -2
  158. package/lib/Utils/index.d.ts +46 -21
  159. package/lib/Utils/index.d.ts.map +1 -1
  160. package/lib/Utils/index.js +48 -21
  161. package/lib/Utils/index.js.map +1 -1
  162. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  163. package/lib/Utils/link-preview-metadata.js +88 -0
  164. package/lib/Utils/link-preview.d.ts +2 -2
  165. package/lib/Utils/link-preview.js +2 -2
  166. package/lib/Utils/message-retry-manager.d.ts +1 -1
  167. package/lib/Utils/messages-media.d.ts +35 -6
  168. package/lib/Utils/messages-media.d.ts.map +1 -1
  169. package/lib/Utils/messages-media.js +69 -22
  170. package/lib/Utils/messages-media.js.map +1 -1
  171. package/lib/Utils/messages.d.ts +45 -5
  172. package/lib/Utils/messages.d.ts.map +1 -1
  173. package/lib/Utils/messages.js +123 -32
  174. package/lib/Utils/messages.js.map +1 -1
  175. package/lib/Utils/modern-messages.d.ts +150 -0
  176. package/lib/Utils/modern-messages.js +496 -0
  177. package/lib/Utils/native-flow.d.ts +11 -0
  178. package/lib/Utils/native-flow.js +116 -0
  179. package/lib/Utils/newsletter-status.d.ts +158 -0
  180. package/lib/Utils/newsletter-status.js +651 -0
  181. package/lib/Utils/noise-handler.d.ts +3 -3
  182. package/lib/Utils/noise-handler.js +3 -3
  183. package/lib/Utils/offline-node-processor.d.ts +1 -1
  184. package/lib/Utils/optional-media.d.ts +3 -0
  185. package/lib/Utils/optional-media.js +46 -0
  186. package/lib/Utils/payment-messages.d.ts +38 -0
  187. package/lib/Utils/payment-messages.js +160 -0
  188. package/lib/Utils/pre-key-manager.d.ts +2 -2
  189. package/lib/Utils/process-message.d.ts +13 -2
  190. package/lib/Utils/process-message.d.ts.map +1 -1
  191. package/lib/Utils/process-message.js +87 -7
  192. package/lib/Utils/process-message.js.map +1 -1
  193. package/lib/Utils/reporting-utils.d.ts +2 -2
  194. package/lib/Utils/reporting-utils.js +1 -1
  195. package/lib/Utils/scheduled-message.d.ts +51 -0
  196. package/lib/Utils/scheduled-message.js +113 -0
  197. package/lib/Utils/sender-key-memory.d.ts +19 -0
  198. package/lib/Utils/sender-key-memory.js +51 -0
  199. package/lib/Utils/signal.d.ts +4 -4
  200. package/lib/Utils/signal.js +4 -4
  201. package/lib/Utils/stanza-ack.d.ts +1 -1
  202. package/lib/Utils/status-stickers.d.ts +127 -0
  203. package/lib/Utils/status-stickers.js +261 -0
  204. package/lib/Utils/sync-action-utils.d.ts +2 -2
  205. package/lib/Utils/sync-action-utils.js +1 -1
  206. package/lib/Utils/tc-token-utils.d.ts +2 -2
  207. package/lib/Utils/tc-token-utils.js +1 -1
  208. package/lib/Utils/ttl-cache.d.ts +29 -0
  209. package/lib/Utils/ttl-cache.js +121 -0
  210. package/lib/Utils/use-mongo-auth-state.d.ts +22 -0
  211. package/lib/Utils/use-mongo-auth-state.js +68 -0
  212. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  213. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -1
  214. package/lib/Utils/use-multi-file-auth-state.js +28 -15
  215. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  216. package/lib/Utils/use-mysql-auth-state.d.ts +20 -0
  217. package/lib/Utils/use-mysql-auth-state.js +80 -0
  218. package/lib/Utils/use-nekodb-auth.d.ts +19 -0
  219. package/lib/Utils/use-nekodb-auth.js +111 -0
  220. package/lib/Utils/use-postgres-auth-state.d.ts +20 -0
  221. package/lib/Utils/use-postgres-auth-state.js +80 -0
  222. package/lib/Utils/use-redis-auth-state.d.ts +20 -0
  223. package/lib/Utils/use-redis-auth-state.js +90 -0
  224. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  225. package/lib/Utils/use-single-file-auth-state.js +109 -0
  226. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  227. package/lib/Utils/use-sqlite-auth-state.js +121 -0
  228. package/lib/Utils/username.d.ts +12 -0
  229. package/lib/Utils/username.js +59 -0
  230. package/lib/Utils/validate-connection.d.ts +2 -2
  231. package/lib/Utils/validate-connection.js +5 -5
  232. package/lib/Utils/voice-recognition.d.ts +53 -0
  233. package/lib/Utils/voice-recognition.js +219 -0
  234. package/lib/VoIP/audio-feeder.d.ts +24 -0
  235. package/lib/VoIP/audio-feeder.js +276 -0
  236. package/lib/VoIP/index.d.ts +93 -0
  237. package/lib/VoIP/index.js +998 -0
  238. package/lib/VoIP/relay-transport.d.ts +5 -0
  239. package/lib/VoIP/relay-transport.js +824 -0
  240. package/lib/VoIP/signaling.d.ts +11 -0
  241. package/lib/VoIP/signaling.js +1099 -0
  242. package/lib/VoIP/types.d.ts +2 -0
  243. package/lib/VoIP/types.js +12 -0
  244. package/lib/VoIP/video-feeder.d.ts +24 -0
  245. package/lib/VoIP/video-feeder.js +276 -0
  246. package/lib/VoIP/wasm-engine.d.ts +26 -0
  247. package/lib/VoIP/wasm-engine.js +1318 -0
  248. package/lib/VoIP/worker-bootstrap.js +1022 -0
  249. package/lib/WABinary/decode.d.ts +1 -1
  250. package/lib/WABinary/decode.js +2 -2
  251. package/lib/WABinary/encode.d.ts +1 -1
  252. package/lib/WABinary/encode.js +2 -2
  253. package/lib/WABinary/generic-utils.d.ts +3 -1
  254. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  255. package/lib/WABinary/generic-utils.js +3 -1
  256. package/lib/WABinary/generic-utils.js.map +1 -1
  257. package/lib/WABinary/index.d.ts +5 -5
  258. package/lib/WABinary/index.js +5 -5
  259. package/lib/WABinary/jid-utils.d.ts +2 -0
  260. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  261. package/lib/WABinary/jid-utils.js +3 -1
  262. package/lib/WABinary/jid-utils.js.map +1 -1
  263. package/lib/WABinary/types.d.ts +1 -1
  264. package/lib/WABinary/types.js +1 -1
  265. package/lib/WAM/BinaryInfo.d.ts +1 -1
  266. package/lib/WAM/encode.d.ts +1 -1
  267. package/lib/WAM/encode.js +2 -2
  268. package/lib/WAM/index.d.ts +3 -3
  269. package/lib/WAM/index.js +3 -3
  270. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -3
  271. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  272. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  273. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +1 -1
  274. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  275. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  276. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  277. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +1 -1
  278. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +3 -3
  279. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +2 -2
  280. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -3
  281. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +2 -2
  282. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -3
  283. package/lib/WAUSync/Protocols/index.d.ts +5 -5
  284. package/lib/WAUSync/Protocols/index.js +5 -5
  285. package/lib/WAUSync/USyncQuery.d.ts +3 -3
  286. package/lib/WAUSync/USyncQuery.js +5 -5
  287. package/lib/WAUSync/index.d.ts +3 -3
  288. package/lib/WAUSync/index.js +3 -3
  289. package/lib/extensions/awang-MessageBuilder.js +1 -1
  290. package/lib/index.d.ts +14 -10
  291. package/lib/index.d.ts.map +1 -1
  292. package/lib/index.js +15 -11
  293. package/lib/index.js.map +1 -1
  294. package/package.json +78 -31
  295. package/MIGRASI-QIRO-BAILEYS-RC25.md +0 -102
  296. package/QIRO-BAILEYS-RC25.md +0 -168
  297. package/THIRD_PARTY_NOTICES.md +0 -49
  298. /package/{engine-requirements.js → config/engine-requirements.js} +0 -0
@@ -0,0 +1,219 @@
1
+ import { downloadContentFromMessage } from './messages-media.js';
2
+ import { normalizeMessageContent } from './messages.js';
3
+ import { areJidsSameUser, isJidGroup, jidNormalizedUser } from '../WABinary/index.js';
4
+
5
+ const DEFAULT_MAX_DURATION = 60;
6
+ const DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
7
+
8
+ const streamToBuffer = async (stream, maxBytes) => {
9
+ const chunks = [];
10
+ let total = 0;
11
+ for await (const chunk of stream) {
12
+ const buffer = Buffer.from(chunk);
13
+ total += buffer.length;
14
+ if (maxBytes && total > maxBytes) {
15
+ throw new Error('voice message exceeds maxBytes');
16
+ }
17
+ chunks.push(buffer);
18
+ }
19
+ return Buffer.concat(chunks);
20
+ };
21
+
22
+ export const normalizeVoiceText = value => String(value ?? '')
23
+ .normalize('NFKD')
24
+ .replace(/\p{M}/gu, '')
25
+ .toLowerCase()
26
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
27
+ .replace(/\s+/g, ' ')
28
+ .trim();
29
+
30
+ export const matchVoiceWakePhrase = (transcript, phrases = []) => {
31
+ const normalizedTranscript = normalizeVoiceText(transcript);
32
+ if (!normalizedTranscript) {
33
+ return null;
34
+ }
35
+ const candidates = [...new Map((Array.isArray(phrases) ? phrases : [phrases])
36
+ .map(phrase => ({ raw: String(phrase ?? '').trim(), normalized: normalizeVoiceText(phrase) }))
37
+ .filter(phrase => phrase.normalized)
38
+ .map(phrase => [phrase.normalized, phrase])).values()]
39
+ .sort((a, b) => b.normalized.length - a.normalized.length);
40
+ for (const phrase of candidates) {
41
+ const index = ` ${normalizedTranscript} `.indexOf(` ${phrase.normalized} `);
42
+ if (index >= 0) {
43
+ return {
44
+ phrase: phrase.raw,
45
+ normalizedPhrase: phrase.normalized,
46
+ normalizedTranscript
47
+ };
48
+ }
49
+ }
50
+ return null;
51
+ };
52
+
53
+ export const removeVoiceWakePhrase = (transcript, wakePhrase) => {
54
+ const normalizedTranscript = normalizeVoiceText(transcript);
55
+ const normalizedPhrase = normalizeVoiceText(wakePhrase);
56
+ if (!normalizedPhrase) {
57
+ return normalizedTranscript;
58
+ }
59
+ const words = normalizedTranscript.split(' ');
60
+ const phraseWords = normalizedPhrase.split(' ');
61
+ for (let index = 0; index <= words.length - phraseWords.length; index += 1) {
62
+ if (phraseWords.every((word, offset) => words[index + offset] === word)) {
63
+ words.splice(index, phraseWords.length);
64
+ break;
65
+ }
66
+ }
67
+ return words.join(' ').trim();
68
+ };
69
+
70
+ const getVoiceSenderJid = message => jidNormalizedUser(message?.key?.participantAlt ||
71
+ message?.key?.participant ||
72
+ message?.key?.remoteJidAlt ||
73
+ message?.key?.remoteJid);
74
+
75
+ const isQuotedToSelf = async ({ message, audioMessage, meId, meLid, getMessage }) => {
76
+ const contextInfo = audioMessage?.contextInfo;
77
+ if (!contextInfo?.quotedMessage && !contextInfo?.stanzaId) {
78
+ return false;
79
+ }
80
+ const quotedAuthor = contextInfo.participantAlt || contextInfo.participant;
81
+ if (quotedAuthor && (areJidsSameUser(quotedAuthor, meId) || areJidsSameUser(quotedAuthor, meLid))) {
82
+ return true;
83
+ }
84
+ if (!contextInfo.stanzaId || typeof getMessage !== 'function') {
85
+ return false;
86
+ }
87
+ const target = await getMessage({
88
+ remoteJid: message.key.remoteJid,
89
+ remoteJidAlt: message.key.remoteJidAlt,
90
+ participant: quotedAuthor,
91
+ id: contextInfo.stanzaId
92
+ });
93
+ return target?.key?.fromMe === true;
94
+ };
95
+
96
+ const normalizeTranscriptionResult = value => {
97
+ if (typeof value === 'string') {
98
+ return { text: value };
99
+ }
100
+ if (value && typeof value === 'object') {
101
+ return {
102
+ ...value,
103
+ text: String(value.text ?? value.transcript ?? '')
104
+ };
105
+ }
106
+ return { text: '' };
107
+ };
108
+
109
+ const getWakePhrases = async (voiceRecognition, context) => {
110
+ const staticPhrases = Array.isArray(voiceRecognition.wakePhrases)
111
+ ? voiceRecognition.wakePhrases
112
+ : voiceRecognition.wakePhrases
113
+ ? [voiceRecognition.wakePhrases]
114
+ : [];
115
+ const dynamicPhrases = typeof voiceRecognition.getWakePhrases === 'function'
116
+ ? await voiceRecognition.getWakePhrases(context)
117
+ : [];
118
+ return [...new Set([
119
+ ...staticPhrases,
120
+ ...(Array.isArray(dynamicPhrases) ? dynamicPhrases : dynamicPhrases ? [dynamicPhrases] : [])
121
+ ].map(value => String(value ?? '').trim()).filter(Boolean))];
122
+ };
123
+
124
+ export const bindVoiceRecognition = (sock, config = {}, dependencies = {}) => {
125
+ const voiceRecognition = config.voiceRecognition;
126
+ if (!voiceRecognition?.enabled || typeof voiceRecognition.transcribe !== 'function') {
127
+ return () => undefined;
128
+ }
129
+ const downloadContent = dependencies.downloadContentFromMessage || downloadContentFromMessage;
130
+ const getMessage = config.getMessage;
131
+ const logger = config.logger;
132
+ const handler = async ({ messages, type }) => {
133
+ if (type !== 'notify') {
134
+ return;
135
+ }
136
+ for (const message of messages || []) {
137
+ try {
138
+ if (
139
+ !message?.message ||
140
+ (message.key?.fromMe && !voiceRecognition.allowFromMe)
141
+ ) {
142
+ continue
143
+ }
144
+ const content = normalizeMessageContent(message.message);
145
+ const audioMessage = content?.audioMessage;
146
+ if (!audioMessage) {
147
+ continue;
148
+ }
149
+ if ((voiceRecognition.pttOnly ?? true) && !audioMessage.ptt) {
150
+ continue;
151
+ }
152
+ const maxDuration = Number.isFinite(voiceRecognition.maxDuration)
153
+ ? Math.max(0, Number(voiceRecognition.maxDuration))
154
+ : DEFAULT_MAX_DURATION;
155
+ if (maxDuration && Number(audioMessage.seconds || 0) > maxDuration) {
156
+ continue;
157
+ }
158
+ const chatJid = jidNormalizedUser(message.key.remoteJid);
159
+ const senderJid = getVoiceSenderJid(message);
160
+ const context = {
161
+ message,
162
+ audioMessage,
163
+ chatJid,
164
+ senderJid,
165
+ isGroup: isJidGroup(chatJid)
166
+ };
167
+ if (typeof voiceRecognition.shouldProcess === 'function' && !(await voiceRecognition.shouldProcess(context))) {
168
+ continue;
169
+ }
170
+ const maxBytes = Number.isFinite(voiceRecognition.maxBytes)
171
+ ? Math.max(0, Number(voiceRecognition.maxBytes))
172
+ : DEFAULT_MAX_BYTES;
173
+ const declaredBytes = Number(audioMessage.fileLength?.toString?.() || audioMessage.fileLength || 0);
174
+ if (maxBytes && declaredBytes > maxBytes) {
175
+ continue;
176
+ }
177
+ const stream = await downloadContent(audioMessage, 'audio', voiceRecognition.downloadOptions || {});
178
+ const buffer = await streamToBuffer(stream, maxBytes);
179
+ const transcription = normalizeTranscriptionResult(await voiceRecognition.transcribe({
180
+ ...context,
181
+ buffer,
182
+ mimetype: audioMessage.mimetype || 'audio/ogg; codecs=opus'
183
+ }));
184
+ const transcript = transcription.text.trim();
185
+ if (!transcript) {
186
+ continue;
187
+ }
188
+ const meId = sock.authState?.creds?.me?.id;
189
+ const meLid = sock.authState?.creds?.me?.lid;
190
+ const quoted = (voiceRecognition.allowQuotedActivation ?? true)
191
+ ? await isQuotedToSelf({ message, audioMessage, meId, meLid, getMessage })
192
+ : false;
193
+ const phrases = quoted ? [] : await getWakePhrases(voiceRecognition, context);
194
+ const wake = quoted ? null : matchVoiceWakePhrase(transcript, phrases);
195
+ const activation = quoted ? 'quoted' : wake ? 'wake-phrase' : null;
196
+ const commandText = wake
197
+ ? removeVoiceWakePhrase(transcript, wake.normalizedPhrase)
198
+ : normalizeVoiceText(transcript);
199
+ const event = {
200
+ ...context,
201
+ ...transcription,
202
+ transcript,
203
+ commandText,
204
+ activation,
205
+ wakePhrase: wake?.phrase || null
206
+ };
207
+ sock.ev.emit('voice.transcription', event);
208
+ if (activation) {
209
+ sock.ev.emit('voice.command', event);
210
+ }
211
+ }
212
+ catch (error) {
213
+ logger?.warn({ err: error, key: message?.key }, 'voice recognition failed');
214
+ }
215
+ }
216
+ };
217
+ sock.ev.on('messages.upsert', handler);
218
+ return () => sock.ev.off('messages.upsert', handler);
219
+ };
@@ -0,0 +1,24 @@
1
+ export declare class AudioFeeder {
2
+ constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string, hooks?: {
3
+ onTrackStart?: (track: string) => void;
4
+ onTrackEnd?: (track: string) => void;
5
+ onIdle?: () => void;
6
+ ffmpegPath?: string;
7
+ });
8
+ readonly queuedChunks: number;
9
+ droppedChunks: number;
10
+ underflowChunks: number;
11
+ rebuffers: number;
12
+ bytesProduced: number;
13
+ chunksEmitted: number;
14
+ readonly playlistLength: number;
15
+ readonly currentTrack: string | null;
16
+ readonly idle: boolean;
17
+ tracksPlayed: number;
18
+ enqueue(source: string | string[]): number;
19
+ clearPlaylist(): void;
20
+ skip(): boolean;
21
+ start(playlist?: string[]): void;
22
+ stop(): void;
23
+ }
24
+ export default AudioFeeder;
@@ -0,0 +1,276 @@
1
+ import { spawn } from 'node:child_process';
2
+ const PREBUFFER_CHUNKS = 12;
3
+ const REBUFFER_CHUNKS = 6;
4
+ const MAX_QUEUED_CHUNKS = 1024;
5
+ const RESUME_QUEUE_CHUNKS = 256;
6
+ const RESYNC_AFTER_MS = 250;
7
+ export class AudioFeeder {
8
+ constructor(sampleRate, channels, framesPerChunk, onChunk, source = 'silence', hooks = {}) {
9
+ this.sampleRate = sampleRate;
10
+ this.channels = channels;
11
+ this.framesPerChunk = framesPerChunk;
12
+ this.onChunk = onChunk;
13
+ this.source = source;
14
+ this.onTrackStart = hooks.onTrackStart ?? (() => {});
15
+ this.onTrackEnd = hooks.onTrackEnd ?? (() => {});
16
+ this.onIdle = hooks.onIdle ?? (() => {});
17
+ this.ffmpegPath = hooks.ffmpegPath || process.env.FFMPEG_PATH || 'ffmpeg';
18
+ this.droppedChunks = 0;
19
+ this.underflowChunks = 0;
20
+ this.bytesProduced = 0;
21
+ this.chunksEmitted = 0;
22
+ this.rebuffers = 0;
23
+ this.tracksPlayed = 0;
24
+ this._proc = null;
25
+ this._playlist = [];
26
+ this._current = null;
27
+ this._sourceEnded = false;
28
+ this._idle = false;
29
+ this._pendingParts = [];
30
+ this._pendingBytes = 0;
31
+ this._queue = [];
32
+ this._emitTimer = null;
33
+ this._startedAtMs = 0;
34
+ this._emitIndex = 0;
35
+ this._buffering = true;
36
+ this._running = false;
37
+ this._chunkSamples = this.framesPerChunk * this.channels;
38
+ this._chunkBytes = this._chunkSamples * Float32Array.BYTES_PER_ELEMENT;
39
+ this._chunkIntervalMs = (this.framesPerChunk / this.sampleRate) * 1000;
40
+ }
41
+ get queuedChunks() {
42
+ return this._queue.length;
43
+ }
44
+ get playlistLength() {
45
+ return this._playlist.length;
46
+ }
47
+ get currentTrack() {
48
+ return this._current;
49
+ }
50
+ get idle() {
51
+ return this._idle;
52
+ }
53
+ enqueue(source) {
54
+ const tracks = Array.isArray(source) ? source : [source];
55
+ for (const track of tracks) {
56
+ if (track) {
57
+ this._playlist.push(track);
58
+ }
59
+ }
60
+ if (this._running && !this._proc) {
61
+ this._advance();
62
+ }
63
+ return this._playlist.length;
64
+ }
65
+ clearPlaylist() {
66
+ this._playlist = [];
67
+ }
68
+ skip() {
69
+ if (!this._proc) {
70
+ return false;
71
+ }
72
+ this._stopSource();
73
+ this._advance();
74
+ return true;
75
+ }
76
+ start(playlist) {
77
+ if (this._running) {
78
+ return;
79
+ }
80
+ this._running = true;
81
+ this._idle = false;
82
+ this._buffering = true;
83
+ this._emitIndex = 0;
84
+ this._startedAtMs = 0;
85
+ const initial = playlist ?? (this.source ? [this.source] : []);
86
+ this._playlist = Array.isArray(initial) ? [...initial] : [initial];
87
+ this._advance();
88
+ this._schedule();
89
+ }
90
+ stop() {
91
+ this._running = false;
92
+ if (this._emitTimer) {
93
+ clearTimeout(this._emitTimer);
94
+ this._emitTimer = null;
95
+ }
96
+ this._stopSource();
97
+ this._playlist = [];
98
+ this._current = null;
99
+ this._pendingParts = [];
100
+ this._pendingBytes = 0;
101
+ this._queue = [];
102
+ this._buffering = true;
103
+ }
104
+ _stopSource() {
105
+ const proc = this._proc;
106
+ this._proc = null;
107
+ if (proc) {
108
+ proc.stdout?.removeAllListeners('data');
109
+ proc.removeAllListeners('exit');
110
+ try {
111
+ proc.kill?.('SIGTERM');
112
+ }
113
+ catch {}
114
+ }
115
+ }
116
+ _advance() {
117
+ const next = this._playlist.shift();
118
+ if (!next) {
119
+ this._current = null;
120
+ if (!this._idle) {
121
+ this._idle = true;
122
+ this.onIdle();
123
+ }
124
+ return;
125
+ }
126
+ this._idle = false;
127
+ this._current = next;
128
+ this._sourceEnded = false;
129
+ this._buffering = true;
130
+ this._spawn(next);
131
+ this.tracksPlayed += 1;
132
+ this.onTrackStart(next);
133
+ }
134
+ _spawn(source) {
135
+ const proc = spawn(this.ffmpegPath, [
136
+ '-hide_banner',
137
+ '-loglevel', 'error',
138
+ '-thread_queue_size', '512',
139
+ ...this._resolveInputArgs(source),
140
+ '-f', 'f32le',
141
+ '-ac', String(this.channels),
142
+ '-ar', String(this.sampleRate),
143
+ 'pipe:1'
144
+ ]);
145
+ this._proc = proc;
146
+ proc.stdout.on('data', chunk => this._absorb(chunk));
147
+ proc.stderr.on('data', chunk => {
148
+ process.stderr.write(`[AudioFeeder] ${chunk.toString().trim()}\n`);
149
+ });
150
+ proc.on('error', err => {
151
+ if (this._proc !== proc) {
152
+ return;
153
+ }
154
+ process.stderr.write(`[AudioFeeder] ffmpeg error: ${err?.message || err}\n`);
155
+ this._proc = null;
156
+ this._sourceEnded = true;
157
+ });
158
+ proc.on('exit', code => {
159
+ if (this._proc !== proc) {
160
+ return;
161
+ }
162
+ if (code !== 0 && code !== null) {
163
+ process.stderr.write(`[AudioFeeder] ffmpeg exited with code=${code}\n`);
164
+ }
165
+ this._proc = null;
166
+ this._sourceEnded = true;
167
+ });
168
+ }
169
+ _resolveInputArgs(source = this.source) {
170
+ if (!source || source === 'silence') {
171
+ return ['-re', '-f', 'lavfi', '-i', `aevalsrc=0:d=3600:s=${this.sampleRate}`];
172
+ }
173
+ if (source.startsWith('lavfi:')) {
174
+ return ['-re', '-f', 'lavfi', '-i', source.slice('lavfi:'.length)];
175
+ }
176
+ return ['-re', '-i', source];
177
+ }
178
+ _absorb(chunk) {
179
+ this._pendingParts.push(chunk);
180
+ this._pendingBytes += chunk.length;
181
+ while (this._pendingBytes >= this._chunkBytes) {
182
+ if (this._queue.length >= MAX_QUEUED_CHUNKS) {
183
+ this._proc?.stdout.pause();
184
+ return;
185
+ }
186
+ this._queue.push(this._takeChunk());
187
+ }
188
+ }
189
+ _takeChunk() {
190
+ const frame = this._pendingParts.length === 1 && this._pendingParts[0].length === this._chunkBytes
191
+ ? this._pendingParts.shift()
192
+ : this._takeFromParts();
193
+ this._pendingBytes -= this._chunkBytes;
194
+ this.bytesProduced += this._chunkBytes;
195
+ const out = new Float32Array(this._chunkSamples);
196
+ out.set(new Float32Array(frame.buffer, frame.byteOffset, this._chunkSamples));
197
+ return out;
198
+ }
199
+ _takeFromParts() {
200
+ const frame = Buffer.allocUnsafe(this._chunkBytes);
201
+ let filled = 0;
202
+ while (filled < this._chunkBytes) {
203
+ const part = this._pendingParts[0];
204
+ const take = Math.min(part.length, this._chunkBytes - filled);
205
+ part.copy(frame, filled, 0, take);
206
+ filled += take;
207
+ if (take === part.length) {
208
+ this._pendingParts.shift();
209
+ }
210
+ else {
211
+ this._pendingParts[0] = part.subarray(take);
212
+ }
213
+ }
214
+ return frame;
215
+ }
216
+ _schedule() {
217
+ if (!this._running) {
218
+ return;
219
+ }
220
+ if (this._startedAtMs === 0) {
221
+ this._startedAtMs = Date.now();
222
+ }
223
+ const target = this._startedAtMs + this._emitIndex * this._chunkIntervalMs;
224
+ const now = Date.now();
225
+ if (now - target > RESYNC_AFTER_MS) {
226
+ this._startedAtMs = now - this._emitIndex * this._chunkIntervalMs;
227
+ }
228
+ this._emitTimer = setTimeout(() => {
229
+ this._emitTimer = null;
230
+ this._tick();
231
+ }, Math.max(0, target - now));
232
+ }
233
+ _tick() {
234
+ if (!this._running && !this._proc) {
235
+ return;
236
+ }
237
+ if (this._sourceEnded && !this._queue.length && !this._pendingBytes) {
238
+ this._sourceEnded = false;
239
+ const finished = this._current;
240
+ this._current = null;
241
+ this.onTrackEnd(finished);
242
+ this._advance();
243
+ }
244
+ if (this._buffering) {
245
+ if (this._queue.length < PREBUFFER_CHUNKS && this._proc) {
246
+ this._startedAtMs = 0;
247
+ this._emitIndex = 0;
248
+ this._schedule();
249
+ return;
250
+ }
251
+ this._buffering = false;
252
+ }
253
+ const chunk = this._queue.shift();
254
+ if (chunk) {
255
+ this.onChunk(chunk);
256
+ }
257
+ else {
258
+ this.underflowChunks += 1;
259
+ this.onChunk(new Float32Array(this._chunkSamples));
260
+ if (this._proc) {
261
+ this.rebuffers += 1;
262
+ this._buffering = true;
263
+ }
264
+ }
265
+ this.chunksEmitted += 1;
266
+ this._emitIndex += 1;
267
+ if (this._buffering && this._queue.length >= REBUFFER_CHUNKS) {
268
+ this._buffering = false;
269
+ }
270
+ if (this._proc?.stdout.isPaused() && this._queue.length <= RESUME_QUEUE_CHUNKS) {
271
+ this._proc.stdout.resume();
272
+ }
273
+ this._schedule();
274
+ }
275
+ }
276
+ export default AudioFeeder;
@@ -0,0 +1,93 @@
1
+ import { EventEmitter } from 'node:events';
2
+ export declare const CallState: Readonly<{
3
+ Idle: 0;
4
+ Calling: 1;
5
+ PreacceptReceived: 2;
6
+ ReceivedCall: 3;
7
+ AcceptSent: 4;
8
+ AcceptReceived: 5;
9
+ Active: 6;
10
+ ActiveElsewhere: 7;
11
+ Ending: 13;
12
+ }>;
13
+ export declare class ActiveCall extends EventEmitter {
14
+ readonly callId: string;
15
+ readonly state: number;
16
+ groupJid?: string;
17
+ end(): void;
18
+ mute(muted: boolean): void;
19
+ waitForEnd(): Promise<string>;
20
+ play(source: string): boolean;
21
+ playVideo(source: string): boolean;
22
+ enqueueVideo(source: string | string[]): number;
23
+ skipVideo(): boolean;
24
+ queuedVideo(): number;
25
+ nowPlayingVideo(): string | null;
26
+ isVideo(): boolean;
27
+ startScreenShare(): unknown;
28
+ stopScreenShare(): unknown;
29
+ isScreenShare(): boolean;
30
+ enqueue(source: string | string[]): number;
31
+ skip(): boolean;
32
+ queued(): number;
33
+ nowPlaying(): string | null;
34
+ }
35
+ export interface VoipClientOptions {
36
+ socket?: any;
37
+ sock?: any;
38
+ conn?: any;
39
+ logger?: (...args: any[]) => void;
40
+ debug?: boolean;
41
+ wasmPath?: string;
42
+ wasmBinary?: Uint8Array | Buffer;
43
+ resourcesPath?: string;
44
+ storageDir?: string;
45
+ ffmpegPath?: string;
46
+ loaderCode?: string;
47
+ workerModulesCode?: string;
48
+ loaderModuleName?: string;
49
+ enableLogs?: boolean;
50
+ options?: Record<string, unknown>;
51
+ }
52
+ export interface VoipCallOptions {
53
+ durationMs?: number;
54
+ audioSource?: string;
55
+ playlist?: string[];
56
+ endWhenQueueEmpty?: boolean;
57
+ idleGraceMs?: number;
58
+ audioStartDelayMs?: number;
59
+ video?: boolean;
60
+ isVideo?: boolean;
61
+ videoSource?: string;
62
+ videoPlaylist?: string[];
63
+ screenShare?: boolean;
64
+ }
65
+ export interface VoipGroupCallOptions extends VoipCallOptions {
66
+ participants?: string[];
67
+ metadata?: any;
68
+ }
69
+ export interface VoipCallInvite {
70
+ callId: string;
71
+ callCreatorJid: string;
72
+ groupJid?: string;
73
+ initialPeerJid?: string;
74
+ pnUserJids?: string[];
75
+ lidUserJids?: string[];
76
+ deviceJidsCsv?: string[];
77
+ chatName?: string;
78
+ }
79
+ export declare class VoipClient {
80
+ constructor(options?: VoipClientOptions);
81
+ connect(): Promise<void>;
82
+ attach(socket: any): Promise<void>;
83
+ call(phoneNumber: string, options?: VoipCallOptions): Promise<ActiveCall>;
84
+ callGroup(groupJid: string, options?: VoipGroupCallOptions): Promise<ActiveCall>;
85
+ joinGroupCall(invite: VoipCallInvite, options?: VoipCallOptions): Promise<ActiveCall>;
86
+ acceptCall(isMicEnabled?: boolean): void;
87
+ disconnect(): void;
88
+ resetCallState(): void;
89
+ }
90
+ export { VideoFeeder, VIDEO_FORMAT_I420 } from './video-feeder.js';
91
+ export { AudioFeeder } from './audio-feeder.js';
92
+ export declare function makeVoipClient(socket: any, options?: VoipClientOptions): Promise<VoipClient>;
93
+ export default VoipClient;