amiudmodz 6.3.0 → 6.3.1

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 (296) hide show
  1. package/lib/Foundation/ai-rich.d.ts +123 -0
  2. package/lib/Foundation/ai-rich.d.ts.map +1 -0
  3. package/lib/Foundation/ai-rich.js +542 -0
  4. package/lib/Foundation/ai-rich.js.map +1 -0
  5. package/lib/Foundation/audio-duration.d.ts +3 -0
  6. package/lib/Foundation/audio-duration.d.ts.map +1 -0
  7. package/lib/Foundation/audio-duration.js +514 -0
  8. package/lib/Foundation/audio-duration.js.map +1 -0
  9. package/lib/Foundation/audio-samples.d.ts +3 -0
  10. package/lib/Foundation/audio-samples.d.ts.map +1 -0
  11. package/lib/Foundation/audio-samples.js +294 -0
  12. package/lib/Foundation/audio-samples.js.map +1 -0
  13. package/lib/Foundation/boom.d.ts +17 -0
  14. package/lib/Foundation/boom.d.ts.map +1 -0
  15. package/lib/Foundation/boom.js +37 -0
  16. package/lib/Foundation/boom.js.map +1 -0
  17. package/lib/Foundation/cache.d.ts +25 -0
  18. package/lib/Foundation/cache.d.ts.map +1 -0
  19. package/lib/Foundation/cache.js +112 -0
  20. package/lib/Foundation/cache.js.map +1 -0
  21. package/lib/Foundation/concurrency.d.ts +13 -0
  22. package/lib/Foundation/concurrency.d.ts.map +1 -0
  23. package/lib/Foundation/concurrency.js +62 -0
  24. package/lib/Foundation/concurrency.js.map +1 -0
  25. package/lib/Foundation/curve25519.d.ts +11 -0
  26. package/lib/Foundation/curve25519.d.ts.map +1 -0
  27. package/lib/Foundation/curve25519.js +178 -0
  28. package/lib/Foundation/curve25519.js.map +1 -0
  29. package/lib/Foundation/image-thumb.d.ts +13 -0
  30. package/lib/Foundation/image-thumb.d.ts.map +1 -0
  31. package/lib/Foundation/image-thumb.js +65 -0
  32. package/lib/Foundation/image-thumb.js.map +1 -0
  33. package/lib/Foundation/link-preview.d.ts +29 -0
  34. package/lib/Foundation/link-preview.d.ts.map +1 -0
  35. package/lib/Foundation/link-preview.js +309 -0
  36. package/lib/Foundation/link-preview.js.map +1 -0
  37. package/lib/Foundation/logger.d.ts +31 -0
  38. package/lib/Foundation/logger.d.ts.map +1 -0
  39. package/lib/Foundation/logger.js +54 -0
  40. package/lib/Foundation/logger.js.map +1 -0
  41. package/lib/Foundation/long.d.ts +33 -0
  42. package/lib/Foundation/long.d.ts.map +1 -0
  43. package/lib/Foundation/long.js +135 -0
  44. package/lib/Foundation/long.js.map +1 -0
  45. package/lib/Foundation/protobuf-minimal.d.ts +115 -0
  46. package/lib/Foundation/protobuf-minimal.d.ts.map +1 -0
  47. package/lib/Foundation/protobuf-minimal.js +614 -0
  48. package/lib/Foundation/protobuf-minimal.js.map +1 -0
  49. package/lib/Foundation/qrcode-terminal.d.ts +2 -0
  50. package/lib/Foundation/qrcode-terminal.d.ts.map +1 -0
  51. package/lib/Foundation/qrcode-terminal.js +405 -0
  52. package/lib/Foundation/qrcode-terminal.js.map +1 -0
  53. package/lib/Foundation/sql-database.d.ts +15 -0
  54. package/lib/Foundation/sql-database.d.ts.map +1 -0
  55. package/lib/Foundation/sql-database.js +719 -0
  56. package/lib/Foundation/sql-database.js.map +1 -0
  57. package/lib/Foundation/wa-crypto.d.ts +14 -0
  58. package/lib/Foundation/wa-crypto.d.ts.map +1 -0
  59. package/lib/Foundation/wa-crypto.js +48 -0
  60. package/lib/Foundation/wa-crypto.js.map +1 -0
  61. package/lib/Foundation/zip.d.ts +2 -0
  62. package/lib/Foundation/zip.d.ts.map +1 -0
  63. package/lib/Foundation/zip.js +98 -0
  64. package/lib/Foundation/zip.js.map +1 -0
  65. package/lib/Signal/libsignal.js +0 -3
  66. package/lib/Signal/libsignal.js.map +1 -1
  67. package/lib/Socket/business.d.ts +3 -1
  68. package/lib/Socket/business.d.ts.map +1 -1
  69. package/lib/Socket/communities.d.ts +3 -1
  70. package/lib/Socket/communities.d.ts.map +1 -1
  71. package/lib/Socket/index.d.ts.map +1 -1
  72. package/lib/Socket/index.js +19 -14
  73. package/lib/Socket/index.js.map +1 -1
  74. package/lib/Socket/messages-recv.d.ts +3 -1
  75. package/lib/Socket/messages-recv.d.ts.map +1 -1
  76. package/lib/Socket/messages-recv.js +6 -2
  77. package/lib/Socket/messages-recv.js.map +1 -1
  78. package/lib/Socket/messages-send.d.ts +3 -1
  79. package/lib/Socket/messages-send.d.ts.map +1 -1
  80. package/lib/Socket/messages-send.js +298 -52
  81. package/lib/Socket/messages-send.js.map +1 -1
  82. package/lib/Utils/messages-media.d.ts.map +1 -1
  83. package/lib/Utils/messages-media.js +89 -26
  84. package/lib/Utils/messages-media.js.map +1 -1
  85. package/lib/Utils/messages.d.ts +6 -0
  86. package/lib/Utils/messages.d.ts.map +1 -1
  87. package/lib/Utils/messages.js +198 -27
  88. package/lib/Utils/messages.js.map +1 -1
  89. package/lib/VoIP/WaVoipCoordinator.d.ts +39 -0
  90. package/lib/VoIP/WaVoipCoordinator.d.ts.map +1 -0
  91. package/lib/VoIP/WaVoipCoordinator.js +156 -0
  92. package/lib/VoIP/WaVoipCoordinator.js.map +1 -0
  93. package/lib/VoIP/app-data/WaAppDataStream.d.ts +35 -0
  94. package/lib/VoIP/app-data/WaAppDataStream.d.ts.map +1 -0
  95. package/lib/VoIP/app-data/WaAppDataStream.js +174 -0
  96. package/lib/VoIP/app-data/WaAppDataStream.js.map +1 -0
  97. package/lib/VoIP/app-data/protocol.d.ts +28 -0
  98. package/lib/VoIP/app-data/protocol.d.ts.map +1 -0
  99. package/lib/VoIP/app-data/protocol.js +167 -0
  100. package/lib/VoIP/app-data/protocol.js.map +1 -0
  101. package/lib/VoIP/bytes.d.ts +19 -0
  102. package/lib/VoIP/bytes.d.ts.map +1 -0
  103. package/lib/VoIP/bytes.js +64 -0
  104. package/lib/VoIP/bytes.js.map +1 -0
  105. package/lib/VoIP/call/WaCallManager.d.ts +58 -0
  106. package/lib/VoIP/call/WaCallManager.d.ts.map +1 -0
  107. package/lib/VoIP/call/WaCallManager.js +434 -0
  108. package/lib/VoIP/call/WaCallManager.js.map +1 -0
  109. package/lib/VoIP/call/WaCallMediaSession.d.ts +143 -0
  110. package/lib/VoIP/call/WaCallMediaSession.d.ts.map +1 -0
  111. package/lib/VoIP/call/WaCallMediaSession.js +1674 -0
  112. package/lib/VoIP/call/WaCallMediaSession.js.map +1 -0
  113. package/lib/VoIP/call/call-state.d.ts +34 -0
  114. package/lib/VoIP/call/call-state.d.ts.map +1 -0
  115. package/lib/VoIP/call/call-state.js +189 -0
  116. package/lib/VoIP/call/call-state.js.map +1 -0
  117. package/lib/VoIP/crypto/encryption.d.ts +6 -0
  118. package/lib/VoIP/crypto/encryption.d.ts.map +1 -0
  119. package/lib/VoIP/crypto/encryption.js +14 -0
  120. package/lib/VoIP/crypto/encryption.js.map +1 -0
  121. package/lib/VoIP/crypto/primitives.d.ts +5 -0
  122. package/lib/VoIP/crypto/primitives.d.ts.map +1 -0
  123. package/lib/VoIP/crypto/primitives.js +22 -0
  124. package/lib/VoIP/crypto/primitives.js.map +1 -0
  125. package/lib/VoIP/crypto/rtcp.d.ts +6 -0
  126. package/lib/VoIP/crypto/rtcp.d.ts.map +1 -0
  127. package/lib/VoIP/crypto/rtcp.js +71 -0
  128. package/lib/VoIP/crypto/rtcp.js.map +1 -0
  129. package/lib/VoIP/crypto/srtp.d.ts +40 -0
  130. package/lib/VoIP/crypto/srtp.d.ts.map +1 -0
  131. package/lib/VoIP/crypto/srtp.js +174 -0
  132. package/lib/VoIP/crypto/srtp.js.map +1 -0
  133. package/lib/VoIP/crypto/ssrc.d.ts +4 -0
  134. package/lib/VoIP/crypto/ssrc.d.ts.map +1 -0
  135. package/lib/VoIP/crypto/ssrc.js +15 -0
  136. package/lib/VoIP/crypto/ssrc.js.map +1 -0
  137. package/lib/VoIP/index.d.ts +82 -104
  138. package/lib/VoIP/index.d.ts.map +1 -1
  139. package/lib/VoIP/index.js +596 -906
  140. package/lib/VoIP/index.js.map +1 -1
  141. package/lib/VoIP/media/WaAudioEngine.d.ts +79 -0
  142. package/lib/VoIP/media/WaAudioEngine.d.ts.map +1 -0
  143. package/lib/VoIP/media/WaAudioEngine.js +478 -0
  144. package/lib/VoIP/media/WaAudioEngine.js.map +1 -0
  145. package/lib/VoIP/media/WaVideoEngine.d.ts +31 -0
  146. package/lib/VoIP/media/WaVideoEngine.d.ts.map +1 -0
  147. package/lib/VoIP/media/WaVideoEngine.js +261 -0
  148. package/lib/VoIP/media/WaVideoEngine.js.map +1 -0
  149. package/lib/VoIP/media/audio-codec.d.ts +74 -0
  150. package/lib/VoIP/media/audio-codec.d.ts.map +1 -0
  151. package/lib/VoIP/media/audio-codec.js +0 -0
  152. package/lib/VoIP/media/audio-codec.js.map +1 -0
  153. package/lib/VoIP/media/audio-reorder.d.ts +19 -0
  154. package/lib/VoIP/media/audio-reorder.d.ts.map +1 -0
  155. package/lib/VoIP/media/audio-reorder.js +112 -0
  156. package/lib/VoIP/media/audio-reorder.js.map +1 -0
  157. package/lib/VoIP/media/h264.d.ts +21 -0
  158. package/lib/VoIP/media/h264.d.ts.map +1 -0
  159. package/lib/VoIP/media/h264.js +239 -0
  160. package/lib/VoIP/media/h264.js.map +1 -0
  161. package/lib/VoIP/media/mlow-codec.d.ts +77 -0
  162. package/lib/VoIP/media/mlow-codec.d.ts.map +1 -0
  163. package/lib/VoIP/media/mlow-codec.js +467 -0
  164. package/lib/VoIP/media/mlow-codec.js.map +1 -0
  165. package/lib/VoIP/media/rtcp.d.ts +10 -0
  166. package/lib/VoIP/media/rtcp.d.ts.map +1 -0
  167. package/lib/VoIP/media/rtcp.js +61 -0
  168. package/lib/VoIP/media/rtcp.js.map +1 -0
  169. package/lib/VoIP/media/rtp.d.ts +56 -0
  170. package/lib/VoIP/media/rtp.d.ts.map +1 -0
  171. package/lib/VoIP/media/rtp.js +225 -0
  172. package/lib/VoIP/media/rtp.js.map +1 -0
  173. package/lib/VoIP/protobuf.d.ts +3 -0
  174. package/lib/VoIP/protobuf.d.ts.map +1 -0
  175. package/lib/VoIP/protobuf.js +30 -0
  176. package/lib/VoIP/protobuf.js.map +1 -0
  177. package/lib/VoIP/relay/WaManualRelay.d.ts +62 -0
  178. package/lib/VoIP/relay/WaManualRelay.d.ts.map +1 -0
  179. package/lib/VoIP/relay/WaManualRelay.js +619 -0
  180. package/lib/VoIP/relay/WaManualRelay.js.map +1 -0
  181. package/lib/VoIP/relay/datachannel/pre-negotiated.d.ts +22 -0
  182. package/lib/VoIP/relay/datachannel/pre-negotiated.d.ts.map +1 -0
  183. package/lib/VoIP/relay/datachannel/pre-negotiated.js +34 -0
  184. package/lib/VoIP/relay/datachannel/pre-negotiated.js.map +1 -0
  185. package/lib/VoIP/relay/dtls/aead.d.ts +23 -0
  186. package/lib/VoIP/relay/dtls/aead.d.ts.map +1 -0
  187. package/lib/VoIP/relay/dtls/aead.js +41 -0
  188. package/lib/VoIP/relay/dtls/aead.js.map +1 -0
  189. package/lib/VoIP/relay/dtls/cert-builder.d.ts +6 -0
  190. package/lib/VoIP/relay/dtls/cert-builder.d.ts.map +1 -0
  191. package/lib/VoIP/relay/dtls/cert-builder.js +68 -0
  192. package/lib/VoIP/relay/dtls/cert-builder.js.map +1 -0
  193. package/lib/VoIP/relay/dtls/der.d.ts +19 -0
  194. package/lib/VoIP/relay/dtls/der.d.ts.map +1 -0
  195. package/lib/VoIP/relay/dtls/der.js +96 -0
  196. package/lib/VoIP/relay/dtls/der.js.map +1 -0
  197. package/lib/VoIP/relay/dtls/ecdhe.d.ts +9 -0
  198. package/lib/VoIP/relay/dtls/ecdhe.d.ts.map +1 -0
  199. package/lib/VoIP/relay/dtls/ecdhe.js +33 -0
  200. package/lib/VoIP/relay/dtls/ecdhe.js.map +1 -0
  201. package/lib/VoIP/relay/dtls/handshake-framing.d.ts +49 -0
  202. package/lib/VoIP/relay/dtls/handshake-framing.d.ts.map +1 -0
  203. package/lib/VoIP/relay/dtls/handshake-framing.js +102 -0
  204. package/lib/VoIP/relay/dtls/handshake-framing.js.map +1 -0
  205. package/lib/VoIP/relay/dtls/handshake-messages.d.ts +64 -0
  206. package/lib/VoIP/relay/dtls/handshake-messages.d.ts.map +1 -0
  207. package/lib/VoIP/relay/dtls/handshake-messages.js +154 -0
  208. package/lib/VoIP/relay/dtls/handshake-messages.js.map +1 -0
  209. package/lib/VoIP/relay/dtls/handshake.d.ts +28 -0
  210. package/lib/VoIP/relay/dtls/handshake.d.ts.map +1 -0
  211. package/lib/VoIP/relay/dtls/handshake.js +555 -0
  212. package/lib/VoIP/relay/dtls/handshake.js.map +1 -0
  213. package/lib/VoIP/relay/dtls/prf.d.ts +13 -0
  214. package/lib/VoIP/relay/dtls/prf.d.ts.map +1 -0
  215. package/lib/VoIP/relay/dtls/prf.js +35 -0
  216. package/lib/VoIP/relay/dtls/prf.js.map +1 -0
  217. package/lib/VoIP/relay/dtls/record.d.ts +25 -0
  218. package/lib/VoIP/relay/dtls/record.d.ts.map +1 -0
  219. package/lib/VoIP/relay/dtls/record.js +49 -0
  220. package/lib/VoIP/relay/dtls/record.js.map +1 -0
  221. package/lib/VoIP/relay/relay-ack.d.ts +31 -0
  222. package/lib/VoIP/relay/relay-ack.d.ts.map +1 -0
  223. package/lib/VoIP/relay/relay-ack.js +142 -0
  224. package/lib/VoIP/relay/relay-ack.js.map +1 -0
  225. package/lib/VoIP/relay/sctp/association.d.ts +22 -0
  226. package/lib/VoIP/relay/sctp/association.d.ts.map +1 -0
  227. package/lib/VoIP/relay/sctp/association.js +434 -0
  228. package/lib/VoIP/relay/sctp/association.js.map +1 -0
  229. package/lib/VoIP/relay/sctp/crc32c.d.ts +2 -0
  230. package/lib/VoIP/relay/sctp/crc32c.d.ts.map +1 -0
  231. package/lib/VoIP/relay/sctp/crc32c.js +20 -0
  232. package/lib/VoIP/relay/sctp/crc32c.js.map +1 -0
  233. package/lib/VoIP/relay/sctp/wire.d.ts +96 -0
  234. package/lib/VoIP/relay/sctp/wire.d.ts.map +1 -0
  235. package/lib/VoIP/relay/sctp/wire.js +206 -0
  236. package/lib/VoIP/relay/sctp/wire.js.map +1 -0
  237. package/lib/VoIP/relay/stun.d.ts +47 -0
  238. package/lib/VoIP/relay/stun.d.ts.map +1 -0
  239. package/lib/VoIP/relay/stun.js +459 -0
  240. package/lib/VoIP/relay/stun.js.map +1 -0
  241. package/lib/VoIP/shim/baileys-resolve.d.ts +2 -0
  242. package/lib/VoIP/shim/baileys-resolve.d.ts.map +1 -0
  243. package/lib/VoIP/shim/baileys-resolve.js +22 -0
  244. package/lib/VoIP/shim/baileys-resolve.js.map +1 -0
  245. package/lib/VoIP/shim/core.d.ts +32 -0
  246. package/lib/VoIP/shim/core.d.ts.map +1 -0
  247. package/lib/VoIP/shim/core.js +67 -0
  248. package/lib/VoIP/shim/core.js.map +1 -0
  249. package/lib/VoIP/shim/crypto.d.ts +2 -0
  250. package/lib/VoIP/shim/crypto.d.ts.map +1 -0
  251. package/lib/VoIP/shim/crypto.js +7 -0
  252. package/lib/VoIP/shim/crypto.js.map +1 -0
  253. package/lib/VoIP/shim/proto.d.ts +2 -0
  254. package/lib/VoIP/shim/proto.d.ts.map +1 -0
  255. package/lib/VoIP/shim/proto.js +10 -0
  256. package/lib/VoIP/shim/proto.js.map +1 -0
  257. package/lib/VoIP/shim/protocol.d.ts +32 -0
  258. package/lib/VoIP/shim/protocol.d.ts.map +1 -0
  259. package/lib/VoIP/shim/protocol.js +131 -0
  260. package/lib/VoIP/shim/protocol.js.map +1 -0
  261. package/lib/VoIP/shim/transport.d.ts +20 -0
  262. package/lib/VoIP/shim/transport.d.ts.map +1 -0
  263. package/lib/VoIP/shim/transport.js +83 -0
  264. package/lib/VoIP/shim/transport.js.map +1 -0
  265. package/lib/VoIP/shim/util.d.ts +13 -0
  266. package/lib/VoIP/shim/util.d.ts.map +1 -0
  267. package/lib/VoIP/shim/util.js +208 -0
  268. package/lib/VoIP/shim/util.js.map +1 -0
  269. package/lib/VoIP/signaling/bridge.d.ts +4 -0
  270. package/lib/VoIP/signaling/bridge.d.ts.map +1 -0
  271. package/lib/VoIP/signaling/bridge.js +103 -0
  272. package/lib/VoIP/signaling/bridge.js.map +1 -0
  273. package/lib/VoIP/signaling/screen-share.d.ts +40 -0
  274. package/lib/VoIP/signaling/screen-share.d.ts.map +1 -0
  275. package/lib/VoIP/signaling/screen-share.js +55 -0
  276. package/lib/VoIP/signaling/screen-share.js.map +1 -0
  277. package/lib/VoIP/signaling/signaling.d.ts +396 -0
  278. package/lib/VoIP/signaling/signaling.d.ts.map +1 -0
  279. package/lib/VoIP/signaling/signaling.js +488 -0
  280. package/lib/VoIP/signaling/signaling.js.map +1 -0
  281. package/lib/VoIP/types.d.ts +37 -12
  282. package/lib/VoIP/types.d.ts.map +1 -1
  283. package/lib/VoIP/types.js +65 -12
  284. package/lib/VoIP/types.js.map +1 -1
  285. package/lib/VoIP/voip-deps.d.ts +46 -0
  286. package/lib/VoIP/voip-deps.d.ts.map +1 -0
  287. package/lib/VoIP/voip-deps.js +244 -0
  288. package/lib/VoIP/voip-deps.js.map +1 -0
  289. package/lib/VoIP/voipClient.d.ts +34 -0
  290. package/lib/VoIP/voipClient.d.ts.map +1 -0
  291. package/lib/VoIP/voipClient.js +351 -0
  292. package/lib/VoIP/voipClient.js.map +1 -0
  293. package/lib/VoIP/wasm-engine.d.ts +2 -2
  294. package/lib/WABinary/generic-utils.js +1 -1
  295. package/lib/WABinary/generic-utils.js.map +1 -1
  296. package/package.json +1 -1
