@fvckerss/baileys 1.0.18 → 1.0.20

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.
@@ -4,569 +4,525 @@ import {
4
4
  randomUUID
5
5
  } from 'crypto';
6
6
 
7
- import { DONATE_URL, LEXER_REGEX } from '../Defaults/index.js';
8
- import { LANGUAGE_KEYWORDS } from '../WABinary/constants.js';
9
- import { CodeHighlightType, RichSubMessageType } from '../Types/RichType.js';
7
+ import { DONATE_URL } from '../Defaults/index.js';
10
8
  import { proto } from '../../WAProto/index.js';
11
9
 
12
- const NOOP = new Set([]);
13
-
14
- export const tokenizeCode = (code, language = 'javascript') => {
15
- const keywords = LANGUAGE_KEYWORDS[language] || NOOP;
16
- const blocks = [];
17
-
18
- LEXER_REGEX.lastIndex = 0;
19
-
20
- let match;
21
-
22
- while ((match = LEXER_REGEX.exec(code)) !== null) {
23
- if (match[1]) {
24
- blocks.push({
25
- highlightType: CodeHighlightType.COMMENT,
26
- codeContent: match[1]
27
- });
28
- } else if (match[2]) {
29
- blocks.push({
30
- highlightType: CodeHighlightType.STRING,
31
- codeContent: match[2]
32
- });
33
- } else if (match[3]) {
34
- blocks.push({
35
- highlightType: keywords.has(match[3])
36
- ? CodeHighlightType.KEYWORD
37
- : CodeHighlightType.METHOD,
38
- codeContent: match[3]
39
- });
40
- } else if (match[4]) {
41
- blocks.push({
42
- highlightType: keywords.has(match[4])
43
- ? CodeHighlightType.KEYWORD
44
- : CodeHighlightType.DEFAULT,
45
- codeContent: match[4]
46
- });
47
- } else if (match[5]) {
48
- blocks.push({
49
- highlightType: CodeHighlightType.NUMBER,
50
- codeContent: match[5]
51
- });
52
- } else {
53
- blocks.push({
54
- highlightType: CodeHighlightType.DEFAULT,
55
- codeContent: match[6]
56
- });
57
- }
10
+ function extractIE(text, { extract = true, hyperlink = true, citation = true, latex = true } = {}) {
11
+ if (!extract) {
12
+ return { text, ie: [], inline_entities: [] };
58
13
  }
59
14
 
60
- return blocks;
61
- };
15
+ const createIE = (type, ie) => {
16
+ if (type == 'hyperlink') {
17
+ return {
18
+ key: ie.key,
19
+ metadata: {
20
+ display_name: ie.text,
21
+ is_trusted: ie.is_trusted,
22
+ url: ie.url,
23
+ __typename: 'GenAIInlineLinkItem',
24
+ },
25
+ };
26
+ }
27
+ if (type == 'citation') {
28
+ return {
29
+ key: ie.key,
30
+ metadata: {
31
+ reference_id: ie.reference_id,
32
+ reference_url: ie.url,
33
+ reference_title: ie.url,
34
+ reference_display_name: ie.url,
35
+ sources: [],
36
+ __typename: 'GenAISearchCitationItem',
37
+ },
38
+ };
39
+ }
40
+ if (type == 'latex') {
41
+ return {
42
+ key: ie.key,
43
+ metadata: {
44
+ latex_expression: ie.text,
45
+ latex_image: {
46
+ url: ie.url,
47
+ width: Number(ie.width) || 100,
48
+ height: Number(ie.height) || 100,
49
+ },
50
+ font_height: Number(ie.font_height) || 83.333333333333,
51
+ padding: Number(ie.padding) || 15,
52
+ __typename: 'GenAILatexItem',
53
+ },
54
+ };
55
+ }
56
+ };
62
57
 
63
- export const toUnified = (submessages, uuid, footerText) => {
64
- const sections = [];
65
-
66
- for (const submessage of submessages) {
67
- switch (submessage.messageType) {
68
-
69
- case RichSubMessageType.CODE: {
70
- const codeMetadata = submessage.codeMetadata;
71
-
72
- sections.push({
73
- view_model: {
74
- primitive: {
75
- language: codeMetadata.codeLanguage,
76
- code_blocks: codeMetadata.codeBlocks.map((block) => ({
77
- content: block.codeContent,
78
- type: CodeHighlightType[block.highlightType]
79
- })),
80
- __typename: 'GenAICodeUXPrimitive'
81
- },
82
- __typename: 'GenAISingleLayoutViewModel'
83
- }
84
- });
85
-
86
- break;
58
+ let ie = [];
59
+ let inline_entities = [];
60
+ let result = '';
61
+ let last = 0;
62
+ let citation_index = 1;
63
+ let hyperlink_index = 0;
64
+ let latex_index = 0;
65
+ let stack = [];
66
+
67
+ for (let i = 0; i < text.length; i++) {
68
+ if (text[i] == '[' && text[i - 1] != '\\') {
69
+ stack.push(i);
70
+ } else if (text[i] == ']' && (text[i + 1] == '(' || text[i + 1] == '<')) {
71
+ let start = stack.pop();
72
+ if (start == null) continue;
73
+
74
+ let open = text[i + 1];
75
+ let close = open == '(' ? ')' : '>';
76
+ let type = open == '(' ? 'link' : 'latex';
77
+ let end = i + 2;
78
+ let depth = 1;
79
+
80
+ while (end < text.length && depth) {
81
+ if (text[end] == open && text[end - 1] != '\\') depth++;
82
+ else if (text[end] == close && text[end - 1] != '\\') depth--;
83
+ end++;
87
84
  }
88
85
 
89
- case RichSubMessageType.TEXT: {
90
- sections.push({
91
- view_model: {
92
- primitive: {
93
- text: submessage.messageText,
94
- inline_entities: submessage.inlineEntities || [],
95
- __typename: 'GenAIMarkdownTextUXPrimitive'
96
- },
97
- __typename: 'GenAISingleLayoutViewModel'
98
- }
99
- });
100
-
101
- break;
86
+ if (depth) continue;
87
+
88
+ let raw = text.slice(start + 1, i).trim();
89
+ let url = text.slice(i + 2, end - 1).trim();
90
+
91
+ let key, tag, data;
92
+
93
+ if (type == 'latex') {
94
+ if (!latex) continue;
95
+ let [txt = '', width = null, height = null, font_height = null, padding = null] = raw.split('|');
96
+ key = `\u004E\u0049\u0058\u0045\u004C_LATEX_${latex_index++}`;
97
+ tag = `{{${key}}}${txt || 'image'}{{/${key}}}`;
98
+ data = { type: 'latex', ie: { key, text: txt, url, width, height, font_height, padding } };
99
+ } else if (raw) {
100
+ if (!hyperlink) continue;
101
+ const trusted = !url.startsWith('!');
102
+ if (!trusted) url = url.slice(1);
103
+ key = `\u004E\u0049\u0058\u0045\u004C_HYPERLINK_${hyperlink_index++}`;
104
+ tag = `{{${key}}}${url}{{/${key}}}`;
105
+ data = { type: 'hyperlink', ie: { key, text: raw, url, is_trusted: trusted } };
106
+ } else {
107
+ if (!citation) continue;
108
+ key = `\u004E\u0049\u0058\u0045\u004C_CITATION_${citation_index - 1}`;
109
+ tag = `{{${key}}}${url}{{/${key}}}`;
110
+ data = { type: 'citation', ie: { reference_id: citation_index++, key, text: '', url } };
102
111
  }
103
112
 
104
- case RichSubMessageType.CONTENT_ITEMS: {
105
- const meta = submessage.contentItemsMetadata;
106
- const items = meta?.itemsMetadata || [];
107
-
108
- if (!items.length) break;
109
-
110
- const first = items[0];
111
-
112
- if (first?.__typename === 'GenAIProductItemCardPrimitive') {
113
- sections.push({
114
- view_model: {
115
- primitive: first,
116
- __typename: 'GenAISingleLayoutViewModel'
117
- }
118
- });
113
+ result += text.slice(last, start) + tag;
114
+ last = end;
115
+ ie.push(data);
119
116
 
120
- break;
121
- }
117
+ const entity = createIE(data.type, data.ie);
118
+ if (entity) inline_entities.push(entity);
122
119
 
123
- if (first?.__typename === 'GenAIFollowUpSuggestionPillPrimitive') {
124
- sections.push({
125
- view_model: {
126
- primitives: items,
127
- __typename: 'GenAIActionRowLayoutViewModel'
128
- }
129
- });
120
+ i = end - 1;
121
+ }
122
+ }
130
123
 
131
- break;
132
- }
124
+ result += text.slice(last);
125
+ return { text: result, ie, inline_entities };
126
+ }
127
+
128
+ function tokenizeCode(code, lang = 'javascript') {
129
+ const keywordsMap = {
130
+ 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']),
131
+ 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']),
132
+ 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']),
133
+ 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']),
134
+ 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']),
135
+ 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']),
136
+ 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']),
137
+ 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']),
138
+ 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']),
139
+ 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']),
140
+ 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']),
141
+ };
133
142
 
134
- break;
135
- }
143
+ if (!lang || lang === 'txt' || lang === 'text' || lang === 'plaintext') {
144
+ return { codeBlock: [{ codeContent: code, highlightType: 0 }], unified_codeBlock: [{ content: code, type: 'DEFAULT' }] };
145
+ }
136
146
 
137
- case RichSubMessageType.TABLE: {
138
- const tableMetadata = submessage.tableMetadata;
139
-
140
- sections.push({
141
- view_model: {
142
- primitive: {
143
- title: tableMetadata.title,
144
- rows: tableMetadata.rows.map((row) => ({
145
- is_header: row.isHeading,
146
- cells: row.items,
147
- markdown_cells: row.items.map((item) => ({ text: item }))
148
- })),
149
- __typename: 'GenATableUXPrimitive'
150
- },
151
- __typename: 'GenAISingleLayoutViewModel'
152
- }
153
- });
154
-
155
- break;
156
- }
147
+ const TYPE_MAP = { 0: 'DEFAULT', 1: 'KEYWORD', 2: 'METHOD', 3: 'STR', 4: 'NUMBER', 5: 'COMMENT' };
148
+ const keywords = keywordsMap[lang.toLowerCase()] || new Set();
149
+ const tokens = [];
150
+ let i = 0;
157
151
 
158
- case RichSubMessageType.INLINE_IMAGE:
159
- case RichSubMessageType.LATEX:
160
- default:
161
- break;
152
+ const push = (content, type) => {
153
+ if (!content) return;
154
+ const last = tokens[tokens.length - 1];
155
+ if (last && last.highlightType === type) {
156
+ last.codeContent += content;
157
+ } else {
158
+ tokens.push({ codeContent: content, highlightType: type });
162
159
  }
163
- }
164
-
165
- if (typeof footerText === 'string' && footerText.trim()) {
166
- sections.push({
167
- view_model: {
168
- primitive: {
169
- text: footerText,
170
- __typename: 'GenAIMarkdownTextUXPrimitive'
171
- },
172
- __typename: 'GenAISingleLayoutViewModel'
173
- }
174
- });
175
- }
176
-
177
- return {
178
- response_id: uuid || randomUUID(),
179
- sections
180
160
  };
181
- };
182
161
 
183
- export const prepareRichResponseMessage = (content) => {
184
- const {
185
- alignment,
186
- code,
187
- contentText,
188
- disclaimerText,
189
- footerText,
190
- headerText,
191
- imageText,
192
- inlineImage,
193
- inlineVideo,
194
- items,
195
- language,
196
- latex,
197
- links,
198
- noHeading,
199
- posts,
200
- products,
201
- product,
202
- suggested,
203
- richResponse,
204
- table,
205
- tapLinkUrl,
206
- title
207
- } = content;
162
+ const isIdentifier = (char) => {
163
+ switch (lang.toLowerCase()) {
164
+ case 'css': return /[a-zA-Z0-9_$-]/.test(char);
165
+ case 'html': return /[a-zA-Z0-9_$:-]/.test(char);
166
+ default: return /[a-zA-Z0-9_$]/.test(char);
167
+ }
168
+ };
208
169
 
209
- const dataProduct = products || product;
170
+ while (i < code.length) {
171
+ const c = code[i];
210
172
 
211
- let submessages = [];
173
+ if (/\s/.test(c)) {
174
+ let s = i;
175
+ while (i < code.length && /\s/.test(code[i])) i++;
176
+ push(code.slice(s, i), 0);
177
+ continue;
178
+ }
212
179
 
213
- if (Array.isArray(richResponse)) {
214
- submessages = richResponse.map((submessage) => {
215
-
216
- if (submessage.text) {
217
- return {
218
- messageType: RichSubMessageType.TEXT,
219
- messageText: submessage.text,
220
- inlineEntities: submessage.inlineEntities
221
- };
222
- }
180
+ if ((c === '/' && code[i + 1] === '/') || (c === '#' && ['python', 'bash'].includes(lang))) {
181
+ let s = i;
182
+ while (i < code.length && code[i] !== '\n') i++;
183
+ push(code.slice(s, i), 5);
184
+ continue;
185
+ }
223
186
 
224
- if (submessage.code) {
225
- const codeLanguage = submessage.language || 'javascript';
226
-
227
- return {
228
- messageType: RichSubMessageType.CODE,
229
- codeMetadata: {
230
- codeLanguage,
231
- codeBlocks: Array.isArray(submessage.code)
232
- ? submessage.code
233
- : tokenizeCode(submessage.code, codeLanguage)
234
- }
235
- };
187
+ if (c === '"' || c === "'" || c === '`') {
188
+ let s = i;
189
+ const q = c;
190
+ i++;
191
+ while (i < code.length) {
192
+ if (code[i] === '\\' && i + 1 < code.length) i += 2;
193
+ else if (code[i] === q) { i++; break; }
194
+ else i++;
236
195
  }
196
+ push(code.slice(s, i), 3);
197
+ continue;
198
+ }
237
199
 
238
- if (submessage.items) {
239
- return {
240
- messageType: RichSubMessageType.CONTENT_ITEMS,
241
- contentItemsMetadata: {
242
- itemsMetadata: submessage.items,
243
- contentType:
244
- proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
245
- }
246
- };
247
- }
200
+ if (/[0-9]/.test(c)) {
201
+ let s = i;
202
+ while (i < code.length && /[0-9._]/.test(code[i])) i++;
203
+ push(code.slice(s, i), 4);
204
+ continue;
205
+ }
248
206
 
249
- if (submessage.inlineImage) {
250
- return {
251
- messageType: RichSubMessageType.INLINE_IMAGE,
252
- imageMetadata: {
253
- imageUrl: submessage.inlineImage,
254
- imageText: submessage.imageText,
255
- alignment: submessage.alignment,
256
- tapLinkUrl: submessage.tapLinkUrl
257
- }
258
- };
207
+ if (/[a-zA-Z_$]/.test(c)) {
208
+ let s = i;
209
+ while (i < code.length && isIdentifier(code[i])) i++;
210
+ const word = code.slice(s, i);
211
+ let type = 0;
212
+
213
+ if (keywords.has(word)) {
214
+ type = 1;
215
+ } else if (lang === 'css') {
216
+ let j = i;
217
+ while (j < code.length && /\s/.test(code[j])) j++;
218
+ if (code[j] === ':') type = 1;
219
+ } else if (lang === 'html') {
220
+ let p = s - 1;
221
+ while (p >= 0 && /\s/.test(code[p])) p--;
222
+ if (code[p] === '<' || (code[p] === '/' && code[p - 1] === '<')) type = 1;
259
223
  }
260
224
 
261
- if (submessage.inlineVideo) {
262
- return {
263
- messageType: RichSubMessageType.TEXT,
264
- messageText: 'INLINE_VIDEO'
265
- };
225
+ if (type === 0) {
226
+ let j = i;
227
+ while (j < code.length && /\s/.test(code[j])) j++;
228
+ if (code[j] === '(') type = 2;
266
229
  }
267
230
 
268
- if (submessage.latex) {
269
- return {
270
- messageType: RichSubMessageType.LATEX,
271
- latexMetadata: {
272
- text: submessage.text,
273
- expressions: submessage.latex
274
- }
275
- };
276
- }
231
+ push(word, type);
232
+ continue;
233
+ }
277
234
 
278
- if (submessage.posts) {
279
- return {
280
- messageType: RichSubMessageType.TEXT,
281
- messageText: 'POSTS'
282
- };
283
- }
235
+ push(c, 0);
236
+ i++;
237
+ }
284
238
 
285
- if (submessage.suggested) {
286
- return {
287
- messageType: RichSubMessageType.CONTENT_ITEMS,
288
- contentItemsMetadata: {
289
- itemsMetadata: submessage.suggested.map((text) => ({
290
- prompt_text: text,
291
- prompt_type: 'SUGGESTED_PROMPT',
292
- __typename: 'GenAIFollowUpSuggestionPillPrimitive'
293
- }))
294
- }
295
- };
296
- }
239
+ return {
240
+ codeBlock: tokens,
241
+ unified_codeBlock: tokens.map((t) => ({ content: t.codeContent, type: TYPE_MAP[t.highlightType] })),
242
+ };
243
+ }
297
244
 
298
- if (submessage.table) {
299
- return {
300
- messageType: RichSubMessageType.TABLE,
301
- tableMetadata: {
302
- title: submessage.title,
303
- rows: submessage.table
304
- }
305
- };
306
- }
245
+ function toTableMetadata(arr, { hyperlink = true, citation = true, latex = true } = {}) {
246
+ if (!Array.isArray(arr) || !arr.every((row) => Array.isArray(row) && row.every((cell) => typeof cell === 'string'))) {
247
+ throw new TypeError('Table must be a nested array of strings');
248
+ }
307
249
 
308
- return submessage;
250
+ const [header, ...rows] = arr;
251
+ const maxLen = Math.max(header.length, ...rows.map((r) => r.length));
252
+ const normalize = (r) => [...r, ...Array(maxLen - r.length).fill('')];
253
+
254
+ const unified_rows = [
255
+ { is_header: true, cells: normalize(header) },
256
+ ...rows.map((r) => ({ is_header: false, cells: normalize(r) })),
257
+ ].map((row) => {
258
+ const markdown_cells = row.cells.map((cell) => {
259
+ const extracted = extractIE(cell, { hyperlink, citation, latex });
260
+ return { text: extracted.text, ...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}) };
309
261
  });
310
- } else {
262
+ return { ...row, ...(markdown_cells.some((c) => c.inline_entities?.length) ? { markdown_cells } : {}) };
263
+ });
311
264
 
312
- if (headerText) {
313
- submessages.push({
314
- messageType: RichSubMessageType.TEXT,
315
- messageText: headerText
316
- });
317
- }
265
+ const rowsMeta = unified_rows.map((r) => ({ items: r.cells, ...(r.is_header ? { isHeading: true } : {}) }));
266
+ return { title: '', rows: rowsMeta, unified_rows };
267
+ }
318
268
 
319
- if (contentText) {
320
- submessages.push({
321
- messageType: RichSubMessageType.TEXT,
322
- messageText: contentText
323
- });
324
- }
269
+ function newLayout(name, data, extra = {}) {
270
+ return {
271
+ ...extra,
272
+ view_model: {
273
+ [Array.isArray(data) ? 'primitives' : 'primitive']: data,
274
+ __typename: `GenAI${name}LayoutViewModel`,
275
+ },
276
+ };
277
+ }
278
+
279
+ function generateVerificationMetadata() {
280
+ const signatureMaterial = Buffer.from(`\u004E\u0049\u0058\u0045\u004C\u002E\u004D\u0065\u0073\u0073\u0061\u0067\u0065\u0042\u0075\u0069\u006C\u0064\u0065\u0072\u0056\u0034\u002E\u0037\u002D\u0056\u0065\u0072\u0069\u0066\u0069\u0063\u0061\u0074\u0069\u006F\u006E\u0053\u0069\u0067\u006E\u0061\u0074\u0075\u0072\u0065\u002E\u004D\u0065\u0074\u0061\u0064\u0061\u0074\u0061`);
281
+ const certificateMaterial = Buffer.from(`\u004E\u0049\u0058\u0045\u004C\u002E\u004D\u0065\u0073\u0073\u0061\u0067\u0065\u0042\u0075\u0069\u006C\u0064\u0065\u0072\u0056\u0034\u002E\u0037\u002D\u0043\u0065\u0072\u0074\u0069\u0066\u0069\u0063\u0061\u0074\u0065\u0043\u0068\u0061\u0069\u006E\u002E\u004D\u0065\u0074\u0061\u0064\u0061\u0074\u0061`);
282
+ const signature = Buffer.concat([signatureMaterial, randomBytes(64 - signatureMaterial.length)]).toString('base64');
283
+ const certificateChain = [
284
+ Buffer.concat([certificateMaterial, randomBytes(684 - certificateMaterial.length)]).toString('base64'),
285
+ Buffer.concat([certificateMaterial, randomBytes(892 - certificateMaterial.length)]).toString('base64'),
286
+ ];
287
+ return { proofs: [{ version: 1, useCase: 1, signature, certificateChain }] };
288
+ }
289
+
290
+ // ==================== FUNGSI UTAMA ====================
291
+
292
+ export const prepareRichResponseMessage = (content, quoted) => {
293
+ const { code, contentText, disclaimerText, footerText, headerText, items, language, links, noHeading, posts, products, product, suggested, richResponse, table, title, image, video, post, reels, tip, widget, footerAction, metadata, source, section } = content;
294
+ const dataProduct = products || product;
325
295
 
326
- if (code) {
327
- const codeLanguage = language || 'javascript';
296
+ let sections = [];
297
+ let submessages = [];
298
+ let responseId = randomUUID();
299
+
300
+ const addContent = (sectionsData, submessagesData) => {
301
+ if (Array.isArray(sectionsData)) sections.push(...sectionsData);
302
+ else if (sectionsData) sections.push(sectionsData);
303
+
304
+ if (Array.isArray(submessagesData)) submessages.push(...submessagesData);
305
+ else if (submessagesData) submessages.push(submessagesData);
306
+ };
328
307
 
329
- submessages.push({
330
- messageType: RichSubMessageType.CODE,
331
- codeMetadata: {
332
- codeLanguage,
333
- codeBlocks: tokenizeCode(code, codeLanguage)
334
- }
335
- });
308
+ const processNode = (node) => {
309
+ if (node.text) {
310
+ const meta = extractIE(node.text);
311
+ addContent(
312
+ newLayout('Single', { text: meta.text, inline_entities: meta.inline_entities, __typename: 'GenAIMarkdownTextUXPrimitive' }),
313
+ { messageType: 2, messageText: node.text }
314
+ );
315
+ }
316
+
317
+ if (node.code) {
318
+ const lang = node.language || 'javascript';
319
+ const meta = tokenizeCode(node.code, lang);
320
+ addContent(
321
+ newLayout('Single', { language: lang, code_blocks: meta.unified_codeBlock, __typename: 'GenAICodeUXPrimitive' }),
322
+ { messageType: 5, codeMetadata: { codeLanguage: lang, codeBlocks: meta.codeBlock } }
323
+ );
336
324
  }
337
325
 
338
- if (items) {
339
- submessages.push({
340
- messageType: RichSubMessageType.CONTENT_ITEMS,
341
- contentItemsMetadata: {
342
- itemsMetadata: items,
343
- contentType:
344
- proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
345
- }
346
- });
326
+ if (node.table) {
327
+ const meta = toTableMetadata(node.table);
328
+ addContent(
329
+ newLayout('Single', { rows: meta.unified_rows, __typename: 'GenATableUXPrimitive' }),
330
+ { messageType: 4, tableMetadata: { title: node.title || '', rows: meta.rows } }
331
+ );
347
332
  }
348
333
 
349
- if (inlineImage) {
350
- submessages.push({
351
- messageType: RichSubMessageType.INLINE_IMAGE,
352
- imageMetadata: {
353
- imageUrl: inlineImage,
354
- imageText,
355
- alignment,
356
- tapLinkUrl
357
- }
358
- });
334
+ if (node.image) {
335
+ const url = typeof node.image === 'string' ? node.image : node.image.url;
336
+ const list = [{ imagePreviewUrl: url, imageHighResUrl: url, sourceUrl: url }];
337
+ addContent(
338
+ newLayout('Single', { media: { url, mime_type: 'image/png' }, imagine_type: 'IMAGE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive' }),
339
+ { messageType: 1, gridImageMetadata: { gridImageUrl: { imagePreviewUrl: url }, imageUrls: list } }
340
+ );
359
341
  }
360
342
 
361
- if (inlineVideo) {
362
- submessages.push({
363
- messageType: RichSubMessageType.TEXT,
364
- messageText: 'INLINE_VIDEO'
365
- });
343
+ if (node.video) {
344
+ const url = typeof node.video === 'string' ? node.video : node.video.url;
345
+ addContent(
346
+ newLayout('Single', { media: { url, mime_type: 'video/mp4' }, imagine_type: 'ANIMATE', status: { status: 'READY' }, thumbnail: { raw_media: null }, __typename: 'GenAIImaginePrimitive' }),
347
+ { messageType: 2, messageText: '[ UNSUPPORTED_TYPE - GenAIImaginePrimitive (ANIMATE)]' }
348
+ );
366
349
  }
367
350
 
368
- if (latex) {
369
- submessages.push({
370
- messageType: RichSubMessageType.LATEX,
371
- latexMetadata: {
372
- text: contentText,
373
- expressions: latex
374
- }
375
- });
351
+ if (node.post) {
352
+ const postItems = Array.isArray(node.post) ? node.post : [node.post];
353
+ const primitives = postItems.map(p => ({
354
+ title: p.title ?? '', subtitle: p.subtitle ?? '', username: p.username ?? '',
355
+ profile_picture_url: p.profile_picture_url ?? p.profile_url ?? '', is_verified: !!(p.is_verified || p.verified),
356
+ thumbnail_url: p.thumbnail_url ?? p.thumbnail ?? '', post_caption: p.post_caption ?? p.caption ?? '',
357
+ likes_count: p.likes_count ?? p.like ?? 0, comments_count: p.comments_count ?? p.comment ?? 0,
358
+ shares_count: p.shares_count ?? p.share ?? 0, post_url: p.post_url ?? p.url ?? '',
359
+ post_deeplink: p.post_deeplink ?? p.deeplink ?? '', source_app: p.source_app || p.source || 'INSTAGRAM',
360
+ footer_label: p.footer_label ?? p.footer ?? '', footer_icon: p.footer_icon ?? p.icon ?? '',
361
+ is_carousel: postItems.length > 1, orientation: p.orientation ?? 'LANDSCAPE',
362
+ post_type: p.post_type ?? 'VIDEO', __typename: 'GenAIPostPrimitive'
363
+ }));
364
+ addContent(
365
+ newLayout('HScroll', primitives),
366
+ { messageType: 2, messageText: '[ UNSUPPORTED_TYPE - GenAIPostPrimitive]' }
367
+ );
376
368
  }
377
369
 
378
- if (links) {
379
- links.forEach((linkField, index) => {
380
- const prefix = 'SS_' + index;
381
- const url = linkField.url || DONATE_URL;
382
-
383
- const sources = linkField.sources?.map((sourceField) => ({
384
- source_type: 'THIRD_PARTY',
385
- source_display_name: sourceField.displayName || 'Donate',
386
- source_subtitle: sourceField.subtitle || 'Saweria',
387
- source_url: sourceField.url || url
388
- }));
389
-
390
- submessages.push({
391
- messageType: RichSubMessageType.TEXT,
392
- messageText: linkField.text + ` {{${prefix}}}¹{{/${prefix}}} `,
393
- inlineEntities: [
394
- {
395
- key: prefix,
396
- metadata: {
397
- reference_id: index + 1,
398
- reference_url: url,
399
- reference_title:
400
- linkField.title || 'For Donation via Saweria',
401
- reference_display_name:
402
- linkField.displayName || 'Donation',
403
- sources: sources || [],
404
- __typename: 'GenAISearchCitationItem'
405
- }
406
- }
407
- ]
408
- });
409
- });
370
+ if (node.reels) {
371
+ const reelItems = Array.isArray(node.reels) ? node.reels : [node.reels];
372
+ const reelsList = reelItems.map(item => ({
373
+ reels_url: item.videoUrl ?? item.url ?? '', thumbnail_url: item.thumbnailUrl ?? item.thumbnail ?? '',
374
+ creator: item.username ?? item.title ?? '', avatar_url: item.profileIconUrl ?? item.profile_url ?? '',
375
+ reels_title: item.reels_title ?? item.title ?? '', likes_count: item.likes_count ?? item.like ?? 0,
376
+ shares_count: item.shares_count ?? item.share ?? 0, view_count: item.view_count ?? item.view ?? 0,
377
+ reel_source: item.reel_source ?? item.source ?? 'IG', is_verified: !!(item.is_verified || item.verified), __typename: 'GenAIReelPrimitive'
378
+ }));
379
+ addContent(
380
+ newLayout('HScroll', reelsList),
381
+ { messageType: 9, contentItemsMetadata: { contentType: 1, itemsMetadata: reelsList.map(item => ({ reelItem: { title: item.creator, profileIconUrl: item.avatar_url, thumbnailUrl: item.thumbnail_url, videoUrl: item.reels_url } })) } }
382
+ );
410
383
  }
411
384
 
412
- if (posts) {
413
- submessages.push({
414
- messageType: RichSubMessageType.TEXT,
415
- messageText: 'POSTS'
416
- });
385
+ if (node.suggested) {
386
+ const s = (Array.isArray(node.suggested) ? node.suggested : [node.suggested]).map(t => ({ prompt_text: t, prompt_type: 'SUGGESTED_PROMPT', __typename: 'GenAIFollowUpSuggestionPillPrimitive' }));
387
+ addContent(
388
+ newLayout(s.length === 1 ? 'Single' : 'ActionRow', s.length === 1 ? s[0] : s, { __typename: 'GenAIUnifiedResponseSection' }),
389
+ undefined
390
+ );
417
391
  }
418
392
 
419
- if (dataProduct) {
420
- const list = Array.isArray(dataProduct) ? dataProduct : [dataProduct];
393
+ if (node.items) {
394
+ addContent(
395
+ newLayout('Single', node.items[0]),
396
+ { messageType: 9, contentItemsMetadata: { contentType: 1, itemsMetadata: node.items } }
397
+ );
398
+ }
421
399
 
422
- submessages.push({
423
- messageType: RichSubMessageType.CONTENT_ITEMS,
424
- contentItemsMetadata: {
425
- contentType:
426
- proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL,
427
- itemsMetadata: list.map((item) => ({
428
- title: item.title,
429
- brand: item.brand,
430
- price: item.price,
431
- sale_price: item.sale_price,
432
- product_url: item.product_url,
433
- image: item.image_url ? { url: item.image_url } : undefined,
434
- additional_images: item.icon_url
435
- ? [{ url: item.icon_url }]
436
- : [],
437
- __typename: 'GenAIProductItemCardPrimitive'
438
- }))
439
- }
440
- });
400
+ if (node.tip) {
401
+ addContent(
402
+ newLayout('Single', { text: 'ⓘ ' + node.tip, __typename: 'GenAIMetadataTextPrimitive' }),
403
+ { messageType: 2, messageText: node.tip }
404
+ );
441
405
  }
442
406
 
443
- if (suggested) {
444
- const suggestionList = Array.isArray(suggested) ? suggested : [suggested];
445
-
446
- submessages.push({
447
- messageType: RichSubMessageType.CONTENT_ITEMS,
448
- contentItemsMetadata: {
449
- itemsMetadata: suggestionList.map((text) => ({
450
- prompt_text: text,
451
- prompt_type: 'SUGGESTED_PROMPT',
452
- __typename: 'GenAIFollowUpSuggestionPillPrimitive'
453
- }))
454
- }
455
- });
407
+ if (node.metadata) {
408
+ addContent(
409
+ newLayout('Single', { text: node.metadata, __typename: 'GenAIMetadataTextPrimitive' }),
410
+ { messageType: 2, messageText: node.metadata }
411
+ );
456
412
  }
457
413
 
458
- if (table) {
459
- submessages.push({
460
- messageType: RichSubMessageType.TABLE,
461
- tableMetadata: {
462
- title,
463
- rows: table.map((items, index) => ({
464
- isHeading: !noHeading && index === 0,
465
- items
466
- }))
467
- }
468
- });
414
+ if (node.source) {
415
+ const sources = Array.isArray(node.source) ? node.source : [node.source];
416
+ const normalized = sources.map(s => ({ icon: s.favicon ?? s.icon ?? '', url: s.url ?? '', title: s.title ?? s.displayName ?? '', subtitle: s.subtitle ?? '' }));
417
+ const src = normalized.map(({ icon, url, title, subtitle }) => ({ source_type: 'THIRD_PARTY', source_display_name: title, source_subtitle: subtitle, source_url: url, favicon: { url: icon, mime_type: 'image/jpeg', width: 16, height: 16 } }));
418
+ addContent(
419
+ newLayout('Single', { sources: src, __typename: 'GenAISearchResultPrimitive' }),
420
+ { messageType: 2, messageText: '[ UNSUPPORTED_TYPE - GenAISearchResultPrimitive]' }
421
+ );
469
422
  }
470
- }
471
423
 
472
- const uuid = randomUUID();
473
- const unified = toUnified(submessages, uuid, footerText);
424
+ if (node.widget) {
425
+ const data = Array.isArray(node.widget) ? node.widget : [node.widget];
426
+ const widgets = data.map(item => ({
427
+ __typename: 'GenAI3PExtWidgetPrimitive',
428
+ header: { __typename: 'GenAI3PExtWidgetStandardHeader', title: item.title ?? '', ...(item.header ?? {}) },
429
+ body: { __typename: 'GenAI3PExtCalendarEventList', sections: item.sections ?? [], ctas: (item.actions ?? []).map(a => ({ __typename: 'GenAI3PExtWidgetCTA', label: a.label ?? '', state: a.state ?? 'PENDING', kind: a.kind ?? 'OTHER', tool_call_id: a.tool_call_id ?? a.id ?? '', ...(a.toast && { toast: { __typename: 'GenAI3PExtWidgetToast', label: a.toast.label ?? a.label ?? '' } }) })), ...(item.body ?? {}) }
430
+ }));
431
+ addContent(
432
+ newLayout(Array.isArray(node.widget) ? 'HScroll' : 'Single', Array.isArray(node.widget) ? widgets : widgets[0]),
433
+ { messageType: 2, messageText: '[ UNSUPPORTED_TYPE - GenAI3PExtWidgetStandardHeader]' }
434
+ );
435
+ }
474
436
 
475
- const base64Data = Buffer.from(JSON.stringify(unified)).toString('base64');
437
+ if (node.footerAction) {
438
+ const items = Array.isArray(node.footerAction) ? node.footerAction : [node.footerAction];
439
+ const actions = items.map(item => ({ __typename: 'GenAIFooterActionPrimitive', cta_text: item.text ?? item.cta_text ?? '', cta_type: item.type ?? item.cta_type ?? 'OPEN_URL', cta_url: item.url ?? item.cta_url ?? '' }));
440
+ addContent(
441
+ newLayout(Array.isArray(node.footerAction) ? 'HScroll' : 'Single', Array.isArray(node.footerAction) ? actions : actions[0]),
442
+ { messageType: 2, messageText: '[ UNSUPPORTED_TYPE - GenAIFooterActionPrimitive]' }
443
+ );
444
+ }
476
445
 
477
- const contextInfo = {
478
- mentionedJid: [],
479
- groupMentions: [],
480
- statusAttributions: [],
481
- forwardingScore: 2,
482
- isForwarded: true,
483
- forwardedAiBotMessageInfo: {
484
- botJid: '259786046210223@bot'
485
- },
486
- forwardOrigin: 4,
487
- botMessageSharingInfo: {
488
- botEntryPointOrigin: 1,
489
- forwardScore: 2
446
+ if (node.section) {
447
+ const secs = Array.isArray(node.section) ? node.section : [node.section];
448
+ addContent(secs, node.submessage || undefined);
490
449
  }
491
450
  };
492
451
 
493
- const richResponseMessage = proto.AIRichResponseMessage.create({
494
- submessages: [],
495
- messageType:
496
- proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
497
- unifiedResponse: {
498
- data: base64Data
499
- },
500
- contextInfo
501
- });
502
-
503
- const message = wrapToBotForwardedMessage(richResponseMessage);
504
- const botMetadata = message.messageContextInfo.botMetadata;
505
-
506
- if (disclaimerText) {
507
- botMetadata.messageDisclaimerText = disclaimerText;
452
+ if (Array.isArray(richResponse)) {
453
+ richResponse.forEach(processNode);
454
+ } else {
455
+ if (headerText) processNode({ text: headerText });
456
+ if (contentText) processNode({ text: contentText });
457
+ if (code) processNode({ code, language });
458
+ if (table) processNode({ table, title, noHeading });
459
+ if (links) processNode({ source: links });
460
+ if (dataProduct) {
461
+ const list = Array.isArray(dataProduct) ? dataProduct : [dataProduct];
462
+ const productData = list.map(item => ({
463
+ title: item.title, brand: item.brand, price: item.price, sale_price: item.sale_price, product_url: item.product_url,
464
+ image: item.image_url ? { url: item.image_url } : undefined, additional_images: item.icon_url ? [{ url: item.icon_url }] : [],
465
+ __typename: 'GenAIProductItemCardPrimitive'
466
+ }));
467
+ processNode({ items: productData });
468
+ }
469
+ if (suggested) processNode({ suggested });
470
+ if (image) processNode({ image });
471
+ if (video) processNode({ video });
472
+ if (post) processNode({ post });
473
+ if (reels) processNode({ reels });
474
+ if (tip) processNode({ tip });
475
+ if (widget) processNode({ widget });
476
+ if (footerAction) processNode({ footerAction });
477
+ if (metadata) processNode({ metadata });
478
+ if (source) processNode({ source });
479
+ if (section) processNode({ section, submessage });
508
480
  }
509
481
 
510
- botMetadata.botResponseId = uuid;
511
-
512
- return message;
513
- };
514
-
515
- export const botMetadataSignature = () => {
516
- const signature = new Uint8Array(64);
517
-
518
- getRandomValues(signature);
519
-
520
- return signature;
521
- };
522
-
523
- export const botMetadataCertificate = (length = 685) => {
524
- const certificate = new Uint8Array(length);
482
+ if (footerText && typeof footerText === 'string' && footerText.trim()) {
483
+ addContent(newLayout('Single', { text: footerText.trim(), __typename: 'GenAIMetadataTextPrimitive' }), undefined);
484
+ }
525
485
 
526
- certificate[0] = 48;
527
- certificate[1] = 130;
486
+ const unifiedData = Buffer.from(JSON.stringify({ response_id: responseId, sections })).toString('base64');
528
487
 
529
- getRandomValues(certificate.subarray(2));
488
+ const qObj = quoted
489
+ ? {
490
+ stanzaId: quoted?.key?.id || quoted?.id,
491
+ participant: quoted?.key?.participant || quoted?.participant || quoted?.key?.remoteJid,
492
+ quotedType: 0,
493
+ quotedMessage: typeof quoted === 'object' && quoted !== null ? (quoted.message ?? quoted) : undefined,
494
+ }
495
+ : {};
530
496
 
531
- return certificate;
532
- };
497
+ const richResponseMessage = proto.AIRichResponseMessage.create({
498
+ submessages: submessages,
499
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
500
+ unifiedResponse: { data: unifiedData },
501
+ contextInfo: {
502
+ forwardingScore: 1,
503
+ isForwarded: true,
504
+ forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
505
+ forwardOrigin: 4,
506
+ ...qObj
507
+ }
508
+ });
533
509
 
534
- export const wrapToBotForwardedMessage = (richResponseMessage) => {
535
- return {
510
+ const message = {
536
511
  messageContextInfo: {
537
512
  threadId: [],
538
- deviceListMetadata: {
539
- senderKeyIndexes: [],
540
- recipientKeyIndexes: [],
541
- recipientKeyHash: '',
542
- recipientTimestamp: Math.floor(Date.now() / 1000)
543
- },
513
+ deviceListMetadata: { senderKeyIndexes: [], recipientKeyIndexes: [], recipientKeyHash: '', recipientTimestamp: Math.floor(Date.now() / 1000) },
544
514
  deviceListMetadataVersion: 2,
545
515
  messageSecret: randomBytes(32),
546
-
547
516
  botMetadata: {
548
- verificationMetadata: {
549
- proofs: [
550
- {
551
- certificateChain: [
552
- botMetadataCertificate(),
553
- botMetadataCertificate(892)
554
- ],
555
- version: 1,
556
- useCase: 1,
557
- signature: botMetadataSignature()
558
- }
559
- ]
560
- }
517
+ verificationMetadata: generateVerificationMetadata(),
518
+ messageDisclaimerText: disclaimerText || '',
519
+ botResponseId: responseId
561
520
  }
562
521
  },
563
-
564
- botForwardedMessage: {
565
- message: {
566
- richResponseMessage
567
- }
568
- }
522
+ botForwardedMessage: { message: { richResponseMessage } }
569
523
  };
524
+
525
+ return message;
570
526
  };
571
527
 
572
528
  //# sourceMappingURL=rich-message-utils.js.map