@brainfish-ai/components 0.35.4 → 0.35.5

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.
@@ -68,7 +68,7 @@ return e.createElement("div",{className:J("w-full px-3 py-4 flex items-center ju
68
68
  /* @__PURE__ */e.createElement("span",null,c?"History":t)),
69
69
  /* @__PURE__ */e.createElement("div",{className:"@3xl:hidden shrink-0","data-name":"HeaderButtons"},!w&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:()=>{g(e=>!e),r()},"aria-label":f?"Collapse widget":"Expand widget",className:"text-primary-foreground device-touch:hidden device-desktop:inline-flex device-desktop-touch:inline-flex"},f?/* @__PURE__ */e.createElement(R,null):/* @__PURE__ */e.createElement(j,null)),m&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:o,"aria-label":"Conversation history",className:"relative text-primary-foreground"},
70
70
  /* @__PURE__ */e.createElement(O,null),l&&!c&&/* @__PURE__ */e.createElement("span",{className:"absolute top-1 right-1 size-2 rounded-full bg-red-500"})),/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:a,"aria-label":"Close widget",className:"text-primary-foreground"},
71
- /* @__PURE__ */e.createElement(b,null))))}const Xr={headerText:"How can we help you today?",searchPlaceholder:"Ask a question or type a search term here ...",attachImageText:"Attach image",allDocumentsText:"All documents",loadingSearchText:"Searching for relevant content...",loadingAnswerText:"Crafting a response...",errorText:"Sorry, we were unable to process the request right now. Please try again in a moment.",followUpPlaceholder:"Type your response or follow-up",positiveAnswerText:"Helpful",negativeAnswerText:"Not helpful",uncertaintyFallbackText:{en:"Sorry, I can't find a clear answer to your question. Please try rephrasing or check the related sources below.",es:"Lo siento, no puedo encontrar una respuesta clara. Intente reformular la pregunta o consulte las fuentes relacionadas.",fr:"Désolé, je ne trouve pas de réponse claire. Essayez de reformuler ou consultez les sources connexes.",de:"Entschuldigung, ich finde keine klare Antwort. Versuchen Sie es anders zu formulieren oder sehen Sie sich die verwandten Quellen an.",it:"Mi dispiace, non trovo una risposta chiara. Prova a riformulare o consulta le fonti correlate.",pt:"Desculpe, não encontro uma resposta clara. Tente reformular ou consulte as fontes relacionadas.",nl:"Sorry, ik kan geen duidelijk antwoord vinden. Probeer het anders te formuleren of bekijk de gerelateerde bronnen.",pl:"Przepraszam, nie znajduję jasnej odpowiedzi. Spróbuj przeformułować pytanie lub sprawdź powiązane źródła.",ru:"Извините, я не могу найти четкого ответа. Попробуйте переформулировать или ознакомьтесь со связанными источниками.",ja:"申し訳ありませんが、明確な回答が見つかりません。質問の言い換えや、関連ソースをご確認ください。",ko:"죄송합니다. 명확한 답변을 찾을 수 없습니다. 질문을 다시 작성하거나 관련 소스를 확인해 주세요.",zh:"抱歉,找不到明确的答案。请尝试重新表述或查看相关来源。","zh-TW":"抱歉,找不到明確的答案。請嘗試重新表述或查看相關來源。"}},Yr=({loadConversationEndpoint:e,headers:t,mergedTextConfig:n})=>{const{setIsLoadingConversation:a,setShowResults:s,answerListDispatch:o,conversationId:i,setConversationId:c,clearConversationId:l,setLoadError:d}=kr(),u=r(r=>{if(!e)return;a(!0),a(!0),s(!0);const i=new AbortController;return fe({endpoint:e,conversationId:r,headers:t,signal:i.signal}).then(({data:e})=>{const t=e.map(e=>({id:e.searchQueryId,state:"completed",question:e.question,isUncertain:Z(e.answer).uncertain,searchQueryId:e.searchQueryId,searchIntentId:e.searchIntentId,blocks:e.answer.split("---").map(e=>Lt({text:e.trim()}))}));o((({answers:e})=>({type:Mt,payload:{answers:e}}))({answers:t})),c(r),s(!0)}).catch(e=>{console.error("Error loading conversation:",e),o(ir()),l(),s(!1),d(n.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment.")}).finally(()=>{a(!1)}),()=>i.abort("Conversation loader aborted")},[e,a,s,t,o,c,d,n.errorText]);return re(()=>{let e;return i&&(console.log("loading conversation",i),e=u(i)),()=>e?.()}),{loadConversationById:u}},en={"image/jpeg":"image","image/png":"image","image/gif":"image","image/webp":"image"};let tn=0;function rn({toasts:t,onDismiss:r}){/* @__PURE__ */
71
+ /* @__PURE__ */e.createElement(b,null))))}const Xr={headerText:"How can we help you today?",searchPlaceholder:"Ask a question or type a search term here ...",attachImageText:"Attach image",allDocumentsText:"All documents",loadingSearchText:"Searching for relevant content...",loadingAnswerText:"Crafting a response...",errorText:"Sorry, we were unable to process the request right now. Please try again in a moment.",followUpPlaceholder:"Type your response or follow-up",positiveAnswerText:"Helpful",negativeAnswerText:"Not helpful",uncertaintyFallbackText:{en:"Sorry, I can't find a clear answer to your question. Please try rephrasing or check the related sources below.",es:"Lo siento, no puedo encontrar una respuesta clara. Intente reformular la pregunta o consulte las fuentes relacionadas.",fr:"Désolé, je ne trouve pas de réponse claire. Essayez de reformuler ou consultez les sources connexes.",de:"Entschuldigung, ich finde keine klare Antwort. Versuchen Sie es anders zu formulieren oder sehen Sie sich die verwandten Quellen an.",it:"Mi dispiace, non trovo una risposta chiara. Prova a riformulare o consulta le fonti correlate.",pt:"Desculpe, não encontro uma resposta clara. Tente reformular ou consulte as fontes relacionadas.",nl:"Sorry, ik kan geen duidelijk antwoord vinden. Probeer het anders te formuleren of bekijk de gerelateerde bronnen.",pl:"Przepraszam, nie znajduję jasnej odpowiedzi. Spróbuj przeformułować pytanie lub sprawdź powiązane źródła.",ru:"Извините, я не могу найти четкого ответа. Попробуйте переформулировать или ознакомьтесь со связанными источниками.",ja:"申し訳ありませんが、明確な回答が見つかりません。質問の言い換えや、関連ソースをご確認ください。",ko:"죄송합니다. 명확한 답변을 찾을 수 없습니다. 질문을 다시 작성하거나 관련 소스를 확인해 주세요.",zh:"抱歉,找不到明确的答案。请尝试重新表述或查看相关来源。","zh-TW":"抱歉,找不到明確的答案。請嘗試重新表述或查看相關來源。"}},Yr=({loadConversationEndpoint:e,headers:t,reconnectHandoff:n})=>{const{setIsLoadingConversation:a,setShowResults:s,answerListDispatch:o,conversationId:i,setConversationId:c,setLoadError:l}=kr(),d=r(r=>{if(c(r),s(!0),!e)return;a(!0),l("");const n=new AbortController;return fe({endpoint:e,conversationId:r,headers:t,signal:n.signal}).then(({data:e})=>{const t=e.map(e=>({id:e.searchQueryId,state:"completed",question:e.question,isUncertain:Z(e.answer).uncertain,searchQueryId:e.searchQueryId,searchIntentId:e.searchIntentId,blocks:e.answer.split("---").map(e=>Lt({text:e.trim()}))}));o((({answers:e})=>({type:Mt,payload:{answers:e}}))({answers:t})),s(!0)}).catch(e=>{n.signal.aborted||e instanceof Error&&"AbortError"===e.name||(console.error("Error loading conversation:",e),o(ir()),s(!0))}).finally(()=>{a(!1)}),()=>n.abort("Conversation loader aborted")},[e,a,s,t,o,c,l]);return re(()=>{let e;return i&&(console.log("loading conversation",i),e=d(i),n?.(i)),()=>e?.()}),{loadConversationById:d}},en={"image/jpeg":"image","image/png":"image","image/gif":"image","image/webp":"image"};let tn=0;function rn({toasts:t,onDismiss:r}){/* @__PURE__ */
72
72
  return e.createElement("div",{className:"fixed top-4 left-4 right-4 z-50 flex flex-col gap-2 pointer-events-none"},/* @__PURE__ */e.createElement(u,null,t.map(t=>/* @__PURE__ */e.createElement(d.div,{key:t.id,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.2},className:"pointer-events-auto flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-3 text-sm text-foreground shadow-lg"},
73
73
  /* @__PURE__ */e.createElement("span",{className:"flex-1"},t.message),
74
74
  /* @__PURE__ */e.createElement("button",{onClick:()=>r(t.id),className:"shrink-0 rounded-full p-0.5 hover:bg-muted transition-colors","aria-label":"Dismiss"},
@@ -79,7 +79,7 @@ return e.createElement("button",{onClick:()=>r({conversationId:t.conversationId,
79
79
  /* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function on({title:t,items:r,onSelect:n,isReadOnly:a=!1,botAvatarUrl:s}){return 0===r.length?null:/* @__PURE__ */e.createElement("section",null,/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 mb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},t),a&&/* @__PURE__ */e.createElement("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground"},"View only")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},r.map(t=>/* @__PURE__ */e.createElement(sn,{key:t.conversationId,item:t,onSelect:n,botAvatarUrl:s}))))}function cn(){/* @__PURE__ */
80
80
  return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const ln=()=>{};function dn({conversations:t,isLoading:r,onSelectConversation:n,botAvatarUrl:a}){const s=n??ln,o=t.filter(e=>"active"===e.status),i=t.filter(e=>"completed"===e.status);return r?/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 px-3 py-4 overflow-hidden"},/* @__PURE__ */e.createElement("div",{className:"h-4 w-16 bg-muted rounded animate-pulse mb-2"}),[...Array(3)].map((t,r)=>/* @__PURE__ */e.createElement(cn,{key:r}))):/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-4 px-3 py-4 min-h-full"},/* @__PURE__ */e.createElement(on,{title:"Active",items:o,onSelect:s,botAvatarUrl:a}),/* @__PURE__ */e.createElement(on,{title:"Previous",items:i,onSelect:s,isReadOnly:!0,botAvatarUrl:a}),0===t.length&&/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center justify-center gap-3 mt-16 text-center px-6"},/* @__PURE__ */e.createElement(Ie,{size:40,className:"text-muted-foreground opacity-40"}),/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-foreground"},"No Threads yet"),/* @__PURE__ */e.createElement("p",{className:"text-xs text-muted-foreground"},"Start a conversation and it will appear here.")))}function un({conversations:t,onSelect:r,onViewAll:n,botAvatarUrl:a}){const s=t.filter(e=>"active"===e.status).slice(0,2);return 0===s.length?null:/* @__PURE__ */e.createElement("div",{className:"w-full p-3 md:p-0","data-name":"ActiveConversations"},/* @__PURE__ */e.createElement("div",{className:"flex items-center justify-between mb-3"},/* @__PURE__ */e.createElement("h3",{className:"text-base font-medium text-foreground"},"Continue conversation"),/* @__PURE__ */e.createElement(v,{type:"button",variant:"ghost",size:"xs",onClick:n},"View all")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},s.map(t=>/* @__PURE__ */e.createElement(sn,{key:t.conversationId,item:t,onSelect:r,botAvatarUrl:a}))))}function mn({onStartNewConversation:t,message:r="This conversation is closed. Messages are read-only."}){/* @__PURE__ */
81
81
  return e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"bg-card shadow-top-soft"},
