import { EnxAction, EnxChoice, EnxLinkCard, EnxMessage, EnxMessageSender, EnxMessageType, EnxSuggestionType, } from './types'; const asMap = (v: unknown): Record => { if (!v) return {}; if (typeof v === 'string') { try { const p = JSON.parse(v); return typeof p === 'object' && p ? (p as Record) : {}; } catch { return {}; } } return typeof v === 'object' ? (v as Record) : {}; }; const parseDate = (v: unknown): Date => { if (typeof v !== 'string') return new Date(); const d = new Date(v); return Number.isNaN(d.getTime()) ? new Date() : d; }; const msgType = (v: string): EnxMessageType => { switch (v) { case 'action': return EnxMessageType.Action; case 'photo': case 'image': return EnxMessageType.Image; case 'video': return EnxMessageType.Video; case 'file': return EnxMessageType.File; case 'single-choice': case 'multi-choice': return EnxMessageType.Suggestion; case 'calendar': return EnxMessageType.Calendar; case 'card': case 'template': case 'article': return EnxMessageType.Text; default: return EnxMessageType.Text; } }; const isMediaUrl = (value: string): boolean => /^https?:\/\//.test(value) || /^data:image\//.test(value) || /^file:\/\//.test(value) || /^content:\/\//.test(value); const asText = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; const findUrlDeep = (input: unknown, depth = 0): string | undefined => { if (depth > 4 || input == null) return undefined; if (typeof input === 'string') return isMediaUrl(input.trim()) ? input.trim() : undefined; if (Array.isArray(input)) { for (const item of input) { const match = findUrlDeep(item, depth + 1); if (match) return match; } return undefined; } if (typeof input === 'object') { const map = input as Record; const preferredKeys = ['url', 'uri', 'src', 'href', 'link', 'image', 'media', 'file', 'video', 'mediaUrl', 'fileUrl', 'videoUrl']; for (const key of preferredKeys) { if (key in map) { const match = findUrlDeep(map[key], depth + 1); if (match) return match; } } for (const value of Object.values(map)) { const match = findUrlDeep(value, depth + 1); if (match) return match; } } return undefined; }; const firstMediaUrl = (payload: Record): string | undefined => { const keys = ['url', 'video', 'videoUrl', 'file', 'fileUrl', 'media', 'mediaUrl', 'image', 'imageUrl', 'attachment', 'attachments']; for (const key of keys) { const match = findUrlDeep(payload[key]); if (match) return match; } return findUrlDeep(payload); }; const inferType = (rawType: string, mediaUrl?: string, mimeType?: string): EnxMessageType => { // Card/template payloads carry a hero image URL; still render as text + linkCard, not as a plain image bubble. if (rawType === 'card' || rawType === 'template' || rawType === 'article' || rawType === 'rich') { return EnxMessageType.Text; } const byRaw = msgType(rawType); if (byRaw !== EnxMessageType.Text) return byRaw; const lowerMime = (mimeType ?? '').toLowerCase(); if (lowerMime.startsWith('image/')) return EnxMessageType.Image; if (lowerMime.startsWith('video/')) return EnxMessageType.Video; const lowerUrl = (mediaUrl ?? '').toLowerCase(); if (/(\.png|\.jpe?g|\.gif|\.webp|\.bmp|\.svg)(\?|$)/.test(lowerUrl) || lowerUrl.startsWith('data:image/')) { return EnxMessageType.Image; } if (/(\.mp4|\.mov|\.m4v|\.webm)(\?|$)/.test(lowerUrl)) return EnxMessageType.Video; if (mediaUrl) return EnxMessageType.File; return EnxMessageType.Text; }; const looksLikePageUrl = (url: string): boolean => { const base = (url.split('?')[0] ?? url).toLowerCase(); if (!/^https?:\/\//.test(url.trim())) return false; if (/\.(png|jpe?g|gif|webp|bmp|svg|mp4|mov|m4v|webm|pdf|zip)(\?|$)/i.test(base)) return false; return true; }; const isLikelyImageUrl = (url: string): boolean => { const lower = (url.split('?')[0] ?? url).toLowerCase(); return /^data:image\//.test(lower) || /\.(png|jpe?g|gif|webp|bmp)(\?|$)/i.test(lower) || /format=jpg|format=png|type=image/i.test(url); }; /** Hero image for link cards — avoid using the page URL as the image source. */ function findCardHeroImageUrl(payload: Record, pageUrl?: string): string | undefined { const tryKeys = [ 'image', 'banner', 'bannerUrl', 'bannerImage', 'coverImage', 'cover', 'thumbnail', 'thumbnailUrl', 'previewImage', 'preview', 'ogImage', 'imageUrl', 'heroImage', 'picture', 'photo', ]; for (const key of tryKeys) { const found = findUrlDeep(payload[key]); if (found && found !== pageUrl && isLikelyImageUrl(found)) return found.trim(); } const mediaMap = asMap(payload.media); const mUrl = asText(mediaMap.url) ?? findUrlDeep(mediaMap); if (mUrl && mUrl !== pageUrl && isLikelyImageUrl(mUrl)) return mUrl.trim(); return undefined; } const firstPageUrlInString = (s: string): string | undefined => { const re = /https?:\/\/[^\s<>]+/gi; let m: RegExpExecArray | null; while ((m = re.exec(s)) !== null) { const u = m[0].replace(/[),.;]+$/, ''); if (looksLikePageUrl(u)) return u; } return undefined; }; /** * Botpress / EnableX sometimes sends a rich card as `type: "text"` with a single `text` body: * Title:…\nSubtitle:…\n\n\nVisit now: */ function tryParseStructuredTextCard(text: string): EnxLinkCard | undefined { const t = text.trim(); if (!t) return undefined; if (!/^\s*Title:\s*\S/im.test(t) || !/^\s*Subtitle:\s*\S/im.test(t)) return undefined; const titleLine = t.match(/^\s*Title:\s*(.+)$/im)?.[1]?.trim(); const subtitleLine = t.match(/^\s*Subtitle:\s*(.+)$/im)?.[1]?.trim(); if (!titleLine && !subtitleLine) return undefined; const urls = Array.from(t.matchAll(/https?:\/\/[^\s<>]+/gi), (m) => m[0].replace(/[),.;]+$/, '')); const imageUrl = urls.find((u) => isLikelyImageUrl(u)); const visitMatch = t.match(/Visit\s+now:\s*(https?:\/\/[^\s<>]+)/i); let pageUrl = visitMatch?.[1]?.replace(/[),.;]+$/, '').trim(); if (!pageUrl) pageUrl = urls.find((u) => looksLikePageUrl(u)); if (!pageUrl) return undefined; return { url: pageUrl, imageUrl, title: titleLine, description: subtitleLine, buttonTitle: 'Visit now', }; } function extractPageUrl( payload: Record, text: string, mediaUrl: string | undefined, type: EnxMessageType, actions: EnxAction[], ): string | undefined { const explicit = asText(payload.url) ?? asText(payload.link) ?? asText(payload.href) ?? asText(payload.buttonUrl) ?? asText(asMap(payload.button).url) ?? asText(asMap(payload.linkButton).url); if (explicit && looksLikePageUrl(explicit)) return explicit.trim(); const fromAction = actions.map((a) => a.url).find((u) => u && looksLikePageUrl(u)); if (fromAction) return fromAction.trim(); if (mediaUrl && looksLikePageUrl(mediaUrl) && (type === EnxMessageType.File || type === EnxMessageType.Text)) { return mediaUrl.trim(); } const fromText = text.trim() ? firstPageUrlInString(text) : undefined; if (fromText) return fromText; return undefined; } function extractLinkCard( payload: Record, text: string, rawType: string, mediaUrl: string | undefined, type: EnxMessageType, actions: EnxAction[], ): EnxLinkCard | undefined { const linkishTypes = new Set([ 'link', 'link-preview', 'link_preview', 'card', 'template', 'article', 'rich', 'website', 'webview', 'company', 'info', ]); const pageUrl = extractPageUrl(payload, text, mediaUrl, type, actions); if (!pageUrl) return undefined; const imageUrl = findCardHeroImageUrl(payload, pageUrl); const title = asText(payload.title) ?? asText(payload.heading) ?? (text.trim() && text.trim() !== pageUrl ? text.trim() : undefined); const description = asText(payload.subtitle) ?? asText(payload.description) ?? asText(payload.body) ?? asText(payload.summary) ?? asText(payload.caption); const primaryAction = actions.find((a) => a.url); const buttonTitle = primaryAction?.title ?? asText(payload.buttonTitle) ?? asText(payload.cta) ?? 'Visit now'; const isLinkishType = linkishTypes.has(rawType); const hasRichFields = !!title || !!description || !!imageUrl; const fileWasPage = type === EnxMessageType.File && !!mediaUrl && looksLikePageUrl(mediaUrl); let hostTitle: string | undefined; try { hostTitle = new URL(pageUrl).hostname.replace(/^www\./, ''); } catch { hostTitle = undefined; } if (isLinkishType || fileWasPage || hasRichFields) { return { url: pageUrl, imageUrl, title: title ?? hostTitle, description, buttonTitle, }; } if ((rawType === 'text' || rawType === '') && looksLikePageUrl(pageUrl)) { return { url: pageUrl, imageUrl, title: title ?? hostTitle, description, buttonTitle, }; } return undefined; } function resolvePayload(data: Record): Record { const inner = asMap(data.payload); if (Object.keys(inner).length > 0) return inner; const nested = asMap(data.data); const nestedPayload = asMap(nested.payload); if (Object.keys(nestedPayload).length > 0) return nestedPayload; if ( typeof data.type === 'string' || typeof data.text === 'string' || data.image != null || data.title != null ) { return data; } return inner; } const INTERNAL_CHAT_TEXT = new Set([ 'stopvideocallforcefully', 'stopaudiocallforcefully', 'startvideocall', ]); function appendVideoCallLandingParams(baseUrl: string, displayName?: string): string { const trimmed = baseUrl.trim(); const name = displayName?.trim() || 'EmbeddedVideo'; const sep = trimmed.includes('?') ? '&' : '?'; // Avoid URLSearchParams — Hermes / RN often ship a stub without .set(). console.log('[enx-chatbot-reactnative] video call URL name param:', name); return `${trimmed}${sep}landing=no&name=${encodeURIComponent(name)}`; } /** EnableX / bot: open embedded video room (handled in ChatWidget WebView). */ export function extractVideoCallUrl(rawData: unknown, botDisplayName?: string): string | undefined { const data = asMap(rawData); const payload = resolvePayload(data); if (asText(payload.audio_video_action)?.toLowerCase() !== 'start') return undefined; const mod = asText(payload.iFrameURL) ?? asText(payload.iFrameURL); if (mod && /^https?:\/\//i.test(mod.trim())) return appendVideoCallLandingParams(mod.trim(), botDisplayName); return undefined; } /** Bot ended the call / agent hung up — close embedded video UI. */ export function isAudioVideoStopPayload(rawData: unknown): boolean { const data = asMap(rawData); const payload = resolvePayload(data); return asText(payload.audio_video_action)?.toLowerCase() === 'stop'; } export function parseBridgeMessage(rawData: unknown): EnxMessage[] { const data = asMap(rawData); const payload = resolvePayload(data); const nestedEnvelope = asMap(data.data); const id = (typeof data.id === 'string' ? data.id : undefined) ?? (typeof nestedEnvelope.id === 'string' ? nestedEnvelope.id : undefined); const timestamp = parseDate(data.sentOn ?? data.createdOn ?? asMap(data.data).sentOn ?? asMap(data.data).createdOn); if (typeof data.authorId === 'string' && data.authorId) { const text = typeof payload.text === 'string' ? payload.text : ''; if (!text) return []; return [{ id, sender: EnxMessageSender.User, type: EnxMessageType.Text, timestamp, text }]; } const direction = asText(data.direction) ?? asText(asMap(data.data).direction); if (direction?.toLowerCase() === 'outgoing') return []; const text = typeof payload.text === 'string' ? payload.text : ''; const textLower = text.trim().toLowerCase(); if (asText(payload.audio_video_action)?.toLowerCase() === 'stop') return []; if ( asText(payload.audio_video_action)?.toLowerCase() === 'start' && (asText(payload.iFrameURLmod) || asText(payload.iFrameURL)) ) { return []; } if (INTERNAL_CHAT_TEXT.has(textLower)) return []; const handoverStatus = asText(payload.handoverStatus); if (handoverStatus && text.trim()) { return [ { id, sender: EnxMessageSender.Bot, type: EnxMessageType.Text, timestamp, text: text.trim(), displayStyle: 'systemCentered', handoverStatus, }, ]; } const rawType = typeof payload.type === 'string' ? payload.type : (text ? 'text' : ''); if (!rawType && !text) return []; const choices: EnxChoice[] = Array.isArray(payload.choices) ? payload.choices .map(asMap) .map((c) => ({ title: String(c.title ?? ''), value: String(c.value ?? c.title ?? ''), isSelected: false })) .filter((c) => c.title) : []; const actions: EnxAction[] = Array.isArray(payload.actions) ? payload.actions .map(asMap) .map((a) => ({ title: String(a.title ?? ''), url: typeof a.url === 'string' ? a.url : typeof a.link === 'string' ? a.link : undefined, action: typeof a.action === 'string' ? a.action : undefined, })) .filter((a) => a.title) : []; const suggestionType = choices.length > 0 ? (rawType === 'single-choice' && payload.allowMultiple !== true ? EnxSuggestionType.Single : EnxSuggestionType.Multiple) : undefined; const mediaUrl = firstMediaUrl(payload); const mimeType = asText(payload.mimeType) ?? asText(payload.contentType) ?? asText(payload.fileType) ?? asText(asMap(payload.media).mimeType) ?? asText(asMap(payload.media).contentType); const type = inferType(rawType, mediaUrl, mimeType); const mediaName = asText(payload.fileName) ?? asText(payload.filename) ?? asText(payload.name) ?? asText(payload.title) ?? 'file'; const subtitle = typeof payload.subtitle === 'string' ? payload.subtitle : undefined; const structuredTextCard = rawType === 'text' ? tryParseStructuredTextCard(text) : undefined; const linkCard = structuredTextCard ?? extractLinkCard(payload, text, rawType, mediaUrl, type, actions); let outType = type; let outMedia = mediaUrl && !linkCard ? { url: mediaUrl, fileName: mediaName, mimeType: mimeType ?? (type === EnxMessageType.Image ? 'image/jpeg' : type === EnxMessageType.Video ? 'video/mp4' : 'application/octet-stream'), } : undefined; if (linkCard) { outType = EnxMessageType.Text; outMedia = undefined; } let outText = text || (typeof payload.title === 'string' ? payload.title : undefined); if (linkCard && outText?.trim() === linkCard.url) outText = undefined; if (linkCard && linkCard.title && outText?.trim() === linkCard.title) outText = undefined; if (linkCard && (rawType === 'card' || rawType === 'template' || rawType === 'article')) { outText = undefined; } if (linkCard && structuredTextCard) { outText = undefined; } let outSubtitle: string | undefined = linkCard ? undefined : subtitle; /** Bot often echoes the media URL in `text` / sends `title`; show only the image/video in the bubble. */ if ((outType === EnxMessageType.Image || outType === EnxMessageType.Video) && outMedia?.url) { outText = undefined; outSubtitle = undefined; } return [{ id, sender: EnxMessageSender.Bot, type: outType, timestamp, text: outText, subtitle: outSubtitle, media: outMedia, linkCard: linkCard ?? undefined, actions: actions.length ? actions : undefined, choices: choices.length ? choices : undefined, suggestionType, }]; }