@xbibzlibrary/whatsbibz 1.4.4 → 2.1.0

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 (70) hide show
  1. package/ANALISIS-ALUR.md +151 -0
  2. package/CHANGELOG.md +50 -2
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +123 -0
  4. package/README.cn.md +218 -33
  5. package/README.id.md +241 -33
  6. package/README.md +246 -33
  7. package/SECURITY.md +18 -6
  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 +17 -8
  14. package/lib/BibzWhats/client.js +175 -81
  15. package/lib/BibzWhats/extract.js +2 -1
  16. package/lib/BibzWhats/version.d.ts +2 -0
  17. package/lib/BibzWhats/version.js +23 -4
  18. package/lib/Defaults/index.d.ts +2 -0
  19. package/lib/Defaults/index.js +9 -1
  20. package/lib/Signal/libsignal.js +16 -0
  21. package/lib/Socket/auto-follow-channel.d.ts +38 -0
  22. package/lib/Socket/auto-follow-channel.js +198 -0
  23. package/lib/Socket/business.d.ts +2 -0
  24. package/lib/Socket/communities.d.ts +2 -0
  25. package/lib/Socket/index.d.ts +2 -0
  26. package/lib/Socket/index.js +6 -1
  27. package/lib/Socket/messages-recv.d.ts +2 -0
  28. package/lib/Socket/messages-recv.js +35 -31
  29. package/lib/Socket/messages-send.d.ts +2 -0
  30. package/lib/Socket/messages-send.js +73 -69
  31. package/lib/Socket/mex.d.ts +1 -1
  32. package/lib/Socket/mex.js +5 -3
  33. package/lib/Socket/newsletter-queries.d.ts +11 -0
  34. package/lib/Socket/newsletter-queries.js +36 -0
  35. package/lib/Socket/newsletter.js +30 -43
  36. package/lib/Socket/socket.js +117 -56
  37. package/lib/Types/Events.d.ts +14 -0
  38. package/lib/Types/Newsletter.d.ts +9 -2
  39. package/lib/Types/Newsletter.js +4 -2
  40. package/lib/Types/Socket.d.ts +16 -2
  41. package/lib/Utils/browser-utils.js +3 -2
  42. package/lib/Utils/crypto.js +2 -1
  43. package/lib/Utils/generics.d.ts +4 -4
  44. package/lib/Utils/generics.js +25 -60
  45. package/lib/Utils/index.d.ts +1 -0
  46. package/lib/Utils/index.js +1 -0
  47. package/lib/Utils/link-preview.js +6 -1
  48. package/lib/Utils/message-retry-manager.d.ts +2 -0
  49. package/lib/Utils/message-retry-manager.js +17 -0
  50. package/lib/Utils/messages-media.d.ts +7 -2
  51. package/lib/Utils/messages-media.js +61 -38
  52. package/lib/Utils/messages.js +2 -1
  53. package/lib/Utils/node-security-2026-10.d.ts +7 -0
  54. package/lib/Utils/node-security-2026-10.js +69 -50
  55. package/lib/Utils/sound-sticker.d.ts +50 -0
  56. package/lib/Utils/sound-sticker.js +311 -0
  57. package/lib/Utils/use-multi-file-auth-state.d.ts +5 -2
  58. package/lib/Utils/use-multi-file-auth-state.js +61 -36
  59. package/lib/VoIP/audio-feeder.d.ts +1 -1
  60. package/lib/VoIP/audio-feeder.js +136 -92
  61. package/lib/VoIP/index.d.ts +53 -7
  62. package/lib/VoIP/index.js +278 -164
  63. package/lib/VoIP/relay-transport.d.ts +10 -0
  64. package/lib/VoIP/relay-transport.js +174 -126
  65. package/lib/VoIP/signaling.js +46 -12
  66. package/lib/VoIP/types.d.ts +6 -2
  67. package/lib/VoIP/wasm-engine.d.ts +7 -0
  68. package/lib/VoIP/wasm-engine.js +230 -99
  69. package/lib/index.d.ts +1 -0
  70. package/package.json +23 -10
@@ -4,7 +4,7 @@ var _a;
4
4
  * WhatsApp VoIP WASM engine.
5
5
  *
6
6
  * Loads the WhatsApp Web VoIP WASM stack inside a Node.js `vm.Context`,
7
- * spawns a 20-thread `worker_threads` pool to mirror the browser's pthread
7
+ * spawns bounded `worker_threads` pools to mirror the browser's pthread
8
8
  * model, and exposes a callback-based JS bridge. Audio-only (no video).