82
- /* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const pn="enableHistoryTab",hn=[p],fn=[m],gn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},yn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:A,onToggleSizeButtonClick:T,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:F,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,botAvatarUrl:X,reconnectHandoff:Y,resetHandoff:ee,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,knowledgeSourceGroups:se},oe)=>{const{answers:ie,answerListDispatch:ce,query:le,setQuery:de,followUpQuery:ue,setFollowUpQuery:me,isSearching:he,setIsSearching:fe,showResults:Ce,setShowResults:Ie,activeAnswerIndex:Ae,setActiveAnswerIndex:Te,conversationId:Re,setConversationId:je,clearConversationId:Oe,isLoadingConversation:De,setShowMobileCloseWidgetButton:ze}=kr(),Le={...Xr,...S},Fe=pe("enableFileAttachment",!1),Ue=_||Fe,Qe=pe(pn,!1),{toasts:Me,showToast:Ve,dismissToast:qe}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),Ke=r(()=>{let e=Re;return e||(e=ge(),je(e)),e},[Re,je]),{attachedFiles:Be,isUploading:He,addFiles:Ge,removeFile:We,clearAttachedFiles:Je,getUploadedAttachments:Ze}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>en[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++tn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:en[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ye({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:Ke,onError:Ve}),[Xe,Ye]=t(s),[et,tt]=t(m),[rt,nt]=t(!0),at=i(null),st=i(null),ot=i(null),it=i([]),ct=i(null),lt=i(null),dt=i(null),ut=i(null),mt=i(null),{suggestions:pt}=Ee({query:le,endpoint:$||"",allowedRegions:V,collectionId:Xe,headers:I,conversationId:Re,delay:300}),{loadConversationById:ht}=Yr({loadConversationEndpoint:E,headers:I,mergedTextConfig:Le}),{showHistory:ft,setShowHistory:gt,conversations:yt,isLoadingHistory:vt,hasUnreadConversations:wt,isViewOnly:bt,setIsViewOnly:Et,handleSelectConversation:$t,completeActiveConversations:xt}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return ve({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),ve({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&we({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{be({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Qe,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,headers:I,userData:U??void 0,currentConversationId:Re,loadConversationById:ht,reconnectHandoff:Y,resetHandoff:ee}),{scrollToLastAnswer:_t,scrollToAnswer:kt}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(it,ct,ut),{subscribeToStateChanges:Nt}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=kr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Ct,includePageLoading:It,includePageDisabled:St,handleIncludePageToggle:Pt,fetchPageContext:At}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ge();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{mt.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&mt.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ce(fr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ce(lr({text:e.content}));const t=Z(a);if(l=t.uncertain,l){const e=Le.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ce(mr({uncertaintyText:e}))}}"answer-error"===e.type&&ce(dr({error:Le.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ce(yr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ce(gr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return Ot({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ce(pr()),ce(fr({message:Le.loadingAnswerText})),Rt({searchQueryId:t,conversationId:r,parameters:n})):jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ce(cr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(mt.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{mt.current===e&&(mt.current=null,e.releaseLock())}},Rt=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ne({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await ke({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ce((({questions:e,index:t})=>({type:Gt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur())}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ce(pr());try{const s=await ke({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur()),fe(!1)}},Ot=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ce(pr());try{const s=await ke({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur()),fe(!1)}},Dt=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Xe,i=await _e({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ce(cr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},zt=async({searchQuery:e=le.trim(),event:t})=>{if(!e)return;const r=Re||ge();je(r);const n=Ze();Je(),fe(!0),Ie(!0),Te(ie.length),_t(),ce((({id:e,query:t,attachments:r})=>({type:qt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),dt.current?.focus();const a=await At(r,e);if(se&&se.length>0&&!at.current)return st.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ce((({index:e}={})=>({type:ar,payload:{index:e}}))()),void fe(!1);try{const s={...U},o=at.current?.collectionIds,i=await Dt({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await Rt({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ce(hr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}},Lt=async e=>{at.current=e;const t=st.current;if(t){st.current=null,ce((({index:e}={})=>({type:sr,payload:{index:e}}))()),fe(!0);try{const r=await Dt({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await Rt({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ce(hr())}catch(r){console.error("Error generating answer after group selection:",r),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}}},Ft=e=>{if(xt(),Et(!1),ee?.(),mt.current){const e=mt.current;mt.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}fe(!1),de(""),me(""),Ie(!1),ce(ir()),Te(0),Je(),Oe(),at.current=null,st.current=null,R?.("New Thread Created",{oldConversationId:Re}),ot.current&&(ot.current.style.height="auto"),e&&(de(e),zt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(oe,()=>({createNewThread:Ft,showFollowUpThread:e=>{nt(e)},subscribeToStateChanges:Nt,focusSearchField:()=>lt.current?.focus()||dt.current?.focus(),showCloseButton:(e=!0)=>{ze(e)},loadConversation:ht})),o(()=>{Ye(s)},[s]),o(()=>{tt(m)},[m]);const Qt=async(e,t,r)=>{if(w){ce((({feedback:e,index:t})=>({type:Zt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await xe({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Re}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Re,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ce((({index:e}={})=>({type:Xt,payload:{index:e}}))({index:r}))}}},Mt=async e=>{const t=void 0!==e?e:ue;t.trim()&&(de(t),me(""),await zt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(de(""),me(""),Ie(!1),ce(ir()),Te(0),Je(),ot.current&&(ot.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Vt=e=>{R?.("Follow-up Question Clicked",{conversationId:Re,question:e}),zt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Kt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Re,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Ut(e.blocks)}))}))(ie,Re);F?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=ct.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=Ce&&rt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return Ce?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,Ce,rt]),/* @__PURE__ */e.createElement("div",{className:J("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",A),"data-name":"ChatSearch",style:q},
82
+ /* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const pn="enableHistoryTab",hn=[p],fn=[m],gn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},yn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:A,onToggleSizeButtonClick:T,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:F,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,botAvatarUrl:X,reconnectHandoff:Y,resetHandoff:ee,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,knowledgeSourceGroups:se},oe)=>{const{answers:ie,answerListDispatch:ce,query:le,setQuery:de,followUpQuery:ue,setFollowUpQuery:me,isSearching:he,setIsSearching:fe,showResults:Ce,setShowResults:Ie,activeAnswerIndex:Ae,setActiveAnswerIndex:Te,conversationId:Re,setConversationId:je,clearConversationId:Oe,isLoadingConversation:De,setShowMobileCloseWidgetButton:ze}=kr(),Le={...Xr,...S},Fe=pe("enableFileAttachment",!1),Ue=_||Fe,Qe=pe(pn,!1),{toasts:Me,showToast:Ve,dismissToast:qe}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),Ke=r(()=>{let e=Re;return e||(e=ge(),je(e)),e},[Re,je]),{attachedFiles:Be,isUploading:He,addFiles:Ge,removeFile:We,clearAttachedFiles:Je,getUploadedAttachments:Ze}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>en[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++tn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:en[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ye({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:Ke,onError:Ve}),[Xe,Ye]=t(s),[et,tt]=t(m),[rt,nt]=t(!0),at=i(null),st=i(null),ot=i(null),it=i([]),ct=i(null),lt=i(null),dt=i(null),ut=i(null),mt=i(null),{suggestions:pt}=Ee({query:le,endpoint:$||"",allowedRegions:V,collectionId:Xe,headers:I,conversationId:Re,delay:300}),{loadConversationById:ht}=Yr({loadConversationEndpoint:E,headers:I,reconnectHandoff:Y}),{showHistory:ft,setShowHistory:gt,conversations:yt,isLoadingHistory:vt,hasUnreadConversations:wt,isViewOnly:bt,setIsViewOnly:Et,handleSelectConversation:$t,completeActiveConversations:xt}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return ve({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),ve({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&we({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{be({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Qe,conversationHistoryEndpoint:te,markConversationReadEndpoint:re,markConversationCompletedEndpoint:ne,headers:I,userData:U??void 0,currentConversationId:Re,loadConversationById:ht,reconnectHandoff:Y,resetHandoff:ee}),{scrollToLastAnswer:_t,scrollToAnswer:kt}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(it,ct,ut),{subscribeToStateChanges:Nt}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=kr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Ct,includePageLoading:It,includePageDisabled:St,handleIncludePageToggle:Pt,fetchPageContext:At}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ge();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{mt.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&mt.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ce(fr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ce(lr({text:e.content}));const t=Z(a);if(l=t.uncertain,l){const e=Le.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ce(mr({uncertaintyText:e}))}}"answer-error"===e.type&&ce(dr({error:Le.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ce(yr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ce(gr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return Ot({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ce(pr()),ce(fr({message:Le.loadingAnswerText})),Rt({searchQueryId:t,conversationId:r,parameters:n})):jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ce(cr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(mt.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{mt.current===e&&(mt.current=null,e.releaseLock())}},Rt=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ne({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await ke({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ce((({questions:e,index:t})=>({type:Gt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur())}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ce(pr());try{const s=await ke({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur()),fe(!1)}},Ot=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ce(pr());try{const s=await ke({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ce(ur()),fe(!1)}},Dt=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Xe,i=await _e({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ce(cr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},zt=async({searchQuery:e=le.trim(),event:t})=>{if(!e)return;const r=Re||ge();je(r);const n=Ze();Je(),fe(!0),Ie(!0),Te(ie.length),_t(),ce((({id:e,query:t,attachments:r})=>({type:qt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),dt.current?.focus();const a=await At(r,e);if(se&&se.length>0&&!at.current)return st.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ce((({index:e}={})=>({type:ar,payload:{index:e}}))()),void fe(!1);try{const s={...U},o=at.current?.collectionIds,i=await Dt({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await Rt({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ce(hr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}},Lt=async e=>{at.current=e;const t=st.current;if(t){st.current=null,ce((({index:e}={})=>({type:sr,payload:{index:e}}))()),fe(!0);try{const r=await Dt({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await Rt({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ce(hr())}catch(r){console.error("Error generating answer after group selection:",r),ce(dr({error:Le.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{fe(!1)}}},Ft=e=>{if(xt(),Et(!1),ee?.(),mt.current){const e=mt.current;mt.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}fe(!1),de(""),me(""),Ie(!1),ce(ir()),Te(0),Je(),Oe(),at.current=null,st.current=null,R?.("New Thread Created",{oldConversationId:Re}),ot.current&&(ot.current.style.height="auto"),e&&(de(e),zt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(oe,()=>({createNewThread:Ft,showFollowUpThread:e=>{nt(e)},subscribeToStateChanges:Nt,focusSearchField:()=>lt.current?.focus()||dt.current?.focus(),showCloseButton:(e=!0)=>{ze(e)},loadConversation:ht})),o(()=>{Ye(s)},[s]),o(()=>{tt(m)},[m]);const Qt=async(e,t,r)=>{if(w){ce((({feedback:e,index:t})=>({type:Zt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await xe({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Re}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Re,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ce((({index:e}={})=>({type:Xt,payload:{index:e}}))({index:r}))}}},Mt=async e=>{const t=void 0!==e?e:ue;t.trim()&&(de(t),me(""),await zt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(de(""),me(""),Ie(!1),ce(ir()),Te(0),Je(),ot.current&&(ot.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Vt=e=>{R?.("Follow-up Question Clicked",{conversationId:Re,question:e}),zt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Kt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Re,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Ut(e.blocks)}))}))(ie,Re);F?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=ct.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=Ce&&rt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return Ce?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,Ce,rt]),/* @__PURE__ */e.createElement("div",{className:J("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",A),"data-name":"ChatSearch",style:q},
83
83
  /* @__PURE__ */e.createElement(rn,{toasts:Me,onDismiss:qe}),(O||!Ce)&&/* @__PURE__ */e.createElement(Zr,{showHistoryButton:Qe,isSearchWidget:K,"data-name":"Header",headerText:Le.headerText,onToggleSizeButtonClick:()=>{T?.()},onBackButtonClick:()=>{Ft()},onCloseWidgetClick:()=>j?.(),showHistory:ft,hasUnreadConversations:wt,onHistoryButtonClick:()=>gt(!0),onHistoryBackClick:()=>gt(!1),className:J("@3xl:mb-4",{"!block":Ce&&K})}),
84
84
  /* @__PURE__ */e.createElement(Se,{className:"w-full relative h-auto flex-grow [&>[data-radix-scroll-area-viewport]>div:first-child]:!block",ref:ct},
85
85
  /* @__PURE__ */e.createElement(u,null,ft?/* @__PURE__ */e.createElement(dn,{conversations:yt,isLoading:vt,onSelectConversation:$t,botAvatarUrl:X}):De?/* @__PURE__ */e.createElement(nn,null):Ce?/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"results",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5},className:"w-full max-w-[100vw] space-y-4 p-3 md:p-0"},ie.map((t,r)=>/* @__PURE__ */e.createElement(d.div,{key:r,ref:e=>it.current[r]=e,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.1*r},className:"space-y-4 last:!mb-8"},
@@ -93,4 +93,4 @@ return e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},t
93
93
  /* @__PURE__ */e.createElement("div",{ref:ut})),Ce&&rt&&!bt&&!W&&!ft&&(()=>{const t=ie.some(e=>"awaiting-knowledge-group"===e.state);/* @__PURE__ */
94
94
  return e.createElement(Wr,{ref:dt,initialQuery:ue,onQueryChange:me,isSearching:he,handleFollowUpSearch:Mt,textConfig:Le,enableFileAttachment:Ue,attachedFiles:Be,isUploading:He,onAddFiles:Ge,onRemoveFile:We,disabled:t})})(),Ce&&bt&&!ft&&/* @__PURE__ */e.createElement(mn,{onStartNewConversation:()=>Ft()}),!ft&&!bt&&W)});yn.displayName="ChatSearch";const vn=c(({featureFlags:t,...r},n)=>/* @__PURE__ */e.createElement(he,{flags:t},/* @__PURE__ */e.createElement(_r,{searchPath:r.searchPath,contentTypeEndpoint:r.contentTypeEndpoint,widgetKey:r.apiKey},
95
95
  /* @__PURE__ */e.createElement(yn,{...r,ref:n}))));vn.displayName="ChatSearch";export{vn as C,Or as N,mn as R,_r as a,Jr as b,kr as u,jr as v};
96
- //# sourceMappingURL=ChatSearch.DAtEyu9O.js.map
96
+ //# sourceMappingURL=ChatSearch.DcQI3eY8.js.map