@vinzsocket/baileys 3.3.0 → 3.3.2

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.
@@ -0,0 +1,1144 @@
1
+ import { proto } from "../../WAProto/index.js";
2
+ import { generateMessageIDV2 } from "./generics.js";
3
+ import { randomBytes, randomUUID } from "crypto";
4
+ export const JS_KEYWORDS = new Set([
5
+ "import",
6
+ "export",
7
+ "from",
8
+ "default",
9
+ "as",
10
+ "const",
11
+ "let",
12
+ "var",
13
+ "function",
14
+ "class",
15
+ "extends",
16
+ "new",
17
+ "return",
18
+ "if",
19
+ "else",
20
+ "for",
21
+ "while",
22
+ "do",
23
+ "switch",
24
+ "case",
25
+ "break",
26
+ "continue",
27
+ "try",
28
+ "catch",
29
+ "finally",
30
+ "throw",
31
+ "async",
32
+ "await",
33
+ "yield",
34
+ "typeof",
35
+ "instanceof",
36
+ "in",
37
+ "of",
38
+ "delete",
39
+ "void",
40
+ "true",
41
+ "false",
42
+ "null",
43
+ "undefined",
44
+ "NaN",
45
+ "Infinity",
46
+ "this",
47
+ "super",
48
+ "static",
49
+ "get",
50
+ "set",
51
+ "debugger",
52
+ "with",
53
+ ]);
54
+ export const PYTHON_KEYWORDS = new Set([
55
+ "import",
56
+ "from",
57
+ "as",
58
+ "def",
59
+ "class",
60
+ "return",
61
+ "if",
62
+ "elif",
63
+ "else",
64
+ "for",
65
+ "while",
66
+ "break",
67
+ "continue",
68
+ "try",
69
+ "except",
70
+ "finally",
71
+ "raise",
72
+ "with",
73
+ "yield",
74
+ "lambda",
75
+ "pass",
76
+ "del",
77
+ "global",
78
+ "nonlocal",
79
+ "assert",
80
+ "True",
81
+ "False",
82
+ "None",
83
+ "and",
84
+ "or",
85
+ "not",
86
+ "in",
87
+ "is",
88
+ "async",
89
+ "await",
90
+ "self",
91
+ "print",
92
+ ]);
93
+ export const GO_KEYWORDS = new Set([
94
+ "func",
95
+ "package",
96
+ "import",
97
+ "return",
98
+ "if",
99
+ "else",
100
+ "for",
101
+ "switch",
102
+ "case",
103
+ "break",
104
+ "continue",
105
+ "type",
106
+ "struct",
107
+ "interface",
108
+ "map",
109
+ "chan",
110
+ "go",
111
+ "defer",
112
+ "const",
113
+ "var",
114
+ "range",
115
+ "true",
116
+ "false",
117
+ "nil",
118
+ "select",
119
+ "default",
120
+ "fallthrough",
121
+ ]);
122
+ export const LUA_KEYWORDS = new Set([
123
+ "function",
124
+ "end",
125
+ "if",
126
+ "then",
127
+ "else",
128
+ "elseif",
129
+ "for",
130
+ "while",
131
+ "do",
132
+ "local",
133
+ "return",
134
+ "true",
135
+ "false",
136
+ "nil",
137
+ "repeat",
138
+ "until",
139
+ "in",
140
+ "not",
141
+ "and",
142
+ "or",
143
+ ]);
144
+ export const BASH_KEYWORDS = new Set([
145
+ "if",
146
+ "then",
147
+ "else",
148
+ "elif",
149
+ "fi",
150
+ "for",
151
+ "while",
152
+ "do",
153
+ "done",
154
+ "case",
155
+ "esac",
156
+ "echo",
157
+ "export",
158
+ "return",
159
+ "in",
160
+ "function",
161
+ "local",
162
+ "read",
163
+ "set",
164
+ "unset",
165
+ "true",
166
+ "false",
167
+ "exit",
168
+ "source",
169
+ "alias",
170
+ "declare",
171
+ "typeset",
172
+ ]);
173
+ export const LANGUAGE_KEYWORDS = {
174
+ javascript: JS_KEYWORDS,
175
+ typescript: JS_KEYWORDS,
176
+ js: JS_KEYWORDS,
177
+ ts: JS_KEYWORDS,
178
+ python: PYTHON_KEYWORDS,
179
+ py: PYTHON_KEYWORDS,
180
+ go: GO_KEYWORDS,
181
+ golang: GO_KEYWORDS,
182
+ lua: LUA_KEYWORDS,
183
+ bash: BASH_KEYWORDS,
184
+ sh: BASH_KEYWORDS,
185
+ shell: BASH_KEYWORDS,
186
+ };
187
+ export var CodeHighlightType;
188
+ (function (CodeHighlightType) {
189
+ CodeHighlightType[(CodeHighlightType["DEFAULT"] = 0)] = "DEFAULT";
190
+ CodeHighlightType[(CodeHighlightType["KEYWORD"] = 1)] = "KEYWORD";
191
+ CodeHighlightType[(CodeHighlightType["METHOD"] = 2)] = "METHOD";
192
+ CodeHighlightType[(CodeHighlightType["STRING"] = 3)] = "STRING";
193
+ CodeHighlightType[(CodeHighlightType["NUMBER"] = 4)] = "NUMBER";
194
+ CodeHighlightType[(CodeHighlightType["COMMENT"] = 5)] = "COMMENT";
195
+ })(CodeHighlightType || (CodeHighlightType = {}));
196
+ export var RichSubMessageType;
197
+ (function (RichSubMessageType) {
198
+ RichSubMessageType[(RichSubMessageType["UNKNOWN"] = 0)] = "UNKNOWN";
199
+ RichSubMessageType[(RichSubMessageType["GRID_IMAGE"] = 1)] = "GRID_IMAGE";
200
+ RichSubMessageType[(RichSubMessageType["TEXT"] = 2)] = "TEXT";
201
+ RichSubMessageType[(RichSubMessageType["INLINE_IMAGE"] = 3)] = "INLINE_IMAGE";
202
+ RichSubMessageType[(RichSubMessageType["TABLE"] = 4)] = "TABLE";
203
+ RichSubMessageType[(RichSubMessageType["CODE"] = 5)] = "CODE";
204
+ RichSubMessageType[(RichSubMessageType["DYNAMIC"] = 6)] = "DYNAMIC";
205
+ RichSubMessageType[(RichSubMessageType["MAP"] = 7)] = "MAP";
206
+ RichSubMessageType[(RichSubMessageType["LATEX"] = 8)] = "LATEX";
207
+ RichSubMessageType[(RichSubMessageType["CONTENT_ITEMS"] = 9)] =
208
+ "CONTENT_ITEMS";
209
+ })(RichSubMessageType || (RichSubMessageType = {}));
210
+ export const tokenizeCode = (codeStr, language = "javascript") => {
211
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS;
212
+ const blocks = [];
213
+ const lines = codeStr.split("\n");
214
+ for (let li = 0; li < lines.length; li++) {
215
+ const line = lines[li];
216
+ const isLast = li === lines.length - 1;
217
+ const nl = isLast ? "" : "\n";
218
+ if (!line.trim()) {
219
+ blocks.push({
220
+ highlightType: CodeHighlightType.DEFAULT,
221
+ codeContent: line + nl,
222
+ });
223
+ continue;
224
+ }
225
+ if (line.trim().startsWith("//") || line.trim().startsWith("#")) {
226
+ blocks.push({
227
+ highlightType: CodeHighlightType.COMMENT,
228
+ codeContent: line + nl,
229
+ });
230
+ continue;
231
+ }
232
+ const regex =
233
+ /(\/\/.*$|#.*$)|(["'`](?:[^"'`\\]|\\.)*["'`])|(\b\d+(?:\.\d+)?\b)|(\b[a-zA-Z_$][\w$]*\b)|([^\s\w$"'`]+)|(\s+)/g;
234
+ let match;
235
+ const tokens = [];
236
+ while ((match = regex.exec(line)) !== null) {
237
+ const val = match[0];
238
+ if (match[1]) {
239
+ tokens.push({
240
+ highlightType: CodeHighlightType.COMMENT,
241
+ codeContent: val,
242
+ });
243
+ } else if (match[2]) {
244
+ tokens.push({
245
+ highlightType: CodeHighlightType.STRING,
246
+ codeContent: val,
247
+ });
248
+ } else if (match[3]) {
249
+ tokens.push({
250
+ highlightType: CodeHighlightType.NUMBER,
251
+ codeContent: val,
252
+ });
253
+ } else if (match[4]) {
254
+ if (keywords.has(val)) {
255
+ tokens.push({
256
+ highlightType: CodeHighlightType.KEYWORD,
257
+ codeContent: val,
258
+ });
259
+ } else {
260
+ const after = line.slice(regex.lastIndex).trimStart();
261
+ if (after.startsWith("(")) {
262
+ tokens.push({
263
+ highlightType: CodeHighlightType.METHOD,
264
+ codeContent: val,
265
+ });
266
+ } else {
267
+ tokens.push({
268
+ highlightType: CodeHighlightType.DEFAULT,
269
+ codeContent: val,
270
+ });
271
+ }
272
+ }
273
+ } else {
274
+ tokens.push({
275
+ highlightType: CodeHighlightType.DEFAULT,
276
+ codeContent: val,
277
+ });
278
+ }
279
+ }
280
+ if (tokens.length === 0) {
281
+ blocks.push({
282
+ highlightType: CodeHighlightType.DEFAULT,
283
+ codeContent: line + nl,
284
+ });
285
+ continue;
286
+ }
287
+ const merged = [];
288
+ for (const t of tokens) {
289
+ const prev = merged.length > 0 ? merged[merged.length - 1] : undefined;
290
+ if (prev && prev.highlightType === t.highlightType) {
291
+ prev.codeContent += t.codeContent;
292
+ } else {
293
+ merged.push({ ...t });
294
+ }
295
+ }
296
+ if (merged.length > 0) {
297
+ merged[merged.length - 1].codeContent += nl;
298
+ }
299
+ blocks.push(...merged);
300
+ }
301
+ return blocks;
302
+ };
303
+ export const buildRichContextInfo = (quoted) => {
304
+ const ctxInfo = {
305
+ forwardingScore: 1,
306
+ isForwarded: true,
307
+ forwardedAiBotMessageInfo: { botJid: "867051314767696@bot" },
308
+ forwardOrigin: 4,
309
+ };
310
+ if (quoted?.key) {
311
+ ctxInfo.stanzaId = quoted.key.id;
312
+ ctxInfo.participant =
313
+ quoted.key.participant || quoted.sender || quoted.key.remoteJid;
314
+ ctxInfo.quotedMessage = quoted.message;
315
+ }
316
+ return ctxInfo;
317
+ };
318
+ export const buildBotForwardedMessage = (
319
+ submessages,
320
+ contextInfo,
321
+ unifiedResponse,
322
+ ) => {
323
+ const richResponse = {
324
+ messageType: 1,
325
+ submessages,
326
+ contextInfo,
327
+ };
328
+ if (unifiedResponse) {
329
+ richResponse.unifiedResponse = unifiedResponse;
330
+ }
331
+ return {
332
+ botForwardedMessage: {
333
+ message: {
334
+ richResponseMessage: richResponse,
335
+ },
336
+ },
337
+ };
338
+ };
339
+ export const generateTableContent = (
340
+ title,
341
+ headers,
342
+ rows,
343
+ quoted,
344
+ options = {},
345
+ ) => {
346
+ const { footer, headerText } = options;
347
+ const tableRows = [
348
+ { items: headers, isHeading: true },
349
+ ...rows.map((row) => ({ items: row.map(String) })),
350
+ ];
351
+ const submessages = [];
352
+ if (headerText) {
353
+ submessages.push({ messageType: 2, messageText: headerText });
354
+ }
355
+ submessages.push({
356
+ messageType: 4,
357
+ tableMetadata: { title, rows: tableRows },
358
+ });
359
+ if (footer) {
360
+ submessages.push({ messageType: 2, messageText: footer });
361
+ }
362
+ const ctxInfo = buildRichContextInfo(quoted);
363
+ return {
364
+ message: buildBotForwardedMessage(submessages, ctxInfo),
365
+ messageId: generateMessageIDV2(),
366
+ };
367
+ };
368
+ export const generateListContent = (title, items, quoted, options = {}) => {
369
+ const { footer, headerText } = options;
370
+ const tableRows = items.map((item) => ({
371
+ items: Array.isArray(item) ? item.map(String) : [String(item)],
372
+ }));
373
+ const submessages = [];
374
+ if (headerText) {
375
+ submessages.push({ messageType: 2, messageText: headerText });
376
+ }
377
+ submessages.push({
378
+ messageType: 4,
379
+ tableMetadata: { title, rows: tableRows },
380
+ });
381
+ if (footer) {
382
+ submessages.push({ messageType: 2, messageText: footer });
383
+ }
384
+ const ctxInfo = buildRichContextInfo(quoted);
385
+ return {
386
+ message: buildBotForwardedMessage(submessages, ctxInfo),
387
+ messageId: generateMessageIDV2(),
388
+ };
389
+ };
390
+ export const generateCodeBlockContent = (code, quoted, options = {}) => {
391
+ const { title, footer, language = "javascript" } = options;
392
+ const submessages = [];
393
+ if (title) {
394
+ submessages.push({ messageType: 2, messageText: title });
395
+ }
396
+ submessages.push({
397
+ messageType: 5,
398
+ codeMetadata: {
399
+ codeLanguage: language,
400
+ codeBlocks: tokenizeCode(code, language),
401
+ },
402
+ });
403
+ if (footer) {
404
+ submessages.push({ messageType: 2, messageText: footer });
405
+ }
406
+ const ctxInfo = buildRichContextInfo(quoted);
407
+ return {
408
+ message: buildBotForwardedMessage(submessages, ctxInfo),
409
+ messageId: generateMessageIDV2(),
410
+ };
411
+ };
412
+ export const generateLatexContent = (quoted, options) => {
413
+ const { text, expressions, headerText, footer } = options;
414
+ const submessages = [];
415
+ if (headerText) {
416
+ submessages.push({ messageType: 2, messageText: headerText });
417
+ }
418
+ const latexExpressions = expressions.map((expr) => {
419
+ const entry = {
420
+ latexExpression: expr.latexExpression,
421
+ url: expr.url,
422
+ width: expr.width,
423
+ height: expr.height,
424
+ };
425
+ if (expr.fontHeight !== undefined) entry.fontHeight = expr.fontHeight;
426
+ if (expr.imageTopPadding !== undefined)
427
+ entry.imageTopPadding = expr.imageTopPadding;
428
+ if (expr.imageLeadingPadding !== undefined)
429
+ entry.imageLeadingPadding = expr.imageLeadingPadding;
430
+ if (expr.imageBottomPadding !== undefined)
431
+ entry.imageBottomPadding = expr.imageBottomPadding;
432
+ if (expr.imageTrailingPadding !== undefined)
433
+ entry.imageTrailingPadding = expr.imageTrailingPadding;
434
+ return entry;
435
+ });
436
+ submessages.push({
437
+ messageType: 8,
438
+ latexMetadata: {
439
+ text: text || "",
440
+ expressions: latexExpressions,
441
+ },
442
+ });
443
+ if (footer) {
444
+ submessages.push({ messageType: 2, messageText: footer });
445
+ }
446
+ const ctxInfo = buildRichContextInfo(quoted);
447
+ return {
448
+ message: buildBotForwardedMessage(submessages, ctxInfo),
449
+ messageId: generateMessageIDV2(),
450
+ };
451
+ };
452
+ export const generateLatexImageContent = async (
453
+ quoted,
454
+ options,
455
+ uploadFn,
456
+ renderLatexToPng,
457
+ ) => {
458
+ const { text, expressions, headerText, footer } = options;
459
+ const submessages = [];
460
+ if (headerText) {
461
+ submessages.push({ messageType: 2, messageText: headerText });
462
+ }
463
+ const latexExpressions = await Promise.all(
464
+ expressions.map(async (expr) => {
465
+ const { buffer, width, height } = await renderLatexToPng(
466
+ expr.latexExpression,
467
+ );
468
+ const uploadResult = await uploadFn(buffer, "image");
469
+ const imageUrl = uploadResult.url || uploadResult.directPath;
470
+ return {
471
+ latexExpression: expr.latexExpression,
472
+ url: imageUrl,
473
+ width,
474
+ height,
475
+ };
476
+ }),
477
+ );
478
+ submessages.push({
479
+ messageType: 8,
480
+ latexMetadata: {
481
+ text: text || "",
482
+ expressions: latexExpressions,
483
+ },
484
+ });
485
+ if (footer) {
486
+ submessages.push({ messageType: 2, messageText: footer });
487
+ }
488
+ const ctxInfo = buildRichContextInfo(quoted);
489
+ return {
490
+ message: buildBotForwardedMessage(submessages, ctxInfo),
491
+ messageId: generateMessageIDV2(),
492
+ };
493
+ };
494
+ export const generateLatexInlineImageContent = async (
495
+ quoted,
496
+ options,
497
+ uploadFn,
498
+ renderLatexToPng,
499
+ ) => {
500
+ const { text, expressions, headerText, footer } = options;
501
+ const submessages = [];
502
+ if (headerText) {
503
+ submessages.push({ messageType: 2, messageText: headerText });
504
+ }
505
+ if (text) {
506
+ submessages.push({ messageType: 2, messageText: text });
507
+ }
508
+ for (const expr of expressions) {
509
+ const { buffer, width, height } = await renderLatexToPng(
510
+ expr.latexExpression,
511
+ );
512
+ const uploadResult = await uploadFn(buffer, "image");
513
+ const imageUrl = uploadResult.url || uploadResult.directPath;
514
+ submessages.push({
515
+ messageType: 3,
516
+ imageMetadata: {
517
+ imageUrl: {
518
+ imagePreviewUrl: imageUrl,
519
+ imageHighResUrl: imageUrl,
520
+ },
521
+ imageText: expr.latexExpression,
522
+ alignment: 2,
523
+ },
524
+ });
525
+ }
526
+ if (footer) {
527
+ submessages.push({ messageType: 2, messageText: footer });
528
+ }
529
+ const ctxInfo = buildRichContextInfo(quoted);
530
+ return {
531
+ message: buildBotForwardedMessage(submessages, ctxInfo),
532
+ messageId: generateMessageIDV2(),
533
+ };
534
+ };
535
+ export const captureUnifiedResponse = (msg) => {
536
+ const botFwd = msg?.botForwardedMessage?.message;
537
+ if (!botFwd) return null;
538
+ const rich = botFwd.richResponseMessage;
539
+ if (!rich?.unifiedResponse?.data) return null;
540
+ return {
541
+ unifiedResponse: { data: rich.unifiedResponse.data },
542
+ submessages: rich.submessages || [],
543
+ contextInfo: rich.contextInfo || {},
544
+ };
545
+ };
546
+ export const generateUnifiedResponseContent = (quoted, captured) => {
547
+ const ctxInfo = buildRichContextInfo(quoted);
548
+ return {
549
+ message: buildBotForwardedMessage(
550
+ captured.submessages,
551
+ ctxInfo,
552
+ captured.unifiedResponse,
553
+ ),
554
+ messageId: generateMessageIDV2(),
555
+ };
556
+ };
557
+ export const generateRichMessageContent = (submessages, quoted) => {
558
+ const ctxInfo = buildRichContextInfo(quoted);
559
+ return {
560
+ message: buildBotForwardedMessage(submessages, ctxInfo),
561
+ messageId: generateMessageIDV2(),
562
+ };
563
+ };
564
+ const HIGHLIGHT_TYPE_MAP = {
565
+ 0: "DEFAULT",
566
+ 1: "KEYWORD",
567
+ 2: "METHOD",
568
+ 3: "STR",
569
+ 4: "NUMBER",
570
+ 5: "COMMENT",
571
+ };
572
+ export const tokenizeCodeV2 = (code, language = "javascript") => {
573
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS;
574
+ const tokens = [];
575
+ let i = 0;
576
+ const n = code.length;
577
+ const push = (codeContent, highlightType) => {
578
+ if (!codeContent) return;
579
+ const last = tokens[tokens.length - 1];
580
+ if (last && last.highlightType === highlightType) {
581
+ last.codeContent += codeContent;
582
+ } else {
583
+ tokens.push({ codeContent, highlightType });
584
+ }
585
+ };
586
+ const isWordStart = (c) => /[a-zA-Z_$]/.test(c);
587
+ const isWord = (c) => /[a-zA-Z0-9_$]/.test(c);
588
+ const isNum = (c) => /[0-9]/.test(c);
589
+ while (i < n) {
590
+ const c = code[i];
591
+ if (c === "\n" || c === "\t" || c === " " || /\s/.test(c)) {
592
+ let s = i;
593
+ while (i < n && /\s/.test(code[i])) i++;
594
+ push(code.slice(s, i), 0);
595
+ continue;
596
+ }
597
+ if (c === "/" && code[i + 1] === "/") {
598
+ let s = i;
599
+ i += 2;
600
+ while (i < n && code[i] !== "\n") i++;
601
+ push(code.slice(s, i), 5);
602
+ continue;
603
+ }
604
+ if (c === "/" && code[i + 1] === "*") {
605
+ let s = i;
606
+ i += 2;
607
+ while (i < n - 1 && !(code[i] === "*" && code[i + 1] === "/")) i++;
608
+ i += 2;
609
+ push(code.slice(s, i), 5);
610
+ continue;
611
+ }
612
+ if (
613
+ c === "#" &&
614
+ (language === "python" ||
615
+ language === "py" ||
616
+ language === "bash" ||
617
+ language === "sh" ||
618
+ language === "shell" ||
619
+ language === "lua")
620
+ ) {
621
+ let s = i;
622
+ i++;
623
+ while (i < n && code[i] !== "\n") i++;
624
+ push(code.slice(s, i), 5);
625
+ continue;
626
+ }
627
+ if (c === '"' || c === "'" || c === "`") {
628
+ let s = i;
629
+ const q = c;
630
+ i++;
631
+ while (i < n) {
632
+ if (code[i] === "\\" && i + 1 < n) {
633
+ i += 2;
634
+ } else if (code[i] === q) {
635
+ i++;
636
+ break;
637
+ } else i++;
638
+ }
639
+ push(code.slice(s, i), 3);
640
+ continue;
641
+ }
642
+ if (isNum(c)) {
643
+ let s = i;
644
+ while (i < n && /[0-9.xXa-fA-FeEbBoO_]/.test(code[i])) i++;
645
+ push(code.slice(s, i), 4);
646
+ continue;
647
+ }
648
+ if (isWordStart(c)) {
649
+ let s = i;
650
+ while (i < n && isWord(code[i])) i++;
651
+ const word = code.slice(s, i);
652
+ let type = 0;
653
+ if (keywords.has(word)) {
654
+ type = 1;
655
+ } else {
656
+ let j = i;
657
+ while (j < n && /\s/.test(code[j])) j++;
658
+ if (code[j] === "(") type = 2;
659
+ }
660
+ push(word, type);
661
+ continue;
662
+ }
663
+ push(c, 0);
664
+ i++;
665
+ }
666
+ return {
667
+ codeBlock: tokens,
668
+ unified_codeBlock: tokens.map((t) => ({
669
+ content: t.codeContent,
670
+ type: HIGHLIGHT_TYPE_MAP[t.highlightType] || "DEFAULT",
671
+ })),
672
+ };
673
+ };
674
+ export const toTableMetadataV2 = (arr) => {
675
+ if (!Array.isArray(arr) || arr.length === 0) {
676
+ throw new Error("Input must be a non-empty array");
677
+ }
678
+ const [title, headerStr, ...rest] = arr;
679
+ const splitCols = (str) => {
680
+ if (typeof str !== "string") return [];
681
+ return str.includes("|")
682
+ ? str.split("|").map((s) => s.trim())
683
+ : str.split(",").map((s) => s.trim());
684
+ };
685
+ const splitRows = (str) => {
686
+ if (typeof str !== "string") return [];
687
+ return str.split(";;").map((row) => splitCols(row));
688
+ };
689
+ const header = splitCols(headerStr);
690
+ const parsedRows = rest.flatMap(splitRows);
691
+ const maxLen = Math.max(header.length, ...parsedRows.map((r) => r.length));
692
+ const unified_rows = [
693
+ {
694
+ is_header: true,
695
+ cells: [...header, ...Array(maxLen - header.length).fill("")],
696
+ },
697
+ ...parsedRows.map((cells) => ({
698
+ is_header: false,
699
+ cells: [...cells, ...Array(maxLen - cells.length).fill("")],
700
+ })),
701
+ ];
702
+ const rows = unified_rows.map((r) => ({
703
+ items: r.cells,
704
+ ...(r.is_header ? { isHeading: true } : {}),
705
+ }));
706
+ return { title, rows, unified_rows };
707
+ };
708
+ export const generateTableContentV2 = (table, quoted, options = {}) => {
709
+ const { title, footer, headerText, text } = options;
710
+ const { unified_rows } = toTableMetadataV2(table);
711
+ const sections = [];
712
+ if (headerText || title) {
713
+ const headingText = headerText || title;
714
+ sections.push({
715
+ view_model: {
716
+ primitive: {
717
+ text: headingText,
718
+ __typename: "GenAIMarkdownTextUXPrimitive",
719
+ },
720
+ __typename: "GenAISingleLayoutViewModel",
721
+ },
722
+ });
723
+ }
724
+ if (text) {
725
+ sections.push({
726
+ view_model: {
727
+ primitive: {
728
+ text,
729
+ __typename: "GenAIMarkdownTextUXPrimitive",
730
+ },
731
+ __typename: "GenAISingleLayoutViewModel",
732
+ },
733
+ });
734
+ }
735
+ sections.push({
736
+ view_model: {
737
+ primitive: {
738
+ rows: unified_rows,
739
+ __typename: "GenATableUXPrimitive",
740
+ },
741
+ __typename: "GenAISingleLayoutViewModel",
742
+ },
743
+ });
744
+ if (footer) {
745
+ sections.push({
746
+ view_model: {
747
+ primitive: {
748
+ text: footer,
749
+ __typename: "GenAIMarkdownTextUXPrimitive",
750
+ },
751
+ __typename: "GenAISingleLayoutViewModel",
752
+ },
753
+ });
754
+ }
755
+ const responseId = randomUUID();
756
+ const unifiedData = {
757
+ response_id: responseId,
758
+ sections,
759
+ };
760
+ const base64Data = Buffer.from(JSON.stringify(unifiedData)).toString(
761
+ "base64",
762
+ );
763
+ const ctxInfo = {
764
+ forwardingScore: 2,
765
+ isForwarded: true,
766
+ forwardedAiBotMessageInfo: { botJid: "259786046210223@bot" },
767
+ forwardOrigin: 4,
768
+ botMessageSharingInfo: {
769
+ botEntryPointOrigin: 1,
770
+ forwardScore: 2,
771
+ },
772
+ };
773
+ if (quoted?.key) {
774
+ ctxInfo.stanzaId = quoted.key.id;
775
+ ctxInfo.participant =
776
+ quoted.key.participant || quoted.sender || quoted.key.remoteJid;
777
+ ctxInfo.quotedMessage = quoted.message;
778
+ }
779
+ const content = {
780
+ messageContextInfo: {
781
+ threadId: [],
782
+ deviceListMetadata: {
783
+ senderKeyIndexes: [],
784
+ recipientKeyIndexes: [],
785
+ recipientKeyHash: "",
786
+ recipientTimestamp: Math.floor(Date.now() / 1000),
787
+ },
788
+ deviceListMetadataVersion: 2,
789
+ messageSecret: randomBytes(32),
790
+ },
791
+ botForwardedMessage: {
792
+ message: {
793
+ richResponseMessage: {
794
+ submessages: [],
795
+ messageType: 1,
796
+ unifiedResponse: { data: base64Data },
797
+ contextInfo: ctxInfo,
798
+ },
799
+ },
800
+ },
801
+ };
802
+ return {
803
+ message: content,
804
+ messageId: generateMessageIDV2(),
805
+ };
806
+ };
807
+ export const generateCodeBlockContentV2 = (code, quoted, options = {}) => {
808
+ const { title, footer, language = "javascript", text } = options;
809
+ const { unified_codeBlock } = tokenizeCodeV2(code, language);
810
+ const sections = [];
811
+ if (text) {
812
+ sections.push({
813
+ view_model: {
814
+ primitive: {
815
+ text,
816
+ __typename: "GenAIMarkdownTextUXPrimitive",
817
+ },
818
+ __typename: "GenAISingleLayoutViewModel",
819
+ },
820
+ });
821
+ }
822
+ sections.push({
823
+ view_model: {
824
+ primitive: {
825
+ language,
826
+ code_blocks: unified_codeBlock,
827
+ __typename: "GenAICodeUXPrimitive",
828
+ },
829
+ __typename: "GenAISingleLayoutViewModel",
830
+ },
831
+ });
832
+ if (footer) {
833
+ sections.push({
834
+ view_model: {
835
+ primitive: {
836
+ text: footer,
837
+ __typename: "GenAIMarkdownTextUXPrimitive",
838
+ },
839
+ __typename: "GenAISingleLayoutViewModel",
840
+ },
841
+ });
842
+ }
843
+ const responseId = randomUUID();
844
+ const unifiedData = {
845
+ response_id: responseId,
846
+ sections,
847
+ };
848
+ const base64Data = Buffer.from(JSON.stringify(unifiedData)).toString(
849
+ "base64",
850
+ );
851
+ const ctxInfo = {
852
+ mentionedJid: [],
853
+ groupMentions: [],
854
+ statusAttributions: [],
855
+ forwardingScore: 2,
856
+ isForwarded: true,
857
+ forwardedAiBotMessageInfo: { botJid: "259786046210223@bot" },
858
+ forwardOrigin: 4,
859
+ botMessageSharingInfo: {
860
+ botEntryPointOrigin: 1,
861
+ forwardScore: 2,
862
+ },
863
+ };
864
+ if (quoted?.key) {
865
+ ctxInfo.stanzaId = quoted.key.id;
866
+ ctxInfo.participant =
867
+ quoted.key.participant || quoted.sender || quoted.key.remoteJid;
868
+ ctxInfo.quotedMessage = quoted.message;
869
+ }
870
+ const content = {
871
+ messageContextInfo: {
872
+ threadId: [],
873
+ deviceListMetadata: {
874
+ senderKeyIndexes: [],
875
+ recipientKeyIndexes: [],
876
+ recipientKeyHash: "",
877
+ recipientTimestamp: Math.floor(Date.now() / 1000),
878
+ },
879
+ deviceListMetadataVersion: 2,
880
+ messageSecret: randomBytes(32),
881
+ },
882
+ botForwardedMessage: {
883
+ message: {
884
+ richResponseMessage: {
885
+ submessages: [],
886
+ messageType: 1,
887
+ unifiedResponse: { data: base64Data },
888
+ contextInfo: ctxInfo,
889
+ },
890
+ },
891
+ },
892
+ };
893
+ return {
894
+ message: content,
895
+ messageId: generateMessageIDV2(),
896
+ };
897
+ };
898
+ export const generateLinkContent = (text, links, quoted, options = {}) => {
899
+ const {
900
+ footer,
901
+ botJid = "867051314767696@bot",
902
+ forwardingScore = 3,
903
+ citations = [],
904
+ proofs = [],
905
+ } = options;
906
+ const submessages = [];
907
+ const fullText = footer ? `${text}${footer}` : text;
908
+ submessages.push({ messageType: 2, messageText: fullText });
909
+ const sections = [];
910
+ const inlineEntities = links.map((link, i) => {
911
+ const url = typeof link === "string" ? link : link.url;
912
+ const displayName =
913
+ typeof link === "object" && link.displayName
914
+ ? link.displayName
915
+ : citations[i]?.sourceTitle || `Link ${i + 1}`;
916
+ return {
917
+ key: `IE_${i}`,
918
+ metadata: {
919
+ display_name: displayName,
920
+ is_trusted: false,
921
+ url,
922
+ __typename: "GenAIInlineLinkItem",
923
+ },
924
+ };
925
+ });
926
+ sections.push({
927
+ view_model: {
928
+ primitive: {
929
+ text,
930
+ inline_entities: inlineEntities,
931
+ __typename: "GenAIMarkdownTextUXPrimitive",
932
+ },
933
+ __typename: "GenAISingleLayoutViewModel",
934
+ },
935
+ });
936
+ if (footer) {
937
+ sections.push({
938
+ view_model: {
939
+ primitive: {
940
+ text: footer,
941
+ __typename: "GenAIMarkdownTextUXPrimitive",
942
+ },
943
+ __typename: "GenAISingleLayoutViewModel",
944
+ },
945
+ });
946
+ }
947
+ const responseId = randomUUID();
948
+ const unifiedData = {
949
+ response_id: responseId,
950
+ sections,
951
+ };
952
+ const base64Data = Buffer.from(JSON.stringify(unifiedData)).toString(
953
+ "base64",
954
+ );
955
+ const ctxInfo = {
956
+ forwardingScore,
957
+ isForwarded: true,
958
+ forwardedAiBotMessageInfo: { botJid },
959
+ forwardOrigin: 4,
960
+ botMessageSharingInfo: {
961
+ forwardScore: forwardingScore,
962
+ },
963
+ };
964
+ if (quoted?.key) {
965
+ ctxInfo.stanzaId = quoted.key.id;
966
+ ctxInfo.participant =
967
+ quoted.key.participant || quoted.sender || quoted.key.remoteJid;
968
+ ctxInfo.quotedMessage = quoted.message;
969
+ }
970
+ const messageContextInfo = {
971
+ messageSecret: randomBytes(32),
972
+ };
973
+ if (citations.length > 0 || proofs.length > 0) {
974
+ const botMetadata = {};
975
+ if (citations.length > 0) {
976
+ botMetadata.richResponseSourcesMetadata = {
977
+ sources: citations.map((c, i) => ({
978
+ provider: 1,
979
+ thumbnailCdnUrl: "",
980
+ sourceProviderUrl:
981
+ typeof links[i] === "string" ? links[i] : links[i]?.url || "",
982
+ sourceQuery: c.sourceQuery || "",
983
+ faviconCdnUrl: c.faviconCdnUrl || "",
984
+ citationNumber: c.citationNumber ?? i + 1,
985
+ sourceTitle: c.sourceTitle || "",
986
+ })),
987
+ };
988
+ }
989
+ if (proofs.length > 0) {
990
+ botMetadata.verificationMetadata = {
991
+ proofs: proofs.map((p) => ({
992
+ version: p.version || 1,
993
+ useCase: p.useCase || 1,
994
+ signature: p.signature || "",
995
+ certificateChain: p.certificateChain || [],
996
+ })),
997
+ };
998
+ }
999
+ messageContextInfo.botMetadata = botMetadata;
1000
+ }
1001
+ const content = {
1002
+ messageContextInfo,
1003
+ botForwardedMessage: {
1004
+ message: {
1005
+ richResponseMessage: {
1006
+ messageType: 1,
1007
+ submessages,
1008
+ unifiedResponse: { data: base64Data },
1009
+ contextInfo: ctxInfo,
1010
+ },
1011
+ },
1012
+ },
1013
+ };
1014
+ return {
1015
+ message: content,
1016
+ messageId: generateMessageIDV2(),
1017
+ };
1018
+ };
1019
+ export const generateLinkContentV2 = (text, links, quoted, options = {}) => {
1020
+ const { footer, searchEngine = "MAME" } = options;
1021
+ const submessages = [];
1022
+ const fullText = footer ? `${text}${footer}` : text;
1023
+ submessages.push({ messageType: 2, messageText: fullText });
1024
+ const sections = [];
1025
+ const inlineEntities = links.map((link, i) => {
1026
+ const url = typeof link === "string" ? link : link.url;
1027
+ const displayName =
1028
+ typeof link === "object" && link.displayName
1029
+ ? link.displayName
1030
+ : `Link ${i + 1}`;
1031
+ const sourceDisplayName =
1032
+ typeof link === "object" && link.sourceDisplayName
1033
+ ? link.sourceDisplayName
1034
+ : `Source ${i + 1}`;
1035
+ const sourceSubtitle =
1036
+ typeof link === "object" && link.sourceSubtitle
1037
+ ? link.sourceSubtitle
1038
+ : "";
1039
+ return {
1040
+ key: `IE_${i}`,
1041
+ metadata: {
1042
+ reference_id: i + 1,
1043
+ reference_url: url,
1044
+ reference_title: displayName,
1045
+ reference_display_name: displayName,
1046
+ sources: [
1047
+ {
1048
+ source_type: "THIRD_PARTY",
1049
+ source_display_name: sourceDisplayName,
1050
+ source_subtitle: sourceSubtitle,
1051
+ source_url: url,
1052
+ },
1053
+ ],
1054
+ __typename: "GenAISearchCitationItem",
1055
+ },
1056
+ };
1057
+ });
1058
+ sections.push({
1059
+ view_model: {
1060
+ primitive: {
1061
+ text,
1062
+ inline_entities: inlineEntities,
1063
+ __typename: "GenAIMarkdownTextUXPrimitive",
1064
+ },
1065
+ __typename: "GenAISingleLayoutViewModel",
1066
+ },
1067
+ });
1068
+ const searchSources = links.map((link, i) => {
1069
+ const url = typeof link === "string" ? link : link.url;
1070
+ const sourceDisplayName =
1071
+ typeof link === "object" && link.sourceDisplayName
1072
+ ? link.sourceDisplayName
1073
+ : `Source ${i + 1}`;
1074
+ const sourceSubtitle =
1075
+ typeof link === "object" && link.sourceSubtitle
1076
+ ? link.sourceSubtitle
1077
+ : "";
1078
+ return {
1079
+ source_type: "THIRD_PARTY",
1080
+ source_display_name: sourceDisplayName,
1081
+ source_subtitle: sourceSubtitle,
1082
+ source_url: url,
1083
+ };
1084
+ });
1085
+ sections.push({
1086
+ view_model: {
1087
+ primitive: {
1088
+ sources: searchSources,
1089
+ search_engine: searchEngine,
1090
+ __typename: "GenAISearchResultPrimitive",
1091
+ },
1092
+ __typename: "GenAISingleLayoutViewModel",
1093
+ },
1094
+ });
1095
+ if (footer) {
1096
+ sections.push({
1097
+ view_model: {
1098
+ primitive: {
1099
+ text: footer,
1100
+ __typename: "GenAIMarkdownTextUXPrimitive",
1101
+ },
1102
+ __typename: "GenAISingleLayoutViewModel",
1103
+ },
1104
+ });
1105
+ }
1106
+ const responseId = randomUUID();
1107
+ const unifiedData = {
1108
+ response_id: responseId,
1109
+ sections,
1110
+ };
1111
+ const base64Data = Buffer.from(JSON.stringify(unifiedData)).toString(
1112
+ "base64",
1113
+ );
1114
+ const ctxInfo = {
1115
+ isForwarded: true,
1116
+ forwardOrigin: 4,
1117
+ };
1118
+ if (quoted?.key) {
1119
+ ctxInfo.participant =
1120
+ quoted.key.participant || quoted.sender || quoted.key.remoteJid;
1121
+ ctxInfo.quotedMessage = quoted.message;
1122
+ }
1123
+ const content = {
1124
+ messageContextInfo: {
1125
+ threadId: [],
1126
+ messageSecret: randomBytes(32),
1127
+ },
1128
+ botForwardedMessage: {
1129
+ message: {
1130
+ richResponseMessage: {
1131
+ messageType: 1,
1132
+ submessages,
1133
+ unifiedResponse: { data: base64Data },
1134
+ contextInfo: ctxInfo,
1135
+ },
1136
+ },
1137
+ },
1138
+ };
1139
+ return {
1140
+ message: content,
1141
+ messageId: generateMessageIDV2(),
1142
+ };
1143
+ };
1144
+ //# sourceMappingURL=rich-messages.js.map