astrabail 1.0.6

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 (224) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,483 @@
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.fetchLatestAstraVersion = exports.asciiDecode = exports.asciiEncode = exports.fromUnicodeEscape = exports.toUnicodeEscape = exports.printQRIfNecessaryListener = exports.COMPANION_PLATFORM_MAP = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.generateParticipantHashV2 = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.isStringNullOrEmpty = exports.getKeyAuthor = exports.BufferJSON = void 0;
40
+ exports.promiseTimeout = promiseTimeout;
41
+ exports.bindWaitForEvent = bindWaitForEvent;
42
+ exports.trimUndefined = trimUndefined;
43
+ exports.bytesToCrockford = bytesToCrockford;
44
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
45
+ const boom_1 = require("@hapi/boom");
46
+ const crypto_1 = require("crypto");
47
+ const axios_1 = __importDefault(require("axios"));
48
+ const index_js_1 = require("../../WAProto/index.js");
49
+ const waVer = require('../Defaults/astrabail-version.json');
50
+ const baileysVersion = waVer?.version || [2, 3000, 1036687490];
51
+ const index_js_2 = require("../Types/index.js");
52
+ const index_js_3 = require("../WABinary/index.js");
53
+ const crypto_js_1 = require("./crypto.js");
54
+ exports.BufferJSON = {
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ replacer: (k, value) => {
57
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
58
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
59
+ }
60
+ return value;
61
+ },
62
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
63
+ reviver: (_, value) => {
64
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
65
+ return Buffer.from(value.data, 'base64');
66
+ }
67
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
68
+ const keys = Object.keys(value);
69
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
70
+ const values = Object.values(value);
71
+ if (values.every(v => typeof v === 'number')) {
72
+ return Buffer.from(values);
73
+ }
74
+ }
75
+ }
76
+ return value;
77
+ }
78
+ };
79
+ const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
80
+ exports.getKeyAuthor = getKeyAuthor;
81
+ const isStringNullOrEmpty = (value) =>
82
+ // eslint-disable-next-line eqeqeq
83
+ value == null || value === '';
84
+ exports.isStringNullOrEmpty = isStringNullOrEmpty;
85
+ const writeRandomPadMax16 = (msg) => {
86
+ const pad = (0, crypto_1.randomBytes)(1);
87
+ const padLength = (pad[0] & 0x0f) + 1;
88
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
89
+ };
90
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
91
+ const unpadRandomMax16 = (e) => {
92
+ const t = new Uint8Array(e);
93
+ if (0 === t.length) {
94
+ throw new Error('unpadPkcs7 given empty bytes');
95
+ }
96
+ var r = t[t.length - 1];
97
+ if (r > t.length) {
98
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
99
+ }
100
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
101
+ };
102
+ exports.unpadRandomMax16 = unpadRandomMax16;
103
+ // code is inspired by whatsmeow
104
+ const generateParticipantHashV2 = (participants) => {
105
+ participants.sort();
106
+ const sha256Hash = (0, crypto_js_1.sha256)(Buffer.from(participants.join(''))).toString('base64');
107
+ return '2:' + sha256Hash.slice(0, 6);
108
+ };
109
+ exports.generateParticipantHashV2 = generateParticipantHashV2;
110
+ const encodeWAMessage = (message) => (0, exports.writeRandomPadMax16)(index_js_1.proto.Message.encode(message).finish());
111
+ exports.encodeWAMessage = encodeWAMessage;
112
+ const generateRegistrationId = () => {
113
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
114
+ };
115
+ exports.generateRegistrationId = generateRegistrationId;
116
+ const encodeBigEndian = (e, t = 4) => {
117
+ let r = e;
118
+ const a = new Uint8Array(t);
119
+ for (let i = t - 1; i >= 0; i--) {
120
+ a[i] = 255 & r;
121
+ r >>>= 8;
122
+ }
123
+ return a;
124
+ };
125
+ exports.encodeBigEndian = encodeBigEndian;
126
+ const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
127
+ exports.toNumber = toNumber;
128
+ /** unix timestamp of a date in seconds */
129
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
130
+ exports.unixTimestampSeconds = unixTimestampSeconds;
131
+ const debouncedTimeout = (intervalMs = 1000, task) => {
132
+ let timeout;
133
+ return {
134
+ start: (newIntervalMs, newTask) => {
135
+ task = newTask || task;
136
+ intervalMs = newIntervalMs || intervalMs;
137
+ timeout && clearTimeout(timeout);
138
+ timeout = setTimeout(() => task?.(), intervalMs);
139
+ },
140
+ cancel: () => {
141
+ timeout && clearTimeout(timeout);
142
+ timeout = undefined;
143
+ },
144
+ setTask: (newTask) => (task = newTask),
145
+ setInterval: (newInterval) => (intervalMs = newInterval)
146
+ };
147
+ };
148
+ exports.debouncedTimeout = debouncedTimeout;
149
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
150
+ exports.delay = delay;
151
+ const delayCancellable = (ms) => {
152
+ const stack = new Error().stack;
153
+ let timeout;
154
+ let reject;
155
+ const delay = new Promise((resolve, _reject) => {
156
+ timeout = setTimeout(resolve, ms);
157
+ reject = _reject;
158
+ });
159
+ const cancel = () => {
160
+ clearTimeout(timeout);
161
+ reject(new boom_1.Boom('Cancelled', {
162
+ statusCode: 500,
163
+ data: {
164
+ stack
165
+ }
166
+ }));
167
+ };
168
+ return { delay, cancel };
169
+ };
170
+ exports.delayCancellable = delayCancellable;
171
+ async function promiseTimeout(ms, promise) {
172
+ if (!ms) {
173
+ return new Promise(promise);
174
+ }
175
+ const stack = new Error().stack;
176
+ // Create a promise that rejects in <ms> milliseconds
177
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
178
+ const p = new Promise((resolve, reject) => {
179
+ delay
180
+ .then(() => reject(new boom_1.Boom('Timed Out', {
181
+ statusCode: index_js_2.DisconnectReason.timedOut,
182
+ data: {
183
+ stack
184
+ }
185
+ })))
186
+ .catch(err => reject(err));
187
+ promise(resolve, reject);
188
+ }).finally(cancel);
189
+ return p;
190
+ }
191
+ // inspired from whatsmeow code
192
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
193
+ const generateMessageIDV2 = (userId) => {
194
+ const data = Buffer.alloc(8 + 20 + 16);
195
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
196
+ if (userId) {
197
+ const id = (0, index_js_3.jidDecode)(userId);
198
+ if (id?.user) {
199
+ data.write(id.user, 8);
200
+ data.write('@c.us', 8 + id.user.length);
201
+ }
202
+ }
203
+ const random = (0, crypto_1.randomBytes)(16);
204
+ random.copy(data, 28);
205
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
206
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
207
+ };
208
+ exports.generateMessageIDV2 = generateMessageIDV2;
209
+ // generate a random ID to attach to a message
210
+ const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
211
+ exports.generateMessageID = generateMessageID;
212
+ function bindWaitForEvent(ev, event) {
213
+ return async (check, timeoutMs) => {
214
+ let listener;
215
+ let closeListener;
216
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
217
+ closeListener = ({ connection, lastDisconnect }) => {
218
+ if (connection === 'close') {
219
+ reject(lastDisconnect?.error || new boom_1.Boom('Connection Closed', { statusCode: index_js_2.DisconnectReason.connectionClosed }));
220
+ }
221
+ };
222
+ ev.on('connection.update', closeListener);
223
+ listener = async (update) => {
224
+ if (await check(update)) {
225
+ resolve();
226
+ }
227
+ };
228
+ ev.on(event, listener);
229
+ }).finally(() => {
230
+ ev.off(event, listener);
231
+ ev.off('connection.update', closeListener);
232
+ });
233
+ };
234
+ }
235
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
236
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
237
+ /**
238
+ * utility that fetches latest baileys version from the master branch.
239
+ * Use to ensure your WA connection is always on the latest version
240
+ */
241
+ const fetchLatestBaileysVersion = async (options = {}) => {
242
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
243
+ try {
244
+ const response = await fetch(URL, {
245
+ dispatcher: options.dispatcher,
246
+ method: 'GET',
247
+ headers: options.headers
248
+ });
249
+ if (!response.ok) {
250
+ throw new boom_1.Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
251
+ }
252
+ const text = await response.text();
253
+ // Extract version from line 7 (const version = [...])
254
+ const lines = text.split('\n');
255
+ const versionLine = lines[6]; // Line 7 (0-indexed)
256
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
257
+ if (versionMatch) {
258
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
259
+ return {
260
+ version,
261
+ isLatest: true
262
+ };
263
+ }
264
+ else {
265
+ throw new Error('Could not parse version from Defaults/index.ts');
266
+ }
267
+ }
268
+ catch (error) {
269
+ return {
270
+ version: baileysVersion,
271
+ isLatest: false,
272
+ error
273
+ };
274
+ }
275
+ };
276
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
277
+ /**
278
+ * A utility that fetches the latest web version of whatsapp.
279
+ * Use to ensure your WA connection is always on the latest version
280
+ */
281
+ const fetchLatestWaWebVersion = async (options = {}) => {
282
+ try {
283
+ // Absolute minimal headers required to bypass anti-bot detection
284
+ const defaultHeaders = {
285
+ 'sec-fetch-site': 'none',
286
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
287
+ };
288
+ const headers = { ...defaultHeaders, ...options.headers };
289
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
290
+ ...options,
291
+ method: 'GET',
292
+ headers
293
+ });
294
+ if (!response.ok) {
295
+ throw new boom_1.Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
296
+ }
297
+ const data = await response.text();
298
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
299
+ const match = data.match(regex);
300
+ if (!match?.[1]) {
301
+ return {
302
+ version: baileysVersion,
303
+ isLatest: false,
304
+ error: {
305
+ message: 'Could not find client revision in the fetched content'
306
+ }
307
+ };
308
+ }
309
+ const clientRevision = match[1];
310
+ return {
311
+ version: [2, 3000, +clientRevision],
312
+ isLatest: true
313
+ };
314
+ }
315
+ catch (error) {
316
+ return {
317
+ version: baileysVersion,
318
+ isLatest: false,
319
+ error
320
+ };
321
+ }
322
+ };
323
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
324
+ /** unique message tag prefix for MD clients */
325
+ const generateMdTagPrefix = () => {
326
+ const bytes = (0, crypto_1.randomBytes)(4);
327
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
328
+ };
329
+ exports.generateMdTagPrefix = generateMdTagPrefix;
330
+ const STATUS_MAP = {
331
+ sender: index_js_1.proto.WebMessageInfo.Status.SERVER_ACK,
332
+ played: index_js_1.proto.WebMessageInfo.Status.PLAYED,
333
+ read: index_js_1.proto.WebMessageInfo.Status.READ,
334
+ 'read-self': index_js_1.proto.WebMessageInfo.Status.READ
335
+ };
336
+ /**
337
+ * Given a type of receipt, returns what the new status of the message should be
338
+ * @param type type from receipt
339
+ */
340
+ const getStatusFromReceiptType = (type) => {
341
+ const status = STATUS_MAP[type];
342
+ if (typeof type === 'undefined') {
343
+ return index_js_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
344
+ }
345
+ return status;
346
+ };
347
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
348
+ const CODE_MAP = {
349
+ conflict: index_js_2.DisconnectReason.connectionReplaced
350
+ };
351
+ /**
352
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
353
+ * @param reason the string reason given, eg. "conflict"
354
+ */
355
+ const getErrorCodeFromStreamError = (node) => {
356
+ const [reasonNode] = (0, index_js_3.getAllBinaryNodeChildren)(node);
357
+ let reason = reasonNode?.tag || 'unknown';
358
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || index_js_2.DisconnectReason.badSession);
359
+ if (statusCode === index_js_2.DisconnectReason.restartRequired) {
360
+ reason = 'restart required';
361
+ }
362
+ return {
363
+ reason,
364
+ statusCode
365
+ };
366
+ };
367
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
368
+ const getCallStatusFromNode = ({ tag, attrs }) => {
369
+ let status;
370
+ switch (tag) {
371
+ case 'offer':
372
+ case 'offer_notice':
373
+ status = 'offer';
374
+ break;
375
+ case 'terminate':
376
+ if (attrs.reason === 'timeout') {
377
+ status = 'timeout';
378
+ }
379
+ else {
380
+ //fired when accepted/rejected/timeout/caller hangs up
381
+ status = 'terminate';
382
+ }
383
+ break;
384
+ case 'reject':
385
+ status = 'reject';
386
+ break;
387
+ case 'accept':
388
+ status = 'accept';
389
+ break;
390
+ default:
391
+ status = 'ringing';
392
+ break;
393
+ }
394
+ return status;
395
+ };
396
+ exports.getCallStatusFromNode = getCallStatusFromNode;
397
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
398
+ const getCodeFromWSError = (error) => {
399
+ let statusCode = 500;
400
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
401
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
402
+ if (!Number.isNaN(code) && code >= 400) {
403
+ statusCode = code;
404
+ }
405
+ }
406
+ else if (
407
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
408
+ error?.code?.startsWith('E') ||
409
+ error?.message?.includes('timed out')) {
410
+ // handle ETIMEOUT, ENOTFOUND etc
411
+ statusCode = 408;
412
+ }
413
+ return statusCode;
414
+ };
415
+ exports.getCodeFromWSError = getCodeFromWSError;
416
+ /**
417
+ * Is the given platform WA business
418
+ * @param platform AuthenticationCreds.platform
419
+ */
420
+ const isWABusinessPlatform = (platform) => {
421
+ return platform === 'smbi' || platform === 'smba';
422
+ };
423
+ exports.isWABusinessPlatform = isWABusinessPlatform;
424
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
425
+ function trimUndefined(obj) {
426
+ for (const key in obj) {
427
+ if (typeof obj[key] === 'undefined') {
428
+ delete obj[key];
429
+ }
430
+ }
431
+ return obj;
432
+ }
433
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
434
+ function bytesToCrockford(buffer) {
435
+ let value = 0;
436
+ let bitCount = 0;
437
+ const crockford = [];
438
+ for (const element of buffer) {
439
+ value = (value << 8) | (element & 0xff);
440
+ bitCount += 8;
441
+ while (bitCount >= 5) {
442
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
443
+ bitCount -= 5;
444
+ }
445
+ }
446
+ if (bitCount > 0) {
447
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
448
+ }
449
+ return crockford.join('');
450
+ }
451
+ function encodeNewsletterMessage(message) {
452
+ return index_js_1.proto.Message.encode(message).finish();
453
+ }
454
+ exports.COMPANION_PLATFORM_MAP = {
455
+ 'Chrome': '49', 'Edge': '50', 'Firefox': '51', 'Opera': '53', 'Safari': '54',
456
+ 'Brave': '1.79.112', 'Vivaldi': '6.2.3105.58', 'Tor': '12.5.3',
457
+ 'Yandex': '23.7.1', 'Falkon': '22.08.3', 'Epiphany': '44.2'
458
+ };
459
+ // Browsers, PLATFORM_MAP, PLATFORM_VERSIONS, getPlatformId moved to browser-utils.js
460
+ const printQRIfNecessaryListener = (ev, logger) => {
461
+ ev.on('connection.update', async ({ qr }) => {
462
+ if (qr) {
463
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m).catch(() => {
464
+ logger.error('QR code terminal not added as dependency');
465
+ });
466
+ QR?.generate(qr, { small: true });
467
+ }
468
+ });
469
+ };
470
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
471
+ const toUnicodeEscape = (text) => text.split('').map(c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')).join('');
472
+ exports.toUnicodeEscape = toUnicodeEscape;
473
+ const fromUnicodeEscape = (escapedText) => escapedText.replace(/\\u[\dA-Fa-f]{4}/g, m => String.fromCharCode(parseInt(m.slice(2), 16)));
474
+ exports.fromUnicodeEscape = fromUnicodeEscape;
475
+ const asciiEncode = (text) => text.split('').map(c => c.charCodeAt(0));
476
+ exports.asciiEncode = asciiEncode;
477
+ const asciiDecode = (...codes) => {
478
+ const arr = Array.isArray(codes[0]) ? codes[0] : codes;
479
+ return arr.map(c => String.fromCharCode(c)).join('');
480
+ };
481
+ exports.asciiDecode = asciiDecode;
482
+
483
+ exports.fetchLatestAstraVersion = exports.fetchLatestBaileysVersion;
@@ -0,0 +1,22 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => Promise<proto.HistorySync>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => {
6
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: WAMessage[];
9
+ lidPnMappings: LIDMapping[];
10
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
11
+ progress: number | null | undefined;
12
+ };
13
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<{
14
+ chats: Chat[];
15
+ contacts: Contact[];
16
+ messages: WAMessage[];
17
+ lidPnMappings: LIDMapping[];
18
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
19
+ progress: number | null | undefined;
20
+ }>;
21
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification;
22
+ //# sourceMappingURL=history.d.ts.map
@@ -0,0 +1,137 @@
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 index_js_1 = require("../../WAProto/index.js");
7
+ const index_js_2 = require("../Types/index.js");
8
+ const index_js_3 = require("../WABinary/index.js");
9
+ const generics_js_1 = require("./generics.js");
10
+ const messages_js_1 = require("./messages.js");
11
+ const messages_media_js_1 = require("./messages-media.js");
12
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
+ const extractPnFromMessages = (messages) => {
14
+ for (const msgItem of messages) {
15
+ const message = msgItem.message;
16
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
17
+ // because userReceipt.userJid is the recipient's JID
18
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
19
+ continue;
20
+ }
21
+ const userJid = message.userReceipt[0]?.userJid;
22
+ if (userJid && ((0, index_js_3.isPnUser)(userJid) || (0, index_js_3.isHostedPnUser)(userJid))) {
23
+ return userJid;
24
+ }
25
+ }
26
+ return undefined;
27
+ };
28
+ const downloadHistory = async (msg, options) => {
29
+ const stream = await (0, messages_media_js_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
30
+ const bufferArray = [];
31
+ for await (const chunk of stream) {
32
+ bufferArray.push(chunk);
33
+ }
34
+ let buffer = Buffer.concat(bufferArray);
35
+ // decompress buffer
36
+ buffer = await inflatePromise(buffer);
37
+ const syncData = index_js_1.proto.HistorySync.decode(buffer);
38
+ return syncData;
39
+ };
40
+ exports.downloadHistory = downloadHistory;
41
+ const processHistoryMessage = (item, logger) => {
42
+ const messages = [];
43
+ const contacts = [];
44
+ const chats = [];
45
+ const lidPnMappings = [];
46
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
47
+ // Extract LID-PN mappings for all sync types
48
+ for (const m of item.phoneNumberToLidMappings || []) {
49
+ if (m.lidJid && m.pnJid) {
50
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
51
+ }
52
+ }
53
+ switch (item.syncType) {
54
+ case index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
55
+ case index_js_1.proto.HistorySync.HistorySyncType.RECENT:
56
+ case index_js_1.proto.HistorySync.HistorySyncType.FULL:
57
+ case index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
58
+ for (const chat of item.conversations) {
59
+ contacts.push({
60
+ id: chat.id,
61
+ name: chat.displayName || chat.name || chat.username || undefined,
62
+ lid: chat.lidJid || chat.accountLid || undefined,
63
+ phoneNumber: chat.pnJid || undefined
64
+ });
65
+ const chatId = chat.id;
66
+ const isLid = (0, index_js_3.isLidUser)(chatId) || (0, index_js_3.isHostedLidUser)(chatId);
67
+ const isPn = (0, index_js_3.isPnUser)(chatId) || (0, index_js_3.isHostedPnUser)(chatId);
68
+ if (isLid && chat.pnJid) {
69
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
70
+ }
71
+ else if (isPn && chat.lidJid) {
72
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
73
+ }
74
+ else if (isLid && !chat.pnJid) {
75
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
76
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
77
+ if (pnFromReceipt) {
78
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
79
+ }
80
+ }
81
+ const msgs = chat.messages || [];
82
+ delete chat.messages;
83
+ for (const item of msgs) {
84
+ const message = item.message;
85
+ messages.push(message);
86
+ if (!chat.messages?.length) {
87
+ // keep only the most recent message in the chat array
88
+ chat.messages = [{ message }];
89
+ }
90
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
91
+ chat.lastMessageRecvTimestamp = (0, generics_js_1.toNumber)(message.messageTimestamp);
92
+ }
93
+ if ((message.messageStubType === index_js_2.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
94
+ message.messageStubType === index_js_2.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
95
+ message.messageStubParameters?.[0]) {
96
+ contacts.push({
97
+ id: message.key.participant || message.key.remoteJid,
98
+ verifiedName: message.messageStubParameters?.[0]
99
+ });
100
+ }
101
+ }
102
+ chats.push({ ...chat });
103
+ }
104
+ break;
105
+ case index_js_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
106
+ for (const c of item.pushnames) {
107
+ contacts.push({ id: c.id, notify: c.pushname });
108
+ }
109
+ break;
110
+ }
111
+ return {
112
+ chats,
113
+ contacts,
114
+ messages,
115
+ lidPnMappings,
116
+ syncType: item.syncType,
117
+ progress: item.progress
118
+ };
119
+ };
120
+ exports.processHistoryMessage = processHistoryMessage;
121
+ const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
122
+ let historyMsg;
123
+ if (msg.initialHistBootstrapInlinePayload) {
124
+ historyMsg = index_js_1.proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
125
+ }
126
+ else {
127
+ historyMsg = await (0, exports.downloadHistory)(msg, options);
128
+ }
129
+ return (0, exports.processHistoryMessage)(historyMsg, logger);
130
+ };
131
+ exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
132
+ const getHistoryMsg = (message) => {
133
+ const normalizedContent = !!message ? (0, messages_js_1.normalizeMessageContent)(message) : undefined;
134
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
135
+ return anyHistoryMsg;
136
+ };
137
+ exports.getHistoryMsg = getHistoryMsg;
@@ -0,0 +1,37 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { type BinaryNode } from '../WABinary/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type IdentityChangeResult = {
5
+ action: 'no_identity_node';
6
+ } | {
7
+ action: 'invalid_notification';
8
+ } | {
9
+ action: 'skipped_companion_device';
10
+ device: number;
11
+ } | {
12
+ action: 'skipped_self_primary';
13
+ } | {
14
+ action: 'debounced';
15
+ } | {
16
+ action: 'skipped_offline';
17
+ } | {
18
+ action: 'skipped_no_session';
19
+ } | {
20
+ action: 'session_refreshed';
21
+ } | {
22
+ action: 'session_refresh_failed';
23
+ error: unknown;
24
+ };
25
+ export type IdentityChangeContext = {
26
+ meId: string | undefined;
27
+ meLid: string | undefined;
28
+ validateSession: (jid: string) => Promise<{
29
+ exists: boolean;
30
+ reason?: string;
31
+ }>;
32
+ assertSessions: (jids: string[], force?: boolean) => Promise<boolean>;
33
+ debounceCache: NodeCache<boolean>;
34
+ logger: ILogger;
35
+ };
36
+ export declare function handleIdentityChange(node: BinaryNode, ctx: IdentityChangeContext): Promise<IdentityChangeResult>;
37
+ //# sourceMappingURL=identity-change-handler.d.ts.map