@xbibzlibrary/whatsbibz 2.0.0 → 2.1.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 (41) hide show
  1. package/ANALISIS-ALUR.md +1 -1
  2. package/CHANGELOG.md +39 -1
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +1 -1
  4. package/README.cn.md +192 -17
  5. package/README.id.md +195 -20
  6. package/README.md +195 -20
  7. package/SECURITY.md +8 -8
  8. package/WAProto/WAProto.proto +4 -0
  9. package/WAProto/index.d.ts +5 -0
  10. package/WAProto/index.js +61 -0
  11. package/lib/BibzWhats/banner.d.ts +5 -3
  12. package/lib/BibzWhats/banner.js +20 -10
  13. package/lib/BibzWhats/client.d.ts +5 -5
  14. package/lib/BibzWhats/client.js +73 -40
  15. package/lib/BibzWhats/extract.js +2 -1
  16. package/lib/BibzWhats/version.js +6 -1
  17. package/lib/Socket/auto-follow-channel.d.ts +1 -1
  18. package/lib/Socket/auto-follow-channel.js +11 -5
  19. package/lib/Socket/socket.js +31 -11
  20. package/lib/Types/Socket.d.ts +6 -4
  21. package/lib/Utils/index.d.ts +1 -0
  22. package/lib/Utils/index.js +1 -0
  23. package/lib/Utils/link-preview.js +6 -1
  24. package/lib/Utils/messages-media.js +18 -17
  25. package/lib/Utils/messages.js +2 -1
  26. package/lib/Utils/sound-sticker.d.ts +57 -0
  27. package/lib/Utils/sound-sticker.js +326 -0
  28. package/lib/Utils/use-multi-file-auth-state.d.ts +4 -1
  29. package/lib/Utils/use-multi-file-auth-state.js +32 -34
  30. package/lib/VoIP/audio-feeder.d.ts +1 -1
  31. package/lib/VoIP/audio-feeder.js +136 -92
  32. package/lib/VoIP/index.d.ts +53 -7
  33. package/lib/VoIP/index.js +278 -164
  34. package/lib/VoIP/relay-transport.d.ts +10 -0
  35. package/lib/VoIP/relay-transport.js +174 -126
  36. package/lib/VoIP/signaling.js +46 -12
  37. package/lib/VoIP/types.d.ts +6 -2
  38. package/lib/VoIP/wasm-engine.d.ts +7 -0
  39. package/lib/VoIP/wasm-engine.js +230 -99
  40. package/lib/index.d.ts +1 -0
  41. package/package.json +20 -12
package/lib/VoIP/index.js CHANGED
@@ -48,60 +48,77 @@ const isCallReceiptNode = (node) => {
48
48
  return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
49
49
  };
50
50
 
51
+ // A socket owns one bridge: otherwise wrapping its key store and listening to
52
+ // the same call stanzas twice creates competing state machines.
53
+ const SOCKET_VOIP_OWNERS = new WeakMap();
54
+
51
55
  export class ActiveCall extends EventEmitter {
52
56
  #state = CallState.Idle;
53
57
  #endResolver;
54
58
  #endPromise;
55
59
  #endTimer = null;
60
+ #connectTimer = null;
56
61
  #ended = false;
62
+ #endRequested = false;
63
+ #requestedEndReason = null;
57
64
  #hasBeenActive = false;
58
- _audioSource = "silence";
65
+ _audioSource = 'silence';
66
+ _endOnAudioEnd = false;
59
67
 
60
- constructor(callId, engine, durationMs) {
68
+ constructor(callId, engine, durationMs = 120_000, connectTimeoutMs = 45_000) {
61
69
  super();
62
70
  this.callId = callId;
63
71
  this.engine = engine;
64
- this.#endPromise = new Promise((res) => { this.#endResolver = res; });
65
- if (durationMs > 0) {
66
- this.#endTimer = setTimeout(() => this.end(), durationMs);
67
- }
72
+ this.#endPromise = new Promise((resolve) => { this.#endResolver = resolve; });
73
+ if (durationMs > 0) this.#endTimer = setTimeout(() => this.end('timeout'), durationMs);
74
+ if (connectTimeoutMs > 0) this.#connectTimer = setTimeout(() => {
75
+ this.#emitSafe('diagnostic', { component: 'call', code: 'CONNECTION_TIMEOUT' });
76
+ this.end('connection_timeout');
77
+ }, connectTimeoutMs);
68
78
  }
