@blurose/baileys 1.1.21 → 1.1.23
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.
- package/README.md +268 -0
- package/WAProto/WAProto.proto +18 -0
- package/WAProto/index.d.ts +1832 -4261
- package/WAProto/index.js +32547 -29291
- package/lib/Defaults/index.js +1 -1
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +8 -6
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +5 -2
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +72 -1
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Types/Events.d.ts +1 -0
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/Message.d.ts +12 -7
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Utils/a2ui.d.ts +45 -1
- package/lib/Utils/a2ui.d.ts.map +1 -1
- package/lib/Utils/a2ui.js +217 -1
- package/lib/Utils/a2ui.js.map +1 -1
- package/lib/Utils/generics.js +1 -1
- package/lib/Utils/history.d.ts +2 -2
- package/lib/Utils/html-apps.d.ts +30 -0
- package/lib/Utils/html-apps.d.ts.map +1 -0
- package/lib/Utils/html-apps.js +99 -0
- package/lib/Utils/html-apps.js.map +1 -0
- package/lib/Utils/html-multiplayer.d.ts +10 -0
- package/lib/Utils/html-multiplayer.d.ts.map +1 -0
- package/lib/Utils/html-multiplayer.js +90 -0
- package/lib/Utils/html-multiplayer.js.map +1 -0
- package/lib/Utils/index.d.ts +9 -0
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +9 -0
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/mbuilder-airich.d.ts +124 -0
- package/lib/Utils/mbuilder-airich.d.ts.map +1 -0
- package/lib/Utils/mbuilder-airich.js +960 -0
- package/lib/Utils/mbuilder-airich.js.map +1 -0
- package/lib/Utils/mbuilder-base.d.ts +32 -0
- package/lib/Utils/mbuilder-base.d.ts.map +1 -0
- package/lib/Utils/mbuilder-base.js +65 -0
- package/lib/Utils/mbuilder-base.js.map +1 -0
- package/lib/Utils/mbuilder-buttonv2.d.ts +27 -0
- package/lib/Utils/mbuilder-buttonv2.d.ts.map +1 -0
- package/lib/Utils/mbuilder-buttonv2.js +165 -0
- package/lib/Utils/mbuilder-buttonv2.js.map +1 -0
- package/lib/Utils/mbuilder-carousel.d.ts +21 -0
- package/lib/Utils/mbuilder-carousel.d.ts.map +1 -0
- package/lib/Utils/mbuilder-carousel.js +120 -0
- package/lib/Utils/mbuilder-carousel.js.map +1 -0
- package/lib/Utils/mbuilder-toolkit.d.ts +90 -0
- package/lib/Utils/mbuilder-toolkit.d.ts.map +1 -0
- package/lib/Utils/mbuilder-toolkit.js +266 -0
- package/lib/Utils/mbuilder-toolkit.js.map +1 -0
- package/lib/Utils/mbuilder-utils.d.ts +69 -0
- package/lib/Utils/mbuilder-utils.d.ts.map +1 -0
- package/lib/Utils/mbuilder-utils.js +214 -0
- package/lib/Utils/mbuilder-utils.js.map +1 -0
- package/lib/Utils/messages.d.ts +1 -0
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +66 -9
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/scheduled-message.d.ts +75 -0
- package/lib/Utils/scheduled-message.d.ts.map +1 -0
- package/lib/Utils/scheduled-message.js +101 -0
- package/lib/Utils/scheduled-message.js.map +1 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +1 -7
- package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -1
- package/lib/Utils/use-multi-file-auth-state.js +39 -47
- package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/package.json +3 -2
|
@@ -0,0 +1,960 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Do not remove this watermark.
|
|
4
|
+
*
|
|
5
|
+
* NIXCODE - Advanced WhatsApp Interactive Message Builder
|
|
6
|
+
* Created by Nixel
|
|
7
|
+
* Contributors: ~ Ahmad tumbuh kembang
|
|
8
|
+
*
|
|
9
|
+
* Copyright (c) 2026 Nixel
|
|
10
|
+
* Permission is granted to use and modify this library for personal or commercial projects.
|
|
11
|
+
*/
|
|
12
|
+
'use strict';
|
|
13
|
+
import crypto from 'crypto';
|
|
14
|
+
import { generateWAMessageFromContent, generateMessageIDV2 } from 'baileys';
|
|
15
|
+
import { BaseBuilder } from './mbuilder-base.js';
|
|
16
|
+
import { Toolkit } from './mbuilder-toolkit.js';
|
|
17
|
+
import { extractIE, waitAllPromises, AIRichError, ItemNotFoundError, DuplicateIdError, InvalidTargetError, ContentValidationError } from './mbuilder-utils.js';
|
|
18
|
+
const VERSION = '4.7';
|
|
19
|
+
export class AIRich extends BaseBuilder {
|
|
20
|
+
constructor(client, { dynamic = true, unsupportedTypeAlert = true } = {}) {
|
|
21
|
+
if (!client) {
|
|
22
|
+
throw new Error('Socket is required');
|
|
23
|
+
}
|
|
24
|
+
super();
|
|
25
|
+
this._client = client;
|
|
26
|
+
this._contextInfo = {};
|
|
27
|
+
this._nodes = [];
|
|
28
|
+
this._idIndex = new Map();
|
|
29
|
+
this._unsupportedTypeAlert = !!unsupportedTypeAlert;
|
|
30
|
+
this._dynamic = !!dynamic;
|
|
31
|
+
this._responseId = crypto.randomUUID();
|
|
32
|
+
this._botResponseId = crypto.randomUUID();
|
|
33
|
+
this._lastMessageKey = null;
|
|
34
|
+
}
|
|
35
|
+
setTitle(title) {
|
|
36
|
+
this._title = title;
|
|
37
|
+
return this;
|
|
38
|
+
}
|
|
39
|
+
setBotMetadata(meta) {
|
|
40
|
+
this._extraPayload = { ...this._extraPayload, botMetadata: { ...this._extraPayload?.botMetadata, ...meta } };
|
|
41
|
+
return this;
|
|
42
|
+
}
|
|
43
|
+
loadFrom(msg) {
|
|
44
|
+
if (!msg)
|
|
45
|
+
throw new Error('AI Rich message needed');
|
|
46
|
+
const message = msg.message ?? msg;
|
|
47
|
+
let richResponseMessage = message?.botForwardedMessage?.message?.richResponseMessage;
|
|
48
|
+
if (!richResponseMessage) {
|
|
49
|
+
richResponseMessage = message?.botForwardedMessage?.richResponseMessage;
|
|
50
|
+
}
|
|
51
|
+
if (!richResponseMessage) {
|
|
52
|
+
richResponseMessage = message?.richResponseMessage;
|
|
53
|
+
}
|
|
54
|
+
if (!richResponseMessage) {
|
|
55
|
+
throw new Error('richResponseMessage not found');
|
|
56
|
+
}
|
|
57
|
+
const messageContextInfo = message?.messageContextInfo ?? {};
|
|
58
|
+
const botMetadata = messageContextInfo?.botMetadata ?? {};
|
|
59
|
+
this._title = botMetadata?.messageDisclaimerText ?? '';
|
|
60
|
+
this._contextInfo = structuredClone(richResponseMessage?.contextInfo ?? {});
|
|
61
|
+
const loadedSubmessages = Array.isArray(richResponseMessage?.submessages) ? structuredClone(richResponseMessage.submessages) : [];
|
|
62
|
+
let loadedSections = [];
|
|
63
|
+
const unifiedData = richResponseMessage?.unifiedResponse?.data;
|
|
64
|
+
if (unifiedData) {
|
|
65
|
+
try {
|
|
66
|
+
const decoded = Buffer.from(unifiedData, 'base64').toString('utf8');
|
|
67
|
+
const unifiedResponse = JSON.parse(decoded);
|
|
68
|
+
if (Array.isArray(unifiedResponse?.sections)) {
|
|
69
|
+
loadedSections = structuredClone(unifiedResponse.sections);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch { }
|
|
73
|
+
}
|
|
74
|
+
this._nodes = [];
|
|
75
|
+
this._idIndex = new Map();
|
|
76
|
+
const maxLength = Math.max(loadedSections.length, loadedSubmessages.length);
|
|
77
|
+
for (let i = 0; i < maxLength; i++) {
|
|
78
|
+
this._nodes.push({
|
|
79
|
+
id: null,
|
|
80
|
+
section: loadedSections[i] ?? null,
|
|
81
|
+
submessage: loadedSubmessages[i] ?? null,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
this._extraPayload = {};
|
|
85
|
+
for (const [key, value] of Object.entries(message)) {
|
|
86
|
+
if (key !== 'messageContextInfo' && key !== 'botForwardedMessage' && key !== 'richResponseMessage') {
|
|
87
|
+
this._extraPayload[key] = structuredClone(value);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
setResponseId(id) {
|
|
93
|
+
if (typeof id !== 'string')
|
|
94
|
+
throw new TypeError('ID must be a string');
|
|
95
|
+
this._responseId = id;
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
refreshResponseId() {
|
|
99
|
+
this._responseId = crypto.randomUUID();
|
|
100
|
+
return this;
|
|
101
|
+
}
|
|
102
|
+
setBotResponseId(id) {
|
|
103
|
+
if (typeof id !== 'string')
|
|
104
|
+
throw new TypeError('ID must be a string');
|
|
105
|
+
this._botResponseId = id;
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
refreshBotResponseId() {
|
|
109
|
+
this._botResponseId = crypto.randomUUID();
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
createAlert(type) {
|
|
113
|
+
if (this._unsupportedTypeAlert) {
|
|
114
|
+
return { messageType: 2, messageText: `[ UNSUPPORTED_TYPE - ${type}]` };
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
addText(text, { hyperlink = true, citation = true, latex = true, id, replace, insertAt } = {}) {
|
|
119
|
+
if (typeof text !== 'string')
|
|
120
|
+
throw new TypeError('Text must be a string');
|
|
121
|
+
const { text: extractedText, inline_entities } = extractIE(text, { hyperlink, citation, latex });
|
|
122
|
+
const section = AIRich.newLayout('Single', {
|
|
123
|
+
text: extractedText,
|
|
124
|
+
...(inline_entities.length && { inline_entities }),
|
|
125
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
126
|
+
});
|
|
127
|
+
const submessages = [{ messageType: 2, messageText: text }].filter(Boolean);
|
|
128
|
+
return this._addContent(section, submessages, { id, replace, insertAt });
|
|
129
|
+
}
|
|
130
|
+
addFOAText(text, { id, replace, insertAt } = {}) {
|
|
131
|
+
if (typeof text !== 'string')
|
|
132
|
+
throw new TypeError('Text must be a string');
|
|
133
|
+
const section = AIRich.newLayout('Single', {
|
|
134
|
+
text,
|
|
135
|
+
__typename: 'FOATextPrimitive',
|
|
136
|
+
});
|
|
137
|
+
const submessages = [{ messageType: 2, messageText: text }];
|
|
138
|
+
return this._addContent(section, submessages, { id, replace, insertAt });
|
|
139
|
+
}
|
|
140
|
+
addCode(language, code, { id, replace, insertAt } = {}) {
|
|
141
|
+
if (typeof language !== 'string' || typeof code !== 'string') {
|
|
142
|
+
throw new TypeError('Language and code must be a string');
|
|
143
|
+
}
|
|
144
|
+
const meta = AIRich.tokenizer(code, language);
|
|
145
|
+
const section = AIRich.newLayout('Single', {
|
|
146
|
+
language,
|
|
147
|
+
code_blocks: meta.unified_codeBlock,
|
|
148
|
+
__typename: 'GenAICodeUXPrimitive',
|
|
149
|
+
});
|
|
150
|
+
const submessages = [{
|
|
151
|
+
messageType: 5,
|
|
152
|
+
codeMetadata: {
|
|
153
|
+
codeLanguage: language,
|
|
154
|
+
codeBlocks: meta.codeBlock,
|
|
155
|
+
},
|
|
156
|
+
}];
|
|
157
|
+
return this._addContent(section, submessages, { id, replace, insertAt });
|
|
158
|
+
}
|
|
159
|
+
addTable(table, { hyperlink = true, citation = true, latex = true, id, replace, insertAt } = {}) {
|
|
160
|
+
if (!Array.isArray(table))
|
|
161
|
+
throw new TypeError('Table must be an array');
|
|
162
|
+
const meta = AIRich.toTableMetadata(table, { hyperlink, citation, latex });
|
|
163
|
+
const section = AIRich.newLayout('Single', {
|
|
164
|
+
rows: meta.unified_rows,
|
|
165
|
+
__typename: 'GenATableUXPrimitive',
|
|
166
|
+
});
|
|
167
|
+
const submessages = [{
|
|
168
|
+
messageType: 4,
|
|
169
|
+
tableMetadata: {
|
|
170
|
+
title: meta.title,
|
|
171
|
+
rows: meta.rows,
|
|
172
|
+
},
|
|
173
|
+
}];
|
|
174
|
+
return this._addContent(section, submessages, { id, replace, insertAt });
|
|
175
|
+
}
|
|
176
|
+
addSource(sources = [], { id, replace, insertAt } = {}) {
|
|
177
|
+
if (!Array.isArray(sources)) {
|
|
178
|
+
throw new TypeError('Sources must be an array of strings, arrays, or objects');
|
|
179
|
+
}
|
|
180
|
+
const isStringArray = sources.every((item) => typeof item === 'string');
|
|
181
|
+
const isArrayFormat = sources.every((item) => Array.isArray(item) && item.every((value) => typeof value === 'string'));
|
|
182
|
+
const isObjectFormat = sources.every((item) => item && typeof item === 'object' && !Array.isArray(item));
|
|
183
|
+
if (!isStringArray && !isArrayFormat && !isObjectFormat) {
|
|
184
|
+
throw new TypeError('Sources must be a string array, array of string arrays, or array of objects');
|
|
185
|
+
}
|
|
186
|
+
if (isStringArray)
|
|
187
|
+
sources = [sources];
|
|
188
|
+
const normalizedSources = sources.map((source) => {
|
|
189
|
+
if (Array.isArray(source)) {
|
|
190
|
+
const [icon, url, title, subtitle] = source;
|
|
191
|
+
return { icon, url, title, subtitle };
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
icon: source.favicon ?? source.icon ?? '',
|
|
195
|
+
url: source.url ?? '',
|
|
196
|
+
title: source.title ?? '',
|
|
197
|
+
subtitle: source.subtitle ?? '',
|
|
198
|
+
};
|
|
199
|
+
});
|
|
200
|
+
const source = normalizedSources.map(({ icon, url, title, subtitle }) => ({
|
|
201
|
+
source_type: 'THIRD_PARTY',
|
|
202
|
+
source_display_name: title,
|
|
203
|
+
source_subtitle: subtitle,
|
|
204
|
+
source_url: url,
|
|
205
|
+
favicon: {
|
|
206
|
+
url: Toolkit.resolveMedia(this._client, icon, 'image'),
|
|
207
|
+
mime_type: 'image/jpeg',
|
|
208
|
+
width: 16,
|
|
209
|
+
height: 16,
|
|
210
|
+
},
|
|
211
|
+
}));
|
|
212
|
+
const submessage = this.createAlert('GenAISearchResultPrimitive');
|
|
213
|
+
const section = AIRich.newLayout('Single', {
|
|
214
|
+
sources: source,
|
|
215
|
+
__typename: 'GenAISearchResultPrimitive',
|
|
216
|
+
});
|
|
217
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
218
|
+
}
|
|
219
|
+
addReels(reelsItems = [], { id, replace, insertAt } = {}) {
|
|
220
|
+
if (!((reelsItems && typeof reelsItems === 'object' && !Array.isArray(reelsItems)) ||
|
|
221
|
+
(Array.isArray(reelsItems) && reelsItems.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
|
|
222
|
+
throw new TypeError('Reels items must be an object or an array of objects');
|
|
223
|
+
}
|
|
224
|
+
const items = Array.isArray(reelsItems) ? reelsItems : [reelsItems];
|
|
225
|
+
const reels = items.map((item) => ({
|
|
226
|
+
...item,
|
|
227
|
+
_avatar: Toolkit.resolveMedia(this._client, item.profileIconUrl ?? item.profile_url ?? item.profile ?? '', 'image'),
|
|
228
|
+
_thumbnail: Toolkit.resolveMedia(this._client, item.thumbnailUrl ?? item.thumbnail ?? '', 'image'),
|
|
229
|
+
}));
|
|
230
|
+
const section = AIRich.newLayout('HScroll', reels.map((item) => ({
|
|
231
|
+
reels_url: item.videoUrl ?? item.url ?? '',
|
|
232
|
+
thumbnail_url: item._thumbnail,
|
|
233
|
+
creator: item.username ?? item.title ?? '',
|
|
234
|
+
avatar_url: item._avatar,
|
|
235
|
+
reels_title: item.reels_title ?? item.title ?? '',
|
|
236
|
+
likes_count: item.likes_count ?? item.like ?? 0,
|
|
237
|
+
shares_count: item.shares_count ?? item.share ?? 0,
|
|
238
|
+
view_count: item.view_count ?? item.view ?? 0,
|
|
239
|
+
reel_source: item.reel_source ?? item.source ?? 'IG',
|
|
240
|
+
is_verified: !!(item.is_verified || item.verified),
|
|
241
|
+
__typename: 'GenAIReelPrimitive',
|
|
242
|
+
})));
|
|
243
|
+
const submessages = [{
|
|
244
|
+
messageType: 9,
|
|
245
|
+
contentItemsMetadata: {
|
|
246
|
+
contentType: 1,
|
|
247
|
+
itemsMetadata: reels.map((item) => ({
|
|
248
|
+
reelItem: {
|
|
249
|
+
title: item.username ?? '',
|
|
250
|
+
profileIconUrl: item._avatar,
|
|
251
|
+
thumbnailUrl: item._thumbnail,
|
|
252
|
+
videoUrl: item.videoUrl ?? item.url ?? '',
|
|
253
|
+
},
|
|
254
|
+
})),
|
|
255
|
+
},
|
|
256
|
+
}];
|
|
257
|
+
return this._addContent(section, submessages, { id, replace, insertAt });
|
|
258
|
+
}
|
|
259
|
+
addImage(imageUrl, { width, height, status = 'READY', update_text, resolveUrl = false, id, replace, insertAt } = {}) {
|
|
260
|
+
if (!(typeof imageUrl === 'string' || Buffer.isBuffer(imageUrl) || (Array.isArray(imageUrl) && imageUrl.every((v) => typeof v === 'string' || Buffer.isBuffer(v))))) {
|
|
261
|
+
throw new TypeError('imageUrl must be string | buffer | array of string/buffer');
|
|
262
|
+
}
|
|
263
|
+
const list = Array.isArray(imageUrl)
|
|
264
|
+
? imageUrl.map((v) => {
|
|
265
|
+
const url = Toolkit.resolveMedia(this._client, v, 'image', { resolveUrl });
|
|
266
|
+
return { imagePreviewUrl: url, imageHighResUrl: url, sourceUrl: url };
|
|
267
|
+
})
|
|
268
|
+
: (() => {
|
|
269
|
+
const url = Toolkit.resolveMedia(this._client, imageUrl, 'image', { resolveUrl });
|
|
270
|
+
return [{ imagePreviewUrl: url, imageHighResUrl: url, sourceUrl: url }];
|
|
271
|
+
})();
|
|
272
|
+
const sections = list.map(({ imagePreviewUrl }) => AIRich.newLayout('Single', {
|
|
273
|
+
media: { url: imagePreviewUrl, mime_type: 'image/png', width, height },
|
|
274
|
+
imagine_type: 'IMAGE',
|
|
275
|
+
status: { status, update_text },
|
|
276
|
+
__typename: 'GenAIImaginePrimitive',
|
|
277
|
+
}));
|
|
278
|
+
const submessage = {
|
|
279
|
+
messageType: 1,
|
|
280
|
+
gridImageMetadata: {
|
|
281
|
+
gridImageUrl: { imagePreviewUrl: list[0]?.imagePreviewUrl },
|
|
282
|
+
imageUrls: list,
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
if (id && sections.length !== 1) {
|
|
286
|
+
throw new Error('Cannot assign one id to multiple image sections');
|
|
287
|
+
}
|
|
288
|
+
return this._addContent(sections, submessage, { id, replace, insertAt });
|
|
289
|
+
}
|
|
290
|
+
addVideo(videoUrl, { autoFill = true, status = 'READY', estimatedTime, id, replace, insertAt } = {}) {
|
|
291
|
+
const isObjectVideo = (v) => v && typeof v === 'object' && !Array.isArray(v) && v.url;
|
|
292
|
+
const isValidPrimitive = typeof videoUrl === 'string' ||
|
|
293
|
+
Buffer.isBuffer(videoUrl) ||
|
|
294
|
+
isObjectVideo(videoUrl) ||
|
|
295
|
+
(Array.isArray(videoUrl) && videoUrl.every((v) => typeof v === 'string' || Buffer.isBuffer(v) || isObjectVideo(v)));
|
|
296
|
+
if (!isValidPrimitive)
|
|
297
|
+
throw new TypeError('videoUrl must be string | buffer | object | array');
|
|
298
|
+
const items = Array.isArray(videoUrl) ? videoUrl : [videoUrl];
|
|
299
|
+
const alert = this.createAlert('GenAIImaginePrimitive (ANIMATE)');
|
|
300
|
+
const sections = [];
|
|
301
|
+
const submessages = [];
|
|
302
|
+
for (const item of items) {
|
|
303
|
+
const isObject = isObjectVideo(item);
|
|
304
|
+
const url = isObject ? Toolkit.resolveMedia(this._client, item.url ?? '', 'video') : Toolkit.resolveMedia(this._client, item, 'video');
|
|
305
|
+
const bufferPromise = autoFill ? Promise.resolve(url).then((u) => Toolkit.fetchBuffer(u)) : null;
|
|
306
|
+
const file_length = isObject && item.file_length != null ? item.file_length : autoFill ? bufferPromise.then((b) => b?.length ?? 0) : 0;
|
|
307
|
+
const duration = isObject && item.duration != null
|
|
308
|
+
? item.duration
|
|
309
|
+
: autoFill
|
|
310
|
+
? bufferPromise.then((b) => Toolkit.getMp4Duration(b, { silent: true }))
|
|
311
|
+
: 0;
|
|
312
|
+
const thumbnail = isObject && item.thumbnail
|
|
313
|
+
? Toolkit.resolveMedia(this._client, item.thumbnail, 'image', { result: 'base64', resize: true, width: 300, height: 300 })
|
|
314
|
+
: autoFill
|
|
315
|
+
? bufferPromise?.then((b) => Toolkit.getMp4Preview(b, { time: 0, result: 'base64' }))
|
|
316
|
+
: null;
|
|
317
|
+
sections.push(AIRich.newLayout('Single', {
|
|
318
|
+
media: {
|
|
319
|
+
url,
|
|
320
|
+
mime_type: isObject ? (item.mime_type ?? 'video/mp4') : 'video/mp4',
|
|
321
|
+
file_length,
|
|
322
|
+
duration,
|
|
323
|
+
},
|
|
324
|
+
imagine_type: 'ANIMATE',
|
|
325
|
+
status: {
|
|
326
|
+
status,
|
|
327
|
+
estimated_completion_time: estimatedTime != null ? Math.floor((Date.now() + estimatedTime) / 1000) : undefined,
|
|
328
|
+
},
|
|
329
|
+
thumbnail: { raw_media: thumbnail },
|
|
330
|
+
__typename: 'GenAIImaginePrimitive',
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
if (alert !== undefined)
|
|
334
|
+
submessages.push(alert);
|
|
335
|
+
if (submessages.length > 1)
|
|
336
|
+
throw new Error('Video content can only have one submessage');
|
|
337
|
+
return this._addContent(sections, submessages[0], { id, replace, insertAt });
|
|
338
|
+
}
|
|
339
|
+
addProduct(data = {}, { id, replace, insertAt } = {}) {
|
|
340
|
+
if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
|
|
341
|
+
throw new TypeError('Product items must be an object or an array of objects');
|
|
342
|
+
}
|
|
343
|
+
const items = Array.isArray(data) ? data : [data];
|
|
344
|
+
const product = items.map((item) => ({
|
|
345
|
+
title: item.title,
|
|
346
|
+
brand: item.brand,
|
|
347
|
+
price: item.price,
|
|
348
|
+
sale_price: item.sale_price,
|
|
349
|
+
product_url: item.product_url ?? item.url,
|
|
350
|
+
image: { url: Toolkit.resolveMedia(this._client, item.image_url ?? item.image, 'image') },
|
|
351
|
+
additional_images: [{ url: Toolkit.resolveMedia(this._client, item.icon_url ?? item.icon, 'image') }],
|
|
352
|
+
__typename: 'GenAIProductItemCardPrimitive',
|
|
353
|
+
}));
|
|
354
|
+
const section = AIRich.newLayout(Array.isArray(data) ? 'HScroll' : 'Single', Array.isArray(data) ? product : product[0]);
|
|
355
|
+
const submessage = this.createAlert('GenAIProductItemCardPrimitive');
|
|
356
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
357
|
+
}
|
|
358
|
+
addPost(data = {}, { id, replace, insertAt } = {}) {
|
|
359
|
+
if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
|
|
360
|
+
throw new TypeError('Post items must be an object or an array of objects');
|
|
361
|
+
}
|
|
362
|
+
const posts = Array.isArray(data) ? data : [data];
|
|
363
|
+
const primitives = posts.map((p) => ({
|
|
364
|
+
title: p.title ?? '',
|
|
365
|
+
subtitle: p.subtitle ?? '',
|
|
366
|
+
username: p.username ?? '',
|
|
367
|
+
profile_picture_url: Toolkit.resolveMedia(this._client, p.profile_picture_url ?? p.profile_url ?? p.profile ?? '', 'image'),
|
|
368
|
+
is_verified: !!(p.is_verified || p.verified),
|
|
369
|
+
thumbnail_url: Toolkit.resolveMedia(this._client, p.thumbnail_url ?? p.thumbnail ?? '', 'image'),
|
|
370
|
+
post_caption: p.post_caption ?? p.caption ?? '',
|
|
371
|
+
likes_count: p.likes_count ?? p.like ?? 0,
|
|
372
|
+
comments_count: p.comments_count ?? p.comment ?? 0,
|
|
373
|
+
shares_count: p.shares_count ?? p.share ?? 0,
|
|
374
|
+
post_url: p.post_url ?? p.url ?? '',
|
|
375
|
+
post_deeplink: p.post_deeplink ?? p.deeplink ?? '',
|
|
376
|
+
source_app: p.source_app || p.source || 'INSTAGRAM',
|
|
377
|
+
footer_label: p.footer_label ?? p.footer ?? '',
|
|
378
|
+
footer_icon: Toolkit.resolveMedia(this._client, p.footer_icon ?? p.icon ?? '', 'image'),
|
|
379
|
+
is_carousel: posts.length > 1,
|
|
380
|
+
orientation: p.orientation ?? 'LANDSCAPE',
|
|
381
|
+
post_type: p.post_type ?? 'VIDEO',
|
|
382
|
+
__typename: 'GenAIPostPrimitive',
|
|
383
|
+
}));
|
|
384
|
+
const section = AIRich.newLayout('HScroll', primitives);
|
|
385
|
+
const submessage = this.createAlert('GenAIPostPrimitive');
|
|
386
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
387
|
+
}
|
|
388
|
+
addMetadata(text, { id, replace, insertAt } = {}) {
|
|
389
|
+
if (typeof text !== 'string')
|
|
390
|
+
throw new TypeError('Text must be a string');
|
|
391
|
+
const section = AIRich.newLayout('Single', { text, __typename: 'GenAIMetadataTextPrimitive' });
|
|
392
|
+
const submessage = { messageType: 2, messageText: text };
|
|
393
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
394
|
+
}
|
|
395
|
+
addTip(text, { id, replace, insertAt } = {}) {
|
|
396
|
+
if (typeof text !== 'string')
|
|
397
|
+
throw new TypeError('Text must be a string');
|
|
398
|
+
const section = AIRich.newLayout('Single', { text: 'ⓘ ' + text, __typename: 'GenAIMetadataTextPrimitive' });
|
|
399
|
+
const submessage = { messageType: 2, messageText: text };
|
|
400
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
401
|
+
}
|
|
402
|
+
addWidget(data, { layout, id, replace, insertAt, ...options } = {}) {
|
|
403
|
+
if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
|
|
404
|
+
throw new TypeError('Widget must be an object or an array of objects');
|
|
405
|
+
}
|
|
406
|
+
const isArray = Array.isArray(data);
|
|
407
|
+
const items = isArray ? data : [data];
|
|
408
|
+
const widgets = items.map((item) => ({
|
|
409
|
+
__typename: 'GenAI3PExtWidgetPrimitive',
|
|
410
|
+
header: {
|
|
411
|
+
__typename: 'GenAI3PExtWidgetStandardHeader',
|
|
412
|
+
title: item.title ?? '',
|
|
413
|
+
...(item.header ?? {}),
|
|
414
|
+
},
|
|
415
|
+
body: {
|
|
416
|
+
__typename: 'GenAI3PExtCalendarEventList',
|
|
417
|
+
sections: item.sections ?? [],
|
|
418
|
+
ctas: (item.actions ?? []).map((action) => ({
|
|
419
|
+
__typename: 'GenAI3PExtWidgetCTA',
|
|
420
|
+
label: action.label ?? '',
|
|
421
|
+
state: action.state ?? 'PENDING',
|
|
422
|
+
kind: action.kind ?? 'OTHER',
|
|
423
|
+
tool_call_id: action.tool_call_id ?? action.id ?? '',
|
|
424
|
+
...(action.toast && {
|
|
425
|
+
toast: {
|
|
426
|
+
__typename: 'GenAI3PExtWidgetToast',
|
|
427
|
+
label: action.toast.label ?? action.label ?? '',
|
|
428
|
+
},
|
|
429
|
+
}),
|
|
430
|
+
})),
|
|
431
|
+
...(item.body ?? {}),
|
|
432
|
+
},
|
|
433
|
+
}));
|
|
434
|
+
const section = AIRich.newLayout(layout ?? (isArray ? 'HScroll' : 'Single'), isArray ? widgets : widgets[0], options);
|
|
435
|
+
const submessage = this.createAlert('GenAI3PExtWidgetStandardHeader');
|
|
436
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
437
|
+
}
|
|
438
|
+
addFooterAction(data, { layout, id, replace, insertAt, ...options } = {}) {
|
|
439
|
+
if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
|
|
440
|
+
throw new TypeError('Footer action must be an object or an array of objects');
|
|
441
|
+
}
|
|
442
|
+
const isArray = Array.isArray(data);
|
|
443
|
+
const items = isArray ? data : [data];
|
|
444
|
+
const actions = items.map((item) => ({
|
|
445
|
+
__typename: 'GenAIFooterActionPrimitive',
|
|
446
|
+
cta_text: item.text ?? item.cta_text ?? '',
|
|
447
|
+
cta_type: item.type ?? item.cta_type ?? 'OPEN_URL',
|
|
448
|
+
cta_url: item.url ?? item.cta_url ?? '',
|
|
449
|
+
}));
|
|
450
|
+
const section = AIRich.newLayout(layout ?? (isArray ? 'HScroll' : 'Single'), isArray ? actions : actions[0], options);
|
|
451
|
+
const submessage = this.createAlert('GenAIFooterActionPrimitive');
|
|
452
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
453
|
+
}
|
|
454
|
+
addSuggest(suggestion, { scroll = true, layout, id, replace, insertAt } = {}) {
|
|
455
|
+
if (!(typeof suggestion === 'string' || (Array.isArray(suggestion) && suggestion.every((v) => typeof v === 'string')))) {
|
|
456
|
+
throw new TypeError('Suggestion must be a string or array of strings');
|
|
457
|
+
}
|
|
458
|
+
const suggest = Array.isArray(suggestion)
|
|
459
|
+
? suggestion.map((text) => ({
|
|
460
|
+
prompt_text: text,
|
|
461
|
+
prompt_type: 'SUGGESTED_PROMPT',
|
|
462
|
+
__typename: 'GenAIFollowUpSuggestionPillPrimitive',
|
|
463
|
+
}))
|
|
464
|
+
: [{ prompt_text: suggestion, prompt_type: 'SUGGESTED_PROMPT', __typename: 'GenAIFollowUpSuggestionPillPrimitive' }];
|
|
465
|
+
const type = layout ?? (suggest.length === 1 ? 'Single' : scroll ? 'HScroll' : 'ActionRow');
|
|
466
|
+
const section = AIRich.newLayout(type, type === 'Single' ? suggest[0] : suggest, { __typename: 'GenAIUnifiedResponseSection' });
|
|
467
|
+
const submessage = this.createAlert('GenAIFollowUpSuggestionPillPrimitive');
|
|
468
|
+
return this._addContent(section, submessage, { id, replace, insertAt });
|
|
469
|
+
}
|
|
470
|
+
async build(jid, { bypassDownload = true, forwarded = true, notification = false, includesUnifiedResponse = true, includesSubmessages = true, quoted, quotedParticipant, messageId, ...options } = {}) {
|
|
471
|
+
const forward = forwarded
|
|
472
|
+
? {
|
|
473
|
+
forwardingScore: 1,
|
|
474
|
+
isForwarded: true,
|
|
475
|
+
forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
|
|
476
|
+
forwardOrigin: 4,
|
|
477
|
+
}
|
|
478
|
+
: {};
|
|
479
|
+
const notif = notification
|
|
480
|
+
? {
|
|
481
|
+
sessionTransparencyMetadata: {
|
|
482
|
+
disclaimerText: '~ Ahmad tumbuh kembang',
|
|
483
|
+
hcaId: `hca_${Date.now()}`,
|
|
484
|
+
sessionTransparencyType: 1,
|
|
485
|
+
},
|
|
486
|
+
}
|
|
487
|
+
: {};
|
|
488
|
+
const qObj = quoted
|
|
489
|
+
? {
|
|
490
|
+
stanzaId: quoted?.key?.id || quoted?.id,
|
|
491
|
+
participant: quotedParticipant || quoted?.key?.participant || quoted?.participant || quoted?.key?.remoteJid,
|
|
492
|
+
quotedType: 0,
|
|
493
|
+
quotedMessage: typeof quoted === 'object' && quoted !== null ? (quoted.message ?? quoted) : undefined,
|
|
494
|
+
}
|
|
495
|
+
: {};
|
|
496
|
+
const sections = this._footer
|
|
497
|
+
? [
|
|
498
|
+
...(await waitAllPromises(this._sections)),
|
|
499
|
+
AIRich.newLayout('Single', {
|
|
500
|
+
text: this._footer,
|
|
501
|
+
__typename: 'GenAIMetadataTextPrimitive',
|
|
502
|
+
}),
|
|
503
|
+
]
|
|
504
|
+
: [...(await waitAllPromises(this._sections))];
|
|
505
|
+
if (this._dynamic) {
|
|
506
|
+
this.refreshResponseId();
|
|
507
|
+
this.refreshBotResponseId();
|
|
508
|
+
}
|
|
509
|
+
return generateWAMessageFromContent(jid, {
|
|
510
|
+
messageContextInfo: {
|
|
511
|
+
deviceListMetadata: {},
|
|
512
|
+
deviceListMetadataVersion: 2,
|
|
513
|
+
botMetadata: {
|
|
514
|
+
messageDisclaimerText: this._title,
|
|
515
|
+
...notif,
|
|
516
|
+
verificationMetadata: AIRich.generateVerificationMetadata(),
|
|
517
|
+
botResponseId: this._botResponseId,
|
|
518
|
+
...(this._extraPayload?.botMetadata || {}),
|
|
519
|
+
},
|
|
520
|
+
},
|
|
521
|
+
...this._extraPayload,
|
|
522
|
+
botForwardedMessage: {
|
|
523
|
+
message: {
|
|
524
|
+
richResponseMessage: {
|
|
525
|
+
messageType: 1,
|
|
526
|
+
submessages: includesSubmessages ? await waitAllPromises(this._submessages) : [],
|
|
527
|
+
unifiedResponse: {
|
|
528
|
+
data: includesUnifiedResponse ? Buffer.from(Toolkit.stringifyEscaped({ response_id: this._responseId, sections })).toString('base64') : '',
|
|
529
|
+
},
|
|
530
|
+
contextInfo: {
|
|
531
|
+
...forward,
|
|
532
|
+
...qObj,
|
|
533
|
+
...this._contextInfo,
|
|
534
|
+
},
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
},
|
|
538
|
+
}, { messageId: messageId || generateMessageIDV2(), ...options });
|
|
539
|
+
}
|
|
540
|
+
async buildEdit(targetJid, targetId, { msg, messageId, ...options } = {}) {
|
|
541
|
+
if (!msg) {
|
|
542
|
+
msg = (await this.build(targetJid, options)).message;
|
|
543
|
+
}
|
|
544
|
+
const editedMessage = msg;
|
|
545
|
+
if (!editedMessage) {
|
|
546
|
+
throw new Error('buildEdit: msg does not contain botForwardedMessage');
|
|
547
|
+
}
|
|
548
|
+
return generateWAMessageFromContent(targetJid, {
|
|
549
|
+
botForwardedMessage: {
|
|
550
|
+
message: {
|
|
551
|
+
protocolMessage: {
|
|
552
|
+
key: {
|
|
553
|
+
remoteJid: targetJid,
|
|
554
|
+
fromMe: true,
|
|
555
|
+
id: targetId,
|
|
556
|
+
},
|
|
557
|
+
type: 14,
|
|
558
|
+
editedMessage,
|
|
559
|
+
},
|
|
560
|
+
},
|
|
561
|
+
},
|
|
562
|
+
}, { messageId: messageId || generateMessageIDV2(), ...options });
|
|
563
|
+
}
|
|
564
|
+
async sendEdit(jid, id, { msg, messageId, additionalNodes = [], ...options } = {}) {
|
|
565
|
+
jid = jid ?? this._lastMessageKey?.remoteJid;
|
|
566
|
+
id = id ?? this._lastMessageKey?.id;
|
|
567
|
+
if (!jid)
|
|
568
|
+
throw new Error('JID is required');
|
|
569
|
+
if (!id)
|
|
570
|
+
throw new Error('Message id is required');
|
|
571
|
+
const msgEdit = await this.buildEdit(jid, id, { msg, messageId: messageId || generateMessageIDV2(), ...options });
|
|
572
|
+
await this._client.relayMessage(jid, msgEdit.message, {
|
|
573
|
+
messageId: msgEdit.key.id,
|
|
574
|
+
additionalNodes,
|
|
575
|
+
});
|
|
576
|
+
return msgEdit;
|
|
577
|
+
}
|
|
578
|
+
async send(jid, { bypassDownload = true, forwarded = true, notification = false, includesUnifiedResponse = true, includesSubmessages = true, messageId, additionalNodes = [], ...options } = {}) {
|
|
579
|
+
const msg = await this.build(jid, {
|
|
580
|
+
forwarded,
|
|
581
|
+
notification,
|
|
582
|
+
includesUnifiedResponse,
|
|
583
|
+
includesSubmessages,
|
|
584
|
+
messageId,
|
|
585
|
+
...options,
|
|
586
|
+
});
|
|
587
|
+
await this._client.relayMessage(msg.key.remoteJid, msg.message, {
|
|
588
|
+
messageId: msg.key.id,
|
|
589
|
+
additionalNodes,
|
|
590
|
+
...options,
|
|
591
|
+
});
|
|
592
|
+
if (includesUnifiedResponse && bypassDownload) {
|
|
593
|
+
await this.sendEdit(jid, msg.key.id, { msg: msg.message });
|
|
594
|
+
}
|
|
595
|
+
this._lastMessageKey = msg.key;
|
|
596
|
+
return msg;
|
|
597
|
+
}
|
|
598
|
+
static tokenizer(code, lang = 'javascript') {
|
|
599
|
+
const keywordsMap = {
|
|
600
|
+
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']),
|
|
601
|
+
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']),
|
|
602
|
+
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']),
|
|
603
|
+
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']),
|
|
604
|
+
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']),
|
|
605
|
+
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']),
|
|
606
|
+
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']),
|
|
607
|
+
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']),
|
|
608
|
+
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']),
|
|
609
|
+
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']),
|
|
610
|
+
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']),
|
|
611
|
+
markdown: new Set(['#', '##', '###', '####', '#####', '######']),
|
|
612
|
+
};
|
|
613
|
+
if (!lang || lang === 'txt' || lang === 'text' || lang === 'plaintext') {
|
|
614
|
+
return { codeBlock: [{ codeContent: code, highlightType: 0 }], unified_codeBlock: [{ content: code, type: 'DEFAULT' }] };
|
|
615
|
+
}
|
|
616
|
+
const TYPE_MAP = { 0: 'DEFAULT', 1: 'KEYWORD', 2: 'METHOD', 3: 'STR', 4: 'NUMBER', 5: 'COMMENT' };
|
|
617
|
+
const keywords = keywordsMap[lang.toLowerCase()] || new Set();
|
|
618
|
+
const tokens = [];
|
|
619
|
+
let i = 0;
|
|
620
|
+
const push = (content, type) => {
|
|
621
|
+
if (!content)
|
|
622
|
+
return;
|
|
623
|
+
const last = tokens[tokens.length - 1];
|
|
624
|
+
if (last && last.highlightType === type)
|
|
625
|
+
last.codeContent += content;
|
|
626
|
+
else
|
|
627
|
+
tokens.push({ codeContent: content, highlightType: type });
|
|
628
|
+
};
|
|
629
|
+
const isIdentifier = (char) => {
|
|
630
|
+
switch (lang.toLowerCase()) {
|
|
631
|
+
case 'css': return /[a-zA-Z0-9_$-]/.test(char);
|
|
632
|
+
case 'html': return /[a-zA-Z0-9_$:-]/.test(char);
|
|
633
|
+
default: return /[a-zA-Z0-9_$]/.test(char);
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
while (i < code.length) {
|
|
637
|
+
const c = code[i];
|
|
638
|
+
if (/\s/.test(c)) {
|
|
639
|
+
let s = i;
|
|
640
|
+
while (i < code.length && /\s/.test(code[i]))
|
|
641
|
+
i++;
|
|
642
|
+
push(code.slice(s, i), 0);
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
if ((c === '/' && code[i + 1] === '/') || (c === '#' && ['python', 'bash'].includes(lang))) {
|
|
646
|
+
let s = i;
|
|
647
|
+
while (i < code.length && code[i] !== '\n')
|
|
648
|
+
i++;
|
|
649
|
+
push(code.slice(s, i), 5);
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
653
|
+
let s = i;
|
|
654
|
+
const q = c;
|
|
655
|
+
i++;
|
|
656
|
+
while (i < code.length) {
|
|
657
|
+
if (code[i] === '\\' && i + 1 < code.length)
|
|
658
|
+
i += 2;
|
|
659
|
+
else if (code[i] === q) {
|
|
660
|
+
i++;
|
|
661
|
+
break;
|
|
662
|
+
}
|
|
663
|
+
else
|
|
664
|
+
i++;
|
|
665
|
+
}
|
|
666
|
+
push(code.slice(s, i), 3);
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
if (/[0-9]/.test(c)) {
|
|
670
|
+
let s = i;
|
|
671
|
+
while (i < code.length && /[0-9._]/.test(code[i]))
|
|
672
|
+
i++;
|
|
673
|
+
push(code.slice(s, i), 4);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
if (/[a-zA-Z_$]/.test(c)) {
|
|
677
|
+
let s = i;
|
|
678
|
+
while (i < code.length && isIdentifier(code[i]))
|
|
679
|
+
i++;
|
|
680
|
+
const word = code.slice(s, i);
|
|
681
|
+
let type = 0;
|
|
682
|
+
if (keywords.has(word))
|
|
683
|
+
type = 1;
|
|
684
|
+
else if (lang === 'css') {
|
|
685
|
+
let j = i;
|
|
686
|
+
while (j < code.length && /\s/.test(code[j]))
|
|
687
|
+
j++;
|
|
688
|
+
if (code[j] === ':')
|
|
689
|
+
type = 1;
|
|
690
|
+
}
|
|
691
|
+
else if (lang === 'html') {
|
|
692
|
+
let p = s - 1;
|
|
693
|
+
while (p >= 0 && /\s/.test(code[p]))
|
|
694
|
+
p--;
|
|
695
|
+
if (code[p] === '<' || (code[p] === '/' && code[p - 1] === '<'))
|
|
696
|
+
type = 1;
|
|
697
|
+
}
|
|
698
|
+
if (type === 0) {
|
|
699
|
+
let j = i;
|
|
700
|
+
while (j < code.length && /\s/.test(code[j]))
|
|
701
|
+
j++;
|
|
702
|
+
if (code[j] === '(')
|
|
703
|
+
type = 2;
|
|
704
|
+
}
|
|
705
|
+
push(word, type);
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
push(c, 0);
|
|
709
|
+
i++;
|
|
710
|
+
}
|
|
711
|
+
return {
|
|
712
|
+
codeBlock: tokens,
|
|
713
|
+
unified_codeBlock: tokens.map((t) => ({ content: t.codeContent, type: TYPE_MAP[t.highlightType] })),
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
static toTableMetadata(arr, { hyperlink = true, citation = true, latex = true } = {}) {
|
|
717
|
+
if (!Array.isArray(arr) || !arr.every((row) => Array.isArray(row) && row.every((cell) => typeof cell === 'string'))) {
|
|
718
|
+
throw new TypeError('Table must be a nested array of strings');
|
|
719
|
+
}
|
|
720
|
+
const [header, ...rows] = arr;
|
|
721
|
+
const maxLen = Math.max(header.length, ...rows.map((r) => r.length));
|
|
722
|
+
const normalize = (r) => [...r, ...Array(maxLen - r.length).fill('')];
|
|
723
|
+
const unified_rows = [
|
|
724
|
+
{ is_header: true, cells: normalize(header) },
|
|
725
|
+
...rows.map((r) => ({ is_header: false, cells: normalize(r) })),
|
|
726
|
+
].map((row) => {
|
|
727
|
+
const markdown_cells = row.cells.map((cell) => {
|
|
728
|
+
const extracted = extractIE(cell, { hyperlink, citation, latex });
|
|
729
|
+
return {
|
|
730
|
+
text: extracted.text,
|
|
731
|
+
...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}),
|
|
732
|
+
};
|
|
733
|
+
});
|
|
734
|
+
return { ...row, ...(markdown_cells.some((c) => c.inline_entities?.length) ? { markdown_cells } : {}) };
|
|
735
|
+
});
|
|
736
|
+
const rowsMeta = unified_rows.map((r) => ({ items: r.cells, ...(r.is_header ? { isHeading: true } : {}) }));
|
|
737
|
+
return { title: '', rows: rowsMeta, unified_rows };
|
|
738
|
+
}
|
|
739
|
+
static generateVerificationMetadata() {
|
|
740
|
+
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${VERSION}\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`);
|
|
741
|
+
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${VERSION}\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`);
|
|
742
|
+
const signature = Buffer.concat([signatureMaterial, crypto.randomBytes(64 - signatureMaterial.length)]).toString('base64');
|
|
743
|
+
const certificateChain = [
|
|
744
|
+
Buffer.concat([certificateMaterial, crypto.randomBytes(684 - certificateMaterial.length)]).toString('base64'),
|
|
745
|
+
Buffer.concat([certificateMaterial, crypto.randomBytes(892 - certificateMaterial.length)]).toString('base64'),
|
|
746
|
+
];
|
|
747
|
+
return { proofs: [{ version: 1, useCase: 1, signature, certificateChain }] };
|
|
748
|
+
}
|
|
749
|
+
static newLayout(name, data, extra = {}) {
|
|
750
|
+
return {
|
|
751
|
+
...extra,
|
|
752
|
+
view_model: {
|
|
753
|
+
[Array.isArray(data) ? 'primitives' : 'primitive']: data,
|
|
754
|
+
__typename: `GenAI${name}LayoutViewModel`,
|
|
755
|
+
},
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
_makeNode(id, section, submessage) {
|
|
759
|
+
return { id: id ?? null, section: section ?? null, submessage: submessage ?? null };
|
|
760
|
+
}
|
|
761
|
+
_registerId(node, id) {
|
|
762
|
+
if (id === undefined || id === null || id === '')
|
|
763
|
+
return;
|
|
764
|
+
if (typeof id !== 'string')
|
|
765
|
+
throw new ContentValidationError('Item id must be a string', { id });
|
|
766
|
+
if (this._idIndex.has(id))
|
|
767
|
+
throw new DuplicateIdError(id);
|
|
768
|
+
node.id = id;
|
|
769
|
+
this._idIndex.set(id, node);
|
|
770
|
+
}
|
|
771
|
+
_unregisterId(node) {
|
|
772
|
+
if (node.id && this._idIndex.get(node.id) === node) {
|
|
773
|
+
this._idIndex.delete(node.id);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
hasId(id) {
|
|
777
|
+
return typeof id === 'string' && this._idIndex.has(id);
|
|
778
|
+
}
|
|
779
|
+
getIds() {
|
|
780
|
+
return [...this._idIndex.keys()];
|
|
781
|
+
}
|
|
782
|
+
peek(id) {
|
|
783
|
+
const node = this._idIndex.get(id);
|
|
784
|
+
if (!node)
|
|
785
|
+
return null;
|
|
786
|
+
return { id: node.id, section: node.section, submessage: node.submessage };
|
|
787
|
+
}
|
|
788
|
+
assignId(index, id) {
|
|
789
|
+
if (!Number.isInteger(index) || index < 0 || index >= this._nodes.length) {
|
|
790
|
+
throw new InvalidTargetError(`Node index ${index} is out of range (0-${this._nodes.length - 1})`, { index });
|
|
791
|
+
}
|
|
792
|
+
const node = this._nodes[index];
|
|
793
|
+
if (node.id) {
|
|
794
|
+
throw new AIRichError(`Node at index ${index} already has id "${node.id}"`, 'ALREADY_HAS_ID', { index, id: node.id });
|
|
795
|
+
}
|
|
796
|
+
this._registerId(node, id);
|
|
797
|
+
return this;
|
|
798
|
+
}
|
|
799
|
+
_getNode(id) {
|
|
800
|
+
if (typeof id !== 'string' || !id)
|
|
801
|
+
throw new ContentValidationError('Item id must be a non-empty string', { id });
|
|
802
|
+
const node = this._idIndex.get(id);
|
|
803
|
+
if (!node)
|
|
804
|
+
throw new ItemNotFoundError(id, this.getIds());
|
|
805
|
+
return node;
|
|
806
|
+
}
|
|
807
|
+
_resolveTarget(target) {
|
|
808
|
+
if (Array.isArray(target)) {
|
|
809
|
+
if (target.length < 1 || target.length > 2)
|
|
810
|
+
throw new ContentValidationError('Target must be id or [id, offset]', { target });
|
|
811
|
+
const [id, offset = 0] = target;
|
|
812
|
+
if (typeof id !== 'string' || !id)
|
|
813
|
+
throw new ContentValidationError('Target id must be a non-empty string', { target });
|
|
814
|
+
if (!Number.isInteger(offset))
|
|
815
|
+
throw new ContentValidationError('Offset must be an integer', { target });
|
|
816
|
+
return { id, offset };
|
|
817
|
+
}
|
|
818
|
+
if (typeof target !== 'string' || !target)
|
|
819
|
+
throw new ContentValidationError('Target must be a non-empty id or [id, offset]', { target });
|
|
820
|
+
return { id: target, offset: 0 };
|
|
821
|
+
}
|
|
822
|
+
_resolveNodeIndex(target) {
|
|
823
|
+
const { id, offset } = this._resolveTarget(target);
|
|
824
|
+
const node = this._getNode(id);
|
|
825
|
+
const baseIndex = this._nodes.indexOf(node);
|
|
826
|
+
if (baseIndex === -1)
|
|
827
|
+
throw new InvalidTargetError(`Item id "${id}" is registered but not present in the node list (internal desync)`, { id });
|
|
828
|
+
const index = baseIndex + offset;
|
|
829
|
+
if (index < 0 || index >= this._nodes.length)
|
|
830
|
+
throw new InvalidTargetError(`Target "${id}" with offset ${offset} resolves to index ${index}, which is out of range (0-${this._nodes.length - 1})`, { id, offset, index });
|
|
831
|
+
return { id, offset, baseIndex, index };
|
|
832
|
+
}
|
|
833
|
+
_validateSections(section) {
|
|
834
|
+
const items = Array.isArray(section) ? section : [section];
|
|
835
|
+
if (!items.length)
|
|
836
|
+
throw new ContentValidationError('At least one section is required');
|
|
837
|
+
for (const item of items) {
|
|
838
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
839
|
+
throw new ContentValidationError('Sections must be plain objects');
|
|
840
|
+
}
|
|
841
|
+
return items;
|
|
842
|
+
}
|
|
843
|
+
_validateSubmessages(submessage) {
|
|
844
|
+
if (submessage === undefined || submessage === null)
|
|
845
|
+
return [];
|
|
846
|
+
const items = Array.isArray(submessage) ? submessage : [submessage];
|
|
847
|
+
for (const item of items) {
|
|
848
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
849
|
+
throw new ContentValidationError('Submessages must be plain objects');
|
|
850
|
+
}
|
|
851
|
+
return items;
|
|
852
|
+
}
|
|
853
|
+
_pairSubmessages(sections, submessages) {
|
|
854
|
+
const n = sections.length;
|
|
855
|
+
const m = submessages.length;
|
|
856
|
+
if (m === 0)
|
|
857
|
+
return sections.map(() => null);
|
|
858
|
+
if (m === 1)
|
|
859
|
+
return sections.map((_, i) => (i === 0 ? submessages[0] : null));
|
|
860
|
+
if (m === n)
|
|
861
|
+
return submessages;
|
|
862
|
+
throw new ContentValidationError(`Cannot pair ${m} submessage(s) with ${n} section(s): expected 0, 1, or ${n}`, { sectionCount: n, submessageCount: m });
|
|
863
|
+
}
|
|
864
|
+
_addContent(section, submessage, { id, replace, insertAt } = {}) {
|
|
865
|
+
const hasReplace = replace !== undefined && replace !== null && replace !== '';
|
|
866
|
+
const hasInsertAt = insertAt !== undefined && insertAt !== null && insertAt !== '';
|
|
867
|
+
if (hasReplace && hasInsertAt)
|
|
868
|
+
throw new ContentValidationError('replace and insertAt cannot be used together');
|
|
869
|
+
const sections = this._validateSections(section);
|
|
870
|
+
const submessages = this._validateSubmessages(submessage);
|
|
871
|
+
if (!sections.length)
|
|
872
|
+
throw new ContentValidationError('At least one section is required');
|
|
873
|
+
if (id !== undefined && id !== null && id !== '' && sections.length !== 1) {
|
|
874
|
+
throw new ContentValidationError('One id can only be assigned to one node', { id, sectionCount: sections.length });
|
|
875
|
+
}
|
|
876
|
+
if (submessages.length && submessages.length !== sections.length && submessages.length !== 1) {
|
|
877
|
+
throw new ContentValidationError('Section and submessage count must match');
|
|
878
|
+
}
|
|
879
|
+
const pairedSubmessages = sections.map((_, index) => {
|
|
880
|
+
if (!submessages.length)
|
|
881
|
+
return undefined;
|
|
882
|
+
return submessages.length === 1 ? submessages[0] : submessages[index];
|
|
883
|
+
});
|
|
884
|
+
if (id && this._idIndex.has(id) && !(hasReplace && this._resolveTarget(replace)?.id === id)) {
|
|
885
|
+
throw new DuplicateIdError(id);
|
|
886
|
+
}
|
|
887
|
+
const newNodes = sections.map((currentSection, index) => {
|
|
888
|
+
return this._makeNode(index === 0 ? id : null, currentSection, pairedSubmessages[index]);
|
|
889
|
+
});
|
|
890
|
+
if (hasReplace) {
|
|
891
|
+
if (newNodes.length !== 1)
|
|
892
|
+
throw new ContentValidationError('replace only supports adding exactly one node');
|
|
893
|
+
const target = this._resolveNodeIndex(replace);
|
|
894
|
+
if (!target)
|
|
895
|
+
throw new ContentValidationError('Target node could not be resolved');
|
|
896
|
+
const oldNode = this._nodes[target.index];
|
|
897
|
+
const newNode = newNodes[0];
|
|
898
|
+
if (!newNode.id && oldNode?.id)
|
|
899
|
+
newNode.id = oldNode.id;
|
|
900
|
+
this._unregisterId(oldNode);
|
|
901
|
+
this._nodes.splice(target.index, 1, newNode);
|
|
902
|
+
if (newNode.id)
|
|
903
|
+
this._idIndex.set(newNode.id, newNode);
|
|
904
|
+
return this;
|
|
905
|
+
}
|
|
906
|
+
if (hasInsertAt) {
|
|
907
|
+
const target = this._resolveNodeIndex(insertAt);
|
|
908
|
+
if (!target)
|
|
909
|
+
throw new ContentValidationError('Target node could not be resolved');
|
|
910
|
+
const insertIndex = target.offset < 0 ? target.index : target.index + 1;
|
|
911
|
+
this._nodes.splice(insertIndex, 0, ...newNodes);
|
|
912
|
+
for (const node of newNodes) {
|
|
913
|
+
if (node.id)
|
|
914
|
+
this._idIndex.set(node.id, node);
|
|
915
|
+
}
|
|
916
|
+
return this;
|
|
917
|
+
}
|
|
918
|
+
this._nodes.push(...newNodes);
|
|
919
|
+
for (const node of newNodes) {
|
|
920
|
+
if (node.id)
|
|
921
|
+
this._idIndex.set(node.id, node);
|
|
922
|
+
}
|
|
923
|
+
return this;
|
|
924
|
+
}
|
|
925
|
+
addSection(section, options = {}) {
|
|
926
|
+
return this._addContent(section, undefined, options);
|
|
927
|
+
}
|
|
928
|
+
addSubmessage(submessage, options = {}) {
|
|
929
|
+
const items = this._validateSubmessages(submessage);
|
|
930
|
+
if (!items.length)
|
|
931
|
+
throw new ContentValidationError('At least one submessage is required');
|
|
932
|
+
return this._addContent(undefined, items, options);
|
|
933
|
+
}
|
|
934
|
+
delete(target) {
|
|
935
|
+
const { index } = this._resolveNodeIndex(target);
|
|
936
|
+
const [oldNode] = this._nodes.splice(index, 1);
|
|
937
|
+
this._unregisterId(oldNode);
|
|
938
|
+
return this;
|
|
939
|
+
}
|
|
940
|
+
get _sections() {
|
|
941
|
+
return this._nodes.filter((n) => n.section !== null).map((n) => n.section);
|
|
942
|
+
}
|
|
943
|
+
get _submessages() {
|
|
944
|
+
return this._nodes.filter((n) => n.submessage !== null).map((n) => n.submessage);
|
|
945
|
+
}
|
|
946
|
+
get sections() {
|
|
947
|
+
return this._sections;
|
|
948
|
+
}
|
|
949
|
+
get items() {
|
|
950
|
+
return this._sections.flatMap((section) => {
|
|
951
|
+
const vm = section?.view_model;
|
|
952
|
+
if (Array.isArray(vm?.primitives))
|
|
953
|
+
return vm.primitives;
|
|
954
|
+
if (vm?.primitive)
|
|
955
|
+
return [vm.primitive];
|
|
956
|
+
return [];
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
//# sourceMappingURL=mbuilder-airich.js.map
|