package/lib/VoIP/index.js CHANGED
@@ -1,941 +1,631 @@
1
- import { EventEmitter } from 'node:events';
2
- import { createHmac, randomBytes } from 'node:crypto';
3
- import { WasmEngine } from './wasm-engine.js';
4
- import { RelayRtcTransport } from './relay-transport.js';
5
- import { SignalingBridge } from './signaling.js';
6
- import { AudioFeeder } from './audio-feeder.js';
7
- import { VideoFeeder, VIDEO_FORMAT_I420 } from './video-feeder.js';
8
- import { CallState } from './types.js';
9
- export { CallState };
10
- const SHA256_LEN = 32;
11
- const toBareJid = jid => {
12
- if (!jid)
13
- return jid;
14
- const value = String(jid);
15
- const at = value.indexOf("@");
16
- if (at < 0)
17
- return value;
18
- const user = value.slice(0, at).split(":")[0];
19
- return `${user}@${value.slice(at + 1)}`;
20
- };
21
- const computeHkdf = (key, salt, info, length) => {
22
- const effectiveSalt = salt && salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(SHA256_LEN, 0);
23
- const prk = createHmac("sha256", effectiveSalt).update(key).digest();
24
- const blocks = Math.ceil(length / SHA256_LEN);
25
- const okm = Buffer.alloc(blocks * SHA256_LEN);
26
- let prev = Buffer.alloc(0);
27
- for (let i = 1; i <= blocks; i += 1) {
28
- prev = createHmac("sha256", prk)
29
- .update(prev)
30
- .update(info)
31
- .update(Buffer.from([i]))
32
- .digest();
33
- prev.copy(okm, (i - 1) * SHA256_LEN);
34
- }
35
- return new Uint8Array(okm.buffer, okm.byteOffset, length);
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
36
6
  };
