@oxidezap/baileyrs 0.3.7 → 0.3.9

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 (129) hide show
  1. package/README.md +56 -8
  2. package/lib/Bridge/history-sync-wire.d.ts +2 -2
  3. package/lib/Bridge/history-sync-wire.js +4 -4
  4. package/lib/Bridge/schema.js +7 -1
  5. package/lib/Bridge/types.d.ts +7 -1
  6. package/lib/Compatibility/auth-state.d.ts +30 -0
  7. package/lib/Compatibility/auth-state.js +96 -0
  8. package/lib/Compatibility/encode-proto-core.d.ts +31 -0
  9. package/lib/Compatibility/encode-proto-core.js +51 -0
  10. package/lib/Compatibility/encode-proto.d.ts +0 -29
  11. package/lib/Compatibility/encode-proto.js +3 -50
  12. package/lib/Compatibility/host-auth-state.d.ts +6 -0
  13. package/lib/Compatibility/host-auth-state.js +162 -0
  14. package/lib/Compatibility/internal/auth-state.d.ts +3 -7
  15. package/lib/Compatibility/internal/auth-state.js +34 -1
  16. package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
  17. package/lib/Compatibility/internal/host-auth-state.js +14 -0
  18. package/lib/Compatibility/legacy-store/device.js +5 -5
  19. package/lib/Compatibility/message-ids.d.ts +17 -0
  20. package/lib/Compatibility/message-ids.js +47 -0
  21. package/lib/Compatibility/message-relay.d.ts +2 -2
  22. package/lib/Compatibility/message-relay.js +4 -4
  23. package/lib/Compatibility/proto-runtime.js +33 -11
  24. package/lib/Compatibility/socket-results.d.ts +1 -1
  25. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  26. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  27. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  28. package/lib/Compatibility/websocket-client.d.ts +11 -3
  29. package/lib/Compatibility/websocket-client.js +84 -11
  30. package/lib/Defaults/index.d.ts +8 -8
  31. package/lib/Defaults/index.js +8 -8
  32. package/lib/Media/content.d.ts +28 -0
  33. package/lib/Media/content.js +129 -0
  34. package/lib/Media/core.d.ts +34 -0
  35. package/lib/Media/core.js +120 -0
  36. package/lib/Media/mutations.d.ts +24 -0
  37. package/lib/Media/mutations.js +38 -0
  38. package/lib/Runtime/aes-gcm.d.ts +4 -0
  39. package/lib/Runtime/aes-gcm.js +11 -0
  40. package/lib/Runtime/bridge.d.ts +44 -0
  41. package/lib/Runtime/bridge.js +76 -0
  42. package/lib/Runtime/buffer.d.ts +9 -0
  43. package/lib/Runtime/buffer.js +22 -0
  44. package/lib/Runtime/bytes.d.ts +61 -0
  45. package/lib/Runtime/bytes.js +270 -0
  46. package/lib/Runtime/host.d.ts +22 -0
  47. package/lib/Runtime/host.js +43 -0
  48. package/lib/Runtime/long.d.ts +33 -0
  49. package/lib/Runtime/long.js +64 -0
  50. package/lib/Runtime/node-media-processors.d.ts +4 -0
  51. package/lib/Runtime/node-media-processors.js +29 -0
  52. package/lib/Runtime/node-media.d.ts +28 -0
  53. package/lib/Runtime/node-media.js +115 -0
  54. package/lib/Runtime/node.d.ts +14 -0
  55. package/lib/Runtime/node.js +81 -0
  56. package/lib/Runtime/paths.d.ts +4 -0
  57. package/lib/Runtime/paths.js +7 -0
  58. package/lib/Runtime/stream.d.ts +11 -0
  59. package/lib/Runtime/stream.js +25 -0
  60. package/lib/Runtime/types.d.ts +98 -0
  61. package/lib/Runtime/types.js +13 -0
  62. package/lib/Socket/core.d.ts +312 -0
  63. package/lib/Socket/core.js +1134 -0
  64. package/lib/Socket/events-core.d.ts +75 -0
  65. package/lib/Socket/events-core.js +1058 -0
  66. package/lib/Socket/events.d.ts +1 -63
  67. package/lib/Socket/events.js +4 -1047
  68. package/lib/Socket/groups.js +4 -3
  69. package/lib/Socket/index.d.ts +521 -103
  70. package/lib/Socket/index.js +10 -1007
  71. package/lib/Socket/messages-core.d.ts +41 -0
  72. package/lib/Socket/messages-core.js +270 -0
  73. package/lib/Socket/messages.d.ts +9 -36
  74. package/lib/Socket/messages.js +3 -260
  75. package/lib/Socket/newsletter.js +3 -3
  76. package/lib/Socket/profile.js +1 -1
  77. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  78. package/lib/Socket/terminal-close-reporter.js +3 -3
  79. package/lib/Socket/transport.d.ts +2 -0
  80. package/lib/Socket/transport.js +16 -1
  81. package/lib/Socket/types.d.ts +2 -0
  82. package/lib/Types/Auth.d.ts +11 -0
  83. package/lib/Types/Message.d.ts +1 -1
  84. package/lib/Types/Socket.d.ts +2 -2
  85. package/lib/Types/index.d.ts +6 -1
  86. package/lib/Utils/browser-utils.d.ts +4 -0
  87. package/lib/Utils/browser-utils.js +53 -2
  88. package/lib/Utils/crypto.d.ts +1 -0
  89. package/lib/Utils/crypto.js +1 -0
  90. package/lib/Utils/event-buffer.d.ts +6 -1
  91. package/lib/Utils/event-buffer.js +28 -27
  92. package/lib/Utils/link-preview.d.ts +4 -3
  93. package/lib/Utils/logger.d.ts +3 -0
  94. package/lib/Utils/logger.js +35 -6
  95. package/lib/Utils/messages-core.d.ts +174 -0
  96. package/lib/Utils/messages-core.js +1042 -0
  97. package/lib/Utils/messages-media-core.d.ts +73 -0
  98. package/lib/Utils/messages-media-core.js +319 -0
  99. package/lib/Utils/messages-media.d.ts +1 -72
  100. package/lib/Utils/messages-media.js +9 -358
  101. package/lib/Utils/messages.d.ts +1 -166
  102. package/lib/Utils/messages.js +7 -1040
  103. package/lib/Utils/optional-peer.js +14 -5
  104. package/lib/Utils/process-history-message-core.d.ts +36 -0
  105. package/lib/Utils/process-history-message-core.js +187 -0
  106. package/lib/Utils/process-history-message.d.ts +5 -43
  107. package/lib/Utils/process-history-message.js +11 -197
  108. package/lib/Utils/process-message-core.d.ts +29 -0
  109. package/lib/Utils/process-message-core.js +112 -0
  110. package/lib/Utils/process-message.d.ts +4 -24
  111. package/lib/Utils/process-message.js +6 -111
  112. package/lib/WABinary/generic-utils.js +7 -5
  113. package/lib/host-shared.d.ts +74 -0
  114. package/lib/host-shared.js +15 -0
  115. package/lib/host-socket-operations.d.ts +3 -0
  116. package/lib/host-socket-operations.js +2 -0
  117. package/lib/host-surface.d.ts +21 -0
  118. package/lib/host-surface.js +35 -0
  119. package/lib/host-types.d.ts +356 -0
  120. package/lib/host-types.js +2 -0
  121. package/lib/host.d.ts +33 -0
  122. package/lib/host.js +31 -0
  123. package/lib/node-surface.d.ts +9 -0
  124. package/lib/node-surface.js +15 -0
  125. package/lib/surface.d.ts +5 -0
  126. package/lib/surface.js +6 -0
  127. package/lib/wasm.d.ts +27 -0
  128. package/lib/wasm.js +27 -0
  129. package/package.json +18 -6
