@mrlegendbot/baileys 1.2.5 → 1.2.7

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 (212) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +14017 -0
  4. package/WAProto/index.js +97691 -2
  5. package/lib/Defaults/index.d.ts +75 -0
  6. package/lib/Defaults/index.js +92 -89
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +10 -9
  9. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  10. package/lib/Signal/Group/group-session-builder.js +22 -21
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +69 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +1 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  16. package/lib/Signal/Group/keyhelper.js +10 -9
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +22 -21
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +60 -51
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +62 -56
  23. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-name.js +40 -38
  25. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  26. package/lib/Signal/Group/sender-key-record.js +34 -33
  27. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -72
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -22
  31. package/lib/Signal/libsignal.d.ts +5 -0
  32. package/lib/Signal/libsignal.js +405 -506
  33. package/lib/Signal/lid-mapping.d.ts +23 -0
  34. package/lib/Signal/lid-mapping.js +258 -276
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +1 -0
  37. package/lib/Socket/Client/types.d.ts +16 -0
  38. package/lib/Socket/Client/types.js +7 -6
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +49 -48
  41. package/lib/Socket/business.d.ts +217 -0
  42. package/lib/Socket/business.js +369 -349
  43. package/lib/Socket/chats.d.ts +125 -0
  44. package/lib/Socket/chats.js +1148 -1172
  45. package/lib/Socket/communities.d.ts +273 -0
  46. package/lib/Socket/communities.js +413 -473
  47. package/lib/Socket/groups.d.ts +161 -0
  48. package/lib/Socket/groups.js +331 -387
  49. package/lib/Socket/index.d.ts +260 -0
  50. package/lib/Socket/index.js +8 -6
  51. package/lib/Socket/messages-recv.d.ts +203 -0
  52. package/lib/Socket/messages-recv.js +1719 -1782
  53. package/lib/Socket/messages-send.d.ts +200 -0
  54. package/lib/Socket/messages-send.js +2508 -1384
  55. package/lib/Socket/mex.d.ts +3 -0
  56. package/lib/Socket/mex.js +35 -40
  57. package/lib/Socket/newsletter.d.ts +170 -0
  58. package/lib/Socket/newsletter.js +191 -239
  59. package/lib/Socket/socket.d.ts +59 -0
  60. package/lib/Socket/socket.js +923 -992
  61. package/lib/Types/Auth.d.ts +117 -0
  62. package/lib/Types/Auth.js +1 -0
  63. package/lib/Types/Bussines.d.ts +25 -0
  64. package/lib/Types/Bussines.js +1 -0
  65. package/lib/Types/Call.d.ts +15 -0
  66. package/lib/Types/Call.js +1 -0
  67. package/lib/Types/Chat.d.ts +124 -0
  68. package/lib/Types/Chat.js +8 -1
  69. package/lib/Types/Contact.d.ts +26 -0
  70. package/lib/Types/Contact.js +1 -0
  71. package/lib/Types/Events.d.ts +256 -0
  72. package/lib/Types/Events.js +2 -1
  73. package/lib/Types/GroupMetadata.d.ts +71 -0
  74. package/lib/Types/GroupMetadata.js +1 -0
  75. package/lib/Types/Label.d.ts +47 -0
  76. package/lib/Types/Label.js +22 -20
  77. package/lib/Types/LabelAssociation.d.ts +30 -0
  78. package/lib/Types/LabelAssociation.js +4 -2
  79. package/lib/Types/Message.d.ts +320 -0
  80. package/lib/Types/Message.js +5 -3
  81. package/lib/Types/Mex.d.ts +141 -0
  82. package/lib/Types/Mex.js +31 -26
  83. package/lib/Types/Product.d.ts +79 -0
  84. package/lib/Types/Product.js +1 -0
  85. package/lib/Types/Signal.d.ts +87 -0
  86. package/lib/Types/Signal.js +2 -1
  87. package/lib/Types/Socket.d.ts +136 -0
  88. package/lib/Types/Socket.js +3 -2
  89. package/lib/Types/State.d.ts +97 -0
  90. package/lib/Types/State.js +52 -4
  91. package/lib/Types/USync.d.ts +26 -0
  92. package/lib/Types/USync.js +1 -0
  93. package/lib/Types/index.d.ts +66 -0
  94. package/lib/Types/index.js +11 -10
  95. package/lib/Utils/auth-utils.d.ts +24 -0
  96. package/lib/Utils/auth-utils.js +277 -240
  97. package/lib/Utils/browser-utils.d.ts +4 -0
  98. package/lib/Utils/browser-utils.js +23 -20
  99. package/lib/Utils/business.d.ts +23 -0
  100. package/lib/Utils/business.js +204 -200
  101. package/lib/Utils/chat-utils.d.ts +100 -0
  102. package/lib/Utils/chat-utils.js +810 -836
  103. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  104. package/lib/Utils/companion-reg-client-utils.js +25 -23
  105. package/lib/Utils/crypto.d.ts +37 -0
  106. package/lib/Utils/crypto.js +86 -70
  107. package/lib/Utils/decode-wa-message.d.ts +66 -0
  108. package/lib/Utils/decode-wa-message.js +284 -277
  109. package/lib/Utils/event-buffer.d.ts +36 -0
  110. package/lib/Utils/event-buffer.js +595 -592
  111. package/lib/Utils/generics.d.ts +92 -0
  112. package/lib/Utils/generics.js +335 -312
  113. package/lib/Utils/history.d.ts +24 -0
  114. package/lib/Utils/history.js +115 -123
  115. package/lib/Utils/identity-change-handler.d.ts +44 -0
  116. package/lib/Utils/identity-change-handler.js +50 -0
  117. package/lib/Utils/index.d.ts +22 -0
  118. package/lib/Utils/index.js +2 -1
  119. package/lib/Utils/link-preview.d.ts +21 -0
  120. package/lib/Utils/link-preview.js +73 -74
  121. package/lib/Utils/logger.d.ts +12 -0
  122. package/lib/Utils/logger.js +2 -3
  123. package/lib/Utils/lt-hash.d.ts +8 -0
  124. package/lib/Utils/lt-hash.js +6 -0
  125. package/lib/Utils/make-mutex.d.ts +9 -0
  126. package/lib/Utils/make-mutex.js +27 -27
  127. package/lib/Utils/message-retry-manager.d.ts +115 -0
  128. package/lib/Utils/message-retry-manager.js +254 -213
  129. package/lib/Utils/messages-media.d.ts +133 -0
  130. package/lib/Utils/messages-media.js +715 -741
  131. package/lib/Utils/messages.d.ts +91 -0
  132. package/lib/Utils/messages.js +827 -791
  133. package/lib/Utils/noise-handler.d.ts +20 -0
  134. package/lib/Utils/noise-handler.js +187 -215
  135. package/lib/Utils/offline-node-processor.d.ts +17 -0
  136. package/lib/Utils/offline-node-processor.js +40 -0
  137. package/lib/Utils/pre-key-manager.d.ts +28 -0
  138. package/lib/Utils/pre-key-manager.js +98 -69
  139. package/lib/Utils/process-message.d.ts +60 -0
  140. package/lib/Utils/process-message.js +586 -617
  141. package/lib/Utils/reporting-utils.d.ts +11 -0
  142. package/lib/Utils/reporting-utils.js +234 -553
  143. package/lib/Utils/signal.d.ts +47 -0
  144. package/lib/Utils/signal.js +170 -217
  145. package/lib/Utils/stanza-ack.d.ts +11 -0
  146. package/lib/Utils/stanza-ack.js +35 -27
  147. package/lib/Utils/sync-action-utils.d.ts +19 -0
  148. package/lib/Utils/sync-action-utils.js +41 -37
  149. package/lib/Utils/tc-token-utils.d.ts +37 -0
  150. package/lib/Utils/tc-token-utils.js +141 -120
  151. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  152. package/lib/Utils/use-multi-file-auth-state.js +105 -87
  153. package/lib/Utils/validate-connection.d.ts +11 -0
  154. package/lib/Utils/validate-connection.js +188 -190
  155. package/lib/WABinary/constants.d.ts +28 -0
  156. package/lib/WABinary/constants.js +1294 -28
  157. package/lib/WABinary/decode.d.ts +7 -0
  158. package/lib/WABinary/decode.js +249 -245
  159. package/lib/WABinary/encode.d.ts +3 -0
  160. package/lib/WABinary/encode.js +206 -201
  161. package/lib/WABinary/generic-utils.d.ts +15 -0
  162. package/lib/WABinary/generic-utils.js +89 -86
  163. package/lib/WABinary/index.d.ts +6 -0
  164. package/lib/WABinary/index.js +1 -0
  165. package/lib/WABinary/jid-utils.d.ts +48 -0
  166. package/lib/WABinary/jid-utils.js +77 -68
  167. package/lib/WABinary/types.d.ts +19 -0
  168. package/lib/WABinary/types.js +1 -0
  169. package/lib/WAM/BinaryInfo.d.ts +9 -0
  170. package/lib/WAM/BinaryInfo.js +8 -7
  171. package/lib/WAM/constants.d.ts +40 -0
  172. package/lib/WAM/constants.js +22853 -19892
  173. package/lib/WAM/encode.d.ts +3 -0
  174. package/lib/WAM/encode.js +132 -121
  175. package/lib/WAM/index.d.ts +4 -0
  176. package/lib/WAM/index.js +1 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +43 -46
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -47
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -22
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -30
  185. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  186. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +20 -19
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +44 -53
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  191. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  192. package/lib/WAUSync/Protocols/index.js +1 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  194. package/lib/WAUSync/USyncQuery.js +88 -79
  195. package/lib/WAUSync/USyncUser.d.ts +17 -0
  196. package/lib/WAUSync/USyncUser.js +29 -28
  197. package/lib/WAUSync/index.d.ts +4 -0
  198. package/lib/WAUSync/index.js +1 -0
  199. package/lib/index.d.ts +12 -0
  200. package/lib/index.js +2 -2
  201. package/package.json +86 -22
  202. package/README.upstream.md +0 -1312
  203. package/WAProto/WAProto.json +0 -1
  204. package/WAProto/WAProto.proto +0 -6275
  205. package/WAProto/compiler.js +0 -550
  206. package/lib/Store/index.js +0 -8
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Store/make-cache-manager-store.js +0 -70
  209. package/lib/Store/make-in-memory-store.js +0 -417
  210. package/lib/Store/make-ordered-dictionary.js +0 -69
  211. package/lib/Store/object-repository.js +0 -27
  212. package/lib/Utils/use-sqlite-auth-state.js +0 -162