37
- const computeHmacSha256 = (data, key) => {
38
- const result = createHmac("sha256", Buffer.from(key)).update(data).digest();
39
- return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
40
11
  };
41
- const isCallReceiptNode = node => {
42
- if (node?.tag !== "receipt")
43
- return false;
44
- const child = Array.isArray(node.content) ? node.content[0] : null;
45
- return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
12
+ var _VoipCall_activeCall, _VoipCall_coordinator, _VoipCall_items, _VoipCall_index, _VoipCall_ended, _VoipCall_onRelease, _VoipCall_autoEndCall, _VoipCall_loop, _VoipCall_onItemAdvance, _VoipCall_target, _VoipCall_autoDowngrade, _VoipCall_startVideoOnFirst, _VoipCall_videoDown, _VoipCall_silenced, _Voip_instances, _Voip_conn, _Voip_client, _Voip_clientForConn, _Voip_calls, _Voip_pending, _Voip_maxConcurrentCalls, _Voip_ffprobePath, _Voip_tmpDir, _Voip_voipLogLevel, _Voip_getClient, _Voip_assertCapacity, _Voip_launch, _Voip_requireCoordinator;
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { EventEmitter } from 'node:events';
16
+ import { VoipClient, ActiveCall } from './voipClient.js';
17
+ import { WaVoipCoordinator } from './WaVoipCoordinator.js';
18
+ import { CallDirection, CallMediaType, CallState, EndCallReason, PayloadType } from './types.js';
19
+ const RESOLUTION_PRESETS = {
20
+ '240p': { width: 320, height: 240, frameRate: 20 },
21
+ '360p': { width: 640, height: 360, frameRate: 30 },
22
+ '480p': { width: 854, height: 480, frameRate: 30 },
23
+ '720p': { width: 1280, height: 720, frameRate: 30 },
24
+ '1080p': { width: 1920, height: 1080, frameRate: 30 },
46
25
  };
47
- export class ActiveCall extends EventEmitter {
48
- constructor(callId, engine, durationMs) {
26
+ function resolveVideoConfig(resolution, sourceDims) {
27
+ if (!resolution) {
28
+ if (!sourceDims?.width || !sourceDims?.height)
29
+ return undefined;
30
+ return applyOrientation(RESOLUTION_PRESETS['480p'], sourceDims);
31
+ }
32
+ if (typeof resolution === 'object')
33
+ return resolution;
34
+ const key = String(resolution).trim().toLowerCase();
35
+ const preset = RESOLUTION_PRESETS[key];
36
+ if (!preset) {
37
+ const known = Object.keys(RESOLUTION_PRESETS).join(', ');
38
+ throw new Error(`Unknown resolution "${resolution}". Use one of: ${known}, or pass { width, height, frameRate } directly.`);
39
+ }
40
+ return applyOrientation(preset, sourceDims);
41
+ }
42
+ function applyOrientation(preset, sourceDims) {
43
+ if (!sourceDims?.width || !sourceDims?.height)
44
+ return { ...preset };
45
+ const sourceIsPortrait = sourceDims.height > sourceDims.width;
46
+ const presetIsPortrait = preset.height > preset.width;
47
+ if (sourceIsPortrait === presetIsPortrait)
48
+ return { ...preset };
49
+ return { ...preset, width: preset.height, height: preset.width };
50
+ }
51
+ const VIDEO_EXTENSIONS = /\.(mp4|mov|webm|mkv|avi|m4v|3gp)(\?|#|$)/i;
52
+ const AUDIO_EXTENSIONS = /\.(mp3|ogg|opus|wav|m4a|aac|flac|weba)(\?|#|$)/i;
53
+ function detectKind(source) {
54
+ if (VIDEO_EXTENSIONS.test(source))
55
+ return 'video';
56
+ if (AUDIO_EXTENSIONS.test(source))
57
+ return 'audio';
58
+ return null;
59
+ }
60
+ function isUrl(source) {
61
+ return /^https?:\/\//i.test(source);
62
+ }
63
+ async function downloadToTemp(url, extHint, maxBytes, tmpDirOverride) {
64
+ const response = await fetch(url, {
65
+ headers: { 'User-Agent': 'Mozilla/5.0' },
66
+ signal: AbortSignal.timeout(30000),
67
+ });
68
+ if (!response.ok)
69
+ throw new Error(`Download failed: HTTP ${response.status}`);
70
+ const declared = Number(response.headers.get('content-length') || 0);
71
+ if (declared && declared > maxBytes)
72
+ throw new Error(`Download too large: ${declared} bytes (max ${maxBytes})`);
73
+ const data = Buffer.from(await response.arrayBuffer());
74
+ if (data.length > maxBytes)
75
+ throw new Error(`Download too large: ${data.length} bytes (max ${maxBytes})`);
76
+ const os = await import('node:os');
77
+ const tmpDir = tmpDirOverride || os.tmpdir();
78
+ if (!fs.existsSync(tmpDir))
79
+ fs.mkdirSync(tmpDir, { recursive: true });
80
+ const filePath = path.join(tmpDir, `voip_${Date.now()}_${Math.random().toString(36).slice(2, 8)}${extHint}`);
81
+ fs.writeFileSync(filePath, data);
82
+ return filePath;
83
+ }
84
+ async function probeMedia(filePath, ffprobePath) {
85
+ try {
86
+ const { execFile } = await import('node:child_process');
87
+ const { promisify } = await import('node:util');
88
+ const execFileAsync = promisify(execFile);
89
+ const { stdout } = await execFileAsync(ffprobePath, [
90
+ '-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', filePath
91
+ ]);
92
+ const parsed = JSON.parse(stdout);
93
+ const duration = parsed?.format?.duration;
94
+ const durationMs = (!duration || isNaN(duration)) ? null : Math.ceil(parseFloat(duration) * 1000);
95
+ const videoStream = parsed?.streams?.find((s) => s.codec_type === 'video');
96
+ let width = videoStream?.width || null;
97
+ let height = videoStream?.height || null;
98
+ const rotation = getEffectiveRotation(videoStream);
99
+ if (width && height && Math.abs(rotation) % 180 === 90) {
100
+ [width, height] = [height, width];
101
+ }
102
+ return { durationMs, width, height };
103
+ }
104
+ catch {
105
+ return { durationMs: null, width: null, height: null };
106
+ }
107
+ }
108
+ function getEffectiveRotation(videoStream) {
109
+ const tagRotate = videoStream?.tags?.rotate;
110
+ if (tagRotate !== undefined) {
111
+ const n = parseInt(tagRotate, 10);
112
+ if (!isNaN(n))
113
+ return ((n % 360) + 360) % 360;
114
+ }
115
+ const matrixSideData = videoStream?.side_data_list?.find((sd) => sd.rotation !== undefined);
116
+ if (matrixSideData) {
117
+ const n = Math.round(matrixSideData.rotation);
118
+ if (!isNaN(n))
119
+ return ((n % 360) + 360) % 360;
120
+ }
121
+ return 0;
122
+ }
123
+ async function normalizeItem(item, ffprobePath, tmpDir) {
124
+ let kind;
125
+ let rawSource;
126
+ let autoAdvance = false;
127
+ if (typeof item === 'string') {
128
+ rawSource = item;
129
+ kind = detectKind(item) ?? 'audio';
130
+ }
131
+ else if (item && typeof item === 'object') {
132
+ autoAdvance = !!item.autoAdvance;
133
+ if (item.video) {
134
+ rawSource = item.video;
135
+ kind = 'video';
136
+ }
137
+ else if (item.audio) {
138
+ rawSource = item.audio;
139
+ kind = 'audio';
140
+ }
141
+ else {
142
+ throw new Error('Playlist item must be a string, or an object with a "video" or "audio" key.');
143
+ }
144
+ }
145
+ else {
146
+ throw new Error('Playlist item must be a string or an object.');
147
+ }
148
+ let source = rawSource;
149
+ let isTemp = false;
150
+ if (isUrl(rawSource)) {
151
+ const extHint = kind === 'video' ? '.mp4' : '.audio';
152
+ const maxBytes = kind === 'video' ? 50 * 1024 * 1024 : 20 * 1024 * 1024;
153
+ source = await downloadToTemp(rawSource, extHint, maxBytes, tmpDir);
154
+ isTemp = true;
155
+ }
156
+ else if (!fs.existsSync(rawSource)) {
157
+ throw new Error(`Media file not found: ${rawSource}`);
158
+ }
159
+ const probed = await probeMedia(source, ffprobePath);
160
+ const durationMs = probed.durationMs ?? undefined;
161
+ const result = { kind, source, isTemp, durationMs, autoAdvance };
162
+ if (kind === 'video' && probed.width && probed.height) {
163
+ result.sourceWidth = probed.width;
164
+ result.sourceHeight = probed.height;
165
+ }
166
+ return result;
167
+ }
168
+ class VoipCall extends EventEmitter {
169
+ constructor(items, onRelease, opts = {}) {
49
170
  super();
50
- this.callId = callId;
51
- this.engine = engine;
52
- this._state = CallState.Idle;
53
- this._endResolver = undefined;
54
- this._endPromise = undefined;
55
- this._endTimer = null;
56
- this._ended = false;
57
- this._audioSource = "silence";
58
- this.end = () => {
59
- if (this._ended)
60
- return;
61
- try {
62
- this.engine.endCall(0, true);
63
- }
64
- catch { }
65
- this._forceEnd("local_end");
66
- };
67
- this.mute = muted => {
68
- try {
69
- this.engine.setMute(muted);
70
- }
71
- catch { }
72
- };
73
- this.waitForEnd = () => this._endPromise;
74
- this._playlist = [];
75
- this._feeder = null;
76
- this._idleTimer = null;
77
- this._endWhenQueueEmpty = true;
78
- this._idleGraceMs = 0;
79
- this._attachFeeder = feeder => {
80
- this._feeder = feeder;
81
- };
82
- this.play = source => {
83
- this._playlist = [];
84
- if (this._feeder) {
85
- this._feeder.clearPlaylist();
86
- this._feeder.enqueue(source);
87
- this._feeder.skip();
88
- return true;
89
- }
90
- this._playlist.push(source);
91
- return false;
92
- };
93
- this.enqueue = source => {
94
- this._clearIdleTimer();
95
- if (this._feeder) {
96
- return this._feeder.enqueue(source);
97
- }
98
- const tracks = Array.isArray(source) ? source : [source];
99
- for (const track of tracks) {
100
- if (track) {
101
- this._playlist.push(track);
102
- }
103
- }
104
- return this._playlist.length;
105
- };
106
- this.skip = () => this._feeder?.skip() ?? false;
107
- this.queued = () => this._feeder?.playlistLength ?? this._playlist.length;
108
- this.nowPlaying = () => this._feeder?.currentTrack ?? null;
109
- this._video = false;
110
- this._videoSource = "black";
111
- this._videoPlaylist = [];
112
- this._videoFeeder = null;
113
- this._attachVideoFeeder = feeder => {
114
- this._videoFeeder = feeder;
115
- };
116
- this.playVideo = source => {
117
- this._videoPlaylist = [];
118
- if (this._videoFeeder) {
119
- this._videoFeeder.clearPlaylist();
120
- this._videoFeeder.enqueue(source);
121
- this._videoFeeder.skip();
122
- return true;
123
- }
124
- this._videoPlaylist.push(source);
125
- return false;
126
- };
127
- this.enqueueVideo = source => {
128
- if (this._videoFeeder) {
129
- return this._videoFeeder.enqueue(source);
130
- }
131
- const tracks = Array.isArray(source) ? source : [source];
132
- for (const track of tracks) {
133
- if (track) {
134
- this._videoPlaylist.push(track);
135
- }
136
- }
137
- return this._videoPlaylist.length;
138
- };
139
- this.skipVideo = () => this._videoFeeder?.skip() ?? false;
140
- this.queuedVideo = () => this._videoFeeder?.playlistLength ?? this._videoPlaylist.length;
141
- this.nowPlayingVideo = () => this._videoFeeder?.currentTrack ?? null;
142
- this.isVideo = () => this._video;
143
- this._screenShare = false;
144
- this.startScreenShare = () => {
145
- if (!this._video) {
146
- throw new Error("screen share needs a video call: pass video: true, or screenShare: true which implies it");
147
- }
148
- this._screenShare = true;
149
- try {
150
- return this.engine.startScreenShare();
151
- }
152
- catch {
153
- return undefined;
154
- }
155
- };
156
- this.stopScreenShare = () => {
157
- this._screenShare = false;
158
- try {
159
- return this.engine.stopScreenShare();
160
- }
161
- catch {
162
- return undefined;
163
- }
164
- };
165
- this.isScreenShare = () => this._screenShare;
166
- this._onVideoTrackStart = track => {
167
- this.emit("videotrack", track);
168
- };
169
- this._onVideoTrackEnd = track => {
170
- this.emit("videotrackend", track);
171
- };
172
- this._clearIdleTimer = () => {
173
- if (this._idleTimer) {
174
- clearTimeout(this._idleTimer);
175
- this._idleTimer = null;
176
- }
177
- };
178
- this._onTrackStart = track => {
179
- this._clearIdleTimer();
180
- this.emit("track", track);
181
- };
182
- this._onTrackEnd = track => {
183
- this.emit("trackend", track);
184
- };
185
- this._onPlaylistIdle = () => {
186
- this.emit("idle");
187
- if (!this._endWhenQueueEmpty) {
188
- return;
189
- }
190
- this._clearIdleTimer();
191
- this._idleTimer = setTimeout(() => {
192
- this._idleTimer = null;
193
- if (this._feeder?.playlistLength || this._feeder?.currentTrack) {
194
- return;
195
- }
196
- this.end();
197
- }, this._idleGraceMs);
198
- };
199
- this._updateState = state => {
200
- this._state = state;
201
- if (state === CallState.PreacceptReceived) {
202
- this.emit("ringing");
203
- }
204
- else if (state === CallState.Active) {
205
- this.emit("connected");
206
- if (this._screenShare) {
207
- try {
208
- this.engine.startScreenShare();
209
- }
210
- catch { }
211
- }
212
- }
213
- else if (state === CallState.Idle || state === CallState.Ending) {
214
- this._forceEnd("ended");
215
- }
216
- };
217
- this._emitAudio = pcm => {
218
- this.emit("audio", pcm);
219
- };
220
- this._forceEnd = reason => {
221
- if (this._ended)
222
- return;
223
- this._ended = true;
224
- this._clearIdleTimer();
225
- if (this._endTimer) {
226
- clearTimeout(this._endTimer);
227
- this._endTimer = null;
228
- }
229
- this.emit("ended", reason);
230
- this._endResolver(reason);
231
- };
232
- this._endPromise = new Promise(resolve => {
233
- this._endResolver = resolve;
171
+ _VoipCall_activeCall.set(this, null);
172
+ _VoipCall_coordinator.set(this, null);
173
+ _VoipCall_items.set(this, void 0);
174
+ _VoipCall_index.set(this, -1);
175
+ _VoipCall_ended.set(this, false);
176
+ _VoipCall_onRelease.set(this, void 0);
177
+ _VoipCall_autoEndCall.set(this, void 0);
178
+ _VoipCall_loop.set(this, void 0);
179
+ _VoipCall_onItemAdvance.set(this, void 0);
180
+ _VoipCall_target.set(this, void 0);
181
+ _VoipCall_autoDowngrade.set(this, void 0);
182
+ _VoipCall_startVideoOnFirst.set(this, void 0);
183
+ _VoipCall_videoDown.set(this, false);
184
+ _VoipCall_silenced.set(this, false);
185
+ this._itemTimer = null;
186
+ __classPrivateFieldSet(this, _VoipCall_items, items, "f");
187
+ __classPrivateFieldSet(this, _VoipCall_onRelease, onRelease, "f");
188
+ __classPrivateFieldSet(this, _VoipCall_autoEndCall, opts.autoEndCall === undefined ? true : !!opts.autoEndCall, "f");
189
+ __classPrivateFieldSet(this, _VoipCall_loop, !!opts.loop, "f");
190
+ __classPrivateFieldSet(this, _VoipCall_onItemAdvance, opts.onItemAdvance, "f");
191
+ __classPrivateFieldSet(this, _VoipCall_target, opts.target ?? null, "f");
192
+ __classPrivateFieldSet(this, _VoipCall_autoDowngrade, opts.autoDowngrade === undefined ? true : !!opts.autoDowngrade, "f");
193
+ __classPrivateFieldSet(this, _VoipCall_startVideoOnFirst, !!opts.startVideoOnFirst, "f");
194
+ }
195
+ async _attach(activeCall) {
196
+ __classPrivateFieldSet(this, _VoipCall_activeCall, activeCall, "f");
197
+ __classPrivateFieldSet(this, _VoipCall_coordinator, activeCall.coordinator, "f");
198
+ activeCall.on('ringing', () => this.emit('ringing'));
199
+ activeCall.on('connected', () => {
200
+ this.emit('connected');
201
+ this._advance().catch((err) => this.emit('error', err));
234
202
  });
235
- if (durationMs > 0) {
236
- this._endTimer = setTimeout(() => this.end(), durationMs);
203
+ activeCall.on('ended', (reason) => this._finish(reason));
204
+ activeCall.on('error', (err) => this.emit('error', err));
205
+ activeCall.on('peer_video', (change) => {
206
+ this._onPeerVideo(change).catch((err) => this.emit('error', err));
207
+ });
208
+ if (activeCall.ended) {
209
+ this._finish('ended');
210
+ return;
211
+ }
212
+ if (activeCall.connected) {
213
+ this.emit('connected');
214
+ this._advance().catch((err) => this.emit('error', err));
215
+ }
216
+ for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished']) {
217
+ activeCall.on(ev, (...args) => this.emit(ev, ...args));
237
218
  }
238
219
  }
239
- get state() {
240
- return this._state;
220
+ get callId() {
221
+ return __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.callId ?? null;
241
222
  }
242
- }
243
- export class VoipClient {
244
- constructor(config = {}) {
245
- this._config = config;
246
- this._log = typeof config.logger === 'function'
247
- ? config.logger
248
- : config.debug ? (...args) => console.log(...args) : () => { };
249
- this._engine = null;
250
- this._relay = null;
251
- this._signaling = null;
252
- this._sock = config.socket || config.sock || config.conn || null;
253
- this._activeCall = null;
254
- this._externalSocket = !!this._sock;
255
- this._capturePtr = 0;
256
- this._captureChunkBytes = 0;
257
- this._captureSampleRate = 16000;
258
- this._captureChannels = 1;
259
- this._captureFramesPerChunk = 320;
260
- this._feeder = null;
261
- this._videoFeeder = null;
262
- this._wsCallHandler = null;
263
- this._wsReceiptHandler = null;
264
- this._captureStartRequested = false;
265
- this._audioStartTimer = null;
266
- this.connect = async () => {
267
- if (!this._sock) {
268
- throw new Error('VoipClient needs the socket you are already logged in with: new VoipClient({ socket: sock }). It never opens a session of its own, so there is no second pairing or QR scan.');
269
- }
270
- if (!this._sock.ws) {
271
- throw new Error('the socket has no websocket yet; call connect() once connection.update reports "open"');
272
- }
273
- await this._initVoipStack();
274
- };
275
- this.attach = async (socket) => {
276
- if (!socket) {
277
- throw new Error('attach needs the reconnected socket');
278
- }
279
- this._detachSocketHandlers();
280
- this._sock = socket;
281
- this._externalSocket = true;
282
- this._signaling?.setSocket?.(socket);
283
- this._bindSocketHandlers();
284
- };
285
- this.connectWithSocket = async (socket) => {
286
- if (!socket) {
287
- throw new Error('connectWithSocket needs the socket you are already logged in with');
288
- }
289
- this._detachSocketHandlers();
290
- this._sock = socket;
291
- this._externalSocket = true;
292
- this._signaling?.setSocket?.(socket);
293
- await this.connect();
294
- };
295
- this.call = async (phoneNumber, opts = {}) => {
296
- if (!this._engine || !this._signaling) {
297
- throw new Error("Not connected. Call connect() first.");
298
- }
299
- if (this._activeCall) {
300
- try {
301
- this._activeCall._forceEnd("replaced");
302
- }
303
- catch { }
304
- try {
305
- this._engine?.endCall?.(0, true);
306
- }
307
- catch { }
308
- try {
309
- this._feeder?.stop();
310
- }
311
- catch { }
312
- this._feeder = null;
313
- try {
314
- this._videoFeeder?.stop();
315
- }
316
- catch { }
317
- this._videoFeeder = null;
318
- this._activeCall = null;
319
- }
320
- const targetNumber = phoneNumber.replace(/\D/g, "");
321
- if (!targetNumber) {
322
- throw new Error("Nomor target tidak valid.");
323
- }
324
- const targetPnJid = `${targetNumber}@s.whatsapp.net`;
325
- const durationMs = opts.durationMs ?? 120000;
326
- const audioSource = opts.audioSource ?? "silence";
327
- const peerLid = await this._signaling.resolveLid(targetPnJid);
328
- if (!peerLid) {
329
- throw new Error(`Tidak bisa resolve LID untuk ${targetPnJid}. Pastikan target valid dan sudah tersimpan mapping LID/PN atau USync LID bisa diakses.`);
223
+ get target() {
224
+ return __classPrivateFieldGet(this, _VoipCall_target, "f");
225
+ }
226
+ mute(value = true) {
227
+ return __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.setMute(value);
228
+ }
229
+ raiseHand(value = true) {
230
+ return __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.raiseHand(value);
231
+ }
232
+ shareScreen(value = true) {
233
+ return __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.shareScreen(value);
234
+ }
235
+ react(emoji) {
236
+ return __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.react(emoji) ?? false;
237
+ }
238
+ async upgradeToVideo() {
239
+ await __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.upgradeToVideo();
240
+ __classPrivateFieldSet(this, _VoipCall_videoDown, false, "f");
241
+ }
242
+ get isVideoDowngraded() {
243
+ return __classPrivateFieldGet(this, _VoipCall_videoDown, "f");
244
+ }
245
+ async _onPeerVideo(change) {
246
+ if (!__classPrivateFieldGet(this, _VoipCall_autoDowngrade, "f") || __classPrivateFieldGet(this, _VoipCall_ended, "f") || __classPrivateFieldGet(this, _VoipCall_silenced, "f") || __classPrivateFieldGet(this, _VoipCall_videoDown, "f"))
247
+ return;
248
+ if (change?.direction !== 'inbound' || change.active || !change.allOff)
249
+ return;
250
+ const current = __classPrivateFieldGet(this, _VoipCall_items, "f")[__classPrivateFieldGet(this, _VoipCall_index, "f")];
251
+ if (current?.kind !== 'video')
252
+ return;
253
+ const callId = __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.callId;
254
+ if (!callId)
255
+ return;
256
+ __classPrivateFieldSet(this, _VoipCall_videoDown, true, "f");
257
+ try {
258
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").stopVideoMidCall(callId, { keepSource: true });
259
+ this.emit('downgraded');
260
+ }
261
+ catch (err) {
262
+ __classPrivateFieldSet(this, _VoipCall_videoDown, false, "f");
263
+ throw new Error(`Failed to downgrade call to audio: ${err?.message || err}`);
264
+ }
265
+ }
266
+ async _advance() {
267
+ if (__classPrivateFieldGet(this, _VoipCall_silenced, "f"))
268
+ return;
269
+ const previous = __classPrivateFieldGet(this, _VoipCall_items, "f")[__classPrivateFieldGet(this, _VoipCall_index, "f")] ?? null;
270
+ __classPrivateFieldSet(this, _VoipCall_index, __classPrivateFieldGet(this, _VoipCall_index, "f") + 1, "f");
271
+ let next = __classPrivateFieldGet(this, _VoipCall_items, "f")[__classPrivateFieldGet(this, _VoipCall_index, "f")];
272
+ if (!next) {
273
+ if (__classPrivateFieldGet(this, _VoipCall_loop, "f") && __classPrivateFieldGet(this, _VoipCall_items, "f").length > 0) {
274
+ this.emit('playlist_looped');
275
+ __classPrivateFieldSet(this, _VoipCall_index, 0, "f");
276
+ next = __classPrivateFieldGet(this, _VoipCall_items, "f")[0];
330
277
  }
331
- const peerJid = peerLid;
332
- const peerPn = targetPnJid;
333
- const isLidCall = true;
334
- for (const jid of [targetPnJid, peerLid]) {
335
- try {
336
- await this._sock.presenceSubscribe(jid);
278
+ else {
279
+ this.emit('playlist_ended');
280
+ if (__classPrivateFieldGet(this, _VoipCall_autoEndCall, "f")) {
281
+ this.end().catch((err) => this.emit('error', err));
337
282
  }
338
- catch { }
339
- }
340
- await new Promise(resolve => setTimeout(resolve, 150));
341
- let peerDeviceJids = [];
342
- try {
343
- peerDeviceJids = await this._signaling.discoverPeerDevices(peerLid);
344
- }
345
- catch (err) {
346
- this._log("[RTC DISCOVER DEVICES ERROR]", err?.message || err);
347
- }
348
- const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
349
- try {
350
- await this._signaling.ensureSessionsForPeers(deviceList);
351
- }
352
- catch (err) {
353
- this._log("[RTC ENSURE SESSIONS WARNING]", err?.message || err);
283
+ return;
354
284
  }
355
- await new Promise(resolve => setTimeout(resolve, 100));
356
- let tcToken = null;
285
+ }
286
+ const isFirst = previous === null && __classPrivateFieldGet(this, _VoipCall_index, "f") === 0;
287
+ if (isFirst && next.kind === 'video' && __classPrivateFieldGet(this, _VoipCall_startVideoOnFirst, "f")) {
357
288
  try {
358
- this._signaling.issueTcToken(peerLid).catch(err => {
359
- this._log("[RTC ISSUE TC TOKEN ASYNC ERROR]", err?.message || err);
360
- });
361
- tcToken = await Promise.race([
362
- this._signaling.ensureTcToken(peerLid, targetPnJid).catch(err => {
363
- this._log("[RTC ENSURE TC TOKEN ERROR]", err?.message || err);
364
- return null;
365
- }),
366
- new Promise(resolve => setTimeout(() => resolve(null), 1500))
367
- ]);
289
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").startVideoMidCall(__classPrivateFieldGet(this, _VoipCall_activeCall, "f").callId);
368
290
  }
369
291
  catch (err) {
370
- this._log("[RTC TC TOKEN FAST PATH ERROR]", err?.message || err);
371
- }
372
- if (!tcToken || !tcToken.length) {
373
- this._log("[RTC TC TOKEN WARNING] TC token kosong, lanjut startCall dengan token kosong.");
374
- tcToken = undefined;
292
+ this.emit('error', new Error(`Failed to start video: ${err?.message || err}`));
375
293
  }
376
- const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
377
- const call = new ActiveCall(callId, this._engine, durationMs);
378
- call._audioSource = audioSource;
379
- call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
380
- call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
381
- call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
382
- call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
383
- call._screenShare = !!opts.screenShare;
384
- call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
385
- call._videoSource = opts.videoSource ?? "black";
386
- call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
387
- this._activeCall = call;
388
- call.once("ended", () => {
389
- if (this._activeCall === call)
390
- this._activeCall = null;
391
- });
392
- call.once("error", () => {
393
- if (this._activeCall === call)
394
- this._activeCall = null;
395
- });
396
- this._log("[RTC START CALL PARAMS]", {
397
- peerJid,
398
- peerPn,
399
- peerList: deviceList,
400
- callId,
401
- isLidCall,
402
- targetPnJid,
403
- peerLid,
404
- hasTcToken: !!tcToken,
405
- tcTokenLength: tcToken?.length || 0
406
- });
294
+ }
295
+ if (!isFirst) {
296
+ const callId = __classPrivateFieldGet(this, _VoipCall_activeCall, "f").callId;
297
+ const videoRunning = previous?.kind === 'video' && !__classPrivateFieldGet(this, _VoipCall_videoDown, "f");
407
298
  try {
408
- const startResult = this._engine.startCall({
409
- peerJid,
410
- peerPn,
411
- peerList: deviceList,
412
- callId,
413
- isVideo: call._video,
414
- isLidCall,
415
- isFromDialer: false,
416
- extraData: tcToken
417
- });
418
- this._log("[RTC START CALL RESULT]", startResult);
419
- }
420
- catch (err) {
421
- if (this._activeCall === call)
422
- this._activeCall = null;
423
- try {
424
- call._forceEnd("start_call_failed");
425
- }
426
- catch { }
427
- throw err;
428
- }
429
- return call;
430
- };
431
- this.callGroup = async (groupJid, opts = {}) => {
432
- if (!this._engine || !this._signaling) {
433
- throw new Error("Not connected. Call connect() first.");
434
- }
435
- if (typeof groupJid !== "string" || !groupJid.endsWith("@g.us")) {
436
- throw new Error(`${JSON.stringify(groupJid)} is not a group jid`);
437
- }
438
- const metadata = opts.metadata ?? await this._sock.groupMetadata(groupJid);
439
- const selfPn = toBareJid(this._sock.authState?.creds?.me?.id ?? this._sock.user?.id ?? "");
440
- const selfLid = toBareJid(this._sock.authState?.creds?.me?.lid ?? "");
441
- const members = (metadata?.participants ?? [])
442
- .map(participant => toBareJid(participant.id ?? participant.jid ?? ""))
443
- .filter(jid => jid && jid !== selfPn && jid !== selfLid);
444
- const wanted = Array.isArray(opts.participants) && opts.participants.length
445
- ? opts.participants.map(toBareJid)
446
- : members;
447
- if (!wanted.length) {
448
- throw new Error(`no one to call in ${groupJid}`);
449
- }
450
- const pnUserJids = [];
451
- const lidUserJids = [];
452
- const deviceJidsCsv = [];
453
- for (const member of wanted) {
454
- const isLid = member.endsWith("@lid");
455
- const lid = isLid ? member : await this._signaling.resolveLid(member).catch(() => null);
456
- const pn = isLid ? "" : member;
457
- if (pn) {
458
- pnUserJids.push(pn);
459
- }
460
- if (lid) {
461
- lidUserJids.push(lid);
462
- let devices = [];
463
- try {
464
- devices = await this._signaling.discoverPeerDevices(lid);
299
+ if (next.kind === 'video') {
300
+ if (previous && previous.kind === 'video') {
301
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").swapVideoSource(callId, next.source);
465
302
  }
466
- catch (err) {
467
- this._log("[RTC GROUP DISCOVER DEVICES ERROR]", member, err?.message || err);
303
+ else {
304
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").loadVideo(callId, next.source);
305
+ }
306
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").loadAudio(callId, next.source);
307
+ if (!videoRunning) {
308
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").startVideoMidCall(callId);
468
309
  }
469
- deviceJidsCsv.push((devices.length ? devices : [lid]).join(","));
470
310
  }
471
- }
472
- if (!lidUserJids.length) {
473
- throw new Error(`could not resolve a LID for anyone in ${groupJid}`);
474
- }
475
- const flatDevices = deviceJidsCsv.join(",").split(",").filter(Boolean);
476
- try {
477
- await this._signaling.ensureSessionsForPeers(flatDevices);
478
- }
479
- catch (err) {
480
- this._log("[RTC GROUP ENSURE SESSIONS WARNING]", err?.message || err);
481
- }
482
- const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
483
- const call = new ActiveCall(callId, this._engine, opts.durationMs ?? 120000);
484
- call._audioSource = opts.audioSource ?? "silence";
485
- call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
486
- call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
487
- call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
488
- call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
489
- call._screenShare = !!opts.screenShare;
490
- call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
491
- call._videoSource = opts.videoSource ?? "black";
492
- call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
493
- call.groupJid = groupJid;
494
- this._activeCall = call;
495
- call.once("ended", () => {
496
- if (this._activeCall === call)
497
- this._activeCall = null;
498
- });
499
- this._log("[RTC START GROUP CALL PARAMS]", { groupJid, callId, pnUserJids, lidUserJids, deviceJidsCsv });
500
- try {
501
- const startResult = this._engine.startGroupCall({
502
- pnUserJids,
503
- lidUserJids,
504
- deviceJidsCsv,
505
- callId,
506
- isVideo: call._video,
507
- groupJid,
508
- chatName: metadata?.subject ?? ""
509
- });
510
- this._log("[RTC START GROUP CALL RESULT]", startResult);
511
- }
512
- catch (err) {
513
- if (this._activeCall === call)
514
- this._activeCall = null;
515
- try {
516
- call._forceEnd("start_group_call_failed");
311
+ else {
312
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").loadAudio(callId, next.source);
313
+ if (videoRunning) {
314
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").stopVideoMidCall(callId, { keepSource: true });
315
+ }
517
316
  }
518
- catch { }
519
- throw err;
520
- }
521
- return call;
522
- };
523
- this.joinGroupCall = async (invite, opts = {}) => {
524
- if (!this._engine || !this._signaling) {
525
- throw new Error("Not connected. Call connect() first.");
526
- }
527
- const callId = invite?.callId ?? invite?.id;
528
- const groupJid = invite?.groupJid ?? invite?.from;
529
- const callCreatorJid = invite?.callCreatorJid ?? invite?.creator ?? invite?.from;
530
- if (!callId || !callCreatorJid) {
531
- throw new Error("joinGroupCall needs at least { callId, callCreatorJid } from the incoming offer");
532
- }
533
- const call = new ActiveCall(callId, this._engine, opts.durationMs ?? 0);
534
- call._audioSource = opts.audioSource ?? "silence";
535
- call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
536
- call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
537
- call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
538
- call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
539
- call._screenShare = !!opts.screenShare;
540
- call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
541
- call._videoSource = opts.videoSource ?? "black";
542
- call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
543
- call.groupJid = groupJid;
544
- this._activeCall = call;
545
- call.once("ended", () => {
546
- if (this._activeCall === call)
547
- this._activeCall = null;
548
- });
549
- try {
550
- const result = this._engine.joinOngoingCall({
551
- callId,
552
- callCreatorJid,
553
- initialPeerJid: invite?.initialPeerJid ?? callCreatorJid,
554
- pnUserJids: invite?.pnUserJids ?? [],
555
- lidUserJids: invite?.lidUserJids ?? [],
556
- deviceJidsCsv: invite?.deviceJidsCsv ?? [],
557
- groupJid: groupJid ?? "",
558
- isVideo: call._video,
559
- joinAndAccept: opts.joinAndAccept ?? true,
560
- chatName: invite?.chatName ?? ""
561
- });
562
- this._log("[RTC JOIN CALL RESULT]", result);
317
+ __classPrivateFieldSet(this, _VoipCall_videoDown, false, "f");
563
318
  }
564
319
  catch (err) {
565
- if (this._activeCall === call)
566
- this._activeCall = null;
567
- try {
568
- call._forceEnd("join_call_failed");
569
- }
570
- catch { }
571
- throw err;
572
- }
573
- return call;
574
- };
575
- this.acceptCall = (isMicEnabled = true, isCameraEnabled) => {
576
- const isVideo = isCameraEnabled !== undefined ? isCameraEnabled : (this._activeCall?._video ?? false);
577
- return this._engine?.acceptCall(isMicEnabled, isVideo);
578
- };
579
- this.disconnect = () => {
580
- this._activeCall?._forceEnd("disconnect");
581
- this._activeCall = null;
582
- this._captureStartRequested = false;
583
- try {
584
- this._feeder?.stop();
585
- }
586
- catch { }
587
- this._feeder = null;
588
- try {
589
- this._videoFeeder?.stop();
590
- }
591
- catch { }
592
- this._videoFeeder = null;
593
- if (this._audioStartTimer) {
594
- clearTimeout(this._audioStartTimer);
595
- this._audioStartTimer = null;
596
- }
597
- try {
598
- this._signaling?.attachEngine?.(null);
599
- }
600
- catch { }
601
- this._detachSocketHandlers();
602
- this._relay?.closeAll();
603
- this._engine?.destroy();
604
- if (!this._externalSocket) {
605
- this._sock?.end?.();
606
- }
607
- this._engine = null;
608
- this._relay = null;
609
- this._signaling = null;
610
- if (!this._externalSocket) {
611
- this._sock = null;
612
- }
613
- };
614
- this.resetCallState = () => {
615
- try {
616
- this._activeCall?._forceEnd("reset");
617
- }
618
- catch { }
619
- try {
620
- this._engine?.endCall?.(0, true);
621
- }
622
- catch { }
623
- try {
624
- this._feeder?.stop();
625
- }
626
- catch { }
627
- this._feeder = null;
628
- try {
629
- this._videoFeeder?.stop();
630
- }
631
- catch { }
632
- this._videoFeeder = null;
633
- if (this._audioStartTimer) {
634
- clearTimeout(this._audioStartTimer);
635
- this._audioStartTimer = null;
636
- }
637
- this._captureStartRequested = false;
638
- this._activeCall = null;
639
- };
640
- this._initVoipStack = async () => {
641
- if (!this._sock) {
642
- throw new Error("Socket Baileys belum tersedia.");
643
- }
644
- this._signaling = new SignalingBridge({
645
- sock: this._sock,
646
- logger: this._config.logger,
647
- debug: this._config.debug
648
- });
649
- await this._signaling.init();
650
- this._relay = new RelayRtcTransport({
651
- onTransportMessage: (data, ip, port) => this._engine?.handleOnTransportMessage(data, ip, port),
652
- onIceRtt: (rttMs, ip, port) => this._engine?.updateIceRtt(rttMs, ip, port)
653
- });
654
- this._engine = new WasmEngine({
655
- callbacks: {
656
- onSignalingXmpp: (peerJid, callId, xmlPayload) => {
657
- this._log("[RTC WASM SIGNALING XMPP]", {
658
- peerJid,
659
- callId,
660
- payloadLength: xmlPayload?.length || 0
661
- });
662
- return this._signaling.sendSignaling(peerJid, callId, xmlPayload);
663
- },
664
- onCallEvent: (eventType, eventData) => this._handleCallEvent(eventType, eventData),
665
- sendDataToRelay: (data, ip, port) => this._relay.send(data, ip, port),
666
- onAudioCaptureInit: config => this._handleAudioCaptureInit(config),
667
- onAudioCaptureStart: () => this._handleAudioCaptureStart(),
668
- onAudioCaptureStop: () => this._handleAudioCaptureStop(),
669
- onAudioPlaybackData: audioData => this._activeCall?._emitAudio(audioData),
670
- onVideoCaptureStart: config => this._handleVideoCaptureStart(config),
671
- onVideoCaptureStop: () => this._handleVideoCaptureStop(),
672
- onDesktopCaptureStart: config => this._handleDesktopCaptureStart(config),
673
- onDesktopCaptureStop: () => this._handleDesktopCaptureStop(),
674
- cryptoHkdf: computeHkdf,
675
- hmacSha256: computeHmacSha256
676
- }
677
- });
678
- await this._engine.initialize();
679
- this._signaling.attachEngine(this._engine);
680
- const selfPnJidRaw = this._sock.authState?.creds?.me?.id ||
681
- this._sock.authState?.creds?.me?.jid ||
682
- this._sock.user?.id ||
683
- this._sock.user?.jid;
684
- const selfPnJid = toBareJid(selfPnJidRaw);
685
- const selfLidJid = this._sock.authState?.creds?.me?.lid ||
686
- this._sock.authState?.creds?.me?.lidJid ||
687
- "";
688
- if (!selfPnJid) {
689
- throw new Error("Tidak bisa membaca JID bot dari socket utama.");
690
- }
691
- this._log("[RTC SELF JID]", { selfPnJid, selfLidJid });
692
- this._engine.initVoipStack(selfPnJid, selfPnJid, selfLidJid);
693
- await this._engine.waitForVoipStackReady();
694
- try {
695
- this._engine.updateNetworkMedium(2, 0);
696
- }
697
- catch { }
698
- this._bindSocketHandlers();
699
- };
700
- this._detachSocketHandlers = () => {
701
- const ws = this._sock?.ws;
702
- if (ws?.off) {
703
- try {
704
- if (this._wsCallHandler)
705
- ws.off("CB:call", this._wsCallHandler);
706
- }
707
- catch { }
708
- try {
709
- if (this._wsReceiptHandler)
710
- ws.off("CB:receipt", this._wsReceiptHandler);
711
- }
712
- catch { }
320
+ this.emit('error', new Error(`Failed to advance to playlist item ${__classPrivateFieldGet(this, _VoipCall_index, "f")} (${next.kind} "${next.source}"): ${err?.message || err}`));
713
321
  }
714
- this._wsCallHandler = null;
715
- this._wsReceiptHandler = null;
716
- };
717
- this._bindSocketHandlers = () => {
718
- if (!this._sock?.ws?.on) {
719
- return;
720
- }
721
- this._detachSocketHandlers();
722
- this._wsCallHandler = node => {
723
- const signaling = this._signaling;
724
- const engine = this._engine;
725
- if (!signaling || !engine)
726
- return;
727
- if (typeof engine.isInitialized === "function" && !engine.isInitialized())
728
- return;
729
- signaling.processIncomingCall(node, engine, this._activeCall?.callId ?? "");
730
- };
731
- this._wsReceiptHandler = node => {
732
- if (!isCallReceiptNode(node))
733
- return;
734
- const signaling = this._signaling;
735
- const engine = this._engine;
736
- if (!signaling || !engine)
737
- return;
738
- if (typeof engine.isInitialized === "function" && !engine.isInitialized())
739
- return;
740
- signaling.processIncomingReceipt(node, engine, this._activeCall?.callId ?? "");
741
- };
742
- this._sock.ws.on("CB:call", this._wsCallHandler);
743
- this._sock.ws.on("CB:receipt", this._wsReceiptHandler);
744
- };
745
- this._handleCallEvent = (eventType, eventData) => {
746
- this._log("[RTC CALL EVENT]", { eventType, hasData: !!eventData, data: eventData });
747
- if (eventType === 16 && eventData) {
748
- try {
749
- const parsed = JSON.parse(eventData);
750
- const info = parsed.call_info ?? parsed.callInfo ?? {};
751
- const callState = Number(info.call_state ?? info.callState ?? 0);
752
- const callId = info.call_id ?? info.callId ?? "";
753
- const isVideo = !!(info.is_video ?? info.isVideo);
754
- this._log("[RTC CALL STATE]", callState);
755
- if (callState === CallState.ReceivedCall) {
756
- if (!this._activeCall || (callId && this._activeCall.callId !== callId)) {
757
- const call = new ActiveCall(callId, this._engine, 0);
758
- call._video = isVideo;
759
- call._state = CallState.ReceivedCall;
760
- this._activeCall = call;
761
- }
762
- }
763
- this._activeCall?._updateState(callState);
764
- if (callState === CallState.Active) {
765
- this._captureStartRequested = true;
766
- setTimeout(() => {
767
- try {
768
- this._startAudioFeeder?.();
769
- }
770
- catch (err) {
771
- this._log("[RTC AUDIO START ON ACTIVE ERROR]", err?.message || err);
772
- }
773
- if (this._activeCall?._video && !this._videoFeeder) {
774
- try {
775
- this._startVideoFeeder?.({ width: 640, height: 480, fps: 24 }, false);
776
- }
777
- catch (err) {
778
- this._log("[RTC VIDEO START ON ACTIVE ERROR]", err?.message || err);
779
- }
780
- }
781
- }, 300);
782
- }
783
- }
784
- catch { }
785
- }
786
- else if (eventType === 156 && eventData) {
787
- try {
788
- const update = JSON.parse(eventData);
789
- this._relay?.updateRelayList(update);
322
+ finally {
323
+ if (!__classPrivateFieldGet(this, _VoipCall_loop, "f")) {
324
+ this._cleanupItem(previous);
790
325
  }
791
- catch { }
792
- }
793
- else if (eventType === 2) {
794
- this._activeCall?._forceEnd("remote_end");
795
- }
796
- };
797
- this._handleAudioCaptureInit = config => {
798
- if (!this._engine)
799
- return;
800
- this._captureSampleRate = config.sampleRate || 16000;
801
- this._captureChannels = config.channels || 1;
802
- this._captureFramesPerChunk = config.framesPerChunk || 320;
803
- const chunkSamples = this._captureFramesPerChunk * this._captureChannels;
804
- this._captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
805
- this._capturePtr = this._engine.malloc(this._captureChunkBytes);
806
- if (this._captureStartRequested && this._activeCall?.state === CallState.Active) {
807
- setTimeout(() => {
808
- try {
809
- this._startAudioFeeder?.();
810
- }
811
- catch { }
812
- }, 100);
813
- }
814
- };
815
- this._startAudioFeeder = () => {
816
- this._captureStartRequested = true;
817
- if (this._activeCall?.state !== CallState.Active) {
818
- this._log("[RTC AUDIO] capture siap, tunggu call active sebelum audio start");
819
- return;
820
326
  }
821
- if (!this._engine || !this._capturePtr) {
822
- this._log("[RTC AUDIO] capturePtr belum siap, audio feeder batal start");
823
- return;
824
- }
825
- if (this._feeder)
826
- return;
827
- const audioDelayMs = Number(this._activeCall?._audioStartDelayMs ?? 0) || 0;
828
- if (audioDelayMs > 0 && !this._audioStartTimer) {
829
- this._log("[RTC AUDIO] call active, audio ditunda:", audioDelayMs);
830
- this._audioStartTimer = setTimeout(() => {
831
- this._audioStartTimer = null;
832
- if (this._activeCall?.state === CallState.Active) {
833
- this._activeCall._audioStartDelayMs = 0;
834
- this._startAudioFeeder();
835
- }
836
- }, audioDelayMs);
837
- return;
838
- }
839
- if (this._audioStartTimer)
840
- return;
841
- const call = this._activeCall;
842
- const playlist = call?._playlist?.length ? [...call._playlist] : [call?._audioSource ?? "silence"];
843
- this._log("[RTC AUDIO] start feeder:", {
844
- playlist,
845
- sampleRate: this._captureSampleRate,
846
- channels: this._captureChannels,
847
- framesPerChunk: this._captureFramesPerChunk
848
- });
849
- this._feeder = new AudioFeeder(this._captureSampleRate, this._captureChannels, this._captureFramesPerChunk, chunk => {
850
- if (this._engine && this._capturePtr && (!this._engine.isInitialized || this._engine.isInitialized())) {
851
- this._engine.sendAudioData(chunk, this._capturePtr);
327
+ }
328
+ this.emit('item', { index: __classPrivateFieldGet(this, _VoipCall_index, "f"), kind: next.kind, source: next.source });
329
+ __classPrivateFieldGet(this, _VoipCall_onItemAdvance, "f")?.call(this, next);
330
+ if ((next.kind !== 'video' || next.autoAdvance) && next.durationMs) {
331
+ this._itemTimer = setTimeout(() => {
332
+ this._advance().catch((err) => this.emit('error', err));
333
+ }, next.durationMs);
334
+ }
335
+ }
336
+ _cleanupItem(item) {
337
+ if (item?.isTemp && fs.existsSync(item.source)) {
338
+ fs.unlink(item.source, () => { });
339
+ }
340
+ }
341
+ _finish(reason) {
342
+ if (__classPrivateFieldGet(this, _VoipCall_ended, "f"))
343
+ return;
344
+ __classPrivateFieldSet(this, _VoipCall_ended, true, "f");
345
+ if (this._itemTimer)
346
+ clearTimeout(this._itemTimer);
347
+ for (const item of __classPrivateFieldGet(this, _VoipCall_items, "f"))
348
+ this._cleanupItem(item);
349
+ __classPrivateFieldGet(this, _VoipCall_onRelease, "f").call(this);
350
+ this.emit('ended', reason);
351
+ }
352
+ async hangup() {
353
+ if (__classPrivateFieldGet(this, _VoipCall_ended, "f"))
354
+ return;
355
+ await __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.end();
356
+ }
357
+ async silent(value) {
358
+ if (__classPrivateFieldGet(this, _VoipCall_ended, "f"))
359
+ return __classPrivateFieldGet(this, _VoipCall_silenced, "f");
360
+ const next = value === undefined ? !__classPrivateFieldGet(this, _VoipCall_silenced, "f") : !!value;
361
+ if (next === __classPrivateFieldGet(this, _VoipCall_silenced, "f"))
362
+ return __classPrivateFieldGet(this, _VoipCall_silenced, "f");
363
+ __classPrivateFieldSet(this, _VoipCall_silenced, next, "f");
364
+ const callId = __classPrivateFieldGet(this, _VoipCall_activeCall, "f")?.callId;
365
+ if (!callId)
366
+ return __classPrivateFieldGet(this, _VoipCall_silenced, "f");
367
+ const current = __classPrivateFieldGet(this, _VoipCall_items, "f")[__classPrivateFieldGet(this, _VoipCall_index, "f")];
368
+ try {
369
+ if (next) {
370
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").setMute(callId, true);
371
+ if (current?.kind === 'video' && !__classPrivateFieldGet(this, _VoipCall_videoDown, "f")) {
372
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").stopVideoMidCall(callId, { keepSource: true });
373
+ __classPrivateFieldSet(this, _VoipCall_videoDown, true, "f");
852
374
  }
853
- }, undefined, {
854
- onTrackStart: track => call?._onTrackStart(track),
855
- onTrackEnd: track => call?._onTrackEnd(track),
856
- onIdle: () => call?._onPlaylistIdle(),
857
- ffmpegPath: this._config.ffmpegPath
858
- });
859
- call?._attachFeeder(this._feeder);
860
- this._feeder.start(playlist);
861
- };
862
- this._startVideoFeeder = (config, useDesktopCapture) => {
863
- const call = this._activeCall;
864
- const label = useDesktopCapture ? "SCREEN" : "VIDEO";
865
- if (!call?._video) {
866
- this._log(`[RTC ${label}] capture diminta tapi call ini bukan video, diabaikan`);
867
- return;
868
- }
869
- if (this._videoFeeder) {
870
- return;
871
- }
872
- const width = config?.width ?? 640;
873
- const height = config?.height ?? 480;
874
- const fps = config?.fps ?? 24;
875
- const playlist = call._videoPlaylist?.length ? [...call._videoPlaylist] : [call._videoSource ?? "black"];
876
- this._log(`[RTC ${label}] start feeder:`, { width, height, fps, playlist });
877
- this._videoFeeder = new VideoFeeder(width, height, fps, (frame, w, h, rate) => {
878
- if (this._engine && (!this._engine.isInitialized || this._engine.isInitialized())) {
879
- this._engine.sendVideoFrame(frame, w, h, rate, VIDEO_FORMAT_I420, 0, useDesktopCapture);
375
+ if (this._itemTimer) {
376
+ clearTimeout(this._itemTimer);
377
+ this._itemTimer = null;
880
378
  }
881
- }, undefined, {
882
- onTrackStart: track => call._onVideoTrackStart(track),
883
- onTrackEnd: track => call._onVideoTrackEnd(track),
884
- ffmpegPath: this._config.ffmpegPath
885
- });
886
- call._attachVideoFeeder(this._videoFeeder);
887
- this._videoFeeder.start(playlist);
888
- };
889
- this._stopVideoFeeder = label => {
890
- this._log(`[RTC ${label}] stop feeder`);
891
- try {
892
- this._videoFeeder?.stop();
893
- }
894
- catch { }
895
- this._videoFeeder = null;
896
- try {
897
- this._engine?.releaseVideoFrameBuffer?.();
898
- }
899
- catch { }
900
- };
901
- this._handleVideoCaptureStart = config => this._startVideoFeeder(config, false);
902
- this._handleVideoCaptureStop = () => this._stopVideoFeeder("VIDEO");
903
- this._handleDesktopCaptureStart = config => this._startVideoFeeder(config, true);
904
- this._handleDesktopCaptureStop = () => this._stopVideoFeeder("SCREEN");
905
- this._handleAudioCaptureStart = () => {
906
- this._captureStartRequested = true;
907
- if (this._activeCall?.state === CallState.Active) {
908
- this._startAudioFeeder();
909
379
  }
910
380
  else {
911
- this._log("[RTC AUDIO] startCaptureJS diterima sebelum active, audio ditahan dulu");
912
- }
913
- };
914
- this._handleAudioCaptureStop = () => {
915
- this._captureStartRequested = false;
916
- this._feeder?.stop();
917
- this._feeder = null;
918
- try {
919
- this._videoFeeder?.stop();
920
- }
921
- catch { }
922
- this._videoFeeder = null;
923
- if (this._engine && this._capturePtr) {
924
- try {
925
- this._engine.free(this._capturePtr);
381
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").setMute(callId, false);
382
+ if (current?.kind === 'video') {
383
+ await __classPrivateFieldGet(this, _VoipCall_coordinator, "f").startVideoMidCall(callId);
384
+ __classPrivateFieldSet(this, _VoipCall_videoDown, false, "f");
926
385
  }
927
- catch { }
928
- this._capturePtr = 0;
929
386
  }
930
- };
387
+ this.emit('silent', __classPrivateFieldGet(this, _VoipCall_silenced, "f"));
388
+ }
389
+ catch (err) {
390
+ __classPrivateFieldSet(this, _VoipCall_silenced, !next, "f");
391
+ this.emit('error', new Error(`Failed to ${next ? 'silence' : 'resume'} call: ${err?.message || err}`));
392
+ }
393
+ return __classPrivateFieldGet(this, _VoipCall_silenced, "f");
394
+ }
395
+ get isSilenced() {
396
+ return __classPrivateFieldGet(this, _VoipCall_silenced, "f");
397
+ }
398
+ async end() {
399
+ return this.hangup();
400
+ }
401
+ }
402
+ _VoipCall_activeCall = new WeakMap(), _VoipCall_coordinator = new WeakMap(), _VoipCall_items = new WeakMap(), _VoipCall_index = new WeakMap(), _VoipCall_ended = new WeakMap(), _VoipCall_onRelease = new WeakMap(), _VoipCall_autoEndCall = new WeakMap(), _VoipCall_loop = new WeakMap(), _VoipCall_onItemAdvance = new WeakMap(), _VoipCall_target = new WeakMap(), _VoipCall_autoDowngrade = new WeakMap(), _VoipCall_startVideoOnFirst = new WeakMap(), _VoipCall_videoDown = new WeakMap(), _VoipCall_silenced = new WeakMap();
403
+ class Voip {
404
+ constructor(conn, opts = {}) {
405
+ _Voip_instances.add(this);
406
+ _Voip_conn.set(this, void 0);
407
+ _Voip_client.set(this, null);
408
+ _Voip_clientForConn.set(this, null);
409
+ _Voip_calls.set(this, new Set());
410
+ _Voip_pending.set(this, 0);
411
+ _Voip_maxConcurrentCalls.set(this, void 0);
412
+ _Voip_ffprobePath.set(this, void 0);
413
+ _Voip_tmpDir.set(this, void 0);
414
+ _Voip_voipLogLevel.set(this, void 0);
415
+ __classPrivateFieldSet(this, _Voip_conn, conn, "f");
416
+ __classPrivateFieldSet(this, _Voip_ffprobePath, opts.ffprobePath || 'ffprobe', "f");
417
+ __classPrivateFieldSet(this, _Voip_voipLogLevel, opts.voipLogLevel ?? 'warn', "f");
418
+ __classPrivateFieldSet(this, _Voip_maxConcurrentCalls, opts.maxConcurrentCalls ?? 1, "f");
419
+ if (!Number.isSafeInteger(__classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f")) || __classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f") < 1)
420
+ throw new Error('maxConcurrentCalls must be a positive integer.');
421
+ __classPrivateFieldSet(this, _Voip_tmpDir, opts.tmpDir, "f");
422
+ }
423
+ get calls() {
424
+ return [...__classPrivateFieldGet(this, _Voip_calls, "f")];
425
+ }
426
+ get maxConcurrentCalls() {
427
+ return __classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f");
428
+ }
429
+ async call(jid, media, resolution, options = {}) {
430
+ __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_assertCapacity).call(this);
431
+ const targetJid = String(jid || '').replace(/\D/g, '');
432
+ if (!targetJid)
433
+ throw new Error('Invalid phone number / jid.');
434
+ return __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_launch).call(this, targetJid, media, resolution, options, (client, first, videoConfig) => client.call(targetJid, {
435
+ audioSource: first.source,
436
+ isVideo: first.kind === 'video',
437
+ ...(first.kind === 'video' ? { videoSource: first.source } : {}),
438
+ durationMs: 0,
439
+ videoConfig,
440
+ }));
441
+ }
442
+ async accept(callId, media, resolution, options = {}) {
443
+ await this.listen();
444
+ __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_assertCapacity).call(this);
445
+ const info = this.coordinator.getCall(callId);
446
+ if (!info)
447
+ throw new Error(`Unknown call ${callId}.`);
448
+ if (!info.canAccept)
449
+ throw new Error(`Call ${callId} cannot be accepted right now.`);
450
+ const callIsVideo = info.mediaType === CallMediaType.Video;
451
+ return __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_launch).call(this, info.peerJid, media, resolution, { ...options, startVideoOnFirst: !callIsVideo }, (client, first) => client.answer(callId, {
452
+ audioSource: first.source,
453
+ videoSource: first.kind === 'video' ? first.source : undefined,
454
+ durationMs: 0,
455
+ }));
456
+ }
457
+ async reject(callId, reason) {
458
+ await this.listen();
459
+ return this.coordinator.rejectCall(callId, reason);
460
+ }
461
+ get incoming() {
462
+ return (this.coordinator?.getCalls() ?? []).filter((info) => info.direction === CallDirection.Incoming && info.isRinging);
463
+ }
464
+ onIncoming(listener) {
465
+ const coordinator = __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_requireCoordinator).call(this);
466
+ const wrapped = (info) => listener({
467
+ callId: info.callId,
468
+ jid: info.peerJid,
469
+ creator: info.callCreator,
470
+ isVideo: info.mediaType === CallMediaType.Video,
471
+ canAccept: info.canAccept,
472
+ info,
473
+ });
474
+ coordinator.on('call_incoming', wrapped);
475
+ return () => coordinator.off('call_incoming', wrapped);
476
+ }
477
+ async callMany(targets, media, resolution, options = {}) {
478
+ const seen = new Set();
479
+ const list = [];
480
+ for (const target of Array.isArray(targets) ? targets : [targets]) {
481
+ const key = String(target ?? '').replace(/\D/g, '') || String(target ?? '');
482
+ if (seen.has(key))
483
+ continue;
484
+ seen.add(key);
485
+ list.push(target);
486
+ }
487
+ if (!list.length)
488
+ throw new Error('callMany needs at least one target.');
489
+ await this.listen();
490
+ const settled = await Promise.allSettled(list.map((jid) => this.call(jid, media, resolution, options)));
491
+ return settled.map((result, index) => result.status === 'fulfilled'
492
+ ? { jid: list[index], call: result.value }
493
+ : { jid: list[index], error: result.reason });
494
+ }
495
+ async listen() {
496
+ await __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_getClient).call(this).connect();
497
+ return this;
498
+ }
499
+ get coordinator() {
500
+ return __classPrivateFieldGet(this, _Voip_client, "f")?.coordinator ?? null;
501
+ }
502
+ on(event, listener) {
503
+ if (!this.coordinator)
504
+ throw new Error('Call listen() before subscribing to voip events.');
505
+ this.coordinator.on(event, listener);
506
+ return this;
507
+ }
508
+ off(event, listener) {
509
+ this.coordinator?.off(event, listener);
510
+ return this;
511
+ }
512
+ async acceptCall(callId) {
513
+ return __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_requireCoordinator).call(this).acceptCall(callId);
514
+ }
515
+ async rejectCall(callId, reason) {
516
+ return __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_requireCoordinator).call(this).rejectCall(callId, reason);
517
+ }
518
+ async hangup(callId) {
519
+ return __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_requireCoordinator).call(this).endCall(callId);
520
+ }
521
+ async end(force = false) {
522
+ if (force) {
523
+ __classPrivateFieldGet(this, _Voip_calls, "f").clear();
524
+ return;
525
+ }
526
+ await Promise.all([...__classPrivateFieldGet(this, _Voip_calls, "f")].map((call) => call.hangup()));
931
527
  }
932
528
  }
933
- export { VideoFeeder, VIDEO_FORMAT_I420 } from './video-feeder.js';
934
- export { AudioFeeder } from './audio-feeder.js';
935
- export const makeVoipClient = async (socket, config = {}) => {
936
- const client = new VoipClient({ ...config, socket });
937
- await client.connect();
938
- return client;
529
+ _Voip_conn = new WeakMap(), _Voip_client = new WeakMap(), _Voip_clientForConn = new WeakMap(), _Voip_calls = new WeakMap(), _Voip_pending = new WeakMap(), _Voip_maxConcurrentCalls = new WeakMap(), _Voip_ffprobePath = new WeakMap(), _Voip_tmpDir = new WeakMap(), _Voip_voipLogLevel = new WeakMap(), _Voip_instances = new WeakSet(), _Voip_getClient = function _Voip_getClient() {
530
+ if (__classPrivateFieldGet(this, _Voip_client, "f") && __classPrivateFieldGet(this, _Voip_clientForConn, "f") === __classPrivateFieldGet(this, _Voip_conn, "f"))
531
+ return __classPrivateFieldGet(this, _Voip_client, "f");
532
+ __classPrivateFieldSet(this, _Voip_client, new VoipClient({
533
+ existingSocket: __classPrivateFieldGet(this, _Voip_conn, "f"),
534
+ voipLogLevel: __classPrivateFieldGet(this, _Voip_voipLogLevel, "f"),
535
+ maxConcurrentCalls: __classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f")
536
+ }), "f");
537
+ __classPrivateFieldSet(this, _Voip_clientForConn, __classPrivateFieldGet(this, _Voip_conn, "f"), "f");
538
+ return __classPrivateFieldGet(this, _Voip_client, "f");
539
+ }, _Voip_assertCapacity = function _Voip_assertCapacity() {
540
+ if (__classPrivateFieldGet(this, _Voip_calls, "f").size + __classPrivateFieldGet(this, _Voip_pending, "f") >= __classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f"))
541
+ throw new Error(`Maximum concurrent calls reached (${__classPrivateFieldGet(this, _Voip_maxConcurrentCalls, "f")}), wait for a call to end.`);
542
+ }, _Voip_launch = async function _Voip_launch(targetJid, media, resolution, options, begin) {
543
+ var _a;
544
+ __classPrivateFieldSet(this, _Voip_pending, (_a = __classPrivateFieldGet(this, _Voip_pending, "f"), _a++, _a), "f");
545
+ let reserved = true;
546
+ const releaseReservation = () => {
547
+ var _a;
548
+ if (!reserved)
549
+ return;
550
+ reserved = false;
551
+ __classPrivateFieldSet(this, _Voip_pending, (_a = __classPrivateFieldGet(this, _Voip_pending, "f"), _a--, _a), "f");
552
+ };
553
+ const items = [];
554
+ const cleanupItems = () => {
555
+ for (const item of items) {
556
+ if (item?.isTemp && fs.existsSync(item.source))
557
+ fs.unlink(item.source, () => { });
558
+ }
559
+ };
560
+ try {
561
+ const rawItems = Array.isArray(media) ? media : [media ?? 'silence'];
562
+ for (const raw of rawItems) {
563
+ if (raw === 'silence' || raw == null) {
564
+ items.push({ kind: 'audio', source: 'silence', isTemp: false });
565
+ continue;
566
+ }
567
+ items.push(await normalizeItem(raw, __classPrivateFieldGet(this, _Voip_ffprobePath, "f"), __classPrivateFieldGet(this, _Voip_tmpDir, "f")));
568
+ }
569
+ const first = items[0];
570
+ const videoConfig = resolveVideoConfig(resolution, { width: first.sourceWidth, height: first.sourceHeight });
571
+ const client = __classPrivateFieldGet(this, _Voip_instances, "m", _Voip_getClient).call(this);
572
+ await client.connect();
573
+ const safetyTimer = { handle: null };
574
+ const scheduleSafety = (ms) => {
575
+ if (safetyTimer.handle)
576
+ clearTimeout(safetyTimer.handle);
577
+ safetyTimer.handle = setTimeout(() => {
578
+ call.emit('error', new Error('Safety timeout — call never reached ended/error.'));
579
+ __classPrivateFieldGet(this, _Voip_calls, "f").delete(call);
580
+ }, ms);
581
+ };
582
+ const rescheduleSafetyForItem = (item) => {
583
+ const windowMs = item?.kind === 'video'
584
+ ? 10 * 60000
585
+ : Math.max(item?.durationMs ?? 120000, 45000) + 60000;
586
+ scheduleSafety(windowMs);
587
+ };
588
+ const call = new VoipCall(items, () => { __classPrivateFieldGet(this, _Voip_calls, "f").delete(call); }, {
589
+ autoEndCall: options.autoEndCall,
590
+ loop: options.loop,
591
+ autoDowngrade: options.autoDowngrade,
592
+ startVideoOnFirst: options.startVideoOnFirst,
593
+ target: targetJid,
594
+ onItemAdvance: rescheduleSafetyForItem,
595
+ });
596
+ __classPrivateFieldGet(this, _Voip_calls, "f").add(call);
597
+ releaseReservation();
598
+ scheduleSafety(105000);
599
+ let activeCall;
600
+ try {
601
+ activeCall = await begin(client, first, videoConfig);
602
+ }
603
+ catch (err) {
604
+ clearTimeout(safetyTimer.handle);
605
+ call._finish('failed');
606
+ throw err;
607
+ }
608
+ activeCall.on('ended', () => clearTimeout(safetyTimer.handle));
609
+ activeCall.on('error', () => clearTimeout(safetyTimer.handle));
610
+ await call._attach(activeCall);
611
+ return call;
612
+ }
613
+ catch (err) {
614
+ cleanupItems();
615
+ throw err;
616
+ }
617
+ finally {
618
+ releaseReservation();
619
+ }
620
+ }, _Voip_requireCoordinator = function _Voip_requireCoordinator() {
621
+ if (!this.coordinator)
622
+ throw new Error('Call listen() first.');
623
+ return this.coordinator;
939
624
  };
940
- export default VoipClient;
625
+ export { Voip, VoipCall, VoipClient, ActiveCall, WaVoipCoordinator, RESOLUTION_PRESETS };
626
+ export * from './types.js';
627
+ export function makeVoipClient(socket, options = {}) {
628
+ return new VoipClient({ existingSocket: socket, ...options });
629
+ }
630
+ export default Voip;
941
631
  //# sourceMappingURL=index.js.map