kage-baileys 25.3.34 → 25.3.36

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.
@@ -286,8 +286,7 @@ async function sendA2UIWidget(
286
286
  type = "im_a2ui",
287
287
  wrapped = true,
288
288
  singleScreen = false,
289
- header,
290
- additionalNodes = []
289
+ header
291
290
  } = {}
292
291
  ) {
293
292
  if (!client) throw new Error("Socket is required");
@@ -350,14 +349,9 @@ async function sendA2UIWidget(
350
349
  },
351
350
  { quoted }
352
351
  );
353
- const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
354
- const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
355
- const finalAdditionalNodes = hasCustomBizNode
356
- ? customNodes
357
- : [getBizBinaryNode(msg.message), ...customNodes];
358
352
  await client.relayMessage(msg.key.remoteJid, msg.message, {
359
353
  messageId: msg.key.id,
360
- additionalNodes: finalAdditionalNodes
354
+ additionalNodes: [getBizBinaryNode(msg.message)]
361
355
  });
362
356
  return msg;
363
357
  }
@@ -870,17 +870,13 @@ class Button extends BaseBuilder {
870
870
  { ...options }
871
871
  );
872
872
  }
873
- async send(jid, { additionalNodes = [], ...options } = {}) {
873
+ async send(jid, { ...options } = {}) {
874
874
  const msg = await this.build(jid, options);
875
- const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
876
- const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
877
- const finalAdditionalNodes = hasCustomBizNode
878
- ? customNodes
879
- : [getBizBinaryNode(msg.message), ...customNodes];
875
+ const bizNode = getBizBinaryNode(msg.message);
880
876
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
881
- ...options,
882
877
  messageId: msg.key.id,
883
- additionalNodes: finalAdditionalNodes
878
+ additionalNodes: [bizNode],
879
+ ...options
884
880
  });
885
881
  return msg;
886
882
  }
@@ -135,19 +135,15 @@ class ButtonV2 extends BaseBuilder {
135
135
  return msg;
136
136
  }
137
137
 
138
- async send(jid, { additionalNodes = [], ...options } = {}) {
138
+ async send(jid, { ...options } = {}) {
139
139
  if (this._buttons.length < 1) throw new Error('ButtonV2 requires at least one button');
140
140
  const msg = await this.build(jid, options);
141
- const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
142
- const hasCustomBizNode = customNodes.some((node) => node?.tag === 'biz' || node?.tag === 'hsm');
143
- const finalAdditionalNodes = hasCustomBizNode
144
- ? customNodes
145
- : [getBizBinaryNode(msg.message), ...customNodes];
141
+ const bizNode = getBizBinaryNode(msg.message);
146
142
 
147
143
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
148
- ...options,
149
144
  messageId: msg.key.id,
150
- additionalNodes: finalAdditionalNodes,
145
+ additionalNodes: [bizNode],
146
+ ...options,
151
147
  });
152
148
  return msg;
153
149
  }
@@ -139,19 +139,15 @@ class Carousel extends BaseBuilder {
139
139
  { ...options }
140
140
  );
141
141
  }
142
- async send(jid, { additionalNodes = [], ...options } = {}) {
142
+ async send(jid, { ...options } = {}) {
143
143
  if (this._cards.length === 0)
144
144
  throw new Error("Carousel requires at least one card (use addCard())");
145
145
  const msg = this.build(jid, options);
146
- const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
147
- const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
148
- const finalAdditionalNodes = hasCustomBizNode
149
- ? customNodes
150
- : [getBizBinaryNode(msg.message), ...customNodes];
146
+ const bizNode = getBizBinaryNode(msg.message);
151
147
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
152
- ...options,
153
148
  messageId: msg.key.id,
154
- additionalNodes: finalAdditionalNodes
149
+ additionalNodes: [bizNode],
150
+ ...options
155
151
  });
156
152
  return msg;
157
153
  }
@@ -3,7 +3,7 @@ import makeWASocket from "../Socket/index.js";
3
3
  import { DisconnectReason } from "../Types/index.js";
