@gqb333/based 2.7.71

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 (201) hide show
  1. package/LICENSE +58 -0
  2. package/README.MD +611 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5604 -0
  5. package/WAProto/index.d.ts +63156 -0
  6. package/WAProto/index.js +195638 -0
  7. package/WAProto/p.html +1 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.d.ts +53 -0
  11. package/lib/Defaults/index.js +108 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  13. package/lib/Signal/Group/ciphertext-message.js +15 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  15. package/lib/Signal/Group/group-session-builder.js +64 -0
  16. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  17. package/lib/Signal/Group/group_cipher.js +96 -0
  18. package/lib/Signal/Group/index.d.ts +11 -0
  19. package/lib/Signal/Group/index.js +57 -0
  20. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  21. package/lib/Signal/Group/keyhelper.js +55 -0
  22. package/lib/Signal/Group/queue-job.d.ts +1 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  25. package/lib/Signal/Group/sender-chain-key.js +34 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  33. package/lib/Signal/Group/sender-key-record.js +53 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  35. package/lib/Signal/Group/sender-key-state.js +99 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +3 -0
  39. package/lib/Signal/libsignal.js +174 -0
  40. package/lib/Socket/Client/index.d.ts +2 -0
  41. package/lib/Socket/Client/index.js +18 -0
  42. package/lib/Socket/Client/types.d.ts +16 -0
  43. package/lib/Socket/Client/types.js +13 -0
  44. package/lib/Socket/Client/websocket.d.ts +13 -0
  45. package/lib/Socket/Client/websocket.js +111 -0
  46. package/lib/Socket/business.d.ts +172 -0
  47. package/lib/Socket/business.js +260 -0
  48. package/lib/Socket/chats.d.ts +85 -0
  49. package/lib/Socket/chats.js +1094 -0
  50. package/lib/Socket/groups.d.ts +124 -0
  51. package/lib/Socket/groups.js +423 -0
  52. package/lib/Socket/index.d.ts +172 -0
  53. package/lib/Socket/index.js +32 -0
  54. package/lib/Socket/messages-interactive.js +259 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1474 -0
  57. package/lib/Socket/messages-send.d.ts +151 -0
  58. package/lib/Socket/messages-send.js +1085 -0
  59. package/lib/Socket/newsletter.d.ts +136 -0
  60. package/lib/Socket/newsletter.js +250 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +1241 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +123 -0
  65. package/lib/Store/index.d.ts +2 -0
  66. package/lib/Store/index.js +8 -0
  67. package/lib/Store/make-in-memory-store.d.ts +118 -0
  68. package/lib/Store/make-in-memory-store.js +452 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +81 -0
  71. package/lib/Store/object-repository.d.ts +10 -0
  72. package/lib/Store/object-repository.js +27 -0
  73. package/lib/Types/Auth.d.ts +114 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Call.d.ts +13 -0
  76. package/lib/Types/Call.js +2 -0
  77. package/lib/Types/Chat.d.ts +109 -0
  78. package/lib/Types/Chat.js +4 -0
  79. package/lib/Types/Contact.d.ts +29 -0
  80. package/lib/Types/Contact.js +2 -0
  81. package/lib/Types/Events.d.ts +199 -0
  82. package/lib/Types/Events.js +2 -0
  83. package/lib/Types/GroupMetadata.d.ts +64 -0
  84. package/lib/Types/GroupMetadata.js +2 -0
  85. package/lib/Types/Label.d.ts +35 -0
  86. package/lib/Types/Label.js +27 -0
  87. package/lib/Types/LabelAssociation.d.ts +29 -0
  88. package/lib/Types/LabelAssociation.js +9 -0
  89. package/lib/Types/Message.d.ts +740 -0
  90. package/lib/Types/Message.js +7 -0
  91. package/lib/Types/Newsletter.d.ts +22 -0
  92. package/lib/Types/Newsletter.js +18 -0
  93. package/lib/Types/Product.d.ts +78 -0
  94. package/lib/Types/Product.js +2 -0
  95. package/lib/Types/Signal.d.ts +63 -0
  96. package/lib/Types/Signal.js +2 -0
  97. package/lib/Types/Socket.d.ts +134 -0
  98. package/lib/Types/Socket.js +2 -0
  99. package/lib/Types/State.d.ts +27 -0
  100. package/lib/Types/State.js +2 -0
  101. package/lib/Types/USync.d.ts +25 -0
  102. package/lib/Types/USync.js +2 -0
  103. package/lib/Types/index.d.ts +65 -0
  104. package/lib/Types/index.js +43 -0
  105. package/lib/Utils/auth-utils.d.ts +18 -0
  106. package/lib/Utils/auth-utils.js +209 -0
  107. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  108. package/lib/Utils/baileys-event-stream.js +63 -0
  109. package/lib/Utils/business.d.ts +22 -0
  110. package/lib/Utils/business.js +234 -0
  111. package/lib/Utils/cache-manager.d.ts +16 -0
  112. package/lib/Utils/cache-manager.js +114 -0
  113. package/lib/Utils/chat-utils.d.ts +70 -0
  114. package/lib/Utils/chat-utils.js +734 -0
  115. package/lib/Utils/crypto.d.ts +40 -0
  116. package/lib/Utils/crypto.js +193 -0
  117. package/lib/Utils/decode-wa-message.d.ts +35 -0
  118. package/lib/Utils/decode-wa-message.js +207 -0
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +619 -0
  121. package/lib/Utils/generics.d.ts +89 -0
  122. package/lib/Utils/generics.js +440 -0
  123. package/lib/Utils/history.d.ts +19 -0
  124. package/lib/Utils/history.js +94 -0
  125. package/lib/Utils/index.d.ts +22 -0
  126. package/lib/Utils/index.js +38 -0
  127. package/lib/Utils/jid-validation.d.ts +2 -0
  128. package/lib/Utils/jid-validation.js +186 -0
  129. package/lib/Utils/link-preview.d.ts +21 -0
  130. package/lib/Utils/link-preview.js +152 -0
  131. package/lib/Utils/logger.d.ts +11 -0
  132. package/lib/Utils/logger.js +59 -0
  133. package/lib/Utils/lt-hash.d.ts +12 -0
  134. package/lib/Utils/lt-hash.js +51 -0
  135. package/lib/Utils/make-mutex.d.ts +7 -0
  136. package/lib/Utils/make-mutex.js +43 -0
  137. package/lib/Utils/messages-media.d.ts +120 -0
  138. package/lib/Utils/messages-media.js +848 -0
  139. package/lib/Utils/messages.d.ts +131 -0
  140. package/lib/Utils/messages.js +1793 -0
  141. package/lib/Utils/newsletter-utils.d.ts +2 -0
  142. package/lib/Utils/newsletter-utils.js +48 -0
  143. package/lib/Utils/noise-handler.d.ts +19 -0
  144. package/lib/Utils/noise-handler.js +150 -0
  145. package/lib/Utils/performance-config.d.ts +70 -0
  146. package/lib/Utils/performance-config.js +183 -0
  147. package/lib/Utils/process-message.d.ts +42 -0
  148. package/lib/Utils/process-message.js +498 -0
  149. package/lib/Utils/rate-limiter.js +90 -0
  150. package/lib/Utils/retry.js +66 -0
  151. package/lib/Utils/signal.d.ts +33 -0
  152. package/lib/Utils/signal.js +153 -0
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +129 -0
  155. package/lib/Utils/validate-connection.d.ts +10 -0
  156. package/lib/Utils/validate-connection.js +233 -0
  157. package/lib/WABinary/constants.d.ts +27 -0
  158. package/lib/WABinary/constants.js +1303 -0
  159. package/lib/WABinary/decode.d.ts +6 -0
  160. package/lib/WABinary/decode.js +279 -0
  161. package/lib/WABinary/encode.d.ts +2 -0
  162. package/lib/WABinary/encode.js +264 -0
  163. package/lib/WABinary/generic-utils.d.ts +14 -0
  164. package/lib/WABinary/generic-utils.js +114 -0
  165. package/lib/WABinary/index.d.ts +5 -0
  166. package/lib/WABinary/index.js +21 -0
  167. package/lib/WABinary/jid-utils.d.ts +38 -0
  168. package/lib/WABinary/jid-utils.js +485 -0
  169. package/lib/WABinary/types.d.ts +18 -0
  170. package/lib/WABinary/types.js +2 -0
  171. package/lib/WAM/BinaryInfo.d.ts +8 -0
  172. package/lib/WAM/BinaryInfo.js +13 -0
  173. package/lib/WAM/constants.d.ts +38 -0
  174. package/lib/WAM/constants.js +15350 -0
  175. package/lib/WAM/encode.d.ts +2 -0
  176. package/lib/WAM/encode.js +155 -0
  177. package/lib/WAM/index.d.ts +3 -0
  178. package/lib/WAM/index.js +19 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +102 -0
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +110 -0
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  191. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  192. package/lib/WAUSync/Protocols/index.js +20 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  194. package/lib/WAUSync/USyncQuery.js +147 -0
  195. package/lib/WAUSync/USyncUser.d.ts +12 -0
  196. package/lib/WAUSync/USyncUser.js +26 -0
  197. package/lib/WAUSync/index.d.ts +3 -0
  198. package/lib/WAUSync/index.js +19 -0
  199. package/lib/index.d.ts +17 -0
  200. package/lib/index.js +53 -0
  201. package/package.json +104 -0
