@x4r1s3/baileys 0.0.0-stage → 1.0.0
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/LICENSE +21 -0
- package/README.md +1262 -2
- package/SECURITY.md +47 -0
- package/WAProto/V +1 -0
- package/WAProto/WAProto.proto +8892 -0
- package/WAProto/index.d.ts +104128 -0
- package/WAProto/index.js +334920 -0
- package/assets/rolling-circle.svg +133 -0
- package/assets/x4r1s3-banner.svg +32 -0
- package/engine-requirements.js +27 -0
- package/lib/Builders/A2UI.js +245 -0
- package/lib/Builders/AIRich.js +179 -0
- package/lib/Builders/Button.js +108 -0
- package/lib/Builders/CFC.js +284 -0
- package/lib/Builders/Carousel.js +81 -0
- package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
- package/lib/Call/audio-feeder.mjs +179 -0
- package/lib/Call/audio-recorder.mjs +250 -0
- package/lib/Call/fetch-wasm-resources.mjs +104 -0
- package/lib/Call/index.mjs +680 -0
- package/lib/Call/relay-transport.mjs +563 -0
- package/lib/Call/signaling.mjs +641 -0
- package/lib/Call/types.mjs +17 -0
- package/lib/Call/video-feeder.mjs +94 -0
- package/lib/Call/wasm-engine.mjs +1372 -0
- package/lib/Call/worker-bootstrap.mjs +1042 -0
- package/lib/Defaults/ban-checker.js +56 -0
- package/lib/Defaults/index.js +170 -0
- package/lib/Signal/Group/ciphertext-message.js +23 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +93 -0
- package/lib/Signal/Group/index.js +23 -0
- package/lib/Signal/Group/keyhelper.js +29 -0
- package/lib/Signal/Group/sender-chain-key.js +37 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
- package/lib/Signal/Group/sender-key-message.js +77 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.js +52 -0
- package/lib/Signal/Group/sender-key-state.js +95 -0
- package/lib/Signal/Group/sender-message-key.js +37 -0
- package/lib/Signal/libsignal.js +440 -0
- package/lib/Signal/lid-mapping.js +292 -0
- package/lib/Socket/Client/index.js +14 -0
- package/lib/Socket/Client/types.js +22 -0
- package/lib/Socket/Client/websocket.js +65 -0
- package/lib/Socket/aigroups.js +327 -0
- package/lib/Socket/ban-checker.js +165 -0
- package/lib/Socket/business.js +419 -0
- package/lib/Socket/chats.js +1921 -0
- package/lib/Socket/communities.js +443 -0
- package/lib/Socket/graphql.js +911 -0
- package/lib/Socket/groups.js +561 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interactive-handler.js +612 -0
- package/lib/Socket/interop.js +575 -0
- package/lib/Socket/managed-account.js +220 -0
- package/lib/Socket/messages-recv.js +2191 -0
- package/lib/Socket/messages-send.js +4104 -0
- package/lib/Socket/mex.js +53 -0
- package/lib/Socket/newsletter.js +291 -0
- package/lib/Socket/privacy.js +458 -0
- package/lib/Socket/registration.js +440 -0
- package/lib/Socket/socket.js +1029 -0
- package/lib/Socket/status-actions.js +287 -0
- package/lib/Socket/username.js +241 -0
- package/lib/Store/index.js +16 -0
- package/lib/Store/make-cache-manager-store.js +101 -0
- package/lib/Store/make-in-memory-store.js +432 -0
- package/lib/Store/make-ordered-dictionary.js +90 -0
- package/lib/Store/object-repository.js +35 -0
- package/lib/Types/Auth.js +13 -0
- package/lib/Types/Bussines.js +13 -0
- package/lib/Types/Call.js +13 -0
- package/lib/Types/Chat.js +19 -0
- package/lib/Types/Contact.js +13 -0
- package/lib/Types/Events.js +13 -0
- package/lib/Types/GroupMetadata.js +13 -0
- package/lib/Types/Label.js +36 -0
- package/lib/Types/LabelAssociation.js +18 -0
- package/lib/Types/Message.js +30 -0
- package/lib/Types/Mex.js +53 -0
- package/lib/Types/Product.js +13 -0
- package/lib/Types/RichType.js +34 -0
- package/lib/Types/Signal.js +13 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +60 -0
- package/lib/Types/USync.js +13 -0
- package/lib/Types/index.js +37 -0
- package/lib/Utils/auth-utils.js +313 -0
- package/lib/Utils/ban-checker.js +48 -0
- package/lib/Utils/bot-capabilities.js +96 -0
- package/lib/Utils/bot-planning-replay.js +177 -0
- package/lib/Utils/browser-utils.js +40 -0
- package/lib/Utils/business.js +242 -0
- package/lib/Utils/c2582.js +147 -0
- package/lib/Utils/chat-utils.js +905 -0
- package/lib/Utils/companion-reg-client-utils.js +44 -0
- package/lib/Utils/consumer-application.js +114 -0
- package/lib/Utils/crypto.js +129 -0
- package/lib/Utils/decode-wa-message.js +496 -0
- package/lib/Utils/direct-chat-theme.js +164 -0
- package/lib/Utils/event-buffer.js +601 -0
- package/lib/Utils/experimental-proto.js +206 -0
- package/lib/Utils/games/miniapp.js +17 -0
- package/lib/Utils/games/slot-machine.js +270 -0
- package/lib/Utils/games/website-preview.js +306 -0
- package/lib/Utils/generics.js +402 -0
- package/lib/Utils/group-history.js +68 -0
- package/lib/Utils/group-wallpaper.js +168 -0
- package/lib/Utils/history.js +162 -0
- package/lib/Utils/identity-change-handler.js +60 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/jid-display-normalization.js +221 -0
- package/lib/Utils/link-preview.js +96 -0
- package/lib/Utils/logger.js +14 -0
- package/lib/Utils/lt-hash.js +19 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/message-composer.js +709 -0
- package/lib/Utils/message-inspect.js +79 -0
- package/lib/Utils/message-retry-manager.js +253 -0
- package/lib/Utils/message-security.js +167 -0
- package/lib/Utils/messages-media.js +1027 -0
- package/lib/Utils/messages.js +2467 -0
- package/lib/Utils/meta-ai-msmsg.js +215 -0
- package/lib/Utils/meta-compositing.js +239 -0
- package/lib/Utils/native-flow.js +158 -0
- package/lib/Utils/newsletter-live-update-utils.js +74 -0
- package/lib/Utils/newsletter-status-utils.js +152 -0
- package/lib/Utils/noise-handler.js +212 -0
- package/lib/Utils/offline-node-processor.js +51 -0
- package/lib/Utils/poll-manager.js +206 -0
- package/lib/Utils/portable-compat.js +12 -0
- package/lib/Utils/pre-key-manager.js +117 -0
- package/lib/Utils/process-message.js +610 -0
- package/lib/Utils/reporting-utils.js +269 -0
- package/lib/Utils/rich-message-utils.js +2841 -0
- package/lib/Utils/scheduled-message.js +107 -0
- package/lib/Utils/signal.js +212 -0
- package/lib/Utils/source-grep.js +57 -0
- package/lib/Utils/stanza-ack.js +49 -0
- package/lib/Utils/sticker-annotation.js +87 -0
- package/lib/Utils/sync-action-utils.js +59 -0
- package/lib/Utils/tc-token-utils.js +174 -0
- package/lib/Utils/use-multi-file-auth-state.js +132 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +120 -0
- package/lib/Utils/validate-connection.js +220 -0
- package/lib/Utils/view-once-utils.js +218 -0
- package/lib/Utils/voip-rekey.js +32 -0
- package/lib/Utils/website-preview.js +27 -0
- package/lib/Utils/welcome-flow.js +228 -0
- package/lib/Utils/x4r1s3.js +144 -0
- package/lib/WABinary/constants.js +1475 -0
- package/lib/WABinary/decode.js +273 -0
- package/lib/WABinary/encode.js +231 -0
- package/lib/WABinary/generic-utils.js +242 -0
- package/lib/WABinary/index.js +17 -0
- package/lib/WABinary/jid-utils.js +107 -0
- package/lib/WABinary/types.js +13 -0
- package/lib/WAM/BinaryInfo.js +21 -0
- package/lib/WAM/constants.js +22864 -0
- package/lib/WAM/encode.js +161 -0
- package/lib/WAM/index.js +15 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
- package/lib/WAUSync/Protocols/index.js +24 -0
- package/lib/WAUSync/USyncQuery.js +213 -0
- package/lib/WAUSync/USyncUser.js +66 -0
- package/lib/WAUSync/index.js +15 -0
- package/lib/antiban.cjs +4726 -0
- package/lib/index.d.ts +1285 -0
- package/lib/index.js +30 -0
- package/package.json +125 -4
|
@@ -0,0 +1,2841 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/rich-message-utils.js
|
|
5
|
+
* About: Rich message utils module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: tokenizeCode, normalizeNewReel, normalizeNewRichImage, prepareNewRichMediaCompatibility, toUnified, buildImaginePrimitive, prepareRichGenerationMessage, buildAdditionalBotMetadataContext; …
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Lia@Changes 09-04-26 [WIP]
|
|
15
|
+
* Adds support for tables and code blocks with richResponseMessage (wrapped inside botForwardedMessage).
|
|
16
|
+
*
|
|
17
|
+
* If you use or copy this code, please credit my name or project. AND DO NOT CHANGE THIS NOTE
|
|
18
|
+
*/
|
|
19
|
+
import { getRandomValues, randomUUID, randomBytes } from 'crypto';
|
|
20
|
+
import { Boom } from '@hapi/boom';
|
|
21
|
+
import { BOT_RENDERING_CONFIG_METADATA, DONATE_URL, LEXER_REGEX } from '../Defaults/index.js';
|
|
22
|
+
import { LANGUAGE_KEYWORDS } from '../WABinary/constants.js';
|
|
23
|
+
import { CodeHighlightType, RichSubMessageType } from '../Types/RichType.js';
|
|
24
|
+
import { proto } from '../../WAProto/index.js';
|
|
25
|
+
import { unixTimestampSeconds } from './generics.js';
|
|
26
|
+
import { generateRichAIResponseContent, generateTableContent } from './message-composer.js';
|
|
27
|
+
import { extractImageThumb } from './messages-media.js';
|
|
28
|
+
const normalizeReminderEnum = (value, enumObject, field) => {
|
|
29
|
+
const normalized = typeof value === 'string' ? enumObject[value] : value;
|
|
30
|
+
if (typeof normalized !== 'number' || !Object.values(enumObject).includes(normalized)) {
|
|
31
|
+
throw new Boom(`reminderMetadata.${field} must be a recognized enum name or number`, { statusCode: 400 });
|
|
32
|
+
}
|
|
33
|
+
return normalized;
|
|
34
|
+
};
|
|
35
|
+
const normalizeReminderMetadata = (value) => {
|
|
36
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
37
|
+
throw new Boom('reminderMetadata must be an object', { statusCode: 400 });
|
|
38
|
+
}
|
|
39
|
+
const metadata = {};
|
|
40
|
+
if (value.requestMessageKey !== undefined && value.requestMessageKey !== null) {
|
|
41
|
+
if (typeof value.requestMessageKey !== 'object' || Array.isArray(value.requestMessageKey)) {
|
|
42
|
+
throw new Boom('reminderMetadata.requestMessageKey must be a message-key object', { statusCode: 400 });
|
|
43
|
+
}
|
|
44
|
+
metadata.requestMessageKey = value.requestMessageKey;
|
|
45
|
+
}
|
|
46
|
+
if (value.action !== undefined && value.action !== null) {
|
|
47
|
+
metadata.action = normalizeReminderEnum(value.action, proto.BotReminderMetadata.ReminderAction, 'action');
|
|
48
|
+
}
|
|
49
|
+
if (value.name !== undefined && value.name !== null) {
|
|
50
|
+
if (typeof value.name !== 'string') throw new Boom('reminderMetadata.name must be a string', { statusCode: 400 });
|
|
51
|
+
metadata.name = value.name;
|
|
52
|
+
}
|
|
53
|
+
if (value.nextTriggerTimestamp !== undefined && value.nextTriggerTimestamp !== null) {
|
|
54
|
+
const timestamp = value.nextTriggerTimestamp;
|
|
55
|
+
const validNumber = typeof timestamp === 'number' && Number.isSafeInteger(timestamp) && timestamp >= 0;
|
|
56
|
+
const validString = typeof timestamp === 'string' && /^\d+$/.test(timestamp) && BigInt(timestamp) <= 0xffffffffffffffffn;
|
|
57
|
+
if (!validNumber && !validString) {
|
|
58
|
+
throw new Boom('reminderMetadata.nextTriggerTimestamp must be a non-negative uint64 integer or digit string', { statusCode: 400 });
|
|
59
|
+
}
|
|
60
|
+
metadata.nextTriggerTimestamp = timestamp;
|
|
61
|
+
}
|
|
62
|
+
if (value.frequency !== undefined && value.frequency !== null) {
|
|
63
|
+
metadata.frequency = normalizeReminderEnum(value.frequency, proto.BotReminderMetadata.ReminderFrequency, 'frequency');
|
|
64
|
+
}
|
|
65
|
+
return metadata;
|
|
66
|
+
};
|
|
67
|
+
const NOOP = new Set([]);
|
|
68
|
+
export const tokenizeCode = (code, language = 'javascript') => {
|
|
69
|
+
const keywords = LANGUAGE_KEYWORDS[language] || NOOP;
|
|
70
|
+
const blocks = [];
|
|
71
|
+
LEXER_REGEX.lastIndex = 0;
|
|
72
|
+
let match;
|
|
73
|
+
while ((match = LEXER_REGEX.exec(code)) !== null) {
|
|
74
|
+
if (match[1]) {
|
|
75
|
+
blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: match[1] });
|
|
76
|
+
}
|
|
77
|
+
else if (match[2]) {
|
|
78
|
+
blocks.push({ highlightType: CodeHighlightType.STRING, codeContent: match[2] });
|
|
79
|
+
}
|
|
80
|
+
else if (match[3]) {
|
|
81
|
+
blocks.push({
|
|
82
|
+
highlightType: keywords.has(match[3]) ? CodeHighlightType.KEYWORD : CodeHighlightType.METHOD,
|
|
83
|
+
codeContent: match[3],
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
else if (match[4]) {
|
|
87
|
+
blocks.push({
|
|
88
|
+
highlightType: keywords.has(match[4]) ? CodeHighlightType.KEYWORD : CodeHighlightType.DEFAULT,
|
|
89
|
+
codeContent: match[4],
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
else if (match[5]) {
|
|
93
|
+
blocks.push({ highlightType: CodeHighlightType.NUMBER, codeContent: match[5] });
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: match[6] });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return blocks;
|
|
100
|
+
};
|
|
101
|
+
const firstImageValue = (...values) => values.find(value => value !== undefined && value !== null && String(value).length > 0);
|
|
102
|
+
|
|
103
|
+
const inferImageMimeType = (url = '') => {
|
|
104
|
+
const path = String(url).split('?')[0].toLowerCase();
|
|
105
|
+
if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';
|
|
106
|
+
if (path.endsWith('.webp')) return 'image/webp';
|
|
107
|
+
if (path.endsWith('.gif')) return 'image/gif';
|
|
108
|
+
return 'image/png';
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** Normalize album image variants without downgrading full-size URLs to previews. */
|
|
112
|
+
const buildRichImagePrimitive = (image = {}, expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)) => {
|
|
113
|
+
const previewUrl = firstImageValue(image.imagePreviewUrl, image.previewUrl, image.preview_url, image.sourceUrl, image.source_url, image.url) || '';
|
|
114
|
+
const fullUrl = firstImageValue(image.imageHighResUrl, image.highResUrl, image.high_res_url, image.fullUrl, image.full_url, image.sourceUrl, image.source_url, image.url, previewUrl);
|
|
115
|
+
const darkPreviewUrl = firstImageValue(image.darkModePreviewUrl, image.dark_mode_preview_url, previewUrl);
|
|
116
|
+
const darkFullUrl = firstImageValue(image.darkModeHighResUrl, image.darkModeHighResUrl, image.dark_mode_high_res_url, image.darkModePreviewUrl, image.dark_mode_preview_url, fullUrl);
|
|
117
|
+
const width = Number(image.previewWidth || image.preview_width || image.width || 600);
|
|
118
|
+
const height = Number(image.previewHeight || image.preview_height || image.height || 400);
|
|
119
|
+
const fullWidth = Number(image.fullWidth || image.full_width || image.highResWidth || image.high_res_width || image.width || width);
|
|
120
|
+
const fullHeight = Number(image.fullHeight || image.full_height || image.highResHeight || image.high_res_height || image.height || height);
|
|
121
|
+
const darkWidth = Number(image.darkWidth || image.dark_width || fullWidth);
|
|
122
|
+
const darkHeight = Number(image.darkHeight || image.dark_height || fullHeight);
|
|
123
|
+
const mimeType = image.mimeType || image.mime_type || inferImageMimeType(fullUrl || previewUrl);
|
|
124
|
+
const media = (url, mediaWidth, mediaHeight) => ({
|
|
125
|
+
url,
|
|
126
|
+
url_fallback: url,
|
|
127
|
+
mime_type: mimeType,
|
|
128
|
+
expiration_timestamp_ms: expiration,
|
|
129
|
+
width: mediaWidth,
|
|
130
|
+
height: mediaHeight
|
|
131
|
+
});
|
|
132
|
+
const primitive = {
|
|
133
|
+
full_image: media(fullUrl, fullWidth, fullHeight),
|
|
134
|
+
asset_query_status: 'FETCHED',
|
|
135
|
+
__typename: 'GenAIImagePrimitive'
|
|
136
|
+
};
|
|
137
|
+
// WhatsApp requires the preview slots to recognize an image primitive.
|
|
138
|
+
// Omitting them makes mixed image/video albums silently drop the image.
|
|
139
|
+
primitive.preview_image = media(previewUrl, width, height);
|
|
140
|
+
primitive.dark_mode_preview_image = media(darkPreviewUrl, darkWidth, darkHeight);
|
|
141
|
+
primitive.dark_mode_full_image = media(darkFullUrl, darkWidth, darkHeight);
|
|
142
|
+
return primitive;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** Normalize the field names used by New compatibility's Meta/reels helpers. */
|
|
146
|
+
export const normalizeNewReel = (reel = {}) => ({
|
|
147
|
+
reels_url: reel.videoUrl || reel.video_url || reel.reels_url || reel.reelsUrl || reel.url || '',
|
|
148
|
+
thumbnail_url: reel.thumbnailUrl || reel.thumbnail_url || reel.thumbnail || '',
|
|
149
|
+
creator: reel.creator || reel.username || reel.title || '',
|
|
150
|
+
avatar_url: reel.profileIconUrl || reel.avatar_url || reel.avatar || reel.icon || '',
|
|
151
|
+
reels_title: reel.title || reel.reels_title || reel.reelsTitle || '',
|
|
152
|
+
likes_count: reel.likesCount ?? reel.likes_count ?? reel.likes ?? 0,
|
|
153
|
+
comments_count: reel.commentsCount ?? reel.comments_count ?? reel.comments ?? 0,
|
|
154
|
+
shares_count: reel.sharesCount ?? reel.shares_count ?? reel.shares ?? 0,
|
|
155
|
+
view_count: reel.viewCount ?? reel.view_count ?? reel.views ?? 0,
|
|
156
|
+
reel_source: reel.reelSource || reel.reel_source || reel.source || 'IG',
|
|
157
|
+
is_verified: !!(reel.isVerified ?? reel.is_verified ?? reel.verified),
|
|
158
|
+
orientation: reel.orientation || reel.ratio || 'LANDSCAPE',
|
|
159
|
+
post_type: reel.postType || reel.post_type || 'VIDEO',
|
|
160
|
+
is_carousel: reel.isCarousel ?? reel.is_carousel ?? false
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
/** Build the New-compatible image/post shape without replacing native image data. */
|
|
164
|
+
export const normalizeNewRichImage = (image = {}) => ({
|
|
165
|
+
thumbnail_url: image.thumbnailUrl || image.thumbnail_url || image.thumbnail || image.previewUrl || image.preview_url || '',
|
|
166
|
+
image_url: image.imageUrl || image.image_url || image.fullUrl || image.full_url || image.url || '',
|
|
167
|
+
source_url: image.sourceUrl || image.source_url || image.url || '',
|
|
168
|
+
title: image.title || image.caption || '',
|
|
169
|
+
creator: image.creator || image.username || '',
|
|
170
|
+
avatar_url: image.profileIconUrl || image.avatar_url || image.avatar || '',
|
|
171
|
+
is_verified: !!(image.isVerified ?? image.is_verified ?? image.verified),
|
|
172
|
+
post_caption: image.postCaption || image.post_caption || image.caption || '',
|
|
173
|
+
likes_count: image.likesCount ?? image.likes_count ?? image.likes ?? 0,
|
|
174
|
+
comments_count: image.commentsCount ?? image.comments_count ?? image.comments ?? 0,
|
|
175
|
+
shares_count: image.sharesCount ?? image.shares_count ?? image.shares ?? 0,
|
|
176
|
+
orientation: image.orientation || image.ratio || 'LANDSCAPE',
|
|
177
|
+
post_type: image.postType || image.post_type || 'IMAGE',
|
|
178
|
+
is_carousel: image.isCarousel ?? image.is_carousel ?? false
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
/** Create the second New-shaped representation beside native AIRich sections. */
|
|
182
|
+
export const prepareNewRichMediaCompatibility = (content = {}) => {
|
|
183
|
+
const reels = (Array.isArray(content.reels) ? content.reels : []).map(normalizeNewReel);
|
|
184
|
+
const images = (Array.isArray(content.images) ? content.images : content.image ? [content.image] : []).map(normalizeNewRichImage);
|
|
185
|
+
const posts = (Array.isArray(content.posts) ? content.posts : content.post ? [content.post] : []).map(normalizeNewRichImage);
|
|
186
|
+
const sections = [];
|
|
187
|
+
if (reels.length) sections.push({ view_model: { primitives: reels.map(item => ({ ...item, __typename: 'GenAIReelPrimitive' })), __typename: 'GenAIHScrollLayoutViewModel' } });
|
|
188
|
+
if (images.length) sections.push({ view_model: { primitives: images.map(item => ({ ...item, __typename: 'GenAIImagePrimitive' })), __typename: 'GenAIHScrollLayoutViewModel' } });
|
|
189
|
+
if (posts.length) sections.push({ view_model: { primitives: posts.map(item => ({ ...item, __typename: 'GenAIPostPrimitive' })), __typename: 'GenAIHScrollLayoutViewModel' } });
|
|
190
|
+
return { compatibility: 'new-rich-media', reels, images, posts, sections };
|
|
191
|
+
};
|
|
192
|
+
// Lia@Changes 09-04-26 --- Inject buffer into unifiedResponse.data to support proper rendering of rich messages (ex: tables and code blocks)
|
|
193
|
+
export const toUnified = (submessages, uuid) => ({
|
|
194
|
+
response_id: uuid || randomUUID(),
|
|
195
|
+
sections: submessages.map((submessage) => {
|
|
196
|
+
switch (submessage.messageType) {
|
|
197
|
+
case RichSubMessageType.CODE: {
|
|
198
|
+
const codeMetadata = submessage.codeMetadata || {};
|
|
199
|
+
return {
|
|
200
|
+
view_model: {
|
|
201
|
+
primitive: {
|
|
202
|
+
language: codeMetadata.codeLanguage || 'javascript',
|
|
203
|
+
code_blocks: (codeMetadata.codeBlocks || []).map((block) => ({ content: block.codeContent, type: CodeHighlightType[block.highlightType] || 'DEFAULT' })),
|
|
204
|
+
__typename: 'GenAICodeUXPrimitive'
|
|
205
|
+
},
|
|
206
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
case RichSubMessageType.GRID_IMAGE: {
|
|
211
|
+
const imageUrls = submessage.gridImageMetadata?.imageUrls ||
|
|
212
|
+
(submessage.gridImageMetadata?.gridImageUrl ? [submessage.gridImageMetadata.gridImageUrl] : []);
|
|
213
|
+
if (!imageUrls.length) return null;
|
|
214
|
+
const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
|
215
|
+
const primitives = imageUrls.map(img => buildRichImagePrimitive(img, expiration));
|
|
216
|
+
return { view_model: { primitives, __typename: 'GenAIGridLayoutViewModel' } };
|
|
217
|
+
}
|
|
218
|
+
case RichSubMessageType.CONTENT_ITEMS: {
|
|
219
|
+
const items = submessage.contentItemsMetadata?.itemsMetadata || [];
|
|
220
|
+
const primitives = items.map((item) => {
|
|
221
|
+
const reel = item?.reelItem || item || {};
|
|
222
|
+
return {
|
|
223
|
+
reels_url: reel.videoUrl || reel.reels_url || reel.url || '',
|
|
224
|
+
thumbnail_url: reel.thumbnailUrl || reel.thumbnail_url || '',
|
|
225
|
+
creator: reel.creator || reel.title || '',
|
|
226
|
+
avatar_url: reel.profileIconUrl || reel.avatar_url || '',
|
|
227
|
+
reels_title: reel.title || reel.reels_title || '',
|
|
228
|
+
likes_count: reel.likesCount ?? reel.likes_count ?? 0,
|
|
229
|
+
shares_count: reel.sharesCount ?? reel.shares_count ?? 0,
|
|
230
|
+
view_count: reel.viewCount ?? reel.view_count ?? 0,
|
|
231
|
+
reel_source: reel.reelSource || reel.reel_source || 'IG',
|
|
232
|
+
is_verified: !!(reel.isVerified ?? reel.is_verified),
|
|
233
|
+
__typename: 'GenAIReelPrimitive'
|
|
234
|
+
};
|
|
235
|
+
}).filter((item) => item.reels_url || item.thumbnail_url || item.reels_title);
|
|
236
|
+
return {
|
|
237
|
+
view_model: {
|
|
238
|
+
primitives,
|
|
239
|
+
__typename: 'GenAIHScrollLayoutViewModel'
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
case RichSubMessageType.INLINE_IMAGE: {
|
|
244
|
+
const image = submessage.imageMetadata || {};
|
|
245
|
+
const rawImage = image.imageUrl || image.url || image.image;
|
|
246
|
+
const imageData = typeof rawImage === 'string'
|
|
247
|
+
? { ...image, url: rawImage }
|
|
248
|
+
: { ...image, ...(rawImage || {}) };
|
|
249
|
+
const primitive = buildRichImagePrimitive({
|
|
250
|
+
...imageData,
|
|
251
|
+
mimeType: imageData.mimeType || imageData.mime_type,
|
|
252
|
+
});
|
|
253
|
+
return primitive.full_image.url
|
|
254
|
+
? {
|
|
255
|
+
view_model: {
|
|
256
|
+
primitives: [{ ...primitive, display_mode: 'FULL_WIDTH', full_width: true }],
|
|
257
|
+
display_mode: 'FULL_WIDTH',
|
|
258
|
+
full_width: true,
|
|
259
|
+
__typename: 'GenAIVStackLayoutViewModel'
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
: {};
|
|
263
|
+
}
|
|
264
|
+
case RichSubMessageType.LATEX: {
|
|
265
|
+
const metadata = submessage.latexMetadata || {};
|
|
266
|
+
const expression = (metadata.expressions || [])[0] || {};
|
|
267
|
+
const item = {
|
|
268
|
+
latex_expression: expression.latexExpression || expression.expression || '',
|
|
269
|
+
font_height: expression.fontHeight,
|
|
270
|
+
padding: expression.padding ?? 15,
|
|
271
|
+
latex_image: {
|
|
272
|
+
url: expression.url || '',
|
|
273
|
+
width: expression.width || 388,
|
|
274
|
+
height: expression.height || 160
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
return {
|
|
278
|
+
view_model: {
|
|
279
|
+
primitive: { item, ...item, __typename: 'GenAILatexUXPrimitive' },
|
|
280
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
case RichSubMessageType.TABLE: {
|
|
285
|
+
const tableMetadata = submessage.tableMetadata || {};
|
|
286
|
+
return {
|
|
287
|
+
view_model: {
|
|
288
|
+
primitive: {
|
|
289
|
+
title: tableMetadata.title || '',
|
|
290
|
+
rows: (tableMetadata.rows || []).map((row) => ({
|
|
291
|
+
is_header: !!row.isHeading,
|
|
292
|
+
cells: row.items || [],
|
|
293
|
+
markdown_cells: (row.items || []).map((item) => ({ text: item }))
|
|
294
|
+
})),
|
|
295
|
+
__typename: 'GenATableUXPrimitive'
|
|
296
|
+
},
|
|
297
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
case RichSubMessageType.MAP: {
|
|
302
|
+
const map = submessage.mapMetadata || {};
|
|
303
|
+
return {
|
|
304
|
+
view_model: {
|
|
305
|
+
primitive: {
|
|
306
|
+
center_latitude: map.centerLatitude,
|
|
307
|
+
center_longitude: map.centerLongitude,
|
|
308
|
+
latitude_delta: map.latitudeDelta,
|
|
309
|
+
longitude_delta: map.longitudeDelta,
|
|
310
|
+
show_info_list: map.showInfoList === true,
|
|
311
|
+
annotations: (map.annotations || []).map((annotation, index) => ({
|
|
312
|
+
annotation_number: annotation.annotationNumber ?? index + 1,
|
|
313
|
+
latitude: annotation.latitude,
|
|
314
|
+
longitude: annotation.longitude,
|
|
315
|
+
title: annotation.title || '',
|
|
316
|
+
body: annotation.body || ''
|
|
317
|
+
})),
|
|
318
|
+
__typename: 'GenAIMapPrimitive'
|
|
319
|
+
},
|
|
320
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
case RichSubMessageType.DYNAMIC: {
|
|
325
|
+
const dynamic = submessage.dynamicMetadata || {};
|
|
326
|
+
const dynamicType = dynamic.type === proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF
|
|
327
|
+
? 'GIF'
|
|
328
|
+
: 'IMAGE';
|
|
329
|
+
return {
|
|
330
|
+
view_model: {
|
|
331
|
+
primitive: {
|
|
332
|
+
dynamic_type: dynamicType,
|
|
333
|
+
version: dynamic.version,
|
|
334
|
+
url: dynamic.url || '',
|
|
335
|
+
loop_count: dynamic.loopCount,
|
|
336
|
+
__typename: 'GenAIDynamicMediaPrimitive'
|
|
337
|
+
},
|
|
338
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
case RichSubMessageType.TEXT:
|
|
343
|
+
return {
|
|
344
|
+
view_model: {
|
|
345
|
+
primitive: {
|
|
346
|
+
text: submessage.messageText || '',
|
|
347
|
+
inline_entities: submessage.inlineEntities || [],
|
|
348
|
+
__typename: 'GenAIMarkdownTextUXPrimitive'
|
|
349
|
+
},
|
|
350
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
default:
|
|
354
|
+
return submessage;
|
|
355
|
+
}
|
|
356
|
+
})
|
|
357
|
+
});
|
|
358
|
+
/**
|
|
359
|
+
* Build the Meta-style AI image/video primitive used for generation states.
|
|
360
|
+
* This is intentionally additive: existing reels, tables, links, and menus keep
|
|
361
|
+
* their current wire format.
|
|
362
|
+
*/
|
|
363
|
+
export const buildImaginePrimitive = ({
|
|
364
|
+
mediaType = 'video',
|
|
365
|
+
url = '',
|
|
366
|
+
thumbnail,
|
|
367
|
+
mimeType,
|
|
368
|
+
fileLength = 0,
|
|
369
|
+
duration = 0,
|
|
370
|
+
status = 'GENERATING',
|
|
371
|
+
estimatedMs,
|
|
372
|
+
imagineType
|
|
373
|
+
} = {}) => {
|
|
374
|
+
const normalizedType = String(mediaType).toLowerCase() === 'image' ? 'IMAGE' : 'ANIMATE';
|
|
375
|
+
const primitive = {
|
|
376
|
+
media: {
|
|
377
|
+
url: url || '',
|
|
378
|
+
mime_type: mimeType || (normalizedType === 'IMAGE' ? 'image/jpeg' : 'video/mp4'),
|
|
379
|
+
file_length: fileLength || 0,
|
|
380
|
+
duration: duration || 0
|
|
381
|
+
},
|
|
382
|
+
imagine_type: imagineType || normalizedType,
|
|
383
|
+
status: { status: String(status || 'GENERATING').toUpperCase() },
|
|
384
|
+
__typename: 'GenAIImaginePrimitive'
|
|
385
|
+
};
|
|
386
|
+
if (estimatedMs != null) {
|
|
387
|
+
primitive.status.estimated_completion_time = Math.floor((Date.now() + Number(estimatedMs)) / 1000);
|
|
388
|
+
}
|
|
389
|
+
if (thumbnail) primitive.thumbnail = { raw_media: thumbnail };
|
|
390
|
+
return primitive;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Prepare a native rich-response message containing a generation primitive.
|
|
395
|
+
* `itemId` is returned to callers so a later edit can replace the same item.
|
|
396
|
+
*/
|
|
397
|
+
export const prepareRichGenerationMessage = ({
|
|
398
|
+
text = '',
|
|
399
|
+
mediaType = 'video',
|
|
400
|
+
url = '',
|
|
401
|
+
thumbnail,
|
|
402
|
+
mimeType,
|
|
403
|
+
fileLength = 0,
|
|
404
|
+
duration = 0,
|
|
405
|
+
status = 'GENERATING',
|
|
406
|
+
estimatedMs,
|
|
407
|
+
itemId = `imagine_${randomUUID()}`,
|
|
408
|
+
responseId = randomUUID(),
|
|
409
|
+
forwarded = true,
|
|
410
|
+
verificationMetadata
|
|
411
|
+
} = {}) => {
|
|
412
|
+
const sections = [];
|
|
413
|
+
if (text) {
|
|
414
|
+
sections.push({ view_model: { primitive: { text: String(text), inline_entities: [], __typename: 'GenAIMarkdownTextUXPrimitive' }, __typename: 'GenAISingleLayoutViewModel' } });
|
|
415
|
+
}
|
|
416
|
+
sections.push({ view_model: { primitive: buildImaginePrimitive({ mediaType, url, thumbnail, mimeType, fileLength, duration, status, estimatedMs }), __typename: 'GenAISingleLayoutViewModel', id: itemId } });
|
|
417
|
+
const submessages = text ? [{ messageType: RichSubMessageType.TEXT, messageText: String(text) }] : [];
|
|
418
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
419
|
+
submessages,
|
|
420
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
421
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ response_id: responseId, sections })) },
|
|
422
|
+
contextInfo: forwarded ? { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } : {}
|
|
423
|
+
});
|
|
424
|
+
const message = wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
425
|
+
message.messageContextInfo = message.messageContextInfo || {};
|
|
426
|
+
message.messageContextInfo.botMetadata = {
|
|
427
|
+
...(message.messageContextInfo.botMetadata || {}),
|
|
428
|
+
botResponseId: responseId
|
|
429
|
+
};
|
|
430
|
+
return { message, responseId, itemId };
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
// Lia@Note 17-04-26 --- WIP
|
|
434
|
+
/**
|
|
435
|
+
* A preview-media descriptor is only meaningful when the client can locate and
|
|
436
|
+
* decrypt the media. A descriptor without a key, hash and direct path describes
|
|
437
|
+
* media that cannot be fetched, so it is dropped rather than shipped
|
|
438
|
+
* present-but-empty (which is what previously produced `''` crypto fields and a
|
|
439
|
+
* hard-coded `image/jpeg` mimetype on every reel).
|
|
440
|
+
*
|
|
441
|
+
* Callers that upload real media supply it as `previewMedia` on the reel item or
|
|
442
|
+
* LaTeX expression: `{ fileSha256, mediaKey, fileEncSha256, directPath, mimetype?, mediaKeyTimestamp?, mediaId? }`.
|
|
443
|
+
*/
|
|
444
|
+
const normalizePreviewMedia = (media) => {
|
|
445
|
+
if (!media || typeof media !== 'object') return null;
|
|
446
|
+
const { fileSha256, mediaKey, fileEncSha256, directPath, mimetype, mediaKeyTimestamp } = media;
|
|
447
|
+
if (!fileSha256 || !mediaKey || !fileEncSha256 || !directPath) return null;
|
|
448
|
+
return {
|
|
449
|
+
fileSha256,
|
|
450
|
+
mediaKey,
|
|
451
|
+
fileEncSha256,
|
|
452
|
+
directPath,
|
|
453
|
+
mediaKeyTimestamp: mediaKeyTimestamp ?? unixTimestampSeconds(),
|
|
454
|
+
mimetype: mimetype || 'image/jpeg'
|
|
455
|
+
};
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
export const buildAdditionalBotMetadataContext = (submessages) => {
|
|
459
|
+
const sources = [];
|
|
460
|
+
const mediaDetailsMetadataList = [];
|
|
461
|
+
for (const submessage of submessages) {
|
|
462
|
+
switch (submessage.messageType) {
|
|
463
|
+
case RichSubMessageType.CONTENT_ITEMS: {
|
|
464
|
+
const itemsMetadata = submessage.contentItemsMetadata?.itemsMetadata || [];
|
|
465
|
+
for (const item of itemsMetadata) {
|
|
466
|
+
const reelItem = item?.reelItem || item || {};
|
|
467
|
+
sources.push({
|
|
468
|
+
provider: 0,
|
|
469
|
+
thumbnailCdnUrl: reelItem.thumbnailUrl || reelItem.thumbnail_url || '',
|
|
470
|
+
sourceProviderUrl: reelItem.videoUrl || reelItem.reels_url || reelItem.url || '',
|
|
471
|
+
sourceQuery: '',
|
|
472
|
+
faviconCdnUrl: reelItem.profileIconUrl || reelItem.avatar_url || '',
|
|
473
|
+
// 1-based source ordinal, not the submessage index.
|
|
474
|
+
citationNumber: sources.length + 1,
|
|
475
|
+
sourceTitle: reelItem.title || reelItem.reels_title || reelItem.creator || ''
|
|
476
|
+
});
|
|
477
|
+
const previewMedia = normalizePreviewMedia(reelItem.previewMedia);
|
|
478
|
+
if (previewMedia) {
|
|
479
|
+
mediaDetailsMetadataList.push({
|
|
480
|
+
id: reelItem.mediaId || reelItem.previewMedia?.mediaId || randomBytes(32).toString('hex'),
|
|
481
|
+
previewMedia
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case RichSubMessageType.LATEX: {
|
|
488
|
+
const expressions = submessage.latexMetadata?.expressions || [];
|
|
489
|
+
for (const expression of expressions) {
|
|
490
|
+
const previewMedia = normalizePreviewMedia(expression?.previewMedia);
|
|
491
|
+
if (previewMedia) {
|
|
492
|
+
mediaDetailsMetadataList.push({
|
|
493
|
+
id: expression.mediaId || expression.previewMedia?.mediaId || randomBytes(32).toString('hex'),
|
|
494
|
+
previewMedia
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return { sources, mediaDetailsMetadataList };
|
|
503
|
+
}
|
|
504
|
+
const richMenuToolId = () => randomBytes(8).toString('hex');
|
|
505
|
+
|
|
506
|
+
const mediaPrimitive = (image, inline = false, padding = 4) => {
|
|
507
|
+
if (!image?.url) return null;
|
|
508
|
+
const media = {
|
|
509
|
+
__typename: 'GenAIMediaItem',
|
|
510
|
+
mime_type: image.mime_type || image.mimeType || 'image/png',
|
|
511
|
+
url: image.url,
|
|
512
|
+
url_fallback: image.url,
|
|
513
|
+
width: image.width || (inline ? 500 : undefined),
|
|
514
|
+
height: image.height || (inline ? 500 : undefined),
|
|
515
|
+
expiration_timestamp_ms: Date.now() + 86400000,
|
|
516
|
+
};
|
|
517
|
+
if (inline) {
|
|
518
|
+
return {
|
|
519
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
520
|
+
text: '{{header}}.{{/header}}',
|
|
521
|
+
inline_entities: [{
|
|
522
|
+
__typename: 'GenAITextInlineEntity',
|
|
523
|
+
key: 'header',
|
|
524
|
+
metadata: {
|
|
525
|
+
__typename: 'GenAILatexItem',
|
|
526
|
+
latex_expression: '.',
|
|
527
|
+
font_height: 24,
|
|
528
|
+
padding,
|
|
529
|
+
latex_image: media,
|
|
530
|
+
},
|
|
531
|
+
}],
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
return {
|
|
535
|
+
__typename: 'GenAIImagePrimitive',
|
|
536
|
+
preview_image: media,
|
|
537
|
+
full_image: media,
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const richMenuButton = (button, toast = '') => {
|
|
542
|
+
const label = typeof button === 'string' ? button : (button?.text || button?.label || button?.id || 'Option');
|
|
543
|
+
return {
|
|
544
|
+
label: String(label),
|
|
545
|
+
state: 'PENDING',
|
|
546
|
+
kind: 'OTHER',
|
|
547
|
+
// Preserve supplied IDs so WhatsApp CTA replies are routable.
|
|
548
|
+
// Legacy string-only buttons retain generated IDs for compatibility.
|
|
549
|
+
tool_call_id: typeof button === 'object' && button?.id != null
|
|
550
|
+
? String(button.id)
|
|
551
|
+
: richMenuToolId(),
|
|
552
|
+
toast: {
|
|
553
|
+
label: typeof button === 'object' && button?.toast != null ? String(button.toast) : String(toast || ''),
|
|
554
|
+
__typename: 'GenAIExtWidgetToast',
|
|
555
|
+
},
|
|
556
|
+
__typename: 'GenAI3PExtWidgetCTA',
|
|
557
|
+
};
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Builds the Meta AI-style rich menu envelope used by vansnowi/baileys.
|
|
562
|
+
* This is an experimental WhatsApp rich-response format, not a standard
|
|
563
|
+
* buttonsMessage/nativeFlowMessage payload.
|
|
564
|
+
*/
|
|
565
|
+
/**
|
|
566
|
+
* Build a universal AIRich social/entity result card.
|
|
567
|
+
* The wire format is provider-neutral; Instagram is exposed as a dedicated
|
|
568
|
+
* convenience wrapper below because it is the primary supported profile view.
|
|
569
|
+
*/
|
|
570
|
+
export const prepareSocialEntityMessage = ({
|
|
571
|
+
username = '',
|
|
572
|
+
platform = 'GENERIC',
|
|
573
|
+
title = 'X4R1S3',
|
|
574
|
+
subtitle = '⚉',
|
|
575
|
+
imageUrl = '',
|
|
576
|
+
entityId,
|
|
577
|
+
entityUrl = '',
|
|
578
|
+
entityType,
|
|
579
|
+
fullName = 'NOT found',
|
|
580
|
+
isVerified = false,
|
|
581
|
+
resultText = 'See results',
|
|
582
|
+
botJid = '867051314767696@bot',
|
|
583
|
+
responseId
|
|
584
|
+
} = {}) => {
|
|
585
|
+
const normalizedPlatform = String(platform || 'GENERIC').toUpperCase();
|
|
586
|
+
const profileUrl = entityUrl || (username ? `https://www.${normalizedPlatform.toLowerCase()}.com/${encodeURIComponent(username)}` : '');
|
|
587
|
+
const resolvedType = entityType || (normalizedPlatform === 'INSTAGRAM' ? 'IG_PROFILE' : 'SOCIAL_PROFILE');
|
|
588
|
+
const displayName = username || fullName || 'Profile';
|
|
589
|
+
const sections = [
|
|
590
|
+
{
|
|
591
|
+
view_model: {
|
|
592
|
+
primitives: [{
|
|
593
|
+
title,
|
|
594
|
+
subtitle,
|
|
595
|
+
...(imageUrl ? { image: { url: imageUrl, mime_type: 'image/png' } } : {}),
|
|
596
|
+
entity_id: String(entityId ?? username ?? ''),
|
|
597
|
+
entity_url: profileUrl,
|
|
598
|
+
entity_type: 'WEBSITE',
|
|
599
|
+
action_type: 'OPEN_URL',
|
|
600
|
+
is_verified: !!isVerified,
|
|
601
|
+
__typename: 'GenAICompactEntityPrimitive'
|
|
602
|
+
}],
|
|
603
|
+
__typename: 'GenAIActionRowLayoutViewModel'
|
|
604
|
+
}
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
view_model: {
|
|
608
|
+
primitives: [{ type: 'HORIZONTAL_LINE', __typename: 'GenAIDividerPrimitive' }],
|
|
609
|
+
__typename: 'GenAIVStackLayoutViewModel'
|
|
610
|
+
}
|
|
611
|
+
},
|
|
612
|
+
{
|
|
613
|
+
view_model: {
|
|
614
|
+
primitives: [
|
|
615
|
+
{ __typename: 'GenAISpacerPrimitive' },
|
|
616
|
+
{
|
|
617
|
+
text: `# {{social_entity_1}}${resultText}\0{{/social_entity_1}} `,
|
|
618
|
+
inline_entities: [{
|
|
619
|
+
key: 'social_entity_1',
|
|
620
|
+
metadata: {
|
|
621
|
+
__typename: 'GenAISocialEntityItem',
|
|
622
|
+
entity_id: String(entityId ?? username ?? ''),
|
|
623
|
+
entity_name: displayName,
|
|
624
|
+
entity_full_name: fullName,
|
|
625
|
+
platform: String(platform || 'GENERIC').toUpperCase(),
|
|
626
|
+
entity_picture_url: imageUrl,
|
|
627
|
+
entity_url: profileUrl,
|
|
628
|
+
entity_type: resolvedType,
|
|
629
|
+
platform: normalizedPlatform,
|
|
630
|
+
is_verified: !!isVerified
|
|
631
|
+
}
|
|
632
|
+
}],
|
|
633
|
+
__typename: 'GenAIMarkdownTextUXPrimitive'
|
|
634
|
+
},
|
|
635
|
+
{ __typename: 'GenAISpacerPrimitive' }
|
|
636
|
+
],
|
|
637
|
+
__typename: 'GenAIActionRowLayoutViewModel'
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
];
|
|
641
|
+
return {
|
|
642
|
+
botForwardedMessage: {
|
|
643
|
+
message: {
|
|
644
|
+
richResponseMessage: {
|
|
645
|
+
messageType: 1,
|
|
646
|
+
submessages: [],
|
|
647
|
+
unifiedResponse: {
|
|
648
|
+
response_id: responseId || randomUUID(),
|
|
649
|
+
data: Buffer.from(JSON.stringify({ sections })).toString('base64')
|
|
650
|
+
},
|
|
651
|
+
contextInfo: {
|
|
652
|
+
isForwarded: true,
|
|
653
|
+
forwardOrigin: 4,
|
|
654
|
+
forwardedAiBotMessageInfo: { botJid }
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
/** Dedicated Instagram profile card using the universal social-entity wire format. */
|
|
663
|
+
export const prepareInstagramProfileMessage = (content = {}) => prepareSocialProfileMessage({
|
|
664
|
+
...content,
|
|
665
|
+
platform: 'INSTAGRAM',
|
|
666
|
+
entityType: 'IG_PROFILE',
|
|
667
|
+
entityUrl: content.entityUrl || (content.username ? `https://www.instagram.com/${encodeURIComponent(content.username)}` : undefined)
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
export const prepareRichMenuMessage = (content = {}) => {
|
|
671
|
+
const { header = {}, body = {}, footer = {}, verificationMetadata } = content || {};
|
|
672
|
+
const sections = [];
|
|
673
|
+
const title = header?.title || '';
|
|
674
|
+
if (title) {
|
|
675
|
+
sections.push({
|
|
676
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
677
|
+
view_model: {
|
|
678
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
679
|
+
primitive: { __typename: 'FOATextPrimitive', text: '# ' + title },
|
|
680
|
+
},
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
const headerImage = mediaPrimitive(header?.image, Boolean(header?.image?.inline));
|
|
684
|
+
if (headerImage) {
|
|
685
|
+
sections.push({
|
|
686
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
687
|
+
view_model: { __typename: 'GenAISingleLayoutViewModel', primitive: headerImage },
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
if (header?.disclaimer) {
|
|
691
|
+
sections.push({
|
|
692
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
693
|
+
view_model: {
|
|
694
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
695
|
+
primitive: { __typename: 'GenAIMarkdownTextUXPrimitive', text: header.disclaimerText || ' ' },
|
|
696
|
+
},
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
const cards = Array.isArray(body?.cards) ? body.cards : [];
|
|
700
|
+
const buttons = Array.isArray(body?.buttons) ? body.buttons : [];
|
|
701
|
+
if (cards.length) {
|
|
702
|
+
sections.push({
|
|
703
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
704
|
+
view_model: {
|
|
705
|
+
primitives: cards.map(card => ({
|
|
706
|
+
__typename: 'GenAI3PExtWidgetPrimitive',
|
|
707
|
+
header: { __typename: 'GenAI3PExtWidgetStandardHeader', title: card?.title || '' },
|
|
708
|
+
body: {
|
|
709
|
+
__typename: 'GenAI3PExtCalendarEventList',
|
|
710
|
+
ctas: (Array.isArray(card?.buttons) ? card.buttons : []).map(button => richMenuButton(button, card?.toast)),
|
|
711
|
+
sections: [],
|
|
712
|
+
},
|
|
713
|
+
})),
|
|
714
|
+
__typename: body.carousel ? 'GenAIHScrollLayoutViewModel' : 'GenAIActionRowLayoutViewModel',
|
|
715
|
+
},
|
|
716
|
+
});
|
|
717
|
+
} else if (buttons.length) {
|
|
718
|
+
sections.push({
|
|
719
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
720
|
+
view_model: {
|
|
721
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
722
|
+
primitive: {
|
|
723
|
+
__typename: 'GenAI3PExtWidgetPrimitive',
|
|
724
|
+
header: { __typename: 'GenAI3PExtWidgetStandardHeader', title: body.title || '' },
|
|
725
|
+
body: {
|
|
726
|
+
__typename: 'GenAI3PExtCalendarEventList',
|
|
727
|
+
ctas: buttons.map(button => richMenuButton(button, body.toast)),
|
|
728
|
+
sections: [],
|
|
729
|
+
},
|
|
730
|
+
},
|
|
731
|
+
},
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
if (footer?.text || footer?.url || footer?.image?.url) {
|
|
735
|
+
const footerImage = mediaPrimitive(footer.image, true, -5);
|
|
736
|
+
sections.push({
|
|
737
|
+
view_model: {
|
|
738
|
+
primitives: [
|
|
739
|
+
{ __typename: 'GenAIFooterActionPrimitive', cta_text: footer.text || 'Open', cta_type: 'OPEN_URL', cta_url: footer.url || '' },
|
|
740
|
+
...(footerImage ? [footerImage] : []),
|
|
741
|
+
],
|
|
742
|
+
__typename: 'GenAIActionRowLayoutViewModel',
|
|
743
|
+
},
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
const unified = { response_id: randomUUID(), sections };
|
|
747
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
748
|
+
submessages: [],
|
|
749
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
750
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
751
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
752
|
+
});
|
|
753
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Builds a GenAI copy-to-clipboard rich response message.
|
|
758
|
+
* Renders a text label with a dark circular copy icon (addon_action_type: COPY_TO_CLIPBOARD).
|
|
759
|
+
*
|
|
760
|
+
* @param {Object} options
|
|
761
|
+
* @param {string} options.text - The text to display (and copy when tapped)
|
|
762
|
+
* @param {string} [options.label] - Optional display label (defaults to text)
|
|
763
|
+
* @param {'END'|'START'|'CENTER'} [options.alignment='END'] - Button alignment
|
|
764
|
+
* @returns {Object} Wrapped botForwardedMessage ready for relayMessage
|
|
765
|
+
*/
|
|
766
|
+
/** Build the manually serialized AIRich command menu shown in the screenshot. */
|
|
767
|
+
export const prepareAIRichCommandMenu = ({ image, title = 'X4R1S3', subtitle = '', code = '', rows = [], buttons = [], footer = 'Developed by - X4R1S3', latexImage, latexExpression = '' } = {}) => {
|
|
768
|
+
if (!image) throw new Error('AIRich command menu requires an image URL');
|
|
769
|
+
if (!Array.isArray(rows)) throw new Error('AIRich command-menu rows must be an array');
|
|
770
|
+
if (!Array.isArray(buttons)) throw new Error('AIRich command-menu buttons must be an array');
|
|
771
|
+
const safeRows = rows.map((row, index) => ({ command: String(row?.[0] ?? row?.command ?? `command_${index + 1}`), description: String(row?.[1] ?? row?.description ?? '') }));
|
|
772
|
+
const table = ['Command | Function', '--- | ---', ...safeRows.map((row) => `${row.command} | ${row.description}`)].join('\n');
|
|
773
|
+
const inlineEntities = latexImage ? [{ key: 'NGA', metadata: { latex_expression: String(latexExpression), latex_image: { url: String(latexImage), width: 400, height: 400 }, font_height: 83.333, padding: 15, __typename: 'GenAILatexItem' } }] : [];
|
|
774
|
+
const text = [String(title), subtitle && String(subtitle), code && `Code: ${String(code)}`, '## Command List', table, footer && String(footer)].filter(Boolean).join('\n');
|
|
775
|
+
const imagePrimitive = { __typename: 'GenAIImagePrimitive', preview_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url: String(image) }, full_image: { __typename: 'GenAIMediaItem', mime_type: 'image/png', url: String(image) } };
|
|
776
|
+
const ctas = buttons.map((button, index) => ({ label: String(button?.text || button?.label || `Button ${index + 1}`), state: 'PENDING', kind: 'OTHER', tool_call_id: String(button?.id || `airich_menu_${index + 1}`), toast: { label: String(button?.toast || ''), __typename: 'GenAIExtWidgetToast' }, __typename: 'GenAI3PExtWidgetCTA' }));
|
|
777
|
+
const footerPrimitives = buttons.map((button, index) => ({ cta_text: String(button?.text || button?.label || `Button ${index + 1}`), cta_type: 'OPEN_URL', cta_url: String(button?.url || ''), __typename: 'GenAIFooterActionPrimitive' }));
|
|
778
|
+
footerPrimitives.push({ cta_text: '☷ OPEN MENU', cta_type: 'OPEN_URL', cta_url: String(buttons[0]?.url || ''), __typename: 'GenAIFooterActionPrimitive' });
|
|
779
|
+
const sections = [
|
|
780
|
+
{ __typename: 'GenAIUnifiedResponseSection', view_model: { __typename: 'GenAISingleLayoutViewModel', primitive: imagePrimitive } },
|
|
781
|
+
...(ctas.length ? [{ __typename: 'GenAIUnifiedResponseSection', view_model: { primitives: [{ __typename: 'GenAI3PExtWidgetPrimitive', header: { __typename: 'GenAI3PExtWidgetStandardHeader', title: 'Command List' }, body: { __typename: 'GenAIExtCalendarEventList', ctas, sections: [] } }], __typename: 'GenAIActionRowLayoutViewModel' } }] : []),
|
|
782
|
+
{ __typename: 'GenAIUnifiedResponseSection', view_model: { primitive: { text: `{{NGA}}${text}{{/NGA}}`, inline_entities: inlineEntities, __typename: 'GenAIMarkdownTextUXPrimitive' }, __typename: 'GenAISingleLayoutViewModel' } },
|
|
783
|
+
{ __typename: 'GenAIUnifiedResponseSection', view_model: { primitives: footerPrimitives, __typename: 'GenAIActionRowLayoutViewModel' } }
|
|
784
|
+
];
|
|
785
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
786
|
+
submessages: [{ messageType: RichSubMessageType.TEXT, messageText: text }],
|
|
787
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
788
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ response_id: randomUUID(), sections })) },
|
|
789
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 }
|
|
790
|
+
});
|
|
791
|
+
return wrapToBotForwardedMessage(richResponseMessage);
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Build the calendar-event-list widget envelope used by AIRich responses.
|
|
796
|
+
* Event section objects are passed through unchanged because their internal
|
|
797
|
+
* schema is not documented by the current Proto definitions.
|
|
798
|
+
*/
|
|
799
|
+
const prepareAIRichCalendarWidgetSection = ({ title = 'Upcoming events', sections = [], actions = [] } = {}) => {
|
|
800
|
+
if (!Array.isArray(sections) || sections.some(section => !section || typeof section !== 'object' || Array.isArray(section))) {
|
|
801
|
+
throw new Boom('calendarWidget.sections must be an array of section objects', { statusCode: 400 });
|
|
802
|
+
}
|
|
803
|
+
if (!Array.isArray(actions) || actions.some(action => !action || typeof action !== 'object' || Array.isArray(action))) {
|
|
804
|
+
throw new Boom('calendarWidget.actions must be an array of action objects', { statusCode: 400 });
|
|
805
|
+
}
|
|
806
|
+
const ctas = actions.map((action, index) => ({
|
|
807
|
+
__typename: 'GenAI3PExtWidgetCTA',
|
|
808
|
+
label: String(action.label ?? ''),
|
|
809
|
+
state: String(action.state ?? 'PENDING'),
|
|
810
|
+
kind: String(action.kind ?? 'OTHER'),
|
|
811
|
+
tool_call_id: String(action.tool_call_id ?? action.toolCallId ?? action.id ?? `calendar_action_${index + 1}`),
|
|
812
|
+
...(action.toast !== undefined ? {
|
|
813
|
+
toast: {
|
|
814
|
+
__typename: 'GenAI3PExtWidgetToast',
|
|
815
|
+
label: String(typeof action.toast === 'object' && action.toast !== null ? action.toast.label ?? action.label ?? '' : action.toast)
|
|
816
|
+
}
|
|
817
|
+
} : {})
|
|
818
|
+
}));
|
|
819
|
+
const widget = {
|
|
820
|
+
__typename: 'GenAI3PExtWidgetPrimitive',
|
|
821
|
+
header: { __typename: 'GenAI3PExtWidgetStandardHeader', title: String(title) },
|
|
822
|
+
body: {
|
|
823
|
+
__typename: 'GenAI3PExtCalendarEventList',
|
|
824
|
+
sections,
|
|
825
|
+
...(ctas.length ? { ctas } : {})
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
return {
|
|
829
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
830
|
+
view_model: {
|
|
831
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
832
|
+
primitive: widget
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
};
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* Prepare a customizable client-rendered contact-style card using the
|
|
839
|
+
* inapp_signup native-flow action. The viewer-local avatar is not sent as
|
|
840
|
+
* media; it is rendered by compatible WhatsApp clients.
|
|
841
|
+
*/
|
|
842
|
+
export const prepareInteractiveContactCardMessage = ({
|
|
843
|
+
title,
|
|
844
|
+
body,
|
|
845
|
+
detailLabel = 'View details',
|
|
846
|
+
description = '',
|
|
847
|
+
buttonName = 'inapp_signup',
|
|
848
|
+
buttonParams = {},
|
|
849
|
+
footer,
|
|
850
|
+
image,
|
|
851
|
+
video,
|
|
852
|
+
gif,
|
|
853
|
+
livePhoto
|
|
854
|
+
} = {}) => {
|
|
855
|
+
const normalizedTitle = String(title ?? '').trim();
|
|
856
|
+
if (!normalizedTitle) {
|
|
857
|
+
throw new Boom('sendInteractiveContactCard requires a non-empty title', { statusCode: 400 });
|
|
858
|
+
}
|
|
859
|
+
if (typeof buttonName !== 'string' || !buttonName.trim()) {
|
|
860
|
+
throw new Boom('sendInteractiveContactCard buttonName must be a non-empty string', { statusCode: 400 });
|
|
861
|
+
}
|
|
862
|
+
if (!buttonParams || typeof buttonParams !== 'object' || Array.isArray(buttonParams)) {
|
|
863
|
+
throw new Boom('sendInteractiveContactCard buttonParams must be an object', { statusCode: 400 });
|
|
864
|
+
}
|
|
865
|
+
const mediaSources = [image, video, gif, livePhoto].filter(value => value !== undefined && value !== null);
|
|
866
|
+
if (mediaSources.length > 1) {
|
|
867
|
+
throw new Boom('sendInteractiveContactCard accepts only one of image, video, gif, or livePhoto', { statusCode: 400 });
|
|
868
|
+
}
|
|
869
|
+
if (livePhoto != null && (!livePhoto || typeof livePhoto !== 'object' || Array.isArray(livePhoto) || !livePhoto.video)) {
|
|
870
|
+
throw new Boom('sendInteractiveContactCard livePhoto requires a video source', { statusCode: 400 });
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const bodyText = body == null
|
|
874
|
+
? `${normalizedTitle}\n${String(detailLabel ?? 'View details')}${description ? `\n\n${String(description)}` : ''}`
|
|
875
|
+
: String(body);
|
|
876
|
+
|
|
877
|
+
const mediaContent = image != null
|
|
878
|
+
? { image }
|
|
879
|
+
: video != null
|
|
880
|
+
? { video }
|
|
881
|
+
: gif != null
|
|
882
|
+
? { video: gif, gifPlayback: true }
|
|
883
|
+
: {};
|
|
884
|
+
|
|
885
|
+
return {
|
|
886
|
+
...mediaContent,
|
|
887
|
+
title: normalizedTitle,
|
|
888
|
+
text: bodyText,
|
|
889
|
+
nativeFlow: [{
|
|
890
|
+
name: buttonName.trim(),
|
|
891
|
+
buttonParamsJson: JSON.stringify(buttonParams)
|
|
892
|
+
}],
|
|
893
|
+
...(footer != null ? { footer: String(footer) } : {})
|
|
894
|
+
};
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* Prepare the legacy location-header button card used by themed bot menus.
|
|
899
|
+
* The JPEG is a LocationMessage thumbnail, not a separately uploaded image.
|
|
900
|
+
*/
|
|
901
|
+
export const prepareLocationButtonCardMessage = ({
|
|
902
|
+
title,
|
|
903
|
+
subtitle = '',
|
|
904
|
+
text = '',
|
|
905
|
+
thumbnail,
|
|
906
|
+
buttons = [],
|
|
907
|
+
latitude = 0,
|
|
908
|
+
longitude = 0,
|
|
909
|
+
footer
|
|
910
|
+
} = {}) => {
|
|
911
|
+
const normalizedTitle = String(title ?? '').trim();
|
|
912
|
+
if (!normalizedTitle) {
|
|
913
|
+
throw new Boom('sendLocationButtonCard requires a non-empty title', { statusCode: 400 });
|
|
914
|
+
}
|
|
915
|
+
if (!Array.isArray(buttons) || buttons.length < 1 || buttons.length > 3) {
|
|
916
|
+
throw new Boom('sendLocationButtonCard requires between 1 and 3 buttons', { statusCode: 400 });
|
|
917
|
+
}
|
|
918
|
+
const normalizedButtons = buttons.map((button, index) => {
|
|
919
|
+
const id = String(button?.id ?? button?.buttonId ?? '').trim();
|
|
920
|
+
const label = String(button?.text ?? button?.buttonText ?? '').trim();
|
|
921
|
+
if (!id || !label) {
|
|
922
|
+
throw new Boom(`sendLocationButtonCard button ${index + 1} requires a non-empty id and text`, { statusCode: 400 });
|
|
923
|
+
}
|
|
924
|
+
return { id, text: label };
|
|
925
|
+
});
|
|
926
|
+
|
|
927
|
+
const degreesLatitude = Number(latitude);
|
|
928
|
+
const degreesLongitude = Number(longitude);
|
|
929
|
+
if (!Number.isFinite(degreesLatitude) || degreesLatitude < -90 || degreesLatitude > 90) {
|
|
930
|
+
throw new Boom('sendLocationButtonCard latitude must be between -90 and 90', { statusCode: 400 });
|
|
931
|
+
}
|
|
932
|
+
if (!Number.isFinite(degreesLongitude) || degreesLongitude < -180 || degreesLongitude > 180) {
|
|
933
|
+
throw new Boom('sendLocationButtonCard longitude must be between -180 and 180', { statusCode: 400 });
|
|
934
|
+
}
|
|
935
|
+
if (thumbnail != null && !Buffer.isBuffer(thumbnail) && !(thumbnail instanceof Uint8Array)) {
|
|
936
|
+
throw new Boom('sendLocationButtonCard thumbnail must be a Buffer or Uint8Array', { statusCode: 400 });
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
return {
|
|
940
|
+
caption: String(text ?? ''),
|
|
941
|
+
location: {
|
|
942
|
+
degreesLatitude,
|
|
943
|
+
degreesLongitude,
|
|
944
|
+
name: normalizedTitle,
|
|
945
|
+
address: String(subtitle ?? ''),
|
|
946
|
+
...(thumbnail != null ? { jpegThumbnail: Buffer.from(thumbnail) } : {})
|
|
947
|
+
},
|
|
948
|
+
buttons: normalizedButtons,
|
|
949
|
+
...(footer != null ? { footer: String(footer) } : {})
|
|
950
|
+
};
|
|
951
|
+
};
|
|
952
|
+
|
|
953
|
+
/** Prepare an image-header button card for menus that should not carry map data. */
|
|
954
|
+
export const prepareMenuButtonCardMessage = ({
|
|
955
|
+
title,
|
|
956
|
+
subtitle = '',
|
|
957
|
+
text = '',
|
|
958
|
+
image,
|
|
959
|
+
buttons = [],
|
|
960
|
+
footer
|
|
961
|
+
} = {}) => {
|
|
962
|
+
const normalizedTitle = String(title ?? '').trim();
|
|
963
|
+
if (!normalizedTitle) {
|
|
964
|
+
throw new Boom('sendMenuButtonCard requires a non-empty title', { statusCode: 400 });
|
|
965
|
+
}
|
|
966
|
+
if (!Buffer.isBuffer(image) && !(image instanceof Uint8Array)) {
|
|
967
|
+
throw new Boom('sendMenuButtonCard image must be a Buffer or Uint8Array', { statusCode: 400 });
|
|
968
|
+
}
|
|
969
|
+
if (image.length === 0) {
|
|
970
|
+
throw new Boom('sendMenuButtonCard image must not be empty', { statusCode: 400 });
|
|
971
|
+
}
|
|
972
|
+
if (!Array.isArray(buttons) || buttons.length < 1 || buttons.length > 3) {
|
|
973
|
+
throw new Boom('sendMenuButtonCard requires between 1 and 3 buttons', { statusCode: 400 });
|
|
974
|
+
}
|
|
975
|
+
const normalizedButtons = buttons.map((button, index) => {
|
|
976
|
+
const id = String(button?.id ?? button?.buttonId ?? '').trim();
|
|
977
|
+
const label = String(button?.text ?? button?.buttonText ?? '').trim();
|
|
978
|
+
if (!id || !label) {
|
|
979
|
+
throw new Boom(`sendMenuButtonCard button ${index + 1} requires a non-empty id and text`, { statusCode: 400 });
|
|
980
|
+
}
|
|
981
|
+
return { id, text: label };
|
|
982
|
+
});
|
|
983
|
+
const caption = [normalizedTitle, String(subtitle ?? '').trim(), String(text ?? '').trim()]
|
|
984
|
+
.filter(Boolean)
|
|
985
|
+
.join('\n');
|
|
986
|
+
return {
|
|
987
|
+
image: Buffer.from(image),
|
|
988
|
+
caption,
|
|
989
|
+
buttons: normalizedButtons,
|
|
990
|
+
...(footer != null ? { footer: String(footer) } : {})
|
|
991
|
+
};
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* Normalize a caller-provided location thumbnail to the compact JPEG form
|
|
996
|
+
* accepted by WhatsApp location-card renderers. The original bytes are kept
|
|
997
|
+
* as a compatibility fallback when no optional image processor is installed.
|
|
998
|
+
*/
|
|
999
|
+
export const normalizeLocationButtonCardThumbnail = async thumbnail => {
|
|
1000
|
+
if (thumbnail == null) {
|
|
1001
|
+
return thumbnail;
|
|
1002
|
+
}
|
|
1003
|
+
const original = Buffer.from(thumbnail);
|
|
1004
|
+
try {
|
|
1005
|
+
const firstPass = await extractImageThumb(original, 192);
|
|
1006
|
+
const originalWidth = Number(firstPass.original?.width) || 0;
|
|
1007
|
+
const originalHeight = Number(firstPass.original?.height) || 0;
|
|
1008
|
+
const longestSide = Math.max(originalWidth, originalHeight);
|
|
1009
|
+
const targetWidth = longestSide > 0
|
|
1010
|
+
? Math.max(1, Math.round(Math.min(192, longestSide) * originalWidth / longestSide))
|
|
1011
|
+
: 192;
|
|
1012
|
+
const buffer = targetWidth === 192
|
|
1013
|
+
? firstPass.buffer
|
|
1014
|
+
: (await extractImageThumb(original, targetWidth)).buffer;
|
|
1015
|
+
return buffer?.length ? buffer : original;
|
|
1016
|
+
}
|
|
1017
|
+
catch {
|
|
1018
|
+
return original;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* Build an arbitrary A2UI interactive message. The command-menu helper below
|
|
1024
|
+
* is only a convenience preset; callers may provide any supported component,
|
|
1025
|
+
* widget, or native-flow payload through this universal builder.
|
|
1026
|
+
*/
|
|
1027
|
+
export const prepareA2UIMessage = ({ imageMessage, bloksWidget = {}, nativeFlowMessage, fallback = '', ...interactiveFields } = {}) => ({
|
|
1028
|
+
interactiveMessage: {
|
|
1029
|
+
...interactiveFields,
|
|
1030
|
+
...(imageMessage ? { header: { imageMessage, hasMediaAttachment: true } } : {}),
|
|
1031
|
+
bloksWidget: {
|
|
1032
|
+
type: bloksWidget.type || 'im_a2ui',
|
|
1033
|
+
data: typeof bloksWidget.data === 'string' ? bloksWidget.data : JSON.stringify(bloksWidget.data || {}),
|
|
1034
|
+
...(bloksWidget.fallback || fallback ? { fallback: String(bloksWidget.fallback || fallback) } : {})
|
|
1035
|
+
},
|
|
1036
|
+
...(nativeFlowMessage ? {
|
|
1037
|
+
nativeFlowMessage: {
|
|
1038
|
+
...nativeFlowMessage,
|
|
1039
|
+
...(nativeFlowMessage.buttons ? { buttons: nativeFlowMessage.buttons } : {})
|
|
1040
|
+
}
|
|
1041
|
+
} : {})
|
|
1042
|
+
}
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
/** Build the A2UI interactive command menu used by the full-size card layout. */
|
|
1046
|
+
export const prepareA2UICommandMenu = ({ imageMessage, title = 'X4R1S3', rows = [], buttons = [], fallback = '' } = {}) => {
|
|
1047
|
+
if (!Array.isArray(rows)) throw new Error('A2UI command-menu rows must be an array');
|
|
1048
|
+
if (!Array.isArray(buttons)) throw new Error('A2UI command-menu buttons must be an array');
|
|
1049
|
+
const safeRows = rows.map((row, index) => ({
|
|
1050
|
+
title: String(row?.[0] ?? row?.title ?? `Command ${index + 1}`),
|
|
1051
|
+
description: String(row?.[1] ?? row?.description ?? ''),
|
|
1052
|
+
id: String(row?.[2] ?? row?.id ?? row?.[0] ?? `command_${index + 1}`)
|
|
1053
|
+
}));
|
|
1054
|
+
const safeButtons = buttons.map((button, index) => ({ id: `a2ui_button_${index + 1}`, label: String(button?.text || button?.label || `Button ${index + 1}`), url: String(button?.url || '') }));
|
|
1055
|
+
const componentIds = ['title', 'divider', 'tableCard', 'footer', ...(safeButtons.length ? ['buttonRow'] : [])];
|
|
1056
|
+
const components = [
|
|
1057
|
+
{ id: 'root', component: 'Column', align: 'center', children: componentIds },
|
|
1058
|
+
{ id: 'title', component: 'Text', text: String(title), variant: 'h2' },
|
|
1059
|
+
{ id: 'divider', component: 'Divider' },
|
|
1060
|
+
{ id: 'tableCard', component: 'Card', child: 'tableColumn' },
|
|
1061
|
+
{ id: 'tableColumn', component: 'Column', children: ['headerRow', ...safeRows.flatMap((_, index) => [`divider_${index}`, `row_${index}`])] },
|
|
1062
|
+
{ id: 'headerRow', component: 'Row', children: ['headerCommand', 'headerFunction'] },
|
|
1063
|
+
{ id: 'headerCommand', component: 'Text', text: 'Command', variant: 'h5' },
|
|
1064
|
+
{ id: 'headerFunction', component: 'Text', text: 'Function', variant: 'h5' },
|
|
1065
|
+
...safeRows.flatMap((row, index) => [
|
|
1066
|
+
{ id: `divider_${index}`, component: 'Divider' },
|
|
1067
|
+
{ id: `row_${index}`, component: 'Row', children: [`command_${index}`, `description_${index}`] },
|
|
1068
|
+
{ id: `command_${index}`, component: 'Text', text: row.title },
|
|
1069
|
+
{ id: `description_${index}`, component: 'Text', text: row.description }
|
|
1070
|
+
]),
|
|
1071
|
+
{ id: 'footer', component: 'Text', text: 'Developed by - X4R1S3', variant: 'caption' }
|
|
1072
|
+
];
|
|
1073
|
+
if (safeButtons.length) {
|
|
1074
|
+
components.push({ id: 'buttonRow', component: 'Row', justify: 'spaceEvenly', children: safeButtons.flatMap((button, index) => [`buttonLabel_${index}`, `button_${index}`]) });
|
|
1075
|
+
safeButtons.forEach((button, index) => {
|
|
1076
|
+
components.push({ id: `buttonLabel_${index}`, component: 'Text', text: button.label });
|
|
1077
|
+
components.push({ id: `button_${index}`, component: 'Button', child: `buttonLabel_${index}`, variant: 'primary', action: { call: 'openUrl', args: { url: button.url } } });
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
return {
|
|
1081
|
+
interactiveMessage: {
|
|
1082
|
+
...(imageMessage ? { header: { imageMessage, hasMediaAttachment: true } } : {}),
|
|
1083
|
+
bloksWidget: { type: 'im_a2ui', data: JSON.stringify({ version: 'v0.9', createSurface: { surfaceId: 'X4R1S3-a2ui-command-menu', catalogId: 'https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json', components } }), fallback: String(fallback || title) },
|
|
1084
|
+
nativeFlowMessage: { messageParamsJson: JSON.stringify({ limited_time_offer: { text: String(title), url: safeButtons[0]?.url || '', copy_code: String(title), expiration_time: Date.now() * 1000 } }), buttons: [{ name: 'single_select', buttonParamsJson: JSON.stringify({ title: String(title), sections: [{ title: 'Available Commands', rows: safeRows }] }) }] }
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
};
|
|
1088
|
+
|
|
1089
|
+
export const prepareCopyToClipboardMessage = (options = {}) => {
|
|
1090
|
+
const { text = '', label, alignment = 'END', verificationMetadata } = options;
|
|
1091
|
+
const displayText = label || text;
|
|
1092
|
+
const sections = [
|
|
1093
|
+
{
|
|
1094
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1095
|
+
view_model: {
|
|
1096
|
+
__typename: 'GenAIAddonActionLayoutViewModel',
|
|
1097
|
+
addon_action_type: 'COPY_TO_CLIPBOARD',
|
|
1098
|
+
addon_action_alignment: alignment,
|
|
1099
|
+
primitives: [
|
|
1100
|
+
{
|
|
1101
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
1102
|
+
text: String(displayText),
|
|
1103
|
+
inline_entities: [],
|
|
1104
|
+
},
|
|
1105
|
+
],
|
|
1106
|
+
},
|
|
1107
|
+
},
|
|
1108
|
+
];
|
|
1109
|
+
const unified = { response_id: randomUUID(), sections };
|
|
1110
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1111
|
+
submessages: [],
|
|
1112
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1113
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1114
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
1115
|
+
});
|
|
1116
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* Builds a GenAI rich text message — plain text rendered inside a forwarded rich response.
|
|
1121
|
+
* Uses GenAIMarkdownTextUXPrimitive inside a GenAISingleLayoutViewModel.
|
|
1122
|
+
*
|
|
1123
|
+
* @param {Object} options
|
|
1124
|
+
* @param {string} options.text - The text content to display
|
|
1125
|
+
* @returns {Object} Wrapped botForwardedMessage ready for relayMessage
|
|
1126
|
+
*/
|
|
1127
|
+
export const prepareRichTextMessage = (options = {}) => {
|
|
1128
|
+
const { text = '', verificationMetadata } = options;
|
|
1129
|
+
const sections = [
|
|
1130
|
+
{
|
|
1131
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1132
|
+
view_model: {
|
|
1133
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1134
|
+
primitive: {
|
|
1135
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
1136
|
+
text: String(text),
|
|
1137
|
+
inline_entities: [],
|
|
1138
|
+
},
|
|
1139
|
+
},
|
|
1140
|
+
},
|
|
1141
|
+
];
|
|
1142
|
+
const unified = { response_id: randomUUID(), sections };
|
|
1143
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1144
|
+
submessages: [],
|
|
1145
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1146
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1147
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
1148
|
+
});
|
|
1149
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1150
|
+
};
|
|
1151
|
+
|
|
1152
|
+
/** Builds Markdown text with an optional GenAI COPY_TO_CLIPBOARD action section. */
|
|
1153
|
+
export const prepareRichQuoteMessage = (options = {}) => {
|
|
1154
|
+
const { text = '', copyText, copyLabel = copyText, alignment = 'END', verificationMetadata } = options;
|
|
1155
|
+
const sections = [{
|
|
1156
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1157
|
+
view_model: {
|
|
1158
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1159
|
+
primitive: { __typename: 'GenAIMarkdownTextUXPrimitive', text: String(text), inline_entities: [] },
|
|
1160
|
+
},
|
|
1161
|
+
}];
|
|
1162
|
+
if (copyText) {
|
|
1163
|
+
sections.push({
|
|
1164
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1165
|
+
view_model: {
|
|
1166
|
+
__typename: 'GenAIAddonActionLayoutViewModel',
|
|
1167
|
+
addon_action_type: 'COPY_TO_CLIPBOARD',
|
|
1168
|
+
addon_action_alignment: alignment,
|
|
1169
|
+
primitives: [{ __typename: 'GenAIMarkdownTextUXPrimitive', text: String(copyLabel || copyText), inline_entities: [] }],
|
|
1170
|
+
},
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
const unified = { response_id: randomUUID(), sections };
|
|
1174
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1175
|
+
submessages: [],
|
|
1176
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1177
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1178
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
1179
|
+
});
|
|
1180
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1181
|
+
};
|
|
1182
|
+
|
|
1183
|
+
/**
|
|
1184
|
+
* Builds a GenAI rich image message — an image rendered inside a forwarded rich response.
|
|
1185
|
+
* Uses GenAIImagePrimitive with preview and full image variants.
|
|
1186
|
+
*
|
|
1187
|
+
* @param {Object} options
|
|
1188
|
+
* @param {string} options.url - Image URL
|
|
1189
|
+
* @param {string} [options.mimeType='image/png'] - MIME type
|
|
1190
|
+
* @returns {Object} Wrapped botForwardedMessage ready for relayMessage
|
|
1191
|
+
*/
|
|
1192
|
+
export const prepareRichImageMessage = (options = {}) => {
|
|
1193
|
+
const { url = '', mimeType, verificationMetadata } = options;
|
|
1194
|
+
const primitive = {
|
|
1195
|
+
...buildRichImagePrimitive({ url, mimeType }),
|
|
1196
|
+
display_mode: 'FULL_WIDTH',
|
|
1197
|
+
full_width: true,
|
|
1198
|
+
};
|
|
1199
|
+
const sections = [
|
|
1200
|
+
{
|
|
1201
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1202
|
+
view_model: {
|
|
1203
|
+
__typename: 'GenAIVStackLayoutViewModel',
|
|
1204
|
+
primitives: [primitive],
|
|
1205
|
+
display_mode: 'FULL_WIDTH',
|
|
1206
|
+
full_width: true,
|
|
1207
|
+
},
|
|
1208
|
+
},
|
|
1209
|
+
];
|
|
1210
|
+
const unified = { response_id: randomUUID(), sections };
|
|
1211
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1212
|
+
submessages: [],
|
|
1213
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1214
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1215
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
1216
|
+
});
|
|
1217
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1218
|
+
};
|
|
1219
|
+
|
|
1220
|
+
|
|
1221
|
+
/**
|
|
1222
|
+
* Builds a GenAI rich link message — inline hyperlinks rendered inside a forwarded rich response.
|
|
1223
|
+
* Uses GenAIInlineLinkItem for simple clickable text links (not citation-style).
|
|
1224
|
+
*
|
|
1225
|
+
* @param {Object} options
|
|
1226
|
+
* @param {Array<Object>} options.links - Array of { text, url, displayName?, isTrusted? }
|
|
1227
|
+
* @returns {Object} Wrapped botForwardedMessage ready for relayMessage
|
|
1228
|
+
*/
|
|
1229
|
+
export const prepareRichLinkMessage = (options = {}) => {
|
|
1230
|
+
const { links = [], text: fallbackText, verificationMetadata } = options;
|
|
1231
|
+
const sections = [];
|
|
1232
|
+
const allInlineEntities = [];
|
|
1233
|
+
let combinedText = '';
|
|
1234
|
+
|
|
1235
|
+
links.forEach((link, index) => {
|
|
1236
|
+
const key = `INLINE_HYPERLINK_${index}`;
|
|
1237
|
+
const displayText = link.text || link.displayName || link.url || '';
|
|
1238
|
+
const url = link.url || '';
|
|
1239
|
+
const isTrusted = link.isTrusted !== false;
|
|
1240
|
+
|
|
1241
|
+
combinedText += `{{${key}}}${displayText}{{/${key}}}`;
|
|
1242
|
+
allInlineEntities.push({
|
|
1243
|
+
key,
|
|
1244
|
+
metadata: {
|
|
1245
|
+
display_name: displayText,
|
|
1246
|
+
is_trusted: isTrusted,
|
|
1247
|
+
url,
|
|
1248
|
+
__typename: 'GenAIInlineLinkItem',
|
|
1249
|
+
},
|
|
1250
|
+
});
|
|
1251
|
+
});
|
|
1252
|
+
|
|
1253
|
+
sections.push({
|
|
1254
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1255
|
+
view_model: {
|
|
1256
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1257
|
+
primitive: {
|
|
1258
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
1259
|
+
text: combinedText || fallbackText || '',
|
|
1260
|
+
inline_entities: allInlineEntities,
|
|
1261
|
+
},
|
|
1262
|
+
},
|
|
1263
|
+
});
|
|
1264
|
+
if (sections.length === 0) {
|
|
1265
|
+
sections.push({
|
|
1266
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1267
|
+
view_model: {
|
|
1268
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1269
|
+
primitive: {
|
|
1270
|
+
__typename: 'GenAIMarkdownTextUXPrimitive',
|
|
1271
|
+
text: '',
|
|
1272
|
+
inline_entities: [],
|
|
1273
|
+
},
|
|
1274
|
+
},
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
const unified = { response_id: randomUUID(), sections };
|
|
1278
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1279
|
+
submessages: [],
|
|
1280
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1281
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1282
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
1283
|
+
});
|
|
1284
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1285
|
+
};
|
|
1286
|
+
|
|
1287
|
+
/** Build an AIRich GRID_IMAGE album instead of the legacy albumMessage collection. */
|
|
1288
|
+
export const prepareGridImageMessage = ({ imageUrls = [], verificationMetadata } = {}) => {
|
|
1289
|
+
if (!Array.isArray(imageUrls) || imageUrls.length < 2) {
|
|
1290
|
+
throw new Error('GRID_IMAGE album requires at least two images');
|
|
1291
|
+
}
|
|
1292
|
+
const submessages = [{
|
|
1293
|
+
messageType: RichSubMessageType.GRID_IMAGE,
|
|
1294
|
+
gridImageMetadata: { imageUrls }
|
|
1295
|
+
}];
|
|
1296
|
+
const unified = toUnified(submessages, randomUUID());
|
|
1297
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1298
|
+
submessages,
|
|
1299
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1300
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1301
|
+
contextInfo: {
|
|
1302
|
+
isForwarded: true,
|
|
1303
|
+
forwardingScore: 1,
|
|
1304
|
+
forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
|
|
1305
|
+
forwardOrigin: 4
|
|
1306
|
+
}
|
|
1307
|
+
});
|
|
1308
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1309
|
+
};
|
|
1310
|
+
|
|
1311
|
+
/**
|
|
1312
|
+
* Build a video grid using the client-supported GenAIVideoPrimitive.
|
|
1313
|
+
*
|
|
1314
|
+
* WhatsApp exposes no AIRich GRID_VIDEO submessage type. Video grids therefore
|
|
1315
|
+
* use the generic unified-response Grid layout with one GenAIVideoPrimitive per
|
|
1316
|
+
* item. This is deliberately separate from prepareGridImageMessage so callers
|
|
1317
|
+
* do not accidentally label video media as GenAIImagePrimitive.
|
|
1318
|
+
*/
|
|
1319
|
+
/** Build a full-width vertical album with one large media item per row. */
|
|
1320
|
+
export const prepareVerticalAlbumMessage = ({ items = [], verificationMetadata } = {}) => {
|
|
1321
|
+
if (!Array.isArray(items) || items.length < 2) throw new Error('Vertical album requires at least two media items');
|
|
1322
|
+
const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
|
1323
|
+
const primitives = items.map((item) => {
|
|
1324
|
+
const kind = item?.type || (item?.video ? 'video' : 'image');
|
|
1325
|
+
if (kind === 'video') {
|
|
1326
|
+
const video = item.video || item.data || item;
|
|
1327
|
+
const url = typeof video === 'string' ? video : (video?.url || video?.videoUrl || '');
|
|
1328
|
+
if (!url) throw new Error('Each video album item requires a video URL');
|
|
1329
|
+
return buildImaginePrimitive({ mediaType: 'video', url, thumbnail: video?.thumbnail || video?.thumbnailUrl, mimeType: video?.mimeType || video?.mime_type || 'video/mp4', fileLength: video?.fileLength || video?.file_length || 0, duration: video?.duration || 0, status: 'READY' });
|
|
1330
|
+
}
|
|
1331
|
+
const rawImage = item?.image || item?.data || item;
|
|
1332
|
+
const image = typeof rawImage === 'string' ? { url: rawImage } : (rawImage || {});
|
|
1333
|
+
const sourceUrl = firstImageValue(
|
|
1334
|
+
image?.imageHighResUrl, image?.highResUrl, image?.fullUrl,
|
|
1335
|
+
image?.imagePreviewUrl, image?.previewUrl, image?.sourceUrl, image?.url
|
|
1336
|
+
) || '';
|
|
1337
|
+
if (!sourceUrl) throw new Error('Each image album item requires an image URL');
|
|
1338
|
+
// Unlike a compact image grid, vertical albums are intended to render
|
|
1339
|
+
// the actual media at full size. Some clients choose preview_image and
|
|
1340
|
+
// never follow full_image, so expose the selected full URL/dimensions
|
|
1341
|
+
// in both slots instead of allowing a thumbnail URL to win.
|
|
1342
|
+
const fullUrl = firstImageValue(
|
|
1343
|
+
image?.imageHighResUrl, image?.highResUrl, image?.high_res_url,
|
|
1344
|
+
image?.fullUrl, image?.full_url, image?.sourceUrl, image?.source_url, image?.url
|
|
1345
|
+
) || sourceUrl;
|
|
1346
|
+
const fullWidth = Number(image?.fullWidth || image?.full_width || image?.highResWidth || image?.high_res_width || image?.width || item?.width || 0);
|
|
1347
|
+
const fullHeight = Number(image?.fullHeight || image?.full_height || image?.highResHeight || image?.high_res_height || image?.height || item?.height || 0);
|
|
1348
|
+
const primitive = buildRichImagePrimitive({
|
|
1349
|
+
...image,
|
|
1350
|
+
imagePreviewUrl: fullUrl,
|
|
1351
|
+
previewUrl: fullUrl,
|
|
1352
|
+
sourceUrl: fullUrl,
|
|
1353
|
+
imageHighResUrl: fullUrl,
|
|
1354
|
+
fullUrl,
|
|
1355
|
+
...(fullWidth > 0 ? { width: fullWidth, fullWidth } : {}),
|
|
1356
|
+
...(fullHeight > 0 ? { height: fullHeight, fullHeight } : {})
|
|
1357
|
+
}, expiration);
|
|
1358
|
+
return { ...primitive, display_mode: 'FULL_WIDTH', full_width: true };
|
|
1359
|
+
});
|
|
1360
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1361
|
+
submessages: [],
|
|
1362
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1363
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ response_id: randomUUID(), sections: [{ view_model: { primitives, display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIVStackLayoutViewModel' } }] })) },
|
|
1364
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 }
|
|
1365
|
+
});
|
|
1366
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1367
|
+
};
|
|
1368
|
+
|
|
1369
|
+
export const prepareVideoGridMessage = ({ videos = [], verificationMetadata } = {}) => {
|
|
1370
|
+
if (!Array.isArray(videos) || videos.length < 2) {
|
|
1371
|
+
throw new Error('Video grid requires at least two videos');
|
|
1372
|
+
}
|
|
1373
|
+
const primitives = videos.map((video) => {
|
|
1374
|
+
const url = typeof video === 'string' ? video : (video?.url || video?.videoUrl || video?.reelsUrl || '');
|
|
1375
|
+
if (!url) throw new Error('Each video-grid item requires a video URL');
|
|
1376
|
+
const item = typeof video === 'string' ? {} : video;
|
|
1377
|
+
return {
|
|
1378
|
+
post_id: item.postId == null ? undefined : String(item.postId),
|
|
1379
|
+
reels_url: url,
|
|
1380
|
+
reels_title: item.title,
|
|
1381
|
+
thumbnail_url: item.thumbnailUrl || item.thumbnail,
|
|
1382
|
+
creator: item.creator,
|
|
1383
|
+
avatar_url: item.avatarUrl,
|
|
1384
|
+
content_hash: item.contentHash,
|
|
1385
|
+
likes_count: item.likes,
|
|
1386
|
+
comments_count: item.comments,
|
|
1387
|
+
shares_count: item.shares,
|
|
1388
|
+
is_verified: item.isVerified,
|
|
1389
|
+
source_app: item.sourceApp,
|
|
1390
|
+
video_delivery_response: {
|
|
1391
|
+
progressive_urls: (item.progressiveUrls || []).map((value) => ({
|
|
1392
|
+
progressive_url: value,
|
|
1393
|
+
__typename: 'GenAIProgressiveUrlResponse'
|
|
1394
|
+
})),
|
|
1395
|
+
dash_manifests: (item.dashManifests || []).map((value) => ({
|
|
1396
|
+
manifest_xml: value,
|
|
1397
|
+
__typename: 'GenAIDashManifestResponse'
|
|
1398
|
+
})),
|
|
1399
|
+
__typename: 'GenAIVideoDeliveryResponse'
|
|
1400
|
+
},
|
|
1401
|
+
__typename: 'GenAIVideoPrimitive'
|
|
1402
|
+
};
|
|
1403
|
+
});
|
|
1404
|
+
const unified = {
|
|
1405
|
+
response_id: randomUUID(),
|
|
1406
|
+
sections: [{
|
|
1407
|
+
view_model: {
|
|
1408
|
+
primitives,
|
|
1409
|
+
__typename: 'GenAIGridLayoutViewModel'
|
|
1410
|
+
}
|
|
1411
|
+
}]
|
|
1412
|
+
};
|
|
1413
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1414
|
+
submessages: [],
|
|
1415
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1416
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1417
|
+
contextInfo: {
|
|
1418
|
+
isForwarded: true,
|
|
1419
|
+
forwardingScore: 1,
|
|
1420
|
+
forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
|
|
1421
|
+
forwardOrigin: 4
|
|
1422
|
+
}
|
|
1423
|
+
});
|
|
1424
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1425
|
+
};
|
|
1426
|
+
|
|
1427
|
+
/**
|
|
1428
|
+
* Builds a compact social-profile card used by WhatsApp's unified response
|
|
1429
|
+
* renderer. The summary is an inline social entity, not ordinary plain text.
|
|
1430
|
+
*/
|
|
1431
|
+
export const prepareSocialProfileMessage = (options = {}) => {
|
|
1432
|
+
const {
|
|
1433
|
+
username,
|
|
1434
|
+
platform = 'instagram',
|
|
1435
|
+
title = 'X4R1S3',
|
|
1436
|
+
subtitle = '⚉',
|
|
1437
|
+
imageUrl = '',
|
|
1438
|
+
entityId = username,
|
|
1439
|
+
entityUrl = `https://www.${platform}.com/${username || ''}`,
|
|
1440
|
+
entityType = platform === 'instagram' ? 'IG_PROFILE' : `${String(platform).toUpperCase()}_PROFILE`,
|
|
1441
|
+
fullName = 'NOT found',
|
|
1442
|
+
isVerified = false,
|
|
1443
|
+
resultText = 'See results'
|
|
1444
|
+
} = options;
|
|
1445
|
+
if (!username || typeof username !== 'string') {
|
|
1446
|
+
throw new Boom('sendSocialProfile requires a username', { statusCode: 400 });
|
|
1447
|
+
}
|
|
1448
|
+
const image = imageUrl ? { url: imageUrl, mime_type: 'image/png' } : undefined;
|
|
1449
|
+
const sections = [
|
|
1450
|
+
{
|
|
1451
|
+
view_model: {
|
|
1452
|
+
primitives: [{
|
|
1453
|
+
title,
|
|
1454
|
+
subtitle,
|
|
1455
|
+
...(image ? { image } : {}),
|
|
1456
|
+
entity_id: String(entityId || username),
|
|
1457
|
+
entity_url: entityUrl,
|
|
1458
|
+
entity_type: 'WEBSITE',
|
|
1459
|
+
action_type: 'OPEN_URL',
|
|
1460
|
+
is_verified: Boolean(isVerified),
|
|
1461
|
+
__typename: 'GenAICompactEntityPrimitive'
|
|
1462
|
+
}],
|
|
1463
|
+
__typename: 'GenAIActionRowLayoutViewModel'
|
|
1464
|
+
}
|
|
1465
|
+
},
|
|
1466
|
+
{
|
|
1467
|
+
view_model: {
|
|
1468
|
+
primitives: [{ type: 'HORIZONTAL_LINE', __typename: 'GenAIDividerPrimitive' }],
|
|
1469
|
+
__typename: 'GenAIVStackLayoutViewModel'
|
|
1470
|
+
}
|
|
1471
|
+
},
|
|
1472
|
+
{
|
|
1473
|
+
view_model: {
|
|
1474
|
+
primitives: [
|
|
1475
|
+
{ __typename: 'GenAISpacerPrimitive' },
|
|
1476
|
+
{
|
|
1477
|
+
text: `# {{social_entity_1}}${resultText}\0{{/social_entity_1}} `,
|
|
1478
|
+
inline_entities: [{
|
|
1479
|
+
key: 'social_entity_1',
|
|
1480
|
+
metadata: {
|
|
1481
|
+
__typename: 'GenAISocialEntityItem',
|
|
1482
|
+
entity_id: username,
|
|
1483
|
+
entity_name: username,
|
|
1484
|
+
entity_full_name: fullName,
|
|
1485
|
+
platform: String(platform || 'GENERIC').toUpperCase(),
|
|
1486
|
+
entity_picture_url: imageUrl,
|
|
1487
|
+
entity_url: entityUrl,
|
|
1488
|
+
entity_type: entityType,
|
|
1489
|
+
is_verified: Boolean(isVerified)
|
|
1490
|
+
}
|
|
1491
|
+
}],
|
|
1492
|
+
__typename: 'GenAIMarkdownTextUXPrimitive'
|
|
1493
|
+
},
|
|
1494
|
+
{ __typename: 'GenAISpacerPrimitive' }
|
|
1495
|
+
],
|
|
1496
|
+
__typename: 'GenAIActionRowLayoutViewModel'
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
];
|
|
1500
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1501
|
+
submessages: [],
|
|
1502
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1503
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ sections })) },
|
|
1504
|
+
contextInfo: { isForwarded: true, forwardOrigin: 4 }
|
|
1505
|
+
});
|
|
1506
|
+
return wrapToBotForwardedMessage(richResponseMessage);
|
|
1507
|
+
};
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
/**
|
|
1511
|
+
* Builds a generic unified-response envelope without reducing its sections to
|
|
1512
|
+
* plain text. This is the extension point for newer WhatsApp primitives that
|
|
1513
|
+
* are present in WAProto but do not yet have a dedicated convenience helper.
|
|
1514
|
+
*/
|
|
1515
|
+
export const prepareUnifiedResponseMessage = ({ sections = [], submessages = [], responseId = randomUUID(), contextInfo } = {}) => {
|
|
1516
|
+
if (!Array.isArray(sections) || sections.length === 0) {
|
|
1517
|
+
throw new Boom('sendUnifiedResponse requires at least one section', { statusCode: 400 });
|
|
1518
|
+
}
|
|
1519
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1520
|
+
submessages,
|
|
1521
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1522
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ response_id: responseId, sections })) },
|
|
1523
|
+
contextInfo: contextInfo || { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1524
|
+
});
|
|
1525
|
+
return wrapToBotForwardedMessage(richResponseMessage);
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
/** Build a protocol-backed AIRich map card with optional numbered annotations. */
|
|
1529
|
+
export const prepareRichMapMessage = ({ text = 'Map location', centerLatitude, centerLongitude, latitudeDelta, longitudeDelta, annotations = [], showInfoList = false, verificationMetadata } = {}) => {
|
|
1530
|
+
if (!Number.isFinite(Number(centerLatitude)) || !Number.isFinite(Number(centerLongitude))) {
|
|
1531
|
+
throw new Boom('prepareRichMapMessage requires centerLatitude and centerLongitude', { statusCode: 400 });
|
|
1532
|
+
}
|
|
1533
|
+
const submessages = [
|
|
1534
|
+
...(text ? [{ messageType: RichSubMessageType.TEXT, messageText: String(text) }] : []),
|
|
1535
|
+
{
|
|
1536
|
+
messageType: RichSubMessageType.MAP,
|
|
1537
|
+
mapMetadata: {
|
|
1538
|
+
centerLatitude: Number(centerLatitude),
|
|
1539
|
+
centerLongitude: Number(centerLongitude),
|
|
1540
|
+
...(latitudeDelta == null ? {} : { latitudeDelta: Number(latitudeDelta) }),
|
|
1541
|
+
...(longitudeDelta == null ? {} : { longitudeDelta: Number(longitudeDelta) }),
|
|
1542
|
+
showInfoList: Boolean(showInfoList),
|
|
1543
|
+
annotations: (Array.isArray(annotations) ? annotations : []).map((annotation, index) => ({
|
|
1544
|
+
annotationNumber: annotation.annotationNumber ?? index + 1,
|
|
1545
|
+
latitude: Number(annotation.latitude),
|
|
1546
|
+
longitude: Number(annotation.longitude),
|
|
1547
|
+
title: String(annotation.title || ''),
|
|
1548
|
+
body: String(annotation.body || '')
|
|
1549
|
+
}))
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
];
|
|
1553
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1554
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1555
|
+
submessages,
|
|
1556
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(toUnified(submessages, randomUUID()))) },
|
|
1557
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1558
|
+
});
|
|
1559
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
/** Build a rich response carrying BotSuggestedPromptMetadata from WAProto. */
|
|
1563
|
+
export const prepareBotPromptSuggestionsMessage = ({ text = '', suggestions = [], selectedPromptIndex, selectedPromptId, verificationMetadata } = {}) => {
|
|
1564
|
+
if (!Array.isArray(suggestions) || suggestions.length === 0) {
|
|
1565
|
+
throw new Boom('prepareBotPromptSuggestionsMessage requires at least one suggestion', { statusCode: 400 });
|
|
1566
|
+
}
|
|
1567
|
+
const envelope = wrapToBotForwardedMessage(proto.AIRichResponseMessage.create({
|
|
1568
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1569
|
+
submessages: [{ messageType: RichSubMessageType.TEXT, messageText: String(text) }],
|
|
1570
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1571
|
+
}), verificationMetadata);
|
|
1572
|
+
envelope.messageContextInfo.botMetadata.suggestedPromptMetadata = {
|
|
1573
|
+
suggestedPrompts: suggestions.map(String),
|
|
1574
|
+
...(selectedPromptIndex == null ? {} : { selectedPromptIndex: Number(selectedPromptIndex) }),
|
|
1575
|
+
...(selectedPromptId == null ? {} : { selectedPromptId: String(selectedPromptId) })
|
|
1576
|
+
};
|
|
1577
|
+
return envelope;
|
|
1578
|
+
};
|
|
1579
|
+
|
|
1580
|
+
/** Build a rich response carrying BotSourcesMetadata for citations/search results. */
|
|
1581
|
+
export const prepareBotSourcesMessage = ({ text = '', sources = [], verificationMetadata } = {}) => {
|
|
1582
|
+
if (!Array.isArray(sources) || sources.length === 0) {
|
|
1583
|
+
throw new Boom('prepareBotSourcesMessage requires at least one source', { statusCode: 400 });
|
|
1584
|
+
}
|
|
1585
|
+
const submessages = [{
|
|
1586
|
+
messageType: RichSubMessageType.TEXT,
|
|
1587
|
+
messageText: String(text || 'Sources')
|
|
1588
|
+
}];
|
|
1589
|
+
const sourceCards = sources.map((source, index) => ({
|
|
1590
|
+
source_type: 'THIRD_PARTY',
|
|
1591
|
+
source_display_name: source.sourceTitle || source.title || '',
|
|
1592
|
+
source_subtitle: source.sourceQuery || source.query || 'Source',
|
|
1593
|
+
source_url: source.sourceProviderUrl || source.url || '',
|
|
1594
|
+
favicon: {
|
|
1595
|
+
url: source.faviconCdnUrl || source.faviconUrl || source.thumbnailCdnUrl || source.thumbnailUrl || '',
|
|
1596
|
+
mime_type: 'image/jpeg',
|
|
1597
|
+
width: 16,
|
|
1598
|
+
height: 16
|
|
1599
|
+
},
|
|
1600
|
+
citation_number: source.citationNumber ?? index + 1
|
|
1601
|
+
})).filter((source) => source.source_url || source.source_display_name);
|
|
1602
|
+
const sections = toUnified(submessages, randomUUID()).sections;
|
|
1603
|
+
if (sourceCards.length) {
|
|
1604
|
+
sections.push({
|
|
1605
|
+
view_model: {
|
|
1606
|
+
primitive: { sources: sourceCards, __typename: 'GenAISearchResultPrimitive' },
|
|
1607
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
}
|
|
1611
|
+
const envelope = wrapToBotForwardedMessage(proto.AIRichResponseMessage.create({
|
|
1612
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1613
|
+
submessages,
|
|
1614
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify({ response_id: randomUUID(), sections })) },
|
|
1615
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1616
|
+
}), verificationMetadata);
|
|
1617
|
+
envelope.messageContextInfo.botMetadata.richResponseSourcesMetadata = {
|
|
1618
|
+
sources: sources.map((source, index) => ({
|
|
1619
|
+
provider: source.provider ?? proto.BotSourcesMetadata.BotSourceItem.SourceProvider.OTHER,
|
|
1620
|
+
thumbnailCdnUrl: source.thumbnailCdnUrl || source.thumbnailUrl || '',
|
|
1621
|
+
sourceProviderUrl: source.sourceProviderUrl || source.url || '',
|
|
1622
|
+
sourceQuery: source.sourceQuery || source.query || '',
|
|
1623
|
+
faviconCdnUrl: source.faviconCdnUrl || source.faviconUrl || '',
|
|
1624
|
+
citationNumber: source.citationNumber ?? index + 1,
|
|
1625
|
+
sourceTitle: source.sourceTitle || source.title || ''
|
|
1626
|
+
}))
|
|
1627
|
+
};
|
|
1628
|
+
return envelope;
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
/** Build an AIRich dynamic image/GIF submessage from WAProto metadata. */
|
|
1632
|
+
export const prepareRichDynamicMediaMessage = ({ url = '', type = 'IMAGE', version = 1, loopCount, verificationMetadata } = {}) => {
|
|
1633
|
+
if (!url || typeof url !== 'string') throw new Boom('prepareRichDynamicMediaMessage requires a URL', { statusCode: 400 });
|
|
1634
|
+
const dynamicTypes = proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType;
|
|
1635
|
+
const normalizedType = String(type).toUpperCase();
|
|
1636
|
+
const dynamicMetadata = {
|
|
1637
|
+
type: normalizedType === 'GIF'
|
|
1638
|
+
? dynamicTypes.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF
|
|
1639
|
+
: dynamicTypes.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE,
|
|
1640
|
+
version: Number(version),
|
|
1641
|
+
url,
|
|
1642
|
+
...(loopCount == null ? {} : { loopCount: Number(loopCount) })
|
|
1643
|
+
};
|
|
1644
|
+
const submessages = [{ messageType: RichSubMessageType.DYNAMIC, dynamicMetadata }];
|
|
1645
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1646
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1647
|
+
submessages,
|
|
1648
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(toUnified(submessages, randomUUID()))) },
|
|
1649
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1650
|
+
});
|
|
1651
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1652
|
+
};
|
|
1653
|
+
|
|
1654
|
+
/** Build a rich response carrying the exact BotPttPromptMetadata transcript field. */
|
|
1655
|
+
export const prepareBotPttTranscriptMessage = ({ text = '', transcript = '', verificationMetadata } = {}) => {
|
|
1656
|
+
if (!transcript || typeof transcript !== 'string') {
|
|
1657
|
+
throw new Boom('prepareBotPttTranscriptMessage requires a transcript', { statusCode: 400 });
|
|
1658
|
+
}
|
|
1659
|
+
const envelope = wrapToBotForwardedMessage(proto.AIRichResponseMessage.create({
|
|
1660
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1661
|
+
submessages: [{ messageType: RichSubMessageType.TEXT, messageText: String(text || transcript) }],
|
|
1662
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1663
|
+
}), verificationMetadata);
|
|
1664
|
+
envelope.messageContextInfo.botMetadata.pttPromptMetadata = { transcript };
|
|
1665
|
+
return envelope;
|
|
1666
|
+
};
|
|
1667
|
+
|
|
1668
|
+
const buildFoaHtmlSection = (html, trustedSources = []) => ({
|
|
1669
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1670
|
+
view_model: {
|
|
1671
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1672
|
+
primitive: {
|
|
1673
|
+
__typename: 'FOAHtmlPrimitiveDemoDONOTUSE',
|
|
1674
|
+
trusted_sources: Array.isArray(trustedSources) ? trustedSources : [],
|
|
1675
|
+
payload: String(html ?? '').trim()
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
});
|
|
1679
|
+
|
|
1680
|
+
const buildRichMediaSection = (media = {}) => {
|
|
1681
|
+
const item = typeof media === 'string' ? { url: media } : media;
|
|
1682
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
1683
|
+
throw new Boom('rich media items must be objects or URLs', { statusCode: 400 });
|
|
1684
|
+
}
|
|
1685
|
+
const type = String(item.type || (item.video || item.videoUrl || item.reelsUrl ? 'video' : 'image')).toLowerCase();
|
|
1686
|
+
if (type === 'video') {
|
|
1687
|
+
const url = item.url || item.videoUrl || item.reelsUrl || item.reels_url || '';
|
|
1688
|
+
if (!url) throw new Boom('video media items require a URL', { statusCode: 400 });
|
|
1689
|
+
const configuredProgressiveUrls = item.progressiveUrls || item.progressive_urls;
|
|
1690
|
+
const progressiveUrls = Array.isArray(configuredProgressiveUrls) && configuredProgressiveUrls.length
|
|
1691
|
+
? configuredProgressiveUrls
|
|
1692
|
+
: [String(url)];
|
|
1693
|
+
const configuredDashManifests = item.dashManifests ?? item.dash_manifests;
|
|
1694
|
+
if (configuredDashManifests != null && !Array.isArray(configuredDashManifests)) {
|
|
1695
|
+
throw new Boom('dashManifests must be an array', { statusCode: 400 });
|
|
1696
|
+
}
|
|
1697
|
+
return {
|
|
1698
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1699
|
+
view_model: {
|
|
1700
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1701
|
+
primitive: {
|
|
1702
|
+
reels_url: String(url),
|
|
1703
|
+
reels_title: item.title,
|
|
1704
|
+
thumbnail_url: item.thumbnailUrl || item.thumbnail_url || item.thumbnail,
|
|
1705
|
+
creator: item.creator,
|
|
1706
|
+
avatar_url: item.avatarUrl || item.avatar_url,
|
|
1707
|
+
source_app: item.sourceApp || item.source_app,
|
|
1708
|
+
video_delivery_response: {
|
|
1709
|
+
progressive_urls: progressiveUrls.map(value => ({ progressive_url: value, __typename: 'GenAIProgressiveUrlResponse' })),
|
|
1710
|
+
dash_manifests: (configuredDashManifests || []).map(value => ({ manifest_xml: value, __typename: 'GenAIDashManifestResponse' })),
|
|
1711
|
+
__typename: 'GenAIVideoDeliveryResponse'
|
|
1712
|
+
},
|
|
1713
|
+
...(item.mimeType || item.mime_type ? { mime_type: item.mimeType || item.mime_type } : {}),
|
|
1714
|
+
...(item.duration == null ? {} : { duration: Number(item.duration) }),
|
|
1715
|
+
__typename: 'GenAIVideoPrimitive'
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
if (type !== 'image' && type !== 'photo') {
|
|
1721
|
+
throw new Boom(`unsupported rich media type: ${type}`, { statusCode: 400 });
|
|
1722
|
+
}
|
|
1723
|
+
const url = item.url || item.imageUrl || item.image_url || '';
|
|
1724
|
+
if (!url) throw new Boom('image media items require a URL', { statusCode: 400 });
|
|
1725
|
+
return {
|
|
1726
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1727
|
+
view_model: {
|
|
1728
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1729
|
+
primitive: buildRichImagePrimitive({ ...item, url })
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
};
|
|
1733
|
+
|
|
1734
|
+
/** Build a tabbed embedded screen containing native image/video primitives and optional HTML. */
|
|
1735
|
+
export const prepareRichMediaMessage = (options = {}) => {
|
|
1736
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) {
|
|
1737
|
+
throw new Boom('prepareRichMediaMessage options must be an object', { statusCode: 400 });
|
|
1738
|
+
}
|
|
1739
|
+
const { title = 'Media', tabHeader = 'Media', media, tabs = [], verificationMetadata } = options;
|
|
1740
|
+
const tabItems = Array.isArray(tabs) && tabs.length ? tabs : [{ id: 'tab_0', tab_header: tabHeader, media }];
|
|
1741
|
+
const embeddedTabs = tabItems.map((tab, index) => {
|
|
1742
|
+
if (!tab || typeof tab !== 'object' || Array.isArray(tab)) {
|
|
1743
|
+
throw new Boom(`rich media tabs[${index}] must be an object`, { statusCode: 400 });
|
|
1744
|
+
}
|
|
1745
|
+
const sections = Array.isArray(tab.sections) ? [...tab.sections] : [];
|
|
1746
|
+
const tabMedia = tab.media == null ? [] : (Array.isArray(tab.media) ? tab.media : [tab.media]);
|
|
1747
|
+
const mediaSections = tabMedia.map(buildRichMediaSection);
|
|
1748
|
+
if (mediaSections.length > 1) {
|
|
1749
|
+
sections.push({
|
|
1750
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1751
|
+
view_model: {
|
|
1752
|
+
__typename: 'GenAIHScrollLayoutViewModel',
|
|
1753
|
+
primitives: mediaSections.map(section => section.view_model.primitive)
|
|
1754
|
+
}
|
|
1755
|
+
});
|
|
1756
|
+
} else {
|
|
1757
|
+
sections.push(...mediaSections);
|
|
1758
|
+
}
|
|
1759
|
+
if (tab.html != null) sections.push(buildFoaHtmlSection(tab.html, tab.trustedSources || options.trustedSources || []));
|
|
1760
|
+
if (!sections.length) throw new Boom(`rich media tabs[${index}] requires media, html, or sections`, { statusCode: 400 });
|
|
1761
|
+
return {
|
|
1762
|
+
id: String(tab.id ?? `tab_${index}`),
|
|
1763
|
+
tab_header: String(tab.tab_header ?? tab.tabHeader ?? tab.title ?? `Media ${index + 1}`),
|
|
1764
|
+
sections,
|
|
1765
|
+
step_entries: Array.isArray(tab.step_entries) ? tab.step_entries : []
|
|
1766
|
+
};
|
|
1767
|
+
});
|
|
1768
|
+
const embeddedScreen = { title: String(title), content: [{ __typename: 'FOAIDNixelButtonSheets', tabs: embeddedTabs }] };
|
|
1769
|
+
const unified = {
|
|
1770
|
+
response_id: randomUUID(),
|
|
1771
|
+
sections: [{ view_model: { primitive: { text: `> ${title}`, __typename: 'GenAIMarkdownTextUXPrimitive' }, __typename: 'GenAISingleLayoutViewModel' } }],
|
|
1772
|
+
embedded_screens: [embeddedScreen]
|
|
1773
|
+
};
|
|
1774
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
1775
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
1776
|
+
submessages: [{ messageType: RichSubMessageType.TEXT, messageText: `> ${title}` }],
|
|
1777
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
1778
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
1779
|
+
});
|
|
1780
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
1781
|
+
};
|
|
1782
|
+
|
|
1783
|
+
const buildRichHtmlScreen = (options = {}) => {
|
|
1784
|
+
const {
|
|
1785
|
+
html = '',
|
|
1786
|
+
trustedSources = [],
|
|
1787
|
+
url = '',
|
|
1788
|
+
title = 'Preview',
|
|
1789
|
+
tabHeader = 'HTML',
|
|
1790
|
+
tabs
|
|
1791
|
+
} = options;
|
|
1792
|
+
const tabItems = Array.isArray(tabs) && tabs.length
|
|
1793
|
+
? tabs
|
|
1794
|
+
: [{ id: 'tab_0', tab_header: tabHeader, html }];
|
|
1795
|
+
const embeddedTabs = tabItems.map((tab, index) => ({
|
|
1796
|
+
id: tab.id || `tab_${index}`,
|
|
1797
|
+
tab_header: tab.tab_header || tab.title || `HTML ${index + 1}`,
|
|
1798
|
+
sections: [{
|
|
1799
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1800
|
+
view_model: {
|
|
1801
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
1802
|
+
primitive: {
|
|
1803
|
+
__typename: 'GenAIaeacdsnwHtmlPrimitive',
|
|
1804
|
+
payload: String(tab.html ?? tab.payload ?? html).trim(),
|
|
1805
|
+
url: tab.url || url,
|
|
1806
|
+
trusted_sources: tab.trustedSources || trustedSources
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
}],
|
|
1810
|
+
step_entries: []
|
|
1811
|
+
}));
|
|
1812
|
+
return {
|
|
1813
|
+
title,
|
|
1814
|
+
embeddedScreen: {
|
|
1815
|
+
title,
|
|
1816
|
+
content: [{
|
|
1817
|
+
__typename: 'FOAIDNixelButtonSheets',
|
|
1818
|
+
tabs: embeddedTabs
|
|
1819
|
+
}]
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
};
|
|
1823
|
+
|
|
1824
|
+
const normalizeEmbeddedScreenInput = (screen) => {
|
|
1825
|
+
if (!screen || typeof screen !== 'object' || Array.isArray(screen)) {
|
|
1826
|
+
throw new Boom('embeddedScreen must be an object', { statusCode: 400 });
|
|
1827
|
+
}
|
|
1828
|
+
if (Object.hasOwn(screen, 'content')) {
|
|
1829
|
+
if (!Array.isArray(screen.content)) {
|
|
1830
|
+
throw new Boom('embeddedScreen.content must be an array', { statusCode: 400 });
|
|
1831
|
+
}
|
|
1832
|
+
return screen;
|
|
1833
|
+
}
|
|
1834
|
+
if (!Array.isArray(screen.tabs)) {
|
|
1835
|
+
throw new Boom('embeddedScreen requires a tabs array or a prebuilt content array', { statusCode: 400 });
|
|
1836
|
+
}
|
|
1837
|
+
const tabs = screen.tabs.map((tab, index) => {
|
|
1838
|
+
if (!tab || typeof tab !== 'object' || Array.isArray(tab) || !Array.isArray(tab.sections)) {
|
|
1839
|
+
throw new Boom(`embeddedScreen.tabs[${index}] requires a sections array`, { statusCode: 400 });
|
|
1840
|
+
}
|
|
1841
|
+
if (tab.sections.some(section => !section || typeof section !== 'object' || Array.isArray(section))) {
|
|
1842
|
+
throw new Boom(`embeddedScreen.tabs[${index}].sections must contain section objects`, { statusCode: 400 });
|
|
1843
|
+
}
|
|
1844
|
+
const { media, ...tabFields } = tab;
|
|
1845
|
+
const mediaItems = media == null ? [] : (Array.isArray(media) ? media : [media]);
|
|
1846
|
+
const mediaSections = mediaItems.map(buildRichMediaSection);
|
|
1847
|
+
const sections = [...tab.sections];
|
|
1848
|
+
if (mediaSections.length > 1) {
|
|
1849
|
+
sections.push({
|
|
1850
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
1851
|
+
view_model: {
|
|
1852
|
+
__typename: 'GenAIHScrollLayoutViewModel',
|
|
1853
|
+
primitives: mediaSections.map(section => section.view_model.primitive)
|
|
1854
|
+
}
|
|
1855
|
+
});
|
|
1856
|
+
}
|
|
1857
|
+
else {
|
|
1858
|
+
sections.push(...mediaSections);
|
|
1859
|
+
}
|
|
1860
|
+
return {
|
|
1861
|
+
...tabFields,
|
|
1862
|
+
id: String(tab.id ?? `tab_${index}`),
|
|
1863
|
+
tab_header: String(tab.tab_header ?? tab.title ?? `Tab ${index + 1}`),
|
|
1864
|
+
sections,
|
|
1865
|
+
step_entries: Array.isArray(tab.step_entries) ? tab.step_entries : []
|
|
1866
|
+
};
|
|
1867
|
+
});
|
|
1868
|
+
const { tabs: _tabs, ...metadata } = screen;
|
|
1869
|
+
return {
|
|
1870
|
+
...metadata,
|
|
1871
|
+
title: String(screen.title ?? 'Screen'),
|
|
1872
|
+
content: [{ __typename: 'FOAIDNixelButtonSheets', tabs }]
|
|
1873
|
+
};
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
/**
|
|
1877
|
+
* Normalize a standalone themed message into the existing AIRich composer.
|
|
1878
|
+
* This intentionally creates no interactiveMessage, buttons, or menu: its
|
|
1879
|
+
* title/body are ordinary unified-response text sections, alongside any
|
|
1880
|
+
* optional rich media fields the caller supplies.
|
|
1881
|
+
*/
|
|
1882
|
+
export const normalizeUnifiedThemedMessageContent = (content = {}) => {
|
|
1883
|
+
if (!content || typeof content !== 'object' || Array.isArray(content)) {
|
|
1884
|
+
throw new Boom('sendUnifiedThemedMessage content must be an object', { statusCode: 400 });
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
const {
|
|
1888
|
+
title,
|
|
1889
|
+
subtitle,
|
|
1890
|
+
text,
|
|
1891
|
+
body,
|
|
1892
|
+
footer,
|
|
1893
|
+
headerText: suppliedHeaderText,
|
|
1894
|
+
contentText: suppliedContentText,
|
|
1895
|
+
footerText: suppliedFooterText,
|
|
1896
|
+
...richContent
|
|
1897
|
+
} = content;
|
|
1898
|
+
const normalizedTitle = title === undefined || title === null ? '' : String(title).trim();
|
|
1899
|
+
const normalizedSubtitle = subtitle === undefined || subtitle === null ? '' : String(subtitle).trim();
|
|
1900
|
+
const headerText = normalizedTitle
|
|
1901
|
+
? `# ${normalizedTitle}${normalizedSubtitle ? `\n\n• ${normalizedSubtitle}` : ''}`
|
|
1902
|
+
: normalizedSubtitle || suppliedHeaderText;
|
|
1903
|
+
const bodyText = text ?? body ?? suppliedContentText;
|
|
1904
|
+
const footerText = footer ?? suppliedFooterText;
|
|
1905
|
+
|
|
1906
|
+
return {
|
|
1907
|
+
...richContent,
|
|
1908
|
+
...(headerText !== undefined ? { headerText: String(headerText) } : {}),
|
|
1909
|
+
...(bodyText !== undefined ? { contentText: String(bodyText) } : {}),
|
|
1910
|
+
...(footerText !== undefined ? { footerText: String(footerText) } : {})
|
|
1911
|
+
};
|
|
1912
|
+
};
|
|
1913
|
+
|
|
1914
|
+
const prepareRichResponseMessageFixedOrder = (content) => {
|
|
1915
|
+
const { alignment, code, compatibility, contentText, disclaimerText, footerText, headerText, html, richHtml, trustedSources, imageText, image, images, inlineImage, inlineVideo, items, language, latex, links, noDonation, noHeading, posts, products, reels, sources: sourceInputs, suggested, richResponse, table, tapLinkUrl, title, verificationMetadata, sections: rawSections, richSections, copyButton, copyToClipboard, copyText, copyLabel, richText, quote, richImage, richLinks, richMap, map, dynamicMedia, richDynamicMedia, socialEntity, socialProfile, richMenu, airichCommandMenu, unifiedResponse, gridImages, verticalAlbum, videoGrid, richGeneration, richLabel, suggestedPrompt, botSources, botPttTranscript } = content;
|
|
1916
|
+
let submessages = [];
|
|
1917
|
+
const extraSections = [];
|
|
1918
|
+
if (Array.isArray(richResponse)) {
|
|
1919
|
+
submessages = richResponse.map((submessage) => {
|
|
1920
|
+
if (submessage.text) {
|
|
1921
|
+
return {
|
|
1922
|
+
messageType: RichSubMessageType.TEXT,
|
|
1923
|
+
messageText: submessage.text,
|
|
1924
|
+
inlineEntities: submessage.inlineEntities
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
else if (submessage.code) {
|
|
1928
|
+
return {
|
|
1929
|
+
messageType: RichSubMessageType.CODE,
|
|
1930
|
+
codeMetadata: {
|
|
1931
|
+
codeLanguage: submessage.language,
|
|
1932
|
+
codeBlocks: submessage.code
|
|
1933
|
+
}
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
else if (submessage.items) {
|
|
1937
|
+
return {
|
|
1938
|
+
messageType: RichSubMessageType.CONTENT_ITEMS,
|
|
1939
|
+
contentItemsMetadata: {
|
|
1940
|
+
itemsMetadata: submessage.items,
|
|
1941
|
+
contentType: proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
|
|
1942
|
+
}
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
else if (submessage.inlineImage) {
|
|
1946
|
+
return {
|
|
1947
|
+
messageType: RichSubMessageType.INLINE_IMAGE,
|
|
1948
|
+
imageMetadata: {
|
|
1949
|
+
imageUrl: submessage.inlineImage,
|
|
1950
|
+
imageText: submessage.imageText,
|
|
1951
|
+
alignment: submessage.alignment,
|
|
1952
|
+
tapLinkUrl: submessage.tapLinkUrl
|
|
1953
|
+
}
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
else if (submessage.inlineVideo) {
|
|
1957
|
+
return {
|
|
1958
|
+
messageType: RichSubMessageType.TEXT,
|
|
1959
|
+
messageText: 'INLINE_VIDEO'
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
else if (submessage.latex) {
|
|
1963
|
+
return {
|
|
1964
|
+
messageType: RichSubMessageType.LATEX,
|
|
1965
|
+
latexMetadata: {
|
|
1966
|
+
text: submessage.text,
|
|
1967
|
+
expressions: submessage.latex
|
|
1968
|
+
}
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1971
|
+
else if (submessage.posts) {
|
|
1972
|
+
return {
|
|
1973
|
+
messageType: RichSubMessageType.TEXT,
|
|
1974
|
+
messageText: 'POSTS'
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
else if (submessage.products) {
|
|
1978
|
+
return {
|
|
1979
|
+
messageType: RichSubMessageType.TEXT,
|
|
1980
|
+
messageText: 'PRODUCTS'
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
else if (submessage.suggested) {
|
|
1984
|
+
return {
|
|
1985
|
+
messageType: RichSubMessageType.TEXT,
|
|
1986
|
+
messageText: 'SUGGESTED_PROMPT'
|
|
1987
|
+
};
|
|
1988
|
+
}
|
|
1989
|
+
else if (submessage.table) {
|
|
1990
|
+
return {
|
|
1991
|
+
messageType: RichSubMessageType.TABLE,
|
|
1992
|
+
tableMetadata: {
|
|
1993
|
+
title: submessage.title,
|
|
1994
|
+
rows: submessage.table
|
|
1995
|
+
}
|
|
1996
|
+
};
|
|
1997
|
+
}
|
|
1998
|
+
return submessage;
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
else {
|
|
2002
|
+
if (headerText) {
|
|
2003
|
+
submessages.push({
|
|
2004
|
+
messageType: RichSubMessageType.TEXT,
|
|
2005
|
+
messageText: headerText
|
|
2006
|
+
});
|
|
2007
|
+
}
|
|
2008
|
+
if (contentText) {
|
|
2009
|
+
submessages.push({
|
|
2010
|
+
messageType: RichSubMessageType.TEXT,
|
|
2011
|
+
messageText: contentText
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
if (code) {
|
|
2015
|
+
language ||= 'javascript';
|
|
2016
|
+
submessages.push({
|
|
2017
|
+
messageType: RichSubMessageType.CODE,
|
|
2018
|
+
codeMetadata: {
|
|
2019
|
+
codeLanguage: language,
|
|
2020
|
+
codeBlocks: tokenizeCode(code, language)
|
|
2021
|
+
}
|
|
2022
|
+
});
|
|
2023
|
+
}
|
|
2024
|
+
const reelItems = Array.isArray(reels) ? reels.map((reel) => ({ reelItem: {
|
|
2025
|
+
title: reel?.title || reel?.reels_title || '',
|
|
2026
|
+
creator: reel?.creator || '',
|
|
2027
|
+
videoUrl: reel?.videoUrl || reel?.reels_url || reel?.url || '',
|
|
2028
|
+
thumbnailUrl: reel?.thumbnailUrl || reel?.thumbnail_url || '',
|
|
2029
|
+
profileIconUrl: reel?.profileIconUrl || reel?.avatar_url || '',
|
|
2030
|
+
likesCount: reel?.likesCount ?? reel?.likes_count ?? 0,
|
|
2031
|
+
sharesCount: reel?.sharesCount ?? reel?.shares_count ?? 0,
|
|
2032
|
+
viewCount: reel?.viewCount ?? reel?.view_count ?? 0,
|
|
2033
|
+
reelSource: reel?.reelSource || reel?.reel_source || 'IG',
|
|
2034
|
+
isVerified: !!(reel?.isVerified ?? reel?.is_verified)
|
|
2035
|
+
} })) : [];
|
|
2036
|
+
const resolvedItems = [
|
|
2037
|
+
...(Array.isArray(items) ? items : []),
|
|
2038
|
+
...reelItems
|
|
2039
|
+
];
|
|
2040
|
+
if (resolvedItems?.length) {
|
|
2041
|
+
submessages.push({
|
|
2042
|
+
messageType: RichSubMessageType.CONTENT_ITEMS,
|
|
2043
|
+
contentItemsMetadata: {
|
|
2044
|
+
itemsMetadata: resolvedItems,
|
|
2045
|
+
contentType: proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
|
|
2046
|
+
}
|
|
2047
|
+
});
|
|
2048
|
+
}
|
|
2049
|
+
if (inlineImage) {
|
|
2050
|
+
const image = typeof inlineImage === 'string' ? { url: inlineImage } : (inlineImage || {});
|
|
2051
|
+
submessages.push({
|
|
2052
|
+
messageType: RichSubMessageType.INLINE_IMAGE,
|
|
2053
|
+
imageMetadata: {
|
|
2054
|
+
...image,
|
|
2055
|
+
imageUrl: image.url || image.imageUrl || image.image || '',
|
|
2056
|
+
imageText,
|
|
2057
|
+
alignment,
|
|
2058
|
+
tapLinkUrl,
|
|
2059
|
+
mimeType: image.mimeType || image.mime_type,
|
|
2060
|
+
width: image.width,
|
|
2061
|
+
height: image.height,
|
|
2062
|
+
fullWidth: image.fullWidth || image.full_width,
|
|
2063
|
+
fullHeight: image.fullHeight || image.full_height
|
|
2064
|
+
}
|
|
2065
|
+
});
|
|
2066
|
+
}
|
|
2067
|
+
if (inlineVideo) {
|
|
2068
|
+
const video = typeof inlineVideo === 'string' ? { url: inlineVideo } : inlineVideo;
|
|
2069
|
+
extraSections.push({
|
|
2070
|
+
view_model: {
|
|
2071
|
+
primitive: buildImaginePrimitive({
|
|
2072
|
+
mediaType: 'video',
|
|
2073
|
+
url: video?.url || video?.videoUrl || video?.video_url || '',
|
|
2074
|
+
mimeType: video?.mimeType || video?.mime_type || video?.mimetype || 'video/mp4',
|
|
2075
|
+
fileLength: video?.fileLength ?? video?.file_length ?? video?.filesize ?? 0,
|
|
2076
|
+
duration: video?.duration ?? 0,
|
|
2077
|
+
thumbnail: video?.thumbnail || video?.thumbnailUrl || video?.thumbnail_url,
|
|
2078
|
+
status: video?.status || 'READY'
|
|
2079
|
+
}),
|
|
2080
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
2081
|
+
}
|
|
2082
|
+
});
|
|
2083
|
+
}
|
|
2084
|
+
if (latex) {
|
|
2085
|
+
submessages.push({
|
|
2086
|
+
messageType: RichSubMessageType.LATEX,
|
|
2087
|
+
latexMetadata: {
|
|
2088
|
+
text: contentText || '',
|
|
2089
|
+
expressions: latex
|
|
2090
|
+
}
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
const defaultDonationLink = {
|
|
2094
|
+
text: '',
|
|
2095
|
+
url: DONATE_URL,
|
|
2096
|
+
title: 'X4R1S3',
|
|
2097
|
+
displayName: 'X4R1S3 bot'
|
|
2098
|
+
};
|
|
2099
|
+
const rawSources = Array.isArray(sourceInputs) ? sourceInputs : [];
|
|
2100
|
+
// Existing `sources: [{ url, displayName, subtitle }]` callers use
|
|
2101
|
+
// citation entities. The serialized AIRich addSource format is the
|
|
2102
|
+
// distinct tuple form: `[[faviconUrl, sourceUrl, displayText], ...]`.
|
|
2103
|
+
const sourceTuples = rawSources.length > 0 && rawSources.every((source) => Array.isArray(source));
|
|
2104
|
+
if (sourceTuples) {
|
|
2105
|
+
const sourceCards = rawSources.map((source) => {
|
|
2106
|
+
const item = Array.isArray(source)
|
|
2107
|
+
? { icon: source[0], url: source[1], text: source[2] }
|
|
2108
|
+
: source;
|
|
2109
|
+
const sourceUrl = item.url || item.sourceUrl || item.source_url || '';
|
|
2110
|
+
return {
|
|
2111
|
+
source_type: 'THIRD_PARTY',
|
|
2112
|
+
source_display_name: item.text || item.displayName || item.sourceDisplayName || '',
|
|
2113
|
+
source_subtitle: item.subtitle || 'AI',
|
|
2114
|
+
source_url: sourceUrl,
|
|
2115
|
+
favicon: {
|
|
2116
|
+
url: item.icon || item.iconUrl || item.favicon || '',
|
|
2117
|
+
mime_type: item.mimeType || 'image/jpeg',
|
|
2118
|
+
width: item.width || 16,
|
|
2119
|
+
height: item.height || 16
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
}).filter((source) => source.source_url || source.source_display_name);
|
|
2123
|
+
if (sourceCards.length) {
|
|
2124
|
+
extraSections.push({
|
|
2125
|
+
view_model: {
|
|
2126
|
+
primitive: { sources: sourceCards, __typename: 'GenAISearchResultPrimitive' },
|
|
2127
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
2128
|
+
}
|
|
2129
|
+
});
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
const sourceLinks = (sourceTuples ? [] : (sourceInputs || links || [])).map((linkField) => {
|
|
2133
|
+
if (typeof linkField === 'string') return { text: '', url: linkField, displayName: linkField };
|
|
2134
|
+
return { text: linkField?.text || linkField?.displayName || linkField?.title || '', ...linkField };
|
|
2135
|
+
});
|
|
2136
|
+
const resolvedLinks = noDonation ? sourceLinks : [...sourceLinks, defaultDonationLink];
|
|
2137
|
+
if (resolvedLinks) {
|
|
2138
|
+
resolvedLinks.forEach((linkField, index) => {
|
|
2139
|
+
const prefix = 'SS_' + index;
|
|
2140
|
+
const url = linkField.url || DONATE_URL;
|
|
2141
|
+
const sources = linkField.sources?.map((sourceField) => ({
|
|
2142
|
+
source_type: 'THIRD_PARTY',
|
|
2143
|
+
source_display_name: sourceField.displayName || 'pair bot',
|
|
2144
|
+
source_subtitle: sourceField.subtitle || 'X4R1S3',
|
|
2145
|
+
source_url: sourceField.url || url
|
|
2146
|
+
}));
|
|
2147
|
+
submessages.push({
|
|
2148
|
+
messageType: RichSubMessageType.TEXT,
|
|
2149
|
+
messageText: String(linkField.text || '') + ` {{${prefix}}}¹{{/${prefix}}} `,
|
|
2150
|
+
inlineEntities: [{
|
|
2151
|
+
key: prefix,
|
|
2152
|
+
metadata: {
|
|
2153
|
+
reference_id: index + 1,
|
|
2154
|
+
reference_url: url,
|
|
2155
|
+
reference_title: linkField.title || 'Get your own bot',
|
|
2156
|
+
reference_display_name: linkField.displayName || 'pair',
|
|
2157
|
+
sources: sources || [],
|
|
2158
|
+
__typename: 'GenAISearchCitationItem'
|
|
2159
|
+
}
|
|
2160
|
+
}]
|
|
2161
|
+
});
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
if (posts) {
|
|
2165
|
+
const postItems = (Array.isArray(posts) ? posts : [posts]).map((post) => ({
|
|
2166
|
+
title: post?.title || '',
|
|
2167
|
+
subtitle: post?.subtitle || '',
|
|
2168
|
+
username: post?.username || post?.user || '',
|
|
2169
|
+
profile_picture_url: post?.profile_picture_url || post?.profile || post?.profile_url || '',
|
|
2170
|
+
is_verified: !!(post?.is_verified ?? post?.verified),
|
|
2171
|
+
thumbnail_url: post?.thumbnail_url || post?.thumbnail || '',
|
|
2172
|
+
post_caption: post?.post_caption || post?.caption || '',
|
|
2173
|
+
likes_count: post?.likes_count ?? post?.like ?? 0,
|
|
2174
|
+
comments_count: post?.comments_count ?? post?.comment ?? 0,
|
|
2175
|
+
shares_count: post?.shares_count ?? post?.share ?? 0,
|
|
2176
|
+
post_url: post?.post_url || post?.url || '',
|
|
2177
|
+
post_deeplink: post?.post_deeplink || post?.deeplink || '',
|
|
2178
|
+
source_app: post?.source_app || post?.source || '',
|
|
2179
|
+
footer_label: post?.footer_label || post?.footer || '',
|
|
2180
|
+
footer_icon: post?.footer_icon || post?.icon || '',
|
|
2181
|
+
is_carousel: post?.is_carousel ?? true,
|
|
2182
|
+
orientation: post?.orientation || 'LANDSCAPE',
|
|
2183
|
+
post_type: post?.post_type || 'VIDEO',
|
|
2184
|
+
__typename: 'GenAIPostPrimitive'
|
|
2185
|
+
}));
|
|
2186
|
+
if (postItems.length) extraSections.push({ view_model: { primitives: postItems, __typename: 'GenAIHScrollLayoutViewModel' } });
|
|
2187
|
+
}
|
|
2188
|
+
if (products) {
|
|
2189
|
+
const productItems = (Array.isArray(products) ? products : [products]).map((product) => ({
|
|
2190
|
+
title: product?.title || '',
|
|
2191
|
+
brand: product?.brand || '',
|
|
2192
|
+
price: product?.price || '',
|
|
2193
|
+
sale_price: product?.sale_price || product?.salePrice || '',
|
|
2194
|
+
product_url: product?.product_url || product?.url || '',
|
|
2195
|
+
image: { url: product?.image?.url || product?.image || '' },
|
|
2196
|
+
additional_images: [{ url: product?.icon_url || product?.icon || '' }],
|
|
2197
|
+
__typename: 'GenAIProductItemCardPrimitive'
|
|
2198
|
+
}));
|
|
2199
|
+
if (productItems.length) {
|
|
2200
|
+
extraSections.push({
|
|
2201
|
+
view_model: Array.isArray(products)
|
|
2202
|
+
? { primitives: productItems, __typename: 'GenAIHScrollLayoutViewModel' }
|
|
2203
|
+
: { primitive: productItems[0], __typename: 'GenAISingleLayoutViewModel' }
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
if (suggested) {
|
|
2208
|
+
submessages.push({
|
|
2209
|
+
messageType: RichSubMessageType.TEXT,
|
|
2210
|
+
messageText: 'SUGGESTED_PROMPT'
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
if (Array.isArray(table)) {
|
|
2214
|
+
submessages.push({
|
|
2215
|
+
messageType: RichSubMessageType.TABLE,
|
|
2216
|
+
tableMetadata: {
|
|
2217
|
+
title,
|
|
2218
|
+
rows: table.map((items, index) => ({
|
|
2219
|
+
isHeading: !noHeading && index == 0,
|
|
2220
|
+
items: Array.isArray(items) ? items.map(String) : [String(items)]
|
|
2221
|
+
}))
|
|
2222
|
+
}
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
if (footerText) {
|
|
2226
|
+
submessages.push({
|
|
2227
|
+
messageType: RichSubMessageType.TEXT,
|
|
2228
|
+
messageText: footerText
|
|
2229
|
+
});
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
const htmlIsTabbedConfig = html && typeof html === 'object' && Array.isArray(html.tabs);
|
|
2233
|
+
const simpleHtmlPayload = htmlIsTabbedConfig ? '' : (typeof html === 'string' ? html : (html?.html ?? html?.payload ?? ''));
|
|
2234
|
+
const htmlPayload = simpleHtmlPayload;
|
|
2235
|
+
const htmlTrustedSources = Array.isArray(html?.trustedSources) ? html.trustedSources : trustedSources;
|
|
2236
|
+
if (String(htmlPayload).trim()) {
|
|
2237
|
+
extraSections.push(buildFoaHtmlSection(htmlPayload, htmlTrustedSources));
|
|
2238
|
+
}
|
|
2239
|
+
const richHtmlOptions = richHtml ?? (htmlIsTabbedConfig ? html : null);
|
|
2240
|
+
const richHtmlConfig = typeof richHtmlOptions === 'string'
|
|
2241
|
+
? { html: richHtmlOptions, trustedSources }
|
|
2242
|
+
: (richHtmlOptions && typeof richHtmlOptions === 'object'
|
|
2243
|
+
? { ...richHtmlOptions, trustedSources: richHtmlOptions.trustedSources ?? trustedSources }
|
|
2244
|
+
: null);
|
|
2245
|
+
const hasRichHtmlContent = !!(richHtmlConfig && (
|
|
2246
|
+
String(richHtmlConfig.html || '').trim() ||
|
|
2247
|
+
(Array.isArray(richHtmlConfig.tabs) && richHtmlConfig.tabs.some(tab => String(tab?.html ?? tab?.payload ?? '').trim()))
|
|
2248
|
+
));
|
|
2249
|
+
let richHtmlScreen;
|
|
2250
|
+
if (hasRichHtmlContent) {
|
|
2251
|
+
richHtmlScreen = buildRichHtmlScreen(richHtmlConfig);
|
|
2252
|
+
submessages.unshift({
|
|
2253
|
+
messageType: RichSubMessageType.TEXT,
|
|
2254
|
+
messageText: `> ${richHtmlScreen.title}`
|
|
2255
|
+
});
|
|
2256
|
+
}
|
|
2257
|
+
const uuid = randomUUID();
|
|
2258
|
+
const unified = toUnified(submessages, uuid);
|
|
2259
|
+
unified.sections = [...unified.sections.filter(Boolean), ...extraSections];
|
|
2260
|
+
if (compatibility === 'new-rich-media' || compatibility === 'both') {
|
|
2261
|
+
const compatible = prepareNewRichMediaCompatibility({ reels, images: images || (inlineImage ? [inlineImage] : image ? [image] : []), posts });
|
|
2262
|
+
unified.sections.push(...compatible.sections);
|
|
2263
|
+
unified.new_rich_media = {
|
|
2264
|
+
compatibility: compatible.compatibility,
|
|
2265
|
+
reels: compatible.reels,
|
|
2266
|
+
images: compatible.images,
|
|
2267
|
+
posts: compatible.posts
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
if (richHtmlScreen) unified.embedded_screens = [richHtmlScreen.embeddedScreen];
|
|
2271
|
+
|
|
2272
|
+
// Compose the remaining AIRich convenience formats as sections. These
|
|
2273
|
+
// aliases intentionally mirror the standalone send* helpers, allowing a
|
|
2274
|
+
// caller to mix them with text, HTML, tables, media, and citations in one
|
|
2275
|
+
// X4R1S3 message. Raw sections remain available as the forward-compatible
|
|
2276
|
+
// escape hatch for new WhatsApp primitives.
|
|
2277
|
+
const composed = { sections: unified.sections, embedded_screens: unified.embedded_screens, submessages, botMetadata: {} };
|
|
2278
|
+
const append = (prepared) => appendPreparedRichContent(composed, prepared);
|
|
2279
|
+
if (copyButton || copyToClipboard || copyText) append(prepareCopyToClipboardMessage(copyButton || copyToClipboard || { text: copyText, label: copyLabel }));
|
|
2280
|
+
if (richText) append(prepareRichTextMessage(typeof richText === 'string' ? { text: richText } : richText));
|
|
2281
|
+
if (quote) append(prepareRichQuoteMessage(typeof quote === 'string' ? { text: quote } : quote));
|
|
2282
|
+
if (richImage) append(prepareRichImageMessage(typeof richImage === 'string' ? { url: richImage } : richImage));
|
|
2283
|
+
if (richLinks) append(prepareRichLinkMessage(Array.isArray(richLinks) ? { links: richLinks } : richLinks));
|
|
2284
|
+
if (richMap || map) append(prepareRichMapMessage(richMap || map));
|
|
2285
|
+
if (dynamicMedia || richDynamicMedia) append(prepareRichDynamicMediaMessage(dynamicMedia || richDynamicMedia));
|
|
2286
|
+
if (socialEntity) append(prepareSocialEntityMessage(socialEntity));
|
|
2287
|
+
if (socialProfile) append(prepareSocialProfileMessage(socialProfile));
|
|
2288
|
+
if (richMenu) append(prepareRichMenuMessage(richMenu));
|
|
2289
|
+
if (airichCommandMenu) append(prepareAIRichCommandMenu(airichCommandMenu));
|
|
2290
|
+
if (gridImages) append(prepareGridImageMessage({ imageUrls: gridImages, verificationMetadata }));
|
|
2291
|
+
if (verticalAlbum) append(prepareVerticalAlbumMessage({ items: verticalAlbum, verificationMetadata }));
|
|
2292
|
+
if (videoGrid) append(prepareVideoGridMessage({ videos: videoGrid, verificationMetadata }));
|
|
2293
|
+
if (richGeneration) append(prepareRichGenerationMessage({ ...richGeneration, verificationMetadata }));
|
|
2294
|
+
if (richLabel) append(buildRichLabelMessage(richLabel));
|
|
2295
|
+
if (suggestedPrompt) append(prepareBotPromptSuggestionsMessage({ ...suggestedPrompt, verificationMetadata }));
|
|
2296
|
+
if (botSources) append(prepareBotSourcesMessage({ ...botSources, verificationMetadata }));
|
|
2297
|
+
if (botPttTranscript) append(prepareBotPttTranscriptMessage({ ...botPttTranscript, verificationMetadata }));
|
|
2298
|
+
if (unifiedResponse && typeof unifiedResponse === 'object') {
|
|
2299
|
+
if (Array.isArray(unifiedResponse.sections)) unified.sections.push(...unifiedResponse.sections);
|
|
2300
|
+
if (Array.isArray(unifiedResponse.embedded_screens)) unified.embedded_screens = [...(unified.embedded_screens || []), ...unifiedResponse.embedded_screens];
|
|
2301
|
+
}
|
|
2302
|
+
for (const section of [...(Array.isArray(rawSections) ? rawSections : []), ...(Array.isArray(richSections) ? richSections : [])]) {
|
|
2303
|
+
if (section && typeof section === 'object') unified.sections.push(section);
|
|
2304
|
+
}
|
|
2305
|
+
if (composed.embedded_screens?.length) unified.embedded_screens = composed.embedded_screens;
|
|
2306
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
2307
|
+
submessages: composed.submessages,
|
|
2308
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
2309
|
+
unifiedResponse: {
|
|
2310
|
+
data: Buffer.from(JSON.stringify(unified)) // Lia@Note 25-04-26 --- Expects "ArrayBufferLike"
|
|
2311
|
+
},
|
|
2312
|
+
contextInfo: {
|
|
2313
|
+
isForwarded: true,
|
|
2314
|
+
forwardingScore: 1,
|
|
2315
|
+
forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
|
|
2316
|
+
forwardOrigin: 4
|
|
2317
|
+
}
|
|
2318
|
+
});
|
|
2319
|
+
const message = wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
2320
|
+
const botMetadata = message.messageContextInfo.botMetadata;
|
|
2321
|
+
Object.assign(botMetadata, composed.botMetadata);
|
|
2322
|
+
// Lia@Note 13-05-26 --- Add disclaimer text on richResponseMessage
|
|
2323
|
+
if (disclaimerText) {
|
|
2324
|
+
botMetadata.messageDisclaimerText = disclaimerText;
|
|
2325
|
+
}
|
|
2326
|
+
// Lia@Note 15-05-26 --- Add responseId from unified directly to botMetadata
|
|
2327
|
+
botMetadata.botResponseId = uuid;
|
|
2328
|
+
// Lia@Note 17-04-26 --- TODO: Fill mediaDetailsMetadataList and sources field
|
|
2329
|
+
const { sources, mediaDetailsMetadataList } = buildAdditionalBotMetadataContext(submessages);
|
|
2330
|
+
if (sources.length > 0) {
|
|
2331
|
+
botMetadata.richResponseSourcesMetadata = { sources };
|
|
2332
|
+
}
|
|
2333
|
+
if (mediaDetailsMetadataList.length > 0) {
|
|
2334
|
+
botMetadata.unifiedResponseMutation = { mediaDetailsMetadataList };
|
|
2335
|
+
}
|
|
2336
|
+
return message;
|
|
2337
|
+
};
|
|
2338
|
+
// Lia@Note 17-04-26 --- signature and certificateChain for proofs[] field
|
|
2339
|
+
/**
|
|
2340
|
+
* @deprecated Generates random bytes that verify against nothing. Kept only for
|
|
2341
|
+
* experimental tooling; the library no longer attaches generated proofs to
|
|
2342
|
+
* messages. Pass real proofs through the `verificationMetadata` option instead.
|
|
2343
|
+
*/
|
|
2344
|
+
export const botMetadataSignature = () => {
|
|
2345
|
+
const signature = new Uint8Array(64);
|
|
2346
|
+
getRandomValues(signature);
|
|
2347
|
+
return signature;
|
|
2348
|
+
};
|
|
2349
|
+
export const botMetadataCertificate = (length = 685) => {
|
|
2350
|
+
const certificate = new Uint8Array(length);
|
|
2351
|
+
certificate[0] = 48;
|
|
2352
|
+
certificate[1] = 130;
|
|
2353
|
+
getRandomValues(certificate.subarray(2));
|
|
2354
|
+
return certificate;
|
|
2355
|
+
};
|
|
2356
|
+
/**
|
|
2357
|
+
* Builds a GenAI HTML primitive message — renders raw HTML inside a forwarded rich response.
|
|
2358
|
+
* Uses FOAHtmlPrimitiveDemoDONOTUSE for full HTML rendering inside the chat bubble.
|
|
2359
|
+
*
|
|
2360
|
+
* This is the game-changer: you can render games, forms, dashboards, and anything
|
|
2361
|
+
* else that HTML/CSS/JS can do, directly inside WhatsApp!
|
|
2362
|
+
*
|
|
2363
|
+
* @param {Object} options
|
|
2364
|
+
* @param {string} options.html - Raw HTML string to render
|
|
2365
|
+
* @param {Array} [options.trustedSources=[]] - Trusted source URLs for security
|
|
2366
|
+
* @returns {Object} Wrapped botForwardedMessage ready for relayMessage
|
|
2367
|
+
*/
|
|
2368
|
+
export const prepareHtmlMessage = (options = {}) => {
|
|
2369
|
+
const { html = '', trustedSources = [], verificationMetadata } = options;
|
|
2370
|
+
const sections = [buildFoaHtmlSection(html, trustedSources)];
|
|
2371
|
+
const unified = { response_id: randomUUID(), sections };
|
|
2372
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
2373
|
+
submessages: [],
|
|
2374
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
2375
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
2376
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 },
|
|
2377
|
+
});
|
|
2378
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
2379
|
+
};
|
|
2380
|
+
|
|
2381
|
+
/**
|
|
2382
|
+
* Build the alternate GenAI HTML envelope used by interactive HTML screens.
|
|
2383
|
+
* Unlike prepareHtmlMessage(), this includes embedded_screens and uses the
|
|
2384
|
+
* aeacdsnw HTML primitive used by the attached game message.
|
|
2385
|
+
*/
|
|
2386
|
+
export const prepareRichHtmlMessage = (options = {}) => {
|
|
2387
|
+
const { verificationMetadata } = options;
|
|
2388
|
+
const { title, embeddedScreen } = buildRichHtmlScreen(options);
|
|
2389
|
+
const unified = {
|
|
2390
|
+
response_id: randomUUID(),
|
|
2391
|
+
sections: [{
|
|
2392
|
+
view_model: {
|
|
2393
|
+
primitive: { text: `> ${title}`, __typename: 'GenAIMarkdownTextUXPrimitive' },
|
|
2394
|
+
__typename: 'GenAISingleLayoutViewModel'
|
|
2395
|
+
}
|
|
2396
|
+
}],
|
|
2397
|
+
embedded_screens: [embeddedScreen]
|
|
2398
|
+
};
|
|
2399
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
2400
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
2401
|
+
submessages: [{ messageType: RichSubMessageType.TEXT, messageText: `> ${title}` }],
|
|
2402
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
2403
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardOrigin: 4 }
|
|
2404
|
+
});
|
|
2405
|
+
return wrapToBotForwardedMessage(richResponseMessage, verificationMetadata);
|
|
2406
|
+
};
|
|
2407
|
+
|
|
2408
|
+
const decodePreparedUnified = (prepared) => {
|
|
2409
|
+
const richResponse = prepared?.botForwardedMessage?.message?.richResponseMessage;
|
|
2410
|
+
const rawData = richResponse?.unifiedResponse?.data;
|
|
2411
|
+
if (!rawData) return null;
|
|
2412
|
+
try {
|
|
2413
|
+
const text = Buffer.isBuffer(rawData)
|
|
2414
|
+
? rawData.toString()
|
|
2415
|
+
: (rawData instanceof Uint8Array ? Buffer.from(rawData).toString() : String(rawData));
|
|
2416
|
+
const decoded = Buffer.from(text, /^[A-Za-z0-9+/]+=*$/.test(text) ? 'base64' : 'utf8').toString();
|
|
2417
|
+
return JSON.parse(decoded);
|
|
2418
|
+
}
|
|
2419
|
+
catch {
|
|
2420
|
+
return null;
|
|
2421
|
+
}
|
|
2422
|
+
};
|
|
2423
|
+
|
|
2424
|
+
/**
|
|
2425
|
+
* Compose each rich fragment in the order its key appears in the caller's
|
|
2426
|
+
* object. The fixed-order renderer remains the single source of wire formats;
|
|
2427
|
+
* this wrapper only orders independently rendered sections before combining
|
|
2428
|
+
* them into one AIRich response.
|
|
2429
|
+
*/
|
|
2430
|
+
export const prepareRichResponseMessage = (content = {}) => {
|
|
2431
|
+
if (!content || typeof content !== 'object' || Array.isArray(content)) {
|
|
2432
|
+
throw new Boom('rich response content must be an object', { statusCode: 400 });
|
|
2433
|
+
}
|
|
2434
|
+
const submessages = [];
|
|
2435
|
+
const sections = [];
|
|
2436
|
+
const embeddedScreens = [];
|
|
2437
|
+
const mergedBotMetadata = {};
|
|
2438
|
+
const compatibility = content.compatibility === 'new-rich-media' || content.compatibility === 'both';
|
|
2439
|
+
let compatibilityAdded = false;
|
|
2440
|
+
let newRichMedia;
|
|
2441
|
+
|
|
2442
|
+
const appendPrepared = (prepared) => {
|
|
2443
|
+
const unified = decodePreparedUnified(prepared);
|
|
2444
|
+
if (Array.isArray(unified?.sections)) sections.push(...unified.sections.filter(Boolean));
|
|
2445
|
+
if (Array.isArray(unified?.embedded_screens)) embeddedScreens.push(...unified.embedded_screens);
|
|
2446
|
+
const richResponse = prepared?.botForwardedMessage?.message?.richResponseMessage;
|
|
2447
|
+
if (Array.isArray(richResponse?.submessages)) submessages.push(...richResponse.submessages);
|
|
2448
|
+
const botMetadata = prepared?.messageContextInfo?.botMetadata;
|
|
2449
|
+
if (botMetadata) Object.assign(mergedBotMetadata, botMetadata);
|
|
2450
|
+
};
|
|
2451
|
+
|
|
2452
|
+
const appendEmbeddedScreen = (screen) => {
|
|
2453
|
+
const normalized = normalizeEmbeddedScreenInput(screen);
|
|
2454
|
+
embeddedScreens.push(normalized);
|
|
2455
|
+
const title = normalized.title === undefined || normalized.title === null ? '' : String(normalized.title).trim();
|
|
2456
|
+
if (title) {
|
|
2457
|
+
appendPrepared(prepareRichResponseMessageFixedOrder({
|
|
2458
|
+
contentText: `> ${title}`,
|
|
2459
|
+
noDonation: true,
|
|
2460
|
+
verificationMetadata: content.verificationMetadata
|
|
2461
|
+
}));
|
|
2462
|
+
}
|
|
2463
|
+
};
|
|
2464
|
+
|
|
2465
|
+
const appendField = (key, value) => {
|
|
2466
|
+
const fragment = { noDonation: true, verificationMetadata: content.verificationMetadata };
|
|
2467
|
+
switch (key) {
|
|
2468
|
+
case 'text':
|
|
2469
|
+
fragment.contentText = value;
|
|
2470
|
+
break;
|
|
2471
|
+
case 'table':
|
|
2472
|
+
appendTableValue(value);
|
|
2473
|
+
return;
|
|
2474
|
+
case 'code':
|
|
2475
|
+
fragment.code = value;
|
|
2476
|
+
fragment.language = content.language;
|
|
2477
|
+
break;
|
|
2478
|
+
case 'inlineImage':
|
|
2479
|
+
fragment.inlineImage = value;
|
|
2480
|
+
fragment.imageText = content.imageText;
|
|
2481
|
+
fragment.alignment = content.alignment;
|
|
2482
|
+
fragment.tapLinkUrl = content.tapLinkUrl;
|
|
2483
|
+
break;
|
|
2484
|
+
case 'html':
|
|
2485
|
+
fragment.html = value;
|
|
2486
|
+
fragment.trustedSources = content.trustedSources;
|
|
2487
|
+
break;
|
|
2488
|
+
case 'richHtml':
|
|
2489
|
+
fragment.richHtml = value;
|
|
2490
|
+
fragment.trustedSources = content.trustedSources;
|
|
2491
|
+
break;
|
|
2492
|
+
case 'richTable':
|
|
2493
|
+
appendTableValue(value);
|
|
2494
|
+
return;
|
|
2495
|
+
case 'tables':
|
|
2496
|
+
if (Array.isArray(value)) value.forEach(appendTableValue);
|
|
2497
|
+
return;
|
|
2498
|
+
case 'richResponse': {
|
|
2499
|
+
if (!Array.isArray(value)) break;
|
|
2500
|
+
for (const item of value) {
|
|
2501
|
+
if (item?.inlineVideo) appendField('inlineVideo', item.inlineVideo);
|
|
2502
|
+
else if (Object.hasOwn(item || {}, 'table')) appendField('table', item.table);
|
|
2503
|
+
else if (item?.posts) appendField('posts', item.posts);
|
|
2504
|
+
else if (item?.products) appendField('products', item.products);
|
|
2505
|
+
else if (item?.suggested) appendField('suggested', item.suggested);
|
|
2506
|
+
else appendPrepared(prepareRichResponseMessageFixedOrder({
|
|
2507
|
+
richResponse: [item],
|
|
2508
|
+
noDonation: true,
|
|
2509
|
+
verificationMetadata: content.verificationMetadata
|
|
2510
|
+
}));
|
|
2511
|
+
}
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
case 'embeddedScreen':
|
|
2515
|
+
appendEmbeddedScreen(value);
|
|
2516
|
+
return;
|
|
2517
|
+
case 'embeddedScreens':
|
|
2518
|
+
if (!Array.isArray(value)) {
|
|
2519
|
+
throw new Boom('embeddedScreens must be an array', { statusCode: 400 });
|
|
2520
|
+
}
|
|
2521
|
+
value.forEach(appendEmbeddedScreen);
|
|
2522
|
+
return;
|
|
2523
|
+
case 'reminderMetadata':
|
|
2524
|
+
mergedBotMetadata.reminderMetadata = normalizeReminderMetadata(value);
|
|
2525
|
+
return;
|
|
2526
|
+
case 'calendarWidget':
|
|
2527
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
2528
|
+
throw new Boom('calendarWidget must be an object', { statusCode: 400 });
|
|
2529
|
+
}
|
|
2530
|
+
sections.push(prepareAIRichCalendarWidgetSection(value));
|
|
2531
|
+
submessages.push({
|
|
2532
|
+
messageType: RichSubMessageType.TEXT,
|
|
2533
|
+
messageText: String(value.title ?? 'Upcoming events')
|
|
2534
|
+
});
|
|
2535
|
+
return;
|
|
2536
|
+
case 'contentItemsGroup':
|
|
2537
|
+
Object.assign(fragment, value);
|
|
2538
|
+
break;
|
|
2539
|
+
default:
|
|
2540
|
+
fragment[key] = value;
|
|
2541
|
+
}
|
|
2542
|
+
appendPrepared(prepareRichResponseMessageFixedOrder(fragment));
|
|
2543
|
+
};
|
|
2544
|
+
|
|
2545
|
+
const appendSimpleTable = (tableRows) => {
|
|
2546
|
+
const normalizedRows = tableRows.map(row => Array.isArray(row) ? row : [row]);
|
|
2547
|
+
appendPrepared(prepareRichResponseMessageFixedOrder({
|
|
2548
|
+
table: normalizedRows,
|
|
2549
|
+
title: content.title,
|
|
2550
|
+
noHeading: content.noHeading,
|
|
2551
|
+
noDonation: true,
|
|
2552
|
+
verificationMetadata: content.verificationMetadata
|
|
2553
|
+
}));
|
|
2554
|
+
};
|
|
2555
|
+
|
|
2556
|
+
const appendRichTable = (table) => {
|
|
2557
|
+
if (!table || typeof table !== 'object' || Array.isArray(table)) return;
|
|
2558
|
+
const richTable = generateTableContent(
|
|
2559
|
+
String(table.title ?? ''),
|
|
2560
|
+
Array.isArray(table.headers) ? table.headers : [],
|
|
2561
|
+
Array.isArray(table.rows) ? table.rows : [],
|
|
2562
|
+
undefined,
|
|
2563
|
+
{ headerText: table.headerText, footer: table.footer }
|
|
2564
|
+
);
|
|
2565
|
+
const richResponse = richTable?.message?.botForwardedMessage?.message?.richResponseMessage;
|
|
2566
|
+
if (Array.isArray(richResponse?.submessages)) {
|
|
2567
|
+
submessages.push(...richResponse.submessages);
|
|
2568
|
+
// Keep rich-object tables as legacy preview submessages. Simple
|
|
2569
|
+
// array tables use appendSimpleTable and remain unified inline
|
|
2570
|
+
// table primitives, so callers can mix both renderers explicitly.
|
|
2571
|
+
}
|
|
2572
|
+
};
|
|
2573
|
+
|
|
2574
|
+
const appendTableValue = (table) => {
|
|
2575
|
+
if (Array.isArray(table)) {
|
|
2576
|
+
appendSimpleTable(table);
|
|
2577
|
+
return;
|
|
2578
|
+
}
|
|
2579
|
+
if (!table || typeof table !== 'object') return;
|
|
2580
|
+
if (Array.isArray(table.headers) && Array.isArray(table.rows)) {
|
|
2581
|
+
appendRichTable(table);
|
|
2582
|
+
}
|
|
2583
|
+
else if (Array.isArray(table.rows)) {
|
|
2584
|
+
appendSimpleTable([...(Array.isArray(table.headers) ? [table.headers] : []), ...table.rows]);
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
|
|
2588
|
+
const appendCompatibility = () => {
|
|
2589
|
+
if (compatibilityAdded || !compatibility) return;
|
|
2590
|
+
compatibilityAdded = true;
|
|
2591
|
+
const compatible = prepareNewRichMediaCompatibility({
|
|
2592
|
+
reels: content.reels,
|
|
2593
|
+
images: content.images || (content.image ? [content.image] : []),
|
|
2594
|
+
posts: content.posts
|
|
2595
|
+
});
|
|
2596
|
+
if (!compatible.sections.length) return;
|
|
2597
|
+
sections.push(...compatible.sections);
|
|
2598
|
+
newRichMedia = {
|
|
2599
|
+
compatibility: compatible.compatibility,
|
|
2600
|
+
reels: compatible.reels,
|
|
2601
|
+
images: compatible.images,
|
|
2602
|
+
posts: compatible.posts
|
|
2603
|
+
};
|
|
2604
|
+
};
|
|
2605
|
+
|
|
2606
|
+
const nonRenderableKeys = new Set([
|
|
2607
|
+
'alignment', 'compatibility', 'copyLabel', 'disclaimerText',
|
|
2608
|
+
'image', 'images', 'language', 'noDonation', 'noHeading', 'title',
|
|
2609
|
+
'tapLinkUrl', 'trustedSources', 'verificationMetadata'
|
|
2610
|
+
]);
|
|
2611
|
+
const renderableKeys = new Set([
|
|
2612
|
+
'headerText', 'contentText', 'text', 'footerText', 'code', 'table', 'richTable', 'tables', 'items', 'reels',
|
|
2613
|
+
'inlineImage', 'inlineVideo', 'latex', 'links', 'sources', 'posts', 'products', 'suggested',
|
|
2614
|
+
'html', 'richHtml', 'richResponse', 'copyButton', 'copyToClipboard', 'copyText',
|
|
2615
|
+
'richText', 'quote', 'richImage', 'richLinks', 'richMap', 'map', 'dynamicMedia',
|
|
2616
|
+
'richDynamicMedia', 'socialEntity', 'socialProfile', 'richMenu', 'airichCommandMenu',
|
|
2617
|
+
'unifiedResponse', 'gridImages', 'verticalAlbum', 'videoGrid', 'richGeneration',
|
|
2618
|
+
'richLabel', 'suggestedPrompt', 'botSources', 'botPttTranscript', 'sections', 'richSections',
|
|
2619
|
+
'calendarWidget', 'embeddedScreen', 'embeddedScreens', 'reminderMetadata'
|
|
2620
|
+
]);
|
|
2621
|
+
const inputEntries = Object.entries(content);
|
|
2622
|
+
const entries = [
|
|
2623
|
+
...inputEntries.filter(([key]) => key === 'headerText'),
|
|
2624
|
+
...inputEntries.filter(([key]) => key !== 'headerText' && key !== 'footerText'),
|
|
2625
|
+
...inputEntries.filter(([key]) => key === 'footerText')
|
|
2626
|
+
];
|
|
2627
|
+
for (let index = 0; index < entries.length; index++) {
|
|
2628
|
+
const [key, value] = entries[index];
|
|
2629
|
+
if (['reels', 'images', 'image', 'posts'].includes(key)) appendCompatibility();
|
|
2630
|
+
if (key === 'items' || key === 'reels') {
|
|
2631
|
+
const grouped = {};
|
|
2632
|
+
let nextIndex = index;
|
|
2633
|
+
while (nextIndex < entries.length && ['items', 'reels'].includes(entries[nextIndex][0])) {
|
|
2634
|
+
const [groupKey, groupValue] = entries[nextIndex];
|
|
2635
|
+
grouped[groupKey] = groupValue;
|
|
2636
|
+
nextIndex++;
|
|
2637
|
+
}
|
|
2638
|
+
if (Object.hasOwn(grouped, 'reels')) appendCompatibility();
|
|
2639
|
+
appendField('contentItemsGroup', grouped);
|
|
2640
|
+
index = nextIndex - 1;
|
|
2641
|
+
continue;
|
|
2642
|
+
}
|
|
2643
|
+
if (!renderableKeys.has(key) || nonRenderableKeys.has(key)) continue;
|
|
2644
|
+
appendField(key, value);
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
if (content.noDonation !== true) {
|
|
2648
|
+
appendPrepared(prepareRichResponseMessageFixedOrder({ links: [], noDonation: false }));
|
|
2649
|
+
}
|
|
2650
|
+
|
|
2651
|
+
const responseId = randomUUID();
|
|
2652
|
+
const unified = {
|
|
2653
|
+
response_id: responseId,
|
|
2654
|
+
sections,
|
|
2655
|
+
...(embeddedScreens.length ? { embedded_screens: embeddedScreens } : {}),
|
|
2656
|
+
...(newRichMedia ? { new_rich_media: newRichMedia } : {})
|
|
2657
|
+
};
|
|
2658
|
+
const richResponseMessage = proto.AIRichResponseMessage.create({
|
|
2659
|
+
submessages,
|
|
2660
|
+
messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
|
|
2661
|
+
unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) },
|
|
2662
|
+
contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 }
|
|
2663
|
+
});
|
|
2664
|
+
const message = wrapToBotForwardedMessage(richResponseMessage, content.verificationMetadata);
|
|
2665
|
+
const botMetadata = message.messageContextInfo.botMetadata;
|
|
2666
|
+
Object.assign(botMetadata, mergedBotMetadata);
|
|
2667
|
+
if (content.disclaimerText) botMetadata.messageDisclaimerText = content.disclaimerText;
|
|
2668
|
+
botMetadata.botResponseId = responseId;
|
|
2669
|
+
const { sources, mediaDetailsMetadataList } = buildAdditionalBotMetadataContext(submessages);
|
|
2670
|
+
if (sources.length > 0) botMetadata.richResponseSourcesMetadata = { sources };
|
|
2671
|
+
if (mediaDetailsMetadataList.length > 0) botMetadata.unifiedResponseMutation = { mediaDetailsMetadataList };
|
|
2672
|
+
return message;
|
|
2673
|
+
};
|
|
2674
|
+
|
|
2675
|
+
export const generateX4R1S3RichAIResponseContent = (content = {}, quoted, options = {}) => {
|
|
2676
|
+
if (!content || typeof content !== 'object' || Array.isArray(content)) {
|
|
2677
|
+
throw new Boom('sendX4R1S3Message content must be an object', { statusCode: 400 });
|
|
2678
|
+
}
|
|
2679
|
+
const x4r1s3Content = { ...content };
|
|
2680
|
+
const aiSections = [];
|
|
2681
|
+
const supportedTypes = new Set(['table', 'list', 'codeBlock', 'latex', 'plain', 'text', 'gridImage', 'inlineImage', 'dynamic', 'map', 'contentItems']);
|
|
2682
|
+
if (Array.isArray(x4r1s3Content.sections) && x4r1s3Content.sections.length > 0) {
|
|
2683
|
+
const rawSections = [];
|
|
2684
|
+
for (const section of x4r1s3Content.sections) {
|
|
2685
|
+
if (section && typeof section === 'object' && !Array.isArray(section) && supportedTypes.has(section.type)) {
|
|
2686
|
+
aiSections.push(section);
|
|
2687
|
+
}
|
|
2688
|
+
else {
|
|
2689
|
+
rawSections.push(section);
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
if (aiSections.length) {
|
|
2693
|
+
if (rawSections.length) x4r1s3Content.sections = rawSections;
|
|
2694
|
+
else delete x4r1s3Content.sections;
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2697
|
+
if (x4r1s3Content.table && !Array.isArray(x4r1s3Content.table) && typeof x4r1s3Content.table === 'object' &&
|
|
2698
|
+
(Array.isArray(x4r1s3Content.table.headers) || Array.isArray(x4r1s3Content.table.rows))) {
|
|
2699
|
+
aiSections.push({ type: 'table', value: x4r1s3Content.table });
|
|
2700
|
+
delete x4r1s3Content.table;
|
|
2701
|
+
}
|
|
2702
|
+
for (const type of ['list', 'codeBlock', 'latex', 'plain', 'text', 'gridImage', 'inlineImage', 'dynamic', 'map', 'contentItems']) {
|
|
2703
|
+
if (x4r1s3Content[type] !== undefined && x4r1s3Content[type] !== null) {
|
|
2704
|
+
aiSections.push({ type, value: x4r1s3Content[type] });
|
|
2705
|
+
delete x4r1s3Content[type];
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
let messageId;
|
|
2709
|
+
if (aiSections.length) {
|
|
2710
|
+
const generated = generateRichAIResponseContent({ sections: aiSections }, quoted, options);
|
|
2711
|
+
messageId = generated.messageId;
|
|
2712
|
+
const generatedSubmessages = generated?.message?.botForwardedMessage?.message?.richResponseMessage?.submessages || [];
|
|
2713
|
+
x4r1s3Content.richResponse = [
|
|
2714
|
+
...(Array.isArray(x4r1s3Content.richResponse) ? x4r1s3Content.richResponse : []),
|
|
2715
|
+
...generatedSubmessages
|
|
2716
|
+
];
|
|
2717
|
+
}
|
|
2718
|
+
const message = prepareRichResponseMessage({
|
|
2719
|
+
...x4r1s3Content,
|
|
2720
|
+
noDonation: options.noDonation ?? true
|
|
2721
|
+
});
|
|
2722
|
+
return { message, messageId };
|
|
2723
|
+
};
|
|
2724
|
+
|
|
2725
|
+
/** Merge any prepared AIRich helper into a single X4R1S3 response. */
|
|
2726
|
+
const appendPreparedRichContent = (target, prepared) => {
|
|
2727
|
+
const unified = decodePreparedUnified(prepared);
|
|
2728
|
+
if (unified?.sections?.length) target.sections.push(...unified.sections);
|
|
2729
|
+
if (Array.isArray(unified?.embedded_screens)) {
|
|
2730
|
+
target.embedded_screens = [...(target.embedded_screens || []), ...unified.embedded_screens];
|
|
2731
|
+
}
|
|
2732
|
+
const richResponse = prepared?.botForwardedMessage?.message?.richResponseMessage;
|
|
2733
|
+
if (Array.isArray(richResponse?.submessages)) target.submessages.push(...richResponse.submessages);
|
|
2734
|
+
const botMetadata = prepared?.messageContextInfo?.botMetadata;
|
|
2735
|
+
if (botMetadata) Object.assign(target.botMetadata, botMetadata);
|
|
2736
|
+
};
|
|
2737
|
+
|
|
2738
|
+
/**
|
|
2739
|
+
* Proofs are forwarded only when the caller supplies real, verifiable proofs.
|
|
2740
|
+
* The library never fabricates a certificate chain or signature: an unverifiable
|
|
2741
|
+
* proof is worse than none, because it asserts provenance the caller cannot back.
|
|
2742
|
+
*/
|
|
2743
|
+
export const hasVerifiableProofs = (verificationMetadata) =>
|
|
2744
|
+
Array.isArray(verificationMetadata?.proofs) && verificationMetadata.proofs.length > 0;
|
|
2745
|
+
|
|
2746
|
+
/**
|
|
2747
|
+
* Attach trusted verification proofs to an already-built rich envelope.
|
|
2748
|
+
*
|
|
2749
|
+
* Pure, null-safe, and idempotent: returns the envelope untouched when no
|
|
2750
|
+
* verifiable proofs are supplied or when the envelope carries no botMetadata.
|
|
2751
|
+
* Used by the send pipeline (`relayMessage`) to auto-inject proofs configured
|
|
2752
|
+
* once on the socket as `config.metaAiRendering.verificationMetadata`, so every
|
|
2753
|
+
* rich message (menu, reels, rich text/image/link, HTML) is covered without each
|
|
2754
|
+
* send method needing to thread the config through.
|
|
2755
|
+
*/
|
|
2756
|
+
export const attachBotVerificationProofs = (envelope, verificationMetadata) => {
|
|
2757
|
+
if (!envelope || !hasVerifiableProofs(verificationMetadata))
|
|
2758
|
+
return envelope;
|
|
2759
|
+
const botMetadata = envelope?.messageContextInfo?.botMetadata;
|
|
2760
|
+
if (!botMetadata || botMetadata.verificationMetadata)
|
|
2761
|
+
return envelope;
|
|
2762
|
+
botMetadata.verificationMetadata = verificationMetadata;
|
|
2763
|
+
return envelope;
|
|
2764
|
+
};
|
|
2765
|
+
|
|
2766
|
+
/**
|
|
2767
|
+
* Build a forwarded AIRich label message.
|
|
2768
|
+
*
|
|
2769
|
+
* This is the small single-label surface used by WhatsApp clients for a
|
|
2770
|
+
* colored forwarded bubble. The unified response is intentionally serialized
|
|
2771
|
+
* as base64 text because that is the wire shape accepted by the raw
|
|
2772
|
+
* `relayMessage` API.
|
|
2773
|
+
*/
|
|
2774
|
+
export const buildRichLabelMessage = ({
|
|
2775
|
+
text = '',
|
|
2776
|
+
variant = 'POSITIVE',
|
|
2777
|
+
backgroundColor = '#FF0000FF',
|
|
2778
|
+
textColor = '#000000FF',
|
|
2779
|
+
responseId = randomUUID(),
|
|
2780
|
+
} = {}) => {
|
|
2781
|
+
const unified = {
|
|
2782
|
+
__typename: 'GenAIUnifiedResponse',
|
|
2783
|
+
response_id: responseId,
|
|
2784
|
+
sections: [{
|
|
2785
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
2786
|
+
view_model: {
|
|
2787
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
2788
|
+
primitive: {
|
|
2789
|
+
__typename: 'GenAILabelPrimitive',
|
|
2790
|
+
text: String(text),
|
|
2791
|
+
variant,
|
|
2792
|
+
background_color_override: backgroundColor,
|
|
2793
|
+
text_color_override: textColor,
|
|
2794
|
+
},
|
|
2795
|
+
},
|
|
2796
|
+
}],
|
|
2797
|
+
};
|
|
2798
|
+
|
|
2799
|
+
return {
|
|
2800
|
+
botForwardedMessage: {
|
|
2801
|
+
message: {
|
|
2802
|
+
richResponseMessage: {
|
|
2803
|
+
messageType: 1,
|
|
2804
|
+
unifiedResponse: {
|
|
2805
|
+
data: Buffer.from(JSON.stringify(unified)).toString('base64'),
|
|
2806
|
+
},
|
|
2807
|
+
contextInfo: {
|
|
2808
|
+
isForwarded: true,
|
|
2809
|
+
forwardOrigin: 4,
|
|
2810
|
+
},
|
|
2811
|
+
},
|
|
2812
|
+
},
|
|
2813
|
+
},
|
|
2814
|
+
};
|
|
2815
|
+
};
|
|
2816
|
+
|
|
2817
|
+
/**
|
|
2818
|
+
* Wrap a rich response in the bot-forwarded envelope.
|
|
2819
|
+
*
|
|
2820
|
+
* @param {Object} richResponseMessage - proto.AIRichResponseMessage
|
|
2821
|
+
* @param {Object} [verificationMetadata] - Trusted proofs supplied by the caller
|
|
2822
|
+
* (typically `config.metaAiRendering.verificationMetadata`). Omitted when absent
|
|
2823
|
+
* or empty, so no fabricated provenance is ever sent.
|
|
2824
|
+
*/
|
|
2825
|
+
export const wrapToBotForwardedMessage = (richResponseMessage, verificationMetadata) => ({
|
|
2826
|
+
messageContextInfo: {
|
|
2827
|
+
botMetadata: {
|
|
2828
|
+
pluginMetadata: {},
|
|
2829
|
+
...(hasVerifiableProofs(verificationMetadata) ? { verificationMetadata } : {}),
|
|
2830
|
+
// Lia@Fix --- The Bloks rendering config is required for the client to resolve
|
|
2831
|
+
// and verify rich media. Without it, rich messages attach media the client
|
|
2832
|
+
// treats as unverified: "WhatsApp can't verify the security of this media",
|
|
2833
|
+
// tapping Download crashes the app, and reel previews stop rendering.
|
|
2834
|
+
botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA
|
|
2835
|
+
}
|
|
2836
|
+
},
|
|
2837
|
+
botForwardedMessage: {
|
|
2838
|
+
message: { richResponseMessage }
|
|
2839
|
+
}
|
|
2840
|
+
});
|
|
2841
|
+
//# sourceMappingURL=rich-message-utils.js.map
|