From 36f6e045ae318255ecc093aabd9c6607216231ea Mon Sep 17 00:00:00 2001 From: bruffridge Date: Tue, 13 Feb 2024 14:53:16 +0000 Subject: [PATCH] deploy: 6d765c87f4ab6691cb80f011b58f5c3be30843e0 --- build/bundle.js | 2 +- build/bundle.js.map | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/bundle.js b/build/bundle.js index 5554b25..b92f5eb 100644 --- a/build/bundle.js +++ b/build/bundle.js @@ -1,2 +1,2 @@ -var app=function(){"use strict";function e(){}function t(e){return e()}function n(){return Object.create(null)}function a(e){e.forEach(t)}function i(e){return"function"==typeof e}function r(e,t){return e!=e?t==t:e!==t||e&&"object"==typeof e||"function"==typeof e}function o(e,t){e.appendChild(t)}function s(e,t,n){e.insertBefore(t,n||null)}function l(e){e.parentNode&&e.parentNode.removeChild(e)}function c(e){return document.createElement(e)}function d(){return e=" ",document.createTextNode(e);var e}function u(e,t,n){null==n?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}function _(e,t,n){const a=t.toLowerCase();a in e?e[a]="boolean"==typeof e[a]&&""===n||n:t in e?e[t]="boolean"==typeof e[t]&&""===n||n:u(e,t,n)}let p;function m(e){p=e}function g(){if(!p)throw new Error("Function called outside component initialization");return p}const E=[],S=[];let h=[];const f=[],b=Promise.resolve();let v=!1;function T(e){h.push(e)}const y=new Set;let C=0;function R(){if(0!==C)return;const e=p;do{try{for(;C{n!==i&&e&&(A={r:0,c:[],p:A},function(e,t,n,a){if(e&&e.o){if(O.has(e))return;O.add(e),A.c.push((()=>{O.delete(e),a&&(n&&e.d(1),a())})),e.o(t)}else a&&a()}(e,1,1,(()=>{t.blocks[n]===e&&(t.blocks[n]=null)})),A.r||a(A.c),A=A.p)})):t.block.d(1),l.c(),I(l,1),l.m(t.mount(),t.anchor),c=!0),t.block=l,t.blocks&&(t.blocks[i]=l),c&&R()}if(!(r=e)||"object"!=typeof r&&"function"!=typeof r||"function"!=typeof r.then){if(t.current!==t.then)return i(t.then,1,t.value,e),!0;t.resolved=e}else{const n=g();if(e.then((e=>{m(n),i(t.then,1,t.value,e),m(null)}),(e=>{if(m(n),i(t.catch,2,t.error,e),m(null),!t.hasCatch)throw e})),t.current!==t.pending)return i(t.pending,0),!0}var r}function w(e,t){const n=e.$$;null!==n.fragment&&(!function(e){const t=[],n=[];h.forEach((a=>-1===e.indexOf(a)?t.push(a):n.push(a))),n.forEach((e=>e())),h=t}(n.after_update),a(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function x(e,t){-1===e.$$.dirty[0]&&(E.push(e),v||(v=!0,b.then(R)),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<{const a=n.length?n[0]:t;return S.ctx&&d(S.ctx[e],S.ctx[e]=a)&&(!S.skip_bound&&S.bound[e]&&S.bound[e](a),h&&x(r,e)),t})):[],S.update(),h=!0,a(S.before_update),S.fragment=!!c&&c(S.ctx),o.target){if(o.hydrate){const e=function(e){return Array.from(e.childNodes)}(o.target);S.fragment&&S.fragment.l(e),e.forEach(l)}else S.fragment&&S.fragment.c();o.intro&&I(r.$$.fragment),function(e,n,r){const{fragment:o,after_update:s}=e.$$;o&&o.m(n,r),T((()=>{const n=e.$$.on_mount.map(t).filter(i);e.$$.on_destroy?e.$$.on_destroy.push(...n):a(n),e.$$.on_mount=[]})),s.forEach(T)}(r,o.target,o.anchor),R()}m(E)}class L{$$=void 0;$$set=void 0;$destroy(){w(this,1),this.$destroy=e}$on(t,n){if(!i(n))return e;const a=this.$$.callbacks[t]||(this.$$.callbacks[t]=[]);return a.push(n),()=>{const e=a.indexOf(n);-1!==e&&a.splice(e,1)}}$set(e){var t;this.$$set&&(t=e,0!==Object.keys(t).length)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}function k(e){return function(e){if(Array.isArray(e))return U(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||F(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function P(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=F(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var a=0,i=function(){};return{s:i,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,r=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw r}}}}function F(e,t){if(e){if("string"==typeof e)return U(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U(e,t):void 0}}function U(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);n=0;--r){var o=this.tryEntries[r],s=o.completion;if("root"===o.tryLoc)return i("end");if(o.tryLoc<=this.prev){var l=a.call(o,"catchLoc"),c=a.call(o,"finallyLoc");if(l&&c){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&a.call(i,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),I(n),E}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var a=n.completion;if("throw"===a.type){var i=a.arg;I(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,a){return this.delegate={iterator:w(t),resultName:n,nextLoc:a},"next"===this.method&&(this.arg=e),E}},t}function W(e,t,n,a,i,r,o){try{var s=e[r](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(a,i)}function $(e){return function(){var t=this,n=arguments;return new Promise((function(a,i){var r=e.apply(t,n);function o(e){W(r,a,i,o,s,"next",e)}function s(e){W(r,a,i,o,s,"throw",e)}o(void 0)}))}}function K(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function Q(e){for(var t=1;t=t&&!e.PERMITTED_KEYS.has(n.key)&&!e.isKeyCombinationPermitted(n)&&n.preventDefault()}},{key:"isKeyCombinationPermitted",value:function(e){return"a"===e.key&&(e.ctrlKey||e.metaKey)}},{key:"onInput",value:function(e,t,n){var a=n.target,i=a.textContent||"";void 0!==e&&i.length>e&&(a.textContent=i.substring(0,e),ge.focusEndOfInput(a)),null==t||t()}}]),e}();de.PERMITTED_KEYS=new Set([le.BACKSPACE,le.DELETE,le.ARROW_RIGHT,le.ARROW_LEFT,le.ARROW_DOWN,le.ARROW_UP,le.META,le.CONTROL,le.ENTER]);var ue=de,_e=function(){function e(){J(this,e)}return te(e,null,[{key:"sanitizePastedTextContent",value:function(e){var t,n;e.preventDefault();var a=null==(t=e.clipboardData)?void 0:t.getData("text/plain");null==(n=document.execCommand)||n.call(document,"insertText",!1,a)}}]),e}(),pe=function(){function e(t,n){var a,i=this;J(this,e);var r=e.processConfig(n,t.textInput);this.elementRef=e.createContainerElement(null==(a=null==r?void 0:r.styles)?void 0:a.container),this.inputElementRef=this.createInputElement(r),this._config=r,this.elementRef.appendChild(this.inputElementRef),setTimeout((function(){var e;ue.add(i.inputElementRef,null==(e=t.textInput)?void 0:e.characterLimit,t._validationHandler)}))}return te(e,[{key:"createInputElement",value:function(t){var n,a,i,r=document.createElement("div");return r.id=e.TEXT_INPUT_ID,r.classList.add("text-input-styling","text-input-placeholder"),r.innerText=(null==(n=null==t?void 0:t.placeholder)?void 0:n.text)||"Ask me anything!",ce.IS_CHROMIUM&&e.preventAutomaticScrollUpOnNewLine(r),"boolean"==typeof(null==t?void 0:t.disabled)&&!0===t.disabled?(r.contentEditable="false",r.classList.add("text-input-disabled")):(r.contentEditable="true",this.addEventListeners(r,t)),Object.assign(r.style,null==(a=null==t?void 0:t.styles)?void 0:a.text),Object.assign(r.style,null==(i=null==t?void 0:t.placeholder)?void 0:i.style),r}},{key:"removeTextIfPlaceholder",value:function(){var t,n,a,i;this.inputElementRef.classList.contains("text-input-placeholder")&&!this.inputElementRef.classList.contains("text-input-disabled")&&(null!=(t=this._config.placeholder)&&t.style&&(re.unsetStyle(this.inputElementRef,null==(n=this._config.placeholder)?void 0:n.style),Object.assign(this.inputElementRef.style,null==(i=null==(a=this._config)?void 0:a.styles)?void 0:i.text)),e.clear(this.inputElementRef),this.inputElementRef.classList.remove("text-input-placeholder"))}},{key:"addEventListeners",value:function(e,t){var n,a,i;e.onfocus=this.onFocus.bind(this,null==(n=null==t?void 0:t.styles)?void 0:n.focus),null!=(a=null==t?void 0:t.styles)&&a.focus&&(e.onblur=this.onBlur.bind(this,t.styles.focus,null==(i=null==t?void 0:t.styles)?void 0:i.container)),e.addEventListener("keydown",this.onKeydown.bind(this)),e.onpaste=_e.sanitizePastedTextContent}},{key:"onFocus",value:function(e){var t=this;ce.IS_SAFARI?setTimeout((function(){t.removeTextIfPlaceholder()})):this.removeTextIfPlaceholder(),Object.assign(this.elementRef.style,e)}},{key:"onBlur",value:function(e,t){re.unsetStyle(this.elementRef,e),t&&Object.assign(this.elementRef.style,t)}},{key:"onKeydown",value:function(e){var t;e.key===le.ENTER&&!e.ctrlKey&&!e.shiftKey&&(e.preventDefault(),null==(t=this.submit)||t.call(this))}}],[{key:"processConfig",value:function(e,t){var n,a,i,r,o;return null!==(n=t)&&void 0!==n||(t={}),null!==(a=t.disabled)&&void 0!==a||(t.disabled=e.isTextInputDisabled),null!==(i=t.placeholder)&&void 0!==i||(t.placeholder={}),null!==(r=(o=t.placeholder).text)&&void 0!==r||(o.text=e.textInputPlaceholderText),t}},{key:"preventAutomaticScrollUpOnNewLine",value:function(e){var t;e.addEventListener("keydown",(function(){t=window.scrollY})),e.addEventListener("input",(function(){t!==window.scrollY&&window.scrollTo({top:t})}))}},{key:"clear",value:function(e){var t=window.scrollY;e.classList.contains("text-input-disabled")||(e.textContent=""),ce.IS_CHROMIUM&&window.scrollTo({top:t})}},{key:"toggleEditability",value:function(e,t){e.contentEditable=t?"true":"false"}},{key:"createContainerElement",value:function(e){var t=document.createElement("div");return t.id="text-input-container",Object.assign(t.style,e),t}}]),e}();pe.TEXT_INPUT_ID="text-input";var me=pe,ge=function(){function e(){J(this,e)}return te(e,null,[{key:"focusEndOfInput",value:function(e){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var n=window.getSelection();null==n||n.removeAllRanges(),null==n||n.addRange(t)}},{key:"focusFromParentElement",value:function(t){var n=t.querySelector("#".concat(me.TEXT_INPUT_ID));n&&e.focusEndOfInput(n)}}]),e}();function Ee(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Se(e,t,n,a){var i="\n".concat(Ee(t)," message: ").concat(JSON.stringify(e)," \n"),r=n?"".concat(Ee(t)," message after interceptor: ").concat(function(e){return e&&JSON.stringify(e)}(a)," \n"):"";return i+r}var he="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",fe={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(e,t,n,a){return"".concat(Se(e,t,n,a),"Make sure the ").concat(t," 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")},INVALID_MODEL_REQUEST:function(e,t){var n="request";return"".concat(Se(e,n,t),"Make sure the ").concat(n,' message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}')},INVALID_MODEL_RESPONSE:function(e,t,n){var a="response";return"".concat(Se(e,a,t,n),"Make sure the ").concat(a,' message is using the {text: string} format, e.g: {text: "Model Response"}')},INVALID_STREAM_EVENT:he,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(he)},be=function(){function e(){J(this,e)}return te(e,null,[{key:"addElements",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a=n-a-e.CODE_SNIPPET_GENERATION_JUMP}},{key:"cloneElement",value:function(e){var t=e.cloneNode(!0);return e.parentNode.replaceChild(t,e),t}},{key:"scrollToBottom",value:function(e){e.scrollTop=e.scrollHeight}},{key:"scrollToTop",value:function(e){e.scrollTop=0}}]),e}();be.CODE_SNIPPET_GENERATION_JUMP=.5;var ve=be,Te=function(){function e(){J(this,e)}return te(e,null,[{key:"speak",value:function(e,t){if(window.SpeechSynthesisUtterance){var n=new SpeechSynthesisUtterance(e);Object.assign(n,t),speechSynthesis.speak(n)}}},{key:"processConfig",value:function(t,n){var a={};setTimeout((function(){if("object"==Z(t)&&(t.lang&&(a.lang=t.lang),t.pitch&&(a.pitch=t.pitch),t.rate&&(a.rate=t.rate),t.volume&&(a.volume=t.volume),t.voiceName)){var e=window.speechSynthesis.getVoices().find((function(e){var n;return e.name.toLocaleLowerCase()===(null==(n=t.voiceName)?void 0:n.toLocaleLowerCase())}));e&&(a.voice=e)}n(a)}),e.LOAD_VOICES_MS)}}]),e}();Te.LOAD_VOICES_MS=200;var ye=Te,Ce=function(){function e(){J(this,e)}return te(e,null,[{key:"checkForContainerStyles",value:function(e,t){var n=e.containerStyle;n&&(Object.assign(t.style,n),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"))}},{key:"handleResponseProperty",value:function(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:"processInitialMessageFile",value:function(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(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(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"),{text:e}}},{key:"flagHTMLUpdateClass",value:function(e){var t;null!=(t=e.children[0])&&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"))}}]),e}(),Re=function(){function e(){J(this,e)}return te(e,null,[{key:"hide",value:function(t){t.getElementsByClassName(e.CONTAINER_CLASS)[0].style.visibility="hidden"}},{key:"applyCustomStylesToElements",value:function(e,t,n){Object.assign(e.style,n.container),Object.assign(t.style,n.avatar)}},{key:"applyCustomStyles",value:function(t,n,a,i){var r,o,s,l;if(null!=(r=a.default)&&r.styles&&e.applyCustomStylesToElements(t,n,a.default.styles),i===we.USER_ROLE)null!=(o=a.user)&&o.styles&&e.applyCustomStylesToElements(t,n,a.user.styles);else{null!=(s=a.ai)&&s.styles&&e.applyCustomStylesToElements(t,n,a.ai.styles);var c=null==(l=a[i])?void 0:l.styles;c&&e.applyCustomStylesToElements(t,n,c)}}},{key:"createAvatar",value:function(t,n){var a,i,r,o,s,l=document.createElement("img");t===we.USER_ROLE?l.src=(null==(a=null==n?void 0:n.user)?void 0:a.src)||(null==(i=null==n?void 0:n.default)?void 0:i.src)||"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==":l.src=(null==(r=null==n?void 0:n[t])?void 0:r.src)||(null==(o=null==n?void 0:n.ai)?void 0:o.src)||(null==(s=null==n?void 0:n.default)?void 0:s.src)||"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8c3ZnIGZpbGw9IiMwMDAwMDAiIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIAoJCXZpZXdCb3g9IjAgMCAzMiAzMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8cGF0aCBkPSJNMjMsMzAuMzZIOWMtMi40MDQsMC00LjM2LTEuOTU2LTQuMzYtNC4zNlYxNWMwLTIuNDA0LDEuOTU2LTQuMzYsNC4zNi00LjM2aDMuNjU5CgkJYzAuMTY3LTEuNTY2LDEuNDE1LTIuODEzLDIuOTgxLTIuOTgxVjUuMzMzYy0xLjEzMS0wLjE3NC0yLTEuMTU0LTItMi4zMzNjMC0xLjMwMSwxLjA1OS0yLjM2LDIuMzYtMi4zNgoJCWMxLjMwMiwwLDIuMzYsMS4wNTksMi4zNiwyLjM2YzAsMS4xNzktMC44NjksMi4xNTktMiwyLjMzM1Y3LjY2YzEuNTY2LDAuMTY3LDIuODE0LDEuNDE1LDIuOTgxLDIuOTgxSDIzCgkJYzIuNDA0LDAsNC4zNiwxLjk1Niw0LjM2LDQuMzZ2MTFDMjcuMzYsMjguNDA0LDI1LjQwNCwzMC4zNiwyMywzMC4zNnogTTksMTEuMzZjLTIuMDA3LDAtMy42NCwxLjYzMy0zLjY0LDMuNjR2MTEKCQljMCwyLjAwNywxLjYzMywzLjY0LDMuNjQsMy42NGgxNGMyLjAwNywwLDMuNjQtMS42MzMsMy42NC0zLjY0VjE1YzAtMi4wMDctMS42MzMtMy42NC0zLjY0LTMuNjRIOXogTTEzLjM4NCwxMC42NGg1LjIzMQoJCUMxOC40MzksOS4zNTQsMTcuMzM0LDguMzYsMTYsOC4zNkMxNC42NjcsOC4zNiwxMy41NjEsOS4zNTQsMTMuMzg0LDEwLjY0eiBNMTYsMS4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NAoJCVMxNS4wOTYsNC42NCwxNiw0LjY0YzAuOTA0LDAsMS42NC0wLjczNiwxLjY0LTEuNjRTMTYuOTA0LDEuMzYsMTYsMS4zNnogTTIwLDI3LjM2aC04Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2CgkJczEuMDU5LTIuMzYsMi4zNi0yLjM2aDhjMS4zMDIsMCwyLjM2LDEuMDU5LDIuMzYsMi4zNlMyMS4zMDIsMjcuMzYsMjAsMjcuMzZ6IE0xMiwyMy4zNmMtMC45MDQsMC0xLjY0LDAuNzM1LTEuNjQsMS42NAoJCXMwLjczNiwxLjY0LDEuNjQsMS42NGg4YzAuOTA0LDAsMS42NC0wLjczNSwxLjY0LTEuNjRzLTAuNzM1LTEuNjQtMS42NC0xLjY0SDEyeiBNMzEsMjMuODZoLTJjLTAuMTk5LDAtMC4zNi0wLjE2MS0wLjM2LTAuMzZWMTUKCQljMC0wLjE5OSwwLjE2MS0wLjM2LDAuMzYtMC4zNmgyYzAuMTk5LDAsMC4zNiwwLjE2MSwwLjM2LDAuMzZ2OC41QzMxLjM2LDIzLjY5OSwzMS4xOTksMjMuODYsMzEsMjMuODZ6IE0yOS4zNiwyMy4xNGgxLjI3OXYtNy43OAoJCUgyOS4zNlYyMy4xNHogTTMsMjMuODZIMWMtMC4xOTksMC0wLjM2LTAuMTYxLTAuMzYtMC4zNlYxNWMwLTAuMTk5LDAuMTYxLTAuMzYsMC4zNi0wLjM2aDJjMC4xOTksMCwwLjM2LDAuMTYxLDAuMzYsMC4zNnY4LjUKCQlDMy4zNiwyMy42OTksMy4xOTksMjMuODYsMywyMy44NnogTTEuMzYsMjMuMTRoMS4yOHYtNy43OEgxLjM2VjIzLjE0eiBNMjAsMjAuMzZjLTEuMzAyLDAtMi4zNi0xLjA1OS0yLjM2LTIuMzYKCQlzMS4wNTktMi4zNiwyLjM2LTIuMzZzMi4zNiwxLjA1OSwyLjM2LDIuMzZDMjIuMzYsMTkuMzAyLDIxLjMwMiwyMC4zNiwyMCwyMC4zNnogTTIwLDE2LjM2Yy0wLjkwNCwwLTEuNjQsMC43MzYtMS42NCwxLjY0CgkJczAuNzM1LDEuNjQsMS42NCwxLjY0czEuNjQtMC43MzUsMS42NC0xLjY0UzIwLjkwNCwxNi4zNiwyMCwxNi4zNnogTTEyLDIwLjM2Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2czEuMDU5LTIuMzYsMi4zNi0yLjM2CgkJczIuMzYsMS4wNTksMi4zNiwyLjM2QzE0LjM2LDE5LjMwMiwxMy4zMDEsMjAuMzYsMTIsMjAuMzZ6IE0xMiwxNi4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NHMwLjczNiwxLjY0LDEuNjQsMS42NAoJCXMxLjY0LTAuNzM1LDEuNjQtMS42NFMxMi45MDQsMTYuMzYsMTIsMTYuMzZ6Ii8+Cgk8cmVjdCBzdHlsZT0iZmlsbDpub25lOyIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIi8+Cjwvc3ZnPg==",l.classList.add("avatar");var c=document.createElement("div");return c.classList.add(e.CONTAINER_CLASS),c.appendChild(l),n&&e.applyCustomStyles(c,l,n,t),c}},{key:"getPosition",value:function(e,t){var n,a,i,r,o,s,l,c,d,u=null==(o=null==(r=null==t?void 0:t[e])?void 0:r.styles)?void 0:o.position;return e!==we.USER_ROLE&&(null!==(n=u)&&void 0!==n||(u=null==(l=null==(s=null==t?void 0:t.ai)?void 0:s.styles)?void 0:l.position)),null!==(a=u)&&void 0!==a||(u=null==(d=null==(c=null==t?void 0:t.default)?void 0:c.styles)?void 0:d.position),null!==(i=u)&&void 0!==i||(u=e===we.USER_ROLE?"right":"left"),u}},{key:"add",value:function(t,n,a){var i="boolean"==typeof a?void 0:a,r=e.createAvatar(n,i),o=e.getPosition(n,i);r.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",r)}}]),e}();Re.CONTAINER_CLASS="avatar-container";var Ne=Re,Oe=function(){function e(){J(this,e)}return te(e,null,[{key:"hide",value:function(t){t.getElementsByClassName(e.NAME_CLASS)[0].style.visibility="hidden"}},{key:"getPosition",value:function(e,t){var n,a,i,r,o,s,l=null==(r=null==t?void 0:t[e])?void 0:r.position;return e!==we.USER_ROLE&&(null!==(n=l)&&void 0!==n||(l=null==(o=null==t?void 0:t.ai)?void 0:o.position)),null!==(a=l)&&void 0!==a||(l=null==(s=null==t?void 0:t.default)?void 0:s.position),null!==(i=l)&&void 0!==i||(l=e===we.USER_ROLE?"right":"left"),l}},{key:"applyStyle",value:function(e,t,n){var a,i,r,o;Object.assign(e.style,null==(a=n.default)?void 0:a.style),t===we.USER_ROLE?Object.assign(e.style,null==(i=n.user)?void 0:i.style):(Object.assign(e.style,null==(r=n.ai)?void 0:r.style),Object.assign(e.style,null==(o=n[t])?void 0:o.style))}},{key:"getNameText",value:function(e,t){var n,a,i,r,o,s;return e===we.USER_ROLE?(null==(n=t.user)?void 0:n.text)||(null==(a=t.default)?void 0:a.text)||"User":e===we.AI_ROLE?(null==(i=t.ai)?void 0:i.text)||(null==(r=t.default)?void 0:r.text)||"AI":(null==(o=t[e])?void 0:o.text)||(null==(s=t.default)?void 0:s.text)||e}},{key:"createName",value:function(t,n){var a=document.createElement("div");return a.classList.add(e.NAME_CLASS),a.textContent=e.getNameText(t,n),e.applyStyle(a,t,n),a}},{key:"add",value:function(t,n,a){var i="boolean"==typeof a?{}:a,r=e.createName(n,i),o=e.getPosition(n,i);r.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",r)}}]),e}();Oe.NAME_CLASS="name";var Ae=Oe,Ie=function(){function e(){J(this,e)}return te(e,null,[{key:"getLastElementsByClass",value:function(e,t,n){for(var a,i=function(){var a=e[r];if(a.bubbleElement.classList.contains(t[0])&&!t.slice(1).find((function(e){return!a.bubbleElement.classList.contains(e)}))){if(!n)return{v:a};if(!n.find((function(e){return a.bubbleElement.classList.contains(e)})))return{v:a}}},r=e.length-1;r>=0;r-=1)if(a=i())return a.v}},{key:"getLastMessage",value:function(e,t,n){for(var a=e.length-1;a>=0;a-=1)if(e[a].role===t){if(!n)return e[a];if(e[a][n])return e[a]}}},{key:"getLastTextToElement",value:function(e,t){for(var n=e.length-1;n>=0;n-=1)if(e[n][0]===t)return e[n]}},{key:"overwriteMessage",value:function(t,n,a,i,r,o){var s=e.getLastElementsByClass(n,[e.getRoleClass(i),o],["loading-message-text"]),l=e.getLastMessage(t,i,r);return l&&(l[r]=a),s}},{key:"getRoleClass",value:function(e){return"".concat(e,"-message")}},{key:"fillEmptyMessageElement",value:function(t,n){0===n.trim().length&&(t.classList.add(e.EMPTY_MESSAGE_CLASS),t.innerHTML='
.
')}},{key:"unfillEmptyMessageElement",value:function(t,n){t.classList.contains(e.EMPTY_MESSAGE_CLASS)&&n.trim().length>0&&t.replaceChildren()}},{key:"getLastMessageBubbleElement",value:function(t){var n,a,i;return Array.from((null==(i=null==(a=null==(n=e.getLastMessageElement(t))?void 0:n.children)?void 0:a[0])?void 0:i.children)||[]).find((function(e){return e.classList.contains("message-bubble")}))}},{key:"getLastMessageElement",value:function(e){return e.children[e.children.length-1]}},{key:"addRoleElements",value:function(e,t,n,a){n&&Ne.add(e,t,n),a&&Ae.add(e,t,a)}},{key:"hideRoleElements",value:function(e,t,n){var a=e[e.length-1].innerContainer;t&&Ne.hide(a),n&&Ae.hide(a)}}]),e}();Ie.AI_ROLE="ai",Ie.USER_ROLE="user",Ie.EMPTY_MESSAGE_CLASS="empty-message";var De,we=Ie,xe=function(){function e(){J(this,e)}return te(e,null,[{key:"mouseUp",value:function(e,t){re.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t.default),Object.assign(e.style,t.hover)}},{key:"mouseDown",value:function(e,t){Object.assign(e.style,t.click)}},{key:"mouseLeave",value:function(e,t){re.unsetAllCSSMouseStates(e,t),Object.assign(e.style,t.default)}},{key:"mouseEnter",value:function(e,t){Object.assign(e.style,t.hover)}},{key:"add",value:function(t,n){t.addEventListener("mouseenter",e.mouseEnter.bind(this,t,n)),t.addEventListener("mouseleave",e.mouseLeave.bind(this,t,n)),t.addEventListener("mousedown",e.mouseDown.bind(this,t,n)),t.addEventListener("mouseup",e.mouseUp.bind(this,t,n))}}]),e}(),Me={"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"}}}},Le=Object.keys(Me),ke=function(){function e(){J(this,e)}return te(e,null,[{key:"applySuggestionEvent",value:function(e,t){setTimeout((function(){t.addEventListener("click",(function(){var n,a;null==(a=e.submitUserMessage)||a.call(e,{text:(null==(n=t.textContent)?void 0:n.trim())||""})}))}))}},{key:"isElementTemporary",value:function(e){var t;return!!e&&(null==(t=e.bubbleElement.children[0])?void 0:t.classList.contains("deep-chat-temporary-message"))}},{key:"doesElementContainDeepChatClass",value:function(e){return Le.find((function(t){return e.classList.contains(t)}))}},{key:"applyEvents",value:function(e,t){var n=Me[t].events;Object.keys(n||[]).forEach((function(t){e.addEventListener(t,null==n?void 0:n[t])}))}},{key:"getProcessedStyles",value:function(e,t,n){var a=Array.from(t.classList).reduce((function(t,n){var a,i=null==(a=e[n])?void 0:a.styles;return i&&e[n].styles&&t.push(i),t}),[]),i=Me[n].styles;if(i){var r=JSON.parse(JSON.stringify(i));r.default&&re.overwriteDefaultWithAlreadyApplied(r,t),a.unshift(r)}var o=re.mergeStatefulStyles(a);return re.processStateful(o,{},{})}},{key:"applyDeepChatUtilities",value:function(t,n,a){Le.forEach((function(t){var i=a.getElementsByClassName(t);Array.from(i||[]).forEach((function(a){var i=e.getProcessedStyles(n,a,t);Pe.applyStylesToElement(a,i),e.applyEvents(a,t)}))}));var i=a.getElementsByClassName("deep-chat-suggestion-button");Array.from(i).forEach((function(n){return e.applySuggestionEvent(t,n)}))}}]),e}(),Pe=function(){function e(){J(this,e)}return te(e,null,[{key:"applyStylesToElement",value:function(e,t){var n=re.processStateful(t,{},{});xe.add(e,n),Object.assign(e.style,n.default)}},{key:"applyEventsToElement",value:function(e,t){Object.keys(t).forEach((function(n){var a=t[n];a&&e.addEventListener(n,a)}))}},{key:"applyClassUtilitiesToElement",value:function(t,n){var a=n.events,i=n.styles;a&&e.applyEventsToElement(t,a),i&&!ke.doesElementContainDeepChatClass(t)&&e.applyStylesToElement(t,i)}},{key:"applyCustomClassUtilities",value:function(t,n){Object.keys(t).forEach((function(a){var i=n.getElementsByClassName(a);Array.from(i).forEach((function(n){t[a]&&e.applyClassUtilitiesToElement(n,t[a])}))}))}},{key:"apply",value:function(t,n){ke.applyDeepChatUtilities(t,t.htmlClassUtilities,n),e.applyCustomClassUtilities(t.htmlClassUtilities,n)}}]),e}(),Fe=function(){function e(){J(this,e)}return te(e,null,[{key:"addElement",value:function(e,t){e.elementRef.appendChild(t),e.elementRef.scrollTop=e.elementRef.scrollHeight}},{key:"createElements",value:function(e,t,n){var a=e.createNewMessageElement("",n);return a.bubbleElement.classList.add("html-message"),a.bubbleElement.innerHTML=t,a}},{key:"overwrite",value:function(e,t,n,a){var i=e.messages,r=we.overwriteMessage(i,a,t,n,"html","html-message");return r&&(r.bubbleElement.innerHTML=t,Pe.apply(e,r.outerContainer),Ce.flagHTMLUpdateClass(r.bubbleElement)),r}},{key:"add",value:function(t,n,a,i,r){var o;if(null!=r&&r.status){var s=this.overwrite(t,n,a,i);if(s)return s;r.status=!1}var l=e.createElements(t,n,a);return we.fillEmptyMessageElement(l.bubbleElement,n),Pe.apply(t,l.outerContainer),Ce.flagHTMLUpdateClass(l.bubbleElement),t.applyCustomStyles(l,a,!1,null==(o=t.messageStyles)?void 0:o.html),e.addElement(t,l.outerContainer),l}}]),e}();function Ue(e){return(De=De||document.createElement("textarea")).innerHTML="&"+e+";",De.value}var Be=Object.prototype.hasOwnProperty;function Ge(e){return[].slice.call(arguments,1).forEach((function(t){if(t){if("object"!=Z(t))throw new TypeError(t+"must be object");Object.keys(t).forEach((function(n){e[n]=t[n]}))}})),e}var Ye=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function He(e){return e.indexOf("\\")<0?e:e.replace(Ye,"$1")}function qe(e){return!(e>=55296&&e<=57343||e>=64976&&e<=65007||65535==(65535&e)||65534==(65535&e)||e>=0&&e<=8||11===e||e>=14&&e<=31||e>=127&&e<=159||e>1114111)}function Ve(e){if(e>65535){var t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}var ze=/&([a-z#][a-z0-9]{1,31});/gi,je=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function We(e,t){var n=0,a=Ue(t);return t!==a?a:35===t.charCodeAt(0)&&je.test(t)&&qe(n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10))?Ve(n):e}function $e(e){return e.indexOf("&")<0?e:e.replace(ze,We)}var Ke=/[&<>"]/,Qe=/[&<>"]/g,Xe={"&":"&","<":"<",">":">",'"':"""};function Ze(e){return Xe[e]}function Je(e){return Ke.test(e)?e.replace(Qe,Ze):e}var et={};function tt(e,t){return++t>=e.length-2?t:"paragraph_open"===e[t].type&&e[t].tight&&"inline"===e[t+1].type&&0===e[t+1].content.length&&"paragraph_close"===e[t+2].type&&e[t+2].tight?tt(e,t+2):t}et.blockquote_open=function(){return"
\n"},et.blockquote_close=function(e,t){return"
"+nt(e,t)},et.code=function(e,t){return e[t].block?"
"+Je(e[t].content)+"
"+nt(e,t):""+Je(e[t].content)+""},et.fence=function(e,t,n,a,i){var r,o,s=e[t],l="",c=n.langPrefix;if(s.params){if(o=(r=s.params.split(/\s+/g)).join(" "),function(e,t){return!!e&&Be.call(e,t)}(i.rules.fence_custom,r[0]))return i.rules.fence_custom[r[0]](e,t,n,a,i);l=' class="'+c+Je($e(He(o)))+'"'}return"
"+(n.highlight&&n.highlight.apply(n.highlight,[s.content].concat(r))||Je(s.content))+"
"+nt(e,t)},et.fence_custom={},et.heading_open=function(e,t){return""},et.heading_close=function(e,t){return"\n"},et.hr=function(e,t,n){return(n.xhtmlOut?"
":"
")+nt(e,t)},et.bullet_list_open=function(){return"
    \n"},et.bullet_list_close=function(e,t){return"
"+nt(e,t)},et.list_item_open=function(){return"
  • "},et.list_item_close=function(){return"
  • \n"},et.ordered_list_open=function(e,t){var n=e[t];return"1?' start="'+n.order+'"':"")+">\n"},et.ordered_list_close=function(e,t){return""+nt(e,t)},et.paragraph_open=function(e,t){return e[t].tight?"":"

    "},et.paragraph_close=function(e,t){var n=!(e[t].tight&&t&&"inline"===e[t-1].type&&!e[t-1].content);return(e[t].tight?"":"

    ")+(n?nt(e,t):"")},et.link_open=function(e,t,n){var a=e[t].title?' title="'+Je($e(e[t].title))+'"':"",i=n.linkTarget?' target="'+n.linkTarget+'"':"";return'"},et.link_close=function(){return""},et.image=function(e,t,n){var a=' src="'+Je(e[t].src)+'"',i=e[t].title?' title="'+Je($e(e[t].title))+'"':"";return""},et.table_open=function(){return"\n"},et.table_close=function(){return"
    \n"},et.thead_open=function(){return"\n"},et.thead_close=function(){return"\n"},et.tbody_open=function(){return"\n"},et.tbody_close=function(){return"\n"},et.tr_open=function(){return""},et.tr_close=function(){return"\n"},et.th_open=function(e,t){var n=e[t];return""},et.th_close=function(){return""},et.td_open=function(e,t){var n=e[t];return""},et.td_close=function(){return""},et.strong_open=function(){return""},et.strong_close=function(){return""},et.em_open=function(){return""},et.em_close=function(){return""},et.del_open=function(){return""},et.del_close=function(){return""},et.ins_open=function(){return""},et.ins_close=function(){return""},et.mark_open=function(){return""},et.mark_close=function(){return""},et.sub=function(e,t){return""+Je(e[t].content)+""},et.sup=function(e,t){return""+Je(e[t].content)+""},et.hardbreak=function(e,t,n){return n.xhtmlOut?"
    \n":"
    \n"},et.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"
    \n":"
    \n":"\n"},et.text=function(e,t){return Je(e[t].content)},et.htmlblock=function(e,t){return e[t].content},et.htmltag=function(e,t){return e[t].content},et.abbr_open=function(e,t){return''},et.abbr_close=function(){return""},et.footnote_ref=function(e,t){var n=Number(e[t].id+1).toString(),a="fnref"+n;return e[t].subId>0&&(a+=":"+e[t].subId),'['+n+"]"},et.footnote_block_open=function(e,t,n){return(n.xhtmlOut?'
    \n':'
    \n')+'
    \n
      \n'},et.footnote_block_close=function(){return"
    \n
    \n"},et.footnote_open=function(e,t){return'
  • '},et.footnote_close=function(){return"
  • \n"},et.footnote_anchor=function(e,t){var n="fnref"+Number(e[t].id+1).toString();return e[t].subId>0&&(n+=":"+e[t].subId),' '},et.dl_open=function(){return"
    \n"},et.dt_open=function(){return"
    "},et.dd_open=function(){return"
    "},et.dl_close=function(){return"
    \n"},et.dt_close=function(){return"\n"},et.dd_close=function(){return"\n"};var nt=et.getBreak=function(e,t){return(t=tt(e,t))"u"&&(a.abbreviations[":"+l]=c),o)}function lt(e){var t=$e(e);try{t=decodeURI(t)}catch(e){}return encodeURI(t)}function ct(e,t){var n,a,i,r=t,o=e.posMax;if(60===e.src.charCodeAt(t)){for(t++;t1||41===n&&--a<0)break;t++}return!(r===t||(i=He(e.src.slice(r,t)),!e.parser.validateLink(i)))&&(e.linkContent=i,e.pos=t,!0)}function dt(e,t){var n,a=t,i=e.posMax,r=e.src.charCodeAt(t);if(34!==r&&39!==r&&40!==r)return!1;for(t++,40===r&&(r=41);t"u"&&(a.references[_]={title:u,href:d}),o)}at.prototype.renderInline=function(e,t,n){for(var a=this.rules,i=e.length,r=0,o="";i--;)o+=a[e[r].type](e,r++,t,n,this);return o},at.prototype.render=function(e,t,n){for(var a=this.rules,i=e.length,r=-1,o="";++r=e.length)&&!vt.test(e[t])}function yt(e,t,n){return e.substr(0,t)+n+e.substr(t+1)}var Ct=[["block",function(e){e.inlineMode?e.tokens.push({type:"inline",content:e.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):e.block.parse(e.src,e.options,e.env,e.tokens)}],["abbr",function(e){var t,n,a,i,r=e.tokens;if(!e.inlineMode)for(t=1,n=r.length-1;t0?o[t].count:1,a=0;a=0;t--)if("text"===(r=i[t]).type){for(l=0,o=r.content,d.lastIndex=0,c=r.level,s=[];u=d.exec(o);)d.lastIndex>l&&s.push({type:"text",content:o.slice(l,u.index+u[1].length),level:c}),s.push({type:"abbr_open",title:e.env.abbreviations[":"+u[2]],level:c++}),s.push({type:"text",content:u[2],level:c}),s.push({type:"abbr_close",level:--c}),l=d.lastIndex-u[3].length;s.length&&(l=0;r--)if("inline"===e.tokens[r].type)for(t=(i=e.tokens[r].children).length-1;t>=0;t--)"text"===(n=i[t]).type&&(a=ht(a=n.content),gt.test(a)&&(a=a.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1—$2").replace(/(^|\s)--(\s|$)/gm,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1–$2")),n.content=a)}],["smartquotes",function(e){var t,n,a,i,r,o,s,l,c,d,u,_,p,m,g,E,S;if(e.options.typographer)for(S=[],g=e.tokens.length-1;g>=0;g--)if("inline"===e.tokens[g].type)for(E=e.tokens[g].children,S.length=0,t=0;t=0&&!(S[p].level<=s);p--);S.length=p+1,r=0,o=(a=n.content).length;e:for(;r=0&&(d=S[p],!(S[p].level=(i=e.eMarks[t])||42!==(n=e.src.charCodeAt(a++))&&45!==n&&43!==n||a=i||((n=e.src.charCodeAt(a++))<48||n>57))return-1;for(;;){if(a>=i)return-1;if(!((n=e.src.charCodeAt(a++))>=48&&n<=57)){if(41===n||46===n)break;return-1}}return a=this.eMarks[e]},Nt.prototype.skipEmptyLines=function(e){for(var t=this.lineMax;en;)if(t!==this.src.charCodeAt(--e))return e+1;return e},Nt.prototype.getLines=function(e,t,n,a){var i,r,o,s,l,c=e;if(e>=t)return"";if(c+1===t)return r=this.bMarks[c]+Math.min(this.tShift[c],n),o=a?this.eMarks[c]+1:this.eMarks[c],this.src.slice(r,o);for(s=new Array(t-e),i=0;cn&&(l=n),l<0&&(l=0),r=this.bMarks[c]+l,o=c+1]/,wt=/^<\/([a-zA-Z]{1,15})[\s>]/;function xt(e,t){var n=e.bMarks[t]+e.blkIndent,a=e.eMarks[t];return e.src.substr(n,a-n)}function Mt(e,t){var n,a,i=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return i>=r||126!==(a=e.src.charCodeAt(i++))&&58!==a||i===(n=e.skipSpaces(i))||n>=r?-1:n}var Lt=[["code",function(e,t,n){var a,i;if(e.tShift[t]-e.blkIndent<4)return!1;for(i=a=t+1;a=4))break;i=++a}return e.line=a,e.tokens.push({type:"code",content:e.getLines(t,i,4+e.blkIndent,!0),block:!0,lines:[t,e.line],level:e.level}),!0}],["fences",function(e,t,n,a){var i,r,o,s,l,c=!1,d=e.bMarks[t]+e.tShift[t],u=e.eMarks[t];if(d+3>u||126!==(i=e.src.charCodeAt(d))&&96!==i||(l=d,(r=(d=e.skipChars(d,i))-l)<3)||(o=e.src.slice(d,u).trim()).indexOf("`")>=0)return!1;if(a)return!0;for(s=t;!(++s>=n||(d=l=e.bMarks[s]+e.tShift[s],u=e.eMarks[s],d=4||(d=e.skipChars(d,i),d-lE||62!==e.src.charCodeAt(g++)||e.level>=e.options.maxNesting)return!1;if(a)return!0;for(32===e.src.charCodeAt(g)&&g++,l=e.blkIndent,e.blkIndent=0,s=[e.bMarks[t]],e.bMarks[t]=g,r=(g=g=E,o=[e.tShift[t]],e.tShift[t]=g-e.bMarks[t],u=e.parser.ruler.getRules("blockquote"),i=t+1;i=(E=e.eMarks[i]));i++)if(62!==e.src.charCodeAt(g++)){if(r)break;for(m=!1,_=0,p=u.length;_=E,o.push(e.tShift[i]),e.tShift[i]=g-e.bMarks[i];for(c=e.parentType,e.parentType="blockquote",e.tokens.push({type:"blockquote_open",lines:d=[t,0],level:e.level++}),e.parser.tokenize(e,t,i),e.tokens.push({type:"blockquote_close",level:--e.level}),e.parentType=c,d[1]=e.line,_=0;_l||42!==(i=e.src.charCodeAt(s++))&&45!==i&&95!==i)return!1;for(r=1;s=0)g=!0;else{if(!((u=Ot(e,t))>=0))return!1;g=!1}if(e.level>=e.options.maxNesting)return!1;if(m=e.src.charCodeAt(u-1),a)return!0;for(S=e.tokens.length,g?(d=e.bMarks[t]+e.tShift[t],p=Number(e.src.substr(d,u-d-1)),e.tokens.push({type:"ordered_list_open",order:p,lines:f=[t,0],level:e.level++})):e.tokens.push({type:"bullet_list_open",lines:f=[t,0],level:e.level++}),i=t,h=!1,v=e.parser.ruler.getRules("list");i=e.eMarks[i]?1:E-u)>4&&(_=1),_<1&&(_=1),r=u-e.bMarks[i]+_,e.tokens.push({type:"list_item_open",lines:b=[t,0],level:e.level++}),s=e.blkIndent,l=e.tight,o=e.tShift[t],c=e.parentType,e.tShift[t]=E-e.bMarks[t],e.blkIndent=r,e.tight=!0,e.parentType="list",e.parser.tokenize(e,t,n,!0),(!e.tight||h)&&(R=!1),h=e.line-t>1&&e.isEmpty(e.line-1),e.blkIndent=s,e.tShift[t]=o,e.tight=l,e.parentType=c,e.tokens.push({type:"list_item_close",level:--e.level}),i=t=e.line,b[1]=i,E=e.bMarks[t],!(i>=n||e.isEmpty(i)||e.tShift[i]d||91!==e.src.charCodeAt(c)||94!==e.src.charCodeAt(c+1)||e.level>=e.options.maxNesting)return!1;for(s=c+2;s=d||58!==e.src.charCodeAt(++s))&&(a||(s++,e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.refs||(e.env.footnotes.refs={}),l=e.src.slice(c+2,s-2),e.env.footnotes.refs[":"+l]=-1,e.tokens.push({type:"footnote_reference_open",label:l,level:e.level++}),i=e.bMarks[t],r=e.tShift[t],o=e.parentType,e.tShift[t]=e.skipSpaces(s)-s,e.bMarks[t]=s,e.blkIndent+=4,e.parentType="footnote",e.tShift[t]=l||(35!==(i=e.src.charCodeAt(s))||s>=l))return!1;for(r=1,i=e.src.charCodeAt(++s);35===i&&s6||ss&&32===e.src.charCodeAt(o-1)&&(l=o),e.line=t+1,e.tokens.push({type:"heading_open",hLevel:r,lines:[t,e.line],level:e.level}),s=n||e.tShift[o]3||(i=e.bMarks[o]+e.tShift[o],r=e.eMarks[o],i>=r)||(a=e.src.charCodeAt(i),45!==a&&61!==a)||(i=e.skipChars(i,a),i=e.skipSpaces(i),i3||s+2>=l||60!==e.src.charCodeAt(s))return!1;if(33===(i=e.src.charCodeAt(s+1))||63===i){if(a)return!0}else{if(47!==i&&!function(e){var t=32|e;return t>=97&&t<=122}(i))return!1;if(47===i){if(!(r=e.src.slice(s,l).match(wt)))return!1}else if(!(r=e.src.slice(s,l).match(Dt)))return!1;if(!0!==It[r[1].toLowerCase()])return!1;if(a)return!0}for(o=t+1;on||(l=t+1,e.tShift[l]=e.eMarks[l]||124!==(i=e.src.charCodeAt(o))&&45!==i&&58!==i||(r=xt(e,t+1),!/^[-:| ]+$/.test(r))||(c=r.split("|"))<=2)return!1;for(u=[],s=0;s=0;if(d=t+1,e.isEmpty(d)&&++d>n||e.tShift[d]=e.options.maxNesting)return!1;c=e.tokens.length,e.tokens.push({type:"dl_open",lines:l=[t,0],level:e.level++}),o=t,r=d;e:for(;;){for(S=!0,E=!1,e.tokens.push({type:"dt_open",lines:[o,o],level:e.level++}),e.tokens.push({type:"inline",content:e.getLines(o,o+1,e.blkIndent,!1).trim(),level:e.level+1,lines:[o,o],children:[]}),e.tokens.push({type:"dt_close",level:--e.level});;){if(e.tokens.push({type:"dd_open",lines:s=[d,0],level:e.level++}),g=e.tight,_=e.ddIndent,u=e.blkIndent,m=e.tShift[r],p=e.parentType,e.blkIndent=e.ddIndent=e.tShift[r]+2,e.tShift[r]=i-e.bMarks[r],e.tight=!0,e.parentType="deflist",e.parser.tokenize(e,r,n,!0),(!e.tight||E)&&(S=!1),E=e.line-r>1&&e.isEmpty(e.line-1),e.tShift[r]=m,e.tight=g,e.parentType=p,e.blkIndent=u,e.ddIndent=_,e.tokens.push({type:"dd_close",level:--e.level}),s[1]=d=e.line,d>=n||e.tShift[d]=n||(o=d,e.isEmpty(o))||e.tShift[o]=n||(e.isEmpty(r)&&r++,r>=n)||e.tShift[r]3)){for(i=!1,r=0,o=s.length;r=n||e.tShift[o]=0&&(e=e.replace(Pt,(function(t,n){var a;return 10===e.charCodeAt(n)?(r=n+1,o=0,t):(a=" ".slice((n-r-o)%4),o=n-r+1,a)}))),i=new Nt(e,this,t,n,a),this.tokenize(i,i.line,i.lineMax)};for(var Gt=[],Yt=0;Yt<256;Yt++)Gt.push(0);function Ht(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function qt(e,t){var n,a,i,r=t,o=!0,s=!0,l=e.posMax,c=e.src.charCodeAt(t);for(n=t>0?e.src.charCodeAt(t-1):-1;r=l&&(o=!1),(i=r-t)>=4?o=s=!1:((32===(a=r?@[]^_`{|}~-".split("").forEach((function(e){Gt[e.charCodeAt(0)]=1}));var Vt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var zt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var jt=["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"],Wt=/^<([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])?)*)>/,$t=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Kt(e,t){return e=e.source,t=t||"",function n(a,i){return a?(i=i.source||i,e=e.replace(a,i),n):new RegExp(e,t)}}var Qt=Kt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Xt=Kt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Qt)(),Zt=Kt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Xt)(),Jt=Kt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Zt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/|/)("processing",/<[?].*?[?]>/)("declaration",/]*>/)("cdata",//)();var en=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,tn=/^&([a-z][a-z0-9]{1,31});/i;var nn=[["text",function(e,t){for(var n=e.pos;n=0&&32===e.pending.charCodeAt(n))if(n>=1&&32===e.pending.charCodeAt(n-1)){for(var r=n-2;r>=0;r--)if(32!==e.pending.charCodeAt(r)){e.pending=e.pending.substring(0,r+1);break}e.push({type:"hardbreak",level:e.level})}else e.pending=e.pending.slice(0,-1),e.push({type:"softbreak",level:e.level});else e.push({type:"softbreak",level:e.level});for(i++;i=s||126!==e.src.charCodeAt(l+1)||e.level>=e.options.maxNesting||(r=l>0?e.src.charCodeAt(l-1):-1,o=e.src.charCodeAt(l+2),126===r)||126===o||32===o||10===o)return!1;for(a=l+2;al+3)return e.pos+=a-l,t||(e.pending+=e.src.slice(l,a)),!0;for(e.pos=l+2,i=1;e.pos+1=s||43!==e.src.charCodeAt(l+1)||e.level>=e.options.maxNesting||(r=l>0?e.src.charCodeAt(l-1):-1,o=e.src.charCodeAt(l+2),43===r)||43===o||32===o||10===o)return!1;for(a=l+2;a=s||61!==e.src.charCodeAt(l+1)||e.level>=e.options.maxNesting||(r=l>0?e.src.charCodeAt(l-1):-1,o=e.src.charCodeAt(l+2),61===r)||61===o||32===o||10===o)return!1;for(a=l+2;a=e.options.maxNesting)return!1;for(e.pos=d+n,s=[n];e.pos=i||e.level>=e.options.maxNesting)return!1;for(e.pos=r+1;e.pos=i||e.level>=e.options.maxNesting)return!1;for(e.pos=r+1;e.pos=e.options.maxNesting||(n=p+1,(a=ot(e,p))<0))return!1;if((s=a+1)<_&&40===e.src.charCodeAt(s)){for(s++;s<_&&(32===(c=e.src.charCodeAt(s))||10===c);s++);if(s>=_)return!1;for(p=s,ct(e,s)?(r=e.linkContent,s=e.pos):r="",p=s;s<_&&(32===(c=e.src.charCodeAt(s))||10===c);s++);if(s<_&&p!==s&&dt(e,s))for(o=e.linkContent,s=e.pos;s<_&&(32===(c=e.src.charCodeAt(s))||10===c);s++);else o="";if(s>=_||41!==e.src.charCodeAt(s))return e.pos=u,!1;s++}else{if(e.linkLevel>0)return!1;for(;s<_&&(32===(c=e.src.charCodeAt(s))||10===c);s++);if(s<_&&91===e.src.charCodeAt(s)&&(p=s+1,(s=ot(e,s))>=0?i=e.src.slice(p,s++):s=p-1),i||(Z(i)>"u"&&(s=a+1),i=e.src.slice(n,a)),!(l=e.env.references[ut(i)]))return e.pos=u,!1;r=l.href,o=l.title}return t||(e.pos=n,e.posMax=a,d?e.push({type:"image",src:r,title:o,alt:e.src.substr(n,a-n),level:e.level}):(e.push({type:"link_open",href:r,title:o,level:e.level++}),e.linkLevel++,e.parser.tokenize(e),e.linkLevel--,e.push({type:"link_close",level:--e.level}))),e.pos=s,e.posMax=_,!0}],["footnote_inline",function(e,t){var n,a,i,r,o=e.posMax,s=e.pos;return!(s+2>=o||94!==e.src.charCodeAt(s)||91!==e.src.charCodeAt(s+1)||e.level>=e.options.maxNesting||(n=s+2,a=ot(e,s+1),a<0))&&(t||(e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.list||(e.env.footnotes.list=[]),i=e.env.footnotes.list.length,e.pos=n,e.posMax=a,e.push({type:"footnote_ref",id:i,level:e.level}),e.linkLevel++,r=e.tokens.length,e.parser.tokenize(e),e.env.footnotes.list[i]={tokens:e.tokens.splice(r)},e.linkLevel--),e.pos=a+1,e.posMax=o,!0)}],["footnote_ref",function(e,t){var n,a,i,r,o=e.posMax,s=e.pos;if(s+3>o||!e.env.footnotes||!e.env.footnotes.refs||91!==e.src.charCodeAt(s)||94!==e.src.charCodeAt(s+1)||e.level>=e.options.maxNesting)return!1;for(a=s+2;a=o||(a++,n=e.src.slice(s+2,a-1),Z(e.env.footnotes.refs[":"+n])>"u"))&&(t||(e.env.footnotes.list||(e.env.footnotes.list=[]),e.env.footnotes.refs[":"+n]<0?(i=e.env.footnotes.list.length,e.env.footnotes.list[i]={label:n,count:0},e.env.footnotes.refs[":"+n]=i):i=e.env.footnotes.refs[":"+n],r=e.env.footnotes.list[i].count,e.env.footnotes.list[i].count++,e.push({type:"footnote_ref",id:i,subId:r,level:e.level})),e.pos=a,e.posMax=o,!0)}],["autolink",function(e,t){var n,a,i,r,o,s=e.pos;return!(60!==e.src.charCodeAt(s)||(n=e.src.slice(s),n.indexOf(">")<0))&&((a=n.match($t))?!(jt.indexOf(a[1].toLowerCase())<0||(r=a[0].slice(1,-1),o=lt(r),!e.parser.validateLink(r)))&&(t||(e.push({type:"link_open",href:o,level:e.level}),e.push({type:"text",content:r,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=a[0].length,!0):!!(i=n.match(Wt))&&(o=lt("mailto:"+(r=i[0].slice(1,-1))),!!e.parser.validateLink(o)&&(t||(e.push({type:"link_open",href:o,level:e.level}),e.push({type:"text",content:r,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=i[0].length,!0)))}],["htmltag",function(e,t){var n,a,i,r=e.pos;return!(!e.options.html||(i=e.posMax,60!==e.src.charCodeAt(r)||r+2>=i)||(n=e.src.charCodeAt(r+1),33!==n&&63!==n&&47!==n&&!function(e){var t=32|e;return t>=97&&t<=122}(n))||(a=e.src.slice(r).match(Jt),!a))&&(t||e.push({type:"htmltag",content:e.src.slice(r,r+a[0].length),level:e.level}),e.pos+=a[0].length,!0)}],["entity",function(e,t){var n,a,i=e.pos,r=e.posMax;if(38!==e.src.charCodeAt(i))return!1;if(i+10)e.pos=n;else{for(t=0;t=r)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},an.prototype.parse=function(e,t,n,a){var i=new rt(e,this,t,n,a);this.tokenize(i)};var on={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","replacements","smartquotes","references","abbr2","footnote_tail"]},block:{rules:["blockquote","code","fences","footnote","heading","hr","htmlblock","lheading","list","paragraph","table"]},inline:{rules:["autolink","backticks","del","emphasis","entity","escape","footnote_ref","htmltag","links","newline","text"]}}},full:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{},block:{},inline:{}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","abbr2"]},block:{rules:["blockquote","code","fences","heading","hr","htmlblock","lheading","list","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","htmltag","links","newline","text"]}}}};function sn(e,t,n){this.src=t,this.env=n,this.options=e.options,this.tokens=[],this.inlineMode=!1,this.inline=e.inline,this.block=e.block,this.renderer=e.renderer,this.typographer=e.typographer}function ln(e,t){"string"!=typeof e&&(t=e,e="default"),t&&null!=t.linkify&&console.warn("linkify option is removed. Use linkify plugin instead:\n\nimport Remarkable from 'remarkable';\nimport linkify from 'remarkable/linkify';\nnew Remarkable().use(linkify)\n"),this.inline=new an,this.block=new kt,this.core=new Rt,this.renderer=new at,this.ruler=new it,this.options={},this.configure(on[e]),this.set(t||{})}ln.prototype.set=function(e){Ge(this.options,e)},ln.prototype.configure=function(e){var t=this;if(!e)throw new Error("Wrong `remarkable` preset, check name/content");e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach((function(n){e.components[n].rules&&t[n].ruler.enable(e.components[n].rules,!0)}))},ln.prototype.use=function(e,t){return e(this,t),this},ln.prototype.parse=function(e,t){var n=new sn(this,e,t);return this.core.process(n),n.tokens},ln.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},ln.prototype.parseInline=function(e,t){var n=new sn(this,e,t);return n.inlineMode=!0,this.core.process(n),n.tokens},ln.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var cn=function(){function e(){J(this,e)}return te(e,null,[{key:"instantiate",value:function(){var e=window.hljs;return new ln(e?{highlight:function(t,n){if(n&&e.getLanguage(n))try{return e.highlight(n,t).value}catch(e){console.error("failed to setup the highlight dependency")}try{return e.highlightAuto(t).value}catch(e){console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"_blank",typographer:!0}:{highlight:function(e){return e},linkTarget:"_blank"})}},{key:"createNew",value:function(){var t=e.instantiate();return t.inline.validateLink=function(){return!0},t}}]),e}(),dn=function(){function e(){J(this,e)}return te(e,null,[{key:"addMessage",value:function(e,t,n,a){var i;e.elementRef.appendChild(t.outerContainer),e.applyCustomStyles(t,a,!0,null==(i=e.messageStyles)?void 0:i[n]),e.elementRef.scrollTop=e.elementRef.scrollHeight}},{key:"wrapInLink",value:function(t,n,a){var i=document.createElement("a");return i.href=n,i.download=a||e.DEFAULT_FILE_NAME,i.target="_blank",i.appendChild(t),i}},{key:"isNonLinkableDataUrl",value:function(e,t){return!(!t.startsWith("data")||"image"===e)&&("any"===e&&t.startsWith("data:text/javascript")||!t.startsWith("data:image"))}},{key:"processContent",value:function(t,n,a,i){return!a||e.isNonLinkableDataUrl(t,a)?n:e.wrapInLink(n,a,i)}},{key:"waitToLoadThenScroll",value:function(e){setTimeout((function(){e.scrollTop=e.scrollHeight}),60)}},{key:"scrollDownOnImageLoad",value:function(t,n){if(t.startsWith("data"))e.waitToLoadThenScroll(n);else try{fetch(t,{mode:"no-cors"}).catch((function(){})).finally((function(){e.waitToLoadThenScroll(n)}))}catch(e){n.scrollTop=n.scrollHeight}}},{key:"reAddFileRefToObject",value:function(e,t){var n;null==(n=e.files)||n.forEach((function(e,n){var a;e.ref&&null!=(a=t.message.files)&&a[n]&&(t.message.files[n].ref=e.ref)}))}},{key:"removeFileRef",value:function(e){var t=Q({},e);return delete t.ref,t}}]),e}();dn.DEFAULT_FILE_NAME="file";var un=dn,_n=function(){function e(){J(this,e)}return te(e,null,[{key:"onNewMessage",value:function(e,t,n){var a,i=JSON.parse(JSON.stringify({message:t,isInitial:n}));un.reAddFileRefToObject(t,i),null==(a=e.onNewMessage)||a.call(e,i),e.dispatchEvent(new CustomEvent("new-message",{detail:i}))}},{key:"onClearMessages",value:function(e){var t;null==(t=e.onClearMessages)||t.call(e),e.dispatchEvent(new CustomEvent("clear-messages"))}},{key:"onRender",value:function(e){var t;null==(t=e.onComponentRender)||t.call(e,e),e.dispatchEvent(new CustomEvent("render",{detail:e}))}},{key:"onError",value:function(e,t){var n;null==(n=e.onError)||n.call(e,t),e.dispatchEvent(new CustomEvent("error",{detail:t}))}}]),e}(),pn=function(){function e(){J(this,e)}return te(e,null,[{key:"applyCustomStylesToElements",value:function(e,t,n){if(n&&(Object.assign(e.outerContainer.style,n.outerContainer),Object.assign(e.innerContainer.style,n.innerContainer),Object.assign(e.bubbleElement.style,n.bubble),t)){var a=e.bubbleElement.children[0],i="a"!==a.tagName.toLocaleLowerCase()?a:a.children[0];Object.assign(i.style,n.media)}}},{key:"applySideStyles",value:function(t,n,a,i){i&&(e.applyCustomStylesToElements(t,a,i.shared),n===we.USER_ROLE?e.applyCustomStylesToElements(t,a,i.user):(e.applyCustomStylesToElements(t,a,i.ai),e.applyCustomStylesToElements(t,a,i[n])))}},{key:"isMessageSideStyles",value:function(e){return!!(e.ai||e.shared||e.user)}},{key:"applyCustomStyles",value:function(t,n,a,i,r){var o;r&&t.default!==r?e.isMessageSideStyles(r)?(e.applySideStyles(n,a,i,t.default),e.applySideStyles(n,a,i,r)):(e.applyCustomStylesToElements(n,i,null==(o=t.default)?void 0:o.shared),e.applyCustomStylesToElements(n,i,r)):e.applySideStyles(n,a,i,t.default)}},{key:"extractParticularSharedStyles",value:function(e,t){if(null!=t&&t.shared){var n=t.shared,a={outerContainer:{},innerContainer:{},bubble:{},media:{}};return e.forEach((function(e){var t,i,r,o;a.outerContainer[e]=(null==(t=n.outerContainer)?void 0:t[e])||"",a.innerContainer[e]=(null==(i=n.innerContainer)?void 0:i[e])||"",a.bubble[e]=(null==(r=n.bubble)?void 0:r[e])||"",a.media[e]=(null==(o=n.media)?void 0:o[e])||""})),a}}}]),e}(),mn=function(){function e(t){var n=this;J(this,e),this.messageElementRefs=[],this.messages=[],this.htmlClassUtilities={},this.textElementsToText=[],this.elementRef=e.createContainerElement(),this.messageStyles=t.messageStyles,this._remarkable=cn.createNew(),this._avatars=t.avatars,this._names=t.names,this._onNewMessage=_n.onNewMessage.bind(this,t),t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),setTimeout((function(){n.submitUserMessage=t.submitUserMessage}))}return te(e,[{key:"addNewTextMessage",value:function(e,t,n){if(null!=n&&n.status){var a=this.overwriteText(t,e,this.messageElementRefs);if(a)return a;n.status=!1}var i=this.createAndAppendNewMessageElement(e,t);return i.bubbleElement.classList.add("text-message"),this.applyCustomStyles(i,t,!1),we.fillEmptyMessageElement(i.bubbleElement,e),this.textElementsToText.push([i,e]),i}},{key:"overwriteText",value:function(e,t,n){var a=we.overwriteMessage(this.messages,n,t,e,"text","text-message");if(a){this.renderText(a.bubbleElement,t);var i=we.getLastTextToElement(this.textElementsToText,a);i&&(i[1]=t)}return a}},{key:"createAndAppendNewMessageElement",value:function(e,t){var n=this,a=this.createNewMessageElement(e,t);return this.elementRef.appendChild(a.outerContainer),setTimeout((function(){return ve.scrollToBottom(n.elementRef)})),a}},{key:"createNewMessageElement",value:function(t,n){var a;null==(a=this._introPanel)||a.hide();var i=this.messageElementRefs[this.messageElementRefs.length-1];return e.isTemporaryElement(i)&&(i.outerContainer.remove(),this.messageElementRefs.pop()),this.createMessageElements(t,n)}},{key:"createMessageElements",value:function(t,n){var a=e.createBaseElements(),i=a.outerContainer,r=a.innerContainer,o=a.bubbleElement;return i.appendChild(r),this.addInnerContainerElements(o,t,n),this.messageElementRefs.push(a),a}},{key:"addInnerContainerElements",value:function(e,t,n){var a;return(null==(a=this.messages[this.messages.length-1])?void 0:a.role)===n&&!this.isLastMessageError()&&we.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names),e.classList.add("message-bubble",we.getRoleClass(n),n===we.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(e,t),we.addRoleElements(e,n,this._avatars,this._names),{bubbleElement:e}}},{key:"applyCustomStyles",value:function(e,t,n,a){e&&this.messageStyles&&pn.applyCustomStyles(this.messageStyles,e,t,n,a)}},{key:"removeLastMessage",value:function(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}},{key:"isLastMessageError",value:function(){var e;return null==(e=we.getLastMessageBubbleElement(this.elementRef))?void 0:e.classList.contains("error-message-text")}},{key:"sendClientUpdate",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];null==(t=this._onNewMessage)||t.call(this,e,n)}},{key:"renderText",value:function(e,t){e.innerHTML=this._remarkable.render(t),0===e.innerText.trim().length&&(e.innerText=t)}},{key:"refreshTextMessages",value:function(){var e=this;this._remarkable=cn.createNew(),this.textElementsToText.forEach((function(t){e.renderText(t[0].bubbleElement,t[1])}))}}],[{key:"createContainerElement",value:function(){var e=document.createElement("div");return e.id="messages",e}},{key:"isTemporaryElement",value:function(e){return(null==e?void 0:e.bubbleElement.classList.contains("loading-message-text"))||ke.isElementTemporary(e)}},{key:"createBaseElements",value:function(){var e=document.createElement("div"),t=document.createElement("div");t.classList.add("inner-message-container"),e.appendChild(t),e.classList.add("outer-message-container");var n=document.createElement("div");return n.classList.add("message-bubble"),t.appendChild(n),{outerContainer:e,innerContainer:t,bubbleElement:n}}},{key:"createMessageContent",value:function(e){var t=e.text,n=e.files,a=e.html,i=e._sessionId,r={role:e.role||we.AI_ROLE};return t&&(r.text=t),n&&(r.files=n),a&&(r.html=a),!t&&!n&&!a&&(r.text=""),i&&(r._sessionId=i),r}}]),e}(),gn=function(){function e(t){J(this,e),this._fileAdded=!1,this._streamedContent="",this._streamType="",this._hasStreamEnded=!1,this._messages=t}return te(e,[{key:"upsertStreamedMessage",value:function(e){var t;if(!this._hasStreamEnded){if(void 0===(null==e?void 0:e.text)&&void 0===(null==e?void 0:e.html))return console.error(fe.INVALID_STREAM_EVENT);var n=(null==e?void 0:e.text)||(null==e?void 0:e.html)||"",a=ve.isScrollbarAtBottomOfElement(this._messages.elementRef),i=void 0!==(null==e?void 0:e.text)?"text":"html";if(this._elements||""!==this._streamedContent){if(this._streamType!==i)return console.error(fe.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(n,i,null==(t=this._elements)?void 0:t.bubbleElement,null==e?void 0:e.overwrite)}else this.setInitialState(i,n,null==e?void 0:e.role);a&&ve.scrollToBottom(this._messages.elementRef)}}},{key:"setInitialState",value:function(t,n,a){var i;this._streamType=t,null!==(i=a)&&void 0!==i||(a=we.AI_ROLE),this._elements="text"===t?this._messages.addNewTextMessage(n,a):Fe.add(this._messages,n,a,this._messages.messageElementRefs),this._elements.bubbleElement.classList.add(e.MESSAGE_CLASS),this._streamedContent=n,this._activeMessageRole=a}},{key:"updateBasedOnType",value:function(e,t,n){var a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];we.unfillEmptyMessageElement(n,e),("text"===t?this.updateText:this.updateHTML).bind(this)(e,n,a)}},{key:"updateText",value:function(e,t,n){this._streamedContent=n?e:this._streamedContent+e,this._messages.textElementsToText[this._messages.textElementsToText.length-1][1]=this._streamedContent,this._messages.renderText(t,this._streamedContent)}},{key:"updateHTML",value:function(t,n,a){if(a)this._streamedContent=t,n.innerHTML=t;else{var i=document.createElement("span");i.innerHTML=t,n.appendChild(i),this._streamedContent=e.HTML_CONTENT_PLACEHOLDER}}},{key:"finaliseStreamedMessage",value:function(){var t,n,a=this._messages.textElementsToText;if(!this._fileAdded||this._elements){if(!this._elements)throw Error(fe.NO_VALID_STREAM_EVENTS_SENT);if(null!=(t=this._elements.bubbleElement)&&t.classList.contains(e.MESSAGE_CLASS)){var i={role:this._activeMessageRole||we.AI_ROLE};"text"===this._streamType?(a[a.length-1][1]=this._streamedContent,i.text=this._streamedContent,this._messages.textToSpeech&&ye.speak(this._streamedContent,this._messages.textToSpeech)):"html"===this._streamType&&(this._streamedContent===e.HTML_CONTENT_PLACEHOLDER&&(this._streamedContent=(null==(n=this._elements.bubbleElement)?void 0:n.innerHTML)||""),this._elements&&Pe.apply(this._messages,this._elements.outerContainer),i.html=this._streamedContent),i&&(this._messages.messages.push(i),this._messages.sendClientUpdate(mn.createMessageContent(i),!1)),this._hasStreamEnded=!0}}}},{key:"markFileAded",value:function(){this._fileAdded=!0}}]),e}();gn.MESSAGE_CLASS="streamed-message",gn.HTML_CONTENT_PLACEHOLDER="htmlplaceholder";var En=gn,Sn=function(){function e(){J(this,e)}var t,n;return te(e,null,[{key:"tempRemoveContentHeader",value:(n=$(j().mark((function t(n,a,i){var r,o;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(null!=n&&n.headers){t.next=2;break}throw new Error("Request settings have not been set up");case 2:return r=n.headers[e.CONTENT_TYPE],delete n.headers[e.CONTENT_TYPE],t.prev=4,t.next=7,a(i);case 7:o=t.sent,t.next=13;break;case 10:throw t.prev=10,t.t0=t.catch(4),n.headers[e.CONTENT_TYPE]=r,t.t0;case 13:return t.abrupt("return",(n.headers[e.CONTENT_TYPE]=r,o));case 14:case"end":return t.stop()}}),t,null,[[4,10]])}))),function(e,t,a){return n.apply(this,arguments)})},{key:"displayError",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"Service error, please try again.";if(console.error(t),"object"==Z(t))return 0===Object.keys(t).length?e.addNewErrorMessage("service",n):e.addNewErrorMessage("service",JSON.stringify(t));e.addNewErrorMessage("service",t)}},{key:"fetch",value:function(e){function t(t,n,a,i){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e,t,n,a){var i,r,o={method:(null==(i=e.requestSettings)?void 0:i.method)||"POST",headers:t};return"GET"!==o.method&&(o.body=n?JSON.stringify(a):a),e.requestSettings.credentials&&(o.credentials=e.requestSettings.credentials),fetch((null==(r=e.requestSettings)?void 0:r.url)||e.url||"",o)}))},{key:"processResponseByType",value:function(e){var t=e.headers.get("content-type");return null!=t&&t.includes("application/json")?e.json():null!=t&&t.includes("text/plain")||!t?e:e.blob()}},{key:"processRequestInterceptor",value:(t=$(j().mark((function e(t,n){var a,i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null==(a=t.requestInterceptor)?void 0:a.call(t,n);case 2:if(e.t0=e.sent,e.t0){e.next=5;break}e.t0=n;case 5:return i=e.t0,r=i,o=i,e.abrupt("return",{body:r.body,headers:r.headers,error:o.error});case 9:case"end":return e.stop()}}),e)}))),function(e,n){return t.apply(this,arguments)})},{key:"validateResponseFormat",value:function(e){return e&&"object"==Z(e)&&("string"==typeof e.error||"string"==typeof e.text||"string"==typeof e.html||Array.isArray(e.files))}},{key:"onInterceptorError",value:function(e,t,n){e.addNewErrorMessage("service",t),null==n||n()}}]),e}();Sn.CONTENT_TYPE="Content-Type";var hn=Sn;function fn(e,t){return bn.apply(this,arguments)}function bn(){return(bn=$(j().mark((function e(t,n){var a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:a=t.getReader();case 1:return e.next=3,a.read();case 3:if((i=e.sent).done){e.next=7;break}n(i.value);case 5:e.next=1;break;case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function vn(e){var t,n,a,i=!1;return function(r){void 0===t?(t=r,n=0,a=-1):t=function(e,t){var n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}(t,r);for(var o=t.length,s=0;n0){var s=i.decode(r.subarray(0,o)),l=o+(32===r[o+1]?2:1),c=i.decode(r.subarray(l));switch(s){case"data":a.data=a.data?a.data+"\n"+c:c;break;case"event":a.event=c;break;case"id":e(a.id=c);break;case"retry":var d=parseInt(c,10);isNaN(d)||t(a.retry=d)}}}}var yn=globalThis&&globalThis.__rest||function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(a=Object.getOwnPropertySymbols(e);i3&&void 0!==T[3])||T[3],_={body:a,headers:null==(o=n.requestSettings)?void 0:o.headers},t.next=4,hn.processRequestInterceptor(n.deepChat,_);case 4:if(p=t.sent,m=p.body,g=p.headers,E=p.error,S=n.streamHandlers,h=S.onOpen,f=S.onClose,b=S.abortStream,!E){t.next=14;break}return t.abrupt("return",hn.onInterceptorError(i,E,f));case 14:if(null==(s=n.requestSettings)||!s.handler){t.next=16;break}return t.abrupt("return",xn.stream(n,m,i));case 16:if((null==(l=n.requestSettings)?void 0:l.url)!==Dn.URL){t.next=18;break}return t.abrupt("return",Dn.requestStream(i,n.streamHandlers));case 18:v=new En(i),Nn((null==(c=n.requestSettings)?void 0:c.url)||n.url||"",{method:(null==(d=n.requestSettings)?void 0:d.method)||"POST",headers:g,credentials:null==(u=n.requestSettings)?void 0:u.credentials,body:r?JSON.stringify(m):m,openWhenHidden:!0,onopen:function(e){return $(j().mark((function t(){return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!e.ok){t.next=2;break}return t.abrupt("return",h());case 2:return t.next=4,hn.processResponseByType(e);case 4:throw t.sent;case 5:case"end":return t.stop()}}),t)})))()},onmessage:function(t){return $(j().mark((function a(){var r,o,s,l,c;return j().wrap((function(a){for(;;)switch(a.prev=a.next){case 0:if(JSON.stringify(t.data)===JSON.stringify("[DONE]")){a.next=9;break}try{l=JSON.parse(t.data)}catch(e){l={}}return a.next=4,null==(o=(r=n.deepChat).responseInterceptor)?void 0:o.call(r,l);case 4:if(a.t0=a.sent,a.t0){a.next=7;break}a.t0=l;case 7:c=a.t0,null==(s=n.extractResultData)||s.call(n,c).then((function(t){e.upsertWFiles(i,v.upsertStreamedMessage.bind(v),v,t)})).catch((function(e){return hn.displayError(i,e)}));case 9:case"end":return a.stop()}}),a)})))()},onerror:function(e){throw f(),e},onclose:function(){v.finaliseStreamedMessage(),f()},signal:b.signal}).catch((function(e){var t;null==(t=n.extractResultData)||t.call(n,e).then((function(){hn.displayError(i,e)})).catch((function(e){hn.displayError(i,e)}))}));case 20:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"simulate",value:function(t,n,a){var i=n;if((a.files||a.html)&&t.addNewMessage(Q({sendUpdate:!1,ignoreText:!0},a),!1),a.text){n.onOpen();var r=a.text.split("");e.populateMessages(r,new En(t),i)}}},{key:"populateMessages",value:function(t,n,a){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=t[i];if(r){n.upsertStreamedMessage({text:r});var o=setTimeout((function(){e.populateMessages(t,n,a,i+1)}),a.simulationInterim||6);a.abortStream.abort=function(){e.abort(o,n,a.onClose)}}else n.finaliseStreamedMessage(),a.onClose()}},{key:"isSimulation",value:function(e){return"object"==Z(e)&&!!e.simulation}},{key:"isSimulatable",value:function(t,n){return e.isSimulation(t)&&n&&(n.text||n.html)}},{key:"abort",value:function(e,t,n){clearTimeout(e),t.finaliseStreamedMessage(),n()}},{key:"upsertWFiles",value:function(e,t,n,a){if(null!=a&&a.text||null!=a&&a.html){var i,r=t(a);null!==(i=n)&&void 0!==i||(n=r||void 0)}null!=a&&a.files&&(e.addNewMessage({files:a.files}),null==n||n.markFileAded())}}]),e}(),In=function(){function e(){J(this,e)}return te(e,null,[{key:"generateResponse",value:function(e){var t=e.messages[e.messages.length-1];if(t.files&&t.files.length>0){if(t.files.length>1)return"These are interesting files!";var n=t.files[0];return n.src&&n.src.startsWith("data:image/gif")?"That is a nice gif!":"image"===n.type?"That is a nice image!":"audio"===n.type?"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(e,t){return"function"==typeof e?e(t):e}},{key:"getResponse",value:function(t){return t.customDemoResponse?e.getCustomResponse(t.customDemoResponse,t.messages[t.messages.length-1]):{text:e.generateResponse(t)}}},{key:"request",value:function(t,n){var a=e.getResponse(n);setTimeout($(j().mark((function e(){var i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null==(r=(i=t.deepChat).responseInterceptor)?void 0:r.call(i,a);case 2:if(e.t0=e.sent,e.t0){e.next=5;break}e.t0=a;case 5:(o=e.t0).error?(n.addNewErrorMessage("service",o.error),t.completionsHandlers.onFinish()):An.isSimulatable(t.deepChat.stream,o)?An.simulate(n,t.streamHandlers,o):(n.addNewMessage(o),t.completionsHandlers.onFinish());case 7:case"end":return e.stop()}}),e)}))),400)}},{key:"requestStream",value:function(t,n){setTimeout((function(){var a=e.getResponse(t);An.simulate(t,n,a)}),400)}}]),e}();In.URL="deep-chat-demo";var Dn=In,wn=function(){function e(){J(this,e)}var t;return te(e,null,[{key:"setup",value:function(e){e.requestSettings.url!==Dn.URL&&(e.permittedErrorPrefixes=["Connection error","Error in server message"],e.websocket="pending")}},{key:"createConnection",value:function(t,n){if(document.body.contains(t.deepChat)){var a=t.requestSettings.websocket;if(a){if(t.requestSettings.handler)return xn.websocket(t,n);try{var i="boolean"!=typeof a?a:void 0,r=new WebSocket(t.requestSettings.url||"",i);t.websocket=r,t.websocket.onopen=function(){var a,i;n.removeError(),t.websocket&&"object"==Z(t.websocket)&&e.assignListeners(t,r,n),null==(i=(a=t.deepChat)._validationHandler)||i.call(a)},t.websocket.onerror=function(a){console.error(a),e.retryConnection(t,n)}}catch(i){console.error(i),e.retryConnection(t,n)}}}}},{key:"retryConnection",value:function(t,n){var a,i;null==(i=(a=t.deepChat)._validationHandler)||i.call(a),document.body.contains(t.deepChat)&&(t.websocket="pending",n.isLastMessageError()||n.addNewErrorMessage("service","Connection error"),setTimeout((function(){e.createConnection(t,n)}),5e3))}},{key:"assignListeners",value:function(t,n,a){var i=this,r={};n.onmessage=function(){var n=$(j().mark((function n(o){var s,l,c,d,u,_,p;return j().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!t.extractResultData){n.next=20;break}return n.prev=1,c=JSON.parse(o.data),n.next=5,null==(l=(s=t.deepChat).responseInterceptor)?void 0:l.call(s,c);case 5:if(n.t0=n.sent,n.t0){n.next=8;break}n.t0=c;case 8:return d=n.t0,n.next=11,t.extractResultData(d);case 11:if((u=n.sent)&&"object"==Z(u)){n.next=14;break}throw Error(fe.INVALID_RESPONSE(c,"server",!!t.deepChat.responseInterceptor,d));case 14:An.isSimulation(t.deepChat.stream)?(_=e.stream.bind(i,t,a,r),p=r[c.role||we.AI_ROLE],An.upsertWFiles(a,_,p,u)):a.addNewMessage(u),n.next=20;break;case 17:n.prev=17,n.t1=n.catch(1),hn.displayError(a,n.t1,"Error in server message");case 20:case"end":return n.stop()}}),n,null,[[1,17]])})));return function(e){return n.apply(this,arguments)}}(),n.onclose=function(){console.error("Connection closed"),a.isLastMessageError()||a.addNewErrorMessage("service","Connection error"),t.deepChat.stream&&t.streamHandlers.abortStream.abort(),e.createConnection(t,a)}}},{key:"sendWebsocket",value:(t=$(j().mark((function t(n,a,i){var r,o,s,l,c,d,u,_,p,m=arguments;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=!(m.length>3&&void 0!==m[3])||m[3],(l=n.websocket)&&"pending"!==l){t.next=4;break}return t.abrupt("return");case 4:return c={body:a,headers:null==(o=n.requestSettings)?void 0:o.headers},t.next=7,hn.processRequestInterceptor(n.deepChat,c);case 7:if(d=t.sent,u=d.body,!(_=d.error)){t.next=12;break}return t.abrupt("return",i.addNewErrorMessage("service",_));case 12:if(e.isWebSocket(l)){t.next=14;break}return t.abrupt("return",l.newUserMessage.listener(u));case 14:if(p=r?JSON.stringify(u):u,(null==(s=n.requestSettings)?void 0:s.url)!==Dn.URL){t.next=17;break}return t.abrupt("return",Dn.request(n,i));case 17:void 0===l.readyState||l.readyState!==l.OPEN?(console.error("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error")):(l.send(JSON.stringify(p)),n.completionsHandlers.onFinish());case 18:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"canSendMessage",value:function(t){return!t||"pending"!==t&&(e.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}},{key:"isWebSocket",value:function(e){return void 0!==e.send}},{key:"stream",value:function(e,t,n,a){if(a){var i=e.deepChat.stream.simulation;if("string"==typeof i){var r,o=a.role||we.AI_ROLE,s=n[o];a.text===i?(null==s||s.finaliseStreamedMessage(),delete n[o]):(null!==(r=n[o])&&void 0!==r||(n[o]=new En(t)),n[o].upsertStreamedMessage(a))}else An.simulate(t,e.streamHandlers,a)}}}]),e}(),xn=function(){function e(){J(this,e)}var t;return te(e,null,[{key:"request",value:(t=$(j().mark((function t(n,a,i){var r,o,s,l,c;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:s=!0,l=function(){var e=$(j().mark((function e(t){var a,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s){e.next=2;break}return e.abrupt("return");case 2:return s=!1,e.next=5,null==(r=(a=n.deepChat).responseInterceptor)?void 0:r.call(a,t);case 5:if(e.t0=e.sent,e.t0){e.next=8;break}e.t0=t;case 8:o=e.t0,hn.validateResponseFormat(o)?"string"==typeof o.error?(console.error(o.error),i.addNewErrorMessage("service",o.error),n.completionsHandlers.onFinish()):An.isSimulatable(n.deepChat.stream,o)?An.simulate(i,n.streamHandlers,o):(i.addNewMessage(o),n.completionsHandlers.onFinish()):(console.error(fe.INVALID_RESPONSE(t,"server",!!n.deepChat.responseInterceptor,o)),i.addNewErrorMessage("service","Error in server message"),n.completionsHandlers.onFinish());case 10:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),c=e.generateOptionalSignals(),null==(o=(r=n.requestSettings).handler)||o.call(r,a,Q(Q({},c),{},{onResponse:l}));case 3:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"attemptToFinaliseStream",value:function(e,t){try{e.finaliseStreamedMessage()}catch(e){console.error(e),t.addNewErrorMessage("service",e)}}},{key:"stream",value:function(t,n,a){var i,r,o=!0,s=!1,l=new En(a);t.streamHandlers.abortStream.abort=function(){e.attemptToFinaliseStream(l,a),t.streamHandlers.onClose(),o=!1};var c=e.generateOptionalSignals();null==(r=(i=t.requestSettings).handler)||r.call(i,n,Q(Q({},c),{},{onOpen:function(){s||!o||(t.streamHandlers.onOpen(),s=!0)},onResponse:function(e){o&&(e&&"object"==Z(e)?e.error?(console.error(e.error),a.addNewErrorMessage("service",e.error),t.streamHandlers.onClose(),o=!1):An.upsertWFiles(a,l.upsertStreamedMessage.bind(l),l,e):console.error(fe.INVALID_RESPONSE(e,"server",!1)))},onClose:function(){o&&(e.attemptToFinaliseStream(l,a),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked}))}},{key:"websocket",value:function(t,n){var a,i,r=this,o={isOpen:!1,newUserMessage:{listener:function(){}},roleToStream:{}};t.websocket=o;var s=function(){var e=$(j().mark((function e(a){var i,s,l,c,d;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o.isOpen){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,null==(s=(i=t.deepChat).responseInterceptor)?void 0:s.call(i,a);case 4:if(e.t0=e.sent,e.t0){e.next=7;break}e.t0=a;case 7:l=e.t0,hn.validateResponseFormat(l)?"string"==typeof l.error?(console.error(l.error),n.isLastMessageError()||n.addNewErrorMessage("service",l.error)):An.isSimulation(t.deepChat.stream)?(c=wn.stream.bind(r,t,n,o.roleToStream),d=o.roleToStream[a.role||we.AI_ROLE],An.upsertWFiles(n,c,d,a)):n.addNewMessage(l):(console.error(fe.INVALID_RESPONSE(a,"server",!!t.deepChat.responseInterceptor,l)),n.addNewErrorMessage("service","Error in server message"));case 9:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),l=e.generateOptionalSignals();null==(i=(a=t.requestSettings).handler)||i.call(a,void 0,Q(Q({},l),{},{onOpen:function(){n.removeError(),o.isOpen=!0},onResponse:s,onClose:function(){o.isOpen=!1},newUserMessage:o.newUserMessage}))}},{key:"generateOptionalSignals",value:function(){return{onClose:function(){},onOpen:function(){},stopClicked:{listener:function(){}},newUserMessage:{listener:function(){}}}}}]),e}(),Mn=function(){function e(){J(this,e)}var t,n;return te(e,null,[{key:"request",value:(n=$(j().mark((function e(t,n,a){var i,r,o,s,l,c,d,u,_,p,m,g,E=arguments;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=!(E.length>3&&void 0!==E[3])||E[3],l={body:n,headers:null==(r=t.requestSettings)?void 0:r.headers},e.next=4,hn.processRequestInterceptor(t.deepChat,l);case 4:if(c=e.sent,d=c.body,u=c.headers,_=c.error,p=t.completionsHandlers.onFinish,!_){e.next=11;break}return e.abrupt("return",hn.onInterceptorError(a,_,p));case 11:if(null==(o=t.requestSettings)||!o.handler){e.next=13;break}return e.abrupt("return",xn.request(t,d,a));case 13:if((null==(s=t.requestSettings)?void 0:s.url)!==Dn.URL){e.next=15;break}return e.abrupt("return",Dn.request(t,a));case 15:m=!0,(g=hn.fetch.bind(this,t,u,i))(d).then((function(e){return m=!!e.ok,e})).then((function(e){return hn.processResponseByType(e)})).then(function(){var e=$(j().mark((function e(n){var i,r,o,s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.extractResultData){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,null==(r=(i=t.deepChat).responseInterceptor)?void 0:r.call(i,n);case 4:if(e.t0=e.sent,e.t0){e.next=7;break}e.t0=n;case 7:return o=e.t0,e.next=10,t.extractResultData(o,g,d);case 10:if(s=e.sent,m){e.next=13;break}throw n;case 13:if(s&&"object"==Z(s)){e.next=15;break}throw Error(fe.INVALID_RESPONSE(n,"response",!!t.deepChat.responseInterceptor,o));case 15:s.makingAnotherRequest||(An.isSimulatable(t.deepChat.stream,s)?An.simulate(a,t.streamHandlers,s):(a.addNewMessage(s),p()));case 16:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()).catch((function(e){hn.displayError(a,e),p()}));case 18:case"end":return e.stop()}}),e,this)}))),function(e,t,a){return n.apply(this,arguments)})},{key:"executePollRequest",value:function(t,n,a,i){var r=t.completionsHandlers.onFinish;fetch(n,a).then((function(e){return e.json()})).then(function(){var o=$(j().mark((function o(s){var l,c,d;return j().wrap((function(o){for(;;)switch(o.prev=o.next){case 0:if(t.extractPollResultData){o.next=2;break}return o.abrupt("return");case 2:return o.t0=t,o.next=5,null==(c=(l=t.deepChat).responseInterceptor)?void 0:c.call(l,s);case 5:if(o.t1=o.sent,o.t1){o.next=8;break}o.t1=s;case 8:return o.t2=o.t1,o.next=11,o.t0.extractPollResultData.call(o.t0,o.t2);case 11:(d=o.sent).timeoutMS?setTimeout((function(){e.executePollRequest(t,n,a,i)}),d.timeoutMS):An.isSimulatable(t.deepChat.stream,s)?An.simulate(i,t.streamHandlers,d):(i.addNewMessage(d),r());case 13:case"end":return o.stop()}}),o)})));return function(e){return o.apply(this,arguments)}}()).catch((function(e){hn.displayError(i,e),r()}))}},{key:"poll",value:(t=$(j().mark((function t(n,a,i){var r,o,s,l,c,d,u,_,p,m,g,E,S,h=arguments;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=!(h.length>3&&void 0!==h[3])||h[3],c={body:a,headers:null==(o=n.requestSettings)?void 0:o.headers},t.next=4,hn.processRequestInterceptor(n.deepChat,c);case 4:if(d=t.sent,u=d.body,_=d.headers,!(p=d.error)){t.next=10;break}return t.abrupt("return",hn.onInterceptorError(i,p));case 10:m=(null==(s=n.requestSettings)?void 0:s.url)||n.url||"",g=(null==(l=n.requestSettings)?void 0:l.method)||"POST",E=r?JSON.stringify(u):u,S={method:g,body:E,headers:_},n.requestSettings.credentials&&(S.credentials=n.requestSettings.credentials),e.executePollRequest(n,m,S,i);case 12:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"verifyKey",value:function(e,t,n,a,i,r,o,s,l){if(""===e)return r(fe.INVALID_KEY);o(),fetch(t,{method:a,headers:n,body:l||null}).then((function(e){return hn.processResponseByType(e)})).then((function(t){s(t,e,i,r)})).catch((function(e){r(fe.CONNECTION_FAILED),console.error(e)}))}}]),e}(),Ln=function(){function e(){J(this,e)}return te(e,null,[{key:"getCharacterLimitMessages",value:function(e,t){var n;if(-1===t)return e;for(var a=0,i=e.length-1;i>=0;i-=1){var r=null==(n=e[i])?void 0:n.text;if(void 0!==r&&(a+=r.length)>t){e[i].text=r.substring(0,r.length-(a-t));break}}return e.slice(Math.max(i,0))}},{key:"getMaxMessages",value:function(e,t){return e.slice(Math.max(e.length-t,0))}},{key:"processMessages",value:function(t,n,a){return void 0!==n?n>0&&(t=e.getMaxMessages(t,n)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===a?t:e.getCharacterLimitMessages(t,a)}}]),e}(),kn=function(){function e(){J(this,e)}return te(e,null,[{key:"parseConfig",value:function(e,t,n,a){var i,r={files:t};if("object"==Z(a)){var o=a.files,s=a.request,l=a.button;o&&(o.infoModal&&(r.files.infoModal=o.infoModal,null!=(i=o.infoModal)&&i.textMarkDown&&(r.infoModalTextMarkUp=n.render(o.infoModal.textMarkDown))),o.acceptedFormats&&(r.files.acceptedFormats=o.acceptedFormats),o.maxNumberOfFiles&&(r.files.maxNumberOfFiles=o.maxNumberOfFiles)),r.button=l,s&&(s.headers||s.method||s.url||s.credentials||e.headers||e.method||e.url||e.credentials)&&(r.request={url:(null==s?void 0:s.url)||e.url,method:(null==s?void 0:s.method)||e.method,headers:(null==s?void 0:s.headers)||e.headers,credentials:(null==s?void 0:s.credentials)||e.credentials})}return r}},{key:"processMixedFiles",value:function(t,n,a){if(a){t.fileTypes.mixedFiles=e.parseConfig(t.requestSettings,{acceptedFormats:""},n,a)}}},{key:"processMicrophone",value:function(t,n,a,i){var r,o,s,l,c,d,u,_,p=Q({acceptedFormats:"audio/*"},(null==(s=t.fileTypes.audio)?void 0:s.files)||{});a&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=e.parseConfig(t.requestSettings,p,n,a),"object"==Z(a)&&a.files&&(null!==(r=(l=t.recordAudio).files)&&void 0!==r||(l.files={}),t.recordAudio.files.format=null==(c=a.files)?void 0:c.format,t.recordAudio.files.maxDurationSeconds=null==(d=a.files)?void 0:d.maxDurationSeconds,null!=(u=t.fileTypes.audio)&&u.files&&(null!==(o=(_=t.fileTypes.audio.files).maxNumberOfFiles)&&void 0!==o||(_.maxNumberOfFiles=a.files.maxNumberOfFiles)))):i||(t.fileTypes.audio=e.parseConfig(t.requestSettings,p,n,a)))}},{key:"processAudioConfig",value:function(t,n,a,i){if(a||i){var r=Q({acceptedFormats:"audio/*"},(null==i?void 0:i.files)||{});t.fileTypes.audio=e.parseConfig(t.requestSettings,r,n,a)}}},{key:"processGifConfig",value:function(t,n,a,i){if(a||i){var r=Q({acceptedFormats:"image/gif"},(null==i?void 0:i.files)||{});t.fileTypes.gifs=e.parseConfig(t.requestSettings,r,n,a)}}},{key:"processCamera",value:function(t,n,a,i){var r,o,s,l,c,d=Q({acceptedFormats:"image/*"},(null==(o=t.fileTypes.images)?void 0:o.files)||{});a&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=e.parseConfig(t.requestSettings,d,n,a),"object"==Z(a)&&(t.camera.modalContainerStyle=a.modalContainerStyle,a.files&&(null!==(r=(s=t.camera).files)&&void 0!==r||(s.files={}),t.camera.files.format=null==(l=a.files)?void 0:l.format,t.camera.files.dimensions=null==(c=a.files)?void 0:c.dimensions))):i||(t.fileTypes.images=e.parseConfig(t.requestSettings,d,n,a)))}},{key:"processImagesConfig",value:function(t,n,a,i){if(a||i){var r=Q({acceptedFormats:"image/*"},(null==i?void 0:i.files)||{});t.fileTypes.images=e.parseConfig(t.requestSettings,r,n,a)}}},{key:"populateDefaultFileIO",value:function(e,t){var n,a,i,r,o;e&&(null!==(n=e.files)&&void 0!==n||(e.files={}),null!==(a=(r=e.files).acceptedFormats)&&void 0!==a||(r.acceptedFormats=t),null!==(i=(o=e.files).maxNumberOfFiles)&&void 0!==i||(o.maxNumberOfFiles=1))}},{key:"set",value:function(t,n,a){e.populateDefaultFileIO(null==a?void 0:a.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),e.populateDefaultFileIO(null==a?void 0:a.images,".png,.jpg");var i=cn.createNew();e.processImagesConfig(n,i,t.images,null==a?void 0:a.images),e.processCamera(n,i,t.camera,t.images),e.processGifConfig(n,i,t.gifs,null==a?void 0:a.gifs),e.processAudioConfig(n,i,t.audio,null==a?void 0:a.audio),e.processMicrophone(n,i,t.microphone,t.audio),e.processMixedFiles(n,i,t.mixedFiles)}}]),e}(),Pn=function(){function e(t,n,a){var i,r,o,s,l;J(this,e),this.rawBody={},this.validateConfigKey=!1,this.canSendMessage=e.canSendMessage,this.requestSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=a,Object.assign(this.rawBody,null==(r=t.request)?void 0:r.additionalBodyProps),this.totalMessagesMaxCharLength=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.totalMessagesMaxCharLength,this.maxMessages=null==(s=null==t?void 0:t.requestBodyLimits)?void 0:s.maxMessages,kn.set(t,this,n),t.request&&(this.requestSettings=t.request),this.demo&&(null!==(i=(l=this.requestSettings).url)&&void 0!==i||(l.url=Dn.URL)),this.requestSettings.websocket&&wn.setup(this)}var t,n,a,i,r,o;return te(e,[{key:"verifyKey",value:function(e,t){}},{key:"getServiceIOByType",value:function(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:(o=$(j().mark((function e(t,n){var a,i,r=arguments;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=!(r.length>2&&void 0!==r[2])||r[2],i=this.deepChat.stream,e.abrupt("return",i&&!An.isSimulation(i)?An.request(this,t,n):Mn.request(this,t,n,a));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return o.apply(this,arguments)})},{key:"callAPIWithText",value:(r=$(j().mark((function e(t,n){var a,i,r,o,s,l,c,d;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return c=Q({messages:n},this.rawBody),d=!1,null!=(r=this.requestSettings.headers)&&r["Content-Type"]||(null!==(a=(o=this.requestSettings).headers)&&void 0!==a||(o.headers={}),null!==(i=(s=this.requestSettings.headers)["Content-Type"])&&void 0!==i||(s["Content-Type"]="application/json"),d=!0),e.next=5,this.request(c,t);case 5:d&&(null==(l=this.requestSettings.headers)||delete l["Content-Type"]);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"callApiWithFiles",value:(i=$(j().mark((function t(n,a,i){var r,o,s;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.createCustomFormDataBody(this.rawBody,a,i),o=this.requestSettings,s=this.getServiceIOByType(i[0]),this.requestSettings=(null==s?void 0:s.request)||this.requestSettings,t.next=4,this.request(r,n,!1);case 4:this.requestSettings=o;case 5:case"end":return t.stop()}}),t,this)}))),function(e,t,n){return i.apply(this,arguments)})},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:a?this.callApiWithFiles(t,n,a):this.callAPIWithText(t,n);case 1:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"callAPI",value:(n=$(j().mark((function e(t,n){var a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=Ln.processMessages(n.messages,this.maxMessages,this.totalMessagesMaxCharLength),this.requestSettings.websocket?(i=Q({messages:a},this.rawBody),wn.sendWebsocket(this,i,n,!1)):this.callServiceAPI(n,a,t.files);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"extractResultData",value:(t=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:if(!t.result){e.next=4;break}return e.abrupt("return",Ce.handleResponseProperty(t));case 4:if(!hn.validateResponseFormat(t)){e.next=6;break}return e.abrupt("return",t);case 6:case"end":return e.stop()}}),e)}))),function(e){return t.apply(this,arguments)})},{key:"isDirectConnection",value:function(){return!1}},{key:"isWebModel",value:function(){return!1}}],[{key:"canSendMessage",value:function(e,t,n){return!!n||(!(!e||""===e.trim())||!!(t&&t.length>0))}},{key:"createCustomFormDataBody",value:function(e,t,n){var a=new FormData;n.forEach((function(e){return a.append("files",e)})),Object.keys(e).forEach((function(t){return a.append(t,String(e[t]))}));var i=0;t.slice(0,t.length-1).forEach((function(e){a.append("message".concat(i+=1),JSON.stringify(e))}));var r=t[t.length-1];return r.text&&(delete r.files,a.append("message".concat(i+=1),JSON.stringify(r))),a}}]),e}(),Fn=function(e){function t(e,n,a,i,r){var o,s;return J(this,t),(o=G(this,t,[e,r])).insertKeyPlaceholderText="API Key",o.keyHelpUrl="",Object.assign(o.rawBody,null==(s=e.request)?void 0:s.additionalBodyProps),o.keyVerificationDetails=n,o.buildHeadersFunc=a,i&&o.setApiKeyProperties(i),o.requestSettings=o.buildRequestSettings(o.key||"",e.request),o}return V(t,e),te(t,[{key:"setApiKeyProperties",value:function(e){this.key=e.key,e.validateKeyProperty&&(this.validateConfigKey=e.validateKeyProperty)}},{key:"buildRequestSettings",value:function(e,t){var n,a=null!=t?t:{};return null!==(n=a.headers)&&void 0!==n||(a.headers={}),Object.assign(a.headers,this.buildHeadersFunc(e)),a}},{key:"keyAuthenticated",value:function(e,t){this.requestSettings=this.buildRequestSettings(t,this.requestSettings),this.key=t,e()}},{key:"verifyKey",value:function(e,t){var n=this.keyVerificationDetails,a=n.url,i=n.method,r=n.handleVerificationResult,o=n.createHeaders,s=n.body,l=(null==o?void 0:o(e))||this.buildHeadersFunc(e);Mn.verifyKey(e,a,l,i,this.keyAuthenticated.bind(this,t.onSuccess),t.onFail,t.onLoad,r,s)}},{key:"isDirectConnection",value:function(){return!0}}]),t}(Pn),Un=function(){function e(){J(this,e)}return te(e,null,[{key:"waitForPropertiesToBeUpdatedBeforeRender",value:function(t){t._propUpdated_=!1,setTimeout((function(){t._propUpdated_?e.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}},{key:"attemptRender",value:function(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,e.waitForPropertiesToBeUpdatedBeforeRender(t))}}]),e}(),Bn=function(e){function t(){var e;return J(this,t),(e=G(this,t))._waitingToRender_=!1,e._propUpdated_=!1,Object.keys(t._attributeToProperty_).forEach((function(n){var a=t._attributeToProperty_[n];e.constructPropertyAccessors(a),e.hasOwnProperty(n)||e.constructPropertyAccessors(a,n)})),e}return V(t,e),te(t,[{key:"constructPropertyAccessors",value:function(e,t){var n;Object.defineProperty(this,t||e,{get:function(){return n},set:function(a){n=a,t?this[e]=a:Un.attemptRender(this)}})}},{key:"attributeChangedCallback",value:function(e,n,a){if(n!==a){var i=t._attributes_[e](a);this[t._attributeToProperty_[e]]=i}}},{key:"onRender",value:function(){}}],[{key:"observedAttributes",get:function(){return Object.keys(t._attributes_)||[]}}]),t}(B(HTMLElement));Bn._attributes_={},Bn._attributeToProperty_={};var Gn=Bn,Yn=function(){function e(){J(this,e)}return te(e,null,[{key:"createSVGElement",value:function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").documentElement}}]),e}(),Hn=function(){function e(){J(this,e)}return te(e,null,[{key:"changeVisibility",value:function(t,n,a,i){i.target.id===e.VISIBLE_ICON_ID?(n.style.display="none",a.style.display="block",t.type="password"):(n.style.display="block",a.style.display="none",t.type="text")}},{key:"createIconElement",value:function(e,t){var n=Yn.createSVGElement(e);return n.id=t,n.classList.add("visibility-icon"),n}},{key:"create",value:function(t){var n=document.createElement("div");n.id="visibility-icon-container";var a=e.createIconElement('\n\n\t\t\n\n',e.VISIBLE_ICON_ID);a.style.display="none",n.appendChild(a);var i=e.createIconElement('\n\n\t\t\n\n',"not-visible-icon");return n.appendChild(i),n.onclick=e.changeVisibility.bind(this,t,a,i),n}}]),e}();Hn.VISIBLE_ICON_ID="visible-icon";var qn=Hn,Vn=function(){function e(){J(this,e)}return te(e,null,[{key:"createCautionText",value:function(){var e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",e}},{key:"createHelpLink",value:function(e){var t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.href=e,t.innerText="Find more info here",t.target="_blank",t}},{key:"createFailText",value:function(){var e=document.createElement("div");return e.id="insert-key-input-invalid-text",e.style.display="none",e}},{key:"createHelpTextContainer",value:function(t){var n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],a=document.createElement("div");a.id="insert-key-help-text-container";var i=document.createElement("div");i.id="insert-key-help-text-contents";var r=e.createFailText();if(i.appendChild(r),t){var o=e.createHelpLink(t);i.appendChild(o)}if(!0===n){var s=e.createCautionText();i.appendChild(s)}return a.appendChild(i),{helpTextContainerElement:a,failTextElement:r}}},{key:"onFail",value:function(e,t,n,a){e.classList.replace("insert-key-input-valid","insert-key-input-invalid"),n.innerText=a,n.style.display="block",t.innerText="Start",e.classList.remove("loading")}},{key:"onLoad",value:function(e,t){e.classList.add("loading"),t.innerHTML='
    '}},{key:"verifyKey",value:function(e,t,n){var a=e.value.trim();n.verifyKey(a,t)}},{key:"addVerificationEvents",value:function(t,n,a,i,r){var o={onSuccess:i,onFail:e.onFail.bind(this,t,n,a),onLoad:e.onLoad.bind(this,t,n)},s=e.verifyKey.bind(this,t,o,r);n.onclick=s,t.onkeydown=function(e){!t.classList.contains("loading")&&e.key===le.ENTER&&s()}}},{key:"createStartButton",value:function(){var e=document.createElement("div");return e.id="start-button",e.innerText="Start",e}},{key:"onInputFocus",value:function(e){e.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}},{key:"createInput",value:function(t){var n=document.createElement("div");n.id="insert-key-input-container";var a=document.createElement("input");return a.id="insert-key-input",a.placeholder=t||"API Key",a.type="password",a.classList.add("insert-key-input-valid"),a.onfocus=e.onInputFocus,n.appendChild(a),n}},{key:"createContents",value:function(t,n){var a,i=document.createElement("div");i.id="insert-key-contents";var r=e.createInput(n.insertKeyPlaceholderText),o=r.children[0],s=qn.create(o);r.appendChild(s),i.appendChild(r);var l=e.createStartButton(),c=e.createHelpTextContainer(n.keyHelpUrl,null==(a=n.deepChat._insertKeyViewStyles)?void 0:a.displayCautionText),d=c.helpTextContainerElement,u=c.failTextElement;return i.appendChild(l),i.appendChild(d),e.addVerificationEvents(o,l,u,t,n),i}},{key:"createElements",value:function(t,n){var a=document.createElement("div");a.id="insert-key-view";var i=e.createContents(t,n);return a.appendChild(i),a}},{key:"render",value:function(t,n,a){var i=e.createElements(n,a);t.replaceChildren(i)}}]),e}(),zn=function(){function e(){J(this,e)}return te(e,null,[{key:"enableButtons",value:function(t,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;window.webLLM?(t&&(t.disabled=!1),n&&(n.disabled=!1)):a<4*Kn.MODULE_SEARCH_LIMIT_S&&setTimeout((function(){return e.enableButtons(t,n,a+1)}),250)}},{key:"setUpInitial",value:function(t,n,a,i){var r=(null==n?void 0:n.downloadClass)||e.DOWNLOAD_BUTTON_CLASS,o=(null==n?void 0:n.uploadClass)||e.UPLOAD_BUTTON_CLASS,s=(null==n?void 0:n.fileInputClass)||e.FILE_INPUT_CLASS;return setTimeout((function(){var n=null==a?void 0:a.getElementsByClassName(r)[0],i=null==a?void 0:a.getElementsByClassName(s)[0],l=null==a?void 0:a.getElementsByClassName(o)[0];n&&(n.onclick=function(){return t()}),i&&(i.onchange=function(){i.files&&i.files.length>0&&t(i.files)}),l&&(l.onclick=function(){return i.click()}),(n||l)&&e.enableButtons(n,l)})),(null==n?void 0:n.initialHtml)||'
    \n Download or upload a web model that will run entirely on your browser:
    \n \n ').concat(i?"":'\n '),"\n
    ")}},{key:"exportFile",value:function(e){for(var t=document.createElement("a"),n=function(n){setTimeout((function(){for(var a=4*n,i=a;i\n Model loaded successfully and has been cached for future requests.\n ".concat(i?"":'
    '),"\n ")}}]),e}();zn.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",zn.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",zn.FILE_INPUT_CLASS="deep-chat-file-input",zn.EXPORT_BUTTON_CLASS="deep-chat-export-button";var jn=zn,Wn={model_list:[{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f32_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f32_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:9109.03,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:6749.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:4618.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-13b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-13b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-13b-chat-hf/Llama-2-13b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:11814.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-70b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-70b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-70b-chat-hf/Llama-2-70b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:43729.05,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx2k-webgpu.wasm",vram_required_MB:2972.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx2k-webgpu.wasm",vram_required_MB:3928.09,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:2041.09,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:2558.09,low_resource_required:!0},{model_url:"https://huggingface.co/mlc-ai/WizardMath-7B-V1.1-q4f16_1-MLC/resolve/main/",local_id:"WizardMath-7B-V1.1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Mistral-7B-Instruct-v0.2-q4f16_1-MLC/resolve/main/",local_id:"Mistral-7B-Instruct-v0.2-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/OpenHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"OpenHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/NeuralHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"NeuralHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{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},$n=function(e){function t(e){var n,a,i;return J(this,t),(n=G(this,t,[e]))._isModelLoaded=!1,n._isModelLoading=!1,n._loadOnFirstMessage=!1,n._webModel={},n.permittedErrorPrefixes=[t.MULTIPLE_MODELS_ERROR,t.WEB_LLM_NOT_FOUND_ERROR,t.GENERIC_ERROR],n._conversationHistory=[],"object"==Z(e.webModel)&&(n._webModel=e.webModel),null!=(a=n._webModel.load)&&a.clearCache&&t.clearAllCache(),n.findModelInWindow(e),n.canSendMessage=n.canSubmit.bind(Y(n)),n._chatEl=null==(i=e.shadowRoot)?void 0:i.children[0],e.initialMessages&&t.setUpHistory(n._conversationHistory,e.initialMessages),n}var n,a,i,r,o,s,l,c,d,u;return V(t,e),te(t,[{key:"setUpMessages",value:function(e){var t=this;this._messages=e,this._removeIntro=function(){e.removeIntroductoryMessage(),t._removeIntro=void 0}}},{key:"findModelInWindow",value:function(e){var n,a=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;window.webLLM?this.configureInit(this.shouldAddInitialMessage(e.introMessage)):i>t.MODULE_SEARCH_LIMIT_S?(null==(n=this._messages)||n.addNewErrorMessage("service",t.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 a.findModelInWindow(e,i+1)}),1e3)}},{key:"shouldAddInitialMessage",value:function(e){var t;return!e&&this._webModel&&!1!==(null==(t=this._webModel.introMessage)?void 0:t.displayed)}},{key:"scrollToTop",value:function(e){var t,n=this;!1!==(null==(t=this._webModel.introMessage)?void 0:t.autoScroll)&&setTimeout((function(){var e,t;null!=(e=n._messages)&&e.elementRef&&ve.scrollToTop(null==(t=n._messages)?void 0:t.elementRef)}),e)}},{key:"getIntroMessage",value:function(e){if(this.shouldAddInitialMessage(e)&&this._chatEl){var t=jn.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:we.AI_ROLE,html:t,sendUpdate:!1}}}},{key:"configureInit",value:(u=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=this._webModel.load)){e.next=8;break}if(!n.onInit){e.next=5;break}return this.init(),e.abrupt("return");case 5:if(!n.onMessage){e.next=8;break}return this._loadOnFirstMessage=!0,e.abrupt("return");case 8:t||this.init();case 9:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"init",value:(d=$(j().mark((function e(t){var n,a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null==(n=this._messages)||n.removeError(),a=this.attemptToCreateChat(),e.t0=a,!e.t0){e.next=6;break}return e.next=6,this.loadModel(a,t);case 6:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"attemptToCreateChat",value:function(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage("service",t.MULTIPLE_MODELS_ERROR),void console.error(t.MULTIPLE_MODELS_ERROR);if(!this._isModelLoaded&&!this._isModelLoading){var n=this._webModel.worker;return Wn.use_web_worker&&n?new window.webLLM.ChatWorkerClient(n):new window.webLLM.ChatModule}}},{key:"getConfig",value:function(){var e,n=t.DEFAULT_MODEL;this._webModel.model&&(n=this._webModel.model);var a=JSON.parse(JSON.stringify(Wn));if(this._webModel.urls){var i=a.model_list.find((function(e){return e.local_id=n}));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 null!=(e=this._webModel.load)&&e.skipCache&&(a.use_cache=!1),{model:n,appConfig:a}}},{key:"loadModel",value:(c=$(j().mark((function e(n,a){var i,r,o,s,l,c,d,u,_,p,m,g,E,S,h,f=this;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.scrollToTop(),t.chat=n,this._isModelLoading=!0,u=!1===(null==(i=this._webModel.introMessage)?void 0:i.displayed),_=function(e){var t;null==(t=f._messages)||t.addNewMessage({html:"
    ".concat(e.text,"
    "),overwrite:!0,sendUpdate:!1}),u&&(setTimeout((function(){var e;return ve.scrollToBottom(null==(e=f._messages)?void 0:e.elementRef)})),u=!1)},t.chat.setInitProgressCallback(_),e.prev=4,m=this.getConfig(),g=m.model,E=m.appConfig,S={},this._webModel.instruction&&(S.conv_config={system:this._webModel.instruction}),this._conversationHistory.length>0&&(S.conversation_history=this._conversationHistory),e.next=10,t.chat.reload(g,S,E,a);case 10:p=e.sent,e.next=16;break;case 13:return e.prev=13,e.t0=e.catch(4),e.abrupt("return",this.unloadChat(e.t0));case 16:null==(o=(r=this.deepChat)._validationHandler)||o.call(r),null!=(s=this._webModel.introMessage)&&s.removeAfterLoad?!1===this._webModel.introMessage.displayed?null==(c=this._messages)||c.removeLastMessage():null==(d=this._removeIntro)||d.call(this):(h=jn.setUpAfterLoad(p,this._webModel.introMessage,this._chatEl,!!this._webModel.worker),null==(l=this._messages)||l.addNewMessage({html:h,overwrite:!0,sendUpdate:!1})),this._isModelLoaded=!0,this._isModelLoading=!1;case 18:case"end":return e.stop()}}),e,this,[[4,13]])}))),function(e,t){return c.apply(this,arguments)})},{key:"unloadChat",value:(l=$(j().mark((function e(n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null==(a=this._messages)||a.addNewErrorMessage("service",t.GENERIC_ERROR),console.error(n),this._isModelLoaded=!1,this._isModelLoading=!1,e.t0=t.chat,!e.t0){e.next=9;break}return e.next=8,t.chat.unload();case 8:t.chat=void 0;case 9:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"immediateResp",value:(s=$(j().mark((function e(n,a,i){var r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,i.generate(a,void 0,0);case 2:return e.t0=e.sent,r={text:e.t0},e.next=6,t.processResponse(this.deepChat,n,r);case 6:(o=e.sent)&&n.addNewMessage(o),this.completionsHandlers.onFinish();case 8:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return s.apply(this,arguments)})},{key:"streamResp",value:(o=$(j().mark((function e(n,a,i){var r,o=this;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.streamHandlers.abortStream.abort=function(){i.interruptGenerate()},this.streamHandlers.onOpen(),r=new En(n),e.next=4,i.generate(a,function(){var e=$(j().mark((function e(a,i){var s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.processResponse(o.deepChat,n,{text:i});case 2:(s=e.sent)&&r.upsertStreamedMessage({text:s.text,overwrite:!0});case 4:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}());case 4:r.finaliseStreamedMessage(),this.streamHandlers.onClose();case 6:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return o.apply(this,arguments)})},{key:"generateRespByType",value:(r=$(j().mark((function e(t,n,a,i){var r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!a){e.next=6;break}return e.next=4,this.streamResp(t,n,i);case 4:e.next=8;break;case 6:return e.next=8,this.immediateResp(t,n,i);case 8:e.next=13;break;case 10:e.prev=10,e.t0=e.catch(0),null==(r=this._messages)||r.addNewErrorMessage("service"),console.log(e.t0);case 13:case"end":return e.stop()}}),e,this,[[0,10]])}))),function(e,t,n,a){return r.apply(this,arguments)})},{key:"generateResp",value:(i=$(j().mark((function e(t,n,a){var i,r,o,s,l,c,d;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=n[n.length-1].text,e.next=3,hn.processRequestInterceptor(this.deepChat,{body:{text:i}});case 3:r=e.sent,o=r.body,s=r.error,l=!!this.deepChat.stream;try{s?(hn.displayError(t,new Error(s)),(l?this.streamHandlers.onClose:this.completionsHandlers.onFinish)()):o&&o.text?this.generateRespByType(t,o.text,!!this.deepChat.stream,a):(c=fe.INVALID_MODEL_REQUEST({body:o},!1),console.error(c),d=l?this.streamHandlers.onClose:this.completionsHandlers.onFinish,hn.onInterceptorError(t,c,d))}catch(e){this.unloadChat(e)}case 8:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return i.apply(this,arguments)})},{key:"callServiceAPI",value:(a=$(j().mark((function e(n,a){var i,r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._isModelLoaded){e.next=7;break}if(!this._loadOnFirstMessage){e.next=6;break}return e.next=4,this.init();case 4:e.next=7;break;case 6:return e.abrupt("return");case 7:!t.chat||this._isModelLoading||(null!=(i=this._webModel.introMessage)&&i.removeAfterMessage&&(null==(r=this._removeIntro)||r.call(this)),n.addLoadingMessage(),this.generateResp(n,a,t.chat));case 8:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"canSubmit",value:function(e){return!(null==e||!e.trim()||this._isModelLoading)&&(!!this._loadOnFirstMessage||!!this._isModelLoaded)}},{key:"isWebModel",value:function(){return!0}}],[{key:"setUpHistory",value:function(e,t){t.forEach((function(n,a){if(n.role===we.USER_ROLE&&n.text){var i=t[a+1];null!=i&&i.text&&i.role!==we.USER_ROLE&&e.push([n.text,i.text])}}))}},{key:"processResponse",value:(n=$(j().mark((function e(t,n,a){var i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null==(i=t.responseInterceptor)?void 0:i.call(t,a);case 2:if(e.t0=e.sent,e.t0){e.next=5;break}e.t0=a;case 5:if(!(r=e.t0).error){e.next=11;break}return hn.displayError(n,new Error(r.error)),e.abrupt("return");case 11:if(r&&r.text){e.next=15;break}return o=fe.INVALID_MODEL_RESPONSE(a,!!t.responseInterceptor,r),hn.displayError(n,new Error(o)),e.abrupt("return");case 15:return e.abrupt("return",r);case 16:case"end":return e.stop()}}),e)}))),function(e,t,a){return n.apply(this,arguments)})},{key:"clearAllCache",value:function(){t.clearCache("webllm/model"),t.clearCache("webllm/wasm")}},{key:"clearCache",value:function(e){caches.open(e).then((function(e){e.keys().then((function(t){t.forEach((function(t){e.delete(t)}))}))}))}}]),t}(Pn);$n.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",$n.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",$n.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",$n.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",$n.MODULE_SEARCH_LIMIT_S=5;var Kn=$n,Qn=function(){function e(){J(this,e)}return te(e,null,[{key:"buildHeaders",value:function(e){return{Authorization:"Bearer ".concat(e),"Content-Type":"application/json"}}},{key:"handleVerificationResult",value:function(e,t,n,a){var i=e;Array.isArray(i.error)&&"Error in `parameters`: field required"===i.error[0]?n(t):a(fe.INVALID_KEY)}},{key:"buildKeyVerificationDetails",value:function(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:e.handleVerificationResult}}}]),e}(),Xn=function(e){function t(e,n,a,i,r,o){var s;return J(this,t),(s=G(this,t,[e,Qn.buildKeyVerificationDetails(),Qn.buildHeaders,r,o])).insertKeyPlaceholderText="Hugging Face Token",s.keyHelpUrl="https://huggingface.co/settings/tokens",s.introPanelMarkUp='\n
    Hugging Face
    \n

    First message may take an extented amount of time to complete as the model needs to be initialized.

    ',s.permittedErrorPrefixes=["Authorization header"],s.url="".concat(t.URL_PREFIX).concat(a),s.textInputPlaceholderText=n,"object"==Z(i)&&(i.model&&(s.url="".concat(t.URL_PREFIX).concat(i.model)),i.options&&(s.rawBody.options=i.options),i.parameters&&(s.rawBody.parameters=i.parameters)),s}var n;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t,n){var a,i=JSON.parse(JSON.stringify(e)),r=t[t.length-1].text;if(r)return null!==(a=i.options)&&void 0!==a||(i.options={}),i.options.wait_for_model=!0,Q({inputs:r},i)}},{key:"callServiceAPI",value:(n=$(j().mark((function e(t,n,a){var i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:i=this.preprocessBody(this.rawBody,n,a),Mn.request(this,i,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t,a){return n.apply(this,arguments)})}]),t}(Fn);Xn.URL_PREFIX="https://api-inference.huggingface.co/models/";var Zn=Xn,Jn=function(e){function t(e,n,a,i,r,o){var s;return J(this,t),(s=G(this,t,[e,n,a,i,r,o])).isTextInputDisabled=!0,s.canSendMessage=t.canSendFile,s}var n;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t,n){return n[0]}},{key:"callServiceAPI",value:(n=$(j().mark((function e(t,n,a){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null!=a&&a[0]){e.next=4;break}throw new Error("No file was added");case 4:Mn.poll(this,a[0],t,!1);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t,a){return n.apply(this,arguments)})}],[{key:"canSendFile",value:function(e,t){return!(null==t||!t[0])}}]),t}(Zn),ea=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.audioClassification,null==(i=e.directConnection)?void 0:i.huggingFace,{audio:{}}])}var n;return V(t,e),te(t,[{key:"extractPollResultData",value:(n=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.estimated_time){e.next=2;break}return e.abrupt("return",{timeoutMS:1e3*(t.estimated_time+1)});case 2:if(!t.error){e.next=4;break}throw t.error;case 4:return e.abrupt("return",{text:(null==(n=t[0])?void 0:n.label)||""});case 5:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Jn),ta=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Attach an image file","google/vit-base-patch16-224",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.imageClassification,null==(i=e.directConnection)?void 0:i.huggingFace,{images:{}}])}var n;return V(t,e),te(t,[{key:"extractPollResultData",value:(n=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.estimated_time){e.next=2;break}return e.abrupt("return",{timeoutMS:1e3*(t.estimated_time+1)});case 2:if(!t.error){e.next=4;break}throw t.error;case 4:return e.abrupt("return",{text:(null==(n=t[0])?void 0:n.label)||""});case 5:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Jn),na="data:image/png;base64,",aa=function(){function e(){J(this,e)}return te(e,null,[{key:"buildHeaders",value:function(e){return{Authorization:"Bearer ".concat(e),"Content-Type":"application/json"}}},{key:"handleVerificationResult",value:function(e,t,n,a){e.message?a(fe.INVALID_KEY):n(t)}},{key:"buildKeyVerificationDetails",value:function(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:e.handleVerificationResult}}}]),e}(),ia=function(e){function t(e,n,a,i,r){var o;return J(this,t),(o=G(this,t,[e,n,a,i,r])).insertKeyPlaceholderText="Stability AI API Key",o.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",o.permittedErrorPrefixes=["Incorrect","invalid_"],o}return V(t,e),te(t)}(Fn),ra=function(e){function t(e){var n,a;J(this,t);var i=JSON.parse(JSON.stringify(e.directConnection)),r=null==i?void 0:i.stabilityAI;(n=G(this,t,[e,aa.buildKeyVerificationDetails(),aa.buildHeaders,r,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}])).url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",n.textInputPlaceholderText="Describe image changes",n.introPanelMarkUp='\n
    Stability AI
    \n
    Image to Image Upscale
    \n

    Upload an image to generate a new one with higher resolution.

    \n

    Click here for more info.

    ';var o=null==(a=null==i?void 0:i.stabilityAI)?void 0:a.imageToImageUpscale;return"object"==Z(o)&&(o.engine_id&&(n.url="https://api.stability.ai/v1/generation/".concat(o.engine_id,"/image-to-image/upscale")),t.cleanConfig(o),Object.assign(n.rawBody,o)),n.canSendMessage=t.canSendFileMessage,n}var n,a;return V(t,e),te(t,[{key:"createFormDataBody",value:function(e,t){var n=new FormData;return n.append("image",t),Object.keys(e).forEach((function(t){n.append(t,String(e[t]))})),n}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){var i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(a){e.next=4;break}throw new Error("Image was not found");case 4:i=this.createFormDataBody(this.rawBody,a[0]),hn.tempRemoveContentHeader(this.requestSettings,Mn.request.bind(this,this,i,t),!1);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{files:t.artifacts.map((function(e){return{src:"".concat(na).concat(e.base64),type:"image"}}))});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"cleanConfig",value:function(e){delete e.engine_id}},{key:"canSendFileMessage",value:function(e,t){return!(null==t||!t[0])}}]),t}(ia),oa=function(e){function t(e){var n,a;J(this,t);var i=JSON.parse(JSON.stringify(e.directConnection)),r=null==i?void 0:i.stabilityAI;(n=G(this,t,[e,aa.buildKeyVerificationDetails(),aa.buildHeaders,r,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}])).url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",n._maskSource="MASK_IMAGE_WHITE",n.textInputPlaceholderText="Describe image changes",n.introPanelMarkUp='\n
    Stability AI
    \n
    Image to Image Masking
    \n

    Upload an image, its mask image to create a new one based on the changes you have described for the mask area.

    \n

    Click here for more info.

    ';var o=null==(a=null==i?void 0:i.stabilityAI)?void 0:a.imageToImageMasking;return"object"==Z(o)&&(o.engine_id&&(n.url="https://api.stability.ai/v1/generation/".concat(o.engine_id,"/image-to-image/masking")),void 0!==o.weight&&null!==o.weight&&(n._imageWeight=o.weight),void 0!==o.mask_source&&null!==o.mask_source&&(n._maskSource=o.mask_source),t.cleanConfig(o),Object.assign(n.rawBody,o)),n.canSendMessage=t.canSendFileTextMessage,n}var n,a;return V(t,e),te(t,[{key:"createFormDataBody",value:function(e,t,n,a){var i=new FormData;return i.append("init_image",t),i.append("mask_source",String(this._maskSource)),i.append("mask_image",n),a&&""!==a&&i.append("text_prompts[0][text]",a),void 0!==this._imageWeight&&null!==this._imageWeight&&i.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(e).forEach((function(t){i.append(t,String(e[t]))})),void 0===i.get("weight")&&i.append("weight",String(1)),i}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){var i,r,o,s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(a&&a[0]&&a[1]){e.next=4;break}throw new Error("Image was not found");case 4:o=null==(r=null==(i=n[n.length-1])?void 0:i.text)?void 0:r.trim(),s=this.createFormDataBody(this.rawBody,a[0],a[1],o),hn.tempRemoveContentHeader(this.requestSettings,Mn.request.bind(this,this,s,t),!1);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{files:t.artifacts.map((function(e){return{src:"".concat(na).concat(e.base64),type:"image"}}))});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"cleanConfig",value:function(e){delete e.engine_id,delete e.weight}},{key:"canSendFileTextMessage",value:function(e,t){return!(null==t||!t[0]||!e||""===e.trim())}}]),t}(ia),sa=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.audioSpeechRecognition,null==(i=e.directConnection)?void 0:i.huggingFace,{audio:{}}])}var n;return V(t,e),te(t,[{key:"extractPollResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.estimated_time){e.next=2;break}return e.abrupt("return",{timeoutMS:1e3*(t.estimated_time+1)});case 2:if(!t.error){e.next=4;break}throw t.error;case 4:return e.abrupt("return",{text:t.text||""});case 5:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Jn),la=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Once upon a time","gpt2",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.textGeneration,null==(i=e.directConnection)?void 0:i.huggingFace])}var n;return V(t,e),te(t,[{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t[0].generated_text||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),ca=function(e){function t(e){var n,a,i,r;J(this,t);var o=null==(i=null==(a=e.directConnection)?void 0:a.huggingFace)?void 0:i.questionAnswer;return(n=G(this,t,[e,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",o,null==(r=e.directConnection)?void 0:r.huggingFace])).permittedErrorPrefixes=["Authorization header","Error in"],n.context=o.context,n}var n;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=t[t.length-1].text;if(n)return{inputs:{question:n,context:this.context,options:{wait_for_model:!0}}}}},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t.answer||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),da=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Insert text to summarize","facebook/bart-large-cnn",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.summarization,null==(i=e.directConnection)?void 0:i.huggingFace])}var n;return V(t,e),te(t,[{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t[0].summary_text||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),ua=function(e){function t(e){var n,a,i,r,o;return J(this,t),null!==(n=(a=G(this,t,[e,"Ask me anything!","facebook/blenderbot-400M-distill",null==(r=null==(i=e.directConnection)?void 0:i.huggingFace)?void 0:r.conversation,null==(o=e.directConnection)?void 0:o.huggingFace])).maxMessages)&&void 0!==n||(a.maxMessages=-1),a}var n;return V(t,e),te(t,[{key:"processMessages",value:function(e){var t=e.filter((function(e){return e.text})),n=t[t.length-1].text,a=t.slice(0,t.length-1);if(n)return{past_user_inputs:a.filter((function(e){return"user"===e.role})).map((function(e){return e.text})),generated_responses:a.filter((function(e){return"ai"===e.role})).map((function(e){return e.text})),mostRecentMessageText:n}}},{key:"preprocessBody",value:function(e,t){var n,a=JSON.parse(JSON.stringify(e)),i=this.processMessages(t);if(i)return null!==(n=a.options)&&void 0!==n||(a.options={}),a.options.wait_for_model=!0,Q({inputs:{past_user_inputs:i.past_user_inputs,generated_responses:i.generated_responses,text:i.mostRecentMessageText}},a)}},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t.generated_text||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),_a=function(e){function t(e){var n,a;J(this,t);var i=JSON.parse(JSON.stringify(e.directConnection)),r=i.stabilityAI;(n=G(this,t,[e,aa.buildKeyVerificationDetails(),aa.buildHeaders,r,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}])).url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",n.textInputPlaceholderText="Describe image changes",n.introPanelMarkUp='\n
    Stability AI: Image to Image
    \n

    Upload an image to create a new one with the changes you have described.

    \n

    Click here for more info.

    ';var o=null==(a=i.stabilityAI)?void 0:a.imageToImage;return"object"==Z(o)&&(o.engine_id&&(n.url="https://api.stability.ai/v1/generation/".concat(o.engine_id,"/text-to-image")),void 0!==o.weight&&null!==o.weight&&(n._imageWeight=o.weight),t.cleanConfig(o),Object.assign(n.rawBody,o)),n.canSendMessage=t.canSendFileTextMessage,n}var n,a;return V(t,e),te(t,[{key:"createFormDataBody",value:function(e,t,n){var a=new FormData;return a.append("init_image",t),n&&""!==n&&a.append("text_prompts[0][text]",n),void 0!==this._imageWeight&&null!==this._imageWeight&&a.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(e).forEach((function(t){a.append(t,String(e[t]))})),void 0===a.get("weight")&&a.append("weight",String(1)),a}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){var i,r,o,s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(a){e.next=4;break}throw new Error("Image was not found");case 4:o=null==(r=null==(i=n[n.length-1])?void 0:i.text)?void 0:r.trim(),s=this.createFormDataBody(this.rawBody,a[0],o),hn.tempRemoveContentHeader(this.requestSettings,Mn.request.bind(this,this,s,t),!1);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{files:t.artifacts.map((function(e){return{src:"".concat(na).concat(e.base64),type:"image"}}))});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"cleanConfig",value:function(e){delete e.engine_id,delete e.weight}},{key:"canSendFileTextMessage",value:function(e,t){return!(null==t||!t[0]||!e||""===e.trim())}}]),t}(ia),pa=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(a=null==(n=e.directConnection)?void 0:n.huggingFace)?void 0:a.translation,null==(i=e.directConnection)?void 0:i.huggingFace])}var n;return V(t,e),te(t,[{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t[0].translation_text||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),ma=function(e){function t(e){var n,a;J(this,t);var i=JSON.parse(JSON.stringify(e.directConnection)),r=i.stabilityAI;(n=G(this,t,[e,aa.buildKeyVerificationDetails(),aa.buildHeaders,r])).url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",n.textInputPlaceholderText="Describe an image",n.introPanelMarkUp='\n
    Stability AI: Text to Image
    \n

    Insert text to generate an image.

    \n

    Click here for more info.

    ';var o=null==(a=i.stabilityAI)?void 0:a.textToImage;return"object"==Z(o)&&(o.engine_id&&(n.url="https://api.stability.ai/v1/generation/".concat(o.engine_id,"/text-to-image")),void 0!==o.weight&&null!==o.weight&&(n._imageWeight=o.weight),t.cleanConfig(o),Object.assign(n.rawBody,o)),n.canSendMessage=t.canSendTextMessage,n}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=JSON.parse(JSON.stringify(e)),a={text:t};return this._imageWeight&&(a.weight=this._imageWeight),n.text_prompts=[a],n}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n[n.length-1].text),Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{files:t.artifacts.map((function(e){return{src:"".concat(na).concat(e.base64),type:"image"}}))});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"cleanConfig",value:function(e){delete e.engine_id,delete e.weight}},{key:"canSendTextMessage",value:function(e){return!(!e||""===e.trim())}}]),t}(ia),ga=function(e){function t(e){var n,a,i,r;return J(this,t),(n=G(this,t,[e,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(a=e.directConnection)?void 0:a.huggingFace)?void 0:i.fillMask,null==(r=e.directConnection)?void 0:r.huggingFace])).introPanelMarkUp='\n
    Hugging Face
    \n

    Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].

    \n

    First message may take an extented amount of time to complete as the model needs to be initialized.

    ',n.permittedErrorPrefixes=["Authorization header","No mask_token"],n}var n;return V(t,e),te(t,[{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t[0].sequence||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Zn),Ea=function(){function e(){J(this,e)}return te(e,null,[{key:"buildHeaders",value:function(e){return{Authorization:"Bearer ".concat(e),"Content-Type":"application/json",accept:"application/json"}}},{key:"handleVerificationResult",value:function(e,t,n,a){var i;null!=(i=e.message)&&i.includes("invalid request: prompt must be at least 1 token long")?n(t):a(fe.INVALID_KEY)}},{key:"buildKeyVerificationDetails",value:function(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:e.handleVerificationResult,body:JSON.stringify({prompt:""})}}}]),e}(),Sa=function(e){function t(e,n,a,i,r){var o;return J(this,t),(o=G(this,t,[e,Ea.buildKeyVerificationDetails(),Ea.buildHeaders,r])).insertKeyPlaceholderText="Cohere API Key",o.keyHelpUrl="https://dashboard.cohere.ai/api-keys",o.permittedErrorPrefixes=["invalid"],o.url=n,o.textInputPlaceholderText=a,i&&"object"==Z(i)&&Object.assign(o.rawBody,i),o}return V(t,e),te(t)}(Fn),ha=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"https://api.cohere.ai/v1/generate","Once upon a time",null==(a=null==(n=e.directConnection)?void 0:n.cohere)?void 0:a.textGeneration,null==(i=e.directConnection)?void 0:i.cohere])}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=JSON.parse(JSON.stringify(e)),a=t[t.length-1].text;if(a)return Q({prompt:a},n)}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{text:(null==(n=t.generations)?void 0:n[0].text)||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Sa),fa=function(e){function t(e){var n,a,i;return J(this,t),G(this,t,[e,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(a=null==(n=e.directConnection)?void 0:n.cohere)?void 0:a.summarization,null==(i=e.directConnection)?void 0:i.cohere])}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=JSON.parse(JSON.stringify(e)),a=t[t.length-1].text;if(a)return Q({text:a},n)}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{text:t.summary||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Sa),ba=function(){function e(){J(this,e)}var t;return te(e,null,[{key:"buildHeaders",value:function(e){return{Authorization:"Bearer ".concat(e),"Content-Type":"application/json"}}},{key:"handleVerificationResult",value:function(e,t,n,a){var i=e;i.error?"invalid_api_key"===i.error.code?a(fe.INVALID_KEY):a(fe.CONNECTION_FAILED):n(t)}},{key:"buildKeyVerificationDetails",value:function(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:e.handleVerificationResult}}},{key:"directFetch",value:(t=$(j().mark((function e(t,n,a){var i,r,o=arguments;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=!(o.length>3&&void 0!==o[3])||o[3],t.requestSettings.method=a,e.next=4,hn.fetch(t,t.requestSettings.headers,i,n).then((function(e){return hn.processResponseByType(e)}));case 4:if(!(r=e.sent).error){e.next=7;break}throw r.error.message;case 7:return e.abrupt("return",r);case 8:case"end":return e.stop()}}),e)}))),function(e,n,a){return t.apply(this,arguments)})}]),e}(),va=function(e){function t(e){var n,a,i,r,o,s;J(this,t);var l=JSON.parse(JSON.stringify(e.directConnection)),c=null==l?void 0:l.openAI;(i=G(this,t,[e,ba.buildKeyVerificationDetails(),ba.buildHeaders,c])).insertKeyPlaceholderText="OpenAI API Key",i.keyHelpUrl="https://platform.openai.com/account/api-keys",i.url="https://api.openai.com/v1/audio/speech",i.permittedErrorPrefixes=["Invalid"],i.introPanelMarkUp='\n
    OpenAI : Text To Speech
    \n

    Generate an audio file based on your text input.

    \n

    Click here for more information.

    ';var d=null==(r=null==l?void 0:l.openAI)?void 0:r.textToSpeech;return"object"==Z(d)&&Object.assign(i.rawBody,d),null!==(n=(o=i.rawBody).model)&&void 0!==n||(o.model=t.DEFAULT_MODEL),null!==(a=(s=i.rawBody).voice)&&void 0!==a||(s.voice=t.DEFAULT_VOIDE),i.textInputPlaceholderText="Insert text to generate audio",i.rawBody.response_format="mp3",i}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n,a,i=JSON.parse(JSON.stringify(e)),r=null==(a=null==(n=t[t.length-1])?void 0:n.text)?void 0:a.trim();return r&&""!==r&&(i.input=r),i}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(a=this.requestSettings)&&a.headers){e.next=2;break}throw new Error("Request settings have not been set up");case 2:this.url=this.requestSettings.url||this.url,i=this.preprocessBody(this.rawBody,n),Mn.request(this,i,t);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t instanceof Blob)){e.next=2;break}return e.abrupt("return",new Promise((function(e){var n=new FileReader;n.readAsDataURL(t),n.onload=function(t){e({files:[{src:t.target.result,type:"audio"}]})}})));case 2:if(!t.error){e.next=4;break}throw t.error.message;case 4:return e.abrupt("return",{error:"error"});case 5:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Fn);va.DEFAULT_MODEL="tts-1",va.DEFAULT_VOIDE="alloy";var Ta=va,ya=function(e){function t(e){var n,a,i,r;J(this,t);var o=JSON.parse(JSON.stringify(e.directConnection)),s=null==o?void 0:o.openAI;(a=G(this,t,[e,ba.buildKeyVerificationDetails(),ba.buildHeaders,s,{audio:{}}])).insertKeyPlaceholderText="OpenAI API Key",a.keyHelpUrl="https://platform.openai.com/account/api-keys",a.introPanelMarkUp='\n
    OpenAI : Speech To Text
    \n

    Upload an audio file to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n

    Click here for more info.

    ',a.url="",a.permittedErrorPrefixes=["Invalid"],a.textInputPlaceholderText="Upload an audio file",a._service_url=t.AUDIO_TRANSCRIPTIONS_URL;var l=null==(i=null==o?void 0:o.openAI)?void 0:i.audio;return"object"==Z(l)&&(a.processConfig(l),t.cleanConfig(l),Object.assign(a.rawBody,l)),null!==(n=(r=a.rawBody).model)&&void 0!==n||(r.model=t.DEFAULT_MODEL),a.rawBody.response_format="json",a.canSendMessage=t.canSendFileMessage,a}var n,a;return V(t,e),te(t,[{key:"processConfig",value:function(e){null!=e&&e.type&&"translation"===e.type&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}},{key:"preprocessBody",value:function(e,t){var n,a,i=JSON.parse(JSON.stringify(e)),r=null==(a=null==(n=t[t.length-1])?void 0:n.text)?void 0:a.trim();return r&&""!==r&&(i.prompt=r),i}},{key:"callServiceAPI",value:(a=$(j().mark((function e(n,a,i){var r,o,s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(r=this.requestSettings)&&r.headers){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null!=i&&i[0]){e.next=4;break}throw new Error("No file was added");case 4:this.url=this.requestSettings.url||this._service_url,o=this.preprocessBody(this.rawBody,a),s=t.createFormDataBody(o,i[0]),hn.tempRemoveContentHeader(this.requestSettings,Mn.request.bind(this,this,s,n),!1);case 7:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error.message;case 2:return e.abrupt("return",{text:t.text});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"canSendFileMessage",value:function(e,t){return!(null==t||!t[0])}},{key:"cleanConfig",value:function(e){delete e.type}},{key:"createFormDataBody",value:function(e,t){var n=new FormData;return n.append("file",t),Object.keys(e).forEach((function(t){n.append(t,String(e[t]))})),n}}]),t}(Fn);ya.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",ya.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",ya.DEFAULT_MODEL="whisper-1";var Ca=ya,Ra=function(){function e(){J(this,e)}return te(e,null,[{key:"buildTextToSpeechHeaders",value:function(e,t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":e}}},{key:"buildSpeechToTextHeaders",value:function(e){return{"Ocp-Apim-Subscription-Key":e,Accept:"application/json"}}},{key:"handleSpeechVerificationResult",value:function(e,t,n,a){e.error?a(fe.INVALID_KEY):n(t)}},{key:"buildSpeechKeyVerificationDetails",value:function(t){return{url:"https://".concat(t,".api.cognitive.microsoft.com/sts/v1.0/issuetoken"),method:"POST",createHeaders:function(e){return{"Ocp-Apim-Subscription-Key":"".concat(e)}},handleVerificationResult:e.handleSpeechVerificationResult}}},{key:"buildSummarizationHeader",value:function(e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"}}},{key:"handleLanguageVerificationResult",value:function(e,t,n,a){var i;"401"===(null==(i=e.error)?void 0:i.code)?a(fe.INVALID_KEY):n(t)}},{key:"buildLanguageKeyVerificationDetails",value:function(t){return{url:"".concat(t,"/language/analyze-text/jobs?api-version=2022-10-01-preview"),method:"POST",createHeaders:function(e){return{"Ocp-Apim-Subscription-Key":"".concat(e)}},handleVerificationResult:e.handleLanguageVerificationResult}}},{key:"handleTranslationVerificationResult",value:function(e,t,n,a){e.json().then((function(e){Array.isArray(e)||401e3!==e.error.code?n(t):a(fe.INVALID_KEY)}))}},{key:"buildTranslationKeyVerificationDetails",value:function(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:function(n){return e.buildTranslationHeaders(t,n)},handleVerificationResult:e.handleTranslationVerificationResult}}},{key:"buildTranslationHeaders",value:function(e,t){var n={"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"};return e&&(n["Ocp-Apim-Subscription-Region"]=e),n}}]),e}(),Na=function(e){function t(e){var n,a,i,r,o,s;J(this,t);var l=null==(r=null==(i=e.directConnection)?void 0:i.azure)?void 0:r.summarization,c=null==(o=e.directConnection)?void 0:o.azure;return(a=G(this,t,[e,Ra.buildSummarizationHeader,l.endpoint,c])).url="",a.textInputPlaceholderText="Insert text to summarize",null!==(n=(s=a.rawBody).language)&&void 0!==n||(s.language="en"),Object.assign(a.rawBody,l),a.url="".concat(l.endpoint,"/language/analyze-text/jobs?api-version=2022-10-01-preview"),a}var n,a,i;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=t[t.length-1].text;if(n)return{analysisInput:{documents:[{id:"1",language:e.language,text:n}]},tasks:[{kind:"ExtractiveSummarization"}]}}},{key:"callServiceAPI",value:(i=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),Mn.request(this,a,t),this.messages=t;case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)})},{key:"extractResultData",value:(a=$(j().mark((function e(t){var n,a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error.message;case 2:return this.messages&&this.completionsHandlers&&(a=t.headers.get("operation-location"),i={method:"GET",headers:null==(n=this.requestSettings)?void 0:n.headers},Mn.executePollRequest(this,a,i,this.messages)),e.abrupt("return",{makingAnotherRequest:!0});case 4:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"extractPollResultData",value:(n=$(j().mark((function e(t){var n,a,i,r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:if("running"!==t.status){e.next=4;break}return e.abrupt("return",{timeoutMS:2e3});case 4:if(!(t.errors.length>0)){e.next=6;break}throw t.errors[0];case 6:if(!(t.tasks.items[0].results.errors.length>0)){e.next=8;break}throw t.tasks.items[0].results.errors[0];case 8:n="",a=P(t.tasks.items[0].results.documents[0].sentences);try{for(a.s();!(i=a.n()).done;)r=i.value,n+=r.text}catch(e){a.e(e)}finally{a.f()}return e.abrupt("return",{text:n||""});case 12:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(function(e){function t(e,n,a,i,r){var o;return J(this,t),(o=G(this,t,[e,Ra.buildLanguageKeyVerificationDetails(a),n,i,r])).insertKeyPlaceholderText="Azure Language Subscription Key",o.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",o.permittedErrorPrefixes=["Access"],o}return V(t,e),te(t)}(Fn)),Oa=function(){function e(){J(this,e)}var t;return te(e,null,[{key:"poll",value:(t=$(j().mark((function e(t,n){var a,i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a={authorization:t,"content-type":"application/json"},e.t0="https://api.assemblyai.com/v2/transcript/",e.next=4,fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:n}),headers:a});case 4:return e.next=6,e.sent.json();case 6:e.t1=e.sent.id,i=e.t0.concat.call(e.t0,e.t1);case 8:if(r){e.next=24;break}return e.next=11,fetch(i,{headers:a});case 11:return e.next=13,e.sent.json();case 13:if("completed"!==(o=e.sent).status){e.next=18;break}r=o,e.next=22;break;case 18:if("error"!==o.status){e.next=20;break}throw new Error("Transcription failed: ".concat(o.error));case 20:return e.next=22,new Promise((function(e){return setTimeout(e,3e3)}));case 22:e.next=8;break;case 24:return e.abrupt("return",r);case 25:case"end":return e.stop()}}),e)}))),function(e,n){return t.apply(this,arguments)})},{key:"buildHeaders",value:function(e){return{Authorization:e,"Content-Type":"application/octet-stream"}}},{key:"handleVerificationResult",value:function(e,t,n,a){var i=e;i.error?"invalid_api_key"===i.error.code?a(fe.INVALID_KEY):a(fe.CONNECTION_FAILED):n(t)}},{key:"buildKeyVerificationDetails",value:function(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:e.handleVerificationResult}}}]),e}(),Aa=function(e){function t(e){var n,a;J(this,t);var i=null==(a=e.directConnection)?void 0:a.assemblyAI;return(n=G(this,t,[e,Oa.buildKeyVerificationDetails(),Oa.buildHeaders,i,{audio:{}}])).insertKeyPlaceholderText="AssemblyAI API Key",n.keyHelpUrl="https://www.assemblyai.com/app/account",n.introPanelMarkUp='\n
    AssemblyAI Audio
    \n

    Upload an audio file to transcribe it into text.\n

    \n Click here for more info.\n

    ',n.url="https://api.assemblyai.com/v2/upload",n.isTextInputDisabled=!0,n.textInputPlaceholderText="Upload an audio file",n.permittedErrorPrefixes=["Authentication","Invalid"],n.canSendMessage=t.canFileSendMessage,n}var n,a;return V(t,e),te(t,[{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){var i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(i=this.requestSettings)&&i.headers){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null!=a&&a[0]){e.next=4;break}throw new Error("No file was added");case 4:Mn.request(this,a[0],t,!1);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){var n,a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return i=null==(a=null==(n=this.requestSettings)?void 0:n.headers)?void 0:a.Authorization,e.next=5,Oa.poll(i,t.upload_url);case 5:return e.t0=e.sent.text,e.abrupt("return",{text:e.t0});case 7:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})}],[{key:"canFileSendMessage",value:function(e,t){return!(null==t||!t[0])}}]),t}(Fn),Ia=function(e){function t(e,n,a,i,r){var o;return J(this,t),(o=G(this,t,[e,Ra.buildSpeechKeyVerificationDetails(a),n,i,r])).insertKeyPlaceholderText="Azure Speech Subscription Key",o.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",o}return V(t,e),te(t)}(Fn),Da=function(e){function t(e){var n,a,i,r,o,s,l,c,d,u;J(this,t);var _=null==(s=null==(o=e.directConnection)?void 0:o.azure)?void 0:s.textToSpeech,p=null==(l=e.directConnection)?void 0:l.azure;return(r=G(this,t,[e,Ra.buildTextToSpeechHeaders.bind({},(null==_?void 0:_.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),_.region,p])).introPanelMarkUp='\n
    Azure Text To Speech
    \n

    Insert text to synthesize it to audio.\n

    \n Click here for more info.\n

    '),r.url="",Object.assign(r.rawBody,_),null!==(n=(c=r.rawBody).lang)&&void 0!==n||(c.lang="en-US"),null!==(a=(d=r.rawBody).name)&&void 0!==a||(d.name="en-US-JennyNeural"),null!==(i=(u=r.rawBody).gender)&&void 0!==i||(u.gender="Female"),r.url="https://".concat(_.region,".tts.speech.microsoft.com/cognitiveservices/v1"),r}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=t[t.length-1].text;if(n)return"\n \n ").concat(n,"\n \n ")}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),Mn.request(this,a,t,!1);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",new Promise((function(e){var n=new FileReader;n.readAsDataURL(t),n.onload=function(t){e({files:[{src:t.target.result,type:"audio"}]})}})));case 1:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Ia);Da.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";var wa=Da,xa=function(e){function t(e){var n,a,i,r;J(this,t);var o=null==(i=null==(a=e.directConnection)?void 0:a.azure)?void 0:i.speechToText,s=null==(r=e.directConnection)?void 0:r.azure;(n=G(this,t,[e,Ra.buildSpeechToTextHeaders,o.region,s,{audio:{files:{acceptedFormats:".wav,.ogg"}}}])).introPanelMarkUp='\n
    Azure Speech To Text
    \n

    Upload a .wav or .ogg audio file to transcribe it into text.\n

    \n Click here for more info.\n

    '),n.url="",n.isTextInputDisabled=!0,n.textInputPlaceholderText="Upload an audio file",n.canSendMessage=t.canFileSendMessage;var l=o.lang||"en-US";return n.url="https://".concat(o.region,".stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=").concat(l,"&format=detailed"),n.recordAudio=void 0,n}var n,a;return V(t,e),te(t,[{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n,a){var i,r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(i=this.requestSettings)&&i.headers){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null!=a&&a[0]){e.next=4;break}throw new Error("No file was added");case 4:null!=(r=this.requestSettings)&&r.headers&&(this.requestSettings.headers["Content-Type"]=a[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Mn.request(this,a[0],t,!1);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error;case 2:return e.abrupt("return",{text:t.DisplayText||""});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"canFileSendMessage",value:function(e,t){return!(null==t||!t[0])}}]),t}(Ia);xa.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";var Ma=xa,La=function(e){function t(e){var n,a,i,r;J(this,t);var o=null==(i=null==(a=e.directConnection)?void 0:a.azure)?void 0:i.translation,s=null==(r=e.directConnection)?void 0:r.azure;return(n=G(this,t,[e,Ra.buildTranslationKeyVerificationDetails(o.region),Ra.buildTranslationHeaders.bind({},null==o?void 0:o.region),s])).insertKeyPlaceholderText="Azure Translate Subscription Key",n.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",n.url="",n.url="https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=".concat(o.language||"es"),n}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e){var t=e[e.length-1].text;if(t)return[{Text:t}]}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(n),Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Array.isArray(t)){e.next=2;break}return e.abrupt("return",{text:(null==(n=t[0].translations)?void 0:n[0].text)||""});case 2:throw t.error;case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Fn),ka=function(){function e(){J(this,e)}var t,n,a,i;return te(e,null,[{key:"storeFiles",value:(i=$(j().mark((function e(t,n,a){var i,r,o,s;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=t.requestSettings.headers){e.next=3;break}return e.abrupt("return");case 3:return t.url="https://api.openai.com/v1/files",r=i[hn.CONTENT_TYPE],delete i[hn.CONTENT_TYPE],o=a.map(function(){var e=$(j().mark((function e(n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=new FormData,e.abrupt("return",(a.append("purpose","assistants"),a.append("file",n),new Promise((function(e){e(ba.directFetch(t,a,"POST",!1))}))));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),e.prev=7,e.next=10,Promise.all(o);case 10:return s=e.sent.map((function(e){return e.id})),e.abrupt("return",(i[hn.CONTENT_TYPE]=r,s));case 14:throw e.prev=14,e.t0=e.catch(7),i[hn.CONTENT_TYPE]=r,hn.displayError(n,e.t0),t.completionsHandlers.onFinish(),e.t0;case 17:case"end":return e.stop()}}),e,null,[[7,14]])}))),function(e,t,n){return i.apply(this,arguments)})},{key:"getType",value:function(e,t){var n=e[t].path;return!n||n.endsWith("png")?"image":"any"}},{key:"getFiles",value:(a=$(j().mark((function t(n,a){var i,r;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=a.map((function(e){var t=e.fileId;return n.url="https://api.openai.com/v1/files/".concat(t,"/content"),new Promise((function(e){e(ba.directFetch(n,void 0,"GET",!1))}))})),t.next=3,Promise.all(i);case 3:return r=t.sent.map((function(t,n){return new Promise((function(i){var r=new FileReader;r.readAsDataURL(t),r.onload=function(t){i({src:t.target.result,name:a[n].name,type:e.getType(a,n)})}}))})),t.next=6,Promise.all(r);case 6:return t.abrupt("return",t.sent);case 7:case"end":return t.stop()}}),t)}))),function(e,t){return a.apply(this,arguments)})},{key:"getFileName",value:function(e){var t=e.split("/");return t[t.length-1]}},{key:"getFileDetails",value:function(t,n){var a,i=[];return null!=(a=null==n?void 0:n.text)&&a.value&&t.content.forEach((function(t){var n,a;null==(a=null==(n=t.text)?void 0:n.annotations)||a.forEach((function(t){var n;t.text&&t.text.startsWith("sandbox:")&&null!=(n=t.file_path)&&n.file_id&&i.push({path:t.text,fileId:t.file_path.file_id,name:e.getFileName(t.text)})}))})),null!=n&&n.image_file&&i.push({fileId:n.image_file.file_id}),i}},{key:"getFilesAndNewText",value:(n=$(j().mark((function t(n,a,i){var r,o,s;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=a.length>0,!t.t0){t.next=6;break}return t.next=4,e.getFiles(n,a);case 4:s=t.sent,null!=(r=null==i?void 0:i.text)&&r.value&&s.forEach((function(e,t){var n;if(e.src){var r=a[t].path;null!=(n=null==i?void 0:i.text)&&n.value&&r&&(i.text.value=i.text.value.replace(r,e.src))}}));case 6:return t.abrupt("return",{files:s,text:null==(o=null==i?void 0:i.text)?void 0:o.value});case 7:case"end":return t.stop()}}),t)}))),function(e,t,a){return n.apply(this,arguments)})},{key:"getFilesAndText",value:(t=$(j().mark((function t(n,a,i){var r;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.getFileDetails(a,i),t.next=3,e.getFilesAndNewText(n,r,i);case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})}]),e}(),Pa=function(e){function t(e){var n,a,i,r,o,s,l,c,d;J(this,t);var u=JSON.parse(JSON.stringify(e.directConnection)),_=u.openAI;(i=G(this,t,[e,ba.buildKeyVerificationDetails(),ba.buildHeaders,_])).insertKeyPlaceholderText="OpenAI API Key",i.keyHelpUrl="https://platform.openai.com/account/api-keys",i.url="",i.permittedErrorPrefixes=["Incorrect"],i.searchedForThreadId=!1,i.config={},i.newAssistantDetails={model:"gpt-4"};var p=null==(r=u.openAI)?void 0:r.assistant;if("object"==Z(p)){i.config=p,Object.assign(i.newAssistantDetails,i.config.new_assistant);var m=(null==(s=null==(o=e.directConnection)?void 0:o.openAI)?void 0:s.assistant).function_handler;m&&(i._functionHandler=m)}else null!=(l=u.openAI)&&l.assistant&&(u.openAI.assistant=p);return null!==(n=(c=i.requestSettings).headers)&&void 0!==n||(c.headers={}),null!==(a=(d=i.requestSettings.headers)["OpenAI-Beta"])&&void 0!==a||(d["OpenAI-Beta"]="assistants=v1"),i.maxMessages=1,i}var n,a,i,r,o,s;return V(t,e),te(t,[{key:"processMessage",value:function(e,t){var n=this.totalMessagesMaxCharLength||-1;return{content:Ln.getCharacterLimitMessages(e,n)[0].text||"",role:"user",file_ids:t}}},{key:"createNewThreadMessages",value:function(e,t,n){var a=JSON.parse(JSON.stringify(e)),i=this.processMessage(t,n);return a.thread={messages:[i]},a}},{key:"callService",value:function(e,n,a){if(this.sessionId){this.url="".concat(t.THREAD_PREFIX,"/").concat(this.sessionId,"/messages");var i=this.processMessage(n,a);Mn.request(this,i,e)}else{this.url="".concat(t.THREAD_PREFIX,"/runs");var r=this.createNewThreadMessages(this.rawBody,n,a);Mn.request(this,r,e)}this.messages=e}},{key:"callServiceAPI",value:(s=$(j().mark((function e(t,n,a){var i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null===(i=(r=this.rawBody).assistant_id)||void 0===i){e.next=6;break}e.next=12;break;case 6:if(e.t0=this.config.assistant_id,e.t0){e.next=11;break}return e.next=10,this.createNewAssistant();case 10:e.t0=e.sent;case 11:r.assistant_id=e.t0;case 12:if(this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messages),!a){e.next=19;break}return e.next=16,ka.storeFiles(this,t,a);case 16:e.t1=e.sent,e.next=20;break;case 19:e.t1=void 0;case 20:o=e.t1,this.requestSettings.method="POST",this.callService(t,n,o);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return s.apply(this,arguments)})},{key:"createNewAssistant",value:(o=$(j().mark((function e(){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.url=t.NEW_ASSISTANT_URL,e.next=4,ba.directFetch(this,JSON.parse(JSON.stringify(this.newAssistantDetails)),"POST");case 4:return n=e.sent,e.abrupt("return",(this.config.assistant_id=n.id,this.config.assistant_id));case 8:e.prev=8,e.t0=e.catch(0),console.error(e.t0),console.error("Failed to create a new assistant");case 11:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(){return o.apply(this,arguments)})},{key:"searchPreviousMessagesForThreadId",value:function(e){var t=e.find((function(e){return e._sessionId}));t&&(this.sessionId=t._sessionId),this.searchedForThreadId=!0}},{key:"extractResultData",value:(r=$(j().mark((function e(n){var a,i,r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.error){e.next=2;break}throw n.error.message;case 2:return e.next=4,this.assignThreadAndRun(n);case 4:return i="".concat(t.THREAD_PREFIX,"/").concat(this.sessionId,"/runs/").concat(this.run_id),r={method:"GET",headers:null==(a=this.requestSettings)?void 0:a.headers},e.abrupt("return",(Mn.executePollRequest(this,i,r,this.messages),{makingAnotherRequest:!0}));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"assignThreadAndRun",value:(i=$(j().mark((function e(n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionId){e.next=8;break}return this.url="".concat(t.THREAD_PREFIX,"/").concat(this.sessionId,"/runs"),e.next=4,ba.directFetch(this,JSON.parse(JSON.stringify(this.rawBody)),"POST");case 4:a=e.sent,this.run_id=a.id,e.next=9;break;case 8:this.sessionId=n.thread_id,this.run_id=n.id,this.messages&&(this.messages.messages[this.messages.messages.length-1]._sessionId=this.sessionId);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"extractPollResultData",value:(a=$(j().mark((function e(n){var a,i,r,o,s,l,c,d,u,_,p,m,g,E,S;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(l=n.status,c=n.required_action,"queued"!==l&&"in_progress"!==l){e.next=3;break}return e.abrupt("return",{timeoutMS:t.POLLING_TIMEOUT_MS});case 3:if("completed"!==l||!this.messages){e.next=21;break}return this.url="".concat(t.THREAD_PREFIX,"/").concat(n.thread_id,"/messages"),e.next=7,ba.directFetch(this,{},"GET");case 7:if(d=e.sent,e.t0=this.deepChat.responseInterceptor,!e.t0){e.next=13;break}return e.next=12,null==(i=(a=this.deepChat).responseInterceptor)?void 0:i.call(a,d);case 12:d=e.sent;case 13:return u=d.data[0],_=u.content.find((function(e){return!!e.text||!!e.image_file})),e.next=17,ka.getFilesAndText(this,u,_);case 17:return p=e.sent,m=p.text,g=p.files,e.abrupt("return",{text:m,_sessionId:this.sessionId,files:g});case 21:if(E=null==(r=null==c?void 0:c.submit_tool_outputs)?void 0:r.tool_calls,"requires_action"!==l||!E){e.next=32;break}return e.next=25,this.handleTools(E);case 25:return S=e.sent,e.next=28,null==(s=(o=this.deepChat).responseInterceptor)?void 0:s.call(o,S);case 28:if(e.t1=e.sent,e.t1){e.next=31;break}e.t1=S;case 31:return e.abrupt("return",e.t1);case 32:throw Error("Thread run status: ".concat(l));case 33:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"handleTools",value:(n=$(j().mark((function e(n){var a,i,r;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._functionHandler){e.next=2;break}throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Assistant) object.");case 2:return a=n.map((function(e){return{name:e.function.name,arguments:e.function.arguments}})),e.next=5,this._functionHandler(a);case 5:if(i=e.sent,Array.isArray(i)&&!i.find((function(e){return"string"!=typeof e}))&&n.length===i.length){e.next=8;break}throw Error("Response must contain an array of strings for each individual function/tool_call, see https://deepchat.dev/docs/directConnection/OpenAI/#assistant-functions.");case 8:return r=i.map((function(e,t){return{tool_call_id:n[t].id,output:e}})),this.url="".concat(t.THREAD_PREFIX,"/").concat(this.sessionId,"/runs/").concat(this.run_id,"/submit_tool_outputs"),e.next=12,ba.directFetch(this,{tool_outputs:r},"POST");case 12:return e.abrupt("return",{timeoutMS:t.POLLING_TIMEOUT_MS});case 13:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})}]),t}(Fn);Pa.THREAD_PREFIX="https://api.openai.com/v1/threads",Pa.NEW_ASSISTANT_URL="https://api.openai.com/v1/assistants",Pa.POLLING_TIMEOUT_MS=800;var Fa=Pa,Ua=function(e){function t(e){var n,a;J(this,t);var i=e.directConnection,r=null==i?void 0:i.openAI;(n=G(this,t,[e,ba.buildKeyVerificationDetails(),ba.buildHeaders,r,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}])).insertKeyPlaceholderText="OpenAI API Key",n.keyHelpUrl="https://platform.openai.com/account/api-keys",n.introPanelMarkUp='\n
    OpenAI DALL·E
    \n

    Insert text to generate an image.

    \n

    Upload 1 PNG image to generate its variation and optionally insert text to specify the change.

    \n

    Upload 2 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.

    \n

    Click here for more info.

    ',n.url="",n.permittedErrorPrefixes=["Incorrect","Invalid input image"];var o=null==(a=null==i?void 0:i.openAI)?void 0:a.images;if(n.camera){var s="object"==Z(o)&&o.size?Number.parseInt(o.size):1024;n.camera.files={dimensions:{width:s,height:s}}}return"object"==Z(o)&&Object.assign(n.rawBody,o),n.canSendMessage=t.canFileSendMessage,n}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=JSON.parse(JSON.stringify(e));return t&&""!==t&&(n.prompt=t),n}},{key:"callApiWithImage",value:function(e,n,a){var i,r,o,s=null==(r=null==(i=n[n.length-1])?void 0:i.text)?void 0:r.trim();if(a[1]||s&&""!==s){this.url=t.IMAGE_EDIT_URL;var l=this.preprocessBody(this.rawBody,s);o=t.createFormDataBody(l,a[0],a[1])}else this.url=t.IMAGE_VARIATIONS_URL,o=t.createFormDataBody(this.rawBody,a[0]);hn.tempRemoveContentHeader(this.requestSettings,Mn.request.bind(this,this,o,e),!1)}},{key:"callServiceAPI",value:(a=$(j().mark((function e(n,a,i){var r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(r=this.requestSettings)&&r.headers){e.next=2;break}throw new Error("Request settings have not been set up");case 2:if(null==i||!i[0]){e.next=6;break}this.callApiWithImage(n,a,i),e.next=11;break;case 6:if(this.requestSettings){e.next=8;break}throw new Error("Request settings have not been set up");case 8:this.url=t.IMAGE_GENERATION_URL,o=this.preprocessBody(this.rawBody,a[a.length-1].text),Mn.request(this,o,n);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error.message;case 2:return e.abrupt("return",{files:t.data.map((function(e){return e.url?{src:e.url,type:"image"}:{src:"".concat(na).concat(e.b64_json),type:"image"}}))});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}],[{key:"canFileSendMessage",value:function(e,t){return!(null==t||!t[0])||!(!e||""===e.trim())}},{key:"createFormDataBody",value:function(e,t,n){var a=new FormData;return a.append("image",t),n&&a.append("mask",n),Object.keys(e).forEach((function(t){a.append(t,String(e[t]))})),a}}]),t}(Fn);Ua.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",Ua.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",Ua.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";var Ba=Ua,Ga=function(e){function t(e){var n,a,i,r,o,s,l;J(this,t);var c=JSON.parse(JSON.stringify(e.directConnection)),d=c.openAI;(i=G(this,t,[e,ba.buildKeyVerificationDetails(),ba.buildHeaders,d])).insertKeyPlaceholderText="OpenAI API Key",i.keyHelpUrl="https://platform.openai.com/account/api-keys",i.url="https://api.openai.com/v1/chat/completions",i.permittedErrorPrefixes=["Incorrect"],i._systemMessage=t.generateSystemMessage("You are a helpful assistant.");var u=null==(r=c.openAI)?void 0:r.chat;if("object"==Z(u)){u.system_prompt&&(i._systemMessage=t.generateSystemMessage(u.system_prompt));var _=(null==(s=null==(o=e.directConnection)?void 0:o.openAI)?void 0:s.chat).function_handler;_&&(i._functionHandler=_),i.cleanConfig(u),Object.assign(i.rawBody,u)}return null!==(n=i.maxMessages)&&void 0!==n||(i.maxMessages=-1),null!==(a=(l=i.rawBody).model)&&void 0!==a||(l.model="gpt-3.5-turbo"),i}var n,a,i;return V(t,e),te(t,[{key:"cleanConfig",value:function(e){delete e.system_prompt,delete e.function_handler}},{key:"preprocessBody",value:function(e,n){var a,i=JSON.parse(JSON.stringify(e)),r=Ln.getCharacterLimitMessages(n,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.content.length:-1).map((function(e){return{content:t.getContent(e),role:e.role===we.USER_ROLE?"user":"assistant"}}));return n.find((function(e){return e.files&&e.files.length>0}))&&(null!==(a=i.max_tokens)&&void 0!==a||(i.max_tokens=300)),i.messages=[this._systemMessage].concat(k(r)),i}},{key:"callServiceAPI",value:(i=$(j().mark((function e(t,n){var a,i;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),(i=this.deepChat.stream)&&("object"!=Z(i)||!i.simulation)||a.stream?(a.stream=!0,An.request(this,a,t)):Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)})},{key:"extractResultData",value:(a=$(j().mark((function e(t,n,a){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.error){e.next=2;break}throw t.error.message;case 2:return e.abrupt("return",t.choices[0].delta?{text:t.choices[0].delta.content||""}:t.choices[0].message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,n,a):{text:t.choices[0].message.content}:{text:""});case 3:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"handleTools",value:(n=$(j().mark((function e(t,n,a){var i,r,o,s,l,c,d,u,_,p;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.tool_calls&&n&&a&&this._functionHandler){e.next=2;break}throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Chat) object.");case 2:return c=JSON.parse(JSON.stringify(a)),d=t.tool_calls.map((function(e){return{name:e.function.name,arguments:e.function.arguments}})),e.next=6,null==(i=this._functionHandler)?void 0:i.call(this,d);case 6:if(!(u=e.sent).text){e.next=15;break}return _={text:u.text},e.next=11,null==(o=(r=this.deepChat).responseInterceptor)?void 0:o.call(r,_);case 11:if(e.t0=e.sent,e.t0){e.next=14;break}e.t0=_;case 14:return e.abrupt("return",e.t0);case 15:if(c.messages.push(t),(!Array.isArray(u)||u.find((function(e){return"string"!=typeof e})))&&d.length!==u.length){e.next=29;break}return u.forEach((function(e,n){var a,i=null==(a=t.tool_calls)?void 0:a[n];null==c||c.messages.push({role:"tool",tool_call_id:null==i?void 0:i.id,name:null==i?void 0:i.function.name,content:e.response})})),delete c.tools,delete c.tool_choice,e.next=19,null==n?void 0:n(c).then((function(e){return hn.processResponseByType(e)}));case 19:return p=e.sent,e.next=22,null==(l=(s=this.deepChat).responseInterceptor)?void 0:l.call(s,p);case 22:if(e.t1=e.sent,e.t1){e.next=25;break}e.t1=p;case 25:if(!(p=e.t1).error){e.next=28;break}throw p.error.message;case 28:return e.abrupt("return",{text:p.choices[0].message.content||""});case 29:throw 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.");case 30:case"end":return e.stop()}}),e,this)}))),function(e,t,a){return n.apply(this,arguments)})}],[{key:"generateSystemMessage",value:function(e){return{role:"system",content:e}}},{key:"getContent",value:function(e){if(e.files&&e.files.length>0){var t=e.files.map((function(e){return{type:"image_url",image_url:{url:e.src}}}));return e.text&&e.text.trim().length>0&&t.unshift({type:"text",text:e.text}),t}return e.text}}]),t}(Fn),Ya=function(e){function t(e){var n,a,i;J(this,t);var r=JSON.parse(JSON.stringify(e.directConnection)),o=null==(i=r.cohere)?void 0:i.chat;return a=G(this,t,[e,"https://api.cohere.ai/v1/chat","Ask me anything!",o,r.cohere]),"object"==Z(o)&&Object.assign(a.rawBody,o),null!==(n=a.maxMessages)&&void 0!==n||(a.maxMessages=-1),a}var n,a;return V(t,e),te(t,[{key:"preprocessBody",value:function(e,t){var n=JSON.parse(JSON.stringify(e)),a=t.filter((function(e){return e.text}));return n.query=a[a.length-1].text,n.chat_history=a.slice(0,a.length-1).map((function(e){return{text:e.text,user_name:"ai"===e.role?"CHATBOT":"USER"}})),n}},{key:"callServiceAPI",value:(a=$(j().mark((function e(t,n){var a;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.requestSettings){e.next=2;break}throw new Error("Request settings have not been set up");case 2:a=this.preprocessBody(this.rawBody,n),Mn.request(this,a,t);case 4:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"extractResultData",value:(n=$(j().mark((function e(t){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.message){e.next=2;break}throw t.message;case 2:return e.abrupt("return",{text:t.text});case 3:case"end":return e.stop()}}),e)}))),function(e){return n.apply(this,arguments)})}]),t}(Sa),Ha=function(){function e(){J(this,e)}return te(e,null,[{key:"create",value:function(e){var t=e.directConnection,n=e.request,a=e.demo;if(e.webModel)return new Kn(e);if(t){if(t.openAI)return t.openAI.images?new Ba(e):t.openAI.speechToText?new Ca(e):t.openAI.textToSpeech?new Ta(e):t.openAI.assistant?new Fa(e):new Ga(e);if(t.assemblyAI)return new Aa(e);if(t.cohere)return t.cohere.textGeneration?new ha(e):t.cohere.summarization?new fa(e):new Ya(e);if(t.huggingFace)return t.huggingFace.textGeneration?new la(e):t.huggingFace.summarization?new da(e):t.huggingFace.translation?new pa(e):t.huggingFace.fillMask?new ga(e):t.huggingFace.questionAnswer?new ca(e):t.huggingFace.audioSpeechRecognition?new sa(e):t.huggingFace.audioClassification?new ea(e):t.huggingFace.imageClassification?new ta(e):new ua(e);if(t.azure){if(t.azure.speechToText)return new Ma(e);if(t.azure.textToSpeech)return new wa(e);if(t.azure.summarization)return new Na(e);if(t.azure.translation)return new La(e)}if(t.stabilityAI)return t.stabilityAI.imageToImage?new _a(e):t.stabilityAI.imageToImageUpscale?new ra(e):t.stabilityAI.imageToImageMasking?new oa(e):new ma(e)}return n?new Pn(e):new Pn(e,void 0,a||!0)}}]),e}(),qa=function(){function e(){J(this,e)}return te(e,null,[{key:"appendStyleSheetToHead",value:function(){var t=document.getElementsByTagName("head")[0];if(!Array.from(t.getElementsByTagName("link")).some((function(t){return t.getAttribute("href")===e.FONT_URL}))){var n=document.createElement("link");n.rel="stylesheet",n.href=e.FONT_URL,t.appendChild(n)}}}]),e}();qa.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap";var Va=qa,za=te((function e(){J(this,e)}));function ja(e){return function(t,n){Object.defineProperty(t,n,{});var a=t.constructor,i=n.toLocaleLowerCase();a._attributes_[i]=za.attibutes[e],a._attributeToProperty_[i]=n}}za.attibutes={string:function(e){return e},number:function(e){return parseFloat(e)},boolean:function(e){return"true"===e},object:function(e){return JSON.parse(e)},array:function(e){return JSON.parse(e)},function:function(e){return new Function("return ".concat(e))()}};var Wa=function(){function e(){J(this,e)}return te(e,null,[{key:"colorToHex",value:function(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(e){return parseInt(e).toString(16).padStart(2,"0")})).join(""))}},{key:"set",value:function(t,n){var a,i,r,o;if(null!=(i=null==(a=null==n?void 0:n.loading)?void 0:a.bubble)&&i.color){var s=e.colorToHex(null==(o=null==(r=null==n?void 0:n.loading)?void 0:r.bubble)?void 0:o.color);t.style.setProperty("--message-dots-color",s),t.style.setProperty("--message-dots-color-fade","".concat(s,"33"))}else t.style.setProperty("--message-dots-color","#848484"),t.style.setProperty("--message-dots-color-fade","#55555533")}}]),e}(),$a=function(){function e(t,n,a){J(this,e),this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,a),this._isDisplayed=!0):n&&(this._elementRef=this.createInternalIntroPanel(n,a),this._isDisplayed=!0)}return te(e,[{key:"createIntroPanelWithChild",value:function(t,n){var a=e.createIntroPanel(n);return"none"===t.style.display&&(t.style.display="block"),a.appendChild(t),a}},{key:"createInternalIntroPanel",value:function(t,n){var a=e.createIntroPanel(n);return a.id="internal-intro-panel",a.innerHTML=t,a}},{key:"hide",value:function(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}},{key:"display",value:function(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}],[{key:"createIntroPanel",value:function(e){var t=document.createElement("div");return t.classList.add("intro-panel"),Object.assign(t.style,e),t}}]),e}(),Ka=function(){function e(){J(this,e)}return te(e,null,[{key:"getText",value:function(e,t){var n;if(!(e.directConnection||e.request||e.webModel||e.demo))return"Connect to any API using the [request](https://deepchat.dev/docs/connect#Request)\n property or a popular service via\n [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n \n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n \n To get started checkout the [Start](https://deepchat.dev/start) page and\n live code [examples](https://deepchat.dev/examples/frameworks).\n \n To remove this message set the [demo](https://deepchat.dev/docs/demo#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 a=null==(n=e.directConnection.openAI)?void 0:n.chat;if("object"==Z(a)&&a.tools&&!a.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object."}else if(e.request&&!e.request.url&&!e.request.handler)return"Please define a `url` or a `handler` property inside the [request](https://deepchat.dev/docs/connect#Request) object.";return null}}]),e}(),Qa=function(){function e(){J(this,e)}var t;return te(e,null,[{key:"createImage",value:function(e,t){var n=new Image;return n.src=e.src,un.scrollDownOnImageLoad(n.src,t),un.processContent("image",n,n.src,e.name)}},{key:"addNewImageMessage",value:(t=$(j().mark((function t(n,a,i){var r,o;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=e.createImage(a,n.elementRef),(o=n.createNewMessageElement("",i)).bubbleElement.appendChild(r),o.bubbleElement.classList.add("image-message"),un.addMessage(n,o,"image",i);case 2:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"createAudioElement",value:function(e,t){var n=document.createElement("audio");return n.src=e.src,n.classList.add("audio-player"),n.controls=!0,ce.IS_SAFARI&&(n.classList.add("audio-player-safari"),n.classList.add(t===we.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),n}},{key:"addNewAudioMessage",value:function(t,n,a){var i=e.createAudioElement(n,a),r=t.createNewMessageElement("",a);r.bubbleElement.appendChild(i),r.bubbleElement.classList.add("audio-message"),un.addMessage(t,r,"audio",a)}},{key:"createAnyFile",value:function(e){var t=document.createElement("div");t.classList.add("any-file-message-contents");var n=document.createElement("div");n.classList.add("any-file-message-icon-container");var a=Yn.createSVGElement('\n\n\n\t\n\t\t\n\t\n\n\n\t\n\t\t\n\t\n\n\n\t\n\t\t\n\t\n\n\n\t\n\t\t\n\t\n\n\n\t\n\t\t\n\t\n\n');a.classList.add("any-file-message-icon"),n.appendChild(a);var i=document.createElement("div");return i.classList.add("any-file-message-text"),i.textContent=e.name||un.DEFAULT_FILE_NAME,t.appendChild(n),t.appendChild(i),un.processContent("any",t,e.src,i.textContent)}},{key:"addNewAnyFileMessage",value:function(t,n,a){var i=t.createNewMessageElement("",a),r=e.createAnyFile(n);i.bubbleElement.classList.add("any-file-message-bubble"),i.bubbleElement.appendChild(r),un.addMessage(t,i,"file",a)}},{key:"addMessages",value:function(t,n,a){n.forEach((function(n){var i,r;n.ref&&(n=un.removeFileRef(n)),"audio"===n.type||null!=(i=n.src)&&i.startsWith("data:audio")?e.addNewAudioMessage(t,n,a):"image"===n.type||null!=(r=n.src)&&r.startsWith("data:image")?e.addNewImageMessage(t,n,a):e.addNewAnyFileMessage(t,n,a)}))}}]),e}(),Xa=function(e){function t(e,n,a){var i,r,o;J(this,t),i=G(this,t,[e]);var s=n.permittedErrorPrefixes,l=n.introPanelMarkUp,c=n.demo;return i._errorMessageOverrides=null==(r=e.errorMessages)?void 0:r.overrides,i._onClearMessages=_n.onClearMessages.bind(Y(i),e),i._onError=_n.onError.bind(Y(i),e),i._displayLoadingMessage=t.getDisplayLoadingMessage(e,n),i._permittedErrorPrefixes=s,i.addSetupMessageIfNeeded(e,n)||i.populateIntroPanel(a,l,e.introPanelStyle),i.addIntroductoryMessage(e,n),e.initialMessages&&i.populateInitialMessages(e.initialMessages),i._displayServiceErrorMessages=null==(o=e.errorMessages)?void 0:o.displayServiceErrorMessages,e.getMessages=function(){return JSON.parse(JSON.stringify(i.messages))},e.clearMessages=i.clearMessages.bind(Y(i),n),e.refreshMessages=i.refreshTextMessages.bind(Y(i)),e.scrollToBottom=ve.scrollToBottom.bind(Y(i),i.elementRef),e._addMessage=function(e,t){i.addNewMessage(Q(Q({},e),{},{sendUpdate:!!t}),!t)},n.isWebModel()&&n.setUpMessages(Y(i)),c&&i.prepareDemo(c),e.textToSpeech&&ye.processConfig(e.textToSpeech,(function(e){i.textToSpeech=e})),i}var n;return V(t,e),te(t,[{key:"prepareDemo",value:function(e){"object"==Z(e)&&(e.response&&(this.customDemoResponse=e.response),e.displayErrors&&(e.displayErrors.default&&this.addNewErrorMessage("",""),e.displayErrors.service&&this.addNewErrorMessage("service",""),e.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),e.displayLoadingBubble&&this.addLoadingMessage())}},{key:"addSetupMessageIfNeeded",value:function(e,t){var n=Ka.getText(e,t);if(n){var a=this.createAndAppendNewMessageElement(n,we.AI_ROLE);this.applyCustomStyles(a,we.AI_ROLE,!1)}return!!n}},{key:"addIntroductoryMessage",value:function(e,t){var n,a;null!=e&&e.shadowRoot&&(this._introMessage=e.introMessage);var i,r=this._introMessage;(null!=t&&t.isWebModel()&&(null!==(n=r)&&void 0!==n||(r=t.getIntroMessage(r))),r)&&(null!=r&&r.text?i=this.createAndAppendNewMessageElement(r.text,we.AI_ROLE):null!=r&&r.html&&(i=Fe.add(this,r.html,we.AI_ROLE,this.messageElementRefs)),i&&(this.applyCustomStyles(i,we.AI_ROLE,!1,null==(a=this.messageStyles)?void 0:a.intro),i.outerContainer.classList.add("deep-chat-intro")))}},{key:"removeIntroductoryMessage",value:function(){var e=this.messageElementRefs[0];e.outerContainer.classList.contains("deep-chat-intro")&&(e.outerContainer.remove(),this.messageElementRefs.shift())}},{key:"populateInitialMessages",value:function(e){var t=this;e.forEach((function(e){Ce.processInitialMessageFile(e),t.addNewMessage(e,!0)})),setTimeout((function(){return ve.scrollToBottom(t.elementRef)}),0)}},{key:"addNewMessage",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=t.createMessageContent(e),i={status:e.overwrite};if(!e.ignoreText&&void 0!==a.text&&null!==e.text&&(this.addNewTextMessage(a.text,a.role,i),!n&&this.textToSpeech&&a.role!==we.USER_ROLE&&ye.speak(a.text,this.textToSpeech)),a.files&&Array.isArray(a.files)&&Qa.addMessages(this,a.files,a.role),void 0!==a.html&&null!==a.html){var r=Fe.add(this,a.html,a.role,this.messageElementRefs,i);ke.isElementTemporary(r)&&delete a.html}this.isValidMessageContent(a)&&this.updateStateOnMessage(a,e.overwrite,e.sendUpdate,n)}},{key:"isValidMessageContent",value:function(e){return e.text||e.html||e.files&&e.files.length>0}},{key:"updateStateOnMessage",value:function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];t||this.messages.push(e),n&&this.sendClientUpdate(e,a)}},{key:"removeMessageOnError",value:function(){var e=this.messageElementRefs[this.messageElementRefs.length-1],n=null==e?void 0:e.bubbleElement;(null!=n&&n.classList.contains(En.MESSAGE_CLASS)&&""===n.textContent||t.isTemporaryElement(e))&&this.removeLastMessage()}},{key:"addNewErrorMessage",value:function(e,n){var a,i,r,o,s;this.removeMessageOnError();var l=t.createBaseElements(),c=l.outerContainer,d=l.bubbleElement;d.classList.add("error-message-text");var u=this.getPermittedMessage(n)||(null==(a=this._errorMessageOverrides)?void 0:a[e])||(null==(i=this._errorMessageOverrides)?void 0:i.default)||"Error, please try again.";this.renderText(d,u);var _=pn.extractParticularSharedStyles(["fontSize","fontFamily"],null==(r=this.messageStyles)?void 0:r.default);pn.applyCustomStylesToElements(l,!1,_),pn.applyCustomStylesToElements(l,!1,null==(o=this.messageStyles)?void 0:o.error),this.elementRef.appendChild(c),ve.scrollToBottom(this.elementRef),this.textToSpeech&&ye.speak(u,this.textToSpeech),null==(s=this._onError)||s.call(this,u)}},{key:"getPermittedMessage",value:function(e){if(e){if(this._displayServiceErrorMessages)return e;if("string"==typeof e&&this._permittedErrorPrefixes){var n=t.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,e);if(n)return n}else if(Array.isArray(e)&&this._permittedErrorPrefixes)for(var a=0;a0&&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(t,n,a){0===a["outside-right"].length&&a["outside-left"].length>0?(t[0].classList.add(e.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),n.classList.add(e.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===a["outside-left"].length&&a["outside-right"].length>0&&(t[3].classList.add(e.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),n.classList.add(e.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}},{key:"adjustOutsideSubmit",value:function(t,n,a){if(!(a["inside-left"].length>0||a["inside-right"].length>0)){if(0===a["outside-right"].length&&a["outside-left"].length>0)return t[0].classList.add(e.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),n.classList.add(e.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),a["outside-left"].map((function(e){return e.button.elementRef.classList.add("submit-button-enlarged")}));if(0===a["outside-left"].length&&a["outside-right"].length>0)return t[3].classList.add(e.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),n.classList.add(e.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),a["outside-right"].map((function(e){return e.button.elementRef.classList.add("submit-button-enlarged")}))}}},{key:"set",value:function(t,n,a,i){!!e.adjustOutsideSubmit(n,a,i)||e.adjustForOutsideButton(n,a,i),e.adjustInputPadding(t,i)}}]),e}();Za.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Za.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Za.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Za.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";var Ja=Za,ei=function(){function e(){J(this,e)}return te(e,null,[{key:"create",value:function(){return Array.from({length:4}).map((function(e,t){var n=document.createElement("div");return n.classList.add("input-button-container"),(0===t||3===t)&&n.classList.add("outer-button-container"),(1===t||2===t)&&n.classList.add("inner-button-container"),n}))}},{key:"add",value:function(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(e){return"outside-left"===e?0:"inside-left"===e?1:"inside-right"===e?2:3}},{key:"addButton",value:function(t,n,a){n.classList.add(a);var i=e.getContainerIndex(a);t[i].appendChild(n),3===i&&n.classList.add("outside-right")}}]),e}(),ti=["camera","gifs","images","audio","mixedFiles","submit","microphone"],ni=function(){function e(){J(this,e)}return te(e,null,[{key:"createTextElement",value:function(e){var t=document.createElement("div");return t.classList.add("text-button"),t.innerText=e,t}},{key:"createElement",value:function(t,n){return n?e.createTextElement(t):Yn.createSVGElement(t)}},{key:"createCustomElement",value:function(t,n){var a,i,r,o,s=null==n?void 0:n[t];return null!=(a=null==s?void 0:s.text)&&a.content?e.createElement(null==(i=null==s?void 0:s.text)?void 0:i.content,!0):null!=(r=null==s?void 0:s.svg)&&r.content?e.createElement(null==(o=null==s?void 0:s.svg)?void 0:o.content,!1):void 0}},{key:"processElement",value:function(e,t){null!=t&&t.classList.contains("text-button")||e.classList.add("input-button-svg")}},{key:"createSpecificStateElement",value:function(t,n,a){var i;return a&&(i=e.createCustomElement(n,a)),e.processElement(t,i),i}},{key:"create",value:function(t,n,a){var i={};if(!a)return e.processElement(t),i;var r=e.createSpecificStateElement(t,n[0],a);i[n[0]]=r;var o=r;return n.slice(1).forEach((function(t){o=e.createCustomElement(t,a)||o,i[t]=o})),i}}]),e}(),ai=function(){function e(){J(this,e)}return te(e,null,[{key:"unsetAllCSS",value:function(e,t){var n,a;t.container&&re.unsetAllCSSMouseStates(e,t.container),null!=(n=t.svg)&&n.styles&&re.unsetAllCSSMouseStates(e.children[0],t.svg.styles),null!=(a=t.text)&&a.styles&&re.unsetAllCSSMouseStates(e.children[0],t.text.styles)}},{key:"unsetActionCSS",value:function(e,t){var n,a;t.container&&re.unsetActivityCSSMouseStates(e,t.container),null!=(n=t.svg)&&n.styles&&re.unsetActivityCSSMouseStates(e.children[0],t.svg.styles),null!=(a=t.text)&&a.styles&&re.unsetActivityCSSMouseStates(e.children[0],t.text.styles)}},{key:"setElementsCSS",value:function(e,t,n){var a,i,r,o,s;Object.assign(e.style,null==(a=t.container)?void 0:a[n]),Object.assign(e.children[0].style,null==(r=null==(i=t.svg)?void 0:i.styles)?void 0:r[n]),Object.assign(e.children[0].style,null==(s=null==(o=t.text)?void 0:o.styles)?void 0:s[n])}},{key:"setElementCssUpToState",value:function(t,n,a){e.setElementsCSS(t,n,"default"),"default"!==a&&(e.setElementsCSS(t,n,"hover"),"hover"!==a&&e.setElementsCSS(t,n,"click"))}}]),e}(),ii=function(){function e(t,n,a,i){J(this,e),this._mouseState={state:"default"},this.elementRef=t,this._customStyles=a,this.position=n,this.dropupText=i}return te(e,[{key:"buttonMouseLeave",value:function(e){this._mouseState.state="default",e&&(ai.unsetAllCSS(this.elementRef,e),ai.setElementsCSS(this.elementRef,e,"default"))}},{key:"buttonMouseEnter",value:function(e){this._mouseState.state="hover",e&&ai.setElementsCSS(this.elementRef,e,"hover")}},{key:"buttonMouseUp",value:function(e){e&&ai.unsetActionCSS(this.elementRef,e),this.buttonMouseEnter(e)}},{key:"buttonMouseDown",value:function(e){this._mouseState.state="click",e&&ai.setElementsCSS(this.elementRef,e,"click")}},{key:"setEvents",value:function(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(e){if(this._customStyles)for(var t=0;t3&&void 0!==arguments[3]&&arguments[3]?t:t[a?"nextSibling":"previousSibling"];i?(t.dispatchEvent(new MouseEvent("mouseleave")),i.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),e.focusItemWhenOnEdge(n,a))}}]),e}(),oi=function(){function e(){J(this,e)}return te(e,null,[{key:"addItemEvents",value:function(e,t,n,a){xe.add(t,a),t.addEventListener("click",(function(){n.click()})),t.addEventListener("mouseenter",(function(t){e.highlightedItem=t.target})),t.addEventListener("mouseleave",(function(){e.highlightedItem=void 0}))}},{key:"createItemText",value:function(e,t){var n=document.createElement("div");return Object.assign(n.style,t),n.classList.add("dropup-menu-item-text"),n.textContent=e||"File",n}},{key:"createItemIcon",value:function(e,t){var n=document.createElement("div");return Object.assign(n.style,t),n.classList.add("dropup-menu-item-icon"),n.appendChild(e.children[0]),n}},{key:"populateItem",value:function(t,n,a,i){var r=t.children[0];r.classList.contains("text-button")?n.appendChild(e.createItemText(r.textContent,null==i?void 0:i.text)):(n.appendChild(e.createItemIcon(t,null==i?void 0:i.iconContainer)),n.appendChild(e.createItemText(a,null==i?void 0:i.text)))}},{key:"createItem",value:function(t,n,a){var i,r=n.elementRef,o=n.dropupText,s=document.createElement("div");Object.assign(s.style,null==(i=null==a?void 0:a.item)?void 0:i.default),e.populateItem(r,s,o,a),s.classList.add("dropup-menu-item");var l=re.processStateful((null==a?void 0:a.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return e.addItemEvents(t,s,r,l),s}}]),e}(),si=function(){function e(t,n){var a,i=this;J(this,e),this._isOpen=!0,this._styles=n,this.elementRef=e.createElement(null==(a=this._styles)?void 0:a.container),this.close(),setTimeout((function(){return i.addWindowEvents(t)}))}return te(e,[{key:"open",value:function(){this.elementRef.style.display="block",this._isOpen=!0}},{key:"close",value:function(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}},{key:"toggle",value:function(){this._isOpen?this.close():this.open()}},{key:"addItem",value:function(e){var t=oi.createItem(this,e,this._styles);this.elementRef.appendChild(t)}},{key:"addWindowEvents",value:function(e){this.clickEvent=this.windowClick.bind(this,e),window.addEventListener("click",this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,e),window.addEventListener("keydown",this.keyDownEvent)}},{key:"windowClick",value:function(e,t){var n;!e.isConnected&&this.clickEvent?window.removeEventListener("click",this.clickEvent):e.parentElement!==(null==(n=t.target.shadowRoot)?void 0:n.children[0])&&this.close()}},{key:"windowKeyDown",value:function(e,t){var n,a,i;!e.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(t.key===le.ESCAPE?(this.close(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):t.key===le.ENTER?(null==(a=this.highlightedItem)||a.click(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent("mouseleave"))):t.key===le.ARROW_DOWN?ri.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):t.key===le.ARROW_UP&&ri.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}}],[{key:"createElement",value:function(e){var t=document.createElement("div");return t.id="dropup-menu",Object.assign(t.style,e),t}}]),e}(),li=function(e){function t(e,n){var a,i;J(this,t);var r=(a=G(this,t,[t.createButtonElement(),void 0,{styles:null==(i=null==n?void 0:n.button)?void 0:i.styles}])).createInnerElements(a._customStyles);return a._menu=new si(e,null==n?void 0:n.menu),a.addClickEvent(),a.buttonContainer=t.createButtonContainer(),a.elementRef.appendChild(r.styles),a.buttonContainer.appendChild(a.elementRef),a.elementRef.classList.add("dropup-icon","upload-file-button"),a.elementRef.children[0].id="dropup-icon",a.buttonContainer.appendChild(a._menu.elementRef),a.reapplyStateStyle("styles"),a.addContainerEvents(e),a}return V(t,e),te(t,[{key:"createInnerElements",value:function(e){return{styles:this.createInnerElement(t.createSVGIconElement(),"styles",e)}}},{key:"createInnerElement",value:function(e,t,n){return ni.createSpecificStateElement(this.elementRef,t,n)||e}},{key:"addClickEvent",value:function(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}},{key:"addItem",value:function(e){this._menu.addItem(e)}},{key:"addContainerEvents",value:function(e){var t=this;e.addEventListener("click",(function(e){e.target.classList.contains("dropup-icon")||t._menu.close()}))}}],[{key:"createButtonElement",value:function(){var e=document.createElement("div");return e.classList.add("input-button"),e}},{key:"createSVGIconElement",value:function(){return Yn.createSVGElement('\n\n \n')}},{key:"createButtonContainer",value:function(){var e=document.createElement("div");return e.id="dropup-container",e}},{key:"getPosition",value:function(e,t){var n,a;return null!=(n=null==t?void 0:t.button)&&n.position?null==(a=null==t?void 0:t.button)?void 0:a.position:e["outside-left"].length>0&&0===e["outside-right"].length?"outside-right":"outside-left"}}]),t}(ii),ci=function(){function e(){J(this,e)}return te(e,null,[{key:"addToDropup",value:function(e,t,n,a){var i=new li(n,a);ti.forEach((function(e){var n=t["dropup-menu"].findIndex((function(t){return t.buttonType===e})),a=t["dropup-menu"][n];a&&(i.addItem(a.button),t["dropup-menu"].splice(n,1))}));var r=li.getPosition(t,a);ei.addButton(e,i.buttonContainer,r),t[r].push({})}},{key:"addToSideContainer",value:function(e,t){["inside-left","inside-right","outside-left","outside-right"].forEach((function(n){var a=n;t[a].forEach((function(t){ei.addButton(e,t.button.elementRef,a)}))}))}},{key:"setPosition",value:function(e,t,n){var a=Q(Q({},e[t]),{},{buttonType:t});n.push(a),delete e[t]}},{key:"createPositionsObj",value:function(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}},{key:"generatePositions",value:function(t){var n=e.createPositionsObj();Object.keys(t).forEach((function(a){var i,r=null==(i=t[a])?void 0:i.button.position;r&&e.setPosition(t,a,n[r])})),0===n["inside-right"].length&&t.submit&&e.setPosition(t,"submit",n["inside-right"]),0===n["outside-right"].length&&(t.submit?e.setPosition(t,"submit",n["outside-right"]):t.microphone?e.setPosition(t,"microphone",n["outside-right"]):t.camera&&e.setPosition(t,"camera",n["outside-right"])),t.submit&&e.setPosition(t,"submit",0===n["outside-left"].length?n["outside-left"]:n["inside-right"]),t.microphone&&e.setPosition(t,"microphone",0===n["outside-left"].length?n["outside-left"]:n["inside-right"]);var a=Object.keys(t);return a.length>1||n["dropup-menu"].length>0?ti.forEach((function(e){t[e]&&n["dropup-menu"].push(Q(Q({},t[e]),{},{buttonType:e}))})):1===a.length&&e.setPosition(t,a[0],0===n["outside-right"].length?n["outside-right"]:n["outside-left"]),n}},{key:"addButtons",value:function(t,n,a,i){var r=e.generatePositions(n);return e.addToSideContainer(t,r),r["dropup-menu"].length>0&&e.addToDropup(t,r,a,i),r}}]),e}(),di={images:{id:"upload-images-icon",svgString:'\n\n \n\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'\n\n \n \n \n \n\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'\n \n \n \n \n \n \n \n \n \n \n',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'\n\nfile\n\n',dropupText:"File"}},ui=function(){function e(t,n,a,i){var r=this;J(this,e),this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",n.maxNumberOfFiles&&(this._fileCountLimit=n.maxNumberOfFiles),this._toggleContainerDisplay=a,this._fileAttachmentsContainerRef=i,n.acceptedFormats&&(this._acceptedFormat=n.acceptedFormats),setTimeout((function(){r._validationHandler=t._validationHandler}))}return te(e,[{key:"attemptAddFile",value:function(t,n){return!!e.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,n,!0),!0)}},{key:"addAttachmentBasedOnType",value:function(t,n,a){var i=e.getTypeFromBlob(t);if("image"===i){var r=e.createImageAttachment(n);this.addFileAttachment(t,"image",r,a)}else if("audio"===i){var o=mi.createAudioAttachment(n);this.addFileAttachment(t,"audio",o,a)}else{var s=e.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",s,a)}}},{key:"addFileAttachment",value:function(t,n,a,i){var r,o=e.createContainer(a);if(this._attachments.length>=this._fileCountLimit){var s=this._attachments[this._attachments.length-1].removeButton;null==s||s.click();var l=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(o,l[0])}else this._fileAttachmentsContainerRef.appendChild(o);var c={file:t,attachmentContainerElement:o,fileType:n};return i&&(c.removeButton=this.createRemoveAttachmentButton(c),o.appendChild(c.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(c),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(r=this._validationHandler)||r.call(this),c}},{key:"createRemoveAttachmentButton",value:function(e){var t=document.createElement("div");t.classList.add("remove-file-attachment-button"),t.onclick=this.removeAttachment.bind(this,e);var n=document.createElement("div");return n.classList.add("x-icon"),n.innerText="×",t.appendChild(n),t}},{key:"removeAttachment",value:function(e){var t,n=this._attachments.findIndex((function(t){return t===e})),a=this._attachments[n].attachmentContainerElement;this._attachments.splice(n,1),mi.stopAttachmentPlayback(a),a.remove(),this._toggleContainerDisplay(!1),null==(t=this._validationHandler)||t.call(this)}},{key:"getFiles",value:function(){return Array.from(this._attachments).map((function(e){return{file:e.file,type:e.fileType}}))}},{key:"removeAllAttachments",value:function(){this._attachments.forEach((function(e){setTimeout((function(){var t;return null==(t=e.removeButton)?void 0:t.click()}))}))}}],[{key:"isFileTypeValid",value:function(e,t){if(""===t)return!0;for(var n=t.split(","),a=0;a\n\n play\n \n');i.classList.add("attachment-icon","play-icon");var r=Yn.createSVGElement(_i);r.classList.add("attachment-icon","stop-icon"),n.replaceChildren(i),a.onplay=function(){n.replaceChildren(r)},a.onpause=function(){n.replaceChildren(i),a.currentTime=0},a.onended=function(){n.replaceChildren(i)},n.onclick=function(){a.paused?a.play():a.pause()}}},{key:"createAudioAttachment",value:function(e){var n=t.createAudioContainer();return t.addAudioElements(n,e),n}},{key:"stopAttachmentPlayback",value:function(e){var t,n,a;null!=(a=null==(n=null==(t=e.children[0])?void 0:t.children)?void 0:n[0])&&a.classList.contains("stop-icon")&&e.children[0].click()}}]),t}(ui);pi.TIMER_LIMIT_S=5999;var mi=pi,gi=function(){function e(){J(this,e)}return te(e,null,[{key:"create",value:function(e,t,n,a,i){return"audio"===i?new mi(e,t,n,a):new ui(e,t,n,a)}}]),e}(),Ei=function(){function e(t,n,a){J(this,e),this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();var i="object"==Z(a)&&!!a.displayFileAttachmentContainer;this.toggleContainerDisplay(i),t.appendChild(this.elementRef),n&&Object.assign(this.elementRef.style,n)}var t;return te(e,[{key:"addType",value:function(e,t,n){var a=gi.create(e,t,this.toggleContainerDisplay.bind(this),this.elementRef,n);return this._fileAttachmentsTypes.push(a),a}},{key:"createAttachmentContainer",value:function(){var e=document.createElement("div");return e.id="file-attachment-container",e}},{key:"toggleContainerDisplay",value:function(e){e?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}},{key:"getAllFileData",value:function(){var e=this._fileAttachmentsTypes.map((function(e){return e.getFiles()})).flat();return e.length>0?e:void 0}},{key:"completePlaceholders",value:(t=$(j().mark((function e(){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Promise.all(this._fileAttachmentsTypes.map(function(){var e=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",null==(n=t.stopPlaceholderCallback)?void 0:n.call(t));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 2:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"addFilesToAnyType",value:function(t){e.addFilesToType(t,this._fileAttachmentsTypes)}},{key:"removeAllFiles",value:function(){this._fileAttachmentsTypes.forEach((function(e){return e.removeAllAttachments()})),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}},{key:"getNumberOfTypes",value:function(){return this._fileAttachmentsTypes.length}}],[{key:"addFilesToType",value:function(e,t){e.forEach((function(e){var n=new FileReader;n.readAsDataURL(e),n.onload=function(n){for(var a=0;a0)}}]),e}(),vi=function(){function e(){J(this,e)}var t,n;return te(e,null,[{key:"validate",value:function(e,t,n,a,i){var r=e(n,a,i);return r?t.changeToSubmitIcon():t.changeToDisabledIcon(),r}},{key:"useValidationFunc",value:(n=$(j().mark((function t(n,a,i,r){var o,s,l,c;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=a.inputElementRef,s=o.classList.contains("text-input-placeholder")?"":o.textContent,t.next=3,i.completePlaceholders();case 3:return l=i.getAllFileData(),c=null==l?void 0:l.map((function(e){return e.file})),t.abrupt("return",e.validate(n,r,s,c));case 5:case"end":return t.stop()}}),t)}))),function(e,t,a,i){return n.apply(this,arguments)})},{key:"useValidationFuncProgrammatic",value:(t=$(j().mark((function t(n,a,i){var r,o;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=null==(r=a.files)?void 0:r.map((function(e){return e.file})),t.abrupt("return",e.validate(n,i,a.text,o,!0));case 2:case"end":return t.stop()}}),t)}))),function(e,n,a){return t.apply(this,arguments)})},{key:"validateWebsocket",value:function(e,t){return!(e.websocket&&!wn.canSendMessage(e.websocket))||(t.changeToDisabledIcon(),!1)}},{key:"attach",value:function(t,n,a,i,r){var o=t.validateInput||Ce.processValidateInput(t);t._validationHandler=function(){var t=$(j().mark((function t(s){var l;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!r.status.loadingActive&&!r.status.requestInProgress&&!0!==n.isSubmitProgrammaticallyDisabled&&e.validateWebsocket(n,r)){t.next=2;break}return t.abrupt("return",!1);case 2:return l=o||n.canSendMessage,t.abrupt("return",l?s?e.useValidationFuncProgrammatic(l,s,r):e.useValidationFunc(l,a,i,r):null);case 4:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}()}}]),e}(),Ti=function(e){function t(e){var n;return J(this,t),"dropup-menu"===(null==e?void 0:e.position)&&(e.position="outside-right"),(n=G(this,t,[t.createMicrophoneElement(),null==e?void 0:e.position,e])).isActive=!1,n._innerElements=n.createInnerElements(n._customStyles),n.changeToDefault(),n}return V(t,e),te(t,[{key:"createInnerElements",value:function(e){var n=t.createSVGIconElement();return{default:this.createInnerElement(n,"default",e),active:this.createInnerElement(n,"active",e),unsupported:this.createInnerElement(n,"unsupported",e),commandMode:this.createInnerElement(n,"commandMode",e)}}},{key:"createInnerElement",value:function(e,t,n){return ni.createSpecificStateElement(this.elementRef,t,n)||e}},{key:"changeToActive",value:function(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}},{key:"changeToDefault",value:function(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}},{key:"changeToCommandMode",value:function(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}},{key:"changeToUnsupported",value:function(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}},{key:"toggleIconFilter",value:function(e){var t=this.elementRef.children[0];if("svg"===t.tagName.toLocaleLowerCase())switch(e){case"default":t.classList.remove("active-microphone-icon","command-microphone-icon"),t.classList.add("default-microphone-icon");break;case"active":t.classList.remove("default-microphone-icon","command-microphone-icon"),t.classList.add("active-microphone-icon");break;case"command":t.classList.remove("active-microphone-icon","default-microphone-icon"),t.classList.add("command-microphone-icon")}}}],[{key:"createMicrophoneElement",value:function(){var e=document.createElement("div");return e.id="microphone-button",e.classList.add("input-button"),e}},{key:"createSVGIconElement",value:function(){var e=Yn.createSVGElement('\n\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\n\n');return e.id="microphone-icon",e}}]),t}(ii),yi={},Ci={},Ri={},Ni={},Oi={};Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.Text=void 0;var Ai=function(){function e(){J(this,e)}return te(e,null,[{key:"capitalize",value:function(t){return t.replace(e.FIRST_CHAR_REGEX,(function(e){return e.toUpperCase()}))}},{key:"lineBreak",value:function(t){return t.replace(e.DOUBLE_LINE,"

    ").replace(e.ONE_LINE,"
    ")}},{key:"isCharDefined",value:function(e){return void 0!==e&&" "!==e&&" "!==e&&"\n"!==e&&""!==e}},{key:"breakupIntoWordsArr",value:function(e){return e.split(/(\W+)/)}}]),e}();Oi.Text=Ai,Ai.FIRST_CHAR_REGEX=/\S/,Ai.DOUBLE_LINE=/\n\n/g,Ai.ONE_LINE=/\n/g,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.Translate=void 0;var Ii=Oi,Di=function(){function e(){J(this,e)}return te(e,null,[{key:"translate",value:function(e,t){for(var n=Ii.Text.breakupIntoWordsArr(e),a=0;ae.clientHeight||e.scrollWidth>e.clientWidth}},{key:"isRequired",value:function(t,n){return t&&e.isElementOverflown(n)}}]),e}();Yi.AutoScroll=Hi;var qi={};Object.defineProperty(qi,"__esModule",{value:!0}),qi.Elements=void 0;var Vi=function(){function e(){J(this,e)}return te(e,null,[{key:"isPrimitiveElement",value:function(e){return"INPUT"===e.tagName||"TEXTAREA"===e.tagName}},{key:"createInterimSpan",value:function(){var e=document.createElement("span");return e.style.color="grey",e.style.pointerEvents="none",e}},{key:"createGenericSpan",value:function(){var e=document.createElement("span");return e.style.pointerEvents="none",e}},{key:"appendSpans",value:function(e,t){if(e.spansPopulated=!0,e.insertInCursorLocation&&document.activeElement===t){var n=window.getSelection();if(null!=n&&n.focusNode){var a=n.getRangeAt(0);return a.insertNode(e.scrollingSpan),a.insertNode(e.interimSpan),a.insertNode(e.finalSpan),a.collapse(!1),n.removeAllRanges(),void n.addRange(a)}}t.appendChild(e.finalSpan),t.appendChild(e.interimSpan),t.appendChild(e.scrollingSpan)}},{key:"applyCustomColors",value:function(e,t){t.interim&&(e.interimSpan.style.color=t.interim),t.final&&(e.finalSpan.style.color=t.final)}},{key:"isInsideShadowDOM",value:function(e){return e.getRootNode()instanceof ShadowRoot}}]),e}();qi.Elements=Vi;var zi={};Object.defineProperty(zi,"__esModule",{value:!0}),zi.Cursor=void 0;var ji=function(){function e(){J(this,e)}return te(e,null,[{key:"setOffsetForGeneric",value:function(t,n){for(var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=0,r=0;r0){var s=e.setOffsetForGeneric(o,n,a);if(-1===s)return-1;a+=s}else if(null!==o.textContent){if(a+o.textContent.length>n){var l=document.createRange();l.setStart(o,n-a),l.collapse(!0);var c=window.getSelection();return null==c||c.removeAllRanges(),null==c||c.addRange(l),t.focus(),-1}a+=o.textContent.length,i+=o.textContent.length}}return i}},{key:"focusEndOfGeneric",value:function(e){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var n=window.getSelection();n&&(n.removeAllRanges(),n.addRange(t))}},{key:"setOffsetForSafariGeneric",value:function(t,n){var a=window.getSelection();if(a){var i=e.getGenericElementCursorOffset(t,a,!0);console.log(i),setTimeout((function(){}),100),e.setOffsetForGeneric(t,i+n)}}},{key:"setOffsetForPrimitive",value:function(e,t,n){n&&e.blur(),e.setSelectionRange(t,t),e.focus()}},{key:"getGenericElementCursorOffset",value:function(e,t,n){var a=0;if(t.rangeCount>0){var i=t.getRangeAt(0),r=i.cloneRange();r.selectNodeContents(e),n?r.setEnd(i.startContainer,i.startOffset):r.setEnd(i.endContainer,i.endOffset),a=r.toString().length}return a}}]),e}();zi.Cursor=ji,Object.defineProperty(Gi,"__esModule",{value:!0}),Gi.CommandUtils=void 0;var Wi=Yi,$i=qi,Ki=Mi,Qi=zi,Xi=Oi,Zi=function(){function e(){J(this,e)}return te(e,null,[{key:"processCommand",value:function(e,t){return(!t||!t.caseSensitive)&&(e=e.toLowerCase()),!1===(null==t?void 0:t.substrings)?Xi.Text.breakupIntoWordsArr(e):e}},{key:"process",value:function(t){var n;return!0===(null===(n=t.settings)||void 0===n?void 0:n.caseSensitive)?t:Object.keys(t).reduce((function(n,a){var i=t[a];return n[a]="string"==typeof i?e.processCommand(i,t.settings):i,n}),{})}},{key:"toggleCommandModeOn",value:function(e){var t;e.isWaitingForCommand=!0,null===(t=e.onCommandModeTrigger)||void 0===t||t.call(e,!0)}},{key:"toggleCommandModeOff",value:function(e){var t;e.isWaitingForCommand&&(null===(t=e.onCommandModeTrigger)||void 0===t||t.call(e,!1),e.isWaitingForCommand=!1)}},{key:"setText",value:function(t,n,a,i){e.toggleCommandModeOff(t),$i.Elements.isPrimitiveElement(i)?(i.value=a,t.isTargetInShadow||Qi.Cursor.setOffsetForPrimitive(i,a.length,!0),Ki.Browser.IS_SAFARI()&&t.autoScroll&&Wi.AutoScroll.scrollSafariPrimitiveToEnd(i)):(i.textContent=a,t.isTargetInShadow||Qi.Cursor.focusEndOfGeneric(i),setTimeout((function(){return Wi.AutoScroll.scrollGeneric(t,i)}))),t.resetRecording(n)}},{key:"checkIfMatchesSubstring",value:function(e,t){return t.includes(e)}},{key:"checkIfMatchesWord",value:function(e,t,n){for(var a=e,i=n.length-1;i>=0;i-=1){for(var r=i,o=a.length-1;n[r]===a[o]&&o>=0;)r-=1,o-=1;if(o<0)return!0}return!1}},{key:"execCommand",value:function(t,n,a,i,r){var o,s,l,c=t.commands;if(c&&i&&a){var d=!0===(null===(o=c.settings)||void 0===o?void 0:o.caseSensitive)?n:n.toLowerCase(),u=Xi.Text.breakupIntoWordsArr(d),_=!1===(null===(s=c.settings)||void 0===s?void 0:s.substrings)?e.checkIfMatchesWord:e.checkIfMatchesSubstring;if(c.commandMode&&_(c.commandMode,d,u))return t.setInterimColorToFinal(),setTimeout((function(){return e.toggleCommandModeOn(t)})),{doNotProcessTranscription:!1};if(!c.commandMode||t.isWaitingForCommand){if(c.stop&&_(c.stop,d,u))return e.toggleCommandModeOff(t),setTimeout((function(){return t.stop()})),{doNotProcessTranscription:!1};if(c.pause&&_(c.pause,d,u))return e.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((function(){var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(c.resume&&_(c.resume,d,u))return t.isPaused=!1,null===(l=t.onPauseTrigger)||void 0===l||l.call(t,!1),e.toggleCommandModeOff(t),t.resetRecording(a),{doNotProcessTranscription:!0};if(c.reset&&_(c.reset,d,u))return void 0!==r&&e.setText(t,a,r,i),{doNotProcessTranscription:!0};if(c.removeAllText&&_(c.removeAllText,d,u))return e.setText(t,a,"",i),{doNotProcessTranscription:!0}}}}}]),e}();Gi.CommandUtils=Zi;var Ji={};Object.defineProperty(Ji,"__esModule",{value:!0}),Ji.Highlight=void 0;var er=qi,tr=zi,nr=function(){function e(){J(this,e)}return te(e,null,[{key:"setStateForPrimitive",value:function(e,t){var n,a;null!==t.selectionStart&&(n=t.selectionStart),null!==t.selectionEnd&&(a=t.selectionEnd),e.isHighlighted=n!==a}},{key:"setStateForGeneric",value:function(e,t){var n=window.getSelection();if(null!=n&&n.focusNode){var a=tr.Cursor.getGenericElementCursorOffset(t,n,!0),i=tr.Cursor.getGenericElementCursorOffset(t,n,!1);e.isHighlighted=a!==i}}},{key:"setState",value:function(t,n){document.activeElement===n&&(er.Elements.isPrimitiveElement(n)?e.setStateForPrimitive(t,n):e.setStateForGeneric(t,n))}},{key:"removeForGeneric",value:function(e,t){var n=window.getSelection();if(n){var a=tr.Cursor.getGenericElementCursorOffset(t,n,!0);n.deleteFromDocument(),tr.Cursor.setOffsetForGeneric(t,a),e.isHighlighted=!1}}},{key:"removeForPrimitive",value:function(e,t){var n=t.selectionStart,a=t.selectionEnd,i=t.value;if(n&&a){var r=i.substring(0,n)+i.substring(a);t.value=r,tr.Cursor.setOffsetForPrimitive(t,n,e.autoScroll)}e.isHighlighted=!1}}]),e}();Ji.Highlight=nr;var ar={};Object.defineProperty(ar,"__esModule",{value:!0}),ar.Padding=void 0;var ir=qi,rr=zi,or=Oi,sr=function(){function e(){J(this,e)}return te(e,null,[{key:"setStateForPrimitiveElement",value:function(e,t){if(document.activeElement===t&&null!==t.selectionStart){var n=t.selectionStart,a=t.value[n-1],i=null===t.selectionEnd?n:t.selectionEnd,r=t.value[i];return or.Text.isCharDefined(a)&&(e.startPadding=" ",e.numberOfSpacesBeforeNewText=1),or.Text.isCharDefined(r)&&(e.endPadding=" ",e.numberOfSpacesAfterNewText=1),void(e.isCursorAtEnd=t.value.length===i)}var o=t.value[t.value.length-1];or.Text.isCharDefined(o)&&(e.startPadding=" ",e.numberOfSpacesBeforeNewText=1),e.isCursorAtEnd=!0}},{key:"setStateForGenericElement",value:function(e,t){var n,a,i;if(document.activeElement===t){var r=window.getSelection();if(null!=r&&r.focusNode){var o=rr.Cursor.getGenericElementCursorOffset(t,r,!0),s=null===(n=t.textContent)||void 0===n?void 0:n[o-1],l=rr.Cursor.getGenericElementCursorOffset(t,r,!1),c=null===(a=t.textContent)||void 0===a?void 0:a[l];return or.Text.isCharDefined(s)&&(e.startPadding=" "),or.Text.isCharDefined(c)&&(e.endPadding=" "),void(e.isCursorAtEnd=(null===(i=t.textContent)||void 0===i?void 0:i.length)===l)}}var d=t.innerText.charAt(t.innerText.length-1);or.Text.isCharDefined(d)&&(e.startPadding=" "),e.isCursorAtEnd=!0}},{key:"setState",value:function(t,n){ir.Elements.isPrimitiveElement(n)?e.setStateForPrimitiveElement(t,n):e.setStateForGenericElement(t,n)}},{key:"adjustStateAfterRecodingPrimitiveElement",value:function(e,t){e.primitiveTextRecorded=!0,e.insertInCursorLocation&&document.activeElement===t&&(null!==t.selectionEnd&&(e.endPadding=e.endPadding+t.value.slice(t.selectionEnd)),null!==t.selectionStart)?e.startPadding=t.value.slice(0,t.selectionStart)+e.startPadding:e.startPadding=t.value+e.startPadding}},{key:"adjustSateForNoTextPrimitiveElement",value:function(e){1===e.numberOfSpacesBeforeNewText&&(e.startPadding=e.startPadding.substring(0,e.startPadding.length-1),e.numberOfSpacesBeforeNewText=0),1===e.numberOfSpacesAfterNewText&&(e.endPadding=e.endPadding.substring(1),e.numberOfSpacesAfterNewText=0)}}]),e}();ar.Padding=sr,Object.defineProperty(ki,"__esModule",{value:!0}),ki.Speech=void 0;var lr=Pi,cr=Ui,dr=Gi,ur=Yi,_r=Ji,pr=qi,mr=ar,gr=Mi,Er=zi,Sr=Oi,hr=function(){function e(){J(this,e),this.finalTranscript="",this.interimSpan=pr.Elements.createInterimSpan(),this.finalSpan=pr.Elements.createGenericSpan(),this.scrollingSpan=pr.Elements.createGenericSpan(),this.isCursorAtEnd=!1,this.spansPopulated=!1,this.startPadding="",this.endPadding="",this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.recognizing=!1,this._displayInterimResults=!0,this.insertInCursorLocation=!0,this.autoScroll=!0,this.isRestarting=!1,this.isPaused=!1,this.isWaitingForCommand=!1,this.isTargetInShadow=!1,this.cannotBeStopped=!1,this.resetState()}return te(e,[{key:"prepareBeforeStart",value:function(e){var t,n;if(null!=e&&e.element)if(lr.EventListeners.add(this,e),Array.isArray(e.element)){var a=e.element.find((function(e){return e===document.activeElement}))||e.element[0];if(!a)return;this.prepare(a)}else this.prepare(e.element);void 0!==(null==e?void 0:e.displayInterimResults)&&(this._displayInterimResults=e.displayInterimResults),null!=e&&e.textColor&&(this._finalTextColor=null===(t=null==e?void 0:e.textColor)||void 0===t?void 0:t.final,pr.Elements.applyCustomColors(this,e.textColor)),void 0!==(null==e?void 0:e.insertInCursorLocation)&&(this.insertInCursorLocation=e.insertInCursorLocation),void 0!==(null==e?void 0:e.autoScroll)&&(this.autoScroll=e.autoScroll),this._onResult=null==e?void 0:e.onResult,this._onPreResult=null==e?void 0:e.onPreResult,this._onStart=null==e?void 0:e.onStart,this._onStop=null==e?void 0:e.onStop,this._onError=null==e?void 0:e.onError,this.onCommandModeTrigger=null==e?void 0:e.onCommandModeTrigger,this.onPauseTrigger=null==e?void 0:e.onPauseTrigger,this._options=e,null!==(n=this._options)&&void 0!==n&&n.commands&&(this.commands=dr.CommandUtils.process(this._options.commands))}},{key:"prepare",value:function(e){mr.Padding.setState(this,e),_r.Highlight.setState(this,e),this.isTargetInShadow=pr.Elements.isInsideShadowDOM(e),pr.Elements.isPrimitiveElement(e)?(this._primitiveElement=e,this._originalText=this._primitiveElement.value):(this._genericElement=e,this._originalText=this._genericElement.textContent)}},{key:"resetRecording",value:function(e){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(e,!0)}},{key:"updateElements",value:function(e,t,n){var a,i=Sr.Text.capitalize(t);if(this.finalTranscript!==i||""!==e){cr.PreResultUtils.process(this,n,""===e,this._onPreResult,this._options)&&(e="",n="");var r=this.commands&&dr.CommandUtils.execCommand(this,n,this._options,this._primitiveElement||this._genericElement,this._originalText);if(r){if(r.doNotProcessTranscription)return;e="",n=""}if(!this.isPaused&&!this.isWaitingForCommand){null===(a=this._onResult)||void 0===a||a.call(this,n,""===e),this.finalTranscript=i,this._displayInterimResults||(e="");var o=""===this.finalTranscript&&""===e;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,e,o):this._genericElement&&this.updateGenericElement(this._genericElement,e,o)}}}},{key:"updatePrimitiveElement",value:function(e,t,n){this.isHighlighted&&_r.Highlight.removeForPrimitive(this,e),this.primitiveTextRecorded||mr.Padding.adjustStateAfterRecodingPrimitiveElement(this,e),n&&mr.Padding.adjustSateForNoTextPrimitiveElement(this);var a=this.startPadding+this.finalTranscript+t;if(e.value=a+this.endPadding,!this.isTargetInShadow){var i=a.length+this.numberOfSpacesAfterNewText;Er.Cursor.setOffsetForPrimitive(e,i,this.autoScroll)}this.autoScroll&&gr.Browser.IS_SAFARI()&&this.isCursorAtEnd&&ur.AutoScroll.scrollSafariPrimitiveToEnd(e)}},{key:"updateGenericElement",value:function(e,t,n){this.isHighlighted&&_r.Highlight.removeForGeneric(this,e),this.spansPopulated||pr.Elements.appendSpans(this,e);var a=(n?"":this.startPadding)+Sr.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=a;var i=ur.AutoScroll.isRequired(this.autoScroll,e);ur.AutoScroll.changeStateIfNeeded(this,i);var r=Sr.Text.lineBreak(t)+(n?"":this.endPadding);this.interimSpan.innerHTML=r,gr.Browser.IS_SAFARI()&&this.insertInCursorLocation&&Er.Cursor.setOffsetForSafariGeneric(e,a.length+r.length),i&&ur.AutoScroll.scrollGeneric(this,e),n&&(this.scrollingSpan.innerHTML="")}},{key:"finalise",value:function(e){this._genericElement&&(e?(this.finalSpan=pr.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=pr.Elements.createInterimSpan(),this.scrollingSpan=pr.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),lr.EventListeners.remove(this)}},{key:"setInterimColorToFinal",value:function(){this.interimSpan.style.color=this._finalTextColor||"black"}},{key:"resetState",value:function(e){this._primitiveElement=void 0,this._genericElement=void 0,this.finalTranscript="",this.finalSpan.innerHTML="",this.interimSpan.innerHTML="",this.scrollingSpan.innerHTML="",this.startPadding="",this.endPadding="",this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,e||(this.stopTimeout=void 0)}},{key:"setStateOnStart",value:function(){var e;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:null===(e=this._onStart)||void 0===e||e.call(this)}},{key:"setStateOnStop",value:function(){var e;this.recognizing=!1,this.isRestarting||null===(e=this._onStop)||void 0===e||e.call(this)}},{key:"setStateOnError",value:function(e){var t;null===(t=this._onError)||void 0===t||t.call(this,e),this.recognizing=!1}}]),e}();ki.Speech=hr,Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.WebSpeech=void 0;var fr=Ri,br=Mi,vr=function(e){function t(){return J(this,t),G(this,t)}return V(t,e),te(t,[{key:"start",value:function(e){var t;void 0===this._extractText&&(this._extractText=br.Browser.IS_SAFARI()?fr.WebSpeechTranscript.extractSafari:fr.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(e),this.instantiateService(e),null===(t=this._service)||void 0===t||t.start(),this._translations=null==e?void 0:e.translations)}},{key:"validate",value:function(){return!!t.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}},{key:"instantiateService",value:function(e){var n,a,i=t.getAPI();this._service=new i,this._service.continuous=!0,this._service.interimResults=null===(n=null==e?void 0:e.displayInterimResults)||void 0===n||n,this._service.lang=(null===(a=null==e?void 0:e.language)||void 0===a?void 0:a.trim())||"en-US",this.setEvents()}},{key:"setEvents",value:function(){var e=this;this._service&&(this._service.onstart=function(){e.setStateOnStart()},this._service.onerror=function(t){br.Browser.IS_SAFARI()&&"Another request is started"===t.message||"aborted"===t.error&&e.isRestarting||"no-speech"!==t.error&&e.error(t.message||t.error)},this._service.onaudioend=function(){e.setStateOnStop()},this._service.onend=function(){e._stopping=!1},this._service.onresult=function(t){if(Z(t.results)>"u"&&e._service)e._service.onend=null,e._service.stop();else if(e._extractText&&!e._stopping){var n=e._extractText(t,e.finalTranscript,e._translations),a=n.interimTranscript,i=n.finalTranscript,r=n.newText;e.updateElements(a,i,r)}})}},{key:"stop",value:function(e){var t;this._stopping=!0,null===(t=this._service)||void 0===t||t.stop(),this.finalise(e)}},{key:"error",value:function(e){console.error(e),this.setStateOnError(e),this.stop()}}],[{key:"getAPI",value:function(){return window.webkitSpeechRecognition||window.SpeechRecognition}}]),t}(ki.Speech);Ci.WebSpeech=vr;var Tr={};Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.GlobalState=void 0;var yr=function(){function e(){J(this,e)}return te(e,null,[{key:"doubleClickDetector",value:function(){return!!e.doubleClickPending||(e.doubleClickPending=!0,setTimeout((function(){e.doubleClickPending=!1}),300),!1)}}]),e}();Tr.GlobalState=yr,yr.doubleClickPending=!1;var Cr={},Rr={};Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.PreventConnectionStop=void 0;var Nr=function(){function e(){J(this,e)}return te(e,null,[{key:"applyPrevention",value:function(e){clearTimeout(e._manualConnectionStopPrevention),e.cannotBeStopped=!0,e._manualConnectionStopPrevention=setTimeout((function(){e.cannotBeStopped=!1}),800)}},{key:"clearPrevention",value:function(e){clearTimeout(e._manualConnectionStopPrevention),e.cannotBeStopped=!1}}]),e}();Rr.PreventConnectionStop=Nr;var Or={},Ar={};Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.README_URL=void 0,Ar.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(Or,"__esModule",{value:!0}),Or.AzureSpeechConfig=void 0;var Ir=Ar,Dr=function(){function e(){J(this,e)}var t,n;return te(e,null,[{key:"validateOptions",value:function(e,t){return t?t.subscriptionKey||t.token||t.retrieveToken?!!t.region||(e("Please define a 'region' property - more info: ".concat(Ir.README_URL)),!1):(e("Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ".concat(Ir.README_URL)),!1):(e("Please provide subscription details - more info: ".concat(Ir.README_URL)),!1)}},{key:"getNewSpeechConfig",value:(n=$(j().mark((function e(t,n){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.region){e.next=2;break}return e.abrupt("return",n.subscriptionKey?t.fromSubscription(n.subscriptionKey.trim(),n.region.trim()):n.token?t.fromAuthorizationToken(n.token.trim(),n.region.trim()):n.retrieveToken?n.retrieveToken().then((function(e){return n.region?t.fromAuthorizationToken((null==e?void 0:e.trim())||"",n.region.trim()):null})).catch((function(e){return console.error(e),null})):null);case 2:case"end":return e.stop()}}),e)}))),function(e,t){return n.apply(this,arguments)})},{key:"process",value:function(e,t){t.language&&(e.speechRecognitionLanguage=t.language.trim())}},{key:"get",value:(t=$(j().mark((function t(n,a){var i;return j().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.getNewSpeechConfig(n,a);case 2:return i=t.sent,t.abrupt("return",(i&&e.process(i,a),i));case 4:case"end":return t.stop()}}),t)}))),function(e,n){return t.apply(this,arguments)})}]),e}();Or.AzureSpeechConfig=Dr;var wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.StopTimeout=void 0;var xr=function(){function e(){J(this,e)}return te(e,null,[{key:"set",value:function(e){e.stopTimeout=setTimeout((function(){return e.stop()}),e.stopTimeoutMS)}},{key:"reset",value:function(t,n){t.stopTimeoutMS=n||e.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),e.set(t)}}]),e}();wr.StopTimeout=xr,xr.DEFAULT_MS=2e4;var Mr={};Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.AzureTranscript=void 0;var Lr=Ni,kr=function(){function e(){J(this,e)}return te(e,null,[{key:"extract",value:function(e,t,n,a){return a&&(e=Lr.Translate.translate(e,a)),n?{interimTranscript:"",finalTranscript:t+e,newText:e}:{interimTranscript:e,finalTranscript:t,newText:e}}}]),e}();Mr.AzureTranscript=kr,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.Azure=void 0;var Pr=Rr,Fr=Or,Ur=wr,Br=Mr,Gr=function(e){function t(){var e;return J(this,t),(e=G(this,t,arguments))._newTextPadding="",e}var n,a;return V(t,e),te(t,[{key:"start",value:function(e,t){this._newTextPadding="",void 0===this.stopTimeout&&Ur.StopTimeout.reset(this,null==e?void 0:e.stopAfterSilenceMs),this.prepareBeforeStart(e),this.startAsync(e),t||Pr.PreventConnectionStop.applyPrevention(this)}},{key:"startAsync",value:(a=$(j().mark((function e(t){var n;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.validate(t),!e.t0){e.next=6;break}return e.next=4,this.instantiateService(t);case 4:this._translations=null==t?void 0:t.translations,null===(n=this._service)||void 0===n||n.startContinuousRecognitionAsync((function(){}),this.error);case 6:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"validate",value:function(e){return t.getAPI()?Fr.AzureSpeechConfig.validateOptions(this.error.bind(this),e):(this.moduleNotFound(),!1)}},{key:"instantiateService",value:(n=$(j().mark((function e(n){var a,i,r,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=t.getAPI(),i=a.AudioConfig.fromDefaultMicrophoneInput(),e.next=4,Fr.AzureSpeechConfig.get(a.SpeechConfig,n);case 4:(r=e.sent)?(o=new a.SpeechRecognizer(r,i),this.setEvents(o),this._service=o,n.retrieveToken&&this.retrieveTokenInterval(n.retrieveToken)):this.error("Unable to contact Azure server");case 6:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"setEvents",value:function(e){e.recognizing=this.onRecognizing.bind(this),e.recognized=this.onRecognized.bind(this),e.sessionStarted=this.onSessionStarted.bind(this),e.canceled=this.onCanceled.bind(this),e.sessionStopped=this.onSessionStopped.bind(this)}},{key:"onRecognizing",value:function(e,t){if(!this._stopping){var n=Br.AzureTranscript.extract(this._newTextPadding+t.result.text,this.finalTranscript,!1,this._translations),a=n.interimTranscript,i=n.finalTranscript,r=n.newText;Ur.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(a,i,r)}}},{key:"onRecognized",value:function(e,t){var n=t.result;switch(n.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(n.text&&!this._stopping){var a=Br.AzureTranscript.extract(this._newTextPadding+n.text,this.finalTranscript,!0,this._translations),i=a.interimTranscript,r=a.finalTranscript,o=a.newText;Ur.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,r,o),""!==r&&(this._newTextPadding=" ")}}}},{key:"onCanceled",value:function(e,t){t.reason===window.SpeechSDK.CancellationReason.Error&&this.error(t.errorDetails)}},{key:"onSessionStarted",value:function(){Pr.PreventConnectionStop.clearPrevention(this),this.setStateOnStart()}},{key:"onSessionStopped",value:function(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}},{key:"retrieveTokenInterval",value:function(e){var t=this;this._retrieveTokenInterval=setInterval((function(){null==e||e().then((function(e){t._service&&(t._service.authorizationToken=(null==e?void 0:e.trim())||"")})).catch((function(e){t.error(e)}))}),1e4)}},{key:"stop",value:function(e){var t;!e&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,null===(t=this._service)||void 0===t||t.stopContinuousRecognitionAsync(),this.finalise(e)}},{key:"moduleNotFound",value:function(){console.error("speech recognition module not found:"),console.error("please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: \";\n\t\tunsubscribe = listen(\n\t\t\twindow,\n\t\t\t'message',\n\t\t\t/** @param {MessageEvent} event */ (event) => {\n\t\t\t\tif (event.source === iframe.contentWindow) fn();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tiframe.src = 'about:blank';\n\t\tiframe.onload = () => {\n\t\t\tunsubscribe = listen(iframe.contentWindow, 'resize', fn);\n\t\t\t// make sure an initial resize event is fired _after_ the iframe is loaded (which is asynchronous)\n\t\t\t// see https://github.com/sveltejs/svelte/issues/4233\n\t\t\tfn();\n\t\t};\n\t}\n\tappend(node, iframe);\n\treturn () => {\n\t\tif (crossorigin) {\n\t\t\tunsubscribe();\n\t\t} else if (unsubscribe && iframe.contentWindow) {\n\t\t\tunsubscribe();\n\t\t}\n\t\tdetach(iframe);\n\t};\n}\nexport const resize_observer_content_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'content-box'\n});\nexport const resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'border-box'\n});\nexport const resize_observer_device_pixel_content_box = /* @__PURE__ */ new ResizeObserverSingleton(\n\t{ box: 'device-pixel-content-box' }\n);\nexport { ResizeObserverSingleton };\n\n/**\n * @returns {void} */\nexport function toggle_class(element, name, toggle) {\n\t// The `!!` is required because an `undefined` flag means flipping the current state.\n\telement.classList.toggle(name, !!toggle);\n}\n\n/**\n * @template T\n * @param {string} type\n * @param {T} [detail]\n * @param {{ bubbles?: boolean, cancelable?: boolean }} [options]\n * @returns {CustomEvent}\n */\nexport function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {\n\treturn new CustomEvent(type, { detail, bubbles, cancelable });\n}\n\n/**\n * @param {string} selector\n * @param {HTMLElement} parent\n * @returns {ChildNodeArray}\n */\nexport function query_selector_all(selector, parent = document.body) {\n\treturn Array.from(parent.querySelectorAll(selector));\n}\n\n/**\n * @param {string} nodeId\n * @param {HTMLElement} head\n * @returns {any[]}\n */\nexport function head_selector(nodeId, head) {\n\tconst result = [];\n\tlet started = 0;\n\tfor (const node of head.childNodes) {\n\t\tif (node.nodeType === 8 /* comment node */) {\n\t\t\tconst comment = node.textContent.trim();\n\t\t\tif (comment === `HEAD_${nodeId}_END`) {\n\t\t\t\tstarted -= 1;\n\t\t\t\tresult.push(node);\n\t\t\t} else if (comment === `HEAD_${nodeId}_START`) {\n\t\t\t\tstarted += 1;\n\t\t\t\tresult.push(node);\n\t\t\t}\n\t\t} else if (started > 0) {\n\t\t\tresult.push(node);\n\t\t}\n\t}\n\treturn result;\n}\n/** */\nexport class HtmlTag {\n\t/**\n\t * @private\n\t * @default false\n\t */\n\tis_svg = false;\n\t/** parent for creating node */\n\te = undefined;\n\t/** html tag nodes */\n\tn = undefined;\n\t/** target */\n\tt = undefined;\n\t/** anchor */\n\ta = undefined;\n\tconstructor(is_svg = false) {\n\t\tthis.is_svg = is_svg;\n\t\tthis.e = this.n = null;\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @returns {void}\n\t */\n\tc(html) {\n\t\tthis.h(html);\n\t}\n\n\t/**\n\t * @param {string} html\n\t * @param {HTMLElement | SVGElement} target\n\t * @param {HTMLElement | SVGElement} anchor\n\t * @returns {void}\n\t */\n\tm(html, target, anchor = null) {\n\t\tif (!this.e) {\n\t\t\tif (this.is_svg)\n\t\t\t\tthis.e = svg_element(/** @type {keyof SVGElementTagNameMap} */ (target.nodeName));\n\t\t\t/** #7364 target for