@oxidezap/baileyrs 0.3.6 → 0.3.8

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 (130) hide show
  1. package/README.md +67 -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 -19
  11. package/lib/Compatibility/encode-proto.js +3 -35
  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.d.ts +5 -0
  24. package/lib/Compatibility/proto-runtime.js +214 -32
  25. package/lib/Compatibility/socket-results.d.ts +1 -1
  26. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  27. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  28. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  29. package/lib/Compatibility/websocket-client.d.ts +11 -3
  30. package/lib/Compatibility/websocket-client.js +84 -11
  31. package/lib/Defaults/index.d.ts +8 -8
  32. package/lib/Defaults/index.js +8 -8
  33. package/lib/Media/content.d.ts +28 -0
  34. package/lib/Media/content.js +129 -0
  35. package/lib/Media/core.d.ts +34 -0
  36. package/lib/Media/core.js +120 -0
  37. package/lib/Media/mutations.d.ts +24 -0
  38. package/lib/Media/mutations.js +38 -0
  39. package/lib/Runtime/aes-gcm.d.ts +4 -0
  40. package/lib/Runtime/aes-gcm.js +11 -0
  41. package/lib/Runtime/bridge.d.ts +44 -0
  42. package/lib/Runtime/bridge.js +76 -0
  43. package/lib/Runtime/buffer.d.ts +9 -0
  44. package/lib/Runtime/buffer.js +22 -0
  45. package/lib/Runtime/bytes.d.ts +61 -0
  46. package/lib/Runtime/bytes.js +270 -0
  47. package/lib/Runtime/host.d.ts +22 -0
  48. package/lib/Runtime/host.js +43 -0
  49. package/lib/Runtime/long.d.ts +33 -0
  50. package/lib/Runtime/long.js +64 -0
  51. package/lib/Runtime/node-media-processors.d.ts +4 -0
  52. package/lib/Runtime/node-media-processors.js +29 -0
  53. package/lib/Runtime/node-media.d.ts +28 -0
  54. package/lib/Runtime/node-media.js +115 -0
  55. package/lib/Runtime/node.d.ts +14 -0
  56. package/lib/Runtime/node.js +81 -0
  57. package/lib/Runtime/paths.d.ts +4 -0
  58. package/lib/Runtime/paths.js +7 -0
  59. package/lib/Runtime/stream.d.ts +11 -0
  60. package/lib/Runtime/stream.js +25 -0
  61. package/lib/Runtime/types.d.ts +98 -0
  62. package/lib/Runtime/types.js +13 -0
  63. package/lib/Socket/core.d.ts +312 -0
  64. package/lib/Socket/core.js +1122 -0
  65. package/lib/Socket/events-core.d.ts +75 -0
  66. package/lib/Socket/events-core.js +1058 -0
  67. package/lib/Socket/events.d.ts +1 -63
  68. package/lib/Socket/events.js +4 -1047
  69. package/lib/Socket/groups.js +4 -3
  70. package/lib/Socket/index.d.ts +521 -103
  71. package/lib/Socket/index.js +10 -1007
  72. package/lib/Socket/messages-core.d.ts +41 -0
  73. package/lib/Socket/messages-core.js +270 -0
  74. package/lib/Socket/messages.d.ts +9 -36
  75. package/lib/Socket/messages.js +3 -260
  76. package/lib/Socket/newsletter.js +3 -3
  77. package/lib/Socket/profile.js +1 -1
  78. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  79. package/lib/Socket/terminal-close-reporter.js +3 -3
  80. package/lib/Socket/transport.d.ts +2 -0
  81. package/lib/Socket/transport.js +16 -1
  82. package/lib/Socket/types.d.ts +2 -0
  83. package/lib/Types/Auth.d.ts +11 -0
  84. package/lib/Types/Message.d.ts +1 -1
  85. package/lib/Types/Socket.d.ts +2 -2
  86. package/lib/Types/index.d.ts +6 -1
  87. package/lib/Utils/browser-utils.d.ts +4 -0
  88. package/lib/Utils/browser-utils.js +53 -2
  89. package/lib/Utils/crypto.d.ts +1 -0
  90. package/lib/Utils/crypto.js +1 -0
  91. package/lib/Utils/event-buffer.d.ts +6 -1
  92. package/lib/Utils/event-buffer.js +28 -27
  93. package/lib/Utils/link-preview.d.ts +4 -3
  94. package/lib/Utils/logger.d.ts +3 -0
  95. package/lib/Utils/logger.js +35 -6
  96. package/lib/Utils/messages-core.d.ts +174 -0
  97. package/lib/Utils/messages-core.js +1042 -0
  98. package/lib/Utils/messages-media-core.d.ts +73 -0
  99. package/lib/Utils/messages-media-core.js +319 -0
  100. package/lib/Utils/messages-media.d.ts +1 -72
  101. package/lib/Utils/messages-media.js +9 -358
  102. package/lib/Utils/messages.d.ts +1 -166
  103. package/lib/Utils/messages.js +7 -1040
  104. package/lib/Utils/optional-peer.js +14 -5
  105. package/lib/Utils/process-history-message-core.d.ts +36 -0
  106. package/lib/Utils/process-history-message-core.js +187 -0
  107. package/lib/Utils/process-history-message.d.ts +5 -43
  108. package/lib/Utils/process-history-message.js +11 -197
  109. package/lib/Utils/process-message-core.d.ts +29 -0
  110. package/lib/Utils/process-message-core.js +112 -0
  111. package/lib/Utils/process-message.d.ts +4 -24
  112. package/lib/Utils/process-message.js +6 -111
  113. package/lib/WABinary/generic-utils.js +7 -5
  114. package/lib/host-shared.d.ts +74 -0
  115. package/lib/host-shared.js +15 -0
  116. package/lib/host-socket-operations.d.ts +3 -0
  117. package/lib/host-socket-operations.js +2 -0
  118. package/lib/host-surface.d.ts +21 -0
  119. package/lib/host-surface.js +35 -0
  120. package/lib/host-types.d.ts +356 -0
  121. package/lib/host-types.js +2 -0
  122. package/lib/host.d.ts +33 -0
  123. package/lib/host.js +31 -0
  124. package/lib/node-surface.d.ts +9 -0
  125. package/lib/node-surface.js +15 -0
  126. package/lib/surface.d.ts +5 -0
  127. package/lib/surface.js +6 -0
  128. package/lib/wasm.d.ts +27 -0
  129. package/lib/wasm.js +27 -0
  130. package/package.json +18 -6