@@ -1,370 +1,393 @@
1
1
  import { Boom } from '@hapi/boom';
2
2
  import { createHash, randomBytes } from 'crypto';
3
- import { proto } from '../../WAProto/compiler.js';
4
- const baileysVersion = [2, 3000, 1035194821];
3
+ import { proto } from '../../WAProto/index.js';
4
+ const baileysVersion = [2, 3000, 1043857760];
5
5
  import { DisconnectReason } from '../Types/index.js';
6
6
  import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
7
  import { sha256 } from './crypto.js';
8
8
  export const BufferJSON = {
9
- replacer: (k, value) => {
10
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
11
- return {
12
- type: 'Buffer',
13
- data: Buffer.from(value?.data || value).toString('base64')
14
- };
15
- }
16
- return value;
17
- },
18
- reviver: (_, value) => {
19
- if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
20
- return Buffer.from(value.data, 'base64');
21
- }
22
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
23
- const keys = Object.keys(value);
24
- if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
25
- const values = Object.values(value);
26
- if (values.every(v => typeof v === 'number')) {
27
- return Buffer.from(values);
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ replacer: (k, value) => {
11
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
13
+ }
14
+ return value;
15
+ },
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ reviver: (_, value) => {
18
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
+ return Buffer.from(value.data, 'base64');
20
+ }
21
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
+ const keys = Object.keys(value);
23
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
+ const values = Object.values(value);
25
+ if (values.every(v => typeof v === 'number')) {
26
+ return Buffer.from(values);
27
+ }
28
+ }
28
29
  }
