@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,7 +1,9 @@
1
- import { createRequire } from 'node:module';
2
1
  /** Filesystem-backed loader, rooted at the importing module. */
3
2
  export const nodePeerLoader = (baseUrl) => {
4
- const requireFrom = createRequire(baseUrl);
3
+ const getBuiltinModule = globalThis.process?.getBuiltinModule;
4
+ if (!getBuiltinModule)
5
+ throw new Error('optional peer loading requires Node compatibility');
6
+ const requireFrom = getBuiltinModule('module').createRequire(baseUrl);
5
7
  return {
6
8
  resolveSpecifier: specifier => requireFrom.resolve(specifier),
7
9
  requireSpecifier: specifier => requireFrom(specifier)
@@ -19,9 +21,16 @@ const isAbsent = (error) => error?.code === 'MODULE_NOT_FOUND';
19
21
  * peer, so a damaged installation is never silently hidden behind the
20
22
  * fallback.
21
23
  */
22
- export const loadOptionalPeer = (specifier, loader = nodePeerLoader(import.meta.url)) => {
24
+ export const loadOptionalPeer = (specifier, loader) => {
25
+ const effectiveLoader = loader ??
26
+ (typeof globalThis.process
27
+ ?.getBuiltinModule === 'function'
28
+ ? nodePeerLoader(import.meta.url)
29
+ : undefined);
30
+ if (!effectiveLoader)
31
+ return undefined;
23
32
  try {
24
- loader.resolveSpecifier(`${specifier}/package.json`);
33
+ effectiveLoader.resolveSpecifier(`${specifier}/package.json`);
25
34
  }
26
35
  catch (error) {
27
36
  if (isAbsent(error))
@@ -29,7 +38,7 @@ export const loadOptionalPeer = (specifier, loader = nodePeerLoader(import.meta.
29
38
  throw error;
30
39
  }
31
40
  try {
32
- return loader.requireSpecifier(specifier);
41
+ return effectiveLoader.requireSpecifier(specifier);
33
42
  }
34
43
  catch (error) {
35
44
  throw new Error(`Failed to load optional peer '${specifier}': it is installed but broken. ` +
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Port of upstream Baileys' `Utils/history.ts:processHistoryMessage`.
3
+ *
4
+ * Walks a decoded `proto.IHistorySync` and produces the
5
+ * `messaging-history.set` payload (chats, contacts, messages, lidPnMappings).
6
+ * The bridge already decoded the proto for us — this module only handles
7
+ * the structured walk + normalization that upstream consumers expect.
8
+ *
9
+ * 1:1 with upstream (`Baileys/src/Utils/history.ts:47-139`); changes here
10
+ * are limited to swapping upstream imports for baileyrs equivalents and
11
+ * keeping the WAProto namespace as our re-export.
12
+ */
13
+ import type { proto } from '../WAProto/runtime.js';
14
+ import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
15
+ import type { ILogger } from './logger.js';
16
+ export interface ProcessedHistorySync {
17
+ chats: Chat[];
18
+ contacts: Contact[];
19
+ messages: WAMessage[];
20
+ lidPnMappings: LIDMapping[];
21
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
22
+ progress: number | null | undefined;
23
+ pastParticipants?: proto.IPastParticipants[] | null;
24
+ }
25
+ /** Sync types whose conversation records are part of the public history payload. */
26
+ export declare const CONVERSATION_HISTORY_SYNC_TYPES: readonly number[];
27
+ export declare const isConversationHistorySync: (syncType: number | null | undefined) => boolean;
28
+ /**
29
+ * Walk a decoded HistorySync proto and extract the upstream
30
+ * `messaging-history.set` payload. Mirrors upstream's behavior exactly,
31
+ * including the side-effect of removing `chat.messages` (kept only as a
32
+ * 1-element preview after the walk).
33
+ */
34
+ export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => ProcessedHistorySync;
35
+ /** Download, decrypt and inflate an external history-sync blob. */
36
+ //# sourceMappingURL=process-history-message-core.d.ts.map
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Port of upstream Baileys' `Utils/history.ts:processHistoryMessage`.
3
+ *
4
+ * Walks a decoded `proto.IHistorySync` and produces the
5
+ * `messaging-history.set` payload (chats, contacts, messages, lidPnMappings).
6
+ * The bridge already decoded the proto for us — this module only handles
7
+ * the structured walk + normalization that upstream consumers expect.
8
+ *
9
+ * 1:1 with upstream (`Baileys/src/Utils/history.ts:47-139`); changes here
10
+ * are limited to swapping upstream imports for baileyrs equivalents and
11
+ * keeping the WAProto namespace as our re-export.
12
+ */
13
+ import { WAProto } from '../Types/index.js';
14
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/jid-utils.js';
15
+ import { asInt64 } from '../Bridge/primitives.js';
16
+ import { createSparseArray } from './sparse-array.js';
17
+ const STUB = WAProto.WebMessageInfo.StubType;
18
+ const extractPnFromMessages = (messages) => {
19
+ for (let index = 0; index < messages.length; index++) {
20
+ const msgItem = messages[index];
21
+ const message = msgItem.message;
22
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats —
23
+ // userReceipt.userJid is the recipient's JID, so it only makes sense
24
+ // when WE were the sender.
25
+ if (!message?.key?.fromMe || !message.userReceipt?.length)
26
+ continue;
27
+ const userJid = message.userReceipt[0]?.userJid;
28
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid)))
29
+ return userJid;
30
+ }
31
+ return undefined;
32
+ };
33
+ /** Sync types whose conversation records are part of the public history payload. */
34
+ export const CONVERSATION_HISTORY_SYNC_TYPES = Object.freeze([
35
+ WAProto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
36
+ WAProto.HistorySync.HistorySyncType.RECENT,
37
+ WAProto.HistorySync.HistorySyncType.FULL,
38
+ WAProto.HistorySync.HistorySyncType.ON_DEMAND
39
+ ]);
40
+ export const isConversationHistorySync = (syncType) => syncType != null && CONVERSATION_HISTORY_SYNC_TYPES.includes(syncType);
41
+ /**
42
+ * Walk a decoded HistorySync proto and extract the upstream
43
+ * `messaging-history.set` payload. Mirrors upstream's behavior exactly,
44
+ * including the side-effect of removing `chat.messages` (kept only as a
45
+ * 1-element preview after the walk).
46
+ */
47
+ export const processHistoryMessage = (item, logger) => {
48
+ let messages = [];
49
+ let contacts = [];
50
+ let chats = [];
51
+ const sourceMappings = item.phoneNumberToLidMappings || [];
52
+ const lidPnMappings = createSparseArray(sourceMappings.length);
53
+ let lidPnMappingCount = 0;
54
+ // LID-PN mappings flow on every sync type.
55
+ for (let index = 0; index < sourceMappings.length; index++) {
56
+ const m = sourceMappings[index];
57
+ if (m.lidJid && m.pnJid)
58
+ lidPnMappings[lidPnMappingCount++] = { lid: m.lidJid, pn: m.pnJid };
59
+ }
60
+ lidPnMappings.length = lidPnMappingCount;
61
+ const syncType = item.syncType;
62
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + syncType?.toString());
63
+ if (isConversationHistorySync(syncType)) {
64
+ const conversations = item.conversations || [];
65
+ let expectedMessages = 0;
66
+ for (let index = 0; index < conversations.length; index++) {
67
+ expectedMessages += conversations[index].messages?.length || 0;
68
+ }
69
+ // History arrives as many small bridge batches. Allocate each result
70
+ // backing store once instead of repeatedly growing it while walking the
71
+ // decoded conversations; invalid entries are compacted by the counters.
72
+ messages = createSparseArray(expectedMessages);
73
+ contacts = createSparseArray(conversations.length);
74
+ chats = createSparseArray(conversations.length);
75
+ lidPnMappings.length = lidPnMappingCount + conversations.length;
76
+ let messageCount = 0;
77
+ let contactCount = 0;
78
+ let chatCount = 0;
79
+ for (let conversationIndex = 0; conversationIndex < conversations.length; conversationIndex++) {
80
+ const conversation = conversations[conversationIndex];
81
+ // `Conversation` is widened to `Chat` because upstream's
82
+ // definition treats them as compatible — the runtime shape
83
+ // matches.
84
+ const chat = conversation;
85
+ const chatId = chat.id;
86
+ if (!chatId) {
87
+ // Server bug or malformed history blob — skip rather than
88
+ // propagate undefined ids that downstream consumers
89
+ // dereference unconditionally.
90
+ continue;
91
+ }
92
+ contacts[contactCount++] = {
93
+ id: chatId,
94
+ name: chat.displayName || chat.name || chat.username || undefined,
95
+ username: chat.username || undefined,
96
+ lid: chat.lidJid || chat.accountLid || undefined,
97
+ phoneNumber: chat.pnJid || undefined
98
+ };
99
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
100
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
101
+ if (isLid && chat.pnJid) {
102
+ lidPnMappings[lidPnMappingCount++] = { lid: chatId, pn: chat.pnJid };
103
+ }
104
+ else if (isPn && chat.lidJid) {
105
+ lidPnMappings[lidPnMappingCount++] = { lid: chat.lidJid, pn: chatId };
106
+ }
107
+ else if (isLid && !chat.pnJid) {
108
+ // Fallback: pull PN from a userReceipt on a fromMe message
109
+ // in this chat. Empty when the chat has no fromMe history.
110
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
111
+ if (pnFromReceipt)
112
+ lidPnMappings[lidPnMappingCount++] = { lid: chatId, pn: pnFromReceipt };
113
+ }
114
+ const msgs = chat.messages || [];
115
+ // Upstream mutates the chat in place: drops the full message
116
+ // list, keeps only the latest as a preview. Consumers that
117
+ // keyed off `chat.messages` for full history previously broke
118
+ // after this call too — that's the upstream contract.
119
+ delete chat.messages;
120
+ for (let messageIndex = 0; messageIndex < msgs.length; messageIndex++) {
121
+ const histMsg = msgs[messageIndex];
122
+ const message = histMsg.message;
123
+ if (!message)
124
+ continue;
125
+ messages[messageCount++] = message;
126
+ if (!chat.messages?.length) {
127
+ // `chat.messages` is typed as `proto.IHistorySyncMsg[]`
128
+ // but we want to store the WAMessage we already
129
+ // extracted. The runtime shape `{ message }` matches
130
+ // IHistorySyncMsg's optional `message` slot — cast is
131
+ // intentional and isolated to this preview-only field.
132
+ chat.messages = [{ message }];
133
+ }
134
+ if (!message.key?.fromMe && !chat.lastMessageRecvTimestamp) {
135
+ // `messageTimestamp` is always set on a decoded message; a
136
+ // value past 2^53 would round, so absence beats a wrong
137
+ // instant here (same contract as the adapter layer).
138
+ chat.lastMessageRecvTimestamp = asInt64(message.messageTimestamp) ?? 0;
139
+ }
140
+ // Extract verifiedName side-channel when WhatsApp sent a
141
+ // privacy-mode stub for the participant. Skip when the
142
+ // stub carries no addressable target (defensive — server
143
+ // always populates one of the two slots in practice).
144
+ if ((message.messageStubType === STUB.BIZ_PRIVACY_MODE_TO_BSP ||
145
+ message.messageStubType === STUB.BIZ_PRIVACY_MODE_TO_FB) &&
146
+ message.messageStubParameters?.[0]) {
147
+ const verifiedNameId = message.key?.participant ?? message.key?.remoteJid;
148
+ if (verifiedNameId) {
149
+ contacts[contactCount++] = {
150
+ id: verifiedNameId,
151
+ verifiedName: message.messageStubParameters[0]
152
+ };
153
+ }
154
+ }
155
+ }
156
+ chats[chatCount++] = chat;
157
+ }
158
+ messages.length = messageCount;
159
+ contacts.length = contactCount;
160
+ chats.length = chatCount;
161
+ lidPnMappings.length = lidPnMappingCount;
162
+ }
163
+ else if (syncType === WAProto.HistorySync.HistorySyncType.PUSH_NAME) {
164
+ const pushnames = item.pushnames || [];
165
+ contacts = createSparseArray(pushnames.length);
166
+ let contactCount = 0;
167
+ for (let index = 0; index < pushnames.length; index++) {
168
+ const c = pushnames[index];
169
+ if (c.id)
170
+ contacts[contactCount++] = { id: c.id, notify: c.pushname || undefined };
171
+ }
172
+ contacts.length = contactCount;
173
+ }
174
+ // NON_BLOCKING_DATA / STATUS_V3 / etc. fall through with empty
175
+ // arrays — upstream behaves the same.
176
+ return {
177
+ chats,
178
+ contacts,
179
+ messages,
180
+ lidPnMappings,
181
+ syncType,
182
+ progress: item.progress,
183
+ pastParticipants: item.pastParticipants
184
+ };
185
+ };
186
+ /** Download, decrypt and inflate an external history-sync blob. */
187
+ //# sourceMappingURL=process-history-message-core.js.map
@@ -1,50 +1,12 @@
1
- /**
2
- * Port of upstream Baileys' `Utils/history.ts:processHistoryMessage`.
3
- *
4
- * Walks a decoded `proto.IHistorySync` and produces the
5
- * `messaging-history.set` payload (chats, contacts, messages, lidPnMappings).
6
- * The bridge already decoded the proto for us — this module only handles
7
- * the structured walk + normalization that upstream consumers expect.
8
- *
9
- * 1:1 with upstream (`Baileys/src/Utils/history.ts:47-139`); changes here
10
- * are limited to swapping upstream imports for baileyrs equivalents and
11
- * keeping the WAProto namespace as our re-export.
12
- */
13
1
  import { proto } from '../WAProto/runtime.js';
14
- import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
15
2
  import type { ILogger } from './logger.js';
16
- export interface ProcessedHistorySync {
17
- chats: Chat[];
18
- contacts: Contact[];
19
- messages: WAMessage[];
20
- lidPnMappings: LIDMapping[];
21
- syncType: proto.HistorySync.HistorySyncType | null | undefined;
22
- progress: number | null | undefined;
23
- pastParticipants?: proto.IPastParticipants[] | null;
24
- }
25
- /** Sync types whose conversation records are part of the public history payload. */
26
- export declare const CONVERSATION_HISTORY_SYNC_TYPES: readonly number[];
27
- export declare const isConversationHistorySync: (syncType: number | null | undefined) => boolean;
28
- /**
29
- * Walk a decoded HistorySync proto and extract the upstream
30
- * `messaging-history.set` payload. Mirrors upstream's behavior exactly,
31
- * including the side-effect of removing `chat.messages` (kept only as a
32
- * 1-element preview after the walk).
33
- */
34
- export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => ProcessedHistorySync;
3
+ import { CONVERSATION_HISTORY_SYNC_TYPES, isConversationHistorySync, processHistoryMessage, type ProcessedHistorySync } from './process-history-message-core.js';
4
+ export { CONVERSATION_HISTORY_SYNC_TYPES, isConversationHistorySync, processHistoryMessage };
5
+ export type { ProcessedHistorySync };
35
6
  /** Download, decrypt and inflate an external history-sync blob. */
36
7
  export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => Promise<proto.HistorySync>;
37
8
  /** Resolve inline or external history-sync content and normalize its public payload. */
38
- export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<ProcessedHistorySync>;
39
- /**
40
- * Extract a history-sync notification through the same wrapper normalization as
41
- * upstream.
42
- *
43
- * Returns `undefined` when the message carries none. It used to throw a Boom
44
- * 400, which breaks the shape every caller writes against a drop-in API —
45
- * `const h = getHistoryMsg(msg); if (!h) return` crashed instead of returning.
46
- * "Absent" is the ordinary case here, not an error: any message that is not a
47
- * history sync takes this path.
48
- */
9
+ /** Extract a history-sync notification through the upstream-compatible wrapper. */
49
10
  export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | undefined;
11
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<ProcessedHistorySync>;
50
12
  //# sourceMappingURL=process-history-message.d.ts.map
@@ -1,188 +1,11 @@
1
- /**
2
- * Port of upstream Baileys' `Utils/history.ts:processHistoryMessage`.
3
- *
4
- * Walks a decoded `proto.IHistorySync` and produces the
5
- * `messaging-history.set` payload (chats, contacts, messages, lidPnMappings).
6
- * The bridge already decoded the proto for us — this module only handles
7
- * the structured walk + normalization that upstream consumers expect.
8
- *
9
- * 1:1 with upstream (`Baileys/src/Utils/history.ts:47-139`); changes here
10
- * are limited to swapping upstream imports for baileyrs equivalents and
11
- * keeping the WAProto namespace as our re-export.
12
- */
1
+ /** Node-facing history helpers. The portable walk lives in the core module. */
13
2
  import { inflateZlib } from '@oxidezap/whatsapp-rust-bridge';
3
+ import { Buffer } from 'node:buffer';
14
4
  import { proto } from '../WAProto/runtime.js';
15
- import { WAProto } from '../Types/index.js';
16
- import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/jid-utils.js';
17
- import { toNumber } from './generics.js';
18
- import { downloadContentFromMessage, normalizeMessageContent } from './messages.js';
19
- import { createSparseArray } from './sparse-array.js';
20
- const STUB = WAProto.WebMessageInfo.StubType;
21
- const extractPnFromMessages = (messages) => {
22
- for (let index = 0; index < messages.length; index++) {
23
- const msgItem = messages[index];
24
- const message = msgItem.message;
25
- // Only extract from outgoing messages (fromMe: true) in 1:1 chats —
26
- // userReceipt.userJid is the recipient's JID, so it only makes sense
27
- // when WE were the sender.
28
- if (!message?.key?.fromMe || !message.userReceipt?.length)
29
- continue;
30
- const userJid = message.userReceipt[0]?.userJid;
31
- if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid)))
32
- return userJid;
33
- }
34
- return undefined;
35
- };
36
- /** Sync types whose conversation records are part of the public history payload. */
37
- export const CONVERSATION_HISTORY_SYNC_TYPES = Object.freeze([
38
- WAProto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
39
- WAProto.HistorySync.HistorySyncType.RECENT,
40
- WAProto.HistorySync.HistorySyncType.FULL,
41
- WAProto.HistorySync.HistorySyncType.ON_DEMAND
42
- ]);
43
- export const isConversationHistorySync = (syncType) => syncType != null && CONVERSATION_HISTORY_SYNC_TYPES.includes(syncType);
44
- /**
45
- * Walk a decoded HistorySync proto and extract the upstream
46
- * `messaging-history.set` payload. Mirrors upstream's behavior exactly,
47
- * including the side-effect of removing `chat.messages` (kept only as a
48
- * 1-element preview after the walk).
49
- */
50
- export const processHistoryMessage = (item, logger) => {
51
- let messages = [];
52
- let contacts = [];
53
- let chats = [];
54
- const sourceMappings = item.phoneNumberToLidMappings || [];
55
- const lidPnMappings = createSparseArray(sourceMappings.length);
56
- let lidPnMappingCount = 0;
57
- // LID-PN mappings flow on every sync type.
58
- for (let index = 0; index < sourceMappings.length; index++) {
59
- const m = sourceMappings[index];
60
- if (m.lidJid && m.pnJid)
61
- lidPnMappings[lidPnMappingCount++] = { lid: m.lidJid, pn: m.pnJid };
62
- }
63
- lidPnMappings.length = lidPnMappingCount;
64
- const syncType = item.syncType;
65
- logger?.trace({ progress: item.progress }, 'processing history of type ' + syncType?.toString());
66
- if (isConversationHistorySync(syncType)) {
67
- const conversations = item.conversations || [];
68
- let expectedMessages = 0;
69
- for (let index = 0; index < conversations.length; index++) {
70
- expectedMessages += conversations[index].messages?.length || 0;
71
- }
72
- // History arrives as many small bridge batches. Allocate each result
73
- // backing store once instead of repeatedly growing it while walking the
74
- // decoded conversations; invalid entries are compacted by the counters.
75
- messages = createSparseArray(expectedMessages);
76
- contacts = createSparseArray(conversations.length);
77
- chats = createSparseArray(conversations.length);
78
- lidPnMappings.length = lidPnMappingCount + conversations.length;
79
- let messageCount = 0;
80
- let contactCount = 0;
81
- let chatCount = 0;
82
- for (let conversationIndex = 0; conversationIndex < conversations.length; conversationIndex++) {
83
- const conversation = conversations[conversationIndex];
84
- // `Conversation` is widened to `Chat` because upstream's
85
- // definition treats them as compatible — the runtime shape
86
- // matches.
87
- const chat = conversation;
88
- const chatId = chat.id;
89
- if (!chatId) {
90
- // Server bug or malformed history blob — skip rather than
91
- // propagate undefined ids that downstream consumers
92
- // dereference unconditionally.
93
- continue;
94
- }
95
- contacts[contactCount++] = {
96
- id: chatId,
97
- name: chat.displayName || chat.name || chat.username || undefined,
98
- username: chat.username || undefined,
99
- lid: chat.lidJid || chat.accountLid || undefined,
100
- phoneNumber: chat.pnJid || undefined
101
- };
102
- const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
103
- const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
104
- if (isLid && chat.pnJid) {
105
- lidPnMappings[lidPnMappingCount++] = { lid: chatId, pn: chat.pnJid };
106
- }
107
- else if (isPn && chat.lidJid) {
108
- lidPnMappings[lidPnMappingCount++] = { lid: chat.lidJid, pn: chatId };
109
- }
110
- else if (isLid && !chat.pnJid) {
111
- // Fallback: pull PN from a userReceipt on a fromMe message
112
- // in this chat. Empty when the chat has no fromMe history.
113
- const pnFromReceipt = extractPnFromMessages(chat.messages || []);
114
- if (pnFromReceipt)
115
- lidPnMappings[lidPnMappingCount++] = { lid: chatId, pn: pnFromReceipt };
116
- }
117
- const msgs = chat.messages || [];
118
- // Upstream mutates the chat in place: drops the full message
119
- // list, keeps only the latest as a preview. Consumers that
120
- // keyed off `chat.messages` for full history previously broke
121
- // after this call too — that's the upstream contract.
122
- delete chat.messages;
123
- for (let messageIndex = 0; messageIndex < msgs.length; messageIndex++) {
124
- const histMsg = msgs[messageIndex];
125
- const message = histMsg.message;
126
- if (!message)
127
- continue;
128
- messages[messageCount++] = message;
129
- if (!chat.messages?.length) {
130
- // `chat.messages` is typed as `proto.IHistorySyncMsg[]`
131
- // but we want to store the WAMessage we already
132
- // extracted. The runtime shape `{ message }` matches
133
- // IHistorySyncMsg's optional `message` slot — cast is
134
- // intentional and isolated to this preview-only field.
135
- chat.messages = [{ message }];
136
- }
137
- if (!message.key?.fromMe && !chat.lastMessageRecvTimestamp) {
138
- chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
139
- }
140
- // Extract verifiedName side-channel when WhatsApp sent a
141
- // privacy-mode stub for the participant. Skip when the
142
- // stub carries no addressable target (defensive — server
143
- // always populates one of the two slots in practice).
144
- if ((message.messageStubType === STUB.BIZ_PRIVACY_MODE_TO_BSP ||
145
- message.messageStubType === STUB.BIZ_PRIVACY_MODE_TO_FB) &&
146
- message.messageStubParameters?.[0]) {
147
- const verifiedNameId = message.key?.participant ?? message.key?.remoteJid;
148
- if (verifiedNameId) {
149
- contacts[contactCount++] = {
150
- id: verifiedNameId,
151
- verifiedName: message.messageStubParameters[0]
152
- };
153
- }
154
- }
155
- }
156
- chats[chatCount++] = chat;
157
- }
158
- messages.length = messageCount;
159
- contacts.length = contactCount;
160
- chats.length = chatCount;
161
- lidPnMappings.length = lidPnMappingCount;
162
- }
163
- else if (syncType === WAProto.HistorySync.HistorySyncType.PUSH_NAME) {
164
- const pushnames = item.pushnames || [];
165
- contacts = createSparseArray(pushnames.length);
166
- let contactCount = 0;
167
- for (let index = 0; index < pushnames.length; index++) {
168
- const c = pushnames[index];
169
- if (c.id)
170
- contacts[contactCount++] = { id: c.id, notify: c.pushname || undefined };
171
- }
172
- contacts.length = contactCount;
173
- }
174
- // NON_BLOCKING_DATA / STATUS_V3 / etc. fall through with empty
175
- // arrays — upstream behaves the same.
176
- return {
177
- chats,
178
- contacts,
179
- messages,
180
- lidPnMappings,
181
- syncType,
182
- progress: item.progress,
183
- pastParticipants: item.pastParticipants
184
- };
185
- };
5
+ import { downloadContentFromMessage } from './messages.js';
6
+ import { normalizeMessageContent } from '../Media/content.js';
7
+ import { CONVERSATION_HISTORY_SYNC_TYPES, isConversationHistorySync, processHistoryMessage } from './process-history-message-core.js';
8
+ export { CONVERSATION_HISTORY_SYNC_TYPES, isConversationHistorySync, processHistoryMessage };
186
9
  /** Download, decrypt and inflate an external history-sync blob. */
187
10
  export const downloadHistory = async (msg, options) => {
188
11
  const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
@@ -192,24 +15,15 @@ export const downloadHistory = async (msg, options) => {
192
15
  return proto.HistorySync.decode(inflateZlib(Buffer.concat(compressed)));
193
16
  };
194
17
  /** Resolve inline or external history-sync content and normalize its public payload. */
18
+ /** Extract a history-sync notification through the upstream-compatible wrapper. */
19
+ export const getHistoryMsg = (message) => {
20
+ const normalizedContent = message ? normalizeMessageContent(message) : undefined;
21
+ return normalizedContent?.protocolMessage?.historySyncNotification ?? undefined;
22
+ };
195
23
  export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
196
24
  const historyMsg = msg.initialHistBootstrapInlinePayload
197
25
  ? proto.HistorySync.decode(inflateZlib(msg.initialHistBootstrapInlinePayload))
198
26
  : await downloadHistory(msg, options);
199
27
  return processHistoryMessage(historyMsg, logger);
200
28
  };
201
- /**
202
- * Extract a history-sync notification through the same wrapper normalization as
203
- * upstream.
204
- *
205
- * Returns `undefined` when the message carries none. It used to throw a Boom
206
- * 400, which breaks the shape every caller writes against a drop-in API —
207
- * `const h = getHistoryMsg(msg); if (!h) return` crashed instead of returning.
208
- * "Absent" is the ordinary case here, not an error: any message that is not a
209
- * history sync takes this path.
210
- */
211
- export const getHistoryMsg = (message) => {
212
- const normalizedContent = message ? normalizeMessageContent(message) : undefined;
213
- return normalizedContent?.protocolMessage?.historySyncNotification ?? undefined;
214
- };
215
29
  //# sourceMappingURL=process-history-message.js.map
@@ -0,0 +1,29 @@
1
+ import type { WAMessage, WAMessageKey } from '../Types/index.js';
2
+ import { proto } from '../WAProto/runtime.js';
3
+ /** Whether an envelope carries user-visible content rather than a control message. */
4
+ export declare const isRealMessage: (message: WAMessage) => boolean;
5
+ export declare const shouldIncrementChatUnread: (message: WAMessage) => boolean;
6
+ /** Normalize device/hosted JIDs and nested reaction/poll keys in place. */
7
+ export declare const cleanMessage: (message: WAMessage, meId: string, meLid: string) => void;
8
+ /** Return the conversation JID represented by a message key. */
9
+ export declare const getChatId: ({ remoteJid, participant, fromMe }: WAMessageKey) => string;
10
+ type PollContext = {
11
+ pollCreatorJid: string;
12
+ pollMsgId: string;
13
+ pollEncKey: Uint8Array;
14
+ voterJid: string;
15
+ };
16
+ type EventContext = {
17
+ eventCreatorJid: string;
18
+ eventMsgId: string;
19
+ eventEncKey: Uint8Array;
20
+ responderJid: string;
21
+ };
22
+ export type MessageCryptoRuntime = {
23
+ decryptPollVotePayload: (payload: Uint8Array, iv: Uint8Array, encKey: Uint8Array, msgId: string, creatorJid: string, voterJid: string) => Uint8Array;
24
+ decryptEventResponsePayload: (payload: Uint8Array, iv: Uint8Array, encKey: Uint8Array, msgId: string, creatorJid: string, responderJid: string) => Uint8Array;
25
+ };
26
+ export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext, crypto: MessageCryptoRuntime): proto.Message.PollVoteMessage;
27
+ export declare function decryptEventResponse({ encPayload, encIv }: proto.Message.IPollEncValue, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }: EventContext, crypto: MessageCryptoRuntime): proto.Message.EventResponseMessage;
28
+ export {};
29
+ //# sourceMappingURL=process-message-core.d.ts.map