4
4
  import { isJidGroup } from "../WABinary/index.js";
5
5
  import defaultLogger from "../Utils/logger.js";
6
- import generics from "../Utils/generics.js";
6
+ import * as generics from "../Utils/generics.js";
7
7
 
8
8
  // Import CommonJS utilities through their default namespace. Node's synthetic
9
9
  // named-export detection can miss exports appended by compiled/merged CJS files.
@@ -12,5 +12,4 @@ export declare const reduceBinaryNodeToDictionary: (node: BinaryNode, tag: strin
12
12
  };
13
13
  export declare const getBinaryNodeMessages: ({ content }: BinaryNode) => proto.WebMessageInfo[];
14
14
  export declare function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i?: number): string;
15
- export declare const getBizBinaryNode: (message: proto.IMessage | Record<string, unknown>) => BinaryNode;
16
- //# sourceMappingURL=generic-utils.d.ts.map
15
+ //# sourceMappingURL=generic-utils.d.ts.map
@@ -1,6 +1,5 @@
1
1
  import { Boom } from '@hapi/boom';
2
2
  import { proto } from '../../WAProto/index.js';
3
- import { randomBytes } from 'node:crypto';
4
3
  import {} from './types.js';
5
4
  // some extra useful utilities
6
5
  const indexCache = new WeakMap();
@@ -111,155 +110,89 @@ export function binaryNodeToString(node, i = 0) {
111
110
  const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>';
112
111
  return tag + content;
113
112
  }
