vanzdev 3.0.4

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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +603 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/index.js +97692 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +120 -0
  9. package/lib/Defaults/wileys-version.json +3 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.js +57 -0
  14. package/lib/Signal/Group/keyhelper.js +55 -0
  15. package/lib/Signal/Group/queue-job.js +57 -0
  16. package/lib/Signal/Group/sender-chain-key.js +34 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-message.js +69 -0
  19. package/lib/Signal/Group/sender-key-name.js +51 -0
  20. package/lib/Signal/Group/sender-key-record.js +53 -0
  21. package/lib/Signal/Group/sender-key-state.js +99 -0
  22. package/lib/Signal/Group/sender-message-key.js +29 -0
  23. package/lib/Signal/libsignal.js +184 -0
  24. package/lib/Socket/Client/index.js +18 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +72 -0
  27. package/lib/Socket/business.js +260 -0
  28. package/lib/Socket/chats.js +997 -0
  29. package/lib/Socket/groups.js +332 -0
  30. package/lib/Socket/index.js +10 -0
  31. package/lib/Socket/messages-recv.js +1155 -0
  32. package/lib/Socket/messages-send.js +913 -0
  33. package/lib/Socket/newsletter.js +283 -0
  34. package/lib/Socket/socket.js +714 -0
  35. package/lib/Socket/usync.js +70 -0
  36. package/lib/Store/index.js +8 -0
  37. package/lib/Store/make-in-memory-store.js +439 -0
  38. package/lib/Store/make-ordered-dictionary.js +81 -0
  39. package/lib/Store/object-repository.js +27 -0
  40. package/lib/Types/Auth.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +4 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +27 -0
  47. package/lib/Types/LabelAssociation.js +9 -0
  48. package/lib/Types/Message.js +7 -0
  49. package/lib/Types/Newsletter.js +18 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +2 -0
  53. package/lib/Types/State.js +2 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +42 -0
  56. package/lib/Utils/auth-utils.js +199 -0
  57. package/lib/Utils/browser-utils.js +35 -0
  58. package/lib/Utils/business.js +234 -0
  59. package/lib/Utils/chat-utils.js +730 -0
  60. package/lib/Utils/crypto.js +193 -0
  61. package/lib/Utils/decode-wa-message.js +217 -0
  62. package/lib/Utils/event-buffer.js +518 -0
  63. package/lib/Utils/generics.js +467 -0
  64. package/lib/Utils/history.js +94 -0
  65. package/lib/Utils/index.js +35 -0
  66. package/lib/Utils/link-preview.js +126 -0
  67. package/lib/Utils/logger.js +7 -0
  68. package/lib/Utils/lt-hash.js +51 -0
  69. package/lib/Utils/make-mutex.js +43 -0
  70. package/lib/Utils/message-retry-manager.js +185 -0
  71. package/lib/Utils/messages-media.js +879 -0
  72. package/lib/Utils/messages.js +1828 -0
  73. package/lib/Utils/noise-handler.js +150 -0
  74. package/lib/Utils/process-message.js +404 -0
  75. package/lib/Utils/signal.js +153 -0
  76. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  77. package/lib/Utils/validate-connection.js +229 -0
  78. package/lib/Utils/wileys-event-stream.js +63 -0
  79. package/lib/WABinary/constants.js +1303 -0
  80. package/lib/WABinary/decode.js +265 -0
  81. package/lib/WABinary/encode.js +250 -0
  82. package/lib/WABinary/generic-utils.js +110 -0
  83. package/lib/WABinary/index.js +21 -0
  84. package/lib/WABinary/jid-utils.js +85 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +13 -0
  87. package/lib/WAM/constants.js +15350 -0
  88. package/lib/WAM/encode.js +155 -0
  89. package/lib/WAM/index.js +19 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  96. package/lib/WAUSync/Protocols/index.js +20 -0
  97. package/lib/WAUSync/USyncQuery.js +89 -0
  98. package/lib/WAUSync/USyncUser.js +26 -0
  99. package/lib/WAUSync/index.js +19 -0
  100. package/lib/index.js +94 -0
  101. package/package.json +119 -0