9
9
  *
10
10
  * @author ShellTear
@@ -18,8 +18,12 @@ import { fileURLToPath } from "node:url";
18
18
  const __filename = fileURLToPath(import.meta.url);
19
19
  const __dirname = path.dirname(__filename);
20
20
  const CALL_WASM_AB_PROPS_JSON = process.env.CALL_WASM_AB_PROPS_JSON ?? "";
21
- const PTHREAD_POOL_SIZE = 20;
21
+ // Preserve the bundled loader's original pool size. Smaller pools can reduce
22
+ // memory use but have not been validated for live media and may deadlock.
23
+ const DEFAULT_PTHREAD_POOL_SIZE = 20;
22
24
  const VOIP_READY_TIMEOUT_MS = 15_000;
25
+ // --input-type is only valid for stdin/eval, not the file-backed workers.
26
+ const workerExecArgv = () => process.execArgv.filter((arg) => !arg.startsWith('--input-type'));
23
27
  const parseJsonObjectEnv = (raw) => {
24
28
  if (!raw)
25
29
  return {};
@@ -60,15 +64,18 @@ const resolveWorkerScriptPath = () => {
60
64
  const compiled = path.join(__dirname, "worker-bootstrap.js");
61
65
  return fs.existsSync(compiled) ? compiled : path.join(__dirname, "worker-bootstrap.mts");
62
66
  };
63
- class NodeWorkerMessagePort {
67
+ /** @internal Bridges a worker to its owning engine, not to other clients. */
68
+ export class NodeWorkerMessagePort {
64
69
  #listeners = new Map();
65
70
  #worker;
71
+ #onCallback;
66
72
  fullyConnected;
67
73
  name;
68
74
  workerID = 0;
69
75
  pthread_ptr = 0;
70
- constructor(worker, name = "WAWebVoipWebWasmWorker") {
76
+ constructor(worker, name = "WAWebVoipWebWasmWorker", onCallback = () => {}) {
71
77
  this.#worker = worker;
78
+ this.#onCallback = onCallback;
72
79
  this.name = name;
73
80
  this.fullyConnected = new Promise((resolve) => {
74
81
  const loadedHandler = (msg) => {
@@ -107,7 +114,7 @@ class NodeWorkerMessagePort {
107
114
  else
108
115
  this.#listeners.clear();
109
116
  };
110
- terminate = () => { this.#worker.terminate(); };
117
+ terminate = () => this.#worker.terminate();
111
118
  close = () => { };
112
119
  isWrappingVirtualMessagePort = () => false;
113
120
  getWorker = () => this.#worker;
@@ -173,6 +180,9 @@ class NodeWorkerMessagePort {
173
180
  if (data.eventDataJson !== undefined)
174
181
  listenerData.eventDataJson = data.eventDataJson;
175
182
  }
183
+ // Engine callbacks are scoped to the worker's owner. The legacy
184
+ // global observers are still notified separately for compatibility.
185
+ try { this.#onCallback(callbackName, listenerData); } catch {}
176
186
  WasmEngine.notifyGlobalCallbackListeners(callbackName, listenerData);
177
187
  return;
178
188
  }
@@ -193,7 +203,7 @@ class NodeWorkerMessagePort {
193
203
  }
194
204
  export class WasmEngine {
195
205
  static #globalCallbackListeners = new Map();
196
- static #globalCallbacksRegistered = false;
206
+ #callbackListeners = new Map();
197
207
  static registerGlobalCallbackListener = (callbackName, handler) => {
198
208
  const key = `callback:${callbackName}`;
199
209
  let set = _a.#globalCallbackListeners.get(key);
@@ -215,12 +225,19 @@ export class WasmEngine {
215
225
  }
216
226
  };
217
227
  #config;
228
+ #pthreadPoolSize;
218
229
  #instance = null;
219
230
  #initialized = false;
231
+ #initializing = false;
232
+ #cancelInitialization = null;
233
+ #generation = 0;
220
234
  #moduleRegistry = new Map();
221
235
  #vmContext = null;
236
+ #vmTimeouts = new Set();
237
+ #vmIntervals = new Set();
222
238
  #unusedWorkers = [];
223
239
  #runningWorkers = [];
240
+ #auxiliaryWorkers = new Set();
224
241
  #pthreads = {};
225
242
  #nextWorkerID = 1;
226
243
  #wasmModule = null;
@@ -233,10 +250,15 @@ export class WasmEngine {
233
250
  #voipStackInitialized = false;
234
251
  #voipStackInitPromise = null;
235
252
  #voipReadyResolver = null;
236
- #voipReadyPromise = null;
253
+ #voipReadyTimer = null;
254
+ #voipInitCancel = null;
255
+ #voipInitError = null;
237
256
  #workerModulesCode = "";
238
257
  #loaderCode = "";
239
258
  constructor(config = {}) {
259
+ const size = config.workerPoolSize ?? DEFAULT_PTHREAD_POOL_SIZE;
260
+ if (!Number.isInteger(size) || size < 4 || size > 20) throw new TypeError('workerPoolSize must be an integer from 4 to 20');
261
+ this.#pthreadPoolSize = size;
240
262
  const basePath = config.resourcesPath
241
263
  ? (path.isAbsolute(config.resourcesPath) ? config.resourcesPath : path.resolve(process.cwd(), config.resourcesPath))
242
264
  : path.resolve(__dirname, "..");
@@ -258,8 +280,24 @@ export class WasmEngine {
258
280
  };
259
281
  }
260
282
  initialize = async () => {
261
- if (this.#initialized)
262
- throw new Error("WasmEngine already initialized");
283
+ if (this.#initialized || this.#initializing)
284
+ throw new Error('WasmEngine already initialized or initializing');
285
+ this.#initializing = true;
286
+ const generation = ++this.#generation;
287
+ const cancelled = Symbol('cancelled');
288
+ let cancel;
289
+ const cancelledPromise = new Promise((resolve) => { cancel = () => resolve(cancelled); });
290
+ this.#cancelInitialization = cancel;
291
+ const checkCurrent = () => {
292
+ if (generation !== this.#generation) throw new Error('VoIP WASM initialization cancelled');
293
+ };
294
+ const cancellable = async (promise) => {
295
+ const result = await Promise.race([promise, cancelledPromise]);
296
+ if (result === cancelled) throw new Error('VoIP WASM initialization cancelled');
297
+ checkCurrent();
298
+ return result;
299
+ };
300
+ try {
263
301
  const voipStorageDir = "/tmp/voip";
264
302
  try {
265
303
  if (!fs.existsSync(voipStorageDir))
@@ -287,7 +325,9 @@ export class WasmEngine {
287
325
  }
288
326
  const memory = new WebAssembly.Memory({ initial: 256, maximum: 32768, shared: true });
289
327
  this.#wasmMemory = memory;
290
- this.#wasmModule = await WebAssembly.compile(wasmBuffer);
328
+ const wasmModule = await cancellable(WebAssembly.compile(wasmBuffer));
329
+ checkCurrent();
330
+ this.#wasmModule = wasmModule;
291
331
  this.#vmContext = this.#createVMContext(memory);
292
332
  const runModuleCode = (code) => { if (code)
293
333
  vm.runInContext(code, this.#vmContext); };
@@ -316,22 +356,53 @@ export class WasmEngine {
316
356
  if (typeof wasmLoader !== "function") {
317
357
  throw new Error(`No compatible WASM loader found. Tried: ${loaderModuleNames.join(", ")}`);
318
358
  }
319
- if (!_a.#globalCallbacksRegistered)
320
- this.#registerGlobalCallbacks();
321
- await this.#initPThreadPool();
359
+ this.#registerInstanceCallbacks();
360
+ await cancellable(this.#initPThreadPool());
361
+ checkCurrent();
362
+ if (this.#unusedWorkers.length !== this.#pthreadPoolSize) {
363
+ throw new Error('Could not create the required VoIP WASM workers');
364
+ }
322
365
  const workersLoadingPromise = this.#loadWasmModuleToAllWorkers();
323
- const readyPromise = wasmLoader({
324
- wasmBinary: wasmBuffer,
325
- wasmMemory: memory,
326
- locateFile: () => this.#config.wasmPath,
327
- onRuntimeInitialized: () => { },
366
+ const readyPromise = Promise.resolve().then(() => {
367
+ checkCurrent();
368
+ return wasmLoader({
369
+ wasmBinary: wasmBuffer,
370
+ wasmMemory: memory,
371
+ pthreadPoolSizeOverride: this.#pthreadPoolSize,
372
+ locateFile: () => this.#config.wasmPath,
373
+ onRuntimeInitialized: () => { },
374
+ });
328
375
  });
329
- const [instance] = await Promise.all([readyPromise, workersLoadingPromise]);
376
+ let initTimer;
377
+ let instance;
378
+ try {
379
+ [instance] = await cancellable(Promise.race([
380
+ Promise.all([readyPromise, workersLoadingPromise]),
381
+ new Promise((_, reject) => { initTimer = setTimeout(() => reject(new Error('VoIP WASM initialization timed out')), 30_000); }),
382
+ ]));
383
+ } finally { clearTimeout(initTimer); }
384
+ checkCurrent();
330
385
  this.#instance = instance;
331
386
  this.#initialized = true;
387
+ } catch (error) {
388
+ // Direct WasmEngine callers also need cleanup after a failed init.
389
+ // A concurrent destroy has already cleaned its own generation.
390
+ if (generation === this.#generation) this.destroy();
391
+ throw error;
392
+ } finally {
393
+ if (this.#cancelInitialization === cancel) this.#cancelInitialization = null;
394
+ this.#initializing = false;
395
+ }
332
396
  };
333
397
  isInitialized = () => this.#initialized;
334
398
  destroy = () => {
399
+ this.#generation++;
400
+ this.#cancelInitialization?.();
401
+ this.#voipInitCancel?.();
402
+ for (const timer of this.#vmTimeouts) clearTimeout(timer);
403
+ for (const timer of this.#vmIntervals) clearInterval(timer);
404
+ this.#vmTimeouts.clear();
405
+ this.#vmIntervals.clear();
335
406
  this.#stopAudioPlaybackLoop();
336
407
  if (this.#instance && typeof this.#instance.endCall === "function") {
337
408
  try {
@@ -339,77 +410,80 @@ export class WasmEngine {
339
410
  }
340
411
  catch { }
341
412
  }
342
- for (const worker of [...this.#runningWorkers, ...this.#unusedWorkers]) {
413
+ for (const worker of [...this.#runningWorkers, ...this.#unusedWorkers, ...this.#auxiliaryWorkers]) {
343
414
  try {
344
- worker.terminate();
415
+ // terminate() is asynchronous; observe rejections even though
416
+ // destroy remains synchronous for backwards compatibility.
417
+ worker.terminate()?.catch?.(() => {});
345
418
  }
346
419
  catch { }
347
420
  }
421
+ this.#auxiliaryWorkers.clear();
348
422
  this.#runningWorkers = [];
349
423
  this.#unusedWorkers = [];
424
+ this.#pthreads = {};
425
+ this.#workersLoadedCount = 0;
426
+ this.#removeRunDependencyCallback = null;
350
427
  this.#instance = null;
351
428
  this.#vmContext = null;
352
429
  this.#moduleRegistry.clear();
353
430
  this.#wasmModule = null;
354
431
  this.#wasmMemory = null;
355
432
  this.#initialized = false;
433
+ this.#voipStackInitialized = false;
434
+ this.#callbackListeners.clear();
356
435
  };
357
436
  initVoipStack = (selfJid, meUserJid, selfLid) => {
358
437
  this.#ensureInitialized();
359
- if (this.#voipStackInitialized || this.#voipStackInitPromise)
360
- return;
361
- this.#voipStackInitPromise = new Promise((resolveInit) => {
362
- this.#voipReadyPromise = new Promise((readyResolve) => {
363
- this.#voipReadyResolver = () => {
364
- this.#voipStackInitialized = true;
365
- this.#voipReadyResolver = null;
366
- this.#voipReadyPromise = null;
367
- readyResolve();
368
- };
369
- });
438
+ if (this.#voipStackInitialized || this.#voipStackInitPromise) return;
439
+ this.#voipInitError = null;
440
+ let settled = false;
441
+ const promise = new Promise((resolve) => {
442
+ const finish = (ready, error = null) => {
443
+ if (settled) return;
444
+ settled = true;
445
+ if (this.#voipReadyTimer) clearTimeout(this.#voipReadyTimer);
446
+ this.#voipReadyTimer = null;
447
+ this.#voipReadyResolver = null;
448
+ this.#voipInitCancel = null;
449
+ this.#voipInitError = error;
450
+ this.#voipStackInitialized = ready;
451
+ resolve();
452
+ };
453
+ this.#voipReadyResolver = () => finish(true);
454
+ this.#voipInitCancel = () => finish(false, new Error('VoIP engine disconnected during initialization'));
455
+ this.#voipReadyTimer = setTimeout(() => {
456
+ // Some upstream bundles do not emit onVoipReady. Preserve the
457
+ // upstream fallback, but label it as an assumption, not proof.
458
+ try { this.#config.callbacks?.onDiagnostic?.({ component: 'wasm', code: 'READY_TIMEOUT_ASSUMED' }); } catch {}
459
+ finish(true);
460
+ }, VOIP_READY_TIMEOUT_MS);
370
461
  try {
371
462
  this.#applyDefaultAbProps();
372
463
  try {
373
464
  this.#instance.initVoipStack(selfJid, meUserJid, selfLid);
374
465
  }
375
466
  catch (modernErr) {
376
- if (modernErr?.name === "BindingError" &&
377
- (String(modernErr?.message ?? "").includes("expected 8 args") ||
378
- String(modernErr?.message ?? "").includes("takes 8"))) {
467
+ if (modernErr?.name === 'BindingError' &&
468
+ (String(modernErr?.message ?? '').includes('expected 8 args') ||
469
+ String(modernErr?.message ?? '').includes('takes 8'))) {
379
470
  this.#instance.initVoipStack(selfJid, meUserJid, selfLid, true, 5, 0, 8, 16);
380
471
  }
381
- else {
382
- throw modernErr;
383
- }
472
+ else throw modernErr;
384
473
  }
385
- Promise.race([
386
- this.#voipReadyPromise,
387
- new Promise((r) => setTimeout(() => {
388
- this.#voipStackInitialized = true;
389
- r();
390
- }, VOIP_READY_TIMEOUT_MS)),
391
- ]).finally(() => {
392
- this.#voipStackInitPromise = null;
393
- resolveInit();
394
- });
395
474
  }
396
- catch {
397
- this.#voipReadyResolver = null;
398
- this.#voipReadyPromise = null;
399
- this.#voipStackInitPromise = null;
400
- resolveInit();
475
+ catch (error) {
476
+ finish(false, new Error('VoIP stack initialization failed', { cause: error }));
401
477
  }
402
478
  });
479
+ this.#voipStackInitPromise = promise;
480
+ void promise.then(() => {
481
+ if (this.#voipStackInitPromise === promise) this.#voipStackInitPromise = null;
482
+ });
403
483
  };
404
484
  waitForVoipStackReady = async () => {
405
- if (this.#voipStackInitialized)
406
- return;
407
- if (this.#voipStackInitPromise) {
408
- await this.#voipStackInitPromise;
409
- }
410
- else {
411
- await new Promise((r) => setTimeout(r, 100));
412
- }
485
+ if (this.#voipStackInitPromise) await this.#voipStackInitPromise;
486
+ if (!this.#voipStackInitialized) throw this.#voipInitError ?? new Error('VoIP stack is not initialized');
413
487
  };
414
488
  isVoipStackReady = () => this.#voipStackInitialized;
415
489
  startCall = (options) => {
@@ -701,6 +775,7 @@ export class WasmEngine {
701
775
  try {
702
776
  const worker = new Worker(workerScriptPath, {
703
777
  stdout: true, stderr: true,
778
+ execArgv: workerExecArgv(),
704
779
  workerData: {
705
780
  wasmPath: this.#config.wasmPath,
706
781
  wasmBinary: this.#config.wasmBinary,
@@ -711,7 +786,7 @@ export class WasmEngine {
711
786
  enableLogs: this.#config.enableLogs,
712
787
  },
713
788
  });
714
- const port = new NodeWorkerMessagePort(worker, "WAWebVoipWebWasmWorker");
789
+ const port = new NodeWorkerMessagePort(worker, "WAWebVoipWebWasmWorker", this.#notifyInstanceCallback);
715
790
  worker.stdout?.on("data", () => { }); // suppress noisy worker stdout
716
791
  worker.stderr?.on("data", filterWorkerStderr);
717
792
  this.#unusedWorkers.push(port);
@@ -719,37 +794,59 @@ export class WasmEngine {
719
794
  catch { }
720
795
  };
721
796
  #initPThreadPool = async () => {
722
- for (let i = 0; i < PTHREAD_POOL_SIZE; i += 1)
797
+ for (let i = 0; i < this.#pthreadPoolSize; i += 1)
723
798
  this.#allocateUnusedWorker();
724
799
  };
725
- #loadWasmModuleToWorker = (worker) => new Promise((resolve) => {
800
+ #loadWasmModuleToWorker = (worker) => new Promise((resolve, reject) => {
801
+ const rawWorker = worker.getWorker();
802
+ const cleanup = () => {
803
+ clearTimeout(timer);
804
+ worker.removeMessageListener('cmd', loadedHandler);
805
+ rawWorker.off?.('error', onError);
806
+ rawWorker.off?.('exit', onExit);
807
+ };
726
808
  const loadedHandler = (msg) => {
727
- if (msg && msg.cmd === "loaded") {
728
- worker.removeMessageListener("cmd", loadedHandler);
809
+ if (msg && msg.cmd === 'loaded') {
810
+ cleanup();
729
811
  this.#workersLoadedCount += 1;
730
- if (this.#workersLoadedCount >= PTHREAD_POOL_SIZE && this.#removeRunDependencyCallback) {
731
- this.#removeRunDependencyCallback("loading-workers");
812
+ if (this.#workersLoadedCount >= this.#pthreadPoolSize && this.#removeRunDependencyCallback) {
813
+ this.#removeRunDependencyCallback('loading-workers');
732
814
  }
733
815
  resolve();
734
816
  }
735
817
  };
736
- worker.addMessageListener("cmd", loadedHandler);
818
+ const onError = () => { cleanup(); reject(new Error('VoIP WASM worker failed to start')); };
819
+ const onExit = () => { cleanup(); reject(new Error('VoIP WASM worker exited before loading')); };
820
+ const timer = setTimeout(() => { cleanup(); reject(new Error('VoIP WASM worker load timed out')); }, 20_000);
821
+ worker.addMessageListener('cmd', loadedHandler);
822
+ rawWorker.once?.('error', onError);
823
+ rawWorker.once?.('exit', onExit);
737
824
  worker.workerID = this.#nextWorkerID++;
738
- worker.postMessage({
739
- cmd: "load", type: "cmd",
740
- wasmMemory: this.#wasmMemory,
741
- wasmModule: this.#wasmModule,
742
- workerID: worker.workerID,
743
- handlers: [],
744
- });
825
+ try {
826
+ worker.postMessage({
827
+ cmd: 'load', type: 'cmd', wasmMemory: this.#wasmMemory,
828
+ wasmModule: this.#wasmModule, workerID: worker.workerID, handlers: [],
829
+ });
830
+ } catch { onError(); }
745
831
  });
746
832
  #loadWasmModuleToAllWorkers = async () => {
747
833
  this.#workersLoadedCount = 0;
748
834
  await Promise.all(this.#unusedWorkers.map((w) => this.#loadWasmModuleToWorker(w)));
749
835
  };
750
- #registerGlobalCallbacks = () => {
836
+ #notifyInstanceCallback = (callbackName, data) => {
837
+ for (const handler of this.#callbackListeners.get(callbackName) ?? []) {
838
+ try { handler(data); } catch {}
839
+ }
840
+ };
841
+ #registerInstanceCallback = (callbackName, handler) => {
842
+ const set = this.#callbackListeners.get(callbackName) ?? new Set();
843
+ set.add(handler);
844
+ this.#callbackListeners.set(callbackName, set);
845
+ };
846
+ #registerInstanceCallbacks = () => {
847
+ this.#callbackListeners.clear();
751
848
  const callbacks = this.#config.callbacks ?? {};
752
- _a.registerGlobalCallbackListener("loggingCallback", (data) => {
849
+ this.#registerInstanceCallback("loggingCallback", (data) => {
753
850
  if (!this.#config.enableLogs)
754
851
  return;
755
852
  const level = data?.level;
@@ -758,7 +855,7 @@ export class WasmEngine {
758
855
  callbacks.onLog?.(mapped, msg);
759
856
  });
760
857
  if (callbacks.onAudioCaptureInit) {
761
- _a.registerGlobalCallbackListener("initCaptureDriverJS", (data) => {
858
+ this.#registerInstanceCallback("initCaptureDriverJS", (data) => {
762
859
  callbacks.onAudioCaptureInit({
763
860
  sampleRate: data?.sample_rate ?? data?.sampleRate,
764
861
  channels: data?.channels,
@@ -767,10 +864,10 @@ export class WasmEngine {
767
864
  });
768
865
  });
769
866
  }
770
- _a.registerGlobalCallbackListener("startCaptureJS", () => callbacks.onAudioCaptureStart?.());
771
- _a.registerGlobalCallbackListener("stopCaptureJS", () => callbacks.onAudioCaptureStop?.());
867
+ this.#registerInstanceCallback("startCaptureJS", () => callbacks.onAudioCaptureStart?.());
868
+ this.#registerInstanceCallback("stopCaptureJS", () => callbacks.onAudioCaptureStop?.());
772
869
  if (callbacks.onAudioPlaybackInit) {
773
- _a.registerGlobalCallbackListener("initPlaybackDriverJS", (data) => {
870
+ this.#registerInstanceCallback("initPlaybackDriverJS", (data) => {
774
871
  callbacks.onAudioPlaybackInit({
775
872
  sampleRate: data?.sample_rate ?? data?.sampleRate,
776
873
  channels: data?.channels,
@@ -779,16 +876,16 @@ export class WasmEngine {
779
876
  });
780
877
  });
781
878
  }
782
- _a.registerGlobalCallbackListener("startPlaybackJS", () => {
879
+ this.#registerInstanceCallback("startPlaybackJS", () => {
783
880
  callbacks.onAudioPlaybackStart?.();
784
881
  this.#startAudioPlaybackLoop();
785
882
  });
786
- _a.registerGlobalCallbackListener("stopPlaybackJS", () => {
883
+ this.#registerInstanceCallback("stopPlaybackJS", () => {
787
884
  this.#stopAudioPlaybackLoop();
788
885
  callbacks.onAudioPlaybackStop?.();
789
886
  });
790
887
  if (callbacks.onSignalingXmpp) {
791
- _a.registerGlobalCallbackListener("onSignalingXmpp", (data) => {
888
+ this.#registerInstanceCallback("onSignalingXmpp", (data) => {
792
889
  const peerJid = data.peerJid ?? data.args?.peerJid;
793
890
  const callId = data.callId ?? data.args?.callId;
794
891
  let xmlPayload = data.xmlPayload ?? data.args?.xmlPayload;
@@ -802,12 +899,12 @@ export class WasmEngine {
802
899
  });
803
900
  }
804
901
  if (callbacks.onCallEvent) {
805
- _a.registerGlobalCallbackListener("onCallEvent", (data) => {
902
+ this.#registerInstanceCallback("onCallEvent", (data) => {
806
903
  callbacks.onCallEvent(data.eventType, data.eventDataJson);
807
904
  });
808
905
  }
809
906
  if (callbacks.sendDataToRelay) {
810
- _a.registerGlobalCallbackListener("sendDataToRelay", (data) => {
907
+ this.#registerInstanceCallback("sendDataToRelay", (data) => {
811
908
  let relayData = data.data ?? data.args?.data;
812
909
  const ip = data.ip ?? data.args?.ip;
813
910
  const portNum = data.port ?? data.args?.port;
@@ -825,13 +922,19 @@ export class WasmEngine {
825
922
  return 0;
826
923
  if (!ip || !portNum)
827
924
  return 0;
828
- callbacks.sendDataToRelay(relayData, ip, portNum);
829
- return relayData.byteLength;
925
+ return callbacks.sendDataToRelay(relayData, ip, portNum) ?? 0;
830
926
  });
831
927
  }
832
- _a.#globalCallbacksRegistered = true;
928
+ this.#registerInstanceCallback("onVoipReady", () => {
929
+ this.#voipReadyResolver?.();
930
+ callbacks.onVoipReady?.();
931
+ });
833
932
  };
834
933
  #requireModule = (name) => {
934
+ const notifyOwner = this.#notifyInstanceCallback;
935
+ class ScopedWorkerMessagePort extends NodeWorkerMessagePort {
936
+ constructor(worker, name) { super(worker, name, notifyOwner); }
937
+ }
835
938
  const preDefinedModules = {
836
939
  Promise,
837
940
  WAWebVoipWebWasmWorkerResource: {
@@ -845,6 +948,7 @@ export class WasmEngine {
845
948
  : resolveWorkerScriptPath();
846
949
  const worker = new Worker(scriptPath, {
847
950
  stdout: true, stderr: true,
951
+ execArgv: workerExecArgv(),
848
952
  workerData: {
849
953
  wasmPath: this.#config.wasmPath,
850
954
  wasmBinary: this.#config.wasmBinary,
@@ -857,14 +961,19 @@ export class WasmEngine {
857
961
  });
858
962
  worker.stdout?.on("data", () => { });
859
963
  worker.stderr?.on("data", filterWorkerStderr);
964
+ // The loader creates another worker pool outside the
965
+ // explicit pthread pool; it must be owned and terminated.
966
+ this.#auxiliaryWorkers.add(worker);
967
+ worker.once('exit', () => this.#auxiliaryWorkers.delete(worker));
968
+ worker.on('error', () => {});
860
969
  return worker;
861
970
  },
862
971
  },
863
972
  WorkerClient: { init: () => { } },
864
973
  WorkerMessagePort: {
865
- WorkerMessagePort: NodeWorkerMessagePort,
974
+ WorkerMessagePort: ScopedWorkerMessagePort,
866
975
  CastWorkerMessagePort: (w) => w,
867
- WorkerSyncedMessagePort: NodeWorkerMessagePort,
976
+ WorkerSyncedMessagePort: ScopedWorkerMessagePort,
868
977
  },
869
978
  bx: Object.assign((id) => String(id), { getURL: () => "" }),
870
979
  HasteSupportData: { handle: () => { } },
@@ -948,6 +1057,27 @@ export class WasmEngine {
948
1057
  return result;
949
1058
  };
950
1059
  #createVMContext = (memory) => {
1060
+ const generation = this.#generation;
1061
+ const current = () => this.#generation === generation;
1062
+ // The bundled loader has its own timeouts. Own them so a cancelled
1063
+ // initialization does not keep the process alive for 15 seconds.
1064
+ const vmSetTimeout = (callback, ms, ...args) => {
1065
+ if (!current()) return null;
1066
+ const timer = setTimeout(() => {
1067
+ this.#vmTimeouts.delete(timer);
1068
+ if (current()) callback(...args);
1069
+ }, ms);
1070
+ this.#vmTimeouts.add(timer);
1071
+ return timer;
1072
+ };
1073
+ const vmClearTimeout = (timer) => { this.#vmTimeouts.delete(timer); clearTimeout(timer); };
1074
+ const vmSetInterval = (callback, ms, ...args) => {
1075
+ if (!current()) return null;
1076
+ const timer = setInterval(() => { if (current()) callback(...args); }, ms);
1077
+ this.#vmIntervals.add(timer);
1078
+ return timer;
1079
+ };
1080
+ const vmClearInterval = (timer) => { this.#vmIntervals.delete(timer); clearInterval(timer); };
951
1081
  const callbacks = this.#config.callbacks ?? {};
952
1082
  const wasmCallbacks = {
953
1083
  onVoipReady: () => {
@@ -1052,7 +1182,7 @@ export class WasmEngine {
1052
1182
  wrapNativeSuper: (Class) => Class,
1053
1183
  };
1054
1184
  const addRunDependency = (dep) => {
1055
- if (dep === "loading-workers" && this.#workersLoadedCount >= PTHREAD_POOL_SIZE) {
1185
+ if (dep === "loading-workers" && this.#workersLoadedCount >= this.#pthreadPoolSize) {
1056
1186
  setImmediate(() => this.#removeRunDependencyCallback?.(dep));
1057
1187
  }
1058
1188
  };
@@ -1077,14 +1207,15 @@ export class WasmEngine {
1077
1207
  selfObj.self = selfObj;
1078
1208
  selfObj.window = selfObj;
1079
1209
  selfObj.globalThis = selfObj;
1080
- if (typeof global !== "undefined") {
1081
- global.WhatsAppVoipWasmCallbacks = wasmCallbacks;
1082
- global.WhatsAppVoipWasmWorkerCompatibleCallbacks = wasmCallbacks;
1083
- }
1210
+ // Keep callbacks inside this engine's VM. Mutating Node's process-wide
1211
+ // global object would overwrite other clients' callbacks and retain
1212
+ // their resources after disconnect.
1084
1213
  const context = vm.createContext({
1085
1214
  self: selfObj, globalThis: selfObj, global: selfObj, window: selfObj,
1086
- console, setTimeout, setInterval, clearTimeout, clearInterval,
1087
- queueMicrotask, performance, babelHelpers, __d,
1215
+ console, setTimeout: vmSetTimeout, setInterval: vmSetInterval,
1216
+ clearTimeout: vmClearTimeout, clearInterval: vmClearInterval,
1217
+ queueMicrotask: (callback) => queueMicrotask(() => { if (current()) callback(); }),
1218
+ performance, babelHelpers, __d,
1088
1219
  require: this.#requireModule,
1089
1220
  addRunDependency, removeRunDependency,
1090
1221
  WebAssembly, SharedArrayBuffer,
package/lib/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export * from './WAUSync/index.js';
10
10
  export { BibzWhatsEngine } from './Socket/engine.js';
11
11
  export * from './Modded/message_builder.js';
12
12
  export { VoipClient, ActiveCall, CallState } from './VoIP/index.js';
13
+ export type { VoipClientOptions, OutgoingCallOptions, VoipDiagnostic, VoipStats } from './VoIP/index.js';
13
14
  export * from './BibzWhats/index.js';
14
15
  export type WASocket = ReturnType<typeof makeWASocket>;
15
16
  /** alias BibzWhats untuk WASocket */