@baileys-md/baileys 10.1.0 → 11.0.0

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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1303 -2
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/fix-imports.js +29 -0
  6. package/WAProto/index.js +13516 -4182
  7. package/lib/Defaults/baileys-version.js +1 -0
  8. package/lib/Defaults/index.js +51 -72
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +94 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +19 -0
  14. package/lib/Signal/Group/queue-job.js +54 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  17. package/lib/Signal/Group/sender-key-message.js +67 -0
  18. package/lib/Signal/Group/sender-key-name.js +48 -0
  19. package/lib/Signal/Group/sender-key-record.js +50 -0
  20. package/lib/Signal/Group/sender-key-state.js +96 -0
  21. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +4 -16
  22. package/lib/Signal/libsignal.js +41 -61
  23. package/lib/Socket/Client/index.js +3 -19
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +50 -0
  26. package/lib/Socket/business.js +37 -42
  27. package/lib/Socket/chats.js +194 -187
  28. package/lib/Socket/communities.js +351 -0
  29. package/lib/Socket/groups.js +87 -90
  30. package/lib/Socket/index.js +7 -8
  31. package/lib/Socket/messages-recv.js +360 -335
  32. package/lib/Socket/messages-send.js +156 -279
  33. package/lib/Socket/mex.js +42 -0
  34. package/lib/Socket/newsletter.js +144 -213
  35. package/lib/Socket/socket.js +128 -161
  36. package/lib/Socket/usync.js +19 -26
  37. package/lib/Types/Auth.js +2 -2
  38. package/lib/Types/Call.js +2 -2
  39. package/lib/Types/Chat.js +8 -4
  40. package/lib/Types/Contact.js +2 -2
  41. package/lib/Types/Events.js +2 -2
  42. package/lib/Types/GroupMetadata.js +2 -2
  43. package/lib/Types/Label.js +3 -5
  44. package/lib/Types/LabelAssociation.js +3 -5
  45. package/lib/Types/Message.js +7 -7
  46. package/lib/Types/Newsletter.js +30 -17
  47. package/lib/Types/Product.js +2 -2
  48. package/lib/Types/Signal.js +2 -2
  49. package/lib/Types/Socket.js +3 -2
  50. package/lib/Types/State.js +2 -2
  51. package/lib/Types/USync.js +2 -2
  52. package/lib/Types/index.js +15 -31
  53. package/lib/Utils/auth-utils.js +31 -47
  54. package/lib/Utils/baileys-event-stream.js +15 -22
  55. package/lib/Utils/business.js +66 -69
  56. package/lib/Utils/chat-utils.js +200 -195
  57. package/lib/Utils/crypto.js +70 -85
  58. package/lib/Utils/decode-wa-message.js +47 -51
  59. package/lib/Utils/event-buffer.js +36 -46
  60. package/lib/Utils/generics.js +116 -188
  61. package/lib/Utils/history.js +37 -46
  62. package/lib/Utils/index.js +19 -33
  63. package/lib/Utils/link-preview.js +14 -55
  64. package/lib/Utils/logger.js +3 -7
  65. package/lib/Utils/lt-hash.js +23 -26
  66. package/lib/{Store → Utils}/make-in-memory-store.js +19 -27
  67. package/lib/Utils/make-mutex.js +7 -10
  68. package/lib/{Store → Utils}/make-ordered-dictionary.js +1 -3
  69. package/lib/Utils/messages-media.js +236 -368
  70. package/lib/Utils/messages.js +278 -510
  71. package/lib/Utils/noise-handler.js +22 -31
  72. package/lib/{Store → Utils}/object-repository.js +1 -4
  73. package/lib/Utils/process-message.js +144 -148
  74. package/lib/Utils/signal.js +71 -64
  75. package/lib/Utils/use-multi-file-auth-state.js +112 -84
  76. package/lib/Utils/validate-connection.js +72 -115
  77. package/lib/WABinary/constants.js +1281 -20
  78. package/lib/WABinary/decode.js +15 -52
  79. package/lib/WABinary/encode.js +14 -48
  80. package/lib/WABinary/generic-utils.js +31 -39
  81. package/lib/WABinary/index.js +6 -21
  82. package/lib/WABinary/jid-utils.js +23 -40
  83. package/lib/WABinary/types.js +2 -2
  84. package/lib/WAM/BinaryInfo.js +2 -5
  85. package/lib/WAM/constants.js +2257 -2366
  86. package/lib/WAM/encode.js +17 -21
  87. package/lib/WAM/index.js +4 -19
  88. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  89. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  90. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  91. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  92. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  93. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +3 -6
  94. package/lib/WAUSync/Protocols/index.js +5 -20
  95. package/lib/WAUSync/USyncQuery.js +34 -32
  96. package/lib/WAUSync/USyncUser.js +2 -5
  97. package/lib/WAUSync/index.js +4 -19
  98. package/lib/index.js +11 -33
  99. package/package.json +25 -54
  100. package/WASignalGroup/GroupProtocol.js +0 -1697
  101. package/WASignalGroup/ciphertext_message.js +0 -16
  102. package/WASignalGroup/group_cipher.js +0 -120
  103. package/WASignalGroup/group_session_builder.js +0 -46
  104. package/WASignalGroup/index.js +0 -5
  105. package/WASignalGroup/keyhelper.js +0 -21
  106. package/WASignalGroup/protobufs.js +0 -3
  107. package/WASignalGroup/queue_job.js +0 -69
  108. package/WASignalGroup/sender_chain_key.js +0 -50
  109. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  110. package/WASignalGroup/sender_key_message.js +0 -92
  111. package/WASignalGroup/sender_key_name.js +0 -70
  112. package/WASignalGroup/sender_key_record.js +0 -56
  113. package/WASignalGroup/sender_key_state.js +0 -129
  114. package/lib/Defaults/baileys-version.json +0 -3
  115. package/lib/Defaults/phonenumber-mcc.json +0 -223
  116. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  117. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  118. package/lib/Socket/Client/web-socket-client.js +0 -62
  119. package/lib/Socket/registration.js +0 -166
  120. package/lib/Store/index.js +0 -8
  121. package/lib/Store/make-cache-manager-store.js +0 -83
  122. package/lib/Store/make-mongo-store.js +0 -567