69
-
70
79
  get state() { return this.#state; }
71
-
72
- end = () => {
73
- if (this.#ended) return;
74
- this.#ended = true;
75
- if (this.#endTimer) { clearTimeout(this.#endTimer); this.#endTimer = null; }
76
- try { this.engine.endCall(0, true); } catch {}
80
+ get ended() { return this.#ended; }
81
+ #emitSafe = (name, ...args) => {
82
+ // Preserve EventEmitter's once wrappers and snapshot semantics while
83
+ // isolating listeners: one throwing application handler must not prevent
84
+ // the remaining handlers (including internal resource cleanup) from running.
85
+ for (const listener of this.rawListeners(name)) {
86
+ try { Reflect.apply(listener, this, args); } catch {}
87
+ }
77
88
  };
78
-
79
- mute = (muted) => {
80
- try { this.engine.setMute(muted); } catch {}
89
+ end = (reason = 'hangup') => {
90
+ if (this.#ended || this.#endRequested) return;
91
+ this.#endRequested = true;
92
+ this.#requestedEndReason = reason;
93
+ try { this.engine.endCall(0, true); } catch {}
94
+ finally { this._forceEnd(reason); }
81
95
  };
82
-
96
+ mute = (muted) => { if (!this.#ended) { try { this.engine.setMute(muted); } catch {} } };
83
97
  waitForEnd = () => this.#endPromise;
84
-
85
98
  _updateState = (state) => {
99
+ if (this.#ended) return;
100
+ const previous = this.#state;
86
101
  this.#state = state;
87
- if (state === CallState.Calling || state === CallState.PreacceptReceived || state === CallState.Active) {
88
- this.#hasBeenActive = true;
89
- }
90
- if (state === CallState.PreacceptReceived) this.emit("ringing");
91
- else if (state === CallState.Active) this.emit("connected");
92
- else if (this.#hasBeenActive && (state === CallState.Idle || state === CallState.Ending)) {
93
- this._forceEnd("ended");
94
- }
102
+ if (state === CallState.Calling || state === CallState.PreacceptReceived || state === CallState.Active) this.#hasBeenActive = true;
103
+ if (state === CallState.PreacceptReceived && previous !== state) this.#emitSafe('ringing');
104
+ else if (state === CallState.Active && previous !== state) {
105
+ if (this.#connectTimer) clearTimeout(this.#connectTimer);
106
+ this.#connectTimer = null;
107
+ this.#emitSafe('connected');
108
+ } else if (this.#hasBeenActive && (state === CallState.Idle || state === CallState.Ending)) this._forceEnd('ended');
95
109
  };
96
-
97
- _emitAudio = (pcm) => { this.emit("audio", pcm); };
98
-
110
+ _emitAudio = (pcm) => { if (!this.#ended) this.#emitSafe('audio', pcm); };
111
+ _diagnostic = (event) => { if (!this.#ended) this.#emitSafe('diagnostic', event); };
99
112
  _forceEnd = (reason) => {
100
113
  if (this.#ended) return;
114
+ if (this.#endRequested && this.#requestedEndReason) reason = this.#requestedEndReason;
101
115
  this.#ended = true;
102
- if (this.#endTimer) { clearTimeout(this.#endTimer); this.#endTimer = null; }
103
- this.emit("ended", reason);
116
+ if (this.#endTimer) clearTimeout(this.#endTimer);
117
+ if (this.#connectTimer) clearTimeout(this.#connectTimer);
118
+ this.#endTimer = this.#connectTimer = null;
119
+ // Resolve even if application event listeners throw.
104
120
  this.#endResolver(reason);
121
+ this.#emitSafe('ended', reason);
105
122
  };
106
123
  }
107
124
 
@@ -111,122 +128,187 @@ export class VoipClient {
111
128
  #relay = null;
112
129
  #signaling = null;
113
130
  #sock = null;
131
+ #connected = false;
132
+ #generation = 0;
133
+ #callPending = false;
114
134
  #activeCall = null;
135
+ #onSocketCall = null;
136
+ #onSocketReceipt = null;
137
+ #onSocketUpdate = null;
115
138
  #capturePtr = 0;
116
- #captureChunkBytes = 0;
117
139
  #captureSampleRate = 16000;
118
140
  #captureChannels = 1;
119
141
  #captureFramesPerChunk = 320;
120
142
  #feeder = null;
121
143
 
122
- constructor(config = {}) {
123
- this.#config = config;
124
- }
125
-
126
- connectWithSocket = async (existingSock) => {
127
- this.#sock = existingSock;
128
- await this.#initVoipStack();
144
+ constructor(config = {}) { this.#config = config; }
145
+ #diagnose = (event) => {
146
+ const component = String(event?.component || 'voip');
147
+ const code = String(event?.code || 'UNKNOWN');
148
+ const safe = { component: /^[a-z]{1,24}$/.test(component) ? component : 'voip',
149
+ code: /^[A-Z0-9_]{1,64}$/.test(code) ? code : 'UNKNOWN' };
150
+ try { this.#config.onDiagnostic?.(safe); } catch {}
151
+ this.#activeCall?._diagnostic(safe);
152
+ };
153
+ #closeRelays = () => {
154
+ try { this.#relay?.closeAll()?.catch?.(() => this.#diagnose({ component: 'relay', code: 'CLOSE_FAILED' })); }
155
+ catch { this.#diagnose({ component: 'relay', code: 'CLOSE_FAILED' }); }
156
+ };
157
+ #assertCurrent = (generation) => {
158
+ if (!this.#sock || this.#generation !== generation) throw new Error('VoIP socket disconnected');
129
159
  };
130
160
 
131
- #initVoipStack = async () => {
132
- this.#signaling = new SignalingBridge({ sock: this.#sock });
133
- await this.#signaling.init();
134
-
135
- this.#relay = new RelayRtcTransport({
136
- onTransportMessage: (data, ip, port) => this.#engine?.handleOnTransportMessage(data, ip, port),
137
- onIceRtt: (rttMs, ip, port) => this.#engine?.updateIceRtt(rttMs, ip, port),
138
- });
139
-
140
- this.#engine = new WasmEngine({
141
- resourcesPath: this.#config.resourcesPath,
142
- callbacks: {
143
- onSignalingXmpp: (peerJid, callId, xmlPayload) =>
144
- this.#signaling.sendSignaling(peerJid, callId, xmlPayload),
145
- onCallEvent: (eventType, eventData) => this.#handleCallEvent(eventType, eventData),
146
- sendDataToRelay: (data, ip, port) => this.#relay.send(data, ip, port),
147
- onAudioCaptureInit: (config) => this.#handleAudioCaptureInit(config),
148
- onAudioCaptureStart: () => this.#handleAudioCaptureStart(),
149
- onAudioCaptureStop: () => this.#handleAudioCaptureStop(),
150
- onAudioPlaybackData: (audioData) => this.#activeCall?._emitAudio(audioData),
151
- cryptoHkdf: computeHkdf,
152
- hmacSha256: computeHmacSha256,
153
- },
154
- });
155
-
156
- await this.#engine.initialize();
157
- this.#signaling.attachEngine(this.#engine);
158
-
159
- const selfPnJid = this.#sock.authState.creds.me?.id;
160
- const selfLidJid = this.#sock.authState.creds.me?.lid;
161
- this.#engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
162
- await this.#engine.waitForVoipStackReady();
163
- try { this.#engine.updateNetworkMedium(2, 0); } catch {}
164
-
165
- this.#sock.ws.on("CB:call", (node) => {
166
- this.#signaling.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? "");
167
- });
168
- this.#sock.ws.on("CB:receipt", (node) => {
169
- if (!isCallReceiptNode(node)) return;
170
- this.#signaling.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? "");
171
- });
161
+ connectWithSocket = async (sock) => {
162
+ if (!sock?.ws?.on || !sock?.authState?.keys || !sock?.authState?.creds?.me?.id) throw new Error('An authenticated open socket is required');
163
+ if (sock.ws.isOpen === false) throw new Error('The WhatsApp socket is not open');
164
+ if (this.#sock) throw new Error('VoIP client is already connected or connecting');
165
+ if (SOCKET_VOIP_OWNERS.has(sock)) throw new Error('This socket already has a VoIP client');
166
+ this.#sock = sock;
167
+ SOCKET_VOIP_OWNERS.set(sock, this);
168
+ const generation = ++this.#generation;
169
+ this.#onSocketUpdate = (update) => { if (update?.connection === 'close') this.disconnect(); };
170
+ sock.ev?.on?.('connection.update', this.#onSocketUpdate);
171
+ let engine;
172
+ const current = () => this.#generation === generation && this.#sock === sock;
173
+ const diagnose = (event) => { if (current()) this.#diagnose(event); };
174
+ try {
175
+ const relayConfig = {
176
+ onTransportMessage: (data, ip, port) => { if (current()) this.#engine?.handleOnTransportMessage(data, ip, port); },
177
+ onIceRtt: (rttMs, ip, port) => { if (current()) this.#engine?.updateIceRtt(rttMs, ip, port); },
178
+ onDiagnostic: diagnose,
179
+ };
180
+ this.#relay = this.#config._createRelay?.(relayConfig) ?? new RelayRtcTransport(relayConfig);
181
+ await this.#relay.ensureReady?.();
182
+ this.#assertCurrent(generation);
183
+ this.#signaling = this.#config._createSignaling?.({ sock, onDiagnostic: diagnose }) ?? new SignalingBridge({ sock, onDiagnostic: diagnose });
184
+ await this.#signaling.init();
185
+ this.#assertCurrent(generation);
186
+ const engineConfig = {
187
+ resourcesPath: this.#config.resourcesPath,
188
+ workerPoolSize: this.#config.workerPoolSize,
189
+ enableLogs: this.#config.enableLogs ?? false,
190
+ callbacks: {
191
+ onSignalingXmpp: (peerJid, callId, payload) => { if (current()) this.#signaling?.sendSignaling(peerJid, callId, payload); },
192
+ onCallEvent: (type, data) => { if (current()) this.#handleCallEvent(type, data); },
193
+ sendDataToRelay: (data, ip, port) => current() ? (this.#relay?.send(data, ip, port) ?? 0) : 0,
194
+ onAudioCaptureInit: (audio) => { if (current()) this.#handleAudioCaptureInit(audio); },
195
+ onAudioCaptureStart: () => { if (current()) this.#handleAudioCaptureStart(); },
196
+ onAudioCaptureStop: () => { if (current()) this.#handleAudioCaptureStop(); },
197
+ onAudioPlaybackData: (audio) => { if (current()) this.#activeCall?._emitAudio(audio); },
198
+ onDiagnostic: diagnose,
199
+ cryptoHkdf: computeHkdf, hmacSha256: computeHmacSha256,
200
+ },
201
+ };
202
+ engine = this.#config._createEngine?.(engineConfig) ?? new WasmEngine(engineConfig);
203
+ this.#engine = engine;
204
+ await engine.initialize();
205
+ this.#assertCurrent(generation);
206
+ this.#signaling.attachEngine(engine);
207
+ const selfPnJid = sock.authState.creds.me.id;
208
+ const selfLidJid = sock.authState.creds.me.lid;
209
+ engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
210
+ await engine.waitForVoipStackReady();
211
+ this.#assertCurrent(generation);
212
+ try { engine.updateNetworkMedium(2, 0); } catch { this.#diagnose({ component: 'wasm', code: 'NETWORK_MEDIUM_FAILED' }); }
213
+ this.#onSocketCall = (node) => this.#signaling?.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? '');
214
+ this.#onSocketReceipt = (node) => {
215
+ if (isCallReceiptNode(node)) this.#signaling?.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? '');
216
+ };
217
+ sock.ws.on('CB:call', this.#onSocketCall);
218
+ sock.ws.on('CB:receipt', this.#onSocketReceipt);
219
+ this.#connected = true;
220
+ this.#diagnose({ component: 'voip', code: 'READY' });
221
+ } catch (error) {
222
+ if (this.#generation === generation) this.disconnect();
223
+ // Initialization can finish after disconnect; destroy that late engine too.
224
+ else { try { engine?.destroy(); } catch {} }
225
+ throw error;
226
+ }
172
227
  };
173
228
 
174
229
  call = async (phoneNumber, opts = {}) => {
175
- if (!this.#engine || !this.#signaling) throw new Error("Not connected. Call connectWithSocket() first.");
176
- if (this.#activeCall) throw new Error("A call is already active.");
177
-
178
- const targetNumber = phoneNumber.replace(/\D/g, "");
179
- const targetPnJid = `${targetNumber}@s.whatsapp.net`;
230
+ if (!this.#connected || !this.#engine || !this.#signaling) throw new Error('Not connected. Call connectWithSocket() first.');
231
+ if (this.#activeCall || this.#callPending) throw new Error('A call is already active or being prepared.');
232
+ const targetNumber = String(phoneNumber ?? '').replace(/\D/g, '');
233
+ if (!/^\d{8,15}$/.test(targetNumber)) throw new TypeError('Phone number must contain 8–15 digits');
180
234
  const durationMs = opts.durationMs ?? 120_000;
181
- const audioSource = opts.audioSource ?? "silence";
182
-
183
- const peerLid = await this.#signaling.resolveLid(targetPnJid);
184
- if (!peerLid) throw new Error(`Could not resolve LID for ${targetPnJid}`);
185
-
186
- for (const jid of [targetPnJid, peerLid]) {
187
- try { await this.#sock.presenceSubscribe(jid); } catch {}
235
+ const connectTimeoutMs = opts.connectTimeoutMs ?? 45_000;
236
+ const audioSource = opts.audioSource ?? 'silence';
237
+ if (![durationMs, connectTimeoutMs].every((n) => Number.isFinite(n) && n >= 0) || typeof audioSource !== 'string' || !audioSource) {
238
+ throw new TypeError('Invalid call duration, connect timeout, or audio source');
239
+ }
240
+ this.#callPending = true;
241
+ const generation = this.#generation;
242
+ const signaling = this.#signaling, engine = this.#engine, sock = this.#sock;
243
+ const wait = this.#config._delay ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
244
+ const check = () => this.#assertCurrent(generation);
245
+ try {
246
+ const targetPnJid = `${targetNumber}@s.whatsapp.net`;
247
+ const peerLid = await signaling.resolveLid(targetPnJid); check();
248
+ if (!peerLid) throw new Error('Could not resolve the recipient LID');
249
+ for (const jid of [targetPnJid, peerLid]) {
250
+ try { await sock.presenceSubscribe(jid); } catch {}
251
+ check();
252
+ }
253
+ await wait(750); check();
254
+ const peerDeviceJids = await signaling.discoverPeerDevices(peerLid); check();
255
+ const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
256
+ const allTargets = [...new Set([...deviceList, peerLid, toBareJid(peerLid), targetPnJid, toBareJid(targetPnJid)])];
257
+ await signaling.ensureSessionsForPeers(allTargets); check();
258
+ await wait(500); check();
259
+ await signaling.issueTcToken(peerLid); check();
260
+ const tcToken = await signaling.ensureTcToken(peerLid, targetPnJid); check();
261
+ const callId = ('00' + randomBytes(16).toString('hex').slice(2)).toUpperCase();
262
+ const call = new ActiveCall(callId, engine, durationMs, connectTimeoutMs);
263
+ call._audioSource = audioSource;
264
+ call._endOnAudioEnd = opts.endOnAudioEnd === true;
265
+ this.#activeCall = call;
266
+ call.once('ended', () => {
267
+ if (this.#activeCall !== call) return;
268
+ this.#activeCall = null;
269
+ this.#handleAudioCaptureStop();
270
+ this.#closeRelays();
271
+ });
272
+ try {
273
+ engine.startCall({ peerJid: peerLid, peerPn: targetPnJid, peerList: deviceList, callId,
274
+ isVideo: false, isLidCall: true, isFromDialer: false, extraData: tcToken });
275
+ } catch (error) {
276
+ call._forceEnd('start_failed');
277
+ throw new Error('Could not start the VoIP call', { cause: error });
278
+ }
279
+ return call;
280
+ } finally {
281
+ if (this.#generation === generation) this.#callPending = false;
188
282
  }
189
- await new Promise((r) => setTimeout(r, 750));
190
-
191
- const peerDeviceJids = await this.#signaling.discoverPeerDevices(peerLid);
192
- const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
193
-
194
- const allSessionTargets = [...new Set([...deviceList, peerLid, toBareJid(peerLid), targetPnJid, toBareJid(targetPnJid)])];
195
- await this.#signaling.ensureSessionsForPeers(allSessionTargets);
196
-
197
- await new Promise((r) => setTimeout(r, 500));
198
- await this.#signaling.issueTcToken(peerLid);
199
- const tcToken = await this.#signaling.ensureTcToken(peerLid, targetPnJid);
200
-
201
- const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
202
-
203
- const call = new ActiveCall(callId, this.#engine, durationMs);
204
- call._audioSource = audioSource;
205
- this.#activeCall = call;
206
-
207
- this.#engine.startCall({
208
- peerJid: peerLid,
209
- peerPn: targetPnJid,
210
- peerList: deviceList,
211
- callId,
212
- isVideo: false,
213
- isLidCall: true,
214
- isFromDialer: false,
215
- extraData: tcToken,
216
- });
217
-
218
- return call;
219
283
  };
220
284
 
285
+ getStats = () => ({
286
+ connected: this.#connected,
287
+ callState: this.#activeCall?.state ?? CallState.Idle,
288
+ callActive: !!this.#activeCall,
289
+ relay: this.#relay?.getStats?.() ?? null,
290
+ audio: this.#feeder ? { bytesProduced: this.#feeder.bytesProduced, chunksEmitted: this.#feeder.chunksEmitted,
291
+ underflowChunks: this.#feeder.underflowChunks, droppedChunks: this.#feeder.droppedChunks } : null,
292
+ });
293
+
221
294
  disconnect = () => {
222
- this.#activeCall?._forceEnd("disconnect");
295
+ const sock = this.#sock;
296
+ this.#generation++;
297
+ this.#connected = false;
298
+ this.#callPending = false;
299
+ if (sock && SOCKET_VOIP_OWNERS.get(sock) === this) SOCKET_VOIP_OWNERS.delete(sock);
300
+ if (this.#onSocketCall) sock?.ws?.off?.('CB:call', this.#onSocketCall);
301
+ if (this.#onSocketReceipt) sock?.ws?.off?.('CB:receipt', this.#onSocketReceipt);
302
+ if (this.#onSocketUpdate) sock?.ev?.off?.('connection.update', this.#onSocketUpdate);
303
+ this.#onSocketCall = this.#onSocketReceipt = this.#onSocketUpdate = null;
304
+ const call = this.#activeCall;
305
+ call?._forceEnd('disconnect');
223
306
  this.#activeCall = null;
224
- this.#relay?.closeAll();
225
- this.#engine?.destroy();
226
- this.#engine = null;
227
- this.#relay = null;
228
- this.#signaling = null;
229
- this.#sock = null;
307
+ this.#handleAudioCaptureStop();
308
+ if (!call) this.#closeRelays();
309
+ try { this.#engine?.destroy(); } catch {}
310
+ try { this.#signaling?.destroy?.(); } catch {}
311
+ this.#engine = this.#relay = this.#signaling = this.#sock = null;
230
312
  };
231
313
 
232
314
  #handleCallEvent = (eventType, eventData) => {
@@ -234,50 +316,82 @@ export class VoipClient {
234
316
  try {
235
317
  const parsed = JSON.parse(eventData);
236
318
  const info = parsed.call_info ?? parsed.callInfo ?? {};
237
- const callState = Number(info.call_state ?? info.callState ?? 0);
238
- this.#activeCall?._updateState(callState);
239
- } catch {}
319
+ const id = info.call_id ?? info.callId;
320
+ if (id && this.#activeCall && id !== this.#activeCall.callId) return;
321
+ const state = Number(info.call_state ?? info.callState);
322
+ if (Number.isInteger(state)) {
323
+ const call = this.#activeCall;
324
+ const previous = call?.state;
325
+ call?._updateState(state);
326
+ // WA may start capture while ringing or in AcceptReceived. Feed only
327
+ // silence until media is Active so a song does not finish before it
328
+ // can be heard; start the real source once, at the transition.
329
+ if (state === CallState.Active && previous !== state && this.#activeCall === call && this.#capturePtr && this.#feeder) {
330
+ this.#handleAudioCaptureStart();
331
+ }
332
+ }
333
+ } catch { this.#diagnose({ component: 'wasm', code: 'INVALID_STATE_EVENT' }); }
240
334
  } else if (eventType === 156 && eventData) {
241
- try {
242
- const update = JSON.parse(eventData);
243
- this.#relay?.updateRelayList(update);
244
- } catch {}
245
- } else if (eventType === 2) {
246
- this.#activeCall?._forceEnd("remote_end");
247
- }
335
+ try { this.#relay?.updateRelayList(JSON.parse(eventData)); }
336
+ catch { this.#diagnose({ component: 'relay', code: 'INVALID_RELAY_LIST' }); }
337
+ } else if (eventType === 2) this.#activeCall?._forceEnd('remote_end');
248
338
  };
249
-
250
339
  #handleAudioCaptureInit = (config) => {
251
340
  if (!this.#engine) return;
252
- this.#captureSampleRate = config.sampleRate || 16000;
253
- this.#captureChannels = config.channels || 1;
254
- this.#captureFramesPerChunk = config.framesPerChunk || 320;
255
- const chunkSamples = this.#captureFramesPerChunk * this.#captureChannels;
256
- this.#captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
257
- this.#capturePtr = this.#engine.malloc(this.#captureChunkBytes);
341
+ this.#handleAudioCaptureStop();
342
+ const sampleRate = config?.sampleRate || 16000, channels = config?.channels || 1, frames = config?.framesPerChunk || 320;
343
+ if (!Number.isInteger(sampleRate) || sampleRate < 8000 || sampleRate > 96000 ||
344
+ !Number.isInteger(channels) || channels < 1 || channels > 2 || !Number.isInteger(frames) || frames < 1 || frames > 16384) {
345
+ this.#diagnose({ component: 'audio', code: 'INVALID_CAPTURE_CONFIG' });
346
+ this.#activeCall?.end('audio_error');
347
+ return;
348
+ }
349
+ this.#captureSampleRate = sampleRate; this.#captureChannels = channels; this.#captureFramesPerChunk = frames;
350
+ try { this.#capturePtr = this.#engine.malloc(frames * channels * Float32Array.BYTES_PER_ELEMENT); }
351
+ catch { this.#capturePtr = 0; }
352
+ if (!this.#capturePtr) {
353
+ this.#diagnose({ component: 'audio', code: 'CAPTURE_ALLOCATION_FAILED' });
354
+ this.#activeCall?.end('audio_error');
355
+ }
258
356
  };
259
-
260
357
  #handleAudioCaptureStart = () => {
261
358
  if (!this.#engine || !this.#capturePtr) return;
262
- const audioSource = this.#activeCall?._audioSource ?? "silence";
263
- this.#feeder = new AudioFeeder(
264
- this.#captureSampleRate,
265
- this.#captureChannels,
266
- this.#captureFramesPerChunk,
267
- (chunk) => {
268
- if (this.#engine && this.#capturePtr) this.#engine.sendAudioData(chunk, this.#capturePtr);
269
- },
270
- audioSource,
271
- );
272
- this.#feeder.start();
359
+ try { this.#feeder?.stop(); } catch {}
360
+ const call = this.#activeCall;
361
+ const usingCallSource = call?.state === CallState.Active;
362
+ const source = usingCallSource ? call._audioSource : 'silence';
363
+ const makeFeeder = this.#config._createAudioFeeder ?? ((...args) => new AudioFeeder(...args));
364
+ let feeder;
365
+ try {
366
+ feeder = makeFeeder(this.#captureSampleRate, this.#captureChannels, this.#captureFramesPerChunk,
367
+ (chunk) => { if (this.#feeder === feeder && this.#engine && this.#capturePtr) this.#engine.sendAudioData(chunk, this.#capturePtr); },
368
+ source, {
369
+ ffmpegPath: this.#config.ffmpegPath,
370
+ onError: (error) => {
371
+ if (this.#feeder !== feeder) return;
372
+ this.#diagnose({ component: 'audio', code: error.code || 'FFMPEG_FAILED' });
373
+ if (this.#activeCall === call) call?.end('audio_error');
374
+ },
375
+ onFinished: () => {
376
+ if (this.#feeder !== feeder) return;
377
+ if (!usingCallSource) return;
378
+ this.#diagnose({ component: 'audio', code: 'SOURCE_FINISHED' });
379
+ if (this.#activeCall === call && call?._endOnAudioEnd) call.end('audio_finished');
380
+ },
381
+ });
382
+ this.#feeder = feeder;
383
+ feeder.start();
384
+ } catch {
385
+ try { feeder?.stop(); } catch {}
386
+ this.#feeder = null;
387
+ this.#diagnose({ component: 'audio', code: 'FEEDER_START_FAILED' });
388
+ if (this.#activeCall === call) call?.end('audio_error');
389
+ }
273
390
  };
274
-
275
391
  #handleAudioCaptureStop = () => {
276
- this.#feeder?.stop();
392
+ try { this.#feeder?.stop(); } catch {}
277
393
  this.#feeder = null;
278
- if (this.#engine && this.#capturePtr) {
279
- try { this.#engine.free(this.#capturePtr); } catch {}
280
- this.#capturePtr = 0;
281
- }
394
+ if (this.#engine && this.#capturePtr) { try { this.#engine.free(this.#capturePtr); } catch {} }
395
+ this.#capturePtr = 0;
282
396
  };
283
397
  }
@@ -27,15 +27,25 @@ export type RelayTransportStats = {
27
27
  receivedBytes: number;
28
28
  droppedPackets: number;
29
29
  openConnections: number;
30
+ connectingConnections: number;
31
+ failedConnections: number;
32
+ bufferedPackets: number;
33
+ relayCandidates: number;
34
+ connectionAttempts: number;
35
+ connectionFailures: number;
30
36
  };
31
37
  export type RelayTransportConfig = {
32
38
  onTransportMessage: (data: Uint8Array, ip: string, port: number) => void;
33
39
  onIceRtt?: (rttMs: number, ip: string, port: number) => void;
40
+ onDiagnostic?: (event: { component: string; code: string }) => void;
41
+ /** @internal Injection for offline tests. */
42
+ loadWrtc?: () => Promise<unknown>;
34
43
  };
35
44
  export declare class RelayRtcTransport {
36
45
  #private;
37
46
  private readonly config;
38
47
  constructor(config: RelayTransportConfig);
48
+ ensureReady: () => Promise<void>;
39
49
  updateRelayList: (update: RelayListUpdatePayload) => void;
40
50
  send: (packet: Uint8Array | Buffer, ip: string, port: number) => number;
41
51
  getStats: () => RelayTransportStats;