@@ -0,0 +1,38 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generics"), exports);
18
+ __exportStar(require("./decode-wa-message"), exports);
19
+ __exportStar(require("./messages"), exports);
20
+ __exportStar(require("./messages-media"), exports);
21
+ __exportStar(require("./validate-connection"), exports);
22
+ __exportStar(require("./crypto"), exports);
23
+ __exportStar(require("./signal"), exports);
24
+ __exportStar(require("./noise-handler"), exports);
25
+ __exportStar(require("./history"), exports);
26
+ __exportStar(require("./chat-utils"), exports);
27
+ __exportStar(require("./lt-hash"), exports);
28
+ __exportStar(require("./auth-utils"), exports);
29
+ __exportStar(require("./baileys-event-stream"), exports);
30
+ __exportStar(require("./use-multi-file-auth-state"), exports);
31
+ __exportStar(require("./link-preview"), exports);
32
+ __exportStar(require("./event-buffer"), exports);
33
+ __exportStar(require("./process-message"), exports);
34
+ __exportStar(require("./performance-config"), exports);
35
+ __exportStar(require("./jid-validation"), exports);
36
+ __exportStar(require("./newsletter-utils"), exports);
37
+ __exportStar(require("./logger"), exports);
38
+ __exportStar(require("./cache-manager"), exports);
@@ -0,0 +1,2 @@
1
+ export declare const isValidJid: (jid: string) => boolean;
2
+ export declare const normalizeJid: (jid: string) => string;
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateJid = exports.toJid = exports.getSenderLid = exports.normalizeJid = exports.isValidJid = void 0;
4
+
5
+ const WABinary_1 = require("../WABinary");
6
+ const performance_config_1 = require("./performance-config");
7
+
8
+ /**
9
+ * Check if a JID is valid
10
+ * @param {string} jid - The JID to validate
11
+ * @returns {boolean} True if valid, false otherwise
12
+ */
13
+ const isValidJid = (jid) => {
14
+ if (!jid || typeof jid !== 'string') {
15
+ return false;
16
+ }
17
+
18
+ // Basic format validation
19
+ if (!jid.includes('@')) {
20
+ return false;
21
+ }
22
+
23
+ // Check for valid server domains
24
+ const validDomains = ['s.whatsapp.net', 'c.us', 'g.us', 'broadcast', 'lid', 'newsletter'];
25
+ const domain = jid.split('@')[1];
26
+ return validDomains.some(validDomain => domain === validDomain || domain.endsWith(validDomain));
27
+ };
28
+
29
+ exports.isValidJid = isValidJid;
30
+
31
+ /**
32
+ * Normalize JID format
33
+ * @param {string} jid - The JID to normalize
34
+ * @returns {string} Normalized JID
35
+ */
36
+ const normalizeJid = (jid) => {
37
+ if (!jid) return jid;
38
+
39
+ // Convert LID to standard JID format
40
+ if ((0, WABinary_1.isLid)(jid)) {
41
+ const converted = (0, WABinary_1.lidToJid)(jid);
42
+ return converted || jid;
43
+ }
44
+
45
+ // Ensure consistent format
46
+ return jid;
47
+ };
48
+
49
+ exports.normalizeJid = normalizeJid;
50
+
51
+ /**
52
+ * Extract sender LID from message
53
+ * @param {Object} msg - The message object
54
+ * @returns {Object} Object containing jid, lid, and validation status
55
+ */
56
+ const getSenderLid = (msg) => {
57
+ try {
58
+ if (!msg || typeof msg !== 'object') {
59
+ return {
60
+ jid: '',
61
+ lid: '',
62
+ isValid: false,
63
+ user: '',
64
+ timestamp: Date.now(),
65
+ error: 'Invalid message object'
66
+ };
67
+ }
68
+
69
+ // Extract from different possible fields
70
+ const jid = msg.key?.remoteJid || msg.remoteJid || msg.from;
71
+ const lid = msg.key?.participant || msg.participant || msg.lid;
72
+
73
+ if (!jid || typeof jid !== 'string') {
74
+ return {
75
+ jid: '',
76
+ lid: typeof lid === 'string' ? lid : '',
77
+ isValid: false,
78
+ user: '',
79
+ timestamp: Date.now(),
80
+ error: 'Missing or invalid JID'
81
+ };
82
+ }
83
+
84
+ // Validate and normalize
85
+ const normalizedJid = normalizeJid(jid);
86
+ const isValid = isValidJid(normalizedJid);
87
+
88
+ const decoded = (0, WABinary_1.jidDecode)(normalizedJid);
89
+ const user = decoded?.user || normalizedJid.split('@')[0] || '';
90
+
91
+ return {
92
+ jid: normalizedJid,
93
+ lid: typeof lid === 'string' ? lid : '',
94
+ isValid: isValid,
95
+ user,
96
+ timestamp: Date.now(),
97
+ ...(isValid ? {} : { error: 'Invalid JID format' })
98
+ };
99
+ } catch (error) {
100
+ performance_config_1.Logger.error('Error in getSenderLid:', error);
101
+ return {
102
+ jid: '',
103
+ lid: '',
104
+ isValid: false,
105
+ user: '',
106
+ timestamp: Date.now(),
107
+ error: 'Error extracting sender information'
108
+ };
109
+ }
110
+ };
111
+
112
+ exports.getSenderLid = getSenderLid;
113
+
114
+ /**
115
+ * Convert LID to JID
116
+ * @param {string} lid - The LID to convert
117
+ * @returns {string} Converted JID
118
+ */
119
+ const toJid = (lid) => {
120
+ if (!lid) return lid;
121
+
122
+ try {
123
+ // Convert LID to JID format
124
+ if ((0, WABinary_1.isLid)(lid)) {
125
+ const converted = (0, WABinary_1.lidToJid)(lid);
126
+ return converted || lid;
127
+ }
128
+
129
+ // If already in JID format, return as-is
130
+ return lid;
131
+ } catch (error) {
132
+ performance_config_1.Logger.error('Error in toJid:', error);
133
+ return lid;
134
+ }
135
+ };
136
+
137
+ exports.toJid = toJid;
138
+
139
+ /**
140
+ * Validate JID with detailed error information
141
+ * @param {string} jid - The JID to validate
142
+ * @returns {Object} Validation result with isValid and error message
143
+ */
144
+ const validateJid = (jid) => {
145
+ try {
146
+ if (!jid) {
147
+ return { isValid: false, error: 'JID is null or undefined' };
148
+ }
149
+
150
+ if (typeof jid !== 'string') {
151
+ return { isValid: false, error: 'JID is not a string' };
152
+ }
153
+
154
+ if (!jid.includes('@')) {
155
+ return { isValid: false, error: 'JID must contain @ character' };
156
+ }
157
+
158
+ const parts = jid.split('@');
159
+ if (parts.length !== 2) {
160
+ return { isValid: false, error: 'JID must have exactly one @ character' };
161
+ }
162
+
163
+ const [user, domain] = parts;
164
+ if (!user || !domain) {
165
+ return { isValid: false, error: 'JID must have both user and domain parts' };
166
+ }
167
+
168
+ // Check for valid domains
169
+ const validDomains = ['s.whatsapp.net', 'c.us', 'g.us', 'broadcast', 'lid', 'newsletter'];
170
+ const isValidDomain = validDomains.some(validDomain =>
171
+ domain === validDomain || domain.endsWith(validDomain)
172
+ );
173
+
174
+ if (!isValidDomain) {
175
+ return { isValid: false, error: `Invalid domain: ${domain}` };
176
+ }
177
+
178
+ return { isValid: true };
179
+
180
+ } catch (error) {
181
+ performance_config_1.Logger.error('Error in validateJid:', error);
182
+ return { isValid: false, error: 'Validation error: ' + error.message };
183
+ }
184
+ };
185
+
186
+ exports.validateJid = validateJid;
@@ -0,0 +1,21 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { ILogger } from './logger';
3
+ import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
4
+ export type URLGenerationOptions = {
5
+ thumbnailWidth: number;
6
+ fetchOpts: {
7
+ /** Timeout in ms */
8
+ timeout: number;
9
+ proxyUrl?: string;
10
+ headers?: AxiosRequestConfig<{}>['headers'];
11
+ };
12
+ uploadImage?: WAMediaUploadFunction;
13
+ logger?: ILogger;
14
+ };
15
+ /**
16
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
17
+ * Return undefined if the fetch failed or no URL was found
18
+ * @param text first matched URL in text
19
+ * @returns the URL info required to generate link preview
20
+ */
21
+ export declare const getUrlInfo: (text: string, opts?: URLGenerationOptions) => Promise<WAUrlInfo | undefined>;
@@ -0,0 +1,152 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getUrlInfo = void 0;
37
+ const messages_1 = require("./messages");
38
+ const messages_media_1 = require("./messages-media");
39
+ const THUMBNAIL_WIDTH_PX = 1200;
40
+ /** Fetches an image and generates a thumbnail for it */
41
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts, logger }) => {
42
+ try {
43
+ const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
44
+ const result = await (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
45
+ logger?.debug({ url, thumbnailWidth }, 'Successfully generated compressed JPEG thumbnail');
46
+ return result;
47
+ } catch (error) {
48
+ logger?.warn({ url, thumbnailWidth, error: error.message }, 'Failed to generate compressed JPEG thumbnail, attempting fallback');
49
+ // Fallback to lower quality if high quality fails
50
+ try {
51
+ const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
52
+ const result = await (0, messages_media_1.extractImageThumb)(stream, Math.min(thumbnailWidth, 512));
53
+ logger?.debug({ url, fallbackWidth: Math.min(thumbnailWidth, 512) }, 'Successfully generated fallback thumbnail');
54
+ return result;
55
+ } catch (fallbackError) {
56
+ logger?.error({ url, error: fallbackError.message }, 'Failed to generate fallback thumbnail');
57
+ throw fallbackError;
58
+ }
59
+ }
60
+ };
61
+ /**
62
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
63
+ * Return undefined if the fetch failed or no URL was found
64
+ * @param text first matched URL in text
65
+ * @returns the URL info required to generate link preview
66
+ */
67
+ const getUrlInfo = async (text, opts = {
68
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
69
+ fetchOpts: { timeout: 3000 }
70
+ }) => {
71
+ var _a;
72
+ try {
73
+ const { unfurl } = await Promise.resolve().then(() => __importStar(require('unfurl.js')));
74
+ let previewLink = text;
75
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
76
+ previewLink = 'https://' + previewLink;
77
+ }
78
+ const requestHeaders = (() => {
79
+ const headers = opts.fetchOpts?.headers;
80
+ if (!headers || typeof headers !== 'object') {
81
+ return undefined;
82
+ }
83
+ const out = {};
84
+ for (const [key, value] of Object.entries(headers)) {
85
+ if (typeof value === 'undefined' || value === null) {
86
+ continue;
87
+ }
88
+ if (Array.isArray(value)) {
89
+ out[key] = value.map(v => v.toString()).join(', ');
90
+ }
91
+ else {
92
+ out[key] = value.toString();
93
+ }
94
+ }
95
+ return out;
96
+ })();
97
+ const info = await unfurl(previewLink, {
98
+ timeout: opts.fetchOpts?.timeout,
99
+ headers: requestHeaders,
100
+ follow: 5
101
+ });
102
+ const title = info?.title || info?.open_graph?.title || info?.twitter_card?.title;
103
+ if (title) {
104
+ const images = [];
105
+ if (info?.open_graph?.images?.length) {
106
+ images.push(...info.open_graph.images.map(img => img === null || img === void 0 ? void 0 : img.url).filter(Boolean));
107
+ }
108
+ if (info?.twitter_card?.images?.length) {
109
+ images.push(...info.twitter_card.images.map(img => img === null || img === void 0 ? void 0 : img.url).filter(Boolean));
110
+ }
111
+ const [image] = images;
112
+ const description = info?.description || info?.open_graph?.description || info?.twitter_card?.description;
113
+ const canonicalUrl = info?.canonical_url || info?.open_graph?.url || previewLink;
114
+ opts.logger?.debug({ url: previewLink, title, imageCount: images.length }, 'Fetched link preview info');
115
+ const urlInfo = {
116
+ 'canonical-url': canonicalUrl,
117
+ 'matched-text': text,
118
+ title,
119
+ description,
120
+ originalThumbnailUrl: image
121
+ };
122
+ if (opts.uploadImage && image) {
123
+ const { imageMessage } = await (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
124
+ upload: opts.uploadImage,
125
+ mediaTypeOverride: 'thumbnail-link',
126
+ options: opts.fetchOpts
127
+ });
128
+ urlInfo.jpegThumbnail = (imageMessage === null || imageMessage === void 0 ? void 0 : imageMessage.jpegThumbnail)
129
+ ? Buffer.from(imageMessage.jpegThumbnail)
130
+ : undefined;
131
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
132
+ }
133
+ else {
134
+ try {
135
+ urlInfo.jpegThumbnail = image
136
+ ? (await getCompressedJpegThumbnail(image, { ...opts, logger: opts.logger })).buffer
137
+ : undefined;
138
+ }
139
+ catch (error) {
140
+ (_a = opts.logger) === null || _a === void 0 ? void 0 : _a.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
141
+ }
142
+ }
143
+ return urlInfo;
144
+ }
145
+ }
146
+ catch (error) {
147
+ if (!error.message.includes('receive a valid') && !error.message.includes('Invalid URL')) {
148
+ throw error;
149
+ }
150
+ }
151
+ };
152
+ exports.getUrlInfo = getUrlInfo;
@@ -0,0 +1,11 @@
1
+ export interface ILogger {
2
+ level: string;
3
+ child(obj: Record<string, unknown>): ILogger;
4
+ trace(obj: unknown, msg?: string): any;
5
+ debug(obj: unknown, msg?: string): any;
6
+ info(obj: unknown, msg?: string): any;
7
+ warn(obj: unknown, msg?: string): any;
8
+ error(obj: unknown, msg?: string): any;
9
+ }
10
+ declare const _default: import("pino").Logger<never, boolean>;
11
+ export default _default;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const pino_1 = __importDefault(require("pino"));
7
+ const { getPerformanceConfig } = require('./performance-config');
8
+ const defaultLogger = (0, pino_1.default)({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
9
+ class EnhancedLogger {
10
+ constructor() {
11
+ this.config = getPerformanceConfig();
12
+ }
13
+
14
+ static error(...args) {
15
+ if (defaultLogger.isLevelEnabled('error')) {
16
+ defaultLogger.error(...args);
17
+ }
18
+ // Additional error tracking if enabled
19
+ if (this.config?.debug?.enableErrorTracking) {
20
+ // Could send to external monitoring service
21
+ console.error('[ERROR TRACK]', ...args);
22
+ }
23
+ }
24
+
25
+ static warn(...args) {
26
+ if (defaultLogger.isLevelEnabled('warn')) {
27
+ defaultLogger.warn(...args);
28
+ }
29
+ }
30
+
31
+ static info(...args) {
32
+ if (this.config?.debug?.enableInfoLogging && defaultLogger.isLevelEnabled('info')) {
33
+ defaultLogger.info(...args);
34
+ }
35
+ }
36
+
37
+ static debug(...args) {
38
+ if (this.config?.debug?.enableDebugLogging && defaultLogger.isLevelEnabled('debug')) {
39
+ defaultLogger.debug(...args);
40
+ }
41
+ }
42
+ static createBaileysLogger(level = 'info', prefix = 'Based') {
43
+ return {
44
+ level,
45
+ debug: (...args) => this.debug(`[${prefix}]`, ...args),
46
+ info: (...args) => this.info(`[${prefix}]`, ...args),
47
+ warn: (...args) => this.warn(`[${prefix}]`, ...args),
48
+ error: (...args) => this.error(`[${prefix}]`, ...args),
49
+ trace: (...args) => this.debug(`[${prefix} TRACE]`, ...args),
50
+ child: (bindings) => ({
51
+ ...this.createBaileysLogger(level, prefix),
52
+ bindings
53
+ })
54
+ };
55
+ }
56
+ }
57
+
58
+ exports.EnhancedLogger = EnhancedLogger;
59
+ exports.default = defaultLogger;
@@ -0,0 +1,12 @@
1
+ declare class d {
2
+ salt: string;
3
+ constructor(e: string);
4
+ add(e: any, t: any): any;
5
+ subtract(e: any, t: any): any;
6
+ subtractThenAdd(e: any, t: any, r: any): any;
7
+ _addSingle(e: any, t: any): Promise<ArrayBuffer>;
8
+ _subtractSingle(e: any, t: any): Promise<ArrayBuffer>;
9
+ performPointwiseWithOverflow(e: any, t: any, r: any): ArrayBuffer;
10
+ }
11
+ export declare const LT_HASH_ANTI_TAMPERING: d;
12
+ export {};
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LT_HASH_ANTI_TAMPERING = void 0;
4
+ const crypto_1 = require("./crypto");
5
+ /**
6
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
7
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
8
+ * if the same series of mutations was made sequentially.
9
+ */
10
+ const o = 128;
11
+ class d {
12
+ constructor(e) {
13
+ this.salt = e;
14
+ }
15
+ add(e, t) {
16
+ var r = this;
17
+ for (const item of t) {
18
+ e = r._addSingle(e, item);
19
+ }
20
+ return e;
21
+ }
22
+ subtract(e, t) {
23
+ var r = this;
24
+ for (const item of t) {
25
+ e = r._subtractSingle(e, item);
26
+ }
27
+ return e;
28
+ }
29
+ subtractThenAdd(e, t, r) {
30
+ var n = this;
31
+ return n.add(n.subtract(e, r), t);
32
+ }
33
+ async _addSingle(e, t) {
34
+ var r = this;
35
+ const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
36
+ return r.performPointwiseWithOverflow(await e, n, ((e, t) => e + t));
37
+ }
38
+ async _subtractSingle(e, t) {
39
+ var r = this;
40
+ const n = new Uint8Array(await (0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
41
+ return r.performPointwiseWithOverflow(await e, n, ((e, t) => e - t));
42
+ }
43
+ performPointwiseWithOverflow(e, t, r) {
44
+ const n = new DataView(e), i = new DataView(t), a = new ArrayBuffer(n.byteLength), s = new DataView(a);
45
+ for (let e = 0; e < n.byteLength; e += 2) {
46
+ s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0);
47
+ }
48
+ return a;
49
+ }
50
+ }
51
+ exports.LT_HASH_ANTI_TAMPERING = new d('WhatsApp Patch Integrity');
@@ -0,0 +1,7 @@
1
+ export declare const makeMutex: () => {
2
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
3
+ };
4
+ export type Mutex = ReturnType<typeof makeMutex>;
5
+ export declare const makeKeyedMutex: () => {
6
+ mutex<T>(key: string, task: () => Promise<T> | T): Promise<T>;
7
+ };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeKeyedMutex = exports.makeMutex = void 0;
4
+ const makeMutex = () => {
5
+ let task = Promise.resolve();
6
+ let taskTimeout;
7
+ return {
8
+ mutex(code) {
9
+ task = (async () => {
10
+ // wait for the previous task to complete
11
+ // if there is an error, we swallow so as to not block the queue
12
+ try {
13
+ await task;
14
+ }
15
+ catch (_a) { }
16
+ try {
17
+ // execute the current task
18
+ const result = await code();
19
+ return result;
20
+ }
21
+ finally {
22
+ clearTimeout(taskTimeout);
23
+ }
24
+ })();
25
+ // we replace the existing task, appending the new piece of execution to it
26
+ // so the next task will have to wait for this one to finish
27
+ return task;
28
+ },
29
+ };
30
+ };
31
+ exports.makeMutex = makeMutex;
32
+ const makeKeyedMutex = () => {
33
+ const map = {};
34
+ return {
35
+ mutex(key, task) {
36
+ if (!map[key]) {
37
+ map[key] = (0, exports.makeMutex)();
38
+ }
39
+ return map[key].mutex(task);
40
+ }
41
+ };
42
+ };
43
+ exports.makeKeyedMutex = makeKeyedMutex;