@@ -1,90 +1,46 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
40
- exports.promiseTimeout = promiseTimeout;
41
- exports.bindWaitForEvent = bindWaitForEvent;
42
- exports.trimUndefined = trimUndefined;
43
- exports.bytesToCrockford = bytesToCrockford;
44
- const boom_1 = require("@hapi/boom");
45
- const axios_1 = __importDefault(require("axios"));
46
- const crypto_1 = require("crypto");
47
- const os_1 = require("os");
48
- const WAProto_1 = require("../../WAProto");
49
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
50
- const Types_1 = require("../Types");
51
- const WABinary_1 = require("../WABinary");
52
- const COMPANION_PLATFORM_MAP = {
53
- 'Chrome': '49',
54
- 'Edge': '50',
55
- 'Firefox': '51',
56
- 'Opera': '53',
57
- 'Safari': '54'
58
- };
1
+ import { Boom } from '@hapi/boom';
2
+ import axios, {} from 'axios';
3
+ import { createHash, randomBytes } from 'crypto';
4
+ import { platform, release } from 'os';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { version } from '../Defaults/baileys-version.js'
7
+ const baileysVersion = version.version;
8
+ import { DisconnectReason } from '../Types/index.js';
9
+ import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
59
10
  const PLATFORM_MAP = {
60
- 'aix': 'AIX',
61
- 'darwin': 'Mac OS',
62
- 'win32': 'Windows',
63
- 'android': 'Android',
64
- 'freebsd': 'FreeBSD',
65
- 'openbsd': 'OpenBSD',
66
- 'sunos': 'Solaris'
11
+ aix: 'AIX',
12
+ darwin: 'Mac OS',
13
+ win32: 'Windows',
14
+ android: 'Android',
15
+ freebsd: 'FreeBSD',
16
+ openbsd: 'OpenBSD',
17
+ sunos: 'Solaris',
18
+ linux: undefined,
19
+ haiku: undefined,
20
+ cygwin: undefined,
21
+ netbsd: undefined
67
22
  };
