@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
@@ -1,5 +1,5 @@
1
1
  import { Boom } from '../Utils/boom.js';
2
- import { generateProfilePicture } from '../Utils/messages-media.js';
2
+ import { generateProfilePicture } from '../Utils/messages-media-core.js';
3
3
  import { isJidGroup } from '../WABinary/index.js';
4
4
  export const makeProfileMethods = (ctx) => {
5
5
  const setPushName = async (name) => {
@@ -96,5 +96,7 @@ export declare const makeTerminalCloseReporter: (opts: {
96
96
  logger: ILogger;
97
97
  /** Overridable for tests; production uses the constant above. */
98
98
  publishTimeoutMs?: number;
99
+ setTimeout: (callback: () => void, ms: number) => unknown;
100
+ clearTimeout: (handle: unknown) => void;
99
101
  }) => TerminalCloseReporter;
100
102
  //# sourceMappingURL=terminal-close-reporter.d.ts.map
@@ -39,7 +39,7 @@
39
39
  */
40
40
  export const TERMINAL_CLOSE_PUBLISH_TIMEOUT_MS = 60000;
41
41
  export const makeTerminalCloseReporter = (opts) => {
42
- const { logger } = opts;
42
+ const { logger, setTimeout: schedule, clearTimeout: cancel } = opts;
43
43
  const publishTimeoutMs = opts.publishTimeoutMs ?? TERMINAL_CLOSE_PUBLISH_TIMEOUT_MS;
44
44
  /**
45
45
  * Claims, not deliveries — see `hasReported`. At most one: a socket has a
@@ -93,12 +93,12 @@ export const makeTerminalCloseReporter = (opts) => {
93
93
  // built the replacement never runs, which is what this guards.
94
94
  // Cleared the moment teardown settles, so it holds the loop only
95
95
  // while one is in flight.
96
- const watchdog = setTimeout(() => {
96
+ const watchdog = schedule(() => {
97
97
  logger.error({ afterMs: publishTimeoutMs }, 'socket teardown is still running; reporting the close anyway');
98
98
  publishOnce();
99
99
  }, publishTimeoutMs);
100
100
  const finish = (err) => {
101
- clearTimeout(watchdog);
101
+ cancel(watchdog);
102
102
  if (err)
103
103
  logger.error({ err }, 'socket teardown failed after a terminal disconnect');
104
104
  publishOnce();
@@ -5,6 +5,8 @@ interface TransportConfig {
5
5
  logger: ILogger;
6
6
  /** RequestInit options passed to fetch() — use `dispatcher` for proxy/TLS config */
7
7
  options?: RequestInit;
8
+ setTimeout?: (callback: () => void, ms: number) => unknown;
9
+ clearTimeout?: (handle: unknown) => void;
8
10
  }
9
11
  export declare const makeTransport: (config: TransportConfig) => JsTransportCallbacks;
10
12
  export declare const makeHttpClient: (config: TransportConfig) => JsHttpClientConfig;
@@ -1,3 +1,4 @@
1
+ import { unrefTimer } from '../Runtime/bytes.js';
1
2
  /**
2
3
  * `WebSocket.send()` takes a `BufferSource`, which is `ArrayBufferView<ArrayBuffer>
3
4
  * | ArrayBuffer` — a `SharedArrayBuffer`-backed view is outside that contract.
@@ -132,7 +133,21 @@ export const makeTransport = (config) => {
132
133
  }
133
134
  // Bound the wait so a pathological close (e.g. half-open TCP peer
134
135
  // never acking FIN) can't hang shutdown beyond a short grace period.
135
- await Promise.race([closed, new Promise(r => setTimeout(r, 500).unref())]);
136
+ const schedule = config.setTimeout ?? ((callback, ms) => setTimeout(callback, ms));
137
+ const cancel = config.clearTimeout ?? (timerHandle => clearTimeout(timerHandle));
138
+ let timer;
139
+ try {
140
+ await Promise.race([
141
+ closed,
142
+ new Promise(resolve => {
143
+ timer = unrefTimer(schedule(resolve, 500));
144
+ })
145
+ ]);
146
+ }
147
+ finally {
148
+ if (timer !== undefined)
149
+ cancel(timer);
150
+ }
136
151
  }
137
152
  };
138
153
  };
@@ -8,6 +8,8 @@ export interface SocketContext extends ClientOperations {
8
8
  ev: ReturnType<typeof makeEventBuffer>;
9
9
  logger: ILogger;
10
10
  fullConfig: SocketConfig;
11
+ encodeProto?: (path: string, message: unknown) => Uint8Array;
12
+ randomBytes?: (length: number) => Uint8Array;
11
13
  getUser: () => {
12
14
  id?: string;
13
15
  lid?: string;
@@ -141,5 +141,16 @@ export type AuthenticationState = {
141
141
  flush?(): Promise<void>;
142
142
  };
143
143
  };
144
+ /**
145
+ * Store-first auth input: a caller-owned byte store is enough — the socket
146
+ * completes the public view (credential mirror + key facade) from it.
147
+ * `makeWASocket({ auth: { store } })` works without `fs`, without legacy
148
+ * `{ creds, keys }`, without `Buffer`.
149
+ */
150
+ export type NativeAuthenticationState = {
151
+ store: NonNullable<AuthenticationState['store']>;
152
+ creds?: AuthenticationState['creds'];
153
+ keys?: AuthenticationState['keys'];
154
+ };
144
155
  export {};
145
156
  //# sourceMappingURL=Auth.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import type Long from 'long';
2
2
  import type { Readable } from 'stream';
3
3
  import type { URL } from 'url';
4
- import type { MediaType as BridgeMediaType, UploadMediaResult, WasmWhatsAppClient } from '@oxidezap/whatsapp-rust-bridge';
4
+ import type { MediaType as BridgeMediaType, UploadMediaResult, WasmWhatsAppClient } from '@oxidezap/whatsapp-rust-bridge/host';
5
5
  import type { WAMessageAddressingMode as WAMessageAddressingModeType } from '../Compatibility/public-api/enum-types.js';
6
6
  import { proto } from '../WAProto/runtime.js';
7
7
  import type { MediaType } from '../Defaults/index.js';
@@ -1,8 +1,8 @@
1
1
  import type { Agent } from 'node:https';
2
2
  import type { URL } from 'url';
3
- import type { CacheConfig, DevicePropsInput } from '@oxidezap/whatsapp-rust-bridge';
3
+ import type { CacheConfig, DevicePropsInput } from '@oxidezap/whatsapp-rust-bridge/host';
4
4
  import type { proto } from '../WAProto/runtime.js';
5
- export type { DeviceAppVersion, DeviceHistorySyncConfig, DevicePlatformType, DevicePropsInput } from '@oxidezap/whatsapp-rust-bridge';
5
+ export type { DeviceAppVersion, DeviceHistorySyncConfig, DevicePlatformType, DevicePropsInput } from '@oxidezap/whatsapp-rust-bridge/host';
6
6
  import type { ILogger } from '../Utils/logger.js';
7
7
  import type { AuthenticationState, LIDMapping, SignalAuthState } from './Auth.js';
8
8
  import type { GroupMetadata } from './GroupMetadata.js';
@@ -13,9 +13,14 @@ export * from './Newsletter.js';
13
13
  export * from './Product.js';
14
14
  export * from './Signal.js';
15
15
  import type { DisconnectReason as DisconnectReasonType } from '../Compatibility/public-api/enum-types.js';
16
- import type { AuthenticationState } from './Auth.js';
16
+ import type { AuthenticationState, NativeAuthenticationState } from './Auth.js';
17
17
  import type { SocketConfig } from './Socket.js';
18
18
  export type UserFacingSocketConfig = Partial<SocketConfig> & {
19
+ auth: AuthenticationState | NativeAuthenticationState;
20
+ };
21
+ /** Host-only socket config requiring the asynchronously hydrated host auth shape. */
22
+ export type HostSocketConfig = Omit<Partial<SocketConfig>, 'auth'> & {
23
+ /** Build with `await createAuthenticationState(store)`; raw `{ store }` is not a valid host auth value. */
19
24
  auth: AuthenticationState;
20
25
  };
21
26
  export type BrowsersMap = {
@@ -1,4 +1,8 @@
1
1
  import type { BrowsersMap } from '../Types/index.js';
2
2
  export declare const Browsers: BrowsersMap;
3
+ export declare const setPlatformInfo: (info: {
4
+ os: string;
5
+ release: string;
6
+ } | undefined) => void;
3
7
  export declare const getPlatformId: (browser: string) => string;
4
8
  //# sourceMappingURL=browser-utils.d.ts.map
@@ -1,4 +1,3 @@
1
- import { platform, release } from 'node:os';
2
1
  import { proto } from '../WAProto/runtime.js';
3
2
  const PLATFORM_MAP = {
4
3
  aix: 'AIX',
@@ -19,7 +18,59 @@ export const Browsers = {
19
18
  baileys: browser => ['Baileys', browser, '6.5.0'],
20
19
  windows: browser => ['Windows', browser, '10.0.22631'],
21
20
  android: osVersion => [osVersion, 'Android', ''],
22
- appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
21
+ appropriate: browser => [
22
+ PLATFORM_MAP[resolvePlatform()] || 'Ubuntu',
23
+ browser,
24
+ resolveRelease()
25
+ ]
26
+ };
27
+ /**
28
+ * Host-overridable platform identity behind `Browsers.appropriate()`.
29
+ * Defaults to the Node values; hosts set it once via `setPlatformInfo()`
30
+ * (stable Ubuntu fallback when unset) instead of branching on runtimes.
31
+ */
32
+ let platformOverride;
33
+ export const setPlatformInfo = (info) => {
34
+ platformOverride = info;
35
+ };
36
+ const resolvePlatform = () => platformOverride?.os ?? nodePlatform();
37
+ const resolveRelease = () => platformOverride?.release ?? nodeRelease();
38
+ // Same lazy-builtin shape as the release below: `process.platform` is
39
+ // available on hosts that polyfill it, otherwise the stable fallback.
40
+ const nodePlatform = () => {
41
+ try {
42
+ const value = globalThis.process;
43
+ if (typeof value?.platform === 'string')
44
+ return value.platform;
45
+ const builtin = value?.getBuiltinModule?.('os')?.platform?.();
46
+ if (typeof builtin === 'string')
47
+ return builtin;
48
+ }
49
+ catch {
50
+ /* fall through to the stable fallback */
51
+ }
52
+ return 'linux';
53
+ };
54
+ // `node:os` is the only reader: dynamic import keeps the static graph
55
+ // host-neutral (workerd has no node:os) while preserving the exact Node
56
+ // values. Synchronous require would reintroduce the static import.
57
+ let cachedRelease;
58
+ const nodeRelease = () => {
59
+ if (cachedRelease !== undefined)
60
+ return cachedRelease;
61
+ try {
62
+ const os = globalThis.process?.getBuiltinModule?.('os');
63
+ const value = os?.release?.();
64
+ if (typeof value === 'string' && value.length > 0) {
65
+ cachedRelease = value;
66
+ return value;
67
+ }
68
+ }
69
+ catch {
70
+ /* fall through to the stable fallback */
71
+ }
72
+ cachedRelease = '22.04.4';
73
+ return cachedRelease;
23
74
  };
24
75
  export const getPlatformId = (browser) => {
25
76
  // Generated enum objects support reverse name lookup at runtime.
@@ -26,6 +26,7 @@ export declare function aesDecryptWithIV(buffer: Uint8Array, key: Uint8Array, IV
26
26
  export declare function aesEncrypt(buffer: Uint8Array, key: Uint8Array): Buffer<ArrayBuffer>;
27
27
  export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
28
28
  export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
29
+ export { sha256Sync as sha256Portable } from '../Runtime/bytes.js';
29
30
  export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
30
31
  export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
31
32
  //# sourceMappingURL=crypto.d.ts.map
@@ -65,6 +65,7 @@ export function aesEncrypWithIV(buffer, key, IV) {
65
65
  export function hmacSign(buffer, key, variant = 'sha256') {
66
66
  return Buffer.from(hmacDigest(variant, key, buffer));
67
67
  }
68
+ export { sha256Sync as sha256Portable } from '../Runtime/bytes.js';
68
69
  export function sha256(buffer) {
69
70
  return createHash('sha256').update(buffer).digest();
70
71
  }
@@ -1,5 +1,6 @@
1
1
  import type { BaileysEventEmitter, BaileysEventMap } from '../Types/index.js';
2
2
  import type { ILogger } from './logger.js';
3
+ import type { RuntimeEventEmitter } from '../Runtime/types.js';
3
4
  type BaileysEventData = Partial<BaileysEventMap>;
4
5
  type BaileysBufferableEventEmitter = BaileysEventEmitter & {
5
6
  process(handler: (events: BaileysEventData) => void | Promise<void>): () => void;
@@ -13,6 +14,10 @@ type BaileysBufferableEventEmitter = BaileysEventEmitter & {
13
14
  * Upstream-compatible event buffer. Non-buffered events stay synchronous;
14
15
  * bufferable events are consolidated and released as one `process()` map.
15
16
  */
16
- export declare const makeEventBuffer: (logger: ILogger) => BaileysBufferableEventEmitter;
17
+ export type EventBufferTimers = {
18
+ setTimeout(callback: () => void, ms: number): unknown;
19
+ clearTimeout(handle: unknown): void;
20
+ };
21
+ export declare const makeEventBuffer: (logger: ILogger, timers?: EventBufferTimers, emitter?: RuntimeEventEmitter) => BaileysBufferableEventEmitter;
17
22
  export {};
18
23
  //# sourceMappingURL=event-buffer.d.ts.map
@@ -1,8 +1,8 @@
1
- import EventEmitter from 'node:events';
1
+ import EventEmitter from 'events';
2
2
  import { WAMessageStatus } from '../Types/index.js';
3
- import { trimUndefined } from './generics.js';
4
- import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js';
5
- import { isRealMessage, shouldIncrementChatUnread } from './process-message.js';
3
+ import { trimUndefined, updateMessageWithReaction, updateMessageWithReceipt } from '../Media/mutations.js';
4
+ import { unrefTimer } from '../Runtime/bytes.js';
5
+ import { isRealMessage, shouldIncrementChatUnread } from './process-message-core.js';
6
6
  const BUFFERABLE_EVENTS = [
7
7
  'messaging-history.set',
8
8
  'chats.upsert',
@@ -385,12 +385,12 @@ const consolidateEvents = (data) => {
385
385
  assignArray('groups.update', Object.values(data.groupUpdates));
386
386
  return events;
387
387
  };
388
- /**
389
- * Upstream-compatible event buffer. Non-buffered events stay synchronous;
390
- * bufferable events are consolidated and released as one `process()` map.
391
- */
392
- export const makeEventBuffer = (logger) => {
393
- const ev = new EventEmitter();
388
+ const defaultEventBufferTimers = {
389
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
390
+ clearTimeout: handle => clearTimeout(handle)
391
+ };
392
+ export const makeEventBuffer = (logger, timers = defaultEventBufferTimers, emitter = new EventEmitter()) => {
393
+ const ev = emitter;
394
394
  const historyCache = new Set();
395
395
  let data = makeBufferData();
396
396
  let buffering = false;
@@ -438,10 +438,10 @@ export const makeEventBuffer = (logger) => {
438
438
  return false;
439
439
  buffering = false;
440
440
  bufferCount = 0;
441
- if (bufferTimeout)
442
- clearTimeout(bufferTimeout);
443
- if (flushPendingTimeout)
444
- clearTimeout(flushPendingTimeout);
441
+ if (bufferTimeout !== undefined)
442
+ timers.clearTimeout(bufferTimeout);
443
+ if (flushPendingTimeout !== undefined)
444
+ timers.clearTimeout(flushPendingTimeout);
445
445
  bufferTimeout = undefined;
446
446
  flushPendingTimeout = undefined;
447
447
  if (historyCache.size > 10000)
@@ -466,15 +466,14 @@ export const makeEventBuffer = (logger) => {
466
466
  if (!buffering) {
467
467
  buffering = true;
468
468
  bufferCount = 0;
469
- if (bufferTimeout)
470
- clearTimeout(bufferTimeout);
471
- bufferTimeout = setTimeout(() => {
469
+ if (bufferTimeout !== undefined)
470
+ timers.clearTimeout(bufferTimeout);
471
+ bufferTimeout = unrefTimer(timers.setTimeout(() => {
472
472
  if (buffering) {
473
473
  logger.warn('Buffer timeout reached, auto-flushing');
474
474
  flush();
475
475
  }
476
- }, 30000);
477
- bufferTimeout.unref?.();
476
+ }, 30000));
478
477
  }
479
478
  bufferCount += 1;
480
479
  };
@@ -510,7 +509,10 @@ export const makeEventBuffer = (logger) => {
510
509
  ev.off(event, listener);
511
510
  },
512
511
  removeAllListeners: event => {
513
- ev.removeAllListeners(event);
512
+ if (event === undefined)
513
+ ev.removeAllListeners();
514
+ else
515
+ ev.removeAllListeners(event);
514
516
  },
515
517
  buffer,
516
518
  flush,
@@ -523,18 +525,17 @@ export const makeEventBuffer = (logger) => {
523
525
  }
524
526
  finally {
525
527
  bufferCount = Math.max(0, bufferCount - 1);
526
- if (bufferCount === 0 && !flushPendingTimeout) {
527
- flushPendingTimeout = setTimeout(flush, 100);
528
- flushPendingTimeout.unref?.();
528
+ if (bufferCount === 0 && flushPendingTimeout === undefined) {
529
+ flushPendingTimeout = unrefTimer(timers.setTimeout(flush, 100));
529
530
  }
530
531
  }
531
532
  };
532
533
  },
533
534
  destroy() {
534
- if (bufferTimeout)
535
- clearTimeout(bufferTimeout);
536
- if (flushPendingTimeout)
537
- clearTimeout(flushPendingTimeout);
535
+ if (bufferTimeout !== undefined)
536
+ timers.clearTimeout(bufferTimeout);
537
+ if (flushPendingTimeout !== undefined)
538
+ timers.clearTimeout(flushPendingTimeout);
538
539
  historyCache.clear();
539
540
  data = makeBufferData();
540
541
  buffering = false;
@@ -1,3 +1,4 @@
1
+ import { Buffer } from 'node:buffer';
1
2
  import type { WAUrlInfo } from '../Types/Message.js';
2
3
  import type { ILogger } from './logger.js';
3
4
  /**
@@ -34,10 +35,10 @@ export type URLGenerationOptions = {
34
35
  */
35
36
  /** Exported under an underscore so the destination guard can be driven directly. */
36
37
  export declare const _getCompressedJpegThumbnail: (url: string, pageUrl: string, { thumbnailWidth, fetchOpts }: URLGenerationOptions) => Promise<{
37
- buffer: any;
38
+ buffer: Buffer<ArrayBufferLike>;
38
39
  original: {
39
- width: any;
40
- height: any;
40
+ width: number | undefined;
41
+ height: number | undefined;
41
42
  };
42
43
  }>;
43
44
  /**
@@ -64,6 +64,9 @@ export interface FallbackLineInput {
64
64
  * without hiding the `pino` peer. Never throws.
65
65
  */
66
66
  export declare const formatFallbackLine: ({ method, currentLevel, bindings, msgPrefix, args }: FallbackLineInput) => string | undefined;
67
+ export declare const setLoggerSink: (sink: ((line: string, delivered: () => void) => void) | undefined) => void;
68
+ /** A fallback logger whose sink belongs to one runtime factory, never process-global. */
69
+ export declare const createRuntimeLogger: (sink: (line: string, delivered: () => void) => void, level?: string) => Logger;
67
70
  declare const _default: Logger;
68
71
  export default _default;
69
72
  //# sourceMappingURL=logger.d.ts.map
@@ -220,7 +220,30 @@ const noteFallbackDelivered = () => {
220
220
  resume();
221
221
  }
222
222
  };
223
- const writeFallbackLine = (line) => {
223
+ /**
224
+ * Where fallback lines go. Node writes stdout (preserving the
225
+ * drain-aware flush contract); hosts call `setLoggerSink()` once (console
226
+ * by default) instead of branching on runtimes at every call site.
227
+ */
228
+ let loggerSink;
229
+ export const setLoggerSink = (sink) => {
230
+ loggerSink = sink;
231
+ };
232
+ const defaultSink = (line, delivered) => {
233
+ try {
234
+ const stdout = globalThis.process?.stdout;
235
+ if (!stdout) {
236
+ console.log(line);
237
+ delivered();
238
+ return;
239
+ }
240
+ stdout.write(`${line}\n`, delivered);
241
+ }
242
+ catch {
243
+ delivered();
244
+ }
245
+ };
246
+ const writeFallbackLine = (line, sink) => {
224
247
  fallbackPendingWrites++;
225
248
  let settled = false;
226
249
  const delivered = () => {
@@ -230,7 +253,8 @@ const writeFallbackLine = (line) => {
230
253
  noteFallbackDelivered();
231
254
  };
232
255
  try {
233
- process.stdout.write(`${line}\n`, delivered);
256
+ ;
257
+ (sink ?? loggerSink ?? defaultSink)(line, delivered);
234
258
  }
235
259
  catch {
236
260
  delivered();
@@ -254,7 +278,7 @@ const createFallbackLogger = (state) => {
254
278
  args
255
279
  });
256
280
  if (line !== undefined)
257
- writeFallbackLine(line);
281
+ writeFallbackLine(line, state.sink);
258
282
  };
259
283
  const logger = {
260
284
  get level() {
@@ -280,7 +304,8 @@ const createFallbackLogger = (state) => {
280
304
  level: options?.level ?? state.level,
281
305
  msgPrefix: `${state.msgPrefix ?? ''}${typeof options?.msgPrefix === 'string' ? options.msgPrefix : ''}` || undefined,
282
306
  onChild: state.onChild,
283
- bindings: { ...state.bindings, ...extra }
307
+ bindings: { ...state.bindings, ...extra },
308
+ sink: state.sink
284
309
  });
285
310
  state.onChild(created);
286
311
  return created;
@@ -311,6 +336,8 @@ const createFallbackLogger = (state) => {
311
336
  };
312
337
  return logger;
313
338
  };
339
+ /** A fallback logger whose sink belongs to one runtime factory, never process-global. */
340
+ export const createRuntimeLogger = (sink, level = DEFAULT_LEVEL) => createFallbackLogger({ level, onChild: () => { }, bindings: { name: 'baileyrs' }, sink });
314
341
  const loadPinoPeer = () => loadOptionalPeer('pino');
315
342
  /**
316
343
  * Deferred because building pino at module evaluation cost ~10 MB of RSS in every
@@ -325,7 +352,8 @@ const loadPinoPeer = () => loadOptionalPeer('pino');
325
352
  let rootLogger;
326
353
  const resolveRootLogger = () => {
327
354
  if (!rootLogger) {
328
- const configuredLevel = process.env.BAILEYRS_LOG_LEVEL || DEFAULT_LEVEL;
355
+ const configuredLevel = globalThis.process?.env
356
+ ?.BAILEYRS_LOG_LEVEL || DEFAULT_LEVEL;
329
357
  const peer = loadPinoPeer();
330
358
  rootLogger = peer
331
359
  ? peer({
@@ -358,7 +386,8 @@ const createDeferredLogger = (bindings, parent, childOptions) => {
358
386
  pendingLevel ??
359
387
  childOptions?.level ??
360
388
  parent?.level() ??
361
- process.env.BAILEYRS_LOG_LEVEL ??
389
+ globalThis.process?.env
390
+ ?.BAILEYRS_LOG_LEVEL ??
362
391
  DEFAULT_LEVEL;
363
392
  const self = { level: peekLevel, resolve };
364
393
  // Hoisted so `logger.child` keeps the stable identity a plain property has.