@@ -0,0 +1,1828 @@
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
+
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = require("fs");
11
+ const WAProto_1 = require("../../WAProto");
12
+ const Defaults_1 = require("../Defaults");
13
+ const Types_1 = require("../Types");
14
+ const WABinary_1 = require("../WABinary");
15
+ const crypto_2 = require("./crypto");
16
+ const generics_1 = require("./generics");
17
+ const messages_media_1 = require("./messages-media");
18
+ const Jimp = require("jimp");
19
+ const { zip } = require("fflate");
20
+ const { randomUUID } = require("crypto");
21
+
22
+ const MIMETYPE_MAP = {
23
+ image: 'image/jpeg',
24
+ video: 'video/mp4',
25
+ document: 'application/pdf',
26
+ audio: 'audio/ogg; codecs=opus',
27
+ sticker: 'image/webp',
28
+ 'product-catalog-image': 'image/jpeg',
29
+ };
30
+ const MessageTypeProto = {
31
+ 'image': Types_1.WAProto.Message.ImageMessage,
32
+ 'video': Types_1.WAProto.Message.VideoMessage,
33
+ 'audio': Types_1.WAProto.Message.AudioMessage,
34
+ 'sticker': Types_1.WAProto.Message.StickerMessage,
35
+ 'document': Types_1.WAProto.Message.DocumentMessage,
36
+ };
37
+ const ButtonType = WAProto_1.proto.Message.ButtonsMessage.HeaderType;
38
+
39
+ const extractUrlFromText = (text) => { var _a; return (_a = text.match(Defaults_1.URL_REGEX)) === null || _a === void 0 ? void 0 : _a[0]; };
40
+ const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
41
+ const url = extractUrlFromText(text);
42
+ if (!!getUrlInfo && url) {
43
+ try {
44
+ const urlInfo = await getUrlInfo(url);
45
+ return urlInfo;
46
+ } catch (error) {
47
+ logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'url generation failed');
48
+ }
49
+ }
50
+ };
51
+ const assertColor = async (color) => {
52
+ let assertedColor;
53
+ if (typeof color === 'number') {
54
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
55
+ } else {
56
+ let hex = color.trim().replace('#', '');
57
+ if (hex.length <= 6) {
58
+ hex = 'FF' + hex.padStart(6, '0');
59
+ }
60
+ assertedColor = parseInt(hex, 16);
61
+ return assertedColor;
62
+ }
63
+ };
64
+
65
+ const prepareWAMessageMedia = async (message, options) => {
66
+ const logger = options.logger;
67
+ let mediaType;
68
+ for (const key of Defaults_1.MEDIA_KEYS) {
69
+ if (key in message) {
70
+ mediaType = key;
71
+ }
72
+ }
73
+ if (!mediaType) {
74
+ throw new boom_1.Boom('Invalid media type', { statusCode: 400 });
75
+ }
76
+ const uploadData = {
77
+ ...message,
78
+ media: message[mediaType]
79
+ };
80
+ delete uploadData[mediaType];
81
+
82
+ const cacheableKey = typeof uploadData.media === 'object' &&
83
+ ('url' in uploadData.media) &&
84
+ !!uploadData.media.url &&
85
+ !!options.mediaCache && (
86
+ mediaType + ':' + uploadData.media.url.toString());
87
+
88
+ if (mediaType === 'document' && !uploadData.fileName) {
89
+ uploadData.fileName = 'file';
90
+ }
91
+ if (!uploadData.mimetype) {
92
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
93
+ }
94
+
95
+ if (cacheableKey) {
96
+ const mediaBuff = options.mediaCache.get(cacheableKey);
97
+ if (mediaBuff) {
98
+ logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'got media cache hit');
99
+ const obj = Types_1.WAProto.Message.decode(mediaBuff);
100
+ const key = `${mediaType}Message`;
101
+ Object.assign(obj[key], { ...uploadData, media: undefined });
102
+ return obj;
103
+ }
104
+ }
105
+
106
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
107
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
108
+ (typeof uploadData['jpegThumbnail'] === 'undefined');
109
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
110
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
111
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
112
+
113
+ const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
114
+ logger,
115
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
116
+ opts: options.options
117
+ });
118
+
119
+ const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
120
+
121
+ const [{ mediaUrl, directPath, handle }] = await Promise.all([
122
+ (async () => {
123
+ const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
124
+ logger === null || logger === void 0 ? void 0 : logger.debug({ mediaType, cacheableKey }, 'uploaded media');
125
+ return result;
126
+ })(),
127
+ (async () => {
128
+ try {
129
+ if (requiresThumbnailComputation) {
130
+ const { thumbnail, originalImageDimensions } = await (0, messages_media_1.generateThumbnail)(bodyPath, mediaType, options);
131
+ uploadData.jpegThumbnail = thumbnail;
132
+ if (!uploadData.width && originalImageDimensions) {
133
+ uploadData.width = originalImageDimensions.width;
134
+ uploadData.height = originalImageDimensions.height;
135
+ logger === null || logger === void 0 ? void 0 : logger.debug('set dimensions');
136
+ }
137
+ logger === null || logger === void 0 ? void 0 : logger.debug('generated thumbnail');
138
+ }
139
+ if (requiresDurationComputation) {
140
+ uploadData.seconds = await (0, messages_media_1.getAudioDuration)(bodyPath);
141
+ logger === null || logger === void 0 ? void 0 : logger.debug('computed audio duration');
142
+ }
143
+ if (requiresWaveformProcessing) {
144
+ uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
145
+ logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
146
+ }
147
+ if (requiresAudioBackground) {
148
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
149
+ logger === null || logger === void 0 ? void 0 : logger.debug('computed backgroundColor audio status');
150
+ }
151
+ } catch (error) {
152
+ logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'failed to obtain extra info');
153
+ }
154
+ })(),
155
+ ]).finally(async () => {
156
+ if (!Buffer.isBuffer(encWriteStream)) {
157
+ encWriteStream.destroy();
158
+ }
159
+ if (didSaveToTmpPath && bodyPath) {
160
+ try {
161
+ await fs_1.promises.access(bodyPath);
162
+ await fs_1.promises.unlink(bodyPath);
163
+ logger === null || logger === void 0 ? void 0 : logger.debug('removed tmp file');
164
+ } catch (error) {
165
+ logger === null || logger === void 0 ? void 0 : logger.warn('failed to remove tmp file');
166
+ }
167
+ }
168
+ });
169
+
170
+ const obj = Types_1.WAProto.Message.fromObject({
171
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
172
+ url: handle ? undefined : mediaUrl,
173
+ directPath,
174
+ mediaKey: mediaKey,
175
+ fileEncSha256: fileEncSha256,
176
+ fileSha256,
177
+ fileLength,
178
+ mediaKeyTimestamp: handle ? undefined : (0, generics_1.unixTimestampSeconds)(),
179
+ ...uploadData,
180
+ media: undefined
181
+ })
182
+ });
183
+ if (uploadData.ptv) {
184
+ obj.ptvMessage = obj.videoMessage;
185
+ delete obj.videoMessage;
186
+ }
187
+ if (cacheableKey) {
188
+ logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
189
+ options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
190
+ }
191
+ return obj;
192
+ };
193
+
194
+ const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
195
+ ephemeralExpiration = ephemeralExpiration || 0;
196
+ const content = {
197
+ ephemeralMessage: {
198
+ message: {
199
+ protocolMessage: {
200
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
201
+ ephemeralExpiration
202
+ }
203
+ }
204
+ }
205
+ };
206
+ return Types_1.WAProto.Message.fromObject(content);
207
+ };
208
+
209
+ async function processLocationThumbnail(input, options = {}) {
210
+ const { maxWidth = 300, maxHeight = 300, quality = 80 } = options;
211
+ let buffer;
212
+ if (typeof input === 'string' && (input.startsWith('http://') || input.startsWith('https://'))) {
213
+ const resp = await axios_1.default.get(input, { responseType: 'arraybuffer' });
214
+ buffer = Buffer.from(resp.data);
215
+ } else if (typeof input === 'string') {
216
+ buffer = await fs_1.promises.readFile(input);
217
+ } else if (Buffer.isBuffer(input)) {
218
+ buffer = input;
219
+ } else {
220
+ throw new Error('thumbnail must be URL, path or Buffer');
221
+ }
222
+ const image = await Jimp.read(buffer);
223
+ image.scaleToFit(maxWidth, maxHeight);
224
+ return await image.quality(quality).getBufferAsync(Jimp.MIME_JPEG);
225
+ }
226
+
227
+ async function prepareAlbumMessageContent(jid, albums, options) {
228
+ if (!Array.isArray(albums)) {
229
+ throw new Error('albums must be an array containing media objects.');
230
+ }
231
+ if (albums.length === 0) {
232
+ throw new Error('albums cannot be empty. At least one media item is required.');
233
+ }
234
+ const validCount = albums.filter((m) => 'image' in m || 'video' in m).length;
235
+ if (validCount === 0) {
236
+ throw new Error('albums contains no valid media. Use \'image\' or \'video\' keys.');
237
+ }
238
+
239
+ let mediaHandle;
240
+ let mediaMsg;
241
+ const message = [];
242
+ const albumMsg = generateWAMessageFromContent(
243
+ jid,
244
+ {
245
+ albumMessage: {
246
+ expectedImageCount: albums.filter((item) => 'image' in item).length,
247
+ expectedVideoCount: albums.filter((item) => 'video' in item).length,
248
+ },
249
+ },
250
+ options
251
+ );
252
+ await options.conn.relayMessage(jid, albumMsg.message, {
253
+ messageId: albumMsg.key.id,
254
+ });
255
+
256
+ for (const media of albums) {
257
+ let content = {};
258
+ if ('image' in media) {
259
+ content = { image: media.image };
260
+ } else if ('video' in media) {
261
+ content = { video: media.video };
262
+ } else {
263
+ continue;
264
+ }
265
+ mediaMsg = await generateWAMessage(
266
+ jid,
267
+ { ...content, ...media },
268
+ {
269
+ userJid: options.userJid,
270
+ upload: async (encFilePath, opts) => {
271
+ const up = await options.conn.waUploadToServer(encFilePath, {
272
+ ...opts,
273
+ newsletter: (0, WABinary_1.isJidNewsletter)(jid),
274
+ });
275
+ mediaHandle = up.handle;
276
+ return up;
277
+ },
278
+ ...options,
279
+ }
280
+ );
281
+ if (mediaMsg) {
282
+ mediaMsg.message.messageContextInfo = {
283
+ messageSecret: (0, crypto_1.randomBytes)(32),
284
+ messageAssociation: {
285
+ associationType: WAProto_1.proto.MessageAssociation.AssociationType.MEDIA_ALBUM,
286
+ parentMessageKey: albumMsg.key,
287
+ },
288
+ };
289
+ }
290
+ message.push(mediaMsg);
291
+ }
292
+ return message;
293
+ }
294
+
295
+ const generateForwardMessageContent = (message, forceForward) => {
296
+ var _a;
297
+ let content = message.message;
298
+ if (!content) {
299
+ throw new boom_1.Boom('no content in message', { statusCode: 400 });
300
+ }
301
+ content = normalizeMessageContent(content);
302
+ content = WAProto_1.proto.Message.decode(WAProto_1.proto.Message.encode(content).finish());
303
+ let key = Object.keys(content)[0];
304
+ let score = ((_a = content[key].contextInfo) === null || _a === void 0 ? void 0 : _a.forwardingScore) || 0;
305
+ score += message.key.fromMe && !forceForward ? 0 : 1;
306
+ if (key === 'conversation') {
307
+ content.extendedTextMessage = { text: content[key] };
308
+ delete content.conversation;
309
+ key = 'extendedTextMessage';
310
+ }
311
+ if (score > 0) {
312
+ content[key].contextInfo = { forwardingScore: score, isForwarded: true };
313
+ } else {
314
+ content[key].contextInfo = {};
315
+ }
316
+ return content;
317
+ };
318
+
319
+ function extractIE(text, { extract = true, hyperlink = true, citation = true, latex = true } = {}) {
320
+ if (!extract) return { text, ie: [], inline_entities: [] };
321
+ const createIE = (type, ie) => {
322
+ if (type === 'hyperlink') return {
323
+ key: ie.key,
324
+ metadata: {
325
+ display_name: ie.text,
326
+ is_trusted: ie.is_trusted,
327
+ url: ie.url,
328
+ __typename: 'GenAIInlineLinkItem',
329
+ },
330
+ };
331
+ if (type === 'citation') return {
332
+ key: ie.key,
333
+ metadata: {
334
+ reference_id: ie.reference_id,
335
+ reference_url: ie.url,
336
+ reference_title: ie.url,
337
+ reference_display_name: ie.url,
338
+ sources: [],
339
+ __typename: 'GenAISearchCitationItem',
340
+ },
341
+ };
342
+ if (type === 'latex') return {
343
+ key: ie.key,
344
+ metadata: {
345
+ latex_expression: ie.text,
346
+ latex_image: { url: ie.url, width: Number(ie.width) || 100, height: Number(ie.height) || 100 },
347
+ font_height: Number(ie.font_height) || 83.333333333333,
348
+ padding: Number(ie.padding) || 15,
349
+ __typename: 'GenAILatexItem',
350
+ },
351
+ };
352
+ };
353
+ let ie = [], inline_entities = [], result = '', last = 0,
354
+ citation_index = 1, hyperlink_index = 0, latex_index = 0, stack = [];
355
+ for (let i = 0; i < text.length; i++) {
356
+ if (text[i] === '[' && text[i - 1] !== '\\') {
357
+ stack.push(i);
358
+ } else if (text[i] === ']' && (text[i + 1] === '(' || text[i + 1] === '<')) {
359
+ let start = stack.pop();
360
+ if (start == null) continue;
361
+ let open = text[i + 1], close = open === '(' ? ')' : '>',
362
+ type = open === '(' ? 'link' : 'latex', end = i + 2, depth = 1;
363
+ while (end < text.length && depth) {
364
+ if (text[end] === open && text[end - 1] !== '\\') depth++;
365
+ else if (text[end] === close && text[end - 1] !== '\\') depth--;
366
+ end++;
367
+ }
368
+ if (depth) continue;
369
+ let raw = text.slice(start + 1, i).trim(), url = text.slice(i + 2, end - 1).trim(), key, tag, data;
370
+ if (type === 'latex') {
371
+ if (!latex) continue;
372
+ let [txt = '', width = null, height = null, font_height = null, padding = null] = raw.split('|');
373
+ key = `LEVVI_LATEX_${latex_index++}`;
374
+ tag = `{{${key}}}${txt || 'image'}{{/${key}}}`;
375
+ data = { type: 'latex', ie: { key, text: txt, url, width, height, font_height, padding } };
376
+ } else if (raw) {
377
+ if (!hyperlink) continue;
378
+ const trusted = !url.startsWith('!');
379
+ if (!trusted) url = url.slice(1);
380
+ key = `LEVVI_HYPERLINK_${hyperlink_index++}`;
381
+ tag = `{{${key}}}${url}{{/${key}}}`;
382
+ data = { type: 'hyperlink', ie: { key, text: raw, url, is_trusted: trusted } };
383
+ } else {
384
+ if (!citation) continue;
385
+ key = `LEVVI_CITATION_${citation_index - 1}`;
386
+ tag = `{{${key}}}${url}{{/${key}}}`;
387
+ data = { type: 'citation', ie: { reference_id: citation_index++, key, text: '', url } };
388
+ }
389
+ result += text.slice(last, start) + tag;
390
+ last = end;
391
+ ie.push(data);
392
+ const entity = createIE(data.type, data.ie);
393
+ if (entity) inline_entities.push(entity);
394
+ i = end - 1;
395
+ }
396
+ }
397
+ result += text.slice(last);
398
+ return { text: result, ie, inline_entities };
399
+ }
400
+
401
+ async function waitAllPromises(input) {
402
+ const isPromise = (v) => v && typeof v.then === 'function';
403
+ const isObject = (v) => v && typeof v === 'object';
404
+ const deep = async (v) => {
405
+ if (isPromise(v)) return deep(await v);
406
+ if (Array.isArray(v)) return Promise.all(v.map(deep));
407
+ if (isObject(v)) {
408
+ const entries = await Promise.all(Object.entries(v).map(async ([k, val]) => [k, await deep(val)]));
409
+ return Object.fromEntries(entries);
410
+ }
411
+ return v;
412
+ };
413
+ return deep(await input);
414
+ }
415
+
416
+ function tokenizer(code, lang = 'javascript') {
417
+ const keywordsMap = {
418
+ javascript: new Set(['break','case','catch','continue','debugger','delete','do','else','finally','for','function','if','in','instanceof','new','return','switch','this','throw','try','typeof','var','void','while','with','true','false','null','undefined','class','const','let','super','extends','export','import','yield','static','constructor','async','await','get','set']),
419
+ typescript: new Set(['abstract','any','as','asserts','bigint','boolean','declare','enum','implements','infer','interface','is','keyof','module','namespace','never','readonly','require','number','object','override','private','protected','public','satisfies','string','symbol','type','unknown','using','from','break','case','catch','continue','do','else','finally','for','function','if','new','return','switch','this','throw','try','var','void','while','class','const','let','extends','import','export','async','await']),
420
+ python: new Set(['False','None','True','and','as','assert','async','await','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']),
421
+ java: new Set(['abstract','assert','boolean','break','byte','case','catch','char','class','const','continue','default','do','double','else','enum','extends','final','finally','float','for','goto','if','implements','import','instanceof','int','interface','long','native','new','package','private','protected','public','return','short','static','strictfp','super','switch','synchronized','this','throw','throws','transient','try','void','volatile','while']),
422
+ golang: new Set(['break','case','chan','const','continue','default','defer','else','fallthrough','for','func','go','goto','if','import','interface','map','package','range','return','select','struct','switch','type','var']),
423
+ c: new Set(['auto','break','case','char','const','continue','default','do','double','else','enum','extern','float','for','goto','if','int','long','register','return','short','signed','sizeof','static','struct','switch','typedef','union','unsigned','void','volatile','while']),
424
+ cpp: new Set(['alignas','alignof','and','auto','bool','break','case','catch','class','const','constexpr','continue','delete','do','double','else','enum','explicit','export','extern','false','float','for','friend','if','inline','int','long','mutable','namespace','new','noexcept','nullptr','operator','private','protected','public','return','short','signed','sizeof','static','struct','switch','template','this','throw','true','try','typedef','typename','union','unsigned','using','virtual','void','while']),
425
+ php: new Set(['abstract','and','array','as','break','callable','case','catch','class','clone','const','continue','declare','default','do','echo','else','elseif','empty','enddeclare','endfor','endforeach','endif','endswitch','endwhile','extends','final','finally','fn','for','foreach','function','global','goto','if','implements','include','include_once','instanceof','interface','match','namespace','new','null','or','private','protected','public','require','require_once','return','static','switch','throw','trait','try','use','var','while','yield']),
426
+ rust: new Set(['as','break','const','continue','crate','else','enum','extern','false','fn','for','if','impl','in','let','loop','match','mod','move','mut','pub','ref','return','self','Self','static','struct','super','trait','true','type','unsafe','use','where','while']),
427
+ html: new Set(['html','head','body','div','span','p','a','img','video','audio','script','style','link','meta','form','input','button','table','tr','td','th','ul','ol','li','section','article','header','footer','nav','main']),
428
+ bash: new Set(['if','then','else','elif','fi','for','while','do','done','case','esac','function','in','select','until','break','continue','return','export','readonly','local','declare']),
429
+ markdown: new Set(['#','##','###','####','#####','######']),
430
+ };
431
+ if (!lang || lang === 'txt' || lang === 'text' || lang === 'plaintext') {
432
+ return {
433
+ codeBlock: [{ codeContent: code, highlightType: 0 }],
434
+ unified_codeBlock: [{ content: code, type: 'DEFAULT' }],
435
+ };
436
+ }
437
+ const TYPE_MAP = { 0:'DEFAULT', 1:'KEYWORD', 2:'METHOD', 3:'STR', 4:'NUMBER', 5:'COMMENT' };
438
+ const keywords = keywordsMap[lang.toLowerCase()] || new Set();
439
+ const tokens = [];
440
+ let i = 0;
441
+ const push = (content, type) => {
442
+ if (!content) return;
443
+ const last = tokens[tokens.length - 1];
444
+ if (last && last.highlightType === type) last.codeContent += content;
445
+ else tokens.push({ codeContent: content, highlightType: type });
446
+ };
447
+ const isIdentifier = (char) => {
448
+ switch (lang.toLowerCase()) {
449
+ case 'css': return /[a-zA-Z0-9_$-]/.test(char);
450
+ case 'html': return /[a-zA-Z0-9_$:-]/.test(char);
451
+ default: return /[a-zA-Z0-9_$]/.test(char);
452
+ }
453
+ };
454
+ while (i < code.length) {
455
+ const c = code[i];
456
+ if (/\s/.test(c)) {
457
+ let s = i;
458
+ while (i < code.length && /\s/.test(code[i])) i++;
459
+ push(code.slice(s, i), 0);
460
+ continue;
461
+ }
462
+ if ((c === '/' && code[i + 1] === '/') || (c === '#' && ['python','bash'].includes(lang))) {
463
+ let s = i;
464
+ while (i < code.length && code[i] !== '\n') i++;
465
+ push(code.slice(s, i), 5);
466
+ continue;
467
+ }
468
+ if (c === '"' || c === "'" || c === '`') {
469
+ let s = i;
470
+ const q = c;
471
+ i++;
472
+ while (i < code.length) {
473
+ if (code[i] === '\\' && i + 1 < code.length) i += 2;
474
+ else if (code[i] === q) { i++; break; }
475
+ else i++;
476
+ }
477
+ push(code.slice(s, i), 3);
478
+ continue;
479
+ }
480
+ if (/[0-9]/.test(c)) {
481
+ let s = i;
482
+ while (i < code.length && /[0-9._]/.test(code[i])) i++;
483
+ push(code.slice(s, i), 4);
484
+ continue;
485
+ }
486
+ if (/[a-zA-Z_$]/.test(c)) {
487
+ let s = i;
488
+ while (i < code.length && isIdentifier(code[i])) i++;
489
+ const word = code.slice(s, i);
490
+ let type = 0;
491
+ if (keywords.has(word)) type = 1;
492
+ else if (lang === 'css') {
493
+ let j = i;
494
+ while (j < code.length && /\s/.test(code[j])) j++;
495
+ if (code[j] === ':') type = 1;
496
+ } else if (lang === 'html') {
497
+ let p = s - 1;
498
+ while (p >= 0 && /\s/.test(code[p])) p--;
499
+ if (code[p] === '<' || (code[p] === '/' && code[p-1] === '<')) type = 1;
500
+ }
501
+ if (type === 0) {
502
+ let j = i;
503
+ while (j < code.length && /\s/.test(code[j])) j++;
504
+ if (code[j] === '(') type = 2;
505
+ }
506
+ push(word, type);
507
+ continue;
508
+ }
509
+ push(c, 0);
510
+ i++;
511
+ }
512
+ return {
513
+ codeBlock: tokens,
514
+ unified_codeBlock: tokens.map(t => ({ content: t.codeContent, type: TYPE_MAP[t.highlightType] })),
515
+ };
516
+ }
517
+
518
+ function toTableMetadata(arr, { hyperlink = true, citation = true, latex = true } = {}) {
519
+ if (!Array.isArray(arr) || !arr.every(row => Array.isArray(row) && row.every(cell => typeof cell === 'string'))) {
520
+ throw new TypeError('Table must be a nested array of strings');
521
+ }
522
+ const [header, ...rows] = arr;
523
+ const maxLen = Math.max(header.length, ...rows.map(r => r.length));
524
+ const normalize = (r) => [...r, ...Array(maxLen - r.length).fill('')];
525
+ const unified_rows = [
526
+ { is_header: true, cells: normalize(header) },
527
+ ...rows.map(r => ({ is_header: false, cells: normalize(r) })),
528
+ ].map(row => {
529
+ const markdown_cells = row.cells.map(cell => {
530
+ const extracted = extractIE(cell, { hyperlink, citation, latex });
531
+ return { text: extracted.text, ...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}) };
532
+ });
533
+ return { ...row, ...(markdown_cells.some(c => c.inline_entities?.length) ? { markdown_cells } : {}) };
534
+ });
535
+ const rowsMeta = unified_rows.map(r => ({
536
+ items: r.cells,
537
+ ...(r.is_header ? { isHeading: true } : {}),
538
+ }));
539
+ return { title: '', rows: rowsMeta, unified_rows };
540
+ }
541
+
542
+ function newLayout(name, data, extra = {}) {
543
+ return {
544
+ ...extra,
545
+ view_model: {
546
+ [Array.isArray(data) ? 'primitives' : 'primitive']: data,
547
+ __typename: `GenAI${name}LayoutViewModel`,
548
+ },
549
+ };
550
+ }
551
+
552
+ const generateWAMessageContent = async (message, options) => {
553
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
554
+ var _p, _q;
555
+ let m = {};
556
+
557
+ if ('text' in message) {
558
+ const extContent = { text: message.text };
559
+ let urlInfo = message.linkPreview;
560
+ if (typeof urlInfo === 'undefined') {
561
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
562
+ }
563
+ if (urlInfo) {
564
+ extContent.matchedText = urlInfo['matched-text'];
565
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
566
+ extContent.description = urlInfo.description;
567
+ extContent.title = urlInfo.title;
568
+ extContent.previewType = 0;
569
+ const img = urlInfo.highQualityThumbnail;
570
+ if (img) {
571
+ extContent.thumbnailDirectPath = img.directPath;
572
+ extContent.mediaKey = img.mediaKey;
573
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
574
+ extContent.thumbnailWidth = img.width;
575
+ extContent.thumbnailHeight = img.height;
576
+ extContent.thumbnailSha256 = img.fileSha256;
577
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
578
+ }
579
+ }
580
+ if (options.backgroundColor) {
581
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
582
+ }
583
+ if (options.font) {
584
+ extContent.font = options.font;
585
+ }
586
+ m.extendedTextMessage = extContent;
587
+ } else if ('contacts' in message) {
588
+ const contactLen = message.contacts.contacts.length;
589
+ if (!contactLen) {
590
+ throw new boom_1.Boom('require atleast 1 contact', { statusCode: 400 });
591
+ }
592
+ if (contactLen === 1) {
593
+ m.contactMessage = Types_1.WAProto.Message.ContactMessage.fromObject(message.contacts.contacts[0]);
594
+ } else {
595
+ m.contactsArrayMessage = Types_1.WAProto.Message.ContactsArrayMessage.fromObject(message.contacts);
596
+ }
597
+ } else if ('location' in message) {
598
+ m.locationMessage = Types_1.WAProto.Message.LocationMessage.fromObject(message.location);
599
+ } else if ('react' in message) {
600
+ if (!message.react.senderTimestampMs) {
601
+ message.react.senderTimestampMs = Date.now();
602
+ }
603
+ m.reactionMessage = Types_1.WAProto.Message.ReactionMessage.fromObject(message.react);
604
+ } else if ('delete' in message) {
605
+ m.protocolMessage = {
606
+ key: message.delete,
607
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.REVOKE
608
+ };
609
+ } else if ('forward' in message) {
610
+ m = generateForwardMessageContent(message.forward, message.force);
611
+ } else if ('disappearingMessagesInChat' in message) {
612
+ const exp = typeof message.disappearingMessagesInChat === 'boolean' ?
613
+ (message.disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
614
+ message.disappearingMessagesInChat;
615
+ m = prepareDisappearingMessageSettingContent(exp);
616
+ } else if ('groupInvite' in message) {
617
+ m.groupInviteMessage = {};
618
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
619
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
620
+ m.groupInviteMessage.caption = message.groupInvite.text;
621
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
622
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
623
+ if (options.getProfilePicUrl) {
624
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
625
+ if (pfpUrl) {
626
+ const resp = await axios_1.default.get(pfpUrl, { responseType: 'arraybuffer' });
627
+ if (resp.status === 200) {
628
+ m.groupInviteMessage.jpegThumbnail = resp.data;
629
+ }
630
+ }
631
+ }
632
+ } else if ('pin' in message) {
633
+ m.pinInChatMessage = {};
634
+ m.messageContextInfo = {};
635
+ m.pinInChatMessage.key = message.pin;
636
+ m.pinInChatMessage.type = message.type;
637
+ m.pinInChatMessage.senderTimestampMs = Date.now();
638
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
639
+ } else if ('keep' in message) {
640
+ m.keepInChatMessage = {};
641
+ m.keepInChatMessage.key = message.keep;
642
+ m.keepInChatMessage.keepType = message.type;
643
+ m.keepInChatMessage.timestampMs = Date.now();
644
+ } else if ('call' in message) {
645
+ m = {
646
+ scheduledCallCreationMessage: {
647
+ scheduledTimestampMs: (_a = message.call.time) !== null && _a !== void 0 ? _a : Date.now(),
648
+ callType: (_b = message.call.type) !== null && _b !== void 0 ? _b : 1,
649
+ title: message.call.title
650
+ }
651
+ };
652
+ } else if ('paymentInvite' in message) {
653
+ m.paymentInviteMessage = {
654
+ serviceType: message.paymentInvite.type,
655
+ expiryTimestamp: message.paymentInvite.expiry
656
+ };
657
+ } else if ('buttonReply' in message) {
658
+ switch (message.type) {
659
+ case 'template':
660
+ m.templateButtonReplyMessage = {
661
+ selectedDisplayText: message.buttonReply.displayText,
662
+ selectedId: message.buttonReply.id,
663
+ selectedIndex: message.buttonReply.index,
664
+ };
665
+ break;
666
+ case 'plain':
667
+ m.buttonsResponseMessage = {
668
+ selectedButtonId: message.buttonReply.id,
669
+ selectedDisplayText: message.buttonReply.displayText,
670
+ type: WAProto_1.proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
671
+ };
672
+ break;
673
+ }
674
+ } else if ('ptv' in message && message.ptv) {
675
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
676
+ m.ptvMessage = videoMessage;
677
+ } else if ('product' in message) {
678
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
679
+ m.productMessage = Types_1.WAProto.Message.ProductMessage.fromObject({
680
+ ...message,
681
+ product: {
682
+ ...message.product,
683
+ productImage: imageMessage,
684
+ }
685
+ });
686
+ } else if ('order' in message) {
687
+ m.orderMessage = Types_1.WAProto.Message.OrderMessage.fromObject({
688
+ orderId: message.order.id,
689
+ thumbnail: message.order.thumbnail,
690
+ itemCount: message.order.itemCount,
691
+ status: message.order.status,
692
+ surface: message.order.surface,
693
+ orderTitle: message.order.title,
694
+ message: message.order.text,
695
+ sellerJid: message.order.seller,
696
+ token: message.order.token,
697
+ totalAmount1000: message.order.amount,
698
+ totalCurrencyCode: message.order.currency
699
+ });
700
+ } else if ('listReply' in message) {
701
+ m.listResponseMessage = { ...message.listReply };
702
+ } else if ('poll' in message) {
703
+ (_p = message.poll).selectableCount || (_p.selectableCount = 0);
704
+ (_q = message.poll).toAnnouncementGroup || (_q.toAnnouncementGroup = false);
705
+ if (!Array.isArray(message.poll.values)) {
706
+ throw new boom_1.Boom('Invalid poll values', { statusCode: 400 });
707
+ }
708
+ if (message.poll.selectableCount < 0
709
+ || message.poll.selectableCount > message.poll.values.length) {
710
+ throw new boom_1.Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, { statusCode: 400 });
711
+ }
712
+ m.messageContextInfo = {
713
+ messageSecret: message.poll.messageSecret || (0, crypto_1.randomBytes)(32),
714
+ };
715
+ const pollCreationMessage = {
716
+ name: message.poll.name,
717
+ selectableOptionsCount: message.poll.selectableCount,
718
+ options: message.poll.values.map(optionName => ({ optionName })),
719
+ };
720
+ if (message.poll.toAnnouncementGroup) {
721
+ m.pollCreationMessageV2 = pollCreationMessage;
722
+ } else {
723
+ if (message.poll.selectableCount === 1) {
724
+ m.pollCreationMessageV3 = pollCreationMessage;
725
+ } else {
726
+ m.pollCreationMessage = pollCreationMessage;
727
+ }
728
+ }
729
+ } else if ('event' in message) {
730
+ m.messageContextInfo = {
731
+ messageSecret: message.event.messageSecret || (0, crypto_1.randomBytes)(32),
732
+ };
733
+ m.eventMessage = { ...message.event };
734
+ } else if ('inviteAdmin' in message) {
735
+ m.newsletterAdminInviteMessage = {};
736
+ m.newsletterAdminInviteMessage.inviteExpiration = message.inviteAdmin.inviteExpiration;
737
+ m.newsletterAdminInviteMessage.caption = message.inviteAdmin.text;
738
+ m.newsletterAdminInviteMessage.newsletterJid = message.inviteAdmin.jid;
739
+ m.newsletterAdminInviteMessage.newsletterName = message.inviteAdmin.subject;
740
+ m.newsletterAdminInviteMessage.jpegThumbnail = message.inviteAdmin.thumbnail;
741
+ } else if ('requestPayment' in message) {
742
+ const sticker = ((_c = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _c === void 0 ? void 0 : _c.sticker) ?
743
+ await prepareWAMessageMedia({ sticker: (_d = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _d === void 0 ? void 0 : _d.sticker, ...options }, options)
744
+ : null;
745
+ let notes = {};
746
+ if ((_e = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _e === void 0 ? void 0 : _e.sticker) {
747
+ notes = {
748
+ stickerMessage: {
749
+ ...sticker === null || sticker === void 0 ? void 0 : sticker.stickerMessage,
750
+ contextInfo: (_f = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _f === void 0 ? void 0 : _f.contextInfo
751
+ }
752
+ };
753
+ } else if (message.requestPayment.note) {
754
+ notes = {
755
+ extendedTextMessage: {
756
+ text: message.requestPayment.note,
757
+ contextInfo: (_g = message === null || message === void 0 ? void 0 : message.requestPayment) === null || _g === void 0 ? void 0 : _g.contextInfo,
758
+ }
759
+ };
760
+ } else {
761
+ throw new boom_1.Boom('Invalid media type', { statusCode: 400 });
762
+ }
763
+ m.requestPaymentMessage = Types_1.WAProto.Message.RequestPaymentMessage.fromObject({
764
+ expiryTimestamp: message.requestPayment.expiry,
765
+ amount1000: message.requestPayment.amount,
766
+ currencyCodeIso4217: message.requestPayment.currency,
767
+ requestFrom: message.requestPayment.from,
768
+ noteMessage: { ...notes },
769
+ background: (_h = message.requestPayment.background) !== null && _h !== void 0 ? _h : null,
770
+ });
771
+ } else if ('sharePhoneNumber' in message) {
772
+ m.protocolMessage = {
773
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
774
+ };
775
+ } else if ('requestPhoneNumber' in message) {
776
+ m.requestPhoneNumberMessage = {};
777
+ } else if ('album' in message) {
778
+ const imageMessages = message.album.filter(item => 'image' in item);
779
+ const videoMessages = message.album.filter(item => 'video' in item);
780
+ m.albumMessage = WAProto_1.proto.Message.AlbumMessage.fromObject({
781
+ expectedImageCount: imageMessages.length,
782
+ expectedVideoCount: videoMessages.length,
783
+ });
784
+ } else if ('groupStatus' in message) {
785
+ const gs = message.groupStatus;
786
+ if (!gs.message) throw new Error('groupStatus.message is required');
787
+ const audienceType = gs.audienceType || 0;
788
+ const backgroundColor = gs.backgroundArgb;
789
+ const textColor = gs.textArgb;
790
+ const font = gs.font;
791
+
792
+ let messageContent = gs.message;
793
+ if (typeof messageContent === 'string') {
794
+ messageContent = {
795
+ extendedTextMessage: {
796
+ text: messageContent,
797
+ contextInfo: {
798
+ statusAudienceMetadata: { audienceType }
799
+ },
800
+ ...(backgroundColor && { backgroundArgb: backgroundColor }),
801
+ ...(textColor && { textArgb: textColor }),
802
+ ...(font && { font: font })
803
+ }
804
+ };
805
+ } else if (messageContent.extendedTextMessage) {
806
+ if (backgroundColor) messageContent.extendedTextMessage.backgroundArgb = backgroundColor;
807
+ if (textColor) messageContent.extendedTextMessage.textArgb = textColor;
808
+ if (font) messageContent.extendedTextMessage.font = font;
809
+ messageContent.extendedTextMessage.contextInfo = {
810
+ ...messageContent.extendedTextMessage.contextInfo,
811
+ statusAudienceMetadata: { audienceType }
812
+ };
813
+ } else if (
814
+ messageContent.imageMessage ||
815
+ messageContent.videoMessage ||
816
+ messageContent.audioMessage ||
817
+ messageContent.documentMessage
818
+ ) {
819
+ const key = Object.keys(messageContent)[0];
820
+ if (!messageContent[key].contextInfo) {
821
+ messageContent[key].contextInfo = {};
822
+ }
823
+ messageContent[key].contextInfo.statusAudienceMetadata = {
824
+ audienceType: audienceType
825
+ };
826
+ }
827
+ m = { groupStatusMessageV2: { message: messageContent } };
828
+ } else if ('orderStatus' in message) {
829
+ const os = message.orderStatus;
830
+ if (!os.image) throw new Error('image is required for orderStatus');
831
+ let imageInput = os.image;
832
+ if (typeof imageInput === 'string' && !imageInput.startsWith('http://') && !imageInput.startsWith('https://')) {
833
+ imageInput = await fs_1.promises.readFile(imageInput);
834
+ }
835
+ const media = await prepareWAMessageMedia(
836
+ { image: imageInput },
837
+ { upload: options.upload, ...options }
838
+ );
839
+ m = {
840
+ viewOnceMessage: {
841
+ message: {
842
+ messageContextInfo: {
843
+ deviceListMetadata: {},
844
+ deviceListMetadataVersion: 2
845
+ },
846
+ interactiveMessage: WAProto_1.proto.Message.InteractiveMessage.create({
847
+ header: {
848
+ title: os.title || 'Order Status',
849
+ hasMediaAttachment: true,
850
+ ...media
851
+ },
852
+ body: {
853
+ text: os.text || 'Silakan cek status pesanan Anda.'
854
+ },
855
+ footer: {
856
+ text: os.footer || 'Powered by LevviCode'
857
+ },
858
+ nativeFlowMessage: {
859
+ buttons: [
860
+ {
861
+ name: 'order_status',
862
+ buttonParamsJson: JSON.stringify({
863
+ reference_id: os.referenceId || 'LV-001',
864
+ order: {
865
+ status: os.status || 'PROCESSING',
866
+ subtotal: {
867
+ value: os.subtotalValue || 0,
868
+ offset: os.subtotalOffset || 100
869
+ },
870
+ tax: {
871
+ value: os.taxValue || 0,
872
+ offset: os.taxOffset || 100
873
+ },
874
+ currency: os.currency || 'IDR'
875
+ }
876
+ })
877
+ }
878
+ ]
879
+ }
880
+ })
881
+ }
882
+ }
883
+ };
884
+ } else if ('buttonsMessage' in message) {
885
+ const bm = message.buttonsMessage
886
+
887
+ let locationMessage
888
+
889
+ if (bm.locationMessage) {
890
+ const loc = bm.locationMessage
891
+ const thumbInput = loc.jpegThumbnail || loc.thumbnail
892
+
893
+ let thumb
894
+ if (thumbInput) {
895
+ thumb = await processLocationThumbnail(thumbInput)
896
+ }
897
+
898
+ locationMessage = WAProto_1.proto.Message.LocationMessage.create({
899
+ degreesLatitude: loc.degreesLatitude || 0,
900
+ degreesLongitude: loc.degreesLongitude || 0,
901
+ name: loc.name || '',
902
+ address: loc.address || '',
903
+ jpegThumbnail: thumb
904
+ })
905
+ }
906
+
907
+ const buttons = (bm.buttons || []).map(btn =>
908
+ WAProto_1.proto.Message.ButtonsMessage.Button.create({
909
+ buttonId: btn.buttonId || '',
910
+ buttonText: WAProto_1.proto.Message.ButtonsMessage.Button.ButtonText.create({
911
+ displayText: btn.buttonText?.displayText || ''
912
+ }),
913
+ type: btn.type || 1,
914
+ nativeFlowInfo: btn.nativeFlowInfo
915
+ ? WAProto_1.proto.Message.ButtonsMessage.Button.NativeFlowInfo.create({
916
+ name: btn.nativeFlowInfo.name || '',
917
+ paramsJson: btn.nativeFlowInfo.paramsJson || '',
918
+ buttonParamsJson:
919
+ btn.nativeFlowInfo.buttonParamsJson ||
920
+ btn.nativeFlowInfo.paramsJson ||
921
+ ''
922
+ })
923
+ : undefined
924
+ })
925
+ )
926
+
927
+ m = {
928
+ buttonsMessage: WAProto_1.proto.Message.ButtonsMessage.create({
929
+ locationMessage,
930
+ contentText: bm.contentText || '',
931
+ footerText: bm.footerText || '',
932
+ buttons,
933
+ headerType: bm.headerType || 6,
934
+ viewOnce: !!bm.viewOnce
935
+ })
936
+ }
937
+ } else if ('stickerPack' in message) {
938
+ const {
939
+ stickers: stickers,
940
+ cover: cover,
941
+ name: name,
942
+ publisher: publisher,
943
+ packId: packId,
944
+ description: description,
945
+ } = message.stickerPack;
946
+ const stickerData = {};
947
+ const stickerPromises = stickers.map(async (s, i) => {
948
+ let buffer;
949
+ if (typeof s.sticker === 'string' && (s.sticker.startsWith('http://') || s.sticker.startsWith('https://'))) {
950
+ const resp = await axios_1.default.get(s.sticker, { responseType: 'arraybuffer' });
951
+ buffer = Buffer.from(resp.data);
952
+ } else if (typeof s.sticker === 'string') {
953
+ buffer = await fs_1.promises.readFile(s.sticker);
954
+ } else if (Buffer.isBuffer(s.sticker)) {
955
+ buffer = s.sticker;
956
+ } else {
957
+ throw new Error('sticker must be URL, path or Buffer');
958
+ }
959
+ const hash = (0, crypto_2.sha256)(buffer).toString('base64url');
960
+ const fileName = `${i.toString().padStart(2, '0')}_${hash}.webp`;
961
+ stickerData[fileName] = [new Uint8Array(buffer), { level: 0 }];
962
+ return {
963
+ fileName: fileName,
964
+ mimetype: 'image/webp',
965
+ isAnimated: s.isAnimated || false,
966
+ isLottie: s.isLottie || false,
967
+ emojis: s.emojis || [],
968
+ accessibilityLabel: s.accessibilityLabel || '',
969
+ };
970
+ });
971
+ const stickerMetadata = await Promise.all(stickerPromises);
972
+
973
+ const zipBuffer = await new Promise((resolve, reject) => {
974
+ zip(stickerData, (err, data) => {
975
+ if (err) reject(err);
976
+ else resolve(Buffer.from(data));
977
+ });
978
+ });
979
+
980
+ let coverBuffer;
981
+ if (typeof cover === 'string' && (cover.startsWith('http://') || cover.startsWith('https://'))) {
982
+ const resp = await axios_1.default.get(cover, { responseType: 'arraybuffer' });
983
+ coverBuffer = Buffer.from(resp.data);
984
+ } else if (typeof cover === 'string') {
985
+ coverBuffer = await fs_1.promises.readFile(cover);
986
+ } else if (Buffer.isBuffer(cover)) {
987
+ coverBuffer = cover;
988
+ } else {
989
+ throw new Error('cover must be URL, path or Buffer');
990
+ }
991
+
992
+ const [stickerPackUpload, coverUpload] = await Promise.all([
993
+ (0, messages_media_1.encryptedStream)(zipBuffer, 'sticker-pack', {
994
+ logger: options.logger,
995
+ opts: options.options,
996
+ }),
997
+ prepareWAMessageMedia(
998
+ { image: coverBuffer },
999
+ { ...options, mediaTypeOverride: 'image' }
1000
+ ),
1001
+ ]);
1002
+
1003
+ const stickerPackUploadResult = await options.upload(stickerPackUpload.encWriteStream, {
1004
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
1005
+ mediaType: 'sticker-pack',
1006
+ timeoutMs: options.mediaUploadTimeoutMs,
1007
+ });
1008
+
1009
+ const coverImage = coverUpload.imageMessage;
1010
+ const imageDataHash = (0, crypto_2.sha256)(coverBuffer).toString('base64');
1011
+ const stickerPackId = packId || (0, generics_1.generateMessageID)();
1012
+
1013
+ m.stickerPackMessage = {
1014
+ name: name,
1015
+ publisher: publisher,
1016
+ stickerPackId: stickerPackId,
1017
+ packDescription: description,
1018
+ stickerPackOrigin: WAProto_1.proto.Message.StickerPackMessage.StickerPackOrigin.THIRD_PARTY,
1019
+ stickerPackSize: stickerPackUpload.fileLength,
1020
+ stickers: stickerMetadata,
1021
+ fileSha256: stickerPackUpload.fileSha256,
1022
+ fileEncSha256: stickerPackUpload.fileEncSha256,
1023
+ mediaKey: stickerPackUpload.mediaKey,
1024
+ directPath: stickerPackUploadResult.directPath,
1025
+ fileLength: stickerPackUpload.fileLength,
1026
+ mediaKeyTimestamp: (0, generics_1.unixTimestampSeconds)(),
1027
+ trayIconFileName: `${stickerPackId}.png`,
1028
+ imageDataHash: imageDataHash,
1029
+ thumbnailDirectPath: coverImage.directPath,
1030
+ thumbnailFileSha256: coverImage.fileSha256,
1031
+ thumbnailFileEncSha256: coverImage.fileEncSha256,
1032
+ thumbnailHeight: coverImage.height,
1033
+ thumbnailWidth: coverImage.width,
1034
+ };
1035
+ } else if ('richMessage' in message) {
1036
+ const rich = message.richMessage;
1037
+ const submessages = [];
1038
+ const sections = [];
1039
+ const richResponseSources = [];
1040
+
1041
+ if (rich.text) {
1042
+ let finalText = rich.text;
1043
+ finalText = finalText.replace(/\[citation\]\((.+?)\)/g, (match, url) => {
1044
+ return `[](\n${url})`;
1045
+ });
1046
+
1047
+ const parsed = typeof finalText === 'string' ? extractIE(finalText) : finalText;
1048
+ const text = parsed.text || parsed;
1049
+ const inline_entities = parsed.ie ? parsed.ie.map(({ type, ie }) => {
1050
+ if (type === 'hyperlink') return {
1051
+ key: ie.key,
1052
+ metadata: {
1053
+ display_name: ie.text,
1054
+ is_trusted: ie.is_trusted,
1055
+ url: ie.url,
1056
+ __typename: 'GenAIInlineLinkItem'
1057
+ }
1058
+ };
1059
+ if (type === 'citation') return {
1060
+ key: ie.key,
1061
+ metadata: {
1062
+ reference_id: ie.reference_id,
1063
+ reference_url: ie.url,
1064
+ reference_title: ie.url,
1065
+ reference_display_name: ie.url,
1066
+ sources: [],
1067
+ __typename: 'GenAISearchCitationItem'
1068
+ }
1069
+ };
1070
+ if (type === 'latex') return {
1071
+ key: ie.key,
1072
+ metadata: {
1073
+ latex_expression: ie.text || '',
1074
+ latex_image: {
1075
+ url: ie.url,
1076
+ width: Number(ie.width) || 100,
1077
+ height: Number(ie.height) || 100
1078
+ },
1079
+ font_height: Number(ie.font_height) || 83.33,
1080
+ padding: Number(ie.padding) || 15,
1081
+ __typename: 'GenAILatexItem'
1082
+ }
1083
+ };
1084
+ return null;
1085
+ }).filter(Boolean) : [];
1086
+ submessages.push({ messageType: 2, messageText: text });
1087
+ sections.push(newLayout('Single', {
1088
+ text,
1089
+ ...(inline_entities.length && { inline_entities }),
1090
+ __typename: 'GenAIMarkdownTextUXPrimitive'
1091
+ }));
1092
+ }
1093
+
1094
+ if (rich.code) {
1095
+ const { language, code } = rich.code;
1096
+ const tok = tokenizer(code, language);
1097
+ submessages.push({ messageType: 5, codeMetadata: { codeLanguage: language, codeBlocks: tok.codeBlock } });
1098
+ sections.push(newLayout('Single', { language, code_blocks: tok.unified_codeBlock, __typename: 'GenAICodeUXPrimitive' }));
1099
+ }
1100
+
1101
+ if (rich.table) {
1102
+ const meta = toTableMetadata(rich.table);
1103
+ submessages.push({ messageType: 4, tableMetadata: { title: meta.title, rows: meta.rows } });
1104
+ sections.push(newLayout('Single', { rows: meta.unified_rows, __typename: 'GenATableUXPrimitive' }));
1105
+ }
1106
+
1107
+ if (rich.image) {
1108
+ const url = rich.image;
1109
+ submessages.push({
1110
+ messageType: 1,
1111
+ gridImageMetadata: {
1112
+ gridImageUrl: { imagePreviewUrl: url },
1113
+ imageUrls: [{ imagePreviewUrl: url, imageHighResUrl: url, sourceUrl: 'https://www.levvicode.cloud/' }]
1114
+ }
1115
+ });
1116
+ sections.push(newLayout('Single', {
1117
+ media: { url, mime_type: 'image/jpeg' },
1118
+ imagine_type: 3,
1119
+ status: { status: 'READY' },
1120
+ __typename: 'GenAIImaginePrimitive'
1121
+ }));
1122
+ }
1123
+
1124
+ if (rich.images) {
1125
+ const urls = Array.isArray(rich.images) ? rich.images : [rich.images];
1126
+ const imageUrls = urls.map(url => ({
1127
+ imagePreviewUrl: url,
1128
+ imageHighResUrl: url,
1129
+ sourceUrl: 'https://www.levvicode.cloud/'
1130
+ }));
1131
+ submessages.push({
1132
+ messageType: 1,
1133
+ gridImageMetadata: {
1134
+ gridImageUrl: { imagePreviewUrl: imageUrls[0]?.imagePreviewUrl },
1135
+ imageUrls
1136
+ }
1137
+ });
1138
+ imageUrls.forEach(({ imagePreviewUrl }) => {
1139
+ sections.push(newLayout('Single', {
1140
+ media: { url: imagePreviewUrl, mime_type: 'image/jpeg' },
1141
+ imagine_type: 3,
1142
+ status: { status: 'READY' },
1143
+ __typename: 'GenAIImaginePrimitive'
1144
+ }));
1145
+ });
1146
+ }
1147
+
1148
+ if (rich.video) {
1149
+ const url = rich.video;
1150
+ sections.push(newLayout('Single', {
1151
+ media: { url, mime_type: 'video/mp4', duration: 10 },
1152
+ imagine_type: 'ANIMATE',
1153
+ status: { status: 'READY' },
1154
+ __typename: 'GenAIImaginePrimitive'
1155
+ }));
1156
+ }
1157
+
1158
+ if (rich.productSingle) {
1159
+ const product = rich.productSingle;
1160
+ sections.push({
1161
+ view_model: {
1162
+ primitive: {
1163
+ title: product.title,
1164
+ brand: product.brand,
1165
+ price: product.price,
1166
+ sale_price: product.sale_price,
1167
+ product_url: product.product_url,
1168
+ image: {
1169
+ url: product.image
1170
+ },
1171
+ additional_images: (product.additional_images || [{ url: product.icon || product.image }]),
1172
+ __typename: "GenAIProductItemCardPrimitive"
1173
+ },
1174
+ __typename: "GenAISingleLayoutViewModel"
1175
+ }
1176
+ });
1177
+ }
1178
+
1179
+ if (rich.productMultiple) {
1180
+ const products = rich.productMultiple;
1181
+ sections.push({
1182
+ view_model: {
1183
+ primitives: products.map(item => ({
1184
+ title: item.title,
1185
+ brand: item.brand,
1186
+ price: item.price,
1187
+ sale_price: item.sale_price,
1188
+ product_url: item.product_url,
1189
+ image: {
1190
+ url: item.image
1191
+ },
1192
+ additional_images: item.additional_images || [{ url: item.icon || item.image }],
1193
+ __typename: "GenAIProductItemCardPrimitive"
1194
+ })),
1195
+ __typename: "GenAIHScrollLayoutViewModel"
1196
+ }
1197
+ });
1198
+ }
1199
+
1200
+ if (rich.post) {
1201
+ const posts = Array.isArray(rich.post) ? rich.post : [rich.post];
1202
+ sections.push(newLayout("HScroll", posts.map(p => ({
1203
+ post_id: p.post_id || randomUUID(),
1204
+ source_app: p.source_app || "INSTAGRAM",
1205
+ post_type: p.post_type || "IMAGE",
1206
+ orientation: p.orientation || "LANDSCAPE",
1207
+ title: p.title || "",
1208
+ subtitle: p.subtitle || "",
1209
+ username: p.username || "",
1210
+ is_verified: !!p.is_verified,
1211
+ profile_picture_url: p.profile_picture_url || "",
1212
+ thumbnail_url: p.thumbnail_url || "",
1213
+ post_caption: p.post_caption || "",
1214
+ post_url: p.post_url || "https://levvicode.cloud",
1215
+ post_deeplink: p.post_deeplink || p.post_url || "https://levvicode.cloud",
1216
+ likes_count: p.likes_count || 0,
1217
+ comments_count: p.comments_count || 0,
1218
+ shares_count: p.shares_count || 0,
1219
+ views_count: p.views_count || 0,
1220
+ footer_label: p.footer_label || "",
1221
+ footer_icon: p.footer_icon || "",
1222
+ is_carousel: posts.length > 1,
1223
+ __typename: "GenAIPostPrimitive"
1224
+ }))));
1225
+ }
1226
+
1227
+ if (rich.reels) {
1228
+ const items = Array.isArray(rich.reels) ? rich.reels : [rich.reels];
1229
+ const reels = items.map(i => ({
1230
+ ...i,
1231
+ _avatar: i.profileIconUrl || i.profile_url || '',
1232
+ _thumbnail: i.thumbnailUrl || i.thumbnail || '',
1233
+ _videoUrl: i.videoUrl || i.url || ''
1234
+ }));
1235
+ submessages.push({
1236
+ messageType: 9,
1237
+ contentItemsMetadata: {
1238
+ contentType: 1,
1239
+ itemsMetadata: reels.map(item => ({
1240
+ reelItem: { title: item.title || '', profileIconUrl: item._avatar, thumbnailUrl: item._thumbnail, videoUrl: item._videoUrl }
1241
+ }))
1242
+ }
1243
+ });
1244
+ reels.forEach((item, idx) => richResponseSources.push({
1245
+ provider: 'LevviCode',
1246
+ thumbnailCDNURL: item._thumbnail,
1247
+ sourceProviderURL: item._videoUrl,
1248
+ sourceQuery: '',
1249
+ faviconCDNURL: item._avatar,
1250
+ citationNumber: idx + 1,
1251
+ sourceTitle: item.title || ''
1252
+ }));
1253
+ sections.push(newLayout('HScroll', reels.map(item => ({
1254
+ reels_url: item._videoUrl,
1255
+ thumbnail_url: item._thumbnail,
1256
+ creator: item.title || '',
1257
+ avatar_url: item._avatar,
1258
+ reels_title: item.reels_title || item.title || '',
1259
+ likes_count: item.likes_count || 0,
1260
+ shares_count: item.shares_count || 0,
1261
+ view_count: item.view_count || 0,
1262
+ reel_source: item.reel_source || 'IG',
1263
+ is_verified: !!(item.is_verified || item.verified),
1264
+ __typename: 'GenAIReelPrimitive'
1265
+ }))));
1266
+ }
1267
+
1268
+ if (rich.sources) {
1269
+ const sourceArr = Array.isArray(rich.sources) ? rich.sources : [rich.sources];
1270
+ const sourceItems = sourceArr.map(s => {
1271
+ if (typeof s === 'object' && !Array.isArray(s)) return s;
1272
+ let iconUrl = s[0];
1273
+ return {
1274
+ source_type: 'THIRD_PARTY',
1275
+ source_display_name: s[2] || '',
1276
+ source_subtitle: 'AI',
1277
+ source_url: s[1] || '',
1278
+ favicon: { url: iconUrl, mime_type: 'image/jpeg', width: 16, height: 16 }
1279
+ };
1280
+ });
1281
+ sections.push(newLayout('Single', { sources: sourceItems, __typename: 'GenAISearchResultPrimitive' }));
1282
+ }
1283
+
1284
+ if (rich.tip) sections.push(newLayout('Single', { text: rich.tip, __typename: 'GenAIMetadataTextPrimitive' }));
1285
+
1286
+ if (rich.suggestions) {
1287
+ const suggest = Array.isArray(rich.suggestions) ? rich.suggestions : [rich.suggestions];
1288
+ sections.push(newLayout('ActionRow', suggest.map(text => ({ prompt_text: text, prompt_type: 'SUGGESTED_PROMPT', __typename: 'GenAIFollowUpSuggestionPillPrimitive' }))));
1289
+ }
1290
+
1291
+ if (rich.footer) sections.push(newLayout('Single', { text: rich.footer, __typename: 'GenAIMetadataTextPrimitive' }));
1292
+
1293
+ const unifiedData = {
1294
+ response_id: randomUUID(),
1295
+ sections: await waitAllPromises(sections)
1296
+ };
1297
+
1298
+ m = {
1299
+ messageContextInfo: {
1300
+ deviceListMetadata: {},
1301
+ deviceListMetadataVersion: 2,
1302
+ botMetadata: {
1303
+ messageDisclaimerText: rich.title || '',
1304
+ richResponseSourcesMetadata: { sources: richResponseSources }
1305
+ }
1306
+ },
1307
+ botForwardedMessage: {
1308
+ message: {
1309
+ richResponseMessage: {
1310
+ messageType: 1,
1311
+ submessages: await waitAllPromises(submessages),
1312
+ unifiedResponse: { data: Buffer.from(JSON.stringify(unifiedData)).toString('base64') },
1313
+ contextInfo: { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid: '0@bot' }, forwardOrigin: 4 }
1314
+ }
1315
+ }
1316
+ }
1317
+ };
1318
+ } else {
1319
+ m = await prepareWAMessageMedia(message, options);
1320
+ }
1321
+
1322
+ if ('buttons' in message && !!message.buttons) {
1323
+ const buttonsMessage = {
1324
+ buttons: message.buttons.map(b => ({ ...b, type: WAProto_1.proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
1325
+ };
1326
+ if ('text' in message) {
1327
+ buttonsMessage.contentText = message.text;
1328
+ buttonsMessage.headerType = ButtonType.EMPTY;
1329
+ } else {
1330
+ if ('caption' in message) {
1331
+ buttonsMessage.contentText = message.caption;
1332
+ }
1333
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1334
+ buttonsMessage.headerType = ButtonType[type];
1335
+ Object.assign(buttonsMessage, m);
1336
+ }
1337
+ if ('title' in message && !!message.title) {
1338
+ buttonsMessage.text = message.title;
1339
+ buttonsMessage.headerType = ButtonType.TEXT;
1340
+ }
1341
+ if ('footer' in message && !!message.footer) {
1342
+ buttonsMessage.footerText = message.footer;
1343
+ }
1344
+ if ('contextInfo' in message && !!message.contextInfo) {
1345
+ buttonsMessage.contextInfo = message.contextInfo;
1346
+ }
1347
+ if ('mentions' in message && !!message.mentions) {
1348
+ buttonsMessage.contextInfo = { mentionedJid: message.mentions };
1349
+ }
1350
+ m = { buttonsMessage };
1351
+ } else if ('templateButtons' in message && !!message.templateButtons) {
1352
+ const msg = {
1353
+ hydratedButtons: message.hasOwnProperty("templateButtons") ? message.templateButtons : message.templateButtons
1354
+ };
1355
+ if ('text' in message) {
1356
+ msg.hydratedContentText = message.text;
1357
+ } else {
1358
+ if ('caption' in message) {
1359
+ msg.hydratedContentText = message.caption;
1360
+ }
1361
+ Object.assign(msg, m);
1362
+ }
1363
+ if ('footer' in message && !!message.footer) {
1364
+ msg.hydratedFooterText = message.footer;
1365
+ }
1366
+ m = {
1367
+ templateMessage: {
1368
+ fourRowTemplate: msg,
1369
+ hydratedTemplate: msg
1370
+ }
1371
+ };
1372
+ }
1373
+ if ('sections' in message && !!message.sections) {
1374
+ const listMessage = {
1375
+ sections: message.sections,
1376
+ buttonText: message.buttonText,
1377
+ title: message.title,
1378
+ footerText: message.footer,
1379
+ description: message.text,
1380
+ listType: WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT
1381
+ };
1382
+ m = { listMessage };
1383
+ }
1384
+ if ('interactiveButtons' in message && !!message.interactiveButtons) {
1385
+ const interactiveMessage = {
1386
+ nativeFlowMessage: Types_1.WAProto.Message.InteractiveMessage.NativeFlowMessage.fromObject({
1387
+ buttons: message.interactiveButtons,
1388
+ })
1389
+ };
1390
+ if ('text' in message) {
1391
+ interactiveMessage.body = {
1392
+ text: message.text
1393
+ };
1394
+ } else if ('caption' in message) {
1395
+ interactiveMessage.body = {
1396
+ text: message.caption
1397
+ };
1398
+ interactiveMessage.header = {
1399
+ title: message.title,
1400
+ subtitle: message.subtitle,
1401
+ hasMediaAttachment: (_j = message === null || message === void 0 ? void 0 : message.media) !== null && _j !== void 0 ? _j : false,
1402
+ };
1403
+ Object.assign(interactiveMessage.header, m);
1404
+ }
1405
+ if ('footer' in message && !!message.footer) {
1406
+ interactiveMessage.footer = {
1407
+ text: message.footer
1408
+ };
1409
+ }
1410
+ if ('title' in message && !!message.title) {
1411
+ interactiveMessage.header = {
1412
+ title: message.title,
1413
+ subtitle: message.subtitle,
1414
+ hasMediaAttachment: (_k = message === null || message === void 0 ? void 0 : message.media) !== null && _k !== void 0 ? _k : false,
1415
+ };
1416
+ Object.assign(interactiveMessage.header, m);
1417
+ }
1418
+ if ('contextInfo' in message && !!message.contextInfo) {
1419
+ interactiveMessage.contextInfo = message.contextInfo;
1420
+ }
1421
+ if ('mentions' in message && !!message.mentions) {
1422
+ interactiveMessage.contextInfo = { mentionedJid: message.mentions };
1423
+ }
1424
+ m = { interactiveMessage };
1425
+ }
1426
+ if ('shop' in message && !!message.shop) {
1427
+ const interactiveMessage = {
1428
+ shopStorefrontMessage: Types_1.WAProto.Message.InteractiveMessage.ShopMessage.fromObject({
1429
+ surface: message.shop,
1430
+ id: message.id
1431
+ })
1432
+ };
1433
+ if ('text' in message) {
1434
+ interactiveMessage.body = {
1435
+ text: message.text
1436
+ };
1437
+ } else if ('caption' in message) {
1438
+ interactiveMessage.body = {
1439
+ text: message.caption
1440
+ };
1441
+ interactiveMessage.header = {
1442
+ title: message.title,
1443
+ subtitle: message.subtitle,
1444
+ hasMediaAttachment: (_l = message === null || message === void 0 ? void 0 : message.media) !== null && _l !== void 0 ? _l : false,
1445
+ };
1446
+ Object.assign(interactiveMessage.header, m);
1447
+ }
1448
+ if ('footer' in message && !!message.footer) {
1449
+ interactiveMessage.footer = {
1450
+ text: message.footer
1451
+ };
1452
+ }
1453
+ if ('title' in message && !!message.title) {
1454
+ interactiveMessage.header = {
1455
+ title: message.title,
1456
+ subtitle: message.subtitle,
1457
+ hasMediaAttachment: (_m = message === null || message === void 0 ? void 0 : message.media) !== null && _m !== void 0 ? _m : false,
1458
+ };
1459
+ Object.assign(interactiveMessage.header, m);
1460
+ }
1461
+ if ('contextInfo' in message && !!message.contextInfo) {
1462
+ interactiveMessage.contextInfo = message.contextInfo;
1463
+ }
1464
+ if ('mentions' in message && !!message.mentions) {
1465
+ interactiveMessage.contextInfo = { mentionedJid: message.mentions };
1466
+ }
1467
+ m = { interactiveMessage };
1468
+ }
1469
+ if ('viewOnce' in message && !!message.viewOnce) {
1470
+ m = { viewOnceMessage: { message: m } };
1471
+ }
1472
+ if ('mentions' in message && ((_o = message.mentions) === null || _o === void 0 ? void 0 : _o.length)) {
1473
+ const [messageType] = Object.keys(m);
1474
+ m[messageType].contextInfo = m[messageType] || {};
1475
+ m[messageType].contextInfo.mentionedJid = message.mentions;
1476
+ }
1477
+ if ('edit' in message) {
1478
+ m = {
1479
+ protocolMessage: {
1480
+ key: message.edit,
1481
+ editedMessage: m,
1482
+ timestampMs: Date.now(),
1483
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1484
+ }
1485
+ };
1486
+ }
1487
+ if ('contextInfo' in message && !!message.contextInfo) {
1488
+ const [messageType] = Object.keys(m);
1489
+ m[messageType] = m[messageType] || {};
1490
+ m[messageType].contextInfo = message.contextInfo;
1491
+ }
1492
+ return Types_1.WAProto.Message.fromObject(m);
1493
+ };
1494
+
1495
+ const generateWAMessageFromContent = (jid, message, options) => {
1496
+ if (!options.timestamp) {
1497
+ options.timestamp = new Date();
1498
+ }
1499
+ const innerMessage = normalizeMessageContent(message);
1500
+ const key = getContentType(innerMessage);
1501
+ const timestamp = (0, generics_1.unixTimestampSeconds)(options.timestamp);
1502
+ const { quoted, userJid } = options;
1503
+
1504
+ if (quoted && !(0, WABinary_1.isJidNewsletter)(jid)) {
1505
+ const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid);
1506
+ let quotedMsg = normalizeMessageContent(quoted.message);
1507
+ const msgType = getContentType(quotedMsg);
1508
+ if (quotedMsg) {
1509
+ quotedMsg = WAProto_1.proto.Message.fromObject({ [msgType]: quotedMsg[msgType] });
1510
+ const quotedContent = quotedMsg[msgType];
1511
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1512
+ delete quotedContent.contextInfo;
1513
+ }
1514
+ const contextInfo = innerMessage[key].contextInfo || {};
1515
+ contextInfo.participant = (0, WABinary_1.jidNormalizedUser)(participant);
1516
+ contextInfo.stanzaId = quoted.key.id;
1517
+ contextInfo.quotedMessage = quotedMsg;
1518
+ if (jid !== quoted.key.remoteJid) {
1519
+ contextInfo.remoteJid = quoted.key.remoteJid;
1520
+ }
1521
+ innerMessage[key].contextInfo = contextInfo;
1522
+ }
1523
+ }
1524
+
1525
+ if (
1526
+ !!(options === null || options === void 0 ? void 0 : options.ephemeralExpiration) &&
1527
+ key !== 'protocolMessage' &&
1528
+ key !== 'ephemeralMessage' &&
1529
+ !(0, WABinary_1.isJidNewsletter)(jid)) {
1530
+ innerMessage[key].contextInfo = {
1531
+ ...(innerMessage[key].contextInfo || {}),
1532
+ expiration: options.ephemeralExpiration || Defaults_1.WA_DEFAULT_EPHEMERAL,
1533
+ };
1534
+ }
1535
+
1536
+ message = Types_1.WAProto.Message.fromObject(message);
1537
+ const messageJSON = {
1538
+ key: {
1539
+ remoteJid: jid,
1540
+ fromMe: true,
1541
+ id: (options === null || options === void 0 ? void 0 : options.messageId) || (0, generics_1.generateMessageIDV2)(),
1542
+ },
1543
+ message: message,
1544
+ messageTimestamp: timestamp,
1545
+ messageStubParameters: [],
1546
+ participant: (0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidStatusBroadcast)(jid) ? userJid : undefined,
1547
+ status: Types_1.WAMessageStatus.PENDING
1548
+ };
1549
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
1550
+ };
1551
+
1552
+ const generateWAMessage = async (jid, content, options) => {
1553
+ var _a;
1554
+ options.logger = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.child({ msgId: options.messageId });
1555
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { newsletter: (0, WABinary_1.isJidNewsletter)(jid), ...options }), options);
1556
+ };
1557
+
1558
+ const getContentType = (content) => {
1559
+ if (content) {
1560
+ const keys = Object.keys(content);
1561
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1562
+ return key;
1563
+ }
1564
+ };
1565
+
1566
+ const normalizeMessageContent = (content) => {
1567
+ if (!content) {
1568
+ return undefined;
1569
+ }
1570
+ for (let i = 0; i < 5; i++) {
1571
+ const inner = getFutureProofMessage(content);
1572
+ if (!inner) {
1573
+ break;
1574
+ }
1575
+ content = inner.message;
1576
+ }
1577
+ return content;
1578
+ function getFutureProofMessage(message) {
1579
+ return ((message === null || message === void 0 ? void 0 : message.ephemeralMessage)
1580
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessage)
1581
+ || (message === null || message === void 0 ? void 0 : message.documentWithCaptionMessage)
1582
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2)
1583
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension)
1584
+ || (message === null || message === void 0 ? void 0 : message.editedMessage)
1585
+ || (message === null || message === void 0 ? void 0 : message.groupMentionedMessage)
1586
+ || (message === null || message === void 0 ? void 0 : message.botInvokeMessage)
1587
+ || (message === null || message === void 0 ? void 0 : message.lottieStickerMessage)
1588
+ || (message === null || message === void 0 ? void 0 : message.eventCoverImage)
1589
+ || (message === null || message === void 0 ? void 0 : message.statusMentionMessage)
1590
+ || (message === null || message === void 0 ? void 0 : message.pollCreationOptionImageMessage)
1591
+ || (message === null || message === void 0 ? void 0 : message.associatedChildMessage)
1592
+ || (message === null || message === void 0 ? void 0 : message.groupStatusMentionMessage)
1593
+ || (message === null || message === void 0 ? void 0 : message.pollCreationMessageV4)
1594
+ || (message === null || message === void 0 ? void 0 : message.pollCreationMessageV5)
1595
+ || (message === null || message === void 0 ? void 0 : message.statusAddYours)
1596
+ || (message === null || message === void 0 ? void 0 : message.groupStatusMessage)
1597
+ || (message === null || message === void 0 ? void 0 : message.limitSharingMessage)
1598
+ || (message === null || message === void 0 ? void 0 : message.botTaskMessage)
1599
+ || (message === null || message === void 0 ? void 0 : message.questionMessage)
1600
+ || (message === null || message === void 0 ? void 0 : message.groupStatusMessageV2)
1601
+ || (message === null || message === void 0 ? void 0 : message.botForwardedMessage));
1602
+ }
1603
+ };
1604
+
1605
+ const extractMessageContent = (content) => {
1606
+ var _a, _b, _c, _d, _e, _f;
1607
+ const extractFromTemplateMessage = (msg) => {
1608
+ if (msg.imageMessage) {
1609
+ return { imageMessage: msg.imageMessage };
1610
+ } else if (msg.documentMessage) {
1611
+ return { documentMessage: msg.documentMessage };
1612
+ } else if (msg.videoMessage) {
1613
+ return { videoMessage: msg.videoMessage };
1614
+ } else if (msg.locationMessage) {
1615
+ return { locationMessage: msg.locationMessage };
1616
+ } else {
1617
+ return {
1618
+ conversation: 'contentText' in msg
1619
+ ? msg.contentText
1620
+ : ('hydratedContentText' in msg ? msg.hydratedContentText : '')
1621
+ };
1622
+ }
1623
+ };
1624
+ content = normalizeMessageContent(content);
1625
+ if (content === null || content === void 0 ? void 0 : content.buttonsMessage) {
1626
+ return extractFromTemplateMessage(content.buttonsMessage);
1627
+ }
1628
+ if ((_a = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _a === void 0 ? void 0 : _a.hydratedFourRowTemplate) {
1629
+ return extractFromTemplateMessage((_b = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _b === void 0 ? void 0 : _b.hydratedFourRowTemplate);
1630
+ }
1631
+ if ((_c = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _c === void 0 ? void 0 : _c.hydratedTemplate) {
1632
+ return extractFromTemplateMessage((_d = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _d === void 0 ? void 0 : _d.hydratedTemplate);
1633
+ }
1634
+ if ((_e = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _e === void 0 ? void 0 : _e.fourRowTemplate) {
1635
+ return extractFromTemplateMessage((_f = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _f === void 0 ? void 0 : _f.fourRowTemplate);
1636
+ }
1637
+ return content;
1638
+ };
1639
+
1640
+ const getDevice = (id) => /^3A.{18}$/.test(id) ? 'ios' :
1641
+ /^3E.{20}$/.test(id) ? 'web' :
1642
+ /^(.{21}|.{32})$/.test(id) ? 'android' :
1643
+ /^(3F|.{18}$)/.test(id) ? 'desktop' :
1644
+ 'unknown';
1645
+
1646
+ const updateMessageWithReceipt = (msg, receipt) => {
1647
+ msg.userReceipt = msg.userReceipt || [];
1648
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1649
+ if (recp) {
1650
+ Object.assign(recp, receipt);
1651
+ } else {
1652
+ msg.userReceipt.push(receipt);
1653
+ }
1654
+ };
1655
+
1656
+ const updateMessageWithReaction = (msg, reaction) => {
1657
+ const authorID = (0, generics_1.getKeyAuthor)(reaction.key);
1658
+ const reactions = (msg.reactions || [])
1659
+ .filter(r => (0, generics_1.getKeyAuthor)(r.key) !== authorID);
1660
+ reaction.text = reaction.text || '';
1661
+ reactions.push(reaction);
1662
+ msg.reactions = reactions;
1663
+ };
1664
+
1665
+ const updateMessageWithPollUpdate = (msg, update) => {
1666
+ var _a, _b;
1667
+ const authorID = (0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey);
1668
+ const reactions = (msg.pollUpdates || [])
1669
+ .filter(r => (0, generics_1.getKeyAuthor)(r.pollUpdateMessageKey) !== authorID);
1670
+ if ((_b = (_a = update.vote) === null || _a === void 0 ? void 0 : _a.selectedOptions) === null || _b === void 0 ? void 0 : _b.length) {
1671
+ reactions.push(update);
1672
+ }
1673
+ msg.pollUpdates = reactions;
1674
+ };
1675
+
1676
+ function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1677
+ var _a, _b, _c;
1678
+ const opts = ((_a = message === null || message === void 0 ? void 0 : message.pollCreationMessage) === null || _a === void 0 ? void 0 : _a.options) || ((_b = message === null || message === void 0 ? void 0 : message.pollCreationMessageV2) === null || _b === void 0 ? void 0 : _b.options) || ((_c = message === null || message === void 0 ? void 0 : message.pollCreationMessageV3) === null || _c === void 0 ? void 0 : _c.options) || [];
1679
+ const voteHashMap = opts.reduce((acc, opt) => {
1680
+ const hash = (0, crypto_2.sha256)(Buffer.from(opt.optionName || '')).toString();
1681
+ acc[hash] = {
1682
+ name: opt.optionName || '',
1683
+ voters: []
1684
+ };
1685
+ return acc;
1686
+ }, {});
1687
+ for (const update of pollUpdates || []) {
1688
+ const { vote } = update;
1689
+ if (!vote) {
1690
+ continue;
1691
+ }
1692
+ for (const option of vote.selectedOptions || []) {
1693
+ const hash = option.toString();
1694
+ let data = voteHashMap[hash];
1695
+ if (!data) {
1696
+ voteHashMap[hash] = {
1697
+ name: 'Unknown',
1698
+ voters: []
1699
+ };
1700
+ data = voteHashMap[hash];
1701
+ }
1702
+ voteHashMap[hash].voters.push((0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey, meId));
1703
+ }
1704
+ }
1705
+ return Object.values(voteHashMap);
1706
+ }
1707
+
1708
+ const aggregateMessageKeysNotFromMe = (keys) => {
1709
+ const keyMap = {};
1710
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1711
+ if (!fromMe) {
1712
+ const uqKey = `${remoteJid}:${participant || ''}`;
1713
+ if (!keyMap[uqKey]) {
1714
+ keyMap[uqKey] = {
1715
+ jid: remoteJid,
1716
+ participant: participant,
1717
+ messageIds: []
1718
+ };
1719
+ }
1720
+ keyMap[uqKey].messageIds.push(id);
1721
+ }
1722
+ }
1723
+ return Object.values(keyMap);
1724
+ };
1725
+
1726
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1727
+
1728
+ const downloadMediaMessage = async (message, type, options, ctx) => {
1729
+ const result = await downloadMsg()
1730
+ .catch(async (error) => {
1731
+ var _a;
1732
+ if (ctx) {
1733
+ if (axios_1.default.isAxiosError(error)) {
1734
+ if (REUPLOAD_REQUIRED_STATUS.includes((_a = error.response) === null || _a === void 0 ? void 0 : _a.status)) {
1735
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1736
+ message = await ctx.reuploadRequest(message);
1737
+ const result = await downloadMsg();
1738
+ return result;
1739
+ }
1740
+ }
1741
+ }
1742
+ throw error;
1743
+ });
1744
+ return result;
1745
+ async function downloadMsg() {
1746
+ const mContent = extractMessageContent(message.message);
1747
+ if (!mContent) {
1748
+ throw new boom_1.Boom('No message present', { statusCode: 400, data: message });
1749
+ }
1750
+ const contentType = getContentType(mContent);
1751
+ let mediaType = contentType === null || contentType === void 0 ? void 0 : contentType.replace('Message', '');
1752
+ const media = mContent[contentType];
1753
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1754
+ throw new boom_1.Boom(`"${contentType}" message is not a media message`);
1755
+ }
1756
+ let download;
1757
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1758
+ download = {
1759
+ directPath: media.thumbnailDirectPath,
1760
+ mediaKey: media.mediaKey
1761
+ };
1762
+ mediaType = 'thumbnail-link';
1763
+ } else {
1764
+ download = media;
1765
+ }
1766
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(download, mediaType, options);
1767
+ if (type === 'buffer') {
1768
+ const bufferArray = [];
1769
+ for await (const chunk of stream) {
1770
+ bufferArray.push(chunk);
1771
+ }
1772
+ return Buffer.concat(bufferArray);
1773
+ }
1774
+ return stream;
1775
+ }
1776
+ };
1777
+
1778
+ const assertMediaContent = (content) => {
1779
+ content = extractMessageContent(content);
1780
+ const mediaContent = (content === null || content === void 0 ? void 0 : content.documentMessage)
1781
+ || (content === null || content === void 0 ? void 0 : content.imageMessage)
1782
+ || (content === null || content === void 0 ? void 0 : content.videoMessage)
1783
+ || (content === null || content === void 0 ? void 0 : content.audioMessage)
1784
+ || (content === null || content === void 0 ? void 0 : content.stickerMessage);
1785
+ if (!mediaContent) {
1786
+ throw new boom_1.Boom('given message is not a media message', { statusCode: 400, data: content });
1787
+ }
1788
+ return mediaContent;
1789
+ };
1790
+
1791
+ const toJid = (id) => {
1792
+ if (!id) return '';
1793
+ if (id.endsWith('@lid')) return id.replace('@lid', '@s.whatsapp.net');
1794
+ if (id.includes('@')) return id;
1795
+ return `${id}@s.whatsapp.net`;
1796
+ };
1797
+
1798
+ const getSenderLid = (message) => {
1799
+ const sender = message.key.participant || message.key.remoteJid;
1800
+ const user = (0, WABinary_1.jidDecode)(sender)?.user || '';
1801
+ const lid = (0, WABinary_1.jidEncode)(user, 'lid');
1802
+ console.log('sender lid:', lid);
1803
+ return { jid: sender, lid };
1804
+ };
1805
+
1806
+ exports.extractUrlFromText = extractUrlFromText;
1807
+ exports.generateLinkPreviewIfRequired = generateLinkPreviewIfRequired;
1808
+ exports.prepareWAMessageMedia = prepareWAMessageMedia;
1809
+ exports.prepareDisappearingMessageSettingContent = prepareDisappearingMessageSettingContent;
1810
+ exports.generateForwardMessageContent = generateForwardMessageContent;
1811
+ exports.generateWAMessageContent = generateWAMessageContent;
1812
+ exports.generateWAMessageFromContent = generateWAMessageFromContent;
1813
+ exports.generateWAMessage = generateWAMessage;
1814
+ exports.getContentType = getContentType;
1815
+ exports.normalizeMessageContent = normalizeMessageContent;
1816
+ exports.extractMessageContent = extractMessageContent;
1817
+ exports.getDevice = getDevice;
1818
+ exports.updateMessageWithReceipt = updateMessageWithReceipt;
1819
+ exports.updateMessageWithReaction = updateMessageWithReaction;
1820
+ exports.updateMessageWithPollUpdate = updateMessageWithPollUpdate;
1821
+ exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
1822
+ exports.aggregateMessageKeysNotFromMe = aggregateMessageKeysNotFromMe;
1823
+ exports.downloadMediaMessage = downloadMediaMessage;
1824
+ exports.assertMediaContent = assertMediaContent;
1825
+ exports.toJid = toJid;
1826
+ exports.getSenderLid = getSenderLid;
1827
+ exports.prepareAlbumMessageContent = prepareAlbumMessageContent;
1828
+ exports.processLocationThumbnail = processLocationThumbnail;