@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { unfurl: unfurl } = require("unfurl.js");
4
+ const { prepareWAMessageMedia: prepareWAMessageMedia } = require("./messages");
5
+ const {
6
+ getHttpStream: getHttpStream,
7
+ extractImageThumb: extractImageThumb,
8
+ } = require("./messages-media");
9
+ const THUMBNAIL_WIDTH_PX = 192;
10
+ const getCompressedJpegThumbnail = async (
11
+ url,
12
+ { thumbnailWidth: thumbnailWidth, fetchOpts: fetchOpts }
13
+ ) => {
14
+ const stream = await getHttpStream(url, fetchOpts);
15
+ const result = await extractImageThumb(stream, thumbnailWidth);
16
+ return result;
17
+ };
18
+ const getUrlInfo = async (
19
+ text,
20
+ opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3e3 } }
21
+ ) => {
22
+ try {
23
+ let previewLink = text;
24
+ if (!text.startsWith("https://") && !text.startsWith("http://")) {
25
+ previewLink = "https://" + previewLink;
26
+ }
27
+ const { open_graph: info } = await unfurl(previewLink, {
28
+ ...opts.fetchOpts,
29
+ oembed: false,
30
+ compress: true,
31
+ size: 0,
32
+ follow: 50,
33
+ });
34
+ if (info && "title" in info && info.title) {
35
+ const image = info.images?.[0]?.url;
36
+ const urlInfo = {
37
+ "canonical-url": info.url,
38
+ "matched-text": text,
39
+ title: info.title,
40
+ description: info.description,
41
+ originalThumbnailUrl: image,
42
+ };
43
+ if (opts.uploadImage) {
44
+ const { imageMessage: imageMessage } = await prepareWAMessageMedia(
45
+ { image: { url: image } },
46
+ {
47
+ upload: opts.uploadImage,
48
+ mediaTypeOverride: "thumbnail-link",
49
+ options: opts.fetchOpts,
50
+ }
51
+ );
52
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
53
+ ? Buffer.from(imageMessage.jpegThumbnail)
54
+ : undefined;
55
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
56
+ } else {
57
+ try {
58
+ urlInfo.jpegThumbnail = image
59
+ ? (await getCompressedJpegThumbnail(image, opts)).buffer
60
+ : undefined;
61
+ } catch (error) {
62
+ opts.logger?.debug(
63
+ { err: error.stack, url: previewLink },
64
+ "error in generating thumbnail"
65
+ );
66
+ }
67
+ }
68
+ return urlInfo;
69
+ }
70
+ } catch (error) {
71
+ if (!error.message.includes("receive a valid")) {
72
+ throw error;
73
+ }
74
+ }
75
+ };
76
+ module.exports = { getUrlInfo: getUrlInfo };
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const pino = require("pino");
4
+ exports.default = pino({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { hkdf: hkdf } = require("./crypto");
4
+ const o = 128;
5
+ class LTHash {
6
+ constructor(e) {
7
+ this.salt = e;
8
+ }
9
+ async add(e, t) {
10
+ for (const item of t) {
11
+ e = await this._addSingle(e, item);
12
+ }
13
+ return e;
14
+ }
15
+ async subtract(e, t) {
16
+ for (const item of t) {
17
+ e = await this._subtractSingle(e, item);
18
+ }
19
+ return e;
20
+ }
21
+ async subtractThenAdd(e, addList, subtractList) {
22
+ const subtracted = await this.subtract(e, subtractList);
23
+ return this.add(subtracted, addList);
24
+ }
25
+ async _addSingle(e, t) {
26
+ const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
27
+ return this.performPointwiseWithOverflow(e, derived, (a, b) => a + b);
28
+ }
29
+ async _subtractSingle(e, t) {
30
+ const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
31
+ return this.performPointwiseWithOverflow(e, derived, (a, b) => a - b);
32
+ }
33
+ performPointwiseWithOverflow(e, t, op) {
34
+ const n = new DataView(e);
35
+ const i = new DataView(t);
36
+ const out = new ArrayBuffer(n.byteLength);
37
+ const s = new DataView(out);
38
+ for (let offset = 0; offset < n.byteLength; offset += 2) {
39
+ s.setUint16(offset, op(n.getUint16(offset, true), i.getUint16(offset, true)), true);
40
+ }
41
+ return out;
42
+ }
43
+ }
44
+ const LT_HASH_ANTI_TAMPERING = new LTHash("WhatsApp Patch Integrity");
45
+ module.exports = { LT_HASH_ANTI_TAMPERING: LT_HASH_ANTI_TAMPERING };
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { Mutex: AsyncMutex } = require("async-mutex");
4
+ const makeMutex = () => {
5
+ const mutex = new AsyncMutex();
6
+ return {
7
+ mutex(code) {
8
+ return mutex.runExclusive(code);
9
+ },
10
+ };
11
+ };
12
+ const makeKeyedMutex = () => {
13
+ const map = new Map();
14
+ return {
15
+ async mutex(key, task) {
16
+ let entry = map.get(key);
17
+ if (!entry) {
18
+ entry = { mutex: new AsyncMutex(), refCount: 0 };
19
+ map.set(key, entry);
20
+ }
21
+ entry.refCount++;
22
+ try {
23
+ return await entry.mutex.runExclusive(task);
24
+ } finally {
25
+ entry.refCount--;
26
+ if (entry.refCount === 0 && map.get(key) === entry) {
27
+ map.delete(key);
28
+ }
29
+ }
30
+ },
31
+ };
32
+ };
33
+ module.exports = { makeMutex: makeMutex, makeKeyedMutex: makeKeyedMutex };
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ // Ported & adapted from PouCode fork for AsepXyz Baileys
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.generateRichMessageContent = exports.generateUnifiedResponseContent = exports.captureUnifiedResponse =
5
+ exports.generateCodeBlockContent = exports.generateListContent = exports.generateTableContent =
6
+ exports.buildBotForwardedMessage = exports.buildRichContextInfo = exports.tokenizeCode =
7
+ exports.RichSubMessageType = exports.CodeHighlightType = exports.LANGUAGE_KEYWORDS =
8
+ exports.PYTHON_KEYWORDS = exports.JS_KEYWORDS = void 0;
9
+ const { generateMessageIDV2 } = require("./generics");
10
+
11
+ const JS_KEYWORDS = new Set([
12
+ 'import', 'export', 'from', 'default', 'as', 'const', 'let', 'var',
13
+ 'function', 'class', 'extends', 'new', 'return', 'if', 'else', 'for',
14
+ 'while', 'do', 'switch', 'case', 'break', 'continue', 'try', 'catch',
15
+ 'finally', 'throw', 'async', 'await', 'yield', 'typeof', 'instanceof',
16
+ 'in', 'of', 'delete', 'void', 'true', 'false', 'null', 'undefined',
17
+ 'NaN', 'Infinity', 'this', 'super', 'static', 'get', 'set', 'debugger', 'with'
18
+ ]);
19
+ exports.JS_KEYWORDS = JS_KEYWORDS;
20
+
21
+ const PYTHON_KEYWORDS = new Set([
22
+ 'import', 'from', 'as', 'def', 'class', 'return', 'if', 'elif', 'else',
23
+ 'for', 'while', 'break', 'continue', 'try', 'except', 'finally', 'raise',
24
+ 'with', 'yield', 'lambda', 'pass', 'del', 'global', 'nonlocal', 'assert',
25
+ 'True', 'False', 'None', 'and', 'or', 'not', 'in', 'is', 'async', 'await',
26
+ 'self', 'print'
27
+ ]);
28
+ exports.PYTHON_KEYWORDS = PYTHON_KEYWORDS;
29
+
30
+ const LANGUAGE_KEYWORDS = {
31
+ javascript: JS_KEYWORDS,
32
+ typescript: JS_KEYWORDS,
33
+ js: JS_KEYWORDS,
34
+ ts: JS_KEYWORDS,
35
+ python: PYTHON_KEYWORDS,
36
+ py: PYTHON_KEYWORDS
37
+ };
38
+ exports.LANGUAGE_KEYWORDS = LANGUAGE_KEYWORDS;
39
+
40
+ var CodeHighlightType;
41
+ (function (CodeHighlightType) {
42
+ CodeHighlightType[(CodeHighlightType['DEFAULT'] = 0)] = 'DEFAULT';
43
+ CodeHighlightType[(CodeHighlightType['KEYWORD'] = 1)] = 'KEYWORD';
44
+ CodeHighlightType[(CodeHighlightType['METHOD'] = 2)] = 'METHOD';
45
+ CodeHighlightType[(CodeHighlightType['STRING'] = 3)] = 'STRING';
46
+ CodeHighlightType[(CodeHighlightType['NUMBER'] = 4)] = 'NUMBER';
47
+ CodeHighlightType[(CodeHighlightType['COMMENT'] = 5)] = 'COMMENT';
48
+ })(CodeHighlightType = exports.CodeHighlightType || (exports.CodeHighlightType = {}));
49
+
50
+ var RichSubMessageType;
51
+ (function (RichSubMessageType) {
52
+ RichSubMessageType[(RichSubMessageType['UNKNOWN'] = 0)] = 'UNKNOWN';
53
+ RichSubMessageType[(RichSubMessageType['GRID_IMAGE'] = 1)] = 'GRID_IMAGE';
54
+ RichSubMessageType[(RichSubMessageType['TEXT'] = 2)] = 'TEXT';
55
+ RichSubMessageType[(RichSubMessageType['INLINE_IMAGE'] = 3)] = 'INLINE_IMAGE';
56
+ RichSubMessageType[(RichSubMessageType['TABLE'] = 4)] = 'TABLE';
57
+ RichSubMessageType[(RichSubMessageType['CODE'] = 5)] = 'CODE';
58
+ RichSubMessageType[(RichSubMessageType['DYNAMIC'] = 6)] = 'DYNAMIC';
59
+ RichSubMessageType[(RichSubMessageType['MAP'] = 7)] = 'MAP';
60
+ RichSubMessageType[(RichSubMessageType['LATEX'] = 8)] = 'LATEX';
61
+ RichSubMessageType[(RichSubMessageType['CONTENT_ITEMS'] = 9)] = 'CONTENT_ITEMS';
62
+ })(RichSubMessageType = exports.RichSubMessageType || (exports.RichSubMessageType = {}));
63
+
64
+ const tokenizeCode = (codeStr, language = 'javascript') => {
65
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS;
66
+ const blocks = [];
67
+ const lines = codeStr.split('\n');
68
+ for (let li = 0; li < lines.length; li++) {
69
+ const line = lines[li];
70
+ const isLast = li === lines.length - 1;
71
+ const nl = isLast ? '' : '\n';
72
+ if (!line.trim()) {
73
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl });
74
+ continue;
75
+ }
76
+ if (line.trim().startsWith('//') || line.trim().startsWith('#')) {
77
+ blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: line + nl });
78
+ continue;
79
+ }
80
+ const regex = /(\/\/.*$|#.*$)|(["'`](?:[^"'`\\]|\\.)*["'`])|(\b\d+(?:\.\d+)?\b)|(\b[a-zA-Z_$][\w$]*\b)|([^\s\w$"'`]+)|(\s+)/g;
81
+ let match;
82
+ const tokens = [];
83
+ while ((match = regex.exec(line)) !== null) {
84
+ const val = match[0];
85
+ if (match[1]) {
86
+ tokens.push({ highlightType: CodeHighlightType.COMMENT, codeContent: val });
87
+ } else if (match[2]) {
88
+ tokens.push({ highlightType: CodeHighlightType.STRING, codeContent: val });
89
+ } else if (match[3]) {
90
+ tokens.push({ highlightType: CodeHighlightType.NUMBER, codeContent: val });
91
+ } else if (match[4]) {
92
+ if (keywords.has(val)) {
93
+ tokens.push({ highlightType: CodeHighlightType.KEYWORD, codeContent: val });
94
+ } else {
95
+ const after = line.slice(regex.lastIndex).trimStart();
96
+ if (after.startsWith('(')) {
97
+ tokens.push({ highlightType: CodeHighlightType.METHOD, codeContent: val });
98
+ } else {
99
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val });
100
+ }
101
+ }
102
+ } else {
103
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val });
104
+ }
105
+ }
106
+ if (tokens.length === 0) {
107
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl });
108
+ continue;
109
+ }
110
+ const merged = [];
111
+ for (const t of tokens) {
112
+ const prev = merged.length > 0 ? merged[merged.length - 1] : undefined;
113
+ if (prev && prev.highlightType === t.highlightType) {
114
+ prev.codeContent += t.codeContent;
115
+ } else {
116
+ merged.push({ ...t });
117
+ }
118
+ }
119
+ if (merged.length > 0) {
120
+ merged[merged.length - 1].codeContent += nl;
121
+ }
122
+ blocks.push(...merged);
123
+ }
124
+ return blocks;
125
+ };
126
+ exports.tokenizeCode = tokenizeCode;
127
+
128
+ const buildRichContextInfo = (quoted, options) => {
129
+ const ctxInfo = {
130
+ forwardingScore: 1,
131
+ isForwarded: true,
132
+ forwardedAiBotMessageInfo: { botJid: options?.botJid ? options.botJid : '867051314767696@bot' },
133
+ forwardOrigin: 4,
134
+ ...(options?.mentions ? { mentionedJid: options.mentions } : {})
135
+ };
136
+ if (quoted?.key) {
137
+ ctxInfo.stanzaId = quoted.key.id;
138
+ ctxInfo.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid;
139
+ ctxInfo.quotedMessage = quoted.message;
140
+ }
141
+ return ctxInfo;
142
+ };
143
+ exports.buildRichContextInfo = buildRichContextInfo;
144
+
145
+ const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
146
+ const richResponse = { messageType: 1, submessages, contextInfo };
147
+ if (unifiedResponse) {
148
+ richResponse.unifiedResponse = unifiedResponse;
149
+ }
150
+ return {
151
+ botForwardedMessage: {
152
+ message: { richResponseMessage: richResponse }
153
+ }
154
+ };
155
+ };
156
+ exports.buildBotForwardedMessage = buildBotForwardedMessage;
157
+
158
+ const generateTableContent = (title, headers, rows, quoted, options = {}) => {
159
+ const { footer, headerText } = options;
160
+ const tableRows = [{ items: headers, isHeading: true }, ...rows.map(row => ({ items: row.map(String) }))];
161
+ const submessages = [];
162
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText });
163
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } });
164
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
165
+ const ctxInfo = buildRichContextInfo(quoted);
166
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
167
+ };
168
+ exports.generateTableContent = generateTableContent;
169
+
170
+ const generateListContent = (title, items, quoted, options = {}) => {
171
+ const { footer, headerText } = options;
172
+ const tableRows = items.map(item => ({
173
+ items: Array.isArray(item) ? item.map(String) : [String(item)]
174
+ }));
175
+ const submessages = [];
176
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText });
177
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } });
178
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
179
+ const ctxInfo = buildRichContextInfo(quoted);
180
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
181
+ };
182
+ exports.generateListContent = generateListContent;
183
+
184
+ const generateCodeBlockContent = (code, quoted, options = {}) => {
185
+ const { title, footer, language = 'javascript' } = options;
186
+ const submessages = [];
187
+ if (title) submessages.push({ messageType: 2, messageText: title });
188
+ submessages.push({
189
+ messageType: 5,
190
+ codeMetadata: { codeLanguage: language, codeBlocks: tokenizeCode(code, language) }
191
+ });
192
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
193
+ const ctxInfo = buildRichContextInfo(quoted);
194
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
195
+ };
196
+ exports.generateCodeBlockContent = generateCodeBlockContent;
197
+
198
+ const generateLatexContent = (quoted, options) => {
199
+ const { text, expressions, headerText, footer } = options;
200
+ const submessages = [];
201
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText });
202
+ const latexExpressions = expressions.map(expr => {
203
+ const entry = {
204
+ latexExpression: expr.latexExpression,
205
+ url: expr.url,
206
+ width: expr.width,
207
+ height: expr.height
208
+ };
209
+ if (expr.fontHeight !== undefined) entry.fontHeight = expr.fontHeight;
210
+ if (expr.imageTopPadding !== undefined) entry.imageTopPadding = expr.imageTopPadding;
211
+ if (expr.imageLeadingPadding !== undefined) entry.imageLeadingPadding = expr.imageLeadingPadding;
212
+ if (expr.imageBottomPadding !== undefined) entry.imageBottomPadding = expr.imageBottomPadding;
213
+ if (expr.imageTrailingPadding !== undefined) entry.imageTrailingPadding = expr.imageTrailingPadding;
214
+ return entry;
215
+ });
216
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } });
217
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
218
+ const ctxInfo = buildRichContextInfo(quoted);
219
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
220
+ };
221
+ exports.generateLatexContent = generateLatexContent;
222
+
223
+ const generateLatexImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
224
+ const { text, expressions, headerText, footer } = options;
225
+ const submessages = [];
226
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText });
227
+ const latexExpressions = await Promise.all(
228
+ expressions.map(async expr => {
229
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression);
230
+ const uploadResult = await uploadFn(buffer, 'image');
231
+ const imageUrl = uploadResult.url || uploadResult.directPath;
232
+ return { latexExpression: expr.latexExpression, url: imageUrl, width, height };
233
+ })
234
+ );
235
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } });
236
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
237
+ const ctxInfo = buildRichContextInfo(quoted);
238
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
239
+ };
240
+ exports.generateLatexImageContent = generateLatexImageContent;
241
+
242
+ const generateLatexInlineImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
243
+ const { text, expressions, headerText, footer } = options;
244
+ const submessages = [];
245
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText });
246
+ if (text) submessages.push({ messageType: 2, messageText: text });
247
+ for (const expr of expressions) {
248
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression);
249
+ const uploadResult = await uploadFn(buffer, 'image');
250
+ const imageUrl = uploadResult.url || uploadResult.directPath;
251
+ submessages.push({
252
+ messageType: 3,
253
+ imageMetadata: {
254
+ imageUrl: { imagePreviewUrl: imageUrl, imageHighResUrl: imageUrl },
255
+ imageText: expr.latexExpression,
256
+ alignment: 2
257
+ }
258
+ });
259
+ }
260
+ if (footer) submessages.push({ messageType: 2, messageText: footer });
261
+ const ctxInfo = buildRichContextInfo(quoted);
262
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
263
+ };
264
+ exports.generateLatexInlineImageContent = generateLatexInlineImageContent;
265
+
266
+ const captureUnifiedResponse = msg => {
267
+ const botFwd = msg?.botForwardedMessage?.message;
268
+ if (!botFwd) return null;
269
+ const rich = botFwd.richResponseMessage;
270
+ if (!rich?.unifiedResponse?.data) return null;
271
+ return {
272
+ unifiedResponse: { data: rich.unifiedResponse.data },
273
+ submessages: rich.submessages || [],
274
+ contextInfo: rich.contextInfo || {}
275
+ };
276
+ };
277
+ exports.captureUnifiedResponse = captureUnifiedResponse;
278
+
279
+ const generateUnifiedResponseContent = (quoted, captured) => {
280
+ const ctxInfo = buildRichContextInfo(quoted);
281
+ return { message: buildBotForwardedMessage(captured.submessages, ctxInfo, captured.unifiedResponse), messageId: generateMessageIDV2() };
282
+ };
283
+ exports.generateUnifiedResponseContent = generateUnifiedResponseContent;
284
+
285
+ const generateRichMessageContent = (submessages, quoted, options) => {
286
+ const ctxInfo = buildRichContextInfo(quoted, options);
287
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() };
288
+ };
289
+ exports.generateRichMessageContent = generateRichMessageContent;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { LRUCache: LRUCache } = require("lru-cache");
4
+ const RECENT_MESSAGES_SIZE = 512;
5
+ const MESSAGE_KEY_SEPARATOR = "\0";
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1e3;
7
+ const PHONE_REQUEST_DELAY = 3e3;
8
+ class MessageRetryManager {
9
+ constructor(logger, maxMsgRetryCount) {
10
+ this.logger = logger;
11
+ this.recentMessagesMap = new LRUCache({
12
+ max: RECENT_MESSAGES_SIZE,
13
+ ttl: 5 * 60 * 1e3,
14
+ ttlAutopurge: true,
15
+ dispose: (_value, key) => {
16
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
17
+ if (separatorIndex > -1) {
18
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
19
+ this.messageKeyIndex.delete(messageId);
20
+ }
21
+ },
22
+ });
23
+ this.messageKeyIndex = new Map();
24
+ this.sessionRecreateHistory = new LRUCache({
25
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
26
+ ttlAutopurge: true,
27
+ });
28
+ this.retryCounters = new LRUCache({
29
+ ttl: 15 * 60 * 1e3,
30
+ ttlAutopurge: true,
31
+ updateAgeOnGet: true,
32
+ });
33
+ this.pendingPhoneRequests = {};
34
+ this.maxMsgRetryCount = 5;
35
+ this.statistics = {
36
+ totalRetries: 0,
37
+ successfulRetries: 0,
38
+ failedRetries: 0,
39
+ mediaRetries: 0,
40
+ sessionRecreations: 0,
41
+ phoneRequests: 0,
42
+ };
43
+ this.maxMsgRetryCount = maxMsgRetryCount;
44
+ }
45
+ addRecentMessage(to, id, message) {
46
+ const key = { to: to, id: id };
47
+ const keyStr = this.keyToString(key);
48
+ this.recentMessagesMap.set(keyStr, {
49
+ message: message,
50
+ timestamp: Date.now(),
51
+ });
52
+ this.messageKeyIndex.set(id, keyStr);
53
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
54
+ }
55
+ getRecentMessage(to, id) {
56
+ const key = { to: to, id: id };
57
+ const keyStr = this.keyToString(key);
58
+ return this.recentMessagesMap.get(keyStr);
59
+ }
60
+ shouldRecreateSession(jid, retryCount, hasSession) {
61
+ if (!hasSession) {
62
+ this.sessionRecreateHistory.set(jid, Date.now());
63
+ this.statistics.sessionRecreations++;
64
+ return {
65
+ reason: "we don't have a Signal session with them",
66
+ recreate: true,
67
+ };
68
+ }
69
+ if (retryCount < 2) {
70
+ return { reason: "", recreate: false };
71
+ }
72
+ const now = Date.now();
73
+ const prevTime = this.sessionRecreateHistory.get(jid);
74
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
75
+ this.sessionRecreateHistory.set(jid, now);
76
+ this.statistics.sessionRecreations++;
77
+ return {
78
+ reason: "retry count > 1 and over an hour since last recreation",
79
+ recreate: true,
80
+ };
81
+ }
82
+ return { reason: "", recreate: false };
83
+ }
84
+ incrementRetryCount(messageId) {
85
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
86
+ this.statistics.totalRetries++;
87
+ return this.retryCounters.get(messageId);
88
+ }
89
+ getRetryCount(messageId) {
90
+ return this.retryCounters.get(messageId) || 0;
91
+ }
92
+ hasExceededMaxRetries(messageId) {
93
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
94
+ }
95
+ markRetrySuccess(messageId) {
96
+ this.statistics.successfulRetries++;
97
+ this.retryCounters.delete(messageId);
98
+ this.cancelPendingPhoneRequest(messageId);
99
+ this.removeRecentMessage(messageId);
100
+ }
101
+ markRetryFailed(messageId) {
102
+ this.statistics.failedRetries++;
103
+ this.retryCounters.delete(messageId);
104
+ this.cancelPendingPhoneRequest(messageId);
105
+ this.removeRecentMessage(messageId);
106
+ }
107
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
108
+ this.cancelPendingPhoneRequest(messageId);
109
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
110
+ delete this.pendingPhoneRequests[messageId];
111
+ this.statistics.phoneRequests++;
112
+ callback();
113
+ }, delay);
114
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
115
+ }
116
+ cancelPendingPhoneRequest(messageId) {
117
+ const timeout = this.pendingPhoneRequests[messageId];
118
+ if (timeout) {
119
+ clearTimeout(timeout);
120
+ delete this.pendingPhoneRequests[messageId];
121
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
122
+ }
123
+ }
124
+ keyToString(key) {
125
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
126
+ }
127
+ removeRecentMessage(messageId) {
128
+ const keyStr = this.messageKeyIndex.get(messageId);
129
+ if (!keyStr) return;
130
+ this.recentMessagesMap.delete(keyStr);
131
+ this.messageKeyIndex.delete(messageId);
132
+ }
133
+ }
134
+ module.exports = { MessageRetryManager: MessageRetryManager };