114
- const BIZ_FLOW_NAMES = new Set([
113
+
114
+ /**
115
+ * Builds the <biz> binary node required for interactive / native flow / carousel messages.
116
+ * Used by Builders (Button, Carousel, A2UI, etc.) when calling relayMessage with additionalNodes.
117
+ */
118
+ const BIZ_SPECIAL = new Set([
115
119
  'mpm',
116
120
  'cta_catalog',
117
121
  'send_location',
118
122
  'call_permission_request',
119
123
  'wa_payment_transaction_details',
120
- 'automated_greeting_message_view_catalog',
124
+ 'automated_greeting_message_view_catalog'
121
125
  ]);
122
126
 
123
- const BIZ_NATIVE_FLOW_ATTRIBUTES = { type: 'native_flow', v: '1' };
127
+ const UNWRAP_KEYS = [
128
+ 'viewOnceMessage',
129
+ 'viewOnceMessageV2',
130
+ 'viewOnceMessageV2Extension',
131
+ 'ephemeralMessage',
132
+ 'documentWithCaptionMessage'
133
+ ];
124
134
 
125
- const createMixedNativeFlowNode = () => ({
126
- tag: 'interactive',
127
- attrs: { ...BIZ_NATIVE_FLOW_ATTRIBUTES },
128
- content: [
129
- {
130
- tag: 'native_flow',
131
- attrs: { v: '9', name: 'mixed' },
132
- },
133
- ],
134
- });
135
-
136
- const createListNode = () => ({
137
- tag: 'list',
138
- attrs: { v: '2', type: 'product_list' },
139
- });
140
-
141
- const unwrapBizMessage = (input) => {
142
- let message = input;
143
- const visited = new Set();
144
- const wrappers = [
145
- 'ephemeralMessage',
146
- 'viewOnceMessage',
147
- 'viewOnceMessageV2',
148
- 'viewOnceMessageV2Extension',
149
- 'documentWithCaptionMessage',
150
- 'editedMessage',
151
- 'groupMentionedMessage',
152
- 'groupStatusMessage',
153
- 'groupStatusMessageV2',
154
- 'botInvokeMessage',
155
- 'botForwardedMessage',
156
- 'deviceSentMessage',
157
- ];
135
+ function unwrapMessage(message) {
136
+ const seen = new Set();
137
+ while (message && typeof message === 'object') {
138
+ if (seen.has(message)) break;
139
+ seen.add(message);
140
+ const key = UNWRAP_KEYS.find(k => message[k]?.message);
141
+ if (!key) return message;
142
+ message = message[key].message;
143
+ }
144
+ return message;
145
+ }
158
146
 
159
- while (message && typeof message === 'object' && !visited.has(message)) {
160
- visited.add(message);
161
- let next;
162
- for (const wrapper of wrappers) {
163
- const candidate = message[wrapper]?.message;
164
- if (candidate && typeof candidate === 'object') {
165
- next = candidate;
166
- break;
167
- }
168
- }
169
- if (!next) break;
170
- message = next;
147
+ export function getBizBinaryNode(message) {
148
+ const inner = unwrapMessage(message);
149
+ const interactive = inner?.interactiveMessage;
150
+ if (!interactive) {
151
+ // Fallback node so callers that always push [getBizBinaryNode(...)] don't put undefined
152
+ return { tag: 'biz', attrs: {} };
171
153
  }
172
154
 
173
- return message && typeof message === 'object' ? message : {};
174
- };
175
-
176
- /**
177
- * Creates the companion business binary node required by WhatsApp for
178
- * interactive, native-flow, carousel, button, template and list messages.
179
- *
180
- * @param {object} input A WAProto message or a message payload.
181
- * @returns {import('./types.js').BinaryNode}
182
- */
183
- export const getBizBinaryNode = (input) => {
184
- const message = unwrapBizMessage(input?.message ?? input);
185
- const interactiveMessage = message.interactiveMessage;
186
- const carouselCards = interactiveMessage?.carouselMessage?.cards;
187
- const cardFlowMessage = Array.isArray(carouselCards)
188
- ? carouselCards.find((card) => card?.nativeFlowMessage)?.nativeFlowMessage
189
- : undefined;
190
- const flowMessage = interactiveMessage?.nativeFlowMessage || cardFlowMessage;
191
- const flowButtons = Array.isArray(flowMessage?.buttons) ? flowMessage.buttons : [];
192
- const firstButtonName = flowButtons.find((button) => typeof button?.name === 'string')?.name;
193
- const bizAttributes = {
194
- actual_actors: '2',
195
- host_storage: '2',
196
- privacy_mode_ts: String(Math.floor(Date.now() / 1000)),
197
- };
198
- const qualityControlNode = {
199
- tag: 'quality_control',
200
- attrs: {
201
- decision_id: randomBytes(20).toString('hex'),
202
- source_type: 'third_party',
203
- },
204
- content: [
205
- {
206
- tag: 'decision_source',
207
- attrs: { value: 'df' },
208
- },
209
- ],
210
- };
211
-
212
- if (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info') {
213
- return {
214
- tag: 'biz',
215
- attrs: {
216
- ...bizAttributes,
217
- native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : 'payment_info',
218
- },
219
- content: [qualityControlNode],
220
- };
155
+ const flow = interactive.nativeFlowMessage;
156
+ const carousel = interactive.carouselMessage;
157
+ if (!carousel && !flow) {
158
+ return { tag: 'biz', attrs: {} };
221
159
  }
222
160
 
223
- if (firstButtonName && BIZ_FLOW_NAMES.has(firstButtonName)) {
161
+ if (carousel) {
224
162
  return {
225
163
  tag: 'biz',
226
- attrs: bizAttributes,
227
- content: [
228
- {
229
- tag: 'interactive',
230
- attrs: { ...BIZ_NATIVE_FLOW_ATTRIBUTES },
231
- content: [
232
- {
233
- tag: 'native_flow',
234
- attrs: { v: '2', name: firstButtonName },
235
- },
236
- ],
237
- },
238
- qualityControlNode,
239
- ],
164
+ attrs: {},
165
+ content: [{
166
+ tag: 'interactive',
167
+ attrs: { type: 'native_flow', v: '1' },
168
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
169
+ }]
240
170
  };
241
171
  }
242
172
 
243
- if (flowMessage || message.buttonsMessage || message.templateMessage) {
244
- return {
245
- tag: 'biz',
246
- attrs: bizAttributes,
247
- content: [createMixedNativeFlowNode(), qualityControlNode],
248
- };
249
- }
173
+ const buttons = flow?.buttons || [];
174
+ const name = buttons[0]?.name;
175
+ const uniform = buttons.length > 0 && buttons.every(b => b.name === name);
250
176
 
251
- if (message.listMessage) {
177
+ if (uniform && (name === 'review_and_pay' || name === 'payment_info' || name === 'payment_method' || name === 'payment_status')) {
252
178
  return {
253
179
  tag: 'biz',
254
- attrs: bizAttributes,
255
- content: [createListNode(), qualityControlNode],
180
+ attrs: { native_flow_name: name === 'review_and_pay' ? 'order_details' : name }
256
181
  };
257
182
  }
258
183
 
184
+ const specialized = uniform && BIZ_SPECIAL.has(name);
259
185
  return {
260
186
  tag: 'biz',
261
- attrs: bizAttributes,
262
- content: [qualityControlNode],
187
+ attrs: {},
188
+ content: [{
189
+ tag: 'interactive',
190
+ attrs: { type: 'native_flow', v: '1' },
191
+ content: [{
192
+ tag: 'native_flow',
193
+ attrs: { v: specialized ? '2' : '9', name: specialized ? name : 'mixed' }
194
+ }]
195
+ }]
263
196
  };
264
- };
197
+ }
265
198
  //# sourceMappingURL=generic-utils.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.3.34",
4
+ "version": "25.3.36",
5
5
  "description": "A WebSockets library for interacting with WhatsApp Web",
6
6
  "keywords": [
7
7
  "whatsapp",
@@ -21,21 +21,25 @@
21
21
  "engine-requirements.js",
22
22
  "extras/**/*",
23
23
  "helpers/**/*",
24
- "licenses/**/*",
25
- "scripts/**/*",
26
- "test/**/*"
24
+ "licenses/**/*"
27
25
  ],
28
26
  "scripts": {
29
- "build:all": "npm run check",
30
- "build": "npm run check",
31
- "check": "node ./scripts/verify-package.mjs",
27
+ "build:all": "npm run build && npm run build:docs",
28
+ "build:docs": "typedoc",
29
+ "build": "tsc -P tsconfig.build.json && tsc-esm-fix --tsconfig=tsconfig.build.json --ext=.js",
32
30
  "changelog:last": "conventional-changelog -p angular -r 2",
33
31
  "changelog:preview": "conventional-changelog -p angular -u",
34
32
  "changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
33
+ "example": "tsx ./Example/example.ts",
35
34
  "gen:protobuf": "sh WAProto/GenerateStatics.sh",
36
- "lint": "npm run check",
35
+ "format": "prettier --write \"src/**/*.{ts,js,json,md}\"",
36
+ "lint": "tsc && eslint src --ext .js,.ts",
37
+ "lint:fix": "npm run format && npm run lint -- --fix",
38
+ "preinstall": "node ./engine-requirements.js",
37
39
  "release": "release-it",
38
- "test": "node --test"
40
+ "test": "node --experimental-vm-modules ./node_modules/.bin/jest --testMatch '**/*.test.ts'",
41
+ "test:e2e": "NODE_TLS_REJECT_UNAUTHORIZED=0 node --experimental-vm-modules ./node_modules/.bin/jest --runInBand --forceExit --testMatch '**/*.test-e2e.ts'",
42
+ "update:version": "tsx ./scripts/update-version.ts"
39
43
  },
40
44
  "dependencies": {
41
45
  "@adiwajshing/keyed-db": "^0.2.4",
@@ -1,63 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
-
6
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
- const sourceRoots = ['lib', 'WAProto', 'extras', 'helpers', 'scripts', 'test'];
8
- const sourceExtensions = new Set(['.js', '.mjs', '.cjs']);
9
- const failures = [];
10
- const checked = [];
11
-
12
- function walk(directory) {
13
- if (!existsSync(directory)) return;
14
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
15
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
16
- const file = path.join(directory, entry.name);
17
- if (entry.isDirectory()) walk(file);
18
- else if (sourceExtensions.has(path.extname(entry.name))) checked.push(file);
19
- }
20
- }
21
-
22
- function resolveLocalImport(sourceFile, specifier) {
23
- const target = path.resolve(path.dirname(sourceFile), specifier);
24
- const candidates = [target];
25
- if (!path.extname(target)) {
26
- candidates.push(`${target}.js`, `${target}.mjs`, `${target}.cjs`, `${target}.json`);
27
- }
28
- candidates.push(path.join(target, 'index.js'), path.join(target, 'index.mjs'), path.join(target, 'index.cjs'));
29
- return candidates.find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
30
- }
31
-
32
- for (const directory of sourceRoots) walk(path.join(root, directory));
33
-
34
- for (const file of checked) {
35
- const result = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
36
- if (result.status !== 0) {
37
- failures.push(`${path.relative(root, file)}: ${result.stderr || result.stdout || 'syntax check failed'}`);
38
- continue;
39
- }
40
-
41
- const source = readFileSync(file, 'utf8');
42
- const importPattern = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
43
- for (const match of source.matchAll(importPattern)) {
44
- if (!resolveLocalImport(file, match[1])) {
45
- failures.push(`${path.relative(root, file)}: unresolved local import ${match[1]}`);
46
- }
47
- }
48
- }
49
-
50
- const packageJson = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
51
- for (const field of ['main', 'types']) {
52
- if (packageJson[field] && !existsSync(path.join(root, packageJson[field]))) {
53
- failures.push(`package.json: ${field} target does not exist: ${packageJson[field]}`);
54
- }
55
- }
56
-
57
- if (failures.length) {
58
- console.error(`Package check failed (${failures.length} issue${failures.length === 1 ? '' : 's'}):`);
59
- for (const failure of failures) console.error(`- ${failure}`);
60
- process.exitCode = 1;
61
- } else {
62
- console.log(`Package check passed: ${checked.length} JavaScript files; syntax and local import paths are valid.`);
63
- }
@@ -1,37 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { getBizBinaryNode } from '../lib/WABinary/index.js';
4
-
5
- test('creates the mixed native-flow node for interactive buttons', () => {
6
- const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'quick_reply' }] } } });
7
- assert.equal(node.tag, 'biz');
8
- assert.equal(node.content[0].tag, 'interactive');
9
- assert.deepEqual(node.content[0].content[0].attrs, { v: '9', name: 'mixed' });
10
- assert.equal(node.content[1].tag, 'quality_control');
11
- });
12
-
13
- test('creates the list companion node for list messages', () => {
14
- const node = getBizBinaryNode({ listMessage: {} });
15
- assert.deepEqual(node.content[0], { tag: 'list', attrs: { v: '2', type: 'product_list' } });
16
- });
17
-
18
- test('uses the dedicated native-flow node for supported special flows', () => {
19
- const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'send_location' }] } } });
20
- assert.equal(node.content[0].content[0].attrs.name, 'send_location');
21
- assert.equal(node.content[0].content[0].attrs.v, '2');
22
- });
23
-
24
- test('maps review_and_pay to the order_details business flow', () => {
25
- const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'review_and_pay' }] } } });
26
- assert.equal(node.attrs.native_flow_name, 'order_details');
27
- });
28
-
29
- test('finds native-flow data inside carousel cards', () => {
30
- const node = getBizBinaryNode({ interactiveMessage: { carouselMessage: { cards: [{ nativeFlowMessage: { buttons: [{ name: 'mpm' }] } }] } } });
31
- assert.equal(node.content[0].content[0].attrs.name, 'mpm');
32
- });
33
-
34
- test('unwraps view-once messages before selecting the business node', () => {
35
- const node = getBizBinaryNode({ viewOnceMessage: { message: { buttonsMessage: {} } } });
36
- assert.equal(node.content[0].content[0].attrs.name, 'mixed');
37
- });