@@ -1,5 +1,29 @@
1
+ import { Buffer } from 'node:buffer';
1
2
  import { initAuthCreds } from '../../Utils/generics.js';
3
+ import { hydrateHostAuthCreds } from '../host-auth-state.js';
2
4
  import { projectNativeStore } from '../legacy-store/native-projection.js';
5
+ const hydrationByState = new WeakMap();
6
+ const preserveNodeCredentialBytes = (creds) => {
7
+ for (const pair of [
8
+ creds.noiseKey,
9
+ creds.pairingEphemeralKeyPair,
10
+ creds.signedIdentityKey,
11
+ creds.signedPreKey.keyPair
12
+ ]) {
13
+ pair.private = Buffer.from(pair.private);
14
+ pair.public = Buffer.from(pair.public);
15
+ }
16
+ creds.signedPreKey.signature = Buffer.from(creds.signedPreKey.signature);
17
+ if (creds.routingInfo)
18
+ creds.routingInfo = Buffer.from(creds.routingInfo);
19
+ };
20
+ export const refreshSocketAuthenticationState = async (state) => {
21
+ if (!state.store)
22
+ return;
23
+ await hydrateHostAuthCreds(state.store, state.creds);
24
+ preserveNodeCredentialBytes(state.creds);
25
+ };
26
+ export const waitForSocketAuthenticationState = (state) => hydrationByState.get(state) ?? Promise.resolve();
3
27
  /**
4
28
  * Complete the public authentication view used by the socket when callers use
5
29
  * the native byte-store path. The byte store remains authoritative: the key
@@ -16,6 +40,15 @@ export const normalizeSocketAuthenticationState = (input) => {
16
40
  if (!creds || !keys) {
17
41
  throw new TypeError('auth must provide both creds and keys when no native store is configured');
18
42
  }
19
- return { creds, keys, ...(store ? { store } : {}) };
43
+ const state = { creds, keys, ...(store ? { store } : {}) };
44
+ if (store && !input.creds) {
45
+ const hydration = refreshSocketAuthenticationState(state);
46
+ // The socket initialization awaits the original promise. Attach a
47
+ // rejection observer immediately so a synchronously rejecting store does
48
+ // not become an unhandled rejection before init reaches its first await.
49
+ void hydration.catch(() => undefined);
50
+ hydrationByState.set(state, hydration);
51
+ }
52
+ return state;
20
53
  };
21
54
  //# sourceMappingURL=auth-state.js.map
@@ -0,0 +1,4 @@
1
+ import type { AuthenticationState, NativeAuthenticationState } from '../../Types/index.js';
2
+ /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
3
+ export declare const normalizeHostAuthenticationState: (input: AuthenticationState | NativeAuthenticationState) => AuthenticationState;
4
+ //# sourceMappingURL=host-auth-state.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
2
+ export const normalizeHostAuthenticationState = (input) => {
3
+ if (!input || typeof input !== 'object')
4
+ throw new TypeError('auth must provide either { creds, keys } or a native store');
5
+ if (input.creds && input.keys)
6
+ return input;
7
+ if (input.store && input.creds)
8
+ return input;
9
+ if (input.store) {
10
+ throw new TypeError('host auth with a native store must be created with await createAuthenticationState(store)');
11
+ }
12
+ throw new TypeError('auth must provide both creds and keys when no native store is configured');
13
+ };
14
+ //# sourceMappingURL=host-auth-state.js.map
@@ -1,9 +1,9 @@
1
1
  // Device credential projection for legacy Baileys authentication states.
2
- import { Buffer } from 'node:buffer';
3
2
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
3
+ import { base64Decode, base64Encode, publicBytes } from '../../Runtime/bytes.js';
4
4
  import { WA_DEFAULT_VERSION } from '../../Defaults/index.js';
5
5
  import { jidDecode, jidEncode } from '../../WABinary/jid-utils.js';
6
- import { DeviceRecordKey, JsonByteEncoding, SignalDomain, SignalKeyLength, TimeValue } from './constants.js';
6
+ import { DeviceRecordKey, SignalDomain, SignalKeyLength, TimeValue } from './constants.js';
7
7
  import { bytesToNumbers, fromJsonBytes, toJsonBytes } from './common.js';
8
8
  import { isAllZero, requireByteArray, requireSafeUnsignedInteger } from './validation.js';
9
9
  const signedDeviceIdentityCodec = proto.ADVSignedDeviceIdentity;
@@ -73,7 +73,7 @@ function deviceFromCreds(creds) {
73
73
  ? bytesToNumbers(creds.signedPreKey.signature)
74
74
  : Array(SignalKeyLength.SIGNATURE).fill(0),
75
75
  adv_secret_key: creds.advSecretKey
76
- ? bytesToNumbers(Buffer.from(creds.advSecretKey, JsonByteEncoding.BASE64))
76
+ ? bytesToNumbers(base64Decode(creds.advSecretKey))
77
77
  : Array(SignalKeyLength.ADV_SECRET).fill(0),
78
78
  account: null,
79
79
  push_name: creds.me.name ?? '',
@@ -159,12 +159,12 @@ function prepareNativeDevice(payload) {
159
159
  };
160
160
  }
161
161
  if (advSecret?.some(byte => byte !== 0)) {
162
- creds.advSecretKey = Buffer.from(advSecret).toString(JsonByteEncoding.BASE64);
162
+ creds.advSecretKey = base64Encode(new Uint8Array(advSecret));
163
163
  }
164
164
  if (routingInfo === null)
165
165
  creds.routingInfo = undefined;
166
166
  else if (routingInfo)
167
- creds.routingInfo = Buffer.from(routingInfo);
167
+ creds.routingInfo = publicBytes(new Uint8Array(routingInfo));
168
168
  };
169
169
  }
170
170
  export function parseDeviceRecordKey(value) {
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Portable message-identity helpers for the runtime-neutral graph.
3
+ *
4
+ * `generateMessageIDV2` is the one place every send path resolves a stanza
5
+ * id through (`Compatibility/message-relay.ts:resolveMessageId`, group
6
+ * invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
7
+ * big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
8
+ * `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
9
+ * WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
10
+ * the same ids without a Node import.
11
+ */
12
+ export declare const generateMessageIDV2Portable: (userId?: string, randomSource?: (length: number) => Uint8Array) => string;
13
+ /** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
14
+ export declare const generateMessageIDPortable: (randomSource?: (length: number) => Uint8Array) => string;
15
+ /** Concatenate without Buffer (pad helper for the portable graph). */
16
+ export declare const concatMessageBytes: (parts: ReadonlyArray<Uint8Array>) => Uint8Array;
17
+ //# sourceMappingURL=message-ids.d.ts.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Portable message-identity helpers for the runtime-neutral graph.
3
+ *
4
+ * `generateMessageIDV2` is the one place every send path resolves a stanza
5
+ * id through (`Compatibility/message-relay.ts:resolveMessageId`, group
6
+ * invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
7
+ * big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
8
+ * `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
9
+ * WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
10
+ * the same ids without a Node import.
11
+ */
12
+ import { concatBytes, hexEncode, randomBytes, sha256Sync, utf8Encode, writeU64BE } from '../Runtime/bytes.js';
13
+ const MESSAGE_ID_PREFIX = '3EB0';
14
+ const MESSAGE_ID_BYTES = 44;
15
+ const RANDOM_OFFSET = 28;
16
+ const writeAsciiInto = (target, text, offset) => {
17
+ const bytes = utf8Encode(text);
18
+ const length = Math.min(bytes.length, target.length - offset);
19
+ for (let i = 0; i < length; i++)
20
+ target[offset + i] = bytes[i];
21
+ };
22
+ /** Extract the user part of a JID without importing the JID utils (cycle-safe). */
23
+ const jidUser = (jid) => {
24
+ const at = jid.indexOf('@');
25
+ const user = at < 0 ? jid : jid.slice(0, at);
26
+ // Baileys hashes the bare user, not the device/agent suffix of a
27
+ // multi-device JID (`user:device` or `user_agent`).
28
+ const bareUser = user.split('_', 1)[0].split(':', 1)[0];
29
+ return bareUser.length > 0 ? bareUser : undefined;
30
+ };
31
+ export const generateMessageIDV2Portable = (userId, randomSource = randomBytes) => {
32
+ const data = new Uint8Array(MESSAGE_ID_BYTES);
33
+ const seconds = Math.floor(Date.now() / 1000);
34
+ data.set(writeU64BE(0, seconds >>> 0), 0);
35
+ const user = userId ? jidUser(userId) : undefined;
36
+ if (user) {
37
+ writeAsciiInto(data, user, 8);
38
+ writeAsciiInto(data, '@c.us', 8 + utf8Encode(user).length);
39
+ }
40
+ data.set(randomSource(16), RANDOM_OFFSET);
41
+ return `${MESSAGE_ID_PREFIX}${hexEncode(sha256Sync(data)).toUpperCase().slice(0, 18)}`;
42
+ };
43
+ /** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
44
+ export const generateMessageIDPortable = (randomSource = randomBytes) => `3EB0${hexEncode(randomSource(18)).toUpperCase()}`;
45
+ /** Concatenate without Buffer (pad helper for the portable graph). */
46
+ export const concatMessageBytes = (parts) => concatBytes(parts);
47
+ //# sourceMappingURL=message-ids.js.map
@@ -10,7 +10,7 @@ export type OwnRelayIdentity = {
10
10
  * Every send path resolves through here, so `messageId` means the same thing
11
11
  * on `sendMessage` and on `relayMessage`.
12
12
  */
13
- export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string) => string;
13
+ export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string, randomBytes?: (length: number) => Uint8Array) => string;
14
14
  export type MessageRelayPlan = {
15
15
  kind: 'message';
16
16
  messageId: string;
@@ -28,5 +28,5 @@ export type MessageRelayPlan = {
28
28
  messageId: string;
29
29
  input: MessageRetransmissionInput;
30
30
  };
31
- export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity) => MessageRelayPlan;
31
+ export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity, randomBytes?: (length: number) => Uint8Array) => MessageRelayPlan;
32
32
  //# sourceMappingURL=message-relay.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { Boom } from '../Utils/boom.js';
2
- import { generateMessageIDV2 } from '../Utils/generics.js';
2
+ import { generateMessageIDV2Portable as generateMessageIDV2 } from './message-ids.js';
3
3
  import { areJidsSameUser, isJidBroadcast, isJidGroup, isJidNewsletter } from '../WABinary/index.js';
4
4
  export const EMPTY_RELAY_NODES = [];
5
5
  /**
@@ -7,7 +7,7 @@ export const EMPTY_RELAY_NODES = [];
7
7
  * Every send path resolves through here, so `messageId` means the same thing
8
8
  * on `sendMessage` and on `relayMessage`.
9
9
  */
10
- export const resolveMessageId = (own, messageId) => messageId || generateMessageIDV2(own?.id);
10
+ export const resolveMessageId = (own, messageId, randomBytes) => messageId || generateMessageIDV2(own?.id, randomBytes);
11
11
  const assertSupportedAttributes = (attributes) => {
12
12
  if (!attributes)
13
13
  return;
@@ -21,7 +21,7 @@ const assertSupportedAttributes = (attributes) => {
21
21
  };
22
22
  const isDirectConversation = (jid) => !isJidGroup(jid) && !isJidBroadcast(jid) && !isJidNewsletter(jid);
23
23
  const isOwnDevice = (jid, own) => (own?.id !== undefined && areJidsSameUser(jid, own.id)) || (own?.lid !== undefined && areJidsSameUser(jid, own.lid));
24
- export const planMessageRelay = (jid, options, own) => {
24
+ export const planMessageRelay = (jid, options, own, randomBytes) => {
25
25
  const { messageId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList } = options;
26
26
  assertSupportedAttributes(additionalAttributes);
27
27
  const nodes = additionalNodes ?? EMPTY_RELAY_NODES;
@@ -30,7 +30,7 @@ export const planMessageRelay = (jid, options, own) => {
30
30
  statusCode: 400
31
31
  });
32
32
  }
33
- const id = resolveMessageId(own, messageId);
33
+ const id = resolveMessageId(own, messageId, randomBytes);
34
34
  const refreshGroupMetadata = useCachedGroupMetadata === false;
35
35
  if (participant) {
36
36
  const requesterIsOwnDevice = isDirectConversation(jid) && isOwnDevice(participant.jid, own);
@@ -9,6 +9,11 @@ type DynamicObject = Record<PropertyKey, unknown>;
9
9
  * repair from a failure it does not understand.
10
10
  */
11
11
  export declare const repairProtoMessage: (path: string, message: unknown) => unknown;
12
+ /**
13
+ * The projection for a caller that addresses the codec by type name. Reference
14
+ * equality means nothing needed translating.
15
+ */
16
+ export declare const projectProtoMessage: (path: string, message: unknown) => unknown;
12
17
  export interface ProtoCompatibilityFacade {
13
18
  proto: DynamicObject;
14
19
  unsupportedCodecs: readonly string[];
@@ -1,16 +1,12 @@
1
- import { Buffer } from 'node:buffer';
2
- import { createRequire } from 'node:module';
3
- import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge';
1
+ import LongRuntime from '../Runtime/long.js';
2
+ import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge/host';
3
+ import { base64Decode, base64Encode, publicBytes } from '../Runtime/bytes.js';
4
4
  import { PROTO_ENUM_SCHEMAS, PROTO_FIELD_FLAG, PROTO_FIELD_KIND, PROTO_MESSAGE_SCHEMAS } from '../WAProto/compatibility-schema.js';
5
5
  const INSTANCE_SCHEMA = Symbol('proto compatibility schema');
6
6
  const EMPTY_ARRAY = Object.freeze([]);
7
7
  const EMPTY_OBJECT = Object.freeze({});
8
8
  const JSON_OPTIONS = Object.freeze({ longs: String, enums: String, bytes: String, json: true });
9
9
  const WORD_BASE = 1n << 32n;
10
- // protobufjs resolves the CommonJS Long constructor internally. Loading that
11
- // same export keeps `instanceof` and prototype identity aligned without
12
- // loading protobufjs itself or adding a second wire runtime.
13
- const LongRuntime = createRequire(import.meta.url)('long');
14
10
  const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
15
11
  const isObject = (value) => typeof value === 'object' && value !== null;
16
12
  const isReaderLike = (value) => isObject(value) && value.buf instanceof Uint8Array && typeof value.pos === 'number' && typeof value.len === 'number';
@@ -161,6 +157,19 @@ class LongBinaryReader extends BinaryReader {
161
157
  }
162
158
  }
163
159
  const longFromValue = (value, unsigned) => LongRuntime.fromValue(value, unsigned);
160
+ /**
161
+ * The neutral codec hands a 64-bit field back as a number while the value is exact as
162
+ * a double, and as a word split past that, where upstream declares a `Long` whose
163
+ * methods callers use. The decode reader above exists for the same reason.
164
+ */
165
+ const hydratedScalar = (kind, value) => {
166
+ if (value instanceof LongRuntime)
167
+ return value;
168
+ const split = isObject(value) && typeof value.low === 'number' && typeof value.high === 'number';
169
+ if (typeof value !== 'number' && typeof value !== 'string' && !split)
170
+ return value;
171
+ return longFromValue(value, kind === PROTO_FIELD_KIND.unsigned64);
172
+ };
164
173
  const longToBigInt = (value, unsigned) => {
165
174
  if (typeof value === 'bigint')
166
175
  return value;
@@ -192,19 +201,45 @@ const longToNumber = (value, unsigned) => {
192
201
  };
193
202
  const bytesToBase64 = (value) => {
194
203
  if (value instanceof Uint8Array) {
195
- return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64');
204
+ return base64Encode(value);
196
205
  }
197
- return Buffer.from(value).toString('base64');
206
+ return base64Encode(Uint8Array.from(value));
198
207
  };
199
208
  const bytesFromObject = (value) => {
200
209
  if (typeof value === 'string')
201
- return Buffer.from(value, 'base64');
210
+ return nodeBytesFromBase64(value);
202
211
  if (isObject(value) && typeof value.length === 'number')
203
212
  return value;
204
213
  if (Array.isArray(value))
205
214
  return value;
206
215
  return undefined;
207
216
  };
217
+ /**
218
+ * Upstream protobufjs materializes `bytes` fields as Node `Buffer` on Node
219
+ * (`protobuf.util.Buffer`), and the compatibility contract asserts
220
+ * `deepStrictEqual` against that — `Buffer` vs `Uint8Array` fails even with
221
+ * identical contents. The host-neutral graph cannot import `node:buffer`,
222
+ * so the base64 decode stays portable and only the wrapping is Node-only,
223
+ * resolved lazily through `process.getBuiltinModule('buffer')` (same
224
+ * lazy-builtin shape `Utils/browser-utils.ts` uses for `node:os`): no
225
+ * static `node:` import, `Buffer.from(u8)` on Node, the plain `Uint8Array`
226
+ * on hosts where there is no upstream-Buffer constraint to keep.
227
+ */
228
+ const nodeBytesFromBase64 = (value) => {
229
+ try {
230
+ const proc = globalThis.process;
231
+ const bufferModule = proc?.getBuiltinModule?.('buffer');
232
+ // protobufjs delegates string coercion to Buffer.from(), including its
233
+ // permissive handling of excess padding and ignored non-alphabet bytes.
234
+ const nodeBytes = bufferModule?.Buffer?.from?.(value, 'base64');
235
+ if (nodeBytes !== undefined)
236
+ return nodeBytes;
237
+ }
238
+ catch {
239
+ /* host runtimes use the strict portable decoder below */
240
+ }
241
+ return base64Decode(value);
242
+ };
208
243
  const oneofName = (field) => {
209
244
  const flags = field[3];
210
245
  if (flags & PROTO_FIELD_FLAG.proto3Optional)
@@ -279,17 +314,32 @@ const defineLazyValue = (target, key, build) => {
279
314
  });
280
315
  };
281
316
  /**
282
- * Type path to schema index, built on first use.
283
- *
284
- * Only the repair path needs it, and that path is only reached after an encode
285
- * has already failed — so an importer that never sends a refused value never
286
- * pays for the 498 entries.
317
+ * Type path to schema index, built on first use. The projection reads it per send,
318
+ * so the first encoded message builds it.
287
319
  */
288
320
  let schemaIdsByPath;
321
+ let lastSchemaPath;
322
+ let lastSchemaId;
323
+ // The send path asks for one type repeatedly, so the last answer is kept.
289
324
  const schemaIdFor = (path) => {
325
+ if (path === lastSchemaPath)
326
+ return lastSchemaId;
290
327
  schemaIdsByPath ?? (schemaIdsByPath = new Map(PROTO_MESSAGE_SCHEMAS.map(([name], index) => [name, index])));
291
- return schemaIdsByPath.get(path);
328
+ lastSchemaPath = path;
329
+ lastSchemaId = schemaIdsByPath.get(path);
330
+ return lastSchemaId;
331
+ };
332
+ // Bridge names stay neutral. Both sides put these at the same number and wire type,
333
+ // so only the spelling differs.
334
+ const FIELD_ALIASES = {
335
+ 'SyncActionValue.AgentAction': ['deviceID', 'deviceId'],
336
+ 'SyncActionValue.ChatAssignmentAction': ['deviceAgentID', 'deviceAgentId'],
337
+ 'Message.ExtendedTextMessage': ['faviconMMSMetadata', 'faviconMmsMetadata'],
338
+ 'Message.MessageHistoryMetadata': ['oldestMessageTimestamp', 'oldestMessageTimestampInWindow']
292
339
  };
340
+ // Indexed by schema id because its readers run per message.
341
+ let aliasBySchema;
342
+ const aliasFor = (schemaId) => (aliasBySchema ?? (aliasBySchema = PROTO_MESSAGE_SCHEMAS.map(([path]) => FIELD_ALIASES[path])))[schemaId];
293
343
  /**
294
344
  * Coerces the three inputs the bridge codec refuses back to what upstream
295
345
  * Baileys writes, and returns `value` itself when there was nothing to coerce.
@@ -318,10 +368,18 @@ const repairMessage = (schemaId, value, ancestors) => {
318
368
  return value;
319
369
  seen.add(value);
320
370
  let output;
371
+ const alias = aliasFor(schemaId);
321
372
  for (const field of fields) {
322
- if (!hasOwn(value, field[0]))
373
+ // Either spelling reaches the same field number, so a refused value has to be
374
+ // coerced under whichever name it arrived with.
375
+ const fieldKey = hasOwn(value, field[0])
376
+ ? field[0]
377
+ : alias !== undefined && alias[0] === field[0] && hasOwn(value, alias[1])
378
+ ? alias[1]
379
+ : undefined;
380
+ if (fieldKey === undefined)
323
381
  continue;
324
- const current = value[field[0]];
382
+ const current = value[fieldKey];
325
383
  if (current === null || current === undefined)
326
384
  continue;
327
385
  const repair = (item) => {
@@ -361,7 +419,7 @@ const repairMessage = (schemaId, value, ancestors) => {
361
419
  converted = repair(current);
362
420
  }
363
421
  if (converted !== current)
364
- (output ?? (output = { ...value }))[field[0]] = converted;
422
+ (output ?? (output = { ...value }))[fieldKey] = converted;
365
423
  }
366
424
  // The ancestor path, not everything ever visited: the same object reached
367
425
  // twice in different branches is legitimate and must still be repaired.
@@ -381,10 +439,117 @@ export const repairProtoMessage = (path, message) => {
381
439
  const schemaId = schemaIdFor(path);
382
440
  return schemaId === undefined ? message : repairMessage(schemaId, message);
383
441
  };
442
+ /**
443
+ * Message-typed fields by name, built on first use. Keyed by the message rather than
444
+ * the schema, which is what keeps the send-path walk proportional to the message.
445
+ */
446
+ const messageFieldsByNameBySchema = [];
447
+ const messageFieldsOf = (schemaId) => {
448
+ const existing = messageFieldsByNameBySchema[schemaId];
449
+ if (existing)
450
+ return existing;
451
+ const index = new Map();
452
+ for (const field of PROTO_MESSAGE_SCHEMAS[schemaId]?.[1] ?? []) {
453
+ if (field[1] === PROTO_FIELD_KIND.message)
454
+ index.set(field[0], field);
455
+ }
456
+ messageFieldsByNameBySchema[schemaId] = index;
457
+ return index;
458
+ };
459
+ /**
460
+ * Rewrites an aliased field's public spelling to the name the codec writes. The send
461
+ * path reaches `encodeProto` directly and that codec drops an unknown key without
462
+ * throwing, so this runs before the encode rather than after a failure. Copy-on-write,
463
+ * like `repairMessage`.
464
+ */
465
+ const projectAliases = (schemaId, value) => {
466
+ if (!isObject(value))
467
+ return value;
468
+ const messageFields = messageFieldsOf(schemaId);
469
+ const alias = aliasFor(schemaId);
470
+ let output;
471
+ if (alias && hasOwn(value, alias[0])) {
472
+ const moved = value[alias[0]];
473
+ // Walked, not just renamed: an aliased message type may carry one of its own.
474
+ const field = messageFields.get(alias[0]);
475
+ (output ?? (output = { ...value }))[alias[1]] =
476
+ field && moved !== null && moved !== undefined ? projectAliases(field[2], moved) : moved;
477
+ delete output[alias[0]];
478
+ }
479
+ // The message's own keys, so the cost follows the message.
480
+ for (const key of Object.keys(value)) {
481
+ if (key === alias?.[0])
482
+ continue;
483
+ const field = messageFields.get(key);
484
+ if (!field)
485
+ continue;
486
+ const current = value[key];
487
+ if (current === null || current === undefined)
488
+ continue;
489
+ let converted = current;
490
+ if (field[3] & PROTO_FIELD_FLAG.repeated) {
491
+ if (Array.isArray(current)) {
492
+ let items;
493
+ for (let index = 0; index < current.length; index++) {
494
+ const item = projectAliases(field[2], current[index]);
495
+ if (item !== current[index])
496
+ (items ?? (items = current.slice()))[index] = item;
497
+ }
498
+ converted = items ?? current;
499
+ }
500
+ }
501
+ else if (field[3] & PROTO_FIELD_FLAG.map) {
502
+ if (isObject(current)) {
503
+ let entries;
504
+ for (const entry in current) {
505
+ const item = projectAliases(field[2], current[entry]);
506
+ if (item !== current[entry])
507
+ (entries ?? (entries = { ...current }))[entry] = item;
508
+ }
509
+ converted = entries ?? current;
510
+ }
511
+ }
512
+ else {
513
+ converted = projectAliases(field[2], current);
514
+ }
515
+ if (converted !== current)
516
+ (output ?? (output = { ...value }))[key] = converted;
517
+ }
518
+ return output ?? value;
519
+ };
520
+ /**
521
+ * The projection for a caller that addresses the codec by type name. Reference
522
+ * equality means nothing needed translating.
523
+ */
524
+ export const projectProtoMessage = (path, message) => {
525
+ const schemaId = schemaIdFor(path);
526
+ return schemaId === undefined ? message : projectAliases(schemaId, message);
527
+ };
528
+ /**
529
+ * The value a field reads out of `data`, taking either spelling. `hasOwn` and not a
530
+ * null check, because an instance carries its defaults on the prototype: an absent
531
+ * public field reads as `0` there and the bridge key would never be reached.
532
+ */
533
+ const fieldValue = (data, field, alias) => !hasOwn(data, field[0]) && alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1])
534
+ ? data[alias[1]]
535
+ : data[field[0]];
536
+ /** True when either spelling is an own property, which is what keeps prototype defaults out of `toObject`. */
537
+ const hasOwnField = (data, field, alias) => hasOwn(data, field[0]) || (alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1]));
384
538
  class ProtoCompatibilityRuntime {
385
539
  constructor(sourceNamespace) {
386
540
  this.namespace = { ...sourceNamespace };
387
541
  this.enums = PROTO_ENUM_SCHEMAS.map(([, entries]) => this.makeEnum(entries));
542
+ // Only the 64-bit names are indexed: `hydrate` looks up every key a partial or a
543
+ // decode produced, and the rest of them need no conversion.
544
+ this.int64FieldsByName = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => {
545
+ const indexed = Object.create(null);
546
+ for (const field of fields) {
547
+ if (field[1] === PROTO_FIELD_KIND.signed64 || field[1] === PROTO_FIELD_KIND.unsigned64) {
548
+ indexed[field[0]] = field[1];
549
+ }
550
+ }
551
+ return indexed;
552
+ });
388
553
  this.messageFields = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => fields.filter(field => field[1] === PROTO_FIELD_KIND.message));
389
554
  this.messageFieldsByName = this.messageFields.map(fields => {
390
555
  const indexed = Object.create(null);
@@ -496,7 +661,11 @@ class ProtoCompatibilityRuntime {
496
661
  constructor.toObject = (message, options) => this.toObject(schemaId, message, options);
497
662
  constructor.getTypeUrl = (prefix = 'type.googleapis.com') => `${prefix}/proto.${path}`;
498
663
  constructor.fromPartial = message => {
499
- const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(message) : message;
664
+ // A partial is not written, so it must not inherit encode's codec
665
+ // requirement: the bridge accepts holders of types it does not implement
666
+ // and simply drops them. Only the alias translation is needed here.
667
+ const projected = this.projectForEncode(schemaId, message, false);
668
+ const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(projected) : projected;
500
669
  return this.hydrate(schemaId, isObject(partial) ? partial : {});
501
670
  };
502
671
  constructor.encode = (message, writer) => {
@@ -606,9 +775,10 @@ class ProtoCompatibilityRuntime {
606
775
  // megamorphic path, where V8 does not elide for..of iterator
607
776
  // allocations (~90 iterator results per WebMessageInfo envelope).
608
777
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
778
+ const alias = aliasFor(schemaId);
609
779
  for (let i = 0; i < fields.length; i++) {
610
780
  const field = fields[i];
611
- const value = data[field[0]];
781
+ const value = fieldValue(data, field, alias);
612
782
  if (value === null || value === undefined)
613
783
  continue;
614
784
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
@@ -668,6 +838,7 @@ class ProtoCompatibilityRuntime {
668
838
  const data = input;
669
839
  const output = {};
670
840
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
841
+ const alias = aliasFor(schemaId);
671
842
  for (const field of fields) {
672
843
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
673
844
  if (options.arrays || options.defaults)
@@ -682,7 +853,7 @@ class ProtoCompatibilityRuntime {
682
853
  }
683
854
  }
684
855
  for (const field of fields) {
685
- const value = data[field[0]];
856
+ const value = fieldValue(data, field, alias);
686
857
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
687
858
  if (value &&
688
859
  typeof value.length === 'number' &&
@@ -700,7 +871,7 @@ class ProtoCompatibilityRuntime {
700
871
  }
701
872
  continue;
702
873
  }
703
- if (value === null || value === undefined || !hasOwn(data, field[0]))
874
+ if (value === null || value === undefined || !hasOwnField(data, field, alias))
704
875
  continue;
705
876
  output[field[0]] = this.toObjectField(field, value, options);
706
877
  const group = oneofName(field);
@@ -722,7 +893,7 @@ class ProtoCompatibilityRuntime {
722
893
  case PROTO_FIELD_KIND.bool:
723
894
  return false;
724
895
  case PROTO_FIELD_KIND.bytes:
725
- return options.bytes === String ? '' : options.bytes === Array ? [] : Buffer.alloc(0);
896
+ return options.bytes === String ? '' : options.bytes === Array ? [] : publicBytes(new Uint8Array(0));
726
897
  case PROTO_FIELD_KIND.signed64:
727
898
  case PROTO_FIELD_KIND.unsigned64:
728
899
  return options.longs === String
@@ -788,11 +959,15 @@ class ProtoCompatibilityRuntime {
788
959
  const source = isObject(value) ? value : {};
789
960
  const instance = Object.create(this.constructorFor(schemaId).prototype);
790
961
  const messageFields = this.messageFieldsByName[schemaId];
791
- for (const key in source) {
792
- const nested = source[key];
962
+ const int64Fields = this.int64FieldsByName[schemaId];
963
+ const alias = aliasFor(schemaId);
964
+ for (const sourceKey in source) {
965
+ const key = alias && sourceKey === alias[1] ? alias[0] : sourceKey;
966
+ const nested = source[sourceKey];
793
967
  const field = messageFields[key];
794
968
  if (!field) {
795
- instance[key] = nested;
969
+ const kind = int64Fields[key];
970
+ instance[key] = kind === undefined ? nested : hydratedScalar(kind, nested);
796
971
  }
797
972
  else if (field[3] & PROTO_FIELD_FLAG.repeated) {
798
973
  if (Array.isArray(nested)) {
@@ -818,19 +993,26 @@ class ProtoCompatibilityRuntime {
818
993
  }
819
994
  return instance;
820
995
  }
821
- projectForEncode(schemaId, value) {
996
+ projectForEncode(schemaId, value, requireCodecs = true) {
822
997
  if (!isObject(value))
823
998
  return value;
824
999
  let output;
825
1000
  if (typeof value[INSTANCE_SCHEMA] === 'number')
826
1001
  output = { ...value };
1002
+ const alias = aliasFor(schemaId);
1003
+ // An own public field wins, including an explicit null or undefined.
1004
+ if (alias && hasOwn(value, alias[0])) {
1005
+ ;
1006
+ (output ?? (output = { ...value }))[alias[1]] = value[alias[0]];
1007
+ delete output[alias[0]];
1008
+ }
827
1009
  for (const field of this.messageFields[schemaId]) {
828
1010
  if (!hasOwn(value, field[0]))
829
1011
  continue;
830
1012
  const nested = value[field[0]];
831
1013
  if (nested === null || nested === undefined)
832
1014
  continue;
833
- if (!this.sourceCodecs[field[2]]) {
1015
+ if (requireCodecs && !this.sourceCodecs[field[2]]) {
834
1016
  throw new Error(`protobuf codec unavailable for ${PROTO_MESSAGE_SCHEMAS[field[2]][0]}`);
835
1017
  }
836
1018
  let converted = nested;
@@ -838,7 +1020,7 @@ class ProtoCompatibilityRuntime {
838
1020
  if (Array.isArray(nested)) {
839
1021
  let items;
840
1022
  for (let index = 0; index < nested.length; index++) {
841
- const item = this.projectForEncode(field[2], nested[index]);
1023
+ const item = this.projectForEncode(field[2], nested[index], requireCodecs);
842
1024
  if (item !== nested[index])
843
1025
  (items ?? (items = nested.slice()))[index] = item;
844
1026
  }
@@ -849,7 +1031,7 @@ class ProtoCompatibilityRuntime {
849
1031
  if (isObject(nested)) {
850
1032
  let entries;
851
1033
  for (const key in nested) {
852
- const item = this.projectForEncode(field[2], nested[key]);
1034
+ const item = this.projectForEncode(field[2], nested[key], requireCodecs);
853
1035
  if (item !== nested[key])
854
1036
  (entries ?? (entries = { ...nested }))[key] = item;
855
1037
  }
@@ -857,7 +1039,7 @@ class ProtoCompatibilityRuntime {
857
1039
  }
858
1040
  }
859
1041
  else {
860
- converted = this.projectForEncode(field[2], nested);
1042
+ converted = this.projectForEncode(field[2], nested, requireCodecs);
861
1043
  }
862
1044
  if (converted !== nested)
863
1045
  (output ?? (output = { ...value }))[field[0]] = converted;
@@ -1,4 +1,4 @@
1
- import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge';
1
+ import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge/host';
2
2
  import type { BinaryNode, WABusinessProfile } from '../Types/index.js';
3
3
  export type ParticipantUpdateResult = {
4
4
  status: string;
@@ -1,5 +1,8 @@
1
- import type { EventEmitter } from 'node:events';
1
+ import type { EventEmitter } from 'events';
2
2
  import type { ILogger } from '../Utils/logger.js';
3
3
  /** Build the low-level tagged-response waiter with upstream timeout semantics. */
4
- export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs?: number) => <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
4
+ export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs: number | undefined, timers: {
5
+ setTimeout: (callback: () => void, ms: number) => unknown;
6
+ clearTimeout: (handle: unknown) => void;
7
+ }) => <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
5
8
  //# sourceMappingURL=tagged-message-waiter.d.ts.map