68
- exports.Browsers = {
69
- ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
70
- macOS: (browser) => ['Mac OS', browser, '14.4.1'],
71
- baileys: (browser) => ['Baileys', browser, '6.5.0'],
72
- windows: (browser) => ['Windows', browser, '10.0.22631'],
23
+ export const Browsers = {
24
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
25
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
26
+ baileys: browser => ['Baileys', browser, '6.5.0'],
27
+ windows: browser => ['Windows', browser, '10.0.22631'],
73
28
  /** The appropriate browser based on your OS & release */
74
- appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
29
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
75
30
  };
76
- const getPlatformId = (browser) => {
77
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
78
- return platformType ? platformType.toString() : '49'; //chrome
31
+ export const getPlatformId = (browser) => {
32
+ const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
33
+ return platformType ? platformType.toString() : '1'; //chrome
79
34
  };
80
- exports.getPlatformId = getPlatformId;
81
- exports.BufferJSON = {
35
+ export const BufferJSON = {
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
37
  replacer: (k, value) => {
83
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
84
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
38
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
39
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
85
40
  }
86
41
  return value;
87
42
  },
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
44
  reviver: (_, value) => {
89
45
  if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
90
46
  const val = value.data || value.value;
@@ -93,18 +49,18 @@ exports.BufferJSON = {
93
49
  return value;
94
50
  }
95
51
  };
96
- const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
97
- exports.getKeyAuthor = getKeyAuthor;
98
- const writeRandomPadMax16 = (msg) => {
99
- const pad = (0, crypto_1.randomBytes)(1);
100
- pad[0] &= 0xf;
101
- if (!pad[0]) {
52
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || '';
53
+ export const writeRandomPadMax16 = (msg) => {
54
+ const pad = randomBytes(1);
55
+ if (pad[0]) {
56
+ pad[0] &= 0xf;
57
+ }
58
+ else {
102
59
  pad[0] = 0xf;
103
60
  }
104
61
  return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
105
62
  };
106
- exports.writeRandomPadMax16 = writeRandomPadMax16;
107
- const unpadRandomMax16 = (e) => {
63
+ export const unpadRandomMax16 = (e) => {
108
64
  const t = new Uint8Array(e);
109
65
  if (0 === t.length) {
110
66
  throw new Error('unpadPkcs7 given empty bytes');
@@ -115,16 +71,11 @@ const unpadRandomMax16 = (e) => {
115
71
  }
116
72
  return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
117
73
  };
118
- exports.unpadRandomMax16 = unpadRandomMax16;
119
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
120
- exports.encodeWAMessage = encodeWAMessage;
121
- const encodeNewsletterMessage = (message) => (WAProto_1.proto.Message.encode(message).finish());
122
- exports.encodeNewsletterMessage = encodeNewsletterMessage;
123
- const generateRegistrationId = () => {
124
- return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
74
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
75
+ export const generateRegistrationId = () => {
76
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
125
77
  };
126
- exports.generateRegistrationId = generateRegistrationId;
127
- const encodeBigEndian = (e, t = 4) => {
78
+ export const encodeBigEndian = (e, t = 4) => {
128
79
  let r = e;
129
80
  const a = new Uint8Array(t);
130
81
  for (let i = t - 1; i >= 0; i--) {
@@ -133,33 +84,28 @@ const encodeBigEndian = (e, t = 4) => {
133
84
  }
134
85
  return a;
135
86
  };
136
- exports.encodeBigEndian = encodeBigEndian;
137
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
138
- exports.toNumber = toNumber;
87
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
139
88
  /** unix timestamp of a date in seconds */
140
- const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
141
- exports.unixTimestampSeconds = unixTimestampSeconds;
142
- const debouncedTimeout = (intervalMs = 1000, task) => {
89
+ export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
90
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
143
91
  let timeout;
144
92
  return {
145
93
  start: (newIntervalMs, newTask) => {
146
94
  task = newTask || task;
147
95
  intervalMs = newIntervalMs || intervalMs;
148
96
  timeout && clearTimeout(timeout);
149
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
97
+ timeout = setTimeout(() => task?.(), intervalMs);
150
98
  },
151
99
  cancel: () => {
152
100
  timeout && clearTimeout(timeout);
153
101
  timeout = undefined;
154
102
  },
155
- setTask: (newTask) => task = newTask,
156
- setInterval: (newInterval) => intervalMs = newInterval
103
+ setTask: (newTask) => (task = newTask),
104
+ setInterval: (newInterval) => (intervalMs = newInterval)
157
105
  };
158
106
  };
159
- exports.debouncedTimeout = debouncedTimeout;
160
- const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
161
- exports.delay = delay;
162
- const delayCancellable = (ms) => {
107
+ export const delay = (ms) => delayCancellable(ms).delay;
108
+ export const delayCancellable = (ms) => {
163
109
  const stack = new Error().stack;
164
110
  let timeout;
165
111
  let reject;
@@ -169,7 +115,7 @@ const delayCancellable = (ms) => {
169
115
  });
170
116
  const cancel = () => {
171
117
  clearTimeout(timeout);
172
- reject(new boom_1.Boom('Cancelled', {
118
+ reject(new Boom('Cancelled', {
173
119
  statusCode: 500,
174
120
  data: {
175
121
  stack
@@ -178,56 +124,53 @@ const delayCancellable = (ms) => {
178
124
  };
179
125
  return { delay, cancel };
180
126
  };
181
- exports.delayCancellable = delayCancellable;
182
- async function promiseTimeout(ms, promise) {
127
+ export async function promiseTimeout(ms, promise) {
183
128
  if (!ms) {
184
129
  return new Promise(promise);
185
130
  }
186
131
  const stack = new Error().stack;
187
132
  // Create a promise that rejects in <ms> milliseconds
188
- const { delay, cancel } = (0, exports.delayCancellable)(ms);
133
+ const { delay, cancel } = delayCancellable(ms);
189
134
  const p = new Promise((resolve, reject) => {
190
135
  delay
191
- .then(() => reject(new boom_1.Boom('Timed Out', {
192
- statusCode: Types_1.DisconnectReason.timedOut,
136
+ .then(() => reject(new Boom('Timed Out', {
137
+ statusCode: DisconnectReason.timedOut,
193
138
  data: {
194
139
  stack
195
140
  }
196
141
  })))
197
142
  .catch(err => reject(err));
198
143
  promise(resolve, reject);
199
- })
200
- .finally(cancel);
144
+ }).finally(cancel);
201
145
  return p;
202
146
  }
203
- const generateMessageIDV2 = (userId) => {
147
+ // inspired from whatsmeow code
148
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
149
+ export const generateMessageIDV2 = (userId) => {
204
150
  const data = Buffer.alloc(8 + 20 + 16);
205
151
  data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
206
152
  if (userId) {
207
- const id = (0, WABinary_1.jidDecode)(userId);
208
- if (id === null || id === void 0 ? void 0 : id.user) {
153
+ const id = jidDecode(userId);
154
+ if (id?.user) {
209
155
  data.write(id.user, 8);
210
156
  data.write('@c.us', 8 + id.user.length);
211
157
  }
212
158
  }
213
- const random = (0, crypto_1.randomBytes)(16);
159
+ const random = randomBytes(16);
214
160
  random.copy(data, 28);
215
- const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
161
+ const hash = createHash('sha256').update(data).digest();
216
162
  return 'BAE5' + hash.toString('hex').toUpperCase().substring(0, 12);
217
163
  };
218
- exports.generateMessageIDV2 = generateMessageIDV2;
219
164
  // generate a random ID to attach to a message
220
- const generateMessageID = () => 'BAE5' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
221
- exports.generateMessageID = generateMessageID;
222
- function bindWaitForEvent(ev, event) {
165
+ export const generateMessageID = () => 'BAE5' + randomBytes(6).toString('hex').toUpperCase();
166
+ export function bindWaitForEvent(ev, event) {
223
167
  return async (check, timeoutMs) => {
224
168
  let listener;
225
169
  let closeListener;
226
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
170
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
227
171
  closeListener = ({ connection, lastDisconnect }) => {
228
172
  if (connection === 'close') {
229
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
230
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
173
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
231
174
  }
232
175
  };
233
176
  ev.on('connection.update', closeListener);
@@ -237,35 +180,21 @@ function bindWaitForEvent(ev, event) {
237
180
  }
238
181
  };
239
182
  ev.on(event, listener);
240
- })
241
- .finally(() => {
183
+ }).finally(() => {
242
184
  ev.off(event, listener);
243
185
  ev.off('connection.update', closeListener);
244
- }));
186
+ });
245
187
  };
246
188
  }
247
- const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
248
- exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
249
- const printQRIfNecessaryListener = (ev, logger) => {
250
- ev.on('connection.update', async ({ qr }) => {
251
- if (qr) {
252
- const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
253
- .catch(() => {
254
- logger.error('QR code terminal not added as dependency');
255
- });
256
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
257
- }
258
- });
259
- };
260
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
189
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
261
190
  /**
262
191
  * utility that fetches latest baileys version from the master branch.
263
192
  * Use to ensure your WA connection is always on the latest version
264
193
  */
265
- const fetchLatestBaileysVersion = async (options = {}) => {
194
+ export const fetchLatestBaileysVersion = async (options = {}) => {
266
195
  const URL = 'https://raw.githubusercontent.com/ruhend2001/apk-dl/refs/heads/master/version.json';
267
196
  try {
268
- const result = await axios_1.default.get(URL, {
197
+ const result = await axios.get(URL, {
269
198
  ...options,
270
199
  responseType: 'json'
271
200
  });
@@ -276,28 +205,27 @@ const fetchLatestBaileysVersion = async (options = {}) => {
276
205
  }
277
206
  catch (error) {
278
207
  return {
279
- version: baileys_version_json_1.version,
208
+ version: baileysVersion,
280
209
  isLatest: false,
281
210
  error
282
211
  };
283
212
  }
284
213
  };
285
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
286
214
  /**
287
215
  * A utility that fetches the latest web version of whatsapp.
288
216
  * Use to ensure your WA connection is always on the latest version
289
217
  */
290
- const fetchLatestWaWebVersion = async (options) => {
218
+ export const fetchLatestWaWebVersion = async (options) => {
291
219
  try {
292
- const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
220
+ const { data } = await axios.get('https://web.whatsapp.com/sw.js', {
293
221
  ...options,
294
222
  responseType: 'json'
295
223
  });
296
224
  const regex = /\\?"client_revision\\?":\s*(\d+)/;
297
225
  const match = data.match(regex);
298
- if (!(match === null || match === void 0 ? void 0 : match[1])) {
226
+ if (!match?.[1]) {
299
227
  return {
300
- version: baileys_version_json_1.version,
228
+ version: baileysVersion,
301
229
  isLatest: false,
302
230
  error: {
303
231
  message: 'Could not find client revision in the fetched content'
@@ -312,49 +240,46 @@ const fetchLatestWaWebVersion = async (options) => {
312
240
  }
313
241
  catch (error) {
314
242
  return {
315
- version: baileys_version_json_1.version,
243
+ version: baileysVersion,
316
244
  isLatest: false,
317
245
  error
318
246
  };
319
247
  }
320
248
  };
321
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
322
249
  /** unique message tag prefix for MD clients */
323
- const generateMdTagPrefix = () => {
324
- const bytes = (0, crypto_1.randomBytes)(4);
250
+ export const generateMdTagPrefix = () => {
251
+ const bytes = randomBytes(4);
325
252
  return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
326
253
  };
327
- exports.generateMdTagPrefix = generateMdTagPrefix;
328
254
  const STATUS_MAP = {
329
- 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
330
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
331
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
332
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
255
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
256
+ played: proto.WebMessageInfo.Status.PLAYED,
257
+ read: proto.WebMessageInfo.Status.READ,
258
+ 'read-self': proto.WebMessageInfo.Status.READ
333
259
  };
334
260
  /**
335
261
  * Given a type of receipt, returns what the new status of the message should be
336
262
  * @param type type from receipt
337
263
  */
338
- const getStatusFromReceiptType = (type) => {
264
+ export const getStatusFromReceiptType = (type) => {
339
265
  const status = STATUS_MAP[type];
340
266
  if (typeof type === 'undefined') {
341
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
267
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
342
268
  }
343
269
  return status;
344
270
  };
345
- exports.getStatusFromReceiptType = getStatusFromReceiptType;
346
271
  const CODE_MAP = {
347
- conflict: Types_1.DisconnectReason.connectionReplaced
272
+ conflict: DisconnectReason.connectionReplaced
348
273
  };
349
274
  /**
350
275
  * Stream errors generally provide a reason, map that to a baileys DisconnectReason
351
276
  * @param reason the string reason given, eg. "conflict"
352
277
  */
353
- const getErrorCodeFromStreamError = (node) => {
354
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
355
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
356
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
357
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
278
+ export const getErrorCodeFromStreamError = (node) => {
279
+ const [reasonNode] = getAllBinaryNodeChildren(node);
280
+ let reason = reasonNode?.tag || 'unknown';
281
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
282
+ if (statusCode === DisconnectReason.restartRequired) {
358
283
  reason = 'restart required';
359
284
  }
360
285
  return {
@@ -362,8 +287,7 @@ const getErrorCodeFromStreamError = (node) => {
362
287
  statusCode
363
288
  };
364
289
  };
365
- exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
366
- const getCallStatusFromNode = ({ tag, attrs }) => {
290
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
367
291
  let status;
368
292
  switch (tag) {
369
293
  case 'offer':
@@ -375,7 +299,7 @@ const getCallStatusFromNode = ({ tag, attrs }) => {
375
299
  status = 'timeout';
376
300
  }
377
301
  else {
378
- // fired when accepted/rejected/timeout/caller hangs up
302
+ //fired when accepted/rejected/timeout/caller hangs up
379
303
  status = 'terminate';
380
304
  }
381
305
  break;
@@ -391,33 +315,33 @@ const getCallStatusFromNode = ({ tag, attrs }) => {
391
315
  }
392
316
  return status;
393
317
  };
394
- exports.getCallStatusFromNode = getCallStatusFromNode;
395
318
  const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
396
- const getCodeFromWSError = (error) => {
397
- var _a, _b, _c;
319
+ export const getCodeFromWSError = (error) => {
398
320
  let statusCode = 500;
399
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
400
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
321
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
322
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
401
323
  if (!Number.isNaN(code) && code >= 400) {
402
324
  statusCode = code;
403
325
  }
404
326
  }
405
- else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
406
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
327
+ else if (
328
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
329
+ error?.code?.startsWith('E') ||
330
+ error?.message?.includes('timed out')) {
331
+ // handle ETIMEOUT, ENOTFOUND etc
407
332
  statusCode = 408;
408
333
  }
409
334
  return statusCode;
410
335
  };
411
- exports.getCodeFromWSError = getCodeFromWSError;
412
336
  /**
413
337
  * Is the given platform WA business
414
338
  * @param platform AuthenticationCreds.platform
415
339
  */
416
- const isWABusinessPlatform = (platform) => {
340
+ export const isWABusinessPlatform = (platform) => {
417
341
  return platform === 'smbi' || platform === 'smba';
418
342
  };
419
- exports.isWABusinessPlatform = isWABusinessPlatform;
420
- function trimUndefined(obj) {
343
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
344
+ export function trimUndefined(obj) {
421
345
  for (const key in obj) {
422
346
  if (typeof obj[key] === 'undefined') {
423
347
  delete obj[key];
@@ -426,12 +350,12 @@ function trimUndefined(obj) {
426
350
  return obj;
427
351
  }
428
352
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
429
- function bytesToCrockford(buffer) {
353
+ export function bytesToCrockford(buffer) {
430
354
  let value = 0;
431
355
  let bitCount = 0;
432
356
  const crockford = [];
433
- for (let i = 0; i < buffer.length; i++) {
434
- value = (value << 8) | (buffer[i] & 0xff);
357
+ for (const element of buffer) {
358
+ value = (value << 8) | (element & 0xff);
435
359
  bitCount += 8;
436
360
  while (bitCount >= 5) {
437
361
  crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
@@ -443,3 +367,7 @@ function bytesToCrockford(buffer) {
443
367
  }
444
368
  return crockford.join('');
445
369
  }
370
+ export function encodeNewsletterMessage(message) {
371
+ return proto.Message.encode(message).finish();
372
+ }
373
+ //# sourceMappingURL=generics.js.map
@@ -1,17 +1,14 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
- const util_1 = require("util");
5
- const zlib_1 = require("zlib");
6
- const WAProto_1 = require("../../WAProto");
7
- const Types_1 = require("../Types");
8
- const WABinary_1 = require("../WABinary");
9
- const generics_1 = require("./generics");
10
- const messages_1 = require("./messages");
11
- const messages_media_1 = require("./messages-media");
12
- const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
- const downloadHistory = async (msg, options) => {
14
- const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
1
+ import { promisify } from 'util';
2
+ import { inflate } from 'zlib';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { WAMessageStubType } from '../Types/index.js';
5
+ import { isJidUser } from '../WABinary/index.js';
6
+ import { toNumber } from './generics.js';
7
+ import { normalizeMessageContent } from './messages.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ const inflatePromise = promisify(inflate);
10
+ export const downloadHistory = async (msg, options) => {
11
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
15
12
  const bufferArray = [];
16
13
  for await (const chunk of stream) {
17
14
  bufferArray.push(chunk);
@@ -19,53 +16,50 @@ const downloadHistory = async (msg, options) => {
19
16
  let buffer = Buffer.concat(bufferArray);
20
17
  // decompress buffer
21
18
  buffer = await inflatePromise(buffer);
22
- const syncData = WAProto_1.proto.HistorySync.decode(buffer);
19
+ const syncData = proto.HistorySync.decode(buffer);
23
20
  return syncData;
24
21
  };
25
- exports.downloadHistory = downloadHistory;
26
- const processHistoryMessage = (item) => {
27
- var _a, _b, _c;
22
+ export const processHistoryMessage = (item) => {
28
23
  const messages = [];
29
24
  const contacts = [];
30
25
  const chats = [];
31
26
  switch (item.syncType) {
32
- case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
- case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
- case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
- case WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
27
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
28
+ case proto.HistorySync.HistorySyncType.RECENT:
29
+ case proto.HistorySync.HistorySyncType.FULL:
30
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
36
31
  for (const chat of item.conversations) {
37
- contacts.push({ id: chat.id, name: chat.name || undefined });
32
+ contacts.push({
33
+ id: chat.id,
34
+ name: chat.name || undefined,
35
+ lid: chat.lidJid || undefined,
36
+ jid: isJidUser(chat.id) ? chat.id : undefined
37
+ });
38
38
  const msgs = chat.messages || [];
39
39
  delete chat.messages;
40
- delete chat.archived;
41
- delete chat.muteEndTime;
42
- delete chat.pinned;
43
40
  for (const item of msgs) {
44
41
  const message = item.message;
45
42
  messages.push(message);
46
- if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
43
+ if (!chat.messages?.length) {
47
44
  // keep only the most recent message in the chat array
48
45
  chat.messages = [{ message }];
49
46
  }
50
47
  if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
51
- chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
48
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
52
49
  }
53
- if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
54
- || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
55
- && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
50
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
51
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
52
+ message.messageStubParameters?.[0]) {
56
53
  contacts.push({
57
54
  id: message.key.participant || message.key.remoteJid,
58
- verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
55
+ verifiedName: message.messageStubParameters?.[0]
59
56
  });
60
57
  }
61
58
  }
62
- if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
63
- delete chat.readOnly;
64
- }
65
59
  chats.push({ ...chat });
66
60
  }
67
61
  break;
68
- case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
62
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
69
63
  for (const c of item.pushnames) {
70
64
  contacts.push({ id: c.id, notify: c.pushname });
71
65
  }
@@ -79,16 +73,13 @@ const processHistoryMessage = (item) => {
79
73
  progress: item.progress
80
74
  };
81
75
  };
82
- exports.processHistoryMessage = processHistoryMessage;
83
- const downloadAndProcessHistorySyncNotification = async (msg, options) => {
84
- const historyMsg = await (0, exports.downloadHistory)(msg, options);
85
- return (0, exports.processHistoryMessage)(historyMsg);
76
+ export const downloadAndProcessHistorySyncNotification = async (msg, options) => {
77
+ const historyMsg = await downloadHistory(msg, options);
78
+ return processHistoryMessage(historyMsg);
86
79
  };
87
- exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
88
- const getHistoryMsg = (message) => {
89
- var _a;
90
- const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
91
- const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
80
+ export const getHistoryMsg = (message) => {
81
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
82
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
92
83
  return anyHistoryMsg;
93
84
  };
94
- exports.getHistoryMsg = getHistoryMsg;
85
+ //# sourceMappingURL=history.js.map