deep-chat-dev 9.0.306 → 9.0.307

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/deepChat.js CHANGED
@@ -12,7 +12,7 @@ function clear(){var t,s;var e=window.scrollY;this.inputElementRef.classList.con
12
12
  // More details in this Stack Overflow question:
13
13
  // https://stackoverflow.com/questions/76285135/prevent-automatic-scroll-when-text-is-inserted-into-contenteditable-div
14
14
  // prettier-ignore
15
- },{key:"preventAutomaticScrollUpOnNewLine",value:function preventAutomaticScrollUpOnNewLine(e){var t;e.addEventListener("keydown",function(){t=window.scrollY;}),e.addEventListener("input",function(){t!==window.scrollY&&window.scrollTo({top:t});});}}]);}();gt.TEXT_INPUT_ID="text-input";var js=gt;var Is=/*#__PURE__*/function(){function Is(){_classCallCheck(this,Is);}return _createClass(Is,null,[{key:"focusEndOfInput",value:function focusEndOfInput(e){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var s=window.getSelection();s==null||s.removeAllRanges(),s==null||s.addRange(t);}},{key:"focusFromParentElement",value:function focusFromParentElement(e){var t=e.querySelector("#".concat(js.TEXT_INPUT_ID));t&&(Ye.IS_SAFARI&&t.focus(),Is.focusEndOfInput(t));}}]);}();function Cn(r){return r.charAt(0).toUpperCase()+r.slice(1);}function Pr(r){return r&&JSON.stringify(r);}function tn(r,e,t,s){var i="\n".concat(Cn(e)," message: ").concat(JSON.stringify(r)," \n"),n=t?"".concat(Cn(e)," message after interceptor: ").concat(Pr(s)," \n"):"";return i+n;}function Dr(r,e,t,s){return"".concat(tn(r,e,t,s),"Make sure the ").concat(e," message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor");}function Br(r,e,t){var s="response";return"".concat(tn(r,s,e,t),"Make sure the ").concat(s," message is using the {text: string} format, e.g: {text: \"Model Response\"}");}function Fr(r,e){var t="request";return"".concat(tn(r,t,e),"Make sure the ").concat(t," message is using the {body: {text: string}} format, e.g: {body: {text: \"Model Response\"}}");}var wn="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",b={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",REQUEST_SETTINGS_ERROR:"Request settings have not been set up",NO_FILE_ADDED_ERROR:"No file was added",IMAGE_NOT_FOUND_ERROR:"Image was not found",INVALID_RESPONSE:Dr,INVALID_MODEL_REQUEST:Fr,INVALID_MODEL_RESPONSE:Br,INVALID_STREAM_ARRAY_RESPONSE:"Multi-response arrays are not supported for streaming",INVALID_STREAM_EVENT:wn,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:"No valid stream events were sent.\n".concat(wn),READABLE_STREAM_CONNECTION_ERROR:"Readable Stream connection error.",DEFINE_FUNCTION_HANDLER:"Please define a `function_handler` property inside the service config."},ur="Authentication",K="Authorization",Ur="authorization",sn="Unauthorized",nn="Authorization header",ht="Invalid",ks="Incorrect",se="authentication_error",we="invalid_request_error",R="Content-Type",Hr="content-type",N="application/json",T="object",je="error",fr="completed",te="Bearer ",z="GET",Z="POST",rn="Upload an audio file",yi=/*#__PURE__*/function(){function yi(){_classCallCheck(this,yi);}return _createClass(yi,null,[{key:"addElements",value:function addElements(e){for(var _len=arguments.length,t=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){t[_key-1]=arguments[_key];}t.forEach(function(s){return e.appendChild(s);});}},{key:"isScrollbarAtBottomOfElement",value:function isScrollbarAtBottomOfElement(e){var t=e.scrollHeight,s=e.clientHeight,i=e.scrollTop,n=t-s;return i>=n-yi.CODE_SNIPPET_GENERATION_JUMP;}},{key:"cloneElement",value:function cloneElement(e){var t=e.cloneNode(!0);return e.parentNode.replaceChild(t,e),t;}// check safari
15
+ },{key:"preventAutomaticScrollUpOnNewLine",value:function preventAutomaticScrollUpOnNewLine(e){var t;e.addEventListener("keydown",function(){t=window.scrollY;}),e.addEventListener("input",function(){t!==window.scrollY&&window.scrollTo({top:t});});}}]);}();gt.TEXT_INPUT_ID="text-input";var js=gt;var Is=/*#__PURE__*/function(){function Is(){_classCallCheck(this,Is);}return _createClass(Is,null,[{key:"focusEndOfInput",value:function focusEndOfInput(e){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var s=window.getSelection();s==null||s.removeAllRanges(),s==null||s.addRange(t);}},{key:"focusFromParentElement",value:function focusFromParentElement(e){var t=e.querySelector("#".concat(js.TEXT_INPUT_ID));t&&(Ye.IS_SAFARI&&t.focus(),Is.focusEndOfInput(t));}}]);}();function Cn(r){return r.charAt(0).toUpperCase()+r.slice(1);}function Pr(r){return r&&JSON.stringify(r);}function tn(r,e,t,s){var i="\n".concat(Cn(e)," message: ").concat(JSON.stringify(r)," \n"),n=t?"".concat(Cn(e)," message after interceptor: ").concat(Pr(s)," \n"):"";return i+n;}function Dr(r,e,t,s){return"".concat(tn(r,e,t,s),"Make sure the ").concat(e," message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor");}function Br(r,e,t){var s="response";return"".concat(tn(r,s,e,t),"Make sure the ").concat(s," message is using the {text: string} format, e.g: {text: \"Model Response\"}");}function Fr(r,e){var t="request";return"".concat(tn(r,t,e),"Make sure the ").concat(t," message is using the {body: {text: string}} format, e.g: {body: {text: \"Model Response\"}}");}var wn="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",b={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",REQUEST_SETTINGS_ERROR:"Request settings have not been set up",NO_FILE_ADDED_ERROR:"No file was added",IMAGE_NOT_FOUND_ERROR:"Image was not found",INVALID_RESPONSE:Dr,INVALID_MODEL_REQUEST:Fr,INVALID_MODEL_RESPONSE:Br,INVALID_STREAM_ARRAY_RESPONSE:"Multi-response arrays are not supported for streaming",INVALID_STREAM_EVENT:wn,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:"No valid stream events were sent.\n".concat(wn),READABLE_STREAM_CONNECTION_ERROR:"Readable Stream connection error.",DEFINE_FUNCTION_HANDLER:"Please define a `function_handler` property inside the service config."},ur="Authentication",K="Authorization",Ur="authorization",sn="Unauthorized",nn="Authorization header",ht="Invalid",ks="Incorrect",ie="authentication_error",we="invalid_request_error",R="Content-Type",Hr="content-type",N="application/json",T="object",je="error",fr="completed",se="Bearer ",z="GET",Z="POST",rn="Upload an audio file",yi=/*#__PURE__*/function(){function yi(){_classCallCheck(this,yi);}return _createClass(yi,null,[{key:"addElements",value:function addElements(e){for(var _len=arguments.length,t=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){t[_key-1]=arguments[_key];}t.forEach(function(s){return e.appendChild(s);});}},{key:"isScrollbarAtBottomOfElement",value:function isScrollbarAtBottomOfElement(e){var t=e.scrollHeight,s=e.clientHeight,i=e.scrollTop,n=t-s;return i>=n-yi.CODE_SNIPPET_GENERATION_JUMP;}},{key:"cloneElement",value:function cloneElement(e){var t=e.cloneNode(!0);return e.parentNode.replaceChild(t,e),t;}// check safari
16
16
  // show only the top of the new message if there is overflow and scroll far enough not to lose user message
17
17
  // can prevent further scroll in streams
18
18
  },{key:"scrollToBottom",value:function scrollToBottom(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;var s=arguments.length>2?arguments[2]:undefined;s?e.scrollTo({left:0,top:s.offsetTop}):t?e.scrollTo({left:0,top:e.scrollHeight,behavior:"smooth"}):e.scrollTop=e.scrollHeight;}},{key:"scrollToTop",value:function scrollToTop(e){e.scrollTop=0;}}]);}();yi.CODE_SNIPPET_GENERATION_JUMP=0.5;var F=yi;var bi=/*#__PURE__*/function(){function bi(){_classCallCheck(this,bi);}return _createClass(bi,null,[{key:"speak",value:function speak(e,t){if(!t.service&&window.SpeechSynthesisUtterance){var s=new SpeechSynthesisUtterance(e);Object.assign(s,t),speechSynthesis.speak(s);}}},{key:"processConfig",value:function processConfig(e,t){var s={};setTimeout(function(){if(_typeof(e)=="object"&&(e.service&&(s.service=e.service),e.lang&&(s.lang=e.lang),e.pitch&&(s.pitch=e.pitch),e.rate&&(s.rate=e.rate),e.volume&&(s.volume=e.volume),e.voiceName)){var i=window.speechSynthesis.getVoices().find(function(n){var o;return n.name.toLocaleLowerCase()===((o=e.voiceName)==null?void 0:o.toLocaleLowerCase());});i&&(s.voice=i);}t(s);},bi.LOAD_VOICES_MS);}}]);}();bi.LOAD_VOICES_MS=200;var Bt=bi;var Nt=/*#__PURE__*/function(){function Nt(){_classCallCheck(this,Nt);}return _createClass(Nt,null,[{key:"colorToHex",value:function colorToHex(e){var t=document.createElement("div");return t.style.color=e,document.body.appendChild(t),"#".concat(window.getComputedStyle(t).color.match(/\d+/g).map(function(n){return parseInt(n).toString(16).padStart(2,"0");}).join(""));}},{key:"setDots",value:function setDots(e,t){var s,i;if((i=(s=t==null?void 0:t.styles)==null?void 0:s.bubble)!=null&&i.color){var n=Nt.colorToHex(t.styles.bubble.color);e.style.setProperty("--loading-message-color",n),e.style.setProperty("--loading-message-color-fade","".concat(n,"33"));}else e.style.setProperty("--loading-message-color","#848484"),e.style.setProperty("--loading-message-color-fade","#55555533");}},{key:"setRing",value:function setRing(e,t){var _ref3=t||{},s=_ref3.color,i=_ref3.width,n=_ref3.height,o=_ref3.margin,a=_ref3.border;if(s){var l=Nt.colorToHex(s);e.style.setProperty("--loading-history-color",l);}else e.style.setProperty("--loading-history-color","#dbdbdb");e.style.setProperty("--loading-history-height",n||"57px"),e.style.setProperty("--loading-history-width",i||"57px"),e.style.setProperty("--loading-history-margin",o||"7px"),e.style.setProperty("--loading-history-border",a||"6px solid");}}]);}();Nt.BUBBLE_CLASS="deep-chat-loading-message-bubble",Nt.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";var Xe=Nt;var Se=/*#__PURE__*/function(){function Se(){_classCallCheck(this,Se);}return _createClass(Se,null,[{key:"setElementProps",value:// prettier-ignore
@@ -21,12 +21,12 @@ function setElementProps(e,t,s,i){var n;s!=="loading"&&(e.applyCustomStyles(t,i,
21
21
  // But it is not actually used by anything in the chat, hence it is removed when adding a message
22
22
  // after the body has been stringified and parsed - the file reference will disappear, hence this readds it
23
23
  },{key:"reAddFileRefToObject",value:function reAddFileRefToObject(e,t){var s;(s=e.files)==null||s.forEach(function(i,n){var o;i.ref&&(o=t.files)!=null&&o[n]&&(t.files[n].ref=i.ref);});}// the chat does not use the actual file
24
- },{key:"removeFileRef",value:function removeFileRef(e){var t=_objectSpread({},e);return delete t.ref,t;}},{key:"isAudioFile",value:function isAudioFile(e){var t=/\.(mp3|ogg|wav|aac|webm|4a)$/i,s=e.type,i=e.src;return s==="audio"||(i==null?void 0:i.startsWith("data:audio"))||i&&t.test(i);}},{key:"isImageFile",value:function isImageFile(e){var t=e.type,s=e.src;return t==="image"||(s==null?void 0:s.startsWith("data:image"))||s&&Se.isImageFileExtension(s);}},{key:"isImageFileExtension",value:function isImageFileExtension(e){return /\.(jpg|jpeg|png|gif|bmp)$/i.test(e);}}]);}();Se.DEFAULT_FILE_NAME="file",Se.FILE_BUBBLE_CLASS="file-message";var ee=Se;var le=/*#__PURE__*/function(){function le(){_classCallCheck(this,le);}return _createClass(le,null,[{key:"checkForContainerStyles",value:function checkForContainerStyles(e,t){var s=e.containerStyle;s&&(Object.assign(t.style,s),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"));}// eslint-disable-next-line @typescript-eslint/no-explicit-any
24
+ },{key:"removeFileRef",value:function removeFileRef(e){var t=_objectSpread({},e);return delete t.ref,t;}},{key:"isAudioFile",value:function isAudioFile(e){var t=/\.(mp3|ogg|wav|aac|webm|4a)$/i,s=e.type,i=e.src;return s==="audio"||(i==null?void 0:i.startsWith("data:audio"))||i&&t.test(i);}},{key:"isImageFile",value:function isImageFile(e){var t=e.type,s=e.src;return t==="image"||(s==null?void 0:s.startsWith("data:image"))||s&&Se.isImageFileExtension(s);}},{key:"isImageFileExtension",value:function isImageFileExtension(e){return /\.(jpg|jpeg|png|gif|bmp)$/i.test(e);}}]);}();Se.DEFAULT_FILE_NAME="file",Se.FILE_BUBBLE_CLASS="file-message";var ee=Se;var te=/*#__PURE__*/function(){function te(){_classCallCheck(this,te);}return _createClass(te,null,[{key:"checkForContainerStyles",value:function checkForContainerStyles(e,t){var s=e.containerStyle;s&&(Object.assign(t.style,s),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"));}// eslint-disable-next-line @typescript-eslint/no-explicit-any
25
25
  },{key:"handleResponseProperty",value:function handleResponseProperty(e){return console.error("The {result: ....} response object type is deprecated since version 1.3.0."),console.error("Please change to using the new response object: https://deepchat.dev/docs/connect#Response"),e.result;}},{key:"processHistory",value:function processHistory(e){var t=e.initialMessages;if(t)return console.error("The initialMessages property is deprecated since version 2.0.0."),console.error("Please change to using the history property instead: https://deepchat.dev/docs/messages/#history"),t;}},{key:"processHistoryFile",value:function processHistoryFile(e){var t=e.file;t&&(console.error("The file property in MessageContent is deprecated since version 1.3.17."),console.error("Please change to using the files array property: https://deepchat.dev/docs/messages/#MessageContent"),e.files=[t]);}},{key:"processValidateInput",value:function processValidateInput(e){var t=e.validateMessageBeforeSending;if(t)return console.error("The validateMessageBeforeSending property is deprecated since version 1.3.24."),console.error("Please change to using validateInput: https://deepchat.dev/docs/interceptors#validateInput"),t;}},{key:"processSubmitUserMessage",value:function processSubmitUserMessage(e){return console.error("The submitUserMessage(text: string) argument string type is deprecated since version 1.4.4."),console.error("Please change to using the new argument type: https://deepchat.dev/docs/methods#submitUserMessage"),_defineProperty({},y,e);}},{key:"flagHTMLUpdateClass",value:function flagHTMLUpdateClass(e){var t;(t=e.children[0])!=null&&t.classList.contains("deep-chat-update-message")&&(console.error('The "deep-chat-update-message" html class is deprecated since version 1.4.4.'),console.error("Please change to using {..., overwrite: true} object: https://deepchat.dev/docs/connect#Response"));}},{key:"processConnect",value:function processConnect(e){var t=e;t.request&&(t.connect?Object.assign(t.connect,t.request):t.connect=t.request,console.error("The request property is deprecated since version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"));}},{key:"checkForStream",value:function checkForStream(e){var t=e.stream;if(t)return console.error("The stream property has been moved to the connect object in version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"),t;}},{key:"fireOnNewMessage",value:function fireOnNewMessage(e,t){var i;var s=e;s.onNewMessage&&(console.error("The onNewMessage event has been deprecated since version 2.0.0."),console.error("Please see the onMessage event: https://deepchat.dev/docs/events#onMessage"),(i=s.onNewMessage)==null||i.call(s,t)),e.dispatchEvent(new CustomEvent("new-message",{detail:t}));}},{key:"processFileConfigConnect",value:function processFileConfigConnect(e){var t=e;t.request&&(console.error("The request property in file configuration is deprecated since version 2.0.0."),console.error("Please use the connect property instead: https://deepchat.dev/docs/files"),t.connect||(t.connect=t.request));}},{key:"processMessageStyles",value:function processMessageStyles(e){if(!e)return;var t=JSON.parse(JSON.stringify(e)),s=t.loading;return s&&(s.outerContainer||s.innerContainer||s.bubble||s.media)&&(console.error("The loading message styles are defined using LoadingMessageStyles interface since version 2.1.0."),console.error("Check it out here: https://deepchat.dev/docs/messages/styles#LoadingMessageStyles"),t.loading={message:{styles:s}}),t;}},{key:"processDemo",value:function processDemo(e){return typeof e=="boolean"||e.displayLoadingBubble&&(console.error("The demo displayLoadingBubble property is deprecated since version 2.1.0."),console.error("Please use displayLoading instead: https://deepchat.dev/docs/modes#demo"),e.displayLoading={message:!0}),e;}},{key:"processCohere",value:function processCohere(e){var t=e,s="Please see the official documentation: https://deepchat.dev/docs/directConnection/Cohere";return t.chat&&(console.error("Cohere chat property is deprecated since version 2.2.3."),console.error(s),delete t.chat),t.textGeneration?(console.error("Cohere textGeneration is not supported since version 2.2.3."),console.error(s),delete t.textGeneration,!1):t.summarization?(console.error("Cohere summarization is not supported since version 2.2.3."),console.error(s),delete t.summarization,!1):!0;}// WORK - update link
26
- },{key:"processStreamHTMLWrappers",value:function processStreamHTMLWrappers(e){if(!e||_typeof(e)!==T)return;var t=e.htmlWrappers;if(t)return console.error("The htmlWrappers property has been moved to Deep Chat's base since version 2.3.0."),console.error("Check it out here: https://deepchat.dev/docs/messages/HTML#htmlWrappers"),t;}}]);}();var lt=/*#__PURE__*/function(){function lt(){_classCallCheck(this,lt);}return _createClass(lt,null,[{key:"mouseUp",value:function mouseUp(e,t){U.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t["default"]),Object.assign(e.style,t.hover);}},{key:"mouseDown",value:function mouseDown(e,t){Object.assign(e.style,t.click);}},{key:"mouseLeave",value:function mouseLeave(e,t){U.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t["default"]);}},{key:"mouseEnter",value:function mouseEnter(e,t){Object.assign(e.style,t.hover);}},{key:"add",value:function add(e,t){e.addEventListener("mouseenter",lt.mouseEnter.bind(this,e,t)),e.addEventListener("mouseleave",lt.mouseLeave.bind(this,e,t)),e.addEventListener("mousedown",lt.mouseDown.bind(this,e,t)),e.addEventListener("mouseup",lt.mouseUp.bind(this,e,t));}}]);}();var jr="deep-chat-temporary-message",qr="deep-chat-suggestion-button",Pi={"deep-chat-button":{styles:{"default":{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},Tn=Object.keys(Pi);var De=/*#__PURE__*/function(){function De(){_classCallCheck(this,De);}return _createClass(De,null,[{key:"applySuggestionEvent",value:function applySuggestionEvent(e,t){setTimeout(function(){t.addEventListener("click",function(){var s,i;(i=e.submitUserMessage)==null||i.call(e,_defineProperty({},y,((s=t.textContent)==null?void 0:s.trim())||""));});});}},{key:"isElementTemporary",value:function isElementTemporary(e){var t;return e?(t=e.bubbleElement.children[0])==null?void 0:t.classList.contains(jr):!1;}},{key:"doesElementContainDeepChatClass",value:function doesElementContainDeepChatClass(e){return Tn.find(function(t){return e.classList.contains(t);});}},{key:"applyEvents",value:function applyEvents(e,t){var s=Pi[t].events;Object.keys(s||[]).forEach(function(i){e.addEventListener(i,s==null?void 0:s[i]);});}},{key:"getProcessedStyles",value:function getProcessedStyles(e,t,s){var i=Array.from(t.classList).reduce(function(a,l){var d;var c=(d=e[l])==null?void 0:d.styles;return c&&e[l].styles&&a.push(c),a;},[]),n=Pi[s].styles;if(n){var a=JSON.parse(JSON.stringify(n));a["default"]&&U.overwriteDefaultWithAlreadyApplied(a,t),i.unshift(a);}var o=U.mergeStatefulStyles(i);return U.processStateful(o);}},{key:"applyDeepChatUtilities",value:function applyDeepChatUtilities(e,t,s){Tn.forEach(function(n){var o=s.getElementsByClassName(n);Array.from(o||[]).forEach(function(a){var l=De.getProcessedStyles(t,a,n);ae.applyStylesToElement(a,l),De.applyEvents(a,n);});});var i=s.getElementsByClassName(qr);Array.from(i).forEach(function(n){return De.applySuggestionEvent(e,n);});}}]);}();var Te=/*#__PURE__*/function(){function Te(){_classCallCheck(this,Te);}return _createClass(Te,null,[{key:"applyStylesToElement",value:function applyStylesToElement(e,t){var s=U.processStateful(t);lt.add(e,s),Object.assign(e.style,s["default"]);}},{key:"applyEventsToElement",value:function applyEventsToElement(e,t){Object.keys(t).forEach(function(s){var i=t[s];i&&e.addEventListener(s,i);});}},{key:"applyClassUtilitiesToElement",value:function applyClassUtilitiesToElement(e,t){var s=t.events,i=t.styles;s&&Te.applyEventsToElement(e,s),i&&!De.doesElementContainDeepChatClass(e)&&Te.applyStylesToElement(e,i);}},{key:"applyCustomClassUtilities",value:function applyCustomClassUtilities(e,t){Object.keys(e).forEach(function(s){var i=t.getElementsByClassName(s);Array.from(i).forEach(function(n){e[s]&&Te.applyClassUtilitiesToElement(n,e[s]);});});}},{key:"apply",value:function apply(e,t){De.applyDeepChatUtilities(e,e.htmlClassUtilities,t),Te.applyCustomClassUtilities(e.htmlClassUtilities,t);}},{key:"traverseNodes",value:function traverseNodes(e,t){e.nodeType===Node.ELEMENT_NODE&&t.push(e.outerHTML),e.childNodes.forEach(function(s){Te.traverseNodes(s,t);});}},{key:"splitHTML",value:function splitHTML(e){var s=new DOMParser().parseFromString(e,"text/html"),i=[];return s.body.childNodes.forEach(function(n){Te.traverseNodes(n,i);}),i;}},{key:"isTemporaryBasedOnHTML",value:function isTemporaryBasedOnHTML(e){var t=document.createElement("div");return t.innerHTML=e,De.isElementTemporary({outerContainer:t,bubbleElement:t,innerContainer:t});}// useful for removing event listeners
27
- },{key:"replaceElementWithNewClone",value:function replaceElementWithNewClone(e,t){var i;var s=(t||e).cloneNode(!0);return(i=e.parentNode)==null||i.replaceChild(s,e),s;}},{key:"tryAddWrapper",value:function tryAddWrapper(e,t,s,i){if(t&&i){var n=(s==null?void 0:s[i])||(s==null?void 0:s["default"]);if(n)return e.innerHTML=n,{contentEl:Te.getTargetWrapper(e),wrapper:!0};}return{contentEl:e,wrapper:!1};}},{key:"getTargetWrapper",value:function getTargetWrapper(e){return e.getElementsByClassName(Te.TARGET_WRAPPER_CLASS)[0]||e;}}]);}();Te.TARGET_WRAPPER_CLASS="html-wrapper";var ae=Te;var Ke=/*#__PURE__*/function(){function Ke(){_classCallCheck(this,Ke);}return _createClass(Ke,null,[{key:"addElement",value:function addElement(e,t,s){var i=F.isScrollbarAtBottomOfElement(e.elementRef);e.appendOuterContainerElemet(t),!e.focusMode&&s&&i&&F.scrollToBottom(e.elementRef,!1,t);}},{key:"createElements",value:function createElements(e,t,s,i){var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;var o=e.createMessageElementsOnOrientation("",s,i,n);o.bubbleElement.classList.add(Ke.HTML_BUBBLE_CLASS);var _ae$tryAddWrapper=ae.tryAddWrapper(o.bubbleElement,t,e._customWrappers,s),a=_ae$tryAddWrapper.contentEl;return a.innerHTML=t,o;}},{key:"overwriteElements",value:function overwriteElements(e,t,s){s.bubbleElement.innerHTML=t,ae.apply(e,s.outerContainer),le.flagHTMLUpdateClass(s.bubbleElement);}// prettier-ignore
28
- },{key:"overwrite",value:function overwrite(e,t,s,i){var n=e.messageToElements,o=v.overwriteMessage(n,i,t,s,"html",Ke.HTML_BUBBLE_CLASS);return o&&Ke.overwriteElements(e,t,o),o;}},{key:"create",value:function create(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;var n=Ke.createElements(e,t,s,i);return v.fillEmptyMessageElement(n.bubbleElement,t),ae.apply(e,n.outerContainer),le.flagHTMLUpdateClass(n.bubbleElement),e.applyCustomStyles(n,s,!1,(o=e.messageStyles)==null?void 0:o.html),n;}// prettier-ignore
29
- },{key:"add",value:function add(e,t,s,i,n){var o=arguments.length>5&&arguments[5]!==undefined?arguments[5]:!1;if(n!=null&&n.status){var l=this.overwrite(e,t,s,e.messageElementRefs);if(l)return l;n.status=!1;}if(o&&e.messageElementRefs.length>0&&ae.isTemporaryBasedOnHTML(t))return;var a=Ke.create(e,t,s,o);return o||Ke.addElement(e,a.outerContainer,i),a;}}]);}();Ke.HTML_BUBBLE_CLASS="html-message";var Be=Ke;var Vr=/*#__PURE__*/function(){function Vr(){_classCallCheck(this,Vr);}return _createClass(Vr,null,[{key:"katex",value:function katex(e,t,s){var a=(s||{}).delimiter||"$";if(a.length!==1)throw new Error("invalid delimiter");var l=function l(u,h){var f;return((f=window.katex)==null?void 0:f.renderToString(u,_objectSpread({displayMode:h,throwOnError:!1,output:"mathml"},e)))||"";},c=function c(u,h,f){var m=!1,p=u.bMarks[h]+u.tShift[h],g=u.eMarks[h];if(p+1>g)return!1;var E=u.src.charAt(p);if(E!==a)return!1;var I=p;p=u.skipChars(p,E);var P=p-I;if(P!==2)return!1;var D=h;for(;++D,!(D>=f||(p=I=u.bMarks[D]+u.tShift[D],g=u.eMarks[D],p<g&&u.tShift[D]<u.blkIndent));)if(u.src.charAt(p)===a&&!(u.tShift[D]-u.blkIndent>=4)&&(p=u.skipChars(p,E),!(p-I<P)&&(p=u.skipSpaces(p),!(p<g)))){m=!0;break;}P=u.tShift[h],u.line=D+(m?1:0);var ie=u.getLines(h+1,D,P,!0).replace(/[ \n]+/g," ").trim();return u.tokens.push({type:"katex",params:null,content:ie,lines:[h,u.line],level:u.level,block:!0}),!0;},d=function d(u,h){var f=u.pos,m=u.posMax;var p=f;if(u.src.charAt(p)!==a)return!1;for(++p;p<m&&u.src.charAt(p)===a;)++p;var g=u.src.slice(f,p);if(g.length>2)return!1;var E=p;var I=0;for(;p<m;){var P=u.src.charAt(p);if(P==="{"&&(p===0||u.src.charAt(p-1)!=="\\"))I+=1;else if(P==="}"&&(p===0||u.src.charAt(p-1)!=="\\")){if(I-=1,I<0)return!1;}else if(P===a&&I===0){var D=p;var ie=p+1;for(;ie<m&&u.src.charAt(ie)===a;)++ie;if(ie-D===g.length){if(!h){var st=u.src.slice(E,D).replace(/[ \n]+/g," ").trim();u.push({type:"katex",content:st,block:g.length>1,level:u.level});}return u.pos=ie,!0;}}p+=1;}return h||(u.pending+=g),u.pos+=g.length,!0;};t.inline.ruler.push("katex",d,s),t.block.ruler.push("katex",c,s),t.renderer.rules.katex=function(u,h){return l(u[h].content,u[h].block);},t.renderer.rules.katex.delimiter=a;}}]);}();var Ns;function pr(r){return Ns=Ns||document.createElement("textarea"),Ns.innerHTML="&"+r+";",Ns.value;}var Gr=Object.prototype.hasOwnProperty;function Kr(r,e){return r?Gr.call(r,e):!1;}function mr(r){var e=[].slice.call(arguments,1);return e.forEach(function(t){if(t){if(_typeof(t)!="object")throw new TypeError(t+"must be object");Object.keys(t).forEach(function(s){r[s]=t[s];});}}),r;}var zr=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Es(r){return r.indexOf("\\")<0?r:r.replace(zr,"$1");}function gr(r){return!(r>=55296&&r<=57343||r>=64976&&r<=65007||(r&65535)===65535||(r&65535)===65534||r>=0&&r<=8||r===11||r>=14&&r<=31||r>=127&&r<=159||r>1114111);}function Di(r){if(r>65535){r-=65536;var e=55296+(r>>10),t=56320+(r&1023);return String.fromCharCode(e,t);}return String.fromCharCode(r);}var Jr=/&([a-z#][a-z0-9]{1,31});/gi,$r=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Wr(r,e){var t=0,s=pr(e);return e!==s?s:e.charCodeAt(0)===35&&$r.test(e)&&(t=e[1].toLowerCase()==="x"?parseInt(e.slice(2),16):parseInt(e.slice(1),10),gr(t))?Di(t):r;}function At(r){return r.indexOf("&")<0?r:r.replace(Jr,Wr);}var Xr=/[&<>"]/,Yr=/[&<>"]/g,Zr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function Qr(r){return Zr[r];}function pe(r){return Xr.test(r)?r.replace(Yr,Qr):r;}var _={};_.blockquote_open=function(){return"<blockquote>\n";};_.blockquote_close=function(r,e){return"</blockquote>"+Tt(r,e);};_.code=function(r,e){return r[e].block?"<pre><code>"+pe(r[e].content)+"</code></pre>"+Tt(r,e):"<code>"+pe(r[e].content)+"</code>";};_.fence=function(r,e,t,s,i){var n=r[e],o="",a=t.langPrefix,l="",c,d,u;if(n.params){if(c=n.params.split(/\s+/g),d=c.join(" "),Kr(i.rules.fence_custom,c[0]))return i.rules.fence_custom[c[0]](r,e,t,s,i);l=pe(At(Es(d))),o=' class="'+a+l+'"';}return t.highlight?u=t.highlight.apply(t.highlight,[n.content].concat(c))||pe(n.content):u=pe(n.content),"<pre><code"+o+">"+u+"</code></pre>"+Tt(r,e);};_.fence_custom={};_.heading_open=function(r,e){return"<h"+r[e].hLevel+">";};_.heading_close=function(r,e){return"</h"+r[e].hLevel+">\n";};_.hr=function(r,e,t){return(t.xhtmlOut?"<hr />":"<hr>")+Tt(r,e);};_.bullet_list_open=function(){return"<ul>\n";};_.bullet_list_close=function(r,e){return"</ul>"+Tt(r,e);};_.list_item_open=function(){return"<li>";};_.list_item_close=function(){return"</li>\n";};_.ordered_list_open=function(r,e){var t=r[e],s=t.order>1?' start="'+t.order+'"':"";return"<ol"+s+">\n";};_.ordered_list_close=function(r,e){return"</ol>"+Tt(r,e);};_.paragraph_open=function(r,e){return r[e].tight?"":"<p>";};_.paragraph_close=function(r,e){var t=!(r[e].tight&&e&&r[e-1].type==="inline"&&!r[e-1].content);return(r[e].tight?"":"</p>")+(t?Tt(r,e):"");};_.link_open=function(r,e,t){var s=r[e].title?' title="'+pe(At(r[e].title))+'"':"",i=t.linkTarget?' target="'+t.linkTarget+'"':"";return'<a href="'+pe(r[e].href)+'"'+s+i+">";};_.link_close=function(){return"</a>";};_.image=function(r,e,t){var s=' src="'+pe(r[e].src)+'"',i=r[e].title?' title="'+pe(At(r[e].title))+'"':"",n=' alt="'+(r[e].alt?pe(At(Es(r[e].alt))):"")+'"',o=t.xhtmlOut?" /":"";return"<img"+s+n+i+o+">";};_.table_open=function(){return"<table>\n";};_.table_close=function(){return"</table>\n";};_.thead_open=function(){return"<thead>\n";};_.thead_close=function(){return"</thead>\n";};_.tbody_open=function(){return"<tbody>\n";};_.tbody_close=function(){return"</tbody>\n";};_.tr_open=function(){return"<tr>";};_.tr_close=function(){return"</tr>\n";};_.th_open=function(r,e){var t=r[e];return"<th"+(t.align?' style="text-align:'+t.align+'"':"")+">";};_.th_close=function(){return"</th>";};_.td_open=function(r,e){var t=r[e];return"<td"+(t.align?' style="text-align:'+t.align+'"':"")+">";};_.td_close=function(){return"</td>";};_.strong_open=function(){return"<strong>";};_.strong_close=function(){return"</strong>";};_.em_open=function(){return"<em>";};_.em_close=function(){return"</em>";};_.del_open=function(){return"<del>";};_.del_close=function(){return"</del>";};_.ins_open=function(){return"<ins>";};_.ins_close=function(){return"</ins>";};_.mark_open=function(){return"<mark>";};_.mark_close=function(){return"</mark>";};_.sub=function(r,e){return"<sub>"+pe(r[e].content)+"</sub>";};_.sup=function(r,e){return"<sup>"+pe(r[e].content)+"</sup>";};_.hardbreak=function(r,e,t){return t.xhtmlOut?"<br />\n":"<br>\n";};_.softbreak=function(r,e,t){return t.breaks?t.xhtmlOut?"<br />\n":"<br>\n":"\n";};_.text=function(r,e){return pe(r[e].content);};_.htmlblock=function(r,e){return r[e].content;};_.htmltag=function(r,e){return r[e].content;};_.abbr_open=function(r,e){return'<abbr title="'+pe(At(r[e].title))+'">';};_.abbr_close=function(){return"</abbr>";};_.footnote_ref=function(r,e){var t=Number(r[e].id+1).toString(),s="fnref"+t;return r[e].subId>0&&(s+=":"+r[e].subId),'<sup class="footnote-ref"><a href="#fn'+t+'" id="'+s+'">['+t+"]</a></sup>";};_.footnote_block_open=function(r,e,t){var s=t.xhtmlOut?"<hr class=\"footnotes-sep\" />\n":"<hr class=\"footnotes-sep\">\n";return s+"<section class=\"footnotes\">\n<ol class=\"footnotes-list\">\n";};_.footnote_block_close=function(){return"</ol>\n</section>\n";};_.footnote_open=function(r,e){var t=Number(r[e].id+1).toString();return'<li id="fn'+t+'" class="footnote-item">';};_.footnote_close=function(){return"</li>\n";};_.footnote_anchor=function(r,e){var t=Number(r[e].id+1).toString(),s="fnref"+t;return r[e].subId>0&&(s+=":"+r[e].subId),' <a href="#'+s+'" class="footnote-backref">↩</a>';};_.dl_open=function(){return"<dl>\n";};_.dt_open=function(){return"<dt>";};_.dd_open=function(){return"<dd>";};_.dl_close=function(){return"</dl>\n";};_.dt_close=function(){return"</dt>\n";};_.dd_close=function(){return"</dd>\n";};function yr(r,e){return++e>=r.length-2?e:r[e].type==="paragraph_open"&&r[e].tight&&r[e+1].type==="inline"&&r[e+1].content.length===0&&r[e+2].type==="paragraph_close"&&r[e+2].tight?yr(r,e+2):e;}var Tt=_.getBreak=function(e,t){return t=yr(e,t),t<e.length&&e[t].type==="list_item_close"?"":"\n";};function on(){this.rules=mr({},_),this.getBreak=_.getBreak;}on.prototype.renderInline=function(r,e,t){for(var s=this.rules,i=r.length,n=0,o="";i--;)o+=s[r[n].type](r,n++,e,t,this);return o;};on.prototype.render=function(r,e,t){for(var s=this.rules,i=r.length,n=-1,o="";++n<i;)r[n].type==="inline"?o+=this.renderInline(r[n].children,e,t):o+=s[r[n].type](r,n,e,t,this);return o;};function _e(){this.__rules__=[],this.__cache__=null;}_e.prototype.__find__=function(r){for(var e=this.__rules__.length,t=-1;e--;)if(this.__rules__[++t].name===r)return t;return-1;};_e.prototype.__compile__=function(){var r=this,e=[""];r.__rules__.forEach(function(t){t.enabled&&t.alt.forEach(function(s){e.indexOf(s)<0&&e.push(s);});}),r.__cache__={},e.forEach(function(t){r.__cache__[t]=[],r.__rules__.forEach(function(s){s.enabled&&(t&&s.alt.indexOf(t)<0||r.__cache__[t].push(s.fn));});});};_e.prototype.at=function(r,e,t){var s=this.__find__(r),i=t||{};if(s===-1)throw new Error("Parser rule not found: "+r);this.__rules__[s].fn=e,this.__rules__[s].alt=i.alt||[],this.__cache__=null;};_e.prototype.before=function(r,e,t,s){var i=this.__find__(r),n=s||{};if(i===-1)throw new Error("Parser rule not found: "+r);this.__rules__.splice(i,0,{name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null;};_e.prototype.after=function(r,e,t,s){var i=this.__find__(r),n=s||{};if(i===-1)throw new Error("Parser rule not found: "+r);this.__rules__.splice(i+1,0,{name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null;};_e.prototype.push=function(r,e,t){var s=t||{};this.__rules__.push({name:r,enabled:!0,fn:e,alt:s.alt||[]}),this.__cache__=null;};_e.prototype.enable=function(r,e){r=Array.isArray(r)?r:[r],e&&this.__rules__.forEach(function(t){t.enabled=!1;}),r.forEach(function(t){var s=this.__find__(t);if(s<0)throw new Error("Rules manager: invalid rule name "+t);this.__rules__[s].enabled=!0;},this),this.__cache__=null;};_e.prototype.disable=function(r){r=Array.isArray(r)?r:[r],r.forEach(function(e){var t=this.__find__(e);if(t<0)throw new Error("Rules manager: invalid rule name "+e);this.__rules__[t].enabled=!1;},this),this.__cache__=null;};_e.prototype.getRules=function(r){return this.__cache__===null&&this.__compile__(),this.__cache__[r]||[];};function eo(r){r.inlineMode?r.tokens.push({type:"inline",content:r.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):r.block.parse(r.src,r.options,r.env,r.tokens);}function Rt(r,e,t,s,i){this.src=r,this.env=s,this.options=t,this.parser=e,this.tokens=i,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0;}Rt.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending="";};Rt.prototype.push=function(r){this.pending&&this.pushPending(),this.tokens.push(r),this.pendingLevel=this.level;};Rt.prototype.cacheSet=function(r,e){for(var t=this.cache.length;t<=r;t++)this.cache.push(0);this.cache[r]=e;};Rt.prototype.cacheGet=function(r){return r<this.cache.length?this.cache[r]:0;};function Ss(r,e){var t,s,i,n=-1,o=r.posMax,a=r.pos,l=r.isInLabel;if(r.isInLabel)return-1;if(r.labelUnmatchedScopes)return r.labelUnmatchedScopes--,-1;for(r.pos=e+1,r.isInLabel=!0,t=1;r.pos<o;){if(i=r.src.charCodeAt(r.pos),i===91)t++;else if(i===93&&(t--,t===0)){s=!0;break;}r.parser.skipToken(r);}return s?(n=r.pos,r.labelUnmatchedScopes=0):r.labelUnmatchedScopes=t-1,r.pos=a,r.isInLabel=l,n;}function to(r,e,t,s){var i,n,o,a,l,c;if(r.charCodeAt(0)!==42||r.charCodeAt(1)!==91||r.indexOf("]:")===-1||(i=new Rt(r,e,t,s,[]),n=Ss(i,1),n<0||r.charCodeAt(n+1)!==58))return-1;for(a=i.posMax,o=n+2;o<a&&i.src.charCodeAt(o)!==10;o++);return l=r.slice(2,n),c=r.slice(n+2,o).trim(),c.length===0?-1:(s.abbreviations||(s.abbreviations={}),_typeof(s.abbreviations[":"+l])>"u"&&(s.abbreviations[":"+l]=c),o);}function so(r){var e=r.tokens,t,s,i,n;if(!r.inlineMode){for(t=1,s=e.length-1;t<s;t++)if(e[t-1].type==="paragraph_open"&&e[t].type==="inline"&&e[t+1].type==="paragraph_close"){for(i=e[t].content;i.length&&(n=to(i,r.inline,r.options,r.env),!(n<0));)i=i.slice(n).trim();e[t].content=i,i.length||(e[t-1].tight=!0,e[t+1].tight=!0);}}}function Bi(r){var e=At(r);try{e=decodeURI(e);}catch(_unused3){}return encodeURI(e);}function br(r,e){var t,s,i,n=e,o=r.posMax;if(r.src.charCodeAt(e)===60){for(e++;e<o;){if(t=r.src.charCodeAt(e),t===10)return!1;if(t===62)return i=Bi(Es(r.src.slice(n+1,e))),r.parser.validateLink(i)?(r.pos=e+1,r.linkContent=i,!0):!1;if(t===92&&e+1<o){e+=2;continue;}e++;}return!1;}for(s=0;e<o&&(t=r.src.charCodeAt(e),!(t===32||t<32||t===127));){if(t===92&&e+1<o){e+=2;continue;}if(t===40&&(s++,s>1)||t===41&&(s--,s<0))break;e++;}return n===e||(i=Es(r.src.slice(n,e)),!r.parser.validateLink(i))?!1:(r.linkContent=i,r.pos=e,!0);}function vr(r,e){var t,s=e,i=r.posMax,n=r.src.charCodeAt(e);if(n!==34&&n!==39&&n!==40)return!1;for(e++,n===40&&(n=41);e<i;){if(t=r.src.charCodeAt(e),t===n)return r.pos=e+1,r.linkContent=Es(r.src.slice(s+1,e)),!0;if(t===92&&e+1<i){e+=2;continue;}e++;}return!1;}function _r(r){return r.trim().replace(/\s+/g," ").toUpperCase();}function io(r,e,t,s){var i,n,o,a,l,c,d,u,h;if(r.charCodeAt(0)!==91||r.indexOf("]:")===-1||(i=new Rt(r,e,t,s,[]),n=Ss(i,0),n<0||r.charCodeAt(n+1)!==58))return-1;for(a=i.posMax,o=n+2;o<a&&(l=i.src.charCodeAt(o),!(l!==32&&l!==10));o++);if(!br(i,o))return-1;for(d=i.linkContent,o=i.pos,c=o,o=o+1;o<a&&(l=i.src.charCodeAt(o),!(l!==32&&l!==10));o++);for(o<a&&c!==o&&vr(i,o)?(u=i.linkContent,o=i.pos):(u="",o=c);o<a&&i.src.charCodeAt(o)===32;)o++;return o<a&&i.src.charCodeAt(o)!==10?-1:(h=_r(r.slice(1,n)),_typeof(s.references[h])>"u"&&(s.references[h]={title:u,href:d}),o);}function no(r){var e=r.tokens,t,s,i,n;if(r.env.references=r.env.references||{},!r.inlineMode){for(t=1,s=e.length-1;t<s;t++)if(e[t].type==="inline"&&e[t-1].type==="paragraph_open"&&e[t+1].type==="paragraph_close"){for(i=e[t].content;i.length&&(n=io(i,r.inline,r.options,r.env),!(n<0));)i=i.slice(n).trim();e[t].content=i,i.length||(e[t-1].tight=!0,e[t+1].tight=!0);}}}function ro(r){var e=r.tokens,t,s,i;for(s=0,i=e.length;s<i;s++)t=e[s],t.type==="inline"&&r.inline.parse(t.content,r.options,r.env,t.children);}function oo(r){var e,t,s,i,n,o,a,l,c,d=0,u=!1,h={};if(r.env.footnotes&&(r.tokens=r.tokens.filter(function(f){return f.type==="footnote_reference_open"?(u=!0,l=[],c=f.label,!1):f.type==="footnote_reference_close"?(u=!1,h[":"+c]=l,!1):(u&&l.push(f),!u);}),!!r.env.footnotes.list)){for(o=r.env.footnotes.list,r.tokens.push({type:"footnote_block_open",level:d++}),e=0,t=o.length;e<t;e++){for(r.tokens.push({type:"footnote_open",id:e,level:d++}),o[e].tokens?(a=[],a.push({type:"paragraph_open",tight:!1,level:d++}),a.push({type:"inline",content:"",level:d,children:o[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--d})):o[e].label&&(a=h[":"+o[e].label]),r.tokens=r.tokens.concat(a),r.tokens[r.tokens.length-1].type==="paragraph_close"?n=r.tokens.pop():n=null,i=o[e].count>0?o[e].count:1,s=0;s<i;s++)r.tokens.push({type:"footnote_anchor",id:e,subId:s,level:d});n&&r.tokens.push(n),r.tokens.push({type:"footnote_close",level:--d});}r.tokens.push({type:"footnote_block_close",level:--d});}}var Rn=" \n()[]'\".,!?-";function Ii(r){return r.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1");}function ao(r){var e,t,s,i,n,o,a,l,c,d,u,h,f=r.tokens;if(r.env.abbreviations){for(r.env.abbrRegExp||(h="(^|["+Rn.split("").map(Ii).join("")+"])("+Object.keys(r.env.abbreviations).map(function(m){return m.substr(1);}).sort(function(m,p){return p.length-m.length;}).map(Ii).join("|")+")($|["+Rn.split("").map(Ii).join("")+"])",r.env.abbrRegExp=new RegExp(h,"g")),d=r.env.abbrRegExp,t=0,s=f.length;t<s;t++)if(f[t].type==="inline"){for(i=f[t].children,e=i.length-1;e>=0;e--)if(n=i[e],n.type==="text"){for(l=0,o=n.content,d.lastIndex=0,c=n.level,a=[];u=d.exec(o);)d.lastIndex>l&&a.push({type:"text",content:o.slice(l,u.index+u[1].length),level:c}),a.push({type:"abbr_open",title:r.env.abbreviations[":"+u[2]],level:c++}),a.push({type:"text",content:u[2],level:c}),a.push({type:"abbr_close",level:--c}),l=d.lastIndex-u[3].length;a.length&&(l<o.length&&a.push({type:"text",content:o.slice(l),level:c}),f[t].children=i=[].concat(i.slice(0,e),a,i.slice(e+1)));}}}}var lo=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,co=/\((c|tm|r|p)\)/ig,ho={c:"©",r:"®",p:"§",tm:"™"};function uo(r){return r.indexOf("(")<0?r:r.replace(co,function(e,t){return ho[t.toLowerCase()];});}function fo(r){var e,t,s,i,n;if(r.options.typographer){for(n=r.tokens.length-1;n>=0;n--)if(r.tokens[n].type==="inline")for(i=r.tokens[n].children,e=i.length-1;e>=0;e--)t=i[e],t.type==="text"&&(s=t.content,s=uo(s),lo.test(s)&&(s=s.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/mg,"$1—$2").replace(/(^|\s)--(\s|$)/mg,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/mg,"$1–$2")),t.content=s);}}var po=/['"]/,Mn=/['"]/g,mo=/[-\s()\[\]]/,In="’";function kn(r,e){return e<0||e>=r.length?!1:!mo.test(r[e]);}function kt(r,e,t){return r.substr(0,e)+t+r.substr(e+1);}function go(r){var e,t,s,i,n,o,a,l,c,d,u,h,f,m,p,g,E;if(r.options.typographer){for(E=[],p=r.tokens.length-1;p>=0;p--)if(r.tokens[p].type==="inline"){for(g=r.tokens[p].children,E.length=0,e=0;e<g.length;e++)if(t=g[e],!(t.type!=="text"||po.test(t.text))){for(a=g[e].level,f=E.length-1;f>=0&&!(E[f].level<=a);f--);E.length=f+1,s=t.content,n=0,o=s.length;e:for(;n<o&&(Mn.lastIndex=n,i=Mn.exec(s),!!i);){if(l=!kn(s,i.index-1),n=i.index+1,m=i[0]==="'",c=!kn(s,n),!c&&!l){m&&(t.content=kt(t.content,i.index,In));continue;}if(u=!c,h=!l,h){for(f=E.length-1;f>=0&&(d=E[f],!(E[f].level<a));f--)if(d.single===m&&E[f].level===a){d=E[f],m?(g[d.token].content=kt(g[d.token].content,d.pos,r.options.quotes[2]),t.content=kt(t.content,i.index,r.options.quotes[3])):(g[d.token].content=kt(g[d.token].content,d.pos,r.options.quotes[0]),t.content=kt(t.content,i.index,r.options.quotes[1])),E.length=f;continue e;}}u?E.push({token:e,pos:i.index,single:m,level:a}):h&&m&&(t.content=kt(t.content,i.index,In));}}}}}var ki=[["block",eo],["abbr",so],["references",no],["inline",ro],["footnote_tail",oo],["abbr2",ao],["replacements",fo],["smartquotes",go]];function Er(){this.options={},this.ruler=new _e();for(var r=0;r<ki.length;r++)this.ruler.push(ki[r][0],ki[r][1]);}Er.prototype.process=function(r){var e,t,s;for(s=this.ruler.getRules(""),e=0,t=s.length;e<t;e++)s[e](r);};function Mt(r,e,t,s,i){var n,o,a,l,c,d,u;for(this.src=r,this.parser=e,this.options=t,this.env=s,this.tokens=i,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",o=this.src,d=0,u=!1,a=l=d=0,c=o.length;l<c;l++){if(n=o.charCodeAt(l),!u)if(n===32){d++;continue;}else u=!0;(n===10||l===c-1)&&(n!==10&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(d),u=!1,d=0,a=l+1);}this.bMarks.push(o.length),this.eMarks.push(o.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1;}Mt.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e];};Mt.prototype.skipEmptyLines=function(e){for(var t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e;};Mt.prototype.skipSpaces=function(e){for(var t=this.src.length;e<t&&this.src.charCodeAt(e)===32;e++);return e;};Mt.prototype.skipChars=function(e,t){for(var s=this.src.length;e<s&&this.src.charCodeAt(e)===t;e++);return e;};Mt.prototype.skipCharsBack=function(e,t,s){if(e<=s)return e;for(;e>s;)if(t!==this.src.charCodeAt(--e))return e+1;return e;};Mt.prototype.getLines=function(e,t,s,i){var n,o,a,l,c,d=e;if(e>=t)return"";if(d+1===t)return o=this.bMarks[d]+Math.min(this.tShift[d],s),a=i?this.eMarks[d]+1:this.eMarks[d],this.src.slice(o,a);for(l=new Array(t-e),n=0;d<t;d++,n++)c=this.tShift[d],c>s&&(c=s),c<0&&(c=0),o=this.bMarks[d]+c,d+1<t||i?a=this.eMarks[d]+1:a=this.eMarks[d],l[n]=this.src.slice(o,a);return l.join("");};function yo(r,e,t){var s,i;if(r.tShift[e]-r.blkIndent<4)return!1;for(i=s=e+1;s<t;){if(r.isEmpty(s)){s++;continue;}if(r.tShift[s]-r.blkIndent>=4){s++,i=s;continue;}break;}return r.line=s,r.tokens.push({type:"code",content:r.getLines(e,i,4+r.blkIndent,!0),block:!0,lines:[e,r.line],level:r.level}),!0;}function bo(r,e,t,s){var i,n,o,a,l,c=!1,d=r.bMarks[e]+r.tShift[e],u=r.eMarks[e];if(d+3>u||(i=r.src.charCodeAt(d),i!==126&&i!==96)||(l=d,d=r.skipChars(d,i),n=d-l,n<3)||(o=r.src.slice(d,u).trim(),o.indexOf("`")>=0))return!1;if(s)return!0;for(a=e;a++,!(a>=t||(d=l=r.bMarks[a]+r.tShift[a],u=r.eMarks[a],d<u&&r.tShift[a]<r.blkIndent));)if(r.src.charCodeAt(d)===i&&!(r.tShift[a]-r.blkIndent>=4)&&(d=r.skipChars(d,i),!(d-l<n)&&(d=r.skipSpaces(d),!(d<u)))){c=!0;break;}return n=r.tShift[e],r.line=a+(c?1:0),r.tokens.push({type:"fence",params:o,content:r.getLines(e+1,a,n,!0),lines:[e,r.line],level:r.level}),!0;}function vo(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p=r.bMarks[e]+r.tShift[e],g=r.eMarks[e];if(p>g||r.src.charCodeAt(p++)!==62||r.level>=r.options.maxNesting)return!1;if(s)return!0;for(r.src.charCodeAt(p)===32&&p++,l=r.blkIndent,r.blkIndent=0,a=[r.bMarks[e]],r.bMarks[e]=p,p=p<g?r.skipSpaces(p):p,n=p>=g,o=[r.tShift[e]],r.tShift[e]=p-r.bMarks[e],u=r.parser.ruler.getRules("blockquote"),i=e+1;i<t&&(p=r.bMarks[i]+r.tShift[i],g=r.eMarks[i],!(p>=g));i++){if(r.src.charCodeAt(p++)===62){r.src.charCodeAt(p)===32&&p++,a.push(r.bMarks[i]),r.bMarks[i]=p,p=p<g?r.skipSpaces(p):p,n=p>=g,o.push(r.tShift[i]),r.tShift[i]=p-r.bMarks[i];continue;}if(n)break;for(m=!1,h=0,f=u.length;h<f;h++)if(u[h](r,i,t,!0)){m=!0;break;}if(m)break;a.push(r.bMarks[i]),o.push(r.tShift[i]),r.tShift[i]=-1337;}for(c=r.parentType,r.parentType="blockquote",r.tokens.push({type:"blockquote_open",lines:d=[e,0],level:r.level++}),r.parser.tokenize(r,e,i),r.tokens.push({type:"blockquote_close",level:--r.level}),r.parentType=c,d[1]=r.line,h=0;h<o.length;h++)r.bMarks[h+e]=a[h],r.tShift[h+e]=o[h];return r.blkIndent=l,!0;}function _o(r,e,t,s){var i,n,o,a=r.bMarks[e],l=r.eMarks[e];if(a+=r.tShift[e],a>l||(i=r.src.charCodeAt(a++),i!==42&&i!==45&&i!==95))return!1;for(n=1;a<l;){if(o=r.src.charCodeAt(a++),o!==i&&o!==32)return!1;o===i&&n++;}return n<3?!1:(s||(r.line=e+1,r.tokens.push({type:"hr",lines:[e,r.line],level:r.level})),!0);}function Ln(r,e){var t,s,i;return s=r.bMarks[e]+r.tShift[e],i=r.eMarks[e],s>=i||(t=r.src.charCodeAt(s++),t!==42&&t!==45&&t!==43)||s<i&&r.src.charCodeAt(s)!==32?-1:s;}function On(r,e){var t,s=r.bMarks[e]+r.tShift[e],i=r.eMarks[e];if(s+1>=i||(t=r.src.charCodeAt(s++),t<48||t>57))return-1;for(;;){if(s>=i)return-1;if(t=r.src.charCodeAt(s++),!(t>=48&&t<=57)){if(t===41||t===46)break;return-1;}}return s<i&&r.src.charCodeAt(s)!==32?-1:s;}function Eo(r,e){var t,s,i=r.level+2;for(t=e+2,s=r.tokens.length-2;t<s;t++)r.tokens[t].level===i&&r.tokens[t].type==="paragraph_open"&&(r.tokens[t+2].tight=!0,r.tokens[t].tight=!0,t+=2);}function So(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p,g,E,I,P,D,ie,st=!0,it,me,An,Mi;if((u=On(r,e))>=0)g=!0;else if((u=Ln(r,e))>=0)g=!1;else return!1;if(r.level>=r.options.maxNesting)return!1;if(p=r.src.charCodeAt(u-1),s)return!0;for(I=r.tokens.length,g?(d=r.bMarks[e]+r.tShift[e],m=Number(r.src.substr(d,u-d-1)),r.tokens.push({type:"ordered_list_open",order:m,lines:D=[e,0],level:r.level++})):r.tokens.push({type:"bullet_list_open",lines:D=[e,0],level:r.level++}),i=e,P=!1,it=r.parser.ruler.getRules("list");i<t&&(E=r.skipSpaces(u),h=r.eMarks[i],E>=h?f=1:f=E-u,f>4&&(f=1),f<1&&(f=1),n=u-r.bMarks[i]+f,r.tokens.push({type:"list_item_open",lines:ie=[e,0],level:r.level++}),a=r.blkIndent,l=r.tight,o=r.tShift[e],c=r.parentType,r.tShift[e]=E-r.bMarks[e],r.blkIndent=n,r.tight=!0,r.parentType="list",r.parser.tokenize(r,e,t,!0),(!r.tight||P)&&(st=!1),P=r.line-e>1&&r.isEmpty(r.line-1),r.blkIndent=a,r.tShift[e]=o,r.tight=l,r.parentType=c,r.tokens.push({type:"list_item_close",level:--r.level}),i=e=r.line,ie[1]=i,E=r.bMarks[e],!(i>=t||r.isEmpty(i)||r.tShift[i]<r.blkIndent));){for(Mi=!1,me=0,An=it.length;me<An;me++)if(it[me](r,i,t,!0)){Mi=!0;break;}if(Mi)break;if(g){if(u=On(r,i),u<0)break;}else if(u=Ln(r,i),u<0)break;if(p!==r.src.charCodeAt(u-1))break;}return r.tokens.push({type:g?"ordered_list_close":"bullet_list_close",level:--r.level}),D[1]=i,r.line=i,st&&Eo(r,I),!0;}function xo(r,e,t,s){var i,n,o,a,l,c=r.bMarks[e]+r.tShift[e],d=r.eMarks[e];if(c+4>d||r.src.charCodeAt(c)!==91||r.src.charCodeAt(c+1)!==94||r.level>=r.options.maxNesting)return!1;for(a=c+2;a<d;a++){if(r.src.charCodeAt(a)===32)return!1;if(r.src.charCodeAt(a)===93)break;}return a===c+2||a+1>=d||r.src.charCodeAt(++a)!==58?!1:(s||(a++,r.env.footnotes||(r.env.footnotes={}),r.env.footnotes.refs||(r.env.footnotes.refs={}),l=r.src.slice(c+2,a-2),r.env.footnotes.refs[":"+l]=-1,r.tokens.push({type:"footnote_reference_open",label:l,level:r.level++}),i=r.bMarks[e],n=r.tShift[e],o=r.parentType,r.tShift[e]=r.skipSpaces(a)-a,r.bMarks[e]=a,r.blkIndent+=4,r.parentType="footnote",r.tShift[e]<r.blkIndent&&(r.tShift[e]+=r.blkIndent,r.bMarks[e]-=r.blkIndent),r.parser.tokenize(r,e,t,!0),r.parentType=o,r.blkIndent-=4,r.tShift[e]=n,r.bMarks[e]=i,r.tokens.push({type:"footnote_reference_close",level:--r.level})),!0);}function Ao(r,e,t,s){var i,n,o,a=r.bMarks[e]+r.tShift[e],l=r.eMarks[e];if(a>=l||(i=r.src.charCodeAt(a),i!==35||a>=l))return!1;for(n=1,i=r.src.charCodeAt(++a);i===35&&a<l&&n<=6;)n++,i=r.src.charCodeAt(++a);return n>6||a<l&&i!==32?!1:(s||(l=r.skipCharsBack(l,32,a),o=r.skipCharsBack(l,35,a),o>a&&r.src.charCodeAt(o-1)===32&&(l=o),r.line=e+1,r.tokens.push({type:"heading_open",hLevel:n,lines:[e,r.line],level:r.level}),a<l&&r.tokens.push({type:"inline",content:r.src.slice(a,l).trim(),level:r.level+1,lines:[e,r.line],children:[]}),r.tokens.push({type:"heading_close",hLevel:n,level:r.level})),!0);}function Co(r,e,t){var s,i,n,o=e+1;return o>=t||r.tShift[o]<r.blkIndent||r.tShift[o]-r.blkIndent>3||(i=r.bMarks[o]+r.tShift[o],n=r.eMarks[o],i>=n)||(s=r.src.charCodeAt(i),s!==45&&s!==61)||(i=r.skipChars(i,s),i=r.skipSpaces(i),i<n)?!1:(i=r.bMarks[e]+r.tShift[e],r.line=o+1,r.tokens.push({type:"heading_open",hLevel:s===61?1:2,lines:[e,r.line],level:r.level}),r.tokens.push({type:"inline",content:r.src.slice(i,r.eMarks[e]).trim(),level:r.level+1,lines:[e,r.line-1],children:[]}),r.tokens.push({type:"heading_close",hLevel:s===61?1:2,level:r.level}),!0);}var Sr={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach(function(r){Sr[r]=!0;});var wo=/^<([a-zA-Z]{1,15})[\s\/>]/,To=/^<\/([a-zA-Z]{1,15})[\s>]/;function Ro(r){var e=r|32;return e>=97&&e<=122;}function Mo(r,e,t,s){var i,n,o,a=r.bMarks[e],l=r.eMarks[e],c=r.tShift[e];if(a+=c,!r.options.html||c>3||a+2>=l||r.src.charCodeAt(a)!==60)return!1;if(i=r.src.charCodeAt(a+1),i===33||i===63){if(s)return!0;}else if(i===47||Ro(i)){if(i===47){if(n=r.src.slice(a,l).match(To),!n)return!1;}else if(n=r.src.slice(a,l).match(wo),!n)return!1;if(Sr[n[1].toLowerCase()]!==!0)return!1;if(s)return!0;}else return!1;for(o=e+1;o<r.lineMax&&!r.isEmpty(o);)o++;return r.line=o,r.tokens.push({type:"htmlblock",level:r.level,lines:[e,r.line],content:r.getLines(e,o,0,!0)}),!0;}function Li(r,e){var t=r.bMarks[e]+r.blkIndent,s=r.eMarks[e];return r.src.substr(t,s-t);}function Io(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m;if(e+2>t||(l=e+1,r.tShift[l]<r.blkIndent)||(o=r.bMarks[l]+r.tShift[l],o>=r.eMarks[l])||(i=r.src.charCodeAt(o),i!==124&&i!==45&&i!==58)||(n=Li(r,e+1),!/^[-:| ]+$/.test(n))||(c=n.split("|"),c<=2))return!1;for(u=[],a=0;a<c.length;a++){if(h=c[a].trim(),!h){if(a===0||a===c.length-1)continue;return!1;}if(!/^:?-+:?$/.test(h))return!1;h.charCodeAt(h.length-1)===58?u.push(h.charCodeAt(0)===58?"center":"right"):h.charCodeAt(0)===58?u.push("left"):u.push("");}if(n=Li(r,e).trim(),n.indexOf("|")===-1||(c=n.replace(/^\||\|$/g,"").split("|"),u.length!==c.length))return!1;if(s)return!0;for(r.tokens.push({type:"table_open",lines:f=[e,0],level:r.level++}),r.tokens.push({type:"thead_open",lines:[e,e+1],level:r.level++}),r.tokens.push({type:"tr_open",lines:[e,e+1],level:r.level++}),a=0;a<c.length;a++)r.tokens.push({type:"th_open",align:u[a],lines:[e,e+1],level:r.level++}),r.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:r.level,children:[]}),r.tokens.push({type:"th_close",level:--r.level});for(r.tokens.push({type:"tr_close",level:--r.level}),r.tokens.push({type:"thead_close",level:--r.level}),r.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:r.level++}),l=e+2;l<t&&!(r.tShift[l]<r.blkIndent||(n=Li(r,l).trim(),n.indexOf("|")===-1));l++){for(c=n.replace(/^\||\|$/g,"").split("|"),r.tokens.push({type:"tr_open",level:r.level++}),a=0;a<c.length;a++)r.tokens.push({type:"td_open",align:u[a],level:r.level++}),d=c[a].substring(c[a].charCodeAt(0)===124?1:0,c[a].charCodeAt(c[a].length-1)===124?c[a].length-1:c[a].length).trim(),r.tokens.push({type:"inline",content:d,level:r.level,children:[]}),r.tokens.push({type:"td_close",level:--r.level});r.tokens.push({type:"tr_close",level:--r.level});}return r.tokens.push({type:"tbody_close",level:--r.level}),r.tokens.push({type:"table_close",level:--r.level}),f[1]=m[1]=l,r.line=l,!0;}function Ps(r,e){var t,s,i=r.bMarks[e]+r.tShift[e],n=r.eMarks[e];return i>=n||(s=r.src.charCodeAt(i++),s!==126&&s!==58)||(t=r.skipSpaces(i),i===t)||t>=n?-1:t;}function ko(r,e){var t,s,i=r.level+2;for(t=e+2,s=r.tokens.length-2;t<s;t++)r.tokens[t].level===i&&r.tokens[t].type==="paragraph_open"&&(r.tokens[t+2].tight=!0,r.tokens[t].tight=!0,t+=2);}function Lo(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p,g,E;if(s)return r.ddIndent<0?!1:Ps(r,e)>=0;if(d=e+1,r.isEmpty(d)&&++d>t||r.tShift[d]<r.blkIndent||(i=Ps(r,d),i<0)||r.level>=r.options.maxNesting)return!1;c=r.tokens.length,r.tokens.push({type:"dl_open",lines:l=[e,0],level:r.level++}),o=e,n=d;e:for(;;){for(E=!0,g=!1,r.tokens.push({type:"dt_open",lines:[o,o],level:r.level++}),r.tokens.push({type:"inline",content:r.getLines(o,o+1,r.blkIndent,!1).trim(),level:r.level+1,lines:[o,o],children:[]}),r.tokens.push({type:"dt_close",level:--r.level});;){if(r.tokens.push({type:"dd_open",lines:a=[d,0],level:r.level++}),p=r.tight,h=r.ddIndent,u=r.blkIndent,m=r.tShift[n],f=r.parentType,r.blkIndent=r.ddIndent=r.tShift[n]+2,r.tShift[n]=i-r.bMarks[n],r.tight=!0,r.parentType="deflist",r.parser.tokenize(r,n,t,!0),(!r.tight||g)&&(E=!1),g=r.line-n>1&&r.isEmpty(r.line-1),r.tShift[n]=m,r.tight=p,r.parentType=f,r.blkIndent=u,r.ddIndent=h,r.tokens.push({type:"dd_close",level:--r.level}),a[1]=d=r.line,d>=t||r.tShift[d]<r.blkIndent)break e;if(i=Ps(r,d),i<0)break;n=d;}if(d>=t||(o=d,r.isEmpty(o))||r.tShift[o]<r.blkIndent||(n=o+1,n>=t)||(r.isEmpty(n)&&n++,n>=t)||r.tShift[n]<r.blkIndent||(i=Ps(r,n),i<0))break;}return r.tokens.push({type:"dl_close",level:--r.level}),l[1]=d,r.line=d,E&&ko(r,c),!0;}function Oo(r,e){var t,s,i,n,o,a=e+1,l;if(t=r.lineMax,a<t&&!r.isEmpty(a)){for(l=r.parser.ruler.getRules("paragraph");a<t&&!r.isEmpty(a);a++)if(!(r.tShift[a]-r.blkIndent>3)){for(i=!1,n=0,o=l.length;n<o;n++)if(l[n](r,a,t,!0)){i=!0;break;}if(i)break;}}return s=r.getLines(e,a,r.blkIndent,!1).trim(),r.line=a,s.length&&(r.tokens.push({type:"paragraph_open",tight:!1,lines:[e,r.line],level:r.level}),r.tokens.push({type:"inline",content:s,level:r.level+1,lines:[e,r.line],children:[]}),r.tokens.push({type:"paragraph_close",tight:!1,level:r.level})),!0;}var Ds=[["code",yo],["fences",bo,["paragraph","blockquote","list"]],["blockquote",vo,["paragraph","blockquote","list"]],["hr",_o,["paragraph","blockquote","list"]],["list",So,["paragraph","blockquote"]],["footnote",xo,["paragraph"]],["heading",Ao,["paragraph","blockquote"]],["lheading",Co],["htmlblock",Mo,["paragraph","blockquote"]],["table",Io,["paragraph"]],["deflist",Lo,["paragraph"]],["paragraph",Oo]];function an(){this.ruler=new _e();for(var r=0;r<Ds.length;r++)this.ruler.push(Ds[r][0],Ds[r][1],{alt:(Ds[r][2]||[]).slice()});}an.prototype.tokenize=function(r,e,t){for(var s=this.ruler.getRules(""),i=s.length,n=e,o=!1,a,l;n<t&&(r.line=n=r.skipEmptyLines(n),!(n>=t||r.tShift[n]<r.blkIndent));){for(l=0;l<i&&(a=s[l](r,n,t,!1),!a);l++);if(r.tight=!o,r.isEmpty(r.line-1)&&(o=!0),n=r.line,n<t&&r.isEmpty(n)){if(o=!0,n++,n<t&&r.parentType==="list"&&r.isEmpty(n))break;r.line=n;}}};var No=/[\n\t]/g,Po=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Do=/\u00a0/g;an.prototype.parse=function(r,e,t,s){var i,n=0,o=0;if(!r)return[];r=r.replace(Do," "),r=r.replace(Po,"\n"),r.indexOf(" ")>=0&&(r=r.replace(No,function(a,l){var c;return r.charCodeAt(l)===10?(n=l+1,o=0,a):(c=" ".slice((l-n-o)%4),o=l-n+1,c);})),i=new Mt(r,this,e,t,s),this.tokenize(i,i.line,i.lineMax);};function Bo(r){switch(r){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1;}}function Fo(r,e){for(var t=r.pos;t<r.posMax&&!Bo(r.src.charCodeAt(t));)t++;return t===r.pos?!1:(e||(r.pending+=r.src.slice(r.pos,t)),r.pos=t,!0);}function Uo(r,e){var t,s,i=r.pos;if(r.src.charCodeAt(i)!==10)return!1;if(t=r.pending.length-1,s=r.posMax,!e)if(t>=0&&r.pending.charCodeAt(t)===32){if(t>=1&&r.pending.charCodeAt(t-1)===32){for(var n=t-2;n>=0;n--)if(r.pending.charCodeAt(n)!==32){r.pending=r.pending.substring(0,n+1);break;}r.push({type:"hardbreak",level:r.level});}else r.pending=r.pending.slice(0,-1),r.push({type:"softbreak",level:r.level});}else r.push({type:"softbreak",level:r.level});for(i++;i<s&&r.src.charCodeAt(i)===32;)i++;return r.pos=i,!0;}var ln=[];for(var Nn=0;Nn<256;Nn++)ln.push(0);"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(r){ln[r.charCodeAt(0)]=1;});function Ho(r,e){var t,s=r.pos,i=r.posMax;if(r.src.charCodeAt(s)!==92)return!1;if(s++,s<i){if(t=r.src.charCodeAt(s),t<256&&ln[t]!==0)return e||(r.pending+=r.src[s]),r.pos+=2,!0;if(t===10){for(e||r.push({type:"hardbreak",level:r.level}),s++;s<i&&r.src.charCodeAt(s)===32;)s++;return r.pos=s,!0;}}return e||(r.pending+="\\"),r.pos++,!0;}function jo(r,e){var t,s,i,n,o,a=r.pos,l=r.src.charCodeAt(a);if(l!==96)return!1;for(t=a,a++,s=r.posMax;a<s&&r.src.charCodeAt(a)===96;)a++;for(i=r.src.slice(t,a),n=o=a;(n=r.src.indexOf("`",o))!==-1;){for(o=n+1;o<s&&r.src.charCodeAt(o)===96;)o++;if(o-n===i.length)return e||r.push({type:"code",content:r.src.slice(a,n).replace(/[ \n]+/g," ").trim(),block:!1,level:r.level}),r.pos=o,!0;}return e||(r.pending+=i),r.pos+=i.length,!0;}function qo(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==126||e||o+4>=n||r.src.charCodeAt(o+1)!==126||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===126)||l===126||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===126;)s++;if(s>o+3)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===126&&r.src.charCodeAt(r.pos+1)===126&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==126&&a!==126&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"del_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"del_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Vo(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==43||e||o+4>=n||r.src.charCodeAt(o+1)!==43||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===43)||l===43||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===43;)s++;if(s!==o+2)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===43&&r.src.charCodeAt(r.pos+1)===43&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==43&&a!==43&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"ins_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"ins_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Go(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==61||e||o+4>=n||r.src.charCodeAt(o+1)!==61||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===61)||l===61||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===61;)s++;if(s!==o+2)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===61&&r.src.charCodeAt(r.pos+1)===61&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==61&&a!==61&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"mark_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"mark_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Pn(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122;}function Dn(r,e){var t=e,s,i,n,o=!0,a=!0,l=r.posMax,c=r.src.charCodeAt(e);for(s=e>0?r.src.charCodeAt(e-1):-1;t<l&&r.src.charCodeAt(t)===c;)t++;return t>=l&&(o=!1),n=t-e,n>=4?o=a=!1:(i=t<l?r.src.charCodeAt(t):-1,(i===32||i===10)&&(o=!1),(s===32||s===10)&&(a=!1),c===95&&(Pn(s)&&(o=!1),Pn(i)&&(a=!1))),{can_open:o,can_close:a,delims:n};}function Ko(r,e){var t,s,i,n,o,a,l,c=r.posMax,d=r.pos,u=r.src.charCodeAt(d);if(u!==95&&u!==42||e)return!1;if(l=Dn(r,d),t=l.delims,!l.can_open)return r.pos+=t,e||(r.pending+=r.src.slice(d,r.pos)),!0;if(r.level>=r.options.maxNesting)return!1;for(r.pos=d+t,a=[t];r.pos<c;){if(r.src.charCodeAt(r.pos)===u){if(l=Dn(r,r.pos),s=l.delims,l.can_close){for(n=a.pop(),o=s;n!==o;){if(o<n){a.push(n-o);break;}if(o-=n,a.length===0)break;r.pos+=n,n=a.pop();}if(a.length===0){t=n,i=!0;break;}r.pos+=s;continue;}l.can_open&&a.push(s),r.pos+=s;continue;}r.parser.skipToken(r);}return i?(r.posMax=r.pos,r.pos=d+t,e||((t===2||t===3)&&r.push({type:"strong_open",level:r.level++}),(t===1||t===3)&&r.push({type:"em_open",level:r.level++}),r.parser.tokenize(r),(t===1||t===3)&&r.push({type:"em_close",level:--r.level}),(t===2||t===3)&&r.push({type:"strong_close",level:--r.level})),r.pos=r.posMax+t,r.posMax=c,!0):(r.pos=d,!1);}var zo=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Jo(r,e){var t,s,i=r.posMax,n=r.pos;if(r.src.charCodeAt(n)!==126||e||n+2>=i||r.level>=r.options.maxNesting)return!1;for(r.pos=n+1;r.pos<i;){if(r.src.charCodeAt(r.pos)===126){t=!0;break;}r.parser.skipToken(r);}return!t||n+1===r.pos||(s=r.src.slice(n+1,r.pos),s.match(/(^|[^\\])(\\\\)*\s/))?(r.pos=n,!1):(r.posMax=r.pos,r.pos=n+1,e||r.push({type:"sub",level:r.level,content:s.replace(zo,"$1")}),r.pos=r.posMax+1,r.posMax=i,!0);}var $o=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Wo(r,e){var t,s,i=r.posMax,n=r.pos;if(r.src.charCodeAt(n)!==94||e||n+2>=i||r.level>=r.options.maxNesting)return!1;for(r.pos=n+1;r.pos<i;){if(r.src.charCodeAt(r.pos)===94){t=!0;break;}r.parser.skipToken(r);}return!t||n+1===r.pos||(s=r.src.slice(n+1,r.pos),s.match(/(^|[^\\])(\\\\)*\s/))?(r.pos=n,!1):(r.posMax=r.pos,r.pos=n+1,e||r.push({type:"sup",level:r.level,content:s.replace($o,"$1")}),r.pos=r.posMax+1,r.posMax=i,!0);}function Xo(r,e){var t,s,i,n,o,a,l,c,d=!1,u=r.pos,h=r.posMax,f=r.pos,m=r.src.charCodeAt(f);if(m===33&&(d=!0,m=r.src.charCodeAt(++f)),m!==91||r.level>=r.options.maxNesting||(t=f+1,s=Ss(r,f),s<0))return!1;if(a=s+1,a<h&&r.src.charCodeAt(a)===40){for(a++;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a>=h)return!1;for(f=a,br(r,a)?(n=r.linkContent,a=r.pos):n="",f=a;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a<h&&f!==a&&vr(r,a))for(o=r.linkContent,a=r.pos;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);else o="";if(a>=h||r.src.charCodeAt(a)!==41)return r.pos=u,!1;a++;}else{if(r.linkLevel>0)return!1;for(;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a<h&&r.src.charCodeAt(a)===91&&(f=a+1,a=Ss(r,a),a>=0?i=r.src.slice(f,a++):a=f-1),i||(_typeof(i)>"u"&&(a=s+1),i=r.src.slice(t,s)),l=r.env.references[_r(i)],!l)return r.pos=u,!1;n=l.href,o=l.title;}return e||(r.pos=t,r.posMax=s,d?r.push({type:"image",src:n,title:o,alt:r.src.substr(t,s-t),level:r.level}):(r.push({type:"link_open",href:n,title:o,level:r.level++}),r.linkLevel++,r.parser.tokenize(r),r.linkLevel--,r.push({type:"link_close",level:--r.level}))),r.pos=a,r.posMax=h,!0;}function Yo(r,e){var t,s,i,n,o=r.posMax,a=r.pos;return a+2>=o||r.src.charCodeAt(a)!==94||r.src.charCodeAt(a+1)!==91||r.level>=r.options.maxNesting||(t=a+2,s=Ss(r,a+1),s<0)?!1:(e||(r.env.footnotes||(r.env.footnotes={}),r.env.footnotes.list||(r.env.footnotes.list=[]),i=r.env.footnotes.list.length,r.pos=t,r.posMax=s,r.push({type:"footnote_ref",id:i,level:r.level}),r.linkLevel++,n=r.tokens.length,r.parser.tokenize(r),r.env.footnotes.list[i]={tokens:r.tokens.splice(n)},r.linkLevel--),r.pos=s+1,r.posMax=o,!0);}function Zo(r,e){var t,s,i,n,o=r.posMax,a=r.pos;if(a+3>o||!r.env.footnotes||!r.env.footnotes.refs||r.src.charCodeAt(a)!==91||r.src.charCodeAt(a+1)!==94||r.level>=r.options.maxNesting)return!1;for(s=a+2;s<o;s++){if(r.src.charCodeAt(s)===32||r.src.charCodeAt(s)===10)return!1;if(r.src.charCodeAt(s)===93)break;}return s===a+2||s>=o||(s++,t=r.src.slice(a+2,s-1),_typeof(r.env.footnotes.refs[":"+t])>"u")?!1:(e||(r.env.footnotes.list||(r.env.footnotes.list=[]),r.env.footnotes.refs[":"+t]<0?(i=r.env.footnotes.list.length,r.env.footnotes.list[i]={label:t,count:0},r.env.footnotes.refs[":"+t]=i):i=r.env.footnotes.refs[":"+t],n=r.env.footnotes.list[i].count,r.env.footnotes.list[i].count++,r.push({type:"footnote_ref",id:i,subId:n,level:r.level})),r.pos=s,r.posMax=o,!0);}var Qo=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"],ea=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,ta=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function sa(r,e){var t,s,i,n,o,a=r.pos;return r.src.charCodeAt(a)!==60||(t=r.src.slice(a),t.indexOf(">")<0)?!1:(s=t.match(ta),s?Qo.indexOf(s[1].toLowerCase())<0||(n=s[0].slice(1,-1),o=Bi(n),!r.parser.validateLink(n))?!1:(e||(r.push({type:"link_open",href:o,level:r.level}),r.push({type:"text",content:n,level:r.level+1}),r.push({type:"link_close",level:r.level})),r.pos+=s[0].length,!0):(i=t.match(ea),i?(n=i[0].slice(1,-1),o=Bi("mailto:"+n),r.parser.validateLink(o)?(e||(r.push({type:"link_open",href:o,level:r.level}),r.push({type:"text",content:n,level:r.level+1}),r.push({type:"link_close",level:r.level})),r.pos+=i[0].length,!0):!1):!1));}function Si(r,e){return r=r.source,e=e||"",function t(s,i){return s?(i=i.source||i,r=r.replace(s,i),t):new RegExp(r,e);};}var ia=/[a-zA-Z_:][a-zA-Z0-9:._-]*/,na=/[^"'=<>`\x00-\x20]+/,ra=/'[^']*'/,oa=/"[^"]*"/,aa=Si(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",na)("single_quoted",ra)("double_quoted",oa)(),la=Si(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",ia)("attr_value",aa)(),ca=Si(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",la)(),da=/<\/[A-Za-z][A-Za-z0-9]*\s*>/,ha=/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/,ua=/<[?].*?[?]>/,fa=/<![A-Z]+\s+[^>]*>/,pa=/<!\[CDATA\[[\s\S]*?\]\]>/,ma=Si(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",ca)("close_tag",da)("comment",ha)("processing",ua)("declaration",fa)("cdata",pa)();function ga(r){var e=r|32;return e>=97&&e<=122;}function ya(r,e){var t,s,i,n=r.pos;return!r.options.html||(i=r.posMax,r.src.charCodeAt(n)!==60||n+2>=i)||(t=r.src.charCodeAt(n+1),t!==33&&t!==63&&t!==47&&!ga(t))||(s=r.src.slice(n).match(ma),!s)?!1:(e||r.push({type:"htmltag",content:r.src.slice(n,n+s[0].length),level:r.level}),r.pos+=s[0].length,!0);}var ba=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,va=/^&([a-z][a-z0-9]{1,31});/i;function _a(r,e){var t,s,i,n=r.pos,o=r.posMax;if(r.src.charCodeAt(n)!==38)return!1;if(n+1<o){if(t=r.src.charCodeAt(n+1),t===35){if(i=r.src.slice(n).match(ba),i)return e||(s=i[1][0].toLowerCase()==="x"?parseInt(i[1].slice(1),16):parseInt(i[1],10),r.pending+=gr(s)?Di(s):Di(65533)),r.pos+=i[0].length,!0;}else if(i=r.src.slice(n).match(va),i){var a=pr(i[1]);if(i[1]!==a)return e||(r.pending+=a),r.pos+=i[0].length,!0;}}return e||(r.pending+="&"),r.pos++,!0;}var Oi=[["text",Fo],["newline",Uo],["escape",Ho],["backticks",jo],["del",qo],["ins",Vo],["mark",Go],["emphasis",Ko],["sub",Jo],["sup",Wo],["links",Xo],["footnote_inline",Yo],["footnote_ref",Zo],["autolink",sa],["htmltag",ya],["entity",_a]];function xi(){this.ruler=new _e();for(var r=0;r<Oi.length;r++)this.ruler.push(Oi[r][0],Oi[r][1]);this.validateLink=Ea;}xi.prototype.skipToken=function(r){var e=this.ruler.getRules(""),t=e.length,s=r.pos,i,n;if((n=r.cacheGet(s))>0){r.pos=n;return;}for(i=0;i<t;i++)if(e[i](r,!0)){r.cacheSet(s,r.pos);return;}r.pos++,r.cacheSet(s,r.pos);};xi.prototype.tokenize=function(r){for(var e=this.ruler.getRules(""),t=e.length,s=r.posMax,i,n;r.pos<s;){for(n=0;n<t&&(i=e[n](r,!1),!i);n++);if(i){if(r.pos>=s)break;continue;}r.pending+=r.src[r.pos++];}r.pending&&r.pushPending();};xi.prototype.parse=function(r,e,t,s){var i=new Rt(r,this,e,t,s);this.tokenize(i);};function Ea(r){var e=["vbscript","javascript","file","data"],t=r.trim().toLowerCase();return t=At(t),!(t.indexOf(":")!==-1&&e.indexOf(t.split(":")[0])!==-1);}var Sa={options:{html:!1,// Enable HTML tags in source
26
+ },{key:"processStreamHTMLWrappers",value:function processStreamHTMLWrappers(e){if(!e||_typeof(e)!==T)return;var t=e.htmlWrappers;if(t)return console.error("The htmlWrappers property has been moved to Deep Chat's base since version 2.3.0."),console.error("Check it out here: https://deepchat.dev/docs/messages/HTML#htmlWrappers"),t;}},{key:"processFocusMode",value:function processFocusMode(e){return!e||typeof e=="boolean"||e.scroll&&(console.error("The scroll property in focusMode has been changed to smoothScroll since version 2.3.0."),console.error("Check it out here: https://deepchat.dev/docs/modes#focusMode"),e.smoothScroll=!0),e;}}]);}();var lt=/*#__PURE__*/function(){function lt(){_classCallCheck(this,lt);}return _createClass(lt,null,[{key:"mouseUp",value:function mouseUp(e,t){U.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t["default"]),Object.assign(e.style,t.hover);}},{key:"mouseDown",value:function mouseDown(e,t){Object.assign(e.style,t.click);}},{key:"mouseLeave",value:function mouseLeave(e,t){U.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t["default"]);}},{key:"mouseEnter",value:function mouseEnter(e,t){Object.assign(e.style,t.hover);}},{key:"add",value:function add(e,t){e.addEventListener("mouseenter",lt.mouseEnter.bind(this,e,t)),e.addEventListener("mouseleave",lt.mouseLeave.bind(this,e,t)),e.addEventListener("mousedown",lt.mouseDown.bind(this,e,t)),e.addEventListener("mouseup",lt.mouseUp.bind(this,e,t));}}]);}();var jr="deep-chat-temporary-message",qr="deep-chat-suggestion-button",Pi={"deep-chat-button":{styles:{"default":{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},Tn=Object.keys(Pi);var De=/*#__PURE__*/function(){function De(){_classCallCheck(this,De);}return _createClass(De,null,[{key:"applySuggestionEvent",value:function applySuggestionEvent(e,t){setTimeout(function(){t.addEventListener("click",function(){var s,i;(i=e.submitUserMessage)==null||i.call(e,_defineProperty({},y,((s=t.textContent)==null?void 0:s.trim())||""));});});}},{key:"isElementTemporary",value:function isElementTemporary(e){var t;return e?(t=e.bubbleElement.children[0])==null?void 0:t.classList.contains(jr):!1;}},{key:"doesElementContainDeepChatClass",value:function doesElementContainDeepChatClass(e){return Tn.find(function(t){return e.classList.contains(t);});}},{key:"applyEvents",value:function applyEvents(e,t){var s=Pi[t].events;Object.keys(s||[]).forEach(function(i){e.addEventListener(i,s==null?void 0:s[i]);});}},{key:"getProcessedStyles",value:function getProcessedStyles(e,t,s){var i=Array.from(t.classList).reduce(function(a,l){var d;var c=(d=e[l])==null?void 0:d.styles;return c&&e[l].styles&&a.push(c),a;},[]),n=Pi[s].styles;if(n){var a=JSON.parse(JSON.stringify(n));a["default"]&&U.overwriteDefaultWithAlreadyApplied(a,t),i.unshift(a);}var o=U.mergeStatefulStyles(i);return U.processStateful(o);}},{key:"applyDeepChatUtilities",value:function applyDeepChatUtilities(e,t,s){Tn.forEach(function(n){var o=s.getElementsByClassName(n);Array.from(o||[]).forEach(function(a){var l=De.getProcessedStyles(t,a,n);le.applyStylesToElement(a,l),De.applyEvents(a,n);});});var i=s.getElementsByClassName(qr);Array.from(i).forEach(function(n){return De.applySuggestionEvent(e,n);});}}]);}();var Te=/*#__PURE__*/function(){function Te(){_classCallCheck(this,Te);}return _createClass(Te,null,[{key:"applyStylesToElement",value:function applyStylesToElement(e,t){var s=U.processStateful(t);lt.add(e,s),Object.assign(e.style,s["default"]);}},{key:"applyEventsToElement",value:function applyEventsToElement(e,t){Object.keys(t).forEach(function(s){var i=t[s];i&&e.addEventListener(s,i);});}},{key:"applyClassUtilitiesToElement",value:function applyClassUtilitiesToElement(e,t){var s=t.events,i=t.styles;s&&Te.applyEventsToElement(e,s),i&&!De.doesElementContainDeepChatClass(e)&&Te.applyStylesToElement(e,i);}},{key:"applyCustomClassUtilities",value:function applyCustomClassUtilities(e,t){Object.keys(e).forEach(function(s){var i=t.getElementsByClassName(s);Array.from(i).forEach(function(n){e[s]&&Te.applyClassUtilitiesToElement(n,e[s]);});});}},{key:"apply",value:function apply(e,t){De.applyDeepChatUtilities(e,e.htmlClassUtilities,t),Te.applyCustomClassUtilities(e.htmlClassUtilities,t);}},{key:"traverseNodes",value:function traverseNodes(e,t){e.nodeType===Node.ELEMENT_NODE&&t.push(e.outerHTML),e.childNodes.forEach(function(s){Te.traverseNodes(s,t);});}},{key:"splitHTML",value:function splitHTML(e){var s=new DOMParser().parseFromString(e,"text/html"),i=[];return s.body.childNodes.forEach(function(n){Te.traverseNodes(n,i);}),i;}},{key:"isTemporaryBasedOnHTML",value:function isTemporaryBasedOnHTML(e){var t=document.createElement("div");return t.innerHTML=e,De.isElementTemporary({outerContainer:t,bubbleElement:t,innerContainer:t});}// useful for removing event listeners
27
+ },{key:"replaceElementWithNewClone",value:function replaceElementWithNewClone(e,t){var i;var s=(t||e).cloneNode(!0);return(i=e.parentNode)==null||i.replaceChild(s,e),s;}},{key:"tryAddWrapper",value:function tryAddWrapper(e,t,s,i){if(t&&i){var n=(s==null?void 0:s[i])||(s==null?void 0:s["default"]);if(n)return e.innerHTML=n,{contentEl:Te.getTargetWrapper(e),wrapper:!0};}return{contentEl:e,wrapper:!1};}},{key:"getTargetWrapper",value:function getTargetWrapper(e){return e.getElementsByClassName(Te.TARGET_WRAPPER_CLASS)[0]||e;}}]);}();Te.TARGET_WRAPPER_CLASS="html-wrapper";var le=Te;var Ke=/*#__PURE__*/function(){function Ke(){_classCallCheck(this,Ke);}return _createClass(Ke,null,[{key:"addElement",value:function addElement(e,t,s){var i=F.isScrollbarAtBottomOfElement(e.elementRef);e.appendOuterContainerElemet(t),!e.focusMode&&s&&i&&F.scrollToBottom(e.elementRef,!1,t);}},{key:"createElements",value:function createElements(e,t,s,i){var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;var o=e.createMessageElementsOnOrientation("",s,i,n);o.bubbleElement.classList.add(Ke.HTML_BUBBLE_CLASS);var _le$tryAddWrapper=le.tryAddWrapper(o.bubbleElement,t,e._customWrappers,s),a=_le$tryAddWrapper.contentEl;return a.innerHTML=t,o;}},{key:"overwriteElements",value:function overwriteElements(e,t,s){s.bubbleElement.innerHTML=t,le.apply(e,s.outerContainer),te.flagHTMLUpdateClass(s.bubbleElement);}// prettier-ignore
28
+ },{key:"overwrite",value:function overwrite(e,t,s,i){var n=e.messageToElements,o=v.overwriteMessage(n,i,t,s,"html",Ke.HTML_BUBBLE_CLASS);return o&&Ke.overwriteElements(e,t,o),o;}},{key:"create",value:function create(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;var n=Ke.createElements(e,t,s,i);return v.fillEmptyMessageElement(n.bubbleElement,t),le.apply(e,n.outerContainer),te.flagHTMLUpdateClass(n.bubbleElement),e.applyCustomStyles(n,s,!1,(o=e.messageStyles)==null?void 0:o.html),n;}// prettier-ignore
29
+ },{key:"add",value:function add(e,t,s,i,n){var o=arguments.length>5&&arguments[5]!==undefined?arguments[5]:!1;if(n!=null&&n.status){var l=this.overwrite(e,t,s,e.messageElementRefs);if(l)return l;n.status=!1;}if(o&&e.messageElementRefs.length>0&&le.isTemporaryBasedOnHTML(t))return;var a=Ke.create(e,t,s,o);return o||Ke.addElement(e,a.outerContainer,i),a;}}]);}();Ke.HTML_BUBBLE_CLASS="html-message";var Be=Ke;var Vr=/*#__PURE__*/function(){function Vr(){_classCallCheck(this,Vr);}return _createClass(Vr,null,[{key:"katex",value:function katex(e,t,s){var a=(s||{}).delimiter||"$";if(a.length!==1)throw new Error("invalid delimiter");var l=function l(u,h){var f;return((f=window.katex)==null?void 0:f.renderToString(u,_objectSpread({displayMode:h,throwOnError:!1,output:"mathml"},e)))||"";},c=function c(u,h,f){var m=!1,p=u.bMarks[h]+u.tShift[h],g=u.eMarks[h];if(p+1>g)return!1;var E=u.src.charAt(p);if(E!==a)return!1;var I=p;p=u.skipChars(p,E);var P=p-I;if(P!==2)return!1;var D=h;for(;++D,!(D>=f||(p=I=u.bMarks[D]+u.tShift[D],g=u.eMarks[D],p<g&&u.tShift[D]<u.blkIndent));)if(u.src.charAt(p)===a&&!(u.tShift[D]-u.blkIndent>=4)&&(p=u.skipChars(p,E),!(p-I<P)&&(p=u.skipSpaces(p),!(p<g)))){m=!0;break;}P=u.tShift[h],u.line=D+(m?1:0);var ne=u.getLines(h+1,D,P,!0).replace(/[ \n]+/g," ").trim();return u.tokens.push({type:"katex",params:null,content:ne,lines:[h,u.line],level:u.level,block:!0}),!0;},d=function d(u,h){var f=u.pos,m=u.posMax;var p=f;if(u.src.charAt(p)!==a)return!1;for(++p;p<m&&u.src.charAt(p)===a;)++p;var g=u.src.slice(f,p);if(g.length>2)return!1;var E=p;var I=0;for(;p<m;){var P=u.src.charAt(p);if(P==="{"&&(p===0||u.src.charAt(p-1)!=="\\"))I+=1;else if(P==="}"&&(p===0||u.src.charAt(p-1)!=="\\")){if(I-=1,I<0)return!1;}else if(P===a&&I===0){var D=p;var ne=p+1;for(;ne<m&&u.src.charAt(ne)===a;)++ne;if(ne-D===g.length){if(!h){var st=u.src.slice(E,D).replace(/[ \n]+/g," ").trim();u.push({type:"katex",content:st,block:g.length>1,level:u.level});}return u.pos=ne,!0;}}p+=1;}return h||(u.pending+=g),u.pos+=g.length,!0;};t.inline.ruler.push("katex",d,s),t.block.ruler.push("katex",c,s),t.renderer.rules.katex=function(u,h){return l(u[h].content,u[h].block);},t.renderer.rules.katex.delimiter=a;}}]);}();var Ns;function pr(r){return Ns=Ns||document.createElement("textarea"),Ns.innerHTML="&"+r+";",Ns.value;}var Gr=Object.prototype.hasOwnProperty;function Kr(r,e){return r?Gr.call(r,e):!1;}function mr(r){var e=[].slice.call(arguments,1);return e.forEach(function(t){if(t){if(_typeof(t)!="object")throw new TypeError(t+"must be object");Object.keys(t).forEach(function(s){r[s]=t[s];});}}),r;}var zr=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Es(r){return r.indexOf("\\")<0?r:r.replace(zr,"$1");}function gr(r){return!(r>=55296&&r<=57343||r>=64976&&r<=65007||(r&65535)===65535||(r&65535)===65534||r>=0&&r<=8||r===11||r>=14&&r<=31||r>=127&&r<=159||r>1114111);}function Di(r){if(r>65535){r-=65536;var e=55296+(r>>10),t=56320+(r&1023);return String.fromCharCode(e,t);}return String.fromCharCode(r);}var Jr=/&([a-z#][a-z0-9]{1,31});/gi,$r=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Wr(r,e){var t=0,s=pr(e);return e!==s?s:e.charCodeAt(0)===35&&$r.test(e)&&(t=e[1].toLowerCase()==="x"?parseInt(e.slice(2),16):parseInt(e.slice(1),10),gr(t))?Di(t):r;}function At(r){return r.indexOf("&")<0?r:r.replace(Jr,Wr);}var Xr=/[&<>"]/,Yr=/[&<>"]/g,Zr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function Qr(r){return Zr[r];}function pe(r){return Xr.test(r)?r.replace(Yr,Qr):r;}var _={};_.blockquote_open=function(){return"<blockquote>\n";};_.blockquote_close=function(r,e){return"</blockquote>"+Tt(r,e);};_.code=function(r,e){return r[e].block?"<pre><code>"+pe(r[e].content)+"</code></pre>"+Tt(r,e):"<code>"+pe(r[e].content)+"</code>";};_.fence=function(r,e,t,s,i){var n=r[e],o="",a=t.langPrefix,l="",c,d,u;if(n.params){if(c=n.params.split(/\s+/g),d=c.join(" "),Kr(i.rules.fence_custom,c[0]))return i.rules.fence_custom[c[0]](r,e,t,s,i);l=pe(At(Es(d))),o=' class="'+a+l+'"';}return t.highlight?u=t.highlight.apply(t.highlight,[n.content].concat(c))||pe(n.content):u=pe(n.content),"<pre><code"+o+">"+u+"</code></pre>"+Tt(r,e);};_.fence_custom={};_.heading_open=function(r,e){return"<h"+r[e].hLevel+">";};_.heading_close=function(r,e){return"</h"+r[e].hLevel+">\n";};_.hr=function(r,e,t){return(t.xhtmlOut?"<hr />":"<hr>")+Tt(r,e);};_.bullet_list_open=function(){return"<ul>\n";};_.bullet_list_close=function(r,e){return"</ul>"+Tt(r,e);};_.list_item_open=function(){return"<li>";};_.list_item_close=function(){return"</li>\n";};_.ordered_list_open=function(r,e){var t=r[e],s=t.order>1?' start="'+t.order+'"':"";return"<ol"+s+">\n";};_.ordered_list_close=function(r,e){return"</ol>"+Tt(r,e);};_.paragraph_open=function(r,e){return r[e].tight?"":"<p>";};_.paragraph_close=function(r,e){var t=!(r[e].tight&&e&&r[e-1].type==="inline"&&!r[e-1].content);return(r[e].tight?"":"</p>")+(t?Tt(r,e):"");};_.link_open=function(r,e,t){var s=r[e].title?' title="'+pe(At(r[e].title))+'"':"",i=t.linkTarget?' target="'+t.linkTarget+'"':"";return'<a href="'+pe(r[e].href)+'"'+s+i+">";};_.link_close=function(){return"</a>";};_.image=function(r,e,t){var s=' src="'+pe(r[e].src)+'"',i=r[e].title?' title="'+pe(At(r[e].title))+'"':"",n=' alt="'+(r[e].alt?pe(At(Es(r[e].alt))):"")+'"',o=t.xhtmlOut?" /":"";return"<img"+s+n+i+o+">";};_.table_open=function(){return"<table>\n";};_.table_close=function(){return"</table>\n";};_.thead_open=function(){return"<thead>\n";};_.thead_close=function(){return"</thead>\n";};_.tbody_open=function(){return"<tbody>\n";};_.tbody_close=function(){return"</tbody>\n";};_.tr_open=function(){return"<tr>";};_.tr_close=function(){return"</tr>\n";};_.th_open=function(r,e){var t=r[e];return"<th"+(t.align?' style="text-align:'+t.align+'"':"")+">";};_.th_close=function(){return"</th>";};_.td_open=function(r,e){var t=r[e];return"<td"+(t.align?' style="text-align:'+t.align+'"':"")+">";};_.td_close=function(){return"</td>";};_.strong_open=function(){return"<strong>";};_.strong_close=function(){return"</strong>";};_.em_open=function(){return"<em>";};_.em_close=function(){return"</em>";};_.del_open=function(){return"<del>";};_.del_close=function(){return"</del>";};_.ins_open=function(){return"<ins>";};_.ins_close=function(){return"</ins>";};_.mark_open=function(){return"<mark>";};_.mark_close=function(){return"</mark>";};_.sub=function(r,e){return"<sub>"+pe(r[e].content)+"</sub>";};_.sup=function(r,e){return"<sup>"+pe(r[e].content)+"</sup>";};_.hardbreak=function(r,e,t){return t.xhtmlOut?"<br />\n":"<br>\n";};_.softbreak=function(r,e,t){return t.breaks?t.xhtmlOut?"<br />\n":"<br>\n":"\n";};_.text=function(r,e){return pe(r[e].content);};_.htmlblock=function(r,e){return r[e].content;};_.htmltag=function(r,e){return r[e].content;};_.abbr_open=function(r,e){return'<abbr title="'+pe(At(r[e].title))+'">';};_.abbr_close=function(){return"</abbr>";};_.footnote_ref=function(r,e){var t=Number(r[e].id+1).toString(),s="fnref"+t;return r[e].subId>0&&(s+=":"+r[e].subId),'<sup class="footnote-ref"><a href="#fn'+t+'" id="'+s+'">['+t+"]</a></sup>";};_.footnote_block_open=function(r,e,t){var s=t.xhtmlOut?"<hr class=\"footnotes-sep\" />\n":"<hr class=\"footnotes-sep\">\n";return s+"<section class=\"footnotes\">\n<ol class=\"footnotes-list\">\n";};_.footnote_block_close=function(){return"</ol>\n</section>\n";};_.footnote_open=function(r,e){var t=Number(r[e].id+1).toString();return'<li id="fn'+t+'" class="footnote-item">';};_.footnote_close=function(){return"</li>\n";};_.footnote_anchor=function(r,e){var t=Number(r[e].id+1).toString(),s="fnref"+t;return r[e].subId>0&&(s+=":"+r[e].subId),' <a href="#'+s+'" class="footnote-backref">↩</a>';};_.dl_open=function(){return"<dl>\n";};_.dt_open=function(){return"<dt>";};_.dd_open=function(){return"<dd>";};_.dl_close=function(){return"</dl>\n";};_.dt_close=function(){return"</dt>\n";};_.dd_close=function(){return"</dd>\n";};function yr(r,e){return++e>=r.length-2?e:r[e].type==="paragraph_open"&&r[e].tight&&r[e+1].type==="inline"&&r[e+1].content.length===0&&r[e+2].type==="paragraph_close"&&r[e+2].tight?yr(r,e+2):e;}var Tt=_.getBreak=function(e,t){return t=yr(e,t),t<e.length&&e[t].type==="list_item_close"?"":"\n";};function on(){this.rules=mr({},_),this.getBreak=_.getBreak;}on.prototype.renderInline=function(r,e,t){for(var s=this.rules,i=r.length,n=0,o="";i--;)o+=s[r[n].type](r,n++,e,t,this);return o;};on.prototype.render=function(r,e,t){for(var s=this.rules,i=r.length,n=-1,o="";++n<i;)r[n].type==="inline"?o+=this.renderInline(r[n].children,e,t):o+=s[r[n].type](r,n,e,t,this);return o;};function _e(){this.__rules__=[],this.__cache__=null;}_e.prototype.__find__=function(r){for(var e=this.__rules__.length,t=-1;e--;)if(this.__rules__[++t].name===r)return t;return-1;};_e.prototype.__compile__=function(){var r=this,e=[""];r.__rules__.forEach(function(t){t.enabled&&t.alt.forEach(function(s){e.indexOf(s)<0&&e.push(s);});}),r.__cache__={},e.forEach(function(t){r.__cache__[t]=[],r.__rules__.forEach(function(s){s.enabled&&(t&&s.alt.indexOf(t)<0||r.__cache__[t].push(s.fn));});});};_e.prototype.at=function(r,e,t){var s=this.__find__(r),i=t||{};if(s===-1)throw new Error("Parser rule not found: "+r);this.__rules__[s].fn=e,this.__rules__[s].alt=i.alt||[],this.__cache__=null;};_e.prototype.before=function(r,e,t,s){var i=this.__find__(r),n=s||{};if(i===-1)throw new Error("Parser rule not found: "+r);this.__rules__.splice(i,0,{name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null;};_e.prototype.after=function(r,e,t,s){var i=this.__find__(r),n=s||{};if(i===-1)throw new Error("Parser rule not found: "+r);this.__rules__.splice(i+1,0,{name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null;};_e.prototype.push=function(r,e,t){var s=t||{};this.__rules__.push({name:r,enabled:!0,fn:e,alt:s.alt||[]}),this.__cache__=null;};_e.prototype.enable=function(r,e){r=Array.isArray(r)?r:[r],e&&this.__rules__.forEach(function(t){t.enabled=!1;}),r.forEach(function(t){var s=this.__find__(t);if(s<0)throw new Error("Rules manager: invalid rule name "+t);this.__rules__[s].enabled=!0;},this),this.__cache__=null;};_e.prototype.disable=function(r){r=Array.isArray(r)?r:[r],r.forEach(function(e){var t=this.__find__(e);if(t<0)throw new Error("Rules manager: invalid rule name "+e);this.__rules__[t].enabled=!1;},this),this.__cache__=null;};_e.prototype.getRules=function(r){return this.__cache__===null&&this.__compile__(),this.__cache__[r]||[];};function eo(r){r.inlineMode?r.tokens.push({type:"inline",content:r.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):r.block.parse(r.src,r.options,r.env,r.tokens);}function Rt(r,e,t,s,i){this.src=r,this.env=s,this.options=t,this.parser=e,this.tokens=i,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0;}Rt.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending="";};Rt.prototype.push=function(r){this.pending&&this.pushPending(),this.tokens.push(r),this.pendingLevel=this.level;};Rt.prototype.cacheSet=function(r,e){for(var t=this.cache.length;t<=r;t++)this.cache.push(0);this.cache[r]=e;};Rt.prototype.cacheGet=function(r){return r<this.cache.length?this.cache[r]:0;};function Ss(r,e){var t,s,i,n=-1,o=r.posMax,a=r.pos,l=r.isInLabel;if(r.isInLabel)return-1;if(r.labelUnmatchedScopes)return r.labelUnmatchedScopes--,-1;for(r.pos=e+1,r.isInLabel=!0,t=1;r.pos<o;){if(i=r.src.charCodeAt(r.pos),i===91)t++;else if(i===93&&(t--,t===0)){s=!0;break;}r.parser.skipToken(r);}return s?(n=r.pos,r.labelUnmatchedScopes=0):r.labelUnmatchedScopes=t-1,r.pos=a,r.isInLabel=l,n;}function to(r,e,t,s){var i,n,o,a,l,c;if(r.charCodeAt(0)!==42||r.charCodeAt(1)!==91||r.indexOf("]:")===-1||(i=new Rt(r,e,t,s,[]),n=Ss(i,1),n<0||r.charCodeAt(n+1)!==58))return-1;for(a=i.posMax,o=n+2;o<a&&i.src.charCodeAt(o)!==10;o++);return l=r.slice(2,n),c=r.slice(n+2,o).trim(),c.length===0?-1:(s.abbreviations||(s.abbreviations={}),_typeof(s.abbreviations[":"+l])>"u"&&(s.abbreviations[":"+l]=c),o);}function so(r){var e=r.tokens,t,s,i,n;if(!r.inlineMode){for(t=1,s=e.length-1;t<s;t++)if(e[t-1].type==="paragraph_open"&&e[t].type==="inline"&&e[t+1].type==="paragraph_close"){for(i=e[t].content;i.length&&(n=to(i,r.inline,r.options,r.env),!(n<0));)i=i.slice(n).trim();e[t].content=i,i.length||(e[t-1].tight=!0,e[t+1].tight=!0);}}}function Bi(r){var e=At(r);try{e=decodeURI(e);}catch(_unused3){}return encodeURI(e);}function br(r,e){var t,s,i,n=e,o=r.posMax;if(r.src.charCodeAt(e)===60){for(e++;e<o;){if(t=r.src.charCodeAt(e),t===10)return!1;if(t===62)return i=Bi(Es(r.src.slice(n+1,e))),r.parser.validateLink(i)?(r.pos=e+1,r.linkContent=i,!0):!1;if(t===92&&e+1<o){e+=2;continue;}e++;}return!1;}for(s=0;e<o&&(t=r.src.charCodeAt(e),!(t===32||t<32||t===127));){if(t===92&&e+1<o){e+=2;continue;}if(t===40&&(s++,s>1)||t===41&&(s--,s<0))break;e++;}return n===e||(i=Es(r.src.slice(n,e)),!r.parser.validateLink(i))?!1:(r.linkContent=i,r.pos=e,!0);}function vr(r,e){var t,s=e,i=r.posMax,n=r.src.charCodeAt(e);if(n!==34&&n!==39&&n!==40)return!1;for(e++,n===40&&(n=41);e<i;){if(t=r.src.charCodeAt(e),t===n)return r.pos=e+1,r.linkContent=Es(r.src.slice(s+1,e)),!0;if(t===92&&e+1<i){e+=2;continue;}e++;}return!1;}function _r(r){return r.trim().replace(/\s+/g," ").toUpperCase();}function io(r,e,t,s){var i,n,o,a,l,c,d,u,h;if(r.charCodeAt(0)!==91||r.indexOf("]:")===-1||(i=new Rt(r,e,t,s,[]),n=Ss(i,0),n<0||r.charCodeAt(n+1)!==58))return-1;for(a=i.posMax,o=n+2;o<a&&(l=i.src.charCodeAt(o),!(l!==32&&l!==10));o++);if(!br(i,o))return-1;for(d=i.linkContent,o=i.pos,c=o,o=o+1;o<a&&(l=i.src.charCodeAt(o),!(l!==32&&l!==10));o++);for(o<a&&c!==o&&vr(i,o)?(u=i.linkContent,o=i.pos):(u="",o=c);o<a&&i.src.charCodeAt(o)===32;)o++;return o<a&&i.src.charCodeAt(o)!==10?-1:(h=_r(r.slice(1,n)),_typeof(s.references[h])>"u"&&(s.references[h]={title:u,href:d}),o);}function no(r){var e=r.tokens,t,s,i,n;if(r.env.references=r.env.references||{},!r.inlineMode){for(t=1,s=e.length-1;t<s;t++)if(e[t].type==="inline"&&e[t-1].type==="paragraph_open"&&e[t+1].type==="paragraph_close"){for(i=e[t].content;i.length&&(n=io(i,r.inline,r.options,r.env),!(n<0));)i=i.slice(n).trim();e[t].content=i,i.length||(e[t-1].tight=!0,e[t+1].tight=!0);}}}function ro(r){var e=r.tokens,t,s,i;for(s=0,i=e.length;s<i;s++)t=e[s],t.type==="inline"&&r.inline.parse(t.content,r.options,r.env,t.children);}function oo(r){var e,t,s,i,n,o,a,l,c,d=0,u=!1,h={};if(r.env.footnotes&&(r.tokens=r.tokens.filter(function(f){return f.type==="footnote_reference_open"?(u=!0,l=[],c=f.label,!1):f.type==="footnote_reference_close"?(u=!1,h[":"+c]=l,!1):(u&&l.push(f),!u);}),!!r.env.footnotes.list)){for(o=r.env.footnotes.list,r.tokens.push({type:"footnote_block_open",level:d++}),e=0,t=o.length;e<t;e++){for(r.tokens.push({type:"footnote_open",id:e,level:d++}),o[e].tokens?(a=[],a.push({type:"paragraph_open",tight:!1,level:d++}),a.push({type:"inline",content:"",level:d,children:o[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--d})):o[e].label&&(a=h[":"+o[e].label]),r.tokens=r.tokens.concat(a),r.tokens[r.tokens.length-1].type==="paragraph_close"?n=r.tokens.pop():n=null,i=o[e].count>0?o[e].count:1,s=0;s<i;s++)r.tokens.push({type:"footnote_anchor",id:e,subId:s,level:d});n&&r.tokens.push(n),r.tokens.push({type:"footnote_close",level:--d});}r.tokens.push({type:"footnote_block_close",level:--d});}}var Rn=" \n()[]'\".,!?-";function Ii(r){return r.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1");}function ao(r){var e,t,s,i,n,o,a,l,c,d,u,h,f=r.tokens;if(r.env.abbreviations){for(r.env.abbrRegExp||(h="(^|["+Rn.split("").map(Ii).join("")+"])("+Object.keys(r.env.abbreviations).map(function(m){return m.substr(1);}).sort(function(m,p){return p.length-m.length;}).map(Ii).join("|")+")($|["+Rn.split("").map(Ii).join("")+"])",r.env.abbrRegExp=new RegExp(h,"g")),d=r.env.abbrRegExp,t=0,s=f.length;t<s;t++)if(f[t].type==="inline"){for(i=f[t].children,e=i.length-1;e>=0;e--)if(n=i[e],n.type==="text"){for(l=0,o=n.content,d.lastIndex=0,c=n.level,a=[];u=d.exec(o);)d.lastIndex>l&&a.push({type:"text",content:o.slice(l,u.index+u[1].length),level:c}),a.push({type:"abbr_open",title:r.env.abbreviations[":"+u[2]],level:c++}),a.push({type:"text",content:u[2],level:c}),a.push({type:"abbr_close",level:--c}),l=d.lastIndex-u[3].length;a.length&&(l<o.length&&a.push({type:"text",content:o.slice(l),level:c}),f[t].children=i=[].concat(i.slice(0,e),a,i.slice(e+1)));}}}}var lo=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,co=/\((c|tm|r|p)\)/ig,ho={c:"©",r:"®",p:"§",tm:"™"};function uo(r){return r.indexOf("(")<0?r:r.replace(co,function(e,t){return ho[t.toLowerCase()];});}function fo(r){var e,t,s,i,n;if(r.options.typographer){for(n=r.tokens.length-1;n>=0;n--)if(r.tokens[n].type==="inline")for(i=r.tokens[n].children,e=i.length-1;e>=0;e--)t=i[e],t.type==="text"&&(s=t.content,s=uo(s),lo.test(s)&&(s=s.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/mg,"$1—$2").replace(/(^|\s)--(\s|$)/mg,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/mg,"$1–$2")),t.content=s);}}var po=/['"]/,Mn=/['"]/g,mo=/[-\s()\[\]]/,In="’";function kn(r,e){return e<0||e>=r.length?!1:!mo.test(r[e]);}function kt(r,e,t){return r.substr(0,e)+t+r.substr(e+1);}function go(r){var e,t,s,i,n,o,a,l,c,d,u,h,f,m,p,g,E;if(r.options.typographer){for(E=[],p=r.tokens.length-1;p>=0;p--)if(r.tokens[p].type==="inline"){for(g=r.tokens[p].children,E.length=0,e=0;e<g.length;e++)if(t=g[e],!(t.type!=="text"||po.test(t.text))){for(a=g[e].level,f=E.length-1;f>=0&&!(E[f].level<=a);f--);E.length=f+1,s=t.content,n=0,o=s.length;e:for(;n<o&&(Mn.lastIndex=n,i=Mn.exec(s),!!i);){if(l=!kn(s,i.index-1),n=i.index+1,m=i[0]==="'",c=!kn(s,n),!c&&!l){m&&(t.content=kt(t.content,i.index,In));continue;}if(u=!c,h=!l,h){for(f=E.length-1;f>=0&&(d=E[f],!(E[f].level<a));f--)if(d.single===m&&E[f].level===a){d=E[f],m?(g[d.token].content=kt(g[d.token].content,d.pos,r.options.quotes[2]),t.content=kt(t.content,i.index,r.options.quotes[3])):(g[d.token].content=kt(g[d.token].content,d.pos,r.options.quotes[0]),t.content=kt(t.content,i.index,r.options.quotes[1])),E.length=f;continue e;}}u?E.push({token:e,pos:i.index,single:m,level:a}):h&&m&&(t.content=kt(t.content,i.index,In));}}}}}var ki=[["block",eo],["abbr",so],["references",no],["inline",ro],["footnote_tail",oo],["abbr2",ao],["replacements",fo],["smartquotes",go]];function Er(){this.options={},this.ruler=new _e();for(var r=0;r<ki.length;r++)this.ruler.push(ki[r][0],ki[r][1]);}Er.prototype.process=function(r){var e,t,s;for(s=this.ruler.getRules(""),e=0,t=s.length;e<t;e++)s[e](r);};function Mt(r,e,t,s,i){var n,o,a,l,c,d,u;for(this.src=r,this.parser=e,this.options=t,this.env=s,this.tokens=i,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",o=this.src,d=0,u=!1,a=l=d=0,c=o.length;l<c;l++){if(n=o.charCodeAt(l),!u)if(n===32){d++;continue;}else u=!0;(n===10||l===c-1)&&(n!==10&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(d),u=!1,d=0,a=l+1);}this.bMarks.push(o.length),this.eMarks.push(o.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1;}Mt.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e];};Mt.prototype.skipEmptyLines=function(e){for(var t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e;};Mt.prototype.skipSpaces=function(e){for(var t=this.src.length;e<t&&this.src.charCodeAt(e)===32;e++);return e;};Mt.prototype.skipChars=function(e,t){for(var s=this.src.length;e<s&&this.src.charCodeAt(e)===t;e++);return e;};Mt.prototype.skipCharsBack=function(e,t,s){if(e<=s)return e;for(;e>s;)if(t!==this.src.charCodeAt(--e))return e+1;return e;};Mt.prototype.getLines=function(e,t,s,i){var n,o,a,l,c,d=e;if(e>=t)return"";if(d+1===t)return o=this.bMarks[d]+Math.min(this.tShift[d],s),a=i?this.eMarks[d]+1:this.eMarks[d],this.src.slice(o,a);for(l=new Array(t-e),n=0;d<t;d++,n++)c=this.tShift[d],c>s&&(c=s),c<0&&(c=0),o=this.bMarks[d]+c,d+1<t||i?a=this.eMarks[d]+1:a=this.eMarks[d],l[n]=this.src.slice(o,a);return l.join("");};function yo(r,e,t){var s,i;if(r.tShift[e]-r.blkIndent<4)return!1;for(i=s=e+1;s<t;){if(r.isEmpty(s)){s++;continue;}if(r.tShift[s]-r.blkIndent>=4){s++,i=s;continue;}break;}return r.line=s,r.tokens.push({type:"code",content:r.getLines(e,i,4+r.blkIndent,!0),block:!0,lines:[e,r.line],level:r.level}),!0;}function bo(r,e,t,s){var i,n,o,a,l,c=!1,d=r.bMarks[e]+r.tShift[e],u=r.eMarks[e];if(d+3>u||(i=r.src.charCodeAt(d),i!==126&&i!==96)||(l=d,d=r.skipChars(d,i),n=d-l,n<3)||(o=r.src.slice(d,u).trim(),o.indexOf("`")>=0))return!1;if(s)return!0;for(a=e;a++,!(a>=t||(d=l=r.bMarks[a]+r.tShift[a],u=r.eMarks[a],d<u&&r.tShift[a]<r.blkIndent));)if(r.src.charCodeAt(d)===i&&!(r.tShift[a]-r.blkIndent>=4)&&(d=r.skipChars(d,i),!(d-l<n)&&(d=r.skipSpaces(d),!(d<u)))){c=!0;break;}return n=r.tShift[e],r.line=a+(c?1:0),r.tokens.push({type:"fence",params:o,content:r.getLines(e+1,a,n,!0),lines:[e,r.line],level:r.level}),!0;}function vo(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p=r.bMarks[e]+r.tShift[e],g=r.eMarks[e];if(p>g||r.src.charCodeAt(p++)!==62||r.level>=r.options.maxNesting)return!1;if(s)return!0;for(r.src.charCodeAt(p)===32&&p++,l=r.blkIndent,r.blkIndent=0,a=[r.bMarks[e]],r.bMarks[e]=p,p=p<g?r.skipSpaces(p):p,n=p>=g,o=[r.tShift[e]],r.tShift[e]=p-r.bMarks[e],u=r.parser.ruler.getRules("blockquote"),i=e+1;i<t&&(p=r.bMarks[i]+r.tShift[i],g=r.eMarks[i],!(p>=g));i++){if(r.src.charCodeAt(p++)===62){r.src.charCodeAt(p)===32&&p++,a.push(r.bMarks[i]),r.bMarks[i]=p,p=p<g?r.skipSpaces(p):p,n=p>=g,o.push(r.tShift[i]),r.tShift[i]=p-r.bMarks[i];continue;}if(n)break;for(m=!1,h=0,f=u.length;h<f;h++)if(u[h](r,i,t,!0)){m=!0;break;}if(m)break;a.push(r.bMarks[i]),o.push(r.tShift[i]),r.tShift[i]=-1337;}for(c=r.parentType,r.parentType="blockquote",r.tokens.push({type:"blockquote_open",lines:d=[e,0],level:r.level++}),r.parser.tokenize(r,e,i),r.tokens.push({type:"blockquote_close",level:--r.level}),r.parentType=c,d[1]=r.line,h=0;h<o.length;h++)r.bMarks[h+e]=a[h],r.tShift[h+e]=o[h];return r.blkIndent=l,!0;}function _o(r,e,t,s){var i,n,o,a=r.bMarks[e],l=r.eMarks[e];if(a+=r.tShift[e],a>l||(i=r.src.charCodeAt(a++),i!==42&&i!==45&&i!==95))return!1;for(n=1;a<l;){if(o=r.src.charCodeAt(a++),o!==i&&o!==32)return!1;o===i&&n++;}return n<3?!1:(s||(r.line=e+1,r.tokens.push({type:"hr",lines:[e,r.line],level:r.level})),!0);}function Ln(r,e){var t,s,i;return s=r.bMarks[e]+r.tShift[e],i=r.eMarks[e],s>=i||(t=r.src.charCodeAt(s++),t!==42&&t!==45&&t!==43)||s<i&&r.src.charCodeAt(s)!==32?-1:s;}function On(r,e){var t,s=r.bMarks[e]+r.tShift[e],i=r.eMarks[e];if(s+1>=i||(t=r.src.charCodeAt(s++),t<48||t>57))return-1;for(;;){if(s>=i)return-1;if(t=r.src.charCodeAt(s++),!(t>=48&&t<=57)){if(t===41||t===46)break;return-1;}}return s<i&&r.src.charCodeAt(s)!==32?-1:s;}function Eo(r,e){var t,s,i=r.level+2;for(t=e+2,s=r.tokens.length-2;t<s;t++)r.tokens[t].level===i&&r.tokens[t].type==="paragraph_open"&&(r.tokens[t+2].tight=!0,r.tokens[t].tight=!0,t+=2);}function So(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p,g,E,I,P,D,ne,st=!0,it,me,An,Mi;if((u=On(r,e))>=0)g=!0;else if((u=Ln(r,e))>=0)g=!1;else return!1;if(r.level>=r.options.maxNesting)return!1;if(p=r.src.charCodeAt(u-1),s)return!0;for(I=r.tokens.length,g?(d=r.bMarks[e]+r.tShift[e],m=Number(r.src.substr(d,u-d-1)),r.tokens.push({type:"ordered_list_open",order:m,lines:D=[e,0],level:r.level++})):r.tokens.push({type:"bullet_list_open",lines:D=[e,0],level:r.level++}),i=e,P=!1,it=r.parser.ruler.getRules("list");i<t&&(E=r.skipSpaces(u),h=r.eMarks[i],E>=h?f=1:f=E-u,f>4&&(f=1),f<1&&(f=1),n=u-r.bMarks[i]+f,r.tokens.push({type:"list_item_open",lines:ne=[e,0],level:r.level++}),a=r.blkIndent,l=r.tight,o=r.tShift[e],c=r.parentType,r.tShift[e]=E-r.bMarks[e],r.blkIndent=n,r.tight=!0,r.parentType="list",r.parser.tokenize(r,e,t,!0),(!r.tight||P)&&(st=!1),P=r.line-e>1&&r.isEmpty(r.line-1),r.blkIndent=a,r.tShift[e]=o,r.tight=l,r.parentType=c,r.tokens.push({type:"list_item_close",level:--r.level}),i=e=r.line,ne[1]=i,E=r.bMarks[e],!(i>=t||r.isEmpty(i)||r.tShift[i]<r.blkIndent));){for(Mi=!1,me=0,An=it.length;me<An;me++)if(it[me](r,i,t,!0)){Mi=!0;break;}if(Mi)break;if(g){if(u=On(r,i),u<0)break;}else if(u=Ln(r,i),u<0)break;if(p!==r.src.charCodeAt(u-1))break;}return r.tokens.push({type:g?"ordered_list_close":"bullet_list_close",level:--r.level}),D[1]=i,r.line=i,st&&Eo(r,I),!0;}function xo(r,e,t,s){var i,n,o,a,l,c=r.bMarks[e]+r.tShift[e],d=r.eMarks[e];if(c+4>d||r.src.charCodeAt(c)!==91||r.src.charCodeAt(c+1)!==94||r.level>=r.options.maxNesting)return!1;for(a=c+2;a<d;a++){if(r.src.charCodeAt(a)===32)return!1;if(r.src.charCodeAt(a)===93)break;}return a===c+2||a+1>=d||r.src.charCodeAt(++a)!==58?!1:(s||(a++,r.env.footnotes||(r.env.footnotes={}),r.env.footnotes.refs||(r.env.footnotes.refs={}),l=r.src.slice(c+2,a-2),r.env.footnotes.refs[":"+l]=-1,r.tokens.push({type:"footnote_reference_open",label:l,level:r.level++}),i=r.bMarks[e],n=r.tShift[e],o=r.parentType,r.tShift[e]=r.skipSpaces(a)-a,r.bMarks[e]=a,r.blkIndent+=4,r.parentType="footnote",r.tShift[e]<r.blkIndent&&(r.tShift[e]+=r.blkIndent,r.bMarks[e]-=r.blkIndent),r.parser.tokenize(r,e,t,!0),r.parentType=o,r.blkIndent-=4,r.tShift[e]=n,r.bMarks[e]=i,r.tokens.push({type:"footnote_reference_close",level:--r.level})),!0);}function Ao(r,e,t,s){var i,n,o,a=r.bMarks[e]+r.tShift[e],l=r.eMarks[e];if(a>=l||(i=r.src.charCodeAt(a),i!==35||a>=l))return!1;for(n=1,i=r.src.charCodeAt(++a);i===35&&a<l&&n<=6;)n++,i=r.src.charCodeAt(++a);return n>6||a<l&&i!==32?!1:(s||(l=r.skipCharsBack(l,32,a),o=r.skipCharsBack(l,35,a),o>a&&r.src.charCodeAt(o-1)===32&&(l=o),r.line=e+1,r.tokens.push({type:"heading_open",hLevel:n,lines:[e,r.line],level:r.level}),a<l&&r.tokens.push({type:"inline",content:r.src.slice(a,l).trim(),level:r.level+1,lines:[e,r.line],children:[]}),r.tokens.push({type:"heading_close",hLevel:n,level:r.level})),!0);}function Co(r,e,t){var s,i,n,o=e+1;return o>=t||r.tShift[o]<r.blkIndent||r.tShift[o]-r.blkIndent>3||(i=r.bMarks[o]+r.tShift[o],n=r.eMarks[o],i>=n)||(s=r.src.charCodeAt(i),s!==45&&s!==61)||(i=r.skipChars(i,s),i=r.skipSpaces(i),i<n)?!1:(i=r.bMarks[e]+r.tShift[e],r.line=o+1,r.tokens.push({type:"heading_open",hLevel:s===61?1:2,lines:[e,r.line],level:r.level}),r.tokens.push({type:"inline",content:r.src.slice(i,r.eMarks[e]).trim(),level:r.level+1,lines:[e,r.line-1],children:[]}),r.tokens.push({type:"heading_close",hLevel:s===61?1:2,level:r.level}),!0);}var Sr={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach(function(r){Sr[r]=!0;});var wo=/^<([a-zA-Z]{1,15})[\s\/>]/,To=/^<\/([a-zA-Z]{1,15})[\s>]/;function Ro(r){var e=r|32;return e>=97&&e<=122;}function Mo(r,e,t,s){var i,n,o,a=r.bMarks[e],l=r.eMarks[e],c=r.tShift[e];if(a+=c,!r.options.html||c>3||a+2>=l||r.src.charCodeAt(a)!==60)return!1;if(i=r.src.charCodeAt(a+1),i===33||i===63){if(s)return!0;}else if(i===47||Ro(i)){if(i===47){if(n=r.src.slice(a,l).match(To),!n)return!1;}else if(n=r.src.slice(a,l).match(wo),!n)return!1;if(Sr[n[1].toLowerCase()]!==!0)return!1;if(s)return!0;}else return!1;for(o=e+1;o<r.lineMax&&!r.isEmpty(o);)o++;return r.line=o,r.tokens.push({type:"htmlblock",level:r.level,lines:[e,r.line],content:r.getLines(e,o,0,!0)}),!0;}function Li(r,e){var t=r.bMarks[e]+r.blkIndent,s=r.eMarks[e];return r.src.substr(t,s-t);}function Io(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m;if(e+2>t||(l=e+1,r.tShift[l]<r.blkIndent)||(o=r.bMarks[l]+r.tShift[l],o>=r.eMarks[l])||(i=r.src.charCodeAt(o),i!==124&&i!==45&&i!==58)||(n=Li(r,e+1),!/^[-:| ]+$/.test(n))||(c=n.split("|"),c<=2))return!1;for(u=[],a=0;a<c.length;a++){if(h=c[a].trim(),!h){if(a===0||a===c.length-1)continue;return!1;}if(!/^:?-+:?$/.test(h))return!1;h.charCodeAt(h.length-1)===58?u.push(h.charCodeAt(0)===58?"center":"right"):h.charCodeAt(0)===58?u.push("left"):u.push("");}if(n=Li(r,e).trim(),n.indexOf("|")===-1||(c=n.replace(/^\||\|$/g,"").split("|"),u.length!==c.length))return!1;if(s)return!0;for(r.tokens.push({type:"table_open",lines:f=[e,0],level:r.level++}),r.tokens.push({type:"thead_open",lines:[e,e+1],level:r.level++}),r.tokens.push({type:"tr_open",lines:[e,e+1],level:r.level++}),a=0;a<c.length;a++)r.tokens.push({type:"th_open",align:u[a],lines:[e,e+1],level:r.level++}),r.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:r.level,children:[]}),r.tokens.push({type:"th_close",level:--r.level});for(r.tokens.push({type:"tr_close",level:--r.level}),r.tokens.push({type:"thead_close",level:--r.level}),r.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:r.level++}),l=e+2;l<t&&!(r.tShift[l]<r.blkIndent||(n=Li(r,l).trim(),n.indexOf("|")===-1));l++){for(c=n.replace(/^\||\|$/g,"").split("|"),r.tokens.push({type:"tr_open",level:r.level++}),a=0;a<c.length;a++)r.tokens.push({type:"td_open",align:u[a],level:r.level++}),d=c[a].substring(c[a].charCodeAt(0)===124?1:0,c[a].charCodeAt(c[a].length-1)===124?c[a].length-1:c[a].length).trim(),r.tokens.push({type:"inline",content:d,level:r.level,children:[]}),r.tokens.push({type:"td_close",level:--r.level});r.tokens.push({type:"tr_close",level:--r.level});}return r.tokens.push({type:"tbody_close",level:--r.level}),r.tokens.push({type:"table_close",level:--r.level}),f[1]=m[1]=l,r.line=l,!0;}function Ps(r,e){var t,s,i=r.bMarks[e]+r.tShift[e],n=r.eMarks[e];return i>=n||(s=r.src.charCodeAt(i++),s!==126&&s!==58)||(t=r.skipSpaces(i),i===t)||t>=n?-1:t;}function ko(r,e){var t,s,i=r.level+2;for(t=e+2,s=r.tokens.length-2;t<s;t++)r.tokens[t].level===i&&r.tokens[t].type==="paragraph_open"&&(r.tokens[t+2].tight=!0,r.tokens[t].tight=!0,t+=2);}function Lo(r,e,t,s){var i,n,o,a,l,c,d,u,h,f,m,p,g,E;if(s)return r.ddIndent<0?!1:Ps(r,e)>=0;if(d=e+1,r.isEmpty(d)&&++d>t||r.tShift[d]<r.blkIndent||(i=Ps(r,d),i<0)||r.level>=r.options.maxNesting)return!1;c=r.tokens.length,r.tokens.push({type:"dl_open",lines:l=[e,0],level:r.level++}),o=e,n=d;e:for(;;){for(E=!0,g=!1,r.tokens.push({type:"dt_open",lines:[o,o],level:r.level++}),r.tokens.push({type:"inline",content:r.getLines(o,o+1,r.blkIndent,!1).trim(),level:r.level+1,lines:[o,o],children:[]}),r.tokens.push({type:"dt_close",level:--r.level});;){if(r.tokens.push({type:"dd_open",lines:a=[d,0],level:r.level++}),p=r.tight,h=r.ddIndent,u=r.blkIndent,m=r.tShift[n],f=r.parentType,r.blkIndent=r.ddIndent=r.tShift[n]+2,r.tShift[n]=i-r.bMarks[n],r.tight=!0,r.parentType="deflist",r.parser.tokenize(r,n,t,!0),(!r.tight||g)&&(E=!1),g=r.line-n>1&&r.isEmpty(r.line-1),r.tShift[n]=m,r.tight=p,r.parentType=f,r.blkIndent=u,r.ddIndent=h,r.tokens.push({type:"dd_close",level:--r.level}),a[1]=d=r.line,d>=t||r.tShift[d]<r.blkIndent)break e;if(i=Ps(r,d),i<0)break;n=d;}if(d>=t||(o=d,r.isEmpty(o))||r.tShift[o]<r.blkIndent||(n=o+1,n>=t)||(r.isEmpty(n)&&n++,n>=t)||r.tShift[n]<r.blkIndent||(i=Ps(r,n),i<0))break;}return r.tokens.push({type:"dl_close",level:--r.level}),l[1]=d,r.line=d,E&&ko(r,c),!0;}function Oo(r,e){var t,s,i,n,o,a=e+1,l;if(t=r.lineMax,a<t&&!r.isEmpty(a)){for(l=r.parser.ruler.getRules("paragraph");a<t&&!r.isEmpty(a);a++)if(!(r.tShift[a]-r.blkIndent>3)){for(i=!1,n=0,o=l.length;n<o;n++)if(l[n](r,a,t,!0)){i=!0;break;}if(i)break;}}return s=r.getLines(e,a,r.blkIndent,!1).trim(),r.line=a,s.length&&(r.tokens.push({type:"paragraph_open",tight:!1,lines:[e,r.line],level:r.level}),r.tokens.push({type:"inline",content:s,level:r.level+1,lines:[e,r.line],children:[]}),r.tokens.push({type:"paragraph_close",tight:!1,level:r.level})),!0;}var Ds=[["code",yo],["fences",bo,["paragraph","blockquote","list"]],["blockquote",vo,["paragraph","blockquote","list"]],["hr",_o,["paragraph","blockquote","list"]],["list",So,["paragraph","blockquote"]],["footnote",xo,["paragraph"]],["heading",Ao,["paragraph","blockquote"]],["lheading",Co],["htmlblock",Mo,["paragraph","blockquote"]],["table",Io,["paragraph"]],["deflist",Lo,["paragraph"]],["paragraph",Oo]];function an(){this.ruler=new _e();for(var r=0;r<Ds.length;r++)this.ruler.push(Ds[r][0],Ds[r][1],{alt:(Ds[r][2]||[]).slice()});}an.prototype.tokenize=function(r,e,t){for(var s=this.ruler.getRules(""),i=s.length,n=e,o=!1,a,l;n<t&&(r.line=n=r.skipEmptyLines(n),!(n>=t||r.tShift[n]<r.blkIndent));){for(l=0;l<i&&(a=s[l](r,n,t,!1),!a);l++);if(r.tight=!o,r.isEmpty(r.line-1)&&(o=!0),n=r.line,n<t&&r.isEmpty(n)){if(o=!0,n++,n<t&&r.parentType==="list"&&r.isEmpty(n))break;r.line=n;}}};var No=/[\n\t]/g,Po=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Do=/\u00a0/g;an.prototype.parse=function(r,e,t,s){var i,n=0,o=0;if(!r)return[];r=r.replace(Do," "),r=r.replace(Po,"\n"),r.indexOf(" ")>=0&&(r=r.replace(No,function(a,l){var c;return r.charCodeAt(l)===10?(n=l+1,o=0,a):(c=" ".slice((l-n-o)%4),o=l-n+1,c);})),i=new Mt(r,this,e,t,s),this.tokenize(i,i.line,i.lineMax);};function Bo(r){switch(r){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1;}}function Fo(r,e){for(var t=r.pos;t<r.posMax&&!Bo(r.src.charCodeAt(t));)t++;return t===r.pos?!1:(e||(r.pending+=r.src.slice(r.pos,t)),r.pos=t,!0);}function Uo(r,e){var t,s,i=r.pos;if(r.src.charCodeAt(i)!==10)return!1;if(t=r.pending.length-1,s=r.posMax,!e)if(t>=0&&r.pending.charCodeAt(t)===32){if(t>=1&&r.pending.charCodeAt(t-1)===32){for(var n=t-2;n>=0;n--)if(r.pending.charCodeAt(n)!==32){r.pending=r.pending.substring(0,n+1);break;}r.push({type:"hardbreak",level:r.level});}else r.pending=r.pending.slice(0,-1),r.push({type:"softbreak",level:r.level});}else r.push({type:"softbreak",level:r.level});for(i++;i<s&&r.src.charCodeAt(i)===32;)i++;return r.pos=i,!0;}var ln=[];for(var Nn=0;Nn<256;Nn++)ln.push(0);"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(r){ln[r.charCodeAt(0)]=1;});function Ho(r,e){var t,s=r.pos,i=r.posMax;if(r.src.charCodeAt(s)!==92)return!1;if(s++,s<i){if(t=r.src.charCodeAt(s),t<256&&ln[t]!==0)return e||(r.pending+=r.src[s]),r.pos+=2,!0;if(t===10){for(e||r.push({type:"hardbreak",level:r.level}),s++;s<i&&r.src.charCodeAt(s)===32;)s++;return r.pos=s,!0;}}return e||(r.pending+="\\"),r.pos++,!0;}function jo(r,e){var t,s,i,n,o,a=r.pos,l=r.src.charCodeAt(a);if(l!==96)return!1;for(t=a,a++,s=r.posMax;a<s&&r.src.charCodeAt(a)===96;)a++;for(i=r.src.slice(t,a),n=o=a;(n=r.src.indexOf("`",o))!==-1;){for(o=n+1;o<s&&r.src.charCodeAt(o)===96;)o++;if(o-n===i.length)return e||r.push({type:"code",content:r.src.slice(a,n).replace(/[ \n]+/g," ").trim(),block:!1,level:r.level}),r.pos=o,!0;}return e||(r.pending+=i),r.pos+=i.length,!0;}function qo(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==126||e||o+4>=n||r.src.charCodeAt(o+1)!==126||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===126)||l===126||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===126;)s++;if(s>o+3)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===126&&r.src.charCodeAt(r.pos+1)===126&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==126&&a!==126&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"del_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"del_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Vo(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==43||e||o+4>=n||r.src.charCodeAt(o+1)!==43||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===43)||l===43||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===43;)s++;if(s!==o+2)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===43&&r.src.charCodeAt(r.pos+1)===43&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==43&&a!==43&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"ins_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"ins_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Go(r,e){var t,s,i,n=r.posMax,o=r.pos,a,l;if(r.src.charCodeAt(o)!==61||e||o+4>=n||r.src.charCodeAt(o+1)!==61||r.level>=r.options.maxNesting||(a=o>0?r.src.charCodeAt(o-1):-1,l=r.src.charCodeAt(o+2),a===61)||l===61||l===32||l===10)return!1;for(s=o+2;s<n&&r.src.charCodeAt(s)===61;)s++;if(s!==o+2)return r.pos+=s-o,e||(r.pending+=r.src.slice(o,s)),!0;for(r.pos=o+2,i=1;r.pos+1<n;){if(r.src.charCodeAt(r.pos)===61&&r.src.charCodeAt(r.pos+1)===61&&(a=r.src.charCodeAt(r.pos-1),l=r.pos+2<n?r.src.charCodeAt(r.pos+2):-1,l!==61&&a!==61&&(a!==32&&a!==10?i--:l!==32&&l!==10&&i++,i<=0))){t=!0;break;}r.parser.skipToken(r);}return t?(r.posMax=r.pos,r.pos=o+2,e||(r.push({type:"mark_open",level:r.level++}),r.parser.tokenize(r),r.push({type:"mark_close",level:--r.level})),r.pos=r.posMax+2,r.posMax=n,!0):(r.pos=o,!1);}function Pn(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122;}function Dn(r,e){var t=e,s,i,n,o=!0,a=!0,l=r.posMax,c=r.src.charCodeAt(e);for(s=e>0?r.src.charCodeAt(e-1):-1;t<l&&r.src.charCodeAt(t)===c;)t++;return t>=l&&(o=!1),n=t-e,n>=4?o=a=!1:(i=t<l?r.src.charCodeAt(t):-1,(i===32||i===10)&&(o=!1),(s===32||s===10)&&(a=!1),c===95&&(Pn(s)&&(o=!1),Pn(i)&&(a=!1))),{can_open:o,can_close:a,delims:n};}function Ko(r,e){var t,s,i,n,o,a,l,c=r.posMax,d=r.pos,u=r.src.charCodeAt(d);if(u!==95&&u!==42||e)return!1;if(l=Dn(r,d),t=l.delims,!l.can_open)return r.pos+=t,e||(r.pending+=r.src.slice(d,r.pos)),!0;if(r.level>=r.options.maxNesting)return!1;for(r.pos=d+t,a=[t];r.pos<c;){if(r.src.charCodeAt(r.pos)===u){if(l=Dn(r,r.pos),s=l.delims,l.can_close){for(n=a.pop(),o=s;n!==o;){if(o<n){a.push(n-o);break;}if(o-=n,a.length===0)break;r.pos+=n,n=a.pop();}if(a.length===0){t=n,i=!0;break;}r.pos+=s;continue;}l.can_open&&a.push(s),r.pos+=s;continue;}r.parser.skipToken(r);}return i?(r.posMax=r.pos,r.pos=d+t,e||((t===2||t===3)&&r.push({type:"strong_open",level:r.level++}),(t===1||t===3)&&r.push({type:"em_open",level:r.level++}),r.parser.tokenize(r),(t===1||t===3)&&r.push({type:"em_close",level:--r.level}),(t===2||t===3)&&r.push({type:"strong_close",level:--r.level})),r.pos=r.posMax+t,r.posMax=c,!0):(r.pos=d,!1);}var zo=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Jo(r,e){var t,s,i=r.posMax,n=r.pos;if(r.src.charCodeAt(n)!==126||e||n+2>=i||r.level>=r.options.maxNesting)return!1;for(r.pos=n+1;r.pos<i;){if(r.src.charCodeAt(r.pos)===126){t=!0;break;}r.parser.skipToken(r);}return!t||n+1===r.pos||(s=r.src.slice(n+1,r.pos),s.match(/(^|[^\\])(\\\\)*\s/))?(r.pos=n,!1):(r.posMax=r.pos,r.pos=n+1,e||r.push({type:"sub",level:r.level,content:s.replace(zo,"$1")}),r.pos=r.posMax+1,r.posMax=i,!0);}var $o=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Wo(r,e){var t,s,i=r.posMax,n=r.pos;if(r.src.charCodeAt(n)!==94||e||n+2>=i||r.level>=r.options.maxNesting)return!1;for(r.pos=n+1;r.pos<i;){if(r.src.charCodeAt(r.pos)===94){t=!0;break;}r.parser.skipToken(r);}return!t||n+1===r.pos||(s=r.src.slice(n+1,r.pos),s.match(/(^|[^\\])(\\\\)*\s/))?(r.pos=n,!1):(r.posMax=r.pos,r.pos=n+1,e||r.push({type:"sup",level:r.level,content:s.replace($o,"$1")}),r.pos=r.posMax+1,r.posMax=i,!0);}function Xo(r,e){var t,s,i,n,o,a,l,c,d=!1,u=r.pos,h=r.posMax,f=r.pos,m=r.src.charCodeAt(f);if(m===33&&(d=!0,m=r.src.charCodeAt(++f)),m!==91||r.level>=r.options.maxNesting||(t=f+1,s=Ss(r,f),s<0))return!1;if(a=s+1,a<h&&r.src.charCodeAt(a)===40){for(a++;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a>=h)return!1;for(f=a,br(r,a)?(n=r.linkContent,a=r.pos):n="",f=a;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a<h&&f!==a&&vr(r,a))for(o=r.linkContent,a=r.pos;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);else o="";if(a>=h||r.src.charCodeAt(a)!==41)return r.pos=u,!1;a++;}else{if(r.linkLevel>0)return!1;for(;a<h&&(c=r.src.charCodeAt(a),!(c!==32&&c!==10));a++);if(a<h&&r.src.charCodeAt(a)===91&&(f=a+1,a=Ss(r,a),a>=0?i=r.src.slice(f,a++):a=f-1),i||(_typeof(i)>"u"&&(a=s+1),i=r.src.slice(t,s)),l=r.env.references[_r(i)],!l)return r.pos=u,!1;n=l.href,o=l.title;}return e||(r.pos=t,r.posMax=s,d?r.push({type:"image",src:n,title:o,alt:r.src.substr(t,s-t),level:r.level}):(r.push({type:"link_open",href:n,title:o,level:r.level++}),r.linkLevel++,r.parser.tokenize(r),r.linkLevel--,r.push({type:"link_close",level:--r.level}))),r.pos=a,r.posMax=h,!0;}function Yo(r,e){var t,s,i,n,o=r.posMax,a=r.pos;return a+2>=o||r.src.charCodeAt(a)!==94||r.src.charCodeAt(a+1)!==91||r.level>=r.options.maxNesting||(t=a+2,s=Ss(r,a+1),s<0)?!1:(e||(r.env.footnotes||(r.env.footnotes={}),r.env.footnotes.list||(r.env.footnotes.list=[]),i=r.env.footnotes.list.length,r.pos=t,r.posMax=s,r.push({type:"footnote_ref",id:i,level:r.level}),r.linkLevel++,n=r.tokens.length,r.parser.tokenize(r),r.env.footnotes.list[i]={tokens:r.tokens.splice(n)},r.linkLevel--),r.pos=s+1,r.posMax=o,!0);}function Zo(r,e){var t,s,i,n,o=r.posMax,a=r.pos;if(a+3>o||!r.env.footnotes||!r.env.footnotes.refs||r.src.charCodeAt(a)!==91||r.src.charCodeAt(a+1)!==94||r.level>=r.options.maxNesting)return!1;for(s=a+2;s<o;s++){if(r.src.charCodeAt(s)===32||r.src.charCodeAt(s)===10)return!1;if(r.src.charCodeAt(s)===93)break;}return s===a+2||s>=o||(s++,t=r.src.slice(a+2,s-1),_typeof(r.env.footnotes.refs[":"+t])>"u")?!1:(e||(r.env.footnotes.list||(r.env.footnotes.list=[]),r.env.footnotes.refs[":"+t]<0?(i=r.env.footnotes.list.length,r.env.footnotes.list[i]={label:t,count:0},r.env.footnotes.refs[":"+t]=i):i=r.env.footnotes.refs[":"+t],n=r.env.footnotes.list[i].count,r.env.footnotes.list[i].count++,r.push({type:"footnote_ref",id:i,subId:n,level:r.level})),r.pos=s,r.posMax=o,!0);}var Qo=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"],ea=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,ta=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function sa(r,e){var t,s,i,n,o,a=r.pos;return r.src.charCodeAt(a)!==60||(t=r.src.slice(a),t.indexOf(">")<0)?!1:(s=t.match(ta),s?Qo.indexOf(s[1].toLowerCase())<0||(n=s[0].slice(1,-1),o=Bi(n),!r.parser.validateLink(n))?!1:(e||(r.push({type:"link_open",href:o,level:r.level}),r.push({type:"text",content:n,level:r.level+1}),r.push({type:"link_close",level:r.level})),r.pos+=s[0].length,!0):(i=t.match(ea),i?(n=i[0].slice(1,-1),o=Bi("mailto:"+n),r.parser.validateLink(o)?(e||(r.push({type:"link_open",href:o,level:r.level}),r.push({type:"text",content:n,level:r.level+1}),r.push({type:"link_close",level:r.level})),r.pos+=i[0].length,!0):!1):!1));}function Si(r,e){return r=r.source,e=e||"",function t(s,i){return s?(i=i.source||i,r=r.replace(s,i),t):new RegExp(r,e);};}var ia=/[a-zA-Z_:][a-zA-Z0-9:._-]*/,na=/[^"'=<>`\x00-\x20]+/,ra=/'[^']*'/,oa=/"[^"]*"/,aa=Si(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",na)("single_quoted",ra)("double_quoted",oa)(),la=Si(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",ia)("attr_value",aa)(),ca=Si(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",la)(),da=/<\/[A-Za-z][A-Za-z0-9]*\s*>/,ha=/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/,ua=/<[?].*?[?]>/,fa=/<![A-Z]+\s+[^>]*>/,pa=/<!\[CDATA\[[\s\S]*?\]\]>/,ma=Si(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",ca)("close_tag",da)("comment",ha)("processing",ua)("declaration",fa)("cdata",pa)();function ga(r){var e=r|32;return e>=97&&e<=122;}function ya(r,e){var t,s,i,n=r.pos;return!r.options.html||(i=r.posMax,r.src.charCodeAt(n)!==60||n+2>=i)||(t=r.src.charCodeAt(n+1),t!==33&&t!==63&&t!==47&&!ga(t))||(s=r.src.slice(n).match(ma),!s)?!1:(e||r.push({type:"htmltag",content:r.src.slice(n,n+s[0].length),level:r.level}),r.pos+=s[0].length,!0);}var ba=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,va=/^&([a-z][a-z0-9]{1,31});/i;function _a(r,e){var t,s,i,n=r.pos,o=r.posMax;if(r.src.charCodeAt(n)!==38)return!1;if(n+1<o){if(t=r.src.charCodeAt(n+1),t===35){if(i=r.src.slice(n).match(ba),i)return e||(s=i[1][0].toLowerCase()==="x"?parseInt(i[1].slice(1),16):parseInt(i[1],10),r.pending+=gr(s)?Di(s):Di(65533)),r.pos+=i[0].length,!0;}else if(i=r.src.slice(n).match(va),i){var a=pr(i[1]);if(i[1]!==a)return e||(r.pending+=a),r.pos+=i[0].length,!0;}}return e||(r.pending+="&"),r.pos++,!0;}var Oi=[["text",Fo],["newline",Uo],["escape",Ho],["backticks",jo],["del",qo],["ins",Vo],["mark",Go],["emphasis",Ko],["sub",Jo],["sup",Wo],["links",Xo],["footnote_inline",Yo],["footnote_ref",Zo],["autolink",sa],["htmltag",ya],["entity",_a]];function xi(){this.ruler=new _e();for(var r=0;r<Oi.length;r++)this.ruler.push(Oi[r][0],Oi[r][1]);this.validateLink=Ea;}xi.prototype.skipToken=function(r){var e=this.ruler.getRules(""),t=e.length,s=r.pos,i,n;if((n=r.cacheGet(s))>0){r.pos=n;return;}for(i=0;i<t;i++)if(e[i](r,!0)){r.cacheSet(s,r.pos);return;}r.pos++,r.cacheSet(s,r.pos);};xi.prototype.tokenize=function(r){for(var e=this.ruler.getRules(""),t=e.length,s=r.posMax,i,n;r.pos<s;){for(n=0;n<t&&(i=e[n](r,!1),!i);n++);if(i){if(r.pos>=s)break;continue;}r.pending+=r.src[r.pos++];}r.pending&&r.pushPending();};xi.prototype.parse=function(r,e,t,s){var i=new Rt(r,this,e,t,s);this.tokenize(i);};function Ea(r){var e=["vbscript","javascript","file","data"],t=r.trim().toLowerCase();return t=At(t),!(t.indexOf(":")!==-1&&e.indexOf(t.split(":")[0])!==-1);}var Sa={options:{html:!1,// Enable HTML tags in source
30
30
  xhtmlOut:!1,// Use '/' to close single tags (<br />)
31
31
  breaks:!1,// Convert '\n' in paragraphs into <br>
32
32
  langPrefix:"language-",// CSS language prefix for fenced blocks
@@ -78,14 +78,14 @@ typographer:!0// Enable smartypants and other sweet transforms
78
78
  });}else return new Fe(yt.DEFAULT_PROPERTIES);}},{key:"createNew",value:function createNew(e){var t=yt.instantiate(e);return yt.addPlugins(t,e),t.inline.validateLink=function(){return!0;},t;}}]);}();yt.DEFAULT_PROPERTIES={breaks:!0,linkTarget:"_blank"// set target to open in a new tab
79
79
  };var xs=yt;var wa=/*#__PURE__*/function(){function wa(e){_classCallCheck(this,wa);this.storageKey="deep-chat-storage",this.maxMessages=1e3,_typeof(e)=="object"&&(e.key&&(this.storageKey=e.key),e.maxMessages&&(this.maxMessages=e.maxMessages),e.clear=this.clear.bind(this));}return _createClass(wa,[{key:"get",value:function get(){var e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[];}},{key:"addMessages",value:function addMessages(e){var t=e.length-this.maxMessages;t<0&&(t=0);var s=e.slice(t,e.length);localStorage.setItem(this.storageKey,JSON.stringify(s));}},{key:"clear",value:function clear(){localStorage.removeItem(this.storageKey);}}]);}();var he=/*#__PURE__*/function(){function he(){_classCallCheck(this,he);}return _createClass(he,null,[{key:"applyCustomStylesToElements",value:function applyCustomStylesToElements(e,t,s){if(s&&(Object.assign(e.outerContainer.style,s.outerContainer),Object.assign(e.innerContainer.style,s.innerContainer),Object.assign(e.bubbleElement.style,s.bubble),t)){var i=e.bubbleElement.children[0],n=i.tagName.toLocaleLowerCase()!=="a"?i:i.children[0];Object.assign(n.style,s.media);}}},{key:"applySideStyles",value:function applySideStyles(e,t,s,i){i&&(he.applyCustomStylesToElements(e,s,i.shared),t===v.USER_ROLE?he.applyCustomStylesToElements(e,s,i.user):(he.applyCustomStylesToElements(e,s,i.ai),he.applyCustomStylesToElements(e,s,i[t])));}},{key:"isElementsStyles",value:function isElementsStyles(e){return!!(e.outerContainer||e.innerContainer||e.bubble||e.media);}// prettier-ignore
80
80
  },{key:"applyCustomStyles",value:function applyCustomStyles(e,t,s,i,n){var o;n&&e["default"]!==n?he.isElementsStyles(n)?(he.applyCustomStylesToElements(t,i,(o=e["default"])==null?void 0:o.shared),he.applyCustomStylesToElements(t,i,n)):(he.applySideStyles(t,s,i,e["default"]),he.applySideStyles(t,s,i,n)):he.applySideStyles(t,s,i,e["default"]);}// prettier-ignore
81
- },{key:"extractParticularSharedStyles",value:function extractParticularSharedStyles(e,t){if(!(t!=null&&t.shared))return;var s=t.shared,i={outerContainer:{},innerContainer:{},bubble:{},media:{}};return e.forEach(function(n){var o,a,l,c;i.outerContainer[n]=((o=s.outerContainer)==null?void 0:o[n])||"",i.innerContainer[n]=((a=s.innerContainer)==null?void 0:a[n])||"",i.bubble[n]=((l=s.bubble)==null?void 0:l[n])||"",i.media[n]=((c=s.media)==null?void 0:c[n])||"";}),i;}}]);}();var Ct=/*#__PURE__*/function(){function Ct(){_classCallCheck(this,Ct);}return _createClass(Ct,null,[{key:"onMessage",value:function onMessage(e,t,s){var n;var i=JSON.parse(JSON.stringify({message:t,isHistory:s,isInitial:s}));ee.reAddFileRefToObject(t,i.message),(n=e.onMessage)==null||n.call(e,i),e.dispatchEvent(new CustomEvent("message",{detail:i})),le.fireOnNewMessage(e,i);}},{key:"onClearMessages",value:function onClearMessages(e){var t;(t=e.onClearMessages)==null||t.call(e),e.dispatchEvent(new CustomEvent("clear-messages"));}},{key:"onRender",value:function onRender(e){var t;(t=e.onComponentRender)==null||t.call(e,e),e.dispatchEvent(new CustomEvent("render",{detail:e}));}},{key:"onInput",value:function onInput(e,t,s){var n,o;var i=JSON.parse(JSON.stringify({content:t,isUser:s}));t.files&&ee.reAddFileRefToObject({files:(n=t.files)==null?void 0:n.map(function(a){return{ref:a};})},i.content),(o=e.onInput)==null||o.call(e,i),e.dispatchEvent(new CustomEvent("input",{detail:i}));}},{key:"onError",value:function onError(e,t){var s;(s=e.onError)==null||s.call(e,t),e.dispatchEvent(new CustomEvent("error",{detail:t}));}}]);}();var X=/*#__PURE__*/function(){function X(){_classCallCheck(this,X);}return _createClass(X,null,[{key:"generateLoadingRingElement",value:function generateLoadingRingElement(){var e=document.createElement("div");return e.classList.add("loading-history"),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e;}},{key:"apply",value:function apply(e,t,s){Xe.setRing(t.bubbleElement,s==null?void 0:s.bubble),s!=null&&s.bubble&&(s=JSON.parse(JSON.stringify(s)),delete s.bubble),e.applyCustomStyles(t,"history",!1,s);}},{key:"addLoadHistoryMessage",value:function addLoadHistoryMessage(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!0;var o,a,l,c,d,u,h,f;e.bubbleElement.classList.add(X.CLASS);var i=s?X.FULL_VIEW_CLASS:X.SMALL_CLASS;e.outerContainer.classList.add(i);var n=s?(c=(l=(a=(o=t.messageStyles)==null?void 0:o.loading)==null?void 0:a.history)==null?void 0:l.full)==null?void 0:c.styles:(f=(h=(u=(d=t.messageStyles)==null?void 0:d.loading)==null?void 0:u.history)==null?void 0:h.small)==null?void 0:f.styles;X.apply(t,e,n),t.elementRef.prepend(e.outerContainer);}},{key:"createDefaultElements",value:function createDefaultElements(e){var t=e.createMessageElements("",v.AI_ROLE),s=t.bubbleElement,i=X.generateLoadingRingElement();return s.appendChild(i),t;}},{key:"addMessage",value:function addMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!0;var n,o,a,l;var s=(l=(a=(o=(n=e.messageStyles)==null?void 0:n.loading)==null?void 0:o.history)==null?void 0:a.full)==null?void 0:l.html,i=s?Be.createElements(e,s,v.AI_ROLE,!0,!0):X.createDefaultElements(e);return X.addLoadHistoryMessage(i,e,t),v.softRemRoleElements(i.innerContainer,e.avatar,e.name),i;}},{key:"tryChangeViewToSmall",value:function tryChangeViewToSmall(e,t){var s,i,n,o,a,l,c,d;if(t!=null&&t.outerContainer.classList.contains(X.FULL_VIEW_CLASS)){t.outerContainer.classList.replace(X.FULL_VIEW_CLASS,X.SMALL_CLASS);var u=(o=(n=(i=(s=e.messageStyles)==null?void 0:s.loading)==null?void 0:i.history)==null?void 0:n.small)==null?void 0:o.styles;u&&X.apply(e,t,u);var h=(d=(c=(l=(a=e.messageStyles)==null?void 0:a.loading)==null?void 0:l.history)==null?void 0:c.small)==null?void 0:d.html;return h&&(t.bubbleElement.innerHTML=h),!0;}return!1;}},{key:"changeFullViewToSmall",value:function changeFullViewToSmall(e){var t=e.messageElementRefs[e.messageElementRefs.length-1];X.tryChangeViewToSmall(e,t)||X.tryChangeViewToSmall(e,e.messageElementRefs[0]);}}]);}();X.CLASS="loading-history-message",X.FULL_VIEW_CLASS="loading-history-message-full-view",X.SMALL_CLASS="loading-history-message-small";var Ze=X;var gs=/*#__PURE__*/function(){function gs(){_classCallCheck(this,gs);}return _createClass(gs,null,[{key:"setFade",value:function setFade(e,t){e.style.transitionDuration=typeof t=="number"?"".concat(t,"ms"):"".concat(gs.DEFAULT_FADE_MS,"ms");}},{key:"fadeAnimation",value:function(){var _fadeAnimation=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(e,t){var s;return _regenerator().w(function(_context){while(1)switch(_context.n){case 0:e.style.opacity="0";s=typeof t=="number"?t:gs.DEFAULT_FADE_MS;_context.n=1;return new Promise(function(i){setTimeout(function(){return i();},s);});case 1:e.style.opacity="1";case 2:return _context.a(2);}},_callee);}));function fadeAnimation(_x,_x2){return _fadeAnimation.apply(this,arguments);}return fadeAnimation;}()}]);}();gs.DEFAULT_FADE_MS=500;var qs=gs;var Bn="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3csvg%20fill='%23000000'%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20viewBox='0%200%2032%2032'%20xml:space='preserve'%3e%3cpath%20d='M23,30.36H9c-2.404,0-4.36-1.956-4.36-4.36V15c0-2.404,1.956-4.36,4.36-4.36h3.659%20c0.167-1.566,1.415-2.813,2.981-2.981V5.333c-1.131-0.174-2-1.154-2-2.333c0-1.301,1.059-2.36,2.36-2.36%20c1.302,0,2.36,1.059,2.36,2.36c0,1.179-0.869,2.159-2,2.333V7.66c1.566,0.167,2.814,1.415,2.981,2.981H23%20c2.404,0,4.36,1.956,4.36,4.36v11C27.36,28.404,25.404,30.36,23,30.36z%20M9,11.36c-2.007,0-3.64,1.633-3.64,3.64v11%20c0,2.007,1.633,3.64,3.64,3.64h14c2.007,0,3.64-1.633,3.64-3.64V15c0-2.007-1.633-3.64-3.64-3.64H9z%20M13.384,10.64h5.231%20C18.439,9.354,17.334,8.36,16,8.36C14.667,8.36,13.561,9.354,13.384,10.64z%20M16,1.36c-0.904,0-1.64,0.736-1.64,1.64%20S15.096,4.64,16,4.64c0.904,0,1.64-0.736,1.64-1.64S16.904,1.36,16,1.36z%20M20,27.36h-8c-1.301,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36h8c1.302,0,2.36,1.059,2.36,2.36S21.302,27.36,20,27.36z%20M12,23.36c-0.904,0-1.64,0.735-1.64,1.64%20s0.736,1.64,1.64,1.64h8c0.904,0,1.64-0.735,1.64-1.64s-0.735-1.64-1.64-1.64H12z%20M31,23.86h-2c-0.199,0-0.36-0.161-0.36-0.36V15%20c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5C31.36,23.699,31.199,23.86,31,23.86z%20M29.36,23.14h1.279v-7.78%20H29.36V23.14z%20M3,23.86H1c-0.199,0-0.36-0.161-0.36-0.36V15c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5%20C3.36,23.699,3.199,23.86,3,23.86z%20M1.36,23.14h1.28v-7.78H1.36V23.14z%20M20,20.36c-1.302,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36s2.36,1.059,2.36,2.36C22.36,19.302,21.302,20.36,20,20.36z%20M20,16.36c-0.904,0-1.64,0.736-1.64,1.64%20s0.735,1.64,1.64,1.64s1.64-0.735,1.64-1.64S20.904,16.36,20,16.36z%20M12,20.36c-1.301,0-2.36-1.059-2.36-2.36s1.059-2.36,2.36-2.36%20s2.36,1.059,2.36,2.36C14.36,19.302,13.301,20.36,12,20.36z%20M12,16.36c-0.904,0-1.64,0.736-1.64,1.64s0.736,1.64,1.64,1.64%20s1.64-0.735,1.64-1.64S12.904,16.36,12,16.36z'/%3e%3crect%20style='fill:none;'%20width='32'%20height='32'/%3e%3c/svg%3e",Fi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAMAAAC/MqoPAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAADNQTFRF////9vX18vLy/Pz86enp4+Li2tnZ1tbWzczM+fn57Ozs4N/f09LS0M/P5uXl7+/v3dzcwtncCAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAAZNSURBVHja7d3bdtsqEABQYABZSLH9/3+ZpnUsIcF5iOM6PfElNoMHMfPQdq3GmL0GkLhEUqLaUExnOtOZznSmM53pTGc605nOdKYznelMZzrTmV4LXSqllKyJDkob26xWq8Zae/iH0QoWTm9d1xur4WuypQJtTd+5dqn0VjcxzNO5/57mEBvdLo8Oron6aseWOjYOFkVvjQs3DmgyONMuht52EfztP+4hdu0i6LCO808/M8c1lE/fuPGej41uUzgdtoO/75N+2ELJ9I3b3//hPXbiMenm3pR/Jt4USgcLBIp4Bh10gqKVhvLo0klCxeSky96nKcj3siw6pJIL4XsoiQ7apyvMY/V3HHrSRioLopvEhSpTCn2TPEuwKYMOIX0tAxRBf/Hpa+lfSqBv9gi1FPsNfTrMAiVmIE/vJhz61FGnQxRIEYE4vfNYdN8Rp6MlHaHotHTn8ejekaZPAjEmyvQWdZFTtYTpXqCGJ0zvcek9Yfoel76nS0ffv1NMp1ca+pkgyfRCGind4L7OWWc605l+cxjsyhqy9AGbPpClc1/nvl5VX0c/3Alk6RU3+Am7shNZ+h6bvidLr7jBB+zKBrL0irOOudmIUDzTmf5gIP+iEuXtRuTVaEmY/oZLfyNMrzjryPc0gerMTdpVg0tvjJUU6bLPcGOoUv46SLL6Wi8yhLf06C7TUyekI0efRaaYqdFltkeNpPumRPSMDxgBYvSM035FrKAmH72hRW99PrpvSdEHkTEGUvSsK3yKVDkuJ92RohcZaehzzirPpOg+J92Tolfc4Cumx5xVXpGiZ34+ICX6W84qv5GiR5NPbiIpOv6BCoSvSkTX+eiaGP092zINvBOj4x8mSf9FqejvNo/cvpOji19ZbmviL0GPLsYMFzgzCor0+Bv/ePDvSJKOb9dJ5UlnbnEHiHgzv6cdTpJOWuc/u3FEucLDOL75xGtBiefrcwgoC9NDSH/jkH6pAuXmBqPQ9HSUPVdZBH1GGOrMXAQdYxcKZfxAoK+KKBKFLosoEoX+u4giUehz8jlcnAuhp78I46yDYNAd+QLR6K+pr+yvxdBTHyVDubQh0UfSxaHSd0lbvNkVRE87JGOtc+PQd2QLQ6fHhJkKsSh6yg13tO08JPprsgrrXWH0dJd2vH1MLPprot4eXoujpzrdhngiD40ek2y92lggPcnWa8qN1Yz0BFuvZhRl0uOfR0v4Ewuli/Bg4Qr3lArqGdndQ3UPO1EunXYwnelMZzrTmc50pjOd6UxnOtOZznSmM53pTGf6kuj6oedFKV0s3fX6sX1S3bsi6a4PD7+/YAqYeBw6pIB/4qEgOqxdSPbGiim4NRRCbzs3Jj0L4UfXtQXQVRfn5IdA/Bw7RZzurEV6EtdsLeGXkIPuA+K1UoVeA0l62zmN/LqfSSft9KkepmoRuvi3nd5uKNFB9zbbXEANqdr941XO0NJx2v2jdJenpf+/3bvn0ts16ph+sd6hX7dPo2+2cZzE02Ia43bzDHqr+2Evnhz74ZHU30ffbKOeng1/NPV30Ns1gYQnSP2P6e65Pfxc6h02XZqXQCjhJ6kPL6bFo4NrGvAU4UII4SE2P1vQuZkuOxckVfehisF1MjUddN/MZBN+kvq5uf0O/xa66gyNS9ktMWlz44rO1Z8C19i5FPdHzPamXn+F3hryPfxMr78+4F+kq22kO6Rf6fUQt+puuustyWv4rbG3l/duztFB96GYoe1cTBdXMr+nw9qVM6ZfxOvzezff0nXi/ZOndvrR6Zvpm0c3h6nhdb+5iS7tsIim/qXZD9+97/Jf+rpZ5BET1ayv0GUzLhEuhBBjIy/RdVPgndutIRt9nt7p5cKFEEJ3Z+jQFDZL+XnMDXxHB73gxn5s9Kc3d3/pFciFkN/QTSXHJpX5l66gDrkQoP6hL3xsPw39la4qOiV8tH78XeSbue6N9mvWa6J/ybpc1CT1Wnh5Qq9meP8IOKH3ddH7E/ri1iYux/SXDrXR4UiPdck/wUpU+FtPf6/orja6O9KL3l56LOvVxe5Ib2qjN0d6Vbex4ghWlU3bPqI90If66MNng680FNpbJijH6kCvaF3uMzQ3+IrpFerV4Y9dffQdN3im10ivbuImhD3Qq5u4HdZkua8znelMZ/pS4z9CPVKkxowNxgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxNy0wMy0yN1QxNTo0NToxNSswMDowMN1xSg4AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTctMDMtMjdUMTU6NDU6MTUrMDA6MDCsLPKyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAABJRU5ErkJggg==";var Ar=/*#__PURE__*/function(){function Ar(e){_classCallCheck(this,Ar);this.className=e;}return _createClass(Ar,[{key:"getAvatarContainer",value:function getAvatarContainer(e){return e.getElementsByClassName(this.className)[0];}},{key:"tryHide",value:function tryHide(e){var t;(t=this.getAvatarContainer(e).style).visibility||(t.visibility="hidden");}},{key:"tryReveal",value:function tryReveal(e){this.getAvatarContainer(e).style.visibility="";}},{key:"trySoftRem",value:function trySoftRem(e){this.getAvatarContainer(e).classList.add("role-hidden");}}]);}();var Ve=/*#__PURE__*/function(_Ar){function Ve(e){var _this3;_classCallCheck(this,Ve);_this3=_callSuper(this,Ve,["avatar-container"]),_this3._avatars=e;return _this3;}_inherits(Ve,_Ar);return _createClass(Ve,[{key:"addBesideBubble",value:function addBesideBubble(e,t){var s=typeof this._avatars=="boolean"?void 0:this._avatars,i=this.createAvatar(t,s),n=this.getPosition(t,s);i.classList.add(n==="left"?"left-item-position":"right-item-position"),e.insertAdjacentElement(n==="left"?"beforebegin":"afterend",i);}},{key:"createAvatar",value:function createAvatar(e,t){var n,o,a,l,c;var s=document.createElement("img");e===v.USER_ROLE?(s.src=((n=t==null?void 0:t.user)==null?void 0:n.src)||((o=t==null?void 0:t["default"])==null?void 0:o.src)||Fi,s.onerror=Ve.errorFallback.bind(this,Fi)):(s.src=((a=t==null?void 0:t[e])==null?void 0:a.src)||((l=t==null?void 0:t.ai)==null?void 0:l.src)||((c=t==null?void 0:t["default"])==null?void 0:c.src)||Bn,s.onerror=Ve.errorFallback.bind(this,Bn)),s.classList.add("avatar"),s.alt="".concat(e," avatar");var i=document.createElement("div");return i.classList.add(this.className),i.appendChild(s),t&&Ve.applyCustomStyles(i,s,t,e),i;}},{key:"getPosition",value:function getPosition(e,t){var i,n,o,a,l,c;var s=(n=(i=t==null?void 0:t[e])==null?void 0:i.styles)==null?void 0:n.position;return e!==v.USER_ROLE&&(s!==null&&s!==void 0?s:s=(a=(o=t==null?void 0:t.ai)==null?void 0:o.styles)==null?void 0:a.position),s!==null&&s!==void 0?s:s=(c=(l=t==null?void 0:t["default"])==null?void 0:l.styles)==null?void 0:c.position,s!==null&&s!==void 0?s:s=e===v.USER_ROLE?"right":"left",s;}}],[{key:"errorFallback",value:function errorFallback(e,t){var s=t.target;s.onerror=null,s.src=e;}},{key:"applyCustomStylesToElements",value:function applyCustomStylesToElements(e,t,s){Object.assign(e.style,s.container),Object.assign(t.style,s.avatar);}},{key:"applyCustomStyles",value:function applyCustomStyles(e,t,s,i){var n,o,a,l;if((n=s["default"])!=null&&n.styles&&Ve.applyCustomStylesToElements(e,t,s["default"].styles),i===v.USER_ROLE)(o=s.user)!=null&&o.styles&&Ve.applyCustomStylesToElements(e,t,s.user.styles);else{(a=s.ai)!=null&&a.styles&&Ve.applyCustomStylesToElements(e,t,s.ai.styles);var c=(l=s[i])==null?void 0:l.styles;c&&Ve.applyCustomStylesToElements(e,t,c);}}}]);}(Ar);var hs=/*#__PURE__*/function(_Ar2){function hs(e){var _this4;_classCallCheck(this,hs);_this4=_callSuper(this,hs,["name"]),_this4._names=e;return _this4;}_inherits(hs,_Ar2);return _createClass(hs,[{key:"addBesideBubble",value:function addBesideBubble(e,t){var s=typeof this._names=="boolean"?{}:this._names,i=this.createName(t,s),n=hs.getPosition(t,s);i.classList.add(n==="left"?"left-item-position":"right-item-position"),e.insertAdjacentElement(n==="left"?"beforebegin":"afterend",i);}},{key:"createName",value:function createName(e,t){var s=document.createElement("div");return s.classList.add(this.className),s.textContent=hs.getNameText(e,t),hs.applyStyle(s,e,t),s;}}],[{key:"getPosition",value:function getPosition(e,t){var i,n,o;var s=(i=t==null?void 0:t[e])==null?void 0:i.position;return e!==v.USER_ROLE&&(s!==null&&s!==void 0?s:s=(n=t==null?void 0:t.ai)==null?void 0:n.position),s!==null&&s!==void 0?s:s=(o=t==null?void 0:t["default"])==null?void 0:o.position,s!==null&&s!==void 0?s:s=e===v.USER_ROLE?"right":"left",s;}},{key:"applyStyle",value:function applyStyle(e,t,s){var i,n,o,a;Object.assign(e.style,(i=s["default"])==null?void 0:i.style),t===v.USER_ROLE?Object.assign(e.style,(n=s.user)==null?void 0:n.style):(Object.assign(e.style,(o=s.ai)==null?void 0:o.style),Object.assign(e.style,(a=s[t])==null?void 0:a.style));}},{key:"getNameText",value:function getNameText(e,t){var s,i,n,o,a,l;return e===v.USER_ROLE?((s=t.user)==null?void 0:s.text)||((i=t["default"])==null?void 0:i.text)||"User":e===v.AI_ROLE?((n=t.ai)==null?void 0:n.text)||((o=t["default"])==null?void 0:o.text)||"AI":((a=t[e])==null?void 0:a.text)||((l=t["default"])==null?void 0:l.text)||e;}}]);}(Ar);var ue=/*#__PURE__*/function(){function ue(e){var _this5=this;_classCallCheck(this,ue);var t,s,i;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.elementRef=ue.createContainerElement(),this.messageStyles=le.processMessageStyles(e.messageStyles),this._remarkable=xs.createNew(e.remarkable),this._applyHTMLToRemarkable=(t=e.remarkable)==null?void 0:t.applyHTML,e.avatars&&(this.avatar=new Ve(e.avatars)),e.names&&(this.name=new hs(e.names)),e.browserStorage&&(this.browserStorage=new wa(e.browserStorage)),this._onMessage=Ct.onMessage.bind(this,e),e.htmlClassUtilities&&(this.htmlClassUtilities=e.htmlClassUtilities),this.focusMode=e.focusMode,this.focusMode||(this._lastGroupMessagesElement=document.createElement("div")),typeof this.focusMode!="boolean"&&(s=this.focusMode)!=null&&s.fade&&qs.setFade(this.elementRef,this.focusMode.fade),this._customWrappers=e.htmlWrappers||le.processStreamHTMLWrappers((i=e.connect)==null?void 0:i.stream),setTimeout(function(){_this5.submitUserMessage=e.submitUserMessage;});}return _createClass(ue,[{key:"addNewTextMessage",value:function addNewTextMessage(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;if(s!=null&&s.status){var o=this.overwriteText(t,e,this.messageElementRefs);if(o)return o;s.status=!1;}var n=i?this.createAndPrependNewMessageElement(e,t,i):this.createAndAppendNewMessageElement(e,t);return n.bubbleElement.classList.add(ue.TEXT_BUBBLE_CLASS),this.applyCustomStyles(n,t,!1),v.fillEmptyMessageElement(n.bubbleElement,e),n;}// prettier-ignore
82
- },{key:"overwriteText",value:function overwriteText(e,t,s){var i=v.overwriteMessage(this.messageToElements,s,t,e,"text",ue.TEXT_BUBBLE_CLASS);return i&&this.renderText(i.bubbleElement,t,e),i;}},{key:"createAndAppendNewMessageElement",value:function createAndAppendNewMessageElement(e,t){return this.focusMode?this.appendNewMessageElementFocusMode(e,t):this.createAndAppendNewMessageElementDefault(e,t);}},{key:"appendNewMessageElementFocusMode",value:function appendNewMessageElementFocusMode(e,t){var i;var s=this.createNewMessageElement(e,t);if(this.appendOuterContainerElemet(s.outerContainer,t),t==="user"){var n=typeof this.focusMode!="boolean"&&((i=this.focusMode)==null?void 0:i.scroll);F.scrollToBottom(this.elementRef,n);}return s;}},{key:"createNewGroupElementFocusMode",value:function createNewGroupElementFocusMode(){var t;(t=this._lastGroupMessagesElement)==null||t.classList.remove(ue.LAST_GROUP_MESSAGES_ACTIVE);var e=document.createElement("div");this._lastGroupMessagesElement&&e.classList.add(ue.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=e;}},{key:"createAndAppendNewMessageElementDefault",value:function createAndAppendNewMessageElementDefault(e,t){var _this6=this;var s=this.createNewMessageElement(e,t),i=F.isScrollbarAtBottomOfElement(this.elementRef);return this.appendOuterContainerElemet(s.outerContainer),setTimeout(function(){t==="user"?F.scrollToBottom(_this6.elementRef):i&&F.scrollToBottom(_this6.elementRef,!1,s.outerContainer);}),s;}},{key:"appendOuterContainerElemet",value:function appendOuterContainerElemet(e,t){var s;this.focusMode&&(t==="user"||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),(s=this._lastGroupMessagesElement)==null||s.appendChild(e),this.elementRef.appendChild(this._lastGroupMessagesElement);}},{key:"createAndPrependNewMessageElement",value:function createAndPrependNewMessageElement(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;var n=this.createNewMessageElement(e,t,s,i);if(s&&(o=this.elementRef.firstChild)!=null&&o.classList.contains(ue.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",n.outerContainer);var a=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=a;}else this.elementRef.insertBefore(n.outerContainer,this.elementRef.firstChild);return n;}},{key:"createMessageElementsOnOrientation",value:function createMessageElementsOnOrientation(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;return s?this.createAndPrependNewMessageElement(e,t,s,i):this.createNewMessageElement(e,t,s,i);}},{key:"createNewMessageElement",value:function createNewMessageElement(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;i||(o=this._introPanel)==null||o.hide();var n=this.messageElementRefs[this.messageElementRefs.length-1];return Ze.changeFullViewToSmall(this),!s&&ue.isTemporaryElement(n)&&(this.revealRoleElementsIfTempRemoved(n,t),this.removeLastMessage()),this.createMessageElements(e,t,s);}// this can be tested by having an ai message, then a temp ai message with html that submits new user message:
81
+ },{key:"extractParticularSharedStyles",value:function extractParticularSharedStyles(e,t){if(!(t!=null&&t.shared))return;var s=t.shared,i={outerContainer:{},innerContainer:{},bubble:{},media:{}};return e.forEach(function(n){var o,a,l,c;i.outerContainer[n]=((o=s.outerContainer)==null?void 0:o[n])||"",i.innerContainer[n]=((a=s.innerContainer)==null?void 0:a[n])||"",i.bubble[n]=((l=s.bubble)==null?void 0:l[n])||"",i.media[n]=((c=s.media)==null?void 0:c[n])||"";}),i;}}]);}();var Ct=/*#__PURE__*/function(){function Ct(){_classCallCheck(this,Ct);}return _createClass(Ct,null,[{key:"onMessage",value:function onMessage(e,t,s){var n;var i=JSON.parse(JSON.stringify({message:t,isHistory:s,isInitial:s}));ee.reAddFileRefToObject(t,i.message),(n=e.onMessage)==null||n.call(e,i),e.dispatchEvent(new CustomEvent("message",{detail:i})),te.fireOnNewMessage(e,i);}},{key:"onClearMessages",value:function onClearMessages(e){var t;(t=e.onClearMessages)==null||t.call(e),e.dispatchEvent(new CustomEvent("clear-messages"));}},{key:"onRender",value:function onRender(e){var t;(t=e.onComponentRender)==null||t.call(e,e),e.dispatchEvent(new CustomEvent("render",{detail:e}));}},{key:"onInput",value:function onInput(e,t,s){var n,o;var i=JSON.parse(JSON.stringify({content:t,isUser:s}));t.files&&ee.reAddFileRefToObject({files:(n=t.files)==null?void 0:n.map(function(a){return{ref:a};})},i.content),(o=e.onInput)==null||o.call(e,i),e.dispatchEvent(new CustomEvent("input",{detail:i}));}},{key:"onError",value:function onError(e,t){var s;(s=e.onError)==null||s.call(e,t),e.dispatchEvent(new CustomEvent("error",{detail:t}));}}]);}();var X=/*#__PURE__*/function(){function X(){_classCallCheck(this,X);}return _createClass(X,null,[{key:"generateLoadingRingElement",value:function generateLoadingRingElement(){var e=document.createElement("div");return e.classList.add("loading-history"),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e.appendChild(document.createElement("div")),e;}},{key:"apply",value:function apply(e,t,s){Xe.setRing(t.bubbleElement,s==null?void 0:s.bubble),s!=null&&s.bubble&&(s=JSON.parse(JSON.stringify(s)),delete s.bubble),e.applyCustomStyles(t,"history",!1,s);}},{key:"addLoadHistoryMessage",value:function addLoadHistoryMessage(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!0;var o,a,l,c,d,u,h,f;e.bubbleElement.classList.add(X.CLASS);var i=s?X.FULL_VIEW_CLASS:X.SMALL_CLASS;e.outerContainer.classList.add(i);var n=s?(c=(l=(a=(o=t.messageStyles)==null?void 0:o.loading)==null?void 0:a.history)==null?void 0:l.full)==null?void 0:c.styles:(f=(h=(u=(d=t.messageStyles)==null?void 0:d.loading)==null?void 0:u.history)==null?void 0:h.small)==null?void 0:f.styles;X.apply(t,e,n),t.elementRef.prepend(e.outerContainer);}},{key:"createDefaultElements",value:function createDefaultElements(e){var t=e.createMessageElements("",v.AI_ROLE),s=t.bubbleElement,i=X.generateLoadingRingElement();return s.appendChild(i),t;}},{key:"addMessage",value:function addMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!0;var n,o,a,l;var s=(l=(a=(o=(n=e.messageStyles)==null?void 0:n.loading)==null?void 0:o.history)==null?void 0:a.full)==null?void 0:l.html,i=s?Be.createElements(e,s,v.AI_ROLE,!0,!0):X.createDefaultElements(e);return X.addLoadHistoryMessage(i,e,t),v.softRemRoleElements(i.innerContainer,e.avatar,e.name),i;}},{key:"tryChangeViewToSmall",value:function tryChangeViewToSmall(e,t){var s,i,n,o,a,l,c,d;if(t!=null&&t.outerContainer.classList.contains(X.FULL_VIEW_CLASS)){t.outerContainer.classList.replace(X.FULL_VIEW_CLASS,X.SMALL_CLASS);var u=(o=(n=(i=(s=e.messageStyles)==null?void 0:s.loading)==null?void 0:i.history)==null?void 0:n.small)==null?void 0:o.styles;u&&X.apply(e,t,u);var h=(d=(c=(l=(a=e.messageStyles)==null?void 0:a.loading)==null?void 0:l.history)==null?void 0:c.small)==null?void 0:d.html;return h&&(t.bubbleElement.innerHTML=h),!0;}return!1;}},{key:"changeFullViewToSmall",value:function changeFullViewToSmall(e){var t=e.messageElementRefs[e.messageElementRefs.length-1];X.tryChangeViewToSmall(e,t)||X.tryChangeViewToSmall(e,e.messageElementRefs[0]);}}]);}();X.CLASS="loading-history-message",X.FULL_VIEW_CLASS="loading-history-message-full-view",X.SMALL_CLASS="loading-history-message-small";var Ze=X;var gs=/*#__PURE__*/function(){function gs(){_classCallCheck(this,gs);}return _createClass(gs,null,[{key:"setFade",value:function setFade(e,t){e.style.transitionDuration=typeof t=="number"?"".concat(t,"ms"):"".concat(gs.DEFAULT_FADE_MS,"ms");}},{key:"fadeAnimation",value:function(){var _fadeAnimation=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(e,t){var s;return _regenerator().w(function(_context){while(1)switch(_context.n){case 0:e.style.opacity="0";s=typeof t=="number"?t:gs.DEFAULT_FADE_MS;_context.n=1;return new Promise(function(i){setTimeout(function(){return i();},s);});case 1:e.style.opacity="1";case 2:return _context.a(2);}},_callee);}));function fadeAnimation(_x,_x2){return _fadeAnimation.apply(this,arguments);}return fadeAnimation;}()}]);}();gs.DEFAULT_FADE_MS=500;var qs=gs;var Bn="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3csvg%20fill='%23000000'%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20viewBox='0%200%2032%2032'%20xml:space='preserve'%3e%3cpath%20d='M23,30.36H9c-2.404,0-4.36-1.956-4.36-4.36V15c0-2.404,1.956-4.36,4.36-4.36h3.659%20c0.167-1.566,1.415-2.813,2.981-2.981V5.333c-1.131-0.174-2-1.154-2-2.333c0-1.301,1.059-2.36,2.36-2.36%20c1.302,0,2.36,1.059,2.36,2.36c0,1.179-0.869,2.159-2,2.333V7.66c1.566,0.167,2.814,1.415,2.981,2.981H23%20c2.404,0,4.36,1.956,4.36,4.36v11C27.36,28.404,25.404,30.36,23,30.36z%20M9,11.36c-2.007,0-3.64,1.633-3.64,3.64v11%20c0,2.007,1.633,3.64,3.64,3.64h14c2.007,0,3.64-1.633,3.64-3.64V15c0-2.007-1.633-3.64-3.64-3.64H9z%20M13.384,10.64h5.231%20C18.439,9.354,17.334,8.36,16,8.36C14.667,8.36,13.561,9.354,13.384,10.64z%20M16,1.36c-0.904,0-1.64,0.736-1.64,1.64%20S15.096,4.64,16,4.64c0.904,0,1.64-0.736,1.64-1.64S16.904,1.36,16,1.36z%20M20,27.36h-8c-1.301,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36h8c1.302,0,2.36,1.059,2.36,2.36S21.302,27.36,20,27.36z%20M12,23.36c-0.904,0-1.64,0.735-1.64,1.64%20s0.736,1.64,1.64,1.64h8c0.904,0,1.64-0.735,1.64-1.64s-0.735-1.64-1.64-1.64H12z%20M31,23.86h-2c-0.199,0-0.36-0.161-0.36-0.36V15%20c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5C31.36,23.699,31.199,23.86,31,23.86z%20M29.36,23.14h1.279v-7.78%20H29.36V23.14z%20M3,23.86H1c-0.199,0-0.36-0.161-0.36-0.36V15c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5%20C3.36,23.699,3.199,23.86,3,23.86z%20M1.36,23.14h1.28v-7.78H1.36V23.14z%20M20,20.36c-1.302,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36s2.36,1.059,2.36,2.36C22.36,19.302,21.302,20.36,20,20.36z%20M20,16.36c-0.904,0-1.64,0.736-1.64,1.64%20s0.735,1.64,1.64,1.64s1.64-0.735,1.64-1.64S20.904,16.36,20,16.36z%20M12,20.36c-1.301,0-2.36-1.059-2.36-2.36s1.059-2.36,2.36-2.36%20s2.36,1.059,2.36,2.36C14.36,19.302,13.301,20.36,12,20.36z%20M12,16.36c-0.904,0-1.64,0.736-1.64,1.64s0.736,1.64,1.64,1.64%20s1.64-0.735,1.64-1.64S12.904,16.36,12,16.36z'/%3e%3crect%20style='fill:none;'%20width='32'%20height='32'/%3e%3c/svg%3e",Fi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAMAAAC/MqoPAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAADNQTFRF////9vX18vLy/Pz86enp4+Li2tnZ1tbWzczM+fn57Ozs4N/f09LS0M/P5uXl7+/v3dzcwtncCAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAAZNSURBVHja7d3bdtsqEABQYABZSLH9/3+ZpnUsIcF5iOM6PfElNoMHMfPQdq3GmL0GkLhEUqLaUExnOtOZznSmM53pTGc605nOdKYznelMZzrTmV4LXSqllKyJDkob26xWq8Zae/iH0QoWTm9d1xur4WuypQJtTd+5dqn0VjcxzNO5/57mEBvdLo8Oron6aseWOjYOFkVvjQs3DmgyONMuht52EfztP+4hdu0i6LCO808/M8c1lE/fuPGej41uUzgdtoO/75N+2ELJ9I3b3//hPXbiMenm3pR/Jt4USgcLBIp4Bh10gqKVhvLo0klCxeSky96nKcj3siw6pJIL4XsoiQ7apyvMY/V3HHrSRioLopvEhSpTCn2TPEuwKYMOIX0tAxRBf/Hpa+lfSqBv9gi1FPsNfTrMAiVmIE/vJhz61FGnQxRIEYE4vfNYdN8Rp6MlHaHotHTn8ejekaZPAjEmyvQWdZFTtYTpXqCGJ0zvcek9Yfoel76nS0ffv1NMp1ca+pkgyfRCGind4L7OWWc605l+cxjsyhqy9AGbPpClc1/nvl5VX0c/3Alk6RU3+Am7shNZ+h6bvidLr7jBB+zKBrL0irOOudmIUDzTmf5gIP+iEuXtRuTVaEmY/oZLfyNMrzjryPc0gerMTdpVg0tvjJUU6bLPcGOoUv46SLL6Wi8yhLf06C7TUyekI0efRaaYqdFltkeNpPumRPSMDxgBYvSM035FrKAmH72hRW99PrpvSdEHkTEGUvSsK3yKVDkuJ92RohcZaehzzirPpOg+J92Tolfc4Cumx5xVXpGiZ34+ICX6W84qv5GiR5NPbiIpOv6BCoSvSkTX+eiaGP092zINvBOj4x8mSf9FqejvNo/cvpOji19ZbmviL0GPLsYMFzgzCor0+Bv/ePDvSJKOb9dJ5UlnbnEHiHgzv6cdTpJOWuc/u3FEucLDOL75xGtBiefrcwgoC9NDSH/jkH6pAuXmBqPQ9HSUPVdZBH1GGOrMXAQdYxcKZfxAoK+KKBKFLosoEoX+u4giUehz8jlcnAuhp78I46yDYNAd+QLR6K+pr+yvxdBTHyVDubQh0UfSxaHSd0lbvNkVRE87JGOtc+PQd2QLQ6fHhJkKsSh6yg13tO08JPprsgrrXWH0dJd2vH1MLPprot4eXoujpzrdhngiD40ek2y92lggPcnWa8qN1Yz0BFuvZhRl0uOfR0v4Ewuli/Bg4Qr3lArqGdndQ3UPO1EunXYwnelMZzrTmc50pjOd6UxnOtOZznSmM53pTGf6kuj6oedFKV0s3fX6sX1S3bsi6a4PD7+/YAqYeBw6pIB/4qEgOqxdSPbGiim4NRRCbzs3Jj0L4UfXtQXQVRfn5IdA/Bw7RZzurEV6EtdsLeGXkIPuA+K1UoVeA0l62zmN/LqfSSft9KkepmoRuvi3nd5uKNFB9zbbXEANqdr941XO0NJx2v2jdJenpf+/3bvn0ts16ph+sd6hX7dPo2+2cZzE02Ia43bzDHqr+2Evnhz74ZHU30ffbKOeng1/NPV30Ns1gYQnSP2P6e65Pfxc6h02XZqXQCjhJ6kPL6bFo4NrGvAU4UII4SE2P1vQuZkuOxckVfehisF1MjUddN/MZBN+kvq5uf0O/xa66gyNS9ktMWlz44rO1Z8C19i5FPdHzPamXn+F3hryPfxMr78+4F+kq22kO6Rf6fUQt+puuustyWv4rbG3l/duztFB96GYoe1cTBdXMr+nw9qVM6ZfxOvzezff0nXi/ZOndvrR6Zvpm0c3h6nhdb+5iS7tsIim/qXZD9+97/Jf+rpZ5BET1ayv0GUzLhEuhBBjIy/RdVPgndutIRt9nt7p5cKFEEJ3Z+jQFDZL+XnMDXxHB73gxn5s9Kc3d3/pFciFkN/QTSXHJpX5l66gDrkQoP6hL3xsPw39la4qOiV8tH78XeSbue6N9mvWa6J/ybpc1CT1Wnh5Qq9meP8IOKH3ddH7E/ri1iYux/SXDrXR4UiPdck/wUpU+FtPf6/orja6O9KL3l56LOvVxe5Ib2qjN0d6Vbex4ghWlU3bPqI90If66MNng680FNpbJijH6kCvaF3uMzQ3+IrpFerV4Y9dffQdN3im10ivbuImhD3Qq5u4HdZkua8znelMZ/pS4z9CPVKkxowNxgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxNy0wMy0yN1QxNTo0NToxNSswMDowMN1xSg4AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTctMDMtMjdUMTU6NDU6MTUrMDA6MDCsLPKyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAABJRU5ErkJggg==";var Ar=/*#__PURE__*/function(){function Ar(e){_classCallCheck(this,Ar);this.className=e;}return _createClass(Ar,[{key:"getAvatarContainer",value:function getAvatarContainer(e){return e.getElementsByClassName(this.className)[0];}},{key:"tryHide",value:function tryHide(e){var t;(t=this.getAvatarContainer(e).style).visibility||(t.visibility="hidden");}},{key:"tryReveal",value:function tryReveal(e){this.getAvatarContainer(e).style.visibility="";}},{key:"trySoftRem",value:function trySoftRem(e){this.getAvatarContainer(e).classList.add("role-hidden");}}]);}();var Ve=/*#__PURE__*/function(_Ar){function Ve(e){var _this3;_classCallCheck(this,Ve);_this3=_callSuper(this,Ve,["avatar-container"]),_this3._avatars=e;return _this3;}_inherits(Ve,_Ar);return _createClass(Ve,[{key:"addBesideBubble",value:function addBesideBubble(e,t){var s=typeof this._avatars=="boolean"?void 0:this._avatars,i=this.createAvatar(t,s),n=this.getPosition(t,s);i.classList.add(n==="left"?"left-item-position":"right-item-position"),e.insertAdjacentElement(n==="left"?"beforebegin":"afterend",i);}},{key:"createAvatar",value:function createAvatar(e,t){var n,o,a,l,c;var s=document.createElement("img");e===v.USER_ROLE?(s.src=((n=t==null?void 0:t.user)==null?void 0:n.src)||((o=t==null?void 0:t["default"])==null?void 0:o.src)||Fi,s.onerror=Ve.errorFallback.bind(this,Fi)):(s.src=((a=t==null?void 0:t[e])==null?void 0:a.src)||((l=t==null?void 0:t.ai)==null?void 0:l.src)||((c=t==null?void 0:t["default"])==null?void 0:c.src)||Bn,s.onerror=Ve.errorFallback.bind(this,Bn)),s.classList.add("avatar"),s.alt="".concat(e," avatar");var i=document.createElement("div");return i.classList.add(this.className),i.appendChild(s),t&&Ve.applyCustomStyles(i,s,t,e),i;}},{key:"getPosition",value:function getPosition(e,t){var i,n,o,a,l,c;var s=(n=(i=t==null?void 0:t[e])==null?void 0:i.styles)==null?void 0:n.position;return e!==v.USER_ROLE&&(s!==null&&s!==void 0?s:s=(a=(o=t==null?void 0:t.ai)==null?void 0:o.styles)==null?void 0:a.position),s!==null&&s!==void 0?s:s=(c=(l=t==null?void 0:t["default"])==null?void 0:l.styles)==null?void 0:c.position,s!==null&&s!==void 0?s:s=e===v.USER_ROLE?"right":"left",s;}}],[{key:"errorFallback",value:function errorFallback(e,t){var s=t.target;s.onerror=null,s.src=e;}},{key:"applyCustomStylesToElements",value:function applyCustomStylesToElements(e,t,s){Object.assign(e.style,s.container),Object.assign(t.style,s.avatar);}},{key:"applyCustomStyles",value:function applyCustomStyles(e,t,s,i){var n,o,a,l;if((n=s["default"])!=null&&n.styles&&Ve.applyCustomStylesToElements(e,t,s["default"].styles),i===v.USER_ROLE)(o=s.user)!=null&&o.styles&&Ve.applyCustomStylesToElements(e,t,s.user.styles);else{(a=s.ai)!=null&&a.styles&&Ve.applyCustomStylesToElements(e,t,s.ai.styles);var c=(l=s[i])==null?void 0:l.styles;c&&Ve.applyCustomStylesToElements(e,t,c);}}}]);}(Ar);var hs=/*#__PURE__*/function(_Ar2){function hs(e){var _this4;_classCallCheck(this,hs);_this4=_callSuper(this,hs,["name"]),_this4._names=e;return _this4;}_inherits(hs,_Ar2);return _createClass(hs,[{key:"addBesideBubble",value:function addBesideBubble(e,t){var s=typeof this._names=="boolean"?{}:this._names,i=this.createName(t,s),n=hs.getPosition(t,s);i.classList.add(n==="left"?"left-item-position":"right-item-position"),e.insertAdjacentElement(n==="left"?"beforebegin":"afterend",i);}},{key:"createName",value:function createName(e,t){var s=document.createElement("div");return s.classList.add(this.className),s.textContent=hs.getNameText(e,t),hs.applyStyle(s,e,t),s;}}],[{key:"getPosition",value:function getPosition(e,t){var i,n,o;var s=(i=t==null?void 0:t[e])==null?void 0:i.position;return e!==v.USER_ROLE&&(s!==null&&s!==void 0?s:s=(n=t==null?void 0:t.ai)==null?void 0:n.position),s!==null&&s!==void 0?s:s=(o=t==null?void 0:t["default"])==null?void 0:o.position,s!==null&&s!==void 0?s:s=e===v.USER_ROLE?"right":"left",s;}},{key:"applyStyle",value:function applyStyle(e,t,s){var i,n,o,a;Object.assign(e.style,(i=s["default"])==null?void 0:i.style),t===v.USER_ROLE?Object.assign(e.style,(n=s.user)==null?void 0:n.style):(Object.assign(e.style,(o=s.ai)==null?void 0:o.style),Object.assign(e.style,(a=s[t])==null?void 0:a.style));}},{key:"getNameText",value:function getNameText(e,t){var s,i,n,o,a,l;return e===v.USER_ROLE?((s=t.user)==null?void 0:s.text)||((i=t["default"])==null?void 0:i.text)||"User":e===v.AI_ROLE?((n=t.ai)==null?void 0:n.text)||((o=t["default"])==null?void 0:o.text)||"AI":((a=t[e])==null?void 0:a.text)||((l=t["default"])==null?void 0:l.text)||e;}}]);}(Ar);var ue=/*#__PURE__*/function(){function ue(e){var _this5=this;_classCallCheck(this,ue);var t,s,i;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.elementRef=ue.createContainerElement(),this.messageStyles=te.processMessageStyles(e.messageStyles),this._remarkable=xs.createNew(e.remarkable),this._applyHTMLToRemarkable=(t=e.remarkable)==null?void 0:t.applyHTML,e.avatars&&(this.avatar=new Ve(e.avatars)),e.names&&(this.name=new hs(e.names)),e.browserStorage&&(this.browserStorage=new wa(e.browserStorage)),this._onMessage=Ct.onMessage.bind(this,e),e.htmlClassUtilities&&(this.htmlClassUtilities=e.htmlClassUtilities),this.focusMode=te.processFocusMode(e.focusMode),this.focusMode||(this._lastGroupMessagesElement=document.createElement("div")),typeof this.focusMode!="boolean"&&(s=this.focusMode)!=null&&s.fade&&qs.setFade(this.elementRef,this.focusMode.fade),this._customWrappers=e.htmlWrappers||te.processStreamHTMLWrappers((i=e.connect)==null?void 0:i.stream),setTimeout(function(){_this5.submitUserMessage=e.submitUserMessage;});}return _createClass(ue,[{key:"addNewTextMessage",value:function addNewTextMessage(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;if(s!=null&&s.status){var o=this.overwriteText(t,e,this.messageElementRefs);if(o)return o;s.status=!1;}var n=i?this.createAndPrependNewMessageElement(e,t,i):this.createAndAppendNewMessageElement(e,t);return n.bubbleElement.classList.add(ue.TEXT_BUBBLE_CLASS),this.applyCustomStyles(n,t,!1),v.fillEmptyMessageElement(n.bubbleElement,e),n;}// prettier-ignore
82
+ },{key:"overwriteText",value:function overwriteText(e,t,s){var i=v.overwriteMessage(this.messageToElements,s,t,e,"text",ue.TEXT_BUBBLE_CLASS);return i&&this.renderText(i.bubbleElement,t,e),i;}},{key:"createAndAppendNewMessageElement",value:function createAndAppendNewMessageElement(e,t){return this.focusMode?this.appendNewMessageElementFocusMode(e,t):this.createAndAppendNewMessageElementDefault(e,t);}},{key:"appendNewMessageElementFocusMode",value:function appendNewMessageElementFocusMode(e,t){var i;var s=this.createNewMessageElement(e,t);if(this.appendOuterContainerElemet(s.outerContainer,t),t==="user"){var n=typeof this.focusMode!="boolean"&&((i=this.focusMode)==null?void 0:i.smoothScroll);F.scrollToBottom(this.elementRef,n);}return s;}},{key:"createNewGroupElementFocusMode",value:function createNewGroupElementFocusMode(){var t;(t=this._lastGroupMessagesElement)==null||t.classList.remove(ue.LAST_GROUP_MESSAGES_ACTIVE);var e=document.createElement("div");this._lastGroupMessagesElement&&e.classList.add(ue.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=e;}},{key:"createAndAppendNewMessageElementDefault",value:function createAndAppendNewMessageElementDefault(e,t){var _this6=this;var s=this.createNewMessageElement(e,t),i=F.isScrollbarAtBottomOfElement(this.elementRef);return this.appendOuterContainerElemet(s.outerContainer),setTimeout(function(){t==="user"?F.scrollToBottom(_this6.elementRef):i&&F.scrollToBottom(_this6.elementRef,!1,s.outerContainer);}),s;}},{key:"appendOuterContainerElemet",value:function appendOuterContainerElemet(e,t){var s;this.focusMode&&(t==="user"||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),(s=this._lastGroupMessagesElement)==null||s.appendChild(e),this.elementRef.appendChild(this._lastGroupMessagesElement);}},{key:"createAndPrependNewMessageElement",value:function createAndPrependNewMessageElement(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;var n=this.createNewMessageElement(e,t,s,i);if(s&&(o=this.elementRef.firstChild)!=null&&o.classList.contains(ue.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",n.outerContainer);var a=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=a;}else this.elementRef.insertBefore(n.outerContainer,this.elementRef.firstChild);return n;}},{key:"createMessageElementsOnOrientation",value:function createMessageElementsOnOrientation(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;return s?this.createAndPrependNewMessageElement(e,t,s,i):this.createNewMessageElement(e,t,s,i);}},{key:"createNewMessageElement",value:function createNewMessageElement(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var o;i||(o=this._introPanel)==null||o.hide();var n=this.messageElementRefs[this.messageElementRefs.length-1];return Ze.changeFullViewToSmall(this),!s&&ue.isTemporaryElement(n)&&(this.revealRoleElementsIfTempRemoved(n,t),this.removeLastMessage()),this.createMessageElements(e,t,s);}// this can be tested by having an ai message, then a temp ai message with html that submits new user message:
83
83
  // https://github.com/OvidijusParsiunas/deep-chat/issues/258
84
84
  // prettier-ignore
85
85
  },{key:"revealRoleElementsIfTempRemoved",value:function revealRoleElementsIfTempRemoved(e,t){if((this.avatar||this.name)&&De.isElementTemporary(e)){var s=this.messageElementRefs[this.messageElementRefs.length-2];s&&this.messageToElements.length>0&&!e.bubbleElement.classList.contains(v.getRoleClass(t))&&v.revealRoleElements(s.innerContainer,this.avatar,this.name);}}},{key:"createElements",value:function createElements(e,t){var s=ue.createBaseElements(t),i=s.outerContainer,n=s.innerContainer,o=s.bubbleElement;return i.appendChild(n),this.addInnerContainerElements(o,e,t),s;}},{key:"createMessageElements",value:function createMessageElements(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var i=this.createElements(e,t);return v.updateRefArr(this.messageElementRefs,i,s),v.classifyRoleMessages(this.messageElementRefs,t),i;}},{key:"addInnerContainerElements",value:// prettier-ignore
86
86
  function addInnerContainerElements(e,t,s){var i=this.messageElementRefs[this.messageElementRefs.length-1];return v.areOuterContainerClassRolesSame(s,i)&&!this.isLastMessageError()&&v.hideRoleElements(i.innerContainer,this.avatar,this.name),e.classList.add("message-bubble",v.getRoleClass(s),s===v.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(e,t,s),v.addRoleElements(e,s,this.avatar,this.name),{bubbleElement:e};}// prettier-ignore
87
87
  },{key:"applyCustomStyles",value:function applyCustomStyles(e,t,s,i){e&&this.messageStyles&&he.applyCustomStyles(this.messageStyles,e,t,s,i);}},{key:"removeMessage",value:function removeMessage(e){e.outerContainer.remove();var t=this.messageElementRefs.findIndex(function(s){return s===e;});this.messageElementRefs.splice(t,1);}},{key:"removeLastMessage",value:function removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop();}},{key:"isLastMessageError",value:function isLastMessageError(){var e;return(e=v.getLastMessageBubbleElement(this.elementRef))==null?void 0:e.classList.contains(v.ERROR_MESSAGE_TEXT_CLASS);}},{key:"sendClientUpdate",value:function sendClientUpdate(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;var s;(s=this._onMessage)==null||s.call(this,e,t);}// role is optional to not add wrapper to error
88
- },{key:"renderText",value:function renderText(e,t,s){var _ae$tryAddWrapper2=ae.tryAddWrapper(e,t,this._customWrappers,s),i=_ae$tryAddWrapper2.contentEl,n=_ae$tryAddWrapper2.wrapper;n&&ae.apply(this,e),i.innerHTML=this._remarkable.render(t),this._applyHTMLToRemarkable&&ae.apply(this,i),i.innerText.trim().length===0&&i.children.length>0&&i.children[0].tagName!=="P"&&(i.innerText=t);}// this is mostly used for enabling highlight.js to highlight code if it downloads later
88
+ },{key:"renderText",value:function renderText(e,t,s){var _le$tryAddWrapper2=le.tryAddWrapper(e,t,this._customWrappers,s),i=_le$tryAddWrapper2.contentEl,n=_le$tryAddWrapper2.wrapper;n&&le.apply(this,e),i.innerHTML=this._remarkable.render(t),this._applyHTMLToRemarkable&&le.apply(this,i),i.innerText.trim().length===0&&i.children.length>0&&i.children[0].tagName!=="P"&&(i.innerText=t);}// this is mostly used for enabling highlight.js to highlight code if it downloads later
89
89
  },{key:"refreshTextMessages",value:function refreshTextMessages(e){var _this7=this;this._remarkable=xs.createNew(e),this.messageToElements.forEach(function(t){t[1].text&&t[0].text&&_this7.renderText(t[1].text.bubbleElement,t[0].text,t[0].role);});}}],[{key:"createContainerElement",value:function createContainerElement(){var e=document.createElement("div");return e.id="messages",e;}},{key:"isTemporaryElement",value:function isTemporaryElement(e){return ue.isLoadingMessage(e)||De.isElementTemporary(e);}},{key:"createBaseElements",value:function createBaseElements(e){var t=document.createElement("div"),s=document.createElement("div");s.classList.add("inner-message-container"),t.appendChild(s),t.classList.add("outer-message-container"),t.classList.add(v.buildRoleOuterContainerClass(e));var i=document.createElement("div");return i.classList.add("message-bubble"),s.appendChild(i),{outerContainer:t,innerContainer:s,bubbleElement:i};}},{key:"createMessageContent",value:function createMessageContent(e){var t=e.text,s=e.files,i=e.html,n=e.custom,o=e._sessionId,a=e.role,l={role:a||v.AI_ROLE};return t&&(l.text=t),s&&(l.files=s),i&&(l.html=i),!t&&!s&&!i&&(l.text=""),n&&(l.custom=n),o&&(l._sessionId=o),l;}},{key:"isLoadingMessage",value:function isLoadingMessage(e){return e==null?void 0:e.bubbleElement.classList.contains(Xe.BUBBLE_CLASS);}}]);}();ue.TEXT_BUBBLE_CLASS="text-message",ue.INTRO_CLASS="deep-chat-intro",ue.LAST_GROUP_MESSAGES_ACTIVE="deep-chat-last-group-messages-active";var Ae=ue;var x=/*#__PURE__*/function(){function x(){_classCallCheck(this,x);}return _createClass(x,null,[{key:"getLastElementsByClass",value:function getLastElementsByClass(e,t,s){var _loop=function _loop(){var n=e[i];if(n.bubbleElement.classList.contains(t[0])&&!t.slice(1).find(function(a){return!n.bubbleElement.classList.contains(a);}))if(s){if(!s.find(function(l){return n.bubbleElement.classList.contains(l);}))return{v:n};}else return{v:n};},_ret;for(var i=e.length-1;i>=0;i-=1){_ret=_loop();if(_ret)return _ret.v;}}},{key:"getLastMessage",value:function getLastMessage(e,t,s){for(var i=e.length-1;i>=0;i-=1)if(e[i][0].role===t)if(s){if(e[i][0][s])return e[i][0];}else return e[i][0];}},{key:"getLastTextToElement",value:function getLastTextToElement(e,t){for(var s=e.length-1;s>=0;s-=1)if(e[s][0]===t)return e[s];}// IMPORTANT: If the overwrite message does not contain a role property it will look for the last 'ai' role message
90
90
  // and if messages have custom roles, it will still look to update the last 'ai' role message
91
91
  // prettier-ignore
@@ -95,33 +95,33 @@ function addInnerContainerElements(e,t,s){var i=this.messageElementRefs[this.mes
95
95
  // and 'custom' property value if it is not shallow copyable
96
96
  // note - structuredClone can fix this but it doesn't have good legacy compatibility
97
97
  },{key:"deepCloneMessagesWithReferences",value:function deepCloneMessagesWithReferences(e){return e.map(function(t){return x.processMessageContent(t);});}},{key:"processMessageContent",value:function processMessageContent(e){if(e==null||_typeof(e)!==T)return e;if(Array.isArray(e))return e.map(function(s){return x.processMessageContent(s);});var t={};return Object.entries(e).forEach(function(_ref5){var _ref6=_slicedToArray(_ref5,2),s=_ref6[0],i=_ref6[1];s==="ref"&&i instanceof File||s==="custom"?t[s]=i:i!==null&&_typeof(i)===T?t[s]=x.processMessageContent(i):t[s]=i;}),t;}}]);}();x.AI_ROLE="ai",x.USER_ROLE="user",x.ERROR_MESSAGE_TEXT_CLASS="error-message-text",x.OUTER_CONTAINER_CLASS_ROLE_PREFIX="deep-chat-outer-container-role-",x.EMPTY_MESSAGE_CLASS="empty-message",x.POSITION_TOP_MESSAGE_CLASS="deep-chat-top-message",x.POSITION_MIDDLE_MESSAGE_CLASS="deep-chat-middle-message",x.POSITION_BOTTOM_MESSAGE_CLASS="deep-chat-bottom-message";var v=x;var Ne=/*#__PURE__*/function(){function Ne(e,t){_classCallCheck(this,Ne);this.allowScroll=!0,this._fileAdded=!1,this._streamType="",this._hasStreamEnded=!1,this._partialText="",this._messages=e,Ne.isFocusModeScrollAllowed(this._messages.focusMode)&&(this.allowScroll=!1),_typeof(t)=="object"&&(this._partialRender=t.partialRender);}return _createClass(Ne,[{key:"upsertStreamedMessage",value:function upsertStreamedMessage(e){if(this._hasStreamEnded)return;if((e==null?void 0:e.text)===void 0&&(e==null?void 0:e.html)===void 0)return console.error(b.INVALID_STREAM_EVENT);e!=null&&e.custom&&this._message&&(this._message.custom=e.custom);var t=(e==null?void 0:e.text)||(e==null?void 0:e.html)||"",s=F.isScrollbarAtBottomOfElement(this._messages.elementRef),i=(e==null?void 0:e.text)!==void 0?"text":"html";if(!this._elements&&!this._message)this.setInitialState(i,t,e==null?void 0:e.role);else{if(this._streamType!==i)return console.error(b.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(t,i,e==null?void 0:e.overwrite);}s&&this.allowScroll&&F.scrollToBottom(this._messages.elementRef);}},{key:"setInitialState",value:function setInitialState(e,t,s){var o,a;this._streamType=e,s!==null&&s!==void 0?s:s=v.AI_ROLE;var i=((o=this._messages._customWrappers)==null?void 0:o[s])||((a=this._messages._customWrappers)==null?void 0:a["default"]),n=i?"":t;this._elements=e==="text"?this._messages.addNewTextMessage(n,s):Be.add(this._messages,n,s,!0),this._elements&&(this._elements.bubbleElement.classList.add(Ne.MESSAGE_CLASS),this._activeMessageRole=s,this._message=_defineProperty({role:this._activeMessageRole},e,n),this._messages.messageToElements.push([this._message,_defineProperty({},e,this._elements)]),i&&this.setTargetWrapperIfNeeded(this._elements,t,this._streamType,i));}// not using existing htmlUtils htmlWrappers logic to be able to stream html
98
- },{key:"setTargetWrapperIfNeeded",value:function setTargetWrapperIfNeeded(e,t,s,i){e.bubbleElement.innerHTML=i,this._targetWrapper=ae.getTargetWrapper(e.bubbleElement),this._elements&&ae.apply(this._messages,this._elements.bubbleElement),this.updateBasedOnType(t,s);}},{key:"updateBasedOnType",value:function updateBasedOnType(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var o;var i=this._targetWrapper||((o=this._elements)==null?void 0:o.bubbleElement);this._partialRender||v.unfillEmptyMessageElement(i,e),(t==="text"?this.updateText:this.updateHTML).bind(this)(e,i,s);}},{key:"updateText",value:function updateText(e,t,s){this._message&&(this._message.text=s?e:this._message.text+e,this._partialRender&&this.isNewPartialRenderParagraph(t,s)&&this.partialRenderNewParagraph(t),this._partialBubble?this.partialRenderBubbleUpdate(e):this._messages.renderText(t,this._message.text));}},{key:"isNewPartialRenderParagraph",value:function isNewPartialRenderParagraph(e,t){var s;return t?(e.innerHTML="",!0):this._partialBubble?this._partialText&&this.shouldCreateNewParagraph(this._partialText):((s=this._message)==null?void 0:s.text)&&this.shouldCreateNewParagraph(this._message.text);}},{key:"shouldCreateNewParagraph",value:function shouldCreateNewParagraph(e){var t=e.indexOf(Ne.PARTIAL_RENDER_TEXT_MARK);return t===-1?!1:!e.substring(t+Ne.PARTIAL_RENDER_TEXT_MARK.length).startsWith("---");}},{key:"partialRenderNewParagraph",value:function partialRenderNewParagraph(e){this._partialText="",this._partialBubble=document.createElement("div"),this._partialBubble.classList.add("partial-render-message"),e.appendChild(this._partialBubble);}},{key:"partialRenderBubbleUpdate",value:function partialRenderBubbleUpdate(e){this._partialText+=e,this._messages.renderText(this._partialBubble,this._partialText);}},{key:"updateHTML",value:function updateHTML(e,t,s){if(this._message)if(s)this._message.html=e,t.innerHTML=e;else{var i=document.createElement("span");i.innerHTML=e,t.appendChild(i),this._message.html=(t==null?void 0:t.innerHTML)||"";}}},{key:"finaliseStreamedMessage",value:function finaliseStreamedMessage(){var e,t;if(!(this._endStreamAfterOperation||!this._message)&&!(this._fileAdded&&!this._elements)){if(!this._elements)throw Error(b.NO_VALID_STREAM_EVENTS_SENT);(e=this._elements.bubbleElement)!=null&&e.classList.contains(Ne.MESSAGE_CLASS)&&(this._streamType==="text"?this._messages.textToSpeech&&Bt.speak(this._message.text||"",this._messages.textToSpeech):this._streamType==="html"&&this._elements&&ae.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement.classList.remove(Ne.MESSAGE_CLASS),this._message&&(this._messages.sendClientUpdate(Ae.createMessageContent(this._message),!1),(t=this._messages.browserStorage)==null||t.addMessages(this._messages.messageToElements.map(function(_ref8){var _ref9=_slicedToArray(_ref8,1),s=_ref9[0];return s;}))),this._hasStreamEnded=!0);}}},{key:"markFileAdded",value:function markFileAdded(){this._fileAdded=!0;}// prettier-ignore
99
- },{key:"endStreamAfterFileDownloaded",value:function(){var _endStreamAfterFileDownloaded=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(e,t){var _yield$t,s,i;return _regenerator().w(function(_context2){while(1)switch(_context2.n){case 0:this._endStreamAfterOperation=!0;_context2.n=1;return t();case 1:_yield$t=_context2.v;s=_yield$t.text;i=_yield$t.files;s&&this.updateBasedOnType(s,"text",!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),i&&e.addNewMessage({files:i});case 2:return _context2.a(2);}},_callee2,this);}));function endStreamAfterFileDownloaded(_x3,_x4){return _endStreamAfterFileDownloaded.apply(this,arguments);}return endStreamAfterFileDownloaded;}()}],[{key:"isFocusModeScrollAllowed",value:function isFocusModeScrollAllowed(e){return _typeof(e)=="object"&&typeof e.preventStreamScroll=="boolean"&&!e.preventStreamScroll;}}]);}();Ne.MESSAGE_CLASS="streamed-message",Ne.PARTIAL_RENDER_TEXT_MARK="\n\n";var Ue=Ne;var w=/*#__PURE__*/function(){function w(){_classCallCheck(this,w);}return _createClass(w,null,[{key:"tempRemoveContentHeader",value:// need to pass stringifyBody boolean separately as binding is throwing an error for some reason
98
+ },{key:"setTargetWrapperIfNeeded",value:function setTargetWrapperIfNeeded(e,t,s,i){e.bubbleElement.innerHTML=i,this._targetWrapper=le.getTargetWrapper(e.bubbleElement),this._elements&&le.apply(this._messages,this._elements.bubbleElement),this.updateBasedOnType(t,s);}},{key:"updateBasedOnType",value:function updateBasedOnType(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var o;var i=this._targetWrapper||((o=this._elements)==null?void 0:o.bubbleElement);this._partialRender||v.unfillEmptyMessageElement(i,e),(t==="text"?this.updateText:this.updateHTML).bind(this)(e,i,s);}},{key:"updateText",value:function updateText(e,t,s){this._message&&(this._message.text=s?e:this._message.text+e,this._partialRender&&this.isNewPartialRenderParagraph(t,s)&&this.partialRenderNewParagraph(t),this._partialBubble?this.partialRenderBubbleUpdate(e):this._messages.renderText(t,this._message.text));}},{key:"isNewPartialRenderParagraph",value:function isNewPartialRenderParagraph(e,t){var s;return t?(e.innerHTML="",!0):this._partialBubble?this._partialText&&this.shouldCreateNewParagraph(this._partialText):((s=this._message)==null?void 0:s.text)&&this.shouldCreateNewParagraph(this._message.text);}},{key:"shouldCreateNewParagraph",value:function shouldCreateNewParagraph(e){var t=e.indexOf(Ne.PARTIAL_RENDER_TEXT_MARK);return t===-1?!1:!e.substring(t+Ne.PARTIAL_RENDER_TEXT_MARK.length).startsWith("---");}},{key:"partialRenderNewParagraph",value:function partialRenderNewParagraph(e){this._partialText="",this._partialBubble=document.createElement("div"),this._partialBubble.classList.add("partial-render-message"),e.appendChild(this._partialBubble);}},{key:"partialRenderBubbleUpdate",value:function partialRenderBubbleUpdate(e){this._partialText+=e,this._messages.renderText(this._partialBubble,this._partialText);}},{key:"updateHTML",value:function updateHTML(e,t,s){if(this._message)if(s)this._message.html=e,t.innerHTML=e;else{var i=document.createElement("span");i.innerHTML=e,t.appendChild(i),this._message.html=(t==null?void 0:t.innerHTML)||"";}}},{key:"finaliseStreamedMessage",value:function finaliseStreamedMessage(){var e,t;if(!(this._endStreamAfterOperation||!this._message)&&!(this._fileAdded&&!this._elements)){if(!this._elements)throw Error(b.NO_VALID_STREAM_EVENTS_SENT);(e=this._elements.bubbleElement)!=null&&e.classList.contains(Ne.MESSAGE_CLASS)&&(this._streamType==="text"?this._messages.textToSpeech&&Bt.speak(this._message.text||"",this._messages.textToSpeech):this._streamType==="html"&&this._elements&&le.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement.classList.remove(Ne.MESSAGE_CLASS),this._message&&(this._messages.sendClientUpdate(Ae.createMessageContent(this._message),!1),(t=this._messages.browserStorage)==null||t.addMessages(this._messages.messageToElements.map(function(_ref8){var _ref9=_slicedToArray(_ref8,1),s=_ref9[0];return s;}))),this._hasStreamEnded=!0);}}},{key:"markFileAdded",value:function markFileAdded(){this._fileAdded=!0;}// prettier-ignore
99
+ },{key:"endStreamAfterFileDownloaded",value:function(){var _endStreamAfterFileDownloaded=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(e,t){var _yield$t,s,i;return _regenerator().w(function(_context2){while(1)switch(_context2.n){case 0:this._endStreamAfterOperation=!0;_context2.n=1;return t();case 1:_yield$t=_context2.v;s=_yield$t.text;i=_yield$t.files;s&&this.updateBasedOnType(s,"text",!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),i&&e.addNewMessage({files:i});case 2:return _context2.a(2);}},_callee2,this);}));function endStreamAfterFileDownloaded(_x3,_x4){return _endStreamAfterFileDownloaded.apply(this,arguments);}return endStreamAfterFileDownloaded;}()}],[{key:"isFocusModeScrollAllowed",value:function isFocusModeScrollAllowed(e){return _typeof(e)=="object"&&typeof e.streamAutoScroll=="boolean"&&!e.streamAutoScroll;}}]);}();Ne.MESSAGE_CLASS="streamed-message",Ne.PARTIAL_RENDER_TEXT_MARK="\n\n";var Ue=Ne;var w=/*#__PURE__*/function(){function w(){_classCallCheck(this,w);}return _createClass(w,null,[{key:"tempRemoveContentHeader",value:// need to pass stringifyBody boolean separately as binding is throwing an error for some reason
100
100
  // prettier-ignore
101
101
  function(){var _tempRemoveContentHeader=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(e,t,s){var i,n,_t2;return _regenerator().w(function(_context3){while(1)switch(_context3.p=_context3.n){case 0:if(e!=null&&e.headers){_context3.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:i=e.headers[R];delete e.headers[R];_context3.p=2;_context3.n=3;return t(s);case 3:n=_context3.v;_context3.n=5;break;case 4:_context3.p=4;_t2=_context3.v;throw e.headers[R]=i,_t2;case 5:return _context3.a(2,(e.headers[R]=i,n));}},_callee3,null,[[2,4]]);}));function tempRemoveContentHeader(_x9,_x0,_x1){return _tempRemoveContentHeader.apply(this,arguments);}return tempRemoveContentHeader;}()},{key:"displayError",value:function displayError(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"Service error, please try again.";if(console.error(t),_typeof(t)===T)return t instanceof Error?e.addNewErrorMessage(B,t.message):Array.isArray(t)||typeof t.error=="string"?e.addNewErrorMessage(B,t):Object.keys(t).length===0?e.addNewErrorMessage(B,s):e.addNewErrorMessage(B,JSON.stringify(t));e.addNewErrorMessage(B,t);}// eslint-disable-next-line @typescript-eslint/no-explicit-any
102
102
  },{key:"fetch",value:function(_fetch){function fetch(_x5,_x6,_x7,_x8){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(e,t,s,i){var o,a;var n={method:((o=e.connectSettings)==null?void 0:o.method)||Z,headers:t};return n.method!==z&&(n.body=s?JSON.stringify(i):i),e.connectSettings.credentials&&(n.credentials=e.connectSettings.credentials),fetch(((a=e.connectSettings)==null?void 0:a.url)||e.url||"",n);})},{key:"processResponseByType",value:function processResponseByType(e){var t=e.headers.get("content-type");return t!=null&&t.includes(N)?e.json():t!=null&&t.includes("text/plain")||!t?e:e.blob();}},{key:"processRequestInterceptor",value:function(){var _processRequestInterceptor=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(e,t){var o,s,i,n,_t3;return _regenerator().w(function(_context4){while(1)switch(_context4.n){case 0:_context4.n=1;return(o=e.requestInterceptor)==null?void 0:o.call(e,t);case 1:_t3=_context4.v;if(_t3){_context4.n=2;break;}_t3=t;case 2:s=_t3;i=s;n=s;return _context4.a(2,{body:i.body,headers:i.headers,error:n.error});}},_callee4);}));function processRequestInterceptor(_x10,_x11){return _processRequestInterceptor.apply(this,arguments);}return processRequestInterceptor;}()},{key:"validateResponseFormat",value:function validateResponseFormat(e,t){if(!e)return!1;var s=Array.isArray(e)?e:[e];return t&&s.length>1?(console.error(b.INVALID_STREAM_ARRAY_RESPONSE),!1):!s.find(function(n){return _typeof(n)!="object"||!(typeof n.error=="string"||typeof n.text=="string"||typeof n.html=="string"||Array.isArray(n.files));});}},{key:"onInterceptorError",value:function onInterceptorError(e,t,s){e.addNewErrorMessage(B,t),s==null||s();}// prettier-ignore
103
- },{key:"basicResponseProcessing",value:function(){var _basicResponseProcessing=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(e,t){var s,i,_s$displayError,n,_s$useRI,o,a,l,c,d,_args5=arguments,_t4;return _regenerator().w(function(_context5){while(1)switch(_context5.n){case 0:s=_args5.length>2&&_args5[2]!==undefined?_args5[2]:{};i=s.io,_s$displayError=s.displayError,n=_s$displayError===void 0?!0:_s$displayError,_s$useRI=s.useRI,o=_s$useRI===void 0?!0:_s$useRI;if(i!=null&&i.extractResultData){_context5.n=1;break;}return _context5.a(2,t);case 1:a=o?i.deepChat.responseInterceptor:void 0;_context5.n=2;return a==null?void 0:a(t);case 2:_t4=_context5.v;if(_t4){_context5.n=3;break;}_t4=t;case 3:l=_t4;_context5.n=4;return i.extractResultData(l);case 4:c=_context5.v;if(!(!c||_typeof(c)!="object"&&!Array.isArray(c))){_context5.n=5;break;}if(n){d=b.INVALID_RESPONSE(t,"response",!!a,l);w.displayError(e,d);}return _context5.a(2);case 5:return _context5.a(2,c);}},_callee5);}));function basicResponseProcessing(_x12,_x13){return _basicResponseProcessing.apply(this,arguments);}return basicResponseProcessing;}()}]);}();function Ta(_x14,_x15){return _Ta.apply(this,arguments);}function _Ta(){_Ta=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee182(r,e){var t,s;return _regenerator().w(function(_context182){while(1)switch(_context182.n){case 0:t=r.getReader();case 1:_context182.n=2;return t.read();case 2:if((s=_context182.v).done){_context182.n=4;break;}e(s.value);case 3:_context182.n=1;break;case 4:return _context182.a(2);}},_callee182);}));return _Ta.apply(this,arguments);}function Ra(r){var e,t,s,i=!1;return function(o){e===void 0?(e=o,t=0,s=-1):e=Ia(e,o);var a=e.length;var l=0;for(;t<a;){i&&(e[t]===10&&(l=++t),i=!1);var c=-1;for(;t<a&&c===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-l);break;case 13:i=!0;case 10:c=t;break;}if(c===-1)break;r(e.subarray(l,c),s),l=t,s=-1;}l===a?e=void 0:l!==0&&(e=e.subarray(l),t-=l);};}function Ma(r,e,t){var s=Fn();var i=new TextDecoder();return function(o,a){if(o.length===0)t==null||t(s),s=Fn();else if(a>0){var l=i.decode(o.subarray(0,a)),c=a+(o[a+1]===32?2:1),d=i.decode(o.subarray(c));switch(l){case"data":s.data=s.data?s.data+"\n"+d:d;break;case"event":s.event=d;break;case"id":r(s.id=d);break;case"retry":var u=parseInt(d,10);isNaN(u)||e(s.retry=u);break;}}};}function Ia(r,e){var t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t;}function Fn(){return{data:"",event:"",id:"",retry:void 0};}var ka=function ka(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t;};var Ui="text/event-stream",La=1e3,Un="last-event-id";function Oa(r,e){var t=e.signal,s=e.headers,i=e.onopen,n=e.onmessage,o=e.onclose,a=e.onerror,l=e.openWhenHidden,c=e.fetch,d=ka(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(function(u,h){var f=Object.assign({},s);f.accept||(f.accept=Ui);var m;function p(){m.abort(),document.hidden||ie();}l||document.addEventListener("visibilitychange",p);var g=La,E=0;function I(){document.removeEventListener("visibilitychange",p),window.clearTimeout(E),m.abort();}t==null||t.addEventListener("abort",function(){I(),u();});var P=c!==null&&c!==void 0?c:window.fetch,D=i!==null&&i!==void 0?i:Na;function ie(){return _ie.apply(this,arguments);}function _ie(){_ie=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(){var st,it,me,_t5;return _regenerator().w(function(_context6){while(1)switch(_context6.p=_context6.n){case 0:m=new AbortController();_context6.p=1;_context6.n=2;return P(r,Object.assign(Object.assign({},d),{headers:f,signal:m.signal}));case 2:it=_context6.v;_context6.n=3;return D(it);case 3:_context6.n=4;return Ta(it.body,Ra(Ma(function(me){me?f[Un]=me:delete f[Un];},function(me){g=me;},n)));case 4:o==null||o();I();u();_context6.n=6;break;case 5:_context6.p=5;_t5=_context6.v;if(!m.signal.aborted)try{me=(st=a==null?void 0:a(_t5))!==null&&st!==void 0?st:g;window.clearTimeout(E),E=window.setTimeout(ie,me);}catch(me){I(),h(me);}case 6:return _context6.a(2);}},_callee6,null,[[1,5]]);}));return _ie.apply(this,arguments);}ie();});}function Na(r){var e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(Ui)))throw new Error("Expected content-type to be ".concat(Ui,", Actual: ").concat(e));}var M=/*#__PURE__*/function(){function M(){_classCallCheck(this,M);}return _createClass(M,null,[{key:"request",value:// prettier-ignore
103
+ },{key:"basicResponseProcessing",value:function(){var _basicResponseProcessing=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(e,t){var s,i,_s$displayError,n,_s$useRI,o,a,l,c,d,_args5=arguments,_t4;return _regenerator().w(function(_context5){while(1)switch(_context5.n){case 0:s=_args5.length>2&&_args5[2]!==undefined?_args5[2]:{};i=s.io,_s$displayError=s.displayError,n=_s$displayError===void 0?!0:_s$displayError,_s$useRI=s.useRI,o=_s$useRI===void 0?!0:_s$useRI;if(i!=null&&i.extractResultData){_context5.n=1;break;}return _context5.a(2,t);case 1:a=o?i.deepChat.responseInterceptor:void 0;_context5.n=2;return a==null?void 0:a(t);case 2:_t4=_context5.v;if(_t4){_context5.n=3;break;}_t4=t;case 3:l=_t4;_context5.n=4;return i.extractResultData(l);case 4:c=_context5.v;if(!(!c||_typeof(c)!="object"&&!Array.isArray(c))){_context5.n=5;break;}if(n){d=b.INVALID_RESPONSE(t,"response",!!a,l);w.displayError(e,d);}return _context5.a(2);case 5:return _context5.a(2,c);}},_callee5);}));function basicResponseProcessing(_x12,_x13){return _basicResponseProcessing.apply(this,arguments);}return basicResponseProcessing;}()}]);}();function Ta(_x14,_x15){return _Ta.apply(this,arguments);}function _Ta(){_Ta=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee182(r,e){var t,s;return _regenerator().w(function(_context182){while(1)switch(_context182.n){case 0:t=r.getReader();case 1:_context182.n=2;return t.read();case 2:if((s=_context182.v).done){_context182.n=4;break;}e(s.value);case 3:_context182.n=1;break;case 4:return _context182.a(2);}},_callee182);}));return _Ta.apply(this,arguments);}function Ra(r){var e,t,s,i=!1;return function(o){e===void 0?(e=o,t=0,s=-1):e=Ia(e,o);var a=e.length;var l=0;for(;t<a;){i&&(e[t]===10&&(l=++t),i=!1);var c=-1;for(;t<a&&c===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-l);break;case 13:i=!0;case 10:c=t;break;}if(c===-1)break;r(e.subarray(l,c),s),l=t,s=-1;}l===a?e=void 0:l!==0&&(e=e.subarray(l),t-=l);};}function Ma(r,e,t){var s=Fn();var i=new TextDecoder();return function(o,a){if(o.length===0)t==null||t(s),s=Fn();else if(a>0){var l=i.decode(o.subarray(0,a)),c=a+(o[a+1]===32?2:1),d=i.decode(o.subarray(c));switch(l){case"data":s.data=s.data?s.data+"\n"+d:d;break;case"event":s.event=d;break;case"id":r(s.id=d);break;case"retry":var u=parseInt(d,10);isNaN(u)||e(s.retry=u);break;}}};}function Ia(r,e){var t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t;}function Fn(){return{data:"",event:"",id:"",retry:void 0};}var ka=function ka(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t;};var Ui="text/event-stream",La=1e3,Un="last-event-id";function Oa(r,e){var t=e.signal,s=e.headers,i=e.onopen,n=e.onmessage,o=e.onclose,a=e.onerror,l=e.openWhenHidden,c=e.fetch,d=ka(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(function(u,h){var f=Object.assign({},s);f.accept||(f.accept=Ui);var m;function p(){m.abort(),document.hidden||ne();}l||document.addEventListener("visibilitychange",p);var g=La,E=0;function I(){document.removeEventListener("visibilitychange",p),window.clearTimeout(E),m.abort();}t==null||t.addEventListener("abort",function(){I(),u();});var P=c!==null&&c!==void 0?c:window.fetch,D=i!==null&&i!==void 0?i:Na;function ne(){return _ne.apply(this,arguments);}function _ne(){_ne=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(){var st,it,me,_t5;return _regenerator().w(function(_context6){while(1)switch(_context6.p=_context6.n){case 0:m=new AbortController();_context6.p=1;_context6.n=2;return P(r,Object.assign(Object.assign({},d),{headers:f,signal:m.signal}));case 2:it=_context6.v;_context6.n=3;return D(it);case 3:_context6.n=4;return Ta(it.body,Ra(Ma(function(me){me?f[Un]=me:delete f[Un];},function(me){g=me;},n)));case 4:o==null||o();I();u();_context6.n=6;break;case 5:_context6.p=5;_t5=_context6.v;if(!m.signal.aborted)try{me=(st=a==null?void 0:a(_t5))!==null&&st!==void 0?st:g;window.clearTimeout(E),E=window.setTimeout(ne,me);}catch(me){I(),h(me);}case 6:return _context6.a(2);}},_callee6,null,[[1,5]]);}));return _ne.apply(this,arguments);}ne();});}function Na(r){var e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(Ui)))throw new Error("Expected content-type to be ".concat(Ui,", Actual: ").concat(e));}var M=/*#__PURE__*/function(){function M(){_classCallCheck(this,M);}return _createClass(M,null,[{key:"request",value:// prettier-ignore
104
104
  function(){var _request=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(e,t,s){var i,n,h,f,m,p,g,o,_yield$w$processReque,a,l,c,d,u,_args7=arguments;return _regenerator().w(function(_context7){while(1)switch(_context7.n){case 0:i=_args7.length>3&&_args7[3]!==undefined?_args7[3]:!0;n=_args7.length>4&&_args7[4]!==undefined?_args7[4]:!1;o={body:t,headers:(h=e.connectSettings)==null?void 0:h.headers};_context7.n=1;return w.processRequestInterceptor(e.deepChat,o);case 1:_yield$w$processReque=_context7.v;a=_yield$w$processReque.body;l=_yield$w$processReque.headers;c=_yield$w$processReque.error;if(!c){_context7.n=2;break;}return _context7.a(2,w.onInterceptorError(s,c,e.streamHandlers.onClose));case 2:if(!((f=e.connectSettings)!=null&&f.handler)){_context7.n=3;break;}return _context7.a(2,ke.stream(e,a,s));case 3:if(!(((m=e.connectSettings)==null?void 0:m.url)===Oe.URL)){_context7.n=4;break;}return _context7.a(2,Oe.requestStream(s,e));case 4:d=new Ue(s,e.stream),u={method:((p=e.connectSettings)==null?void 0:p.method)||Z,headers:l,credentials:(g=e.connectSettings)==null?void 0:g.credentials,body:i?JSON.stringify(a):a};return _context7.a(2,(_typeof(e.stream)=="object"&&e.stream.readable?M.handleReadableStream(e,s,d,u,n,a):M.handleEventStream(e,s,d,u,n,a),d));}},_callee7);}));function request(_x16,_x17,_x18){return _request.apply(this,arguments);}return request;}()// prettier-ignore
105
- },{key:"handleReadableStream",value:function handleReadableStream(e,t,s,i,n,o){var d;var _e$streamHandlers=e.streamHandlers,a=_e$streamHandlers.onOpen,l=_e$streamHandlers.onClose;var c=!1;fetch(((d=e.connectSettings)==null?void 0:d.url)||e.url||"",i).then(/*#__PURE__*/function(){var _ref0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(u){var p,g,h,f,m,_yield$h$read,E,I,P,D,ie,_t6;return _regenerator().w(function(_context8){while(1)switch(_context8.n){case 0:if(u.body){_context8.n=1;break;}throw new Error(b.READABLE_STREAM_CONNECTION_ERROR);case 1:h=u.body.getReader(),f=new TextDecoder();a();m=!1;case 2:if(!(!m&&!c)){_context8.n=8;break;}_context8.n=3;return h.read();case 3:_yield$h$read=_context8.v;E=_yield$h$read.value;I=_yield$h$read.done;if(!(m=I,m)){_context8.n=4;break;}M.handleClose(e,s,l,n);_context8.n=7;break;case 4:P=f.decode(E,{stream:!0});_context8.n=5;return(g=(p=e.deepChat).responseInterceptor)==null?void 0:g.call(p,P);case 5:_t6=_context8.v;if(_t6){_context8.n=6;break;}_t6=P;case 6:D=_t6;ie=_typeof(D)=="object"?D:_defineProperty({},y,P);M.handleMessage(e,t,s,ie,o);case 7:_context8.n=2;break;case 8:return _context8.a(2);}},_callee8);}));return function(_x19){return _ref0.apply(this,arguments);};}())["catch"](function(u){M.handleError(e,t,u);}),e.streamHandlers.onAbort=function(){s.finaliseStreamedMessage(),e.streamHandlers.onClose(),c=!0;};}// prettier-ignore
105
+ },{key:"handleReadableStream",value:function handleReadableStream(e,t,s,i,n,o){var d;var _e$streamHandlers=e.streamHandlers,a=_e$streamHandlers.onOpen,l=_e$streamHandlers.onClose;var c=!1;fetch(((d=e.connectSettings)==null?void 0:d.url)||e.url||"",i).then(/*#__PURE__*/function(){var _ref0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(u){var p,g,h,f,m,_yield$h$read,E,I,P,D,ne,_t6;return _regenerator().w(function(_context8){while(1)switch(_context8.n){case 0:if(u.body){_context8.n=1;break;}throw new Error(b.READABLE_STREAM_CONNECTION_ERROR);case 1:h=u.body.getReader(),f=new TextDecoder();a();m=!1;case 2:if(!(!m&&!c)){_context8.n=8;break;}_context8.n=3;return h.read();case 3:_yield$h$read=_context8.v;E=_yield$h$read.value;I=_yield$h$read.done;if(!(m=I,m)){_context8.n=4;break;}M.handleClose(e,s,l,n);_context8.n=7;break;case 4:P=f.decode(E,{stream:!0});_context8.n=5;return(g=(p=e.deepChat).responseInterceptor)==null?void 0:g.call(p,P);case 5:_t6=_context8.v;if(_t6){_context8.n=6;break;}_t6=P;case 6:D=_t6;ne=_typeof(D)=="object"?D:_defineProperty({},y,P);M.handleMessage(e,t,s,ne,o);case 7:_context8.n=2;break;case 8:return _context8.a(2);}},_callee8);}));return function(_x19){return _ref0.apply(this,arguments);};}())["catch"](function(u){M.handleError(e,t,u);}),e.streamHandlers.onAbort=function(){s.finaliseStreamedMessage(),e.streamHandlers.onClose(),c=!0;};}// prettier-ignore
106
106
  },{key:"handleEventStream",value:function handleEventStream(e,t,s,i,n,o){var d;var _e$streamHandlers2=e.streamHandlers,a=_e$streamHandlers2.onOpen,l=_e$streamHandlers2.onClose,c=new AbortController();e.streamHandlers.onAbort=function(){s.finaliseStreamedMessage(),e.streamHandlers.onClose(),c.abort();},Oa(((d=e.connectSettings)==null?void 0:d.url)||e.url||"",_objectSpread(_objectSpread({},i),{},{openWhenHidden:!0,// keep stream open when browser tab not open
107
107
  onopen:function onopen(u){return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(){return _regenerator().w(function(_context9){while(1)switch(_context9.n){case 0:if(!u.ok){_context9.n=1;break;}return _context9.a(2,a());case 1:_context9.n=2;return w.processResponseByType(u);case 2:throw _context9.v;case 3:return _context9.a(2);}},_callee9);}))();},onmessage:function onmessage(u){return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(){var h,f,m,p,_t7;return _regenerator().w(function(_context0){while(1)switch(_context0.n){case 0:if(!(JSON.stringify(u.data)!==JSON.stringify("[DONE]"))){_context0.n=3;break;}try{m=JSON.parse(u.data);}catch(_unused6){m={};}_context0.n=1;return(f=(h=e.deepChat).responseInterceptor)==null?void 0:f.call(h,m);case 1:_t7=_context0.v;if(_t7){_context0.n=2;break;}_t7=m;case 2:p=_t7;M.handleMessage(e,t,s,p,o);case 3:return _context0.a(2);}},_callee0);}))();},onerror:function onerror(u){throw l(),u;},onclose:function onclose(){M.handleClose(e,s,l,n);},signal:c.signal}))["catch"](function(u){M.handleError(e,t,u);});}//prettier-ignore
108
108
  },{key:"handleMessage",value:function handleMessage(e,t,s,i,n){var o;(o=e.extractResultData)==null||o.call(e,i,n).then(function(a){M.upsertContent(t,s.upsertStreamedMessage.bind(s),s,a),t.removeError();})["catch"](function(a){t.isLastMessageError()||w.displayError(t,a);});}// eslint-disable-next-line @typescript-eslint/no-explicit-any
109
109
  },{key:"handleError",value:function handleError(e,t,s){var i;t.isLastMessageError()||(i=e.extractResultData)==null||i.call(e,s).then(function(){w.displayError(t,s);})["catch"](function(n){w.displayError(t,n);});}},{key:"handleClose",value:function handleClose(e,t,s,i){if(e.asyncCallInProgress){e.asyncCallInProgress=!1;return;}try{t.finaliseStreamedMessage(),s();}catch(n){if(!i)throw n;}}// io is only passed for demo to simulate a real stream
110
- },{key:"simulate",value:function(){var _simulate=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(e,t,s,i){var n,_n2,o,_n3,_o2;return _regenerator().w(function(_context1){while(1)switch(_context1.n){case 0:_context1.n=1;return w.basicResponseProcessing(e,s,{io:i,useRI:!1});case 1:if(_context1.v){_context1.n=2;break;}return _context1.a(2,t.onClose());case 2:if(!(Array.isArray(s)&&(s=s[0]),s.files)){_context1.n=4;break;}_context1.n=3;return w.basicResponseProcessing(e,{files:s.files},{io:i});case 3:n=_context1.v;e.addNewMessage(_objectSpread({sendUpdate:!1},n),!1);case 4:if(s.text){t.onOpen();_n2=s.text.split(""),o=new Ue(e,i==null?void 0:i.stream);M.populateMessages(e,_n2,o,t,"text",0,i);}if(s.html){t.onOpen();_n3=ae.splitHTML(s.html);_n3.length===0&&(_n3=s.html.split(""));_o2=new Ue(e,i==null?void 0:i.stream);M.populateMessages(e,_n3,_o2,t,"html",0,i);}s.error&&(w.displayError(e,s.error),t.onClose()),t.onAbort=function(){t.onClose();};case 5:return _context1.a(2);}},_callee1);}));function simulate(_x20,_x21,_x22,_x23){return _simulate.apply(this,arguments);}return simulate;}()// prettier-ignore
110
+ },{key:"simulate",value:function(){var _simulate=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(e,t,s,i){var n,_n2,o,_n3,_o2;return _regenerator().w(function(_context1){while(1)switch(_context1.n){case 0:_context1.n=1;return w.basicResponseProcessing(e,s,{io:i,useRI:!1});case 1:if(_context1.v){_context1.n=2;break;}return _context1.a(2,t.onClose());case 2:if(!(Array.isArray(s)&&(s=s[0]),s.files)){_context1.n=4;break;}_context1.n=3;return w.basicResponseProcessing(e,{files:s.files},{io:i});case 3:n=_context1.v;e.addNewMessage(_objectSpread({sendUpdate:!1},n),!1);case 4:if(s.text){t.onOpen();_n2=s.text.split(""),o=new Ue(e,i==null?void 0:i.stream);M.populateMessages(e,_n2,o,t,"text",0,i);}if(s.html){t.onOpen();_n3=le.splitHTML(s.html);_n3.length===0&&(_n3=s.html.split(""));_o2=new Ue(e,i==null?void 0:i.stream);M.populateMessages(e,_n3,_o2,t,"html",0,i);}s.error&&(w.displayError(e,s.error),t.onClose()),t.onAbort=function(){t.onClose();};case 5:return _context1.a(2);}},_callee1);}));function simulate(_x20,_x21,_x22,_x23){return _simulate.apply(this,arguments);}return simulate;}()// prettier-ignore
111
111
  // io is only passed for demo to simulate a real stream
112
112
  },{key:"populateMessages",value:function(){var _populateMessages=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(e,t,s,i,n,o,a){var l,d,c,_t8;return _regenerator().w(function(_context10){while(1)switch(_context10.p=_context10.n){case 0:l=t[o];if(!l){_context10.n=5;break;}_context10.p=1;_context10.n=2;return w.basicResponseProcessing(e,_defineProperty({},n,l),{io:a});case 2:d=_context10.v;M.upsertContent(e,s.upsertStreamedMessage.bind(s),s,d),e.removeError();_context10.n=4;break;case 3:_context10.p=3;_t8=_context10.v;e.isLastMessageError()||w.displayError(e,_t8);case 4:c=setTimeout(function(){M.populateMessages(e,t,s,i,n,o+1,a);},i.simulationInterim||6);i.onAbort=function(){M.abort(c,s,i.onClose);};_context10.n=6;break;case 5:s.finaliseStreamedMessage(),i.onClose();case 6:return _context10.a(2);}},_callee10,null,[[1,3]]);}));function populateMessages(_x24,_x25,_x26,_x27,_x28,_x29,_x30){return _populateMessages.apply(this,arguments);}return populateMessages;}()},{key:"isSimulation",value:function isSimulation(e){return _typeof(e)=="object"&&!!e.simulation;}},{key:"isSimulatable",value:function isSimulatable(e,t){return M.isSimulation(e)&&t&&(t.text||t.html);}},{key:"abort",value:function abort(e,t,s){clearTimeout(e),t.finaliseStreamedMessage(),s();}},{key:"upsertContent",value:function upsertContent(e,t,s,i){if(i&&Array.isArray(i)&&(i=i[0]),i!=null&&i.text||i!=null&&i.html){var n=t(i);s!==null&&s!==void 0?s:s=n||void 0;}if(i!=null&&i.files&&(e.addNewMessage({files:i.files}),s==null||s.markFileAdded()),i!=null&&i.error)throw i.error;}}]);}();var bt=/*#__PURE__*/function(){function bt(){_classCallCheck(this,bt);}return _createClass(bt,null,[{key:"generateResponse",value:function generateResponse(e){var t=e[e.length-1][0];if(t.files&&t.files.length>0){if(t.files.length>1)return"These are interesting files!";var s=t.files[0];return s.src&&s.src.startsWith("data:image/gif")?"That is a nice gif!":s.type==="image"?"That is a nice image!":s.type==="audio"?"I like the sound of that!":"That is an interesting file!";}if(t.text){if(t.text.charAt(t.text.length-1)==="?")return"I'm sorry but I can't answer that question...";if(t.text.includes("updog"))return"What's updog?";}return"Hi there! This is a demo response!";}},{key:"getCustomResponse",value:function getCustomResponse(e,t){return typeof e=="function"?e(t):e;}},{key:"getResponse",value:function getResponse(_ref10){var e=_ref10.customDemoResponse,t=_ref10.messageToElements;return e?bt.getCustomResponse(e,t[t.length-1][0]):_defineProperty({},y,bt.generateResponse(t));}// timeout is used to simulate a timeout for a response to come back
113
113
  },{key:"request",value:function request(e,t){var s=bt.getResponse(t);setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(){var i,n,o;return _regenerator().w(function(_context11){while(1)switch(_context11.n){case 0:_context11.n=1;return w.basicResponseProcessing(t,s,{io:e});case 1:i=_context11.v;if(i){_context11.n=2;break;}return _context11.a(2,e.completionsHandlers.onFinish());case 2:n=Array.isArray(i)?i:[i],o=n.find(function(a){return typeof a.error=="string";});o?(t.addNewErrorMessage(B,o.error),e.completionsHandlers.onFinish()):M.isSimulatable(e.stream,i)?M.simulate(t,e.streamHandlers,i):(n.forEach(function(a){return t.addNewMessage(a);}),e.completionsHandlers.onFinish());case 3:return _context11.a(2);}},_callee11);})),400);}// timeout is used to simulate a timeout for a response to come back
114
- },{key:"requestStream",value:function requestStream(e,t){setTimeout(function(){var s=bt.getResponse(e);M.simulate(e,t.streamHandlers,s,t);},400);}}]);}();bt.URL="deep-chat-demo";var Oe=bt;var re=/*#__PURE__*/function(){function re(){_classCallCheck(this,re);}return _createClass(re,null,[{key:"setup",value:function setup(e){e.permittedErrorPrefixes=["Connection error","Error in server message"],e.websocket="pending";}},{key:"isElementPresentInDOM",value:function isElementPresentInDOM(e){return e.getRootNode({composed:!0})instanceof Document;}},{key:"createConnection",value:function createConnection(e,t){if(!re.isElementPresentInDOM(e.deepChat))return;var s=e.connectSettings.websocket;if(s){if(e.connectSettings.handler)return ke.websocket(e,t);try{var i=typeof s!="boolean"?s:void 0,n=new WebSocket(e.connectSettings.url||"",i);e.websocket=n,e.websocket.onopen=function(){var o,a;t.removeError(),e.websocket&&_typeof(e.websocket)===T&&re.assignListeners(e,n,t),(a=(o=e.deepChat)._validationHandler)==null||a.call(o);},e.websocket.onerror=function(o){console.error(o),re.retryConnection(e,t);};}catch(i){console.error(i),re.retryConnection(e,t);}}}},{key:"retryConnection",value:function retryConnection(e,t){var s,i;(i=(s=e.deepChat)._validationHandler)==null||i.call(s),re.isElementPresentInDOM(e.deepChat)&&(e.websocket="pending",t.isLastMessageError()||t.addNewErrorMessage(B,"Connection error"),setTimeout(function(){re.createConnection(e,t);},5e3));}},{key:"assignListeners",value:function assignListeners(e,t,s){var _this8=this;var i={};t.onmessage=/*#__PURE__*/function(){var _ref13=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(n){var o,a,l,c,_l2,_c,_t9;return _regenerator().w(function(_context12){while(1)switch(_context12.p=_context12.n){case 0:if(!e.extractResultData){_context12.n=8;break;}_context12.p=1;o=JSON.parse(n.data);_context12.n=2;return w.basicResponseProcessing(s,o,{io:e,displayError:!1});case 2:a=_context12.v;if(a){_context12.n=3;break;}throw Error(b.INVALID_RESPONSE(o,"server",!!e.deepChat.responseInterceptor,a));case 3:if(!M.isSimulation(e.stream)){_context12.n=4;break;}l=re.stream.bind(_this8,e,s,i),c=i[o.role||v.AI_ROLE];M.upsertContent(s,l,c,a);_context12.n=6;break;case 4:_l2=Array.isArray(a)?a:[a],_c=_l2.find(function(d){return typeof d.error=="string";});if(!_c){_context12.n=5;break;}throw _c.error;case 5:_l2.forEach(function(d){return s.addNewMessage(d);});case 6:_context12.n=8;break;case 7:_context12.p=7;_t9=_context12.v;w.displayError(s,_t9,"Error in server message");case 8:return _context12.a(2);}},_callee12,null,[[1,7]]);}));return function(_x31){return _ref13.apply(this,arguments);};}(),t.onclose=function(){var n,o;console.error("Connection closed"),s.isLastMessageError()||s.addNewErrorMessage(B,"Connection error"),e.stream&&((o=(n=e.streamHandlers).onAbort)==null||o.call(n)),re.createConnection(e,s);};}},{key:"sendWebsocket",value:function(){var _sendWebsocket=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(e,t,s){var i,d,u,n,o,_yield$w$processReque2,a,l,c,_args13=arguments;return _regenerator().w(function(_context13){while(1)switch(_context13.n){case 0:i=_args13.length>3&&_args13[3]!==undefined?_args13[3]:!0;if(!(((d=e.connectSettings)==null?void 0:d.url)===Oe.URL)){_context13.n=1;break;}return _context13.a(2,Oe.request(e,s));case 1:n=e.websocket;if(!(!n||n==="pending")){_context13.n=2;break;}return _context13.a(2);case 2:o={body:t,headers:(u=e.connectSettings)==null?void 0:u.headers};_context13.n=3;return w.processRequestInterceptor(e.deepChat,o);case 3:_yield$w$processReque2=_context13.v;a=_yield$w$processReque2.body;l=_yield$w$processReque2.error;if(!l){_context13.n=4;break;}return _context13.a(2,s.addNewErrorMessage(B,l));case 4:if(re.isWebSocket(n)){_context13.n=5;break;}return _context13.a(2,n.newUserMessage.listener(a));case 5:c=i?JSON.stringify(a):a;n.readyState===void 0||n.readyState!==n.OPEN?(console.error("Connection is not open"),s.isLastMessageError()||s.addNewErrorMessage(B,"Connection error")):(n.send(JSON.stringify(c)),e.completionsHandlers.onFinish());case 6:return _context13.a(2);}},_callee13);}));function sendWebsocket(_x32,_x33,_x34){return _sendWebsocket.apply(this,arguments);}return sendWebsocket;}()},{key:"canSendMessage",value:function canSendMessage(e){return e?e==="pending"?!1:re.isWebSocket(e)?e.readyState!==void 0&&e.readyState===e.OPEN:e.isOpen:!0;}// if false then it is the internal websocket handler
114
+ },{key:"requestStream",value:function requestStream(e,t){setTimeout(function(){var s=bt.getResponse(e);M.simulate(e,t.streamHandlers,s,t);},400);}}]);}();bt.URL="deep-chat-demo";var Oe=bt;var oe=/*#__PURE__*/function(){function oe(){_classCallCheck(this,oe);}return _createClass(oe,null,[{key:"setup",value:function setup(e){e.permittedErrorPrefixes=["Connection error","Error in server message"],e.websocket="pending";}},{key:"isElementPresentInDOM",value:function isElementPresentInDOM(e){return e.getRootNode({composed:!0})instanceof Document;}},{key:"createConnection",value:function createConnection(e,t){if(!oe.isElementPresentInDOM(e.deepChat))return;var s=e.connectSettings.websocket;if(s){if(e.connectSettings.handler)return ke.websocket(e,t);try{var i=typeof s!="boolean"?s:void 0,n=new WebSocket(e.connectSettings.url||"",i);e.websocket=n,e.websocket.onopen=function(){var o,a;t.removeError(),e.websocket&&_typeof(e.websocket)===T&&oe.assignListeners(e,n,t),(a=(o=e.deepChat)._validationHandler)==null||a.call(o);},e.websocket.onerror=function(o){console.error(o),oe.retryConnection(e,t);};}catch(i){console.error(i),oe.retryConnection(e,t);}}}},{key:"retryConnection",value:function retryConnection(e,t){var s,i;(i=(s=e.deepChat)._validationHandler)==null||i.call(s),oe.isElementPresentInDOM(e.deepChat)&&(e.websocket="pending",t.isLastMessageError()||t.addNewErrorMessage(B,"Connection error"),setTimeout(function(){oe.createConnection(e,t);},5e3));}},{key:"assignListeners",value:function assignListeners(e,t,s){var _this8=this;var i={};t.onmessage=/*#__PURE__*/function(){var _ref13=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(n){var o,a,l,c,_l2,_c,_t9;return _regenerator().w(function(_context12){while(1)switch(_context12.p=_context12.n){case 0:if(!e.extractResultData){_context12.n=8;break;}_context12.p=1;o=JSON.parse(n.data);_context12.n=2;return w.basicResponseProcessing(s,o,{io:e,displayError:!1});case 2:a=_context12.v;if(a){_context12.n=3;break;}throw Error(b.INVALID_RESPONSE(o,"server",!!e.deepChat.responseInterceptor,a));case 3:if(!M.isSimulation(e.stream)){_context12.n=4;break;}l=oe.stream.bind(_this8,e,s,i),c=i[o.role||v.AI_ROLE];M.upsertContent(s,l,c,a);_context12.n=6;break;case 4:_l2=Array.isArray(a)?a:[a],_c=_l2.find(function(d){return typeof d.error=="string";});if(!_c){_context12.n=5;break;}throw _c.error;case 5:_l2.forEach(function(d){return s.addNewMessage(d);});case 6:_context12.n=8;break;case 7:_context12.p=7;_t9=_context12.v;w.displayError(s,_t9,"Error in server message");case 8:return _context12.a(2);}},_callee12,null,[[1,7]]);}));return function(_x31){return _ref13.apply(this,arguments);};}(),t.onclose=function(){var n,o;console.error("Connection closed"),s.isLastMessageError()||s.addNewErrorMessage(B,"Connection error"),e.stream&&((o=(n=e.streamHandlers).onAbort)==null||o.call(n)),oe.createConnection(e,s);};}},{key:"sendWebsocket",value:function(){var _sendWebsocket=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(e,t,s){var i,d,u,n,o,_yield$w$processReque2,a,l,c,_args13=arguments;return _regenerator().w(function(_context13){while(1)switch(_context13.n){case 0:i=_args13.length>3&&_args13[3]!==undefined?_args13[3]:!0;if(!(((d=e.connectSettings)==null?void 0:d.url)===Oe.URL)){_context13.n=1;break;}return _context13.a(2,Oe.request(e,s));case 1:n=e.websocket;if(!(!n||n==="pending")){_context13.n=2;break;}return _context13.a(2);case 2:o={body:t,headers:(u=e.connectSettings)==null?void 0:u.headers};_context13.n=3;return w.processRequestInterceptor(e.deepChat,o);case 3:_yield$w$processReque2=_context13.v;a=_yield$w$processReque2.body;l=_yield$w$processReque2.error;if(!l){_context13.n=4;break;}return _context13.a(2,s.addNewErrorMessage(B,l));case 4:if(oe.isWebSocket(n)){_context13.n=5;break;}return _context13.a(2,n.newUserMessage.listener(a));case 5:c=i?JSON.stringify(a):a;n.readyState===void 0||n.readyState!==n.OPEN?(console.error("Connection is not open"),s.isLastMessageError()||s.addNewErrorMessage(B,"Connection error")):(n.send(JSON.stringify(c)),e.completionsHandlers.onFinish());case 6:return _context13.a(2);}},_callee13);}));function sendWebsocket(_x32,_x33,_x34){return _sendWebsocket.apply(this,arguments);}return sendWebsocket;}()},{key:"canSendMessage",value:function canSendMessage(e){return e?e==="pending"?!1:oe.isWebSocket(e)?e.readyState!==void 0&&e.readyState===e.OPEN:e.isOpen:!0;}// if false then it is the internal websocket handler
115
115
  },{key:"isWebSocket",value:function isWebSocket(e){return e.send!==void 0;}},{key:"stream",value:function stream(e,t,s,i){if(!i)return;var n=e.stream.simulation;if(typeof n=="string"){var _s$o;var o=i.role||v.AI_ROLE,a=s[o];i.text===n||i.html===n?(a==null||a.finaliseStreamedMessage(),delete s[o]):((_s$o=s[o])!==null&&_s$o!==void 0?_s$o:s[o]=new Ue(t,e.stream),s[o].upsertStreamedMessage(i));}else M.simulate(t,e.streamHandlers,i);}}]);}();var ke=/*#__PURE__*/function(){function ke(){_classCallCheck(this,ke);}return _createClass(ke,null,[{key:"request",value:function(){var _request2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee15(e,t,s){var a,l,i,n,o;return _regenerator().w(function(_context15){while(1)switch(_context15.n){case 0:i=!0;n=/*#__PURE__*/function(){var _ref14=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(c){var d,u,h;return _regenerator().w(function(_context14){while(1)switch(_context14.n){case 0:if(i){_context14.n=1;break;}return _context14.a(2);case 1:i=!1;_context14.n=2;return w.basicResponseProcessing(s,c,{io:e,displayError:!1});case 2:d=_context14.v;if(!d)console.error(b.INVALID_RESPONSE(c,"server",!!e.deepChat.responseInterceptor,d)),s.addNewErrorMessage(B,"Error in server message"),e.completionsHandlers.onFinish();else{u=Array.isArray(d)?d:[d],h=u.find(function(f){return typeof f.error=="string";});h?(console.error(h.error),s.addNewErrorMessage(B,h.error),e.completionsHandlers.onFinish()):M.isSimulatable(e.stream,d)?M.simulate(s,e.streamHandlers,d):(u.forEach(function(f){return s.addNewMessage(f);}),e.completionsHandlers.onFinish());}case 3:return _context14.a(2);}},_callee14);}));return function n(_x38){return _ref14.apply(this,arguments);};}(),o=ke.generateOptionalSignals();(l=(a=e.connectSettings).handler)==null||l.call(a,t,_objectSpread(_objectSpread({},o),{},{onResponse:n}));case 1:return _context15.a(2);}},_callee15);}));function request(_x35,_x36,_x37){return _request2.apply(this,arguments);}return request;}()},{key:"attemptToFinaliseStream",value:function attemptToFinaliseStream(e,t){try{var s=t.messageElementRefs[t.messageElementRefs.length-1];Ae.isLoadingMessage(s)?t.removeLastMessage():e.finaliseStreamedMessage();}catch(s){console.error(s),t.addNewErrorMessage(B,s);}}// prettier-ignore
116
116
  },{key:"stream",value:function stream(e,t,s){var u,h;var i=!0,n=!1;var o=new Ue(s,e.stream),a=function a(){n||!i||(e.streamHandlers.onOpen(),n=!0);},l=function l(){i&&(ke.attemptToFinaliseStream(o,s),e.streamHandlers.onClose(),i=!1);},c=/*#__PURE__*/function(){var _ref15=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee16(f){var m,p;return _regenerator().w(function(_context16){while(1)switch(_context16.n){case 0:if(i){_context16.n=1;break;}return _context16.a(2);case 1:_context16.n=2;return w.basicResponseProcessing(s,f,{io:e,displayError:!1});case 2:m=_context16.v;if(m)m.error?(ke.streamError(m.error,o,e,s),i=!1):M.upsertContent(s,o.upsertStreamedMessage.bind(o),o,m);else{p=b.INVALID_RESPONSE(f,"server",!!e.deepChat.responseInterceptor,m);ke.streamError(p,o,e,s),i=!1;}case 3:return _context16.a(2);}},_callee16);}));return function c(_x39){return _ref15.apply(this,arguments);};}();e.streamHandlers.onAbort=function(){ke.attemptToFinaliseStream(o,s),e.streamHandlers.onClose(),i=!1;};var d=ke.generateOptionalSignals();(h=(u=e.connectSettings).handler)==null||h.call(u,t,_objectSpread(_objectSpread({},d),{},{onOpen:a,onResponse:c,onClose:l,stopClicked:e.streamHandlers.stopClicked}));}},{key:"streamError",value:function streamError(e,t,s,i){console.error(e),t.finaliseStreamedMessage(),i.addNewErrorMessage(B,e),s.streamHandlers.onClose();}// prettier-ignore
117
- },{key:"websocket",value:function websocket(e,t){var _this9=this;var l,c;var s={isOpen:!1,newUserMessage:{listener:function listener(){}},roleToStream:{}};e.websocket=s;var i=function i(){t.removeError(),s.isOpen=!0;},n=function n(){s.isOpen=!1;},o=/*#__PURE__*/function(){var _ref16=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee17(d){var u,h,f,m,p,g;return _regenerator().w(function(_context17){while(1)switch(_context17.n){case 0:_context17.n=1;return w.basicResponseProcessing(t,d,{io:e,displayError:!1});case 1:u=_context17.v;if(!u)console.error(b.INVALID_RESPONSE(d,"server",!!e.deepChat.responseInterceptor,u)),t.addNewErrorMessage(B,"Error in server message");else{h=Array.isArray(u)?u:[u],f=h.find(function(m){return typeof m.error=="string";});if(f)console.error(f.error),t.isLastMessageError()||t.addNewErrorMessage(B,f.error);else if(M.isSimulation(e.stream)){m=u,p=re.stream.bind(_this9,e,t,s.roleToStream),g=s.roleToStream[m.role||v.AI_ROLE];M.upsertContent(t,p,g,m);}else h.forEach(function(m){return t.addNewMessage(m);});}case 2:return _context17.a(2);}},_callee17);}));return function o(_x40){return _ref16.apply(this,arguments);};}(),a=ke.generateOptionalSignals();(c=(l=e.connectSettings).handler)==null||c.call(l,void 0,_objectSpread(_objectSpread({},a),{},{onOpen:i,onResponse:o,onClose:n,newUserMessage:s.newUserMessage}));}},{key:"generateOptionalSignals",value:function generateOptionalSignals(){return{onClose:function onClose(){},onOpen:function onOpen(){},stopClicked:{listener:function listener(){}},newUserMessage:{listener:function listener(){}}};}}]);}();var V=/*#__PURE__*/function(){function V(){_classCallCheck(this,V);}return _createClass(V,null,[{key:"request",value:// prettier-ignore
117
+ },{key:"websocket",value:function websocket(e,t){var _this9=this;var l,c;var s={isOpen:!1,newUserMessage:{listener:function listener(){}},roleToStream:{}};e.websocket=s;var i=function i(){t.removeError(),s.isOpen=!0;},n=function n(){s.isOpen=!1;},o=/*#__PURE__*/function(){var _ref16=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee17(d){var u,h,f,m,p,g;return _regenerator().w(function(_context17){while(1)switch(_context17.n){case 0:_context17.n=1;return w.basicResponseProcessing(t,d,{io:e,displayError:!1});case 1:u=_context17.v;if(!u)console.error(b.INVALID_RESPONSE(d,"server",!!e.deepChat.responseInterceptor,u)),t.addNewErrorMessage(B,"Error in server message");else{h=Array.isArray(u)?u:[u],f=h.find(function(m){return typeof m.error=="string";});if(f)console.error(f.error),t.isLastMessageError()||t.addNewErrorMessage(B,f.error);else if(M.isSimulation(e.stream)){m=u,p=oe.stream.bind(_this9,e,t,s.roleToStream),g=s.roleToStream[m.role||v.AI_ROLE];M.upsertContent(t,p,g,m);}else h.forEach(function(m){return t.addNewMessage(m);});}case 2:return _context17.a(2);}},_callee17);}));return function o(_x40){return _ref16.apply(this,arguments);};}(),a=ke.generateOptionalSignals();(c=(l=e.connectSettings).handler)==null||c.call(l,void 0,_objectSpread(_objectSpread({},a),{},{onOpen:i,onResponse:o,onClose:n,newUserMessage:s.newUserMessage}));}},{key:"generateOptionalSignals",value:function generateOptionalSignals(){return{onClose:function onClose(){},onOpen:function onOpen(){},stopClicked:{listener:function listener(){}},newUserMessage:{listener:function listener(){}}};}}]);}();var V=/*#__PURE__*/function(){function V(){_classCallCheck(this,V);}return _createClass(V,null,[{key:"request",value:// prettier-ignore
118
118
  function(){var _request3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee19(e,t,s){var i,u,h,f,n,_yield$w$processReque3,o,a,l,c,d,_args19=arguments;return _regenerator().w(function(_context19){while(1)switch(_context19.n){case 0:i=_args19.length>3&&_args19[3]!==undefined?_args19[3]:!0;n={body:t,headers:(u=e.connectSettings)==null?void 0:u.headers};_context19.n=1;return w.processRequestInterceptor(e.deepChat,n);case 1:_yield$w$processReque3=_context19.v;o=_yield$w$processReque3.body;a=_yield$w$processReque3.headers;l=_yield$w$processReque3.error;c=e.completionsHandlers.onFinish;if(!l){_context19.n=2;break;}return _context19.a(2,w.onInterceptorError(s,l,c));case 2:if(!((h=e.connectSettings)!=null&&h.handler)){_context19.n=3;break;}return _context19.a(2,ke.request(e,o,s));case 3:if(!(((f=e.connectSettings)==null?void 0:f.url)===Oe.URL)){_context19.n=4;break;}return _context19.a(2,Oe.request(e,s));case 4:d=!0;w.fetch(e,a,i,o).then(function(m){return d=!!m.ok,m;}).then(function(m){return w.processResponseByType(m);}).then(/*#__PURE__*/function(){var _ref17=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee18(m){var E,I,p,g,_t0;return _regenerator().w(function(_context18){while(1)switch(_context18.n){case 0:if(e.extractResultData){_context18.n=1;break;}return _context18.a(2);case 1:_context18.n=2;return(I=(E=e.deepChat).responseInterceptor)==null?void 0:I.call(E,m);case 2:_t0=_context18.v;if(_t0){_context18.n=3;break;}_t0=m;case 3:p=_t0;_context18.n=4;return e.extractResultData(p,o);case 4:g=_context18.v;if(d){_context18.n=5;break;}throw m;case 5:if(!(!g||_typeof(g)!==T&&!Array.isArray(g))){_context18.n=6;break;}throw Error(b.INVALID_RESPONSE(m,"response",!!e.deepChat.responseInterceptor,p));case 6:if(!g.error){_context18.n=7;break;}throw g.error;case 7:if(!e.asyncCallInProgress){_context18.n=8;break;}e.asyncCallInProgress=!1;return _context18.a(2);case 8:M.isSimulatable(e.stream,g)?M.simulate(s,e.streamHandlers,g):((Array.isArray(g)?g:[g]).forEach(function(D){return s.addNewMessage(D);}),c());case 9:return _context18.a(2);}},_callee18);}));return function(_x44){return _ref17.apply(this,arguments);};}())["catch"](function(m){w.displayError(s,m),c();});case 5:return _context19.a(2);}},_callee19);}));function request(_x41,_x42,_x43){return _request3.apply(this,arguments);}return request;}()},{key:"executePollRequest",value:function executePollRequest(e,t,s,i){var n=e.completionsHandlers.onFinish;fetch(t,s).then(function(o){return o.json();}).then(/*#__PURE__*/function(){var _ref18=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee20(o){var l,c,a,_t1,_t10;return _regenerator().w(function(_context20){while(1)switch(_context20.n){case 0:if(e.extractPollResultData){_context20.n=1;break;}return _context20.a(2);case 1:_t1=e;_context20.n=2;return(c=(l=e.deepChat).responseInterceptor)==null?void 0:c.call(l,o);case 2:_t10=_context20.v;if(_t10){_context20.n=3;break;}_t10=o;case 3:_context20.n=4;return _t1.extractPollResultData.call(_t1,_t10);case 4:a=_context20.v;a.timeoutMS?setTimeout(function(){V.executePollRequest(e,t,s,i);},a.timeoutMS):M.isSimulatable(e.stream,a)?M.simulate(i,e.streamHandlers,a):(i.addNewMessage(a),n());case 5:return _context20.a(2);}},_callee20);}));return function(_x45){return _ref18.apply(this,arguments);};}())["catch"](function(o){w.displayError(i,o),n();});}// prettier-ignore
119
119
  },{key:"poll",value:function(){var _poll=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee21(e,t,s){var i,f,m,p,n,_yield$w$processReque4,o,a,l,c,d,u,h,_args21=arguments;return _regenerator().w(function(_context21){while(1)switch(_context21.n){case 0:i=_args21.length>3&&_args21[3]!==undefined?_args21[3]:!0;n={body:t,headers:(f=e.connectSettings)==null?void 0:f.headers};_context21.n=1;return w.processRequestInterceptor(e.deepChat,n);case 1:_yield$w$processReque4=_context21.v;o=_yield$w$processReque4.body;a=_yield$w$processReque4.headers;l=_yield$w$processReque4.error;if(!l){_context21.n=2;break;}return _context21.a(2,w.onInterceptorError(s,l));case 2:c=((m=e.connectSettings)==null?void 0:m.url)||e.url||"",d=((p=e.connectSettings)==null?void 0:p.method)||Z,u=i?JSON.stringify(o):o,h={method:d,body:u,headers:a};e.connectSettings.credentials&&(h.credentials=e.connectSettings.credentials),V.executePollRequest(e,c,h,s);case 3:return _context21.a(2);}},_callee21);}));function poll(_x46,_x47,_x48){return _poll.apply(this,arguments);}return poll;}()// prettier-ignore
120
- },{key:"verifyKey",value:function verifyKey(e,t,s,i,n,o,a,l,c){if(e==="")return o(b.INVALID_KEY);a(),fetch(t,{method:i,headers:s,body:c||null}).then(function(d){return w.processResponseByType(d);}).then(function(d){l(d,e,n,o);})["catch"](function(d){o(b.CONNECTION_FAILED),console.error(d);});}}]);}();var nt=/*#__PURE__*/function(){function nt(e,t,s){_classCallCheck(this,nt);this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=t,s.fetchHistory&&this.fetchHistory(s.fetchHistory),e.loadHistory&&this.setupLoadHistoryOnScroll(e.loadHistory),this.setupInitialHistory(e);}return _createClass(nt,[{key:"fetchHistory",value:function(){var _fetchHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee22(e){var _this0=this;var t,s;return _regenerator().w(function(_context22){while(1)switch(_context22.n){case 0:t=Ze.addMessage(this._messages);_context22.n=1;return e();case 1:s=_context22.v;this._messages.removeMessage(t),nt.displayIntroMessages(this._messages.messageElementRefs),s.forEach(function(i){return _this0._messages.addAnyMessage(i,!0);}),setTimeout(function(){return F.scrollToBottom(_this0._messages.elementRef);},0);case 2:return _context22.a(2);}},_callee22,this);}));function fetchHistory(_x49){return _fetchHistory.apply(this,arguments);}return fetchHistory;}()},{key:"processLoadedHistory",value:function processLoadedHistory(e){var _this1=this;var a;var _this$_messages=this._messages,t=_this$_messages.messageElementRefs,s=_this$_messages.messageToElements,i=_this$_messages.elementRef,n=(a=t.find(function(l){return!l.outerContainer.classList.contains(Ae.INTRO_CLASS);}))==null?void 0:a.outerContainer,o=i.scrollTop;e==null||e.reverse().map(function(l){var c=_this1._messages.addAnyMessage(_objectSpread(_objectSpread({},l),{},{sendUpdate:!0}),!0,!0);if(c){var d=v.generateMessageBody(c,t,!0);s.unshift([c,d]);}return c;}).filter(function(l){return!!l;}).reverse().forEach(function(l){return _this1._messages.sendClientUpdate(l,!0);}),n&&(i.scrollTop=o+n.offsetTop-40);}},{key:"populateMessages",value:function populateMessages(e,t){this._messages.removeMessage(e),this._isPaginationComplete=t.findIndex(function(a){return!a;})<0;var s=t.filter(function(a){return!!a;});this.processLoadedHistory(s);var _this$_messages2=this._messages,i=_this$_messages2.messageElementRefs,n=_this$_messages2.avatar,o=_this$_messages2.name;v.resetAllRoleElements(i,n,o);}},{key:"setupLoadHistoryOnScroll",value:function(){var _setupLoadHistoryOnScroll=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee24(e){var _this10=this;return _regenerator().w(function(_context24){while(1)switch(_context24.n){case 0:this._messages.elementRef.onscroll=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee23(){var t,s,_t11;return _regenerator().w(function(_context23){while(1)switch(_context23.p=_context23.n){case 0:if(!(!_this10._isLoading&&!_this10._isPaginationComplete&&_this10._messages.elementRef.scrollTop===0)){_context23.n=4;break;}_this10._isLoading=!0;t=Ze.addMessage(_this10._messages,!1);_context23.p=1;_context23.n=2;return e(_this10._index++);case 2:s=_context23.v;_this10.populateMessages(t,s),_this10._isLoading=!1;_context23.n=4;break;case 3:_context23.p=3;_t11=_context23.v;_this10._messages.removeMessage(t),_this10._isPaginationComplete=!0,_this10._messages.addNewErrorMessage(B,nt.FAILED_ERROR_MESSAGE,!0),console.error(_t11);case 4:return _context23.a(2);}},_callee23,null,[[1,3]]);}));case 1:return _context24.a(2);}},_callee24,this);}));function setupLoadHistoryOnScroll(_x50){return _setupLoadHistoryOnScroll.apply(this,arguments);}return setupLoadHistoryOnScroll;}()},{key:"populateInitialHistory",value:function populateInitialHistory(e){var _this11=this;e.forEach(function(t){le.processHistoryFile(t),_this11._messages.addAnyMessage(t,!0);});}},{key:"loadInitialHistory",value:function(){var _loadInitialHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee25(e){var _this12=this;var t,s,i,_t12;return _regenerator().w(function(_context25){while(1)switch(_context25.p=_context25.n){case 0:this._isLoading=!0;t=Ze.addMessage(this._messages);_context25.p=1;_context25.n=2;return e(this._index++);case 2:s=_context25.v;i=this._messages.elementRef.scrollTop;this.populateMessages(t,s),i===0&&setTimeout(function(){return F.scrollToBottom(_this12._messages.elementRef);},0);_context25.n=4;break;case 3:_context25.p=3;_t12=_context25.v;this._messages.removeMessage(t),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(B,nt.FAILED_ERROR_MESSAGE,!0),console.error(_t12);case 4:nt.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1;case 5:return _context25.a(2);}},_callee25,this,[[1,3]]);}));function loadInitialHistory(_x51){return _loadInitialHistory.apply(this,arguments);}return loadInitialHistory;}()},{key:"setupInitialHistory",value:function(){var _setupInitialHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee26(e){var s,t;return _regenerator().w(function(_context26){while(1)switch(_context26.n){case 0:e.loadHistory&&this.loadInitialHistory(e.loadHistory);t=e.history||le.processHistory(e)||((s=this._messages.browserStorage)==null?void 0:s.get());t&&(this.populateInitialHistory(t),this._index+=1);case 1:return _context26.a(2);}},_callee26,this);}));function setupInitialHistory(_x52){return _setupInitialHistory.apply(this,arguments);}return setupInitialHistory;}()}],[{key:"addErrorPrefix",value:function addErrorPrefix(e){var _e$permittedErrorPref;(_e$permittedErrorPref=e.permittedErrorPrefixes)!==null&&_e$permittedErrorPref!==void 0?_e$permittedErrorPref:e.permittedErrorPrefixes=[],e.permittedErrorPrefixes.push(nt.FAILED_ERROR_MESSAGE);}},{key:"displayIntroMessages",value:function displayIntroMessages(e){for(var t=0;t<e.length;t+=1){var s=e[0];if(s.outerContainer.classList.contains(Ae.INTRO_CLASS))s.outerContainer.style.display="";else break;}}}]);}();nt.FAILED_ERROR_MESSAGE="Failed to load history";var As=nt;var J=/*#__PURE__*/function(){function J(){_classCallCheck(this,J);}return _createClass(J,null,[{key:"getCharacterLimitMessages",value:function getCharacterLimitMessages(e,t){var n;if(t===-1)return e;var s=0,i=e.length-1;for(i;i>=0;i-=1){var o=(n=e[i])==null?void 0:n.text;if(o!==void 0&&(s+=o.length,s>t)){e[i].text=o.substring(0,o.length-(s-t));break;}}return e.slice(Math.max(i,0));}},{key:"getMaxMessages",value:function getMaxMessages(e,t){return e.slice(Math.max(e.length-t,0));}// if maxMessages is not defined we send all messages
120
+ },{key:"verifyKey",value:function verifyKey(e,t,s,i,n,o,a,l,c){if(e==="")return o(b.INVALID_KEY);a(),fetch(t,{method:i,headers:s,body:c||null}).then(function(d){return w.processResponseByType(d);}).then(function(d){l(d,e,n,o);})["catch"](function(d){o(b.CONNECTION_FAILED),console.error(d);});}}]);}();var nt=/*#__PURE__*/function(){function nt(e,t,s){_classCallCheck(this,nt);this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=t,s.fetchHistory&&this.fetchHistory(s.fetchHistory),e.loadHistory&&this.setupLoadHistoryOnScroll(e.loadHistory),this.setupInitialHistory(e);}return _createClass(nt,[{key:"fetchHistory",value:function(){var _fetchHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee22(e){var _this0=this;var t,s;return _regenerator().w(function(_context22){while(1)switch(_context22.n){case 0:t=Ze.addMessage(this._messages);_context22.n=1;return e();case 1:s=_context22.v;this._messages.removeMessage(t),nt.displayIntroMessages(this._messages.messageElementRefs),s.forEach(function(i){return _this0._messages.addAnyMessage(i,!0);}),setTimeout(function(){return F.scrollToBottom(_this0._messages.elementRef);},0);case 2:return _context22.a(2);}},_callee22,this);}));function fetchHistory(_x49){return _fetchHistory.apply(this,arguments);}return fetchHistory;}()},{key:"processLoadedHistory",value:function processLoadedHistory(e){var _this1=this;var a;var _this$_messages=this._messages,t=_this$_messages.messageElementRefs,s=_this$_messages.messageToElements,i=_this$_messages.elementRef,n=(a=t.find(function(l){return!l.outerContainer.classList.contains(Ae.INTRO_CLASS);}))==null?void 0:a.outerContainer,o=i.scrollTop;e==null||e.reverse().map(function(l){var c=_this1._messages.addAnyMessage(_objectSpread(_objectSpread({},l),{},{sendUpdate:!0}),!0,!0);if(c){var d=v.generateMessageBody(c,t,!0);s.unshift([c,d]);}return c;}).filter(function(l){return!!l;}).reverse().forEach(function(l){return _this1._messages.sendClientUpdate(l,!0);}),n&&(i.scrollTop=o+n.offsetTop-40);}},{key:"populateMessages",value:function populateMessages(e,t){this._messages.removeMessage(e),this._isPaginationComplete=t.findIndex(function(a){return!a;})<0;var s=t.filter(function(a){return!!a;});this.processLoadedHistory(s);var _this$_messages2=this._messages,i=_this$_messages2.messageElementRefs,n=_this$_messages2.avatar,o=_this$_messages2.name;v.resetAllRoleElements(i,n,o);}},{key:"setupLoadHistoryOnScroll",value:function(){var _setupLoadHistoryOnScroll=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee24(e){var _this10=this;return _regenerator().w(function(_context24){while(1)switch(_context24.n){case 0:this._messages.elementRef.onscroll=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee23(){var t,s,_t11;return _regenerator().w(function(_context23){while(1)switch(_context23.p=_context23.n){case 0:if(!(!_this10._isLoading&&!_this10._isPaginationComplete&&_this10._messages.elementRef.scrollTop===0)){_context23.n=4;break;}_this10._isLoading=!0;t=Ze.addMessage(_this10._messages,!1);_context23.p=1;_context23.n=2;return e(_this10._index++);case 2:s=_context23.v;_this10.populateMessages(t,s),_this10._isLoading=!1;_context23.n=4;break;case 3:_context23.p=3;_t11=_context23.v;_this10._messages.removeMessage(t),_this10._isPaginationComplete=!0,_this10._messages.addNewErrorMessage(B,nt.FAILED_ERROR_MESSAGE,!0),console.error(_t11);case 4:return _context23.a(2);}},_callee23,null,[[1,3]]);}));case 1:return _context24.a(2);}},_callee24,this);}));function setupLoadHistoryOnScroll(_x50){return _setupLoadHistoryOnScroll.apply(this,arguments);}return setupLoadHistoryOnScroll;}()},{key:"populateInitialHistory",value:function populateInitialHistory(e){var _this11=this;e.forEach(function(t){te.processHistoryFile(t),_this11._messages.addAnyMessage(t,!0);});}},{key:"loadInitialHistory",value:function(){var _loadInitialHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee25(e){var _this12=this;var t,s,i,_t12;return _regenerator().w(function(_context25){while(1)switch(_context25.p=_context25.n){case 0:this._isLoading=!0;t=Ze.addMessage(this._messages);_context25.p=1;_context25.n=2;return e(this._index++);case 2:s=_context25.v;i=this._messages.elementRef.scrollTop;this.populateMessages(t,s),i===0&&setTimeout(function(){return F.scrollToBottom(_this12._messages.elementRef);},0);_context25.n=4;break;case 3:_context25.p=3;_t12=_context25.v;this._messages.removeMessage(t),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(B,nt.FAILED_ERROR_MESSAGE,!0),console.error(_t12);case 4:nt.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1;case 5:return _context25.a(2);}},_callee25,this,[[1,3]]);}));function loadInitialHistory(_x51){return _loadInitialHistory.apply(this,arguments);}return loadInitialHistory;}()},{key:"setupInitialHistory",value:function(){var _setupInitialHistory=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee26(e){var s,t;return _regenerator().w(function(_context26){while(1)switch(_context26.n){case 0:e.loadHistory&&this.loadInitialHistory(e.loadHistory);t=e.history||te.processHistory(e)||((s=this._messages.browserStorage)==null?void 0:s.get());t&&(this.populateInitialHistory(t),this._index+=1);case 1:return _context26.a(2);}},_callee26,this);}));function setupInitialHistory(_x52){return _setupInitialHistory.apply(this,arguments);}return setupInitialHistory;}()}],[{key:"addErrorPrefix",value:function addErrorPrefix(e){var _e$permittedErrorPref;(_e$permittedErrorPref=e.permittedErrorPrefixes)!==null&&_e$permittedErrorPref!==void 0?_e$permittedErrorPref:e.permittedErrorPrefixes=[],e.permittedErrorPrefixes.push(nt.FAILED_ERROR_MESSAGE);}},{key:"displayIntroMessages",value:function displayIntroMessages(e){for(var t=0;t<e.length;t+=1){var s=e[0];if(s.outerContainer.classList.contains(Ae.INTRO_CLASS))s.outerContainer.style.display="";else break;}}}]);}();nt.FAILED_ERROR_MESSAGE="Failed to load history";var As=nt;var J=/*#__PURE__*/function(){function J(){_classCallCheck(this,J);}return _createClass(J,null,[{key:"getCharacterLimitMessages",value:function getCharacterLimitMessages(e,t){var n;if(t===-1)return e;var s=0,i=e.length-1;for(i;i>=0;i-=1){var o=(n=e[i])==null?void 0:n.text;if(o!==void 0&&(s+=o.length,s>t)){e[i].text=o.substring(0,o.length-(s-t));break;}}return e.slice(Math.max(i,0));}},{key:"getMaxMessages",value:function getMaxMessages(e,t){return e.slice(Math.max(e.length-t,0));}// if maxMessages is not defined we send all messages
121
121
  // if maxMessages above 0 we send that number
122
122
  // if maxMessages 0 or below we send only what is in the request
123
123
  },{key:"processMessages",value:function processMessages(e,t,s){return t!==void 0?t>0&&(e=J.getMaxMessages(e,t)):e=[e[e.length-1]],e=JSON.parse(JSON.stringify(e)),s===void 0?e:J.getCharacterLimitMessages(e,s);}}]);}();var W=/*#__PURE__*/function(){function W(){_classCallCheck(this,W);}return _createClass(W,null,[{key:"parseConfig",value:// prettier-ignore
124
- function parseConfig(e,t,s,i){var o;var n={files:t};if(_typeof(i)=="object"){le.processFileConfigConnect(i);var a=i.files,l=i.connect,c=i.button;a&&(a.infoModal&&(n.files.infoModal=a.infoModal,(o=a.infoModal)!=null&&o.textMarkDown&&(n.infoModalTextMarkUp=s.render(a.infoModal.textMarkDown))),a.acceptedFormats&&(n.files.acceptedFormats=a.acceptedFormats),a.maxNumberOfFiles&&(n.files.maxNumberOfFiles=a.maxNumberOfFiles)),n.button=c,l&&(l.headers||l.method||l.url||l.credentials||e.headers||e.method||e.url||e.credentials)&&(n.connect={url:(l==null?void 0:l.url)||e.url,method:(l==null?void 0:l.method)||e.method,headers:(l==null?void 0:l.headers)||e.headers,credentials:(l==null?void 0:l.credentials)||e.credentials});}return n;}},{key:"processMixedFiles",value:function processMixedFiles(e,t,s){if(s){var i={acceptedFormats:""};e.fileTypes.mixedFiles=W.parseConfig(e.connectSettings,i,t,s);}}// needs to be set after audio to overwrite maxNumberOfFiles
124
+ function parseConfig(e,t,s,i){var o;var n={files:t};if(_typeof(i)=="object"){te.processFileConfigConnect(i);var a=i.files,l=i.connect,c=i.button;a&&(a.infoModal&&(n.files.infoModal=a.infoModal,(o=a.infoModal)!=null&&o.textMarkDown&&(n.infoModalTextMarkUp=s.render(a.infoModal.textMarkDown))),a.acceptedFormats&&(n.files.acceptedFormats=a.acceptedFormats),a.maxNumberOfFiles&&(n.files.maxNumberOfFiles=a.maxNumberOfFiles)),n.button=c,l&&(l.headers||l.method||l.url||l.credentials||e.headers||e.method||e.url||e.credentials)&&(n.connect={url:(l==null?void 0:l.url)||e.url,method:(l==null?void 0:l.method)||e.method,headers:(l==null?void 0:l.headers)||e.headers,credentials:(l==null?void 0:l.credentials)||e.credentials});}return n;}},{key:"processMixedFiles",value:function processMixedFiles(e,t,s){if(s){var i={acceptedFormats:""};e.fileTypes.mixedFiles=W.parseConfig(e.connectSettings,i,t,s);}}// needs to be set after audio to overwrite maxNumberOfFiles
125
125
  // prettier-ignore
126
126
  },{key:"processMicrophone",value:function processMicrophone(e,t,s,i){var _l$files,_h$maxNumberOfFiles;var a,l,c,d,u,h;var o=_objectSpread({acceptedFormats:"audio/*"},((a=e.fileTypes.audio)==null?void 0:a.files)||{});s&&(navigator.mediaDevices.getUserMedia!==void 0?(e.recordAudio=W.parseConfig(e.connectSettings,o,t,s),_typeof(s)=="object"&&s.files&&((_l$files=(l=e.recordAudio).files)!==null&&_l$files!==void 0?_l$files:l.files={},e.recordAudio.files.format=(c=s.files)==null?void 0:c.format,e.recordAudio.files.maxDurationSeconds=(d=s.files)==null?void 0:d.maxDurationSeconds,(u=e.fileTypes.audio)!=null&&u.files&&((_h$maxNumberOfFiles=(h=e.fileTypes.audio.files).maxNumberOfFiles)!==null&&_h$maxNumberOfFiles!==void 0?_h$maxNumberOfFiles:h.maxNumberOfFiles=s.files.maxNumberOfFiles))):i||(e.fileTypes.audio=W.parseConfig(e.connectSettings,o,t,s)));}// prettier-ignore
127
127
  },{key:"processAudioConfig",value:function processAudioConfig(e,t,s,i){if(!s&&!i)return;var o=_objectSpread({acceptedFormats:"audio/*"},(i==null?void 0:i.files)||{});e.fileTypes.audio=W.parseConfig(e.connectSettings,o,t,s);}// prettier-ignore
@@ -129,8 +129,8 @@ function parseConfig(e,t,s,i){var o;var n={files:t};if(_typeof(i)=="object"){le.
129
129
  // prettier-ignore
130
130
  },{key:"processCamera",value:function processCamera(e,t,s,i){var _l$files2;var a,l,c,d;var o=_objectSpread({acceptedFormats:"image/*"},((a=e.fileTypes.images)==null?void 0:a.files)||{});s&&(navigator.mediaDevices.getUserMedia!==void 0?(e.camera=W.parseConfig(e.connectSettings,o,t,s),_typeof(s)=="object"&&(e.camera.modalContainerStyle=s.modalContainerStyle,s.files&&((_l$files2=(l=e.camera).files)!==null&&_l$files2!==void 0?_l$files2:l.files={},e.camera.files.format=(c=s.files)==null?void 0:c.format,e.camera.files.dimensions=(d=s.files)==null?void 0:d.dimensions))):i||(e.fileTypes.images=W.parseConfig(e.connectSettings,o,t,s)));}// prettier-ignore
131
131
  },{key:"processImagesConfig",value:function processImagesConfig(e,t,s,i){if(!s&&!i)return;var o=_objectSpread({acceptedFormats:"image/*"},(i==null?void 0:i.files)||{});e.fileTypes.images=W.parseConfig(e.connectSettings,o,t,s);}// default for direct service
132
- },{key:"populateDefaultFileIO",value:function populateDefaultFileIO(e,t){var _e$files,_s$acceptedFormats,_i$maxNumberOfFiles;var s,i;e&&((_e$files=e.files)!==null&&_e$files!==void 0?_e$files:e.files={},(_s$acceptedFormats=(s=e.files).acceptedFormats)!==null&&_s$acceptedFormats!==void 0?_s$acceptedFormats:s.acceptedFormats=t,(_i$maxNumberOfFiles=(i=e.files).maxNumberOfFiles)!==null&&_i$maxNumberOfFiles!==void 0?_i$maxNumberOfFiles:i.maxNumberOfFiles=1);}},{key:"set",value:function set(e,t,s){W.populateDefaultFileIO(s==null?void 0:s.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),W.populateDefaultFileIO(s==null?void 0:s.images,".png,.jpg");var i=xs.createNew(e.remarkable);W.processImagesConfig(t,i,e.images,s==null?void 0:s.images),W.processCamera(t,i,e.camera,e.images),W.processGifConfig(t,i,e.gifs,s==null?void 0:s.gifs),W.processAudioConfig(t,i,e.audio,s==null?void 0:s.audio),W.processMicrophone(t,i,e.microphone,e.audio),W.processMixedFiles(t,i,e.mixedFiles);}}]);}();var wt=/*#__PURE__*/function(){function wt(e,t,s){var _a$url;_classCallCheck(this,wt);var i,n,o,a,l;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=wt.canSendMessage,this.connectSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=e,this.demo=s,Object.assign(this.rawBody,(i=e.connect)==null?void 0:i.additionalBodyProps),this.totalMessagesMaxCharLength=(n=e==null?void 0:e.requestBodyLimits)==null?void 0:n.totalMessagesMaxCharLength,this.maxMessages=(o=e==null?void 0:e.requestBodyLimits)==null?void 0:o.maxMessages,W.set(e,this,t),e.connect&&(this.connectSettings=e.connect),this.demo&&((_a$url=(a=this.connectSettings).url)!==null&&_a$url!==void 0?_a$url:a.url=Oe.URL),this.connectSettings.websocket&&re.setup(this),this.stream=((l=this.deepChat.connect)==null?void 0:l.stream)||le.checkForStream(this.deepChat),e.loadHistory&&As.addErrorPrefix(this);}return _createClass(wt,[{key:"verifyKey",value:function verifyKey(e,t){}},{key:"getServiceIOByType",value:function getServiceIOByType(e){if(e.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(e.type.startsWith("image")){if(this.fileTypes.gifs&&e.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera;}return this.fileTypes.mixedFiles;}},{key:"request",value:function(){var _request4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee27(e,t){var s,_args27=arguments;return _regenerator().w(function(_context27){while(1)switch(_context27.n){case 0:s=_args27.length>2&&_args27[2]!==undefined?_args27[2]:!0;return _context27.a(2,this.stream&&!M.isSimulation(this.stream)?M.request(this,e,t,s):V.request(this,e,t,s));}},_callee27,this);}));function request(_x53,_x54){return _request4.apply(this,arguments);}return request;}()},{key:"callAPIWithText",value:function(){var _callAPIWithText=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee28(e,t){var _o$headers,_a$R;var n,o,a,l,s,i;return _regenerator().w(function(_context28){while(1)switch(_context28.n){case 0:s=_objectSpread({messages:t},this.rawBody);i=!1;(n=this.connectSettings.headers)!=null&&n[R]||((_o$headers=(o=this.connectSettings).headers)!==null&&_o$headers!==void 0?_o$headers:o.headers={},(_a$R=(a=this.connectSettings.headers)[R])!==null&&_a$R!==void 0?_a$R:a[R]=N,i=!0);_context28.n=1;return this.request(s,e);case 1:i&&((l=this.connectSettings.headers)==null||delete l[R]);case 2:return _context28.a(2);}},_callee28,this);}));function callAPIWithText(_x55,_x56){return _callAPIWithText.apply(this,arguments);}return callAPIWithText;}()},{key:"callApiWithFiles",value:function(){var _callApiWithFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee29(e,t,s){var i,n,o;return _regenerator().w(function(_context29){while(1)switch(_context29.n){case 0:i=wt.createCustomFormDataBody(this.rawBody,t,s),n=this.connectSettings,o=this.getServiceIOByType(s[0]);this.connectSettings=(o==null?void 0:o.connect)||this.connectSettings;_context29.n=1;return this.request(i,e,!1);case 1:this.connectSettings=n;case 2:return _context29.a(2);}},_callee29,this);}));function callApiWithFiles(_x57,_x58,_x59){return _callApiWithFiles.apply(this,arguments);}return callApiWithFiles;}()},{key:"callServiceAPI",value:function(){var _callServiceAPI=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee30(e,t,s){return _regenerator().w(function(_context30){while(1)switch(_context30.n){case 0:s?this.callApiWithFiles(e,t,s):this.callAPIWithText(e,t);case 1:return _context30.a(2);}},_callee30,this);}));function callServiceAPI(_x60,_x61,_x62){return _callServiceAPI.apply(this,arguments);}return callServiceAPI;}()// prettier-ignore
133
- },{key:"callAPI",value:function(){var _callAPI=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee31(e,t){var i,s,n;return _regenerator().w(function(_context31){while(1)switch(_context31.n){case 0:if(this.connectSettings){_context31.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:s=J.processMessages(t.messageToElements.map(function(_ref20){var _ref21=_slicedToArray(_ref20,1),n=_ref21[0];return n;}),this.maxMessages,this.totalMessagesMaxCharLength);if(this.connectSettings.websocket&&(!this.connectSettings.handler||this.connectSettings.url!==Oe.URL)){n=_objectSpread({messages:s},this.rawBody);e.files&&(i=this.getServiceIOByType(e.files[0]))!=null&&i.connect?this.callApiWithFiles(t,s,e.files):re.sendWebsocket(this,n,t,!1);}else this.callServiceAPI(t,s,e.files);case 2:return _context31.a(2);}},_callee31,this);}));function callAPI(_x63,_x64){return _callAPI.apply(this,arguments);}return callAPI;}()},{key:"extractResultData",value:function(){var _extractResultData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee32(e){return _regenerator().w(function(_context32){while(1)switch(_context32.n){case 0:if(!e.result){_context32.n=1;break;}return _context32.a(2,le.handleResponseProperty(e));case 1:if(!w.validateResponseFormat(e,!!this.stream)){_context32.n=2;break;}return _context32.a(2,e);case 2:return _context32.a(2);}},_callee32,this);}));function extractResultData(_x65){return _extractResultData.apply(this,arguments);}return extractResultData;}()},{key:"isDirectConnection",value:function isDirectConnection(){return!1;}},{key:"isWebModel",value:function isWebModel(){return!1;}},{key:"isCustomView",value:function isCustomView(){return!1;}}],[{key:"canSendMessage",value:function canSendMessage(e,t,s){return s?!0:!!(e&&e.trim()!=="")||!!(t&&t.length>0);}},{key:"createCustomFormDataBody",value:function createCustomFormDataBody(e,t,s){var i=new FormData();s.forEach(function(a){return i.append("files",a);}),Object.keys(e).forEach(function(a){return i.append(a,String(e[a]));});var n=0;t.slice(0,t.length-1).forEach(function(a){i.append("message".concat(n+=1),JSON.stringify(a));});var o=t[t.length-1];return o.text&&(delete o.files,i.append("message".concat(n+=1),JSON.stringify(o))),i;}}]);}();var k=/*#__PURE__*/function(_wt){// prettier-ignore
132
+ },{key:"populateDefaultFileIO",value:function populateDefaultFileIO(e,t){var _e$files,_s$acceptedFormats,_i$maxNumberOfFiles;var s,i;e&&((_e$files=e.files)!==null&&_e$files!==void 0?_e$files:e.files={},(_s$acceptedFormats=(s=e.files).acceptedFormats)!==null&&_s$acceptedFormats!==void 0?_s$acceptedFormats:s.acceptedFormats=t,(_i$maxNumberOfFiles=(i=e.files).maxNumberOfFiles)!==null&&_i$maxNumberOfFiles!==void 0?_i$maxNumberOfFiles:i.maxNumberOfFiles=1);}},{key:"set",value:function set(e,t,s){W.populateDefaultFileIO(s==null?void 0:s.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),W.populateDefaultFileIO(s==null?void 0:s.images,".png,.jpg");var i=xs.createNew(e.remarkable);W.processImagesConfig(t,i,e.images,s==null?void 0:s.images),W.processCamera(t,i,e.camera,e.images),W.processGifConfig(t,i,e.gifs,s==null?void 0:s.gifs),W.processAudioConfig(t,i,e.audio,s==null?void 0:s.audio),W.processMicrophone(t,i,e.microphone,e.audio),W.processMixedFiles(t,i,e.mixedFiles);}}]);}();var wt=/*#__PURE__*/function(){function wt(e,t,s){var _a$url;_classCallCheck(this,wt);var i,n,o,a,l;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=wt.canSendMessage,this.connectSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=e,this.demo=s,Object.assign(this.rawBody,(i=e.connect)==null?void 0:i.additionalBodyProps),this.totalMessagesMaxCharLength=(n=e==null?void 0:e.requestBodyLimits)==null?void 0:n.totalMessagesMaxCharLength,this.maxMessages=(o=e==null?void 0:e.requestBodyLimits)==null?void 0:o.maxMessages,W.set(e,this,t),e.connect&&(this.connectSettings=e.connect),this.demo&&((_a$url=(a=this.connectSettings).url)!==null&&_a$url!==void 0?_a$url:a.url=Oe.URL),this.connectSettings.websocket&&oe.setup(this),this.stream=((l=this.deepChat.connect)==null?void 0:l.stream)||te.checkForStream(this.deepChat),e.loadHistory&&As.addErrorPrefix(this);}return _createClass(wt,[{key:"verifyKey",value:function verifyKey(e,t){}},{key:"getServiceIOByType",value:function getServiceIOByType(e){if(e.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(e.type.startsWith("image")){if(this.fileTypes.gifs&&e.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera;}return this.fileTypes.mixedFiles;}},{key:"request",value:function(){var _request4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee27(e,t){var s,_args27=arguments;return _regenerator().w(function(_context27){while(1)switch(_context27.n){case 0:s=_args27.length>2&&_args27[2]!==undefined?_args27[2]:!0;return _context27.a(2,this.stream&&!M.isSimulation(this.stream)?M.request(this,e,t,s):V.request(this,e,t,s));}},_callee27,this);}));function request(_x53,_x54){return _request4.apply(this,arguments);}return request;}()},{key:"callAPIWithText",value:function(){var _callAPIWithText=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee28(e,t){var _o$headers,_a$R;var n,o,a,l,s,i;return _regenerator().w(function(_context28){while(1)switch(_context28.n){case 0:s=_objectSpread({messages:t},this.rawBody);i=!1;(n=this.connectSettings.headers)!=null&&n[R]||((_o$headers=(o=this.connectSettings).headers)!==null&&_o$headers!==void 0?_o$headers:o.headers={},(_a$R=(a=this.connectSettings.headers)[R])!==null&&_a$R!==void 0?_a$R:a[R]=N,i=!0);_context28.n=1;return this.request(s,e);case 1:i&&((l=this.connectSettings.headers)==null||delete l[R]);case 2:return _context28.a(2);}},_callee28,this);}));function callAPIWithText(_x55,_x56){return _callAPIWithText.apply(this,arguments);}return callAPIWithText;}()},{key:"callApiWithFiles",value:function(){var _callApiWithFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee29(e,t,s){var i,n,o;return _regenerator().w(function(_context29){while(1)switch(_context29.n){case 0:i=wt.createCustomFormDataBody(this.rawBody,t,s),n=this.connectSettings,o=this.getServiceIOByType(s[0]);this.connectSettings=(o==null?void 0:o.connect)||this.connectSettings;_context29.n=1;return this.request(i,e,!1);case 1:this.connectSettings=n;case 2:return _context29.a(2);}},_callee29,this);}));function callApiWithFiles(_x57,_x58,_x59){return _callApiWithFiles.apply(this,arguments);}return callApiWithFiles;}()},{key:"callServiceAPI",value:function(){var _callServiceAPI=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee30(e,t,s){return _regenerator().w(function(_context30){while(1)switch(_context30.n){case 0:s?this.callApiWithFiles(e,t,s):this.callAPIWithText(e,t);case 1:return _context30.a(2);}},_callee30,this);}));function callServiceAPI(_x60,_x61,_x62){return _callServiceAPI.apply(this,arguments);}return callServiceAPI;}()// prettier-ignore
133
+ },{key:"callAPI",value:function(){var _callAPI=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee31(e,t){var i,s,n;return _regenerator().w(function(_context31){while(1)switch(_context31.n){case 0:if(this.connectSettings){_context31.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:s=J.processMessages(t.messageToElements.map(function(_ref20){var _ref21=_slicedToArray(_ref20,1),n=_ref21[0];return n;}),this.maxMessages,this.totalMessagesMaxCharLength);if(this.connectSettings.websocket&&(!this.connectSettings.handler||this.connectSettings.url!==Oe.URL)){n=_objectSpread({messages:s},this.rawBody);e.files&&(i=this.getServiceIOByType(e.files[0]))!=null&&i.connect?this.callApiWithFiles(t,s,e.files):oe.sendWebsocket(this,n,t,!1);}else this.callServiceAPI(t,s,e.files);case 2:return _context31.a(2);}},_callee31,this);}));function callAPI(_x63,_x64){return _callAPI.apply(this,arguments);}return callAPI;}()},{key:"extractResultData",value:function(){var _extractResultData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee32(e){return _regenerator().w(function(_context32){while(1)switch(_context32.n){case 0:if(!e.result){_context32.n=1;break;}return _context32.a(2,te.handleResponseProperty(e));case 1:if(!w.validateResponseFormat(e,!!this.stream)){_context32.n=2;break;}return _context32.a(2,e);case 2:return _context32.a(2);}},_callee32,this);}));function extractResultData(_x65){return _extractResultData.apply(this,arguments);}return extractResultData;}()},{key:"isDirectConnection",value:function isDirectConnection(){return!1;}},{key:"isWebModel",value:function isWebModel(){return!1;}},{key:"isCustomView",value:function isCustomView(){return!1;}}],[{key:"canSendMessage",value:function canSendMessage(e,t,s){return s?!0:!!(e&&e.trim()!=="")||!!(t&&t.length>0);}},{key:"createCustomFormDataBody",value:function createCustomFormDataBody(e,t,s){var i=new FormData();s.forEach(function(a){return i.append("files",a);}),Object.keys(e).forEach(function(a){return i.append(a,String(e[a]));});var n=0;t.slice(0,t.length-1).forEach(function(a){i.append("message".concat(n+=1),JSON.stringify(a));});var o=t[t.length-1];return o.text&&(delete o.files,i.append("message".concat(n+=1),JSON.stringify(o))),i;}}]);}();var k=/*#__PURE__*/function(_wt){// prettier-ignore
134
134
  function k(e,t,s,i,n){var _this13;_classCallCheck(this,k);var o;_this13=_callSuper(this,k,[e,n]),_this13.insertKeyPlaceholderText="API Key",_this13.keyHelpUrl="",_this13.asyncCallInProgress=!1,Object.assign(_this13.rawBody,(o=e.connect)==null?void 0:o.additionalBodyProps),_this13._keyVerificationDetails=t,_this13._buildHeadersFunc=s,i&&_this13.setApiKeyProperties(i),_this13.connectSettings=_this13.buildConnectSettings(_this13.key||"",e.connect);return _this13;}_inherits(k,_wt);return _createClass(k,[{key:"setApiKeyProperties",value:function setApiKeyProperties(e){this.key=e.key,e.validateKeyProperty&&(this.validateKeyProperty=e.validateKeyProperty);}},{key:"buildConnectSettings",value:function buildConnectSettings(e,t){var _s$headers;var s=t!==null&&t!==void 0?t:{};return(_s$headers=s.headers)!==null&&_s$headers!==void 0?_s$headers:s.headers={},Object.assign(s.headers,this._buildHeadersFunc(e)),s;}},{key:"keyAuthenticated",value:function keyAuthenticated(e,t){this.connectSettings=this.buildConnectSettings(t,this.connectSettings),this.key=t,e();}// prettier-ignore
135
135
  },{key:"verifyKey",value:function verifyKey(e,t){var _this$_keyVerificatio=this._keyVerificationDetails,s=_this$_keyVerificatio.url,i=_this$_keyVerificatio.method,n=_this$_keyVerificatio.handleVerificationResult,o=_this$_keyVerificatio.createHeaders,a=_this$_keyVerificatio.body,l=_this$_keyVerificatio.augmentUrl,c=(o==null?void 0:o(e))||this._buildHeadersFunc(e),d=(l==null?void 0:l(e))||s;V.verifyKey(e,d,c,i,this.keyAuthenticated.bind(this,t.onSuccess),t.onFail,t.onLoad,n,a);}},{key:"isDirectConnection",value:function isDirectConnection(){return!0;}},{key:"callDirectServiceServiceAPI",value:function(){var _callDirectServiceServiceAPI=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee33(e,t,s,i,n){var o,a;return _regenerator().w(function(_context33){while(1)switch(_context33.n){case 0:if(this.connectSettings){_context33.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:o=s(this.rawBody,t),a=i?this.stream:!1;if(!(a&&(_typeof(a)!==T||!a.simulation)||o.stream)){_context33.n=2;break;}o.stream=!0,i!=null&&i.readable&&(this.stream={readable:!0}),M.request(this,o,e);_context33.n=4;break;case 2:_context33.n=3;return V.request(this,o,e,n);case 3:return _context33.a(2,_context33.v);case 4:return _context33.a(2);}},_callee33,this);}));function callDirectServiceServiceAPI(_x66,_x67,_x68,_x69,_x70){return _callDirectServiceServiceAPI.apply(this,arguments);}return callDirectServiceServiceAPI;}()},{key:"callToolFunction",value:function(){var _callToolFunction=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee34(e,t){var n,o,s,a,l,_t13,_t14;return _regenerator().w(function(_context34){while(1)switch(_context34.n){case 0:this.asyncCallInProgress=!0;_context34.n=1;return e(t);case 1:s=_context34.v;if(Array.isArray(s)){_context34.n=6;break;}if(!s.text){_context34.n=5;break;}a=_defineProperty({},y,s.text);_context34.n=2;return(o=(n=this.deepChat).responseInterceptor)==null?void 0:o.call(n,a);case 2:_t13=_context34.v;if(_t13){_context34.n=3;break;}_t13=a;case 3:l=_t13;if(!Array.isArray(l)){_context34.n=4;break;}throw Error("Function tool response interceptor cannot return an array");case 4:return _context34.a(2,{processedResponse:l});case 5:throw Error("Function tool response must be an array or contain a text property");case 6:_context34.n=7;return Promise.all(s);case 7:_t14=_context34.v;return _context34.a(2,{responses:_t14});}},_callee34,this);}));function callToolFunction(_x71,_x72){return _callToolFunction.apply(this,arguments);}return callToolFunction;}()},{key:"makeAnotherRequest",value:function makeAnotherRequest(e,t){try{return t&&(this.stream?M.request(this,e,t):V.request(this,e,t)),_defineProperty({},y,"");}catch(s){throw this.asyncCallInProgress=!1,s;}}},{key:"genereteAPIKeyName",value:function genereteAPIKeyName(e){return"".concat(e," API Key");}},{key:"extractStreamResultWToolsGeneric",value:function(){var _extractStreamResultWToolsGeneric=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee35(e,t,s,i,n,o){var a,l,c;return _regenerator().w(function(_context35){while(1)switch(_context35.n){case 0:a=t.delta,l=t.finish_reason;if(!(l==="tool_calls")){_context35.n=1;break;}c={tool_calls:e._streamToolCalls};return _context35.a(2,(e._streamToolCalls=void 0,this.handleToolsGeneric(c,s,i,n,o)));case 1:a!=null&&a.tool_calls&&(e._streamToolCalls?a.tool_calls.forEach(function(c,d){e._streamToolCalls&&(e._streamToolCalls[d]["function"].arguments+=c["function"].arguments);}):e._streamToolCalls=a.tool_calls);case 2:return _context35.a(2,_defineProperty({},y,(a==null?void 0:a.content)||""));}},_callee35,this);}));function extractStreamResultWToolsGeneric(_x73,_x74,_x75,_x76,_x77,_x78){return _extractStreamResultWToolsGeneric.apply(this,arguments);}return extractStreamResultWToolsGeneric;}()},{key:"handleToolsGeneric",value:function(){var _handleToolsGeneric=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee36(e,t,s,i,n){var o,a,_yield$this$callToolF,l,c;return _regenerator().w(function(_context36){while(1)switch(_context36.n){case 0:if(!(!e.tool_calls||!i||!t)){_context36.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:o=JSON.parse(JSON.stringify(i));a=e.tool_calls.map(function(d){return{name:d["function"].name,arguments:d["function"].arguments};});_context36.n=2;return this.callToolFunction(t,a);case 2:_yield$this$callToolF=_context36.v;l=_yield$this$callToolF.responses;c=_yield$this$callToolF.processedResponse;if(!c){_context36.n=3;break;}return _context36.a(2,c);case 3:if(!(n&&(o.messages=o.messages.slice(o.messages.length-1),n.message&&o.messages.unshift({role:"system",content:n.message})),o.messages.push({tool_calls:e.tool_calls,role:"assistant",content:null}),!l.find(function(_ref24){var d=_ref24.response;return typeof d!="string";})&&a.length===l.length)){_context36.n=4;break;}return _context36.a(2,(l.forEach(function(d,u){var f;var h=(f=e.tool_calls)==null?void 0:f[u];o==null||o.messages.push({role:"tool",tool_call_id:h==null?void 0:h.id,name:h==null?void 0:h["function"].name,content:d.response});}),this.makeAnotherRequest(o,s)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context36.a(2);}},_callee36,this);}));function handleToolsGeneric(_x79,_x80,_x81,_x82,_x83){return _handleToolsGeneric.apply(this,arguments);}return handleToolsGeneric;}()}],[{key:"getImageContent",value:function getImageContent(e){return e.filter(function(t){return t.type==="image";}).map(function(t){return{type:"image_url",image_url:{url:t.src||""}};}).filter(function(t){return t.image_url.url.length>0;});}},{key:"getTextWImagesContent",value:function getTextWImagesContent(e){if(e.files&&e.files.length>0){var t=this.getImageContent(e.files);return e.text&&e.text.trim().length>0&&t.unshift(_defineProperty({type:"text"},y,e.text)),t.length>0?t:e.text||"";}return e.text||"";}},{key:"getTextWFilesContent",value:function getTextWFilesContent(e,t){if(e.files&&e.files.length>0){var s=t(e.files);return e.text&&e.text.trim().length>0&&s.unshift(_defineProperty({type:"text"},y,e.text)),s;}return e.text||"";}}]);}(wt);var Vs=/*#__PURE__*/function(){function Vs(){_classCallCheck(this,Vs);}return _createClass(Vs,null,[{key:"waitForPropertiesToBeUpdatedBeforeRender",value:function waitForPropertiesToBeUpdatedBeforeRender(e){e._propUpdated_=!1,setTimeout(function(){e._propUpdated_?Vs.waitForPropertiesToBeUpdatedBeforeRender(e):(e._waitingToRender_=!1,e.onRender());});}},{key:"attemptRender",value:function attemptRender(e){e._propUpdated_=!0,e._waitingToRender_||(e._waitingToRender_=!0,Vs.waitForPropertiesToBeUpdatedBeforeRender(e));}}]);}();var ze=/*#__PURE__*/function(_HTMLElement){// If this is not working, try using propertyName directly
136
136
  function ze(){var _this14;_classCallCheck(this,ze);_this14=_callSuper(this,ze),_this14._waitingToRender_=!1,_this14._propUpdated_=!1,Object.keys(ze._attributeToProperty_).forEach(function(e){var t=ze._attributeToProperty_[e];_this14.constructPropertyAccessors(t),_this14.hasOwnProperty(e)||_this14.constructPropertyAccessors(t,e);});return _this14;}_inherits(ze,_HTMLElement);return _createClass(ze,[{key:"constructPropertyAccessors",value:// need to be called here as accessors need to be set for the class instance
@@ -148,20 +148,20 @@ function changeVisibility(e,t,s,i){i.target.id===rt.VISIBLE_ICON_ID?(t.style.dis
148
148
  {model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f16-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f16",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f16-ctx2k-webgpu.wasm",vram_required_MB:5063.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f32-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f32",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f32-ctx2k-webgpu.wasm",vram_required_MB:5394.53,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f16_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:899.11,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f32_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:992.11,low_resource_required:!0}],use_web_worker:!0},L=/*#__PURE__*/function(_wt2){function L(e){var _this15;_classCallCheck(this,L);var t,s;_this15=_callSuper(this,L,[e]),_this15._isModelLoaded=!1,_this15._isModelLoading=!1,_this15._loadOnFirstMessage=!1,_this15._webModel={},_this15.permittedErrorPrefixes=[L.MULTIPLE_MODELS_ERROR,L.WEB_LLM_NOT_FOUND_ERROR,L.GENERIC_ERROR],_this15._conversationHistory=[],_typeof(e.webModel)=="object"&&(_this15._webModel=e.webModel),(t=_this15._webModel.load)!=null&&t.clearCache&&L.clearAllCache(),_this15.findModelInWindow(e),_this15.canSendMessage=_this15.canSubmit.bind(_assertThisInitialized(_this15)),_this15._chatEl=(s=e.shadowRoot)==null?void 0:s.children[0],e.history&&L.setUpHistory(_this15._conversationHistory,e.history);return _this15;}// need ref of messages object as web model exhibits unique behaviour to manipulate chat
149
149
  _inherits(L,_wt2);return _createClass(L,[{key:"setUpMessages",value:function setUpMessages(e){var _this16=this;this._messages=e,this._removeIntro=function(){e.removeIntroductoryMessage(),_this16._removeIntro=void 0;};}},{key:"findModelInWindow",value:function findModelInWindow(e){var _this17=this;var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var s;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):t>L.MODULE_SEARCH_LIMIT_S?((s=this._messages)==null||s.addNewErrorMessage(B,L.WEB_LLM_NOT_FOUND_ERROR),console.error("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console.error("https://deepchat.dev/examples/externalModules")):setTimeout(function(){return _this17.findModelInWindow(e,t+1);},1e3);}},{key:"shouldAddIntroMessage",value:function shouldAddIntroMessage(e){var t;return!e&&this._webModel&&((t=this._webModel.introMessage)==null?void 0:t.displayed)!==!1;}},{key:"scrollToTop",value:function scrollToTop(e){var _this18=this;var t;((t=this._webModel.introMessage)==null?void 0:t.autoScroll)!==!1&&setTimeout(function(){var s,i;(s=_this18._messages)!=null&&s.elementRef&&F.scrollToTop((i=_this18._messages)==null?void 0:i.elementRef);},e);}// prettier-ignore
150
150
  },{key:"getIntroMessage",value:function getIntroMessage(e){if(!this.shouldAddIntroMessage(e)||!this._chatEl)return;var t=Gs.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:v.AI_ROLE,html:t,sendUpdate:!1};}},{key:"configureInit",value:function(){var _configureInit=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee37(e){var t;return _regenerator().w(function(_context37){while(1)switch(_context37.n){case 0:t=this._webModel.load;if(!t){_context37.n=2;break;}if(!t.onInit){_context37.n=1;break;}this.init();return _context37.a(2);case 1:if(!t.onMessage){_context37.n=2;break;}this._loadOnFirstMessage=!0;return _context37.a(2);case 2:e||this.init();case 3:return _context37.a(2);}},_callee37,this);}));function configureInit(_x84){return _configureInit.apply(this,arguments);}return configureInit;}()},{key:"init",value:function(){var _init=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee38(e){var s,t,_t15;return _regenerator().w(function(_context38){while(1)switch(_context38.n){case 0:(s=this._messages)==null||s.removeError();t=this.attemptToCreateChat();_t15=t;if(!_t15){_context38.n=1;break;}_context38.n=1;return this.loadModel(t,e);case 1:return _context38.a(2);}},_callee38,this);}));function init(_x85){return _init.apply(this,arguments);}return init;}()},{key:"attemptToCreateChat",value:function attemptToCreateChat(){var t;if(L.chat){(t=this._messages)==null||t.addNewErrorMessage(B,L.MULTIPLE_MODELS_ERROR),console.error(L.MULTIPLE_MODELS_ERROR);return;}if(this._isModelLoaded||this._isModelLoading)return;var e=this._webModel.worker;return Hn.use_web_worker&&e?new window.webLLM.ChatWorkerClient(e):new window.webLLM.ChatModule();}},{key:"getConfig",value:function getConfig(){var s;var e=L.DEFAULT_MODEL;this._webModel.model&&(e=this._webModel.model);var t=JSON.parse(JSON.stringify(Hn));if(this._webModel.urls){var i=t.model_list.find(function(n){return n.local_id=e;});i&&(this._webModel.urls.model&&(i.model_url=this._webModel.urls.model),this._webModel.urls.wasm&&(i.model_lib_url=this._webModel.urls.wasm));}return(s=this._webModel.load)!=null&&s.skipCache&&(t.use_cache=!1),{model:e,appConfig:t};}// prettier-ignore
151
- },{key:"loadModel",value:function(){var _loadModel=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee39(e,t){var _this19=this;var o,a,l,c,d,u,h,s,i,n,_this$getConfig,f,m,p,_f,_t16;return _regenerator().w(function(_context39){while(1)switch(_context39.p=_context39.n){case 0:this.scrollToTop(),L.chat=e,this._isModelLoading=!0;s=((o=this._webModel.introMessage)==null?void 0:o.displayed)===!1;i=function i(f){var m;(m=_this19._messages)==null||m.addNewMessage({html:"<div>".concat(f.text,"</div>"),overwrite:!0,sendUpdate:!1}),s&&(setTimeout(function(){var p;return F.scrollToBottom((p=_this19._messages)==null?void 0:p.elementRef);}),s=!1);};L.chat.setInitProgressCallback(i);_context39.p=1;_this$getConfig=this.getConfig(),f=_this$getConfig.model,m=_this$getConfig.appConfig,p={};this._webModel.instruction&&(p.conv_config={system:this._webModel.instruction});this._conversationHistory.length>0&&(p.conversation_history=this._conversationHistory);_context39.n=2;return L.chat.reload(f,p,m,t);case 2:n=_context39.v;_context39.n=4;break;case 3:_context39.p=3;_t16=_context39.v;return _context39.a(2,this.unloadChat(_t16));case 4:if((l=(a=this.deepChat)._validationHandler)==null||l.call(a),(c=this._webModel.introMessage)!=null&&c.removeAfterLoad)this._webModel.introMessage.displayed===!1?(u=this._messages)==null||u.removeLastMessage():(h=this._removeIntro)==null||h.call(this);else{_f=Gs.setUpAfterLoad(n,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);(d=this._messages)==null||d.addNewMessage({html:_f,overwrite:!0,sendUpdate:!1});}this._isModelLoaded=!0,this._isModelLoading=!1;case 5:return _context39.a(2);}},_callee39,this,[[1,3]]);}));function loadModel(_x86,_x87){return _loadModel.apply(this,arguments);}return loadModel;}()},{key:"unloadChat",value:function(){var _unloadChat=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee40(e){var t,_t17;return _regenerator().w(function(_context40){while(1)switch(_context40.n){case 0:(t=this._messages)==null||t.addNewErrorMessage(B,L.GENERIC_ERROR);console.error(e);this._isModelLoaded=!1;this._isModelLoading=!1;_t17=L.chat;if(!_t17){_context40.n=2;break;}_context40.n=1;return L.chat.unload();case 1:L.chat=void 0;case 2:return _context40.a(2);}},_callee40,this);}));function unloadChat(_x88){return _unloadChat.apply(this,arguments);}return unloadChat;}()},{key:"immediateResp",value:function(){var _immediateResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee41(e,t,s){var i,n,_t18,_t19,_t20;return _regenerator().w(function(_context41){while(1)switch(_context41.n){case 0:_t18=_defineProperty;_t19={};_t20=y;_context41.n=1;return s.generate(t,void 0,0);case 1:i=_t18(_t19,_t20,_context41.v);_context41.n=2;return L.processResponse(this.deepChat,e,i);case 2:n=_context41.v;n&&n.forEach(function(o){return e.addNewMessage(o);}),this.completionsHandlers.onFinish();case 3:return _context41.a(2);}},_callee41,this);}));function immediateResp(_x89,_x90,_x91){return _immediateResp.apply(this,arguments);}return immediateResp;}()},{key:"streamResp",value:function(){var _streamResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee43(e,t,s){var _this20=this;var i;return _regenerator().w(function(_context43){while(1)switch(_context43.n){case 0:this.streamHandlers.onAbort=function(){s.interruptGenerate();},this.streamHandlers.onOpen();i=new Ue(e);_context43.n=1;return s.generate(t,/*#__PURE__*/function(){var _ref25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee42(n,o){var a;return _regenerator().w(function(_context42){while(1)switch(_context42.n){case 0:_context42.n=1;return L.processResponse(_this20.deepChat,e,_defineProperty({},y,o));case 1:a=_context42.v;a&&i.upsertStreamedMessage(_defineProperty(_defineProperty({},y,a[0].text),"overwrite",!0));case 2:return _context42.a(2);}},_callee42);}));return function(_x95,_x96){return _ref25.apply(this,arguments);};}());case 1:i.finaliseStreamedMessage();this.streamHandlers.onClose();case 2:return _context43.a(2);}},_callee43,this);}));function streamResp(_x92,_x93,_x94){return _streamResp.apply(this,arguments);}return streamResp;}()},{key:"generateRespByType",value:function(){var _generateRespByType=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee44(e,t,s,i){var n,_t21;return _regenerator().w(function(_context44){while(1)switch(_context44.p=_context44.n){case 0:_context44.p=0;if(!s){_context44.n=2;break;}_context44.n=1;return this.streamResp(e,t,i);case 1:_context44.n=3;break;case 2:_context44.n=3;return this.immediateResp(e,t,i);case 3:_context44.n=5;break;case 4:_context44.p=4;_t21=_context44.v;(n=this._messages)==null||n.addNewErrorMessage(B),console.log(_t21);case 5:return _context44.a(2);}},_callee44,this,[[0,4]]);}));function generateRespByType(_x97,_x98,_x99,_x100){return _generateRespByType.apply(this,arguments);}return generateRespByType;}()},{key:"generateResp",value:function(){var _generateResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee45(e,t,s){var i,_yield$w$processReque5,n,o,a,l,c;return _regenerator().w(function(_context45){while(1)switch(_context45.n){case 0:i=t[t.length-1].text;_context45.n=1;return w.processRequestInterceptor(this.deepChat,{body:_defineProperty({},y,i)});case 1:_yield$w$processReque5=_context45.v;n=_yield$w$processReque5.body;o=_yield$w$processReque5.error;a=!!this.stream;try{if(o)w.displayError(e,new Error(o)),(a?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(!n||!n.text){l=b.INVALID_MODEL_REQUEST({body:n},!1);console.error(l);c=a?this.streamHandlers.onClose:this.completionsHandlers.onFinish;w.onInterceptorError(e,l,c);}else this.generateRespByType(e,n.text,!!this.stream,s);}catch(l){this.unloadChat(l);}case 2:return _context45.a(2);}},_callee45,this);}));function generateResp(_x101,_x102,_x103){return _generateResp.apply(this,arguments);}return generateResp;}()},{key:"callServiceAPI",value:function(){var _callServiceAPI2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee46(e,t){var s,i;return _regenerator().w(function(_context46){while(1)switch(_context46.n){case 0:if(this._isModelLoaded){_context46.n=3;break;}if(!this._loadOnFirstMessage){_context46.n=2;break;}_context46.n=1;return this.init();case 1:_context46.n=3;break;case 2:return _context46.a(2);case 3:!L.chat||this._isModelLoading||((s=this._webModel.introMessage)!=null&&s.removeAfterMessage&&((i=this._removeIntro)==null||i.call(this)),e.addLoadingMessage(),this.generateResp(e,t,L.chat));case 4:return _context46.a(2);}},_callee46,this);}));function callServiceAPI(_x104,_x105){return _callServiceAPI2.apply(this,arguments);}return callServiceAPI;}()},{key:"canSubmit",value:function canSubmit(e){return!(e!=null&&e.trim())||this._isModelLoading?!1:this._loadOnFirstMessage?!0:!!this._isModelLoaded;}},{key:"isWebModel",value:function isWebModel(){return!0;}}],[{key:"setUpHistory",value:function setUpHistory(e,t){t.forEach(function(s,i){if(s.role===v.USER_ROLE&&s.text){var n=t[i+1];n!=null&&n.text&&n.role!==v.USER_ROLE&&e.push([s.text,n.text]);}});}},{key:"processResponse",value:function(){var _processResponse=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee47(e,t,s){var a,l,i,n,o,d,_t22;return _regenerator().w(function(_context47){while(1)switch(_context47.n){case 0:_context47.n=1;return(a=e.responseInterceptor)==null?void 0:a.call(e,s);case 1:_t22=_context47.v;if(_t22){_context47.n=2;break;}_t22=s;case 2:i=_t22;if(!((l=e.connect)!=null&&l.stream&&Array.isArray(i)&&i.length>1)){_context47.n=3;break;}console.error(b.INVALID_STREAM_ARRAY_RESPONSE);return _context47.a(2);case 3:n=Array.isArray(i)?i:[i],o=n.find(function(c){return typeof c.error=="string";});if(!o){_context47.n=4;break;}w.displayError(t,new Error(o.error));return _context47.a(2);case 4:if(!n.find(function(d){return!d||!d.text;})){_context47.n=5;break;}d=b.INVALID_MODEL_RESPONSE(s,!!e.responseInterceptor,i);w.displayError(t,new Error(d));return _context47.a(2);case 5:return _context47.a(2,n);}},_callee47);}));function processResponse(_x106,_x107,_x108){return _processResponse.apply(this,arguments);}return processResponse;}()},{key:"clearAllCache",value:function clearAllCache(){L.clearCache("webllm/model"),L.clearCache("webllm/wasm");}},{key:"clearCache",value:function clearCache(e){caches.open(e).then(function(t){t.keys().then(function(s){s.forEach(function(i){t["delete"](i);});});});}}]);}(wt);L.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",L.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",L.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",L.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",L.MODULE_SEARCH_LIMIT_S=5;var Cs=L;var Ks=/*#__PURE__*/function(){function Ks(){_classCallCheck(this,Ks);}return _createClass(Ks,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}// prettier-ignore
151
+ },{key:"loadModel",value:function(){var _loadModel=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee39(e,t){var _this19=this;var o,a,l,c,d,u,h,s,i,n,_this$getConfig,f,m,p,_f,_t16;return _regenerator().w(function(_context39){while(1)switch(_context39.p=_context39.n){case 0:this.scrollToTop(),L.chat=e,this._isModelLoading=!0;s=((o=this._webModel.introMessage)==null?void 0:o.displayed)===!1;i=function i(f){var m;(m=_this19._messages)==null||m.addNewMessage({html:"<div>".concat(f.text,"</div>"),overwrite:!0,sendUpdate:!1}),s&&(setTimeout(function(){var p;return F.scrollToBottom((p=_this19._messages)==null?void 0:p.elementRef);}),s=!1);};L.chat.setInitProgressCallback(i);_context39.p=1;_this$getConfig=this.getConfig(),f=_this$getConfig.model,m=_this$getConfig.appConfig,p={};this._webModel.instruction&&(p.conv_config={system:this._webModel.instruction});this._conversationHistory.length>0&&(p.conversation_history=this._conversationHistory);_context39.n=2;return L.chat.reload(f,p,m,t);case 2:n=_context39.v;_context39.n=4;break;case 3:_context39.p=3;_t16=_context39.v;return _context39.a(2,this.unloadChat(_t16));case 4:if((l=(a=this.deepChat)._validationHandler)==null||l.call(a),(c=this._webModel.introMessage)!=null&&c.removeAfterLoad)this._webModel.introMessage.displayed===!1?(u=this._messages)==null||u.removeLastMessage():(h=this._removeIntro)==null||h.call(this);else{_f=Gs.setUpAfterLoad(n,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);(d=this._messages)==null||d.addNewMessage({html:_f,overwrite:!0,sendUpdate:!1});}this._isModelLoaded=!0,this._isModelLoading=!1;case 5:return _context39.a(2);}},_callee39,this,[[1,3]]);}));function loadModel(_x86,_x87){return _loadModel.apply(this,arguments);}return loadModel;}()},{key:"unloadChat",value:function(){var _unloadChat=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee40(e){var t,_t17;return _regenerator().w(function(_context40){while(1)switch(_context40.n){case 0:(t=this._messages)==null||t.addNewErrorMessage(B,L.GENERIC_ERROR);console.error(e);this._isModelLoaded=!1;this._isModelLoading=!1;_t17=L.chat;if(!_t17){_context40.n=2;break;}_context40.n=1;return L.chat.unload();case 1:L.chat=void 0;case 2:return _context40.a(2);}},_callee40,this);}));function unloadChat(_x88){return _unloadChat.apply(this,arguments);}return unloadChat;}()},{key:"immediateResp",value:function(){var _immediateResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee41(e,t,s){var i,n,_t18,_t19,_t20;return _regenerator().w(function(_context41){while(1)switch(_context41.n){case 0:_t18=_defineProperty;_t19={};_t20=y;_context41.n=1;return s.generate(t,void 0,0);case 1:i=_t18(_t19,_t20,_context41.v);_context41.n=2;return L.processResponse(this.deepChat,e,i);case 2:n=_context41.v;n&&n.forEach(function(o){return e.addNewMessage(o);}),this.completionsHandlers.onFinish();case 3:return _context41.a(2);}},_callee41,this);}));function immediateResp(_x89,_x90,_x91){return _immediateResp.apply(this,arguments);}return immediateResp;}()},{key:"streamResp",value:function(){var _streamResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee43(e,t,s){var _this20=this;var i;return _regenerator().w(function(_context43){while(1)switch(_context43.n){case 0:this.streamHandlers.onAbort=function(){s.interruptGenerate();},this.streamHandlers.onOpen();i=new Ue(e);_context43.n=1;return s.generate(t,/*#__PURE__*/function(){var _ref25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee42(n,o){var a;return _regenerator().w(function(_context42){while(1)switch(_context42.n){case 0:_context42.n=1;return L.processResponse(_this20.deepChat,e,_defineProperty({},y,o));case 1:a=_context42.v;a&&i.upsertStreamedMessage(_defineProperty(_defineProperty({},y,a[0].text),"overwrite",!0));case 2:return _context42.a(2);}},_callee42);}));return function(_x95,_x96){return _ref25.apply(this,arguments);};}());case 1:i.finaliseStreamedMessage();this.streamHandlers.onClose();case 2:return _context43.a(2);}},_callee43,this);}));function streamResp(_x92,_x93,_x94){return _streamResp.apply(this,arguments);}return streamResp;}()},{key:"generateRespByType",value:function(){var _generateRespByType=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee44(e,t,s,i){var n,_t21;return _regenerator().w(function(_context44){while(1)switch(_context44.p=_context44.n){case 0:_context44.p=0;if(!s){_context44.n=2;break;}_context44.n=1;return this.streamResp(e,t,i);case 1:_context44.n=3;break;case 2:_context44.n=3;return this.immediateResp(e,t,i);case 3:_context44.n=5;break;case 4:_context44.p=4;_t21=_context44.v;(n=this._messages)==null||n.addNewErrorMessage(B),console.log(_t21);case 5:return _context44.a(2);}},_callee44,this,[[0,4]]);}));function generateRespByType(_x97,_x98,_x99,_x100){return _generateRespByType.apply(this,arguments);}return generateRespByType;}()},{key:"generateResp",value:function(){var _generateResp=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee45(e,t,s){var i,_yield$w$processReque5,n,o,a,l,c;return _regenerator().w(function(_context45){while(1)switch(_context45.n){case 0:i=t[t.length-1].text;_context45.n=1;return w.processRequestInterceptor(this.deepChat,{body:_defineProperty({},y,i)});case 1:_yield$w$processReque5=_context45.v;n=_yield$w$processReque5.body;o=_yield$w$processReque5.error;a=!!this.stream;try{if(o)w.displayError(e,new Error(o)),(a?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(!n||!n.text){l=b.INVALID_MODEL_REQUEST({body:n},!1);console.error(l);c=a?this.streamHandlers.onClose:this.completionsHandlers.onFinish;w.onInterceptorError(e,l,c);}else this.generateRespByType(e,n.text,!!this.stream,s);}catch(l){this.unloadChat(l);}case 2:return _context45.a(2);}},_callee45,this);}));function generateResp(_x101,_x102,_x103){return _generateResp.apply(this,arguments);}return generateResp;}()},{key:"callServiceAPI",value:function(){var _callServiceAPI2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee46(e,t){var s,i;return _regenerator().w(function(_context46){while(1)switch(_context46.n){case 0:if(this._isModelLoaded){_context46.n=3;break;}if(!this._loadOnFirstMessage){_context46.n=2;break;}_context46.n=1;return this.init();case 1:_context46.n=3;break;case 2:return _context46.a(2);case 3:!L.chat||this._isModelLoading||((s=this._webModel.introMessage)!=null&&s.removeAfterMessage&&((i=this._removeIntro)==null||i.call(this)),e.addLoadingMessage(),this.generateResp(e,t,L.chat));case 4:return _context46.a(2);}},_callee46,this);}));function callServiceAPI(_x104,_x105){return _callServiceAPI2.apply(this,arguments);}return callServiceAPI;}()},{key:"canSubmit",value:function canSubmit(e){return!(e!=null&&e.trim())||this._isModelLoading?!1:this._loadOnFirstMessage?!0:!!this._isModelLoaded;}},{key:"isWebModel",value:function isWebModel(){return!0;}}],[{key:"setUpHistory",value:function setUpHistory(e,t){t.forEach(function(s,i){if(s.role===v.USER_ROLE&&s.text){var n=t[i+1];n!=null&&n.text&&n.role!==v.USER_ROLE&&e.push([s.text,n.text]);}});}},{key:"processResponse",value:function(){var _processResponse=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee47(e,t,s){var a,l,i,n,o,d,_t22;return _regenerator().w(function(_context47){while(1)switch(_context47.n){case 0:_context47.n=1;return(a=e.responseInterceptor)==null?void 0:a.call(e,s);case 1:_t22=_context47.v;if(_t22){_context47.n=2;break;}_t22=s;case 2:i=_t22;if(!((l=e.connect)!=null&&l.stream&&Array.isArray(i)&&i.length>1)){_context47.n=3;break;}console.error(b.INVALID_STREAM_ARRAY_RESPONSE);return _context47.a(2);case 3:n=Array.isArray(i)?i:[i],o=n.find(function(c){return typeof c.error=="string";});if(!o){_context47.n=4;break;}w.displayError(t,new Error(o.error));return _context47.a(2);case 4:if(!n.find(function(d){return!d||!d.text;})){_context47.n=5;break;}d=b.INVALID_MODEL_RESPONSE(s,!!e.responseInterceptor,i);w.displayError(t,new Error(d));return _context47.a(2);case 5:return _context47.a(2,n);}},_callee47);}));function processResponse(_x106,_x107,_x108){return _processResponse.apply(this,arguments);}return processResponse;}()},{key:"clearAllCache",value:function clearAllCache(){L.clearCache("webllm/model"),L.clearCache("webllm/wasm");}},{key:"clearCache",value:function clearCache(e){caches.open(e).then(function(t){t.keys().then(function(s){s.forEach(function(i){t["delete"](i);});});});}}]);}(wt);L.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",L.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",L.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",L.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",L.MODULE_SEARCH_LIMIT_S=5;var Cs=L;var Ks=/*#__PURE__*/function(){function Ks(){_classCallCheck(this,Ks);}return _createClass(Ks,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}// prettier-ignore
152
152
  },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;Array.isArray(n.error)&&n.error[0]==="Error in `parameters`: field required"?s(t):i(b.INVALID_KEY);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:Z,handleVerificationResult:Ks.handleVerificationResult};}}]);}();var ys=/*#__PURE__*/function(_k){// prettier-ignore
153
153
  function ys(e,t,s,i,n,o){var _this21;_classCallCheck(this,ys);_this21=_callSuper(this,ys,[e,Ks.buildKeyVerificationDetails(),Ks.buildHeaders,n,o]),_this21.insertKeyPlaceholderText="Hugging Face Token",_this21.keyHelpUrl="https://huggingface.co/settings/tokens",_this21.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>",_this21.permittedErrorPrefixes=[nn],_this21.url="".concat(ys.URL_PREFIX).concat(s),_this21.textInputPlaceholderText=t,_typeof(i)=="object"&&(i.model&&(_this21.url="".concat(ys.URL_PREFIX).concat(i.model)),i.options&&(_this21.rawBody.options=i.options),i.parameters&&(_this21.rawBody.parameters=i.parameters));return _this21;}// prettier-ignore
154
154
  _inherits(ys,_k);return _createClass(ys,[{key:"preprocessBody",value:function preprocessBody(e,t,s){var _i$options;var i=JSON.parse(JSON.stringify(e)),n=t[t.length-1].text;if(n)return(_i$options=i.options)!==null&&_i$options!==void 0?_i$options:i.options={},i.options.wait_for_model=!0,_objectSpread({inputs:n},i);}},{key:"callServiceAPI",value:function(){var _callServiceAPI3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee48(e,t,s){var i;return _regenerator().w(function(_context48){while(1)switch(_context48.n){case 0:if(this.connectSettings){_context48.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:i=this.preprocessBody(this.rawBody,t,s);V.request(this,i,e);case 2:return _context48.a(2);}},_callee48,this);}));function callServiceAPI(_x109,_x110,_x111){return _callServiceAPI3.apply(this,arguments);}return callServiceAPI;}()}]);}(k);ys.URL_PREFIX="https://api-inference.huggingface.co/models/";var et=ys;var Ls=/*#__PURE__*/function(_et){// prettier-ignore
155
155
  function Ls(e,t,s,i,n,o){var _this22;_classCallCheck(this,Ls);_this22=_callSuper(this,Ls,[e,t,s,i,n,o]),_this22.isTextInputDisabled=!0,_this22.canSendMessage=Ls.canSendFile;return _this22;}_inherits(Ls,_et);return _createClass(Ls,[{key:"preprocessBody",value:function preprocessBody(e,t,s){return s[0];}// prettier-ignore
156
156
  },{key:"callServiceAPI",value:function(){var _callServiceAPI4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee49(e,t,s){return _regenerator().w(function(_context49){while(1)switch(_context49.n){case 0:if(this.connectSettings){_context49.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(s!=null&&s[0]){_context49.n=2;break;}throw new Error(b.NO_FILE_ADDED_ERROR);case 2:V.poll(this,s[0],e,!1);case 3:return _context49.a(2);}},_callee49,this);}));function callServiceAPI(_x112,_x113,_x114){return _callServiceAPI4.apply(this,arguments);}return callServiceAPI;}()}],[{key:"canSendFile",value:function canSendFile(e,t){return!!(t!=null&&t[0]);}}]);}(et);var Ba=/*#__PURE__*/function(_Ls){// prettier-ignore
157
- function Ba(e){_classCallCheck(this,Ba);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.audioClassification,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ba,[e,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",t,s,{audio:{}}]);}_inherits(Ba,_Ls);return _createClass(Ba,[{key:"extractPollResultData",value:function(){var _extractPollResultData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee50(e){var t;return _regenerator().w(function(_context50){while(1)switch(_context50.n){case 0:if(!e.estimated_time){_context50.n=1;break;}return _context50.a(2,{timeoutMS:(e.estimated_time+1)*1e3});case 1:if(!e.error){_context50.n=2;break;}throw e.error;case 2:return _context50.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.label)||""));}},_callee50);}));function extractPollResultData(_x115){return _extractPollResultData.apply(this,arguments);}return extractPollResultData;}()}]);}(Ls);var Fa=/*#__PURE__*/function(_Ls2){function Fa(e){_classCallCheck(this,Fa);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.imageClassification,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Fa,[e,"Attach an image file","google/vit-base-patch16-224",t,s,{images:{}}]);}_inherits(Fa,_Ls2);return _createClass(Fa,[{key:"extractPollResultData",value:function(){var _extractPollResultData2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee51(e){var t;return _regenerator().w(function(_context51){while(1)switch(_context51.n){case 0:if(!e.estimated_time){_context51.n=1;break;}return _context51.a(2,{timeoutMS:(e.estimated_time+1)*1e3});case 1:if(!e.error){_context51.n=2;break;}throw e.error;case 2:return _context51.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.label)||""));}},_callee51);}));function extractPollResultData(_x116){return _extractPollResultData2.apply(this,arguments);}return extractPollResultData;}()}]);}(Ls);var jt="data:image/png;base64,";var qe=/*#__PURE__*/function(){function qe(){_classCallCheck(this,qe);}return _createClass(qe,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}// prettier-ignore
157
+ function Ba(e){_classCallCheck(this,Ba);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.audioClassification,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ba,[e,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",t,s,{audio:{}}]);}_inherits(Ba,_Ls);return _createClass(Ba,[{key:"extractPollResultData",value:function(){var _extractPollResultData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee50(e){var t;return _regenerator().w(function(_context50){while(1)switch(_context50.n){case 0:if(!e.estimated_time){_context50.n=1;break;}return _context50.a(2,{timeoutMS:(e.estimated_time+1)*1e3});case 1:if(!e.error){_context50.n=2;break;}throw e.error;case 2:return _context50.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.label)||""));}},_callee50);}));function extractPollResultData(_x115){return _extractPollResultData.apply(this,arguments);}return extractPollResultData;}()}]);}(Ls);var Fa=/*#__PURE__*/function(_Ls2){function Fa(e){_classCallCheck(this,Fa);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.imageClassification,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Fa,[e,"Attach an image file","google/vit-base-patch16-224",t,s,{images:{}}]);}_inherits(Fa,_Ls2);return _createClass(Fa,[{key:"extractPollResultData",value:function(){var _extractPollResultData2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee51(e){var t;return _regenerator().w(function(_context51){while(1)switch(_context51.n){case 0:if(!e.estimated_time){_context51.n=1;break;}return _context51.a(2,{timeoutMS:(e.estimated_time+1)*1e3});case 1:if(!e.error){_context51.n=2;break;}throw e.error;case 2:return _context51.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.label)||""));}},_callee51);}));function extractPollResultData(_x116){return _extractPollResultData2.apply(this,arguments);}return extractPollResultData;}()}]);}(Ls);var jt="data:image/png;base64,";var qe=/*#__PURE__*/function(){function qe(){_classCallCheck(this,qe);}return _createClass(qe,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}// prettier-ignore
158
158
  },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){e.message?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:z,handleVerificationResult:qe.handleVerificationResult};}}]);}();var Ai=/*#__PURE__*/function(_k2){// prettier-ignore
159
159
  function Ai(e,t,s,i,n){var _this23;_classCallCheck(this,Ai);_this23=_callSuper(this,Ai,[e,t,s,i,n]),_this23.insertKeyPlaceholderText=_this23.genereteAPIKeyName("Stability AI"),_this23.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",_this23.permittedErrorPrefixes=[ks,"invalid_"];return _this23;}_inherits(Ai,_k2);return _createClass(Ai);}(k);var zs=/*#__PURE__*/function(_Ai){function zs(e){var _this24;_classCallCheck(this,zs);var o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t==null?void 0:t.stabilityAI,i={images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}};_this24=_callSuper(this,zs,[e,qe.buildKeyVerificationDetails(),qe.buildHeaders,s,i]),_this24.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",_this24.textInputPlaceholderText="Describe image changes",_this24.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Stability AI</b></div>\n <div style=\"width: 100%; text-align: center; margin-left: -10px; margin-top: 5px\"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href=\"https://platform.stability.ai/\" target=\"_blank\">here</a> for more info.</p>";var n=(o=t==null?void 0:t.stabilityAI)==null?void 0:o.imageToImageUpscale;_typeof(n)=="object"&&(n.engine_id&&(_this24.url="https://api.stability.ai/v1/generation/".concat(n.engine_id,"/image-to-image/upscale")),zs.cleanConfig(n),Object.assign(_this24.rawBody,n)),_this24.canSendMessage=zs.canSendFileMessage;return _this24;}_inherits(zs,_Ai);return _createClass(zs,[{key:"createFormDataBody",value:function createFormDataBody(e,t){var s=new FormData();return s.append("image",t),Object.keys(e).forEach(function(i){s.append(i,String(e[i]));}),s;}// prettier-ignore
160
160
  },{key:"callServiceAPI",value:function(){var _callServiceAPI5=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee52(e,t,s){var i;return _regenerator().w(function(_context52){while(1)switch(_context52.n){case 0:if(this.connectSettings){_context52.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(s){_context52.n=2;break;}throw new Error(b.IMAGE_NOT_FOUND_ERROR);case 2:i=this.createFormDataBody(this.rawBody,s[0]);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,i,e),!1);case 3:return _context52.a(2);}},_callee52,this);}));function callServiceAPI(_x117,_x118,_x119){return _callServiceAPI5.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee53(e){return _regenerator().w(function(_context53){while(1)switch(_context53.n){case 0:if(!e.message){_context53.n=1;break;}throw e.message;case 1:return _context53.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee53);}));function extractResultData(_x120){return _extractResultData2.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id;}},{key:"canSendFileMessage",value:function canSendFileMessage(e,t){return!!(t!=null&&t[0]);}}]);}(Ai);var Js=/*#__PURE__*/function(_Ai2){function Js(e){var _this25;_classCallCheck(this,Js);var o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t==null?void 0:t.stabilityAI,i={images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}};_this25=_callSuper(this,Js,[e,qe.buildKeyVerificationDetails(),qe.buildHeaders,s,i]),_this25.url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",_this25._maskSource="MASK_IMAGE_WHITE",_this25.textInputPlaceholderText="Describe image changes",_this25.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Stability AI</b></div>\n <div style=\"width: 100%; text-align: center; margin-left: -10px; margin-top: 5px\"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href=\"https://platform.stability.ai/\" target=\"_blank\">here</a> for more info.</p>";var n=(o=t==null?void 0:t.stabilityAI)==null?void 0:o.imageToImageMasking;_typeof(n)=="object"&&(n.engine_id&&(_this25.url="https://api.stability.ai/v1/generation/".concat(n.engine_id,"/image-to-image/masking")),n.weight!==void 0&&n.weight!==null&&(_this25._imageWeight=n.weight),n.mask_source!==void 0&&n.mask_source!==null&&(_this25._maskSource=n.mask_source),Js.cleanConfig(n),Object.assign(_this25.rawBody,n)),_this25.canSendMessage=Js.canSendFileTextMessage;return _this25;}_inherits(Js,_Ai2);return _createClass(Js,[{key:"createFormDataBody",value:function createFormDataBody(e,t,s,i){var n=new FormData();return n.append("init_image",t),n.append("mask_source",String(this._maskSource)),n.append("mask_image",s),i&&i!==""&&n.append("text_prompts[0][text]",i),this._imageWeight!==void 0&&this._imageWeight!==null&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(e).forEach(function(o){n.append(o,String(e[o]));}),n.get("weight")===void 0&&n.append("weight",String(1)),n;}// prettier-ignore
161
161
  },{key:"callServiceAPI",value:function(){var _callServiceAPI6=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee54(e,t,s){var o,a,i,n;return _regenerator().w(function(_context54){while(1)switch(_context54.n){case 0:if(this.connectSettings){_context54.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(!(!s||!s[0]||!s[1])){_context54.n=2;break;}throw new Error(b.IMAGE_NOT_FOUND_ERROR);case 2:i=(a=(o=t[t.length-1])==null?void 0:o.text)==null?void 0:a.trim(),n=this.createFormDataBody(this.rawBody,s[0],s[1],i);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,n,e),!1);case 3:return _context54.a(2);}},_callee54,this);}));function callServiceAPI(_x121,_x122,_x123){return _callServiceAPI6.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee55(e){return _regenerator().w(function(_context55){while(1)switch(_context55.n){case 0:if(!e.message){_context55.n=1;break;}throw e.message;case 1:return _context55.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee55);}));function extractResultData(_x124){return _extractResultData3.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id,delete e.weight;}},{key:"canSendFileTextMessage",value:function canSendFileTextMessage(e,t){return!!(t!=null&&t[0])&&!!(e&&e.trim()!=="");}}]);}(Ai);var Ua=/*#__PURE__*/function(_Ls3){function Ua(e){_classCallCheck(this,Ua);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.audioSpeechRecognition,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ua,[e,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",t,s,{audio:{}}]);}_inherits(Ua,_Ls3);return _createClass(Ua,[{key:"extractPollResultData",value:function(){var _extractPollResultData3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee56(e){return _regenerator().w(function(_context56){while(1)switch(_context56.n){case 0:if(!e.estimated_time){_context56.n=1;break;}return _context56.a(2,{timeoutMS:(e.estimated_time+1)*1e3});case 1:if(!e.error){_context56.n=2;break;}throw e.error;case 2:return _context56.a(2,_defineProperty({},y,e.text||""));}},_callee56);}));function extractPollResultData(_x125){return _extractPollResultData3.apply(this,arguments);}return extractPollResultData;}()}]);}(Ls);var Ha=/*#__PURE__*/function(_et2){function Ha(e){_classCallCheck(this,Ha);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.textGeneration,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ha,[e,"Once upon a time","gpt2",t,s]);}_inherits(Ha,_et2);return _createClass(Ha,[{key:"extractResultData",value:function(){var _extractResultData4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee57(e){var t;return _regenerator().w(function(_context57){while(1)switch(_context57.n){case 0:if(!e.error){_context57.n=1;break;}throw e.error;case 1:return _context57.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.generated_text)||""));}},_callee57);}));function extractResultData(_x126){return _extractResultData4.apply(this,arguments);}return extractResultData;}()}]);}(et);var ja=/*#__PURE__*/function(_et3){function ja(e){var _this26;_classCallCheck(this,ja);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.questionAnswer,s=(o=e.directConnection)==null?void 0:o.huggingFace;_this26=_callSuper(this,ja,[e,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",t,s]),_this26.permittedErrorPrefixes=[nn,"Error in"],_this26._context=t.context;return _this26;}_inherits(ja,_et3);return _createClass(ja,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=t[t.length-1].text;if(s)return{inputs:{question:s,context:this._context,options:{wait_for_model:!0}}};}},{key:"extractResultData",value:function(){var _extractResultData5=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee58(e){return _regenerator().w(function(_context58){while(1)switch(_context58.n){case 0:if(!e.error){_context58.n=1;break;}throw e.error;case 1:return _context58.a(2,_defineProperty({},y,e.answer||""));}},_callee58);}));function extractResultData(_x127){return _extractResultData5.apply(this,arguments);}return extractResultData;}()}]);}(et);var qa=/*#__PURE__*/function(_et4){function qa(e){_classCallCheck(this,qa);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.summarization,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,qa,[e,"Insert text to summarize","facebook/bart-large-cnn",t,s]);}_inherits(qa,_et4);return _createClass(qa,[{key:"extractResultData",value:function(){var _extractResultData6=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee59(e){var t;return _regenerator().w(function(_context59){while(1)switch(_context59.n){case 0:if(!e.error){_context59.n=1;break;}throw e.error;case 1:return _context59.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.summary_text)||""));}},_callee59);}));function extractResultData(_x128){return _extractResultData6.apply(this,arguments);}return extractResultData;}()}]);}(et);var Va=/*#__PURE__*/function(_et5){function Va(e){var _this27$maxMessages;var _this27;_classCallCheck(this,Va);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.conversation,s=(o=e.directConnection)==null?void 0:o.huggingFace;_this27=_callSuper(this,Va,[e,"Ask me anything!","facebook/blenderbot-400M-distill",t,s]),(_this27$maxMessages=_this27.maxMessages)!==null&&_this27$maxMessages!==void 0?_this27$maxMessages:_this27.maxMessages=-1;return _this27;}// prettier-ignore
162
162
  _inherits(Va,_et5);return _createClass(Va,[{key:"processMessages",value:function processMessages(e){var t=e.filter(function(a){return a.text;}),s=t[t.length-1].text,i=t.slice(0,t.length-1);if(!s)return;var n=i.filter(function(a){return a.role==="user";}).map(function(a){return a.text;}),o=i.filter(function(a){return a.role==="ai";}).map(function(a){return a.text;});return{past_user_inputs:n,generated_responses:o,mostRecentMessageText:s};}// prettier-ignore
163
163
  },{key:"preprocessBody",value:function preprocessBody(e,t){var _s$options;var s=JSON.parse(JSON.stringify(e)),i=this.processMessages(t);if(i)return(_s$options=s.options)!==null&&_s$options!==void 0?_s$options:s.options={},s.options.wait_for_model=!0,_objectSpread({inputs:_defineProperty({past_user_inputs:i.past_user_inputs,generated_responses:i.generated_responses},y,i.mostRecentMessageText)},s);}},{key:"extractResultData",value:function(){var _extractResultData7=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee60(e){return _regenerator().w(function(_context60){while(1)switch(_context60.n){case 0:if(!e.error){_context60.n=1;break;}throw e.error;case 1:return _context60.a(2,_defineProperty({},y,e.generated_text||""));}},_callee60);}));function extractResultData(_x129){return _extractResultData7.apply(this,arguments);}return extractResultData;}()}]);}(et);var $s=/*#__PURE__*/function(_Ai3){function $s(e){var _this28;_classCallCheck(this,$s);var o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.stabilityAI,i={images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}};_this28=_callSuper(this,$s,[e,qe.buildKeyVerificationDetails(),qe.buildHeaders,s,i]),_this28.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",_this28.textInputPlaceholderText="Describe image changes",_this28.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Stability AI: Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href=\"https://platform.stability.ai/\" target=\"_blank\">here</a> for more info.</p>";var n=(o=t.stabilityAI)==null?void 0:o.imageToImage;_typeof(n)=="object"&&(n.engine_id&&(_this28.url="https://api.stability.ai/v1/generation/".concat(n.engine_id,"/text-to-image")),n.weight!==void 0&&n.weight!==null&&(_this28._imageWeight=n.weight),$s.cleanConfig(n),Object.assign(_this28.rawBody,n)),_this28.canSendMessage=$s.canSendFileTextMessage;return _this28;}_inherits($s,_Ai3);return _createClass($s,[{key:"createFormDataBody",value:function createFormDataBody(e,t,s){var i=new FormData();return i.append("init_image",t),s&&s!==""&&i.append("text_prompts[0][text]",s),this._imageWeight!==void 0&&this._imageWeight!==null&&i.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(e).forEach(function(n){i.append(n,String(e[n]));}),i.get("weight")===void 0&&i.append("weight",String(1)),i;}// prettier-ignore
164
- },{key:"callServiceAPI",value:function(){var _callServiceAPI7=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee61(e,t,s){var o,a,i,n;return _regenerator().w(function(_context61){while(1)switch(_context61.n){case 0:if(this.connectSettings){_context61.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(s){_context61.n=2;break;}throw new Error(b.IMAGE_NOT_FOUND_ERROR);case 2:i=(a=(o=t[t.length-1])==null?void 0:o.text)==null?void 0:a.trim(),n=this.createFormDataBody(this.rawBody,s[0],i);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,n,e),!1);case 3:return _context61.a(2);}},_callee61,this);}));function callServiceAPI(_x130,_x131,_x132){return _callServiceAPI7.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData8=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee62(e){return _regenerator().w(function(_context62){while(1)switch(_context62.n){case 0:if(!e.message){_context62.n=1;break;}throw e.message;case 1:return _context62.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee62);}));function extractResultData(_x133){return _extractResultData8.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id,delete e.weight;}},{key:"canSendFileTextMessage",value:function canSendFileTextMessage(e,t){return!!(t!=null&&t[0])&&!!(e&&e.trim()!=="");}}]);}(Ai);var Ga=/*#__PURE__*/function(_et6){function Ga(e){_classCallCheck(this,Ga);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.translation,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ga,[e,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",t,s]);}_inherits(Ga,_et6);return _createClass(Ga,[{key:"extractResultData",value:function(){var _extractResultData9=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee63(e){var t;return _regenerator().w(function(_context63){while(1)switch(_context63.n){case 0:if(!e.error){_context63.n=1;break;}throw e.error;case 1:return _context63.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.translation_text)||""));}},_callee63);}));function extractResultData(_x134){return _extractResultData9.apply(this,arguments);}return extractResultData;}()}]);}(et);var Ws=/*#__PURE__*/function(_Ai4){function Ws(e){var _this29;_classCallCheck(this,Ws);var n;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.stabilityAI;_this29=_callSuper(this,Ws,[e,qe.buildKeyVerificationDetails(),qe.buildHeaders,s]),_this29.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",_this29.textInputPlaceholderText="Describe an image",_this29.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href=\"https://platform.stability.ai/\" target=\"_blank\">here</a> for more info.</p>";var i=(n=t.stabilityAI)==null?void 0:n.textToImage;_typeof(i)=="object"&&(i.engine_id&&(_this29.url="https://api.stability.ai/v1/generation/".concat(i.engine_id,"/text-to-image")),i.weight!==void 0&&i.weight!==null&&(_this29._imageWeight=i.weight),Ws.cleanConfig(i),Object.assign(_this29.rawBody,i)),_this29.canSendMessage=Ws.canSendTextMessage;return _this29;}_inherits(Ws,_Ai4);return _createClass(Ws,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=t[t.length-1].text,i=JSON.parse(JSON.stringify(e)),n=_defineProperty({},y,s);return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i;}},{key:"callServiceAPI",value:function(){var _callServiceAPI8=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee64(e,t){return _regenerator().w(function(_context64){while(1)switch(_context64.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context64.a(2);}},_callee64,this);}));function callServiceAPI(_x135,_x136){return _callServiceAPI8.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee65(e){return _regenerator().w(function(_context65){while(1)switch(_context65.n){case 0:if(!e.message){_context65.n=1;break;}throw e.message;case 1:return _context65.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee65);}));function extractResultData(_x137){return _extractResultData0.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id,delete e.weight;}},{key:"canSendTextMessage",value:function canSendTextMessage(e){return!!(e&&e.trim()!=="");}}]);}(Ai);var Ka=/*#__PURE__*/function(_et7){function Ka(e){var _this30;_classCallCheck(this,Ka);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.fillMask,s=(o=e.directConnection)==null?void 0:o.huggingFace;_this30=_callSuper(this,Ka,[e,"The goal of life is [MASK].","bert-base-uncased",t,s]),_this30.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>",_this30.permittedErrorPrefixes=[nn,"No mask_token"];return _this30;}_inherits(Ka,_et7);return _createClass(Ka,[{key:"extractResultData",value:function(){var _extractResultData1=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee66(e){var t;return _regenerator().w(function(_context66){while(1)switch(_context66.n){case 0:if(!e.error){_context66.n=1;break;}throw e.error;case 1:return _context66.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.sequence)||""));}},_callee66);}));function extractResultData(_x138){return _extractResultData1.apply(this,arguments);}return extractResultData;}()}]);}(et);var ct=/*#__PURE__*/function(){function ct(){_classCallCheck(this,ct);}return _createClass(ct,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(te).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://open.bigmodel.cn/api/paas/v4/models",method:z,handleVerificationResult:ct.handleVerificationResult};}}]);}();var za=/*#__PURE__*/function(_k3){function za(e){var _o$model,_a$voice;var _this31;_classCallCheck(this,za);var n,o,a;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this31=_callSuper(this,za,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this31.insertKeyPlaceholderText=_this31.genereteAPIKeyName("BigModel"),_this31.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this31.url="https://open.bigmodel.cn/api/paas/v4/audio/speech",_this31.permittedErrorPrefixes=[K,se];var i=(n=t.bigModel)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this31.cleanConfig(i),Object.assign(_this31.rawBody,i)),(_o$model=(o=_this31.rawBody).model)!==null&&_o$model!==void 0?_o$model:o.model="cogtts",(_a$voice=(a=_this31.rawBody).voice)!==null&&_a$voice!==void 0?_a$voice:a.voice="tongtong";return _this31;}_inherits(za,_k3);return _createClass(za,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI9=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee67(e,t){return _regenerator().w(function(_context67){while(1)switch(_context67.n){case 0:return _context67.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee67,this);}));function callServiceAPI(_x139,_x140){return _callServiceAPI9.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData10=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee68(e){var t;return _regenerator().w(function(_context68){while(1)switch(_context68.n){case 0:t=new Blob([e],{type:"audio/mpeg"});return _context68.a(2,{files:[{src:URL.createObjectURL(t),type:"audio"}]});}},_callee68);}));function extractResultData(_x141){return _extractResultData10.apply(this,arguments);}return extractResultData;}()}]);}(k);var dt=/*#__PURE__*/function(){function dt(){_classCallCheck(this,dt);}return _createClass(dt,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(te).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.together.xyz/v1/models",method:z,handleVerificationResult:dt.handleVerificationResult};}}]);}();var Ja=/*#__PURE__*/function(_k4){function Ja(e){var _o$model2,_a$voice2;var _this32;_classCallCheck(this,Ja);var n,o,a;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this32=_callSuper(this,Ja,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this32.insertKeyPlaceholderText=_this32.genereteAPIKeyName("Together AI"),_this32.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this32.url="https://api.together.xyz/v1/audio/speech",_this32.permittedErrorPrefixes=[we,se];var i=(n=t.together)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this32.cleanConfig(i),Object.assign(_this32.rawBody,i)),(_o$model2=(o=_this32.rawBody).model)!==null&&_o$model2!==void 0?_o$model2:o.model="cartesia/sonic",(_a$voice2=(a=_this32.rawBody).voice)!==null&&_a$voice2!==void 0?_a$voice2:a.voice="laidback woman";return _this32;}_inherits(Ja,_k4);return _createClass(Ja,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee69(e,t){return _regenerator().w(function(_context69){while(1)switch(_context69.n){case 0:return _context69.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee69,this);}));function callServiceAPI(_x142,_x143){return _callServiceAPI0.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData11=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee70(e){var t;return _regenerator().w(function(_context70){while(1)switch(_context70.n){case 0:t=new Blob([e],{type:"audio/mpeg"});return _context70.a(2,{files:[{src:URL.createObjectURL(t),type:"audio"}]});}},_callee70);}));function extractResultData(_x144){return _extractResultData11.apply(this,arguments);}return extractResultData;}()}]);}(k);var bs=/*#__PURE__*/function(){function bs(){_classCallCheck(this,bs);}return _createClass(bs,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}// prettier-ignore
164
+ },{key:"callServiceAPI",value:function(){var _callServiceAPI7=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee61(e,t,s){var o,a,i,n;return _regenerator().w(function(_context61){while(1)switch(_context61.n){case 0:if(this.connectSettings){_context61.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(s){_context61.n=2;break;}throw new Error(b.IMAGE_NOT_FOUND_ERROR);case 2:i=(a=(o=t[t.length-1])==null?void 0:o.text)==null?void 0:a.trim(),n=this.createFormDataBody(this.rawBody,s[0],i);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,n,e),!1);case 3:return _context61.a(2);}},_callee61,this);}));function callServiceAPI(_x130,_x131,_x132){return _callServiceAPI7.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData8=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee62(e){return _regenerator().w(function(_context62){while(1)switch(_context62.n){case 0:if(!e.message){_context62.n=1;break;}throw e.message;case 1:return _context62.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee62);}));function extractResultData(_x133){return _extractResultData8.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id,delete e.weight;}},{key:"canSendFileTextMessage",value:function canSendFileTextMessage(e,t){return!!(t!=null&&t[0])&&!!(e&&e.trim()!=="");}}]);}(Ai);var Ga=/*#__PURE__*/function(_et6){function Ga(e){_classCallCheck(this,Ga);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.translation,s=(o=e.directConnection)==null?void 0:o.huggingFace;return _callSuper(this,Ga,[e,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",t,s]);}_inherits(Ga,_et6);return _createClass(Ga,[{key:"extractResultData",value:function(){var _extractResultData9=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee63(e){var t;return _regenerator().w(function(_context63){while(1)switch(_context63.n){case 0:if(!e.error){_context63.n=1;break;}throw e.error;case 1:return _context63.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.translation_text)||""));}},_callee63);}));function extractResultData(_x134){return _extractResultData9.apply(this,arguments);}return extractResultData;}()}]);}(et);var Ws=/*#__PURE__*/function(_Ai4){function Ws(e){var _this29;_classCallCheck(this,Ws);var n;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.stabilityAI;_this29=_callSuper(this,Ws,[e,qe.buildKeyVerificationDetails(),qe.buildHeaders,s]),_this29.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",_this29.textInputPlaceholderText="Describe an image",_this29.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href=\"https://platform.stability.ai/\" target=\"_blank\">here</a> for more info.</p>";var i=(n=t.stabilityAI)==null?void 0:n.textToImage;_typeof(i)=="object"&&(i.engine_id&&(_this29.url="https://api.stability.ai/v1/generation/".concat(i.engine_id,"/text-to-image")),i.weight!==void 0&&i.weight!==null&&(_this29._imageWeight=i.weight),Ws.cleanConfig(i),Object.assign(_this29.rawBody,i)),_this29.canSendMessage=Ws.canSendTextMessage;return _this29;}_inherits(Ws,_Ai4);return _createClass(Ws,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=t[t.length-1].text,i=JSON.parse(JSON.stringify(e)),n=_defineProperty({},y,s);return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i;}},{key:"callServiceAPI",value:function(){var _callServiceAPI8=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee64(e,t){return _regenerator().w(function(_context64){while(1)switch(_context64.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context64.a(2);}},_callee64,this);}));function callServiceAPI(_x135,_x136){return _callServiceAPI8.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee65(e){return _regenerator().w(function(_context65){while(1)switch(_context65.n){case 0:if(!e.message){_context65.n=1;break;}throw e.message;case 1:return _context65.a(2,{files:e.artifacts.map(function(s){return{src:"".concat(jt).concat(s.base64),type:"image"};})});}},_callee65);}));function extractResultData(_x137){return _extractResultData0.apply(this,arguments);}return extractResultData;}()}],[{key:"cleanConfig",value:function cleanConfig(e){delete e.engine_id,delete e.weight;}},{key:"canSendTextMessage",value:function canSendTextMessage(e){return!!(e&&e.trim()!=="");}}]);}(Ai);var Ka=/*#__PURE__*/function(_et7){function Ka(e){var _this30;_classCallCheck(this,Ka);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.huggingFace)==null?void 0:n.fillMask,s=(o=e.directConnection)==null?void 0:o.huggingFace;_this30=_callSuper(this,Ka,[e,"The goal of life is [MASK].","bert-base-uncased",t,s]),_this30.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>",_this30.permittedErrorPrefixes=[nn,"No mask_token"];return _this30;}_inherits(Ka,_et7);return _createClass(Ka,[{key:"extractResultData",value:function(){var _extractResultData1=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee66(e){var t;return _regenerator().w(function(_context66){while(1)switch(_context66.n){case 0:if(!e.error){_context66.n=1;break;}throw e.error;case 1:return _context66.a(2,_defineProperty({},y,((t=e[0])==null?void 0:t.sequence)||""));}},_callee66);}));function extractResultData(_x138){return _extractResultData1.apply(this,arguments);}return extractResultData;}()}]);}(et);var ct=/*#__PURE__*/function(){function ct(){_classCallCheck(this,ct);}return _createClass(ct,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(se).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://open.bigmodel.cn/api/paas/v4/models",method:z,handleVerificationResult:ct.handleVerificationResult};}}]);}();var za=/*#__PURE__*/function(_k3){function za(e){var _o$model,_a$voice;var _this31;_classCallCheck(this,za);var n,o,a;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this31=_callSuper(this,za,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this31.insertKeyPlaceholderText=_this31.genereteAPIKeyName("BigModel"),_this31.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this31.url="https://open.bigmodel.cn/api/paas/v4/audio/speech",_this31.permittedErrorPrefixes=[K,ie];var i=(n=t.bigModel)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this31.cleanConfig(i),Object.assign(_this31.rawBody,i)),(_o$model=(o=_this31.rawBody).model)!==null&&_o$model!==void 0?_o$model:o.model="cogtts",(_a$voice=(a=_this31.rawBody).voice)!==null&&_a$voice!==void 0?_a$voice:a.voice="tongtong";return _this31;}_inherits(za,_k3);return _createClass(za,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI9=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee67(e,t){return _regenerator().w(function(_context67){while(1)switch(_context67.n){case 0:return _context67.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee67,this);}));function callServiceAPI(_x139,_x140){return _callServiceAPI9.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData10=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee68(e){var t;return _regenerator().w(function(_context68){while(1)switch(_context68.n){case 0:t=new Blob([e],{type:"audio/mpeg"});return _context68.a(2,{files:[{src:URL.createObjectURL(t),type:"audio"}]});}},_callee68);}));function extractResultData(_x141){return _extractResultData10.apply(this,arguments);}return extractResultData;}()}]);}(k);var dt=/*#__PURE__*/function(){function dt(){_classCallCheck(this,dt);}return _createClass(dt,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(se).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.together.xyz/v1/models",method:z,handleVerificationResult:dt.handleVerificationResult};}}]);}();var Ja=/*#__PURE__*/function(_k4){function Ja(e){var _o$model2,_a$voice2;var _this32;_classCallCheck(this,Ja);var n,o,a;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this32=_callSuper(this,Ja,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this32.insertKeyPlaceholderText=_this32.genereteAPIKeyName("Together AI"),_this32.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this32.url="https://api.together.xyz/v1/audio/speech",_this32.permittedErrorPrefixes=[we,ie];var i=(n=t.together)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this32.cleanConfig(i),Object.assign(_this32.rawBody,i)),(_o$model2=(o=_this32.rawBody).model)!==null&&_o$model2!==void 0?_o$model2:o.model="cartesia/sonic",(_a$voice2=(a=_this32.rawBody).voice)!==null&&_a$voice2!==void 0?_a$voice2:a.voice="laidback woman";return _this32;}_inherits(Ja,_k4);return _createClass(Ja,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI0=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee69(e,t){return _regenerator().w(function(_context69){while(1)switch(_context69.n){case 0:return _context69.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee69,this);}));function callServiceAPI(_x142,_x143){return _callServiceAPI0.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData11=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee70(e){var t;return _regenerator().w(function(_context70){while(1)switch(_context70.n){case 0:t=new Blob([e],{type:"audio/mpeg"});return _context70.a(2,{files:[{src:URL.createObjectURL(t),type:"audio"}]});}},_callee70);}));function extractResultData(_x144){return _extractResultData11.apply(this,arguments);}return extractResultData;}()}]);}(k);var bs=/*#__PURE__*/function(){function bs(){_classCallCheck(this,bs);}return _createClass(bs,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}// prettier-ignore
165
165
  },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.code==="invalid_api_key"?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:z,handleVerificationResult:bs.handleVerificationResult};}// eslint-disable-next-line @typescript-eslint/no-explicit-any
166
166
  },{key:"directFetch",value:function(){var _directFetch=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee71(e,t,s){var i,n,_args71=arguments;return _regenerator().w(function(_context71){while(1)switch(_context71.n){case 0:i=_args71.length>3&&_args71[3]!==undefined?_args71[3]:!0;e.connectSettings.method=s;_context71.n=1;return w.fetch(e,e.connectSettings.headers,i,t).then(function(o){return w.processResponseByType(o);});case 1:n=_context71.v;if(!n.error){_context71.n=2;break;}throw n.error.message;case 2:return _context71.a(2,n);}},_callee71);}));function directFetch(_x145,_x146,_x147){return _directFetch.apply(this,arguments);}return directFetch;}()}]);}();bs.FUNCTION_TOOL_RESP_ERROR="Response object must either be {response: string}[] for each individual function or {text: string} for a direct response, see https://deepchat.dev/docs/directConnection/OpenAI#FunctionHandler.",bs.FUNCTION_TOOL_RESP_ARR_ERROR="Arrays are not accepted in handler responses";var G=bs;var ye=/*#__PURE__*/function(){function ye(){_classCallCheck(this,ye);}return _createClass(ye,null,[{key:"storeFiles",value:function(){var _storeFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee73(e,t,s,i){var n,o,a,l,_t23;return _regenerator().w(function(_context73){while(1)switch(_context73.p=_context73.n){case 0:n=e.connectSettings.headers;if(n){_context73.n=1;break;}return _context73.a(2);case 1:e.url=i;o=n[R];delete n[R];a=s.map(/*#__PURE__*/function(){var _ref40=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee72(l){var c;return _regenerator().w(function(_context72){while(1)switch(_context72.n){case 0:c=new FormData();return _context72.a(2,(c.append("purpose","assistants"),c.append("file",l),new Promise(function(d){d(G.directFetch(e,c,Z,!1));})));}},_callee72);}));return function(_x152){return _ref40.apply(this,arguments);};}());_context73.p=2;_context73.n=3;return Promise.all(a);case 3:l=_context73.v.map(function(c){return{id:c.id,name:c.filename};});return _context73.a(2,(n[R]=o,l));case 4:_context73.p=4;_t23=_context73.v;throw n[R]=o,w.displayError(t,_t23),e.completionsHandlers.onFinish(),_t23;case 5:return _context73.a(2);}},_callee73,null,[[2,4]]);}));function storeFiles(_x148,_x149,_x150,_x151){return _storeFiles.apply(this,arguments);}return storeFiles;}()},{key:"getType",value:function getType(e,t){var s=e[t].path;return!s||s.endsWith("png")?"image":"any";}},{key:"getFiles",value:function(){var _getFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee74(e,t,s,i){var n,a;return _regenerator().w(function(_context74){while(1)switch(_context74.n){case 0:n=t.map(function(_ref41){var l=_ref41.fileId;return e.url="".concat(s).concat(l).concat(i),new Promise(function(c){c(G.directFetch(e,void 0,"GET",!1));});});_context74.n=1;return Promise.all(n);case 1:a=_context74.v.map(function(l,c){return new Promise(function(d){var u=new FileReader();u.readAsDataURL(l),u.onload=function(h){d({src:h.target.result,name:t[c].name,type:ye.getType(t,c)});};});});_context74.n=2;return Promise.all(a);case 2:return _context74.a(2,_context74.v);}},_callee74);}));function getFiles(_x153,_x154,_x155,_x156){return _getFiles.apply(this,arguments);}return getFiles;}()},{key:"getFileName",value:function getFileName(e){var t=e.split("/");return t[t.length-1];}// prettier-ignore
167
167
  },{key:"getFilesAndNewText",value:function(){var _getFilesAndNewText=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee75(e,t,s,i,n){var c,d,o,a,l,_t24;return _regenerator().w(function(_context75){while(1)switch(_context75.n){case 0:a=s.getFilesPrefix,l=s.getFilesPostfix;_t24=t.length>0;if(!_t24){_context75.n=2;break;}_context75.n=1;return ye.getFiles(e,t,a,l);case 1:o=_context75.v;(c=n==null?void 0:n.text)!=null&&c.value&&o.forEach(function(u,h){var m;if(!u.src)return;var f=t[h].path;(m=n==null?void 0:n.text)!=null&&m.value&&f&&(n.text.value=n.text.value.replace(f,u.src));});case 2:return _context75.a(2,(d=n==null?void 0:n.text)!=null&&d.value?_defineProperty(_defineProperty({},y,n.text.value),"role",i):{files:o,role:i});}},_callee75);}));function getFilesAndNewText(_x157,_x158,_x159,_x160,_x161){return _getFilesAndNewText.apply(this,arguments);}return getFilesAndNewText;}()// Noticed an issue where text contains a sandbox hyperlink to a csv, but no annotation provided
@@ -180,13 +180,13 @@ function ot(e,t,s,i,n,o){var _this33;_classCallCheck(this,ot);if(_this33=_callSu
180
180
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
181
181
  },{key:"createStreamRun",value:function(){var _createStreamRun=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee91(e){return _regenerator().w(function(_context91){while(1)switch(_context91.n){case 0:e.stream=!0;this._waitingForStreamResponse=!0;_context91.n=1;return M.request(this,e,this._messages,!0,!0);case 1:this._messageStream=_context91.v;case 2:return _context91.a(2);}},_callee91,this);}));function createStreamRun(_x185){return _createStreamRun.apply(this,arguments);}return createStreamRun;}()}],[{key:"processImageMessage",value:function processImageMessage(e,t){var s=t==null?void 0:t.filter(function(i){return ee.isImageFileExtension(i.name);}).map(function(i){return{type:"image_file",image_file:{file_id:i.id}};});if(s&&s.length>0)return e.text&&e.text.length>0&&s.push(_defineProperty({type:"text"},y,e.text)),{content:s,role:"user"};}},{key:"processAttachmentsMessage",value:function processAttachmentsMessage(e,t,s){return{attachments:t.map(function(n){return{tools:[{type:s}],file_id:n.id};}),content:[_defineProperty({type:"text"},y,e.text)],role:"user"};}}]);}(k);ot.POLLING_TIMEOUT_MS=500;var Xs=ot;var cn=/*#__PURE__*/function(_Xs){function cn(e){var _a$headers,_l$OpenAIBeta;var _this36;_classCallCheck(this,cn);var o,a,l,c,d;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.openAI,i=(o=t.openAI)==null?void 0:o.assistant,n=cn.buildUrlSegments(i);if(_this36=_callSuper(this,cn,[e,i,n,G.buildKeyVerificationDetails(),G.buildHeaders,s]),(_a$headers=(a=_this36.connectSettings).headers)!==null&&_a$headers!==void 0?_a$headers:a.headers={},(_l$OpenAIBeta=(l=_this36.connectSettings.headers)["OpenAI-Beta"])!==null&&_l$OpenAIBeta!==void 0?_l$OpenAIBeta:l["OpenAI-Beta"]="assistants=v2",_this36.shouldFetchHistory&&_this36.sessionId&&(_this36.fetchHistory=_this36.fetchHistoryFunc.bind(_assertThisInitialized(_this36))),_typeof(i)===T){var _ref57=(d=(c=e.directConnection)==null?void 0:c.openAI)==null?void 0:d.assistant,u=_ref57.function_handler,h=_ref57.files_tool_type;u&&(_this36.functionHandler=u),h&&(_this36.filesToolType=h);}return _this36;}_inherits(cn,_Xs);return _createClass(cn,null,[{key:"buildUrlSegments",value:function buildUrlSegments(e){var t=_typeof(e)=="object"&&e.custom_base_url||"https://api.openai.com/v1";return{threadsPrefix:"".concat(t,"/threads"),threadsPosfix:"",newAssistantUrl:"".concat(t,"/assistants"),createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:"".concat(t,"/files"),getFilesPrefix:"".concat(t,"/files/"),getFilesPostfix:"/content"};}}]);}(Xs);var Sn=/*#__PURE__*/function(){function Sn(){_classCallCheck(this,Sn);}return _createClass(Sn,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty({"api-key":e},R,N);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(e){return{url:"".concat(e.endpoint,"/openai/models?api-version=").concat(e.version),method:z,handleVerificationResult:G.handleVerificationResult};}},{key:"validateURLDetails",value:function validateURLDetails(e){var t=e.endpoint,s=e.version,i=e.deploymentId;return t&&s&&i;}}]);}();Sn.URL_DETAILS_ERROR_MESSAGE="Please define the Azure URL Details. [More Information](https://deepchat.dev/docs/directConnection/Azure)";var Ce=Sn;var Pt=/*#__PURE__*/function(_Xs2){function Pt(e){var _g$headers;var _this37;_classCallCheck(this,Pt);var c,d,u,h,f,m,p,g;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.azure,i=(c=t.azure)==null?void 0:c.openAI,n=(i==null?void 0:i.urlDetails)||{},o="".concat((d=i==null?void 0:i.urlDetails)==null?void 0:d.endpoint,"/openai/"),a="?api-version=".concat((u=i==null?void 0:i.urlDetails)==null?void 0:u.version),l={threadsPrefix:"".concat(o).concat(Pt.THREAD_RESOURCE),threadsPosfix:a,newAssistantUrl:"".concat(o).concat(Pt.NEW_ASSISTANT_RESOURCE).concat(a),createMessagePostfix:a,listMessagesPostfix:"order=desc&api-version=".concat((h=i==null?void 0:i.urlDetails)==null?void 0:h.version),storeFiles:"".concat(o,"files").concat(a),getFilesPrefix:"".concat(o,"files/"),getFilesPostfix:"/content".concat(a)};if(_this37=_callSuper(this,Pt,[e,i==null?void 0:i.assistant,l,Ce.buildKeyVerificationDetails(n),Ce.buildHeaders,s]),_this37.permittedErrorPrefixes=[Ce.URL_DETAILS_ERROR_MESSAGE],_this37.insertKeyPlaceholderText=_this37.genereteAPIKeyName("Azure OpenAI"),_this37.keyHelpUrl="https://learn.microsoft.com/en-us/answers/questions/1193991/how-to-get-the-value-of-openai-api-key",_this37.isTextInputDisabled=!1,_typeof(i==null?void 0:i.assistant)===T){var _ref59=(p=(m=(f=e.directConnection)==null?void 0:f.azure)==null?void 0:m.openAI)==null?void 0:p.assistant,E=_ref59.function_handler,I=_ref59.files_tool_type;E&&(_this37.functionHandler=E),I&&(_this37.filesToolType=I);}Ce.validateURLDetails(n)?(_g$headers=(g=_this37.connectSettings).headers)!==null&&_g$headers!==void 0?_g$headers:g.headers={}:(_this37.isTextInputDisabled=!0,_this37.canSendMessage=function(){return!1;},setTimeout(function(){e.addMessage(_defineProperty({},je,Ce.URL_DETAILS_ERROR_MESSAGE));}));return _this37;}_inherits(Pt,_Xs2);return _createClass(Pt);}(Xs);Pt.THREAD_RESOURCE="threads",Pt.NEW_ASSISTANT_RESOURCE="assistants";var qi=Pt;var q=/*#__PURE__*/function(){function q(){_classCallCheck(this,q);}return _createClass(q,null,[{key:"addAttributes",value:function addAttributes(e){e.role="button",e.setAttribute("tabindex","0");}},{key:"addAriaBusy",value:function addAriaBusy(e){e.setAttribute("aria-busy","true");}},{key:"removeAriaBusy",value:function removeAriaBusy(e){e.removeAttribute("aria-busy");}},{key:"addAriaDisabled",value:function addAriaDisabled(e){e.setAttribute("aria-disabled","true");}},{key:"removeAriaDisabled",value:function removeAriaDisabled(e){e.removeAttribute("aria-disabled");}},{key:"removeAriaAttributes",value:function removeAriaAttributes(e){q.removeAriaBusy(e),q.removeAriaDisabled(e);}}]);}();var Cr="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<svg height=\"1.4em\" width=\"1.4em\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n\t viewBox=\"0 0 490.9 490.9\" xml:space=\"preserve\">\n\t<g>\n\t\t<g>\n\t\t\t<path d=\"M245.5,322.9c53,0,96.2-43.2,96.2-96.2V96.2c0-53-43.2-96.2-96.2-96.2s-96.2,43.2-96.2,96.2v130.5\n\t\t\t\tC149.3,279.8,192.5,322.9,245.5,322.9z M173.8,96.2c0-39.5,32.2-71.7,71.7-71.7s71.7,32.2,71.7,71.7v130.5\n\t\t\t\tc0,39.5-32.2,71.7-71.7,71.7s-71.7-32.2-71.7-71.7V96.2z\"/>\n\t\t\t<path d=\"M94.4,214.5c-6.8,0-12.3,5.5-12.3,12.3c0,85.9,66.7,156.6,151.1,162.8v76.7h-63.9c-6.8,0-12.3,5.5-12.3,12.3\n\t\t\t\ts5.5,12.3,12.3,12.3h152.3c6.8,0,12.3-5.5,12.3-12.3s-5.5-12.3-12.3-12.3h-63.9v-76.7c84.4-6.3,151.1-76.9,151.1-162.8\n\t\t\t\tc0-6.8-5.5-12.3-12.3-12.3s-12.3,5.5-12.3,12.3c0,76.6-62.3,138.9-138.9,138.9s-138.9-62.3-138.9-138.9\n\t\t\t\tC106.6,220,101.2,214.5,94.4,214.5z\"/>\n\t\t</g>\n\t</g>\n</svg>\n",be=/*#__PURE__*/function(){function be(){_classCallCheck(this,be);}return _createClass(be,null,[{key:"createTextElement",value:function createTextElement(e){var t=document.createElement("div");return t.classList.add(be.INPUT_BUTTON_INNER_TEXT_CLASS),t.innerText=e,t;}},{key:"tryAddSVGElement",value:function tryAddSVGElement(e,t,s,i){s?e.push(Qe.createSVGElement(s)):s!==""&&i&&e.push(t);}},{key:"createCustomElements",value:function createCustomElements(e,t,s){var l,c;var i=s==null?void 0:s[e],n=(l=i==null?void 0:i.text)==null?void 0:l.content,o=(c=i==null?void 0:i.svg)==null?void 0:c.content,a=[];return be.tryAddSVGElement(a,t,o,n),n&&a.push(be.createTextElement(n)),a.length>0?a:void 0;}},{key:"reassignClassBasedOnChildren",value:function reassignClassBasedOnChildren(e,t){e.classList.remove(be.INPUT_BUTTON_SVG_CLASS,be.INPUT_BUTTON_SVG_TEXT_CLASS),t.find(function(s){return s.classList.contains(be.INPUT_BUTTON_INNER_TEXT_CLASS);})?t.length>1&&e.classList.add(be.INPUT_BUTTON_SVG_TEXT_CLASS):e.classList.add(be.INPUT_BUTTON_SVG_CLASS);}}]);}();be.INPUT_BUTTON_SVG_TEXT_CLASS="input-button-svg-text",be.INPUT_BUTTON_INNER_TEXT_CLASS="text-button",be.INPUT_BUTTON_SVG_CLASS="input-button-svg";var He=be;var us=/*#__PURE__*/function(){function us(){_classCallCheck(this,us);}return _createClass(us,null,[{key:"parseSVGTextElements",value:function parseSVGTextElements(e){return _defineProperty({svg:e.find(function(t){return t.tagName.toLowerCase()==="svg";})},y,e.find(function(t){return t.tagName.toLowerCase()==="div";}));}}]);}();var $=/*#__PURE__*/function(){function $(){_classCallCheck(this,$);}return _createClass($,null,[{key:"unsetAllCSS",value:function unsetAllCSS(e,t){var n,o;t.container&&U.unsetAllCSSMouseStates(e,t.container);var _us$parseSVGTextEleme=us.parseSVGTextElements(Array.from(e.children)),s=_us$parseSVGTextEleme.svg,i=_us$parseSVGTextEleme.text;(n=t.svg)!=null&&n.styles&&s&&U.unsetAllCSSMouseStates(s,t.svg.styles),(o=t.text)!=null&&o.styles&&i&&U.unsetAllCSSMouseStates(i,t.text.styles);}},{key:"unsetActionCSS",value:function unsetActionCSS(e,t){var n,o;t.container&&U.unsetActivityCSSMouseStates(e,t.container);var _us$parseSVGTextEleme2=us.parseSVGTextElements(Array.from(e.children)),s=_us$parseSVGTextEleme2.svg,i=_us$parseSVGTextEleme2.text;(n=t.svg)!=null&&n.styles&&s&&U.unsetActivityCSSMouseStates(s,t.svg.styles),(o=t.text)!=null&&o.styles&&i&&U.unsetActivityCSSMouseStates(i,t.text.styles);}},{key:"setElementsCSS",value:function setElementsCSS(e,t,s){var o,a,l,c,d;Object.assign(e.style,(o=t.container)==null?void 0:o[s]);var _us$parseSVGTextEleme3=us.parseSVGTextElements(Array.from(e.children)),i=_us$parseSVGTextEleme3.svg,n=_us$parseSVGTextEleme3.text;i&&Object.assign(i.style,(l=(a=t.svg)==null?void 0:a.styles)==null?void 0:l[s]),n&&Object.assign(n.style,(d=(c=t.text)==null?void 0:c.styles)==null?void 0:d[s]);}},{key:"setElementCssUpToState",value:function setElementCssUpToState(e,t,s){$.setElementsCSS(e,t,"default"),s!=="default"&&($.setElementsCSS(e,t,"hover"),s!=="hover"&&$.setElementsCSS(e,t,"click"));}}]);}();var It=/*#__PURE__*/function(){// prettier-ignore
182
182
  function It(e,t,s,i,n,o){_classCallCheck(this,It);this._mouseState={state:"default"},this.isCustom=!1,q.addAttributes(e),this.elementRef=e,this.svg=Qe.createSVGElement(t),this.customStyles=n,this.position=s,this._tooltipSettings=i,this.dropupText=o;}return _createClass(It,[{key:"buttonMouseLeave",value:function buttonMouseLeave(e){var t;this._mouseState.state="default",((t=this._activeTooltip)==null?void 0:t.element.style.visibility)==="visible"&&this._tooltipSettings&&Le.hide(this._activeTooltip,this._tooltipSettings),e&&($.unsetAllCSS(this.elementRef,e),$.setElementsCSS(this.elementRef,e,"default"));}},{key:"buttonMouseEnter",value:function buttonMouseEnter(e){var t;this._mouseState.state="hover",this._tooltipSettings&&(this._activeTooltip=Le.display(this.elementRef,this._tooltipSettings,(t=this._activeTooltip)==null?void 0:t.element)),e&&$.setElementsCSS(this.elementRef,e,"hover");}},{key:"buttonMouseUp",value:function buttonMouseUp(e){e&&$.unsetActionCSS(this.elementRef,e),this.buttonMouseEnter(e);}},{key:"buttonMouseDown",value:function buttonMouseDown(e){this._mouseState.state="click",e&&$.setElementsCSS(this.elementRef,e,"click");}// be careful not to use onclick as that is used for button functionality
183
- },{key:"setEvents",value:function setEvents(e){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,e),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,e),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,e),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,e);}},{key:"unsetCustomStateStyles",value:function unsetCustomStateStyles(e){if(this.customStyles)for(var t=0;t<e.length;t+=1){var _s2=e[t],i=_s2&&this.customStyles[_s2];i&&$.unsetActionCSS(this.elementRef,i);}}},{key:"reapplyStateStyle",value:function reapplyStateStyle(e,t){if(!this.customStyles)return;t&&this.unsetCustomStateStyles(t);var s=this.customStyles[e];s&&$.setElementCssUpToState(this.elementRef,s,this._mouseState.state),this.setEvents(s);}},{key:"changeElementsByState",value:function changeElementsByState(e){var _this$elementRef;(_this$elementRef=this.elementRef).replaceChildren.apply(_this$elementRef,_toConsumableArray(e)),He.reassignClassBasedOnChildren(this.elementRef,e);}},{key:"buildDefaultIconElement",value:function buildDefaultIconElement(e){var t=this.svg.cloneNode(!0);return t.id=e,[t];}},{key:"createInnerElements",value:function createInnerElements(e,t,s){var i=He.createCustomElements(t,this.svg,s);if(i&&i.length>0){if(this.position==="dropup-menu"){var n=this.svg.cloneNode(!0);n.id=i[0]===this.svg?e:"dropup-menu-item-icon-element-custom",i[0]=n;}return i;}return this.buildDefaultIconElement(e);}}]);}();var vi=/*#__PURE__*/function(_It){function vi(e){var _this38;_classCallCheck(this,vi);var s,i;var t=((i=(s=e==null?void 0:e["default"])==null?void 0:s.svg)==null?void 0:i.content)||vi.EMPTY_SVG;_this38=_callSuper(this,vi,[document.createElement("div"),t,void 0,void 0,e]),_this38.isActive=!1,_this38._innerElements=_this38.createInnerElementsForStates(_this38.customStyles),_this38.changeToDefault();return _this38;}_inherits(vi,_It);return _createClass(vi,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(e){return{"default":this.createInnerButtonElements("default",e),active:this.createInnerButtonElements("active",e),unavailable:this.createInnerButtonElements("unavailable",e)};}},{key:"createInnerButtonElements",value:function createInnerButtonElements(e,t){return He.createCustomElements(e,this.svg,t)||[this.svg];}},{key:"changeState",value:function changeState(e){this.changeElementsByState(e),this.elementRef.classList.replace(He.INPUT_BUTTON_SVG_CLASS,"deep-chat-openai-realtime-button");}},{key:"changeToActive",value:function changeToActive(){this.changeState(this._innerElements.active),this.reapplyStateStyle("active",["unavailable","default"]),this.isActive=!0;}},{key:"changeToDefault",value:function changeToDefault(){var e,t,s,i;this.changeState(this._innerElements["default"]),(e=this.customStyles)!=null&&e.active&&$.unsetAllCSS(this.elementRef,(t=this.customStyles)==null?void 0:t.active),(s=this.customStyles)!=null&&s.unavailable&&$.unsetAllCSS(this.elementRef,(i=this.customStyles)==null?void 0:i.unavailable),this.reapplyStateStyle("default",["active","unavailable"]),this.isActive=!1;}},{key:"changeToUnavailable",value:function changeToUnavailable(){var e,t,s,i;this.changeState(this._innerElements.unavailable),(e=this.customStyles)!=null&&e.active&&$.unsetAllCSS(this.elementRef,(t=this.customStyles)==null?void 0:t.active),(s=this.customStyles)!=null&&s["default"]&&$.unsetAllCSS(this.elementRef,(i=this.customStyles)==null?void 0:i["default"]),this.reapplyStateStyle("unavailable",["default","active"]),this.isActive=!1;}}]);}(It);vi.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';var Ys=vi;var oe=/*#__PURE__*/function(){function oe(){_classCallCheck(this,oe);}return _createClass(oe,null,[{key:"setPropertyValueIfDoesNotExist",value:function setPropertyValueIfDoesNotExist(e,t,s){var _e$i,_e$i2;var i=t[0];t.length===1?(_e$i=e[i])!==null&&_e$i!==void 0?_e$i:e[i]=s:((_e$i2=e[i])!==null&&_e$i2!==void 0?_e$i2:e[i]={},t.shift(),oe.setPropertyValueIfDoesNotExist(e[i],t,s));}},{key:"setPropertyValue",value:function setPropertyValue(e,t,s){var _e$i3;var i=t[0];t.length===1?e[i]=s:((_e$i3=e[i])!==null&&_e$i3!==void 0?_e$i3:e[i]={},t.shift(),oe.setPropertyValue(e[i],t,s));}},{key:"getObjectValue",value:function getObjectValue(e,t){var s=t[0],i=e[s];return i===void 0||t.length===1?i:oe.getObjectValue(i,t.slice(1));}},{key:"overwritePropertyObjectFromAnother",value:function overwritePropertyObjectFromAnother(e,t,s){var i=oe.getObjectValue(t,s);if(i){var n=_objectSpread(_objectSpread({},i),oe.getObjectValue(e,s)||{});oe.setPropertyValue(e,s,n);}}},{key:"isJson",value:function isJson(e){try{return JSON.stringify(e),!0;}catch(_unused8){return!1;}}// prettier-ignore
183
+ },{key:"setEvents",value:function setEvents(e){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,e),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,e),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,e),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,e);}},{key:"unsetCustomStateStyles",value:function unsetCustomStateStyles(e){if(this.customStyles)for(var t=0;t<e.length;t+=1){var _s2=e[t],i=_s2&&this.customStyles[_s2];i&&$.unsetActionCSS(this.elementRef,i);}}},{key:"reapplyStateStyle",value:function reapplyStateStyle(e,t){if(!this.customStyles)return;t&&this.unsetCustomStateStyles(t);var s=this.customStyles[e];s&&$.setElementCssUpToState(this.elementRef,s,this._mouseState.state),this.setEvents(s);}},{key:"changeElementsByState",value:function changeElementsByState(e){var _this$elementRef;(_this$elementRef=this.elementRef).replaceChildren.apply(_this$elementRef,_toConsumableArray(e)),He.reassignClassBasedOnChildren(this.elementRef,e);}},{key:"buildDefaultIconElement",value:function buildDefaultIconElement(e){var t=this.svg.cloneNode(!0);return t.id=e,[t];}},{key:"createInnerElements",value:function createInnerElements(e,t,s){var i=He.createCustomElements(t,this.svg,s);if(i&&i.length>0){if(this.position==="dropup-menu"){var n=this.svg.cloneNode(!0);n.id=i[0]===this.svg?e:"dropup-menu-item-icon-element-custom",i[0]=n;}return i;}return this.buildDefaultIconElement(e);}}]);}();var vi=/*#__PURE__*/function(_It){function vi(e){var _this38;_classCallCheck(this,vi);var s,i;var t=((i=(s=e==null?void 0:e["default"])==null?void 0:s.svg)==null?void 0:i.content)||vi.EMPTY_SVG;_this38=_callSuper(this,vi,[document.createElement("div"),t,void 0,void 0,e]),_this38.isActive=!1,_this38._innerElements=_this38.createInnerElementsForStates(_this38.customStyles),_this38.changeToDefault();return _this38;}_inherits(vi,_It);return _createClass(vi,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(e){return{"default":this.createInnerButtonElements("default",e),active:this.createInnerButtonElements("active",e),unavailable:this.createInnerButtonElements("unavailable",e)};}},{key:"createInnerButtonElements",value:function createInnerButtonElements(e,t){return He.createCustomElements(e,this.svg,t)||[this.svg];}},{key:"changeState",value:function changeState(e){this.changeElementsByState(e),this.elementRef.classList.replace(He.INPUT_BUTTON_SVG_CLASS,"deep-chat-openai-realtime-button");}},{key:"changeToActive",value:function changeToActive(){this.changeState(this._innerElements.active),this.reapplyStateStyle("active",["unavailable","default"]),this.isActive=!0;}},{key:"changeToDefault",value:function changeToDefault(){var e,t,s,i;this.changeState(this._innerElements["default"]),(e=this.customStyles)!=null&&e.active&&$.unsetAllCSS(this.elementRef,(t=this.customStyles)==null?void 0:t.active),(s=this.customStyles)!=null&&s.unavailable&&$.unsetAllCSS(this.elementRef,(i=this.customStyles)==null?void 0:i.unavailable),this.reapplyStateStyle("default",["active","unavailable"]),this.isActive=!1;}},{key:"changeToUnavailable",value:function changeToUnavailable(){var e,t,s,i;this.changeState(this._innerElements.unavailable),(e=this.customStyles)!=null&&e.active&&$.unsetAllCSS(this.elementRef,(t=this.customStyles)==null?void 0:t.active),(s=this.customStyles)!=null&&s["default"]&&$.unsetAllCSS(this.elementRef,(i=this.customStyles)==null?void 0:i["default"]),this.reapplyStateStyle("unavailable",["default","active"]),this.isActive=!1;}}]);}(It);vi.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';var Ys=vi;var ae=/*#__PURE__*/function(){function ae(){_classCallCheck(this,ae);}return _createClass(ae,null,[{key:"setPropertyValueIfDoesNotExist",value:function setPropertyValueIfDoesNotExist(e,t,s){var _e$i,_e$i2;var i=t[0];t.length===1?(_e$i=e[i])!==null&&_e$i!==void 0?_e$i:e[i]=s:((_e$i2=e[i])!==null&&_e$i2!==void 0?_e$i2:e[i]={},t.shift(),ae.setPropertyValueIfDoesNotExist(e[i],t,s));}},{key:"setPropertyValue",value:function setPropertyValue(e,t,s){var _e$i3;var i=t[0];t.length===1?e[i]=s:((_e$i3=e[i])!==null&&_e$i3!==void 0?_e$i3:e[i]={},t.shift(),ae.setPropertyValue(e[i],t,s));}},{key:"getObjectValue",value:function getObjectValue(e,t){var s=t[0],i=e[s];return i===void 0||t.length===1?i:ae.getObjectValue(i,t.slice(1));}},{key:"overwritePropertyObjectFromAnother",value:function overwritePropertyObjectFromAnother(e,t,s){var i=ae.getObjectValue(t,s);if(i){var n=_objectSpread(_objectSpread({},i),ae.getObjectValue(e,s)||{});ae.setPropertyValue(e,s,n);}}},{key:"isJson",value:function isJson(e){try{return JSON.stringify(e),!0;}catch(_unused8){return!1;}}// prettier-ignore
184
184
  },{key:"assignPropertyFromOneToAnother",value:function assignPropertyFromOneToAnother(e,t,s){var _t$e;(_t$e=t[e])!==null&&_t$e!==void 0?_t$e:t[e]={},Object.assign(t[e],s==null?void 0:s[e]);}}]);}();var _i=/*#__PURE__*/_createClass(function _i(){_classCallCheck(this,_i);});_i.SESSION_STARTED="sts-session-started",_i.SESSION_STOPPED="sts-session-stopped";var Zs=_i;var wr="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z\"></path>\n</svg>",Vi="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z\"></path>\n</svg>",O=/*#__PURE__*/function(_k6){function O(e){var _c$model;var _this39;_classCallCheck(this,O);var n,o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=O.getKey(e);_this39=_callSuper(this,O,[e,G.buildKeyVerificationDetails(),G.buildHeaders,{key:s}]),_this39.insertKeyPlaceholderText=_this39.genereteAPIKeyName("OpenAI"),_this39.keyHelpUrl="https://platform.openai.com/account/api-keys",_this39._microphoneButton=null,_this39._toggleButton=null,_this39._errorElement=null,_this39._loadingElement=null,_this39._pc=null,_this39._mediaStream=null,_this39._isMuted=!1;var i=(n=t.openAI)==null?void 0:n.realtime;if(_typeof(i)===T){_this39._avatarConfig=i.avatar,_this39._ephemeralKey=i.ephemeralKey,_this39._errorConfig=i.error,_this39._loadingConfig=i.loading,Object.assign(_this39.rawBody,i.config);var d=(a=(o=e.directConnection)==null?void 0:o.openAI)==null?void 0:a.realtime,_ref61=d.config||{},u=_ref61.function_handler;u&&(_this39._functionHandler=u),_this39._events=i.events,d.methods=_this39.generateMethods(),_this39.setInputAudioTranscribe(e,(l=d.config)==null?void 0:l.input_audio_transcription);}(_c$model=(c=_this39.rawBody).model)!==null&&_c$model!==void 0?_c$model:c.model="gpt-4o-realtime-preview-2025-06-03",_this39._avatarConfig=O.buildAvatarConfig(i),_this39._buttonsConfig=O.buildButtonsConfig(i),_this39._avatarEl=O.createAvatar(_this39._avatarConfig),_this39._containerEl=_this39.createContainer(),_this39._deepChat=e;return _this39;}_inherits(O,_k6);return _createClass(O,[{key:"setInputAudioTranscribe",value:// https://community.openai.com/t/unable-to-access-user-audio-transcript-in-realtime-api/1001570/3
185
185
  function setInputAudioTranscribe(e,t){if(t){var _s3="whisper-1";_typeof(t)=="object"?this.rawBody.input_audio_transcription={model:t.model||_s3,language:t.language,prompt:t.prompt}:this.rawBody.input_audio_transcription={model:_s3};}else e.onMessage&&(console.warn("To get user audio transcription, set `input_audio_transcription` in the `realtime` config."),console.warn("See: https://deepchat.dev/docs/directConnection/OpenAI/OpenAIRealtime#OpenAIRealtimeConfig"));}// called after API key was inserted
186
- },{key:"setUpView",value:function setUpView(e,t){e.style.display="none",t.appendChild(this._containerEl),this.setup();}},{key:"setup",value:function(){var _setup=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee92(){var i,e,t,s;return _regenerator().w(function(_context92){while(1)switch(_context92.n){case 0:e=(i=this._deepChat.directConnection)==null?void 0:i.openAI;if(e){_context92.n=1;break;}return _context92.a(2);case 1:t=e==null?void 0:e.realtime;if(!(_typeof(t)!="object"||!t.autoStart&&!t.autoFetchEphemeralKey)){_context92.n=2;break;}return _context92.a(2);case 2:s=this.key||e.key;(t.fetchEphemeralKey||s)&&t.autoStart&&(this.changeToUnavailable(),this.displayLoading()),this.fetchEphemeralKey(t.autoStart);case 3:return _context92.a(2);}},_callee92,this);}));function setup(){return _setup.apply(this,arguments);}return setup;}()},{key:"fetchEphemeralKey",value:function(){var _fetchEphemeralKey=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee93(e){var o,t,s,i,n,a,_t30,_t31,_t32;return _regenerator().w(function(_context93){while(1)switch(_context93.p=_context93.n){case 0:t=(o=this._deepChat.directConnection)==null?void 0:o.openAI,s=_typeof(t==null?void 0:t.realtime)=="object"?t==null?void 0:t.realtime.fetchEphemeralKey:void 0,i=t==null?void 0:t.realtime,n=this.key||t.key;if(!(_typeof(i)=="object")){_context93.n=8;break;}if(this._ephemeralKey){_context93.n=7;break;}_context93.p=1;if(!s){_context93.n=3;break;}a=s();a.then&&(this._retrievingEphemeralKey=a);_context93.n=2;return a;case 2:this._ephemeralKey=_context93.v;_context93.n=5;break;case 3:_t30=n;if(!_t30){_context93.n=5;break;}this._retrievingEphemeralKey=this.getEphemeralKey(n);_context93.n=4;return this._retrievingEphemeralKey;case 4:this._ephemeralKey=_context93.v;case 5:_context93.n=7;break;case 6:_context93.p=6;_t31=_context93.v;this.displayFailedToRetrieveEphemeralKey(_t31);case 7:this._ephemeralKey&&(e?this.init(this._ephemeralKey):this.changeToAvailable());_context93.n=12;break;case 8:if(!n){_context93.n=12;break;}_context93.p=9;this._retrievingEphemeralKey=this.getEphemeralKey(n);_context93.n=10;return this._retrievingEphemeralKey;case 10:this._ephemeralKey=_context93.v;e&&this.init(this._ephemeralKey);_context93.n=12;break;case 11:_context93.p=11;_t32=_context93.v;this.displayFailedToRetrieveEphemeralKey(_t32);case 12:return _context93.a(2);}},_callee93,this,[[9,11],[1,6]]);}));function fetchEphemeralKey(_x186){return _fetchEphemeralKey.apply(this,arguments);}return fetchEphemeralKey;}()},{key:"getEphemeralKey",value:function(){var _getEphemeralKey=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee94(e){return _regenerator().w(function(_context94){while(1)switch(_context94.n){case 0:_context94.n=1;return fetch("https://api.openai.com/v1/realtime/sessions",{method:Z,body:JSON.stringify(this.rawBody),headers:_defineProperty(_defineProperty({},R,N),K,"".concat(te).concat(e))});case 1:_context94.n=2;return _context94.v.json();case 2:return _context94.a(2,_context94.v.client_secret.value);}},_callee94,this);}));function getEphemeralKey(_x187){return _getEphemeralKey.apply(this,arguments);}return getEphemeralKey;}()},{key:"generateMethods",value:function generateMethods(){var _this40=this;return{updateConfig:function updateConfig(e){var t;(t=_this40._dc)==null||t.send(JSON.stringify({type:"session.update",session:e}));},sendMessage:function sendMessage(e,t){var s=t||"system",n={role:s,type:"message",content:[{type:s==="system"||s==="user"?"input_text":"text",text:e}]};_this40.sendMessage(n);}};}},{key:"createContainer",value:function createContainer(){var e=document.createElement("div");return e.id="deep-chat-openai-realtime-container",e.appendChild(this.createAvatarContainer()),e.appendChild(this.createButtonsContainer()),e.appendChild(this.createError()),e;}},{key:"createAvatarContainer",value:function createAvatarContainer(){var t,s;var e=document.createElement("div");return e.id="deep-chat-openai-realtime-avatar-container",Object.assign(e.style,(s=(t=this._avatarConfig)==null?void 0:t.styles)==null?void 0:s.container),e.appendChild(this._avatarEl),e;}},{key:"createButtonsContainer",value:function createButtonsContainer(){var i;var e=document.createElement("div");e.id="deep-chat-openai-realtime-buttons-container",Object.assign(e.style,(i=this._buttonsConfig)==null?void 0:i.container),this._microphoneButton=this.createMicophoneButton();var t=O.createButtonContainer(this._microphoneButton.elementRef);this._toggleButton=this.createToggleButton();var s=O.createButtonContainer(this._toggleButton.elementRef);return e.appendChild(t),e.appendChild(s),e.appendChild(this.createLoading()),e;}},{key:"createMicophoneButton",value:function createMicophoneButton(){var _this41=this;var t;var e=new Ys((t=this._buttonsConfig)==null?void 0:t.microphone);return e.elementRef.classList.add(O.BUTTON_DEFAULT,"deep-chat-openai-realtime-microphone"),e.elementRef.onclick=function(){e.isActive?(_this41.toggleMicorphone(!0),e.elementRef.classList.replace(O.MICROPHONE_ACTIVE,O.BUTTON_DEFAULT),e.changeToDefault(),_this41._isMuted=!1):(_this41.toggleMicorphone(!1),e.elementRef.classList.replace(O.BUTTON_DEFAULT,O.MICROPHONE_ACTIVE),q.removeAriaAttributes(e.elementRef),e.changeToActive(),_this41._isMuted=!0);},e;}},{key:"toggleMicorphone",value:function toggleMicorphone(e){var t;(t=this._mediaStream)==null||t.getAudioTracks().forEach(function(s){return s.enabled=e;});}},{key:"createToggleButton",value:function createToggleButton(){var _this42=this;var t;var e=new Ys((t=this._buttonsConfig)==null?void 0:t.toggle);return e.elementRef.classList.add(O.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),e.elementRef.onclick=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee95(){var s,i,_t33,_t34;return _regenerator().w(function(_context95){while(1)switch(_context95.p=_context95.n){case 0:if(!e.isActive){_context95.n=1;break;}e.changeToDefault(),_this42.stop();_context95.n=9;break;case 1:_context95.p=1;if(!_this42._ephemeralKey){_context95.n=3;break;}_this42.displayLoading();_context95.n=2;return _this42.init(_this42._ephemeralKey);case 2:_context95.n=7;break;case 3:if(!_this42._retrievingEphemeralKey){_context95.n=6;break;}_this42.displayLoading();_context95.n=4;return _this42._retrievingEphemeralKey;case 4:i=_context95.v;_t33=(s=_this42._toggleButton)!=null&&s.isActive;if(!_t33){_context95.n=5;break;}_context95.n=5;return _this42.init(i);case 5:_context95.n=7;break;case 6:_this42.displayLoading();_context95.n=7;return _this42.fetchEphemeralKey(!0);case 7:_context95.n=9;break;case 8:_context95.p=8;_t34=_context95.v;console.error("Failed to start conversation:",_t34),_this42.displayError(),_this42.hideLoading();case 9:return _context95.a(2);}},_callee95,null,[[1,8]]);})),e;}},{key:"init",value:function(){var _init2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee98(e){var _this43=this;var t,s,i,n,o,a,l,c,_t37,_t38,_t39,_t40;return _regenerator().w(function(_context98){while(1)switch(_context98.p=_context98.n){case 0:t=new RTCPeerConnection();this._pc=t;s=document.createElement("audio");s.autoplay=!0;i=new AudioContext(),n=i.createAnalyser();n.fftSize=256;o=new Uint8Array(n.frequencyBinCount);this._pc.ontrack=/*#__PURE__*/function(){var _ref63=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee96(a){var l,_t35;return _regenerator().w(function(_context96){while(1)switch(_context96.n){case 0:if(!a.streams[0]){_context96.n=2;break;}s.srcObject=a.streams[0];l=i.createMediaStreamSource(a.streams[0]);_t35=i.state==="suspended";if(!_t35){_context96.n=1;break;}_context96.n=1;return i.resume();case 1:l.connect(n);_this43.monitorFrequencies(n,o);_context96.n=3;break;case 2:console.error("No streams found in the ontrack event."),_this43.displayError();case 3:return _context96.a(2);}},_callee96);}));return function(_x189){return _ref63.apply(this,arguments);};}();_context98.n=1;return navigator.mediaDevices.getUserMedia({audio:!0}).then(function(a){var l;t===_this43._pc&&(_this43._mediaStream=a,(l=_this43._pc)==null||l.addTrack(_this43._mediaStream.getTracks()[0]),_this43._isMuted&&_this43.toggleMicorphone(!1));})["catch"](function(a){console.error("Error accessing microphone:",a),_this43.displayError();});case 1:this._dc=this._pc.createDataChannel("oai-events");this._dc.addEventListener("message",/*#__PURE__*/function(){var _ref64=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee97(a){var c,d,u,l,f,m,p,_t36;return _regenerator().w(function(_context97){while(1)switch(_context97.p=_context97.n){case 0:l=JSON.parse(a.data);if(!(l.type==="session.created")){_context97.n=1;break;}_this43.removeUnavailable(),_this43._toggleButton&&(q.removeAriaAttributes(_this43._toggleButton.elementRef),_this43._toggleButton.changeToActive()),(d=(c=_this43._events)==null?void 0:c.started)==null||d.call(c),_this43._deepChat.dispatchEvent(new CustomEvent(Zs.SESSION_STARTED)),_this43.hideLoading();_context97.n=7;break;case 1:if(!(l.type==="response.done")){_context97.n=6;break;}f=(u=JSON.parse(a.data).response.output)==null?void 0:u[0];if(!((f==null?void 0:f.type)==="function_call")){_context97.n=5;break;}m=f.name,p=f.call_id;_context97.p=2;_context97.n=3;return _this43.handleTool(m,f.arguments,p);case 3:_context97.n=5;break;case 4:_context97.p=4;_t36=_context97.v;_this43.stopOnError(_t36);case 5:_context97.n=7;break;case 6:l.type===je?_this43.stopOnError(l.error.message):l.type===we?_this43.stopOnError(l.message):l.type==="response.audio_transcript.delta"||(l.type==="response.audio_transcript.done"?l.transcript&&Ct.onMessage(_this43._deepChat,{role:"ai",text:l.transcript},!1):l.type==="conversation.item.input_audio_transcription.completed"&&l.transcript&&Ct.onMessage(_this43._deepChat,{role:"user",text:l.transcript},!1));case 7:return _context97.a(2);}},_callee97,null,[[2,4]]);}));return function(_x190){return _ref64.apply(this,arguments);};}());_context98.p=2;_context98.n=3;return this._pc.createOffer();case 3:a=_context98.v;_t37=t!==this._pc;if(_t37){_context98.n=5;break;}_context98.n=4;return this._pc.setLocalDescription(a);case 4:_t37=t!==this._pc;case 5:if(!_t37){_context98.n=6;break;}return _context98.a(2);case 6:_context98.n=7;return fetch("https://api.openai.com/v1/realtime",{method:Z,body:a.sdp,headers:_defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,"application/sdp")});case 7:l=_context98.v;if(!(t!==this._pc)){_context98.n=8;break;}return _context98.a(2);case 8:_context98.n=9;return l.text();case 9:_t38=_context98.v;c={type:"answer",sdp:_t38};_t39=t!==this._pc;if(_t39){_context98.n=11;break;}_context98.n=10;return this._pc.setRemoteDescription(c);case 10:_t39=t!==this._pc;case 11:if(!_t39){_context98.n=12;break;}return _context98.a(2);case 12:_context98.n=14;break;case 13:_context98.p=13;_t40=_context98.v;console.error(_t40),this.displayError();case 14:return _context98.a(2);}},_callee98,this,[[2,13]]);}));function init(_x188){return _init2.apply(this,arguments);}return init;}()// there is a bug where sometimes upon refreshing the browser too many times the frequencyData is all 0s
186
+ },{key:"setUpView",value:function setUpView(e,t){e.style.display="none",t.appendChild(this._containerEl),this.setup();}},{key:"setup",value:function(){var _setup=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee92(){var i,e,t,s;return _regenerator().w(function(_context92){while(1)switch(_context92.n){case 0:e=(i=this._deepChat.directConnection)==null?void 0:i.openAI;if(e){_context92.n=1;break;}return _context92.a(2);case 1:t=e==null?void 0:e.realtime;if(!(_typeof(t)!="object"||!t.autoStart&&!t.autoFetchEphemeralKey)){_context92.n=2;break;}return _context92.a(2);case 2:s=this.key||e.key;(t.fetchEphemeralKey||s)&&t.autoStart&&(this.changeToUnavailable(),this.displayLoading()),this.fetchEphemeralKey(t.autoStart);case 3:return _context92.a(2);}},_callee92,this);}));function setup(){return _setup.apply(this,arguments);}return setup;}()},{key:"fetchEphemeralKey",value:function(){var _fetchEphemeralKey=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee93(e){var o,t,s,i,n,a,_t30,_t31,_t32;return _regenerator().w(function(_context93){while(1)switch(_context93.p=_context93.n){case 0:t=(o=this._deepChat.directConnection)==null?void 0:o.openAI,s=_typeof(t==null?void 0:t.realtime)=="object"?t==null?void 0:t.realtime.fetchEphemeralKey:void 0,i=t==null?void 0:t.realtime,n=this.key||t.key;if(!(_typeof(i)=="object")){_context93.n=8;break;}if(this._ephemeralKey){_context93.n=7;break;}_context93.p=1;if(!s){_context93.n=3;break;}a=s();a.then&&(this._retrievingEphemeralKey=a);_context93.n=2;return a;case 2:this._ephemeralKey=_context93.v;_context93.n=5;break;case 3:_t30=n;if(!_t30){_context93.n=5;break;}this._retrievingEphemeralKey=this.getEphemeralKey(n);_context93.n=4;return this._retrievingEphemeralKey;case 4:this._ephemeralKey=_context93.v;case 5:_context93.n=7;break;case 6:_context93.p=6;_t31=_context93.v;this.displayFailedToRetrieveEphemeralKey(_t31);case 7:this._ephemeralKey&&(e?this.init(this._ephemeralKey):this.changeToAvailable());_context93.n=12;break;case 8:if(!n){_context93.n=12;break;}_context93.p=9;this._retrievingEphemeralKey=this.getEphemeralKey(n);_context93.n=10;return this._retrievingEphemeralKey;case 10:this._ephemeralKey=_context93.v;e&&this.init(this._ephemeralKey);_context93.n=12;break;case 11:_context93.p=11;_t32=_context93.v;this.displayFailedToRetrieveEphemeralKey(_t32);case 12:return _context93.a(2);}},_callee93,this,[[9,11],[1,6]]);}));function fetchEphemeralKey(_x186){return _fetchEphemeralKey.apply(this,arguments);}return fetchEphemeralKey;}()},{key:"getEphemeralKey",value:function(){var _getEphemeralKey=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee94(e){return _regenerator().w(function(_context94){while(1)switch(_context94.n){case 0:_context94.n=1;return fetch("https://api.openai.com/v1/realtime/sessions",{method:Z,body:JSON.stringify(this.rawBody),headers:_defineProperty(_defineProperty({},R,N),K,"".concat(se).concat(e))});case 1:_context94.n=2;return _context94.v.json();case 2:return _context94.a(2,_context94.v.client_secret.value);}},_callee94,this);}));function getEphemeralKey(_x187){return _getEphemeralKey.apply(this,arguments);}return getEphemeralKey;}()},{key:"generateMethods",value:function generateMethods(){var _this40=this;return{updateConfig:function updateConfig(e){var t;(t=_this40._dc)==null||t.send(JSON.stringify({type:"session.update",session:e}));},sendMessage:function sendMessage(e,t){var s=t||"system",n={role:s,type:"message",content:[{type:s==="system"||s==="user"?"input_text":"text",text:e}]};_this40.sendMessage(n);}};}},{key:"createContainer",value:function createContainer(){var e=document.createElement("div");return e.id="deep-chat-openai-realtime-container",e.appendChild(this.createAvatarContainer()),e.appendChild(this.createButtonsContainer()),e.appendChild(this.createError()),e;}},{key:"createAvatarContainer",value:function createAvatarContainer(){var t,s;var e=document.createElement("div");return e.id="deep-chat-openai-realtime-avatar-container",Object.assign(e.style,(s=(t=this._avatarConfig)==null?void 0:t.styles)==null?void 0:s.container),e.appendChild(this._avatarEl),e;}},{key:"createButtonsContainer",value:function createButtonsContainer(){var i;var e=document.createElement("div");e.id="deep-chat-openai-realtime-buttons-container",Object.assign(e.style,(i=this._buttonsConfig)==null?void 0:i.container),this._microphoneButton=this.createMicophoneButton();var t=O.createButtonContainer(this._microphoneButton.elementRef);this._toggleButton=this.createToggleButton();var s=O.createButtonContainer(this._toggleButton.elementRef);return e.appendChild(t),e.appendChild(s),e.appendChild(this.createLoading()),e;}},{key:"createMicophoneButton",value:function createMicophoneButton(){var _this41=this;var t;var e=new Ys((t=this._buttonsConfig)==null?void 0:t.microphone);return e.elementRef.classList.add(O.BUTTON_DEFAULT,"deep-chat-openai-realtime-microphone"),e.elementRef.onclick=function(){e.isActive?(_this41.toggleMicorphone(!0),e.elementRef.classList.replace(O.MICROPHONE_ACTIVE,O.BUTTON_DEFAULT),e.changeToDefault(),_this41._isMuted=!1):(_this41.toggleMicorphone(!1),e.elementRef.classList.replace(O.BUTTON_DEFAULT,O.MICROPHONE_ACTIVE),q.removeAriaAttributes(e.elementRef),e.changeToActive(),_this41._isMuted=!0);},e;}},{key:"toggleMicorphone",value:function toggleMicorphone(e){var t;(t=this._mediaStream)==null||t.getAudioTracks().forEach(function(s){return s.enabled=e;});}},{key:"createToggleButton",value:function createToggleButton(){var _this42=this;var t;var e=new Ys((t=this._buttonsConfig)==null?void 0:t.toggle);return e.elementRef.classList.add(O.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),e.elementRef.onclick=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee95(){var s,i,_t33,_t34;return _regenerator().w(function(_context95){while(1)switch(_context95.p=_context95.n){case 0:if(!e.isActive){_context95.n=1;break;}e.changeToDefault(),_this42.stop();_context95.n=9;break;case 1:_context95.p=1;if(!_this42._ephemeralKey){_context95.n=3;break;}_this42.displayLoading();_context95.n=2;return _this42.init(_this42._ephemeralKey);case 2:_context95.n=7;break;case 3:if(!_this42._retrievingEphemeralKey){_context95.n=6;break;}_this42.displayLoading();_context95.n=4;return _this42._retrievingEphemeralKey;case 4:i=_context95.v;_t33=(s=_this42._toggleButton)!=null&&s.isActive;if(!_t33){_context95.n=5;break;}_context95.n=5;return _this42.init(i);case 5:_context95.n=7;break;case 6:_this42.displayLoading();_context95.n=7;return _this42.fetchEphemeralKey(!0);case 7:_context95.n=9;break;case 8:_context95.p=8;_t34=_context95.v;console.error("Failed to start conversation:",_t34),_this42.displayError(),_this42.hideLoading();case 9:return _context95.a(2);}},_callee95,null,[[1,8]]);})),e;}},{key:"init",value:function(){var _init2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee98(e){var _this43=this;var t,s,i,n,o,a,l,c,_t37,_t38,_t39,_t40;return _regenerator().w(function(_context98){while(1)switch(_context98.p=_context98.n){case 0:t=new RTCPeerConnection();this._pc=t;s=document.createElement("audio");s.autoplay=!0;i=new AudioContext(),n=i.createAnalyser();n.fftSize=256;o=new Uint8Array(n.frequencyBinCount);this._pc.ontrack=/*#__PURE__*/function(){var _ref63=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee96(a){var l,_t35;return _regenerator().w(function(_context96){while(1)switch(_context96.n){case 0:if(!a.streams[0]){_context96.n=2;break;}s.srcObject=a.streams[0];l=i.createMediaStreamSource(a.streams[0]);_t35=i.state==="suspended";if(!_t35){_context96.n=1;break;}_context96.n=1;return i.resume();case 1:l.connect(n);_this43.monitorFrequencies(n,o);_context96.n=3;break;case 2:console.error("No streams found in the ontrack event."),_this43.displayError();case 3:return _context96.a(2);}},_callee96);}));return function(_x189){return _ref63.apply(this,arguments);};}();_context98.n=1;return navigator.mediaDevices.getUserMedia({audio:!0}).then(function(a){var l;t===_this43._pc&&(_this43._mediaStream=a,(l=_this43._pc)==null||l.addTrack(_this43._mediaStream.getTracks()[0]),_this43._isMuted&&_this43.toggleMicorphone(!1));})["catch"](function(a){console.error("Error accessing microphone:",a),_this43.displayError();});case 1:this._dc=this._pc.createDataChannel("oai-events");this._dc.addEventListener("message",/*#__PURE__*/function(){var _ref64=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee97(a){var c,d,u,l,f,m,p,_t36;return _regenerator().w(function(_context97){while(1)switch(_context97.p=_context97.n){case 0:l=JSON.parse(a.data);if(!(l.type==="session.created")){_context97.n=1;break;}_this43.removeUnavailable(),_this43._toggleButton&&(q.removeAriaAttributes(_this43._toggleButton.elementRef),_this43._toggleButton.changeToActive()),(d=(c=_this43._events)==null?void 0:c.started)==null||d.call(c),_this43._deepChat.dispatchEvent(new CustomEvent(Zs.SESSION_STARTED)),_this43.hideLoading();_context97.n=7;break;case 1:if(!(l.type==="response.done")){_context97.n=6;break;}f=(u=JSON.parse(a.data).response.output)==null?void 0:u[0];if(!((f==null?void 0:f.type)==="function_call")){_context97.n=5;break;}m=f.name,p=f.call_id;_context97.p=2;_context97.n=3;return _this43.handleTool(m,f.arguments,p);case 3:_context97.n=5;break;case 4:_context97.p=4;_t36=_context97.v;_this43.stopOnError(_t36);case 5:_context97.n=7;break;case 6:l.type===je?_this43.stopOnError(l.error.message):l.type===we?_this43.stopOnError(l.message):l.type==="response.audio_transcript.delta"||(l.type==="response.audio_transcript.done"?l.transcript&&Ct.onMessage(_this43._deepChat,{role:"ai",text:l.transcript},!1):l.type==="conversation.item.input_audio_transcription.completed"&&l.transcript&&Ct.onMessage(_this43._deepChat,{role:"user",text:l.transcript},!1));case 7:return _context97.a(2);}},_callee97,null,[[2,4]]);}));return function(_x190){return _ref64.apply(this,arguments);};}());_context98.p=2;_context98.n=3;return this._pc.createOffer();case 3:a=_context98.v;_t37=t!==this._pc;if(_t37){_context98.n=5;break;}_context98.n=4;return this._pc.setLocalDescription(a);case 4:_t37=t!==this._pc;case 5:if(!_t37){_context98.n=6;break;}return _context98.a(2);case 6:_context98.n=7;return fetch("https://api.openai.com/v1/realtime",{method:Z,body:a.sdp,headers:_defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,"application/sdp")});case 7:l=_context98.v;if(!(t!==this._pc)){_context98.n=8;break;}return _context98.a(2);case 8:_context98.n=9;return l.text();case 9:_t38=_context98.v;c={type:"answer",sdp:_t38};_t39=t!==this._pc;if(_t39){_context98.n=11;break;}_context98.n=10;return this._pc.setRemoteDescription(c);case 10:_t39=t!==this._pc;case 11:if(!_t39){_context98.n=12;break;}return _context98.a(2);case 12:_context98.n=14;break;case 13:_context98.p=13;_t40=_context98.v;console.error(_t40),this.displayError();case 14:return _context98.a(2);}},_callee98,this,[[2,13]]);}));function init(_x188){return _init2.apply(this,arguments);}return init;}()// there is a bug where sometimes upon refreshing the browser too many times the frequencyData is all 0s
187
187
  // in such instance please wait and refresh at a later time
188
188
  },{key:"monitorFrequencies",value:function monitorFrequencies(e,t){var _this44=this;var s=function(_s4){function s(){return _s4.apply(this,arguments);}s.toString=function(){return _s4.toString();};return s;}(function(){var c;e.getByteFrequencyData(t);var i=t.reduce(function(d,u){return d+u;},0),n=t.length*255,o=i/n*100,a=1,l=a+o/100*(((c=_this44._avatarConfig)==null?void 0:c.maxScale)-a);_this44._avatarEl.style.transform="scale(".concat(l,")"),requestAnimationFrame(s);});s();}},{key:"stopOnError",value:function stopOnError(e){this.stop(),console.error(e),this.displayError();}},{key:"stop",value:function stop(){var e,t,s;(e=this._mediaStream)==null||e.getTracks().forEach(function(i){return i.stop();}),this._mediaStream=null,this._pc&&(this._pc.close(),this._pc=null,(s=(t=this._events)==null?void 0:t.stopped)==null||s.call(t),this._deepChat.dispatchEvent(new CustomEvent(Zs.SESSION_STOPPED)),this._dc=void 0);}},{key:"changeToUnavailable",value:function changeToUnavailable(){this._microphoneButton&&O.changeButtonToUnavailable(this._microphoneButton),this._toggleButton&&O.changeButtonToUnavailable(this._toggleButton);}},{key:"changeToAvailable",value:function changeToAvailable(){this._microphoneButton&&O.changeButtonToAvailable(this._microphoneButton),this._toggleButton&&O.changeButtonToAvailable(this._toggleButton);}},{key:"removeUnavailable",value:function removeUnavailable(){this._microphoneButton&&O.removeButtonUnavailable(this._microphoneButton),this._toggleButton&&O.removeButtonUnavailable(this._toggleButton);}},{key:"createError",value:function createError(){var t;var e=document.createElement("div");return e.id="deep-chat-openai-realtime-error",Object.assign(e.style,(t=this._errorConfig)==null?void 0:t.style),this._errorElement=e,e;}},{key:"displayFailedToRetrieveEphemeralKey",value:function displayFailedToRetrieveEphemeralKey(e){console.error("Failed to retrieve ephemeral key"),console.error(e),this.displayError();}},{key:"displayError",value:function displayError(){var e;this._errorElement&&(this._errorElement.style.display="block",this._errorElement.textContent=((e=this._errorConfig)==null?void 0:e.text)||"Error",this.changeToUnavailable()),this.hideLoading();}},{key:"createLoading",value:function createLoading(){var t,s;var e=document.createElement("div");return e.id="deep-chat-openai-realtime-loading",this._loadingElement=e,(t=this._loadingConfig)!=null&&t.html&&(this._loadingElement.innerHTML=this._loadingConfig.html),Object.assign(e.style,(s=this._loadingConfig)==null?void 0:s.style),e.style.display="none",e;}},{key:"displayLoading",value:function displayLoading(){var e,t,s;this._toggleButton&&(this._toggleButton.changeToActive(),this._toggleButton.elementRef.classList.add(O.BUTTON_LOADING),q.removeAriaDisabled(this._toggleButton.elementRef),q.addAriaBusy(this._toggleButton.elementRef)),(typeof((e=this._loadingConfig)==null?void 0:e.display)!="boolean"||this._loadingConfig.display)&&this._loadingElement&&(this._loadingElement.style.display="block",(t=this._loadingConfig)!=null&&t.html||(this._loadingElement.textContent=((s=this._loadingConfig)==null?void 0:s.text)||"Loading"));}},{key:"hideLoading",value:function hideLoading(){this._toggleButton&&(this._toggleButton.elementRef.classList.remove(O.BUTTON_LOADING),q.removeAriaBusy(this._toggleButton.elementRef)),this._loadingElement&&(this._loadingElement.style.display="none");}// https://platform.openai.com/docs/guides/function-calling?api-mode=responses
189
- },{key:"handleTool",value:function(){var _handleTool=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee99(e,t,s){var i,n;return _regenerator().w(function(_context99){while(1)switch(_context99.n){case 0:if(this._functionHandler){_context99.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:_context99.n=2;return this._functionHandler({name:e,arguments:t});case 2:i=_context99.v;if(!(_typeof(i)!="object"||!oe.isJson(i))){_context99.n=3;break;}throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');case 3:n={type:"function_call_output",call_id:s,output:JSON.stringify(i)};this.sendMessage(n);case 4:return _context99.a(2);}},_callee99,this);}));function handleTool(_x191,_x192,_x193){return _handleTool.apply(this,arguments);}return handleTool;}()// https://platform.openai.com/docs/api-reference/realtime-client-events/conversation/item/create
189
+ },{key:"handleTool",value:function(){var _handleTool=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee99(e,t,s){var i,n;return _regenerator().w(function(_context99){while(1)switch(_context99.n){case 0:if(this._functionHandler){_context99.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:_context99.n=2;return this._functionHandler({name:e,arguments:t});case 2:i=_context99.v;if(!(_typeof(i)!="object"||!ae.isJson(i))){_context99.n=3;break;}throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');case 3:n={type:"function_call_output",call_id:s,output:JSON.stringify(i)};this.sendMessage(n);case 4:return _context99.a(2);}},_callee99,this);}));function handleTool(_x191,_x192,_x193){return _handleTool.apply(this,arguments);}return handleTool;}()// https://platform.openai.com/docs/api-reference/realtime-client-events/conversation/item/create
190
190
  },{key:"sendMessage",value:function sendMessage(e){if(!this._dc)return;var t=JSON.stringify({type:"conversation.item.create",item:e});this._dc.send(t);var s={type:"response.create"};this._dc.send(JSON.stringify(s));}},{key:"isCustomView",value:function isCustomView(){return!0;}}],[{key:"getKey",value:function getKey(e){var t=e.directConnection.openAI;if(t!=null&&t.key)return t.key;var s=t==null?void 0:t.realtime;if(_typeof(s)=="object"&&(s.ephemeralKey||s.fetchEphemeralKey))return"placeholder";}},{key:"buildAvatarConfig",value:function buildAvatarConfig(e){var t=_typeof(e)=="object"&&e.avatar?JSON.parse(JSON.stringify(e.avatar)):{};return t.maxScale=t.maxScale&&t.maxScale>=1?t.maxScale:2.5,t;}},{key:"buildButtonsConfig",value:function buildButtonsConfig(e){var _t$microphone,_o$default,_a$svg,_l$content,_t$toggle,_h$default,_f$svg,_m$content,_p$active,_g$svg,_E$content;var s,i,n,o,a,l,c,d,u,h,f,m,p,g,E;var t=_typeof(e)=="object"&&e.buttons?JSON.parse(JSON.stringify(e.buttons)):{};return(n=(i=(s=t.microphone)==null?void 0:s["default"])==null?void 0:i.text)!=null&&n.content||((_t$microphone=t.microphone)!==null&&_t$microphone!==void 0?_t$microphone:t.microphone={},(_o$default=(o=t.microphone)["default"])!==null&&_o$default!==void 0?_o$default:o["default"]={},(_a$svg=(a=t.microphone["default"]).svg)!==null&&_a$svg!==void 0?_a$svg:a.svg={},(_l$content=(l=t.microphone["default"].svg).content)!==null&&_l$content!==void 0?_l$content:l.content=Cr),(u=(d=(c=t.toggle)==null?void 0:c["default"])==null?void 0:d.text)!=null&&u.content||((_t$toggle=t.toggle)!==null&&_t$toggle!==void 0?_t$toggle:t.toggle={},(_h$default=(h=t.toggle)["default"])!==null&&_h$default!==void 0?_h$default:h["default"]={},(_f$svg=(f=t.toggle["default"]).svg)!==null&&_f$svg!==void 0?_f$svg:f.svg={},(_m$content=(m=t.toggle["default"].svg).content)!==null&&_m$content!==void 0?_m$content:m.content=wr,(_p$active=(p=t.toggle).active)!==null&&_p$active!==void 0?_p$active:p.active={},(_g$svg=(g=t.toggle.active).svg)!==null&&_g$svg!==void 0?_g$svg:g.svg={},(_E$content=(E=t.toggle.active.svg).content)!==null&&_E$content!==void 0?_E$content:E.content=Vi),t;}},{key:"createAvatar",value:function createAvatar(e){var s;var t=document.createElement("img");return t.id="deep-chat-openai-realtime-avatar",Object.assign(t.style,(s=e==null?void 0:e.styles)==null?void 0:s.image),t.src=(e==null?void 0:e.src)||Fi,t;}},{key:"createButtonContainer",value:function createButtonContainer(e){var t=document.createElement("div");return t.classList.add("deep-chat-openai-realtime-button-container"),t.appendChild(e),t;}},{key:"changeButtonToUnavailable",value:function changeButtonToUnavailable(e){e.elementRef.classList.add(O.UNAVAILABLE),q.removeAriaBusy(e.elementRef),q.addAriaDisabled(e.elementRef),e.changeToUnavailable();}},{key:"changeButtonToAvailable",value:function changeButtonToAvailable(e){O.removeButtonUnavailable(e),e.changeToDefault();}},{key:"removeButtonUnavailable",value:function removeButtonUnavailable(e){q.removeAriaDisabled(e.elementRef),e.elementRef.classList.remove(O.UNAVAILABLE);}}]);}(k);O.BUTTON_DEFAULT="deep-chat-openai-realtime-button-default",O.BUTTON_LOADING="deep-chat-openai-realtime-button-loading",O.MICROPHONE_ACTIVE="deep-chat-openai-realtime-microphone-active",O.UNAVAILABLE="deep-chat-openai-realtime-button-unavailable";var Gi=O;var Dt=/*#__PURE__*/function(_k7){function Dt(e){var _o$model3,_a$voice3;var _this45;_classCallCheck(this,Dt);var n,o,a;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t==null?void 0:t.openAI;_this45=_callSuper(this,Dt,[e,G.buildKeyVerificationDetails(),G.buildHeaders,s]),_this45.insertKeyPlaceholderText=_this45.genereteAPIKeyName("OpenAI"),_this45.keyHelpUrl="https://platform.openai.com/account/api-keys",_this45.url="https://api.openai.com/v1/audio/speech",_this45.permittedErrorPrefixes=[ht],_this45.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>OpenAI : Text To Speech</b></div>\n <p>Generate an audio file based on your text input.</p>\n <p>Click <a href=\"https://platform.openai.com/docs/guides/text-to-speech\" target=\"_blank\">here</a>\n for more information.</p>";var i=(n=t==null?void 0:t.openAI)==null?void 0:n.textToSpeech;_typeof(i)===T&&Object.assign(_this45.rawBody,i),(_o$model3=(o=_this45.rawBody).model)!==null&&_o$model3!==void 0?_o$model3:o.model=Dt.DEFAULT_MODEL,(_a$voice3=(a=_this45.rawBody).voice)!==null&&_a$voice3!==void 0?_a$voice3:a.voice=Dt.DEFAULT_VOIDE,_this45.textInputPlaceholderText="Insert text to generate audio",_this45.rawBody.response_format="mp3";return _this45;}_inherits(Dt,_k7);return _createClass(Dt,[{key:"preprocessBody",value:function preprocessBody(e,t){var n,o;var s=JSON.parse(JSON.stringify(e)),i=(o=(n=t[t.length-1])==null?void 0:n.text)==null?void 0:o.trim();return i&&i!==""&&(s.input=i),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI10=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee100(e,t){return _regenerator().w(function(_context100){while(1)switch(_context100.n){case 0:this.url=this.connectSettings.url||this.url,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context100.a(2);}},_callee100,this);}));function callServiceAPI(_x194,_x195){return _callServiceAPI10.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData13=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee101(e){return _regenerator().w(function(_context101){while(1)switch(_context101.n){case 0:if(!(e instanceof Blob)){_context101.n=1;break;}return _context101.a(2,new Promise(function(t){var s=new FileReader();s.readAsDataURL(e),s.onload=function(i){t({files:[{src:i.target.result,type:"audio"}]});};}));case 1:if(!e.error){_context101.n=2;break;}throw e.error.message;case 2:return _context101.a(2,_defineProperty({},je,je));}},_callee101);}));function extractResultData(_x196){return _extractResultData13.apply(this,arguments);}return extractResultData;}()}]);}(k);Dt.DEFAULT_MODEL="tts-1",Dt.DEFAULT_VOIDE="alloy";var Ki=Dt;var Re=/*#__PURE__*/function(_k8){function Re(e){var _o$model4;var _this46;_classCallCheck(this,Re);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t==null?void 0:t.openAI;_this46=_callSuper(this,Re,[e,G.buildKeyVerificationDetails(),G.buildHeaders,s,{audio:{}}]),_this46.insertKeyPlaceholderText=_this46.genereteAPIKeyName("OpenAI"),_this46.keyHelpUrl="https://platform.openai.com/account/api-keys",_this46.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>OpenAI : Speech To Text</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href=\"https://platform.openai.com/docs/guides/speech-to-text\" target=\"_blank\">here</a> for more info.</p>",_this46.url="",_this46.permittedErrorPrefixes=[ht],_this46.textInputPlaceholderText=rn,_this46._service_url=Re.AUDIO_TRANSCRIPTIONS_URL;var i=(n=t==null?void 0:t.openAI)==null?void 0:n.audio;_typeof(i)=="object"&&(_this46.processConfig(i),Re.cleanConfig(i),Object.assign(_this46.rawBody,i)),(_o$model4=(o=_this46.rawBody).model)!==null&&_o$model4!==void 0?_o$model4:o.model=Re.DEFAULT_MODEL,_this46.rawBody.response_format="json",_this46.canSendMessage=Re.canSendFileMessage;return _this46;}_inherits(Re,_k8);return _createClass(Re,[{key:"processConfig",value:function processConfig(e){e!=null&&e.type&&e.type==="translation"&&(this._service_url=Re.AUDIO_TRANSLATIONS_URL,delete e.language);}},{key:"preprocessBody",value:function preprocessBody(e,t){var n,o;var s=JSON.parse(JSON.stringify(e)),i=(o=(n=t[t.length-1])==null?void 0:n.text)==null?void 0:o.trim();return i&&i!==""&&(s.prompt=i),s;}// prettier-ignore
191
191
  },{key:"callServiceAPI",value:function(){var _callServiceAPI11=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee102(e,t,s){var o,i,n;return _regenerator().w(function(_context102){while(1)switch(_context102.n){case 0:if((o=this.connectSettings)!=null&&o.headers){_context102.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(s!=null&&s[0]){_context102.n=2;break;}throw new Error(b.NO_FILE_ADDED_ERROR);case 2:this.url=this.connectSettings.url||this._service_url;i=this.preprocessBody(this.rawBody,t),n=Re.createFormDataBody(i,s[0]);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,n,e),!1);case 3:return _context102.a(2);}},_callee102,this);}));function callServiceAPI(_x197,_x198,_x199){return _callServiceAPI11.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData14=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee103(e){return _regenerator().w(function(_context103){while(1)switch(_context103.n){case 0:if(!e.error){_context103.n=1;break;}throw e.error.message;case 1:return _context103.a(2,_defineProperty({},y,e.text));}},_callee103);}));function extractResultData(_x200){return _extractResultData14.apply(this,arguments);}return extractResultData;}()}],[{key:"canSendFileMessage",value:function canSendFileMessage(e,t){return!!(t!=null&&t[0]);}},{key:"cleanConfig",value:function cleanConfig(e){delete e.type;}},{key:"createFormDataBody",value:function createFormDataBody(e,t){var s=new FormData();return s.append("file",t),Object.keys(e).forEach(function(i){s.append(i,String(e[i]));}),s;}}]);}(k);Re.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Re.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Re.DEFAULT_MODEL="whisper-1";var zi=Re;var ve=/*#__PURE__*/function(){function ve(){_classCallCheck(this,ve);}return _createClass(ve,null,[{key:"buildTextToSpeechHeaders",value:function buildTextToSpeechHeaders(e,t){return _defineProperty(_defineProperty(_defineProperty({},ve.SUBSCRIPTION_KEY_NAME,t),R,"application/ssml+xml"),"X-Microsoft-OutputFormat",e);}},{key:"buildSpeechToTextHeaders",value:function buildSpeechToTextHeaders(e){return _defineProperty(_defineProperty({},ve.SUBSCRIPTION_KEY_NAME,e),"Accept",N);}// prettier-ignore
192
192
  },{key:"handleSpeechVerificationResult",value:function handleSpeechVerificationResult(e,t,s,i){e.error?i(b.INVALID_KEY):s(t);}},{key:"buildSpeechKeyVerificationDetails",value:function buildSpeechKeyVerificationDetails(e){return{url:"https://".concat(e,".api.cognitive.microsoft.com/sts/v1.0/issuetoken"),method:Z,createHeaders:function createHeaders(t){return _defineProperty({},ve.SUBSCRIPTION_KEY_NAME,"".concat(t));},handleVerificationResult:ve.handleSpeechVerificationResult};}},{key:"buildSummarizationHeader",value:function buildSummarizationHeader(e){return _defineProperty(_defineProperty({},ve.SUBSCRIPTION_KEY_NAME,e),R,N);}// prettier-ignore
@@ -204,13 +204,13 @@ function vt(e){var _a$lang,_l$name,_c$gender;var _this51;_classCallCheck(this,vt
204
204
  "https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest",at.REGION_ERROR_MESSAGE=// eslint-disable-next-line max-len
205
205
  "Please define a region config property. [More Information](https://deepchat.dev/docs/directConnection/Azure#SpeechToText)";var Wi=at;var Wa=/*#__PURE__*/function(_k10){// prettier-ignore
206
206
  function Wa(e){var _this53;_classCallCheck(this,Wa);var i,n,o;var t=(n=(i=e.directConnection)==null?void 0:i.azure)==null?void 0:n.translation,s=(o=e.directConnection)==null?void 0:o.azure;_this53=_callSuper(this,Wa,[e,tt.buildTranslationKeyVerificationDetails(t.region),tt.buildTranslationHeaders.bind({},t==null?void 0:t.region),s]),_this53.insertKeyPlaceholderText="Azure Translate Subscription Key",_this53.keyHelpUrl=// eslint-disable-next-line max-len
207
- "https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",_this53.url="",_this53.url="https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=".concat(t.language||"es");return _this53;}_inherits(Wa,_k10);return _createClass(Wa,[{key:"preprocessBody",value:function preprocessBody(e){var t=e[e.length-1].text;if(t)return[{Text:t}];}},{key:"callServiceAPI",value:function(){var _callServiceAPI16=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee114(e,t){return _regenerator().w(function(_context114){while(1)switch(_context114.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context114.a(2);}},_callee114,this);}));function callServiceAPI(_x218,_x219){return _callServiceAPI16.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData19=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee115(e){var t;return _regenerator().w(function(_context115){while(1)switch(_context115.n){case 0:if(!Array.isArray(e)){_context115.n=1;break;}return _context115.a(2,_defineProperty({},y,((t=e[0].translations)==null?void 0:t[0].text)||""));case 1:throw e.error;case 2:return _context115.a(2);}},_callee115);}));function extractResultData(_x220){return _extractResultData19.apply(this,arguments);}return extractResultData;}()}]);}(k);var Xa=/*#__PURE__*/function(_k11){function Xa(e){var _o$model5;var _this54;_classCallCheck(this,Xa);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this54=_callSuper(this,Xa,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this54.insertKeyPlaceholderText=_this54.genereteAPIKeyName("BigModel"),_this54.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this54.url="https://open.bigmodel.cn/api/paas/v4/images/generations",_this54.permittedErrorPrefixes=[K,se];var i=(n=t.bigModel)==null?void 0:n.images;_typeof(i)===T&&(_this54.cleanConfig(i),Object.assign(_this54.rawBody,i)),(_o$model5=(o=_this54.rawBody).model)!==null&&_o$model5!==void 0?_o$model5:o.model="cogview-4-250304";return _this54;}_inherits(Xa,_k11);return _createClass(Xa,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.prompt=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI17=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee116(e,t){return _regenerator().w(function(_context116){while(1)switch(_context116.n){case 0:return _context116.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee116,this);}));function callServiceAPI(_x221,_x222){return _callServiceAPI17.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData20=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee117(e){return _regenerator().w(function(_context117){while(1)switch(_context117.n){case 0:return _context117.a(2,{files:e.data.map(function(s){return s!=null&&s.url?{src:s.url,type:"image"}:{src:"",type:"image"};})});}},_callee117);}));function extractResultData(_x223){return _extractResultData20.apply(this,arguments);}return extractResultData;}()}]);}(k);var Ft=/*#__PURE__*/function(){function Ft(){_classCallCheck(this,Ft);}return _createClass(Ft,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(te).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.groq.com/openai/v1/models",method:z,handleVerificationResult:Ft.handleVerificationResult};}}]);}();var Ya=/*#__PURE__*/function(_k12){function Ya(e){var _o$model6,_a$voice4,_l$response_format;var _this55;_classCallCheck(this,Ya);var n,o,a,l;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.groq;_this55=_callSuper(this,Ya,[e,Ft.buildKeyVerificationDetails(),Ft.buildHeaders,s]),_this55.insertKeyPlaceholderText=_this55.genereteAPIKeyName("Groq"),_this55.keyHelpUrl="https://console.groq.com/keys",_this55.url="https://api.groq.com/openai/v1/audio/speech",_this55.permittedErrorPrefixes=[ht,"property"];var i=(n=t.groq)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this55.cleanConfig(i),Object.assign(_this55.rawBody,i)),(_o$model6=(o=_this55.rawBody).model)!==null&&_o$model6!==void 0?_o$model6:o.model="playai-tts",(_a$voice4=(a=_this55.rawBody).voice)!==null&&_a$voice4!==void 0?_a$voice4:a.voice="Fritz-PlayAI",(_l$response_format=(l=_this55.rawBody).response_format)!==null&&_l$response_format!==void 0?_l$response_format:l.response_format="mp3";return _this55;}_inherits(Ya,_k12);return _createClass(Ya,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI18=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee118(e,t){return _regenerator().w(function(_context118){while(1)switch(_context118.n){case 0:return _context118.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee118,this);}));function callServiceAPI(_x224,_x225){return _callServiceAPI18.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData21=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee119(e){var t,s;return _regenerator().w(function(_context119){while(1)switch(_context119.n){case 0:t=this.rawBody.response_format||"mp3",s=new Blob([e],{type:"audio/".concat(t)});return _context119.a(2,{files:[{src:URL.createObjectURL(s),type:"audio"}]});}},_callee119,this);}));function extractResultData(_x226){return _extractResultData21.apply(this,arguments);}return extractResultData;}()}]);}(k);var Za=/*#__PURE__*/function(_k13){function Za(e){var _o$model7;var _this56;_classCallCheck(this,Za);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this56=_callSuper(this,Za,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this56.insertKeyPlaceholderText=_this56.genereteAPIKeyName("Together AI"),_this56.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this56.url="https://api.together.xyz/v1/images/generations",_this56.permittedErrorPrefixes=[we,se];var i=(n=t.together)==null?void 0:n.images;_typeof(i)===T&&(_this56.cleanConfig(i),Object.assign(_this56.rawBody,i)),(_o$model7=(o=_this56.rawBody).model)!==null&&_o$model7!==void 0?_o$model7:o.model="black-forest-labs/FLUX.1-schnell-Free";return _this56;}_inherits(Za,_k13);return _createClass(Za,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.prompt=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI19=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee120(e,t){return _regenerator().w(function(_context120){while(1)switch(_context120.n){case 0:return _context120.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee120,this);}));function callServiceAPI(_x227,_x228){return _callServiceAPI19.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData22=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee121(e){return _regenerator().w(function(_context121){while(1)switch(_context121.n){case 0:return _context121.a(2,{files:e.data.map(function(s){return s!=null&&s.url?{src:s.url,type:"image"}:s!=null&&s.b64_json?{src:"data:image/png;base64,".concat(s.b64_json),type:"image"}:{src:"",type:"image"};})});}},_callee121);}));function extractResultData(_x229){return _extractResultData22.apply(this,arguments);}return extractResultData;}()}]);}(k);var ws=/*#__PURE__*/function(_k14){// https://platform.openai.com/docs/models/gpt-4o-audio-preview
207
+ "https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",_this53.url="",_this53.url="https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=".concat(t.language||"es");return _this53;}_inherits(Wa,_k10);return _createClass(Wa,[{key:"preprocessBody",value:function preprocessBody(e){var t=e[e.length-1].text;if(t)return[{Text:t}];}},{key:"callServiceAPI",value:function(){var _callServiceAPI16=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee114(e,t){return _regenerator().w(function(_context114){while(1)switch(_context114.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context114.a(2);}},_callee114,this);}));function callServiceAPI(_x218,_x219){return _callServiceAPI16.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData19=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee115(e){var t;return _regenerator().w(function(_context115){while(1)switch(_context115.n){case 0:if(!Array.isArray(e)){_context115.n=1;break;}return _context115.a(2,_defineProperty({},y,((t=e[0].translations)==null?void 0:t[0].text)||""));case 1:throw e.error;case 2:return _context115.a(2);}},_callee115);}));function extractResultData(_x220){return _extractResultData19.apply(this,arguments);}return extractResultData;}()}]);}(k);var Xa=/*#__PURE__*/function(_k11){function Xa(e){var _o$model5;var _this54;_classCallCheck(this,Xa);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this54=_callSuper(this,Xa,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this54.insertKeyPlaceholderText=_this54.genereteAPIKeyName("BigModel"),_this54.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this54.url="https://open.bigmodel.cn/api/paas/v4/images/generations",_this54.permittedErrorPrefixes=[K,ie];var i=(n=t.bigModel)==null?void 0:n.images;_typeof(i)===T&&(_this54.cleanConfig(i),Object.assign(_this54.rawBody,i)),(_o$model5=(o=_this54.rawBody).model)!==null&&_o$model5!==void 0?_o$model5:o.model="cogview-4-250304";return _this54;}_inherits(Xa,_k11);return _createClass(Xa,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.prompt=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI17=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee116(e,t){return _regenerator().w(function(_context116){while(1)switch(_context116.n){case 0:return _context116.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee116,this);}));function callServiceAPI(_x221,_x222){return _callServiceAPI17.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData20=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee117(e){return _regenerator().w(function(_context117){while(1)switch(_context117.n){case 0:return _context117.a(2,{files:e.data.map(function(s){return s!=null&&s.url?{src:s.url,type:"image"}:{src:"",type:"image"};})});}},_callee117);}));function extractResultData(_x223){return _extractResultData20.apply(this,arguments);}return extractResultData;}()}]);}(k);var Ft=/*#__PURE__*/function(){function Ft(){_classCallCheck(this,Ft);}return _createClass(Ft,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},R,N),K,"".concat(se).concat(e));}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.message===sn?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.groq.com/openai/v1/models",method:z,handleVerificationResult:Ft.handleVerificationResult};}}]);}();var Ya=/*#__PURE__*/function(_k12){function Ya(e){var _o$model6,_a$voice4,_l$response_format;var _this55;_classCallCheck(this,Ya);var n,o,a,l;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.groq;_this55=_callSuper(this,Ya,[e,Ft.buildKeyVerificationDetails(),Ft.buildHeaders,s]),_this55.insertKeyPlaceholderText=_this55.genereteAPIKeyName("Groq"),_this55.keyHelpUrl="https://console.groq.com/keys",_this55.url="https://api.groq.com/openai/v1/audio/speech",_this55.permittedErrorPrefixes=[ht,"property"];var i=(n=t.groq)==null?void 0:n.textToSpeech;_typeof(i)===T&&(_this55.cleanConfig(i),Object.assign(_this55.rawBody,i)),(_o$model6=(o=_this55.rawBody).model)!==null&&_o$model6!==void 0?_o$model6:o.model="playai-tts",(_a$voice4=(a=_this55.rawBody).voice)!==null&&_a$voice4!==void 0?_a$voice4:a.voice="Fritz-PlayAI",(_l$response_format=(l=_this55.rawBody).response_format)!==null&&_l$response_format!==void 0?_l$response_format:l.response_format="mp3";return _this55;}_inherits(Ya,_k12);return _createClass(Ya,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.input=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI18=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee118(e,t){return _regenerator().w(function(_context118){while(1)switch(_context118.n){case 0:return _context118.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee118,this);}));function callServiceAPI(_x224,_x225){return _callServiceAPI18.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData21=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee119(e){var t,s;return _regenerator().w(function(_context119){while(1)switch(_context119.n){case 0:t=this.rawBody.response_format||"mp3",s=new Blob([e],{type:"audio/".concat(t)});return _context119.a(2,{files:[{src:URL.createObjectURL(s),type:"audio"}]});}},_callee119,this);}));function extractResultData(_x226){return _extractResultData21.apply(this,arguments);}return extractResultData;}()}]);}(k);var Za=/*#__PURE__*/function(_k13){function Za(e){var _o$model7;var _this56;_classCallCheck(this,Za);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this56=_callSuper(this,Za,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this56.insertKeyPlaceholderText=_this56.genereteAPIKeyName("Together AI"),_this56.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this56.url="https://api.together.xyz/v1/images/generations",_this56.permittedErrorPrefixes=[we,ie];var i=(n=t.together)==null?void 0:n.images;_typeof(i)===T&&(_this56.cleanConfig(i),Object.assign(_this56.rawBody,i)),(_o$model7=(o=_this56.rawBody).model)!==null&&_o$model7!==void 0?_o$model7:o.model="black-forest-labs/FLUX.1-schnell-Free";return _this56;}_inherits(Za,_k13);return _createClass(Za,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t[t.length-1];return s.prompt=(i==null?void 0:i.text)||"",s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI19=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee120(e,t){return _regenerator().w(function(_context120){while(1)switch(_context120.n){case 0:return _context120.a(2,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this)));}},_callee120,this);}));function callServiceAPI(_x227,_x228){return _callServiceAPI19.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData22=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee121(e){return _regenerator().w(function(_context121){while(1)switch(_context121.n){case 0:return _context121.a(2,{files:e.data.map(function(s){return s!=null&&s.url?{src:s.url,type:"image"}:s!=null&&s.b64_json?{src:"data:image/png;base64,".concat(s.b64_json),type:"image"}:{src:"",type:"image"};})});}},_callee121);}));function extractResultData(_x229){return _extractResultData22.apply(this,arguments);}return extractResultData;}()}]);}(k);var ws=/*#__PURE__*/function(_k14){// https://platform.openai.com/docs/models/gpt-4o-audio-preview
208
208
  // prettier-ignore
209
209
  function ws(e,t,s,i,n){var _this57$maxMessages,_p$model;var _this57;_classCallCheck(this,ws);var u,h,f,m,p;var o=JSON.parse(JSON.stringify(e.directConnection)),a=t||G.buildKeyVerificationDetails(),l=s||G.buildHeaders,c=i||o.openAI;_this57=_callSuper(this,ws,[e,a,l,c]),_this57.insertKeyPlaceholderText=_this57.genereteAPIKeyName("OpenAI"),_this57.keyHelpUrl="https://platform.openai.com/account/api-keys",_this57.url="https://api.openai.com/v1/chat/completions",_this57.permittedErrorPrefixes=[ks],_this57._systemMessage="";var d=n||((u=o.openAI)==null?void 0:u.chat);if(_typeof(d)===T){d.system_prompt&&(_this57._systemMessage=d.system_prompt);var g=(m=(f=(h=e.directConnection)==null?void 0:h.openAI)==null?void 0:f.chat)==null?void 0:m.function_handler;g&&(_this57._functionHandler=g),_this57.cleanConfig(d),Object.assign(_this57.rawBody,d);}(_this57$maxMessages=_this57.maxMessages)!==null&&_this57$maxMessages!==void 0?_this57$maxMessages:_this57.maxMessages=-1,(_p$model=(p=_this57.rawBody).model)!==null&&_p$model!==void 0?_p$model:p.model="gpt-4o";return _this57;}_inherits(ws,_k14);return _createClass(ws,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler;}// mention that microphone is not supported because the outputted base64 is not accepted
210
210
  // use speech to speech instead
211
211
  // give allowed regex example for audio format rules
212
212
  },{key:"preprocessBody",value:// prettier-ignore
213
- function preprocessBody(e,t){var _s$max_tokens;var o;var s=JSON.parse(JSON.stringify(e)),i=(o=s.modalities)==null?void 0:o.includes("audio"),n=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(a){return{content:ws.getContent(a,i),role:a.role===v.USER_ROLE?"user":"assistant"};});return t.find(function(a){return a.files&&a.files.length>0;})&&((_s$max_tokens=s.max_tokens)!==null&&_s$max_tokens!==void 0?_s$max_tokens:s.max_tokens=300),this._systemMessage&&n.unshift({role:"system",content:this._systemMessage}),s.messages=n,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI20=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee122(e,t){var _this$_messages3;return _regenerator().w(function(_context122){while(1)switch(_context122.n){case 0:(_this$_messages3=this._messages)!==null&&_this$_messages3!==void 0?_this$_messages3:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context122.a(2);}},_callee122,this);}));function callServiceAPI(_x230,_x231){return _callServiceAPI20.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData23=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee123(e,t){var s,i,n,o,a,l,c,d;return _regenerator().w(function(_context123){while(1)switch(_context123.n){case 0:if(!e.error){_context123.n=1;break;}throw e.error.message;case 1:if(!((i=(s=e.choices)==null?void 0:s[0])!=null&&i.delta)){_context123.n=2;break;}return _context123.a(2,this.extractStreamResult(e.choices[0],t));case 2:if(!((o=(n=e.choices)==null?void 0:n[0])!=null&&o.message)){_context123.n=5;break;}if(!e.choices[0].message.tool_calls){_context123.n=3;break;}return _context123.a(2,this.handleToolsGeneric(e.choices[0].message,this._functionHandler,this._messages,t));case 3:if(!((a=e.choices[0].message)!=null&&a.audio)){_context123.n=4;break;}c=this.deepChat.textToSpeech,d=_typeof(c)=="object"&&typeof((l=c==null?void 0:c.service)==null?void 0:l.displayText)=="boolean";return _context123.a(2,_defineProperty({files:[{src:"data:audio/wav;base64,".concat(e.choices[0].message.audio.data),type:"audio"}]},y,d?e.choices[0].message.audio.transcript:void 0));case 4:return _context123.a(2,_defineProperty({},y,e.choices[0].message.content));case 5:return _context123.a(2,_defineProperty({},y,""));}},_callee123,this);}));function extractResultData(_x232,_x233){return _extractResultData23.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee124(e,t){return _regenerator().w(function(_context124){while(1)switch(_context124.n){case 0:return _context124.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee124,this);}));function extractStreamResult(_x234,_x235){return _extractStreamResult.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getFileContent",value:function getFileContent(e,t){return e.map(function(i){var n,o,a;if(i.type==="audio"&&t){var l=(n=i.src)==null?void 0:n.split(",")[1],c=((a=(o=i.src)==null?void 0:o.match(/data:audio\/([^;]+)/))==null?void 0:a[1])||"wav";return{type:"input_audio",input_audio:{data:l,format:c}};}return{type:"image_url",image_url:{url:i.src}};});}},{key:"getContent",value:function getContent(e,t){if(e.files&&e.files.length>0){var _s9=ws.getFileContent(e.files,t);return e.text&&e.text.trim().length>0&&_s9.unshift(_defineProperty({type:"text"},y,e.text)),_s9;}return e.text;}}]);}(k);var hn=/*#__PURE__*/function(_ws){function hn(e){var _this58;_classCallCheck(this,hn);var o,a,l,c,d,u,h;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.azure,i=((a=(o=t.azure)==null?void 0:o.openAI)==null?void 0:a.urlDetails)||{},n=(c=(l=t.azure)==null?void 0:l.openAI)==null?void 0:c.chat;if(_this58=_callSuper(this,hn,[e,Ce.buildKeyVerificationDetails(i),Ce.buildHeaders,s,n]),_this58.permittedErrorPrefixes=[Ce.URL_DETAILS_ERROR_MESSAGE],_this58.isTextInputDisabled=!1,_typeof(n)===T){var _ref83=(h=(u=(d=e.directConnection)==null?void 0:d.azure)==null?void 0:u.openAI)==null?void 0:h.chat,f=_ref83.function_handler;f&&(_this58._functionHandler=f);}Ce.validateURLDetails(i)?_this58.url=hn.buildURL(i):(_this58.isTextInputDisabled=!0,_this58.canSendMessage=function(){return!1;},setTimeout(function(){e.addMessage(_defineProperty({},je,Ce.URL_DETAILS_ERROR_MESSAGE));}));return _this58;}_inherits(hn,_ws);return _createClass(hn,null,[{key:"buildURL",value:function buildURL(e){var t=e.endpoint,s=e.deploymentId,i=e.version;return"".concat(t,"/openai/deployments/").concat(s,"/chat/completions?api-version=").concat(i);}}]);}(ws);var Qs=/*#__PURE__*/function(_k15){function Qs(e){var _this59$maxMessages,_c$model2;var _this59;_classCallCheck(this,Qs);var n,o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this59=_callSuper(this,Qs,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this59.insertKeyPlaceholderText=_this59.genereteAPIKeyName("BigModel"),_this59.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this59.url="https://open.bigmodel.cn/api/paas/v4/chat/completions",_this59.permittedErrorPrefixes=[K,se],_this59._systemMessage="";var i=(n=t.bigModel)==null?void 0:n.chat;if(_typeof(i)===T){i.system_prompt&&(_this59._systemMessage=i.system_prompt);var d=(l=(a=(o=e.directConnection)==null?void 0:o.bigModel)==null?void 0:a.chat)==null?void 0:l.function_handler;d&&(_this59._functionHandler=d),_this59.cleanConfig(i),Object.assign(_this59.rawBody,i);}(_this59$maxMessages=_this59.maxMessages)!==null&&_this59$maxMessages!==void 0?_this59$maxMessages:_this59.maxMessages=-1,(_c$model2=(c=_this59.rawBody).model)!==null&&_c$model2!==void 0?_c$model2:c.model="glm-4.5";return _this59;}_inherits(Qs,_k15);return _createClass(Qs,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:Qs.getTextWFilesContent(n,Qs.getFileContent),role:n.role==="ai"?"assistant":"user"};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI21=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee125(e,t){var _this$_messages4;return _regenerator().w(function(_context125){while(1)switch(_context125.n){case 0:(_this$_messages4=this._messages)!==null&&_this$_messages4!==void 0?_this$_messages4:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context125.a(2);}},_callee125,this);}));function callServiceAPI(_x236,_x237){return _callServiceAPI21.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData24=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee126(e,t){var _s0;return _regenerator().w(function(_context126){while(1)switch(_context126.n){case 0:if(!e.error){_context126.n=1;break;}throw e.error.message;case 1:if(!(e.choices.length>0)){_context126.n=3;break;}if(!(e.choices[0].delta!==void 0)){_context126.n=2;break;}return _context126.a(2,this.extractStreamResult(e.choices[0],t));case 2:if(!(e.choices[0].message!==void 0)){_context126.n=3;break;}_s0=e.choices[0].message;return _context126.a(2,_s0.tool_calls?this.handleToolsGeneric({tool_calls:_s0.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s0.content));case 3:return _context126.a(2,_defineProperty({},y,""));}},_callee126,this);}));function extractResultData(_x238,_x239){return _extractResultData24.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee127(e,t){var o,a,l,c,s,i,n,d;return _regenerator().w(function(_context127){while(1)switch(_context127.n){case 0:s=e.delta,i=e.finish_reason,n=(o=this._messages)==null?void 0:o.messageToElements[this._messages.messageToElements.length-2];if(!((n==null?void 0:n[0].role)==="ai"&&((a=n==null?void 0:n[0].text)==null?void 0:a.replace(/\n/g,"").trim().length)===0&&((l=this._messages)==null||l.removeMessage(n[1].text),(c=this._messages)==null||c.messageToElements.splice(this._messages.messageToElements.length-2,1)),i==="tool_calls")){_context127.n=2;break;}if(!s.tool_calls){_context127.n=1;break;}d={tool_calls:s.tool_calls};return _context127.a(2,this.handleToolsGeneric(d,this._functionHandler,this._messages,t));case 1:return _context127.a(2,_defineProperty({},y,(s==null?void 0:s.content)||""));case 2:return _context127.a(2,_defineProperty({},y,(s==null?void 0:s.content)||""));}},_callee127,this);}));function extractStreamResult(_x240,_x241){return _extractStreamResult2.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getFileContent",value:function getFileContent(e){return e.map(function(t){return t.type==="image"?{type:"image_url",image_url:{url:t.src||""}}:{type:"file",file_url:{url:t.src||""}};});}}]);}(k);var Qa=/*#__PURE__*/function(_k16){function Qa(e){var _this60$maxMessages,_o$model8;var _this60;_classCallCheck(this,Qa);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this60=_callSuper(this,Qa,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this60.insertKeyPlaceholderText=_this60.genereteAPIKeyName("Together AI"),_this60.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this60.url="https://api.together.xyz/v1/chat/completions",_this60.permittedErrorPrefixes=[we,se],_this60._systemMessage="";var i=(n=t.together)==null?void 0:n.chat;_typeof(i)===T&&(i.system_prompt&&(_this60._systemMessage=i.system_prompt),_this60.cleanConfig(i),Object.assign(_this60.rawBody,i)),(_this60$maxMessages=_this60.maxMessages)!==null&&_this60$maxMessages!==void 0?_this60$maxMessages:_this60.maxMessages=-1,(_o$model8=(o=_this60.rawBody).model)!==null&&_o$model8!==void 0?_o$model8:o.model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo";return _this60;}_inherits(Qa,_k16);return _createClass(Qa,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role==="ai"?"assistant":n.role};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI22=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee128(e,t){return _regenerator().w(function(_context128){while(1)switch(_context128.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context128.a(2);}},_callee128,this);}));function callServiceAPI(_x242,_x243){return _callServiceAPI22.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee129(e){return _regenerator().w(function(_context129){while(1)switch(_context129.n){case 0:if(!e.error){_context129.n=1;break;}throw e.error.message;case 1:if(!(e.choices.length>0)){_context129.n=3;break;}if(!(e.choices[0].message!==void 0)){_context129.n=2;break;}return _context129.a(2,_defineProperty({},y,e.choices[0].message.content));case 2:if(!(e.choices[0].delta!==void 0)){_context129.n=3;break;}return _context129.a(2,_defineProperty({},y,e.choices[0].delta.content));case 3:return _context129.a(2,_defineProperty({},y,""));}},_callee129);}));function extractResultData(_x244){return _extractResultData25.apply(this,arguments);}return extractResultData;}()}]);}(k);var Me=/*#__PURE__*/function(_k17){function Me(e){var _this61;_classCallCheck(this,Me);var o;var t=e.directConnection,s=t==null?void 0:t.openAI,i={images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}};_this61=_callSuper(this,Me,[e,G.buildKeyVerificationDetails(),G.buildHeaders,s,i]),_this61.insertKeyPlaceholderText=_this61.genereteAPIKeyName("OpenAI"),_this61.keyHelpUrl="https://platform.openai.com/account/api-keys",_this61.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>OpenAI DALL\xB7E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href=\"https://platform.openai.com/docs/guides/images/introduction\" target=\"_blank\">here</a>\n for more info.</p>",_this61.url="",_this61.permittedErrorPrefixes=[ks,"Invalid input image"];var n=(o=t==null?void 0:t.openAI)==null?void 0:o.images;if(_this61.camera){var a=_typeof(n)=="object"&&n.size?Number.parseInt(n.size):1024;_this61.camera.files={dimensions:{width:a,height:a}};}_typeof(n)===T&&Object.assign(_this61.rawBody,n),_this61.canSendMessage=Me.canFileSendMessage;return _this61;}_inherits(Me,_k17);return _createClass(Me,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e));return t&&t!==""&&(s.prompt=t),s;}// prettier-ignore
213
+ function preprocessBody(e,t){var _s$max_tokens;var o;var s=JSON.parse(JSON.stringify(e)),i=(o=s.modalities)==null?void 0:o.includes("audio"),n=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(a){return{content:ws.getContent(a,i),role:a.role===v.USER_ROLE?"user":"assistant"};});return t.find(function(a){return a.files&&a.files.length>0;})&&((_s$max_tokens=s.max_tokens)!==null&&_s$max_tokens!==void 0?_s$max_tokens:s.max_tokens=300),this._systemMessage&&n.unshift({role:"system",content:this._systemMessage}),s.messages=n,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI20=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee122(e,t){var _this$_messages3;return _regenerator().w(function(_context122){while(1)switch(_context122.n){case 0:(_this$_messages3=this._messages)!==null&&_this$_messages3!==void 0?_this$_messages3:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context122.a(2);}},_callee122,this);}));function callServiceAPI(_x230,_x231){return _callServiceAPI20.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData23=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee123(e,t){var s,i,n,o,a,l,c,d;return _regenerator().w(function(_context123){while(1)switch(_context123.n){case 0:if(!e.error){_context123.n=1;break;}throw e.error.message;case 1:if(!((i=(s=e.choices)==null?void 0:s[0])!=null&&i.delta)){_context123.n=2;break;}return _context123.a(2,this.extractStreamResult(e.choices[0],t));case 2:if(!((o=(n=e.choices)==null?void 0:n[0])!=null&&o.message)){_context123.n=5;break;}if(!e.choices[0].message.tool_calls){_context123.n=3;break;}return _context123.a(2,this.handleToolsGeneric(e.choices[0].message,this._functionHandler,this._messages,t));case 3:if(!((a=e.choices[0].message)!=null&&a.audio)){_context123.n=4;break;}c=this.deepChat.textToSpeech,d=_typeof(c)=="object"&&typeof((l=c==null?void 0:c.service)==null?void 0:l.displayText)=="boolean";return _context123.a(2,_defineProperty({files:[{src:"data:audio/wav;base64,".concat(e.choices[0].message.audio.data),type:"audio"}]},y,d?e.choices[0].message.audio.transcript:void 0));case 4:return _context123.a(2,_defineProperty({},y,e.choices[0].message.content));case 5:return _context123.a(2,_defineProperty({},y,""));}},_callee123,this);}));function extractResultData(_x232,_x233){return _extractResultData23.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee124(e,t){return _regenerator().w(function(_context124){while(1)switch(_context124.n){case 0:return _context124.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee124,this);}));function extractStreamResult(_x234,_x235){return _extractStreamResult.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getFileContent",value:function getFileContent(e,t){return e.map(function(i){var n,o,a;if(i.type==="audio"&&t){var l=(n=i.src)==null?void 0:n.split(",")[1],c=((a=(o=i.src)==null?void 0:o.match(/data:audio\/([^;]+)/))==null?void 0:a[1])||"wav";return{type:"input_audio",input_audio:{data:l,format:c}};}return{type:"image_url",image_url:{url:i.src}};});}},{key:"getContent",value:function getContent(e,t){if(e.files&&e.files.length>0){var _s9=ws.getFileContent(e.files,t);return e.text&&e.text.trim().length>0&&_s9.unshift(_defineProperty({type:"text"},y,e.text)),_s9;}return e.text;}}]);}(k);var hn=/*#__PURE__*/function(_ws){function hn(e){var _this58;_classCallCheck(this,hn);var o,a,l,c,d,u,h;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.azure,i=((a=(o=t.azure)==null?void 0:o.openAI)==null?void 0:a.urlDetails)||{},n=(c=(l=t.azure)==null?void 0:l.openAI)==null?void 0:c.chat;if(_this58=_callSuper(this,hn,[e,Ce.buildKeyVerificationDetails(i),Ce.buildHeaders,s,n]),_this58.permittedErrorPrefixes=[Ce.URL_DETAILS_ERROR_MESSAGE],_this58.isTextInputDisabled=!1,_typeof(n)===T){var _ref83=(h=(u=(d=e.directConnection)==null?void 0:d.azure)==null?void 0:u.openAI)==null?void 0:h.chat,f=_ref83.function_handler;f&&(_this58._functionHandler=f);}Ce.validateURLDetails(i)?_this58.url=hn.buildURL(i):(_this58.isTextInputDisabled=!0,_this58.canSendMessage=function(){return!1;},setTimeout(function(){e.addMessage(_defineProperty({},je,Ce.URL_DETAILS_ERROR_MESSAGE));}));return _this58;}_inherits(hn,_ws);return _createClass(hn,null,[{key:"buildURL",value:function buildURL(e){var t=e.endpoint,s=e.deploymentId,i=e.version;return"".concat(t,"/openai/deployments/").concat(s,"/chat/completions?api-version=").concat(i);}}]);}(ws);var Qs=/*#__PURE__*/function(_k15){function Qs(e){var _this59$maxMessages,_c$model2;var _this59;_classCallCheck(this,Qs);var n,o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.bigModel;_this59=_callSuper(this,Qs,[e,ct.buildKeyVerificationDetails(),ct.buildHeaders,s]),_this59.insertKeyPlaceholderText=_this59.genereteAPIKeyName("BigModel"),_this59.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",_this59.url="https://open.bigmodel.cn/api/paas/v4/chat/completions",_this59.permittedErrorPrefixes=[K,ie],_this59._systemMessage="";var i=(n=t.bigModel)==null?void 0:n.chat;if(_typeof(i)===T){i.system_prompt&&(_this59._systemMessage=i.system_prompt);var d=(l=(a=(o=e.directConnection)==null?void 0:o.bigModel)==null?void 0:a.chat)==null?void 0:l.function_handler;d&&(_this59._functionHandler=d),_this59.cleanConfig(i),Object.assign(_this59.rawBody,i);}(_this59$maxMessages=_this59.maxMessages)!==null&&_this59$maxMessages!==void 0?_this59$maxMessages:_this59.maxMessages=-1,(_c$model2=(c=_this59.rawBody).model)!==null&&_c$model2!==void 0?_c$model2:c.model="glm-4.5";return _this59;}_inherits(Qs,_k15);return _createClass(Qs,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:Qs.getTextWFilesContent(n,Qs.getFileContent),role:n.role==="ai"?"assistant":"user"};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI21=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee125(e,t){var _this$_messages4;return _regenerator().w(function(_context125){while(1)switch(_context125.n){case 0:(_this$_messages4=this._messages)!==null&&_this$_messages4!==void 0?_this$_messages4:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context125.a(2);}},_callee125,this);}));function callServiceAPI(_x236,_x237){return _callServiceAPI21.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData24=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee126(e,t){var _s0;return _regenerator().w(function(_context126){while(1)switch(_context126.n){case 0:if(!e.error){_context126.n=1;break;}throw e.error.message;case 1:if(!(e.choices.length>0)){_context126.n=3;break;}if(!(e.choices[0].delta!==void 0)){_context126.n=2;break;}return _context126.a(2,this.extractStreamResult(e.choices[0],t));case 2:if(!(e.choices[0].message!==void 0)){_context126.n=3;break;}_s0=e.choices[0].message;return _context126.a(2,_s0.tool_calls?this.handleToolsGeneric({tool_calls:_s0.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s0.content));case 3:return _context126.a(2,_defineProperty({},y,""));}},_callee126,this);}));function extractResultData(_x238,_x239){return _extractResultData24.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee127(e,t){var o,a,l,c,s,i,n,d;return _regenerator().w(function(_context127){while(1)switch(_context127.n){case 0:s=e.delta,i=e.finish_reason,n=(o=this._messages)==null?void 0:o.messageToElements[this._messages.messageToElements.length-2];if(!((n==null?void 0:n[0].role)==="ai"&&((a=n==null?void 0:n[0].text)==null?void 0:a.replace(/\n/g,"").trim().length)===0&&((l=this._messages)==null||l.removeMessage(n[1].text),(c=this._messages)==null||c.messageToElements.splice(this._messages.messageToElements.length-2,1)),i==="tool_calls")){_context127.n=2;break;}if(!s.tool_calls){_context127.n=1;break;}d={tool_calls:s.tool_calls};return _context127.a(2,this.handleToolsGeneric(d,this._functionHandler,this._messages,t));case 1:return _context127.a(2,_defineProperty({},y,(s==null?void 0:s.content)||""));case 2:return _context127.a(2,_defineProperty({},y,(s==null?void 0:s.content)||""));}},_callee127,this);}));function extractStreamResult(_x240,_x241){return _extractStreamResult2.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getFileContent",value:function getFileContent(e){return e.map(function(t){return t.type==="image"?{type:"image_url",image_url:{url:t.src||""}}:{type:"file",file_url:{url:t.src||""}};});}}]);}(k);var Qa=/*#__PURE__*/function(_k16){function Qa(e){var _this60$maxMessages,_o$model8;var _this60;_classCallCheck(this,Qa);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.together;_this60=_callSuper(this,Qa,[e,dt.buildKeyVerificationDetails(),dt.buildHeaders,s]),_this60.insertKeyPlaceholderText=_this60.genereteAPIKeyName("Together AI"),_this60.keyHelpUrl="https://api.together.xyz/settings/api-keys",_this60.url="https://api.together.xyz/v1/chat/completions",_this60.permittedErrorPrefixes=[we,ie],_this60._systemMessage="";var i=(n=t.together)==null?void 0:n.chat;_typeof(i)===T&&(i.system_prompt&&(_this60._systemMessage=i.system_prompt),_this60.cleanConfig(i),Object.assign(_this60.rawBody,i)),(_this60$maxMessages=_this60.maxMessages)!==null&&_this60$maxMessages!==void 0?_this60$maxMessages:_this60.maxMessages=-1,(_o$model8=(o=_this60.rawBody).model)!==null&&_o$model8!==void 0?_o$model8:o.model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo";return _this60;}_inherits(Qa,_k16);return _createClass(Qa,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role==="ai"?"assistant":n.role};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI22=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee128(e,t){return _regenerator().w(function(_context128){while(1)switch(_context128.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context128.a(2);}},_callee128,this);}));function callServiceAPI(_x242,_x243){return _callServiceAPI22.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee129(e){return _regenerator().w(function(_context129){while(1)switch(_context129.n){case 0:if(!e.error){_context129.n=1;break;}throw e.error.message;case 1:if(!(e.choices.length>0)){_context129.n=3;break;}if(!(e.choices[0].message!==void 0)){_context129.n=2;break;}return _context129.a(2,_defineProperty({},y,e.choices[0].message.content));case 2:if(!(e.choices[0].delta!==void 0)){_context129.n=3;break;}return _context129.a(2,_defineProperty({},y,e.choices[0].delta.content));case 3:return _context129.a(2,_defineProperty({},y,""));}},_callee129);}));function extractResultData(_x244){return _extractResultData25.apply(this,arguments);}return extractResultData;}()}]);}(k);var Me=/*#__PURE__*/function(_k17){function Me(e){var _this61;_classCallCheck(this,Me);var o;var t=e.directConnection,s=t==null?void 0:t.openAI,i={images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}};_this61=_callSuper(this,Me,[e,G.buildKeyVerificationDetails(),G.buildHeaders,s,i]),_this61.insertKeyPlaceholderText=_this61.genereteAPIKeyName("OpenAI"),_this61.keyHelpUrl="https://platform.openai.com/account/api-keys",_this61.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>OpenAI DALL\xB7E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href=\"https://platform.openai.com/docs/guides/images/introduction\" target=\"_blank\">here</a>\n for more info.</p>",_this61.url="",_this61.permittedErrorPrefixes=[ks,"Invalid input image"];var n=(o=t==null?void 0:t.openAI)==null?void 0:o.images;if(_this61.camera){var a=_typeof(n)=="object"&&n.size?Number.parseInt(n.size):1024;_this61.camera.files={dimensions:{width:a,height:a}};}_typeof(n)===T&&Object.assign(_this61.rawBody,n),_this61.canSendMessage=Me.canFileSendMessage;return _this61;}_inherits(Me,_k17);return _createClass(Me,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e));return t&&t!==""&&(s.prompt=t),s;}// prettier-ignore
214
214
  },{key:"callApiWithImage",value:function callApiWithImage(e,t,s){var o,a;var i;var n=(a=(o=t[t.length-1])==null?void 0:o.text)==null?void 0:a.trim();if(s[1]||n&&n!==""){this.url=Me.IMAGE_EDIT_URL;var l=this.preprocessBody(this.rawBody,n);i=Me.createFormDataBody(l,s[0],s[1]);}else this.url=Me.IMAGE_VARIATIONS_URL,i=Me.createFormDataBody(this.rawBody,s[0]);w.tempRemoveContentHeader(this.connectSettings,V.request.bind(this,this,i,e),!1);}},{key:"callServiceAPI",value:function(){var _callServiceAPI23=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee130(e,t,s){var i,n;return _regenerator().w(function(_context130){while(1)switch(_context130.n){case 0:if((i=this.connectSettings)!=null&&i.headers){_context130.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:if(!(s!=null&&s[0])){_context130.n=2;break;}this.callApiWithImage(e,t,s);_context130.n=4;break;case 2:if(this.connectSettings){_context130.n=3;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 3:this.url=Me.IMAGE_GENERATION_URL;n=this.preprocessBody(this.rawBody,t[t.length-1].text);V.request(this,n,e);case 4:return _context130.a(2);}},_callee130,this);}));function callServiceAPI(_x245,_x246,_x247){return _callServiceAPI23.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData26=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee131(e){return _regenerator().w(function(_context131){while(1)switch(_context131.n){case 0:if(!e.error){_context131.n=1;break;}throw e.error.message;case 1:return _context131.a(2,{files:e.data.map(function(s){return s.url?{src:s.url,type:"image"}:{src:"".concat(jt).concat(s.b64_json),type:"image"};})});}},_callee131);}));function extractResultData(_x248){return _extractResultData26.apply(this,arguments);}return extractResultData;}()// private static readonly MODAL_MARKDOWN = `
215
215
  // 1 image:
216
216
  // - With text - edits image based on the text
@@ -220,31 +220,31 @@ function preprocessBody(e,t){var _s$max_tokens;var o;var s=JSON.parse(JSON.strin
220
220
  // Add text to describe the required modification.
221
221
  // Click here for [more info](https://platform.openai.com/docs/guides/images/introduction).
222
222
  // `;
223
- }],[{key:"canFileSendMessage",value:function canFileSendMessage(e,t){return!!(t!=null&&t[0])||!!(e&&e.trim()!=="");}},{key:"createFormDataBody",value:function createFormDataBody(e,t,s){var i=new FormData();return i.append("image",t),s&&i.append("mask",s),Object.keys(e).forEach(function(n){i.append(n,String(e[n]));}),i;}}]);}(k);Me.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",Me.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",Me.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";var Xi=Me;var ei=/*#__PURE__*/function(){function ei(){_classCallCheck(this,ei);}return _createClass(ei,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===se?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://openrouter.ai/api/v1/key",method:z,handleVerificationResult:ei.handleVerificationResult};}}]);}();var ps=/*#__PURE__*/function(_k18){function ps(e){var _this62$maxMessages,_o$model9,_a$max_tokens;var _this62;_classCallCheck(this,ps);var i,n,o,a;var s=JSON.parse(JSON.stringify(e.directConnection)).openRouter;if(_this62=_callSuper(this,ps,[e,ei.buildKeyVerificationDetails(),ei.buildHeaders,s]),_this62.insertKeyPlaceholderText=_this62.genereteAPIKeyName("OpenRouter"),_this62.keyHelpUrl="https://openrouter.ai/keys",_this62.url="https://openrouter.ai/api/v1/chat/completions",_this62.permittedErrorPrefixes=[we,se],_this62._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this62._systemMessage=s.system_prompt);var l=(n=(i=e.directConnection)==null?void 0:i.openRouter)==null?void 0:n.function_handler;l&&(_this62._functionHandler=l),_this62.cleanConfig(s),Object.assign(_this62.rawBody,s);}(_this62$maxMessages=_this62.maxMessages)!==null&&_this62$maxMessages!==void 0?_this62$maxMessages:_this62.maxMessages=-1,(_o$model9=(o=_this62.rawBody).model)!==null&&_o$model9!==void 0?_o$model9:o.model="openai/gpt-4o",(_a$max_tokens=(a=_this62.rawBody).max_tokens)!==null&&_a$max_tokens!==void 0?_a$max_tokens:a.max_tokens=1e3;return _this62;}_inherits(ps,_k18);return _createClass(ps,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(o){return{content:ps.getContent(o),role:o.role===v.USER_ROLE?"user":"assistant"};}),n=[];return this._systemMessage&&n.push({role:"system",content:this._systemMessage}),n.push.apply(n,_toConsumableArray(i)),s.messages=n,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI24=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee132(e,t){var _this$_messages5;return _regenerator().w(function(_context132){while(1)switch(_context132.n){case 0:(_this$_messages5=this._messages)!==null&&_this$_messages5!==void 0?_this$_messages5:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context132.a(2);}},_callee132,this);}));function callServiceAPI(_x249,_x250){return _callServiceAPI24.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData27=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee133(e,t){var s,i,n,o,a,l,_a5,_l4;return _regenerator().w(function(_context133){while(1)switch(_context133.n){case 0:if(!e.error){_context133.n=1;break;}throw e.error.message;case 1:if(!(e.object==="chat.completion.chunk")){_context133.n=4;break;}a=(s=e.choices)==null?void 0:s[0];if(!(a!=null&&a.delta)){_context133.n=2;break;}return _context133.a(2,this.extractStreamResult(a,t));case 2:if(!((i=e.message)!=null&&i.images)){_context133.n=3;break;}l=e.message.images.map(function(c){return{src:c.image_url.url};});return _context133.a(2,_defineProperty(_defineProperty({},y,e.message.content||""),"files",l));case 3:return _context133.a(2,_defineProperty({},y,""));case 4:if(!(e.object==="chat.completion")){_context133.n=6;break;}_a5=(n=e.choices)==null?void 0:n[0];if(!(_a5!=null&&_a5.message)){_context133.n=6;break;}if(!_a5.message.tool_calls){_context133.n=5;break;}return _context133.a(2,this.handleToolsGeneric({tool_calls:_a5.message.tool_calls},this._functionHandler,this._messages,t));case 5:_l4=((o=_a5.message.images)==null?void 0:o.map(function(c){return{src:c.image_url.url};}))||[];return _context133.a(2,_defineProperty(_defineProperty({},y,_a5.message.content||""),"files",_l4));case 6:return _context133.a(2,_defineProperty({},y,""));}},_callee133,this);}));function extractResultData(_x251,_x252){return _extractResultData27.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee134(e,t){var s,i;return _regenerator().w(function(_context134){while(1)switch(_context134.n){case 0:s=e.delta;if(!(s!=null&&s.images)){_context134.n=1;break;}i=s.images.map(function(n){return{src:n.image_url.url};});return _context134.a(2,_defineProperty(_defineProperty({},y,s.content||""),"files",i));case 1:return _context134.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee134,this);}));function extractStreamResult(_x253,_x254){return _extractStreamResult3.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getAudioContent",value:function getAudioContent(e){return e.filter(function(t){return t.type==="audio";}).map(function(t){var n,o,a;var s=(n=t.src)==null?void 0:n.split(",")[1],i=(a=(o=t.src)==null?void 0:o.match(/data:audio\/([^;]+)/))==null?void 0:a[1];return{type:"input_audio",input_audio:{data:s||"",format:i==="wav"||i==="mp3"?i:"mp3"}};}).filter(function(t){return t.input_audio.data.length>0;});}},{key:"getContent",value:function getContent(e){if(e.files&&e.files.length>0){var t=[].concat(_toConsumableArray(ps.getImageContent(e.files)),_toConsumableArray(ps.getAudioContent(e.files)));return e.text&&e.text.trim().length>0&&t.unshift(_defineProperty({type:"text"},y,e.text)),t.length>0?t:e.text||"";}return e.text||"";}}]);}(k);var ti=/*#__PURE__*/function(){function ti(){_classCallCheck(this,ti);}return _createClass(ti,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){e.error?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.perplexity.ai/chat/completions",method:Z,handleVerificationResult:ti.handleVerificationResult};}}]);}();var el=/*#__PURE__*/function(_k19){function el(e){var _this63$maxMessages,_i$model;var _this63;_classCallCheck(this,el);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).perplexity;_this63=_callSuper(this,el,[e,ti.buildKeyVerificationDetails(),ti.buildHeaders,s]),_this63.insertKeyPlaceholderText=_this63.genereteAPIKeyName("Perplexity"),_this63.keyHelpUrl="https://www.perplexity.ai/settings/api",_this63.url="https://api.perplexity.ai/chat/completions",_this63.permittedErrorPrefixes=[ht,ur,"Permission denied"],_this63._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this63._systemMessage=s.system_prompt),_this63.cleanConfig(s),Object.assign(_this63.rawBody,s)),(_this63$maxMessages=_this63.maxMessages)!==null&&_this63$maxMessages!==void 0?_this63$maxMessages:_this63.maxMessages=-1,(_i$model=(i=_this63.rawBody).model)!==null&&_i$model!==void 0?_i$model:i.model="sonar";return _this63;}_inherits(el,_k19);return _createClass(el,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee135(e,t){return _regenerator().w(function(_context135){while(1)switch(_context135.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context135.a(2);}},_callee135,this);}));function callServiceAPI(_x255,_x256){return _callServiceAPI25.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData28=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee136(e){var t;return _regenerator().w(function(_context136){while(1)switch(_context136.n){case 0:if(!e.error){_context136.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context136.n=3;break;}t=e.choices[0];if(!(t.delta&&t.delta.content)){_context136.n=2;break;}return _context136.a(2,_defineProperty({},y,t.delta.content));case 2:if(!(t.message&&t.message.content)){_context136.n=3;break;}return _context136.a(2,_defineProperty({},y,t.message.content));case 3:return _context136.a(2,_defineProperty({},y,""));}},_callee136);}));function extractResultData(_x257){return _extractResultData28.apply(this,arguments);}return extractResultData;}()}]);}(k);var si=/*#__PURE__*/function(){function si(){_classCallCheck(this,si);}return _createClass(si,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===se?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.deepseek.com/models",method:z,handleVerificationResult:si.handleVerificationResult};}}]);}();var tl=/*#__PURE__*/function(_k20){function tl(e){var _this64$maxMessages,_i$model2,_n$temperature,_o$max_tokens;var _this64;_classCallCheck(this,tl);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).deepSeek;_this64=_callSuper(this,tl,[e,si.buildKeyVerificationDetails(),si.buildHeaders,s]),_this64.insertKeyPlaceholderText=_this64.genereteAPIKeyName("DeepSeek"),_this64.keyHelpUrl="https://platform.deepseek.com/api_keys",_this64.url="https://api.deepseek.com/v1/chat/completions",_this64.permittedErrorPrefixes=[we,se],_this64._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this64._systemMessage=s.system_prompt),_this64.cleanConfig(s),Object.assign(_this64.rawBody,s)),(_this64$maxMessages=_this64.maxMessages)!==null&&_this64$maxMessages!==void 0?_this64$maxMessages:_this64.maxMessages=-1,(_i$model2=(i=_this64.rawBody).model)!==null&&_i$model2!==void 0?_i$model2:i.model="deepseek-chat",(_n$temperature=(n=_this64.rawBody).temperature)!==null&&_n$temperature!==void 0?_n$temperature:n.temperature=1,(_o$max_tokens=(o=_this64.rawBody).max_tokens)!==null&&_o$max_tokens!==void 0?_o$max_tokens:o.max_tokens=4096;return _this64;}_inherits(tl,_k20);return _createClass(tl,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI26=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee137(e,t){return _regenerator().w(function(_context137){while(1)switch(_context137.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context137.a(2);}},_callee137,this);}));function callServiceAPI(_x258,_x259){return _callServiceAPI26.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData29=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee138(e){var t;return _regenerator().w(function(_context138){while(1)switch(_context138.n){case 0:if(!e.error){_context138.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context138.n=3;break;}t=e.choices[0];if(!(t.delta&&t.delta.content)){_context138.n=2;break;}return _context138.a(2,_defineProperty({},y,t.delta.content));case 2:if(!(t.message&&t.message.content)){_context138.n=3;break;}return _context138.a(2,_defineProperty({},y,t.message.content));case 3:return _context138.a(2,_defineProperty({},y,""));}},_callee138);}));function extractResultData(_x260){return _extractResultData29.apply(this,arguments);}return extractResultData;}()}]);}(k);var ii=/*#__PURE__*/function(){function ii(){_classCallCheck(this,ii);}return _createClass(ii,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var o;((o=e.base_resp)==null?void 0:o.status_code)===1004?i(b.INVALID_KEY):s(t);}// WORK - similar
224
- },{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.minimax.io/v1/files/delete",method:Z,handleVerificationResult:ii.handleVerificationResult};}}]);}();var sl=/*#__PURE__*/function(_k21){function sl(e){var _this65$maxMessages,_i$model3;var _this65;_classCallCheck(this,sl);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).miniMax;_this65=_callSuper(this,sl,[e,ii.buildKeyVerificationDetails(),ii.buildHeaders,s]),_this65.insertKeyPlaceholderText=_this65.genereteAPIKeyName("MiniMax"),_this65.keyHelpUrl="https://www.minimaxi.com",_this65.url="https://api.minimax.io/v1/text/chatcompletion_v2",_this65.permittedErrorPrefixes=[we,se,"insufficient balance"],_this65._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this65._systemMessage=s.system_prompt),_this65.cleanConfig(s),Object.assign(_this65.rawBody,s)),(_this65$maxMessages=_this65.maxMessages)!==null&&_this65$maxMessages!==void 0?_this65$maxMessages:_this65.maxMessages=-1,(_i$model3=(i=_this65.rawBody).model)!==null&&_i$model3!==void 0?_i$model3:i.model="MiniMax-M1";return _this65;}_inherits(sl,_k21);return _createClass(sl,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI27=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee139(e,t){return _regenerator().w(function(_context139){while(1)switch(_context139.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context139.a(2);}},_callee139,this);}));function callServiceAPI(_x261,_x262){return _callServiceAPI27.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData30=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee140(e){var t,_s1;return _regenerator().w(function(_context140){while(1)switch(_context140.n){case 0:if(!e.error){_context140.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context140.n=3;break;}_s1=e.choices[0];if(!(_s1.delta&&_s1.delta.content)){_context140.n=2;break;}return _context140.a(2,_defineProperty({},y,_s1.delta.content));case 2:if(!(_s1.message&&_s1.message.content)){_context140.n=3;break;}return _context140.a(2,_defineProperty({},y,_s1.message.content));case 3:if(!(typeof((t=e.base_resp)==null?void 0:t.status_code)=="number"&&e.base_resp.status_code>0)){_context140.n=4;break;}throw e.base_resp.status_msg;case 4:return _context140.a(2,_defineProperty({},y,""));}},_callee140);}));function extractResultData(_x263){return _extractResultData30.apply(this,arguments);}return extractResultData;}()}]);}(k);var ni=/*#__PURE__*/function(){function ni(){_classCallCheck(this,ni);}return _createClass(ni,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N),"accept",N);}// prettier-ignore
223
+ }],[{key:"canFileSendMessage",value:function canFileSendMessage(e,t){return!!(t!=null&&t[0])||!!(e&&e.trim()!=="");}},{key:"createFormDataBody",value:function createFormDataBody(e,t,s){var i=new FormData();return i.append("image",t),s&&i.append("mask",s),Object.keys(e).forEach(function(n){i.append(n,String(e[n]));}),i;}}]);}(k);Me.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",Me.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",Me.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";var Xi=Me;var ei=/*#__PURE__*/function(){function ei(){_classCallCheck(this,ei);}return _createClass(ei,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===ie?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://openrouter.ai/api/v1/key",method:z,handleVerificationResult:ei.handleVerificationResult};}}]);}();var ps=/*#__PURE__*/function(_k18){function ps(e){var _this62$maxMessages,_o$model9,_a$max_tokens;var _this62;_classCallCheck(this,ps);var i,n,o,a;var s=JSON.parse(JSON.stringify(e.directConnection)).openRouter;if(_this62=_callSuper(this,ps,[e,ei.buildKeyVerificationDetails(),ei.buildHeaders,s]),_this62.insertKeyPlaceholderText=_this62.genereteAPIKeyName("OpenRouter"),_this62.keyHelpUrl="https://openrouter.ai/keys",_this62.url="https://openrouter.ai/api/v1/chat/completions",_this62.permittedErrorPrefixes=[we,ie],_this62._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this62._systemMessage=s.system_prompt);var l=(n=(i=e.directConnection)==null?void 0:i.openRouter)==null?void 0:n.function_handler;l&&(_this62._functionHandler=l),_this62.cleanConfig(s),Object.assign(_this62.rawBody,s);}(_this62$maxMessages=_this62.maxMessages)!==null&&_this62$maxMessages!==void 0?_this62$maxMessages:_this62.maxMessages=-1,(_o$model9=(o=_this62.rawBody).model)!==null&&_o$model9!==void 0?_o$model9:o.model="openai/gpt-4o",(_a$max_tokens=(a=_this62.rawBody).max_tokens)!==null&&_a$max_tokens!==void 0?_a$max_tokens:a.max_tokens=1e3;return _this62;}_inherits(ps,_k18);return _createClass(ps,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(o){return{content:ps.getContent(o),role:o.role===v.USER_ROLE?"user":"assistant"};}),n=[];return this._systemMessage&&n.push({role:"system",content:this._systemMessage}),n.push.apply(n,_toConsumableArray(i)),s.messages=n,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI24=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee132(e,t){var _this$_messages5;return _regenerator().w(function(_context132){while(1)switch(_context132.n){case 0:(_this$_messages5=this._messages)!==null&&_this$_messages5!==void 0?_this$_messages5:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context132.a(2);}},_callee132,this);}));function callServiceAPI(_x249,_x250){return _callServiceAPI24.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData27=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee133(e,t){var s,i,n,o,a,l,_a5,_l4;return _regenerator().w(function(_context133){while(1)switch(_context133.n){case 0:if(!e.error){_context133.n=1;break;}throw e.error.message;case 1:if(!(e.object==="chat.completion.chunk")){_context133.n=4;break;}a=(s=e.choices)==null?void 0:s[0];if(!(a!=null&&a.delta)){_context133.n=2;break;}return _context133.a(2,this.extractStreamResult(a,t));case 2:if(!((i=e.message)!=null&&i.images)){_context133.n=3;break;}l=e.message.images.map(function(c){return{src:c.image_url.url};});return _context133.a(2,_defineProperty(_defineProperty({},y,e.message.content||""),"files",l));case 3:return _context133.a(2,_defineProperty({},y,""));case 4:if(!(e.object==="chat.completion")){_context133.n=6;break;}_a5=(n=e.choices)==null?void 0:n[0];if(!(_a5!=null&&_a5.message)){_context133.n=6;break;}if(!_a5.message.tool_calls){_context133.n=5;break;}return _context133.a(2,this.handleToolsGeneric({tool_calls:_a5.message.tool_calls},this._functionHandler,this._messages,t));case 5:_l4=((o=_a5.message.images)==null?void 0:o.map(function(c){return{src:c.image_url.url};}))||[];return _context133.a(2,_defineProperty(_defineProperty({},y,_a5.message.content||""),"files",_l4));case 6:return _context133.a(2,_defineProperty({},y,""));}},_callee133,this);}));function extractResultData(_x251,_x252){return _extractResultData27.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee134(e,t){var s,i;return _regenerator().w(function(_context134){while(1)switch(_context134.n){case 0:s=e.delta;if(!(s!=null&&s.images)){_context134.n=1;break;}i=s.images.map(function(n){return{src:n.image_url.url};});return _context134.a(2,_defineProperty(_defineProperty({},y,s.content||""),"files",i));case 1:return _context134.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee134,this);}));function extractStreamResult(_x253,_x254){return _extractStreamResult3.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getAudioContent",value:function getAudioContent(e){return e.filter(function(t){return t.type==="audio";}).map(function(t){var n,o,a;var s=(n=t.src)==null?void 0:n.split(",")[1],i=(a=(o=t.src)==null?void 0:o.match(/data:audio\/([^;]+)/))==null?void 0:a[1];return{type:"input_audio",input_audio:{data:s||"",format:i==="wav"||i==="mp3"?i:"mp3"}};}).filter(function(t){return t.input_audio.data.length>0;});}},{key:"getContent",value:function getContent(e){if(e.files&&e.files.length>0){var t=[].concat(_toConsumableArray(ps.getImageContent(e.files)),_toConsumableArray(ps.getAudioContent(e.files)));return e.text&&e.text.trim().length>0&&t.unshift(_defineProperty({type:"text"},y,e.text)),t.length>0?t:e.text||"";}return e.text||"";}}]);}(k);var ti=/*#__PURE__*/function(){function ti(){_classCallCheck(this,ti);}return _createClass(ti,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){e.error?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.perplexity.ai/chat/completions",method:Z,handleVerificationResult:ti.handleVerificationResult};}}]);}();var el=/*#__PURE__*/function(_k19){function el(e){var _this63$maxMessages,_i$model;var _this63;_classCallCheck(this,el);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).perplexity;_this63=_callSuper(this,el,[e,ti.buildKeyVerificationDetails(),ti.buildHeaders,s]),_this63.insertKeyPlaceholderText=_this63.genereteAPIKeyName("Perplexity"),_this63.keyHelpUrl="https://www.perplexity.ai/settings/api",_this63.url="https://api.perplexity.ai/chat/completions",_this63.permittedErrorPrefixes=[ht,ur,"Permission denied"],_this63._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this63._systemMessage=s.system_prompt),_this63.cleanConfig(s),Object.assign(_this63.rawBody,s)),(_this63$maxMessages=_this63.maxMessages)!==null&&_this63$maxMessages!==void 0?_this63$maxMessages:_this63.maxMessages=-1,(_i$model=(i=_this63.rawBody).model)!==null&&_i$model!==void 0?_i$model:i.model="sonar";return _this63;}_inherits(el,_k19);return _createClass(el,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI25=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee135(e,t){return _regenerator().w(function(_context135){while(1)switch(_context135.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context135.a(2);}},_callee135,this);}));function callServiceAPI(_x255,_x256){return _callServiceAPI25.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData28=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee136(e){var t;return _regenerator().w(function(_context136){while(1)switch(_context136.n){case 0:if(!e.error){_context136.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context136.n=3;break;}t=e.choices[0];if(!(t.delta&&t.delta.content)){_context136.n=2;break;}return _context136.a(2,_defineProperty({},y,t.delta.content));case 2:if(!(t.message&&t.message.content)){_context136.n=3;break;}return _context136.a(2,_defineProperty({},y,t.message.content));case 3:return _context136.a(2,_defineProperty({},y,""));}},_callee136);}));function extractResultData(_x257){return _extractResultData28.apply(this,arguments);}return extractResultData;}()}]);}(k);var si=/*#__PURE__*/function(){function si(){_classCallCheck(this,si);}return _createClass(si,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===ie?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.deepseek.com/models",method:z,handleVerificationResult:si.handleVerificationResult};}}]);}();var tl=/*#__PURE__*/function(_k20){function tl(e){var _this64$maxMessages,_i$model2,_n$temperature,_o$max_tokens;var _this64;_classCallCheck(this,tl);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).deepSeek;_this64=_callSuper(this,tl,[e,si.buildKeyVerificationDetails(),si.buildHeaders,s]),_this64.insertKeyPlaceholderText=_this64.genereteAPIKeyName("DeepSeek"),_this64.keyHelpUrl="https://platform.deepseek.com/api_keys",_this64.url="https://api.deepseek.com/v1/chat/completions",_this64.permittedErrorPrefixes=[we,ie],_this64._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this64._systemMessage=s.system_prompt),_this64.cleanConfig(s),Object.assign(_this64.rawBody,s)),(_this64$maxMessages=_this64.maxMessages)!==null&&_this64$maxMessages!==void 0?_this64$maxMessages:_this64.maxMessages=-1,(_i$model2=(i=_this64.rawBody).model)!==null&&_i$model2!==void 0?_i$model2:i.model="deepseek-chat",(_n$temperature=(n=_this64.rawBody).temperature)!==null&&_n$temperature!==void 0?_n$temperature:n.temperature=1,(_o$max_tokens=(o=_this64.rawBody).max_tokens)!==null&&_o$max_tokens!==void 0?_o$max_tokens:o.max_tokens=4096;return _this64;}_inherits(tl,_k20);return _createClass(tl,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI26=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee137(e,t){return _regenerator().w(function(_context137){while(1)switch(_context137.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context137.a(2);}},_callee137,this);}));function callServiceAPI(_x258,_x259){return _callServiceAPI26.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData29=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee138(e){var t;return _regenerator().w(function(_context138){while(1)switch(_context138.n){case 0:if(!e.error){_context138.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context138.n=3;break;}t=e.choices[0];if(!(t.delta&&t.delta.content)){_context138.n=2;break;}return _context138.a(2,_defineProperty({},y,t.delta.content));case 2:if(!(t.message&&t.message.content)){_context138.n=3;break;}return _context138.a(2,_defineProperty({},y,t.message.content));case 3:return _context138.a(2,_defineProperty({},y,""));}},_callee138);}));function extractResultData(_x260){return _extractResultData29.apply(this,arguments);}return extractResultData;}()}]);}(k);var ii=/*#__PURE__*/function(){function ii(){_classCallCheck(this,ii);}return _createClass(ii,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var o;((o=e.base_resp)==null?void 0:o.status_code)===1004?i(b.INVALID_KEY):s(t);}// WORK - similar
224
+ },{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.minimax.io/v1/files/delete",method:Z,handleVerificationResult:ii.handleVerificationResult};}}]);}();var sl=/*#__PURE__*/function(_k21){function sl(e){var _this65$maxMessages,_i$model3;var _this65;_classCallCheck(this,sl);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).miniMax;_this65=_callSuper(this,sl,[e,ii.buildKeyVerificationDetails(),ii.buildHeaders,s]),_this65.insertKeyPlaceholderText=_this65.genereteAPIKeyName("MiniMax"),_this65.keyHelpUrl="https://www.minimaxi.com",_this65.url="https://api.minimax.io/v1/text/chatcompletion_v2",_this65.permittedErrorPrefixes=[we,ie,"insufficient balance"],_this65._systemMessage="",_typeof(s)===T&&(s.system_prompt&&(_this65._systemMessage=s.system_prompt),_this65.cleanConfig(s),Object.assign(_this65.rawBody,s)),(_this65$maxMessages=_this65.maxMessages)!==null&&_this65$maxMessages!==void 0?_this65$maxMessages:_this65.maxMessages=-1,(_i$model3=(i=_this65.rawBody).model)!==null&&_i$model3!==void 0?_i$model3:i.model="MiniMax-M1";return _this65;}_inherits(sl,_k21);return _createClass(sl,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:n.text||"",role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI27=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee139(e,t){return _regenerator().w(function(_context139){while(1)switch(_context139.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context139.a(2);}},_callee139,this);}));function callServiceAPI(_x261,_x262){return _callServiceAPI27.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData30=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee140(e){var t,_s1;return _regenerator().w(function(_context140){while(1)switch(_context140.n){case 0:if(!e.error){_context140.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context140.n=3;break;}_s1=e.choices[0];if(!(_s1.delta&&_s1.delta.content)){_context140.n=2;break;}return _context140.a(2,_defineProperty({},y,_s1.delta.content));case 2:if(!(_s1.message&&_s1.message.content)){_context140.n=3;break;}return _context140.a(2,_defineProperty({},y,_s1.message.content));case 3:if(!(typeof((t=e.base_resp)==null?void 0:t.status_code)=="number"&&e.base_resp.status_code>0)){_context140.n=4;break;}throw e.base_resp.status_msg;case 4:return _context140.a(2,_defineProperty({},y,""));}},_callee140);}));function extractResultData(_x263){return _extractResultData30.apply(this,arguments);}return extractResultData;}()}]);}(k);var ni=/*#__PURE__*/function(){function ni(){_classCallCheck(this,ni);}return _createClass(ni,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N),"accept",N);}// prettier-ignore
225
225
  },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){e.detail?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.mistral.ai/v1/models",method:z,handleVerificationResult:ni.handleVerificationResult};}}]);}();var un=/*#__PURE__*/function(_k22){function un(e){var _this66$maxMessages,_o$model0;var _this66;_classCallCheck(this,un);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).mistral;if(_this66=_callSuper(this,un,[e,ni.buildKeyVerificationDetails(),ni.buildHeaders,s]),_this66.insertKeyPlaceholderText=_this66.genereteAPIKeyName("Mistral"),_this66.keyHelpUrl="https://console.mistral.ai/api-keys/",_this66.url="https://api.mistral.ai/v1/chat/completions",_this66.permittedErrorPrefixes=[ht],_this66._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this66._systemMessage=s.system_prompt);var a=(n=(i=e.directConnection)==null?void 0:i.mistral)==null?void 0:n.function_handler;a&&(_this66._functionHandler=a),_this66.cleanConfig(s),Object.assign(_this66.rawBody,s);}(_this66$maxMessages=_this66.maxMessages)!==null&&_this66$maxMessages!==void 0?_this66$maxMessages:_this66.maxMessages=-1,(_o$model0=(o=_this66.rawBody).model)!==null&&_o$model0!==void 0?_o$model0:o.model="mistral-small-latest";return _this66;}_inherits(un,_k22);return _createClass(un,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{role:n.role==="ai"?"assistant":"user",content:k.getTextWFilesContent(n,un.getFileContent)};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI28=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee141(e,t){var _this$_messages6;return _regenerator().w(function(_context141){while(1)switch(_context141.n){case 0:(_this$_messages6=this._messages)!==null&&_this$_messages6!==void 0?_this$_messages6:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context141.a(2);}},_callee141,this);}));function callServiceAPI(_x264,_x265){return _callServiceAPI28.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData31=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee142(e,t){var _s10;return _regenerator().w(function(_context142){while(1)switch(_context142.n){case 0:if(!e.message){_context142.n=1;break;}throw e.message;case 1:if(!e.error){_context142.n=2;break;}throw e.error.message;case 2:if(!(e.choices&&e.choices.length>0)){_context142.n=4;break;}_s10=e.choices[0];if(!_s10.delta){_context142.n=3;break;}return _context142.a(2,this.extractStreamResult(_s10,t));case 3:if(!_s10.message){_context142.n=4;break;}return _context142.a(2,_s10.message.tool_calls?this.handleToolsGeneric({tool_calls:_s10.message.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s10.message.content||""));case 4:return _context142.a(2,_defineProperty({},y,""));}},_callee142,this);}));function extractResultData(_x266,_x267){return _extractResultData31.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee143(e,t){var s,i,n;return _regenerator().w(function(_context143){while(1)switch(_context143.n){case 0:s=e.delta,i=e.finish_reason;if(!(i==="tool_calls"&&s!=null&&s.tool_calls)){_context143.n=1;break;}n={tool_calls:s.tool_calls};return _context143.a(2,this.handleToolsGeneric(n,this._functionHandler,this._messages,t));case 1:return _context143.a(2,_defineProperty({},y,(s==null?void 0:s.content)||""));}},_callee143,this);}));function extractStreamResult(_x268,_x269){return _extractStreamResult4.apply(this,arguments);}return extractStreamResult;}()}],[{key:"getFileContent",value:function getFileContent(e){return e.map(function(t){return t.type==="image"?{type:"image_url",image_url:t.src||""}:_defineProperty({type:"text"},y,"[Unsupported file type: ".concat(t.type,"]"));});}}]);}(k);var fn=/*#__PURE__*/function(_k23){function fn(e){var _this67$maxMessages,_c$model3;var _this67;_classCallCheck(this,fn);var n,o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.groq;_this67=_callSuper(this,fn,[e,Ft.buildKeyVerificationDetails(),Ft.buildHeaders,s]),_this67.insertKeyPlaceholderText=_this67.genereteAPIKeyName("Groq"),_this67.keyHelpUrl="https://console.groq.com/keys",_this67.url="https://api.groq.com/openai/v1/chat/completions",_this67.permittedErrorPrefixes=[ht,"property"],_this67._systemMessage="";var i=(n=t.groq)==null?void 0:n.chat;if(_typeof(i)===T){i.system_prompt&&(_this67._systemMessage=i.system_prompt);var d=(l=(a=(o=e.directConnection)==null?void 0:o.groq)==null?void 0:a.chat)==null?void 0:l.function_handler;d&&(_this67._functionHandler=d),_this67.cleanConfig(i),Object.assign(_this67.rawBody,i);}(_this67$maxMessages=_this67.maxMessages)!==null&&_this67$maxMessages!==void 0?_this67$maxMessages:_this67.maxMessages=-1,(_c$model3=(c=_this67.rawBody).model)!==null&&_c$model3!==void 0?_c$model3:c.model="llama-3.3-70b-versatile";return _this67;}_inherits(fn,_k23);return _createClass(fn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:fn.getTextWImagesContent(n),role:n.role==="ai"?"assistant":n.role};});return this._systemMessage&&i.unshift({role:"system",content:this._systemMessage}),s.messages=i,s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI29=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee144(e,t){var _this$_messages7;return _regenerator().w(function(_context144){while(1)switch(_context144.n){case 0:(_this$_messages7=this._messages)!==null&&_this$_messages7!==void 0?_this$_messages7:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context144.a(2);}},_callee144,this);}));function callServiceAPI(_x270,_x271){return _callServiceAPI29.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData32=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee145(e,t){var s,i,n,o;return _regenerator().w(function(_context145){while(1)switch(_context145.n){case 0:if(!e.error){_context145.n=1;break;}throw e.error.message;case 1:return _context145.a(2,(i=(s=e.choices)==null?void 0:s[0])!=null&&i.delta?this.extractStreamResult(e.choices[0],t):(o=(n=e.choices)==null?void 0:n[0])!=null&&o.message?e.choices[0].message.tool_calls?this.handleToolsGeneric(e.choices[0].message,this._functionHandler,this._messages,t,{message:this._systemMessage}):_defineProperty({},y,e.choices[0].message.content||""):_defineProperty({},y,""));}},_callee145,this);}));function extractResultData(_x272,_x273){return _extractResultData32.apply(this,arguments);}return extractResultData;}()// https://console.groq.com/docs/tool-use
226
- },{key:"extractStreamResult",value:function(){var _extractStreamResult5=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee146(e,t){return _regenerator().w(function(_context146){while(1)switch(_context146.n){case 0:return _context146.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee146,this);}));function extractStreamResult(_x274,_x275){return _extractStreamResult5.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var ri=/*#__PURE__*/function(){function ri(){_classCallCheck(this,ri);}return _createClass(ri,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N),"accept",N);}// prettier-ignore
227
- },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){typeof e.message=="string"?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/models",method:z,handleVerificationResult:ri.handleVerificationResult};}}]);}();var oi=/*#__PURE__*/function(_k24){function oi(e){var _this68$maxMessages,_i$model4;var _this68;_classCallCheck(this,oi);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).cohere;if(_this68=_callSuper(this,oi,[e,ri.buildKeyVerificationDetails(),ri.buildHeaders,s]),_this68.insertKeyPlaceholderText=_this68.genereteAPIKeyName("Cohere"),_this68.keyHelpUrl="https://dashboard.cohere.ai/api-keys",_this68.permittedErrorPrefixes=["invalid"],_this68.url="https://api.cohere.com/v2/chat",_typeof(s)===T){var n=le.processCohere(s);_this68.canSendMessage=function(){return n;},_this68.cleanConfig(s),Object.assign(_this68.rawBody,s);}(_this68$maxMessages=_this68.maxMessages)!==null&&_this68$maxMessages!==void 0?_this68$maxMessages:_this68.maxMessages=-1,(_i$model4=(i=_this68.rawBody).model)!==null&&_i$model4!==void 0?_i$model4:i.model="command-a-03-2025";return _this68;}_inherits(oi,_k24);return _createClass(oi,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t.filter(function(n){return n.text;});return s.messages=i.map(function(n){return{role:n.role==="ai"?"assistant":"user",content:n.text};}),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI30=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee147(e,t){return _regenerator().w(function(_context147){while(1)switch(_context147.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{readable:!0});case 1:return _context147.a(2);}},_callee147,this);}));function callServiceAPI(_x276,_x277){return _callServiceAPI30.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData33=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee148(e){var t,s,i,n;return _regenerator().w(function(_context148){while(1)switch(_context148.n){case 0:if(!(typeof e.message=="string")){_context148.n=1;break;}throw e.message;case 1:if(!(this.stream&&e.text)){_context148.n=2;break;}n=oi.parseBundledEvents(e.text);return _context148.a(2,{text:oi.aggregateBundledEventsText(n)});case 2:if(!("message"in e&&(i=(s=(t=e.message)==null?void 0:t.content)==null?void 0:s[0])!=null&&i.text)){_context148.n=3;break;}return _context148.a(2,_defineProperty({},y,e.message.content[0].text));case 3:throw new Error("Invalid response format from Cohere API");case 4:return _context148.a(2);}},_callee148,this);}));function extractResultData(_x278){return _extractResultData33.apply(this,arguments);}return extractResultData;}()}],[{key:"parseBundledEvents",value:function parseBundledEvents(e){var t=e.trim().split("\n"),s=[];var _iterator2=_createForOfIteratorHelper(t),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var i=_step2.value;if(i.trim())try{var n=JSON.parse(i);s.push(n);}catch(n){console.error("Failed to parse line:",i,n);}}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}return s;}},{key:"aggregateBundledEventsText",value:function aggregateBundledEventsText(e){return e.filter(function(t){var s,i,n;return t.type==="content-delta"&&((n=(i=(s=t.delta)==null?void 0:s.message)==null?void 0:i.content)==null?void 0:n.text);}).map(function(t){var s,i,n;return(n=(i=(s=t.delta)==null?void 0:s.message)==null?void 0:i.content)==null?void 0:n.text;}).join("");}}]);}(k);var ai=/*#__PURE__*/function(){function ai(){_classCallCheck(this,ai);}return _createClass(ai,null,[{key:"buildHeaders",value:function buildHeaders(){return _defineProperty({},R,N);}// prettier-ignore
226
+ },{key:"extractStreamResult",value:function(){var _extractStreamResult5=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee146(e,t){return _regenerator().w(function(_context146){while(1)switch(_context146.n){case 0:return _context146.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee146,this);}));function extractStreamResult(_x274,_x275){return _extractStreamResult5.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var ri=/*#__PURE__*/function(){function ri(){_classCallCheck(this,ri);}return _createClass(ri,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N),"accept",N);}// prettier-ignore
227
+ },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){typeof e.message=="string"?i(b.INVALID_KEY):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/models",method:z,handleVerificationResult:ri.handleVerificationResult};}}]);}();var oi=/*#__PURE__*/function(_k24){function oi(e){var _this68$maxMessages,_i$model4;var _this68;_classCallCheck(this,oi);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).cohere;if(_this68=_callSuper(this,oi,[e,ri.buildKeyVerificationDetails(),ri.buildHeaders,s]),_this68.insertKeyPlaceholderText=_this68.genereteAPIKeyName("Cohere"),_this68.keyHelpUrl="https://dashboard.cohere.ai/api-keys",_this68.permittedErrorPrefixes=["invalid"],_this68.url="https://api.cohere.com/v2/chat",_typeof(s)===T){var n=te.processCohere(s);_this68.canSendMessage=function(){return n;},_this68.cleanConfig(s),Object.assign(_this68.rawBody,s);}(_this68$maxMessages=_this68.maxMessages)!==null&&_this68$maxMessages!==void 0?_this68$maxMessages:_this68.maxMessages=-1,(_i$model4=(i=_this68.rawBody).model)!==null&&_i$model4!==void 0?_i$model4:i.model="command-a-03-2025";return _this68;}_inherits(oi,_k24);return _createClass(oi,[{key:"cleanConfig",value:function cleanConfig(e){delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=t.filter(function(n){return n.text;});return s.messages=i.map(function(n){return{role:n.role==="ai"?"assistant":"user",content:n.text};}),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI30=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee147(e,t){return _regenerator().w(function(_context147){while(1)switch(_context147.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{readable:!0});case 1:return _context147.a(2);}},_callee147,this);}));function callServiceAPI(_x276,_x277){return _callServiceAPI30.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData33=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee148(e){var t,s,i,n;return _regenerator().w(function(_context148){while(1)switch(_context148.n){case 0:if(!(typeof e.message=="string")){_context148.n=1;break;}throw e.message;case 1:if(!(this.stream&&e.text)){_context148.n=2;break;}n=oi.parseBundledEvents(e.text);return _context148.a(2,{text:oi.aggregateBundledEventsText(n)});case 2:if(!("message"in e&&(i=(s=(t=e.message)==null?void 0:t.content)==null?void 0:s[0])!=null&&i.text)){_context148.n=3;break;}return _context148.a(2,_defineProperty({},y,e.message.content[0].text));case 3:throw new Error("Invalid response format from Cohere API");case 4:return _context148.a(2);}},_callee148,this);}));function extractResultData(_x278){return _extractResultData33.apply(this,arguments);}return extractResultData;}()}],[{key:"parseBundledEvents",value:function parseBundledEvents(e){var t=e.trim().split("\n"),s=[];var _iterator2=_createForOfIteratorHelper(t),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var i=_step2.value;if(i.trim())try{var n=JSON.parse(i);s.push(n);}catch(n){console.error("Failed to parse line:",i,n);}}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}return s;}},{key:"aggregateBundledEventsText",value:function aggregateBundledEventsText(e){return e.filter(function(t){var s,i,n;return t.type==="content-delta"&&((n=(i=(s=t.delta)==null?void 0:s.message)==null?void 0:i.content)==null?void 0:n.text);}).map(function(t){var s,i,n;return(n=(i=(s=t.delta)==null?void 0:s.message)==null?void 0:i.content)==null?void 0:n.text;}).join("");}}]);}(k);var ai=/*#__PURE__*/function(){function ai(){_classCallCheck(this,ai);}return _createClass(ai,null,[{key:"buildHeaders",value:function buildHeaders(){return _defineProperty({},R,N);}// prettier-ignore
228
228
  },{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var o;var n=e;n.error?n.error.code===403||(o=n.error.message)!=null&&o.includes("API key")?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}// https://ai.google.dev/api/models#method:-models.list
229
229
  },{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){var e="https://generativelanguage.googleapis.com/v1beta/models?key=";return{url:e,augmentUrl:function augmentUrl(t){return"".concat(e).concat(t);},method:z,handleVerificationResult:ai.handleVerificationResult};}}]);}();var pn=/*#__PURE__*/function(_k25){function pn(e){var _this69$maxMessages;var _this69;_classCallCheck(this,pn);var i;var s=JSON.parse(JSON.stringify(e.directConnection)).gemini;if(_this69=_callSuper(this,pn,[e,ai.buildKeyVerificationDetails(),ai.buildHeaders,s]),_this69.insertKeyPlaceholderText=_this69.genereteAPIKeyName("Gemini"),_this69.keyHelpUrl="https://aistudio.google.com/app/apikey",_this69.urlPrefix="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent",_this69.url="",_this69.permittedErrorPrefixes=["API_KEY_INVALID"],_typeof(s)===T){s.system_prompt&&(_this69._systemPrompt=s.system_prompt);var _ref119=(i=e.directConnection)==null?void 0:i.gemini,n=_ref119.function_handler;n&&(_this69._functionHandler=n),s.model&&(_this69.urlPrefix="https://generativelanguage.googleapis.com/v1beta/models/".concat(s.model,":generateContent")),_this69.cleanConfig(s);}Object.assign(_this69.rawBody,s),(_this69$maxMessages=_this69.maxMessages)!==null&&_this69$maxMessages!==void 0?_this69$maxMessages:_this69.maxMessages=-1;return _this69;}_inherits(pn,_k25);return _createClass(pn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.model,delete e.key;}},{key:"preprocessBody",value:// prettier-ignore
230
230
  function preprocessBody(e,t){var n;var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-(((n=this._systemPrompt)==null?void 0:n.length)||0):-1).map(function(o){return pn.getContent(o);});return s.contents=i,this._systemPrompt&&(s.systemInstruction={parts:[_defineProperty({},y,this._systemPrompt)]}),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI31=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee149(e,t){var _this$_messages8;var s,i;return _regenerator().w(function(_context149){while(1)switch(_context149.n){case 0:if(this.connectSettings){_context149.n=1;break;}throw new Error(b.REQUEST_SETTINGS_ERROR);case 1:(_this$_messages8=this._messages)!==null&&_this$_messages8!==void 0?_this$_messages8:this._messages=e;s=this.preprocessBody(this.rawBody,t),i=this.stream;i&&(_typeof(i)!==T||!i.simulation)||s.stream?(this.url="".concat(this.urlPrefix.replace(":generateContent",":streamGenerateContent"),"?alt=sse&key=").concat(this.key),M.request(this,s,e)):(this.url="".concat(this.urlPrefix,"?key=").concat(this.key),V.request(this,s,e));case 2:return _context149.a(2);}},_callee149,this);}));function callServiceAPI(_x279,_x280){return _callServiceAPI31.apply(this,arguments);}return callServiceAPI;}()// https://ai.google.dev/gemini-api/docs/function-calling?example=weather
231
- },{key:"extractResultData",value:function(){var _extractResultData34=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee150(e,t){var s,i,n,o,a,l,c,d;return _regenerator().w(function(_context150){while(1)switch(_context150.n){case 0:if(!e.error){_context150.n=1;break;}throw e.error.message||"Gemini API Error";case 1:if(!((n=(i=(s=e.candidates)==null?void 0:s[0])==null?void 0:i.content)!=null&&n.parts)){_context150.n=3;break;}a=e.candidates[0].content.parts,l=a.find(function(u){return u.functionCall;});if(!(l!=null&&l.functionCall)){_context150.n=2;break;}return _context150.a(2,this.handleTools([l.functionCall],t));case 2:c=a.find(function(u){return u.text;}),d=a.find(function(u){var h;return((h=u.inlineData)==null?void 0:h.mimeType)==="image/png";});return _context150.a(2,_defineProperty(_defineProperty({},y,(c==null?void 0:c.text)||""),"files",(o=d==null?void 0:d.inlineData)!=null&&o.data?[{src:"data:image/png;base64,".concat(d.inlineData.data)}]:[]));case 3:return _context150.a(2,_defineProperty({},y,""));}},_callee150,this);}));function extractResultData(_x281,_x282){return _extractResultData34.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee151(e,t){var s,i,_yield$this$callToolF2,n,o,a,l;return _regenerator().w(function(_context151){while(1)switch(_context151.n){case 0:if(!(!e||!t||!this._functionHandler)){_context151.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.map(function(l){return{name:l.name,arguments:JSON.stringify(l.args)};});_context151.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF2=_context151.v;n=_yield$this$callToolF2.responses;o=_yield$this$callToolF2.processedResponse;if(!o){_context151.n=3;break;}return _context151.a(2,o);case 3:a={parts:e.map(function(l){return{functionCall:{name:l.name,args:l.args}};}),role:"model"};if(!(s.contents.push(a),!n.find(function(_ref123){var l=_ref123.response;return typeof l!="string";})&&i.length===n.length)){_context151.n=4;break;}l={parts:n.map(function(c,d){return{functionResponse:{name:e[d].name,response:{result:c.response}}};}),role:"user"};return _context151.a(2,(s.contents.push(l),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context151.a(2);}},_callee151,this);}));function handleTools(_x283,_x284){return _handleTools2.apply(this,arguments);}return handleTools;}()}],[{key:"getContent",value:function getContent(e){var t=[];return e.text&&e.text.trim().length>0&&t.push(_defineProperty({},y,e.text)),e.files&&e.files.length>0&&e.files.forEach(function(s){if(s.src&&s.src.includes("data:")){var _s$src$split=s.src.split(","),_s$src$split2=_slicedToArray(_s$src$split,2),i=_s$src$split2[0],n=_s$src$split2[1];t.push({inlineData:{mimeType:i.replace("data:","").replace(";base64",""),data:n}});}}),{parts:t,role:e.role===v.USER_ROLE?"user":"model"};}}]);}(k);var li=/*#__PURE__*/function(){function li(){_classCallCheck(this,li);}return _createClass(li,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({"x-api-key":e},R,N),"anthropic-version","2023-06-01"),"anthropic-dangerous-direct-browser-access","true");}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===se?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.anthropic.com/v1/models",method:z,handleVerificationResult:li.handleVerificationResult};}}]);}();var ci=/*#__PURE__*/function(_k26){function ci(e){var _this70$maxMessages,_o$model1,_a$max_tokens2;var _this70;_classCallCheck(this,ci);var i,n,o,a;var s=JSON.parse(JSON.stringify(e.directConnection)).claude;if(_this70=_callSuper(this,ci,[e,li.buildKeyVerificationDetails(),li.buildHeaders,s]),_this70.insertKeyPlaceholderText=_this70.genereteAPIKeyName("Claude"),_this70.keyHelpUrl="https://console.anthropic.com/settings/keys",_this70.url="https://api.anthropic.com/v1/messages",_this70.permittedErrorPrefixes=[se,we],_this70._streamToolCalls={type:"tool_use",id:"",name:"",input:""},_this70._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this70._systemMessage=s.system_prompt);var l=(n=(i=e.directConnection)==null?void 0:i.claude)==null?void 0:n.function_handler;l&&(_this70._functionHandler=l),_this70.cleanConfig(s),Object.assign(_this70.rawBody,s);}(_this70$maxMessages=_this70.maxMessages)!==null&&_this70$maxMessages!==void 0?_this70$maxMessages:_this70.maxMessages=-1,(_o$model1=(o=_this70.rawBody).model)!==null&&_o$model1!==void 0?_o$model1:o.model="claude-3-5-sonnet-20241022",(_a$max_tokens2=(a=_this70.rawBody).max_tokens)!==null&&_a$max_tokens2!==void 0?_a$max_tokens2:a.max_tokens=4096;return _this70;}_inherits(ci,_k26);return _createClass(ci,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:ci.getTextWFilesContent(n,ci.getFileContent),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=i,this._systemMessage&&(s.system=this._systemMessage),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI32=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee152(e,t){var _this$_messages9;return _regenerator().w(function(_context152){while(1)switch(_context152.n){case 0:(_this$_messages9=this._messages)!==null&&_this$_messages9!==void 0?_this$_messages9:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context152.a(2);}},_callee152,this);}));function callServiceAPI(_x285,_x286){return _callServiceAPI32.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData35=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee153(e,t){var s,i,n,o,a;return _regenerator().w(function(_context153){while(1)switch(_context153.n){case 0:if(!e.error){_context153.n=1;break;}throw e.error.message;case 1:if(!(e.content&&e.content.length>0)){_context153.n=3;break;}o=e.content.find(function(l){return l.type==="tool_use";});if(!o){_context153.n=2;break;}return _context153.a(2,this.handleTools([o],t));case 2:a=e.content.find(function(l){return l.type==="text";});if(!a){_context153.n=3;break;}return _context153.a(2,_defineProperty({},y,a.text));case 3:if(!(e.type==="content_block_delta"&&e.delta&&e.delta.type==="text_delta")){_context153.n=4;break;}return _context153.a(2,_defineProperty({},y,e.delta.text||""));case 4:if(!(e.type==="content_block_start"&&((s=e.content_block)==null?void 0:s.type)==="tool_use")){_context153.n=5;break;}this._streamToolCalls=e.content_block,this._streamToolCalls.input="";_context153.n=7;break;case 5:if(!(e.type==="content_block_delta"&&((i=e.delta)==null?void 0:i.type)==="input_json_delta")){_context153.n=6;break;}this._streamToolCalls.input+=e.delta.partial_json||"";_context153.n=7;break;case 6:if(!(e.type==="message_delta"&&((n=e.delta)==null?void 0:n.stop_reason)==="tool_use")){_context153.n=7;break;}return _context153.a(2,(this._streamToolCalls.input=JSON.parse(this._streamToolCalls.input),this.handleTools([this._streamToolCalls],t)));case 7:return _context153.a(2,_defineProperty({},y,""));}},_callee153,this);}));function extractResultData(_x287,_x288){return _extractResultData35.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee154(e,t){var s,i,_yield$this$callToolF3,n,o,a,l;return _regenerator().w(function(_context154){while(1)switch(_context154.n){case 0:if(!(!e||!t||!this._functionHandler)){_context154.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.map(function(l){return{name:l.name,arguments:JSON.stringify(l.input)};});_context154.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF3=_context154.v;n=_yield$this$callToolF3.responses;o=_yield$this$callToolF3.processedResponse;if(!o){_context154.n=3;break;}return _context154.a(2,o);case 3:a=e.map(function(l){return{type:"tool_use",id:l.id,name:l.name,input:l.input};});if(!(s.messages.push({role:"assistant",content:a}),!n.find(function(_ref128){var l=_ref128.response;return typeof l!="string";})&&i.length===n.length)){_context154.n=4;break;}l=n.map(function(c,d){return{type:"tool_result",tool_use_id:e[d].id,content:c.response};});return _context154.a(2,(s.messages.push({role:"user",content:l}),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context154.a(2);}},_callee154,this);}));function handleTools(_x289,_x290){return _handleTools3.apply(this,arguments);}return handleTools;}()}],[{key:"getFileContent",value:function getFileContent(e){return e.map(function(t){var s,i,n;if(t.type==="image"){var o=(s=t.src)==null?void 0:s.split(",")[1];return{type:"image",source:{type:"base64",media_type:((n=(i=t.src)==null?void 0:i.match(/data:([^;]+)/))==null?void 0:n[1])||"image/jpeg",data:o||""}};}return _defineProperty({type:"text"},y,"[Unsupported file type: ".concat(t.type,"]"));});}}]);}(k);var jn=/*#__PURE__*/function(){function jn(){_classCallCheck(this,jn);}return _createClass(jn,null,[{key:"buildHeaders",value:function buildHeaders(){return{};}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"",method:z,handleVerificationResult:function handleVerificationResult(){}};}}]);}();var di=/*#__PURE__*/function(_k27){function di(e){var _this71$maxMessages,_l$model,_c$stream;var _this71;_classCallCheck(this,di);var o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=jn.buildKeyVerificationDetails(),i=jn.buildHeaders;_this71=_callSuper(this,di,[e,s,i,{key:"placeholder"}]),_this71.insertKeyPlaceholderText="",_this71.keyHelpUrl="",_this71.validateKeyProperty=!1,_this71.url="http://localhost:11434/api/chat",_this71.permittedErrorPrefixes=["Error"];var n=t.ollama;if(_typeof(n)===T){n.system&&(_this71._systemMessage=di.generateSystemMessage(n.system));var d=(a=(o=e.directConnection)==null?void 0:o.ollama)==null?void 0:a.function_handler;d&&(_this71._functionHandler=d),_this71.cleanConfig(n),Object.assign(_this71.rawBody,n);}(_this71$maxMessages=_this71.maxMessages)!==null&&_this71$maxMessages!==void 0?_this71$maxMessages:_this71.maxMessages=-1,(_l$model=(l=_this71.rawBody).model)!==null&&_l$model!==void 0?_l$model:l.model="llama3.2",(_c$stream=(c=_this71.rawBody).stream)!==null&&_c$stream!==void 0?_c$stream:c.stream=!1;return _this71;}_inherits(di,_k27);return _createClass(di,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system,delete e.function_handler;}},{key:"preprocessBody",value:function preprocessBody(e,t){var n;var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-(((n=this._systemMessage)==null?void 0:n.content.length)||0):-1).map(function(o){var a={content:o.text||"",role:o.role===v.USER_ROLE?"user":"assistant"};if(o.files&&o.files.length>0){var l=di.getImageData(o.files);l.length>0&&(a.images=l);}return a;});return s.messages=_toConsumableArray(i),this._systemMessage&&s.messages.unshift(this._systemMessage),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI33=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee155(e,t){var _this$_messages0;return _regenerator().w(function(_context155){while(1)switch(_context155.n){case 0:(_this$_messages0=this._messages)!==null&&_this$_messages0!==void 0?_this$_messages0:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{readable:!0});case 1:return _context155.a(2);}},_callee155,this);}));function callServiceAPI(_x291,_x292){return _callServiceAPI33.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData36=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee156(e,t){var s,i,n;return _regenerator().w(function(_context156){while(1)switch(_context156.n){case 0:if(!e.error){_context156.n=1;break;}throw e.error.message;case 1:if(!e.text){_context156.n=2;break;}n=JSON.parse(e.text);return _context156.a(2,(s=n.message)!=null&&s.tool_calls?this.handleTools({tool_calls:n.message.tool_calls},t):_defineProperty({},y,((i=n.message)==null?void 0:i.content)||""));case 2:return _context156.a(2,e.message?e.message.tool_calls?this.handleTools({tool_calls:e.message.tool_calls},t):_defineProperty({},y,e.message.content||""):_defineProperty({},y,""));}},_callee156,this);}));function extractResultData(_x293,_x294){return _extractResultData36.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee157(e,t){var s,i,_yield$this$callToolF4,n,o;return _regenerator().w(function(_context157){while(1)switch(_context157.n){case 0:if(!(!e.tool_calls||!t||!this._functionHandler)){_context157.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.tool_calls.map(function(a){return{name:a["function"].name,arguments:JSON.stringify(a["function"].arguments)};});_context157.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF4=_context157.v;n=_yield$this$callToolF4.responses;o=_yield$this$callToolF4.processedResponse;if(!o){_context157.n=3;break;}return _context157.a(2,o);case 3:if(!(s.messages.push({tool_calls:e.tool_calls,role:"assistant",content:""}),!n.find(function(_ref133){var a=_ref133.response;return typeof a!="string";})&&i.length===n.length)){_context157.n=4;break;}return _context157.a(2,(n.forEach(function(a,l){var d;var c=(d=e.tool_calls)==null?void 0:d[l];s==null||s.messages.push({role:"tool",tool_name:c==null?void 0:c["function"].name,content:a.response});}),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context157.a(2);}},_callee157,this);}));function handleTools(_x295,_x296){return _handleTools4.apply(this,arguments);}return handleTools;}()}],[{key:"generateSystemMessage",value:function generateSystemMessage(e){return{role:"system",content:e};}},{key:"getImageData",value:function getImageData(e){return e.filter(function(t){return t.type==="image";}).map(function(t){var i;return((i=t.src)==null?void 0:i.split(",")[1])||"";}).filter(function(t){return t.length>0;});}}]);}(k);var Ut=/*#__PURE__*/function(){function Ut(){_classCallCheck(this,Ut);}return _createClass(Ut,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty({Authorization:"".concat(te).concat(e)},R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===se||n.error.type===we?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.x.ai/v1/models",method:z,handleVerificationResult:Ut.handleVerificationResult};}}]);}();var Ei=/*#__PURE__*/function(_k28){function Ei(e){var _o$model10;var _this72;_classCallCheck(this,Ei);var n,o;var t=e.directConnection,s=t==null?void 0:t.x;_this72=_callSuper(this,Ei,[e,Ut.buildKeyVerificationDetails(),Ut.buildHeaders,s]),_this72.insertKeyPlaceholderText=_this72.genereteAPIKeyName("X"),_this72.keyHelpUrl="https://console.x.ai/team/default/api-keys",_this72.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>X Image Generation</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p>Click <a target=\"_blank\" href=\"https://docs.x.ai/docs/api-reference#image-generations\" target=\"_blank\">\n here</a> for more info.</p>",_this72.url=Ei.IMAGE_GENERATION_URL,_this72.permittedErrorPrefixes=[we,se];var i=(n=t==null?void 0:t.x)==null?void 0:n.images;_typeof(i)===T&&Object.assign(_this72.rawBody,i),(_o$model10=(o=_this72.rawBody).model)!==null&&_o$model10!==void 0?_o$model10:o.model="grok-2-image";return _this72;}_inherits(Ei,_k28);return _createClass(Ei,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=t[t.length-1].text,i=JSON.parse(JSON.stringify(e));return s&&s!==""&&(i.prompt=s),i;}},{key:"callServiceAPI",value:function(){var _callServiceAPI34=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee158(e,t){return _regenerator().w(function(_context158){while(1)switch(_context158.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context158.a(2);}},_callee158,this);}));function callServiceAPI(_x297,_x298){return _callServiceAPI34.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData37=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee159(e){return _regenerator().w(function(_context159){while(1)switch(_context159.n){case 0:if(!e.error){_context159.n=1;break;}throw e.error.message;case 1:return _context159.a(2,{files:e.data.map(function(s){return s.url?{src:s.url,type:"image"}:{src:"".concat(jt).concat(s.b64_json),type:"image"};})});}},_callee159);}));function extractResultData(_x299){return _extractResultData37.apply(this,arguments);}return extractResultData;}()}]);}(k);Ei.IMAGE_GENERATION_URL="https://api.x.ai/v1/images/generations";var Yi=Ei;var hi=/*#__PURE__*/function(){function hi(){_classCallCheck(this,hi);}return _createClass(hi,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===we?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",method:z,handleVerificationResult:hi.handleVerificationResult};}}]);}();var mn=/*#__PURE__*/function(_k29){function mn(e){var _this73$maxMessages,_o$model11;var _this73;_classCallCheck(this,mn);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).qwen;if(_this73=_callSuper(this,mn,[e,hi.buildKeyVerificationDetails(),hi.buildHeaders,s]),_this73.insertKeyPlaceholderText=_this73.genereteAPIKeyName("Qwen"),_this73.keyHelpUrl="https://www.alibabacloud.com/help/en/model-studio/get-api-key",_this73.url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",_this73.permittedErrorPrefixes=["No static","The model",ks],_this73._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this73._systemMessage=s.system_prompt);var a=(n=(i=e.directConnection)==null?void 0:i.qwen)==null?void 0:n.function_handler;a&&(_this73._functionHandler=a),_this73.cleanConfig(s),Object.assign(_this73.rawBody,s);}(_this73$maxMessages=_this73.maxMessages)!==null&&_this73$maxMessages!==void 0?_this73$maxMessages:_this73.maxMessages=-1,(_o$model11=(o=_this73.rawBody).model)!==null&&_o$model11!==void 0?_o$model11:o.model="qwen-plus";return _this73;}_inherits(mn,_k29);return _createClass(mn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:mn.getTextWImagesContent(n),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI35=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee160(e,t){var _this$_messages1;return _regenerator().w(function(_context160){while(1)switch(_context160.n){case 0:(_this$_messages1=this._messages)!==null&&_this$_messages1!==void 0?_this$_messages1:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context160.a(2);}},_callee160,this);}));function callServiceAPI(_x300,_x301){return _callServiceAPI35.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData38=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee161(e,t){var _s11;return _regenerator().w(function(_context161){while(1)switch(_context161.n){case 0:if(!e.error){_context161.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context161.n=3;break;}_s11=e.choices[0];if(!_s11.delta){_context161.n=2;break;}return _context161.a(2,this.extractStreamResult(_s11,t));case 2:if(!_s11.message){_context161.n=3;break;}return _context161.a(2,_s11.message.tool_calls?this.handleToolsGeneric({tool_calls:_s11.message.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s11.message.content||""));case 3:return _context161.a(2,_defineProperty({},y,""));}},_callee161,this);}));function extractResultData(_x302,_x303){return _extractResultData38.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult6=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee162(e,t){return _regenerator().w(function(_context162){while(1)switch(_context162.n){case 0:return _context162.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee162,this);}));function extractStreamResult(_x304,_x305){return _extractStreamResult6.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var ui=/*#__PURE__*/function(){function ui(){_classCallCheck(this,ui);}return _createClass(ui,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(te).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===se?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.moonshot.ai/v1/models",method:z,handleVerificationResult:ui.handleVerificationResult};}}]);}();var gn=/*#__PURE__*/function(_k30){function gn(e){var _this74$maxMessages,_o$model12;var _this74;_classCallCheck(this,gn);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).kimi;if(_this74=_callSuper(this,gn,[e,ui.buildKeyVerificationDetails(),ui.buildHeaders,s]),_this74.insertKeyPlaceholderText=_this74.genereteAPIKeyName("Kimi"),_this74.keyHelpUrl="https://platform.moonshot.ai/console/api-keys",_this74.url="https://api.moonshot.ai/v1/chat/completions",_this74.permittedErrorPrefixes=[ht,"Not found"],_this74._systemMessage="You are Kimi, a helpful assistant created by Moonshot AI.",_typeof(s)===T){s.system_prompt&&(_this74._systemMessage=s.system_prompt);var a=(n=(i=e.directConnection)==null?void 0:i.kimi)==null?void 0:n.function_handler;a&&(_this74._functionHandler=a),_this74.cleanConfig(s),Object.assign(_this74.rawBody,s);}(_this74$maxMessages=_this74.maxMessages)!==null&&_this74$maxMessages!==void 0?_this74$maxMessages:_this74.maxMessages=-1,(_o$model12=(o=_this74.rawBody).model)!==null&&_o$model12!==void 0?_o$model12:o.model="moonshot-v1-8k";return _this74;}_inherits(gn,_k30);return _createClass(gn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:gn.getTextWImagesContent(n),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI36=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee163(e,t){var _this$_messages10;return _regenerator().w(function(_context163){while(1)switch(_context163.n){case 0:(_this$_messages10=this._messages)!==null&&_this$_messages10!==void 0?_this$_messages10:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context163.a(2);}},_callee163,this);}));function callServiceAPI(_x306,_x307){return _callServiceAPI36.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData39=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee164(e,t){var _s12;return _regenerator().w(function(_context164){while(1)switch(_context164.n){case 0:if(!e.error){_context164.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context164.n=3;break;}_s12=e.choices[0];if(!_s12.delta){_context164.n=2;break;}return _context164.a(2,this.extractStreamResult(_s12,t));case 2:if(!_s12.message){_context164.n=3;break;}return _context164.a(2,_s12.message.tool_calls?this.handleToolsGeneric({tool_calls:_s12.message.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s12.message.content||""));case 3:return _context164.a(2,_defineProperty({},y,""));}},_callee164,this);}));function extractResultData(_x308,_x309){return _extractResultData39.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult7=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee165(e,t){return _regenerator().w(function(_context165){while(1)switch(_context165.n){case 0:return _context165.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee165,this);}));function extractStreamResult(_x310,_x311){return _extractStreamResult7.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var il=/*#__PURE__*/function(_k31){function il(e){var _this75$maxMessages,_o$model13;var _this75;_classCallCheck(this,il);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.x;_this75=_callSuper(this,il,[e,Ut.buildKeyVerificationDetails(),Ut.buildHeaders,s]),_this75.insertKeyPlaceholderText=_this75.genereteAPIKeyName("X"),_this75.keyHelpUrl="https://console.x.ai/team/default/api-keys",_this75.url="https://api.x.ai/v1/chat/completions",_this75.permittedErrorPrefixes=[we,se],_this75._systemMessage="";var i=(n=t.x)==null?void 0:n.chat;_typeof(i)===T&&(i.system_prompt&&(_this75._systemMessage=i.system_prompt),_this75.cleanConfig(i),Object.assign(_this75.rawBody,i)),(_this75$maxMessages=_this75.maxMessages)!==null&&_this75$maxMessages!==void 0?_this75$maxMessages:_this75.maxMessages=-1,(_o$model13=(o=_this75.rawBody).model)!==null&&_o$model13!==void 0?_o$model13:o.model="grok-3-latest";return _this75;}_inherits(il,_k31);return _createClass(il,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(o){return{content:o.text||"",role:o.role===v.USER_ROLE?"user":"assistant"};}),n={role:"system",content:this._systemMessage};return s.messages=[n].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI37=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee166(e,t){return _regenerator().w(function(_context166){while(1)switch(_context166.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context166.a(2);}},_callee166,this);}));function callServiceAPI(_x312,_x313){return _callServiceAPI37.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData40=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee167(e){var t,s,i,n,o;return _regenerator().w(function(_context167){while(1)switch(_context167.n){case 0:if(!e.error){_context167.n=1;break;}throw e.error.message;case 1:if(!(e.object==="chat.completion.chunk")){_context167.n=2;break;}o=(t=e.choices)==null?void 0:t[0];return _context167.a(2,(s=o==null?void 0:o.delta)!=null&&s.content?_defineProperty({},y,o.delta.content):_defineProperty({},y,""));case 2:return _context167.a(2,e.object==="chat.completion"&&(n=(i=e.choices)==null?void 0:i[0])!=null&&n.message?_defineProperty({},y,e.choices[0].message.content||""):_defineProperty({},y,""));}},_callee167);}));function extractResultData(_x314){return _extractResultData40.apply(this,arguments);}return extractResultData;}()}]);}(k);var nl=/*#__PURE__*/function(){function nl(){_classCallCheck(this,nl);}return _createClass(nl,null,[{key:"create",value:// this should only be called when no _activeService is set or is demo as otherwise we don't want to reconnect
232
- function create(e){var t=e.directConnection,s=e.connect,i=e.demo,n=e.webModel;if(n)return new Cs(e);if(t){if(t.openAI)return t.openAI.images?new Xi(e):t.openAI.speechToText?new zi(e):t.openAI.textToSpeech?new Ki(e):t.openAI.assistant?new cn(e):t.openAI.realtime?new Gi(e):new ws(e);if(t.assemblyAI)return new dn(e);if(t.cohere)return new oi(e);if(t.huggingFace)return t.huggingFace.textGeneration?new Ha(e):t.huggingFace.summarization?new qa(e):t.huggingFace.translation?new Ga(e):t.huggingFace.fillMask?new Ka(e):t.huggingFace.questionAnswer?new ja(e):t.huggingFace.audioSpeechRecognition?new Ua(e):t.huggingFace.audioClassification?new Ba(e):t.huggingFace.imageClassification?new Fa(e):new Va(e);if(t.azure){if(t.azure.openAI){if(t.azure.openAI.chat)return new hn(e);if(t.azure.openAI.assistant)return new qi(e);}if(t.azure.speechToText)return new Wi(e);if(t.azure.textToSpeech)return new $i(e);if(t.azure.summarization)return new Ji(e);if(t.azure.translation)return new Wa(e);}if(t.stabilityAI)return t.stabilityAI.imageToImage?new $s(e):t.stabilityAI.imageToImageUpscale?new zs(e):t.stabilityAI.imageToImageMasking?new Js(e):new Ws(e);if(t.mistral)return new un(e);if(t.gemini)return new pn(e);if(t.claude)return new ci(e);if(t.deepSeek)return new tl(e);if(t.miniMax)return new sl(e);if(t.openRouter)return new ps(e);if(t.kimi)return new gn(e);if(t.x)return t.x.images?new Yi(e):new il(e);if(t.qwen)return new mn(e);if(t.together)return t.together.images?new Za(e):t.together.textToSpeech?new Ja(e):new Qa(e);if(t.bigModel)return t.bigModel.images?new Xa(e):t.bigModel.textToSpeech?new za(e):new Qs(e);if(t.groq)return t.groq.textToSpeech?new Ya(e):new fn(e);if(t.perplexity)return new el(e);if(t.ollama)return new di(e);}return s&&Object.keys(s).length>0&&!i?new wt(e):new wt(e,void 0,i||!0);}}]);}();var xn=/*#__PURE__*/_createClass(function xn(){_classCallCheck(this,xn);});xn.attibutes={string:function string(e){return e;},number:function number(e){return parseFloat(e);},"boolean":function boolean(e){return e==="true";},object:function object(e){return JSON.parse(e);},array:function array(e){return JSON.parse(e);},"function":function _function(e){return new Function("return ".concat(e))();}};var Zi=xn;function A(r){return function(e,t){Object.defineProperty(e,t,{});var s=e.constructor,i=t.toLocaleLowerCase();s._attributes_[i]=Zi.attibutes[r],s._attributeToProperty_[i]=t;};}var fi=/*#__PURE__*/function(){function fi(e,t,s){_classCallCheck(this,fi);this._isDisplayed=!1,e?(this._elementRef=this.createIntroPanelWithChild(e,s),this._isDisplayed=!0):t&&(this._elementRef=this.createInternalIntroPanel(t,s),this._isDisplayed=!0);}return _createClass(fi,[{key:"createIntroPanelWithChild",value:function createIntroPanelWithChild(e,t){var s=fi.createIntroPanel(t);return e.style.display==="none"&&(e.style.display="block"),s.appendChild(e),s;}},{key:"createInternalIntroPanel",value:function createInternalIntroPanel(e,t){var s=fi.createIntroPanel(t);return s.id="internal-intro-panel",s.innerHTML=e,s;}},{key:"hide",value:function hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1);}},{key:"display",value:function display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0);}}],[{key:"createIntroPanel",value:function createIntroPanel(e){var t=document.createElement("div");return t.classList.add("intro-panel"),Object.assign(t.style,e),t;}}]);}();var rl="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n\t viewBox=\"50 30 420 450\" xml:space=\"preserve\">\n<g filter=\"brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)\">\n\t<g>\n\t\t<path d=\"M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z\"/>\n\t</g>\n</g>\n</svg>",ne=/*#__PURE__*/function(){function ne(){_classCallCheck(this,ne);}return _createClass(ne,null,[{key:"createImage",value:function createImage(e,t,s,i){var n=new Image();return n.src=e.src,i&&ee.scrollDownOnImageLoad(n.src,t,s),ee.processContent("image",n,n.src,e.name);}// WORK - image still does not scroll down when loaded
233
- },{key:"createImageMessage",value:function createImageMessage(e,t,s,i,n){var o=e.createNewMessageElement("",s),a=!i&&!e.focusMode&&n,l=ne.createImage(t,e.elementRef,o.outerContainer,a);return o.bubbleElement.appendChild(l),o.bubbleElement.classList.add(ne.IMAGE_BUBBLE_CLASS),{type:"image",elements:o};}},{key:"createAudioElement",value:function createAudioElement(e,t){var s=document.createElement("audio");return s.src=e.src,s.classList.add("audio-player"),s.controls=!0,Ye.IS_SAFARI&&(s.classList.add("audio-player-safari"),s.classList.add(t===v.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),s;}},{key:"autoPlayAudio",value:function autoPlayAudio(e){e.addEventListener("loadeddata",function(){e.play()["catch"](function(t){console.warn("Auto-play failed:",t);});});}},{key:"createNewAudioMessage",value:function createNewAudioMessage(e,t,s,i){var n=ne.createAudioElement(t,s),o=e.createMessageElementsOnOrientation("",s,i);return o.bubbleElement.appendChild(n),o.bubbleElement.classList.add(ne.AUDIO_BUBBLE_CLASS),{type:"audio",elements:o,audioElement:n};}},{key:"createAnyFile",value:function createAnyFile(e){var t=document.createElement("div");t.classList.add("any-file-message-contents");var s=document.createElement("div");s.classList.add("any-file-message-icon-container");var i=Qe.createSVGElement(rl);i.classList.add("any-file-message-icon"),s.appendChild(i);var n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=e.name||ee.DEFAULT_FILE_NAME,t.appendChild(s),t.appendChild(n),ee.processContent("any",t,e.src,n.textContent);}},{key:"createNewAnyFileMessage",value:function createNewAnyFileMessage(e,t,s,i){var n=e.createMessageElementsOnOrientation("",s,i),o=ne.createAnyFile(t);return n.bubbleElement.classList.add(ne.ANY_FILE_BUBBLE_CLASS),n.bubbleElement.appendChild(o),{type:"file",elements:n};}},{key:"createMessages",value:function createMessages(e,t,s,i){var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;return t.map(function(o,a){var l;if(o.ref&&(o=ee.removeFileRef(o)),ee.isAudioFile(o)){var c=ne.createNewAudioMessage(e,o,s,n),d=(l=e.textToSpeech)==null?void 0:l.service;return d&&(d.autoPlay&&ne.autoPlayAudio(c.audioElement),typeof d.displayAudio=="boolean"&&!d.displayAudio)?void 0:c;}return ee.isImageFile(o)?ne.createImageMessage(e,o,s,n,i&&a===0):ne.createNewAnyFileMessage(e,o,s,n);}).filter(function(o){return o!==void 0;});}// no overwrite previous message logic as it is complex to track which files are to be overwritten
234
- },{key:"addMessages",value:function addMessages(e,t,s,i,n){var o=!i&&F.isScrollbarAtBottomOfElement(e.elementRef);ne.createMessages(e,t,s,o,n).filter(function(l){return l!==void 0;}).forEach(function(_ref145,d){var l=_ref145.type,c=_ref145.elements;var u=d===0&&o;ee.addMessage(e,c,l,s,n,u);});}}]);}();ne.IMAGE_BUBBLE_CLASS="image-message",ne.AUDIO_BUBBLE_CLASS="audio-message",ne.ANY_FILE_BUBBLE_CLASS="any-file-message";var pi=ne;var Ee=/*#__PURE__*/function(){function Ee(){_classCallCheck(this,Ee);}return _createClass(Ee,null,[{key:"removeElements",value:function removeElements(e,t){if(!t)return;var s=e.findIndex(function(i){return i===t;});e.splice(s,1),t==null||t.outerContainer.remove();}},{key:"removeFilesMessages",value:function removeFilesMessages(e,t){var s;(s=t[1].files)==null||s.forEach(function(i){Ee.removeElements(e.messageElementRefs,i);}),delete t[0].files,delete t[1].files;}},{key:"removeTextHTMLMessage",value:function removeTextHTMLMessage(e,t,s){var i=t[1][s];Ee.removeElements(e.messageElementRefs,i),delete t[0][s],delete t[1][s];}},{key:"updateHTMLMessage",value:function updateHTMLMessage(e,t,s){var i,n,o;if(t[1].html)Be.overwriteElements(e,s,t[1].html);else{var a=Be.create(e,s,t[0].role),l=((n=t[1].files)==null?void 0:n[((i=t[1].files)==null?void 0:i.length)-1])||t[1].text,c=l.outerContainer.nextSibling;(o=c==null?void 0:c.parentElement)==null||o.insertBefore(a.outerContainer,c),e.messageElementRefs.splice(e.messageElementRefs.length-1,1);var d=e.messageElementRefs.findIndex(function(u){return u===l;});e.messageElementRefs.splice(d+1,0,a),t[1].html=a;}t[0].html=s;}// finds beforeElement, creates new elements, remove old and adds new ones
231
+ },{key:"extractResultData",value:function(){var _extractResultData34=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee150(e,t){var s,i,n,o,a,l,c,d;return _regenerator().w(function(_context150){while(1)switch(_context150.n){case 0:if(!e.error){_context150.n=1;break;}throw e.error.message||"Gemini API Error";case 1:if(!((n=(i=(s=e.candidates)==null?void 0:s[0])==null?void 0:i.content)!=null&&n.parts)){_context150.n=3;break;}a=e.candidates[0].content.parts,l=a.find(function(u){return u.functionCall;});if(!(l!=null&&l.functionCall)){_context150.n=2;break;}return _context150.a(2,this.handleTools([l.functionCall],t));case 2:c=a.find(function(u){return u.text;}),d=a.find(function(u){var h;return((h=u.inlineData)==null?void 0:h.mimeType)==="image/png";});return _context150.a(2,_defineProperty(_defineProperty({},y,(c==null?void 0:c.text)||""),"files",(o=d==null?void 0:d.inlineData)!=null&&o.data?[{src:"data:image/png;base64,".concat(d.inlineData.data)}]:[]));case 3:return _context150.a(2,_defineProperty({},y,""));}},_callee150,this);}));function extractResultData(_x281,_x282){return _extractResultData34.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools2=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee151(e,t){var s,i,_yield$this$callToolF2,n,o,a,l;return _regenerator().w(function(_context151){while(1)switch(_context151.n){case 0:if(!(!e||!t||!this._functionHandler)){_context151.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.map(function(l){return{name:l.name,arguments:JSON.stringify(l.args)};});_context151.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF2=_context151.v;n=_yield$this$callToolF2.responses;o=_yield$this$callToolF2.processedResponse;if(!o){_context151.n=3;break;}return _context151.a(2,o);case 3:a={parts:e.map(function(l){return{functionCall:{name:l.name,args:l.args}};}),role:"model"};if(!(s.contents.push(a),!n.find(function(_ref123){var l=_ref123.response;return typeof l!="string";})&&i.length===n.length)){_context151.n=4;break;}l={parts:n.map(function(c,d){return{functionResponse:{name:e[d].name,response:{result:c.response}}};}),role:"user"};return _context151.a(2,(s.contents.push(l),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context151.a(2);}},_callee151,this);}));function handleTools(_x283,_x284){return _handleTools2.apply(this,arguments);}return handleTools;}()}],[{key:"getContent",value:function getContent(e){var t=[];return e.text&&e.text.trim().length>0&&t.push(_defineProperty({},y,e.text)),e.files&&e.files.length>0&&e.files.forEach(function(s){if(s.src&&s.src.includes("data:")){var _s$src$split=s.src.split(","),_s$src$split2=_slicedToArray(_s$src$split,2),i=_s$src$split2[0],n=_s$src$split2[1];t.push({inlineData:{mimeType:i.replace("data:","").replace(";base64",""),data:n}});}}),{parts:t,role:e.role===v.USER_ROLE?"user":"model"};}}]);}(k);var li=/*#__PURE__*/function(){function li(){_classCallCheck(this,li);}return _createClass(li,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty(_defineProperty({"x-api-key":e},R,N),"anthropic-version","2023-06-01"),"anthropic-dangerous-direct-browser-access","true");}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===ie?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.anthropic.com/v1/models",method:z,handleVerificationResult:li.handleVerificationResult};}}]);}();var ci=/*#__PURE__*/function(_k26){function ci(e){var _this70$maxMessages,_o$model1,_a$max_tokens2;var _this70;_classCallCheck(this,ci);var i,n,o,a;var s=JSON.parse(JSON.stringify(e.directConnection)).claude;if(_this70=_callSuper(this,ci,[e,li.buildKeyVerificationDetails(),li.buildHeaders,s]),_this70.insertKeyPlaceholderText=_this70.genereteAPIKeyName("Claude"),_this70.keyHelpUrl="https://console.anthropic.com/settings/keys",_this70.url="https://api.anthropic.com/v1/messages",_this70.permittedErrorPrefixes=[ie,we],_this70._streamToolCalls={type:"tool_use",id:"",name:"",input:""},_this70._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this70._systemMessage=s.system_prompt);var l=(n=(i=e.directConnection)==null?void 0:i.claude)==null?void 0:n.function_handler;l&&(_this70._functionHandler=l),_this70.cleanConfig(s),Object.assign(_this70.rawBody,s);}(_this70$maxMessages=_this70.maxMessages)!==null&&_this70$maxMessages!==void 0?_this70$maxMessages:_this70.maxMessages=-1,(_o$model1=(o=_this70.rawBody).model)!==null&&_o$model1!==void 0?_o$model1:o.model="claude-3-5-sonnet-20241022",(_a$max_tokens2=(a=_this70.rawBody).max_tokens)!==null&&_a$max_tokens2!==void 0?_a$max_tokens2:a.max_tokens=4096;return _this70;}_inherits(ci,_k26);return _createClass(ci,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:ci.getTextWFilesContent(n,ci.getFileContent),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=i,this._systemMessage&&(s.system=this._systemMessage),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI32=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee152(e,t){var _this$_messages9;return _regenerator().w(function(_context152){while(1)switch(_context152.n){case 0:(_this$_messages9=this._messages)!==null&&_this$_messages9!==void 0?_this$_messages9:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context152.a(2);}},_callee152,this);}));function callServiceAPI(_x285,_x286){return _callServiceAPI32.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData35=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee153(e,t){var s,i,n,o,a;return _regenerator().w(function(_context153){while(1)switch(_context153.n){case 0:if(!e.error){_context153.n=1;break;}throw e.error.message;case 1:if(!(e.content&&e.content.length>0)){_context153.n=3;break;}o=e.content.find(function(l){return l.type==="tool_use";});if(!o){_context153.n=2;break;}return _context153.a(2,this.handleTools([o],t));case 2:a=e.content.find(function(l){return l.type==="text";});if(!a){_context153.n=3;break;}return _context153.a(2,_defineProperty({},y,a.text));case 3:if(!(e.type==="content_block_delta"&&e.delta&&e.delta.type==="text_delta")){_context153.n=4;break;}return _context153.a(2,_defineProperty({},y,e.delta.text||""));case 4:if(!(e.type==="content_block_start"&&((s=e.content_block)==null?void 0:s.type)==="tool_use")){_context153.n=5;break;}this._streamToolCalls=e.content_block,this._streamToolCalls.input="";_context153.n=7;break;case 5:if(!(e.type==="content_block_delta"&&((i=e.delta)==null?void 0:i.type)==="input_json_delta")){_context153.n=6;break;}this._streamToolCalls.input+=e.delta.partial_json||"";_context153.n=7;break;case 6:if(!(e.type==="message_delta"&&((n=e.delta)==null?void 0:n.stop_reason)==="tool_use")){_context153.n=7;break;}return _context153.a(2,(this._streamToolCalls.input=JSON.parse(this._streamToolCalls.input),this.handleTools([this._streamToolCalls],t)));case 7:return _context153.a(2,_defineProperty({},y,""));}},_callee153,this);}));function extractResultData(_x287,_x288){return _extractResultData35.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee154(e,t){var s,i,_yield$this$callToolF3,n,o,a,l;return _regenerator().w(function(_context154){while(1)switch(_context154.n){case 0:if(!(!e||!t||!this._functionHandler)){_context154.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.map(function(l){return{name:l.name,arguments:JSON.stringify(l.input)};});_context154.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF3=_context154.v;n=_yield$this$callToolF3.responses;o=_yield$this$callToolF3.processedResponse;if(!o){_context154.n=3;break;}return _context154.a(2,o);case 3:a=e.map(function(l){return{type:"tool_use",id:l.id,name:l.name,input:l.input};});if(!(s.messages.push({role:"assistant",content:a}),!n.find(function(_ref128){var l=_ref128.response;return typeof l!="string";})&&i.length===n.length)){_context154.n=4;break;}l=n.map(function(c,d){return{type:"tool_result",tool_use_id:e[d].id,content:c.response};});return _context154.a(2,(s.messages.push({role:"user",content:l}),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context154.a(2);}},_callee154,this);}));function handleTools(_x289,_x290){return _handleTools3.apply(this,arguments);}return handleTools;}()}],[{key:"getFileContent",value:function getFileContent(e){return e.map(function(t){var s,i,n;if(t.type==="image"){var o=(s=t.src)==null?void 0:s.split(",")[1];return{type:"image",source:{type:"base64",media_type:((n=(i=t.src)==null?void 0:i.match(/data:([^;]+)/))==null?void 0:n[1])||"image/jpeg",data:o||""}};}return _defineProperty({type:"text"},y,"[Unsupported file type: ".concat(t.type,"]"));});}}]);}(k);var jn=/*#__PURE__*/function(){function jn(){_classCallCheck(this,jn);}return _createClass(jn,null,[{key:"buildHeaders",value:function buildHeaders(){return{};}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"",method:z,handleVerificationResult:function handleVerificationResult(){}};}}]);}();var di=/*#__PURE__*/function(_k27){function di(e){var _this71$maxMessages,_l$model,_c$stream;var _this71;_classCallCheck(this,di);var o,a,l,c;var t=JSON.parse(JSON.stringify(e.directConnection)),s=jn.buildKeyVerificationDetails(),i=jn.buildHeaders;_this71=_callSuper(this,di,[e,s,i,{key:"placeholder"}]),_this71.insertKeyPlaceholderText="",_this71.keyHelpUrl="",_this71.validateKeyProperty=!1,_this71.url="http://localhost:11434/api/chat",_this71.permittedErrorPrefixes=["Error"];var n=t.ollama;if(_typeof(n)===T){n.system&&(_this71._systemMessage=di.generateSystemMessage(n.system));var d=(a=(o=e.directConnection)==null?void 0:o.ollama)==null?void 0:a.function_handler;d&&(_this71._functionHandler=d),_this71.cleanConfig(n),Object.assign(_this71.rawBody,n);}(_this71$maxMessages=_this71.maxMessages)!==null&&_this71$maxMessages!==void 0?_this71$maxMessages:_this71.maxMessages=-1,(_l$model=(l=_this71.rawBody).model)!==null&&_l$model!==void 0?_l$model:l.model="llama3.2",(_c$stream=(c=_this71.rawBody).stream)!==null&&_c$stream!==void 0?_c$stream:c.stream=!1;return _this71;}_inherits(di,_k27);return _createClass(di,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system,delete e.function_handler;}},{key:"preprocessBody",value:function preprocessBody(e,t){var n;var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-(((n=this._systemMessage)==null?void 0:n.content.length)||0):-1).map(function(o){var a={content:o.text||"",role:o.role===v.USER_ROLE?"user":"assistant"};if(o.files&&o.files.length>0){var l=di.getImageData(o.files);l.length>0&&(a.images=l);}return a;});return s.messages=_toConsumableArray(i),this._systemMessage&&s.messages.unshift(this._systemMessage),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI33=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee155(e,t){var _this$_messages0;return _regenerator().w(function(_context155){while(1)switch(_context155.n){case 0:(_this$_messages0=this._messages)!==null&&_this$_messages0!==void 0?_this$_messages0:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{readable:!0});case 1:return _context155.a(2);}},_callee155,this);}));function callServiceAPI(_x291,_x292){return _callServiceAPI33.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData36=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee156(e,t){var s,i,n;return _regenerator().w(function(_context156){while(1)switch(_context156.n){case 0:if(!e.error){_context156.n=1;break;}throw e.error.message;case 1:if(!e.text){_context156.n=2;break;}n=JSON.parse(e.text);return _context156.a(2,(s=n.message)!=null&&s.tool_calls?this.handleTools({tool_calls:n.message.tool_calls},t):_defineProperty({},y,((i=n.message)==null?void 0:i.content)||""));case 2:return _context156.a(2,e.message?e.message.tool_calls?this.handleTools({tool_calls:e.message.tool_calls},t):_defineProperty({},y,e.message.content||""):_defineProperty({},y,""));}},_callee156,this);}));function extractResultData(_x293,_x294){return _extractResultData36.apply(this,arguments);}return extractResultData;}()},{key:"handleTools",value:function(){var _handleTools4=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee157(e,t){var s,i,_yield$this$callToolF4,n,o;return _regenerator().w(function(_context157){while(1)switch(_context157.n){case 0:if(!(!e.tool_calls||!t||!this._functionHandler)){_context157.n=1;break;}throw Error(b.DEFINE_FUNCTION_HANDLER);case 1:s=JSON.parse(JSON.stringify(t));i=e.tool_calls.map(function(a){return{name:a["function"].name,arguments:JSON.stringify(a["function"].arguments)};});_context157.n=2;return this.callToolFunction(this._functionHandler,i);case 2:_yield$this$callToolF4=_context157.v;n=_yield$this$callToolF4.responses;o=_yield$this$callToolF4.processedResponse;if(!o){_context157.n=3;break;}return _context157.a(2,o);case 3:if(!(s.messages.push({tool_calls:e.tool_calls,role:"assistant",content:""}),!n.find(function(_ref133){var a=_ref133.response;return typeof a!="string";})&&i.length===n.length)){_context157.n=4;break;}return _context157.a(2,(n.forEach(function(a,l){var d;var c=(d=e.tool_calls)==null?void 0:d[l];s==null||s.messages.push({role:"tool",tool_name:c==null?void 0:c["function"].name,content:a.response});}),this.makeAnotherRequest(s,this._messages)));case 4:throw Error("Function tool response must be an array or contain a text property");case 5:return _context157.a(2);}},_callee157,this);}));function handleTools(_x295,_x296){return _handleTools4.apply(this,arguments);}return handleTools;}()}],[{key:"generateSystemMessage",value:function generateSystemMessage(e){return{role:"system",content:e};}},{key:"getImageData",value:function getImageData(e){return e.filter(function(t){return t.type==="image";}).map(function(t){var i;return((i=t.src)==null?void 0:i.split(",")[1])||"";}).filter(function(t){return t.length>0;});}}]);}(k);var Ut=/*#__PURE__*/function(){function Ut(){_classCallCheck(this,Ut);}return _createClass(Ut,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty({Authorization:"".concat(se).concat(e)},R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===ie||n.error.type===we?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.x.ai/v1/models",method:z,handleVerificationResult:Ut.handleVerificationResult};}}]);}();var Ei=/*#__PURE__*/function(_k28){function Ei(e){var _o$model10;var _this72;_classCallCheck(this,Ei);var n,o;var t=e.directConnection,s=t==null?void 0:t.x;_this72=_callSuper(this,Ei,[e,Ut.buildKeyVerificationDetails(),Ut.buildHeaders,s]),_this72.insertKeyPlaceholderText=_this72.genereteAPIKeyName("X"),_this72.keyHelpUrl="https://console.x.ai/team/default/api-keys",_this72.introPanelMarkUp="\n <div style=\"width: 100%; text-align: center; margin-left: -10px\"><b>X Image Generation</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p>Click <a target=\"_blank\" href=\"https://docs.x.ai/docs/api-reference#image-generations\" target=\"_blank\">\n here</a> for more info.</p>",_this72.url=Ei.IMAGE_GENERATION_URL,_this72.permittedErrorPrefixes=[we,ie];var i=(n=t==null?void 0:t.x)==null?void 0:n.images;_typeof(i)===T&&Object.assign(_this72.rawBody,i),(_o$model10=(o=_this72.rawBody).model)!==null&&_o$model10!==void 0?_o$model10:o.model="grok-2-image";return _this72;}_inherits(Ei,_k28);return _createClass(Ei,[{key:"preprocessBody",value:function preprocessBody(e,t){var s=t[t.length-1].text,i=JSON.parse(JSON.stringify(e));return s&&s!==""&&(i.prompt=s),i;}},{key:"callServiceAPI",value:function(){var _callServiceAPI34=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee158(e,t){return _regenerator().w(function(_context158){while(1)switch(_context158.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this));case 1:return _context158.a(2);}},_callee158,this);}));function callServiceAPI(_x297,_x298){return _callServiceAPI34.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData37=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee159(e){return _regenerator().w(function(_context159){while(1)switch(_context159.n){case 0:if(!e.error){_context159.n=1;break;}throw e.error.message;case 1:return _context159.a(2,{files:e.data.map(function(s){return s.url?{src:s.url,type:"image"}:{src:"".concat(jt).concat(s.b64_json),type:"image"};})});}},_callee159);}));function extractResultData(_x299){return _extractResultData37.apply(this,arguments);}return extractResultData;}()}]);}(k);Ei.IMAGE_GENERATION_URL="https://api.x.ai/v1/images/generations";var Yi=Ei;var hi=/*#__PURE__*/function(){function hi(){_classCallCheck(this,hi);}return _createClass(hi,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===we?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",method:z,handleVerificationResult:hi.handleVerificationResult};}}]);}();var mn=/*#__PURE__*/function(_k29){function mn(e){var _this73$maxMessages,_o$model11;var _this73;_classCallCheck(this,mn);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).qwen;if(_this73=_callSuper(this,mn,[e,hi.buildKeyVerificationDetails(),hi.buildHeaders,s]),_this73.insertKeyPlaceholderText=_this73.genereteAPIKeyName("Qwen"),_this73.keyHelpUrl="https://www.alibabacloud.com/help/en/model-studio/get-api-key",_this73.url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",_this73.permittedErrorPrefixes=["No static","The model",ks],_this73._systemMessage="",_typeof(s)===T){s.system_prompt&&(_this73._systemMessage=s.system_prompt);var a=(n=(i=e.directConnection)==null?void 0:i.qwen)==null?void 0:n.function_handler;a&&(_this73._functionHandler=a),_this73.cleanConfig(s),Object.assign(_this73.rawBody,s);}(_this73$maxMessages=_this73.maxMessages)!==null&&_this73$maxMessages!==void 0?_this73$maxMessages:_this73.maxMessages=-1,(_o$model11=(o=_this73.rawBody).model)!==null&&_o$model11!==void 0?_o$model11:o.model="qwen-plus";return _this73;}_inherits(mn,_k29);return _createClass(mn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:mn.getTextWImagesContent(n),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI35=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee160(e,t){var _this$_messages1;return _regenerator().w(function(_context160){while(1)switch(_context160.n){case 0:(_this$_messages1=this._messages)!==null&&_this$_messages1!==void 0?_this$_messages1:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context160.a(2);}},_callee160,this);}));function callServiceAPI(_x300,_x301){return _callServiceAPI35.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData38=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee161(e,t){var _s11;return _regenerator().w(function(_context161){while(1)switch(_context161.n){case 0:if(!e.error){_context161.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context161.n=3;break;}_s11=e.choices[0];if(!_s11.delta){_context161.n=2;break;}return _context161.a(2,this.extractStreamResult(_s11,t));case 2:if(!_s11.message){_context161.n=3;break;}return _context161.a(2,_s11.message.tool_calls?this.handleToolsGeneric({tool_calls:_s11.message.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s11.message.content||""));case 3:return _context161.a(2,_defineProperty({},y,""));}},_callee161,this);}));function extractResultData(_x302,_x303){return _extractResultData38.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult6=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee162(e,t){return _regenerator().w(function(_context162){while(1)switch(_context162.n){case 0:return _context162.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee162,this);}));function extractStreamResult(_x304,_x305){return _extractStreamResult6.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var ui=/*#__PURE__*/function(){function ui(){_classCallCheck(this,ui);}return _createClass(ui,null,[{key:"buildHeaders",value:function buildHeaders(e){return _defineProperty(_defineProperty({},K,"".concat(se).concat(e)),R,N);}},{key:"handleVerificationResult",value:function handleVerificationResult(e,t,s,i){var n=e;n.error?n.error.type===ie?i(b.INVALID_KEY):i(b.CONNECTION_FAILED):s(t);}},{key:"buildKeyVerificationDetails",value:function buildKeyVerificationDetails(){return{url:"https://api.moonshot.ai/v1/models",method:z,handleVerificationResult:ui.handleVerificationResult};}}]);}();var gn=/*#__PURE__*/function(_k30){function gn(e){var _this74$maxMessages,_o$model12;var _this74;_classCallCheck(this,gn);var i,n,o;var s=JSON.parse(JSON.stringify(e.directConnection)).kimi;if(_this74=_callSuper(this,gn,[e,ui.buildKeyVerificationDetails(),ui.buildHeaders,s]),_this74.insertKeyPlaceholderText=_this74.genereteAPIKeyName("Kimi"),_this74.keyHelpUrl="https://platform.moonshot.ai/console/api-keys",_this74.url="https://api.moonshot.ai/v1/chat/completions",_this74.permittedErrorPrefixes=[ht,"Not found"],_this74._systemMessage="You are Kimi, a helpful assistant created by Moonshot AI.",_typeof(s)===T){s.system_prompt&&(_this74._systemMessage=s.system_prompt);var a=(n=(i=e.directConnection)==null?void 0:i.kimi)==null?void 0:n.function_handler;a&&(_this74._functionHandler=a),_this74.cleanConfig(s),Object.assign(_this74.rawBody,s);}(_this74$maxMessages=_this74.maxMessages)!==null&&_this74$maxMessages!==void 0?_this74$maxMessages:_this74.maxMessages=-1,(_o$model12=(o=_this74.rawBody).model)!==null&&_o$model12!==void 0?_o$model12:o.model="moonshot-v1-8k";return _this74;}_inherits(gn,_k30);return _createClass(gn,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.function_handler,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(n){return{content:gn.getTextWImagesContent(n),role:n.role===v.USER_ROLE?"user":"assistant"};});return s.messages=[{role:"system",content:this._systemMessage}].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI36=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee163(e,t){var _this$_messages10;return _regenerator().w(function(_context163){while(1)switch(_context163.n){case 0:(_this$_messages10=this._messages)!==null&&_this$_messages10!==void 0?_this$_messages10:this._messages=e,this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context163.a(2);}},_callee163,this);}));function callServiceAPI(_x306,_x307){return _callServiceAPI36.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData39=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee164(e,t){var _s12;return _regenerator().w(function(_context164){while(1)switch(_context164.n){case 0:if(!e.error){_context164.n=1;break;}throw e.error.message;case 1:if(!(e.choices&&e.choices.length>0)){_context164.n=3;break;}_s12=e.choices[0];if(!_s12.delta){_context164.n=2;break;}return _context164.a(2,this.extractStreamResult(_s12,t));case 2:if(!_s12.message){_context164.n=3;break;}return _context164.a(2,_s12.message.tool_calls?this.handleToolsGeneric({tool_calls:_s12.message.tool_calls},this._functionHandler,this._messages,t):_defineProperty({},y,_s12.message.content||""));case 3:return _context164.a(2,_defineProperty({},y,""));}},_callee164,this);}));function extractResultData(_x308,_x309){return _extractResultData39.apply(this,arguments);}return extractResultData;}()},{key:"extractStreamResult",value:function(){var _extractStreamResult7=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee165(e,t){return _regenerator().w(function(_context165){while(1)switch(_context165.n){case 0:return _context165.a(2,this.extractStreamResultWToolsGeneric(this,e,this._functionHandler,this._messages,t));}},_callee165,this);}));function extractStreamResult(_x310,_x311){return _extractStreamResult7.apply(this,arguments);}return extractStreamResult;}()}]);}(k);var il=/*#__PURE__*/function(_k31){function il(e){var _this75$maxMessages,_o$model13;var _this75;_classCallCheck(this,il);var n,o;var t=JSON.parse(JSON.stringify(e.directConnection)),s=t.x;_this75=_callSuper(this,il,[e,Ut.buildKeyVerificationDetails(),Ut.buildHeaders,s]),_this75.insertKeyPlaceholderText=_this75.genereteAPIKeyName("X"),_this75.keyHelpUrl="https://console.x.ai/team/default/api-keys",_this75.url="https://api.x.ai/v1/chat/completions",_this75.permittedErrorPrefixes=[we,ie],_this75._systemMessage="";var i=(n=t.x)==null?void 0:n.chat;_typeof(i)===T&&(i.system_prompt&&(_this75._systemMessage=i.system_prompt),_this75.cleanConfig(i),Object.assign(_this75.rawBody,i)),(_this75$maxMessages=_this75.maxMessages)!==null&&_this75$maxMessages!==void 0?_this75$maxMessages:_this75.maxMessages=-1,(_o$model13=(o=_this75.rawBody).model)!==null&&_o$model13!==void 0?_o$model13:o.model="grok-3-latest";return _this75;}_inherits(il,_k31);return _createClass(il,[{key:"cleanConfig",value:function cleanConfig(e){delete e.system_prompt,delete e.key;}},{key:"preprocessBody",value:function preprocessBody(e,t){var s=JSON.parse(JSON.stringify(e)),i=J.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.length:-1).map(function(o){return{content:o.text||"",role:o.role===v.USER_ROLE?"user":"assistant"};}),n={role:"system",content:this._systemMessage};return s.messages=[n].concat(_toConsumableArray(i)),s;}},{key:"callServiceAPI",value:function(){var _callServiceAPI37=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee166(e,t){return _regenerator().w(function(_context166){while(1)switch(_context166.n){case 0:this.callDirectServiceServiceAPI(e,t,this.preprocessBody.bind(this),{});case 1:return _context166.a(2);}},_callee166,this);}));function callServiceAPI(_x312,_x313){return _callServiceAPI37.apply(this,arguments);}return callServiceAPI;}()},{key:"extractResultData",value:function(){var _extractResultData40=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee167(e){var t,s,i,n,o;return _regenerator().w(function(_context167){while(1)switch(_context167.n){case 0:if(!e.error){_context167.n=1;break;}throw e.error.message;case 1:if(!(e.object==="chat.completion.chunk")){_context167.n=2;break;}o=(t=e.choices)==null?void 0:t[0];return _context167.a(2,(s=o==null?void 0:o.delta)!=null&&s.content?_defineProperty({},y,o.delta.content):_defineProperty({},y,""));case 2:return _context167.a(2,e.object==="chat.completion"&&(n=(i=e.choices)==null?void 0:i[0])!=null&&n.message?_defineProperty({},y,e.choices[0].message.content||""):_defineProperty({},y,""));}},_callee167);}));function extractResultData(_x314){return _extractResultData40.apply(this,arguments);}return extractResultData;}()}]);}(k);var nl=/*#__PURE__*/function(){function nl(){_classCallCheck(this,nl);}return _createClass(nl,null,[{key:"create",value:// this should only be called when no _activeService is set or is demo as otherwise we don't want to reconnect
232
+ function create(e){var t=e.directConnection,s=e.connect,i=e.demo,n=e.webModel;if(n)return new Cs(e);if(t){if(t.openAI)return t.openAI.images?new Xi(e):t.openAI.speechToText?new zi(e):t.openAI.textToSpeech?new Ki(e):t.openAI.assistant?new cn(e):t.openAI.realtime?new Gi(e):new ws(e);if(t.assemblyAI)return new dn(e);if(t.cohere)return new oi(e);if(t.huggingFace)return t.huggingFace.textGeneration?new Ha(e):t.huggingFace.summarization?new qa(e):t.huggingFace.translation?new Ga(e):t.huggingFace.fillMask?new Ka(e):t.huggingFace.questionAnswer?new ja(e):t.huggingFace.audioSpeechRecognition?new Ua(e):t.huggingFace.audioClassification?new Ba(e):t.huggingFace.imageClassification?new Fa(e):new Va(e);if(t.azure){if(t.azure.openAI){if(t.azure.openAI.chat)return new hn(e);if(t.azure.openAI.assistant)return new qi(e);}if(t.azure.speechToText)return new Wi(e);if(t.azure.textToSpeech)return new $i(e);if(t.azure.summarization)return new Ji(e);if(t.azure.translation)return new Wa(e);}if(t.stabilityAI)return t.stabilityAI.imageToImage?new $s(e):t.stabilityAI.imageToImageUpscale?new zs(e):t.stabilityAI.imageToImageMasking?new Js(e):new Ws(e);if(t.mistral)return new un(e);if(t.gemini)return new pn(e);if(t.claude)return new ci(e);if(t.deepSeek)return new tl(e);if(t.miniMax)return new sl(e);if(t.openRouter)return new ps(e);if(t.kimi)return new gn(e);if(t.x)return t.x.images?new Yi(e):new il(e);if(t.qwen)return new mn(e);if(t.together)return t.together.images?new Za(e):t.together.textToSpeech?new Ja(e):new Qa(e);if(t.bigModel)return t.bigModel.images?new Xa(e):t.bigModel.textToSpeech?new za(e):new Qs(e);if(t.groq)return t.groq.textToSpeech?new Ya(e):new fn(e);if(t.perplexity)return new el(e);if(t.ollama)return new di(e);}return s&&Object.keys(s).length>0&&!i?new wt(e):new wt(e,void 0,i||!0);}}]);}();var xn=/*#__PURE__*/_createClass(function xn(){_classCallCheck(this,xn);});xn.attibutes={string:function string(e){return e;},number:function number(e){return parseFloat(e);},"boolean":function boolean(e){return e==="true";},object:function object(e){return JSON.parse(e);},array:function array(e){return JSON.parse(e);},"function":function _function(e){return new Function("return ".concat(e))();}};var Zi=xn;function A(r){return function(e,t){Object.defineProperty(e,t,{});var s=e.constructor,i=t.toLocaleLowerCase();s._attributes_[i]=Zi.attibutes[r],s._attributeToProperty_[i]=t;};}var fi=/*#__PURE__*/function(){function fi(e,t,s){_classCallCheck(this,fi);this._isDisplayed=!1,e?(this._elementRef=this.createIntroPanelWithChild(e,s),this._isDisplayed=!0):t&&(this._elementRef=this.createInternalIntroPanel(t,s),this._isDisplayed=!0);}return _createClass(fi,[{key:"createIntroPanelWithChild",value:function createIntroPanelWithChild(e,t){var s=fi.createIntroPanel(t);return e.style.display==="none"&&(e.style.display="block"),s.appendChild(e),s;}},{key:"createInternalIntroPanel",value:function createInternalIntroPanel(e,t){var s=fi.createIntroPanel(t);return s.id="internal-intro-panel",s.innerHTML=e,s;}},{key:"hide",value:function hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1);}},{key:"display",value:function display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0);}}],[{key:"createIntroPanel",value:function createIntroPanel(e){var t=document.createElement("div");return t.classList.add("intro-panel"),Object.assign(t.style,e),t;}}]);}();var rl="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n\t viewBox=\"50 30 420 450\" xml:space=\"preserve\">\n<g filter=\"brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)\">\n\t<g>\n\t\t<path d=\"M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z\"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d=\"M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z\"/>\n\t</g>\n</g>\n</svg>",re=/*#__PURE__*/function(){function re(){_classCallCheck(this,re);}return _createClass(re,null,[{key:"createImage",value:function createImage(e,t,s,i){var n=new Image();return n.src=e.src,i&&ee.scrollDownOnImageLoad(n.src,t,s),ee.processContent("image",n,n.src,e.name);}// WORK - image still does not scroll down when loaded
233
+ },{key:"createImageMessage",value:function createImageMessage(e,t,s,i,n){var o=e.createNewMessageElement("",s),a=!i&&!e.focusMode&&n,l=re.createImage(t,e.elementRef,o.outerContainer,a);return o.bubbleElement.appendChild(l),o.bubbleElement.classList.add(re.IMAGE_BUBBLE_CLASS),{type:"image",elements:o};}},{key:"createAudioElement",value:function createAudioElement(e,t){var s=document.createElement("audio");return s.src=e.src,s.classList.add("audio-player"),s.controls=!0,Ye.IS_SAFARI&&(s.classList.add("audio-player-safari"),s.classList.add(t===v.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),s;}},{key:"autoPlayAudio",value:function autoPlayAudio(e){e.addEventListener("loadeddata",function(){e.play()["catch"](function(t){console.warn("Auto-play failed:",t);});});}},{key:"createNewAudioMessage",value:function createNewAudioMessage(e,t,s,i){var n=re.createAudioElement(t,s),o=e.createMessageElementsOnOrientation("",s,i);return o.bubbleElement.appendChild(n),o.bubbleElement.classList.add(re.AUDIO_BUBBLE_CLASS),{type:"audio",elements:o,audioElement:n};}},{key:"createAnyFile",value:function createAnyFile(e){var t=document.createElement("div");t.classList.add("any-file-message-contents");var s=document.createElement("div");s.classList.add("any-file-message-icon-container");var i=Qe.createSVGElement(rl);i.classList.add("any-file-message-icon"),s.appendChild(i);var n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=e.name||ee.DEFAULT_FILE_NAME,t.appendChild(s),t.appendChild(n),ee.processContent("any",t,e.src,n.textContent);}},{key:"createNewAnyFileMessage",value:function createNewAnyFileMessage(e,t,s,i){var n=e.createMessageElementsOnOrientation("",s,i),o=re.createAnyFile(t);return n.bubbleElement.classList.add(re.ANY_FILE_BUBBLE_CLASS),n.bubbleElement.appendChild(o),{type:"file",elements:n};}},{key:"createMessages",value:function createMessages(e,t,s,i){var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;return t.map(function(o,a){var l;if(o.ref&&(o=ee.removeFileRef(o)),ee.isAudioFile(o)){var c=re.createNewAudioMessage(e,o,s,n),d=(l=e.textToSpeech)==null?void 0:l.service;return d&&(d.autoPlay&&re.autoPlayAudio(c.audioElement),typeof d.displayAudio=="boolean"&&!d.displayAudio)?void 0:c;}return ee.isImageFile(o)?re.createImageMessage(e,o,s,n,i&&a===0):re.createNewAnyFileMessage(e,o,s,n);}).filter(function(o){return o!==void 0;});}// no overwrite previous message logic as it is complex to track which files are to be overwritten
234
+ },{key:"addMessages",value:function addMessages(e,t,s,i,n){var o=!i&&F.isScrollbarAtBottomOfElement(e.elementRef);re.createMessages(e,t,s,o,n).filter(function(l){return l!==void 0;}).forEach(function(_ref145,d){var l=_ref145.type,c=_ref145.elements;var u=d===0&&o;ee.addMessage(e,c,l,s,n,u);});}}]);}();re.IMAGE_BUBBLE_CLASS="image-message",re.AUDIO_BUBBLE_CLASS="audio-message",re.ANY_FILE_BUBBLE_CLASS="any-file-message";var pi=re;var Ee=/*#__PURE__*/function(){function Ee(){_classCallCheck(this,Ee);}return _createClass(Ee,null,[{key:"removeElements",value:function removeElements(e,t){if(!t)return;var s=e.findIndex(function(i){return i===t;});e.splice(s,1),t==null||t.outerContainer.remove();}},{key:"removeFilesMessages",value:function removeFilesMessages(e,t){var s;(s=t[1].files)==null||s.forEach(function(i){Ee.removeElements(e.messageElementRefs,i);}),delete t[0].files,delete t[1].files;}},{key:"removeTextHTMLMessage",value:function removeTextHTMLMessage(e,t,s){var i=t[1][s];Ee.removeElements(e.messageElementRefs,i),delete t[0][s],delete t[1][s];}},{key:"updateHTMLMessage",value:function updateHTMLMessage(e,t,s){var i,n,o;if(t[1].html)Be.overwriteElements(e,s,t[1].html);else{var a=Be.create(e,s,t[0].role),l=((n=t[1].files)==null?void 0:n[((i=t[1].files)==null?void 0:i.length)-1])||t[1].text,c=l.outerContainer.nextSibling;(o=c==null?void 0:c.parentElement)==null||o.insertBefore(a.outerContainer,c),e.messageElementRefs.splice(e.messageElementRefs.length-1,1);var d=e.messageElementRefs.findIndex(function(u){return u===l;});e.messageElementRefs.splice(d+1,0,a),t[1].html=a;}t[0].html=s;}// finds beforeElement, creates new elements, remove old and adds new ones
235
235
  },{key:"updateFileMessages",value:function updateFileMessages(e,t,s){var u,h;var i=t[0].role,n=pi.createMessages(e,s,i,!!t[1].text),o=t[1].html,a=((h=t[1].files)==null?void 0:h[((u=t[1].files)==null?void 0:u.length)-1])||t[1].text,l=o||a;var c=e.messageElementRefs.findIndex(function(f){return f===l;});a&&(c+=1);var d=(o==null?void 0:o.outerContainer)||(a==null?void 0:a.outerContainer.nextSibling);n.forEach(function(_ref146,p){var f=_ref146.type,m=_ref146.elements;var g;ee.setElementProps(e,m,f,i),(g=d.parentElement)==null||g.insertBefore(m.outerContainer,d),e.messageElementRefs.splice(e.messageElementRefs.length-1,1),e.messageElementRefs.splice(c+p,0,m);}),Ee.removeFilesMessages(e,t),t[1].files=n.map(function(_ref147){var f=_ref147.elements;return f;}),t[0].files=s;}},{key:"updateTextMessage",value:function updateTextMessage(e,t,s){var i,n;if(t[1].text)e.renderText(t[1].text.bubbleElement,s,t[0].role);else{var o=e.createElements(s,t[0].role),a=((i=t[1].files)==null?void 0:i[0])||t[1].html;(n=a.outerContainer.parentElement)==null||n.insertBefore(o.outerContainer,a.outerContainer);var l=e.messageElementRefs.findIndex(function(c){return c===a;});e.messageElementRefs.splice(l,0,o),t[1].text=o;}t[0].text=s;}},{key:"isElementActive",value:function isElementActive(e){var t,s;return xe.isActiveElement((t=e.text)==null?void 0:t.bubbleElement.classList)||xe.isActiveElement((s=e.html)==null?void 0:s.bubbleElement.classList);}// note that overwrite and 'deep-chat-temporary-message' are used to remove a message
236
- },{key:"update",value:function update(e,t,s){var i=e.messageToElements[s];if(i){if(Ee.isElementActive(i[1]))return console.error("Cannot update a message that is being streamed");t.text&&Ee.updateTextMessage(e,i,t.text),t.files?Ee.updateFileMessages(e,i,t.files):Ee.removeFilesMessages(e,i),t.html&&Ee.updateHTMLMessage(e,i,t.html),!t.text&&i[1].text&&Ee.removeTextHTMLMessage(e,i,"text"),!t.html&&i[1].html&&Ee.removeTextHTMLMessage(e,i,"html");var n=e.messageElementRefs,o=e.avatar,a=e.name;v.classifyRoleMessages(n),v.resetAllRoleElements(n,o,a);}else console.error("Message index not found. Please use the `getMessages` method to find the correct index");}}]);}();var ol=/*#__PURE__*/function(){function ol(){_classCallCheck(this,ol);}return _createClass(ol,null,[{key:"getText",value:function getText(e,t){var s;if(!e.directConnection&&!e.connect&&!e.webModel&&!e.demo)return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/modes#demo) property to true.";if(e.directConnection){if(!t.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";var i=(s=e.directConnection.openAI)==null?void 0:s.chat;if(_typeof(i)=="object"&&i.tools&&!i.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object.";}else if(e.connect&&!e.connect.url&&!e.connect.handler)return"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null;}}]);}();var xe=/*#__PURE__*/function(_Ae){function xe(e,t,s){var _this76;_classCallCheck(this,xe);var a,l;_this76=_callSuper(this,xe,[e]);var i=t.permittedErrorPrefixes,n=t.introPanelMarkUp,o=t.demo;_this76._errorMessageOverrides=(a=e.errorMessages)==null?void 0:a.overrides,_this76._onClearMessages=Ct.onClearMessages.bind(_this76,e),_this76._onError=Ct.onError.bind(_this76,e),_this76._isLoadingMessageAllowed=xe.getDefaultDisplayLoadingMessage(e,t),_typeof(e.displayLoadingBubble)=="object"&&e.displayLoadingBubble.toggle&&(e.displayLoadingBubble.toggle=_this76.setLoadingToggle.bind(_this76)),_this76._permittedErrorPrefixes=i,_this76.addSetupMessageIfNeeded(e,t)||_this76.populateIntroPanel(s,n,e.introPanelStyle),o&&_this76.prepareDemo(le.processDemo(o),e.loadHistory),_this76.addIntroductoryMessages(e,t),new As(e,_this76,t),_this76._displayServiceErrorMessages=(l=e.errorMessages)==null?void 0:l.displayServiceErrorMessages,e.getMessages=function(){return v.deepCloneMessagesWithReferences(_this76.messageToElements.map(function(_ref148){var _ref149=_slicedToArray(_ref148,1),c=_ref149[0];return c;}));},e.clearMessages=_this76.clearMessages.bind(_this76,t),e.refreshMessages=_this76.refreshTextMessages.bind(_this76,e.remarkable),e.scrollToBottom=F.scrollToBottom.bind(_this76,_this76.elementRef),e.addMessage=function(c,d){_this76.addAnyMessage(_objectSpread(_objectSpread({},c),{},{sendUpdate:!!d}),!d);},e.updateMessage=function(c,d){return Ee.update(_this76,c,d);},t.isWebModel()&&t.setUpMessages(_this76),e.textToSpeech&&Bt.processConfig(e.textToSpeech,function(c){_this76.textToSpeech=c;});return _this76;}// WORK - document how to display loading with toggle after user message via onMessage
236
+ },{key:"update",value:function update(e,t,s){var i=e.messageToElements[s];if(i){if(Ee.isElementActive(i[1]))return console.error("Cannot update a message that is being streamed");t.text&&Ee.updateTextMessage(e,i,t.text),t.files?Ee.updateFileMessages(e,i,t.files):Ee.removeFilesMessages(e,i),t.html&&Ee.updateHTMLMessage(e,i,t.html),!t.text&&i[1].text&&Ee.removeTextHTMLMessage(e,i,"text"),!t.html&&i[1].html&&Ee.removeTextHTMLMessage(e,i,"html");var n=e.messageElementRefs,o=e.avatar,a=e.name;v.classifyRoleMessages(n),v.resetAllRoleElements(n,o,a);}else console.error("Message index not found. Please use the `getMessages` method to find the correct index");}}]);}();var ol=/*#__PURE__*/function(){function ol(){_classCallCheck(this,ol);}return _createClass(ol,null,[{key:"getText",value:function getText(e,t){var s;if(!e.directConnection&&!e.connect&&!e.webModel&&!e.demo)return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/modes#demo) property to true.";if(e.directConnection){if(!t.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";var i=(s=e.directConnection.openAI)==null?void 0:s.chat;if(_typeof(i)=="object"&&i.tools&&!i.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object.";}else if(e.connect&&!e.connect.url&&!e.connect.handler)return"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null;}}]);}();var xe=/*#__PURE__*/function(_Ae){function xe(e,t,s){var _this76;_classCallCheck(this,xe);var a,l;_this76=_callSuper(this,xe,[e]);var i=t.permittedErrorPrefixes,n=t.introPanelMarkUp,o=t.demo;_this76._errorMessageOverrides=(a=e.errorMessages)==null?void 0:a.overrides,_this76._onClearMessages=Ct.onClearMessages.bind(_this76,e),_this76._onError=Ct.onError.bind(_this76,e),_this76._isLoadingMessageAllowed=xe.getDefaultDisplayLoadingMessage(e,t),_typeof(e.displayLoadingBubble)=="object"&&e.displayLoadingBubble.toggle&&(e.displayLoadingBubble.toggle=_this76.setLoadingToggle.bind(_this76)),_this76._permittedErrorPrefixes=i,_this76.addSetupMessageIfNeeded(e,t)||_this76.populateIntroPanel(s,n,e.introPanelStyle),o&&_this76.prepareDemo(te.processDemo(o),e.loadHistory),_this76.addIntroductoryMessages(e,t),new As(e,_this76,t),_this76._displayServiceErrorMessages=(l=e.errorMessages)==null?void 0:l.displayServiceErrorMessages,e.getMessages=function(){return v.deepCloneMessagesWithReferences(_this76.messageToElements.map(function(_ref148){var _ref149=_slicedToArray(_ref148,1),c=_ref149[0];return c;}));},e.clearMessages=_this76.clearMessages.bind(_this76,t),e.refreshMessages=_this76.refreshTextMessages.bind(_this76,e.remarkable),e.scrollToBottom=F.scrollToBottom.bind(_this76,_this76.elementRef),e.addMessage=function(c,d){_this76.addAnyMessage(_objectSpread(_objectSpread({},c),{},{sendUpdate:!!d}),!d);},e.updateMessage=function(c,d){return Ee.update(_this76,c,d);},t.isWebModel()&&t.setUpMessages(_this76),e.textToSpeech&&Bt.processConfig(e.textToSpeech,function(c){_this76.textToSpeech=c;});return _this76;}// WORK - document how to display loading with toggle after user message via onMessage
237
237
  _inherits(xe,_Ae);return _createClass(xe,[{key:"setLoadingToggle",value:function setLoadingToggle(e){var t=this.messageElementRefs[this.messageElementRefs.length-1];!e&&Ae.isLoadingMessage(t)?(this.removeLastMessage(),delete this._activeLoadingConfig):(this._activeLoadingConfig&&this.removeLastMessage(),this._activeLoadingConfig=e||{},this.addLoadingMessage(!0));}},{key:"prepareDemo",value:function prepareDemo(e,t){var s;if(_typeof(e)=="object"){if(!t&&e.displayLoading){var i=e.displayLoading.history;i!=null&&i.small&&Ze.addMessage(this,!1),i!=null&&i.full&&Ze.addMessage(this);}e.displayErrors&&(e.displayErrors["default"]&&this.addNewErrorMessage("",""),e.displayErrors.service&&this.addNewErrorMessage(B,""),e.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),(s=e.displayLoading)!=null&&s.message&&this.addLoadingMessage(),e.response&&(this.customDemoResponse=e.response);}}},{key:"addSetupMessageIfNeeded",value:function addSetupMessageIfNeeded(e,t){var s=ol.getText(e,t);if(s){var i=this.createAndAppendNewMessageElement(s,v.AI_ROLE);this.applyCustomStyles(i,v.AI_ROLE,!1);}return!!s;}// WORK - const file for deep chat classes
238
- },{key:"addIntroductoryMessages",value:function addIntroductoryMessages(e,t){var _this77=this;e!=null&&e.shadowRoot&&(this._introMessage=e.introMessage);var s=this._introMessage;t!=null&&t.isWebModel()&&(s!==null&&s!==void 0?s:s=t.getIntroMessage(s));var i=!(e!=null&&e.history)&&!!(e!=null&&e.loadHistory||t!=null&&t.fetchHistory);s&&(Array.isArray(s)?s.forEach(function(n,o){if(o!==0){var a=_this77.messageElementRefs[_this77.messageElementRefs.length-1].innerContainer;v.hideRoleElements(a,_this77.avatar,_this77.name);}_this77.addIntroductoryMessage(n,i);}):this.addIntroductoryMessage(s,i));}},{key:"addIntroductoryMessage",value:function addIntroductoryMessage(e,t){var i;var s;return e!=null&&e.text?s=this.createAndAppendNewMessageElement(e.text,v.AI_ROLE):e!=null&&e.html&&(s=Be.add(this,e.html,v.AI_ROLE,!1)),s&&(this.applyCustomStyles(s,v.AI_ROLE,!1,(i=this.messageStyles)==null?void 0:i.intro),s.outerContainer.classList.add(Ae.INTRO_CLASS),t&&(s.outerContainer.style.display="none")),s;}},{key:"removeIntroductoryMessage",value:function removeIntroductoryMessage(){var e=this.messageElementRefs[0];e.outerContainer.classList.contains(Ae.INTRO_CLASS)&&(e.outerContainer.remove(),this.messageElementRefs.shift());}},{key:"addAnyMessage",value:function addAnyMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;return e.error?this.addNewErrorMessage(B,e.error,s):this.addNewMessage(e,t,s);}},{key:"tryAddTextMessage",value:function tryAddTextMessage(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;e.text!==void 0&&s.text!==null&&(this.addNewTextMessage(e.text,e.role,t,n),!i&&this.textToSpeech&&e.role!==v.USER_ROLE&&Bt.speak(e.text,this.textToSpeech));}},{key:"tryAddFileMessages",value:function tryAddFileMessages(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;e.files&&Array.isArray(e.files)&&pi.addMessages(this,e.files,e.role,!!e.text,t);}},{key:"tryAddHTMLMessage",value:function tryAddHTMLMessage(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;if(e.html!==void 0&&e.html!==null){var i=!e.text&&(!e.files||e.files.length===0),n=Be.add(this,e.html,e.role,i,t,s);!s&&De.isElementTemporary(n)&&delete e.html;}}// this should not be activated by streamed messages
238
+ },{key:"addIntroductoryMessages",value:function addIntroductoryMessages(e,t){var _this77=this;e!=null&&e.shadowRoot&&(this._introMessage=e.introMessage);var s=this._introMessage;t!=null&&t.isWebModel()&&(s!==null&&s!==void 0?s:s=t.getIntroMessage(s));var i=!(e!=null&&e.history)&&!!(e!=null&&e.loadHistory||t!=null&&t.fetchHistory);s&&(Array.isArray(s)?s.forEach(function(n,o){if(o!==0){var a=_this77.messageElementRefs[_this77.messageElementRefs.length-1].innerContainer;v.hideRoleElements(a,_this77.avatar,_this77.name);}_this77.addIntroductoryMessage(n,i);}):this.addIntroductoryMessage(s,i));}},{key:"addIntroductoryMessage",value:function addIntroductoryMessage(e,t){var i;var s;return e!=null&&e.text?s=this.createAndAppendNewMessageElement(e.text,v.AI_ROLE):e!=null&&e.html&&(s=Be.add(this,e.html,v.AI_ROLE,!1)),s&&(this.applyCustomStyles(s,v.AI_ROLE,!1,(i=this.messageStyles)==null?void 0:i.intro),s.outerContainer.classList.add(Ae.INTRO_CLASS),t&&(s.outerContainer.style.display="none")),s;}},{key:"removeIntroductoryMessage",value:function removeIntroductoryMessage(){var e=this.messageElementRefs[0];e.outerContainer.classList.contains(Ae.INTRO_CLASS)&&(e.outerContainer.remove(),this.messageElementRefs.shift());}},{key:"addAnyMessage",value:function addAnyMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;return e.error?this.addNewErrorMessage(B,e.error,s):this.addNewMessage(e,t,s);}},{key:"tryAddTextMessage",value:function tryAddTextMessage(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var n=arguments.length>4&&arguments[4]!==undefined?arguments[4]:!1;!s.ignoreText&&e.text!==void 0&&s.text!==null&&(this.addNewTextMessage(e.text,e.role,t,n),!i&&this.textToSpeech&&e.role!==v.USER_ROLE&&Bt.speak(e.text,this.textToSpeech));}},{key:"tryAddFileMessages",value:function tryAddFileMessages(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;e.files&&Array.isArray(e.files)&&pi.addMessages(this,e.files,e.role,!!e.text,t);}},{key:"tryAddHTMLMessage",value:function tryAddHTMLMessage(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;if(e.html!==void 0&&e.html!==null){var i=!e.text&&(!e.files||e.files.length===0),n=Be.add(this,e.html,e.role,i,t,s);!s&&De.isElementTemporary(n)&&delete e.html;}}// this should not be activated by streamed messages
239
239
  },{key:"addNewMessage",value:function addNewMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:!1;var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var a,l,c,d;e.role!==v.USER_ROLE&&((a=this._hiddenAttachments)==null||a.removeHiddenFiles());var i=xe.createMessageContent(e),n=(c=(l=this.textToSpeech)==null?void 0:l.service)==null?void 0:c.displayText;typeof n=="boolean"&&!n&&delete i.text;var o={status:e.overwrite};return s?(this.tryAddHTMLMessage(i,o,s),this.tryAddFileMessages(i,s),this.tryAddTextMessage(i,o,e,t,s)):(this.tryAddTextMessage(i,o,e,t,s),this.tryAddFileMessages(i,s),this.tryAddHTMLMessage(i,o,s)),this.isValidMessageContent(i)&&!s&&(this.updateStateOnMessage(i,e.overwrite,e.sendUpdate,t),t||(d=this.browserStorage)==null||d.addMessages(this.messageToElements.map(function(_ref150){var _ref151=_slicedToArray(_ref150,1),u=_ref151[0];return u;}))),this._activeLoadingConfig&&this.addLoadingMessage(!1),i;}},{key:"isValidMessageContent",value:function isValidMessageContent(e){return e.text||e.html||e.files&&e.files.length>0;}},{key:"updateStateOnMessage",value:function updateStateOnMessage(e,t){var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!0;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;if(!t){var n=v.generateMessageBody(e,this.messageElementRefs);this.messageToElements.push([e,n]);}s&&this.sendClientUpdate(e,i);}// prettier-ignore
240
240
  },{key:"removeMessageOnError",value:function removeMessageOnError(){var e=this.messageElementRefs[this.messageElementRefs.length-1],t=e==null?void 0:e.bubbleElement;(t!=null&&t.classList.contains(Ue.MESSAGE_CLASS)&&t.textContent===""||xe.isTemporaryElement(e))&&this.removeLastMessage();}// prettier-ignore
241
241
  },{key:"addNewErrorMessage",value:function addNewErrorMessage(e,t){var _this78=this;var s=arguments.length>2&&arguments[2]!==undefined?arguments[2]:!1;var c,d,u,h,f,m;(c=this._hiddenAttachments)==null||c.readdHiddenFiles(),this.removeMessageOnError();var i=this.getPermittedMessage(t)||((d=this._errorMessageOverrides)==null?void 0:d[e])||((u=this._errorMessageOverrides)==null?void 0:u["default"])||"Error, please try again.",n=this.createMessageElementsOnOrientation(i,"error",s);v.hideRoleElements(n.innerContainer,this.avatar,this.name);var o=n.bubbleElement,a=n.outerContainer;o.classList.add(v.ERROR_MESSAGE_TEXT_CLASS),this.renderText(o,i);var l=he.extractParticularSharedStyles(["fontSize","fontFamily"],(h=this.messageStyles)==null?void 0:h["default"]);he.applyCustomStylesToElements(n,!1,l),he.applyCustomStylesToElements(n,!1,(f=this.messageStyles)==null?void 0:f.error),s||this.appendOuterContainerElemet(a),this.textToSpeech&&Bt.speak(i,this.textToSpeech),(m=this._onError)==null||m.call(this,i),setTimeout(function(){return F.scrollToBottom(_this78.elementRef);});}},{key:"getPermittedMessage",value:function getPermittedMessage(e){if(e){var t=xe.extractErrorMessages(e);for(var _s13=0;_s13<t.length;_s13+=1){var i=t[_s13];if(typeof i=="string"){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){var n=xe.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(n)return n;}}}}}},{key:"removeError",value:function removeError(){this.isLastMessageError()&&v.getLastMessageElement(this.elementRef).remove();}},{key:"addDefaultLoadingMessage",value:function addDefaultLoadingMessage(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:v.AI_ROLE;var s=this.createMessageElements("",t),i=s.bubbleElement;s.bubbleElement.classList.add(Xe.DOTS_CONTAINER_CLASS);var n=document.createElement("div");return n.classList.add("loading-message-dots"),i.appendChild(n),Xe.setDots(i,e),s;}// prettier-ignore
242
- },{key:"addLoadingMessage",value:function addLoadingMessage(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:!1;var a,l,c,d,u,h;if(Ae.isLoadingMessage(this.messageElementRefs[this.messageElementRefs.length-1])||!this._activeLoadingConfig&&!e&&!this._isLoadingMessageAllowed)return;var t=((a=this._activeLoadingConfig)==null?void 0:a.role)||v.AI_ROLE,s=((l=this._activeLoadingConfig)==null?void 0:l.style)||((d=(c=this.messageStyles)==null?void 0:c.loading)==null?void 0:d.message),i=s==null?void 0:s.html,n=i?Be.createElements(this,i,t,!1):this.addDefaultLoadingMessage(s,t);this.appendOuterContainerElemet(n.outerContainer),n.bubbleElement.classList.add(Xe.BUBBLE_CLASS),this.applyCustomStyles(n,t,!1,s==null?void 0:s.styles),(h=(u=this.avatar)==null?void 0:u.getAvatarContainer(n.innerContainer))==null||h.classList.add("loading-avatar-container"),!this.focusMode&&F.isScrollbarAtBottomOfElement(this.elementRef)&&F.scrollToBottom(this.elementRef);}},{key:"populateIntroPanel",value:function populateIntroPanel(e,t,s){(e||t)&&(this._introPanel=new fi(e,t,s),this._introPanel._elementRef&&(ae.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)));}},{key:"addMultipleFiles",value:function(){var _addMultipleFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee168(e,t){return _regenerator().w(function(_context168){while(1)switch(_context168.n){case 0:return _context168.a(2,(this._hiddenAttachments=t,Promise.all((e||[]).map(function(s){return new Promise(function(i){if(!s.type||s.type==="any"){var n=s.file.name||ee.DEFAULT_FILE_NAME;i({name:n,type:"any",ref:s.file});}else{var _n5=new FileReader();_n5.readAsDataURL(s.file),_n5.onload=function(){i({src:_n5.result,type:s.type,ref:s.file});};}});}))));}},_callee168,this);}));function addMultipleFiles(_x315,_x316){return _addMultipleFiles.apply(this,arguments);}return addMultipleFiles;}()},{key:"clearMessages",value:// WORK - update all message classes to use deep-chat prefix
242
+ },{key:"addLoadingMessage",value:function addLoadingMessage(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:!1;var a,l,c,d,u,h;if(Ae.isLoadingMessage(this.messageElementRefs[this.messageElementRefs.length-1])||!this._activeLoadingConfig&&!e&&!this._isLoadingMessageAllowed)return;var t=((a=this._activeLoadingConfig)==null?void 0:a.role)||v.AI_ROLE,s=((l=this._activeLoadingConfig)==null?void 0:l.style)||((d=(c=this.messageStyles)==null?void 0:c.loading)==null?void 0:d.message),i=s==null?void 0:s.html,n=i?Be.createElements(this,i,t,!1):this.addDefaultLoadingMessage(s,t);this.appendOuterContainerElemet(n.outerContainer),n.bubbleElement.classList.add(Xe.BUBBLE_CLASS),this.applyCustomStyles(n,t,!1,s==null?void 0:s.styles),(h=(u=this.avatar)==null?void 0:u.getAvatarContainer(n.innerContainer))==null||h.classList.add("loading-avatar-container"),!this.focusMode&&F.isScrollbarAtBottomOfElement(this.elementRef)&&F.scrollToBottom(this.elementRef);}},{key:"populateIntroPanel",value:function populateIntroPanel(e,t,s){(e||t)&&(this._introPanel=new fi(e,t,s),this._introPanel._elementRef&&(le.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)));}},{key:"addMultipleFiles",value:function(){var _addMultipleFiles=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee168(e,t){return _regenerator().w(function(_context168){while(1)switch(_context168.n){case 0:return _context168.a(2,(this._hiddenAttachments=t,Promise.all((e||[]).map(function(s){return new Promise(function(i){if(!s.type||s.type==="any"){var n=s.file.name||ee.DEFAULT_FILE_NAME;i({name:n,type:"any",ref:s.file});}else{var _n5=new FileReader();_n5.readAsDataURL(s.file),_n5.onload=function(){i({src:_n5.result,type:s.type,ref:s.file});};}});}))));}},_callee168,this);}));function addMultipleFiles(_x315,_x316){return _addMultipleFiles.apply(this,arguments);}return addMultipleFiles;}()},{key:"clearMessages",value:// WORK - update all message classes to use deep-chat prefix
243
243
  function clearMessages(e,t){var _this$messageToElemen;var n,o,a;var s=[];this.messageElementRefs.forEach(function(l){xe.isActiveElement(l.bubbleElement.classList)?s.push(l):l.outerContainer.remove();}),Array.from(this.elementRef.children).forEach(function(l){var d;var c=(d=l.children[0])==null?void 0:d.children[0];c!=null&&c.classList.contains(v.ERROR_MESSAGE_TEXT_CLASS)&&l.remove();}),this.messageElementRefs=s;var i=this.messageToElements.filter(function(l){return l[1].text&&xe.isActiveElement(l[1].text.bubbleElement.classList)||l[1].html&&xe.isActiveElement(l[1].html.bubbleElement.classList);});(_this$messageToElemen=this.messageToElements).splice.apply(_this$messageToElemen,[0,this.messageToElements.length].concat(_toConsumableArray(i))),t!==!1&&((n=this._introPanel)!=null&&n._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),(o=this.browserStorage)==null||o.clear(),(a=this._onClearMessages)==null||a.call(this),delete e.sessionId;}}],[{key:"getDefaultDisplayLoadingMessage",value:function getDefaultDisplayLoadingMessage(e,t){var _ref152;return _typeof(e.displayLoadingBubble)=="object"&&e.displayLoadingBubble.toggle?!1:t.websocket?_typeof(e.displayLoadingBubble)===T?!1:!!e.displayLoadingBubble:(_ref152=_typeof(e.displayLoadingBubble)===T||e.displayLoadingBubble)!==null&&_ref152!==void 0?_ref152:!0;}},{key:"checkPermittedErrorPrefixes",value:function checkPermittedErrorPrefixes(e,t){for(var _s14=0;_s14<e.length;_s14+=1)if(t.startsWith(e[_s14]))return t;}},{key:"extractErrorMessages",value:function extractErrorMessages(e){return Array.isArray(e)?e:e instanceof Error?[e.message]:typeof e=="string"?[e]:_typeof(e)=="object"&&e.error?[e.error]:[];}},{key:"isActiveElement",value:function isActiveElement(e){return e?e.contains(Xe.BUBBLE_CLASS)||e.contains(Ze.CLASS)||e.contains(Ue.MESSAGE_CLASS):!1;}}]);}(Ae);var Q=/*#__PURE__*/function(){function Q(){_classCallCheck(this,Q);}return _createClass(Q,null,[{key:"adjustInputPadding",value:function adjustInputPadding(e,t){t["inside-left"].length>0&&e.classList.add("text-input-inner-left-adjustment"),t["inside-right"].length>0&&e.classList.add("text-input-inner-right-adjustment");}},{key:"adjustForOutsideButton",value:function adjustForOutsideButton(e,t,s){s["outside-right"].length===0&&s["outside-left"].length>0?(e[0].classList.add(Q.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),t.classList.add(Q.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):s["outside-left"].length===0&&s["outside-right"].length>0&&(e[3].classList.add(Q.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),t.classList.add(Q.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS));}// when submit is the only button
244
244
  // when submit button is outside by itself - we increase the height for a better look
245
245
  },{key:"adjustOutsideSubmit",value:function adjustOutsideSubmit(e,t,s){if(!(s["inside-left"].length>0||s["inside-right"].length>0)){if(s["outside-right"].length===0&&s["outside-left"].length>0)return e[0].classList.add(Q.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),t.classList.add(Q.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),s["outside-left"].map(function(i){return i.button.elementRef.classList.add("submit-button-enlarged");});if(s["outside-left"].length===0&&s["outside-right"].length>0)return e[3].classList.add(Q.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),t.classList.add(Q.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),s["outside-right"].map(function(i){return i.button.elementRef.classList.add("submit-button-enlarged");});}}// prettier-ignore
246
246
  },{key:"set",value:function set(e,t,s,i){!!Q.adjustOutsideSubmit(t,s,i)||Q.adjustForOutsideButton(t,s,i),Q.adjustInputPadding(e,i);}}]);}();Q.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Q.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Q.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Q.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";var Qi=Q;var Ht=/*#__PURE__*/function(){function Ht(){_classCallCheck(this,Ht);}return _createClass(Ht,null,[{key:"create",value:function create(){return Array.from({length:4}).map(function(e,t){var s=document.createElement("div");return s.classList.add("input-button-container"),(t===0||t===3)&&s.classList.add("outer-button-container"),(t===1||t===2)&&s.classList.add("inner-button-container"),s;});}},{key:"add",value:function add(e,t){e.insertBefore(t[1],e.firstChild),e.insertBefore(t[0],e.firstChild),e.appendChild(t[2]),e.appendChild(t[3]);}},{key:"getContainerIndex",value:function getContainerIndex(e){return e==="outside-left"?0:e==="inside-left"?1:e==="inside-right"?2:3;}},{key:"addButton",value:function addButton(e,t,s){t.classList.add(s);var i=Ht.getContainerIndex(s);e[i].appendChild(t),i===3&&t.classList.add("outside-right");}}]);}();var qn=["camera","gifs","images","audio","mixedFiles","submit","microphone"],al="<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 22 22\" fill=\"none\">\n <rect x=\"2.5\" y=\"2.5\" width=\"17\" height=\"17\" rx=\"2\" stroke=\"#000000\" stroke-width=\"1.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>\n",fe=/*#__PURE__*/function(){function fe(){_classCallCheck(this,fe);}return _createClass(fe,null,[{key:"addItemEvents",value:function addItemEvents(e,t,s,i){lt.add(t,i),t.addEventListener("click",function(){s.click();}),t.addEventListener("mouseenter",function(n){e.highlightedItem=n.target;}),t.addEventListener("mouseleave",function(){e.highlightedItem=void 0;});}},{key:"createItemText",value:function createItemText(e,t){var s=document.createElement("div");return Object.assign(s.style,t),s.classList.add(fe.TEXT_CLASS),s.textContent=e||"File",s;}},{key:"createItemIcon",value:function createItemIcon(e,t){var s=document.createElement("div");return Object.assign(s.style,t),s.classList.add(fe.ICON_CLASS),s.appendChild(e),s;}},{key:"populateItem",value:function populateItem(e,t,s){var i=e.elementRef,n=e.dropupText,o=e.svg,a=e.customStyles,l=i.children[0],c=a&&Object.values(a).find(function(d){var u;return((u=d.svg)==null?void 0:u.content)==="";});l.classList.contains(He.INPUT_BUTTON_INNER_TEXT_CLASS)?(c||t.appendChild(fe.createItemIcon(o,s==null?void 0:s.iconContainer)),t.appendChild(fe.createItemText(l.textContent,s==null?void 0:s.text))):(c||t.appendChild(fe.createItemIcon(i.children[0],s==null?void 0:s.iconContainer)),t.appendChild(fe.createItemText(n,s==null?void 0:s.text)));}},{key:"createItem",value:function createItem(e,t,s){var o;var i=document.createElement("div");Object.assign(i.style,(o=s==null?void 0:s.item)==null?void 0:o["default"]),fe.populateItem(t,i,s),i.classList.add(fe.MENU_ITEM_CLASS);var n=t.elementRef;if(t.isCustom)t.setDropupItem(i);else{var a=U.processStateful((s==null?void 0:s.item)||{});fe.addItemEvents(e,i,n,a);}return i;}}]);}();fe.MENU_ITEM_CLASS="dropup-menu-item",fe.TEXT_CLASS="dropup-menu-item-text",fe.ICON_CLASS="dropup-menu-item-icon";var Pe=fe;var H=/*#__PURE__*/function(_It2){// prettier-ignore
247
- function H(e,t,s,i){var _this79;_classCallCheck(this,H);var l,c,d,u,h,f;var n=((u=(d=(c=(l=e==null?void 0:e.styles)==null?void 0:l.button)==null?void 0:c["default"])==null?void 0:d.text)==null?void 0:u.content)||"Custom ".concat(t),o=al,a=Le.tryCreateConfig("Custom ".concat(t),e==null?void 0:e.tooltip);_this79=_callSuper(this,H,[H.createButtonElement(),o,e==null?void 0:e.position,a,((h=e==null?void 0:e.styles)==null?void 0:h.button)||a&&{},n]),_this79._state="default",_this79.isCustom=!0,_this79._innerElements=_this79.createInnerElementsForStates(_this79.customStyles),_this79._menuStyles=i,_this79._onClick=e.onClick,_this79._dropupStyles=(f=e.styles)==null?void 0:f.dropup,_this79.setSetState(e),_this79.addClickListener(s),_this79.changeState(e.initialState,!0);return _this79;}_inherits(H,_It2);return _createClass(H,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(e){var t="custom-icon",s=this.createInnerElements(t,"default",e);return{"default":s,active:this.genStateInnerElements(t,"active",s,e),disabled:this.genStateInnerElements(t,"disabled",s,e)};}},{key:"setSetState",value:function setSetState(e){var _this80=this;e.setState=function(t){t==="default"&&_this80.changeToDefault(),t==="active"&&_this80.changeToActive(),t==="disabled"&&_this80.changeToDisabled();};}},{key:"addClickListener",value:function addClickListener(e){var _this81=this;this.elementRef.addEventListener("click",function(){var s;var t=(s=_this81._onClick)==null?void 0:s.call(_this81,_this81._state);e==null||e(),(t==="default"||t==="active"||t==="disabled")&&_this81.changeState(t);});}},{key:"changeState",value:function changeState(e,t){e==="disabled"?this.changeToDisabled(t):e==="active"?this.changeToActive(t):this.changeToDefault(t);}},{key:"applyDropupContentStyles",value:function applyDropupContentStyles(e){var t=Array.from(this.elementRef.children);if(e!=null&&e.text){var _s15=t.find(function(i){return i.classList.contains(Pe.TEXT_CLASS);});_s15&&Object.assign(_s15.style,e.text);}if(e!=null&&e.iconContainer){var _s16=t.find(function(i){return i.classList.contains(Pe.ICON_CLASS);});_s16&&Object.assign(_s16.style,e.iconContainer);}}},{key:"resetDropupItem",value:function resetDropupItem(e){var s,i,n;this.elementRef=ae.replaceElementWithNewClone(this.elementRef,this._originalElementRef),this.elementRef.innerHTML="",((s=e==null?void 0:e.svg)==null?void 0:s.content)===""||this.elementRef.appendChild(Pe.createItemIcon(this.svg,(i=this._menuStyles)==null?void 0:i.iconContainer)),this.elementRef.appendChild(Pe.createItemText(this.dropupText,(n=this._menuStyles)==null?void 0:n.text));}},{key:"assignDropupItemStyle",value:function assignDropupItemStyle(e,t){var i;this.elementRef.parentElement&&this._originalElementRef&&this.resetDropupItem(t),this.applyDropupContentStyles(e),Object.assign(this.elementRef.style,(i=e==null?void 0:e.item)==null?void 0:i["default"]);var s=U.processStateful((e==null?void 0:e.item)||{});lt.add(this.elementRef,s),this.addClickListener();}},{key:"changeToDefault",value:function changeToDefault(e){var t,s,i,n,o,a;!e&&this._state==="default"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t["default"],(s=this.customStyles)==null?void 0:s["default"]):(this.changeElementsByState(this._innerElements["default"]),(i=this.customStyles)!=null&&i.active&&$.unsetAllCSS(this.elementRef,(n=this.customStyles)==null?void 0:n.active),(o=this.customStyles)!=null&&o.disabled&&$.unsetAllCSS(this.elementRef,(a=this.customStyles)==null?void 0:a.disabled),this.reapplyStateStyle("default",["active","disabled"])),this.elementRef.classList.remove(H.DISABLED_CONTAINER_CLASS,H.ACTIVE_CONTAINER_CLASS),this.elementRef.classList.add(H.DEFAULT_CONTAINER_CLASS),q.removeAriaDisabled(this.elementRef),this._state="default");}},{key:"changeToActive",value:function changeToActive(e){var t,s;!e&&this._state==="active"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t.active,(s=this.customStyles)==null?void 0:s.active):(this.changeElementsByState(this._innerElements.active),this.reapplyStateStyle("active",["disabled","default"])),this.elementRef.classList.remove(H.DISABLED_CONTAINER_CLASS,H.DEFAULT_CONTAINER_CLASS),this.elementRef.classList.add(H.ACTIVE_CONTAINER_CLASS),q.removeAriaDisabled(this.elementRef),this._state="active");}},{key:"changeToDisabled",value:function changeToDisabled(e){var t,s,i,n,o,a;!e&&this._state==="disabled"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t.disabled,(s=this.customStyles)==null?void 0:s.disabled):(this.changeElementsByState(this._innerElements.disabled),(i=this.customStyles)!=null&&i.active&&$.unsetAllCSS(this.elementRef,(n=this.customStyles)==null?void 0:n.active),(o=this.customStyles)!=null&&o["default"]&&$.unsetAllCSS(this.elementRef,(a=this.customStyles)==null?void 0:a["default"]),this.reapplyStateStyle("disabled",["default","active"])),this.elementRef.classList.remove(H.ACTIVE_CONTAINER_CLASS,H.DEFAULT_CONTAINER_CLASS),this.elementRef.classList.add(H.DISABLED_CONTAINER_CLASS),q.addAriaDisabled(this.elementRef),this._state="disabled");}// called after class is initialised
247
+ function H(e,t,s,i){var _this79;_classCallCheck(this,H);var l,c,d,u,h,f;var n=((u=(d=(c=(l=e==null?void 0:e.styles)==null?void 0:l.button)==null?void 0:c["default"])==null?void 0:d.text)==null?void 0:u.content)||"Custom ".concat(t),o=al,a=Le.tryCreateConfig("Custom ".concat(t),e==null?void 0:e.tooltip);_this79=_callSuper(this,H,[H.createButtonElement(),o,e==null?void 0:e.position,a,((h=e==null?void 0:e.styles)==null?void 0:h.button)||a&&{},n]),_this79._state="default",_this79.isCustom=!0,_this79._innerElements=_this79.createInnerElementsForStates(_this79.customStyles),_this79._menuStyles=i,_this79._onClick=e.onClick,_this79._dropupStyles=(f=e.styles)==null?void 0:f.dropup,_this79.setSetState(e),_this79.addClickListener(s),_this79.changeState(e.initialState,!0);return _this79;}_inherits(H,_It2);return _createClass(H,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(e){var t="custom-icon",s=this.createInnerElements(t,"default",e);return{"default":s,active:this.genStateInnerElements(t,"active",s,e),disabled:this.genStateInnerElements(t,"disabled",s,e)};}},{key:"setSetState",value:function setSetState(e){var _this80=this;e.setState=function(t){t==="default"&&_this80.changeToDefault(),t==="active"&&_this80.changeToActive(),t==="disabled"&&_this80.changeToDisabled();};}},{key:"addClickListener",value:function addClickListener(e){var _this81=this;this.elementRef.addEventListener("click",function(){var s;var t=(s=_this81._onClick)==null?void 0:s.call(_this81,_this81._state);e==null||e(),(t==="default"||t==="active"||t==="disabled")&&_this81.changeState(t);});}},{key:"changeState",value:function changeState(e,t){e==="disabled"?this.changeToDisabled(t):e==="active"?this.changeToActive(t):this.changeToDefault(t);}},{key:"applyDropupContentStyles",value:function applyDropupContentStyles(e){var t=Array.from(this.elementRef.children);if(e!=null&&e.text){var _s15=t.find(function(i){return i.classList.contains(Pe.TEXT_CLASS);});_s15&&Object.assign(_s15.style,e.text);}if(e!=null&&e.iconContainer){var _s16=t.find(function(i){return i.classList.contains(Pe.ICON_CLASS);});_s16&&Object.assign(_s16.style,e.iconContainer);}}},{key:"resetDropupItem",value:function resetDropupItem(e){var s,i,n;this.elementRef=le.replaceElementWithNewClone(this.elementRef,this._originalElementRef),this.elementRef.innerHTML="",((s=e==null?void 0:e.svg)==null?void 0:s.content)===""||this.elementRef.appendChild(Pe.createItemIcon(this.svg,(i=this._menuStyles)==null?void 0:i.iconContainer)),this.elementRef.appendChild(Pe.createItemText(this.dropupText,(n=this._menuStyles)==null?void 0:n.text));}},{key:"assignDropupItemStyle",value:function assignDropupItemStyle(e,t){var i;this.elementRef.parentElement&&this._originalElementRef&&this.resetDropupItem(t),this.applyDropupContentStyles(e),Object.assign(this.elementRef.style,(i=e==null?void 0:e.item)==null?void 0:i["default"]);var s=U.processStateful((e==null?void 0:e.item)||{});lt.add(this.elementRef,s),this.addClickListener();}},{key:"changeToDefault",value:function changeToDefault(e){var t,s,i,n,o,a;!e&&this._state==="default"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t["default"],(s=this.customStyles)==null?void 0:s["default"]):(this.changeElementsByState(this._innerElements["default"]),(i=this.customStyles)!=null&&i.active&&$.unsetAllCSS(this.elementRef,(n=this.customStyles)==null?void 0:n.active),(o=this.customStyles)!=null&&o.disabled&&$.unsetAllCSS(this.elementRef,(a=this.customStyles)==null?void 0:a.disabled),this.reapplyStateStyle("default",["active","disabled"])),this.elementRef.classList.remove(H.DISABLED_CONTAINER_CLASS,H.ACTIVE_CONTAINER_CLASS),this.elementRef.classList.add(H.DEFAULT_CONTAINER_CLASS),q.removeAriaDisabled(this.elementRef),this._state="default");}},{key:"changeToActive",value:function changeToActive(e){var t,s;!e&&this._state==="active"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t.active,(s=this.customStyles)==null?void 0:s.active):(this.changeElementsByState(this._innerElements.active),this.reapplyStateStyle("active",["disabled","default"])),this.elementRef.classList.remove(H.DISABLED_CONTAINER_CLASS,H.DEFAULT_CONTAINER_CLASS),this.elementRef.classList.add(H.ACTIVE_CONTAINER_CLASS),q.removeAriaDisabled(this.elementRef),this._state="active");}},{key:"changeToDisabled",value:function changeToDisabled(e){var t,s,i,n,o,a;!e&&this._state==="disabled"||(this.elementRef.classList.contains(Pe.MENU_ITEM_CLASS)?this.assignDropupItemStyle((t=this._dropupStyles)==null?void 0:t.disabled,(s=this.customStyles)==null?void 0:s.disabled):(this.changeElementsByState(this._innerElements.disabled),(i=this.customStyles)!=null&&i.active&&$.unsetAllCSS(this.elementRef,(n=this.customStyles)==null?void 0:n.active),(o=this.customStyles)!=null&&o["default"]&&$.unsetAllCSS(this.elementRef,(a=this.customStyles)==null?void 0:a["default"]),this.reapplyStateStyle("disabled",["default","active"])),this.elementRef.classList.remove(H.ACTIVE_CONTAINER_CLASS,H.DEFAULT_CONTAINER_CLASS),this.elementRef.classList.add(H.DISABLED_CONTAINER_CLASS),q.addAriaDisabled(this.elementRef),this._state="disabled");}// called after class is initialised
248
248
  },{key:"setDropupItem",value:function setDropupItem(e){this.elementRef=e,this._originalElementRef=e.cloneNode(!0),this.changeState(this._state,!0);}},{key:"genStateInnerElements",value:function genStateInnerElements(e,t,s,i){var l,c,d,u;var n=this.createInnerElements(e,t,i);var o=(c=(l=i==null?void 0:i[t])==null?void 0:l.svg)==null?void 0:c.content,a=(u=(d=i==null?void 0:i[t])==null?void 0:d.text)==null?void 0:u.content;if(o===void 0||a===void 0){var _us$parseSVGTextEleme4=us.parseSVGTextElements(s),h=_us$parseSVGTextEleme4.svg,f=_us$parseSVGTextEleme4[y],_us$parseSVGTextEleme5=us.parseSVGTextElements(n),m=_us$parseSVGTextEleme5.svg,p=_us$parseSVGTextEleme5[y],g=[];H.addToInnerElements(g,o,h,m),H.addToInnerElements(g,a,f,p),n=g;}return n;}}],[{key:"createButtonElement",value:function createButtonElement(){var e=document.createElement("div");return e.classList.add("input-button",H.BUTTON_CLASS),e;}},{key:"addToInnerElements",value:function addToInnerElements(e,t,s,i){t===void 0&&s?e.push(s.cloneNode(!0)):i&&e.push(i);}},{key:"add",value:function add(e,t){var s=e.customButtons,i=e.focusInput,n=e.dropupStyles;s==null||s.forEach(function(o,a){var l={button:new H(o,a+1,i,n==null?void 0:n.menu)};t["".concat(H.INDICATOR_PREFIX).concat(a+1)]=l;});}}]);}(It);H.INDICATOR_PREFIX="custom",H.BUTTON_CLASS="custom-button",H.DISABLED_CONTAINER_CLASS="custom-button-container-disabled",H.DEFAULT_CONTAINER_CLASS="custom-button-container-default",H.ACTIVE_CONTAINER_CLASS="custom-button-container-active";var xt=H;var ll="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z\"></path>\n</svg>";var Ts=/*#__PURE__*/function(){function Ts(){_classCallCheck(this,Ts);}return _createClass(Ts,null,[{key:"focusItemWhenOnEdge",value:function focusItemWhenOnEdge(e,t){var s=t?e.children[0]:e.children[e.children.length-1];Ts.focusSiblingItem(s,e,t,!0);}// isEdgeItem means is it a start or end item
249
249
  // prettier-ignore
250
250
  },{key:"focusSiblingItem",value:function focusSiblingItem(e,t,s){var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:!1;var n=i?e:e[s?"nextSibling":"previousSibling"];n?(e.dispatchEvent(new MouseEvent("mouseleave")),n.dispatchEvent(new MouseEvent("mouseenter"))):(e.dispatchEvent(new MouseEvent("mouseleave")),Ts.focusItemWhenOnEdge(t,s));}}]);}();var yn=/*#__PURE__*/function(){function yn(e,t){var _this82=this;_classCallCheck(this,yn);var s;this._isOpen=!0,this._styles=t,this.elementRef=yn.createElement((s=this._styles)==null?void 0:s.container),this.close(),setTimeout(function(){return _this82.addWindowEvents(e);});}return _createClass(yn,[{key:"open",value:function open(){this.elementRef.style.display="block",this._isOpen=!0;}},{key:"close",value:function close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1);}},{key:"toggle",value:function toggle(){this._isOpen?this.close():this.open();}},{key:"addItem",value:function addItem(e){var t=Pe.createItem(this,e,this._styles);this.elementRef.appendChild(t);}// prettier-ignore
@@ -292,11 +292,11 @@ return _createClass(Os,[{key:"addType",value:function addType(e,t,s,i){var n=Ll.
292
292
  function gi(e,t,s,i,n,o){var _this101;_classCallCheck(this,gi);var u,h,f,m,p,g,E,I,P,D;var a=(u=s==null?void 0:s.button)==null?void 0:u.position,l=((m=(f=(h=s==null?void 0:s.button)==null?void 0:h.styles)==null?void 0:f.text)==null?void 0:m.content)||o,c=Le.tryCreateConfig("Upload File",(p=s==null?void 0:s.button)==null?void 0:p.tooltip);_this101=_callSuper(this,gi,[gi.createButtonElement(),n,a,c,s.button,l]);var d=_this101.createInnerElementsForStates(i,_this101.customStyles);_this101._inputElement=gi.createInputElement((g=s==null?void 0:s.files)==null?void 0:g.acceptedFormats),_this101.addClickEvent(e,s),_this101.changeElementsByState(d.styles),_this101.reapplyStateStyle("styles"),_this101._fileAttachmentsType=t,_this101._openModalOnce=((I=(E=s.files)==null?void 0:E.infoModal)==null?void 0:I.openModalOnce)===!1||(D=(P=s.files)==null?void 0:P.infoModal)==null?void 0:D.openModalOnce;return _this101;}_inherits(gi,_It5);return _createClass(gi,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(e,t){return{styles:this.createInnerElements(e,"styles",t)};}},{key:"triggerImportPrompt",value:function triggerImportPrompt(e){e.onchange=this["import"].bind(this,e),e.click();}},{key:"import",value:function _import(e){Os.addFilesToType(Array.from(e.files||[]),[this._fileAttachmentsType]),e.value="";}},{key:"addClickEvent",value:function addClickEvent(e,t){var s=this.triggerImportPrompt.bind(this,this._inputElement),i=Et.createTextModalFunc(e,t,s);this.elementRef.onclick=this.click.bind(this,i);}},{key:"click",value:function click(e){e&&(this._openModalOnce===void 0||this._openModalOnce===!0)?(e(),this._openModalOnce===!0&&(this._openModalOnce=!1)):this.triggerImportPrompt(this._inputElement);}}],[{key:"createInputElement",value:function createInputElement(e){var t=document.createElement("input");return t.type="file",t.accept=e||"",t.hidden=!0,t.multiple=!0,t;}},{key:"createButtonElement",value:function createButtonElement(){var e=document.createElement("div");return e.classList.add("input-button"),e;}}]);}(It);var $e=/*#__PURE__*/function(){function $e(){_classCallCheck(this,$e);}return _createClass($e,null,[{key:"create",value:function create(e,t,s){var i=$e.createElement(s);$e.addEvents(i,e,t),e.appendChild(i);}},{key:"createElement",value:function createElement(e){var t=document.createElement("div");return t.id="drag-and-drop",_typeof(e)===T&&Object.assign(t.style,e),t;}},{key:"addEvents",value:function addEvents(e,t,s){t.ondragenter=function(i){i.preventDefault(),$e.display(e);},e.ondragleave=function(i){i.preventDefault(),$e.hide(e);},e.ondragover=function(i){i.preventDefault();},e.ondrop=function(i){i.preventDefault(),$e.uploadFile(s,i),$e.hide(e);};}},{key:"uploadFile",value:function uploadFile(e,t){var i;var s=(i=t.dataTransfer)==null?void 0:i.files;s&&e.addFilesToAnyType(Array.from(s));}},{key:"display",value:function display(e){e.style.display="block";}},{key:"hide",value:function hide(e){e.style.display="none";}},{key:"isEnabled",value:function isEnabled(e,t){return t!==void 0&&t===!1?!1:!!t||e.getNumberOfTypes()>0;}}]);}();var ut=/*#__PURE__*/function(){function ut(){_classCallCheck(this,ut);}return _createClass(ut,null,[{key:"validate",value:// prettier-ignore
293
293
  function validate(e,t,s,i,n){var o=e(s,i,n);return o?t.changeToSubmitIcon():t.changeToDisabledIcon(),o;}// prettier-ignore
294
294
  },{key:"useValidationFunc",value:function(){var _useValidationFunc=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee175(e,t,s,i){var n,o,a;return _regenerator().w(function(_context175){while(1)switch(_context175.n){case 0:n=t.isTextInputEmpty()?"":t.inputElementRef.textContent;_context175.n=1;return s.completePlaceholders();case 1:o=s.getAllFileData(),a=o==null?void 0:o.map(function(l){return l.file;});return _context175.a(2,ut.validate(e,i,n,a));}},_callee175);}));function useValidationFunc(_x324,_x325,_x326,_x327){return _useValidationFunc.apply(this,arguments);}return useValidationFunc;}()// prettier-ignore
295
- },{key:"useValidationFuncProgrammatic",value:function(){var _useValidationFuncProgrammatic=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee176(e,t,s){var n,i;return _regenerator().w(function(_context176){while(1)switch(_context176.n){case 0:i=(n=t.files)==null?void 0:n.map(function(o){return o.file;});return _context176.a(2,ut.validate(e,s,t.text,i,!0));}},_callee176);}));function useValidationFuncProgrammatic(_x328,_x329,_x330){return _useValidationFuncProgrammatic.apply(this,arguments);}return useValidationFuncProgrammatic;}()},{key:"validateWebsocket",value:function validateWebsocket(e,t){var s=e.websocket,i=e.connectSettings;return s&&i.url!==Oe.URL&&!re.canSendMessage(s)?(t.changeToDisabledIcon(),!1):!0;}// prettier-ignore
296
- },{key:"attach",value:function attach(e,t,s,i,n){var o=e.validateInput||le.processValidateInput(e);e._validationHandler=/*#__PURE__*/function(){var _ref155=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee177(a){var l;return _regenerator().w(function(_context177){while(1)switch(_context177.n){case 0:if(!(n.status.loadingActive||n.status.requestInProgress||t.isSubmitProgrammaticallyDisabled===!0||!ut.validateWebsocket(t,n))){_context177.n=1;break;}return _context177.a(2,!1);case 1:l=o||t.canSendMessage;return _context177.a(2,l?a?ut.useValidationFuncProgrammatic(l,a,n):ut.useValidationFunc(l,s,i,n):null);}},_callee177);}));return function(_x331){return _ref155.apply(this,arguments);};}();}}]);}();var Lr=/*#__PURE__*/function(){function Lr(){_classCallCheck(this,Lr);}return _createClass(Lr,null,[{key:"getFileName",value:function getFileName(e,t){var s=/* @__PURE__ */new Date(),i=String(s.getHours()).padStart(2,"0"),n=String(s.getMinutes()).padStart(2,"0"),o=String(s.getSeconds()).padStart(2,"0");return"".concat(e,"-").concat(i,"-").concat(n,"-").concat(o,".").concat(t);}}]);}();var Ol=/*#__PURE__*/function(_Ci2){function Ol(e,t){var _this102;_classCallCheck(this,Ol);var s,i;_this102=_callSuper(this,Ol,[t.button]),_this102._waitingForBrowserApproval=!1,_this102._audioType=e,_this102._extension=((s=t.files)==null?void 0:s.format)||"mp3",_this102._maxDurationSeconds=(i=t.files)==null?void 0:i.maxDurationSeconds,_this102.elementRef.onclick=_this102.buttonClick.bind(_assertThisInitialized(_this102));return _this102;}_inherits(Ol,_Ci2);return _createClass(Ol,[{key:"buttonClick",value:function buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()));}},{key:"stop",value:function stop(){var _this103=this;return new Promise(function(e){var t,s;_this103.changeToDefault(),(t=_this103._mediaRecorder)==null||t.stop(),(s=_this103._mediaStream)==null||s.getTracks().forEach(function(i){return i.stop();}),setTimeout(function(){e();},10);});}},{key:"record",value:function record(){var _this104=this;navigator.mediaDevices.getUserMedia({audio:!0}).then(function(e){_this104.changeToActive(),_this104._mediaRecorder=new MediaRecorder(e),_this104._audioType.addPlaceholderAttachment(_this104.stop.bind(_this104),_this104._maxDurationSeconds),_this104._mediaStream=e,_this104._mediaRecorder.addEventListener("dataavailable",function(t){_this104.createFile(t);}),_this104._mediaRecorder.start();})["catch"](function(e){console.error(e),_this104.stop();})["finally"](function(){_this104._waitingForBrowserApproval=!1;});}},{key:"createFile",value:function createFile(e){var _this105=this;var t=new Blob([e.data],{type:"audio/".concat(this._extension)}),s=Lr.getFileName(this._newFilePrefix||"audio",this._extension),i=new File([t],s,{type:t.type}),n=new FileReader();n.readAsDataURL(i),n.onload=function(o){_this105._audioType.completePlaceholderAttachment(i,o.target.result);};}}]);}(Ci);var Nl="<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n<svg xmlns=\"http://www.w3.org/2000/svg\" stroke=\"currentColor\" fill=\"none\" stroke-width=\"1\" viewBox=\"0 0 24 24\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"14\"></line>\n <polygon points=\"22 2 15 22 11 14 2 10 22 2\"></polygon>\n</svg>\n";var St=/*#__PURE__*/function(){function St(){_classCallCheck(this,St);}return _createClass(St,null,[{key:"resetSubmit",value:function resetSubmit(e,t){t?e.unsetCustomStateStyles(["loading","submit"]):e.unsetCustomStateStyles(["stop","loading","submit"]),e.reapplyStateStyle("submit");}},{key:"overwriteDefaultStyleWithSubmit",value:function overwriteDefaultStyleWithSubmit(e,t){if(!e.submit)return;var s=JSON.parse(JSON.stringify(e[t]||{}));oe.overwritePropertyObjectFromAnother(s,e.submit,["container","default"]),oe.overwritePropertyObjectFromAnother(s,e.submit,["text","styles","default"]),oe.overwritePropertyObjectFromAnother(s,e.submit,["svg","styles","default"]),e[t]=s;}// prettier-ignore
297
- },{key:"setUpDisabledButton",value:function setUpDisabledButton(e){oe.setPropertyValueIfDoesNotExist(e,["submit","container","default","backgroundColor"],""),oe.setPropertyValueIfDoesNotExist(e,["disabled","container","default","backgroundColor"],"unset"),oe.setPropertyValueIfDoesNotExist(e.submit,["svg","styles","default","filter"],""),oe.setPropertyValueIfDoesNotExist(e.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),oe.setPropertyValueIfDoesNotExist(e.disabled,["text","styles","default","color"],"grey"),St.overwriteDefaultStyleWithSubmit(e,"disabled");}},{key:"process",value:function process(e){var t=JSON.parse(JSON.stringify(e||{}));return St.overwriteDefaultStyleWithSubmit(t,"loading"),St.overwriteDefaultStyleWithSubmit(t,"stop"),e!=null&&e.alwaysEnabled||St.setUpDisabledButton(t),t;}}]);}();var j=/*#__PURE__*/function(_It6){// prettier-ignore
295
+ },{key:"useValidationFuncProgrammatic",value:function(){var _useValidationFuncProgrammatic=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee176(e,t,s){var n,i;return _regenerator().w(function(_context176){while(1)switch(_context176.n){case 0:i=(n=t.files)==null?void 0:n.map(function(o){return o.file;});return _context176.a(2,ut.validate(e,s,t.text,i,!0));}},_callee176);}));function useValidationFuncProgrammatic(_x328,_x329,_x330){return _useValidationFuncProgrammatic.apply(this,arguments);}return useValidationFuncProgrammatic;}()},{key:"validateWebsocket",value:function validateWebsocket(e,t){var s=e.websocket,i=e.connectSettings;return s&&i.url!==Oe.URL&&!oe.canSendMessage(s)?(t.changeToDisabledIcon(),!1):!0;}// prettier-ignore
296
+ },{key:"attach",value:function attach(e,t,s,i,n){var o=e.validateInput||te.processValidateInput(e);e._validationHandler=/*#__PURE__*/function(){var _ref155=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee177(a){var l;return _regenerator().w(function(_context177){while(1)switch(_context177.n){case 0:if(!(n.status.loadingActive||n.status.requestInProgress||t.isSubmitProgrammaticallyDisabled===!0||!ut.validateWebsocket(t,n))){_context177.n=1;break;}return _context177.a(2,!1);case 1:l=o||t.canSendMessage;return _context177.a(2,l?a?ut.useValidationFuncProgrammatic(l,a,n):ut.useValidationFunc(l,s,i,n):null);}},_callee177);}));return function(_x331){return _ref155.apply(this,arguments);};}();}}]);}();var Lr=/*#__PURE__*/function(){function Lr(){_classCallCheck(this,Lr);}return _createClass(Lr,null,[{key:"getFileName",value:function getFileName(e,t){var s=/* @__PURE__ */new Date(),i=String(s.getHours()).padStart(2,"0"),n=String(s.getMinutes()).padStart(2,"0"),o=String(s.getSeconds()).padStart(2,"0");return"".concat(e,"-").concat(i,"-").concat(n,"-").concat(o,".").concat(t);}}]);}();var Ol=/*#__PURE__*/function(_Ci2){function Ol(e,t){var _this102;_classCallCheck(this,Ol);var s,i;_this102=_callSuper(this,Ol,[t.button]),_this102._waitingForBrowserApproval=!1,_this102._audioType=e,_this102._extension=((s=t.files)==null?void 0:s.format)||"mp3",_this102._maxDurationSeconds=(i=t.files)==null?void 0:i.maxDurationSeconds,_this102.elementRef.onclick=_this102.buttonClick.bind(_assertThisInitialized(_this102));return _this102;}_inherits(Ol,_Ci2);return _createClass(Ol,[{key:"buttonClick",value:function buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()));}},{key:"stop",value:function stop(){var _this103=this;return new Promise(function(e){var t,s;_this103.changeToDefault(),(t=_this103._mediaRecorder)==null||t.stop(),(s=_this103._mediaStream)==null||s.getTracks().forEach(function(i){return i.stop();}),setTimeout(function(){e();},10);});}},{key:"record",value:function record(){var _this104=this;navigator.mediaDevices.getUserMedia({audio:!0}).then(function(e){_this104.changeToActive(),_this104._mediaRecorder=new MediaRecorder(e),_this104._audioType.addPlaceholderAttachment(_this104.stop.bind(_this104),_this104._maxDurationSeconds),_this104._mediaStream=e,_this104._mediaRecorder.addEventListener("dataavailable",function(t){_this104.createFile(t);}),_this104._mediaRecorder.start();})["catch"](function(e){console.error(e),_this104.stop();})["finally"](function(){_this104._waitingForBrowserApproval=!1;});}},{key:"createFile",value:function createFile(e){var _this105=this;var t=new Blob([e.data],{type:"audio/".concat(this._extension)}),s=Lr.getFileName(this._newFilePrefix||"audio",this._extension),i=new File([t],s,{type:t.type}),n=new FileReader();n.readAsDataURL(i),n.onload=function(o){_this105._audioType.completePlaceholderAttachment(i,o.target.result);};}}]);}(Ci);var Nl="<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n<svg xmlns=\"http://www.w3.org/2000/svg\" stroke=\"currentColor\" fill=\"none\" stroke-width=\"1\" viewBox=\"0 0 24 24\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"14\"></line>\n <polygon points=\"22 2 15 22 11 14 2 10 22 2\"></polygon>\n</svg>\n";var St=/*#__PURE__*/function(){function St(){_classCallCheck(this,St);}return _createClass(St,null,[{key:"resetSubmit",value:function resetSubmit(e,t){t?e.unsetCustomStateStyles(["loading","submit"]):e.unsetCustomStateStyles(["stop","loading","submit"]),e.reapplyStateStyle("submit");}},{key:"overwriteDefaultStyleWithSubmit",value:function overwriteDefaultStyleWithSubmit(e,t){if(!e.submit)return;var s=JSON.parse(JSON.stringify(e[t]||{}));ae.overwritePropertyObjectFromAnother(s,e.submit,["container","default"]),ae.overwritePropertyObjectFromAnother(s,e.submit,["text","styles","default"]),ae.overwritePropertyObjectFromAnother(s,e.submit,["svg","styles","default"]),e[t]=s;}// prettier-ignore
297
+ },{key:"setUpDisabledButton",value:function setUpDisabledButton(e){ae.setPropertyValueIfDoesNotExist(e,["submit","container","default","backgroundColor"],""),ae.setPropertyValueIfDoesNotExist(e,["disabled","container","default","backgroundColor"],"unset"),ae.setPropertyValueIfDoesNotExist(e.submit,["svg","styles","default","filter"],""),ae.setPropertyValueIfDoesNotExist(e.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),ae.setPropertyValueIfDoesNotExist(e.disabled,["text","styles","default","color"],"grey"),St.overwriteDefaultStyleWithSubmit(e,"disabled");}},{key:"process",value:function process(e){var t=JSON.parse(JSON.stringify(e||{}));return St.overwriteDefaultStyleWithSubmit(t,"loading"),St.overwriteDefaultStyleWithSubmit(t,"stop"),e!=null&&e.alwaysEnabled||St.setUpDisabledButton(t),t;}}]);}();var j=/*#__PURE__*/function(_It6){// prettier-ignore
298
298
  function j(e,t,s,i,n,o){var _this106;_classCallCheck(this,j);var a=St.process(e.submitButtonStyles),l=Nl,c=Le.tryCreateConfig("Submit",a==null?void 0:a.tooltip);_this106=_callSuper(this,j,[j.createButtonContainerElement(),l,a==null?void 0:a.position,c,a]),_this106._isSVGLoadingIconOverriden=!1,_this106.status={requestInProgress:!1,loadingActive:!1},_this106._messages=s,_this106._textInput=t,_this106._fileAttachments=n,_this106._innerElements=_this106.createInnerElementsForStates(),_this106._stopClicked={listener:function listener(){}},_this106._serviceIO=i,_this106._alwaysEnabled=!!(a!=null&&a.alwaysEnabled),e.disableSubmitButton=_this106.disableSubmitButton.bind(_assertThisInitialized(_this106),i),_this106.attemptOverwriteLoadingStyle(e),o.microphone&&_this106.setUpSpeechToText(o.microphone.button,e.speechToText),setTimeout(function(){var d;_this106._validationHandler=e._validationHandler,_this106.assignHandlers(_this106._validationHandler),(d=_this106._validationHandler)==null||d.call(_assertThisInitialized(_this106));});return _this106;}_inherits(j,_It6);return _createClass(j,[{key:"createInnerElementsForStates",value:function createInnerElementsForStates(){var _this$createCustomEle=this.createCustomElements(),e=_this$createCustomEle.submit,t=_this$createCustomEle.loading,s=_this$createCustomEle.stop;return{submit:e,loading:t||[j.createLoadingIconElement()],stop:s||[j.createStopIconElement()],disabled:this.createDisabledIconElement(e)};}},{key:"createCustomElements",value:function createCustomElements(){var _this107=this;var e=He.createCustomElements("submit",this.svg,this.customStyles),t={loading:void 0,stop:void 0};return Object.keys(t).forEach(function(s){var i=s,n=He.createCustomElements(i,_this107.svg,_this107.customStyles);n&&(t[i]=n);}),t.submit=e||this.buildDefaultIconElement("submit-icon"),t;}},{key:"createDisabledIconElement",value:function createDisabledIconElement(e){return He.createCustomElements("disabled",this.svg,this.customStyles)||[e[0].cloneNode(!0)];}// prettier-ignore
299
- },{key:"attemptOverwriteLoadingStyle",value:function attemptOverwriteLoadingStyle(e){var t,s,i,n,o,a,l,c,d;if(!((s=(t=this.customStyles)==null?void 0:t.submit)!=null&&s.svg||(o=(n=(i=this.customStyles)==null?void 0:i.loading)==null?void 0:n.svg)!=null&&o.content||(c=(l=(a=this.customStyles)==null?void 0:a.loading)==null?void 0:l.text)!=null&&c.content)&&(e.displayLoadingBubble===void 0||e.displayLoadingBubble===!0)){var u=document.createElement("style");u.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",(d=e.shadowRoot)==null||d.appendChild(u),this._isSVGLoadingIconOverriden=!0;}}},{key:"assignHandlers",value:function assignHandlers(e){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,e)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,e),stopClicked:this._stopClicked};var t=this._serviceIO.stream;_typeof(t)=="object"&&typeof t.simulation=="number"&&(this._serviceIO.streamHandlers.simulationInterim=t.simulation);}},{key:"setUpSpeechToText",value:function setUpSpeechToText(e,t){this._microphoneButton=e,this._stopSTTAfterSubmit=_typeof(t)=="object"?t.stopAfterSubmit:!1;}},{key:"resetSubmit",value:function resetSubmit(e){this.status.requestInProgress=!1,this.status.loadingActive=!1,e();}},{key:"submitFromInput",value:function(){var _submitFromInput=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee178(){var e,t;return _regenerator().w(function(_context178){while(1)switch(_context178.n){case 0:_context178.n=1;return this._fileAttachments.completePlaceholders();case 1:e=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit(_defineProperty(_defineProperty({},y,""),"files",e));else{t=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit(_defineProperty(_defineProperty({},y,t),"files",e));}case 2:return _context178.a(2);}},_callee178,this);}));function submitFromInput(){return _submitFromInput.apply(this,arguments);}return submitFromInput;}()},{key:"programmaticSubmit",value:function(){var _programmaticSubmit=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee179(e){var _this108=this;var t;return _regenerator().w(function(_context179){while(1)switch(_context179.n){case 0:typeof e=="string"&&(e=le.processSubmitUserMessage(e));t=_defineProperty({},y,e.text);e.files&&(t.files=Array.from(e.files).map(function(s){return{file:s,type:We.getTypeFromBlob(s)};})),e.custom&&(t.custom=e.custom),setTimeout(function(){return _this108.attemptSubmit(t,!0);});case 1:return _context179.a(2);}},_callee179);}));function programmaticSubmit(_x332){return _programmaticSubmit.apply(this,arguments);}return programmaticSubmit;}()// TO-DO - should be disabled when loading history
299
+ },{key:"attemptOverwriteLoadingStyle",value:function attemptOverwriteLoadingStyle(e){var t,s,i,n,o,a,l,c,d;if(!((s=(t=this.customStyles)==null?void 0:t.submit)!=null&&s.svg||(o=(n=(i=this.customStyles)==null?void 0:i.loading)==null?void 0:n.svg)!=null&&o.content||(c=(l=(a=this.customStyles)==null?void 0:a.loading)==null?void 0:l.text)!=null&&c.content)&&(e.displayLoadingBubble===void 0||e.displayLoadingBubble===!0)){var u=document.createElement("style");u.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",(d=e.shadowRoot)==null||d.appendChild(u),this._isSVGLoadingIconOverriden=!0;}}},{key:"assignHandlers",value:function assignHandlers(e){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,e)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,e),stopClicked:this._stopClicked};var t=this._serviceIO.stream;_typeof(t)=="object"&&typeof t.simulation=="number"&&(this._serviceIO.streamHandlers.simulationInterim=t.simulation);}},{key:"setUpSpeechToText",value:function setUpSpeechToText(e,t){this._microphoneButton=e,this._stopSTTAfterSubmit=_typeof(t)=="object"?t.stopAfterSubmit:!1;}},{key:"resetSubmit",value:function resetSubmit(e){this.status.requestInProgress=!1,this.status.loadingActive=!1,e();}},{key:"submitFromInput",value:function(){var _submitFromInput=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee178(){var e,t;return _regenerator().w(function(_context178){while(1)switch(_context178.n){case 0:_context178.n=1;return this._fileAttachments.completePlaceholders();case 1:e=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit(_defineProperty(_defineProperty({},y,""),"files",e));else{t=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit(_defineProperty(_defineProperty({},y,t),"files",e));}case 2:return _context178.a(2);}},_callee178,this);}));function submitFromInput(){return _submitFromInput.apply(this,arguments);}return submitFromInput;}()},{key:"programmaticSubmit",value:function(){var _programmaticSubmit=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee179(e){var _this108=this;var t;return _regenerator().w(function(_context179){while(1)switch(_context179.n){case 0:typeof e=="string"&&(e=te.processSubmitUserMessage(e));t=_defineProperty({},y,e.text);e.files&&(t.files=Array.from(e.files).map(function(s){return{file:s,type:We.getTypeFromBlob(s)};})),e.custom&&(t.custom=e.custom),setTimeout(function(){return _this108.attemptSubmit(t,!0);});case 1:return _context179.a(2);}},_callee179);}));function programmaticSubmit(_x332){return _programmaticSubmit.apply(this,arguments);}return programmaticSubmit;}()// TO-DO - should be disabled when loading history
300
300
  },{key:"attemptSubmit",value:function(){var _attemptSubmit=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee180(e){var t,n,o,a,l,s,i,_args180=arguments,_t44,_t45,_t46;return _regenerator().w(function(_context180){while(1)switch(_context180.n){case 0:t=_args180.length>1&&_args180[1]!==undefined?_args180[1]:!1;_context180.n=1;return(n=this._validationHandler)==null?void 0:n.call(this,t?e:void 0);case 1:_t44=_context180.v;_t45=!1;if(!(_t44===_t45)){_context180.n=2;break;}return _context180.a(2);case 2:this.changeToLoadingIcon();this._textInput.clear();_t46=typeof this._messages.focusMode!="boolean"&&(o=this._messages.focusMode)!=null&&o.fade;if(!_t46){_context180.n=3;break;}_context180.n=3;return qs.fadeAnimation(this._messages.elementRef,this._messages.focusMode.fade);case 3:_context180.n=4;return this.addNewMessage(e);case 4:this._serviceIO.isWebModel()||this._messages.addLoadingMessage();s=(a=e.files)==null?void 0:a.map(function(c){return c.file;}),i=_defineProperty(_defineProperty({},y,e.text===""?void 0:e.text),"files",s);_context180.n=5;return this._serviceIO.callAPI(i,this._messages);case 5:(l=this._fileAttachments)==null||l.hideFiles();case 6:return _context180.a(2);}},_callee180,this);}));function attemptSubmit(_x333){return _attemptSubmit.apply(this,arguments);}return attemptSubmit;}()},{key:"addNewMessage",value:function(){var _addNewMessage=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee181(_ref156){var e,t,s,i,_t47;return _regenerator().w(function(_context181){while(1)switch(_context181.n){case 0:e=_ref156.text,t=_ref156.files,s=_ref156.custom;i={role:v.USER_ROLE,custom:s};e&&(i.text=e);_t47=t;if(!_t47){_context181.n=2;break;}_context181.n=1;return this._messages.addMultipleFiles(t,this._fileAttachments);case 1:i.files=_context181.v;case 2:this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId);Object.keys(i).length>0&&this._messages.addNewMessage(i);case 3:return _context181.a(2);}},_callee181,this);}));function addNewMessage(_x334){return _addNewMessage.apply(this,arguments);}return addNewMessage;}()},{key:"stopStream",value:function stopStream(){var e,t,s;(t=(e=this._serviceIO.streamHandlers).onAbort)==null||t.call(e),(s=this._stopClicked)==null||s.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler);}},{key:"changeToStopIcon",value:function changeToStopIcon(){this._serviceIO.websocket||(this.elementRef.classList.remove(j.LOADING_CLASS,j.DISABLED_CLASS,j.SUBMIT_CLASS),q.removeAriaAttributes(this.elementRef),this.changeElementsByState(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this.status.loadingActive=!1);}},{key:"changeToLoadingIcon",value:function changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.changeElementsByState(this._innerElements.loading),this.elementRef.classList.remove(j.SUBMIT_CLASS,j.DISABLED_CLASS),q.removeAriaDisabled(this.elementRef),this.elementRef.classList.add(j.LOADING_CLASS),q.addAriaBusy(this.elementRef),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=function(){},this.status.requestInProgress=!0,this.status.loadingActive=!0);}// called every time when user triggers an input via ValidationHandler - hence use class to check if not already present
301
301
  },{key:"changeToSubmitIcon",value:function changeToSubmitIcon(){var _this109=this;this.elementRef.classList.contains(j.SUBMIT_CLASS)||(this.elementRef.classList.remove(j.LOADING_CLASS,j.DISABLED_CLASS),q.removeAriaAttributes(this.elementRef),this.elementRef.classList.add(j.SUBMIT_CLASS),this.changeElementsByState(this._innerElements.submit),St.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=function(){var e;_this109.submitFromInput(),(e=_this109._microphoneButton)!=null&&e.isActive&&Rs.toggleSpeechAfterSubmit(_this109._microphoneButton.elementRef,!!_this109._stopSTTAfterSubmit);});}// called every time when user triggers an input via ValidationHandler - hence use class to check if not already present
302
302
  },{key:"changeToDisabledIcon",value:function changeToDisabledIcon(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:!1;this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef.classList.contains(j.DISABLED_CLASS)||(this.elementRef.classList.remove(j.LOADING_CLASS,j.SUBMIT_CLASS),q.removeAriaBusy(this.elementRef),this.elementRef.classList.add(j.DISABLED_CLASS),q.addAriaDisabled(this.elementRef),this.changeElementsByState(this._innerElements.disabled),this.reapplyStateStyle("disabled",["submit"]),this.elementRef.onclick=function(){});}},{key:"disableSubmitButton",value:function disableSubmitButton(e,t){var s;e.isSubmitProgrammaticallyDisabled=t!==!1,!(this.status.requestInProgress||this.status.loadingActive)&&(t===!1?(s=this._validationHandler)==null||s.call(this):this.changeToDisabledIcon(!0));}}],[{key:"createButtonContainerElement",value:function createButtonContainerElement(){var e=document.createElement("div");return e.classList.add("input-button"),e;}},{key:"createLoadingIconElement",value:function createLoadingIconElement(){var e=document.createElement("div");return e.classList.add("loading-submit-button"),e;}},{key:"createStopIconElement",value:function createStopIconElement(){var e=document.createElement("div");return e.id="stop-icon",e;}}]);}(It);j.SUBMIT_CLASS="submit-button",j.LOADING_CLASS="loading-button",j.DISABLED_CLASS="disabled-button";var en=j;var Pl="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 32 32\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z\"/>\n</svg>\n",Dl="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z\"></path>\n</svg>\n",Bl="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 1024 1024\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z\"/>\n</svg>",Fl="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M4.89163 13.2687L9.16582 17.5427L18.7085 8\" stroke=\"#000000\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>";var vn=/*#__PURE__*/function(_Et){// prettier-ignore
@@ -306,5 +306,5 @@ function vn(e,t,s,i){var _this110;_classCallCheck(this,vn);_this110=_callSuper(t
306
306
  function addClickEvent(e,t,s,i){var n=vn.createCameraModalFunc(e,t,s,i);this.elementRef.onclick=n;}}],[{key:"createButtonElement",value:function createButtonElement(){var e=document.createElement("div");return e.classList.add("input-button"),e;}}]);}(It);var Lt=/*#__PURE__*/function(){function Lt(e,t,s,i){_classCallCheck(this,Lt);this.elementRef=Lt.createPanelElement(e.inputAreaStyle);var n={},o=this.createFileUploadComponents(e,s,i,n),a=new js(e,s,o);e.speechToText&&!n.microphone&&(n.microphone={button:new Rs(e,a,t.addNewErrorMessage.bind(t))});var l=new en(e,a,t,s,o,n);a.submit=l.submitFromInput.bind(l),ut.attach(e,s,a,o,l),e.submitUserMessage=l.programmaticSubmit.bind(l),n.submit={button:l},e.customButtons&&xt.add(e,n),Lt.addElements(this.elementRef,a,n,i,o,e.dropupStyles),Lt.assignOnInput(e,s,o,a);}return _createClass(Lt,[{key:"createFileUploadComponents",value:// prettier-ignore
307
307
  function createFileUploadComponents(e,t,s,i){var o,a,l,c;var n=new Os(this.elementRef,e.attachmentContainerStyle,t.demo);if(Lt.createUploadButtons(e,t,t.fileTypes||{},n,s,i),(o=t.camera)!=null&&o.files){var d=((a=i.images)==null?void 0:a.fileType)||n.addType(e,t,t.camera.files,"images");i.camera={button:new _n(s,d,t.camera)};}if((l=t.recordAudio)!=null&&l.files){var _d=((c=i.audio)==null?void 0:c.fileType)||n.addType(e,t,t.recordAudio.files,"audio");i.microphone={button:new Ol(_d,t.recordAudio)};}return $e.isEnabled(n,e.dragAndDrop)&&$e.create(s,n,e.dragAndDrop),n;}// prettier-ignore
308
308
  }],[{key:"createPanelElement",value:function createPanelElement(e){var t=document.createElement("div");return t.id="input",Object.assign(t.style,e),t;}},{key:"createUploadButtons",value:function createUploadButtons(e,t,s,i,n,o){Object.keys(s).forEach(function(a){var l=a,c=s[l];if(c.files){var d=i.addType(e,t,c.files,l),_fl$l=fl[l],u=_fl$l.id,h=_fl$l.svgString,f=_fl$l.dropupText,m=new gi(n,d,c,u,h,f);o[l]={button:m,fileType:d};}});}// prettier-ignore
309
- },{key:"addElements",value:function addElements(e,t,s,i,n,o){F.addElements(e,t.elementRef);var a=Ht.create(),l=de.addButtons(a,s,i,o);Qi.set(t.inputElementRef,a,n.elementRef,l),Ht.add(e,a);}},{key:"assignOnInput",value:function assignOnInput(e,t,s,i){t.onInput=function(n){setTimeout(function(){var o=s.getAllFileData(),a=i.inputElementRef.innerText.trim(),l=_defineProperty({},y,a);o&&(l.files=o.map(function(c){return c.file;})),Ct.onInput(e,l,n);});};}}]);}();var En=/*#__PURE__*/function(){function En(){_classCallCheck(this,En);}return _createClass(En,null,[{key:"createElements",value:function createElements(e,t,s){var i=document.createElement("div");i.id="chat-view";var n=new xe(e,t,s);t.websocket&&re.createConnection(t,n);var o=new Lt(e,n,t,i);return F.addElements(i,n.elementRef,o.elementRef),i;}},{key:"render",value:function render(e,t,s,i){var n=En.createElements(e,s,i);t.replaceChildren(n),s.isCustomView()&&s.setUpView(n,t);}}]);}();var Hl="#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:\" \";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#deep-chat-openai-realtime-container{height:100%;width:100%}#deep-chat-openai-realtime-avatar-container{height:60%;width:100%;display:flex;justify-content:center;align-items:center}#deep-chat-openai-realtime-avatar{border-radius:50%;height:110px;border:1px solid rgb(215,215,215);padding:8px;-webkit-user-select:none;user-select:none;margin-top:20px}#deep-chat-openai-realtime-buttons-container{height:40%;display:flex;position:relative}.deep-chat-openai-realtime-button-container{height:100%;width:50%;display:flex;justify-content:center;align-items:center}.deep-chat-openai-realtime-button{width:70px;height:70px;border-radius:50%;display:flex;justify-content:center;align-items:center;cursor:pointer}.deep-chat-openai-realtime-button-default{background-color:#e3e3e3}.deep-chat-openai-realtime-button-default:hover{background-color:#d4d4d4}.deep-chat-openai-realtime-button-default:active{background-color:#c5c5c5}.deep-chat-openai-realtime-button-loading{opacity:.7;pointer-events:none}.deep-chat-openai-realtime-microphone-active{background-color:#ffe7e7}.deep-chat-openai-realtime-microphone-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-microphone-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-microphone>*{height:30px;width:30px}.deep-chat-openai-realtime-microphone-active>*{filter:brightness(0) saturate(100%) invert(35%) sepia(60%) saturate(1360%) hue-rotate(325deg) brightness(95%) contrast(92%)}.deep-chat-openai-realtime-toggle>*{height:32px;width:32px;padding-left:3px;filter:brightness(0) saturate(100%) invert(22%) sepia(0%) saturate(4537%) hue-rotate(208deg) brightness(105%) contrast(91%)}.deep-chat-openai-realtime-button-unavailable{opacity:.45;pointer-events:none}#deep-chat-openai-realtime-error{color:red;position:absolute;top:calc(50% + 40px);left:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;left:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:\" \";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.deep-chat-last-group-messages-active{height:100%}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border);border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:\"\";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child,.message-bubble>.partial-render-message>p:first-child,.html-wrapper>p:first-child{margin-top:0}.message-bubble>p:last-child,.message-bubble>.partial-render-message:last-child>p,.html-wrapper>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.role-hidden{display:none}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:3}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:2;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.tooltip{position:absolute;visibility:hidden;z-index:1;pointer-events:none;padding:5px 7px;background-color:#333;border-radius:5px;width:max-content}.tooltip-text{color:#fff;font-size:13px}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button-svg-text{padding:1px;height:1.65em;display:flex}.input-button-svg-text>svg{padding:.22rem}.input-button-svg-text>div{margin-left:2px}.input-button:hover,.input-button:focus-visible{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.input-button:active:not(:hover){background-color:transparent}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em;width:max-content}#custom-icon{height:100%;width:1.2em}.custom-button-container-default{color:#505050}.custom-button-container-default>.dropup-menu-item-icon{color:unset}.custom-button-container-default>svg{filter:brightness(0) saturate(100%) invert(39%) sepia(1%) saturate(0%) hue-rotate(83deg) brightness(93%) contrast(90%)}.custom-button-container-default>.dropup-menu-item-icon>svg{position:absolute;left:.2em}.custom-button-container-active{background-color:#edf7ff;color:#0285ff}.custom-button-container-active:hover,.custom-button-container-active:focus-visible{background-color:#def0ff}.custom-button-container-active:active{background-color:#d2eaff}.custom-button-container-active>svg{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.custom-button-container-disabled{color:#aeaeae;cursor:auto}.custom-button-container-disabled>div{pointer-events:none}.custom-button-container-disabled:hover,.custom-button-container-disabled:focus-visible{background-color:transparent}.custom-button-container-disabled:active{background-color:transparent}.custom-button-container-disabled>svg{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}.dropup-button>*{pointer-events:none}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:hover,.dropup-menu-item:focus-visible{background-color:#f3f3f3}.dropup-menu-item:active{background-color:#ebebeb}.dropup-menu-item:active:not(:hover){background-color:transparent}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}#dropup-menu-item-icon-element-custom{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.28em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%)}.dropup-menu-item-text{margin-left:.56em;margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}";var jl=Object.defineProperty,C=function C(r,e,t,s){for(var i=void 0,n=r.length-1,o;n>=0;n--)(o=r[n])&&(i=o(e,t,i)||i);return i&&jl(e,t,i),i;};var S=/*#__PURE__*/function(_Hi){function S(){var _this115;_classCallCheck(this,S);var e;_this115=_callSuper(this,S),_this115.getMessages=function(){return[];},_this115.submitUserMessage=function(){return console.warn("submitUserMessage failed - please wait for chat view to render before calling this property.");},_this115.addMessage=function(){return console.warn("addMessage failed - please wait for chat view to render before calling this property.");},_this115.updateMessage=function(){},_this115.clearMessages=function(){},_this115.focusInput=function(){return Is.focusFromParentElement(_this115._elementRef);},_this115.refreshMessages=function(){},_this115.scrollToBottom=function(){},_this115.disableSubmitButton=function(){},_this115.setPlaceholderText=function(){},_this115._hasBeenRendered=!1,_this115._auxiliaryStyleApplied=!1,_this115._elementRef=document.createElement("div"),_this115._elementRef.id="container",_this115.attachShadow({mode:"open"}).appendChild(_this115._elementRef),(e=_this115.shadowRoot)==null||e.appendChild(Le.buildElement()),ds.apply(Hl,_this115.shadowRoot),setTimeout(function(){_this115._hasBeenRendered||_this115.onRender();},20);return _this115;}_inherits(S,_Hi);return _createClass(S,[{key:"changeToChatView",value:function changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender();}// prettier-ignore
310
- },{key:"onRender",value:function onRender(){var _this$_childElement;Hs.attemptAppendStyleSheetToHead(this.style),le.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=nl.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(ds.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),ds.applyDefaultStyleToComponent(this.style,this.chatStyle),le.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?Us.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):!(this._activeService instanceof k)||this._activeService.key?((_this$_childElement=this._childElement)!==null&&_this$_childElement!==void 0?_this$_childElement:this._childElement=this.children[0],En.render(this,this._elementRef,this._activeService,this._childElement)):this._activeService instanceof k&&ce.render(this._elementRef,this.changeToChatView.bind(this),this._activeService),this._hasBeenRendered||Ct.onRender(this),this._hasBeenRendered=!0;}},{key:"disconnectedCallback",value:function disconnectedCallback(){Cs.chat=void 0;}}]);}(Hi);C([A("object")],S.prototype,"connect");C([A("object")],S.prototype,"directConnection");C([A("object")],S.prototype,"webModel");C([A("object")],S.prototype,"requestBodyLimits");C([A("function")],S.prototype,"requestInterceptor");C([A("function")],S.prototype,"responseInterceptor");C([A("function")],S.prototype,"validateInput");C([A("function")],S.prototype,"loadHistory");C([A("object")],S.prototype,"chatStyle");C([A("object")],S.prototype,"attachmentContainerStyle");C([A("object")],S.prototype,"dropupStyles");C([A("object")],S.prototype,"inputAreaStyle");C([A("object")],S.prototype,"textInput");C([A("object")],S.prototype,"submitButtonStyles");C([A("object")],S.prototype,"customButtons");C([A("string")],S.prototype,"auxiliaryStyle");C([A("array")],S.prototype,"history");C([A("object")],S.prototype,"browserStorage");C([A("object")],S.prototype,"introMessage");C([A("object")],S.prototype,"avatars");C([A("object")],S.prototype,"names");C([A("object")],S.prototype,"displayLoadingBubble");C([A("object")],S.prototype,"errorMessages");C([A("object")],S.prototype,"messageStyles");C([A("object")],S.prototype,"textToSpeech");C([A("object")],S.prototype,"speechToText");C([A("object")],S.prototype,"images");C([A("object")],S.prototype,"gifs");C([A("object")],S.prototype,"camera");C([A("object")],S.prototype,"audio");C([A("object")],S.prototype,"microphone");C([A("object")],S.prototype,"mixedFiles");C([A("object")],S.prototype,"dragAndDrop");C([A("object")],S.prototype,"introPanelStyle");C([A("object")],S.prototype,"htmlWrappers");C([A("object")],S.prototype,"htmlClassUtilities");C([A("object")],S.prototype,"remarkable");C([A("object")],S.prototype,"focusMode");C([A("function")],S.prototype,"onMessage");C([A("function")],S.prototype,"onClearMessages");C([A("function")],S.prototype,"onComponentRender");C([A("function")],S.prototype,"onInput");C([A("function")],S.prototype,"onError");C([A("object")],S.prototype,"demo");C([A("object")],S.prototype,"_insertKeyViewStyles");customElements.define("deep-chat",S);export{S as DeepChat};
309
+ },{key:"addElements",value:function addElements(e,t,s,i,n,o){F.addElements(e,t.elementRef);var a=Ht.create(),l=de.addButtons(a,s,i,o);Qi.set(t.inputElementRef,a,n.elementRef,l),Ht.add(e,a);}},{key:"assignOnInput",value:function assignOnInput(e,t,s,i){t.onInput=function(n){setTimeout(function(){var o=s.getAllFileData(),a=i.inputElementRef.innerText.trim(),l=_defineProperty({},y,a);o&&(l.files=o.map(function(c){return c.file;})),Ct.onInput(e,l,n);});};}}]);}();var En=/*#__PURE__*/function(){function En(){_classCallCheck(this,En);}return _createClass(En,null,[{key:"createElements",value:function createElements(e,t,s){var i=document.createElement("div");i.id="chat-view";var n=new xe(e,t,s);t.websocket&&oe.createConnection(t,n);var o=new Lt(e,n,t,i);return F.addElements(i,n.elementRef,o.elementRef),i;}},{key:"render",value:function render(e,t,s,i){var n=En.createElements(e,s,i);t.replaceChildren(n),s.isCustomView()&&s.setUpView(n,t);}}]);}();var Hl="#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:\" \";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#deep-chat-openai-realtime-container{height:100%;width:100%}#deep-chat-openai-realtime-avatar-container{height:60%;width:100%;display:flex;justify-content:center;align-items:center}#deep-chat-openai-realtime-avatar{border-radius:50%;height:110px;border:1px solid rgb(215,215,215);padding:8px;-webkit-user-select:none;user-select:none;margin-top:20px}#deep-chat-openai-realtime-buttons-container{height:40%;display:flex;position:relative}.deep-chat-openai-realtime-button-container{height:100%;width:50%;display:flex;justify-content:center;align-items:center}.deep-chat-openai-realtime-button{width:70px;height:70px;border-radius:50%;display:flex;justify-content:center;align-items:center;cursor:pointer}.deep-chat-openai-realtime-button-default{background-color:#e3e3e3}.deep-chat-openai-realtime-button-default:hover{background-color:#d4d4d4}.deep-chat-openai-realtime-button-default:active{background-color:#c5c5c5}.deep-chat-openai-realtime-button-loading{opacity:.7;pointer-events:none}.deep-chat-openai-realtime-microphone-active{background-color:#ffe7e7}.deep-chat-openai-realtime-microphone-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-microphone-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-microphone>*{height:30px;width:30px}.deep-chat-openai-realtime-microphone-active>*{filter:brightness(0) saturate(100%) invert(35%) sepia(60%) saturate(1360%) hue-rotate(325deg) brightness(95%) contrast(92%)}.deep-chat-openai-realtime-toggle>*{height:32px;width:32px;padding-left:3px;filter:brightness(0) saturate(100%) invert(22%) sepia(0%) saturate(4537%) hue-rotate(208deg) brightness(105%) contrast(91%)}.deep-chat-openai-realtime-button-unavailable{opacity:.45;pointer-events:none}#deep-chat-openai-realtime-error{color:red;position:absolute;top:calc(50% + 40px);left:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;left:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:\" \";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.deep-chat-last-group-messages-active{height:100%}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border);border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:\"\";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child,.message-bubble>.partial-render-message>p:first-child,.html-wrapper>p:first-child{margin-top:0}.message-bubble>p:last-child,.message-bubble>.partial-render-message:last-child>p,.html-wrapper>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.role-hidden{display:none}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:3}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:2;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.tooltip{position:absolute;visibility:hidden;z-index:1;pointer-events:none;padding:5px 7px;background-color:#333;border-radius:5px;width:max-content}.tooltip-text{color:#fff;font-size:13px}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button-svg-text{padding:1px;height:1.65em;display:flex}.input-button-svg-text>svg{padding:.22rem}.input-button-svg-text>div{margin-left:2px}.input-button:hover,.input-button:focus-visible{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.input-button:active:not(:hover){background-color:transparent}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em;width:max-content}#custom-icon{height:100%;width:1.2em}.custom-button-container-default{color:#505050}.custom-button-container-default>.dropup-menu-item-icon{color:unset}.custom-button-container-default>svg{filter:brightness(0) saturate(100%) invert(39%) sepia(1%) saturate(0%) hue-rotate(83deg) brightness(93%) contrast(90%)}.custom-button-container-default>.dropup-menu-item-icon>svg{position:absolute;left:.2em}.custom-button-container-active{background-color:#edf7ff;color:#0285ff}.custom-button-container-active:hover,.custom-button-container-active:focus-visible{background-color:#def0ff}.custom-button-container-active:active{background-color:#d2eaff}.custom-button-container-active>svg{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.custom-button-container-disabled{color:#aeaeae;cursor:auto}.custom-button-container-disabled>div{pointer-events:none}.custom-button-container-disabled:hover,.custom-button-container-disabled:focus-visible{background-color:transparent}.custom-button-container-disabled:active{background-color:transparent}.custom-button-container-disabled>svg{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}.dropup-button>*{pointer-events:none}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:hover,.dropup-menu-item:focus-visible{background-color:#f3f3f3}.dropup-menu-item:active{background-color:#ebebeb}.dropup-menu-item:active:not(:hover){background-color:transparent}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}#dropup-menu-item-icon-element-custom{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.28em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%)}.dropup-menu-item-text{margin-left:.56em;margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}";var jl=Object.defineProperty,C=function C(r,e,t,s){for(var i=void 0,n=r.length-1,o;n>=0;n--)(o=r[n])&&(i=o(e,t,i)||i);return i&&jl(e,t,i),i;};var S=/*#__PURE__*/function(_Hi){function S(){var _this115;_classCallCheck(this,S);var e;_this115=_callSuper(this,S),_this115.getMessages=function(){return[];},_this115.submitUserMessage=function(){return console.warn("submitUserMessage failed - please wait for chat view to render before calling this property.");},_this115.addMessage=function(){return console.warn("addMessage failed - please wait for chat view to render before calling this property.");},_this115.updateMessage=function(){},_this115.clearMessages=function(){},_this115.focusInput=function(){return Is.focusFromParentElement(_this115._elementRef);},_this115.refreshMessages=function(){},_this115.scrollToBottom=function(){},_this115.disableSubmitButton=function(){},_this115.setPlaceholderText=function(){},_this115._hasBeenRendered=!1,_this115._auxiliaryStyleApplied=!1,_this115._elementRef=document.createElement("div"),_this115._elementRef.id="container",_this115.attachShadow({mode:"open"}).appendChild(_this115._elementRef),(e=_this115.shadowRoot)==null||e.appendChild(Le.buildElement()),ds.apply(Hl,_this115.shadowRoot),setTimeout(function(){_this115._hasBeenRendered||_this115.onRender();},20);return _this115;}_inherits(S,_Hi);return _createClass(S,[{key:"changeToChatView",value:function changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender();}// prettier-ignore
310
+ },{key:"onRender",value:function onRender(){var _this$_childElement;Hs.attemptAppendStyleSheetToHead(this.style),te.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=nl.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(ds.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),ds.applyDefaultStyleToComponent(this.style,this.chatStyle),te.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?Us.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):!(this._activeService instanceof k)||this._activeService.key?((_this$_childElement=this._childElement)!==null&&_this$_childElement!==void 0?_this$_childElement:this._childElement=this.children[0],En.render(this,this._elementRef,this._activeService,this._childElement)):this._activeService instanceof k&&ce.render(this._elementRef,this.changeToChatView.bind(this),this._activeService),this._hasBeenRendered||Ct.onRender(this),this._hasBeenRendered=!0;}},{key:"disconnectedCallback",value:function disconnectedCallback(){Cs.chat=void 0;}}]);}(Hi);C([A("object")],S.prototype,"connect");C([A("object")],S.prototype,"directConnection");C([A("object")],S.prototype,"webModel");C([A("object")],S.prototype,"requestBodyLimits");C([A("function")],S.prototype,"requestInterceptor");C([A("function")],S.prototype,"responseInterceptor");C([A("function")],S.prototype,"validateInput");C([A("function")],S.prototype,"loadHistory");C([A("object")],S.prototype,"chatStyle");C([A("object")],S.prototype,"attachmentContainerStyle");C([A("object")],S.prototype,"dropupStyles");C([A("object")],S.prototype,"inputAreaStyle");C([A("object")],S.prototype,"textInput");C([A("object")],S.prototype,"submitButtonStyles");C([A("object")],S.prototype,"customButtons");C([A("string")],S.prototype,"auxiliaryStyle");C([A("array")],S.prototype,"history");C([A("object")],S.prototype,"browserStorage");C([A("object")],S.prototype,"introMessage");C([A("object")],S.prototype,"avatars");C([A("object")],S.prototype,"names");C([A("object")],S.prototype,"displayLoadingBubble");C([A("object")],S.prototype,"errorMessages");C([A("object")],S.prototype,"messageStyles");C([A("object")],S.prototype,"textToSpeech");C([A("object")],S.prototype,"speechToText");C([A("object")],S.prototype,"images");C([A("object")],S.prototype,"gifs");C([A("object")],S.prototype,"camera");C([A("object")],S.prototype,"audio");C([A("object")],S.prototype,"microphone");C([A("object")],S.prototype,"mixedFiles");C([A("object")],S.prototype,"dragAndDrop");C([A("object")],S.prototype,"introPanelStyle");C([A("object")],S.prototype,"htmlWrappers");C([A("object")],S.prototype,"htmlClassUtilities");C([A("object")],S.prototype,"remarkable");C([A("object")],S.prototype,"focusMode");C([A("function")],S.prototype,"onMessage");C([A("function")],S.prototype,"onClearMessages");C([A("function")],S.prototype,"onComponentRender");C([A("function")],S.prototype,"onInput");C([A("function")],S.prototype,"onError");C([A("object")],S.prototype,"demo");C([A("object")],S.prototype,"_insertKeyViewStyles");customElements.define("deep-chat",S);export{S as DeepChat};