@smart-cloud/ai-kit-ui 1.4.2 → 1.4.3

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/dist/index.cjs CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(le?`
31
- Follow these additional instructions: ${le}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),q=await z.run(async({signal:V,onStatus:fe})=>(await(0,H.prompt)({messages:re,images:[Be],outputLanguage:"en",responseConstraint:cr},{signal:V,onStatus:fe,context:P,modeOverride:i,onDeviceTimeoutOverride:n})).result);if(!q){N("");return}let he=(U&&U!=="auto"?U:null)||At(),Q=Lt(q).trim();try{_("Translating result...");let V=await z.run(async({signal:fe})=>await mr(Q,he,{signal:fe,context:P,modeOverride:i,onDeviceTimeoutOverride:n,silent:!0}));N(V)}catch(V){N(Q),console.warn("AI Kit: failed to parse SEO JSON",V)}break}}}catch($){Le($ instanceof Error?$.message:r.I18n.get("An unknown error occurred."))}_(void 0)},[F,z,le,ge,U,Ie,Je,P,p,Pe,ct,pe,Te]),nt=(0,B.useCallback)(async()=>{await ze("backend-only")},[ze]),kt=(0,B.useCallback)(i=>{switch(p){case"proofread":return(0,m.jsx)(it.IconCircleDashedCheck,{className:i});case"translate":return(0,m.jsx)(it.IconLanguage,{className:i});case"summarize":return(0,m.jsx)(it.IconSum,{className:i});case"rewrite":case"write":return(0,m.jsx)(it.IconPencilCode,{className:i});case"generateImageMetadata":case"generatePostMetadata":return(0,m.jsx)(it.IconSeo,{className:i});default:return(0,m.jsx)(H.AiKitFeatureIcon,{mode:p,className:i})}},[p]),We=(0,B.useCallback)(()=>{switch(p){case"proofread":return z.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return z.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return z.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return z.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return z.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[F,z.lastSource,p]),rt=(0,B.useCallback)(()=>{switch(p){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[F,p]),He=(0,B.useCallback)(async()=>{de(!1),N(null),Le(null),K.current=!1,z.reset(),G||be()},[be,K,z,G]),Ke=(0,B.useCallback)(async()=>{z.busy&&z.cancel()},[z.busy]);(0,B.useEffect)(()=>{!Ae||!g||!pe||z.busy||E||K.current||(K.current=!0,queueMicrotask(()=>{ze(ke)}))},[z.busy,K,Ae,pe,g,E,ze,ke]),(0,B.useEffect)(()=>{Te&&p!=="proofread"&&(pe||(Ze(!0),K.current=!0))},[Te,pe,p]),(0,B.useEffect)(()=>{let i=!0;return(async()=>{try{await(0,H.waitForAiKitReady)();let R=await ua();i&&Qe(R)}catch(R){console.error(R),i&&Qe(!1)}})(),()=>{i=!1}},[]);let qe=(0,B.useMemo)(()=>{let i=[];if(p==="translate"){let R=H.LANGUAGE_OPTIONS.find($=>$.value===ct)?.label;i.push(r.I18n.get("Input language")+": "+(R?r.I18n.get(R):"auto"))}if(U&&Y?.outputLanguage){let R=H.LANGUAGE_OPTIONS.find($=>$.value===U)?.label;i.push(r.I18n.get("Output language")+": "+(R?r.I18n.get(R):U))}return p==="summarize"&&Pe&&Y?.type&&i.push(r.I18n.get("Type")+": "+r.I18n.get(Pe)),(p==="write"||p==="rewrite")&&Je&&Y?.tone&&i.push(r.I18n.get("Tone")+": "+r.I18n.get(Je)),(p==="write"||p==="rewrite"||p==="summarize")&&ge&&Y?.length&&i.push(r.I18n.get("Length")+": "+r.I18n.get(ge)),le?.trim()&&Y?.instructions&&i.push(r.I18n.get("Instructions")+": \u2713"),i.length?i.join(" \u2022 "):r.I18n.get("No overrides")},[F,p,ct,U,Pe,Je,ge,le]),ce={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Xe=h==="modal"?b.Modal.Root:b.Group,Ue=h==="modal"?b.Modal.Content:b.Group,Ut=h==="modal"?b.Modal.Body:b.Group,Ot=L==="collapse"?b.Collapse:b.Stack,pt=L==="horizontal"?b.Group:b.Stack;return(0,B.useEffect)(()=>{if(!(h!=="modal"||!Ae))return document.body.style.overflow="hidden",document.body.onkeydown=i=>{i.key==="Escape"&&(i.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,h]),(0,m.jsxs)(m.Fragment,{children:[G&&(0,m.jsx)(b.Button,{leftSection:oe&&(ie?(0,m.jsx)("span",{dangerouslySetInnerHTML:{__html:ie}}):kt()),className:ue?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:Ae,onClick:()=>de(!0),"data-ai-kit-open-button":!0,children:ue&&r.I18n.get(ne||Rt)}),Ae&&(0,m.jsxs)(Xe,{opened:!0,className:"ai-feature-root",onClose:He,padding:"md",gap:"md",size:"md",portalProps:h==="modal"?{target:ye,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":ee,"data-ai-kit-variation":h,children:[h==="modal"&&(0,m.jsx)(b.Modal.Overlay,{}),(0,m.jsxs)(Ue,{w:"100%",style:{left:0},children:[h==="modal"&&(0,m.jsxs)(b.Modal.Header,{style:{zIndex:1e3},children:[kt("ai-feature-title-icon"),(0,m.jsx)(b.Modal.Title,{children:r.I18n.get(Rt)}),(0,m.jsx)(b.Modal.CloseButton,{})]}),(0,m.jsx)(Ut,{w:"100%",style:{zIndex:1001},children:(0,m.jsxs)(Pt,{enabled:h!=="modal",working:z.busy,variation:h,children:[(0,m.jsxs)(b.Stack,{gap:"sm",mb:"sm",p:"sm",children:[je&&(0,m.jsx)(b.Alert,{color:"red",children:r.I18n.get(je)}),Te&&p!=="proofread"&&(0,m.jsxs)(b.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,m.jsxs)(b.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>Ze(i=>!i):void 0,children:[L==="collapse"&&(0,m.jsxs)(b.Stack,{gap:0,children:[(0,m.jsx)(b.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,m.jsx)(b.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:qe})]}),L==="collapse"&&(0,m.jsx)(b.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:i=>{i.stopPropagation(),Ze(R=>!R)},children:St?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,m.jsxs)(Ot,{in:St,children:[L==="collapse"&&(0,m.jsx)(b.Divider,{my:"sm"}),(0,m.jsxs)(pt,{gap:"xs",justify:"space-between",children:[p==="write"&&Y?.text&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.TextInput,{size:"xs",className:"ai-feature-option",styles:ce,disabled:z.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:Ie||"",onChange:i=>{let R=i.target.value;Se(R),D?.({text:R})}})}),(p==="write"||p==="rewrite"||p==="generateImageMetadata"||p==="generatePostMetadata")&&Y?.instructions&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.TextInput,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:le||"",onChange:i=>{let R=i.target.value;ut(R),D?.({instructions:R})}})}),p==="translate"&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ce,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...H.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,R)=>i.label.localeCompare(R.label))],value:ct||"auto",onChange:i=>{let R=i;ht(R),dt(void 0),D?.({inputLanguage:R})}})}),Y?.outputLanguage&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ce,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[p==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...H.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,R)=>i.label.localeCompare(R.label))],value:U||yn.settings.defaultOutputLanguage||(p==="rewrite"?"auto":""),onChange:i=>{let R=i;gt(R),dt(void 0),D?.({outputLanguage:R})}})}),p==="summarize"&&Y?.type&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:Pe||"key-points",onChange:i=>{let R=i;Ct(R),D?.({type:R})}})}),(p==="write"||p==="rewrite")&&Y?.tone&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:p==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:Je||(p==="write"?"neutral":"as-is"),onChange:i=>{let R=i;me(R),D?.({tone:R})}})}),(p==="write"||p==="rewrite"||p==="summarize")&&Y?.length&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:p==="write"||p==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:ge||(p==="rewrite"?"as-is":"short"),onChange:i=>{let R=i;at(R),D?.({length:R})}})}),p==="summarize"||p==="write"||p==="rewrite"&&Y?.outputFormat&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:W||"markdown",onChange:i=>{let R=i;ft(R),D?.({outputFormat:R})}})})]})]})]}),z.busy&&mt&&(0,m.jsx)(Pt,{enabled:h==="modal",working:!0,variation:h,children:(0,m.jsxs)(b.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,m.jsx)(b.Loader,{size:"sm"}),(0,m.jsx)(b.Input.Label,{className:"ai-feature-status-text",children:mt})]})}),E&&(0,m.jsxs)(b.Stack,{mt:"md",children:[p==="proofread"&&(E.corrections.length===0?(0,m.jsx)(b.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,m.jsx)(mn,{original:Ie,corrections:E.corrections}),E.correctedInput?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,m.jsx)(b.Group,{c:"pre",className:"ai-feature-generated-content",children:E.correctedInput})]}):null]})),p==="generateImageMetadata"&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:E.alt_text||"",onChange:i=>N({...E,alt_text:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:E.title||"",onChange:i=>N({...E,title:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:E.caption||"",onChange:i=>N({...E,caption:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:E.description||"",onChange:i=>N({...E,description:i.target.value})})]}),p==="generatePostMetadata"&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:E.title||"",onChange:i=>N({...E,title:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:E.excerpt||"",onChange:i=>N({...E,excerpt:i.target.value})})]}),p!=="proofread"&&p!=="generateImageMetadata"&&p!=="generatePostMetadata"&&typeof E=="string"&&(0,m.jsx)(An,{value:E,editable:!!l,onChange:i=>{N(i)}})]}),E===""&&(0,m.jsx)(An,{value:E,editable:!1})]}),(0,m.jsxs)(b.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[z.busy&&(0,m.jsx)(b.Button,{variant:"outline",size:"sm",onClick:Ke,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!z.busy&&(0,m.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!pe,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:We()}),!z.busy&&z.lastSource==="on-device"&&lt&&Ne&&(0,m.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!pe,onClick:nt,"data-ai-kit-regenerate-on-backend-button":!0,children:rt()}),!z.busy&&w&&(0,m.jsx)(b.Button,{variant:"outline",size:"sm",disabled:!E||p==="proofread"&&E.corrections.length===0,onClick:async()=>{w(W==="html"?await ea(E):E),He()},"data-ai-kit-accept-button":!0,children:r.I18n.get(se)}),(0,m.jsx)(b.Button,{variant:"default",size:"sm",onClick:He,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,m.jsx)(Jt,{variation:h})]})})]})]})]})};function An(e){let{value:a,editable:g,onChange:l}=e;return g?(0,m.jsxs)(b.Stack,{p:0,gap:"sm",children:[(0,m.jsx)(b.Input.Label,{children:r.I18n.get("Generated content")}),(0,m.jsx)(b.Textarea,{value:a,onChange:n=>l?.(n.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,m.jsx)(b.Input.Label,{children:r.I18n.get("Preview")}),(0,m.jsx)(b.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,m.jsx)(ma.default,{remarkPlugins:[pa.default],children:a})})]}):(0,m.jsx)(b.Stack,{className:"ai-feature-generated-content",children:a?(0,m.jsx)(ma.default,{remarkPlugins:[pa.default],children:a}):(0,m.jsx)(b.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var vn=vt(hr);var k=require("@mantine/core"),we=require("@tabler/icons-react"),Bt=require("@smart-cloud/ai-kit-core"),Tn=require("@wordpress/data"),T=require("aws-amplify/utils"),o=require("react"),Sn=Ye(require("react-markdown"),1),Rn=Ye(require("remark-gfm"),1);var fr="ai-kit-chatbot-attachments",st="attachments";var ha=null;function kr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function ta(){if(!kr())return null;ha||(ha=new Promise(e=>{try{let a=window.indexedDB.open(fr,1);a.onerror=()=>e(null),a.onblocked=()=>e(null),a.onupgradeneeded=()=>{let g=a.result;g.objectStoreNames.contains(st)||g.createObjectStore(st,{keyPath:"id"})},a.onsuccess=()=>e(a.result)}catch(a){console.warn("[AiChatbot] IndexedDB is not available",a),e(null)}}));try{return await ha}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function fa(e,a){let g=await ta();return g?new Promise((l,n)=>{try{let h=g.transaction(st,e),I=h.objectStore(st),G=a(I);h.oncomplete=()=>l(G),h.onerror=()=>n(h.error),h.onabort=()=>n(h.error)}catch(h){n(h)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function ka(e,a,g){await vr();let l={id:e,blob:a,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await fa("readwrite",h=>(h.put(l),e))}async function ba(e){let a=await ta();return a?new Promise((g,l)=>{try{let n=a.transaction(st,"readonly"),h=n.objectStore(st).get(e);h.onsuccess=()=>{let I=h.result;g(I??null)},h.onerror=()=>l(h.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function br(e){await fa("readwrite",a=>{a.delete(e)})}async function aa(){await fa("readwrite",e=>{e.clear()})}async function ya(e){let a=await ta();a&&await new Promise((g,l)=>{try{let n=a.transaction(st,"readwrite"),h=n.objectStore(st),I=h.getAllKeys();I.onsuccess=()=>{let G=I.result;for(let ue of G){let oe=String(ue);e.has(oe)||h.delete(ue)}},I.onerror=()=>l(I.error),n.oncomplete=()=>g(),n.onerror=()=>l(n.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yr=50*1024*1024;async function Ar(){let e=await ta();return e?new Promise((a,g)=>{try{let l=e.transaction(st,"readonly"),n=l.objectStore(st).getAll();n.onsuccess=()=>{let h=n.result||[];a(h)},n.onerror=()=>g(n.error),l.onerror=()=>g(l.error),l.onabort=()=>g(l.error)}catch(l){g(l)}}).catch(a=>(console.warn("[AiChatbot] Failed to get all attachments",a),[])):[]}async function vr(){let e=await Ar();if(e.length===0)return;let a=e.sort((h,I)=>h.createdAt-I.createdAt),g=a.reduce((h,I)=>h+I.size,0),l=[],n=0;for(;g>yr&&n<a.length;){let h=a[n];h&&(l.push(h.id),g-=h.size),n++}for(let h of l)await br(h);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");T.I18n.putVocabularies(yt);var na=1440*60*1e3,Aa=!1,wr=1,Tr="localstorage",Dt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function wt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Sr=4,Rr=5*1024*1024,Ir=e=>{let a=(e?.name||"").toString(),g=(e?.code||"").toString(),l=(e?.message||"").toString();return a==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},zr=(e,a)=>{if(!e)return null;let g=e.step,l=T.I18n.get((e.message??"").trim()),n=typeof e.progress=="number"?e.progress:null,h=n==null?null:Math.round(n*100);switch(g){case"decide":return l||T.I18n.get("Checking capabilities...");case"on-device:init":return l||T.I18n.get("Initializing on-device AI...");case"on-device:download":return h==null?l||T.I18n.get("Downloading model..."):l||`${T.I18n.get("Downloading model...")} ${h}%`;case"on-device:ready":return l||T.I18n.get("On-device model ready...");case"on-device:run":return l||T.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return T.I18n.get(a.assistantThinkingLabel??oa.assistantThinkingLabel);case"done":return l||T.I18n.get("Done.");case"error":return l||T.I18n.get("An error occurred.");default:return l||null}};function va(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Et=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},ra=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},In=e=>{!e||e.length===0||e.forEach(a=>ra(a.objectUrl))},wn=e=>{e.forEach(a=>In(a.attachments))},Cr=e=>{let{rootElement:a,store:g,previewMode:l,title:n,openButtonTitle:h,openButtonIcon:I,showOpenButtonTitle:G=!0,showOpenButtonIcon:ue=!0,colorMode:oe,language:ne,onClose:ie,context:Ne,placeholder:se,maxImages:L,maxImageBytes:p,historyStorage:P=Tr,emptyHistoryAfterDays:ke=wr,labels:ee,openButtonIconLayout:ae="top",openButtonPosition:be="bottom-right"}=e,w=(0,o.useMemo)(()=>({...oa,...ee||{}}),[ee]),D=zt(),[F,ye]=(0,o.useState)(""),[Y,Te]=(0,o.useState)([]),[M,_]=(0,o.useState)(null),[Ae,de]=(0,o.useState)(!1),[St,Ze]=(0,o.useState)(0),lt=(0,o.useRef)(null),Qe=(0,o.useRef)([]),je=(0,o.useRef)(null),Le=(0,o.useRef)(null),E=(0,o.useRef)(null),[N,Ie]=(0,o.useState)([]),[Se,Be]=(0,o.useState)(null),[le,ut]=(0,o.useState)(!1),[Re,dt]=(0,o.useState)(!1),[ct,ht]=(0,o.useState)(!1),[W,ft]=(0,o.useState)(!1),[U,gt]=(0,o.useState)(!0),[ge,at]=(0,o.useState)(null),[Je,me]=(0,o.useState)(!1),[Pe,Ct]=(0,o.useState)(null),[K,Rt]=(0,o.useState)(null),[Kt,_e]=(0,o.useState)(!1),[pe,z]=(0,o.useState)(null),mt=(0,o.useRef)(pe);(0,o.useEffect)(()=>{mt.current=pe},[pe]);let ze=(0,o.useRef)(null),nt=(0,o.useRef)(!1),[kt,We]=(0,o.useState)(null),rt=(0,o.useRef)(null),He=(0,o.useRef)(null),Ke=(0,o.useRef)(null),qe=(0,o.useRef)(null),ce=(0,o.useCallback)(t=>{t.forEach(c=>ra(c.objectUrl))},[]),Xe=(0,o.useCallback)(()=>{ce(q.current),Te([]),rt.current&&(rt.current.value="")},[ce]),Ue=(0,o.useCallback)(()=>{he.current&&ra(he.current.objectUrl),_(null),Qe.current=[],Ze(0)},[]),Ut=(0,o.useCallback)(async()=>{try{ye(""),Ue();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),c=new MediaRecorder(t,{mimeType:"audio/webm"}),v=new AudioContext,u=v.createMediaStreamSource(t),C=v.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),je.current=v,Le.current=C;let S=new Uint8Array(C.fftSize),j=()=>{if(!Le.current)return;Le.current.getByteTimeDomainData(S);let te=0;for(let Ge=0;Ge<S.length;Ge++){let It=(S[Ge]-128)/128;te+=It*It}let xe=Math.sqrt(te/S.length),Oe=Math.min(100,xe*200);Ze(Oe),E.current=requestAnimationFrame(j)};j(),Qe.current=[];let J=Date.now();c.ondataavailable=te=>{te.data.size>0&&Qe.current.push(te.data)},c.onstop=()=>{let te=new Blob(Qe.current,{type:"audio/webm"}),xe=(Date.now()-J)/1e3,Oe=Et(te);Oe&&_({id:wt("composer-audio"),blob:te,objectUrl:Oe,duration:xe}),t.getTracks().forEach(Ge=>Ge.stop()),E.current&&(cancelAnimationFrame(E.current),E.current=null),je.current&&(je.current.close(),je.current=null),Le.current=null,Ze(0)},lt.current=c,c.start(),de(!0)}catch(t){console.error("Failed to start recording:",t)}},[Ue]),Ot=(0,o.useCallback)(()=>{lt.current&&Ae&&(lt.current.stop(),de(!1))},[Ae]);(0,o.useEffect)(()=>()=>{E.current&&cancelAnimationFrame(E.current),je.current&&je.current.close(),Ue()},[Ue]);let[pt,i]=(0,o.useState)(null),R=(0,o.useRef)(F),$=(0,o.useRef)(N),re=(0,o.useRef)(pt),q=(0,o.useRef)(Y),he=(0,o.useRef)(M);(0,o.useEffect)(()=>{R.current=F},[F]),(0,o.useEffect)(()=>{q.current=Y},[Y]),(0,o.useEffect)(()=>{he.current=M},[M]),(0,o.useEffect)(()=>{$.current=N},[N]),(0,o.useEffect)(()=>{re.current=pt},[pt]),(0,o.useEffect)(()=>{ne&&T.I18n.setLanguage(ne||"en")},[ne]);let Q=(0,Tn.useSelect)(()=>(0,Bt.getStoreSelect)(g).isShowChatbotPreview()),V=(0,o.useMemo)(()=>Math.max(0,L??Sr),[L]),fe=(0,o.useMemo)(()=>Math.max(0,p??Rr),[p]),d=N.length>0,A=(0,o.useMemo)(()=>D.busy&&pe==="chat",[D.busy,pe]),O=(0,o.useMemo)(()=>A?!1:F.trim().length>0||M!==null,[F,A,M]),Z=(0,o.useMemo)(()=>{let t=h||w.askMeLabel;return T.I18n.get(t)},[h,w.askMeLabel,ne]),ve=(0,o.useMemo)(()=>{let t=n||w.modalTitle;return T.I18n.get(t)},[n,w.modalTitle,ne]),Ce=(0,o.useMemo)(()=>{let t=se||w.placeholder;return T.I18n.get(t)},[se,w.placeholder,ne]),et=(0,o.useMemo)(()=>{let t="ai-docs-ask",c=`ai-open-btn--${be}`;return`${t} ${c}`},[be]),Me=(0,o.useCallback)(()=>{let t=qe.current;if(t)try{let c=window.innerHeight||document.documentElement.clientHeight,v=360,u=1e3,C=Math.floor(c*.8),S=Math.max(v,Math.min(C,u));t.style.height=`${S}px`}catch{}},[]),$e=(0,o.useCallback)(()=>{let t=K;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[K]),De=(0,o.useCallback)(()=>{ft(!1),Re&&dt(!1),ht(!1),ie?.()},[Re,ie]);(0,o.useEffect)(()=>{if(W)return Me(),window.addEventListener("resize",Me),()=>window.removeEventListener("resize",Me)},[W,Me]),(0,o.useEffect)(()=>{if(!(!W||!Re))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[W,Re,De]);let xt=(0,o.useMemo)(()=>Y.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[Y]);(0,o.useEffect)(()=>{d||gt(!0)},[d]),(0,o.useEffect)(()=>()=>{ce(q.current)},[ce]),(0,o.useEffect)(()=>{let t=K;if(!t)return;let c=()=>{let v=t.scrollHeight-(t.scrollTop+t.clientHeight);gt(v<20)};return t.addEventListener("scroll",c),()=>{t.removeEventListener("scroll",c)}},[W,K]),(0,o.useEffect)(()=>{if(!U)return;let t=K;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[N,D.busy,U,K]),(0,o.useEffect)(()=>{W||at(null)},[W]);let Nt=(0,o.useMemo)(()=>D.busy?zr(D.statusEvent,w)||T.I18n.get("Working\u2026"):null,[D.busy,D.statusEvent,ne,w]),Dn=(0,o.useMemo)(()=>{for(let t=N.length-1;t>=0;t--){let c=N[t];if(c.role==="user"&&c.clientStatus==="canceled")return c.id}return null},[N]),jt=(0,o.useCallback)(t=>{Ie(c=>{let v=[...c].map((S,j)=>({m:S,i:j})).reverse().find(S=>S.m.role==="user"&&S.m.clientStatus==="pending")?.i;if(v==null)return c;let u=c.slice(),C=u[v];return u[v]={...C,clientStatus:t??void 0},u})},[Ie]),Wt=(0,o.useCallback)(()=>{if(!(!D.busy||mt.current!=="chat")){nt.current=!0;try{D.cancel()}catch{}jt("canceled"),z(null),Be(null),$e()}},[D,jt,$e]),En=(0,o.useCallback)(t=>{let c=q.current,v=Array.from(t.target.files||[]),u=Math.max(0,V-c.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let S of v){if(C.length>=u)break;let j=/image\/(jpeg|png|gif|webp)/i.test(S.type),J=S.size<=fe,te=[...c,...C].some(Oe=>Oe.file.name===S.name&&Oe.file.size===S.size&&Oe.file.lastModified===S.lastModified);if(!j||!J||te)continue;let xe=Et(S);xe&&C.push({id:wt("composer-image"),file:S,objectUrl:xe})}C.length&&Te(S=>[...S,...C]),t.currentTarget.value=""},[V,fe]),Bn=(0,o.useCallback)(t=>{Te(c=>{if(t<0||t>=c.length)return c;let v=c[t];return v&&ra(v.objectUrl),c.filter((u,C)=>C!==t)})},[]),bt=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(Se)return bt.current&&(window.clearTimeout(bt.current),bt.current=null),bt.current=window.setTimeout(()=>{Be(null),bt.current=null},6e3),()=>{bt.current&&(window.clearTimeout(bt.current),bt.current=null)}},[Se]);let Ta=(0,o.useCallback)(async(t,c)=>{let v=P!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async S=>{let j=wt("attachment-image"),J;if(v)try{J=await ka(j,S.file,{name:S.file.name,type:S.file.type,size:S.file.size})??void 0}catch(xe){console.warn("[AiChatbot] Failed to persist image",xe)}let te=Et(S.file);return{id:j,name:S.file.name,type:S.file.type||"application/octet-stream",size:S.file.size,blobId:J,objectUrl:te??void 0,blob:S.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(c){let C=wt("attachment-audio"),S;if(v)try{S=await ka(C,c.blob,{name:`audio-${Date.now()}.webm`,type:c.blob.type,size:c.blob.size})??void 0}catch(J){console.warn("[AiChatbot] Failed to persist audio",J)}let j=Et(c.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:c.blob.type||"audio/webm",size:c.blob.size,blobId:S,objectUrl:j??void 0,blob:c.blob,duration:c.duration,mediaType:"audio"})}return u},[P]),Sa=(0,o.useCallback)(async t=>{let c=[];for(let v of t){let u;if(v.attachments&&v.attachments.length>0){u=[];for(let C of v.attachments){let S;if(C.blobId)try{S=(await ba(C.blobId))?.blob??void 0}catch(J){console.warn("[AiChatbot] Failed to hydrate attachment",J)}if(!S)continue;let j=S?Et(S):null;u.push({...C,objectUrl:j??void 0,blob:S??void 0})}}c.push({...v,attachments:u})}return c},[]),Ra=(0,o.useCallback)(async t=>{if(!t||t.length===0){Xe();return}let c=[];for(let v of t){let u=v.blob;if(!u&&v.blobId)try{u=(await ba(v.blobId))?.blob??void 0}catch(j){console.warn("[AiChatbot] Failed to reload attachment",j)}if(!u)continue;let C=u instanceof File?u:new File([u],v.name||"attachment",{type:v.type||u.type||"application/octet-stream"}),S=Et(C);if(S&&(c.push({id:wt("composer-image"),file:C,objectUrl:S}),c.length>=V))break}if(c.length===0){Xe();return}Te(v=>(ce(v),c)),rt.current&&(rt.current.value="")},[Xe,ce,V]),ia=(0,o.useCallback)((t,c)=>{t&&at({url:t,title:c})},[]),Kn=(0,o.useCallback)(()=>{at(null)},[]),Ia=(0,o.useCallback)(()=>{wn($.current),Xe(),Ue(),Ie([]),Be(null),Ke.current=null,i(null),gt(!0),ut(!1);let t=va(P);if(t)try{t.removeItem(Dt)}catch{}aa()},[Xe,Ue,P]),Un=(0,o.useCallback)(()=>{ut(!0)},[]),On=(0,o.useCallback)(()=>{D.busy&&mt.current==="chat"&&Wt(),Ia()},[D.busy,Wt,Ia]),za=(0,o.useCallback)(()=>{ut(!1)},[]),Ca=(0,o.useCallback)(async(t,c)=>{if(!D.busy)try{let v=Ke.current&&Date.now()-Ke.current.storedAt<ke*na?Ke.current.id:void 0;if(!v)return;z("feedback"),Be(null),await D.run(async({signal:u,onStatus:C})=>(await(0,Bt.sendFeedbackMessage)({sessionId:v,feedbackMessageId:t,feedbackType:c},{signal:u,onStatus:C,context:Ne}),null)),Be(null)}catch(v){let u=v?.message?.trim()||T.I18n.get("An error occurred.");Be(u),console.error("Failed to send feedback",v)}finally{z(v=>v==="feedback"?null:v)}},[D,ne]),xa=(0,o.useCallback)((t,c)=>{Ie(v=>v.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===c?{...u,feedback:void 0}:{...u,feedback:c})),Ca(t,c)},[Ca]),qt=(0,o.useCallback)(async()=>{let t=R.current.trim(),c=he.current;if(!t&&!c||D.busy)return;nt.current=!1,Be(null),z("chat");let v=[...q.current],u=await Ta(v,c),C=wt("user"),S=Date.now(),j={id:C,role:"user",content:t||(c?"[Audio message]":""),createdAt:S,clientStatus:"pending",attachments:u.length?u:void 0};ye(""),Xe(),Ue(),Ie(J=>[...J,j]),W||ft(!0),$e();try{let J=Ke.current&&Date.now()-Ke.current.storedAt<ke*na?Ke.current.id:void 0,te=await D.run(async({signal:Oe,onStatus:Ge})=>await(0,Bt.sendChatMessage)({sessionId:J,message:t||void 0,audio:c?.blob,images:v.map($n=>$n.file)},{signal:Oe,onStatus:Ge,context:Ne}));if(nt.current){jt("canceled");return}if(!te)throw new Error(T.I18n.get(D.error??w.emptyResponseLabel));te.sessionId&&(Ke.current={id:te.sessionId,storedAt:Date.now()});let xe={id:te.metadata?.messageId||wt("assistant"),role:"assistant",content:te.result||"",citations:te.citations,createdAt:Date.now()};Ie(Oe=>[...Oe.map(It=>It.id===C?{...It,clientStatus:void 0}:It),xe]),i(S)}catch(J){if(console.error("Error during ask()",J),nt.current||Ir(J)){jt("canceled");return}let te=J?.message?.trim()||T.I18n.get(w.unexpectedErrorLabel);Ie(xe=>[...xe.map(Ge=>Ge.id===C?{...Ge,clientStatus:void 0}:Ge),{id:wt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${te}`,createdAt:Date.now()}]),i(S)}finally{z(J=>J==="chat"?null:J),nt.current=!1,He.current&&He.current.focus(),$e()}},[D,Ta,Xe,Ue,W,$e,jt,w.emptyResponseLabel,w.unexpectedErrorLabel,ne]),Nn=(0,o.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),O&&qt())},[qt,O]),jn=(0,o.useCallback)(()=>{ft(!0)},[]);(0,o.useEffect)(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let Hn=(0,o.useCallback)(()=>{dt(t=>{let c=!t;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),c?(ht(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{ht(!1),ze.current=null})})):ht(!1),c})},[]),Gn=(0,o.useCallback)(t=>{ye(t.content),(async()=>(await Ra(t.attachments),Ie(c=>c.filter(v=>v.id!==t.id)),In(t.attachments),queueMicrotask(()=>He.current?.focus())))()},[Ra]),La=(0,o.useMemo)(()=>ue?I?(0,s.jsx)("img",{src:I,className:"ai-open-btn-icon",alt:T.I18n.get(w.askMeLabel||Z)}):(0,s.jsx)(we.IconMessage,{size:18}):null,[ue,I,w,Z,ne]),Fn=(0,o.useMemo)(()=>{let t=La,c=G?(0,s.jsx)(k.Text,{inherit:!0,children:Z}):null;if(!ue&&!c)return null;if(!ue)return c;if(!G)return t;switch(ae){case"top":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[t,c]});case"bottom":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[c,t]});case"right":return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[c,t]});default:return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[t,c]})}},[La,ue,G,Z,ae]),Wn=(0,o.useMemo)(()=>A,[A]),qn=(0,o.useMemo)(()=>!A,[A]),Yn=(0,o.useMemo)(()=>Se||(d?T.I18n.get(w.readyLabel):T.I18n.get(w.readyEmptyLabel)),[Se,d,w.readyLabel,w.readyEmptyLabel,ne]),Vn=(0,o.useMemo)(()=>A?T.I18n.get(w.cancelLabel):T.I18n.get(w.sendLabel),[A,w.cancelLabel,w.sendLabel,ne]),Jn=(0,o.useMemo)(()=>A?(0,s.jsx)(we.IconPlayerStop,{size:18}):(0,s.jsx)(we.IconSend,{size:18}),[A]),_n=(0,o.useCallback)(()=>{if(A){Wt();return}qt()},[A,Wt,qt]);return(0,o.useEffect)(()=>{if(!W||!Pe||!K)return;let t=()=>{let J=window.getComputedStyle(K).overflowY,te=J==="auto"||J==="scroll",xe=Math.ceil(K.scrollHeight),Oe=Math.floor(K.clientHeight),Ge=xe>Oe;return te&&Ge},c=!1,v=j=>{if(!t())return;j.preventDefault();let J=K.scrollHeight-K.clientHeight;K.scrollTop=Math.max(0,Math.min(J,K.scrollTop+j.deltaY))},u=()=>{let j=t();_e(j),j!==c&&(c=j,c?Pe.addEventListener("wheel",v,{passive:!1}):Pe.removeEventListener("wheel",v))};u();let C=new ResizeObserver(u);C.observe(K);let S=new MutationObserver(u);return S.observe(K,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{c&&Pe.removeEventListener("wheel",v),C.disconnect(),S.disconnect(),window.removeEventListener("resize",u)}},[W,Pe,K]),(0,o.useEffect)(()=>{let t=!1,c=va(P);if(!c){P==="nostorage"&&aa(),me(!0);return}return(async()=>{try{let v=c.getItem(Dt);if(!v){me(!0);return}let u=JSON.parse(v),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>ke*na){c.removeItem(Dt),await aa(),me(!0);return}let j=(Array.isArray(u.messages)?u.messages:[]).map(te=>te?.role==="user"&&te.clientStatus==="pending"?{...te,clientStatus:"canceled"}:te),J=await Sa(j);if(t){wn(J);return}Ie(J),i(C),u.session&&u.session.id&&(Ke.current=u.session)}catch(v){console.warn("[AiChatbot] Failed to load history",v);try{c.removeItem(Dt)}catch{}}finally{t||me(!0)}})(),()=>{t=!0}},[P,ke,Sa]),(0,o.useEffect)(()=>{if(!Je)return;let t=va(P);if(!t)return;let c=re.current;if(!c)return;if(Date.now()-c>ke*na){try{t.removeItem(Dt)}catch{}ya(new Set);return}let v=N.map(({attachments:S,...j})=>({...j,attachments:S?.map(({objectUrl:J,blob:te,...xe})=>xe)})),u={version:1,lastUserSentAt:c,session:Ke.current,messages:v};try{t.setItem(Dt,JSON.stringify(u))}catch{}let C=new Set;v.forEach(S=>{S.attachments?.forEach(j=>{j.blobId&&C.add(j.blobId)})}),ya(C)},[Je,N,pt,P,ke]),l&&!Q||!l&&Q?null:(0,s.jsxs)(k.Group,{className:et,children:[!W&&(0,s.jsx)(k.Button,{variant:"filled",className:G?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:jn,"aria-label":Z,title:Z,"data-ai-kit-open-button":!0,children:Fn}),W&&(0,s.jsx)(k.Modal.Root,{ref:qe,opened:W,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:De,className:et+" ai-chat-container"+(Re?" maximized":"")+(Re&&ct?" ai-max-enter":""),portalProps:{target:a,reuseTargetNode:!0},"data-ai-kit-theme":oe,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:Ct,children:[(0,s.jsxs)(k.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(k.Modal.Title,{className:"ai-chat-title",children:ve}),(0,s.jsxs)(k.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(k.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:Hn,title:Re?T.I18n.get(w.restoreSizeLabel):T.I18n.get(w.maximizeLabel),"aria-label":Re?T.I18n.get(w.restoreSizeLabel):T.I18n.get(w.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Re?(0,s.jsx)(we.IconMinimize,{size:16}):(0,s.jsx)(we.IconMaximize,{size:16})}),(0,s.jsx)(k.Modal.CloseButton,{"aria-label":T.I18n.get(w.closeChatLabel)})]})]}),(0,s.jsxs)(k.Modal.Body,{className:"ai-chat-scroll",ref:Rt,"data-scrollable":Kt?"true":"false",children:[N.map(t=>{let c=t.role==="user",v=c&&t.clientStatus==="canceled"&&t.id===Dn;return(0,s.jsx)(k.Group,{justify:c?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>We(t.id),onMouseLeave:()=>We(u=>u===t.id?null:u),children:(0,s.jsxs)(k.Stack,{gap:4,w:"100%",style:{alignItems:c?"flex-end":"flex-start"},children:[(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(k.Text,{className:"ai-chat-header",children:[(0,s.jsx)(k.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:c?T.I18n.get(w.userLabel):T.I18n.get(w.assistantLabel)}),"\xA0",(0,s.jsx)(k.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(Sn.default,{remarkPlugins:[Rn.default],children:t.content}):(0,s.jsx)(k.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(k.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>ia(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||T.I18n.get("View image"),"aria-label":u.name||T.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:T.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(k.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(k.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(k.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:T.I18n.get("Audio no longer available")})},u.id))]}),v&&(0,s.jsxs)(k.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:T.I18n.get(w.notSentLabel)})}),kt===t.id&&(0,s.jsx)(k.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Gn(t),title:T.I18n.get(w.editLabel),"aria-label":T.I18n.get(w.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(we.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(k.Stack,{className:"ai-citations",children:[(0,s.jsx)(k.Text,{fw:"bold",size:"sm",mb:"xs",children:T.I18n.get(w.referencesLabel)}),(0,s.jsx)(k.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let S=u.sourceUrl||u.url,j=u.title||S||`${T.I18n.get(w.referenceLabel)} #${C+1}`;return(0,s.jsxs)(k.List.Item,{children:[S?(0,s.jsx)(k.Anchor,{href:S,target:"_blank",rel:"noreferrer",children:j}):(0,s.jsx)(k.Text,{children:j}),u.snippet?(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(k.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(k.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>xa(t.id,"accepted"),"aria-label":T.I18n.get(w.acceptResponseLabel),disabled:D.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(k.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>xa(t.id,"rejected"),"aria-label":T.I18n.get(w.rejectResponseLabel),disabled:D.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Wn&&(0,s.jsx)(k.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble typing",children:[Nt?(0,s.jsx)(k.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:Nt})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),qn&&(0,s.jsx)(k.Group,{className:"ai-status-line",children:(0,s.jsx)(k.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:Yn})})}),(0,s.jsxs)(k.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(k.Modal,{opened:le,onClose:za,centered:!0,title:T.I18n.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[(0,s.jsx)(k.Text,{size:"sm",children:T.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(k.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(k.Button,{variant:"default",onClick:za,"data-ai-kit-no-button":!0,children:T.I18n.get("No")}),(0,s.jsx)(k.Button,{color:"var(--ai-kit-color-danger, red)",onClick:On,disabled:!d&&!A,"data-ai-kit-yes-button":!0,children:T.I18n.get("Yes")})]})]}),(0,s.jsx)(k.Group,{children:(0,s.jsx)(k.Textarea,{className:"ai-message",ref:He,placeholder:Ce,value:F,onChange:t=>{ye(t.target.value),M&&Ue()},onKeyDown:Nn,rows:3,disabled:Ae||!!M})}),Aa&&Ae&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:T.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${St}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Aa&&M&&!Ae&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[T.I18n.get("Audio recorded")," (",Math.round(M.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:M.objectUrl})]}),(0,s.jsxs)(k.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(k.Group,{justify:"flex-start",children:(0,s.jsx)(k.Button,{variant:"light",leftSection:(0,s.jsx)(we.IconTrash,{size:18}),onClick:Un,disabled:!d&&!A,"data-ai-kit-reset-button":!0,children:T.I18n.get(w.resetLabel)})}),(0,s.jsxs)(k.Group,{justify:"flex-end",children:[Aa&&(0,s.jsx)(s.Fragment,{children:M?(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconX,{size:18}),onClick:Ue,disabled:A,title:T.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:T.I18n.get("Clear")}):(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconMicrophone,{size:18}),onClick:Ae?Ot:Ut,disabled:A,title:Ae?T.I18n.get("Stop recording"):T.I18n.get("Record audio"),color:Ae?"red":void 0,"data-ai-kit-microphone-button":!0,children:Ae?T.I18n.get("Stop"):T.I18n.get("Record")})}),V>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconPaperclip,{size:18}),onClick:()=>rt.current?.click(),disabled:Y.length>=V||A||Ae||!!M,title:T.I18n.get(w.addImageLabel),"data-ai-kit-add-image-button":!0,children:T.I18n.get(w.addLabel)}),(0,s.jsx)(k.Input,{ref:rt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:En})]}),(0,s.jsx)(k.Button,{leftSection:Jn,variant:"filled",onClick:_n,disabled:!A&&!O,"data-ai-kit-send-button":!0,children:Vn})]})]}),xt.length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:xt.map(({url:t,title:c},v)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":c||T.I18n.get("View image"),onClick:()=>ia(t,c),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),ia(t,c))},children:(0,s.jsx)(k.Button,{variant:"white",onClick:u=>{u.stopPropagation(),Bn(v)},"aria-label":T.I18n.get(w.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:T.I18n.get(w.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},Y[v]?.id??v))})]})]})}),(0,s.jsx)(k.Modal,{opened:!!ge,onClose:Kn,centered:!0,size:"auto",title:ge?.title||T.I18n.get("Image preview"),children:ge&&(0,s.jsx)("img",{src:ge.url,alt:ge.title||T.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},zn=vt(Cr,{showOpenButton:!0,variation:"modal"});var y=require("@mantine/core"),Tt=require("@smart-cloud/ai-kit-core"),X=require("aws-amplify/utils"),x=require("react"),xn=Ye(require("react-markdown"),1),Ln=Ye(require("rehype-raw"),1),Pn=Ye(require("remark-gfm"),1),Ve=require("@tabler/icons-react");var f=require("react/jsx-runtime");X.I18n.putVocabularies(yt);var Cn=!1;function xr(e){let a=e?.citations?.docs??[],g=e?.citations?.chunks??[],l=new Map;for(let n of a)l.set(n.docId,{doc:n,chunks:[]});for(let n of g){let h=l.get(n.docId);h?h.chunks.push(n):l.set(n.docId,{doc:{docId:n.docId},chunks:[n]})}return Array.from(l.values())}function wa(e){return!!e&&/[\p{L}\p{N}_]/u.test(e)}function Lr(e,a){let g=e.length;if(a<=0)return 0;if(a>=g)return g;let l=e[a-1]??"",n=e[a]??"";if(wa(l)&&wa(n)){let h=a;for(;h<g&&wa(e[h]??"");)h++;return h}return a}function Pr(e){let a=globalThis?.CSS?.escape;return typeof a=="function"?a(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}var Mr=e=>{let{autoRun:a=!0,context:g,title:l,showOpenButton:n=!1,openButtonTitle:h,showOpenButtonTitle:I=!0,openButtonIcon:G,showOpenButtonIcon:ue=!0,searchButtonIcon:oe,showSearchButtonTitle:ne=!0,showSearchButtonIcon:ie=!0,showSources:Ne=!0,topK:se=10,getSearchText:L,enableUserFilters:p=!1,availableCategories:P,availableTags:ke,variation:ee,rootElement:ae,colorMode:be,language:w,onClose:D,onClickDoc:F}=e,[ye,Y]=(0,x.useState)(!n),[Te,M]=(0,x.useState)(""),[_,Ae]=(0,x.useState)(!1),[de,St]=(0,x.useState)(null),[Ze,lt]=(0,x.useState)(0),Qe=(0,x.useRef)(null),je=(0,x.useRef)([]),Le=(0,x.useRef)(null),E=(0,x.useRef)(null),[N,Ie]=(0,x.useState)(!1),[Se,Be]=(0,x.useState)([]),[le,ut]=(0,x.useState)([]),[Re,dt]=(0,x.useState)([]),[ct,ht]=(0,x.useState)(""),[W,ft]=(0,x.useState)(null),[U,gt]=(0,x.useState)(!1),ge=(0,x.useRef)(null),at=(0,x.useRef)(null),Je=1440*60*1e3,{busy:me,error:Pe,statusEvent:Ct,result:K,run:Rt,cancel:Kt,reset:_e}=zt(),pe=(0,x.useRef)(!1),z=(0,x.useRef)([]),mt=K?.sessionId,ze=K?.citations?.docs??[],nt=K?.citations?.chunks??[],kt=K?.citations?.anchors??[],We=K?.result??"",rt=(0,x.useMemo)(()=>{if(ie)return oe?.trim()?(0,f.jsx)("img",{src:oe,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,f.jsx)(Ve.IconSearch,{size:18})},[oe,ie]),He=(0,x.useMemo)(()=>(w&&X.I18n.setLanguage(w||"en"),X.I18n.get(l||"Search with AI-Kit")),[w]),Ke=(0,x.useMemo)(()=>Ct?X.I18n.get("Searching\u2026"):null,[w,Ct]),qe=(0,x.useMemo)(()=>Te||L,[Te,L]),ce=(0,x.useMemo)(()=>{if(me||!ye)return!1;let d=typeof qe=="function"?qe():qe;return!!(d&&d.trim().length>0||de)},[qe,me,de,ye]),Xe=(0,x.useMemo)(()=>{if(!W)return!1;let d=Object.keys(W.allowedCategories).length>0,A=W.allowedTags.length>0;return d||A},[W]),Ue=(0,x.useMemo)(()=>Se.length===0||!W?[]:Se.flatMap(d=>W.allowedCategories[d]||[]).filter((d,A,O)=>O.indexOf(d)===A),[Se,W]),Ut=(0,x.useCallback)(async()=>{try{M("");let d=await navigator.mediaDevices.getUserMedia({audio:!0}),A=new MediaRecorder(d,{mimeType:"audio/webm"}),O=new AudioContext,Z=O.createMediaStreamSource(d),ve=O.createAnalyser();ve.fftSize=2048,ve.smoothingTimeConstant=.8,Z.connect(ve),Le.current=O,E.current=ve;let Ce=new Uint8Array(ve.fftSize),et=()=>{if(!E.current)return;E.current.getByteTimeDomainData(Ce);let Me=0;for(let xt=0;xt<Ce.length;xt++){let Nt=(Ce[xt]-128)/128;Me+=Nt*Nt}let $e=Math.sqrt(Me/Ce.length),De=Math.min(100,$e*200);lt(De),ge.current=requestAnimationFrame(et)};et(),je.current=[],A.ondataavailable=Me=>{Me.data.size>0&&je.current.push(Me.data)},A.onstop=()=>{let Me=new Blob(je.current,{type:"audio/webm"});St(Me),d.getTracks().forEach($e=>$e.stop()),ge.current&&(cancelAnimationFrame(ge.current),ge.current=null),Le.current&&(Le.current.close(),Le.current=null),E.current=null,lt(0)},Qe.current=A,A.start(),Ae(!0)}catch(d){console.error("Failed to start recording:",d)}},[]),Ot=(0,x.useCallback)(()=>{Qe.current&&_&&(Qe.current.stop(),Ae(!1))},[_]),pt=(0,x.useCallback)(()=>{St(null),je.current=[],lt(0),at.current=null},[]);(0,x.useEffect)(()=>()=>{ge.current&&cancelAnimationFrame(ge.current),Le.current&&Le.current.close()},[]),(0,x.useEffect)(()=>{if(!p)return;if(P||ke){ft({allowedCategories:P||{},allowedTags:ke||[]});return}(async()=>{gt(!0);try{let A=await(0,Tt.resolveBackend)();if(!A.available){console.error("Backend not available for metadata options");return}let O={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:A.available,backendTransport:A.transport,backendApiName:A.apiName,backendBaseUrl:A.baseUrl,reason:A.reason??""},Z=await(0,Tt.dispatchBackend)(O,g??"frontend","/kb/metadata-options","GET",null,{});ft({allowedCategories:Z.allowedCategories||{},allowedTags:Z.allowedTags||[]})}catch(A){console.error("Failed to load metadata options:",A)}finally{gt(!1)}})()},[p,P,ke,g]);let i=(0,x.useCallback)(async()=>{let d;if(!de){if(d=typeof qe=="function"?qe():qe,!d)return;M(d)}let A=Date.now(),O=de&&at.current?.blob===de&&A-at.current.uploadTimestamp<Je;de&&!O&&(at.current={blob:de,uploadTimestamp:A}),_e(),await Rt(async({signal:Z,onStatus:ve})=>await(0,Tt.sendSearchMessage)({sessionId:mt,...d&&{query:d},...de&&{audio:de},topK:se,...p&&{userSelectedCategories:Se},...p&&le.length>0&&{userSelectedSubcategories:le},...p&&Re.length>0&&{userSelectedTags:Re}},{signal:Z,onStatus:ve,context:g}))},[g,qe,de,Rt,_e,se,mt,p,Se,le,Re]),R=(0,x.useCallback)(async()=>{Y(!1),_e(),n||D()},[D,_e,pe,n]);(0,x.useEffect)(()=>{!a||!ce||me||pe.current||(pe.current=!0,queueMicrotask(()=>{i()}))},[me,pe,ce,a,i]),(0,x.useEffect)(()=>{ce||(pe.current=!0)},[ce]),(0,x.useEffect)(()=>{let d=z.current,A=Se;(d.length!==A.length||!A.every(Z=>d.includes(Z)))&&d.length>0&&_e(),z.current=[...A]},[Se,_e]);let $=(0,x.useMemo)(()=>xr(K),[K]),re=(0,x.useMemo)(()=>{let d=new Map;return ze.forEach((A,O)=>{A?.docId&&d.set(A.docId,O+1)}),d},[ze]),q=(0,x.useMemo)(()=>{let d=new Map;return nt.forEach(A=>{A?.chunkId&&A?.docId&&d.set(A.chunkId,A.docId)}),d},[nt]),he=(0,x.useMemo)(()=>{if(!We)return"";if(!kt.length||re.size===0)return We;let d=[...kt].filter(Z=>Array.isArray(Z?.chunkIds)&&Z?.span?.end!==void 0).sort((Z,ve)=>{let Ce=Z.span?.end??0,et=ve.span?.end??0;return Ce-et}),A=0,O=[];for(let Z of d){let ve=Z.span?.end;if(typeof ve!="number"||ve<A)continue;let Ce=Array.from(new Set((Z.chunkIds??[]).map(De=>De?q.get(De):void 0).map(De=>De?re.get(De):void 0).filter(De=>typeof De=="number")));if(!Ce.length)continue;let et=Math.min(ve,We.length),Me=Lr(We,et);O.push(We.slice(A,Me));let $e=Ce.map(De=>`<a href="#docsearch-source-${De}" data-docsearch-cite="${De}" style="color: inherit; text-decoration: none;">${De}</a>`).join(",");O.push(`<sup>${$e}</sup>`),A=Me}return O.push(We.slice(A)),O.join("")},[kt,We,re,q]),Q=ee==="modal"?y.Modal.Root:y.Group,V=ee==="modal"?y.Modal.Content:y.Group,fe=ee==="modal"?y.Modal.Body:y.Group;return(0,x.useEffect)(()=>{if(!(ee!=="modal"||!ye))return document.body.style.overflow="hidden",document.body.onkeydown=d=>{d.key==="Escape"&&(d.preventDefault(),R())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[R,ee,ye]),(0,f.jsxs)(f.Fragment,{children:[n&&(0,f.jsx)(y.Button,{leftSection:ue&&(G?(0,f.jsx)("span",{dangerouslySetInnerHTML:{__html:G}}):(0,f.jsx)(Ve.IconSearch,{size:18})),className:I?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ye,onClick:()=>Y(!0),"data-ai-kit-open-button":!0,children:I&&X.I18n.get(h||He)}),ye&&(0,f.jsxs)(Q,{opened:!0,className:"doc-search-root",onClose:R,padding:"md",gap:"md",size:"xl",portalProps:ee==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":be,"data-ai-kit-variation":ee,children:[ee==="modal"&&(0,f.jsx)(y.Modal.Overlay,{}),(0,f.jsxs)(V,{w:"100%",style:{left:0,...ee==="modal"&&!K?.result&&{overflow:"visible"}},children:[ee==="modal"&&(0,f.jsxs)(y.Modal.Header,{style:{zIndex:1e3},children:[(0,f.jsx)(Tt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,f.jsx)(y.Modal.Title,{children:X.I18n.get(He)}),(0,f.jsx)(y.Modal.CloseButton,{})]}),(0,f.jsx)(fe,{w:"100%",style:{zIndex:1001,...ee==="modal"&&!K?.result&&{overflow:"visible"}},children:(0,f.jsx)(Pt,{enabled:ee!=="modal",working:me,variation:ee,children:(0,f.jsx)(y.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,f.jsxs)(y.Stack,{gap:"sm",children:[ee!=="modal"&&(0,f.jsxs)(y.Group,{justify:"space-between",children:[(0,f.jsx)(y.Title,{order:4,style:{margin:0},children:X.I18n.get(He)}),n&&(0,f.jsx)(y.Button,{variant:"subtle",color:"gray",size:"xs",onClick:R,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":X.I18n.get("Close"),children:(0,f.jsx)(Ve.IconX,{size:18,style:{color:be==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),(0,f.jsxs)(y.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,f.jsx)(y.TextInput,{style:{flex:1},value:Te,onChange:d=>{M(d.currentTarget.value),de&&pt()},placeholder:de?X.I18n.get("Audio recorded"):X.I18n.get("Search the documentation\u2026"),disabled:me||_||!!de,onKeyDown:d=>{d.key==="Enter"&&ce&&(d.preventDefault(),i())}}),Cn&&(0,f.jsx)(f.Fragment,{children:de?(0,f.jsx)(y.Button,{variant:"outline",size:"sm",color:"red",onClick:pt,disabled:me,title:X.I18n.get("Clear audio"),children:(0,f.jsx)(Ve.IconMicrophoneOff,{size:18})}):(0,f.jsx)(y.Button,{variant:_?"filled":"outline",size:"sm",color:_?"red":"gray",onClick:_?Ot:Ut,disabled:me,title:_?X.I18n.get("Stop recording"):X.I18n.get("Record audio"),style:_?{transform:`scale(${1+Ze/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,f.jsx)(Ve.IconMicrophone,{size:18})})}),(0,f.jsx)(y.Button,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{i()},disabled:!ce,className:ne?"doc-search-button":"doc-search-button-no-title",children:ne?X.I18n.get("Search"):null}),me?(0,f.jsx)(y.Button,{variant:"outline",size:"sm",onClick:Kt,children:X.I18n.get("Stop")}):null]}),!me&&!Pe&&!K?.result?(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:X.I18n.get("Enter a search query to start.")}):null,p&&W&&Xe&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsx)(y.Button,{variant:"subtle",size:"xs",onClick:()=>Ie(!N),leftSection:N?(0,f.jsx)(Ve.IconChevronDown,{size:14}):(0,f.jsx)(Ve.IconChevronRight,{size:14}),style:{alignSelf:"flex-start"},children:X.I18n.get("Filters")}),(0,f.jsx)(y.Collapse,{in:N,children:(0,f.jsxs)(y.Stack,{gap:"md",children:[Object.keys(W.allowedCategories).length>0&&(0,f.jsxs)("div",{children:[(0,f.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:X.I18n.get("Categories")}),(0,f.jsx)(y.Group,{gap:"md",children:Object.keys(W.allowedCategories).map(d=>(0,f.jsx)(y.Checkbox,{label:X.I18n.get(d),checked:Se.includes(d),onChange:A=>{if(A.currentTarget.checked)Be([...Se,d]);else{Be(Se.filter(Z=>Z!==d));let O=W.allowedCategories[d]||[];ut(le.filter(Z=>!O.includes(Z)))}},disabled:me||U},d))})]}),Ue.length>0&&(0,f.jsxs)("div",{children:[(0,f.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:X.I18n.get("Subcategories")}),(0,f.jsx)(y.Group,{gap:"md",children:Ue.map(d=>(0,f.jsx)(y.Checkbox,{label:X.I18n.get(d),checked:le.includes(d),onChange:A=>{A.currentTarget.checked?ut([...le,d]):ut(le.filter(O=>O!==d))},disabled:me||U},d))})]}),W.allowedTags.length>0&&(0,f.jsx)(y.MultiSelect,{label:X.I18n.get("Tags"),placeholder:X.I18n.get("Select or type tags..."),data:W.allowedTags.map(d=>({value:d,label:X.I18n.get(d)})),value:Re,onChange:dt,searchValue:ct,onSearchChange:ht,disabled:me||U,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Cn&&(0,f.jsxs)(f.Fragment,{children:[_&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsxs)(y.Text,{size:"xs",c:"dimmed",children:[X.I18n.get("Recording...")," \u{1F3A4}"]}),(0,f.jsx)(y.Progress,{value:Ze,size:"sm",color:"red",animated:!0,striped:!0})]}),de&&!_&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsx)(y.Text,{size:"xs",c:"dimmed",children:X.I18n.get("Recorded audio:")}),(0,f.jsx)("audio",{controls:!0,src:URL.createObjectURL(de),className:"ai-kit-audio-player"})]})]}),Pe?(0,f.jsx)(y.Alert,{color:"red",title:X.I18n.get("Error"),children:Pe}):null,me&&Ke&&(0,f.jsx)(Pt,{enabled:ee==="modal",working:!0,variation:ee,children:(0,f.jsxs)(y.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,f.jsx)(y.Loader,{size:"sm"}),(0,f.jsx)(y.Text,{size:"sm",c:"dimmed",children:Ke})]})}),K?.result?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(y.Divider,{}),(0,f.jsxs)(y.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:X.I18n.get("AI Summary")}),(0,f.jsx)(xn.default,{remarkPlugins:[Pn.default],rehypePlugins:[Ln.default],components:{a:({href:d,children:A,...O})=>{let Z=typeof d=="string"&&d.startsWith("#docsearch-source-");return(0,f.jsx)("a",{href:d,...O,onClick:ve=>{if(!Z)return;ve.preventDefault();let Ce=d.slice(1),et=`#${Pr(Ce)}`;(ae??document).querySelector?.(et)?.scrollIntoView({block:"start",behavior:"smooth"})},children:A})}},"data-doc-search-result-content":!0,children:he||We})]})]}):null,Ne&&(K?.citations?.docs?.length||K?.citations?.chunks?.length)?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(y.Divider,{}),(0,f.jsxs)(y.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:X.I18n.get("Sources")}),$.map(({doc:d})=>{let A=d.sourceUrl?.trim()||void 0,O=d.docId?re.get(d.docId):void 0,Z=d.title?.trim()||d.docId,ve=(0,f.jsxs)(y.Text,{fw:600,style:{display:"inline"},children:[O?`${O}. `:"",Z]});return(0,f.jsx)(y.Paper,{withBorder:!0,radius:"md",p:"sm",id:O?`docsearch-source-${O}`:void 0,children:(0,f.jsx)(y.Stack,{gap:"xs",children:(0,f.jsx)(y.Group,{justify:"space-between",align:"flex-start",children:(0,f.jsxs)(y.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[A?(0,f.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{F&&(Ce.preventDefault(),F?.(d))},"data-doc-search-source-title":!0,children:ve}):ve,(0,f.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{F&&(Ce.preventDefault(),F?.(d))},"data-doc-search-source-url":!0,children:d.sourceUrl}),d.author?(0,f.jsx)(y.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:d.author}):null,d.description?(0,f.jsx)(y.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:d.description}):null]})})})},d.docId)})]})]}):null,(0,f.jsx)(Jt,{variation:ee})]})})})})]})]})]})},Mn=vt(Mr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
31
+ Follow these additional instructions: ${le}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),q=await z.run(async({signal:V,onStatus:fe})=>(await(0,H.prompt)({messages:re,images:[Be],outputLanguage:"en",responseConstraint:cr},{signal:V,onStatus:fe,context:P,modeOverride:i,onDeviceTimeoutOverride:n})).result);if(!q){N("");return}let he=(U&&U!=="auto"?U:null)||At(),Q=Lt(q).trim();try{_("Translating result...");let V=await z.run(async({signal:fe})=>await mr(Q,he,{signal:fe,context:P,modeOverride:i,onDeviceTimeoutOverride:n,silent:!0}));N(V)}catch(V){N(Q),console.warn("AI Kit: failed to parse SEO JSON",V)}break}}}catch($){Le($ instanceof Error?$.message:r.I18n.get("An unknown error occurred."))}_(void 0)},[F,z,le,ge,U,Ie,Je,P,p,Pe,ct,pe,Te]),nt=(0,B.useCallback)(async()=>{await ze("backend-only")},[ze]),kt=(0,B.useCallback)(i=>{switch(p){case"proofread":return(0,m.jsx)(it.IconCircleDashedCheck,{className:i});case"translate":return(0,m.jsx)(it.IconLanguage,{className:i});case"summarize":return(0,m.jsx)(it.IconSum,{className:i});case"rewrite":case"write":return(0,m.jsx)(it.IconPencilCode,{className:i});case"generateImageMetadata":case"generatePostMetadata":return(0,m.jsx)(it.IconSeo,{className:i});default:return(0,m.jsx)(H.AiKitFeatureIcon,{mode:p,className:i})}},[p]),We=(0,B.useCallback)(()=>{switch(p){case"proofread":return z.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return z.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return z.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return z.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return z.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[F,z.lastSource,p]),rt=(0,B.useCallback)(()=>{switch(p){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[F,p]),He=(0,B.useCallback)(async()=>{de(!1),N(null),Le(null),K.current=!1,z.reset(),G||be()},[be,K,z,G]),Ke=(0,B.useCallback)(async()=>{z.busy&&z.cancel()},[z.busy]);(0,B.useEffect)(()=>{!Ae||!g||!pe||z.busy||E||K.current||(K.current=!0,queueMicrotask(()=>{ze(ke)}))},[z.busy,K,Ae,pe,g,E,ze,ke]),(0,B.useEffect)(()=>{Te&&p!=="proofread"&&(pe||(Ze(!0),K.current=!0))},[Te,pe,p]),(0,B.useEffect)(()=>{let i=!0;return(async()=>{try{await(0,H.waitForAiKitReady)();let R=await ua();i&&Qe(R)}catch(R){console.error(R),i&&Qe(!1)}})(),()=>{i=!1}},[]);let qe=(0,B.useMemo)(()=>{let i=[];if(p==="translate"){let R=H.LANGUAGE_OPTIONS.find($=>$.value===ct)?.label;i.push(r.I18n.get("Input language")+": "+(R?r.I18n.get(R):"auto"))}if(U&&Y?.outputLanguage){let R=H.LANGUAGE_OPTIONS.find($=>$.value===U)?.label;i.push(r.I18n.get("Output language")+": "+(R?r.I18n.get(R):U))}return p==="summarize"&&Pe&&Y?.type&&i.push(r.I18n.get("Type")+": "+r.I18n.get(Pe)),(p==="write"||p==="rewrite")&&Je&&Y?.tone&&i.push(r.I18n.get("Tone")+": "+r.I18n.get(Je)),(p==="write"||p==="rewrite"||p==="summarize")&&ge&&Y?.length&&i.push(r.I18n.get("Length")+": "+r.I18n.get(ge)),le?.trim()&&Y?.instructions&&i.push(r.I18n.get("Instructions")+": \u2713"),i.length?i.join(" \u2022 "):r.I18n.get("No overrides")},[F,p,ct,U,Pe,Je,ge,le]),ce={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Xe=h==="modal"?b.Modal.Root:b.Group,Ue=h==="modal"?b.Modal.Content:b.Group,Ut=h==="modal"?b.Modal.Body:b.Group,Ot=L==="collapse"?b.Collapse:b.Stack,pt=L==="horizontal"?b.Group:b.Stack;return(0,B.useEffect)(()=>{if(!(h!=="modal"||!Ae))return document.body.style.overflow="hidden",document.body.onkeydown=i=>{i.key==="Escape"&&(i.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,h]),(0,m.jsxs)(m.Fragment,{children:[G&&(0,m.jsx)(b.Button,{leftSection:oe&&(ie?(0,m.jsx)("span",{dangerouslySetInnerHTML:{__html:ie}}):kt()),className:ue?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:Ae,onClick:()=>de(!0),"data-ai-kit-open-button":!0,children:ue&&r.I18n.get(ne||Rt)}),Ae&&(0,m.jsxs)(Xe,{opened:!0,className:"ai-feature-root",onClose:He,padding:"md",gap:"md",size:"md",portalProps:h==="modal"?{target:ye,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":ee,"data-ai-kit-variation":h,children:[h==="modal"&&(0,m.jsx)(b.Modal.Overlay,{}),(0,m.jsxs)(Ue,{w:"100%",style:{left:0},children:[h==="modal"&&(0,m.jsxs)(b.Modal.Header,{style:{zIndex:1e3},children:[kt("ai-feature-title-icon"),(0,m.jsx)(b.Modal.Title,{children:r.I18n.get(Rt)}),(0,m.jsx)(b.Modal.CloseButton,{})]}),(0,m.jsx)(Ut,{w:"100%",style:{zIndex:1001},children:(0,m.jsxs)(Pt,{enabled:h!=="modal",working:z.busy,variation:h,children:[(0,m.jsxs)(b.Stack,{gap:"sm",mb:"sm",p:"sm",children:[je&&(0,m.jsx)(b.Alert,{color:"red",children:r.I18n.get(je)}),Te&&p!=="proofread"&&(0,m.jsxs)(b.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,m.jsxs)(b.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>Ze(i=>!i):void 0,children:[L==="collapse"&&(0,m.jsxs)(b.Stack,{gap:0,children:[(0,m.jsx)(b.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,m.jsx)(b.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:qe})]}),L==="collapse"&&(0,m.jsx)(b.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:i=>{i.stopPropagation(),Ze(R=>!R)},children:St?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,m.jsxs)(Ot,{in:St,children:[L==="collapse"&&(0,m.jsx)(b.Divider,{my:"sm"}),(0,m.jsxs)(pt,{gap:"xs",justify:"space-between",children:[p==="write"&&Y?.text&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.TextInput,{size:"xs",className:"ai-feature-option",styles:ce,disabled:z.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:Ie||"",onChange:i=>{let R=i.target.value;Se(R),D?.({text:R})}})}),(p==="write"||p==="rewrite"||p==="generateImageMetadata"||p==="generatePostMetadata")&&Y?.instructions&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.TextInput,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:le||"",onChange:i=>{let R=i.target.value;ut(R),D?.({instructions:R})}})}),p==="translate"&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ce,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...H.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,R)=>i.label.localeCompare(R.label))],value:ct||"auto",onChange:i=>{let R=i;ht(R),dt(void 0),D?.({inputLanguage:R})}})}),Y?.outputLanguage&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ce,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[p==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...H.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,R)=>i.label.localeCompare(R.label))],value:U||yn.settings.defaultOutputLanguage||(p==="rewrite"?"auto":""),onChange:i=>{let R=i;gt(R),dt(void 0),D?.({outputLanguage:R})}})}),p==="summarize"&&Y?.type&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:Pe||"key-points",onChange:i=>{let R=i;Ct(R),D?.({type:R})}})}),(p==="write"||p==="rewrite")&&Y?.tone&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:p==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:Je||(p==="write"?"neutral":"as-is"),onChange:i=>{let R=i;me(R),D?.({tone:R})}})}),(p==="write"||p==="rewrite"||p==="summarize")&&Y?.length&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:p==="write"||p==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:ge||(p==="rewrite"?"as-is":"short"),onChange:i=>{let R=i;at(R),D?.({length:R})}})}),p==="summarize"||p==="write"||p==="rewrite"&&Y?.outputFormat&&(0,m.jsx)(b.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,m.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ce,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:W||"markdown",onChange:i=>{let R=i;ft(R),D?.({outputFormat:R})}})})]})]})]}),z.busy&&mt&&(0,m.jsx)(Pt,{enabled:h==="modal",working:!0,variation:h,children:(0,m.jsxs)(b.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,m.jsx)(b.Loader,{size:"sm"}),(0,m.jsx)(b.Input.Label,{className:"ai-feature-status-text",children:mt})]})}),E&&(0,m.jsxs)(b.Stack,{mt:"md",children:[p==="proofread"&&(E.corrections.length===0?(0,m.jsx)(b.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,m.jsx)(mn,{original:Ie,corrections:E.corrections}),E.correctedInput?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,m.jsx)(b.Group,{c:"pre",className:"ai-feature-generated-content",children:E.correctedInput})]}):null]})),p==="generateImageMetadata"&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:E.alt_text||"",onChange:i=>N({...E,alt_text:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:E.title||"",onChange:i=>N({...E,title:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:E.caption||"",onChange:i=>N({...E,caption:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:E.description||"",onChange:i=>N({...E,description:i.target.value})})]}),p==="generatePostMetadata"&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:E.title||"",onChange:i=>N({...E,title:i.target.value})}),(0,m.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:E.excerpt||"",onChange:i=>N({...E,excerpt:i.target.value})})]}),p!=="proofread"&&p!=="generateImageMetadata"&&p!=="generatePostMetadata"&&typeof E=="string"&&(0,m.jsx)(An,{value:E,editable:!!l,onChange:i=>{N(i)}})]}),E===""&&(0,m.jsx)(An,{value:E,editable:!1})]}),(0,m.jsxs)(b.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[z.busy&&(0,m.jsx)(b.Button,{variant:"outline",size:"sm",onClick:Ke,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!z.busy&&(0,m.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!pe,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:We()}),!z.busy&&z.lastSource==="on-device"&&lt&&Ne&&(0,m.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!pe,onClick:nt,"data-ai-kit-regenerate-on-backend-button":!0,children:rt()}),!z.busy&&w&&(0,m.jsx)(b.Button,{variant:"outline",size:"sm",disabled:!E||p==="proofread"&&E.corrections.length===0,onClick:async()=>{w(W==="html"?await ea(E):E),He()},"data-ai-kit-accept-button":!0,children:r.I18n.get(se)}),(0,m.jsx)(b.Button,{variant:"default",size:"sm",onClick:He,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,m.jsx)(Jt,{variation:h})]})})]})]})]})};function An(e){let{value:a,editable:g,onChange:l}=e;return g?(0,m.jsxs)(b.Stack,{p:0,gap:"sm",children:[(0,m.jsx)(b.Input.Label,{children:r.I18n.get("Generated content")}),(0,m.jsx)(b.Textarea,{value:a,onChange:n=>l?.(n.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,m.jsx)(b.Input.Label,{children:r.I18n.get("Preview")}),(0,m.jsx)(b.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,m.jsx)(ma.default,{remarkPlugins:[pa.default],children:a})})]}):(0,m.jsx)(b.Stack,{className:"ai-feature-generated-content",children:a?(0,m.jsx)(ma.default,{remarkPlugins:[pa.default],children:a}):(0,m.jsx)(b.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var vn=vt(hr);var k=require("@mantine/core"),we=require("@tabler/icons-react"),Bt=require("@smart-cloud/ai-kit-core"),Tn=require("@wordpress/data"),T=require("aws-amplify/utils"),o=require("react"),Sn=Ye(require("react-markdown"),1),Rn=Ye(require("remark-gfm"),1);var fr="ai-kit-chatbot-attachments",st="attachments";var ha=null;function kr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function ta(){if(!kr())return null;ha||(ha=new Promise(e=>{try{let a=window.indexedDB.open(fr,1);a.onerror=()=>e(null),a.onblocked=()=>e(null),a.onupgradeneeded=()=>{let g=a.result;g.objectStoreNames.contains(st)||g.createObjectStore(st,{keyPath:"id"})},a.onsuccess=()=>e(a.result)}catch(a){console.warn("[AiChatbot] IndexedDB is not available",a),e(null)}}));try{return await ha}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function fa(e,a){let g=await ta();return g?new Promise((l,n)=>{try{let h=g.transaction(st,e),I=h.objectStore(st),G=a(I);h.oncomplete=()=>l(G),h.onerror=()=>n(h.error),h.onabort=()=>n(h.error)}catch(h){n(h)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function ka(e,a,g){await vr();let l={id:e,blob:a,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await fa("readwrite",h=>(h.put(l),e))}async function ba(e){let a=await ta();return a?new Promise((g,l)=>{try{let n=a.transaction(st,"readonly"),h=n.objectStore(st).get(e);h.onsuccess=()=>{let I=h.result;g(I??null)},h.onerror=()=>l(h.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function br(e){await fa("readwrite",a=>{a.delete(e)})}async function aa(){await fa("readwrite",e=>{e.clear()})}async function ya(e){let a=await ta();a&&await new Promise((g,l)=>{try{let n=a.transaction(st,"readwrite"),h=n.objectStore(st),I=h.getAllKeys();I.onsuccess=()=>{let G=I.result;for(let ue of G){let oe=String(ue);e.has(oe)||h.delete(ue)}},I.onerror=()=>l(I.error),n.oncomplete=()=>g(),n.onerror=()=>l(n.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yr=50*1024*1024;async function Ar(){let e=await ta();return e?new Promise((a,g)=>{try{let l=e.transaction(st,"readonly"),n=l.objectStore(st).getAll();n.onsuccess=()=>{let h=n.result||[];a(h)},n.onerror=()=>g(n.error),l.onerror=()=>g(l.error),l.onabort=()=>g(l.error)}catch(l){g(l)}}).catch(a=>(console.warn("[AiChatbot] Failed to get all attachments",a),[])):[]}async function vr(){let e=await Ar();if(e.length===0)return;let a=e.sort((h,I)=>h.createdAt-I.createdAt),g=a.reduce((h,I)=>h+I.size,0),l=[],n=0;for(;g>yr&&n<a.length;){let h=a[n];h&&(l.push(h.id),g-=h.size),n++}for(let h of l)await br(h);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");T.I18n.putVocabularies(yt);var na=1440*60*1e3,Aa=!1,wr=1,Tr="localstorage",Dt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function wt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Sr=4,Rr=5*1024*1024,Ir=e=>{let a=(e?.name||"").toString(),g=(e?.code||"").toString(),l=(e?.message||"").toString();return a==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},zr=(e,a)=>{if(!e)return null;let g=e.step,l=T.I18n.get((e.message??"").trim()),n=typeof e.progress=="number"?e.progress:null,h=n==null?null:Math.round(n*100);switch(g){case"decide":return l||T.I18n.get("Checking capabilities...");case"on-device:init":return l||T.I18n.get("Initializing on-device AI...");case"on-device:download":return h==null?l||T.I18n.get("Downloading model..."):l||`${T.I18n.get("Downloading model...")} ${h}%`;case"on-device:ready":return l||T.I18n.get("On-device model ready...");case"on-device:run":return l||T.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return T.I18n.get(a.assistantThinkingLabel??oa.assistantThinkingLabel);case"done":return l||T.I18n.get("Done.");case"error":return l||T.I18n.get("An error occurred.");default:return l||null}};function va(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Et=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},ra=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},In=e=>{!e||e.length===0||e.forEach(a=>ra(a.objectUrl))},wn=e=>{e.forEach(a=>In(a.attachments))},Cr=e=>{let{rootElement:a,store:g,previewMode:l,title:n,openButtonTitle:h,openButtonIcon:I,showOpenButtonTitle:G=!0,showOpenButtonIcon:ue=!0,colorMode:oe,language:ne,onClose:ie,context:Ne,placeholder:se,maxImages:L,maxImageBytes:p,historyStorage:P=Tr,emptyHistoryAfterDays:ke=wr,labels:ee,openButtonIconLayout:ae="top",openButtonPosition:be="bottom-right"}=e,w=(0,o.useMemo)(()=>({...oa,...ee||{}}),[ee]),D=zt(),[F,ye]=(0,o.useState)(""),[Y,Te]=(0,o.useState)([]),[M,_]=(0,o.useState)(null),[Ae,de]=(0,o.useState)(!1),[St,Ze]=(0,o.useState)(0),lt=(0,o.useRef)(null),Qe=(0,o.useRef)([]),je=(0,o.useRef)(null),Le=(0,o.useRef)(null),E=(0,o.useRef)(null),[N,Ie]=(0,o.useState)([]),[Se,Be]=(0,o.useState)(null),[le,ut]=(0,o.useState)(!1),[Re,dt]=(0,o.useState)(!1),[ct,ht]=(0,o.useState)(!1),[W,ft]=(0,o.useState)(!1),[U,gt]=(0,o.useState)(!0),[ge,at]=(0,o.useState)(null),[Je,me]=(0,o.useState)(!1),[Pe,Ct]=(0,o.useState)(null),[K,Rt]=(0,o.useState)(null),[Kt,_e]=(0,o.useState)(!1),[pe,z]=(0,o.useState)(null),mt=(0,o.useRef)(pe);(0,o.useEffect)(()=>{mt.current=pe},[pe]);let ze=(0,o.useRef)(null),nt=(0,o.useRef)(!1),[kt,We]=(0,o.useState)(null),rt=(0,o.useRef)(null),He=(0,o.useRef)(null),Ke=(0,o.useRef)(null),qe=(0,o.useRef)(null),ce=(0,o.useCallback)(t=>{t.forEach(c=>ra(c.objectUrl))},[]),Xe=(0,o.useCallback)(()=>{ce(q.current),Te([]),rt.current&&(rt.current.value="")},[ce]),Ue=(0,o.useCallback)(()=>{he.current&&ra(he.current.objectUrl),_(null),Qe.current=[],Ze(0)},[]),Ut=(0,o.useCallback)(async()=>{try{ye(""),Ue();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),c=new MediaRecorder(t,{mimeType:"audio/webm"}),v=new AudioContext,u=v.createMediaStreamSource(t),C=v.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),je.current=v,Le.current=C;let S=new Uint8Array(C.fftSize),j=()=>{if(!Le.current)return;Le.current.getByteTimeDomainData(S);let te=0;for(let Ge=0;Ge<S.length;Ge++){let It=(S[Ge]-128)/128;te+=It*It}let xe=Math.sqrt(te/S.length),Oe=Math.min(100,xe*200);Ze(Oe),E.current=requestAnimationFrame(j)};j(),Qe.current=[];let J=Date.now();c.ondataavailable=te=>{te.data.size>0&&Qe.current.push(te.data)},c.onstop=()=>{let te=new Blob(Qe.current,{type:"audio/webm"}),xe=(Date.now()-J)/1e3,Oe=Et(te);Oe&&_({id:wt("composer-audio"),blob:te,objectUrl:Oe,duration:xe}),t.getTracks().forEach(Ge=>Ge.stop()),E.current&&(cancelAnimationFrame(E.current),E.current=null),je.current&&(je.current.close(),je.current=null),Le.current=null,Ze(0)},lt.current=c,c.start(),de(!0)}catch(t){console.error("Failed to start recording:",t)}},[Ue]),Ot=(0,o.useCallback)(()=>{lt.current&&Ae&&(lt.current.stop(),de(!1))},[Ae]);(0,o.useEffect)(()=>()=>{E.current&&cancelAnimationFrame(E.current),je.current&&je.current.close(),Ue()},[Ue]);let[pt,i]=(0,o.useState)(null),R=(0,o.useRef)(F),$=(0,o.useRef)(N),re=(0,o.useRef)(pt),q=(0,o.useRef)(Y),he=(0,o.useRef)(M);(0,o.useEffect)(()=>{R.current=F},[F]),(0,o.useEffect)(()=>{q.current=Y},[Y]),(0,o.useEffect)(()=>{he.current=M},[M]),(0,o.useEffect)(()=>{$.current=N},[N]),(0,o.useEffect)(()=>{re.current=pt},[pt]),(0,o.useEffect)(()=>{ne&&T.I18n.setLanguage(ne||"en")},[ne]);let Q=(0,Tn.useSelect)(()=>(0,Bt.getStoreSelect)(g).isShowChatbotPreview()),V=(0,o.useMemo)(()=>Math.max(0,L??Sr),[L]),fe=(0,o.useMemo)(()=>Math.max(0,p??Rr),[p]),d=N.length>0,A=(0,o.useMemo)(()=>D.busy&&pe==="chat",[D.busy,pe]),O=(0,o.useMemo)(()=>A?!1:F.trim().length>0||M!==null,[F,A,M]),Z=(0,o.useMemo)(()=>{let t=h||w.askMeLabel;return T.I18n.get(t)},[h,w.askMeLabel,ne]),ve=(0,o.useMemo)(()=>{let t=n||w.modalTitle;return T.I18n.get(t)},[n,w.modalTitle,ne]),Ce=(0,o.useMemo)(()=>{let t=se||w.placeholder;return T.I18n.get(t)},[se,w.placeholder,ne]),et=(0,o.useMemo)(()=>{let t="ai-docs-ask",c=`ai-open-btn--${be}`;return`${t} ${c}`},[be]),Me=(0,o.useCallback)(()=>{let t=qe.current;if(t)try{let c=window.innerHeight||document.documentElement.clientHeight,v=360,u=1e3,C=Math.floor(c*.8),S=Math.max(v,Math.min(C,u));t.style.height=`${S}px`}catch{}},[]),$e=(0,o.useCallback)(()=>{let t=K;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[K]),De=(0,o.useCallback)(()=>{ft(!1),Re&&dt(!1),ht(!1),ie?.()},[Re,ie]);(0,o.useEffect)(()=>{if(W)return Me(),window.addEventListener("resize",Me),()=>window.removeEventListener("resize",Me)},[W,Me]),(0,o.useEffect)(()=>{if(!(!W||!Re))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[W,Re,De]);let xt=(0,o.useMemo)(()=>Y.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[Y]);(0,o.useEffect)(()=>{d||gt(!0)},[d]),(0,o.useEffect)(()=>()=>{ce(q.current)},[ce]),(0,o.useEffect)(()=>{let t=K;if(!t)return;let c=()=>{let v=t.scrollHeight-(t.scrollTop+t.clientHeight);gt(v<20)};return t.addEventListener("scroll",c),()=>{t.removeEventListener("scroll",c)}},[W,K]),(0,o.useEffect)(()=>{if(!U)return;let t=K;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[N,D.busy,U,K]),(0,o.useEffect)(()=>{W||at(null)},[W]);let Nt=(0,o.useMemo)(()=>D.busy?zr(D.statusEvent,w)||T.I18n.get("Working\u2026"):null,[D.busy,D.statusEvent,ne,w]),Dn=(0,o.useMemo)(()=>{for(let t=N.length-1;t>=0;t--){let c=N[t];if(c.role==="user"&&c.clientStatus==="canceled")return c.id}return null},[N]),jt=(0,o.useCallback)(t=>{Ie(c=>{let v=[...c].map((S,j)=>({m:S,i:j})).reverse().find(S=>S.m.role==="user"&&S.m.clientStatus==="pending")?.i;if(v==null)return c;let u=c.slice(),C=u[v];return u[v]={...C,clientStatus:t??void 0},u})},[Ie]),Wt=(0,o.useCallback)(()=>{if(!(!D.busy||mt.current!=="chat")){nt.current=!0;try{D.cancel()}catch{}jt("canceled"),z(null),Be(null),$e()}},[D,jt,$e]),En=(0,o.useCallback)(t=>{let c=q.current,v=Array.from(t.target.files||[]),u=Math.max(0,V-c.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let S of v){if(C.length>=u)break;let j=/image\/(jpeg|png|gif|webp)/i.test(S.type),J=S.size<=fe,te=[...c,...C].some(Oe=>Oe.file.name===S.name&&Oe.file.size===S.size&&Oe.file.lastModified===S.lastModified);if(!j||!J||te)continue;let xe=Et(S);xe&&C.push({id:wt("composer-image"),file:S,objectUrl:xe})}C.length&&Te(S=>[...S,...C]),t.currentTarget.value=""},[V,fe]),Bn=(0,o.useCallback)(t=>{Te(c=>{if(t<0||t>=c.length)return c;let v=c[t];return v&&ra(v.objectUrl),c.filter((u,C)=>C!==t)})},[]),bt=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(Se)return bt.current&&(window.clearTimeout(bt.current),bt.current=null),bt.current=window.setTimeout(()=>{Be(null),bt.current=null},6e3),()=>{bt.current&&(window.clearTimeout(bt.current),bt.current=null)}},[Se]);let Ta=(0,o.useCallback)(async(t,c)=>{let v=P!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async S=>{let j=wt("attachment-image"),J;if(v)try{J=await ka(j,S.file,{name:S.file.name,type:S.file.type,size:S.file.size})??void 0}catch(xe){console.warn("[AiChatbot] Failed to persist image",xe)}let te=Et(S.file);return{id:j,name:S.file.name,type:S.file.type||"application/octet-stream",size:S.file.size,blobId:J,objectUrl:te??void 0,blob:S.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(c){let C=wt("attachment-audio"),S;if(v)try{S=await ka(C,c.blob,{name:`audio-${Date.now()}.webm`,type:c.blob.type,size:c.blob.size})??void 0}catch(J){console.warn("[AiChatbot] Failed to persist audio",J)}let j=Et(c.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:c.blob.type||"audio/webm",size:c.blob.size,blobId:S,objectUrl:j??void 0,blob:c.blob,duration:c.duration,mediaType:"audio"})}return u},[P]),Sa=(0,o.useCallback)(async t=>{let c=[];for(let v of t){let u;if(v.attachments&&v.attachments.length>0){u=[];for(let C of v.attachments){let S;if(C.blobId)try{S=(await ba(C.blobId))?.blob??void 0}catch(J){console.warn("[AiChatbot] Failed to hydrate attachment",J)}if(!S)continue;let j=S?Et(S):null;u.push({...C,objectUrl:j??void 0,blob:S??void 0})}}c.push({...v,attachments:u})}return c},[]),Ra=(0,o.useCallback)(async t=>{if(!t||t.length===0){Xe();return}let c=[];for(let v of t){let u=v.blob;if(!u&&v.blobId)try{u=(await ba(v.blobId))?.blob??void 0}catch(j){console.warn("[AiChatbot] Failed to reload attachment",j)}if(!u)continue;let C=u instanceof File?u:new File([u],v.name||"attachment",{type:v.type||u.type||"application/octet-stream"}),S=Et(C);if(S&&(c.push({id:wt("composer-image"),file:C,objectUrl:S}),c.length>=V))break}if(c.length===0){Xe();return}Te(v=>(ce(v),c)),rt.current&&(rt.current.value="")},[Xe,ce,V]),ia=(0,o.useCallback)((t,c)=>{t&&at({url:t,title:c})},[]),Kn=(0,o.useCallback)(()=>{at(null)},[]),Ia=(0,o.useCallback)(()=>{wn($.current),Xe(),Ue(),Ie([]),Be(null),Ke.current=null,i(null),gt(!0),ut(!1);let t=va(P);if(t)try{t.removeItem(Dt)}catch{}aa()},[Xe,Ue,P]),Un=(0,o.useCallback)(()=>{ut(!0)},[]),On=(0,o.useCallback)(()=>{D.busy&&mt.current==="chat"&&Wt(),Ia()},[D.busy,Wt,Ia]),za=(0,o.useCallback)(()=>{ut(!1)},[]),Ca=(0,o.useCallback)(async(t,c)=>{if(!D.busy)try{let v=Ke.current&&Date.now()-Ke.current.storedAt<ke*na?Ke.current.id:void 0;if(!v)return;z("feedback"),Be(null),await D.run(async({signal:u,onStatus:C})=>(await(0,Bt.sendFeedbackMessage)({sessionId:v,feedbackMessageId:t,feedbackType:c},{signal:u,onStatus:C,context:Ne}),null)),Be(null)}catch(v){let u=v?.message?.trim()||T.I18n.get("An error occurred.");Be(u),console.error("Failed to send feedback",v)}finally{z(v=>v==="feedback"?null:v)}},[D,ne]),xa=(0,o.useCallback)((t,c)=>{Ie(v=>v.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===c?{...u,feedback:void 0}:{...u,feedback:c})),Ca(t,c)},[Ca]),qt=(0,o.useCallback)(async()=>{let t=R.current.trim(),c=he.current;if(!t&&!c||D.busy)return;nt.current=!1,Be(null),z("chat");let v=[...q.current],u=await Ta(v,c),C=wt("user"),S=Date.now(),j={id:C,role:"user",content:t||(c?"[Audio message]":""),createdAt:S,clientStatus:"pending",attachments:u.length?u:void 0};ye(""),Xe(),Ue(),Ie(J=>[...J,j]),W||ft(!0),$e();try{let J=Ke.current&&Date.now()-Ke.current.storedAt<ke*na?Ke.current.id:void 0,te=await D.run(async({signal:Oe,onStatus:Ge})=>await(0,Bt.sendChatMessage)({sessionId:J,message:t||void 0,audio:c?.blob,images:v.map($n=>$n.file)},{signal:Oe,onStatus:Ge,context:Ne}));if(nt.current){jt("canceled");return}if(!te)throw new Error(T.I18n.get(D.error??w.emptyResponseLabel));te.sessionId&&(Ke.current={id:te.sessionId,storedAt:Date.now()});let xe={id:te.metadata?.messageId||wt("assistant"),role:"assistant",content:te.result||"",citations:te.citations,createdAt:Date.now()};Ie(Oe=>[...Oe.map(It=>It.id===C?{...It,clientStatus:void 0}:It),xe]),i(S)}catch(J){if(console.error("Error during ask()",J),nt.current||Ir(J)){jt("canceled");return}let te=J?.message?.trim()||T.I18n.get(w.unexpectedErrorLabel);Ie(xe=>[...xe.map(Ge=>Ge.id===C?{...Ge,clientStatus:void 0}:Ge),{id:wt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${te}`,createdAt:Date.now()}]),i(S)}finally{z(J=>J==="chat"?null:J),nt.current=!1,He.current&&He.current.focus(),$e()}},[D,Ta,Xe,Ue,W,$e,jt,w.emptyResponseLabel,w.unexpectedErrorLabel,ne]),Nn=(0,o.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),O&&qt())},[qt,O]),jn=(0,o.useCallback)(()=>{ft(!0)},[]);(0,o.useEffect)(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let Hn=(0,o.useCallback)(()=>{dt(t=>{let c=!t;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),c?(ht(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{ht(!1),ze.current=null})})):ht(!1),c})},[]),Gn=(0,o.useCallback)(t=>{ye(t.content),(async()=>(await Ra(t.attachments),Ie(c=>c.filter(v=>v.id!==t.id)),In(t.attachments),queueMicrotask(()=>He.current?.focus())))()},[Ra]),La=(0,o.useMemo)(()=>ue?I?(0,s.jsx)("img",{src:I,className:"ai-open-btn-icon",alt:T.I18n.get(w.askMeLabel||Z)}):(0,s.jsx)(we.IconMessage,{size:18}):null,[ue,I,w,Z,ne]),Fn=(0,o.useMemo)(()=>{let t=La,c=G?(0,s.jsx)(k.Text,{inherit:!0,children:Z}):null;if(!ue&&!c)return null;if(!ue)return c;if(!G)return t;switch(ae){case"top":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[t,c]});case"bottom":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[c,t]});case"right":return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[c,t]});default:return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[t,c]})}},[La,ue,G,Z,ae]),Wn=(0,o.useMemo)(()=>A,[A]),qn=(0,o.useMemo)(()=>!A,[A]),Yn=(0,o.useMemo)(()=>Se||(d?T.I18n.get(w.readyLabel):T.I18n.get(w.readyEmptyLabel)),[Se,d,w.readyLabel,w.readyEmptyLabel,ne]),Vn=(0,o.useMemo)(()=>A?T.I18n.get(w.cancelLabel):T.I18n.get(w.sendLabel),[A,w.cancelLabel,w.sendLabel,ne]),Jn=(0,o.useMemo)(()=>A?(0,s.jsx)(we.IconPlayerStop,{size:18}):(0,s.jsx)(we.IconSend,{size:18}),[A]),_n=(0,o.useCallback)(()=>{if(A){Wt();return}qt()},[A,Wt,qt]);return(0,o.useEffect)(()=>{if(!W||!Pe||!K)return;let t=()=>{let J=window.getComputedStyle(K).overflowY,te=J==="auto"||J==="scroll",xe=Math.ceil(K.scrollHeight),Oe=Math.floor(K.clientHeight),Ge=xe>Oe;return te&&Ge},c=!1,v=j=>{if(!t())return;j.preventDefault();let J=K.scrollHeight-K.clientHeight;K.scrollTop=Math.max(0,Math.min(J,K.scrollTop+j.deltaY))},u=()=>{let j=t();_e(j),j!==c&&(c=j,c?Pe.addEventListener("wheel",v,{passive:!1}):Pe.removeEventListener("wheel",v))};u();let C=new ResizeObserver(u);C.observe(K);let S=new MutationObserver(u);return S.observe(K,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{c&&Pe.removeEventListener("wheel",v),C.disconnect(),S.disconnect(),window.removeEventListener("resize",u)}},[W,Pe,K]),(0,o.useEffect)(()=>{let t=!1,c=va(P);if(!c){P==="nostorage"&&aa(),me(!0);return}return(async()=>{try{let v=c.getItem(Dt);if(!v){me(!0);return}let u=JSON.parse(v),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>ke*na){c.removeItem(Dt),await aa(),me(!0);return}let j=(Array.isArray(u.messages)?u.messages:[]).map(te=>te?.role==="user"&&te.clientStatus==="pending"?{...te,clientStatus:"canceled"}:te),J=await Sa(j);if(t){wn(J);return}Ie(J),i(C),u.session&&u.session.id&&(Ke.current=u.session)}catch(v){console.warn("[AiChatbot] Failed to load history",v);try{c.removeItem(Dt)}catch{}}finally{t||me(!0)}})(),()=>{t=!0}},[P,ke,Sa]),(0,o.useEffect)(()=>{if(!Je)return;let t=va(P);if(!t)return;let c=re.current;if(!c)return;if(Date.now()-c>ke*na){try{t.removeItem(Dt)}catch{}ya(new Set);return}let v=N.map(({attachments:S,...j})=>({...j,attachments:S?.map(({objectUrl:J,blob:te,...xe})=>xe)})),u={version:1,lastUserSentAt:c,session:Ke.current,messages:v};try{t.setItem(Dt,JSON.stringify(u))}catch{}let C=new Set;v.forEach(S=>{S.attachments?.forEach(j=>{j.blobId&&C.add(j.blobId)})}),ya(C)},[Je,N,pt,P,ke]),l&&!Q||!l&&Q?null:(0,s.jsxs)(k.Group,{className:et,children:[!W&&(0,s.jsx)(k.Button,{variant:"filled",className:G?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:jn,"aria-label":Z,title:Z,"data-ai-kit-open-button":!0,children:Fn}),W&&(0,s.jsx)(k.Modal.Root,{ref:qe,opened:W,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:De,className:et+" ai-chat-container"+(Re?" maximized":"")+(Re&&ct?" ai-max-enter":""),portalProps:{target:a,reuseTargetNode:!0},"data-ai-kit-theme":oe,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:Ct,children:[(0,s.jsxs)(k.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(k.Modal.Title,{className:"ai-chat-title",children:ve}),(0,s.jsxs)(k.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(k.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:Hn,title:Re?T.I18n.get(w.restoreSizeLabel):T.I18n.get(w.maximizeLabel),"aria-label":Re?T.I18n.get(w.restoreSizeLabel):T.I18n.get(w.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Re?(0,s.jsx)(we.IconMinimize,{size:16}):(0,s.jsx)(we.IconMaximize,{size:16})}),(0,s.jsx)(k.Modal.CloseButton,{"aria-label":T.I18n.get(w.closeChatLabel)})]})]}),(0,s.jsxs)(k.Modal.Body,{className:"ai-chat-scroll",ref:Rt,"data-scrollable":Kt?"true":"false",children:[N.map(t=>{let c=t.role==="user",v=c&&t.clientStatus==="canceled"&&t.id===Dn;return(0,s.jsx)(k.Group,{justify:c?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>We(t.id),onMouseLeave:()=>We(u=>u===t.id?null:u),children:(0,s.jsxs)(k.Stack,{gap:4,w:"100%",style:{alignItems:c?"flex-end":"flex-start"},children:[(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(k.Text,{className:"ai-chat-header",children:[(0,s.jsx)(k.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:c?T.I18n.get(w.userLabel):T.I18n.get(w.assistantLabel)}),"\xA0",(0,s.jsx)(k.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(Sn.default,{remarkPlugins:[Rn.default],children:t.content}):(0,s.jsx)(k.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(k.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>ia(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||T.I18n.get("View image"),"aria-label":u.name||T.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:T.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(k.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(k.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(k.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:T.I18n.get("Audio no longer available")})},u.id))]}),v&&(0,s.jsxs)(k.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:T.I18n.get(w.notSentLabel)})}),kt===t.id&&(0,s.jsx)(k.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Gn(t),title:T.I18n.get(w.editLabel),"aria-label":T.I18n.get(w.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(we.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(k.Stack,{className:"ai-citations",children:[(0,s.jsx)(k.Text,{fw:"bold",size:"sm",mb:"xs",children:T.I18n.get(w.referencesLabel)}),(0,s.jsx)(k.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let S=u.sourceUrl||u.url,j=u.title||S||`${T.I18n.get(w.referenceLabel)} #${C+1}`;return(0,s.jsxs)(k.List.Item,{children:[S?(0,s.jsx)(k.Anchor,{href:S,target:"_blank",rel:"noreferrer",children:j}):(0,s.jsx)(k.Text,{children:j}),u.snippet?(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(k.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(k.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>xa(t.id,"accepted"),"aria-label":T.I18n.get(w.acceptResponseLabel),disabled:D.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(k.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>xa(t.id,"rejected"),"aria-label":T.I18n.get(w.rejectResponseLabel),disabled:D.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Wn&&(0,s.jsx)(k.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble typing",children:[Nt?(0,s.jsx)(k.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:Nt})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),qn&&(0,s.jsx)(k.Group,{className:"ai-status-line",children:(0,s.jsx)(k.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:Yn})})}),(0,s.jsxs)(k.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(k.Modal,{opened:le,onClose:za,centered:!0,title:T.I18n.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[(0,s.jsx)(k.Text,{size:"sm",children:T.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(k.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(k.Button,{variant:"default",onClick:za,"data-ai-kit-no-button":!0,children:T.I18n.get("No")}),(0,s.jsx)(k.Button,{color:"var(--ai-kit-color-danger, red)",onClick:On,disabled:!d&&!A,"data-ai-kit-yes-button":!0,children:T.I18n.get("Yes")})]})]}),(0,s.jsx)(k.Group,{children:(0,s.jsx)(k.Textarea,{className:"ai-message",ref:He,placeholder:Ce,value:F,onChange:t=>{ye(t.target.value),M&&Ue()},onKeyDown:Nn,rows:3,disabled:Ae||!!M})}),Aa&&Ae&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:T.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${St}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Aa&&M&&!Ae&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[T.I18n.get("Audio recorded")," (",Math.round(M.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:M.objectUrl})]}),(0,s.jsxs)(k.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(k.Group,{justify:"flex-start",children:(0,s.jsx)(k.Button,{variant:"light",leftSection:(0,s.jsx)(we.IconTrash,{size:18}),onClick:Un,disabled:!d&&!A,"data-ai-kit-reset-button":!0,children:T.I18n.get(w.resetLabel)})}),(0,s.jsxs)(k.Group,{justify:"flex-end",children:[Aa&&(0,s.jsx)(s.Fragment,{children:M?(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconX,{size:18}),onClick:Ue,disabled:A,title:T.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:T.I18n.get("Clear")}):(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconMicrophone,{size:18}),onClick:Ae?Ot:Ut,disabled:A,title:Ae?T.I18n.get("Stop recording"):T.I18n.get("Record audio"),color:Ae?"red":void 0,"data-ai-kit-microphone-button":!0,children:Ae?T.I18n.get("Stop"):T.I18n.get("Record")})}),V>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(we.IconPaperclip,{size:18}),onClick:()=>rt.current?.click(),disabled:Y.length>=V||A||Ae||!!M,title:T.I18n.get(w.addImageLabel),"data-ai-kit-add-image-button":!0,children:T.I18n.get(w.addLabel)}),(0,s.jsx)(k.Input,{ref:rt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:En})]}),(0,s.jsx)(k.Button,{leftSection:Jn,variant:"filled",onClick:_n,disabled:!A&&!O,"data-ai-kit-send-button":!0,children:Vn})]})]}),xt.length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:xt.map(({url:t,title:c},v)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":c||T.I18n.get("View image"),onClick:()=>ia(t,c),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),ia(t,c))},children:(0,s.jsx)(k.Button,{variant:"white",onClick:u=>{u.stopPropagation(),Bn(v)},"aria-label":T.I18n.get(w.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:T.I18n.get(w.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},Y[v]?.id??v))})]})]})}),(0,s.jsx)(k.Modal,{opened:!!ge,onClose:Kn,centered:!0,size:"auto",title:ge?.title||T.I18n.get("Image preview"),children:ge&&(0,s.jsx)("img",{src:ge.url,alt:ge.title||T.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},zn=vt(Cr,{showOpenButton:!0,variation:"modal"});var y=require("@mantine/core"),Tt=require("@smart-cloud/ai-kit-core"),X=require("aws-amplify/utils"),x=require("react"),xn=Ye(require("react-markdown"),1),Ln=Ye(require("rehype-raw"),1),Pn=Ye(require("remark-gfm"),1),Ve=require("@tabler/icons-react");var f=require("react/jsx-runtime");X.I18n.putVocabularies(yt);var Cn=!1;function xr(e){let a=e?.citations?.docs??[],g=e?.citations?.chunks??[],l=new Map;for(let n of a)l.set(n.docId,{doc:n,chunks:[]});for(let n of g){let h=l.get(n.docId);h?h.chunks.push(n):l.set(n.docId,{doc:{docId:n.docId},chunks:[n]})}return Array.from(l.values())}function wa(e){return!!e&&/[\p{L}\p{N}_]/u.test(e)}function Lr(e,a){let g=e.length;if(a<=0)return 0;if(a>=g)return g;let l=e[a-1]??"",n=e[a]??"";if(wa(l)&&wa(n)){let h=a;for(;h<g&&wa(e[h]??"");)h++;return h}return a}function Pr(e){let a=globalThis?.CSS?.escape;return typeof a=="function"?a(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}var Mr=e=>{let{autoRun:a=!0,context:g,title:l,showOpenButton:n=!1,openButtonTitle:h,showOpenButtonTitle:I=!0,openButtonIcon:G,showOpenButtonIcon:ue=!0,searchButtonIcon:oe,showSearchButtonTitle:ne=!0,showSearchButtonIcon:ie=!0,showSources:Ne=!0,topK:se=10,getSearchText:L,enableUserFilters:p=!1,availableCategories:P,availableTags:ke,variation:ee,rootElement:ae,colorMode:be,language:w,onClose:D,onClickDoc:F}=e,[ye,Y]=(0,x.useState)(!n),[Te,M]=(0,x.useState)(""),[_,Ae]=(0,x.useState)(!1),[de,St]=(0,x.useState)(null),[Ze,lt]=(0,x.useState)(0),Qe=(0,x.useRef)(null),je=(0,x.useRef)([]),Le=(0,x.useRef)(null),E=(0,x.useRef)(null),[N,Ie]=(0,x.useState)(!1),[Se,Be]=(0,x.useState)([]),[le,ut]=(0,x.useState)([]),[Re,dt]=(0,x.useState)([]),[ct,ht]=(0,x.useState)(""),[W,ft]=(0,x.useState)(null),[U,gt]=(0,x.useState)(!1),ge=(0,x.useRef)(null),at=(0,x.useRef)(null),Je=1440*60*1e3,{busy:me,error:Pe,statusEvent:Ct,result:K,run:Rt,cancel:Kt,reset:_e}=zt(),pe=(0,x.useRef)(!1),z=(0,x.useRef)([]),mt=K?.sessionId,ze=K?.citations?.docs??[],nt=K?.citations?.chunks??[],kt=K?.citations?.anchors??[],We=K?.result??"",rt=(0,x.useMemo)(()=>{if(ie)return oe?.trim()?(0,f.jsx)("img",{src:oe,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,f.jsx)(Ve.IconSearch,{size:18})},[oe,ie]),He=(0,x.useMemo)(()=>(w&&X.I18n.setLanguage(w||"en"),X.I18n.get(l||"Search with AI-Kit")),[w]),Ke=(0,x.useMemo)(()=>Ct?X.I18n.get("Searching\u2026"):null,[w,Ct]),qe=(0,x.useMemo)(()=>Te||L,[Te,L]),ce=(0,x.useMemo)(()=>{if(me||!ye)return!1;let d=typeof qe=="function"?qe():qe;return!!(d&&d.trim().length>0||de)},[qe,me,de,ye]),Xe=(0,x.useMemo)(()=>{if(!W)return!1;let d=Object.keys(W.allowedCategories).length>0,A=W.allowedTags.length>0;return d||A},[W]),Ue=(0,x.useMemo)(()=>Se.length===0||!W?[]:Se.flatMap(d=>W.allowedCategories[d]||[]).filter((d,A,O)=>O.indexOf(d)===A),[Se,W]),Ut=(0,x.useCallback)(async()=>{try{M("");let d=await navigator.mediaDevices.getUserMedia({audio:!0}),A=new MediaRecorder(d,{mimeType:"audio/webm"}),O=new AudioContext,Z=O.createMediaStreamSource(d),ve=O.createAnalyser();ve.fftSize=2048,ve.smoothingTimeConstant=.8,Z.connect(ve),Le.current=O,E.current=ve;let Ce=new Uint8Array(ve.fftSize),et=()=>{if(!E.current)return;E.current.getByteTimeDomainData(Ce);let Me=0;for(let xt=0;xt<Ce.length;xt++){let Nt=(Ce[xt]-128)/128;Me+=Nt*Nt}let $e=Math.sqrt(Me/Ce.length),De=Math.min(100,$e*200);lt(De),ge.current=requestAnimationFrame(et)};et(),je.current=[],A.ondataavailable=Me=>{Me.data.size>0&&je.current.push(Me.data)},A.onstop=()=>{let Me=new Blob(je.current,{type:"audio/webm"});St(Me),d.getTracks().forEach($e=>$e.stop()),ge.current&&(cancelAnimationFrame(ge.current),ge.current=null),Le.current&&(Le.current.close(),Le.current=null),E.current=null,lt(0)},Qe.current=A,A.start(),Ae(!0)}catch(d){console.error("Failed to start recording:",d)}},[]),Ot=(0,x.useCallback)(()=>{Qe.current&&_&&(Qe.current.stop(),Ae(!1))},[_]),pt=(0,x.useCallback)(()=>{St(null),je.current=[],lt(0),at.current=null},[]);(0,x.useEffect)(()=>()=>{ge.current&&cancelAnimationFrame(ge.current),Le.current&&Le.current.close()},[]),(0,x.useEffect)(()=>{if(!p)return;if(P||ke){ft({allowedCategories:P||{},allowedTags:ke||[]});return}(async()=>{gt(!0);try{let A=await(0,Tt.resolveBackend)();if(!A.available){console.error("Backend not available for metadata options");return}let O={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:A.available,backendTransport:A.transport,backendApiName:A.apiName,backendBaseUrl:A.baseUrl,reason:A.reason??""},Z=await(0,Tt.dispatchBackend)(O,g??"frontend","/kb/metadata-options","GET",null,{});ft({allowedCategories:Z.allowedCategories||{},allowedTags:Z.allowedTags||[]})}catch(A){console.error("Failed to load metadata options:",A)}finally{gt(!1)}})()},[p,P,ke,g]);let i=(0,x.useCallback)(async()=>{let d;if(!de){if(d=typeof qe=="function"?qe():qe,!d)return;M(d)}let A=Date.now(),O=de&&at.current?.blob===de&&A-at.current.uploadTimestamp<Je;de&&!O&&(at.current={blob:de,uploadTimestamp:A}),_e(),await Rt(async({signal:Z,onStatus:ve})=>await(0,Tt.sendSearchMessage)({sessionId:mt,...d&&{query:d},...de&&{audio:de},topK:se,...p&&{userSelectedCategories:Se},...p&&le.length>0&&{userSelectedSubcategories:le},...p&&Re.length>0&&{userSelectedTags:Re}},{signal:Z,onStatus:ve,context:g}))},[g,qe,de,Rt,_e,se,mt,p,Se,le,Re]),R=(0,x.useCallback)(async()=>{Y(!1),_e(),n||D()},[D,_e,pe,n]);(0,x.useEffect)(()=>{!a||!ce||me||pe.current||(pe.current=!0,queueMicrotask(()=>{i()}))},[me,pe,ce,a,i]),(0,x.useEffect)(()=>{ce||(pe.current=!0)},[ce]),(0,x.useEffect)(()=>{let d=z.current,A=Se;(d.length!==A.length||!A.every(Z=>d.includes(Z)))&&d.length>0&&_e(),z.current=[...A]},[Se,_e]);let $=(0,x.useMemo)(()=>xr(K),[K]),re=(0,x.useMemo)(()=>{let d=new Map;return ze.forEach((A,O)=>{A?.docId&&d.set(A.docId,O+1)}),d},[ze]),q=(0,x.useMemo)(()=>{let d=new Map;return nt.forEach(A=>{A?.chunkId&&A?.docId&&d.set(A.chunkId,A.docId)}),d},[nt]),he=(0,x.useMemo)(()=>{if(!We)return"";if(!kt.length||re.size===0)return We;let d=[...kt].filter(Z=>Array.isArray(Z?.chunkIds)&&Z?.span?.end!==void 0).sort((Z,ve)=>{let Ce=Z.span?.end??0,et=ve.span?.end??0;return Ce-et}),A=0,O=[];for(let Z of d){let ve=Z.span?.end;if(typeof ve!="number"||ve<A)continue;let Ce=Array.from(new Set((Z.chunkIds??[]).map(De=>De?q.get(De):void 0).map(De=>De?re.get(De):void 0).filter(De=>typeof De=="number")));if(!Ce.length)continue;let et=Math.min(ve,We.length),Me=Lr(We,et);O.push(We.slice(A,Me));let $e=Ce.map(De=>`<a href="#docsearch-source-${De}" data-docsearch-cite="${De}" style="color: inherit; text-decoration: none;">${De}</a>`).join(",");O.push(`<sup>${$e}</sup>`),A=Me}return O.push(We.slice(A)),O.join("")},[kt,We,re,q]),Q=ee==="modal"?y.Modal.Root:y.Group,V=ee==="modal"?y.Modal.Content:y.Group,fe=ee==="modal"?y.Modal.Body:y.Group;return(0,x.useEffect)(()=>{if(!(ee!=="modal"||!ye))return document.body.style.overflow="hidden",document.body.onkeydown=d=>{d.key==="Escape"&&(d.preventDefault(),R())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[R,ee,ye]),(0,f.jsxs)(f.Fragment,{children:[n&&(0,f.jsx)(y.Button,{leftSection:ue&&(G?(0,f.jsx)("span",{dangerouslySetInnerHTML:{__html:G}}):(0,f.jsx)(Ve.IconSearch,{size:18})),className:I?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ye,onClick:()=>Y(!0),"data-ai-kit-open-button":!0,children:I&&X.I18n.get(h||He)}),ye&&(0,f.jsxs)(Q,{opened:!0,className:"doc-search-root",onClose:R,padding:"md",gap:"md",size:"xl",portalProps:ee==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":be,"data-ai-kit-variation":ee,children:[ee==="modal"&&(0,f.jsx)(y.Modal.Overlay,{}),(0,f.jsxs)(V,{w:"100%",style:{left:0,...ee==="modal"&&!K?.result&&{overflow:"visible"}},children:[ee==="modal"&&(0,f.jsxs)(y.Modal.Header,{style:{zIndex:1e3},children:[(0,f.jsx)(Tt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,f.jsx)(y.Modal.Title,{children:X.I18n.get(He)}),(0,f.jsx)(y.Modal.CloseButton,{})]}),(0,f.jsx)(fe,{w:"100%",style:{zIndex:1001,...ee==="modal"&&!K?.result&&{overflow:"visible"}},children:(0,f.jsx)(Pt,{enabled:ee!=="modal",working:me,variation:ee,children:(0,f.jsx)(y.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,f.jsxs)(y.Stack,{gap:"sm",children:[ee!=="modal"&&(0,f.jsxs)(y.Group,{justify:"space-between",children:[(0,f.jsx)(y.Title,{order:4,style:{margin:0},children:X.I18n.get(He)}),n&&(0,f.jsx)(y.Button,{variant:"subtle",color:"gray",size:"xs",onClick:R,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":X.I18n.get("Close"),children:(0,f.jsx)(Ve.IconX,{size:18,style:{color:be==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),(0,f.jsxs)(y.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,f.jsx)(y.TextInput,{style:{flex:1},value:Te,onChange:d=>{M(d.currentTarget.value),de&&pt()},placeholder:de?X.I18n.get("Audio recorded"):X.I18n.get("Search the documentation\u2026"),disabled:me||_||!!de,onKeyDown:d=>{d.key==="Enter"&&ce&&(d.preventDefault(),i())}}),Cn&&(0,f.jsx)(f.Fragment,{children:de?(0,f.jsx)(y.Button,{variant:"outline",size:"sm",color:"red",onClick:pt,disabled:me,title:X.I18n.get("Clear audio"),children:(0,f.jsx)(Ve.IconMicrophoneOff,{size:18})}):(0,f.jsx)(y.Button,{variant:_?"filled":"outline",size:"sm",color:_?"red":"gray",onClick:_?Ot:Ut,disabled:me,title:_?X.I18n.get("Stop recording"):X.I18n.get("Record audio"),style:_?{transform:`scale(${1+Ze/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,f.jsx)(Ve.IconMicrophone,{size:18})})}),(0,f.jsx)(y.Button,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{i()},disabled:!ce,className:ne?"doc-search-button":"doc-search-button-no-title",children:ne?X.I18n.get("Search"):null}),me?(0,f.jsx)(y.Button,{variant:"outline",size:"sm",onClick:Kt,children:X.I18n.get("Stop")}):null]}),!me&&!Pe&&!K?.result?(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:X.I18n.get("Enter a search query to start.")}):null,p&&W&&Xe&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsx)(y.Button,{variant:"subtle",size:"xs",onClick:()=>Ie(!N),leftSection:N?(0,f.jsx)(Ve.IconChevronDown,{size:14}):(0,f.jsx)(Ve.IconChevronRight,{size:14}),style:{alignSelf:"flex-start"},children:X.I18n.get("Filters")}),(0,f.jsx)(y.Collapse,{in:N,children:(0,f.jsxs)(y.Stack,{gap:"md",children:[Object.keys(W.allowedCategories).length>0&&(0,f.jsxs)("div",{children:[(0,f.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:X.I18n.get("Categories")}),(0,f.jsx)(y.Group,{gap:"md",children:Object.keys(W.allowedCategories).map(d=>(0,f.jsx)(y.Checkbox,{label:X.I18n.get(d),checked:Se.includes(d),onChange:A=>{if(A.currentTarget.checked)Be([...Se,d]);else{Be(Se.filter(Z=>Z!==d));let O=W.allowedCategories[d]||[];ut(le.filter(Z=>!O.includes(Z)))}},disabled:me||U},d))})]}),Ue.length>0&&(0,f.jsxs)("div",{children:[(0,f.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:X.I18n.get("Subcategories")}),(0,f.jsx)(y.Group,{gap:"md",children:Ue.map(d=>(0,f.jsx)(y.Checkbox,{label:X.I18n.get(d),checked:le.includes(d),onChange:A=>{A.currentTarget.checked?ut([...le,d]):ut(le.filter(O=>O!==d))},disabled:me||U},d))})]}),W.allowedTags.length>0&&(0,f.jsx)(y.MultiSelect,{label:X.I18n.get("Tags"),placeholder:X.I18n.get("Select or type tags..."),data:W.allowedTags.map(d=>({value:d,label:X.I18n.get(d)})),value:Re,onChange:dt,searchValue:ct,onSearchChange:ht,disabled:me||U,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Cn&&(0,f.jsxs)(f.Fragment,{children:[_&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsxs)(y.Text,{size:"xs",c:"dimmed",children:[X.I18n.get("Recording...")," \u{1F3A4}"]}),(0,f.jsx)(y.Progress,{value:Ze,size:"sm",color:"red",animated:!0,striped:!0})]}),de&&!_&&(0,f.jsxs)(y.Stack,{gap:"xs",children:[(0,f.jsx)(y.Text,{size:"xs",c:"dimmed",children:X.I18n.get("Recorded audio:")}),(0,f.jsx)("audio",{controls:!0,src:URL.createObjectURL(de),className:"ai-kit-audio-player"})]})]}),Pe?(0,f.jsx)(y.Alert,{color:"red",title:X.I18n.get("Error"),children:Pe}):null,me&&Ke&&(0,f.jsx)(Pt,{enabled:ee==="modal",working:!0,variation:ee,children:(0,f.jsxs)(y.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,f.jsx)(y.Loader,{size:"sm"}),(0,f.jsx)(y.Text,{size:"sm",c:"dimmed",children:Ke})]})}),K?.result?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(y.Divider,{}),(0,f.jsxs)(y.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:X.I18n.get("AI Summary")}),(0,f.jsx)(xn.default,{remarkPlugins:[Pn.default],rehypePlugins:[Ln.default],components:{a:({href:d,children:A,...O})=>{let Z=typeof d=="string"&&d.startsWith("#docsearch-source-");return(0,f.jsx)("a",{href:d,...O,onClick:ve=>{if(!Z)return;ve.preventDefault();let Ce=d.slice(1),et=`#${Pr(Ce)}`;(ae??document).querySelector?.(et)?.scrollIntoView({block:"start",behavior:"smooth"})},children:A})}},"data-doc-search-result-content":!0,children:he||We})]})]}):null,Ne&&(K?.citations?.docs?.length||K?.citations?.chunks?.length)?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(y.Divider,{}),(0,f.jsxs)(y.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,f.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:X.I18n.get("Sources")}),$.map(({doc:d})=>{let A=d.sourceUrl?.trim()||void 0,O=d.docId?re.get(d.docId):void 0,Z=d.title?.trim()||d.docId,ve=(0,f.jsxs)(y.Text,{fw:600,style:{display:"inline"},children:[O?`${O}. `:"",Z]});return(0,f.jsx)(y.Paper,{withBorder:!0,radius:"md",p:"sm",id:O?`docsearch-source-${O}`:void 0,style:{wordBreak:"break-word"},children:(0,f.jsx)(y.Stack,{gap:"xs",children:(0,f.jsx)(y.Group,{justify:"space-between",align:"flex-start",children:(0,f.jsxs)(y.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[A?(0,f.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{F&&(Ce.preventDefault(),F?.(d))},"data-doc-search-source-title":!0,children:ve}):ve,(0,f.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{F&&(Ce.preventDefault(),F?.(d))},"data-doc-search-source-url":!0,children:d.sourceUrl}),d.author?(0,f.jsx)(y.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:d.author}):null,d.description?(0,f.jsx)(y.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:d.description}):null]})})})},d.docId)})]})]}):null,(0,f.jsx)(Jt,{variation:ee})]})})})})]})]})]})},Mn=vt(Mr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
package/dist/index.js CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(ne?`
31
- Follow these additional instructions: ${ne}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),O=await T.run(async({signal:j,onStatus:ge})=>(await Pn({messages:X,images:[Ue],outputLanguage:"en",responseConstraint:co},{signal:j,onStatus:ge,context:I,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!O){D("");return}let ce=(P&&P!=="auto"?P:null)||Et(),q=aa(O).trim();try{G("Translating result...");let j=await T.run(async({signal:ge})=>await mo(q,ce,{signal:ge,context:I,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));D(j)}catch(j){D(q),console.warn("AI Kit: failed to parse SEO JSON",j)}break}}}catch(F){Pe(F instanceof Error?F.message:r.get("An unknown error occurred."))}G(void 0)},[K,T,ne,le,P,Ie,Ve,I,d,Me,gt,de,we]),it=It(async()=>{await ze("backend-only")},[ze]),vt=It(o=>{switch(d){case"proofread":return k(ro,{className:o});case"translate":return k(oo,{className:o});case"summarize":return k(lo,{className:o});case"rewrite":case"write":return k(io,{className:o});case"generateImageMetadata":case"generatePostMetadata":return k(so,{className:o});default:return k($r,{mode:d,className:o})}},[d]),qe=It(()=>{switch(d){case"proofread":return T.lastSource?r.get("Proofread again"):r.get("Proofread");case"translate":return T.lastSource?r.get("Translate again"):r.get("Translate");case"rewrite":return T.lastSource?r.get("Rewrite again"):r.get("Rewrite");case"summarize":return T.lastSource?r.get("Summarize again"):r.get("Summarize");default:return T.lastSource?r.get("Regenerate"):r.get("Generate")}},[K,T.lastSource,d]),st=It(()=>{switch(d){case"proofread":return r.get("Proofread on Backend");case"translate":return r.get("Translate on Backend");case"rewrite":return r.get("Rewrite on Backend");case"summarize":return r.get("Summarize on Backend");default:return r.get("Regenerate on Backend")}},[K,d]),Fe=It(async()=>{oe(!1),D(null),Pe(null),L.current=!1,T.reset(),B||pe()},[pe,L,T,B]),Oe=It(async()=>{T.busy&&T.cancel()},[T.busy]);ha(()=>{!fe||!g||!de||T.busy||x||L.current||(L.current=!0,queueMicrotask(()=>{ze(me)}))},[T.busy,L,fe,de,g,x,ze,me]),ha(()=>{we&&d!=="proofread"&&(de||(Ze(!0),L.current=!0))},[we,de,d]),ha(()=>{let o=!0;return(async()=>{try{await to();let A=await An();o&&Qe(A)}catch(A){console.error(A),o&&Qe(!1)}})(),()=>{o=!1}},[]);let Ye=ra(()=>{let o=[];if(d==="translate"){let A=pa.find(F=>F.value===gt)?.label;o.push(r.get("Input language")+": "+(A?r.get(A):"auto"))}if(P&&N?.outputLanguage){let A=pa.find(F=>F.value===P)?.label;o.push(r.get("Output language")+": "+(A?r.get(A):P))}return d==="summarize"&&Me&&N?.type&&o.push(r.get("Type")+": "+r.get(Me)),(d==="write"||d==="rewrite")&&Ve&&N?.tone&&o.push(r.get("Tone")+": "+r.get(Ve)),(d==="write"||d==="rewrite"||d==="summarize")&&le&&N?.length&&o.push(r.get("Length")+": "+r.get(le)),ne?.trim()&&N?.instructions&&o.push(r.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):r.get("No overrides")},[K,d,gt,P,Me,Ve,le,ne]),ie={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Xe=c==="modal"?Ot.Root:Tt,Ne=c==="modal"?Ot.Content:Tt,Qt=c==="modal"?Ot.Body:Tt,Xt=R==="collapse"?qr:zt,ht=R==="horizontal"?Tt:zt;return ha(()=>{if(!(c!=="modal"||!fe))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),Fe())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[Fe,c]),Ae(oa,{children:[B&&k(Ut,{leftSection:ee&&(te?k("span",{dangerouslySetInnerHTML:{__html:te}}):vt()),className:re?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:fe,onClick:()=>oe(!0),"data-ai-kit-open-button":!0,children:re&&r.get(Q||Pt)}),fe&&Ae(Xe,{opened:!0,className:"ai-feature-root",onClose:Fe,padding:"md",gap:"md",size:"md",portalProps:c==="modal"?{target:he,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":V,"data-ai-kit-variation":c,children:[c==="modal"&&k(Ot.Overlay,{}),Ae(Ne,{w:"100%",style:{left:0},children:[c==="modal"&&Ae(Ot.Header,{style:{zIndex:1e3},children:[vt("ai-feature-title-icon"),k(Ot.Title,{children:r.get(Pt)}),k(Ot.CloseButton,{})]}),k(Qt,{w:"100%",style:{zIndex:1001},children:Ae(Yt,{enabled:c!=="modal",working:T.busy,variation:c,children:[Ae(zt,{gap:"sm",mb:"sm",p:"sm",children:[Ge&&k(xa,{color:"red",children:r.get(Ge)}),we&&d!=="proofread"&&Ae(Jr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[Ae(Tt,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>Ze(o=>!o):void 0,children:[R==="collapse"&&Ae(zt,{gap:0,children:[k(Ln,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.get("Options")}),k(Ln,{size:"xs",c:"dimmed",style:{marginTop:2},children:Ye})]}),R==="collapse"&&k(Ut,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),Ze(A=>!A)},children:Lt?r.get("Hide"):r.get("Show")})]}),Ae(Xt,{in:Lt,children:[R==="collapse"&&k(Yr,{my:"sm"}),Ae(ht,{gap:"xs",justify:"space-between",children:[d==="write"&&N?.text&&k(Rt,{label:r.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:k(St,{size:"xs",className:"ai-feature-option",styles:ie,disabled:T.busy,label:r.get("Topic"),description:R!=="horizontal"?r.get("The topic or subject for the AI to write about."):void 0,value:Ie||"",onChange:o=>{let A=o.target.value;Te(A),C?.({text:A})}})}),(d==="write"||d==="rewrite"||d==="generateImageMetadata"||d==="generatePostMetadata")&&N?.instructions&&k(Rt,{label:r.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:k(St,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Instructions"),description:R!=="horizontal"?r.get("Additional instructions to guide the AI."):void 0,value:ne||"",onChange:o=>{let A=o.target.value;dt(A),C?.({instructions:A})}})}),d==="translate"&&k(Rt,{label:r.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",styles:ie,className:"ai-feature-option",label:r.get("Input language"),description:R!=="horizontal"?r.get("The language of the input text."):void 0,data:[{value:"auto",label:r.get("Auto-detect")},...pa.map(o=>({value:o.value,label:r.get(o.label)})).sort((o,A)=>o.label.localeCompare(A.label))],value:gt||"auto",onChange:o=>{let A=o;yt(A),ct(void 0),C?.({inputLanguage:A})}})}),N?.outputLanguage&&k(Rt,{label:r.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",styles:ie,className:"ai-feature-option",label:r.get("Output language"),description:R!=="horizontal"?r.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[d==="rewrite"?{value:"auto",label:r.get("Auto-detect")}:void 0].filter(Boolean),...pa.map(o=>({value:o.value,label:r.get(o.label)})).sort((o,A)=>o.label.localeCompare(A.label))],value:P||En.settings.defaultOutputLanguage||(d==="rewrite"?"auto":""),onChange:o=>{let A=o;mt(A),ct(void 0),C?.({outputLanguage:A})}})}),d==="summarize"&&N?.type&&k(Rt,{label:r.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Type"),description:R!=="horizontal"?r.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.get("Headline")},{value:"key-points",label:r.get("Key Points")},{value:"teaser",label:r.get("Teaser")},{value:"tldr",label:r.get("TL;DR")}],value:Me||"key-points",onChange:o=>{let A=o;Gt(A),C?.({type:A})}})}),(d==="write"||d==="rewrite")&&N?.tone&&k(Rt,{label:r.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Tone"),description:R!=="horizontal"?r.get("The tone or style for the AI to use."):void 0,data:d==="write"?[{value:"neutral",label:r.get("Neutral")},{value:"formal",label:r.get("Formal")},{value:"casual",label:r.get("Casual")}]:[{value:"as-is",label:r.get("As-Is")},{value:"more-formal",label:r.get("More formal")},{value:"more-casual",label:r.get("More casual")}],value:Ve||(d==="write"?"neutral":"as-is"),onChange:o=>{let A=o;ue(A),C?.({tone:A})}})}),(d==="write"||d==="rewrite"||d==="summarize")&&N?.length&&k(Rt,{label:r.get("The target output length."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Length"),description:R!=="horizontal"?r.get("The target output length."):void 0,data:d==="write"||d==="summarize"?[{value:"short",label:r.get("Short")},{value:"medium",label:r.get("Medium")},{value:"long",label:r.get("Long")}]:[{value:"as-is",label:r.get("As-Is")},{value:"shorter",label:r.get("Shorter")},{value:"longer",label:r.get("Longer")}],value:le||(d==="rewrite"?"as-is":"short"),onChange:o=>{let A=o;ot(A),C?.({length:A})}})}),d==="summarize"||d==="write"||d==="rewrite"&&N?.outputFormat&&k(Rt,{label:r.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Output format"),description:R!=="horizontal"?r.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.get("Plain Text")},{value:"markdown",label:r.get("Markdown")},{value:"html",label:r.get("HTML")}],value:U||"markdown",onChange:o=>{let A=o;At(A),C?.({outputFormat:A})}})})]})]})]}),T.busy&&pt&&k(Yt,{enabled:c==="modal",working:!0,variation:c,children:Ae(Tt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[k(Vr,{size:"sm"}),k(La.Label,{className:"ai-feature-status-text",children:pt})]})}),x&&Ae(zt,{mt:"md",children:[d==="proofread"&&(x.corrections.length===0?k(xa,{color:"green",children:r.get("No issues found. Your text looks great!")}):Ae(oa,{children:[k("p",{style:{marginTop:0,opacity:.85},children:r.get("Hover highlights to see explanations.")}),k(xn,{original:Ie,corrections:x.corrections}),x.correctedInput?Ae(oa,{children:[k("h4",{style:{marginTop:16,marginBottom:8},children:r.get("Corrected")}),k(Tt,{c:"pre",className:"ai-feature-generated-content",children:x.correctedInput})]}):null]})),d==="generateImageMetadata"&&Ae(oa,{children:[k(St,{readOnly:!s,label:r.get("Alt Text"),description:r.get("The alt text for the image."),value:x.alt_text||"",onChange:o=>D({...x,alt_text:o.target.value})}),k(St,{readOnly:!s,label:r.get("Title"),description:r.get("The title for the image."),value:x.title||"",onChange:o=>D({...x,title:o.target.value})}),k(St,{readOnly:!s,label:r.get("Caption"),description:r.get("The caption for the image."),value:x.caption||"",onChange:o=>D({...x,caption:o.target.value})}),k(St,{readOnly:!s,label:r.get("Description"),description:r.get("The description for the image."),value:x.description||"",onChange:o=>D({...x,description:o.target.value})})]}),d==="generatePostMetadata"&&Ae(oa,{children:[k(St,{readOnly:!s,label:r.get("Title"),description:r.get("The title for the post."),value:x.title||"",onChange:o=>D({...x,title:o.target.value})}),k(St,{readOnly:!s,label:r.get("Excerpt"),description:r.get("The excerpt for the post."),value:x.excerpt||"",onChange:o=>D({...x,excerpt:o.target.value})})]}),d!=="proofread"&&d!=="generateImageMetadata"&&d!=="generatePostMetadata"&&typeof x=="string"&&k(Bn,{value:x,editable:!!s,onChange:o=>{D(o)}})]}),x===""&&k(Bn,{value:x,editable:!1})]}),Ae(Tt,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[T.busy&&k(Ut,{variant:"outline",size:"sm",onClick:Oe,"data-ai-kit-cancel-button":!0,children:r.get("Cancel")}),!T.busy&&k(Ut,{variant:"filled",size:"sm",disabled:!de,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:qe()}),!T.busy&&T.lastSource==="on-device"&&ut&&He&&k(Ut,{variant:"filled",size:"sm",disabled:!de,onClick:it,"data-ai-kit-regenerate-on-backend-button":!0,children:st()}),!T.busy&&f&&k(Ut,{variant:"outline",size:"sm",disabled:!x||d==="proofread"&&x.corrections.length===0,onClick:async()=>{f(U==="html"?await za(x):x),Fe()},"data-ai-kit-accept-button":!0,children:r.get(ae)}),k(Ut,{variant:"default",size:"sm",onClick:Fe,"data-ai-kit-close-button":!0,children:r.get("Close")})]}),k(da,{variation:c})]})})]})]})]})};function Bn(t){let{value:n,editable:g,onChange:s}=t;return g?Ae(zt,{p:0,gap:"sm",children:[k(La.Label,{children:r.get("Generated content")}),k(_r,{value:n,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),k(La.Label,{children:r.get("Preview")}),k(zt,{className:"ai-feature-generated-content ai-feature-preview",children:k(Mn,{remarkPlugins:[Dn],children:n})})]}):k(zt,{className:"ai-feature-generated-content",children:n?k(Mn,{remarkPlugins:[Dn],children:n}):k(xa,{color:"yellow",children:r.get("No content generated.")})})}var fo=Kt(ho);import{ActionIcon as Un,Anchor as To,Box as So,Button as tt,Group as Ke,Input as Ro,List as On,Modal as Nt,Stack as at,Text as Le,Textarea as Io}from"@mantine/core";import{IconMaximize as zo,IconMessage as Co,IconMicrophone as xo,IconMinimize as Lo,IconPaperclip as Po,IconPencil as Mo,IconPlayerStop as Do,IconSend as Eo,IconTrash as Bo,IconX as Ko}from"@tabler/icons-react";import{getStoreSelect as Uo,sendChatMessage as Oo,sendFeedbackMessage as No}from"@smart-cloud/ai-kit-core";import{useSelect as jo}from"@wordpress/data";import{I18n as b}from"aws-amplify/utils";import{useCallback as _,useEffect as be,useMemo as ve,useRef as Re,useState as ye}from"react";import Ho from"react-markdown";import Go from"remark-gfm";var ko="ai-kit-chatbot-attachments",lt="attachments";var Pa=null;function bo(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function fa(){if(!bo())return null;Pa||(Pa=new Promise(t=>{try{let n=window.indexedDB.open(ko,1);n.onerror=()=>t(null),n.onblocked=()=>t(null),n.onupgradeneeded=()=>{let g=n.result;g.objectStoreNames.contains(lt)||g.createObjectStore(lt,{keyPath:"id"})},n.onsuccess=()=>t(n.result)}catch(n){console.warn("[AiChatbot] IndexedDB is not available",n),t(null)}}));try{return await Pa}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function Ma(t,n){let g=await fa();return g?new Promise((s,a)=>{try{let c=g.transaction(lt,t),w=c.objectStore(lt),B=n(w);c.oncomplete=()=>s(B),c.onerror=()=>a(c.error),c.onabort=()=>a(c.error)}catch(c){a(c)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Da(t,n,g){await wo();let s={id:t,blob:n,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await Ma("readwrite",c=>(c.put(s),t))}async function Ea(t){let n=await fa();return n?new Promise((g,s)=>{try{let a=n.transaction(lt,"readonly"),c=a.objectStore(lt).get(t);c.onsuccess=()=>{let w=c.result;g(w??null)},c.onerror=()=>s(c.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function yo(t){await Ma("readwrite",n=>{n.delete(t)})}async function ka(){await Ma("readwrite",t=>{t.clear()})}async function Ba(t){let n=await fa();n&&await new Promise((g,s)=>{try{let a=n.transaction(lt,"readwrite"),c=a.objectStore(lt),w=c.getAllKeys();w.onsuccess=()=>{let B=w.result;for(let re of B){let ee=String(re);t.has(ee)||c.delete(re)}},w.onerror=()=>s(w.error),a.oncomplete=()=>g(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var Ao=50*1024*1024;async function vo(){let t=await fa();return t?new Promise((n,g)=>{try{let s=t.transaction(lt,"readonly"),a=s.objectStore(lt).getAll();a.onsuccess=()=>{let c=a.result||[];n(c)},a.onerror=()=>g(a.error),s.onerror=()=>g(s.error),s.onabort=()=>g(s.error)}catch(s){g(s)}}).catch(n=>(console.warn("[AiChatbot] Failed to get all attachments",n),[])):[]}async function wo(){let t=await vo();if(t.length===0)return;let n=t.sort((c,w)=>c.createdAt-w.createdAt),g=n.reduce((c,w)=>c+w.size,0),s=[],a=0;for(;g>Ao&&a<n.length;){let c=n[a];c&&(s.push(c.id),g-=c.size),a++}for(let c of s)await yo(c);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as jn,jsx as m,jsxs as Y}from"react/jsx-runtime";b.putVocabularies(Dt);var ba=1440*60*1e3,Ka=!1,Fo=1,Wo="localstorage",Jt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function Ct(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var qo=4,Yo=5*1024*1024,Vo=t=>{let n=(t?.name||"").toString(),g=(t?.code||"").toString(),s=(t?.message||"").toString();return n==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Jo=(t,n)=>{if(!t)return null;let g=t.step,s=b.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,c=a==null?null:Math.round(a*100);switch(g){case"decide":return s||b.get("Checking capabilities...");case"on-device:init":return s||b.get("Initializing on-device AI...");case"on-device:download":return c==null?s||b.get("Downloading model..."):s||`${b.get("Downloading model...")} ${c}%`;case"on-device:ready":return s||b.get("On-device model ready...");case"on-device:run":return s||b.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return b.get(n.assistantThinkingLabel??Oa.assistantThinkingLabel);case"done":return s||b.get("Done.");case"error":return s||b.get("An error occurred.");default:return s||null}};function Ua(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var _t=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},ya=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},Hn=t=>{!t||t.length===0||t.forEach(n=>ya(n.objectUrl))},Nn=t=>{t.forEach(n=>Hn(n.attachments))},_o=t=>{let{rootElement:n,store:g,previewMode:s,title:a,openButtonTitle:c,openButtonIcon:w,showOpenButtonTitle:B=!0,showOpenButtonIcon:re=!0,colorMode:ee,language:Q,onClose:te,context:He,placeholder:ae,maxImages:R,maxImageBytes:d,historyStorage:I=Wo,emptyHistoryAfterDays:me=Fo,labels:V,openButtonIconLayout:Z="top",openButtonPosition:pe="bottom-right"}=t,f=ve(()=>({...Oa,...V||{}}),[V]),C=qt(),[K,he]=ye(""),[N,we]=ye([]),[z,G]=ye(null),[fe,oe]=ye(!1),[Lt,Ze]=ye(0),ut=Re(null),Qe=Re([]),Ge=Re(null),Pe=Re(null),x=Re(null),[D,Ie]=ye([]),[Te,Ue]=ye(null),[ne,dt]=ye(!1),[Se,ct]=ye(!1),[gt,yt]=ye(!1),[U,At]=ye(!1),[P,mt]=ye(!0),[le,ot]=ye(null),[Ve,ue]=ye(!1),[Me,Gt]=ye(null),[L,Pt]=ye(null),[Zt,Je]=ye(!1),[de,T]=ye(null),pt=Re(de);be(()=>{pt.current=de},[de]);let ze=Re(null),it=Re(!1),[vt,qe]=ye(null),st=Re(null),Fe=Re(null),Oe=Re(null),Ye=Re(null),ie=_(e=>{e.forEach(u=>ya(u.objectUrl))},[]),Xe=_(()=>{ie(O.current),we([]),st.current&&(st.current.value="")},[ie]),Ne=_(()=>{ce.current&&ya(ce.current.objectUrl),G(null),Qe.current=[],Ze(0)},[]),Qt=_(async()=>{try{he(""),Ne();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),u=new MediaRecorder(e,{mimeType:"audio/webm"}),h=new AudioContext,i=h.createMediaStreamSource(e),S=h.createAnalyser();S.fftSize=2048,S.smoothingTimeConstant=.8,i.connect(S),Ge.current=h,Pe.current=S;let y=new Uint8Array(S.fftSize),E=()=>{if(!Pe.current)return;Pe.current.getByteTimeDomainData(y);let J=0;for(let We=0;We<y.length;We++){let Mt=(y[We]-128)/128;J+=Mt*Mt}let xe=Math.sqrt(J/y.length),je=Math.min(100,xe*200);Ze(je),x.current=requestAnimationFrame(E)};E(),Qe.current=[];let H=Date.now();u.ondataavailable=J=>{J.data.size>0&&Qe.current.push(J.data)},u.onstop=()=>{let J=new Blob(Qe.current,{type:"audio/webm"}),xe=(Date.now()-H)/1e3,je=_t(J);je&&G({id:Ct("composer-audio"),blob:J,objectUrl:je,duration:xe}),e.getTracks().forEach(We=>We.stop()),x.current&&(cancelAnimationFrame(x.current),x.current=null),Ge.current&&(Ge.current.close(),Ge.current=null),Pe.current=null,Ze(0)},ut.current=u,u.start(),oe(!0)}catch(e){console.error("Failed to start recording:",e)}},[Ne]),Xt=_(()=>{ut.current&&fe&&(ut.current.stop(),oe(!1))},[fe]);be(()=>()=>{x.current&&cancelAnimationFrame(x.current),Ge.current&&Ge.current.close(),Ne()},[Ne]);let[ht,o]=ye(null),A=Re(K),F=Re(D),X=Re(ht),O=Re(N),ce=Re(z);be(()=>{A.current=K},[K]),be(()=>{O.current=N},[N]),be(()=>{ce.current=z},[z]),be(()=>{F.current=D},[D]),be(()=>{X.current=ht},[ht]),be(()=>{Q&&b.setLanguage(Q||"en")},[Q]);let q=jo(()=>Uo(g).isShowChatbotPreview()),j=ve(()=>Math.max(0,R??qo),[R]),ge=ve(()=>Math.max(0,d??Yo),[d]),l=D.length>0,p=ve(()=>C.busy&&de==="chat",[C.busy,de]),M=ve(()=>p?!1:K.trim().length>0||z!==null,[K,p,z]),W=ve(()=>{let e=c||f.askMeLabel;return b.get(e)},[c,f.askMeLabel,Q]),ke=ve(()=>{let e=a||f.modalTitle;return b.get(e)},[a,f.modalTitle,Q]),Ce=ve(()=>{let e=ae||f.placeholder;return b.get(e)},[ae,f.placeholder,Q]),et=ve(()=>{let e="ai-docs-ask",u=`ai-open-btn--${pe}`;return`${e} ${u}`},[pe]),De=_(()=>{let e=Ye.current;if(e)try{let u=window.innerHeight||document.documentElement.clientHeight,h=360,i=1e3,S=Math.floor(u*.8),y=Math.max(h,Math.min(S,i));e.style.height=`${y}px`}catch{}},[]),_e=_(()=>{let e=L;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[L]),Ee=_(()=>{At(!1),Se&&ct(!1),yt(!1),te?.()},[Se,te]);be(()=>{if(U)return De(),window.addEventListener("resize",De),()=>window.removeEventListener("resize",De)},[U,De]),be(()=>{if(!(!U||!Se))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[U,Se,Ee]);let Ft=ve(()=>N.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[N]);be(()=>{l||mt(!0)},[l]),be(()=>()=>{ie(O.current)},[ie]),be(()=>{let e=L;if(!e)return;let u=()=>{let h=e.scrollHeight-(e.scrollTop+e.clientHeight);mt(h<20)};return e.addEventListener("scroll",u),()=>{e.removeEventListener("scroll",u)}},[U,L]),be(()=>{if(!P)return;let e=L;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[D,C.busy,P,L]),be(()=>{U||ot(null)},[U]);let ea=ve(()=>C.busy?Jo(C.statusEvent,f)||b.get("Working\u2026"):null,[C.busy,C.statusEvent,Q,f]),Jn=ve(()=>{for(let e=D.length-1;e>=0;e--){let u=D[e];if(u.role==="user"&&u.clientStatus==="canceled")return u.id}return null},[D]),ta=_(e=>{Ie(u=>{let h=[...u].map((y,E)=>({m:y,i:E})).reverse().find(y=>y.m.role==="user"&&y.m.clientStatus==="pending")?.i;if(h==null)return u;let i=u.slice(),S=i[h];return i[h]={...S,clientStatus:e??void 0},i})},[Ie]),la=_(()=>{if(!(!C.busy||pt.current!=="chat")){it.current=!0;try{C.cancel()}catch{}ta("canceled"),T(null),Ue(null),_e()}},[C,ta,_e]),_n=_(e=>{let u=O.current,h=Array.from(e.target.files||[]),i=Math.max(0,j-u.length);if(i===0){e.currentTarget.value="";return}let S=[];for(let y of h){if(S.length>=i)break;let E=/image\/(jpeg|png|gif|webp)/i.test(y.type),H=y.size<=ge,J=[...u,...S].some(je=>je.file.name===y.name&&je.file.size===y.size&&je.file.lastModified===y.lastModified);if(!E||!H||J)continue;let xe=_t(y);xe&&S.push({id:Ct("composer-image"),file:y,objectUrl:xe})}S.length&&we(y=>[...y,...S]),e.currentTarget.value=""},[j,ge]),$n=_(e=>{we(u=>{if(e<0||e>=u.length)return u;let h=u[e];return h&&ya(h.objectUrl),u.filter((i,S)=>S!==e)})},[]),wt=Re(null);be(()=>{if(Te)return wt.current&&(window.clearTimeout(wt.current),wt.current=null),wt.current=window.setTimeout(()=>{Ue(null),wt.current=null},6e3),()=>{wt.current&&(window.clearTimeout(wt.current),wt.current=null)}},[Te]);let ja=_(async(e,u)=>{let h=I!=="nostorage",i=[];if(e.length>0){let S=await Promise.all(e.map(async y=>{let E=Ct("attachment-image"),H;if(h)try{H=await Da(E,y.file,{name:y.file.name,type:y.file.type,size:y.file.size})??void 0}catch(xe){console.warn("[AiChatbot] Failed to persist image",xe)}let J=_t(y.file);return{id:E,name:y.file.name,type:y.file.type||"application/octet-stream",size:y.file.size,blobId:H,objectUrl:J??void 0,blob:y.file,mediaType:"image"}}));i.push(...S.filter(Boolean))}if(u){let S=Ct("attachment-audio"),y;if(h)try{y=await Da(S,u.blob,{name:`audio-${Date.now()}.webm`,type:u.blob.type,size:u.blob.size})??void 0}catch(H){console.warn("[AiChatbot] Failed to persist audio",H)}let E=_t(u.blob);i.push({id:S,name:`audio-${Date.now()}.webm`,type:u.blob.type||"audio/webm",size:u.blob.size,blobId:y,objectUrl:E??void 0,blob:u.blob,duration:u.duration,mediaType:"audio"})}return i},[I]),Ha=_(async e=>{let u=[];for(let h of e){let i;if(h.attachments&&h.attachments.length>0){i=[];for(let S of h.attachments){let y;if(S.blobId)try{y=(await Ea(S.blobId))?.blob??void 0}catch(H){console.warn("[AiChatbot] Failed to hydrate attachment",H)}if(!y)continue;let E=y?_t(y):null;i.push({...S,objectUrl:E??void 0,blob:y??void 0})}}u.push({...h,attachments:i})}return u},[]),Ga=_(async e=>{if(!e||e.length===0){Xe();return}let u=[];for(let h of e){let i=h.blob;if(!i&&h.blobId)try{i=(await Ea(h.blobId))?.blob??void 0}catch(E){console.warn("[AiChatbot] Failed to reload attachment",E)}if(!i)continue;let S=i instanceof File?i:new File([i],h.name||"attachment",{type:h.type||i.type||"application/octet-stream"}),y=_t(S);if(y&&(u.push({id:Ct("composer-image"),file:S,objectUrl:y}),u.length>=j))break}if(u.length===0){Xe();return}we(h=>(ie(h),u)),st.current&&(st.current.value="")},[Xe,ie,j]),Aa=_((e,u)=>{e&&ot({url:e,title:u})},[]),Zn=_(()=>{ot(null)},[]),Fa=_(()=>{Nn(F.current),Xe(),Ne(),Ie([]),Ue(null),Oe.current=null,o(null),mt(!0),dt(!1);let e=Ua(I);if(e)try{e.removeItem(Jt)}catch{}ka()},[Xe,Ne,I]),Qn=_(()=>{dt(!0)},[]),Xn=_(()=>{C.busy&&pt.current==="chat"&&la(),Fa()},[C.busy,la,Fa]),Wa=_(()=>{dt(!1)},[]),qa=_(async(e,u)=>{if(!C.busy)try{let h=Oe.current&&Date.now()-Oe.current.storedAt<me*ba?Oe.current.id:void 0;if(!h)return;T("feedback"),Ue(null),await C.run(async({signal:i,onStatus:S})=>(await No({sessionId:h,feedbackMessageId:e,feedbackType:u},{signal:i,onStatus:S,context:He}),null)),Ue(null)}catch(h){let i=h?.message?.trim()||b.get("An error occurred.");Ue(i),console.error("Failed to send feedback",h)}finally{T(h=>h==="feedback"?null:h)}},[C,Q]),Ya=_((e,u)=>{Ie(h=>h.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===u?{...i,feedback:void 0}:{...i,feedback:u})),qa(e,u)},[qa]),ua=_(async()=>{let e=A.current.trim(),u=ce.current;if(!e&&!u||C.busy)return;it.current=!1,Ue(null),T("chat");let h=[...O.current],i=await ja(h,u),S=Ct("user"),y=Date.now(),E={id:S,role:"user",content:e||(u?"[Audio message]":""),createdAt:y,clientStatus:"pending",attachments:i.length?i:void 0};he(""),Xe(),Ne(),Ie(H=>[...H,E]),U||At(!0),_e();try{let H=Oe.current&&Date.now()-Oe.current.storedAt<me*ba?Oe.current.id:void 0,J=await C.run(async({signal:je,onStatus:We})=>await Oo({sessionId:H,message:e||void 0,audio:u?.blob,images:h.map(cr=>cr.file)},{signal:je,onStatus:We,context:He}));if(it.current){ta("canceled");return}if(!J)throw new Error(b.get(C.error??f.emptyResponseLabel));J.sessionId&&(Oe.current={id:J.sessionId,storedAt:Date.now()});let xe={id:J.metadata?.messageId||Ct("assistant"),role:"assistant",content:J.result||"",citations:J.citations,createdAt:Date.now()};Ie(je=>[...je.map(Mt=>Mt.id===S?{...Mt,clientStatus:void 0}:Mt),xe]),o(y)}catch(H){if(console.error("Error during ask()",H),it.current||Vo(H)){ta("canceled");return}let J=H?.message?.trim()||b.get(f.unexpectedErrorLabel);Ie(xe=>[...xe.map(We=>We.id===S?{...We,clientStatus:void 0}:We),{id:Ct("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${J}`,createdAt:Date.now()}]),o(y)}finally{T(H=>H==="chat"?null:H),it.current=!1,Fe.current&&Fe.current.focus(),_e()}},[C,ja,Xe,Ne,U,_e,ta,f.emptyResponseLabel,f.unexpectedErrorLabel,Q]),er=_(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),M&&ua())},[ua,M]),tr=_(()=>{At(!0)},[]);be(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let ar=_(()=>{ct(e=>{let u=!e;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),u?(yt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{yt(!1),ze.current=null})})):yt(!1),u})},[]),nr=_(e=>{he(e.content),(async()=>(await Ga(e.attachments),Ie(u=>u.filter(h=>h.id!==e.id)),Hn(e.attachments),queueMicrotask(()=>Fe.current?.focus())))()},[Ga]),Va=ve(()=>re?w?m("img",{src:w,className:"ai-open-btn-icon",alt:b.get(f.askMeLabel||W)}):m(Co,{size:18}):null,[re,w,f,W,Q]),rr=ve(()=>{let e=Va,u=B?m(Le,{inherit:!0,children:W}):null;if(!re&&!u)return null;if(!re)return u;if(!B)return e;switch(Z){case"top":return Y(at,{gap:4,align:"center",children:[e,u]});case"bottom":return Y(at,{gap:4,align:"center",children:[u,e]});case"right":return Y(Ke,{gap:6,align:"center",children:[u,e]});default:return Y(Ke,{gap:6,align:"center",children:[e,u]})}},[Va,re,B,W,Z]),or=ve(()=>p,[p]),ir=ve(()=>!p,[p]),sr=ve(()=>Te||(l?b.get(f.readyLabel):b.get(f.readyEmptyLabel)),[Te,l,f.readyLabel,f.readyEmptyLabel,Q]),lr=ve(()=>p?b.get(f.cancelLabel):b.get(f.sendLabel),[p,f.cancelLabel,f.sendLabel,Q]),ur=ve(()=>p?m(Do,{size:18}):m(Eo,{size:18}),[p]),dr=_(()=>{if(p){la();return}ua()},[p,la,ua]);return be(()=>{if(!U||!Me||!L)return;let e=()=>{let H=window.getComputedStyle(L).overflowY,J=H==="auto"||H==="scroll",xe=Math.ceil(L.scrollHeight),je=Math.floor(L.clientHeight),We=xe>je;return J&&We},u=!1,h=E=>{if(!e())return;E.preventDefault();let H=L.scrollHeight-L.clientHeight;L.scrollTop=Math.max(0,Math.min(H,L.scrollTop+E.deltaY))},i=()=>{let E=e();Je(E),E!==u&&(u=E,u?Me.addEventListener("wheel",h,{passive:!1}):Me.removeEventListener("wheel",h))};i();let S=new ResizeObserver(i);S.observe(L);let y=new MutationObserver(i);return y.observe(L,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{u&&Me.removeEventListener("wheel",h),S.disconnect(),y.disconnect(),window.removeEventListener("resize",i)}},[U,Me,L]),be(()=>{let e=!1,u=Ua(I);if(!u){I==="nostorage"&&ka(),ue(!0);return}return(async()=>{try{let h=u.getItem(Jt);if(!h){ue(!0);return}let i=JSON.parse(h),S=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!S||Date.now()-S>me*ba){u.removeItem(Jt),await ka(),ue(!0);return}let E=(Array.isArray(i.messages)?i.messages:[]).map(J=>J?.role==="user"&&J.clientStatus==="pending"?{...J,clientStatus:"canceled"}:J),H=await Ha(E);if(e){Nn(H);return}Ie(H),o(S),i.session&&i.session.id&&(Oe.current=i.session)}catch(h){console.warn("[AiChatbot] Failed to load history",h);try{u.removeItem(Jt)}catch{}}finally{e||ue(!0)}})(),()=>{e=!0}},[I,me,Ha]),be(()=>{if(!Ve)return;let e=Ua(I);if(!e)return;let u=X.current;if(!u)return;if(Date.now()-u>me*ba){try{e.removeItem(Jt)}catch{}Ba(new Set);return}let h=D.map(({attachments:y,...E})=>({...E,attachments:y?.map(({objectUrl:H,blob:J,...xe})=>xe)})),i={version:1,lastUserSentAt:u,session:Oe.current,messages:h};try{e.setItem(Jt,JSON.stringify(i))}catch{}let S=new Set;h.forEach(y=>{y.attachments?.forEach(E=>{E.blobId&&S.add(E.blobId)})}),Ba(S)},[Ve,D,ht,I,me]),s&&!q||!s&&q?null:Y(Ke,{className:et,children:[!U&&m(tt,{variant:"filled",className:B?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:tr,"aria-label":W,title:W,"data-ai-kit-open-button":!0,children:rr}),U&&m(Nt.Root,{ref:Ye,opened:U,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Ee,className:et+" ai-chat-container"+(Se?" maximized":"")+(Se&&gt?" ai-max-enter":""),portalProps:{target:n,reuseTargetNode:!0},"data-ai-kit-theme":ee,"data-ai-kit-variation":"modal",children:Y("div",{className:"ai-chat-container-internal",ref:Gt,children:[Y(Nt.Header,{className:"ai-chat-header-bar",children:[m(Nt.Title,{className:"ai-chat-title",children:ke}),Y(Ke,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&m(Un,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:ar,title:Se?b.get(f.restoreSizeLabel):b.get(f.maximizeLabel),"aria-label":Se?b.get(f.restoreSizeLabel):b.get(f.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Se?m(Lo,{size:16}):m(zo,{size:16})}),m(Nt.CloseButton,{"aria-label":b.get(f.closeChatLabel)})]})]}),Y(Nt.Body,{className:"ai-chat-scroll",ref:Pt,"data-scrollable":Zt?"true":"false",children:[D.map(e=>{let u=e.role==="user",h=u&&e.clientStatus==="canceled"&&e.id===Jn;return m(Ke,{justify:u?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>qe(e.id),onMouseLeave:()=>qe(i=>i===e.id?null:i),children:Y(at,{gap:4,w:"100%",style:{alignItems:u?"flex-end":"flex-start"},children:[Y(at,{className:"ai-chat-bubble",children:[Y(Le,{className:"ai-chat-header",children:[m(Le,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:u?b.get(f.userLabel):b.get(f.assistantLabel)}),"\xA0",m(Le,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?m(Ho,{remarkPlugins:[Go],children:e.content}):m(Le,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&Y(at,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&m(Ke,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>m("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>Aa(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||b.get("View image"),"aria-label":i.name||b.get("View image"),children:!i.objectUrl&&m(Le,{size:"xs",c:"dimmed",children:b.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>m(So,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?Y(at,{gap:"xs",children:[m("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&Y(Le,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):m(Le,{size:"xs",c:"dimmed",children:b.get("Audio no longer available")})},i.id))]}),h&&Y(Ke,{justify:"flex-end",gap:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:m("em",{children:b.get(f.notSentLabel)})}),vt===e.id&&m(Un,{size:"sm",variant:"subtle",onClick:()=>nr(e),title:b.get(f.editLabel),"aria-label":b.get(f.editLabel),"data-ai-kit-edit-button":!0,children:m(Mo,{size:14})})]}),e.citations&&e.citations.length>0&&Y(at,{className:"ai-citations",children:[m(Le,{fw:"bold",size:"sm",mb:"xs",children:b.get(f.referencesLabel)}),m(On,{spacing:"xs",size:"sm",children:e.citations.map((i,S)=>{let y=i.sourceUrl||i.url,E=i.title||y||`${b.get(f.referenceLabel)} #${S+1}`;return Y(On.Item,{children:[y?m(To,{href:y,target:"_blank",rel:"noreferrer",children:E}):m(Le,{children:E}),i.snippet?m(Le,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},S)})})]}),e.role==="assistant"&&Y(Ke,{className:"ai-feedback",gap:"xs",children:[m(tt,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>Ya(e.id,"accepted"),"aria-label":b.get(f.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),m(tt,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>Ya(e.id,"rejected"),"aria-label":b.get(f.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),or&&m(Ke,{justify:"flex-start",className:"ai-chat-row assistant status",children:Y(at,{className:"ai-chat-bubble typing",children:[ea?m(Le,{size:"sm",c:"dimmed",children:m("em",{children:ea})}):null,Y("div",{className:"typing-indicator",children:[m("span",{}),m("span",{}),m("span",{})]})]})})]}),ir&&m(Ke,{className:"ai-status-line",children:m(Le,{className:"ai-status-text",children:m("em",{children:sr})})}),Y(at,{className:"ai-box ai-box-open",children:[Y(Nt,{opened:ne,onClose:Wa,centered:!0,title:b.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[m(Le,{size:"sm",children:b.get("Are you sure you want to reset the conversation?")}),Y(Ke,{justify:"flex-end",mt:"md",children:[m(tt,{variant:"default",onClick:Wa,"data-ai-kit-no-button":!0,children:b.get("No")}),m(tt,{color:"var(--ai-kit-color-danger, red)",onClick:Xn,disabled:!l&&!p,"data-ai-kit-yes-button":!0,children:b.get("Yes")})]})]}),m(Ke,{children:m(Io,{className:"ai-message",ref:Fe,placeholder:Ce,value:K,onChange:e=>{he(e.target.value),z&&Ne()},onKeyDown:er,rows:3,disabled:fe||!!z})}),Ka&&fe&&Y(at,{gap:"xs",mt:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:m("em",{children:b.get("Recording...")})}),m("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:m("div",{style:{width:`${Lt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Ka&&z&&!fe&&Y(at,{gap:"xs",mt:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:Y("em",{children:[b.get("Audio recorded")," (",Math.round(z.duration),"s)"]})}),m("audio",{className:"ai-kit-audio-player",controls:!0,src:z.objectUrl})]}),Y(Ke,{className:"ai-actions",justify:"space-between",w:"100%",children:[m(Ke,{justify:"flex-start",children:m(tt,{variant:"light",leftSection:m(Bo,{size:18}),onClick:Qn,disabled:!l&&!p,"data-ai-kit-reset-button":!0,children:b.get(f.resetLabel)})}),Y(Ke,{justify:"flex-end",children:[Ka&&m(jn,{children:z?m(tt,{variant:"outline",leftSection:m(Ko,{size:18}),onClick:Ne,disabled:p,title:b.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:b.get("Clear")}):m(tt,{variant:"outline",leftSection:m(xo,{size:18}),onClick:fe?Xt:Qt,disabled:p,title:fe?b.get("Stop recording"):b.get("Record audio"),color:fe?"red":void 0,"data-ai-kit-microphone-button":!0,children:fe?b.get("Stop"):b.get("Record")})}),j>0&&Y(jn,{children:[m(tt,{variant:"outline",leftSection:m(Po,{size:18}),onClick:()=>st.current?.click(),disabled:N.length>=j||p||fe||!!z,title:b.get(f.addImageLabel),"data-ai-kit-add-image-button":!0,children:b.get(f.addLabel)}),m(Ro,{ref:st,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:_n})]}),m(tt,{leftSection:ur,variant:"filled",onClick:dr,disabled:!p&&!M,"data-ai-kit-send-button":!0,children:lr})]})]}),Ft.length>0&&m(Ke,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ft.map(({url:e,title:u},h)=>m("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":u||b.get("View image"),onClick:()=>Aa(e,u),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),Aa(e,u))},children:m(tt,{variant:"white",onClick:i=>{i.stopPropagation(),$n(h)},"aria-label":b.get(f.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:b.get(f.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},N[h]?.id??h))})]})]})}),m(Nt,{opened:!!le,onClose:Zn,centered:!0,size:"auto",title:le?.title||b.get("Image preview"),children:le&&m("img",{src:le.url,alt:le.title||b.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},$o=Kt(_o,{showOpenButton:!0,variation:"modal"});import{Alert as Zo,Anchor as Gn,Button as jt,Checkbox as Fn,Collapse as Qo,Divider as Wn,Group as kt,Loader as Xo,Modal as Ht,MultiSelect as ei,Paper as qn,Progress as ti,Stack as bt,Text as nt,TextInput as ai,Title as ni}from"@mantine/core";import{AiKitDocSearchIcon as ri,dispatchBackend as oi,resolveBackend as ii,sendSearchMessage as si}from"@smart-cloud/ai-kit-core";import{I18n as $}from"aws-amplify/utils";import{useCallback as ia,useEffect as $t,useMemo as rt,useRef as xt,useState as $e}from"react";import li from"react-markdown";import ui from"rehype-raw";import di from"remark-gfm";import{IconChevronDown as ci,IconChevronRight as gi,IconMicrophone as mi,IconMicrophoneOff as pi,IconSearch as Yn,IconX as hi}from"@tabler/icons-react";import{Fragment as sa,jsx as v,jsxs as se}from"react/jsx-runtime";$.putVocabularies(Dt);var Vn=!1;function fi(t){let n=t?.citations?.docs??[],g=t?.citations?.chunks??[],s=new Map;for(let a of n)s.set(a.docId,{doc:a,chunks:[]});for(let a of g){let c=s.get(a.docId);c?c.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}function Na(t){return!!t&&/[\p{L}\p{N}_]/u.test(t)}function ki(t,n){let g=t.length;if(n<=0)return 0;if(n>=g)return g;let s=t[n-1]??"",a=t[n]??"";if(Na(s)&&Na(a)){let c=n;for(;c<g&&Na(t[c]??"");)c++;return c}return n}function bi(t){let n=globalThis?.CSS?.escape;return typeof n=="function"?n(t):t.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}var yi=t=>{let{autoRun:n=!0,context:g,title:s,showOpenButton:a=!1,openButtonTitle:c,showOpenButtonTitle:w=!0,openButtonIcon:B,showOpenButtonIcon:re=!0,searchButtonIcon:ee,showSearchButtonTitle:Q=!0,showSearchButtonIcon:te=!0,showSources:He=!0,topK:ae=10,getSearchText:R,enableUserFilters:d=!1,availableCategories:I,availableTags:me,variation:V,rootElement:Z,colorMode:pe,language:f,onClose:C,onClickDoc:K}=t,[he,N]=$e(!a),[we,z]=$e(""),[G,fe]=$e(!1),[oe,Lt]=$e(null),[Ze,ut]=$e(0),Qe=xt(null),Ge=xt([]),Pe=xt(null),x=xt(null),[D,Ie]=$e(!1),[Te,Ue]=$e([]),[ne,dt]=$e([]),[Se,ct]=$e([]),[gt,yt]=$e(""),[U,At]=$e(null),[P,mt]=$e(!1),le=xt(null),ot=xt(null),Ve=1440*60*1e3,{busy:ue,error:Me,statusEvent:Gt,result:L,run:Pt,cancel:Zt,reset:Je}=qt(),de=xt(!1),T=xt([]),pt=L?.sessionId,ze=L?.citations?.docs??[],it=L?.citations?.chunks??[],vt=L?.citations?.anchors??[],qe=L?.result??"",st=rt(()=>{if(te)return ee?.trim()?v("img",{src:ee,alt:"",style:{width:18,height:18,objectFit:"contain"}}):v(Yn,{size:18})},[ee,te]),Fe=rt(()=>(f&&$.setLanguage(f||"en"),$.get(s||"Search with AI-Kit")),[f]),Oe=rt(()=>Gt?$.get("Searching\u2026"):null,[f,Gt]),Ye=rt(()=>we||R,[we,R]),ie=rt(()=>{if(ue||!he)return!1;let l=typeof Ye=="function"?Ye():Ye;return!!(l&&l.trim().length>0||oe)},[Ye,ue,oe,he]),Xe=rt(()=>{if(!U)return!1;let l=Object.keys(U.allowedCategories).length>0,p=U.allowedTags.length>0;return l||p},[U]),Ne=rt(()=>Te.length===0||!U?[]:Te.flatMap(l=>U.allowedCategories[l]||[]).filter((l,p,M)=>M.indexOf(l)===p),[Te,U]),Qt=ia(async()=>{try{z("");let l=await navigator.mediaDevices.getUserMedia({audio:!0}),p=new MediaRecorder(l,{mimeType:"audio/webm"}),M=new AudioContext,W=M.createMediaStreamSource(l),ke=M.createAnalyser();ke.fftSize=2048,ke.smoothingTimeConstant=.8,W.connect(ke),Pe.current=M,x.current=ke;let Ce=new Uint8Array(ke.fftSize),et=()=>{if(!x.current)return;x.current.getByteTimeDomainData(Ce);let De=0;for(let Ft=0;Ft<Ce.length;Ft++){let ea=(Ce[Ft]-128)/128;De+=ea*ea}let _e=Math.sqrt(De/Ce.length),Ee=Math.min(100,_e*200);ut(Ee),le.current=requestAnimationFrame(et)};et(),Ge.current=[],p.ondataavailable=De=>{De.data.size>0&&Ge.current.push(De.data)},p.onstop=()=>{let De=new Blob(Ge.current,{type:"audio/webm"});Lt(De),l.getTracks().forEach(_e=>_e.stop()),le.current&&(cancelAnimationFrame(le.current),le.current=null),Pe.current&&(Pe.current.close(),Pe.current=null),x.current=null,ut(0)},Qe.current=p,p.start(),fe(!0)}catch(l){console.error("Failed to start recording:",l)}},[]),Xt=ia(()=>{Qe.current&&G&&(Qe.current.stop(),fe(!1))},[G]),ht=ia(()=>{Lt(null),Ge.current=[],ut(0),ot.current=null},[]);$t(()=>()=>{le.current&&cancelAnimationFrame(le.current),Pe.current&&Pe.current.close()},[]),$t(()=>{if(!d)return;if(I||me){At({allowedCategories:I||{},allowedTags:me||[]});return}(async()=>{mt(!0);try{let p=await ii();if(!p.available){console.error("Backend not available for metadata options");return}let M={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:p.available,backendTransport:p.transport,backendApiName:p.apiName,backendBaseUrl:p.baseUrl,reason:p.reason??""},W=await oi(M,g??"frontend","/kb/metadata-options","GET",null,{});At({allowedCategories:W.allowedCategories||{},allowedTags:W.allowedTags||[]})}catch(p){console.error("Failed to load metadata options:",p)}finally{mt(!1)}})()},[d,I,me,g]);let o=ia(async()=>{let l;if(!oe){if(l=typeof Ye=="function"?Ye():Ye,!l)return;z(l)}let p=Date.now(),M=oe&&ot.current?.blob===oe&&p-ot.current.uploadTimestamp<Ve;oe&&!M&&(ot.current={blob:oe,uploadTimestamp:p}),Je(),await Pt(async({signal:W,onStatus:ke})=>await si({sessionId:pt,...l&&{query:l},...oe&&{audio:oe},topK:ae,...d&&{userSelectedCategories:Te},...d&&ne.length>0&&{userSelectedSubcategories:ne},...d&&Se.length>0&&{userSelectedTags:Se}},{signal:W,onStatus:ke,context:g}))},[g,Ye,oe,Pt,Je,ae,pt,d,Te,ne,Se]),A=ia(async()=>{N(!1),Je(),a||C()},[C,Je,de,a]);$t(()=>{!n||!ie||ue||de.current||(de.current=!0,queueMicrotask(()=>{o()}))},[ue,de,ie,n,o]),$t(()=>{ie||(de.current=!0)},[ie]),$t(()=>{let l=T.current,p=Te;(l.length!==p.length||!p.every(W=>l.includes(W)))&&l.length>0&&Je(),T.current=[...p]},[Te,Je]);let F=rt(()=>fi(L),[L]),X=rt(()=>{let l=new Map;return ze.forEach((p,M)=>{p?.docId&&l.set(p.docId,M+1)}),l},[ze]),O=rt(()=>{let l=new Map;return it.forEach(p=>{p?.chunkId&&p?.docId&&l.set(p.chunkId,p.docId)}),l},[it]),ce=rt(()=>{if(!qe)return"";if(!vt.length||X.size===0)return qe;let l=[...vt].filter(W=>Array.isArray(W?.chunkIds)&&W?.span?.end!==void 0).sort((W,ke)=>{let Ce=W.span?.end??0,et=ke.span?.end??0;return Ce-et}),p=0,M=[];for(let W of l){let ke=W.span?.end;if(typeof ke!="number"||ke<p)continue;let Ce=Array.from(new Set((W.chunkIds??[]).map(Ee=>Ee?O.get(Ee):void 0).map(Ee=>Ee?X.get(Ee):void 0).filter(Ee=>typeof Ee=="number")));if(!Ce.length)continue;let et=Math.min(ke,qe.length),De=ki(qe,et);M.push(qe.slice(p,De));let _e=Ce.map(Ee=>`<a href="#docsearch-source-${Ee}" data-docsearch-cite="${Ee}" style="color: inherit; text-decoration: none;">${Ee}</a>`).join(",");M.push(`<sup>${_e}</sup>`),p=De}return M.push(qe.slice(p)),M.join("")},[vt,qe,X,O]),q=V==="modal"?Ht.Root:kt,j=V==="modal"?Ht.Content:kt,ge=V==="modal"?Ht.Body:kt;return $t(()=>{if(!(V!=="modal"||!he))return document.body.style.overflow="hidden",document.body.onkeydown=l=>{l.key==="Escape"&&(l.preventDefault(),A())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[A,V,he]),se(sa,{children:[a&&v(jt,{leftSection:re&&(B?v("span",{dangerouslySetInnerHTML:{__html:B}}):v(Yn,{size:18})),className:w?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:he,onClick:()=>N(!0),"data-ai-kit-open-button":!0,children:w&&$.get(c||Fe)}),he&&se(q,{opened:!0,className:"doc-search-root",onClose:A,padding:"md",gap:"md",size:"xl",portalProps:V==="modal"?{target:Z,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":pe,"data-ai-kit-variation":V,children:[V==="modal"&&v(Ht.Overlay,{}),se(j,{w:"100%",style:{left:0,...V==="modal"&&!L?.result&&{overflow:"visible"}},children:[V==="modal"&&se(Ht.Header,{style:{zIndex:1e3},children:[v(ri,{className:"doc-search-title-icon"}),v(Ht.Title,{children:$.get(Fe)}),v(Ht.CloseButton,{})]}),v(ge,{w:"100%",style:{zIndex:1001,...V==="modal"&&!L?.result&&{overflow:"visible"}},children:v(Yt,{enabled:V!=="modal",working:ue,variation:V,children:v(qn,{shadow:"sm",radius:"md",p:"md",children:se(bt,{gap:"sm",children:[V!=="modal"&&se(kt,{justify:"space-between",children:[v(ni,{order:4,style:{margin:0},children:$.get(Fe)}),a&&v(jt,{variant:"subtle",color:"gray",size:"xs",onClick:A,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":$.get("Close"),children:v(hi,{size:18,style:{color:pe==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),se(kt,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[v(ai,{style:{flex:1},value:we,onChange:l=>{z(l.currentTarget.value),oe&&ht()},placeholder:oe?$.get("Audio recorded"):$.get("Search the documentation\u2026"),disabled:ue||G||!!oe,onKeyDown:l=>{l.key==="Enter"&&ie&&(l.preventDefault(),o())}}),Vn&&v(sa,{children:oe?v(jt,{variant:"outline",size:"sm",color:"red",onClick:ht,disabled:ue,title:$.get("Clear audio"),children:v(pi,{size:18})}):v(jt,{variant:G?"filled":"outline",size:"sm",color:G?"red":"gray",onClick:G?Xt:Qt,disabled:ue,title:G?$.get("Stop recording"):$.get("Record audio"),style:G?{transform:`scale(${1+Ze/300})`,transition:"transform 0.1s ease-out"}:void 0,children:v(mi,{size:18})})}),v(jt,{variant:"filled",size:"sm",leftSection:st,onClick:()=>{o()},disabled:!ie,className:Q?"doc-search-button":"doc-search-button-no-title",children:Q?$.get("Search"):null}),ue?v(jt,{variant:"outline",size:"sm",onClick:Zt,children:$.get("Stop")}):null]}),!ue&&!Me&&!L?.result?v(nt,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:$.get("Enter a search query to start.")}):null,d&&U&&Xe&&se(bt,{gap:"xs",children:[v(jt,{variant:"subtle",size:"xs",onClick:()=>Ie(!D),leftSection:D?v(ci,{size:14}):v(gi,{size:14}),style:{alignSelf:"flex-start"},children:$.get("Filters")}),v(Qo,{in:D,children:se(bt,{gap:"md",children:[Object.keys(U.allowedCategories).length>0&&se("div",{children:[v(nt,{size:"sm",fw:500,mb:"xs",children:$.get("Categories")}),v(kt,{gap:"md",children:Object.keys(U.allowedCategories).map(l=>v(Fn,{label:$.get(l),checked:Te.includes(l),onChange:p=>{if(p.currentTarget.checked)Ue([...Te,l]);else{Ue(Te.filter(W=>W!==l));let M=U.allowedCategories[l]||[];dt(ne.filter(W=>!M.includes(W)))}},disabled:ue||P},l))})]}),Ne.length>0&&se("div",{children:[v(nt,{size:"sm",fw:500,mb:"xs",children:$.get("Subcategories")}),v(kt,{gap:"md",children:Ne.map(l=>v(Fn,{label:$.get(l),checked:ne.includes(l),onChange:p=>{p.currentTarget.checked?dt([...ne,l]):dt(ne.filter(M=>M!==l))},disabled:ue||P},l))})]}),U.allowedTags.length>0&&v(ei,{label:$.get("Tags"),placeholder:$.get("Select or type tags..."),data:U.allowedTags.map(l=>({value:l,label:$.get(l)})),value:Se,onChange:ct,searchValue:gt,onSearchChange:yt,disabled:ue||P,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Vn&&se(sa,{children:[G&&se(bt,{gap:"xs",children:[se(nt,{size:"xs",c:"dimmed",children:[$.get("Recording...")," \u{1F3A4}"]}),v(ti,{value:Ze,size:"sm",color:"red",animated:!0,striped:!0})]}),oe&&!G&&se(bt,{gap:"xs",children:[v(nt,{size:"xs",c:"dimmed",children:$.get("Recorded audio:")}),v("audio",{controls:!0,src:URL.createObjectURL(oe),className:"ai-kit-audio-player"})]})]}),Me?v(Zo,{color:"red",title:$.get("Error"),children:Me}):null,ue&&Oe&&v(Yt,{enabled:V==="modal",working:!0,variation:V,children:se(kt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[v(Xo,{size:"sm"}),v(nt,{size:"sm",c:"dimmed",children:Oe})]})}),L?.result?se(sa,{children:[v(Wn,{}),se(bt,{gap:"xs","data-doc-search-result":!0,children:[v(nt,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:$.get("AI Summary")}),v(li,{remarkPlugins:[di],rehypePlugins:[ui],components:{a:({href:l,children:p,...M})=>{let W=typeof l=="string"&&l.startsWith("#docsearch-source-");return v("a",{href:l,...M,onClick:ke=>{if(!W)return;ke.preventDefault();let Ce=l.slice(1),et=`#${bi(Ce)}`;(Z??document).querySelector?.(et)?.scrollIntoView({block:"start",behavior:"smooth"})},children:p})}},"data-doc-search-result-content":!0,children:ce||qe})]})]}):null,He&&(L?.citations?.docs?.length||L?.citations?.chunks?.length)?se(sa,{children:[v(Wn,{}),se(bt,{gap:"sm","data-doc-search-sources":!0,children:[v(nt,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:$.get("Sources")}),F.map(({doc:l})=>{let p=l.sourceUrl?.trim()||void 0,M=l.docId?X.get(l.docId):void 0,W=l.title?.trim()||l.docId,ke=se(nt,{fw:600,style:{display:"inline"},children:[M?`${M}. `:"",W]});return v(qn,{withBorder:!0,radius:"md",p:"sm",id:M?`docsearch-source-${M}`:void 0,children:v(bt,{gap:"xs",children:v(kt,{justify:"space-between",align:"flex-start",children:se(bt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[p?v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{K&&(Ce.preventDefault(),K?.(l))},"data-doc-search-source-title":!0,children:ke}):ke,v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{K&&(Ce.preventDefault(),K?.(l))},"data-doc-search-source-url":!0,children:l.sourceUrl}),l.author?v(nt,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:l.author}):null,l.description?v(nt,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:l.description}):null]})})})},l.docId)})]})]}):null,v(da,{variation:V})]})})})})]})]})]})},Ai=Kt(yi);export{$o as AiChatbot,fo as AiFeature,Oa as DEFAULT_CHATBOT_LABELS,Ai as DocSearch,An as isBackendConfigured,za as markdownToHtml,Et as readDefaultOutputLanguage,aa as stripCodeFence,Dt as translations,qt as useAiRun,Kt as withAiKitShell};
31
+ Follow these additional instructions: ${ne}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),O=await T.run(async({signal:j,onStatus:ge})=>(await Pn({messages:X,images:[Ue],outputLanguage:"en",responseConstraint:co},{signal:j,onStatus:ge,context:I,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!O){D("");return}let ce=(P&&P!=="auto"?P:null)||Et(),q=aa(O).trim();try{G("Translating result...");let j=await T.run(async({signal:ge})=>await mo(q,ce,{signal:ge,context:I,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));D(j)}catch(j){D(q),console.warn("AI Kit: failed to parse SEO JSON",j)}break}}}catch(F){Pe(F instanceof Error?F.message:r.get("An unknown error occurred."))}G(void 0)},[K,T,ne,le,P,Ie,Ve,I,d,Me,gt,de,we]),it=It(async()=>{await ze("backend-only")},[ze]),vt=It(o=>{switch(d){case"proofread":return k(ro,{className:o});case"translate":return k(oo,{className:o});case"summarize":return k(lo,{className:o});case"rewrite":case"write":return k(io,{className:o});case"generateImageMetadata":case"generatePostMetadata":return k(so,{className:o});default:return k($r,{mode:d,className:o})}},[d]),qe=It(()=>{switch(d){case"proofread":return T.lastSource?r.get("Proofread again"):r.get("Proofread");case"translate":return T.lastSource?r.get("Translate again"):r.get("Translate");case"rewrite":return T.lastSource?r.get("Rewrite again"):r.get("Rewrite");case"summarize":return T.lastSource?r.get("Summarize again"):r.get("Summarize");default:return T.lastSource?r.get("Regenerate"):r.get("Generate")}},[K,T.lastSource,d]),st=It(()=>{switch(d){case"proofread":return r.get("Proofread on Backend");case"translate":return r.get("Translate on Backend");case"rewrite":return r.get("Rewrite on Backend");case"summarize":return r.get("Summarize on Backend");default:return r.get("Regenerate on Backend")}},[K,d]),Fe=It(async()=>{oe(!1),D(null),Pe(null),L.current=!1,T.reset(),B||pe()},[pe,L,T,B]),Oe=It(async()=>{T.busy&&T.cancel()},[T.busy]);ha(()=>{!fe||!g||!de||T.busy||x||L.current||(L.current=!0,queueMicrotask(()=>{ze(me)}))},[T.busy,L,fe,de,g,x,ze,me]),ha(()=>{we&&d!=="proofread"&&(de||(Ze(!0),L.current=!0))},[we,de,d]),ha(()=>{let o=!0;return(async()=>{try{await to();let A=await An();o&&Qe(A)}catch(A){console.error(A),o&&Qe(!1)}})(),()=>{o=!1}},[]);let Ye=ra(()=>{let o=[];if(d==="translate"){let A=pa.find(F=>F.value===gt)?.label;o.push(r.get("Input language")+": "+(A?r.get(A):"auto"))}if(P&&N?.outputLanguage){let A=pa.find(F=>F.value===P)?.label;o.push(r.get("Output language")+": "+(A?r.get(A):P))}return d==="summarize"&&Me&&N?.type&&o.push(r.get("Type")+": "+r.get(Me)),(d==="write"||d==="rewrite")&&Ve&&N?.tone&&o.push(r.get("Tone")+": "+r.get(Ve)),(d==="write"||d==="rewrite"||d==="summarize")&&le&&N?.length&&o.push(r.get("Length")+": "+r.get(le)),ne?.trim()&&N?.instructions&&o.push(r.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):r.get("No overrides")},[K,d,gt,P,Me,Ve,le,ne]),ie={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Xe=c==="modal"?Ot.Root:Tt,Ne=c==="modal"?Ot.Content:Tt,Qt=c==="modal"?Ot.Body:Tt,Xt=R==="collapse"?qr:zt,ht=R==="horizontal"?Tt:zt;return ha(()=>{if(!(c!=="modal"||!fe))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),Fe())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[Fe,c]),Ae(oa,{children:[B&&k(Ut,{leftSection:ee&&(te?k("span",{dangerouslySetInnerHTML:{__html:te}}):vt()),className:re?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:fe,onClick:()=>oe(!0),"data-ai-kit-open-button":!0,children:re&&r.get(Q||Pt)}),fe&&Ae(Xe,{opened:!0,className:"ai-feature-root",onClose:Fe,padding:"md",gap:"md",size:"md",portalProps:c==="modal"?{target:he,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":V,"data-ai-kit-variation":c,children:[c==="modal"&&k(Ot.Overlay,{}),Ae(Ne,{w:"100%",style:{left:0},children:[c==="modal"&&Ae(Ot.Header,{style:{zIndex:1e3},children:[vt("ai-feature-title-icon"),k(Ot.Title,{children:r.get(Pt)}),k(Ot.CloseButton,{})]}),k(Qt,{w:"100%",style:{zIndex:1001},children:Ae(Yt,{enabled:c!=="modal",working:T.busy,variation:c,children:[Ae(zt,{gap:"sm",mb:"sm",p:"sm",children:[Ge&&k(xa,{color:"red",children:r.get(Ge)}),we&&d!=="proofread"&&Ae(Jr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[Ae(Tt,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>Ze(o=>!o):void 0,children:[R==="collapse"&&Ae(zt,{gap:0,children:[k(Ln,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.get("Options")}),k(Ln,{size:"xs",c:"dimmed",style:{marginTop:2},children:Ye})]}),R==="collapse"&&k(Ut,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),Ze(A=>!A)},children:Lt?r.get("Hide"):r.get("Show")})]}),Ae(Xt,{in:Lt,children:[R==="collapse"&&k(Yr,{my:"sm"}),Ae(ht,{gap:"xs",justify:"space-between",children:[d==="write"&&N?.text&&k(Rt,{label:r.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:k(St,{size:"xs",className:"ai-feature-option",styles:ie,disabled:T.busy,label:r.get("Topic"),description:R!=="horizontal"?r.get("The topic or subject for the AI to write about."):void 0,value:Ie||"",onChange:o=>{let A=o.target.value;Te(A),C?.({text:A})}})}),(d==="write"||d==="rewrite"||d==="generateImageMetadata"||d==="generatePostMetadata")&&N?.instructions&&k(Rt,{label:r.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:k(St,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Instructions"),description:R!=="horizontal"?r.get("Additional instructions to guide the AI."):void 0,value:ne||"",onChange:o=>{let A=o.target.value;dt(A),C?.({instructions:A})}})}),d==="translate"&&k(Rt,{label:r.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",styles:ie,className:"ai-feature-option",label:r.get("Input language"),description:R!=="horizontal"?r.get("The language of the input text."):void 0,data:[{value:"auto",label:r.get("Auto-detect")},...pa.map(o=>({value:o.value,label:r.get(o.label)})).sort((o,A)=>o.label.localeCompare(A.label))],value:gt||"auto",onChange:o=>{let A=o;yt(A),ct(void 0),C?.({inputLanguage:A})}})}),N?.outputLanguage&&k(Rt,{label:r.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",styles:ie,className:"ai-feature-option",label:r.get("Output language"),description:R!=="horizontal"?r.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[d==="rewrite"?{value:"auto",label:r.get("Auto-detect")}:void 0].filter(Boolean),...pa.map(o=>({value:o.value,label:r.get(o.label)})).sort((o,A)=>o.label.localeCompare(A.label))],value:P||En.settings.defaultOutputLanguage||(d==="rewrite"?"auto":""),onChange:o=>{let A=o;mt(A),ct(void 0),C?.({outputLanguage:A})}})}),d==="summarize"&&N?.type&&k(Rt,{label:r.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Type"),description:R!=="horizontal"?r.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.get("Headline")},{value:"key-points",label:r.get("Key Points")},{value:"teaser",label:r.get("Teaser")},{value:"tldr",label:r.get("TL;DR")}],value:Me||"key-points",onChange:o=>{let A=o;Gt(A),C?.({type:A})}})}),(d==="write"||d==="rewrite")&&N?.tone&&k(Rt,{label:r.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Tone"),description:R!=="horizontal"?r.get("The tone or style for the AI to use."):void 0,data:d==="write"?[{value:"neutral",label:r.get("Neutral")},{value:"formal",label:r.get("Formal")},{value:"casual",label:r.get("Casual")}]:[{value:"as-is",label:r.get("As-Is")},{value:"more-formal",label:r.get("More formal")},{value:"more-casual",label:r.get("More casual")}],value:Ve||(d==="write"?"neutral":"as-is"),onChange:o=>{let A=o;ue(A),C?.({tone:A})}})}),(d==="write"||d==="rewrite"||d==="summarize")&&N?.length&&k(Rt,{label:r.get("The target output length."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Length"),description:R!=="horizontal"?r.get("The target output length."):void 0,data:d==="write"||d==="summarize"?[{value:"short",label:r.get("Short")},{value:"medium",label:r.get("Medium")},{value:"long",label:r.get("Long")}]:[{value:"as-is",label:r.get("As-Is")},{value:"shorter",label:r.get("Shorter")},{value:"longer",label:r.get("Longer")}],value:le||(d==="rewrite"?"as-is":"short"),onChange:o=>{let A=o;ot(A),C?.({length:A})}})}),d==="summarize"||d==="write"||d==="rewrite"&&N?.outputFormat&&k(Rt,{label:r.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:k(Vt,{disabled:T.busy,size:"xs",className:"ai-feature-option",styles:ie,label:r.get("Output format"),description:R!=="horizontal"?r.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.get("Plain Text")},{value:"markdown",label:r.get("Markdown")},{value:"html",label:r.get("HTML")}],value:U||"markdown",onChange:o=>{let A=o;At(A),C?.({outputFormat:A})}})})]})]})]}),T.busy&&pt&&k(Yt,{enabled:c==="modal",working:!0,variation:c,children:Ae(Tt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[k(Vr,{size:"sm"}),k(La.Label,{className:"ai-feature-status-text",children:pt})]})}),x&&Ae(zt,{mt:"md",children:[d==="proofread"&&(x.corrections.length===0?k(xa,{color:"green",children:r.get("No issues found. Your text looks great!")}):Ae(oa,{children:[k("p",{style:{marginTop:0,opacity:.85},children:r.get("Hover highlights to see explanations.")}),k(xn,{original:Ie,corrections:x.corrections}),x.correctedInput?Ae(oa,{children:[k("h4",{style:{marginTop:16,marginBottom:8},children:r.get("Corrected")}),k(Tt,{c:"pre",className:"ai-feature-generated-content",children:x.correctedInput})]}):null]})),d==="generateImageMetadata"&&Ae(oa,{children:[k(St,{readOnly:!s,label:r.get("Alt Text"),description:r.get("The alt text for the image."),value:x.alt_text||"",onChange:o=>D({...x,alt_text:o.target.value})}),k(St,{readOnly:!s,label:r.get("Title"),description:r.get("The title for the image."),value:x.title||"",onChange:o=>D({...x,title:o.target.value})}),k(St,{readOnly:!s,label:r.get("Caption"),description:r.get("The caption for the image."),value:x.caption||"",onChange:o=>D({...x,caption:o.target.value})}),k(St,{readOnly:!s,label:r.get("Description"),description:r.get("The description for the image."),value:x.description||"",onChange:o=>D({...x,description:o.target.value})})]}),d==="generatePostMetadata"&&Ae(oa,{children:[k(St,{readOnly:!s,label:r.get("Title"),description:r.get("The title for the post."),value:x.title||"",onChange:o=>D({...x,title:o.target.value})}),k(St,{readOnly:!s,label:r.get("Excerpt"),description:r.get("The excerpt for the post."),value:x.excerpt||"",onChange:o=>D({...x,excerpt:o.target.value})})]}),d!=="proofread"&&d!=="generateImageMetadata"&&d!=="generatePostMetadata"&&typeof x=="string"&&k(Bn,{value:x,editable:!!s,onChange:o=>{D(o)}})]}),x===""&&k(Bn,{value:x,editable:!1})]}),Ae(Tt,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[T.busy&&k(Ut,{variant:"outline",size:"sm",onClick:Oe,"data-ai-kit-cancel-button":!0,children:r.get("Cancel")}),!T.busy&&k(Ut,{variant:"filled",size:"sm",disabled:!de,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:qe()}),!T.busy&&T.lastSource==="on-device"&&ut&&He&&k(Ut,{variant:"filled",size:"sm",disabled:!de,onClick:it,"data-ai-kit-regenerate-on-backend-button":!0,children:st()}),!T.busy&&f&&k(Ut,{variant:"outline",size:"sm",disabled:!x||d==="proofread"&&x.corrections.length===0,onClick:async()=>{f(U==="html"?await za(x):x),Fe()},"data-ai-kit-accept-button":!0,children:r.get(ae)}),k(Ut,{variant:"default",size:"sm",onClick:Fe,"data-ai-kit-close-button":!0,children:r.get("Close")})]}),k(da,{variation:c})]})})]})]})]})};function Bn(t){let{value:n,editable:g,onChange:s}=t;return g?Ae(zt,{p:0,gap:"sm",children:[k(La.Label,{children:r.get("Generated content")}),k(_r,{value:n,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),k(La.Label,{children:r.get("Preview")}),k(zt,{className:"ai-feature-generated-content ai-feature-preview",children:k(Mn,{remarkPlugins:[Dn],children:n})})]}):k(zt,{className:"ai-feature-generated-content",children:n?k(Mn,{remarkPlugins:[Dn],children:n}):k(xa,{color:"yellow",children:r.get("No content generated.")})})}var fo=Kt(ho);import{ActionIcon as Un,Anchor as To,Box as So,Button as tt,Group as Ke,Input as Ro,List as On,Modal as Nt,Stack as at,Text as Le,Textarea as Io}from"@mantine/core";import{IconMaximize as zo,IconMessage as Co,IconMicrophone as xo,IconMinimize as Lo,IconPaperclip as Po,IconPencil as Mo,IconPlayerStop as Do,IconSend as Eo,IconTrash as Bo,IconX as Ko}from"@tabler/icons-react";import{getStoreSelect as Uo,sendChatMessage as Oo,sendFeedbackMessage as No}from"@smart-cloud/ai-kit-core";import{useSelect as jo}from"@wordpress/data";import{I18n as b}from"aws-amplify/utils";import{useCallback as _,useEffect as be,useMemo as ve,useRef as Re,useState as ye}from"react";import Ho from"react-markdown";import Go from"remark-gfm";var ko="ai-kit-chatbot-attachments",lt="attachments";var Pa=null;function bo(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function fa(){if(!bo())return null;Pa||(Pa=new Promise(t=>{try{let n=window.indexedDB.open(ko,1);n.onerror=()=>t(null),n.onblocked=()=>t(null),n.onupgradeneeded=()=>{let g=n.result;g.objectStoreNames.contains(lt)||g.createObjectStore(lt,{keyPath:"id"})},n.onsuccess=()=>t(n.result)}catch(n){console.warn("[AiChatbot] IndexedDB is not available",n),t(null)}}));try{return await Pa}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function Ma(t,n){let g=await fa();return g?new Promise((s,a)=>{try{let c=g.transaction(lt,t),w=c.objectStore(lt),B=n(w);c.oncomplete=()=>s(B),c.onerror=()=>a(c.error),c.onabort=()=>a(c.error)}catch(c){a(c)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Da(t,n,g){await wo();let s={id:t,blob:n,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await Ma("readwrite",c=>(c.put(s),t))}async function Ea(t){let n=await fa();return n?new Promise((g,s)=>{try{let a=n.transaction(lt,"readonly"),c=a.objectStore(lt).get(t);c.onsuccess=()=>{let w=c.result;g(w??null)},c.onerror=()=>s(c.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function yo(t){await Ma("readwrite",n=>{n.delete(t)})}async function ka(){await Ma("readwrite",t=>{t.clear()})}async function Ba(t){let n=await fa();n&&await new Promise((g,s)=>{try{let a=n.transaction(lt,"readwrite"),c=a.objectStore(lt),w=c.getAllKeys();w.onsuccess=()=>{let B=w.result;for(let re of B){let ee=String(re);t.has(ee)||c.delete(re)}},w.onerror=()=>s(w.error),a.oncomplete=()=>g(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var Ao=50*1024*1024;async function vo(){let t=await fa();return t?new Promise((n,g)=>{try{let s=t.transaction(lt,"readonly"),a=s.objectStore(lt).getAll();a.onsuccess=()=>{let c=a.result||[];n(c)},a.onerror=()=>g(a.error),s.onerror=()=>g(s.error),s.onabort=()=>g(s.error)}catch(s){g(s)}}).catch(n=>(console.warn("[AiChatbot] Failed to get all attachments",n),[])):[]}async function wo(){let t=await vo();if(t.length===0)return;let n=t.sort((c,w)=>c.createdAt-w.createdAt),g=n.reduce((c,w)=>c+w.size,0),s=[],a=0;for(;g>Ao&&a<n.length;){let c=n[a];c&&(s.push(c.id),g-=c.size),a++}for(let c of s)await yo(c);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as jn,jsx as m,jsxs as Y}from"react/jsx-runtime";b.putVocabularies(Dt);var ba=1440*60*1e3,Ka=!1,Fo=1,Wo="localstorage",Jt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function Ct(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var qo=4,Yo=5*1024*1024,Vo=t=>{let n=(t?.name||"").toString(),g=(t?.code||"").toString(),s=(t?.message||"").toString();return n==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Jo=(t,n)=>{if(!t)return null;let g=t.step,s=b.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,c=a==null?null:Math.round(a*100);switch(g){case"decide":return s||b.get("Checking capabilities...");case"on-device:init":return s||b.get("Initializing on-device AI...");case"on-device:download":return c==null?s||b.get("Downloading model..."):s||`${b.get("Downloading model...")} ${c}%`;case"on-device:ready":return s||b.get("On-device model ready...");case"on-device:run":return s||b.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return b.get(n.assistantThinkingLabel??Oa.assistantThinkingLabel);case"done":return s||b.get("Done.");case"error":return s||b.get("An error occurred.");default:return s||null}};function Ua(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var _t=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},ya=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},Hn=t=>{!t||t.length===0||t.forEach(n=>ya(n.objectUrl))},Nn=t=>{t.forEach(n=>Hn(n.attachments))},_o=t=>{let{rootElement:n,store:g,previewMode:s,title:a,openButtonTitle:c,openButtonIcon:w,showOpenButtonTitle:B=!0,showOpenButtonIcon:re=!0,colorMode:ee,language:Q,onClose:te,context:He,placeholder:ae,maxImages:R,maxImageBytes:d,historyStorage:I=Wo,emptyHistoryAfterDays:me=Fo,labels:V,openButtonIconLayout:Z="top",openButtonPosition:pe="bottom-right"}=t,f=ve(()=>({...Oa,...V||{}}),[V]),C=qt(),[K,he]=ye(""),[N,we]=ye([]),[z,G]=ye(null),[fe,oe]=ye(!1),[Lt,Ze]=ye(0),ut=Re(null),Qe=Re([]),Ge=Re(null),Pe=Re(null),x=Re(null),[D,Ie]=ye([]),[Te,Ue]=ye(null),[ne,dt]=ye(!1),[Se,ct]=ye(!1),[gt,yt]=ye(!1),[U,At]=ye(!1),[P,mt]=ye(!0),[le,ot]=ye(null),[Ve,ue]=ye(!1),[Me,Gt]=ye(null),[L,Pt]=ye(null),[Zt,Je]=ye(!1),[de,T]=ye(null),pt=Re(de);be(()=>{pt.current=de},[de]);let ze=Re(null),it=Re(!1),[vt,qe]=ye(null),st=Re(null),Fe=Re(null),Oe=Re(null),Ye=Re(null),ie=_(e=>{e.forEach(u=>ya(u.objectUrl))},[]),Xe=_(()=>{ie(O.current),we([]),st.current&&(st.current.value="")},[ie]),Ne=_(()=>{ce.current&&ya(ce.current.objectUrl),G(null),Qe.current=[],Ze(0)},[]),Qt=_(async()=>{try{he(""),Ne();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),u=new MediaRecorder(e,{mimeType:"audio/webm"}),h=new AudioContext,i=h.createMediaStreamSource(e),S=h.createAnalyser();S.fftSize=2048,S.smoothingTimeConstant=.8,i.connect(S),Ge.current=h,Pe.current=S;let y=new Uint8Array(S.fftSize),E=()=>{if(!Pe.current)return;Pe.current.getByteTimeDomainData(y);let J=0;for(let We=0;We<y.length;We++){let Mt=(y[We]-128)/128;J+=Mt*Mt}let xe=Math.sqrt(J/y.length),je=Math.min(100,xe*200);Ze(je),x.current=requestAnimationFrame(E)};E(),Qe.current=[];let H=Date.now();u.ondataavailable=J=>{J.data.size>0&&Qe.current.push(J.data)},u.onstop=()=>{let J=new Blob(Qe.current,{type:"audio/webm"}),xe=(Date.now()-H)/1e3,je=_t(J);je&&G({id:Ct("composer-audio"),blob:J,objectUrl:je,duration:xe}),e.getTracks().forEach(We=>We.stop()),x.current&&(cancelAnimationFrame(x.current),x.current=null),Ge.current&&(Ge.current.close(),Ge.current=null),Pe.current=null,Ze(0)},ut.current=u,u.start(),oe(!0)}catch(e){console.error("Failed to start recording:",e)}},[Ne]),Xt=_(()=>{ut.current&&fe&&(ut.current.stop(),oe(!1))},[fe]);be(()=>()=>{x.current&&cancelAnimationFrame(x.current),Ge.current&&Ge.current.close(),Ne()},[Ne]);let[ht,o]=ye(null),A=Re(K),F=Re(D),X=Re(ht),O=Re(N),ce=Re(z);be(()=>{A.current=K},[K]),be(()=>{O.current=N},[N]),be(()=>{ce.current=z},[z]),be(()=>{F.current=D},[D]),be(()=>{X.current=ht},[ht]),be(()=>{Q&&b.setLanguage(Q||"en")},[Q]);let q=jo(()=>Uo(g).isShowChatbotPreview()),j=ve(()=>Math.max(0,R??qo),[R]),ge=ve(()=>Math.max(0,d??Yo),[d]),l=D.length>0,p=ve(()=>C.busy&&de==="chat",[C.busy,de]),M=ve(()=>p?!1:K.trim().length>0||z!==null,[K,p,z]),W=ve(()=>{let e=c||f.askMeLabel;return b.get(e)},[c,f.askMeLabel,Q]),ke=ve(()=>{let e=a||f.modalTitle;return b.get(e)},[a,f.modalTitle,Q]),Ce=ve(()=>{let e=ae||f.placeholder;return b.get(e)},[ae,f.placeholder,Q]),et=ve(()=>{let e="ai-docs-ask",u=`ai-open-btn--${pe}`;return`${e} ${u}`},[pe]),De=_(()=>{let e=Ye.current;if(e)try{let u=window.innerHeight||document.documentElement.clientHeight,h=360,i=1e3,S=Math.floor(u*.8),y=Math.max(h,Math.min(S,i));e.style.height=`${y}px`}catch{}},[]),_e=_(()=>{let e=L;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[L]),Ee=_(()=>{At(!1),Se&&ct(!1),yt(!1),te?.()},[Se,te]);be(()=>{if(U)return De(),window.addEventListener("resize",De),()=>window.removeEventListener("resize",De)},[U,De]),be(()=>{if(!(!U||!Se))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[U,Se,Ee]);let Ft=ve(()=>N.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[N]);be(()=>{l||mt(!0)},[l]),be(()=>()=>{ie(O.current)},[ie]),be(()=>{let e=L;if(!e)return;let u=()=>{let h=e.scrollHeight-(e.scrollTop+e.clientHeight);mt(h<20)};return e.addEventListener("scroll",u),()=>{e.removeEventListener("scroll",u)}},[U,L]),be(()=>{if(!P)return;let e=L;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[D,C.busy,P,L]),be(()=>{U||ot(null)},[U]);let ea=ve(()=>C.busy?Jo(C.statusEvent,f)||b.get("Working\u2026"):null,[C.busy,C.statusEvent,Q,f]),Jn=ve(()=>{for(let e=D.length-1;e>=0;e--){let u=D[e];if(u.role==="user"&&u.clientStatus==="canceled")return u.id}return null},[D]),ta=_(e=>{Ie(u=>{let h=[...u].map((y,E)=>({m:y,i:E})).reverse().find(y=>y.m.role==="user"&&y.m.clientStatus==="pending")?.i;if(h==null)return u;let i=u.slice(),S=i[h];return i[h]={...S,clientStatus:e??void 0},i})},[Ie]),la=_(()=>{if(!(!C.busy||pt.current!=="chat")){it.current=!0;try{C.cancel()}catch{}ta("canceled"),T(null),Ue(null),_e()}},[C,ta,_e]),_n=_(e=>{let u=O.current,h=Array.from(e.target.files||[]),i=Math.max(0,j-u.length);if(i===0){e.currentTarget.value="";return}let S=[];for(let y of h){if(S.length>=i)break;let E=/image\/(jpeg|png|gif|webp)/i.test(y.type),H=y.size<=ge,J=[...u,...S].some(je=>je.file.name===y.name&&je.file.size===y.size&&je.file.lastModified===y.lastModified);if(!E||!H||J)continue;let xe=_t(y);xe&&S.push({id:Ct("composer-image"),file:y,objectUrl:xe})}S.length&&we(y=>[...y,...S]),e.currentTarget.value=""},[j,ge]),$n=_(e=>{we(u=>{if(e<0||e>=u.length)return u;let h=u[e];return h&&ya(h.objectUrl),u.filter((i,S)=>S!==e)})},[]),wt=Re(null);be(()=>{if(Te)return wt.current&&(window.clearTimeout(wt.current),wt.current=null),wt.current=window.setTimeout(()=>{Ue(null),wt.current=null},6e3),()=>{wt.current&&(window.clearTimeout(wt.current),wt.current=null)}},[Te]);let ja=_(async(e,u)=>{let h=I!=="nostorage",i=[];if(e.length>0){let S=await Promise.all(e.map(async y=>{let E=Ct("attachment-image"),H;if(h)try{H=await Da(E,y.file,{name:y.file.name,type:y.file.type,size:y.file.size})??void 0}catch(xe){console.warn("[AiChatbot] Failed to persist image",xe)}let J=_t(y.file);return{id:E,name:y.file.name,type:y.file.type||"application/octet-stream",size:y.file.size,blobId:H,objectUrl:J??void 0,blob:y.file,mediaType:"image"}}));i.push(...S.filter(Boolean))}if(u){let S=Ct("attachment-audio"),y;if(h)try{y=await Da(S,u.blob,{name:`audio-${Date.now()}.webm`,type:u.blob.type,size:u.blob.size})??void 0}catch(H){console.warn("[AiChatbot] Failed to persist audio",H)}let E=_t(u.blob);i.push({id:S,name:`audio-${Date.now()}.webm`,type:u.blob.type||"audio/webm",size:u.blob.size,blobId:y,objectUrl:E??void 0,blob:u.blob,duration:u.duration,mediaType:"audio"})}return i},[I]),Ha=_(async e=>{let u=[];for(let h of e){let i;if(h.attachments&&h.attachments.length>0){i=[];for(let S of h.attachments){let y;if(S.blobId)try{y=(await Ea(S.blobId))?.blob??void 0}catch(H){console.warn("[AiChatbot] Failed to hydrate attachment",H)}if(!y)continue;let E=y?_t(y):null;i.push({...S,objectUrl:E??void 0,blob:y??void 0})}}u.push({...h,attachments:i})}return u},[]),Ga=_(async e=>{if(!e||e.length===0){Xe();return}let u=[];for(let h of e){let i=h.blob;if(!i&&h.blobId)try{i=(await Ea(h.blobId))?.blob??void 0}catch(E){console.warn("[AiChatbot] Failed to reload attachment",E)}if(!i)continue;let S=i instanceof File?i:new File([i],h.name||"attachment",{type:h.type||i.type||"application/octet-stream"}),y=_t(S);if(y&&(u.push({id:Ct("composer-image"),file:S,objectUrl:y}),u.length>=j))break}if(u.length===0){Xe();return}we(h=>(ie(h),u)),st.current&&(st.current.value="")},[Xe,ie,j]),Aa=_((e,u)=>{e&&ot({url:e,title:u})},[]),Zn=_(()=>{ot(null)},[]),Fa=_(()=>{Nn(F.current),Xe(),Ne(),Ie([]),Ue(null),Oe.current=null,o(null),mt(!0),dt(!1);let e=Ua(I);if(e)try{e.removeItem(Jt)}catch{}ka()},[Xe,Ne,I]),Qn=_(()=>{dt(!0)},[]),Xn=_(()=>{C.busy&&pt.current==="chat"&&la(),Fa()},[C.busy,la,Fa]),Wa=_(()=>{dt(!1)},[]),qa=_(async(e,u)=>{if(!C.busy)try{let h=Oe.current&&Date.now()-Oe.current.storedAt<me*ba?Oe.current.id:void 0;if(!h)return;T("feedback"),Ue(null),await C.run(async({signal:i,onStatus:S})=>(await No({sessionId:h,feedbackMessageId:e,feedbackType:u},{signal:i,onStatus:S,context:He}),null)),Ue(null)}catch(h){let i=h?.message?.trim()||b.get("An error occurred.");Ue(i),console.error("Failed to send feedback",h)}finally{T(h=>h==="feedback"?null:h)}},[C,Q]),Ya=_((e,u)=>{Ie(h=>h.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===u?{...i,feedback:void 0}:{...i,feedback:u})),qa(e,u)},[qa]),ua=_(async()=>{let e=A.current.trim(),u=ce.current;if(!e&&!u||C.busy)return;it.current=!1,Ue(null),T("chat");let h=[...O.current],i=await ja(h,u),S=Ct("user"),y=Date.now(),E={id:S,role:"user",content:e||(u?"[Audio message]":""),createdAt:y,clientStatus:"pending",attachments:i.length?i:void 0};he(""),Xe(),Ne(),Ie(H=>[...H,E]),U||At(!0),_e();try{let H=Oe.current&&Date.now()-Oe.current.storedAt<me*ba?Oe.current.id:void 0,J=await C.run(async({signal:je,onStatus:We})=>await Oo({sessionId:H,message:e||void 0,audio:u?.blob,images:h.map(cr=>cr.file)},{signal:je,onStatus:We,context:He}));if(it.current){ta("canceled");return}if(!J)throw new Error(b.get(C.error??f.emptyResponseLabel));J.sessionId&&(Oe.current={id:J.sessionId,storedAt:Date.now()});let xe={id:J.metadata?.messageId||Ct("assistant"),role:"assistant",content:J.result||"",citations:J.citations,createdAt:Date.now()};Ie(je=>[...je.map(Mt=>Mt.id===S?{...Mt,clientStatus:void 0}:Mt),xe]),o(y)}catch(H){if(console.error("Error during ask()",H),it.current||Vo(H)){ta("canceled");return}let J=H?.message?.trim()||b.get(f.unexpectedErrorLabel);Ie(xe=>[...xe.map(We=>We.id===S?{...We,clientStatus:void 0}:We),{id:Ct("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${J}`,createdAt:Date.now()}]),o(y)}finally{T(H=>H==="chat"?null:H),it.current=!1,Fe.current&&Fe.current.focus(),_e()}},[C,ja,Xe,Ne,U,_e,ta,f.emptyResponseLabel,f.unexpectedErrorLabel,Q]),er=_(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),M&&ua())},[ua,M]),tr=_(()=>{At(!0)},[]);be(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let ar=_(()=>{ct(e=>{let u=!e;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),u?(yt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{yt(!1),ze.current=null})})):yt(!1),u})},[]),nr=_(e=>{he(e.content),(async()=>(await Ga(e.attachments),Ie(u=>u.filter(h=>h.id!==e.id)),Hn(e.attachments),queueMicrotask(()=>Fe.current?.focus())))()},[Ga]),Va=ve(()=>re?w?m("img",{src:w,className:"ai-open-btn-icon",alt:b.get(f.askMeLabel||W)}):m(Co,{size:18}):null,[re,w,f,W,Q]),rr=ve(()=>{let e=Va,u=B?m(Le,{inherit:!0,children:W}):null;if(!re&&!u)return null;if(!re)return u;if(!B)return e;switch(Z){case"top":return Y(at,{gap:4,align:"center",children:[e,u]});case"bottom":return Y(at,{gap:4,align:"center",children:[u,e]});case"right":return Y(Ke,{gap:6,align:"center",children:[u,e]});default:return Y(Ke,{gap:6,align:"center",children:[e,u]})}},[Va,re,B,W,Z]),or=ve(()=>p,[p]),ir=ve(()=>!p,[p]),sr=ve(()=>Te||(l?b.get(f.readyLabel):b.get(f.readyEmptyLabel)),[Te,l,f.readyLabel,f.readyEmptyLabel,Q]),lr=ve(()=>p?b.get(f.cancelLabel):b.get(f.sendLabel),[p,f.cancelLabel,f.sendLabel,Q]),ur=ve(()=>p?m(Do,{size:18}):m(Eo,{size:18}),[p]),dr=_(()=>{if(p){la();return}ua()},[p,la,ua]);return be(()=>{if(!U||!Me||!L)return;let e=()=>{let H=window.getComputedStyle(L).overflowY,J=H==="auto"||H==="scroll",xe=Math.ceil(L.scrollHeight),je=Math.floor(L.clientHeight),We=xe>je;return J&&We},u=!1,h=E=>{if(!e())return;E.preventDefault();let H=L.scrollHeight-L.clientHeight;L.scrollTop=Math.max(0,Math.min(H,L.scrollTop+E.deltaY))},i=()=>{let E=e();Je(E),E!==u&&(u=E,u?Me.addEventListener("wheel",h,{passive:!1}):Me.removeEventListener("wheel",h))};i();let S=new ResizeObserver(i);S.observe(L);let y=new MutationObserver(i);return y.observe(L,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{u&&Me.removeEventListener("wheel",h),S.disconnect(),y.disconnect(),window.removeEventListener("resize",i)}},[U,Me,L]),be(()=>{let e=!1,u=Ua(I);if(!u){I==="nostorage"&&ka(),ue(!0);return}return(async()=>{try{let h=u.getItem(Jt);if(!h){ue(!0);return}let i=JSON.parse(h),S=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!S||Date.now()-S>me*ba){u.removeItem(Jt),await ka(),ue(!0);return}let E=(Array.isArray(i.messages)?i.messages:[]).map(J=>J?.role==="user"&&J.clientStatus==="pending"?{...J,clientStatus:"canceled"}:J),H=await Ha(E);if(e){Nn(H);return}Ie(H),o(S),i.session&&i.session.id&&(Oe.current=i.session)}catch(h){console.warn("[AiChatbot] Failed to load history",h);try{u.removeItem(Jt)}catch{}}finally{e||ue(!0)}})(),()=>{e=!0}},[I,me,Ha]),be(()=>{if(!Ve)return;let e=Ua(I);if(!e)return;let u=X.current;if(!u)return;if(Date.now()-u>me*ba){try{e.removeItem(Jt)}catch{}Ba(new Set);return}let h=D.map(({attachments:y,...E})=>({...E,attachments:y?.map(({objectUrl:H,blob:J,...xe})=>xe)})),i={version:1,lastUserSentAt:u,session:Oe.current,messages:h};try{e.setItem(Jt,JSON.stringify(i))}catch{}let S=new Set;h.forEach(y=>{y.attachments?.forEach(E=>{E.blobId&&S.add(E.blobId)})}),Ba(S)},[Ve,D,ht,I,me]),s&&!q||!s&&q?null:Y(Ke,{className:et,children:[!U&&m(tt,{variant:"filled",className:B?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:tr,"aria-label":W,title:W,"data-ai-kit-open-button":!0,children:rr}),U&&m(Nt.Root,{ref:Ye,opened:U,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Ee,className:et+" ai-chat-container"+(Se?" maximized":"")+(Se&&gt?" ai-max-enter":""),portalProps:{target:n,reuseTargetNode:!0},"data-ai-kit-theme":ee,"data-ai-kit-variation":"modal",children:Y("div",{className:"ai-chat-container-internal",ref:Gt,children:[Y(Nt.Header,{className:"ai-chat-header-bar",children:[m(Nt.Title,{className:"ai-chat-title",children:ke}),Y(Ke,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&m(Un,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:ar,title:Se?b.get(f.restoreSizeLabel):b.get(f.maximizeLabel),"aria-label":Se?b.get(f.restoreSizeLabel):b.get(f.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Se?m(Lo,{size:16}):m(zo,{size:16})}),m(Nt.CloseButton,{"aria-label":b.get(f.closeChatLabel)})]})]}),Y(Nt.Body,{className:"ai-chat-scroll",ref:Pt,"data-scrollable":Zt?"true":"false",children:[D.map(e=>{let u=e.role==="user",h=u&&e.clientStatus==="canceled"&&e.id===Jn;return m(Ke,{justify:u?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>qe(e.id),onMouseLeave:()=>qe(i=>i===e.id?null:i),children:Y(at,{gap:4,w:"100%",style:{alignItems:u?"flex-end":"flex-start"},children:[Y(at,{className:"ai-chat-bubble",children:[Y(Le,{className:"ai-chat-header",children:[m(Le,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:u?b.get(f.userLabel):b.get(f.assistantLabel)}),"\xA0",m(Le,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?m(Ho,{remarkPlugins:[Go],children:e.content}):m(Le,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&Y(at,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&m(Ke,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>m("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>Aa(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||b.get("View image"),"aria-label":i.name||b.get("View image"),children:!i.objectUrl&&m(Le,{size:"xs",c:"dimmed",children:b.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>m(So,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?Y(at,{gap:"xs",children:[m("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&Y(Le,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):m(Le,{size:"xs",c:"dimmed",children:b.get("Audio no longer available")})},i.id))]}),h&&Y(Ke,{justify:"flex-end",gap:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:m("em",{children:b.get(f.notSentLabel)})}),vt===e.id&&m(Un,{size:"sm",variant:"subtle",onClick:()=>nr(e),title:b.get(f.editLabel),"aria-label":b.get(f.editLabel),"data-ai-kit-edit-button":!0,children:m(Mo,{size:14})})]}),e.citations&&e.citations.length>0&&Y(at,{className:"ai-citations",children:[m(Le,{fw:"bold",size:"sm",mb:"xs",children:b.get(f.referencesLabel)}),m(On,{spacing:"xs",size:"sm",children:e.citations.map((i,S)=>{let y=i.sourceUrl||i.url,E=i.title||y||`${b.get(f.referenceLabel)} #${S+1}`;return Y(On.Item,{children:[y?m(To,{href:y,target:"_blank",rel:"noreferrer",children:E}):m(Le,{children:E}),i.snippet?m(Le,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},S)})})]}),e.role==="assistant"&&Y(Ke,{className:"ai-feedback",gap:"xs",children:[m(tt,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>Ya(e.id,"accepted"),"aria-label":b.get(f.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),m(tt,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>Ya(e.id,"rejected"),"aria-label":b.get(f.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),or&&m(Ke,{justify:"flex-start",className:"ai-chat-row assistant status",children:Y(at,{className:"ai-chat-bubble typing",children:[ea?m(Le,{size:"sm",c:"dimmed",children:m("em",{children:ea})}):null,Y("div",{className:"typing-indicator",children:[m("span",{}),m("span",{}),m("span",{})]})]})})]}),ir&&m(Ke,{className:"ai-status-line",children:m(Le,{className:"ai-status-text",children:m("em",{children:sr})})}),Y(at,{className:"ai-box ai-box-open",children:[Y(Nt,{opened:ne,onClose:Wa,centered:!0,title:b.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[m(Le,{size:"sm",children:b.get("Are you sure you want to reset the conversation?")}),Y(Ke,{justify:"flex-end",mt:"md",children:[m(tt,{variant:"default",onClick:Wa,"data-ai-kit-no-button":!0,children:b.get("No")}),m(tt,{color:"var(--ai-kit-color-danger, red)",onClick:Xn,disabled:!l&&!p,"data-ai-kit-yes-button":!0,children:b.get("Yes")})]})]}),m(Ke,{children:m(Io,{className:"ai-message",ref:Fe,placeholder:Ce,value:K,onChange:e=>{he(e.target.value),z&&Ne()},onKeyDown:er,rows:3,disabled:fe||!!z})}),Ka&&fe&&Y(at,{gap:"xs",mt:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:m("em",{children:b.get("Recording...")})}),m("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:m("div",{style:{width:`${Lt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Ka&&z&&!fe&&Y(at,{gap:"xs",mt:"xs",children:[m(Le,{size:"xs",c:"dimmed",children:Y("em",{children:[b.get("Audio recorded")," (",Math.round(z.duration),"s)"]})}),m("audio",{className:"ai-kit-audio-player",controls:!0,src:z.objectUrl})]}),Y(Ke,{className:"ai-actions",justify:"space-between",w:"100%",children:[m(Ke,{justify:"flex-start",children:m(tt,{variant:"light",leftSection:m(Bo,{size:18}),onClick:Qn,disabled:!l&&!p,"data-ai-kit-reset-button":!0,children:b.get(f.resetLabel)})}),Y(Ke,{justify:"flex-end",children:[Ka&&m(jn,{children:z?m(tt,{variant:"outline",leftSection:m(Ko,{size:18}),onClick:Ne,disabled:p,title:b.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:b.get("Clear")}):m(tt,{variant:"outline",leftSection:m(xo,{size:18}),onClick:fe?Xt:Qt,disabled:p,title:fe?b.get("Stop recording"):b.get("Record audio"),color:fe?"red":void 0,"data-ai-kit-microphone-button":!0,children:fe?b.get("Stop"):b.get("Record")})}),j>0&&Y(jn,{children:[m(tt,{variant:"outline",leftSection:m(Po,{size:18}),onClick:()=>st.current?.click(),disabled:N.length>=j||p||fe||!!z,title:b.get(f.addImageLabel),"data-ai-kit-add-image-button":!0,children:b.get(f.addLabel)}),m(Ro,{ref:st,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:_n})]}),m(tt,{leftSection:ur,variant:"filled",onClick:dr,disabled:!p&&!M,"data-ai-kit-send-button":!0,children:lr})]})]}),Ft.length>0&&m(Ke,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ft.map(({url:e,title:u},h)=>m("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":u||b.get("View image"),onClick:()=>Aa(e,u),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),Aa(e,u))},children:m(tt,{variant:"white",onClick:i=>{i.stopPropagation(),$n(h)},"aria-label":b.get(f.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:b.get(f.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},N[h]?.id??h))})]})]})}),m(Nt,{opened:!!le,onClose:Zn,centered:!0,size:"auto",title:le?.title||b.get("Image preview"),children:le&&m("img",{src:le.url,alt:le.title||b.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},$o=Kt(_o,{showOpenButton:!0,variation:"modal"});import{Alert as Zo,Anchor as Gn,Button as jt,Checkbox as Fn,Collapse as Qo,Divider as Wn,Group as kt,Loader as Xo,Modal as Ht,MultiSelect as ei,Paper as qn,Progress as ti,Stack as bt,Text as nt,TextInput as ai,Title as ni}from"@mantine/core";import{AiKitDocSearchIcon as ri,dispatchBackend as oi,resolveBackend as ii,sendSearchMessage as si}from"@smart-cloud/ai-kit-core";import{I18n as $}from"aws-amplify/utils";import{useCallback as ia,useEffect as $t,useMemo as rt,useRef as xt,useState as $e}from"react";import li from"react-markdown";import ui from"rehype-raw";import di from"remark-gfm";import{IconChevronDown as ci,IconChevronRight as gi,IconMicrophone as mi,IconMicrophoneOff as pi,IconSearch as Yn,IconX as hi}from"@tabler/icons-react";import{Fragment as sa,jsx as v,jsxs as se}from"react/jsx-runtime";$.putVocabularies(Dt);var Vn=!1;function fi(t){let n=t?.citations?.docs??[],g=t?.citations?.chunks??[],s=new Map;for(let a of n)s.set(a.docId,{doc:a,chunks:[]});for(let a of g){let c=s.get(a.docId);c?c.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}function Na(t){return!!t&&/[\p{L}\p{N}_]/u.test(t)}function ki(t,n){let g=t.length;if(n<=0)return 0;if(n>=g)return g;let s=t[n-1]??"",a=t[n]??"";if(Na(s)&&Na(a)){let c=n;for(;c<g&&Na(t[c]??"");)c++;return c}return n}function bi(t){let n=globalThis?.CSS?.escape;return typeof n=="function"?n(t):t.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}var yi=t=>{let{autoRun:n=!0,context:g,title:s,showOpenButton:a=!1,openButtonTitle:c,showOpenButtonTitle:w=!0,openButtonIcon:B,showOpenButtonIcon:re=!0,searchButtonIcon:ee,showSearchButtonTitle:Q=!0,showSearchButtonIcon:te=!0,showSources:He=!0,topK:ae=10,getSearchText:R,enableUserFilters:d=!1,availableCategories:I,availableTags:me,variation:V,rootElement:Z,colorMode:pe,language:f,onClose:C,onClickDoc:K}=t,[he,N]=$e(!a),[we,z]=$e(""),[G,fe]=$e(!1),[oe,Lt]=$e(null),[Ze,ut]=$e(0),Qe=xt(null),Ge=xt([]),Pe=xt(null),x=xt(null),[D,Ie]=$e(!1),[Te,Ue]=$e([]),[ne,dt]=$e([]),[Se,ct]=$e([]),[gt,yt]=$e(""),[U,At]=$e(null),[P,mt]=$e(!1),le=xt(null),ot=xt(null),Ve=1440*60*1e3,{busy:ue,error:Me,statusEvent:Gt,result:L,run:Pt,cancel:Zt,reset:Je}=qt(),de=xt(!1),T=xt([]),pt=L?.sessionId,ze=L?.citations?.docs??[],it=L?.citations?.chunks??[],vt=L?.citations?.anchors??[],qe=L?.result??"",st=rt(()=>{if(te)return ee?.trim()?v("img",{src:ee,alt:"",style:{width:18,height:18,objectFit:"contain"}}):v(Yn,{size:18})},[ee,te]),Fe=rt(()=>(f&&$.setLanguage(f||"en"),$.get(s||"Search with AI-Kit")),[f]),Oe=rt(()=>Gt?$.get("Searching\u2026"):null,[f,Gt]),Ye=rt(()=>we||R,[we,R]),ie=rt(()=>{if(ue||!he)return!1;let l=typeof Ye=="function"?Ye():Ye;return!!(l&&l.trim().length>0||oe)},[Ye,ue,oe,he]),Xe=rt(()=>{if(!U)return!1;let l=Object.keys(U.allowedCategories).length>0,p=U.allowedTags.length>0;return l||p},[U]),Ne=rt(()=>Te.length===0||!U?[]:Te.flatMap(l=>U.allowedCategories[l]||[]).filter((l,p,M)=>M.indexOf(l)===p),[Te,U]),Qt=ia(async()=>{try{z("");let l=await navigator.mediaDevices.getUserMedia({audio:!0}),p=new MediaRecorder(l,{mimeType:"audio/webm"}),M=new AudioContext,W=M.createMediaStreamSource(l),ke=M.createAnalyser();ke.fftSize=2048,ke.smoothingTimeConstant=.8,W.connect(ke),Pe.current=M,x.current=ke;let Ce=new Uint8Array(ke.fftSize),et=()=>{if(!x.current)return;x.current.getByteTimeDomainData(Ce);let De=0;for(let Ft=0;Ft<Ce.length;Ft++){let ea=(Ce[Ft]-128)/128;De+=ea*ea}let _e=Math.sqrt(De/Ce.length),Ee=Math.min(100,_e*200);ut(Ee),le.current=requestAnimationFrame(et)};et(),Ge.current=[],p.ondataavailable=De=>{De.data.size>0&&Ge.current.push(De.data)},p.onstop=()=>{let De=new Blob(Ge.current,{type:"audio/webm"});Lt(De),l.getTracks().forEach(_e=>_e.stop()),le.current&&(cancelAnimationFrame(le.current),le.current=null),Pe.current&&(Pe.current.close(),Pe.current=null),x.current=null,ut(0)},Qe.current=p,p.start(),fe(!0)}catch(l){console.error("Failed to start recording:",l)}},[]),Xt=ia(()=>{Qe.current&&G&&(Qe.current.stop(),fe(!1))},[G]),ht=ia(()=>{Lt(null),Ge.current=[],ut(0),ot.current=null},[]);$t(()=>()=>{le.current&&cancelAnimationFrame(le.current),Pe.current&&Pe.current.close()},[]),$t(()=>{if(!d)return;if(I||me){At({allowedCategories:I||{},allowedTags:me||[]});return}(async()=>{mt(!0);try{let p=await ii();if(!p.available){console.error("Backend not available for metadata options");return}let M={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:p.available,backendTransport:p.transport,backendApiName:p.apiName,backendBaseUrl:p.baseUrl,reason:p.reason??""},W=await oi(M,g??"frontend","/kb/metadata-options","GET",null,{});At({allowedCategories:W.allowedCategories||{},allowedTags:W.allowedTags||[]})}catch(p){console.error("Failed to load metadata options:",p)}finally{mt(!1)}})()},[d,I,me,g]);let o=ia(async()=>{let l;if(!oe){if(l=typeof Ye=="function"?Ye():Ye,!l)return;z(l)}let p=Date.now(),M=oe&&ot.current?.blob===oe&&p-ot.current.uploadTimestamp<Ve;oe&&!M&&(ot.current={blob:oe,uploadTimestamp:p}),Je(),await Pt(async({signal:W,onStatus:ke})=>await si({sessionId:pt,...l&&{query:l},...oe&&{audio:oe},topK:ae,...d&&{userSelectedCategories:Te},...d&&ne.length>0&&{userSelectedSubcategories:ne},...d&&Se.length>0&&{userSelectedTags:Se}},{signal:W,onStatus:ke,context:g}))},[g,Ye,oe,Pt,Je,ae,pt,d,Te,ne,Se]),A=ia(async()=>{N(!1),Je(),a||C()},[C,Je,de,a]);$t(()=>{!n||!ie||ue||de.current||(de.current=!0,queueMicrotask(()=>{o()}))},[ue,de,ie,n,o]),$t(()=>{ie||(de.current=!0)},[ie]),$t(()=>{let l=T.current,p=Te;(l.length!==p.length||!p.every(W=>l.includes(W)))&&l.length>0&&Je(),T.current=[...p]},[Te,Je]);let F=rt(()=>fi(L),[L]),X=rt(()=>{let l=new Map;return ze.forEach((p,M)=>{p?.docId&&l.set(p.docId,M+1)}),l},[ze]),O=rt(()=>{let l=new Map;return it.forEach(p=>{p?.chunkId&&p?.docId&&l.set(p.chunkId,p.docId)}),l},[it]),ce=rt(()=>{if(!qe)return"";if(!vt.length||X.size===0)return qe;let l=[...vt].filter(W=>Array.isArray(W?.chunkIds)&&W?.span?.end!==void 0).sort((W,ke)=>{let Ce=W.span?.end??0,et=ke.span?.end??0;return Ce-et}),p=0,M=[];for(let W of l){let ke=W.span?.end;if(typeof ke!="number"||ke<p)continue;let Ce=Array.from(new Set((W.chunkIds??[]).map(Ee=>Ee?O.get(Ee):void 0).map(Ee=>Ee?X.get(Ee):void 0).filter(Ee=>typeof Ee=="number")));if(!Ce.length)continue;let et=Math.min(ke,qe.length),De=ki(qe,et);M.push(qe.slice(p,De));let _e=Ce.map(Ee=>`<a href="#docsearch-source-${Ee}" data-docsearch-cite="${Ee}" style="color: inherit; text-decoration: none;">${Ee}</a>`).join(",");M.push(`<sup>${_e}</sup>`),p=De}return M.push(qe.slice(p)),M.join("")},[vt,qe,X,O]),q=V==="modal"?Ht.Root:kt,j=V==="modal"?Ht.Content:kt,ge=V==="modal"?Ht.Body:kt;return $t(()=>{if(!(V!=="modal"||!he))return document.body.style.overflow="hidden",document.body.onkeydown=l=>{l.key==="Escape"&&(l.preventDefault(),A())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[A,V,he]),se(sa,{children:[a&&v(jt,{leftSection:re&&(B?v("span",{dangerouslySetInnerHTML:{__html:B}}):v(Yn,{size:18})),className:w?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:he,onClick:()=>N(!0),"data-ai-kit-open-button":!0,children:w&&$.get(c||Fe)}),he&&se(q,{opened:!0,className:"doc-search-root",onClose:A,padding:"md",gap:"md",size:"xl",portalProps:V==="modal"?{target:Z,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":pe,"data-ai-kit-variation":V,children:[V==="modal"&&v(Ht.Overlay,{}),se(j,{w:"100%",style:{left:0,...V==="modal"&&!L?.result&&{overflow:"visible"}},children:[V==="modal"&&se(Ht.Header,{style:{zIndex:1e3},children:[v(ri,{className:"doc-search-title-icon"}),v(Ht.Title,{children:$.get(Fe)}),v(Ht.CloseButton,{})]}),v(ge,{w:"100%",style:{zIndex:1001,...V==="modal"&&!L?.result&&{overflow:"visible"}},children:v(Yt,{enabled:V!=="modal",working:ue,variation:V,children:v(qn,{shadow:"sm",radius:"md",p:"md",children:se(bt,{gap:"sm",children:[V!=="modal"&&se(kt,{justify:"space-between",children:[v(ni,{order:4,style:{margin:0},children:$.get(Fe)}),a&&v(jt,{variant:"subtle",color:"gray",size:"xs",onClick:A,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":$.get("Close"),children:v(hi,{size:18,style:{color:pe==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),se(kt,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[v(ai,{style:{flex:1},value:we,onChange:l=>{z(l.currentTarget.value),oe&&ht()},placeholder:oe?$.get("Audio recorded"):$.get("Search the documentation\u2026"),disabled:ue||G||!!oe,onKeyDown:l=>{l.key==="Enter"&&ie&&(l.preventDefault(),o())}}),Vn&&v(sa,{children:oe?v(jt,{variant:"outline",size:"sm",color:"red",onClick:ht,disabled:ue,title:$.get("Clear audio"),children:v(pi,{size:18})}):v(jt,{variant:G?"filled":"outline",size:"sm",color:G?"red":"gray",onClick:G?Xt:Qt,disabled:ue,title:G?$.get("Stop recording"):$.get("Record audio"),style:G?{transform:`scale(${1+Ze/300})`,transition:"transform 0.1s ease-out"}:void 0,children:v(mi,{size:18})})}),v(jt,{variant:"filled",size:"sm",leftSection:st,onClick:()=>{o()},disabled:!ie,className:Q?"doc-search-button":"doc-search-button-no-title",children:Q?$.get("Search"):null}),ue?v(jt,{variant:"outline",size:"sm",onClick:Zt,children:$.get("Stop")}):null]}),!ue&&!Me&&!L?.result?v(nt,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:$.get("Enter a search query to start.")}):null,d&&U&&Xe&&se(bt,{gap:"xs",children:[v(jt,{variant:"subtle",size:"xs",onClick:()=>Ie(!D),leftSection:D?v(ci,{size:14}):v(gi,{size:14}),style:{alignSelf:"flex-start"},children:$.get("Filters")}),v(Qo,{in:D,children:se(bt,{gap:"md",children:[Object.keys(U.allowedCategories).length>0&&se("div",{children:[v(nt,{size:"sm",fw:500,mb:"xs",children:$.get("Categories")}),v(kt,{gap:"md",children:Object.keys(U.allowedCategories).map(l=>v(Fn,{label:$.get(l),checked:Te.includes(l),onChange:p=>{if(p.currentTarget.checked)Ue([...Te,l]);else{Ue(Te.filter(W=>W!==l));let M=U.allowedCategories[l]||[];dt(ne.filter(W=>!M.includes(W)))}},disabled:ue||P},l))})]}),Ne.length>0&&se("div",{children:[v(nt,{size:"sm",fw:500,mb:"xs",children:$.get("Subcategories")}),v(kt,{gap:"md",children:Ne.map(l=>v(Fn,{label:$.get(l),checked:ne.includes(l),onChange:p=>{p.currentTarget.checked?dt([...ne,l]):dt(ne.filter(M=>M!==l))},disabled:ue||P},l))})]}),U.allowedTags.length>0&&v(ei,{label:$.get("Tags"),placeholder:$.get("Select or type tags..."),data:U.allowedTags.map(l=>({value:l,label:$.get(l)})),value:Se,onChange:ct,searchValue:gt,onSearchChange:yt,disabled:ue||P,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Vn&&se(sa,{children:[G&&se(bt,{gap:"xs",children:[se(nt,{size:"xs",c:"dimmed",children:[$.get("Recording...")," \u{1F3A4}"]}),v(ti,{value:Ze,size:"sm",color:"red",animated:!0,striped:!0})]}),oe&&!G&&se(bt,{gap:"xs",children:[v(nt,{size:"xs",c:"dimmed",children:$.get("Recorded audio:")}),v("audio",{controls:!0,src:URL.createObjectURL(oe),className:"ai-kit-audio-player"})]})]}),Me?v(Zo,{color:"red",title:$.get("Error"),children:Me}):null,ue&&Oe&&v(Yt,{enabled:V==="modal",working:!0,variation:V,children:se(kt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[v(Xo,{size:"sm"}),v(nt,{size:"sm",c:"dimmed",children:Oe})]})}),L?.result?se(sa,{children:[v(Wn,{}),se(bt,{gap:"xs","data-doc-search-result":!0,children:[v(nt,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:$.get("AI Summary")}),v(li,{remarkPlugins:[di],rehypePlugins:[ui],components:{a:({href:l,children:p,...M})=>{let W=typeof l=="string"&&l.startsWith("#docsearch-source-");return v("a",{href:l,...M,onClick:ke=>{if(!W)return;ke.preventDefault();let Ce=l.slice(1),et=`#${bi(Ce)}`;(Z??document).querySelector?.(et)?.scrollIntoView({block:"start",behavior:"smooth"})},children:p})}},"data-doc-search-result-content":!0,children:ce||qe})]})]}):null,He&&(L?.citations?.docs?.length||L?.citations?.chunks?.length)?se(sa,{children:[v(Wn,{}),se(bt,{gap:"sm","data-doc-search-sources":!0,children:[v(nt,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:$.get("Sources")}),F.map(({doc:l})=>{let p=l.sourceUrl?.trim()||void 0,M=l.docId?X.get(l.docId):void 0,W=l.title?.trim()||l.docId,ke=se(nt,{fw:600,style:{display:"inline"},children:[M?`${M}. `:"",W]});return v(qn,{withBorder:!0,radius:"md",p:"sm",id:M?`docsearch-source-${M}`:void 0,style:{wordBreak:"break-word"},children:v(bt,{gap:"xs",children:v(kt,{justify:"space-between",align:"flex-start",children:se(bt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[p?v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{K&&(Ce.preventDefault(),K?.(l))},"data-doc-search-source-title":!0,children:ke}):ke,v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ce=>{K&&(Ce.preventDefault(),K?.(l))},"data-doc-search-source-url":!0,children:l.sourceUrl}),l.author?v(nt,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:l.author}):null,l.description?v(nt,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:l.description}):null]})})})},l.docId)})]})]}):null,v(da,{variation:V})]})})})})]})]})]})},Ai=Kt(yi);export{$o as AiChatbot,fo as AiFeature,Oa as DEFAULT_CHATBOT_LABELS,Ai as DocSearch,An as isBackendConfigured,za as markdownToHtml,Et as readDefaultOutputLanguage,aa as stripCodeFence,Dt as translations,qt as useAiRun,Kt as withAiKitShell};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/ai-kit-ui",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -1123,6 +1123,7 @@ const DocSearchBase: FC<Props> = (props) => {
1123
1123
  ? `docsearch-source-${docNumber}`
1124
1124
  : undefined
1125
1125
  }
1126
+ style={{ wordBreak: "break-word" }}
1126
1127
  >
1127
1128
  <Stack gap="xs">
1128
1129
  <Group