@@ -0,0 +1,1134 @@
1
+ import { base64UrlEncode, unrefTimer } from '../Runtime/bytes.js';
2
+ import { encodeProtoCompat as encodeProtoCompatCore } from '../Compatibility/encode-proto-core.js';
3
+ import { normalizeHostAuthenticationState } from '../Compatibility/internal/host-auth-state.js';
4
+ import { hydrateHostAuthCreds } from '../Compatibility/host-auth-state.js';
5
+ import { makeHistoryRuntime } from '../Runtime/bridge.js';
6
+ import { makeMutex } from '../Compatibility/internal/make-mutex.js';
7
+ import { isNativeMemoryStore } from '../Compatibility/internal/native-memory-store.js';
8
+ import { toBridgeMediaType } from '../Compatibility/media-type.js';
9
+ import { bindSignalRepositoryContext, makeDefaultSignalRepository } from '../Compatibility/signal-repository.js';
10
+ import { bridgeBusinessProfileToBaileys } from '../Compatibility/socket-results.js';
11
+ import { makeStanzaResponseMethods } from '../Compatibility/stanza-responses.js';
12
+ import { makeParticipatingRefreshHandler } from '../Compatibility/participating-refresh.js';
13
+ import { makeTaggedMessageWaiter } from '../Compatibility/tagged-message-waiter.js';
14
+ import { isRawNodeForwardingEnabled, WebSocketClient } from '../Compatibility/websocket-client.js';
15
+ import { DEFAULT_CONNECTION_CONFIG, MEDIA_TYPES } from '../Defaults/index.js';
16
+ import { DisconnectReason, WA_PRESENCES } from '../Types/index.js';
17
+ import { assertArgumentDomain } from '../Utils/argument-domain.js';
18
+ import { Boom } from '../Utils/boom.js';
19
+ import { makeEventBuffer } from '../Utils/event-buffer.js';
20
+ import { _registerActiveBridgeClient, _unregisterActiveBridgeClient, downloadMediaMessage, MEDIA_DOWNLOAD_TYPES } from '../Utils/messages-core.js';
21
+ import { makeHistorySyncAdmission, resolveHistorySyncPolicy, isHistorySyncFullyDisabled } from '../Compatibility/history-sync-admission.js';
22
+ import { assertNodeErrorFree } from '../WABinary/generic-utils.js';
23
+ import { makeBlockingMethods } from './blocking.js';
24
+ import { makeBusinessMethods } from './business.js';
25
+ import { makeChatActionMethods } from './chat-actions.js';
26
+ import { makeContactMethods } from './contacts.js';
27
+ import { makeCommunityMethods } from './communities.js';
28
+ import { makeBridgeClientOwner } from './bridge-client-owner.js';
29
+ import { warnUnsupportedConfig } from './unsupported-config.js';
30
+ import { wrapBridgeClient } from './bridge-error-boundary.js';
31
+ import { makeTerminalCloseReporter } from './terminal-close-reporter.js';
32
+ import { mapConnectFailureToDisconnect } from './terminal-close.js';
33
+ import { makeEventHandlers } from './events-core.js';
34
+ import { makeGroupMethods } from './groups.js';
35
+ import { makeInternalMethods, makeUnexpectedErrorReporter } from './internals.js';
36
+ import { makeMessageMethodsCore } from './messages-core.js';
37
+ import { makeNewsletterMethods } from './newsletter.js';
38
+ import { makePreKeyMethods } from './prekeys.js';
39
+ import { makePresenceMethods } from './presence.js';
40
+ import { makePrivacyMethods } from './privacy.js';
41
+ import { makeServerQueryMethods } from './server-queries.js';
42
+ import { makeProfileMethods } from './profile.js';
43
+ import { mapReachoutTimelock } from './reachout.js';
44
+ import { makeHttpClient, makeTransport } from './transport.js';
45
+ import { makeWithClient } from './client-operations.js';
46
+ import { makeUSyncMethods } from './usync.js';
47
+ import { createRuntimeLogger } from '../Utils/logger.js';
48
+ /**
49
+ * Default mapping for the legacy `browser[1]` slot — preserved so users on the
50
+ * existing `Browsers.macOS('Chrome')` style get the same `DeviceProps.platformType`
51
+ * they always got. Anything outside this set falls back to `CHROME` (matching
52
+ * the prior bridge behavior). Override with the explicit `deviceProps` config.
53
+ */
54
+ const browserToPlatformType = (browser) => {
55
+ switch (browser) {
56
+ case 'Chrome':
57
+ return 'CHROME';
58
+ case 'Firefox':
59
+ return 'FIREFOX';
60
+ case 'Safari':
61
+ return 'SAFARI';
62
+ case 'Edge':
63
+ return 'EDGE';
64
+ case 'Opera':
65
+ return 'OPERA';
66
+ case 'Desktop':
67
+ return 'DESKTOP';
68
+ case 'Android':
69
+ return 'ANDROID_PHONE';
70
+ default:
71
+ return 'CHROME';
72
+ }
73
+ };
74
+ const COMPLETION_FAILURE_CODES = new Map([
75
+ ['Generic', 400],
76
+ ['LoggedOut', 401],
77
+ ['TempBanned', 402],
78
+ ['AccountLocked', 403],
79
+ ['UnknownLogout', 406],
80
+ ['ClientOutdated', 405],
81
+ ['BadUserAgent', 409],
82
+ ['CatExpired', 413],
83
+ ['CatInvalid', 414],
84
+ ['NotFound', 415],
85
+ ['ClientUnknown', 418],
86
+ ['InternalServerError', 500],
87
+ ['Experimental', 501],
88
+ ['ServiceUnavailable', 503]
89
+ ]);
90
+ const completionFailureCode = (reason) => {
91
+ const named = COMPLETION_FAILURE_CODES.get(reason);
92
+ if (named !== undefined)
93
+ return named;
94
+ const unknown = /^Unknown\((-?\d+)\)$/.exec(reason)?.[1];
95
+ return unknown === undefined ? undefined : Number(unknown);
96
+ };
97
+ /** Build the ws EventEmitter with auto-enable raw node forwarding */
98
+ export const createWASocketFactory = (runtime) => {
99
+ const runtimeLogger = createRuntimeLogger((line, delivered) => runtime.loggerSink(line, delivered), runtime.logLevel());
100
+ let engineInitialized = false;
101
+ return (config) => createWASocketFactoryInner(runtime, config, () => {
102
+ if (engineInitialized)
103
+ return false;
104
+ engineInitialized = true;
105
+ return true;
106
+ }, () => {
107
+ engineInitialized = false;
108
+ }, runtimeLogger);
109
+ };
110
+ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization, resetEngineInitialization, runtimeLogger) => {
111
+ const platform = config.browser === undefined ? runtime.platformInfo?.() : undefined;
112
+ const mergedConfig = {
113
+ ...DEFAULT_CONNECTION_CONFIG,
114
+ ...config,
115
+ ...(platform ? { browser: [platform.os, 'Chrome', platform.release] } : {}),
116
+ logger: config.logger ?? runtime.defaultLogger ?? runtimeLogger
117
+ };
118
+ const { logger } = mergedConfig;
119
+ // Against `config`, not `fullConfig`: only what this caller actually passed
120
+ // is worth naming. Merging the defaults first would report every unsupported
121
+ // option on every socket, including the ones nobody chose.
122
+ warnUnsupportedConfig(config, logger);
123
+ // `Partial<SocketConfig>` lets an explicit `undefined` overwrite the default
124
+ // in the shallow merge above; resolve against the raw config so the socket
125
+ // keeps the default policy instead of throwing on the first notification.
126
+ const shouldSyncHistoryMessage = resolveHistorySyncPolicy(config.shouldSyncHistoryMessage);
127
+ if (isHistorySyncFullyDisabled(shouldSyncHistoryMessage)) {
128
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
129
+ }
130
+ const auth = (runtime.normalizeAuth ?? normalizeHostAuthenticationState)(mergedConfig.auth);
131
+ const fullConfig = { ...mergedConfig, auth };
132
+ const getExposedKeys = runtime.makeTransactionKeyStore
133
+ ? runtime.makeTransactionKeyStore(auth.keys, logger, fullConfig.transactionOpts)
134
+ : () => auth.keys;
135
+ const ev = makeEventBuffer(logger, {
136
+ setTimeout: runtime.setTimeout,
137
+ clearTimeout: runtime.clearTimeout
138
+ }, runtime.events.createEmitter());
139
+ // Upstream mutates authState.creds before notifying user listeners. Register
140
+ // this first so `ev.on('creds.update', saveCreds)` persists the merged state
141
+ // rather than the pre-pair placeholder.
142
+ ev.on('creds.update', update => Object.assign(auth.creds, update));
143
+ let user;
144
+ /** True once `init()` has finished wiring the client and started its read loop. */
145
+ let initialized = false;
146
+ /** True while the socket's end handlers run — see `end`. */
147
+ let runningEndHandlers = false;
148
+ /**
149
+ * Consumer teardown hooks, plus the socket's own. Declared here rather than
150
+ * beside their registrations so the owner below can close over the list
151
+ * before anything fills it.
152
+ */
153
+ const socketEndHandlers = [];
154
+ /**
155
+ * Drain both auth stores, returning the FIRST failure rather than throwing
156
+ * so the caller can finish the rest of its work and still report it.
157
+ *
158
+ * Called through their owners on purpose: collecting the two methods into
159
+ * an array and invoking them bare drops the receiver, so a consumer store
160
+ * whose `flush()` touches `this` throws on `undefined` and the teardown
161
+ * publishes a close with the auth writes unpersisted.
162
+ */
163
+ const flushStores = async () => {
164
+ let firstError;
165
+ try {
166
+ await auth.store?.flush?.();
167
+ }
168
+ catch (e) {
169
+ firstError ?? (firstError = e);
170
+ }
171
+ try {
172
+ await autoWrappedStore?.flush?.();
173
+ }
174
+ catch (e) {
175
+ firstError ?? (firstError = e);
176
+ }
177
+ return firstError;
178
+ };
179
+ /**
180
+ * Single home for the bridge client's lifetime. `ws` below reads the current
181
+ * client from it, and this teardown closes `ws` — the cycle is fine because
182
+ * both directions only run once the socket is live.
183
+ */
184
+ const owner = makeBridgeClientOwner({
185
+ logger,
186
+ /**
187
+ * Everything the socket owns beyond the client itself. Runs once, with
188
+ * the client still usable, whether or not one was ever adopted — a
189
+ * teardown that landed mid-init still has a transport to close and a
190
+ * store to drain.
191
+ */
192
+ teardown: async (client, error) => {
193
+ try {
194
+ await ws.close();
195
+ }
196
+ catch {
197
+ // The transport refused to close cleanly. Go straight at the
198
+ // client so the disconnect still happens *before* the barrier
199
+ // and flush below: `release` retries it, but that runs after the
200
+ // flush, and the closing-session ratchet writes a disconnect
201
+ // enqueues would then have nothing left to persist them.
202
+ try {
203
+ await client?.disconnect();
204
+ }
205
+ catch {
206
+ /* ignore */
207
+ }
208
+ }
209
+ if (client) {
210
+ // Barrier: bridge cleanup paths fired during `disconnect()` may
211
+ // emit `set()` calls that are still queued as microtasks /
212
+ // `setImmediate` callbacks at this point. Two yields to the
213
+ // event loop drain (1) the microtask queue and (2) the next
214
+ // macrotask tick where wasm-bindgen async callbacks land.
215
+ // Without this barrier the flushes below run before the bridge
216
+ // has finished writing — a race that loses the last few sets
217
+ // (typically the closing-session ratchet step).
218
+ await new Promise(resolve => {
219
+ if (runtime.setImmediate)
220
+ runtime.setImmediate(() => resolve());
221
+ else
222
+ runtime.setTimeout(() => resolve(), 0);
223
+ });
224
+ await new Promise(resolve => {
225
+ if (runtime.setImmediate)
226
+ runtime.setImmediate(() => resolve());
227
+ else
228
+ runtime.setTimeout(() => resolve(), 0);
229
+ });
230
+ }
231
+ const firstFlushError = await flushStores();
232
+ // End handlers run before the flush error is rethrown: they are the
233
+ // consumer's teardown hook, and a corrupt-on-shutdown auth store is
234
+ // exactly when they most need to run.
235
+ //
236
+ // The flag makes a re-entrant `end()` from inside one of them a
237
+ // no-op instead of a deadlock: shared cleanup used both directly and
238
+ // as an end hook would otherwise be handed the very promise that is
239
+ // waiting for it to return, and nothing would ever settle — no
240
+ // release, and no terminal close until the watchdog.
241
+ runningEndHandlers = true;
242
+ try {
243
+ for (const handler of socketEndHandlers) {
244
+ try {
245
+ await handler(error);
246
+ }
247
+ catch (handlerError) {
248
+ logger.error({ err: handlerError }, 'error in socket end handler');
249
+ }
250
+ }
251
+ }
252
+ finally {
253
+ runningEndHandlers = false;
254
+ }
255
+ if (firstFlushError)
256
+ throw firstFlushError;
257
+ },
258
+ release: async (client) => {
259
+ // `disconnect()` before `free()` drains exactly one shape: a
260
+ // `disconnect()` still in flight. Since bridge 0.21.1, freeing
261
+ // with ordinary calls pending (`fetchBlocklist()`, `logout()`) is
262
+ // safe — its `Drop` signals shutdown and aborts the background
263
+ // tasks — but freeing mid-`disconnect()` still aborts the process
264
+ // (recursively acquiring the teardown mutex). See
265
+ // `__tests__/bridge-free-safety.test.ts`.
266
+ //
267
+ // That shape is reachable: `WebSocketClient.close()` early-returns
268
+ // when `closing`/`closed` is already set without awaiting the
269
+ // disconnect it skipped, so `void sock.ws.close(); await sock.end()`
270
+ // could otherwise reach `free()` with the first disconnect still
271
+ // running. Awaiting it here is the belt to `ws.close()`'s braces.
272
+ let disconnected = true;
273
+ try {
274
+ await client.disconnect();
275
+ }
276
+ catch {
277
+ disconnected = false;
278
+ }
279
+ // Disconnect may schedule the final store callback on later ticks;
280
+ // drain those callbacks before the last durability flush.
281
+ if (disconnected) {
282
+ await new Promise(resolve => {
283
+ if (runtime.setImmediate)
284
+ runtime.setImmediate(() => resolve());
285
+ else
286
+ runtime.setTimeout(() => resolve(), 0);
287
+ });
288
+ await new Promise(resolve => {
289
+ if (runtime.setImmediate)
290
+ runtime.setImmediate(() => resolve());
291
+ else
292
+ runtime.setTimeout(() => resolve(), 0);
293
+ });
294
+ }
295
+ // Teardown already flushed, but only after its own disconnect
296
+ // attempts. If those all failed and this one succeeded, the
297
+ // closing-session ratchet writes it enqueues arrived after that
298
+ // flush — with nothing left to persist them. Cheap enough to just
299
+ // drain again.
300
+ if (disconnected) {
301
+ const lateFlushError = await flushStores();
302
+ if (lateFlushError)
303
+ logger.error({ err: lateFlushError }, 'failed to flush after the final disconnect');
304
+ }
305
+ // Unregister before freeing: `free()` is swallowed, so ordering it
306
+ // last would leave the module-level pointer aimed at a client that is
307
+ // already gone if anything between them threw.
308
+ _unregisterActiveBridgeClient(wrapBridgeClient(client));
309
+ try {
310
+ client.free();
311
+ }
312
+ catch {
313
+ /* ignore */
314
+ }
315
+ }
316
+ });
317
+ const ws = new WebSocketClient(fullConfig.waWebSocketUrl, fullConfig, () => owner.peek(), runtime.events.createEmitter());
318
+ let tagEpoch = 0;
319
+ // Per-socket random prefix avoids collisions between sockets created
320
+ // in the same millisecond. Date.now()-based prefixes (the previous
321
+ // implementation) collided in test loops and worker pools — every
322
+ // socket started at `tagEpoch=0` and a tagged message-id collision
323
+ // breaks waitForMessage routing.
324
+ const tagPrefix = `${base64UrlEncode(runtime.randomBytes(6))}.`;
325
+ const generateMessageTag = () => `${tagPrefix}${tagEpoch++}`;
326
+ let pairedAccount;
327
+ let cachedAccount;
328
+ // Holds the wrapped store created when the user passed legacy
329
+ // `auth: { creds, keys }` instead of `auth.store`. We need it in
330
+ // `end()` to drain the debounced `saveCreds` timer — `auth.store?.flush?.()`
331
+ // covers the explicit-store path but not this one.
332
+ let autoWrappedStore;
333
+ // Mirrors the engine's `enable_auto_reconnect`, which defaults to on. Only
334
+ // `sock.setAutoReconnect()` moves it, and the dispatcher reads it to tell a
335
+ // transient drop from a terminal one.
336
+ let autoReconnectEnabled = true;
337
+ /** Owns reporting the terminal close: once, after teardown, never not at all. */
338
+ const terminalClose = makeTerminalCloseReporter({
339
+ logger,
340
+ setTimeout: runtime.setTimeout,
341
+ clearTimeout: runtime.clearTimeout
342
+ });
343
+ const runCompletionError = (completion) => {
344
+ let statusCode = DisconnectReason.connectionClosed;
345
+ let message = 'Connection closed';
346
+ if (completion.reason === 'unknown') {
347
+ message = `Connection run ended: ${completion.detail}`;
348
+ }
349
+ else if (completion.reason === 'stopped') {
350
+ message = 'Connection run stopped';
351
+ }
352
+ else if (completion.reason === 'already-running') {
353
+ message = 'Connection run was already running';
354
+ }
355
+ else if (completion.reason === 'auto-reconnect-disabled') {
356
+ const protocol = completion.protocolError;
357
+ if (protocol?.kind === 'conflict') {
358
+ statusCode = DisconnectReason.connectionReplaced;
359
+ message = 'Connection replaced';
360
+ }
361
+ else if (protocol?.kind === 'stream-error') {
362
+ statusCode = mapConnectFailureToDisconnect(protocol.code);
363
+ }
364
+ else if (protocol?.kind === 'connect-failure') {
365
+ statusCode = mapConnectFailureToDisconnect(completionFailureCode(protocol.reason));
366
+ }
367
+ else if (completion.connection?.kind === 'server-close') {
368
+ message = completion.connection.reason;
369
+ }
370
+ }
371
+ return new Boom(message, { statusCode, data: { runCompletion: completion } });
372
+ };
373
+ const reportTerminalClose = (error, publish) => terminalClose.reportAfter(() => owner.close(error).finally(() => initPromise), publish);
374
+ /**
375
+ * Held in a reporter rather than captured, because `sock.onUnexpectedError`
376
+ * is an assignable property: a consumer that replaces it has to be the one
377
+ * the socket's own failure paths reach afterwards.
378
+ */
379
+ const unexpectedErrors = makeUnexpectedErrorReporter(logger);
380
+ const ctx = {
381
+ ev,
382
+ logger,
383
+ fullConfig,
384
+ encodeProto: (path, message) => encodeProtoCompatCore(path, message, runtime.bridge.encodeProto.bind(runtime.bridge)),
385
+ randomBytes: runtime.randomBytes,
386
+ ws,
387
+ reportUnexpectedError: unexpectedErrors.report,
388
+ getUser: () => user,
389
+ getMe: () => {
390
+ const me = auth.creds.me;
391
+ const id = user?.id ?? me?.id;
392
+ if (!id)
393
+ return undefined;
394
+ return { ...me, id, ...(user?.lid ? { lid: user.lid } : {}) };
395
+ },
396
+ setUser: u => {
397
+ user = u;
398
+ },
399
+ withClient: makeWithClient(getClient)
400
+ };
401
+ function getClient() {
402
+ if (initError)
403
+ return Promise.reject(initError);
404
+ // Teardown retains the client through closing to disconnect the transport.
405
+ // Ordinary operations must stop being admitted when close() is called.
406
+ if (owner.isClosing()) {
407
+ return Promise.reject(new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
408
+ }
409
+ // Otherwise gated on `initialized`, not merely on the client
410
+ // existing. `adopt()` publishes it several awaits before
411
+ // `setDeviceProps`, the account lookups and `run()`, so keying off
412
+ // `peek()` alone would hand ordinary calls like `sendMessage()` a
413
+ // half-built client whose read loop has not started — and skip the
414
+ // `initError` check when startup later fails.
415
+ if (initialized) {
416
+ const ready = owner.peek();
417
+ if (ready)
418
+ return Promise.resolve(wrapBridgeClient(ready));
419
+ }
420
+ return initPromise.then(() => {
421
+ if (initError)
422
+ throw initError;
423
+ // Closing may have started while initialization was pending.
424
+ // This gate does not track admitted operations. Bridge 0.21.1 tolerates
425
+ // free() during ordinary calls, but not during disconnect(); release
426
+ // still awaits that drain before freeing the client.
427
+ if (owner.isClosing()) {
428
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
429
+ }
430
+ const built = owner.peek();
431
+ if (!built)
432
+ throw new Boom('Client not initialized', { statusCode: 500 });
433
+ return wrapBridgeClient(built);
434
+ });
435
+ }
436
+ // The native repository delegates Signal state directly to the core and does
437
+ // not need the standalone transaction facade. Keep that facade lazy for the
438
+ // public authState and custom repository contracts that can observe it.
439
+ const signalAuthState = {
440
+ creds: auth.creds,
441
+ keys: fullConfig.makeSignalRepository === makeDefaultSignalRepository ? auth.keys : getExposedKeys()
442
+ };
443
+ bindSignalRepositoryContext(signalAuthState, ctx);
444
+ const signalRepository = fullConfig.makeSignalRepository(signalAuthState, logger);
445
+ const devicesMutex = makeMutex();
446
+ const messageMutex = makeMutex();
447
+ const receiptMutex = makeMutex();
448
+ const appStatePatchMutex = makeMutex();
449
+ const notificationMutex = makeMutex();
450
+ const activeCallContexts = new Map();
451
+ socketEndHandlers.push(() => activeCallContexts.clear());
452
+ const groupMethods = makeGroupMethods(ctx);
453
+ const communityMethods = makeCommunityMethods(ctx, groupMethods);
454
+ const refreshParticipating = makeParticipatingRefreshHandler(ctx, {
455
+ groupFetchAllParticipating: groupMethods.groupFetchAllParticipating,
456
+ communityFetchAllParticipating: communityMethods.communityFetchAllParticipating
457
+ });
458
+ const eventHandlers = makeEventHandlers(ctx, {
459
+ onPairSuccess: data => {
460
+ pairedAccount = data;
461
+ owner
462
+ .peek()
463
+ ?.getAccount?.()
464
+ .then((acc) => {
465
+ cachedAccount = acc ?? undefined;
466
+ })
467
+ .catch(() => { });
468
+ if (auth.store) {
469
+ const refreshAuthState = runtime.refreshAuthState ?? (state => hydrateHostAuthCreds(state.store, state.creds).then(() => undefined));
470
+ void refreshAuthState(auth).then(() => ev.emit('creds.update', auth.creds), error => ctx.reportUnexpectedError(error, 'refreshing credentials after pairing'));
471
+ }
472
+ },
473
+ onIncomingCall: event => {
474
+ const { callId, callCreator, type } = event.action;
475
+ if (type === 'reject' || type === 'accept' || type === 'timeout' || type === 'terminate') {
476
+ activeCallContexts.delete(callId);
477
+ }
478
+ else if (callCreator) {
479
+ activeCallContexts.set(callId, { peer: event.from, callCreator });
480
+ }
481
+ },
482
+ onDirtyState: event => refreshParticipating(event.dirtyType),
483
+ /**
484
+ * The engine has stopped reconnecting, so this client is dead weight
485
+ * that only `free()` reclaims — `run()` returns `void`, so its loop
486
+ * exiting is otherwise invisible from here.
487
+ *
488
+ * Tearing down and reporting are both handed to the reporter: the close
489
+ * has to reach the consumer exactly once and only after this socket has
490
+ * released what it owns, or a replacement built in response overlaps it
491
+ * on the same auth folder.
492
+ */
493
+ onTerminalClose: (error, publish) => {
494
+ // `owner.close()`, not `end()`. `end()` short-circuits when called
495
+ // from inside an end handler — it has to, or the handler awaits the
496
+ // teardown waiting for it — and a terminal event raised from one of
497
+ // those would then publish against an already-resolved promise,
498
+ // letting a close listener build a replacement while the old client
499
+ // is still owned. This waits for the real teardown, and cannot
500
+ // deadlock because `reportAfter` runs it detached; nothing in the
501
+ // teardown is waiting on this.
502
+ reportTerminalClose(error, publish);
503
+ },
504
+ isAutoReconnectEnabled: () => autoReconnectEnabled,
505
+ // Timers the dispatcher armed outlive the events that armed them, and
506
+ // only the terminal-close path clears them. Ending the socket any other
507
+ // way — `sock.end()`, an `await using` scope exiting — has to as well,
508
+ // or one fires from a socket whose client is already freed.
509
+ onCleanup: cleanup => socketEndHandlers.push(cleanup)
510
+ }, {
511
+ ...makeHistoryRuntime(runtime),
512
+ BinaryReader: runtime.bridge.BinaryReader,
513
+ Long: runtime.Long,
514
+ setTimeout: runtime.setTimeout,
515
+ clearTimeout: runtime.clearTimeout
516
+ });
517
+ const init = async () => {
518
+ // Announce startup before awaiting storage, and allow callers to attach
519
+ // listeners first. A slow or failed hydration still has a lifecycle.
520
+ runtime.queueMicrotask(() => {
521
+ if (owner.isClosing())
522
+ return;
523
+ ev.emit('connection.update', {
524
+ connection: 'connecting',
525
+ receivedPendingNotifications: false,
526
+ qr: undefined
527
+ });
528
+ });
529
+ await runtime.waitForAuthState?.(auth);
530
+ // `initWasmEngine` reads `logger.level` synchronously while installing
531
+ // the Rust-side logger: a consumer logger without the pino shape
532
+ // (notably the throwing test double, which has no `level` at all)
533
+ // throws here, before any socket exists. That throw is inside `init()`,
534
+ // so without this guard it becomes an `initError` and `getClient()`
535
+ // reports "Bridge client failed to initialize" instead of connecting.
536
+ // The engine keeps its previous logger in that case, which is fine:
537
+ // Rust-side log routing is process-global and outlives any one socket.
538
+ // A throwing `logger.error` here would surface as an unhandled
539
+ // rejection on a chain the caller never sees, so the fallback call is
540
+ // guarded too.
541
+ try {
542
+ if (claimEngineInitialization()) {
543
+ const bridgeLogger = typeof logger.level === 'string'
544
+ ? logger
545
+ : {
546
+ level: 'silent',
547
+ trace: () => { },
548
+ debug: () => { },
549
+ info: () => { },
550
+ warn: () => { },
551
+ error: () => { }
552
+ };
553
+ runtime.bridge.initWasmEngine(bridgeLogger, runtime.nativeCrypto);
554
+ }
555
+ }
556
+ catch (err) {
557
+ resetEngineInitialization();
558
+ throw err;
559
+ }
560
+ // Auto-promote upstream-Baileys-style `auth: { creds, keys }` to a
561
+ // `JsStoreCallbacks`-shaped store via `wrapLegacyStore`. The synthetic
562
+ // `saveCreds` callback re-emits `creds.update` so the bot's existing
563
+ // `ev.on('creds.update', saveCreds)` listener handles persistence —
564
+ // matches the lifecycle hook every upstream-Baileys setup already
565
+ // wires, so migration needs zero changes to the auth block.
566
+ const useNativeMemory = auth.store ? isNativeMemoryStore(auth.store) : false;
567
+ let bridgeStore = useNativeMemory ? null : (auth.store ?? null);
568
+ if (!bridgeStore && !useNativeMemory && auth.creds && auth.keys) {
569
+ if (!runtime.wrapLegacyStore)
570
+ throw new Error('legacy auth requires the Node runtime');
571
+ const legacyState = { creds: auth.creds, keys: auth.keys };
572
+ const wrapped = await runtime.wrapLegacyStore(legacyState, async () => {
573
+ ev.emit('creds.update', auth.creds);
574
+ }, logger);
575
+ bridgeStore = wrapped;
576
+ // Stash on the closure so `end()` can drain the debounced
577
+ // `saveCreds` timer. `auth.store?.flush?.()` only runs when the
578
+ // caller passed an explicit store — this auto-wrap path needs
579
+ // its own hook.
580
+ autoWrappedStore = wrapped;
581
+ logger.debug('auth: auto-wrapped legacy {creds, keys} via wrapLegacyStore');
582
+ }
583
+ if (useNativeMemory)
584
+ logger.debug('auth: using socket-local native memory backend');
585
+ const created = await runtime.bridge.createWhatsAppClient(makeTransport({ ...fullConfig, setTimeout: runtime.setTimeout, clearTimeout: runtime.clearTimeout }), makeHttpClient(fullConfig), eventHandlers, bridgeStore, fullConfig.cache ?? null, fullConfig.version, fullConfig.wantedPreKeyCount ?? null,
586
+ // Passed through exactly as configured, never normalized by truthiness:
587
+ // the bridge only honours a literal `true` here and rejects any
588
+ // other truthy value at construction, so a `!!`/ternary-style
589
+ // coercion could promote a malformed opt-out into an opt-in.
590
+ // Absent stays strict.
591
+ fullConfig.dangerSkipCertChainVerify, makeHistorySyncAdmission(shouldSyncHistoryMessage));
592
+ // `end()` can land while the client is still being built — a `sock.end()`
593
+ // or `await using` right after `makeWASocket()` does exactly that. When
594
+ // it has, `adopt` frees this client and tells us to stop: nothing else
595
+ // would ever own it, and `run()` below would reconnect it forever
596
+ // against a socket the caller already disposed.
597
+ // `adopt` starts releasing the refused client; joining it here keeps
598
+ // that work inside `initPromise`, which `Symbol.asyncDispose` awaits.
599
+ // `adopt` also refuses when `discard()` already reset a half-built
600
+ // client to `starting` (init failure after adopt): the client is being
601
+ // released by that path, and `run()` below would reconnect a freed
602
+ // handle forever, so stop the same way.
603
+ // Bridge 0.23 can finish the constructor before its initial store
604
+ // enumeration has settled. If teardown won the race, wait on a normal
605
+ // client operation before releasing the refused client so that this
606
+ // initialization work cannot outlive async disposal.
607
+ if (owner.isClosing())
608
+ await created.getJid().catch(() => undefined);
609
+ if (!owner.adopt(created))
610
+ return owner.settled();
611
+ // Fallback for standalone helpers like `downloadContentFromMessage`
612
+ // that carry no socket reference. Registered wrapped so those helpers
613
+ // reject with a caller stack too; the memoized wrap keeps the
614
+ // unregister identity check working.
615
+ _registerActiveBridgeClient(wrapBridgeClient(created), logger);
616
+ // Replay a preference set before the client existed. `setAutoReconnect`
617
+ // forwards through `client?.`, so `makeWASocket(cfg).setAutoReconnect(false)`
618
+ // — the idiomatic first line — used to move only the JS mirror and leave
619
+ // the engine retrying.
620
+ if (!autoReconnectEnabled)
621
+ created.setAutoReconnect(false);
622
+ // Everything below talks to `created`, which stays valid for the whole
623
+ // body, and re-checks `isClosing()` between awaits: once teardown has
624
+ // started it owns this client, and issuing more bridge calls against it
625
+ // races the release.
626
+ if (fullConfig.pushName) {
627
+ await created.setInitialPushName(fullConfig.pushName);
628
+ }
629
+ if (owner.isClosing())
630
+ return;
631
+ const [osName, browserName] = fullConfig.browser;
632
+ const deviceOs = browserName === 'Android' ? 'Android' : osName;
633
+ await created.setDeviceProps({
634
+ os: deviceOs,
635
+ platformType: browserToPlatformType(browserName),
636
+ ...fullConfig.deviceProps
637
+ });
638
+ if (owner.isClosing())
639
+ return;
640
+ const [jid, lid, account] = await Promise.all([
641
+ created.getJid(),
642
+ created.getLid(),
643
+ created.getAccount().catch(() => undefined)
644
+ ]);
645
+ if (owner.isClosing())
646
+ return;
647
+ if (jid) {
648
+ user = { id: jid, lid: lid ?? undefined };
649
+ }
650
+ if (account) {
651
+ cachedAccount = account;
652
+ }
653
+ // Android browser slot flips the noise-handshake identity to
654
+ // `UserAgent.platform = ANDROID` (no `web_info`), mirroring upstream
655
+ // Baileys PR #2201. Required for the server to deliver view_once payloads.
656
+ if (browserName === 'Android') {
657
+ await created.setClientProfile({ preset: 'android', osVersion: osName });
658
+ if (owner.isClosing())
659
+ return;
660
+ }
661
+ if (isRawNodeForwardingEnabled(ws)) {
662
+ created.setRawNodeForwarding(true);
663
+ }
664
+ // Same race as above: teardown already owns and releases this client, so
665
+ // starting the read loop now would run against a handle about to go.
666
+ if (owner.isClosing())
667
+ return;
668
+ // `run()` deliberately returns immediately so callers can use the
669
+ // client while supervision owns its background task. Registering the
670
+ // completion observer after it is started is safe: bridge 0.21.0 admits
671
+ // late observers against the stored result for this run generation.
672
+ created.run();
673
+ const observedClient = created;
674
+ void created
675
+ .waitForRunCompletion()
676
+ .then(completion => {
677
+ // The owner identity is the socket generation fence. A completion
678
+ // from a client that teardown already released must never close a
679
+ // later socket using the same auth state.
680
+ if (owner.isClosing() || owner.peek() !== observedClient)
681
+ return;
682
+ const error = runCompletionError(completion);
683
+ reportTerminalClose(error, () => ev.emit('connection.update', {
684
+ connection: 'close',
685
+ lastDisconnect: { error, date: new Date() }
686
+ }));
687
+ }, error => {
688
+ if (owner.isClosing() || owner.peek() !== observedClient)
689
+ return;
690
+ const closeError = new Boom('Connection run ended without a completion result', {
691
+ statusCode: DisconnectReason.connectionClosed
692
+ });
693
+ reportTerminalClose(closeError, () => ev.emit('connection.update', {
694
+ connection: 'close',
695
+ lastDisconnect: { error: closeError, date: new Date() }
696
+ }));
697
+ try {
698
+ logger.error({ err: error }, 'bridge run completion observation failed');
699
+ }
700
+ catch {
701
+ // A consumer logger cannot prevent the terminal cleanup above.
702
+ }
703
+ })
704
+ .catch(() => {
705
+ // The reporter contains teardown and publish failures; this final guard
706
+ // also contains a consumer logger that throws from an observation path.
707
+ });
708
+ initialized = true;
709
+ };
710
+ /**
711
+ * Joins startup too, not just the teardown.
712
+ *
713
+ * `owner.close()` covers the client it can see. A close landing while
714
+ * `createWhatsAppClient()` is still pending sees none — the client arrives
715
+ * afterwards, `adopt()` refuses it, and the release runs detached. Without
716
+ * waiting for `init()` to finish, `await sock.end()` therefore returns while
717
+ * that client is still disconnecting and being freed, and the replacement
718
+ * socket the consumer builds next overlaps it on the same auth folder.
719
+ *
720
+ * `initPromise` is declared below and swallows its own failures, so this
721
+ * neither hits its TDZ (nothing can call `end` during the synchronous
722
+ * construction below) nor masks the teardown error.
723
+ */
724
+ const end = (error) => {
725
+ // Called from inside an end handler, the teardown is already running and
726
+ // is waiting for that handler to return. Handing back its promise would
727
+ // have the handler await itself.
728
+ if (runningEndHandlers)
729
+ return Promise.resolve();
730
+ return owner.close(error).finally(() => initPromise);
731
+ };
732
+ let initError;
733
+ // Started only once `end` exists. `init()`'s synchronous prefix reaches
734
+ // `await createWhatsAppClient(...)` before the bridge can dispatch anything,
735
+ // so today nothing can call `onTerminalClose` — and therefore `end` — that
736
+ // early. But that is an argument about the current shape of `init()`, not a
737
+ // rule the code enforces: dispatch a terminal close any sooner and line 401
738
+ // becomes a `ReferenceError` inside a bridge callback, where no `try/catch`
739
+ // of ours can reach it. Ordering it here makes the dependency structural.
740
+ const initPromise = init().catch(err => {
741
+ // A failure caused by an explicit shutdown must keep its existing
742
+ // Connection Closed behavior and must not publish a second lifecycle.
743
+ if (owner.isClosing())
744
+ return owner.discard();
745
+ initError = new Boom('Bridge client failed to initialize: ' + (err instanceof Error ? err.message : String(err)), {
746
+ statusCode: 500,
747
+ decorate: { cause: err }
748
+ });
749
+ try {
750
+ logger.error({ err }, 'failed to initialize bridge client');
751
+ }
752
+ catch {
753
+ // A consumer logger cannot prevent the half-built-client
754
+ // cleanup below — and an unguarded throw here surfaces as an
755
+ // unhandled rejection on a chain the caller never sees.
756
+ }
757
+ // Initialization can fail before run() installs its completion observer.
758
+ // Report that failure through the same once-only lifecycle as a run exit.
759
+ // Keep this detached: the reporter joins initPromise after teardown, so
760
+ // awaiting it here would make initialization wait for itself.
761
+ if (!owner.isClosing()) {
762
+ const error = initError;
763
+ reportTerminalClose(error, () => ev.emit('connection.update', {
764
+ connection: 'close',
765
+ lastDisconnect: { error, date: new Date() }
766
+ }));
767
+ }
768
+ // Join teardown without allowing its failure to reject initPromise.
769
+ return owner.discard();
770
+ });
771
+ /**
772
+ * Idempotent shutdown that later callers can actually await — the socket
773
+ * now ends *itself* on a terminal disconnect, so a consumer's
774
+ * `await sock.end()` is usually the second call. Resolving it early while
775
+ * the first was still flushing turned
776
+ * `close` → `await sock.end()` → `makeWASocket()` into two writers on one
777
+ * auth folder.
778
+ */
779
+ const logout = async (msg) => {
780
+ user = undefined;
781
+ const logoutError = new Boom(msg || 'Logged out', { statusCode: DisconnectReason.loggedOut });
782
+ // `Client::logout()` dispatches `LoggedOut` itself, which the dispatcher
783
+ // turns into the terminal close. Reporting our own on top of that gave
784
+ // consumers two `close` events for one logout, and upstream guarantees
785
+ // at most one — so watch for the dispatcher's instead of assuming
786
+ // either way. Counting rather than flagging, because a terminal close
787
+ // may already have happened earlier in this socket's life.
788
+ // `Client::logout()` dispatches `LoggedOut` itself, which the dispatcher
789
+ // turns into the terminal close. Reporting our own on top of that gave
790
+ // consumers two closes for one logout, and upstream guarantees at most
791
+ // one — so watch for the dispatcher's instead of assuming either way.
792
+ const reportedBefore = terminalClose.hasReported();
793
+ const live = owner.peek();
794
+ if (live) {
795
+ try {
796
+ await live.logout();
797
+ }
798
+ catch {
799
+ /* ignore */
800
+ }
801
+ }
802
+ // Nothing announced it: no client at all, or `logout()` threw before the
803
+ // bridge got to it. Upstream always reports exactly one close for a
804
+ // logout, so emitting none would be worse than emitting one too many.
805
+ // Keyed on a close having been *reported*, not on the socket closing —
806
+ // a plain `end()` reports nothing, so keying off that would let a logout
807
+ // racing one finish with no close at all.
808
+ const mayNeedFallback = !reportedBefore && !terminalClose.hasReported();
809
+ try {
810
+ await end(logoutError);
811
+ }
812
+ finally {
813
+ // After the teardown, like the dispatcher's own close: doing it
814
+ // before would hand a logged-out handler a socket still flushing the
815
+ // auth folder it is about to delete. In a `finally` because `end()`
816
+ // rethrows the first flush failure and the owner releases the client
817
+ // regardless — on that path listeners would otherwise see no
818
+ // terminal close at all for a socket that has definitely ended.
819
+ // Rechecked here, not just before the await: a dispatcher close
820
+ // arriving while `end()` ran would otherwise be followed by this
821
+ // stale decision, giving consumers two closes for one logout.
822
+ if (mayNeedFallback && !terminalClose.hasReported()) {
823
+ terminalClose.reportNow(() => ev.emit('connection.update', {
824
+ connection: 'close',
825
+ lastDisconnect: {
826
+ error: logoutError,
827
+ date: new Date()
828
+ }
829
+ }));
830
+ }
831
+ }
832
+ // The close is published on a chain one hop further out than the
833
+ // teardown both paths await, so without this `await sock.logout()`
834
+ // returns just before the event it caused.
835
+ //
836
+ // Skipped when re-entered from an end handler, for the same reason
837
+ // `end()` short-circuits there: the publish waits for the teardown, the
838
+ // teardown waits for the handler, and the handler would be waiting here
839
+ // — stalled until the watchdog fires.
840
+ if (!runningEndHandlers)
841
+ await terminalClose.published();
842
+ };
843
+ const registerSocketEndHandler = (handler) => {
844
+ socketEndHandlers.push(handler);
845
+ };
846
+ const waitForConnectionUpdate = (check, timeoutMs) => {
847
+ return new Promise((resolve, reject) => {
848
+ let timeout;
849
+ const cleanup = () => {
850
+ ev.off('connection.update', listener);
851
+ if (timeout !== undefined)
852
+ runtime.clearTimeout(timeout);
853
+ };
854
+ const listener = async (update) => {
855
+ if (update.connection === 'close') {
856
+ cleanup();
857
+ reject(update.lastDisconnect?.error ??
858
+ new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
859
+ return;
860
+ }
861
+ try {
862
+ if (!(await check(update)))
863
+ return;
864
+ cleanup();
865
+ resolve();
866
+ }
867
+ catch (error) {
868
+ cleanup();
869
+ reject(error);
870
+ }
871
+ };
872
+ ev.on('connection.update', listener);
873
+ if (timeoutMs) {
874
+ timeout = unrefTimer(runtime.setTimeout(() => {
875
+ cleanup();
876
+ reject(new Boom('Timed out waiting for connection update', { statusCode: 408 }));
877
+ }, timeoutMs)
878
+ // Don't keep the process alive if the caller has already stopped
879
+ // awaiting (e.g. sock.end() during shutdown with in-flight queries).
880
+ );
881
+ }
882
+ });
883
+ };
884
+ const fetchReachoutTimelock = async () => {
885
+ const payload = await ctx.withClient(client => client.fetchReachoutTimelock());
886
+ const state = mapReachoutTimelock(payload) ?? { isActive: false };
887
+ ev.emit('connection.update', { reachoutTimeLock: state });
888
+ return state;
889
+ };
890
+ const query = async (node, timeoutMs) => {
891
+ if (!node.attrs.id)
892
+ node.attrs.id = generateMessageTag();
893
+ const result = (await ctx.withClient(client => client.queryNode(node, timeoutMs)));
894
+ assertNodeErrorFree(result);
895
+ return result;
896
+ };
897
+ const waitForMessage = makeTaggedMessageWaiter(ws, logger, fullConfig.defaultQueryTimeoutMs, {
898
+ setTimeout: runtime.setTimeout,
899
+ clearTimeout: runtime.clearTimeout
900
+ });
901
+ const usyncMethods = makeUSyncMethods({
902
+ queryNode: query,
903
+ queryUsync: async (typedQuery) => ctx.withClient(client => client.queryUsync(typedQuery))
904
+ });
905
+ const sock = {
906
+ ev,
907
+ logger,
908
+ ws,
909
+ type: 'md',
910
+ /**
911
+ * `await using sock = makeWASocket(config)` — frees the wasm client on
912
+ * scope exit. Nothing else can: the bridge holds the JS event callbacks
913
+ * as wasm-bindgen externrefs and those callbacks reach back to this
914
+ * closure, so the reference cycle crosses the JS/wasm boundary and no
915
+ * `FinalizationRegistry` will ever fire for the client.
916
+ *
917
+ * Delegates to `end()`, so it flushes the auth store and is idempotent.
918
+ *
919
+ * Then awaits `initPromise`, because `end()` alone does not satisfy the
920
+ * async-disposal contract: called before `createWhatsAppClient()`
921
+ * settles, it sees `client === undefined`, frees nothing, and resolves
922
+ * while initialization is still running. What actually disposes that
923
+ * client is the `ended` guard inside `init()` — so code after the
924
+ * `await using` scope would otherwise overlap with bridge construction,
925
+ * event callbacks, and store access. `end()` runs first because it sets
926
+ * `ended` synchronously, which is what makes `init()` bail out early.
927
+ *
928
+ * The `finally` is load-bearing: `end()` rethrows the first auth-store
929
+ * flush failure, and letting that propagate directly would skip the wait
930
+ * and resolve the disposer with `init()` still in flight — losing the
931
+ * one guarantee it exists to provide, in exactly the situation where
932
+ * cleanup already went wrong. `initPromise` swallows its own failures,
933
+ * so awaiting it here cannot mask the flush error.
934
+ */
935
+ async [Symbol.asyncDispose]() {
936
+ try {
937
+ await end(undefined);
938
+ }
939
+ finally {
940
+ await initPromise;
941
+ }
942
+ },
943
+ // Upstream `socket.ts:1106-1108` returns `authState.creds.me`, which
944
+ // carries `{ id, lid, name, verifiedName, ... }` — full Contact
945
+ // shape. Returning the bare `{id, lid}` like before broke
946
+ // upstream-port code that read `sock.user.name` /
947
+ // `sock.user.verifiedName`. Build the same structure on the fly
948
+ // from the merged auth.creds + paired-account state.
949
+ get user() {
950
+ if (!user?.id)
951
+ return undefined;
952
+ return {
953
+ id: user.id,
954
+ lid: user.lid,
955
+ name: pairedAccount?.businessName ?? auth.creds?.me?.name,
956
+ verifiedName: auth.creds?.me?.verifiedName,
957
+ ...(auth.creds?.me?.phoneNumber ? { phoneNumber: auth.creds.me.phoneNumber } : {})
958
+ };
959
+ },
960
+ get waClient() {
961
+ const live = owner.peek();
962
+ return live && wrapBridgeClient(live);
963
+ },
964
+ get isConnected() {
965
+ return owner.peek()?.isConnected() ?? false;
966
+ },
967
+ get isLoggedIn() {
968
+ return owner.peek()?.isLoggedIn() ?? false;
969
+ },
970
+ get authState() {
971
+ return {
972
+ creds: {
973
+ ...auth.creds,
974
+ ...(user ? { me: { ...auth.creds.me, id: user.id, lid: user.lid } } : {}),
975
+ ...(cachedAccount ? { account: cachedAccount } : {}),
976
+ ...(pairedAccount?.platform ? { platform: pairedAccount.platform } : {})
977
+ },
978
+ keys: getExposedKeys()
979
+ };
980
+ },
981
+ devicesMutex,
982
+ messageMutex,
983
+ receiptMutex,
984
+ appStatePatchMutex,
985
+ notificationMutex,
986
+ generateMessageTag,
987
+ sendNode: async (frame) => {
988
+ return ctx.withClient(client => client.sendNode(frame));
989
+ },
990
+ assertSessions: async (jids, force) => {
991
+ return ctx.withClient(client => client.assertSessions(jids, force ?? false));
992
+ },
993
+ getUSyncDevices: async (jids, useCache, ignoreZeroDevices) => {
994
+ return ctx.withClient(client => client.getUSyncDevices(jids, useCache, ignoreZeroDevices));
995
+ },
996
+ waitForMessage,
997
+ query,
998
+ sendRawMessage: async (data) => {
999
+ return ctx.withClient(client => client.sendRawMessage(data instanceof Uint8Array ? data : new Uint8Array(data)));
1000
+ },
1001
+ /**
1002
+ * `dsmMessage` is accepted so the signature matches upstream, and
1003
+ * refused rather than ignored. Upstream uses it to encrypt a different
1004
+ * plaintext for the caller's own other devices; the engine encrypts one
1005
+ * payload for every recipient, so honouring it is not possible here and
1006
+ * dropping it would send those devices the wrong message.
1007
+ */
1008
+ createParticipantNodes: async (jids, message, extraAttrs, dsmMessage) => {
1009
+ if (dsmMessage) {
1010
+ throw new Boom('createParticipantNodes: dsmMessage is not supported, the engine encrypts one payload for every recipient and cannot substitute a different one for your own devices', { statusCode: 501 });
1011
+ }
1012
+ const bytes = ctx.encodeProto('Message', message);
1013
+ return ctx.withClient(client => client.createParticipantNodesBytes(jids, bytes, extraAttrs ?? {}));
1014
+ },
1015
+ signalRepository,
1016
+ ...makePreKeyMethods(ctx),
1017
+ end,
1018
+ logout,
1019
+ registerSocketEndHandler,
1020
+ waitForConnectionUpdate,
1021
+ setAutoReconnect: (enabled) => {
1022
+ // Mirrored locally because the dispatcher has to know: with this off,
1023
+ // a plain drop is terminal rather than the start of a backoff.
1024
+ autoReconnectEnabled = enabled;
1025
+ owner.peek()?.setAutoReconnect(enabled);
1026
+ },
1027
+ /**
1028
+ * Update presence either globally (`available`/`unavailable`) or per-chat
1029
+ * (`composing`/`recording`/`paused`), matching upstream Baileys' overload.
1030
+ * Chat-state updates require `toJid`; omitting it raises `Boom(400)` so the
1031
+ * caller hears about the protocol mistake instead of the bridge silently
1032
+ * sending nothing.
1033
+ */
1034
+ sendPresenceUpdate: async (type, toJid) => {
1035
+ // Ahead of the client: an off-union value used to fall through to the
1036
+ // chat-state branch and be reported as a missing jid.
1037
+ assertArgumentDomain('sendPresenceUpdate', 'type', type, WA_PRESENCES);
1038
+ return ctx.withClient(async (c) => {
1039
+ if (type === 'available' || type === 'unavailable') {
1040
+ return c.sendPresence(type);
1041
+ }
1042
+ if (!toJid) {
1043
+ throw new Boom(`sendPresenceUpdate('${type}') requires a target jid`, { statusCode: 400 });
1044
+ }
1045
+ return c.sendChatState(toJid, type);
1046
+ });
1047
+ },
1048
+ /**
1049
+ * Plaintext media upload helper, source-compatible with the upstream
1050
+ * Baileys `sock.waUploadToServer(buf, { mediaType })` shape so existing
1051
+ * callers (or `prepareWAMessageMedia(msg, { upload: sock.waUploadToServer })`)
1052
+ * keep working. Delegates to the bridge's encrypt + CDN-failover upload.
1053
+ */
1054
+ waUploadToServer: async (data, opts) => {
1055
+ // The upstream set, which is wider than what the bridge uploads:
1056
+ // `toBridgeMediaType` below still refuses the ones it cannot map.
1057
+ assertArgumentDomain('waUploadToServer', 'mediaType', opts?.mediaType, MEDIA_TYPES);
1058
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
1059
+ return ctx.withClient(client => client.uploadMedia(bytes, toBridgeMediaType(opts.mediaType)));
1060
+ },
1061
+ ...makePrivacyMethods(ctx),
1062
+ updateDefaultDisappearingMode: async (duration) => {
1063
+ await ctx.withClient(client => client.updateDefaultDisappearingMode(duration));
1064
+ },
1065
+ rejectCall: async (callId, callFrom) => {
1066
+ const context = activeCallContexts.get(callId);
1067
+ await ctx.withClient(client => client.rejectCall(callId, context?.peer ?? callFrom, context?.callCreator ?? callFrom));
1068
+ activeCallContexts.delete(callId);
1069
+ },
1070
+ /**
1071
+ * Fetch the account's current reachout-timelock state from the server.
1072
+ *
1073
+ * The same state is also pushed proactively via the
1074
+ * `NotificationUserReachoutTimelockUpdate` MEX notification, which is
1075
+ * surfaced on `connection.update.reachoutTimeLock` automatically. Use
1076
+ * this method to query on demand (e.g. on app start, or after a 463
1077
+ * nack hints that the timelock just kicked in).
1078
+ *
1079
+ * Emits the result on `connection.update.reachoutTimeLock` as a side
1080
+ * effect for parity with the push path. Returns the same state for
1081
+ * callers that prefer awaiting.
1082
+ */
1083
+ fetchReachoutTimelock,
1084
+ /** Upstream Baileys-compatible name. */
1085
+ fetchAccountReachoutTimelock: fetchReachoutTimelock,
1086
+ getBusinessProfile: async (jid) => {
1087
+ return bridgeBusinessProfileToBaileys(await ctx.withClient(client => client.getBusinessProfile(jid)));
1088
+ },
1089
+ fetchMessageHistory: async (count, oldestMsgKey, oldestMsgTimestamp) => {
1090
+ return ctx.withClient(client => client.fetchMessageHistory(count, oldestMsgKey.remoteJid || '', oldestMsgKey.id || '', oldestMsgKey.fromMe || false, typeof oldestMsgTimestamp === 'number' ? oldestMsgTimestamp : oldestMsgTimestamp.toNumber()));
1091
+ },
1092
+ sendStatusMessage: async (message, recipients) => {
1093
+ const bytes = ctx.encodeProto('Message', message);
1094
+ return ctx.withClient(client => client.sendStatusMessageBytes(bytes, recipients));
1095
+ },
1096
+ ...makeMessageMethodsCore(ctx, ctx.encodeProto, runtime.Long),
1097
+ ...groupMethods,
1098
+ ...communityMethods,
1099
+ ...makeContactMethods(ctx),
1100
+ ...makeProfileMethods(ctx),
1101
+ ...makeChatActionMethods(ctx),
1102
+ ...makeInternalMethods(ctx),
1103
+ ...usyncMethods,
1104
+ ...makeStanzaResponseMethods(ctx),
1105
+ ...makePresenceMethods(ctx),
1106
+ ...makeBlockingMethods(ctx),
1107
+ ...makeNewsletterMethods(ctx),
1108
+ ...makeBusinessMethods(ctx),
1109
+ ...makeServerQueryMethods(ctx),
1110
+ downloadMedia: async (message, type, options = {}) => {
1111
+ // Checked here as well as in the helper: the client is awaited while
1112
+ // the context below is built, and a check past that await reports a
1113
+ // stack without the caller in it.
1114
+ assertArgumentDomain('downloadMedia', 'type', type, MEDIA_DOWNLOAD_TYPES);
1115
+ return ctx.withClient(client => downloadMediaMessage(message, type, options, {
1116
+ logger,
1117
+ reuploadRequest: (m) => sock.updateMediaMessage(m),
1118
+ waClient: client
1119
+ }));
1120
+ }
1121
+ };
1122
+ // Assigning replaces the handler the socket itself reports through, rather
1123
+ // than shadowing it with a second one only a consumer could reach.
1124
+ Object.defineProperty(sock, 'onUnexpectedError', {
1125
+ get: () => unexpectedErrors.handler,
1126
+ set: (handler) => {
1127
+ unexpectedErrors.handler = handler;
1128
+ },
1129
+ enumerable: true,
1130
+ configurable: true
1131
+ });
1132
+ return sock;
1133
+ };
1134
+ //# sourceMappingURL=core.js.map