29
- }
30
+ return value;
30
31
  }
31
- return value;
32
- }
33
32
  };
34
33
  export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
35
- export const isStringNullOrEmpty = value => value == null || value === '';
36
- export const writeRandomPadMax16 = msg => {
37
- const pad = randomBytes(1);
38
- const padLength = (pad[0] & 0x0f) + 1;
39
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
34
+ export const isStringNullOrEmpty = (value) =>
35
+ // eslint-disable-next-line eqeqeq
36
+ value == null || value === '';
37
+ export const writeRandomPadMax16 = (msg) => {
38
+ const pad = randomBytes(1);
39
+ const padLength = (pad[0] & 0x0f) + 1;
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
40
41
  };
41
- export const unpadRandomMax16 = e => {
42
- const t = new Uint8Array(e);
43
- if (0 === t.length) {
44
- throw new Error('unpadPkcs7 given empty bytes');
45
- }
46
- var r = t[t.length - 1];
47
- if (r > t.length) {
48
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
49
- }
50
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
42
+ export const unpadRandomMax16 = (e) => {
43
+ const t = new Uint8Array(e);
44
+ if (0 === t.length) {
45
+ throw new Error('unpadPkcs7 given empty bytes');
46
+ }
47
+ var r = t[t.length - 1];
48
+ if (r > t.length) {
49
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
50
+ }
51
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
51
52
  };
52
- export const generateParticipantHashV2 = participants => {
53
- participants.sort();
54
- const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
55
- return '2:' + sha256Hash.slice(0, 6);
53
+ // code is inspired by whatsmeow
54
+ export const generateParticipantHashV2 = (participants) => {
55
+ participants.sort();
56
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
+ return '2:' + sha256Hash.slice(0, 6);
56
58
  };
57
- export const encodeWAMessage = message => writeRandomPadMax16(proto.Message.encode(message).finish());
59
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
58
60
  export const generateRegistrationId = () => {
59
- return Uint16Array.from(randomBytes(2))[0] & 16383;
61
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
60
62
  };
61
63
  export const encodeBigEndian = (e, t = 4) => {
62
- let r = e;
63
- const a = new Uint8Array(t);
64
- for (let i = t - 1; i >= 0; i--) {
65
- a[i] = 255 & r;
66
- r >>>= 8;
67
- }
68
- return a;
64
+ let r = e;
65
+ const a = new Uint8Array(t);
66
+ for (let i = t - 1; i >= 0; i--) {
67
+ a[i] = 255 & r;
68
+ r >>>= 8;
69
+ }
70
+ return a;
69
71
  };
70
- export const toNumber = t => typeof t === 'object' && t ? 'toNumber' in t ? t.toNumber() : t.low : t || 0;
72
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
73
+ /** unix timestamp of a date in seconds */
71
74
  export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
72
75
  export const debouncedTimeout = (intervalMs = 1000, task) => {
73
- let timeout;
74
- return {
75
- start: (newIntervalMs, newTask) => {
76
- task = newTask || task;
77
- intervalMs = newIntervalMs || intervalMs;
78
- timeout && clearTimeout(timeout);
79
- timeout = setTimeout(() => task?.(), intervalMs);
80
- },
81
- cancel: () => {
82
- timeout && clearTimeout(timeout);
83
- timeout = undefined;
84
- },
85
- setTask: newTask => task = newTask,
86
- setInterval: newInterval => intervalMs = newInterval
87
- };
76
+ let timeout;
77
+ return {
78
+ start: (newIntervalMs, newTask) => {
79
+ task = newTask || task;
80
+ intervalMs = newIntervalMs || intervalMs;
81
+ timeout && clearTimeout(timeout);
82
+ timeout = setTimeout(() => task?.(), intervalMs);
83
+ },
84
+ cancel: () => {
85
+ timeout && clearTimeout(timeout);
86
+ timeout = undefined;
87
+ },
88
+ setTask: (newTask) => (task = newTask),
89
+ setInterval: (newInterval) => (intervalMs = newInterval)
90
+ };
88
91
  };
89
- export const delay = ms => delayCancellable(ms).delay;
90
- export const delayCancellable = ms => {
91
- const stack = new Error().stack;
92
- let timeout;
93
- let reject;
94
- const delay = new Promise((resolve, _reject) => {
95
- timeout = setTimeout(resolve, ms);
96
- reject = _reject;
97
- });
98
- const cancel = () => {
99
- clearTimeout(timeout);
100
- reject(new Boom('Cancelled', {
101
- statusCode: 500,
102
- data: {
103
- stack
104
- }
105
- }));
106
- };
107
- return {
108
- delay,
109
- cancel
110
- };
92
+ export const delay = (ms) => delayCancellable(ms).delay;
93
+ export const delayCancellable = (ms) => {
94
+ const stack = new Error().stack;
95
+ let timeout;
96
+ let reject;
97
+ const delay = new Promise((resolve, _reject) => {
98
+ timeout = setTimeout(resolve, ms);
99
+ reject = _reject;
100
+ });
101
+ const cancel = () => {
102
+ clearTimeout(timeout);
103
+ reject(new Boom('Cancelled', {
104
+ statusCode: 500,
105
+ data: {
106
+ stack
107
+ }
108
+ }));
109
+ };
110
+ return { delay, cancel };
111
111
  };
112
112
  export async function promiseTimeout(ms, promise) {
113
- if (!ms) {
114
- return new Promise(promise);
115
- }
116
- const stack = new Error().stack;
117
- const {
118
- delay,
119
- cancel
120
- } = delayCancellable(ms);
121
- const p = new Promise((resolve, reject) => {
122
- delay.then(() => reject(new Boom('Timed Out', {
123
- statusCode: DisconnectReason.timedOut,
124
- data: {
125
- stack
126
- }
127
- }))).catch(err => reject(err));
128
- promise(resolve, reject);
129
- }).finally(cancel);
130
- return p;
113
+ if (!ms) {
114
+ return new Promise(promise);
115
+ }
116
+ const stack = new Error().stack;
117
+ // Create a promise that rejects in <ms> milliseconds
118
+ const { delay, cancel } = delayCancellable(ms);
119
+ const p = new Promise((resolve, reject) => {
120
+ delay
121
+ .then(() => reject(new Boom('Timed Out', {
122
+ statusCode: DisconnectReason.timedOut,
123
+ data: {
124
+ stack
125
+ }
126
+ })))
127
+ .catch(err => reject(err));
128
+ promise(resolve, reject);
129
+ }).finally(cancel);
130
+ return p;
131
131
  }
132
- export const generateMessageIDV2 = userId => {
133
- const data = Buffer.alloc(8 + 20 + 16);
134
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
135
- if (userId) {
136
- const id = jidDecode(userId);
137
- if (id?.user) {
138
- data.write(id.user, 8);
139
- data.write('@c.us', 8 + id.user.length);
132
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.alloc(8 + 20 + 16);
136
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
137
+ if (userId) {
138
+ const id = jidDecode(userId);
139
+ if (id?.user) {
140
+ data.write(id.user, 8);
141
+ data.write('@c.us', 8 + id.user.length);
142
+ }
140
143
  }
141
- }
142
- const random = randomBytes(16);
143
- random.copy(data, 28);
144
- const hash = createHash('sha256').update(data).digest();
145
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
144
+ const random = randomBytes(16);
145
+ random.copy(data, 28);
146
+ const hash = createHash('sha256').update(data).digest();
147
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
146
148
  };
149
+ // generate a random ID to attach to a message
147
150
  export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
148
151
  export function bindWaitForEvent(ev, event) {
149
- return async (check, timeoutMs) => {
150
- let listener;
151
- let closeListener;
152
- await promiseTimeout(timeoutMs, (resolve, reject) => {
153
- closeListener = ({
154
- connection,
155
- lastDisconnect
156
- }) => {
157
- if (connection === 'close') {
158
- reject(lastDisconnect?.error || new Boom('Connection Closed', {
159
- statusCode: DisconnectReason.connectionClosed
160
- }));
161
- }
162
- };
163
- ev.on('connection.update', closeListener);
164
- listener = async update => {
165
- if (await check(update)) {
166
- resolve();
167
- }
168
- };
169
- ev.on(event, listener);
170
- }).finally(() => {
171
- ev.off(event, listener);
172
- ev.off('connection.update', closeListener);
173
- });
174
- };
152
+ return async (check, timeoutMs) => {
153
+ let listener;
154
+ let closeListener;
155
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
156
+ closeListener = ({ connection, lastDisconnect }) => {
157
+ if (connection === 'close') {
158
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
159
+ }
160
+ };
161
+ ev.on('connection.update', closeListener);
162
+ listener = async (update) => {
163
+ if (await check(update)) {
164
+ resolve();
165
+ }
166
+ };
167
+ ev.on(event, listener);
168
+ }).finally(() => {
169
+ ev.off(event, listener);
170
+ ev.off('connection.update', closeListener);
171
+ });
172
+ };
175
173
  }
176
- export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update');
174
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
175
+ /**
176
+ * utility that fetches latest baileys version from the master branch.
177
+ * Use to ensure your WA connection is always on the latest version
178
+ */
177
179
  export const fetchLatestBaileysVersion = async (options = {}) => {
178
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
179
- try {
180
- const response = await fetch(URL, {
181
- dispatcher: options.dispatcher,
182
- method: 'GET',
183
- headers: options.headers
184
- });
185
- if (!response.ok) {
186
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, {
187
- statusCode: response.status
188
- });
180
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
181
+ try {
182
+ const response = await fetch(URL, {
183
+ dispatcher: options.dispatcher,
184
+ method: 'GET',
185
+ headers: options.headers
186
+ });
187
+ if (!response.ok) {
188
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
189
+ }
190
+ const text = await response.text();
191
+ // Extract version from line 7 (const version = [...])
192
+ const lines = text.split('\n');
193
+ const versionLine = lines[6]; // Line 7 (0-indexed)
194
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
195
+ if (versionMatch) {
196
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
197
+ return {
198
+ version,
199
+ isLatest: true
200
+ };
201
+ }
202
+ else {
203
+ throw new Error('Could not parse version from Defaults/index.ts');
204
+ }
189
205
  }
190
- const text = await response.text();
191
- const lines = text.split('\n');
192
- const versionLine = lines[6];
193
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
194
- if (versionMatch) {
195
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
196
- return {
197
- version,
198
- isLatest: true
199
- };
200
- } else {
201
- throw new Error('Could not parse version from Defaults/index.ts');
206
+ catch (error) {
207
+ return {
208
+ version: baileysVersion,
209
+ isLatest: false,
210
+ error
211
+ };
202
212
  }
203
- } catch (error) {
204
- return {
205
- version: baileysVersion,
206
- isLatest: false,
207
- error
208
- };
209
- }
210
213
  };
214
+ /**
215
+ * A utility that fetches the latest web version of whatsapp.
216
+ * Use to ensure your WA connection is always on the latest version
217
+ */
211
218
  export const fetchLatestWaWebVersion = async (options = {}) => {
212
- try {
213
- const defaultHeaders = {
214
- 'sec-fetch-site': 'none',
215
- 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
216
- };
217
- const headers = {
218
- ...defaultHeaders,
219
- ...options.headers
220
- };
221
- const response = await fetch('https://web.whatsapp.com/sw.js', {
222
- ...options,
223
- method: 'GET',
224
- headers
225
- });
226
- if (!response.ok) {
227
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, {
228
- statusCode: response.status
229
- });
230
- }
231
- const data = await response.text();
232
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
233
- const match = data.match(regex);
234
- if (!match?.[1]) {
235
- return {
236
- version: baileysVersion,
237
- isLatest: false,
238
- error: {
239
- message: 'Could not find client revision in the fetched content'
219
+ try {
220
+ // Absolute minimal headers required to bypass anti-bot detection
221
+ const defaultHeaders = {
222
+ 'sec-fetch-site': 'none',
223
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
224
+ };
225
+ const headers = { ...defaultHeaders, ...options.headers };
226
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
227
+ ...options,
228
+ method: 'GET',
229
+ headers
230
+ });
231
+ if (!response.ok) {
232
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
233
+ }
234
+ const data = await response.text();
235
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
236
+ const match = data.match(regex);
237
+ if (!match?.[1]) {
238
+ return {
239
+ version: baileysVersion,
240
+ isLatest: false,
241
+ error: {
242
+ message: 'Could not find client revision in the fetched content'
243
+ }
244
+ };
240
245
  }
241
- };
246
+ const clientRevision = match[1];
247
+ return {
248
+ version: [2, 3000, +clientRevision],
249
+ isLatest: true
250
+ };
251
+ }
252
+ catch (error) {
253
+ return {
254
+ version: baileysVersion,
255
+ isLatest: false,
256
+ error
257
+ };
242
258
  }
243
- const clientRevision = match[1];
244
- return {
245
- version: [2, 3000, +clientRevision],
246
- isLatest: true
247
- };
248
- } catch (error) {
249
- return {
250
- version: baileysVersion,
251
- isLatest: false,
252
- error
253
- };
254
- }
255
259
  };
260
+ /** unique message tag prefix for MD clients */
256
261
  export const generateMdTagPrefix = () => {
257
- const bytes = randomBytes(4);
258
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
262
+ const bytes = randomBytes(4);
263
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
259
264
  };
260
265
  const STATUS_MAP = {
261
- sender: proto.WebMessageInfo.Status.SERVER_ACK,
262
- played: proto.WebMessageInfo.Status.PLAYED,
263
- read: proto.WebMessageInfo.Status.READ,
264
- 'read-self': proto.WebMessageInfo.Status.READ
266
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
267
+ played: proto.WebMessageInfo.Status.PLAYED,
268
+ read: proto.WebMessageInfo.Status.READ,
269
+ 'read-self': proto.WebMessageInfo.Status.READ
265
270
  };
266
- export const getStatusFromReceiptType = type => {
267
- const status = STATUS_MAP[type];
268
- if (typeof type === 'undefined') {
269
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
270
- }
271
- return status;
271
+ /**
272
+ * Given a type of receipt, returns what the new status of the message should be
273
+ * @param type type from receipt
274
+ */
275
+ export const getStatusFromReceiptType = (type) => {
276
+ const status = STATUS_MAP[type];
277
+ if (typeof type === 'undefined') {
278
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
279
+ }
280
+ return status;
272
281
  };
273
282
  const CODE_MAP = {
274
- conflict: DisconnectReason.connectionReplaced
283
+ conflict: DisconnectReason.connectionReplaced
275
284
  };
276
- export const getErrorCodeFromStreamError = node => {
277
- const [reasonNode] = getAllBinaryNodeChildren(node);
278
- let reason = reasonNode?.tag || 'unknown';
279
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
280
- if (statusCode === DisconnectReason.restartRequired) {
281
- reason = 'restart required';
282
- }
283
- return {
284
- reason,
285
- statusCode
286
- };
285
+ /**
286
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
287
+ * @param reason the string reason given, eg. "conflict"
288
+ */
289
+ export const getErrorCodeFromStreamError = (node) => {
290
+ const [reasonNode] = getAllBinaryNodeChildren(node);
291
+ let reason = reasonNode?.tag || 'unknown';
292
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
293
+ if (statusCode === DisconnectReason.restartRequired) {
294
+ reason = 'restart required';
295
+ }
296
+ return {
297
+ reason,
298
+ statusCode
299
+ };
287
300
  };
288
- export const getCallStatusFromNode = ({
289
- tag,
290
- attrs
291
- }) => {
292
- let status;
293
- switch (tag) {
294
- case 'offer':
295
- case 'offer_notice':
296
- status = 'offer';
297
- break;
298
- case 'terminate':
299
- if (attrs.reason === 'timeout') {
300
- status = 'timeout';
301
- } else {
302
- status = 'terminate';
303
- }
304
- break;
305
- case 'preaccept':
306
- status = 'preaccept';
307
- break;
308
- case 'transport':
309
- status = 'transport';
310
- break;
311
- case 'relaylatency':
312
- status = 'relaylatency';
313
- break;
314
- case 'reject':
315
- status = 'reject';
316
- break;
317
- case 'accept':
318
- status = 'accept';
319
- break;
320
- default:
321
- status = 'ringing';
322
- break;
323
- }
324
- return status;
301
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
302
+ let status;
303
+ switch (tag) {
304
+ case 'offer':
305
+ case 'offer_notice':
306
+ status = 'offer';
307
+ break;
308
+ case 'terminate':
309
+ if (attrs.reason === 'timeout') {
310
+ status = 'timeout';
311
+ }
312
+ else {
313
+ //fired when accepted/rejected/timeout/caller hangs up
314
+ status = 'terminate';
315
+ }
316
+ break;
317
+ case 'preaccept':
318
+ status = 'preaccept';
319
+ break;
320
+ case 'transport':
321
+ status = 'transport';
322
+ break;
323
+ case 'relaylatency':
324
+ status = 'relaylatency';
325
+ break;
326
+ case 'reject':
327
+ status = 'reject';
328
+ break;
329
+ case 'accept':
330
+ status = 'accept';
331
+ break;
332
+ default:
333
+ status = 'ringing';
334
+ break;
335
+ }
336
+ return status;
325
337
  };
326
338
  const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
327
- export const getCodeFromWSError = error => {
328
- let statusCode = 500;
329
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
330
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
331
- if (!Number.isNaN(code) && code >= 400) {
332
- statusCode = code;
339
+ export const getCodeFromWSError = (error) => {
340
+ let statusCode = 500;
341
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
342
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
343
+ if (!Number.isNaN(code) && code >= 400) {
344
+ statusCode = code;
345
+ }
346
+ }
347
+ else if (
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
+ error?.code?.startsWith('E') ||
350
+ error?.message?.includes('timed out')) {
351
+ // handle ETIMEOUT, ENOTFOUND etc
352
+ statusCode = 408;
333
353
  }
334
- } else if (error?.code?.startsWith('E') || error?.message?.includes('timed out')) {
335
- statusCode = 408;
336
- }
337
- return statusCode;
354
+ return statusCode;
338
355
  };
339
- export const isWABusinessPlatform = platform => {
340
- return platform === 'smbi' || platform === 'smba';
356
+ /**
357
+ * Is the given platform WA business
358
+ * @param platform AuthenticationCreds.platform
359
+ */
360
+ export const isWABusinessPlatform = (platform) => {
361
+ return platform === 'smbi' || platform === 'smba';
341
362
  };
363
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
364
  export function trimUndefined(obj) {
343
- for (const key in obj) {
344
- if (typeof obj[key] === 'undefined') {
345
- delete obj[key];
365
+ for (const key in obj) {
366
+ if (typeof obj[key] === 'undefined') {
367
+ delete obj[key];
368
+ }
346
369
  }
347
- }
348
- return obj;
370
+ return obj;
349
371
  }
350
372
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
351
373
  export function bytesToCrockford(buffer) {
352
- let value = 0;
353
- let bitCount = 0;
354
- const crockford = [];
355
- for (const element of buffer) {
356
- value = value << 8 | element & 0xff;
357
- bitCount += 8;
358
- while (bitCount >= 5) {
359
- crockford.push(CROCKFORD_CHARACTERS.charAt(value >>> bitCount - 5 & 31));
360
- bitCount -= 5;
374
+ let value = 0;
375
+ let bitCount = 0;
376
+ const crockford = [];
377
+ for (const element of buffer) {
378
+ value = (value << 8) | (element & 0xff);
379
+ bitCount += 8;
380
+ while (bitCount >= 5) {
381
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
382
+ bitCount -= 5;
383
+ }
384
+ }
385
+ if (bitCount > 0) {
386
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
361
387
  }
362
- }
363
- if (bitCount > 0) {
364
- crockford.push(CROCKFORD_CHARACTERS.charAt(value << 5 - bitCount & 31));
365
- }
366
- return crockford.join('');
388
+ return crockford.join('');
367
389
  }
368
390
  export function encodeNewsletterMessage(message) {
369
- return proto.Message.encode(message).finish();
391
+ return proto.Message.encode(message).finish();
370
392
  }
393
+ //# sourceMappingURL=generics.js.map