deep-chat-dev 1.1.27 → 1.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- class t{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class e{static onLoad(t){t.innerHTML='<div id="large-loading-ring"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,n,s){const o=e.createElements(),r={onSuccess:n,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};s.key&&s.verifyKey(s.key,r),i.replaceChildren(o)}}class i{static apply(t,e){if(e)try{i.applyStyleSheet(t,e)}catch{i.addStyleElement(t,e)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}}var n=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(n||{});class s{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&s.unsetStyle(t,e.click),e.hover&&s.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){s.unsetActivityCSSMouseStates(t,e),e.default&&s.unsetStyle(t,e.default)}static generateStateful(t,e,i){const n=t.default||{},s=Object.assign(JSON.parse(JSON.stringify({...n,...e})),null==t?void 0:t.hover);return{default:n,hover:s,click:Object.assign(JSON.parse(JSON.stringify({...s,...i})),null==t?void 0:t.click)}}}let o=class{};o.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),o.IS_CHROMIUM=window.chrome;class r{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const n=null==(e=t.clipboardData)?void 0:e.getData("text/plain");null==(i=document.execCommand)||i.call(document,"insertHTML",!1,n)}}const a=class{static add(t,e){t.addEventListener("keydown",a.onKeyDown.bind(this,e)),t.oninput=a.onInput.bind(this,e)}static onKeyDown(t,e){const i=e.target.textContent;i&&i.length>=t&&!a.PERMITTED_KEYS.has(e.key)&&!a.isKeyCombinationPermitted(e)&&e.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e){const i=e.target,n=i.textContent;n&&n.length>t&&(i.textContent=n.substring(0,t),h.focusEndOfInput(i))}};let l=a;l.PERMITTED_KEYS=new Set([n.BACKSPACE,n.DELETE,n.ARROW_RIGHT,n.ARROW_LEFT,n.ARROW_DOWN,n.ARROW_UP,n.META,n.CONTROL,n.ENTER]);const c=class{constructor(t,e){var i;const n=c.processConfig(t,e);this.elementRef=c.createContainerElement(null==(i=null==n?void 0:n.styles)?void 0:i.container),this.inputElementRef=this.createInputElement(n),this._config=n,this.elementRef.appendChild(this.inputElementRef),null!=e&&e.characterLimit&&l.add(this.inputElementRef,null==e?void 0:e.characterLimit)}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}static clear(t){const e=window.scrollY;t.classList.contains("text-input-disabled")||(t.textContent=""),o.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(t){var e,i,n;const s=document.createElement("div");return s.id=c.TEXT_INPUT_ID,s.classList.add("text-input-styling","text-input-placeholder"),s.innerText=(null==(e=null==t?void 0:t.placeholder)?void 0:e.text)||"Ask me anything!",o.IS_CHROMIUM&&c.preventAutomaticScrollUpOnNewLine(s),"boolean"==typeof(null==t?void 0:t.disabled)&&!0===t.disabled?(s.contentEditable="false",s.classList.add("text-input-disabled")):(s.contentEditable="true",s.onfocus=this.onFocus.bind(this),s.addEventListener("keydown",this.onKeydown.bind(this)),s.onpaste=r.sanitizePastedTextContent),Object.assign(s.style,null==(i=null==t?void 0:t.styles)?void 0:i.text),Object.assign(s.style,null==(n=null==t?void 0:t.placeholder)?void 0:n.style),s}removeTextIfPlaceholder(){var t,e,i,n;this.inputElementRef.classList.contains("text-input-placeholder")&&!this.inputElementRef.classList.contains("text-input-disabled")&&(null!=(t=this._config.placeholder)&&t.style&&(s.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(i=this._config)?void 0:i.styles)?void 0:n.text)),c.clear(this.inputElementRef),this.inputElementRef.classList.remove("text-input-placeholder"))}static toggleEditability(t,e){t.contentEditable=e?"true":"false"}onFocus(){o.IS_SAFARI?setTimeout((()=>{this.removeTextIfPlaceholder()})):this.removeTextIfPlaceholder()}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}onKeydown(t){var e;t.key===n.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}};let u=c;u.TEXT_INPUT_ID="text-input";class h{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${u.TEXT_INPUT_ID}`);e&&h.focusEndOfInput(e)}}function d(t){let e,i,n,s=!1;return function(o){void 0===e?(e=o,i=0,n=-1):e=function(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}(e,o);const r=e.length;let a=0;for(;i<r;){s&&(10===e[i]&&(a=++i),s=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===n&&(n=i-a);break;case 13:s=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),n),a=i,n=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}var p=globalThis&&globalThis.__rest||function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const m="text/event-stream",f=1e3,v="last-event-id";function g(t,e){var{signal:i,headers:n,onopen:s,onmessage:o,onclose:r,onerror:a,openWhenHidden:l,fetch:c}=e,u=p(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,h)=>{const p=Object.assign({},n);let g;function w(){g.abort(),document.hidden||A()}p.accept||(p.accept=m),l||document.addEventListener("visibilitychange",w);let y=f,x=0;function M(){document.removeEventListener("visibilitychange",w),window.clearTimeout(x),g.abort()}null==i||i.addEventListener("abort",(()=>{M(),e()}));const k=c??window.fetch,j=s??b;async function A(){var i;g=new AbortController;try{const i=await k(t,Object.assign(Object.assign({},u),{headers:p,signal:g.signal}));await j(i),await async function(t,e){const i=t.getReader();let n;for(;!(n=await i.read()).done;)e(n.value)}(i.body,d(function(t,e,i){let n={data:"",event:"",id:"",retry:void 0};const s=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(n),n={data:"",event:"",id:"",retry:void 0};else if(r>0){const i=s.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),l=s.decode(o.subarray(a));switch(i){case"data":n.data=n.data?n.data+"\n"+l:l;break;case"event":n.event=l;break;case"id":t(n.id=l);break;case"retry":const i=parseInt(l,10);isNaN(i)||e(n.retry=i)}}}}((t=>{t?p[v]=t:delete p[v]}),(t=>{y=t}),o))),null==r||r(),M(),e()}catch(t){if(!g.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:y;window.clearTimeout(x),x=window.setTimeout(A,e)}catch(t){M(),h(t)}}}A()}))}function b(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(m))throw new Error(`Expected content-type to be ${m}, Actual: ${e}`)}const w="Invalid API Key",y="Failed to connect",x=class{static temporarilyRemoveHeader(t,e,i){if(null==t||!t.headers)throw new Error("Request settings have not been set up");const n=t.headers[x.CONTENT_TYPE];delete t.headers[x.CONTENT_TYPE],e(i),t.headers[x.CONTENT_TYPE]=n}static displayError(t,e){if(console.error(e),"object"==typeof e)return 0===Object.keys(e).length?t.addNewErrorMessage("service","Service error, please try again."):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}};let M=x;M.CONTENT_TYPE="Content-Type";const k=class{static generateResponseForOneMessage(t){if(t.file)return"image"===t.file.type?"That is a nice image!":"audio"===t.file.type?"I like the sound of that!":"gif"===t.file.type?"That is a nice gif!":"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!"}static generateResponse(t){const e=[];for(let i=t.messages.length-1;i>=0&&"ai"!==t.messages[i].role;i-=1)e.push(t.messages[i]);if(1===e.length)return k.generateResponseForOneMessage(t.messages[t.messages.length-1]);const i=t.messages.findIndex((t=>t.text));return-1!==i&&e.splice(i,1),1===e.length?k.generateResponseForOneMessage(t.messages[t.messages.length-1]):"Wow, very cool files!"}static request(t,e,i){const n=k.generateResponse(t);setTimeout((()=>{const s={text:n},o=(null==i?void 0:i(s))||s;t.addNewMessage(o,!0,!0),e()}),400)}static requestStream(t,e,i){const n=k.generateResponse(t).split(" ");setTimeout((()=>{const s=t.addNewStreamedMessage();e(),k.populateMessages(s,n,t,i)}),400)}static populateMessages(t,e,i,n,s=0){setTimeout((()=>{const o=e[s];o?(i.updateStreamedMessage(`${o} `,t),k.populateMessages(t,e,i,n,s+1)):(i.finaliseStreamedMessage(),n())}),70)}};let j=k;j.URL="deep-chat-demo";class A{static request(t,e,i,n,s=!0){var o,r,a,l,c,u;const h={body:e,headers:null==(o=t.requestSettings)?void 0:o.headers},{body:d,headers:p}=(null==(a=(r=t.deepChat).requestInterceptor)?void 0:a.call(r,h))||h;if((null==(l=t.requestSettings)?void 0:l.url)===j.URL)return j.request(i,n,t.deepChat.responseInterceptor);let m=!0;fetch((null==(c=t.requestSettings)?void 0:c.url)||t.url||"",{method:(null==(u=t.requestSettings)?void 0:u.method)||"POST",headers:p,body:s?JSON.stringify(d):d}).then((t=>(m=!!t.ok,t))).then((t=>A.processResponseByType(t))).then((async e=>{var s,o;if(!t.extractResultData)return;const r=await t.extractResultData((null==(o=(s=t.deepChat).responseInterceptor)?void 0:o.call(s,e))||e);if(!m)throw e;r.pollingInAnotherRequest||(i.addNewMessage(r,!0,!0),n())})).catch((t=>{M.displayError(i,t),n()}))}static requestStream(t,e,i,n,s,o,r=!0){var a,l,c,u,h,d;const p={body:e,headers:null==(a=t.requestSettings)?void 0:a.headers},{body:m,headers:f}=(null==(c=(l=t.deepChat).requestInterceptor)?void 0:c.call(l,p))||p;if((null==(u=t.requestSettings)?void 0:u.url)===j.URL)return j.requestStream(i,n,s);let v=null;g((null==(h=t.requestSettings)?void 0:h.url)||t.url||"",{method:(null==(d=t.requestSettings)?void 0:d.method)||"POST",headers:f,body:r?JSON.stringify(m):m,openWhenHidden:!0,async onopen(t){if(t.ok)return v=i.addNewStreamedMessage(),n();throw await A.processResponseByType(t)},onmessage(e){var n;if(console.log(e),JSON.stringify(e.data)!==JSON.stringify("[DONE]")){const s=JSON.parse(e.data);null==(n=t.extractResultData)||n.call(t,s).then((t=>{v&&i.updateStreamedMessage(t.text,v)}))}},onerror(t){throw s(),t},onclose(){i.finaliseStreamedMessage(),s()},signal:o.signal}).catch((e=>{var n;null==(n=t.extractResultData)||n.call(t,e).then((()=>{M.displayError(i,e)})).catch((t=>{M.displayError(i,t)}))}))}static executePollRequest(t,e,i,n,s){console.log("polling"),fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData((null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{A.executePollRequest(t,e,i,n,s)}),l.timeoutMS):(console.log("finished polling"),n.addNewMessage(l,!0,!0),s())})).catch((t=>{M.displayError(n,t),s()}))}static poll(t,e,i,n,s=!0){var o,r,a,l,c;const u={body:e,headers:null==(o=t.requestSettings)?void 0:o.headers},{body:h,headers:d}=(null==(a=(r=t.deepChat).requestInterceptor)?void 0:a.call(r,u))||u,p=(null==(l=t.requestSettings)?void 0:l.url)||t.url||"",m={method:(null==(c=t.requestSettings)?void 0:c.method)||"POST",body:s?JSON.stringify(h):h,headers:d};A.executePollRequest(t,p,m,i,n)}static verifyKey(t,e,i,n,s,o,r,a,l){if(""===t)return o(w);r(),fetch(e,{method:n,headers:i,body:l||null}).then((t=>A.processResponseByType(t))).then((e=>{a(e,t,s,o)})).catch((t=>{o(y),console.error(t)}))}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}}class S{static getCharacterLimitMessages(t,e){var i;let n=0,s=t.length-1;for(;s>=0;s-=1){const o=null==(i=t[s])?void 0:i.text;if(void 0!==o&&(n+=o.length,n>e)){t[s].text=o.substring(0,o.length-(n-e));break}}return t.slice(Math.max(s,0))}static getRequestMessages(t,e){var i;const n=[];let s=(null==(i=t.files)?void 0:i.length)||0,o=!!t.text;for(let t=e.length-1;t>=0;t-=1){const i=e[t];if(n.push(i),i.file?s-=1:i.text&&(o=!1),0===s&&!o)break}return n}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i,n){return void 0!==i?i>0&&(e=S.getMaxMessages(e,i)):e=S.getRequestMessages(t,e),void 0===n?e:S.getCharacterLimitMessages(e,n)}}class T{static setup(t,e){if(t.requestSettings.url!==j.URL){const i="boolean"!=typeof e?e:void 0;t.websocket=T.connect(t.requestSettings.url,i),t.permittedErrorPrefixes=["Connection error"]}}static connect(t,e){return new WebSocket(t||"",e)}static assignListeners(t,e){t.websocket&&(t.websocket.onmessage=async i=>{var n,s;if(t.extractResultData)try{const o=JSON.parse(i.data),r=await t.extractResultData((null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,o))||o);e.addNewMessage(r,!0,!0)}catch(t){M.displayError(e,t)}},t.websocket.onerror=t=>{console.error(t),e.addNewErrorMessage("service","Connection error")},t.websocket.onclose=()=>{console.error("Connection closed"),e.isLastMessageError()||e.addNewErrorMessage("service","Connection error")})}static sendWebsocket(t,e,i,n,s,o=!0){var r,a,l,c;const u={body:i,headers:null==(r=e.requestSettings)?void 0:r.headers},{body:h}=(null==(l=(a=e.deepChat).requestInterceptor)?void 0:l.call(a,u))||u,d=o?JSON.stringify(h):h;if((null==(c=e.requestSettings)?void 0:c.url)===j.URL)return j.request(n,s,e.deepChat.responseInterceptor);t.readyState!==t.OPEN?(console.error("Connection is not open"),n.addNewErrorMessage("service","Connection error")):t.send(JSON.stringify(d))}}var z;function O(t){return(z=z||document.createElement("textarea")).innerHTML="&"+t+";",z.value}var C=Object.prototype.hasOwnProperty;function L(t){return[].slice.call(arguments,1).forEach((function(e){if(e){if("object"!=typeof e)throw new TypeError(e+"must be object");Object.keys(e).forEach((function(i){t[i]=e[i]}))}})),t}var I=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function N(t){return t.indexOf("\\")<0?t:t.replace(I,"$1")}function E(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||65535==(65535&t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function D(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var _=/&([a-z#][a-z0-9]{1,31});/gi,P=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function R(t,e){var i=0,n=O(e);return e!==n?n:35===e.charCodeAt(0)&&P.test(e)&&E(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?D(i):t}function F(t){return t.indexOf("&")<0?t:t.replace(_,R)}var B=/[&<>"]/,q=/[&<>"]/g,Y={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function U(t){return Y[t]}function Z(t){return B.test(t)?t.replace(q,U):t}var J={};function V(t,e){return++e>=t.length-2?e:"paragraph_open"===t[e].type&&t[e].tight&&"inline"===t[e+1].type&&0===t[e+1].content.length&&"paragraph_close"===t[e+2].type&&t[e+2].tight?V(t,e+2):e}J.blockquote_open=function(){return"<blockquote>\n"},J.blockquote_close=function(t,e){return"</blockquote>"+$(t,e)},J.code=function(t,e){return t[e].block?"<pre><code>"+Z(t[e].content)+"</code></pre>"+$(t,e):"<code>"+Z(t[e].content)+"</code>"},J.fence=function(t,e,i,n,s){var o,r,a=t[e],l="",c=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&C.call(t,e)}(s.rules.fence_custom,o[0]))return s.rules.fence_custom[o[0]](t,e,i,n,s);l=' class="'+c+Z(F(N(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Z(a.content))+"</code></pre>"+$(t,e)},J.fence_custom={},J.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},J.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},J.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+$(t,e)},J.bullet_list_open=function(){return"<ul>\n"},J.bullet_list_close=function(t,e){return"</ul>"+$(t,e)},J.list_item_open=function(){return"<li>"},J.list_item_close=function(){return"</li>\n"},J.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},J.ordered_list_close=function(t,e){return"</ol>"+$(t,e)},J.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},J.paragraph_close=function(t,e){var i=!(t[e].tight&&e&&"inline"===t[e-1].type&&!t[e-1].content);return(t[e].tight?"":"</p>")+(i?$(t,e):"")},J.link_open=function(t,e,i){var n=t[e].title?' title="'+Z(F(t[e].title))+'"':"",s=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Z(t[e].href)+'"'+n+s+">"},J.link_close=function(){return"</a>"},J.image=function(t,e,i){var n=' src="'+Z(t[e].src)+'"',s=t[e].title?' title="'+Z(F(t[e].title))+'"':"";return"<img"+n+(' alt="'+(t[e].alt?Z(F(N(t[e].alt))):"")+'"')+s+(i.xhtmlOut?" /":"")+">"},J.table_open=function(){return"<table>\n"},J.table_close=function(){return"</table>\n"},J.thead_open=function(){return"<thead>\n"},J.thead_close=function(){return"</thead>\n"},J.tbody_open=function(){return"<tbody>\n"},J.tbody_close=function(){return"</tbody>\n"},J.tr_open=function(){return"<tr>"},J.tr_close=function(){return"</tr>\n"},J.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},J.th_close=function(){return"</th>"},J.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},J.td_close=function(){return"</td>"},J.strong_open=function(){return"<strong>"},J.strong_close=function(){return"</strong>"},J.em_open=function(){return"<em>"},J.em_close=function(){return"</em>"},J.del_open=function(){return"<del>"},J.del_close=function(){return"</del>"},J.ins_open=function(){return"<ins>"},J.ins_close=function(){return"</ins>"},J.mark_open=function(){return"<mark>"},J.mark_close=function(){return"</mark>"},J.sub=function(t,e){return"<sub>"+Z(t[e].content)+"</sub>"},J.sup=function(t,e){return"<sup>"+Z(t[e].content)+"</sup>"},J.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},J.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},J.text=function(t,e){return Z(t[e].content)},J.htmlblock=function(t,e){return t[e].content},J.htmltag=function(t,e){return t[e].content},J.abbr_open=function(t,e){return'<abbr title="'+Z(F(t[e].title))+'">'},J.abbr_close=function(){return"</abbr>"},J.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),n="fnref"+i;return t[e].subId>0&&(n+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+n+'">['+i+"]</a></sup>"},J.footnote_block_open=function(t,e,i){return(i.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},J.footnote_block_close=function(){return"</ol>\n</section>\n"},J.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},J.footnote_close=function(){return"</li>\n"},J.footnote_anchor=function(t,e){var i="fnref"+Number(t[e].id+1).toString();return t[e].subId>0&&(i+=":"+t[e].subId),' <a href="#'+i+'" class="footnote-backref">↩</a>'},J.dl_open=function(){return"<dl>\n"},J.dt_open=function(){return"<dt>"},J.dd_open=function(){return"<dd>"},J.dl_close=function(){return"</dl>\n"},J.dt_close=function(){return"</dt>\n"},J.dd_close=function(){return"</dd>\n"};var $=J.getBreak=function(t,e){return(e=V(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function H(){this.rules=L({},J),this.getBreak=J.getBreak}function G(){this.t=[],this.i=null}function K(t,e,i,n,s){this.src=t,this.env=n,this.options=i,this.parser=e,this.tokens=s,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0}function Q(t,e){var i,n,s,o=-1,r=t.posMax,a=t.pos,l=t.isInLabel;if(t.isInLabel)return-1;if(t.labelUnmatchedScopes)return t.labelUnmatchedScopes--,-1;for(t.pos=e+1,t.isInLabel=!0,i=1;t.pos<r;){if(91===(s=t.src.charCodeAt(t.pos)))i++;else if(93===s&&0===--i){n=!0;break}t.parser.skipToken(t)}return n?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=l,o}function W(t,e,i,n){var s,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=Q(s=new K(t,e,i,n,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&10!==s.src.charCodeAt(r);r++);return l=t.slice(2,o),0===(c=t.slice(o+2,r).trim()).length?-1:(n.abbreviations||(n.abbreviations={}),typeof n.abbreviations[":"+l]>"u"&&(n.abbreviations[":"+l]=c),r)}function X(t){var e=F(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function tt(t,e){var i,n,s,o=e,r=t.posMax;if(60===t.src.charCodeAt(e)){for(e++;e<r;){if(10===(i=t.src.charCodeAt(e)))return!1;if(62===i)return s=X(N(t.src.slice(o+1,e))),!!t.parser.validateLink(s)&&(t.pos=e+1,t.linkContent=s,!0);92===i&&e+1<r?e+=2:e++}return!1}for(n=0;e<r&&!(32===(i=t.src.charCodeAt(e))||i<32||127===i);)if(92===i&&e+1<r)e+=2;else{if(40===i&&++n>1||41===i&&--n<0)break;e++}return!(o===e||(s=N(t.src.slice(o,e)),!t.parser.validateLink(s)))&&(t.linkContent=s,t.pos=e,!0)}function et(t,e){var i,n=e,s=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<s;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=N(t.src.slice(n+1,e)),!0;92===i&&e+1<s?e+=2:e++}return!1}function it(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function nt(t,e,i,n){var s,o,r,a,l,c,u,h,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=Q(s=new K(t,e,i,n,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&(32===(l=s.src.charCodeAt(r))||10===l);r++);if(!tt(s,r))return-1;for(u=s.linkContent,c=r=s.pos,r+=1;r<a&&(32===(l=s.src.charCodeAt(r))||10===l);r++);for(r<a&&c!==r&&et(s,r)?(h=s.linkContent,r=s.pos):(h="",r=c);r<a&&32===s.src.charCodeAt(r);)r++;return r<a&&10!==s.src.charCodeAt(r)?-1:(d=it(t.slice(1,o)),typeof n.references[d]>"u"&&(n.references[d]={title:h,href:u}),r)}H.prototype.renderInline=function(t,e,i){for(var n=this.rules,s=t.length,o=0,r="";s--;)r+=n[t[o].type](t,o++,e,i,this);return r},H.prototype.render=function(t,e,i){for(var n=this.rules,s=t.length,o=-1,r="";++o<s;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=n[t[o].type](t,o,e,i,this);return r},G.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},G.prototype.l=function(){var t=this,e=[""];t.t.forEach((function(t){t.enabled&&t.alt.forEach((function(t){e.indexOf(t)<0&&e.push(t)}))})),t.i={},e.forEach((function(e){t.i[e]=[],t.t.forEach((function(i){i.enabled&&(e&&i.alt.indexOf(e)<0||t.i[e].push(i.fn))}))}))},G.prototype.at=function(t,e,i){var n=this.o(t),s=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t[n].fn=e,this.t[n].alt=s.alt||[],this.i=null},G.prototype.before=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},G.prototype.after=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},G.prototype.push=function(t,e,i){var n=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:n.alt||[]}),this.i=null},G.prototype.enable=function(t,e){t=Array.isArray(t)?t:[t],e&&this.t.forEach((function(t){t.enabled=!1})),t.forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!0}),this),this.i=null},G.prototype.disable=function(t){(t=Array.isArray(t)?t:[t]).forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!1}),this),this.i=null},G.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},K.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},K.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},K.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},K.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var st=" \n()[]'\".,!?-";function ot(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var rt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,at=/\((c|tm|r|p)\)/gi,lt={c:"©",r:"®",p:"§",tm:"™"};function ct(t){return t.indexOf("(")<0?t:t.replace(at,(function(t,e){return lt[e.toLowerCase()]}))}var ut=/['"]/,ht=/['"]/g,dt=/[-\s()\[\]]/,pt="’";function mt(t,e){return!(e<0||e>=t.length)&&!dt.test(t[e])}function ft(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var vt=[["block",function(t){t.inlineMode?t.tokens.push({type:"inline",content:t.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):t.block.parse(t.src,t.options,t.env,t.tokens)}],["abbr",function(t){var e,i,n,s,o=t.tokens;if(!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("paragraph_open"===o[e-1].type&&"inline"===o[e].type&&"paragraph_close"===o[e+1].type){for(n=o[e].content;n.length&&!((s=W(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,i,n,s,o=t.tokens;if(t.env.references=t.env.references||{},!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("inline"===o[e].type&&"paragraph_open"===o[e-1].type&&"paragraph_close"===o[e+1].type){for(n=o[e].content;n.length&&!((s=nt(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,i,n,s=t.tokens;for(i=0,n=s.length;i<n;i++)"inline"===(e=s[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,i,n,s,o,r,a,l,c,u=0,h=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(h=!0,l=[],c=t.label,!1):"footnote_reference_close"===t.type?(h=!1,d[":"+c]=l,!1):(h&&l.push(t),!h)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:u++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:u++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:u++}),a.push({type:"inline",content:"",level:u,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--u})):r[e].label&&(a=d[":"+r[e].label]),t.tokens=t.tokens.concat(a),o="paragraph_close"===t.tokens[t.tokens.length-1].type?t.tokens.pop():null,s=r[e].count>0?r[e].count:1,n=0;n<s;n++)t.tokens.push({type:"footnote_anchor",id:e,subId:n,level:u});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--u})}t.tokens.push({type:"footnote_block_close",level:--u})}}],["abbr2",function(t){var e,i,n,s,o,r,a,l,c,u,h,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+st.split("").map(ot).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(ot).join("|")+")($|["+st.split("").map(ot).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),u=t.env.abbrRegExp,i=0,n=p.length;i<n;i++)if("inline"===p[i].type)for(e=(s=p[i].children).length-1;e>=0;e--)if("text"===(o=s[e]).type){for(l=0,r=o.content,u.lastIndex=0,c=o.level,a=[];h=u.exec(r);)u.lastIndex>l&&a.push({type:"text",content:r.slice(l,h.index+h[1].length),level:c}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+h[2]],level:c++}),a.push({type:"text",content:h[2],level:c}),a.push({type:"abbr_close",level:--c}),l=u.lastIndex-h[3].length;a.length&&(l<r.length&&a.push({type:"text",content:r.slice(l),level:c}),p[i].children=s=[].concat(s.slice(0,e),a,s.slice(e+1)))}}],["replacements",function(t){var e,i,n,s,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(s=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=s[e]).type&&(n=ct(n=i.content),rt.test(n)&&(n=n.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")),i.content=n)}],["smartquotes",function(t){var e,i,n,s,o,r,a,l,c,u,h,d,p,m,f,v,g;if(t.options.typographer)for(g=[],f=t.tokens.length-1;f>=0;f--)if("inline"===t.tokens[f].type)for(v=t.tokens[f].children,g.length=0,e=0;e<v.length;e++)if("text"===(i=v[e]).type&&!ut.test(i.text)){for(a=v[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(n=i.content).length;t:for(;o<r&&(ht.lastIndex=o,s=ht.exec(n),s);)if(l=!mt(n,s.index-1),o=s.index+1,m="'"===s[0],(c=!mt(n,o))||l){if(h=!c,d=!l)for(p=g.length-1;p>=0&&(u=g[p],!(g[p].level<a));p--)if(u.single===m&&g[p].level===a){u=g[p],m?(v[u.token].content=ft(v[u.token].content,u.pos,t.options.quotes[2]),i.content=ft(i.content,s.index,t.options.quotes[3])):(v[u.token].content=ft(v[u.token].content,u.pos,t.options.quotes[0]),i.content=ft(i.content,s.index,t.options.quotes[1])),g.length=p;continue t}h?g.push({token:e,pos:s.index,single:m,level:a}):d&&m&&(i.content=ft(i.content,s.index,pt))}else m&&(i.content=ft(i.content,s.index,pt))}}]];function gt(){this.options={},this.ruler=new G;for(var t=0;t<vt.length;t++)this.ruler.push(vt[t][0],vt[t][1])}function bt(t,e,i,n,s){var o,r,a,l,c,u,h;for(this.src=t,this.parser=e,this.options=i,this.env=n,this.tokens=s,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",u=0,h=!1,a=l=u=0,c=(r=this.src).length;l<c;l++){if(o=r.charCodeAt(l),!h){if(32===o){u++;continue}h=!0}(10===o||l===c-1)&&(10!==o&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(u),h=!1,u=0,a=l+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function wt(t,e){var i,n,s;return(n=t.bMarks[e]+t.tShift[e])>=(s=t.eMarks[e])||42!==(i=t.src.charCodeAt(n++))&&45!==i&&43!==i||n<s&&32!==t.src.charCodeAt(n)?-1:n}function yt(t,e){var i,n=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];if(n+1>=s||((i=t.src.charCodeAt(n++))<48||i>57))return-1;for(;;){if(n>=s)return-1;if(!((i=t.src.charCodeAt(n++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return n<s&&32!==t.src.charCodeAt(n)?-1:n}gt.prototype.process=function(t){var e,i,n;for(e=0,i=(n=this.ruler.getRules("")).length;e<i;e++)n[e](t)},bt.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},bt.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},bt.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},bt.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},bt.prototype.skipCharsBack=function(t,e,i){if(t<=i)return t;for(;t>i;)if(e!==this.src.charCodeAt(--t))return t+1;return t},bt.prototype.getLines=function(t,e,i,n){var s,o,r,a,l,c=t;if(t>=e)return"";if(c+1===e)return o=this.bMarks[c]+Math.min(this.tShift[c],i),r=n?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,r);for(a=new Array(e-t),s=0;c<e;c++,s++)(l=this.tShift[c])>i&&(l=i),l<0&&(l=0),o=this.bMarks[c]+l,r=c+1<e||n?this.eMarks[c]+1:this.eMarks[c],a[s]=this.src.slice(o,r);return a.join("")};var xt={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach((function(t){xt[t]=!0}));var Mt=/^<([a-zA-Z]{1,15})[\s\/>]/,kt=/^<\/([a-zA-Z]{1,15})[\s>]/;function jt(t,e){var i=t.bMarks[e]+t.blkIndent,n=t.eMarks[e];return t.src.substr(i,n-i)}function At(t,e){var i,n,s=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return s>=o||126!==(n=t.src.charCodeAt(s++))&&58!==n||s===(i=t.skipSpaces(s))||i>=o?-1:i}var St=[["code",function(t,e,i){var n,s;if(t.tShift[e]-t.blkIndent<4)return!1;for(s=n=e+1;n<i;)if(t.isEmpty(n))n++;else{if(!(t.tShift[n]-t.blkIndent>=4))break;s=++n}return t.line=n,t.tokens.push({type:"code",content:t.getLines(e,s,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,n){var s,o,r,a,l,c=!1,u=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(u+3>h||126!==(s=t.src.charCodeAt(u))&&96!==s||(l=u,(o=(u=t.skipChars(u,s))-l)<3)||(r=t.src.slice(u,h).trim()).indexOf("`")>=0)return!1;if(n)return!0;for(a=e;!(++a>=i||(u=l=t.bMarks[a]+t.tShift[a],h=t.eMarks[a],u<h&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(u)!==s||t.tShift[a]-t.blkIndent>=4||(u=t.skipChars(u,s),u-l<o||(u=t.skipSpaces(u),u<h)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,f=t.bMarks[e]+t.tShift[e],v=t.eMarks[e];if(f>v||62!==t.src.charCodeAt(f++)||t.level>=t.options.maxNesting)return!1;if(n)return!0;for(32===t.src.charCodeAt(f)&&f++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r=[t.tShift[e]],t.tShift[e]=f-t.bMarks[e],h=t.parser.ruler.getRules("blockquote"),s=e+1;s<i&&!((f=t.bMarks[s]+t.tShift[s])>=(v=t.eMarks[s]));s++)if(62!==t.src.charCodeAt(f++)){if(o)break;for(m=!1,d=0,p=h.length;d<p;d++)if(h[d](t,s,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[s]),r.push(t.tShift[s]),t.tShift[s]=-1337}else 32===t.src.charCodeAt(f)&&f++,a.push(t.bMarks[s]),t.bMarks[s]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r.push(t.tShift[s]),t.tShift[s]=f-t.bMarks[s];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:u=[e,0],level:t.level++}),t.parser.tokenize(t,e,s),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,u[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,n){var s,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(s=t.src.charCodeAt(a++))&&45!==s&&95!==s)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==s&&32!==r)return!1;r===s&&o++}return!(o<3)&&(n||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,f,v,g,b,w,y,x,M,k,j,A=!0;if((h=yt(t,e))>=0)f=!0;else{if(!((h=wt(t,e))>=0))return!1;f=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(h-1),n)return!0;for(g=t.tokens.length,f?(u=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(u,h-u-1)),t.tokens.push({type:"ordered_list_open",order:p,lines:w=[e,0],level:t.level++})):t.tokens.push({type:"bullet_list_open",lines:w=[e,0],level:t.level++}),s=e,b=!1,x=t.parser.ruler.getRules("list");s<i&&((d=(v=t.skipSpaces(h))>=t.eMarks[s]?1:v-h)>4&&(d=1),d<1&&(d=1),o=h-t.bMarks[s]+d,t.tokens.push({type:"list_item_open",lines:y=[e,0],level:t.level++}),a=t.blkIndent,l=t.tight,r=t.tShift[e],c=t.parentType,t.tShift[e]=v-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(A=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),s=e=t.line,y[1]=s,v=t.bMarks[e],!(s>=i||t.isEmpty(s)||t.tShift[s]<t.blkIndent));){for(j=!1,M=0,k=x.length;M<k;M++)if(x[M](t,s,i,!0)){j=!0;break}if(j)break;if(f){if((h=yt(t,s))<0)break}else if((h=wt(t,s))<0)break;if(m!==t.src.charCodeAt(h-1))break}return t.tokens.push({type:f?"ordered_list_close":"bullet_list_close",level:--t.level}),w[1]=s,t.line=s,A&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,g),!0},["paragraph","blockquote"]],["footnote",function(t,e,i,n){var s,o,r,a,l,c=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(c+4>u||91!==t.src.charCodeAt(c)||94!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting)return!1;for(a=c+2;a<u;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===c+2||a+1>=u||58!==t.src.charCodeAt(++a))&&(n||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),l=t.src.slice(c+2,a-2),t.env.footnotes.refs[":"+l]=-1,t.tokens.push({type:"footnote_reference_open",label:l,level:t.level++}),s=t.bMarks[e],o=t.tShift[e],r=t.parentType,t.tShift[e]=t.skipSpaces(a)-a,t.bMarks[e]=a,t.blkIndent+=4,t.parentType="footnote",t.tShift[e]<t.blkIndent&&(t.tShift[e]+=t.blkIndent,t.bMarks[e]-=t.blkIndent),t.parser.tokenize(t,e,i,!0),t.parentType=r,t.blkIndent-=4,t.tShift[e]=o,t.bMarks[e]=s,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)},["paragraph"]],["heading",function(t,e,i,n){var s,o,r,a=t.bMarks[e]+t.tShift[e],l=t.eMarks[e];if(a>=l||(35!==(s=t.src.charCodeAt(a))||a>=l))return!1;for(o=1,s=t.src.charCodeAt(++a);35===s&&a<l&&o<=6;)o++,s=t.src.charCodeAt(++a);return!(o>6||a<l&&32!==s)&&(n||(l=t.skipCharsBack(l,32,a),(r=t.skipCharsBack(l,35,a))>a&&32===t.src.charCodeAt(r-1)&&(l=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<l&&t.tokens.push({type:"inline",content:t.src.slice(a,l).trim(),level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"heading_close",hLevel:o,level:t.level})),!0)},["paragraph","blockquote"]],["lheading",function(t,e,i){var n,s,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(s=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],s>=o)||(n=t.src.charCodeAt(s),45!==n&&61!==n)||(s=t.skipChars(s,n),s=t.skipSpaces(s),s<o))&&(s=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===n?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(s,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===n?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,i,n){var s,o,r,a=t.bMarks[e],l=t.eMarks[e],c=t.tShift[e];if(a+=c,!t.options.html||c>3||a+2>=l||60!==t.src.charCodeAt(a))return!1;if(33===(s=t.src.charCodeAt(a+1))||63===s){if(n)return!0}else{if(47!==s&&!function(t){var e=32|t;return e>=97&&e<=122}(s))return!1;if(47===s){if(!(o=t.src.slice(a,l).match(kt)))return!1}else if(!(o=t.src.slice(a,l).match(Mt)))return!1;if(!0!==xt[o[1].toLowerCase()])return!1;if(n)return!0}for(r=e+1;r<t.lineMax&&!t.isEmpty(r);)r++;return t.line=r,t.tokens.push({type:"htmlblock",level:t.level,lines:[e,t.line],content:t.getLines(e,r,0,!0)}),!0},["paragraph","blockquote"]],["table",function(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m;if(e+2>i||(l=e+1,t.tShift[l]<t.blkIndent)||(r=t.bMarks[l]+t.tShift[l])>=t.eMarks[l]||124!==(s=t.src.charCodeAt(r))&&45!==s&&58!==s||(o=jt(t,e+1),!/^[-:| ]+$/.test(o))||(c=o.split("|"))<=2)return!1;for(h=[],a=0;a<c.length;a++){if(!(d=c[a].trim())){if(0===a||a===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?h.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?h.push("left"):h.push("")}if(-1===(o=jt(t,e).trim()).indexOf("|")||(c=o.replace(/^\||\|$/g,"").split("|"),h.length!==c.length))return!1;if(n)return!0;for(t.tokens.push({type:"table_open",lines:p=[e,0],level:t.level++}),t.tokens.push({type:"thead_open",lines:[e,e+1],level:t.level++}),t.tokens.push({type:"tr_open",lines:[e,e+1],level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"th_open",align:h[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:t.level,children:[]}),t.tokens.push({type:"th_close",level:--t.level});for(t.tokens.push({type:"tr_close",level:--t.level}),t.tokens.push({type:"thead_close",level:--t.level}),t.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:t.level++}),l=e+2;l<i&&!(t.tShift[l]<t.blkIndent||(o=jt(t,l).trim(),-1===o.indexOf("|")));l++){for(c=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"td_open",align:h[a],level:t.level++}),u=c[a].substring(124===c[a].charCodeAt(0)?1:0,124===c[a].charCodeAt(c[a].length-1)?c[a].length-1:c[a].length).trim(),t.tokens.push({type:"inline",content:u,level:t.level,children:[]}),t.tokens.push({type:"td_close",level:--t.level});t.tokens.push({type:"tr_close",level:--t.level})}return t.tokens.push({type:"tbody_close",level:--t.level}),t.tokens.push({type:"table_close",level:--t.level}),p[1]=m[1]=l,t.line=l,!0},["paragraph"]],["deflist",function(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,f,v,g;if(n)return!(t.ddIndent<0)&&At(t,e)>=0;if(u=e+1,t.isEmpty(u)&&++u>i||t.tShift[u]<t.blkIndent||(s=At(t,u))<0||t.level>=t.options.maxNesting)return!1;c=t.tokens.length,t.tokens.push({type:"dl_open",lines:l=[e,0],level:t.level++}),r=e,o=u;t:for(;;){for(g=!0,v=!1,t.tokens.push({type:"dt_open",lines:[r,r],level:t.level++}),t.tokens.push({type:"inline",content:t.getLines(r,r+1,t.blkIndent,!1).trim(),level:t.level+1,lines:[r,r],children:[]}),t.tokens.push({type:"dt_close",level:--t.level});;){if(t.tokens.push({type:"dd_open",lines:a=[u,0],level:t.level++}),f=t.tight,d=t.ddIndent,h=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=s-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||v)&&(g=!1),v=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=f,t.parentType=p,t.blkIndent=h,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=u=t.line,u>=i||t.tShift[u]<t.blkIndent)break t;if((s=At(t,u))<0)break;o=u}if(u>=i||(r=u,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(s=At(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),l[1]=u,t.line=u,g&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,c),!0},["paragraph"]],["paragraph",function(t,e){var i,n,s,o,r,a,l=e+1;if(l<(i=t.lineMax)&&!t.isEmpty(l))for(a=t.parser.ruler.getRules("paragraph");l<i&&!t.isEmpty(l);l++)if(!(t.tShift[l]-t.blkIndent>3)){for(s=!1,o=0,r=a.length;o<r;o++)if(a[o](t,l,i,!0)){s=!0;break}if(s)break}return n=t.getLines(e,l,t.blkIndent,!1).trim(),t.line=l,n.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:n,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function Tt(){this.ruler=new G;for(var t=0;t<St.length;t++)this.ruler.push(St[t][0],St[t][1],{alt:(St[t][2]||[]).slice()})}Tt.prototype.tokenize=function(t,e,i){for(var n,s=this.ruler.getRules(""),o=s.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(n=0;n<o&&!s[n](t,r,i,!1);n++);if(t.tight=!a,t.isEmpty(t.line-1)&&(a=!0),(r=t.line)<i&&t.isEmpty(r)){if(a=!0,++r<i&&"list"===t.parentType&&t.isEmpty(r))break;t.line=r}}};var zt=/[\n\t]/g,Ot=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Ct=/\u00a0/g;function Lt(t){switch(t){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}Tt.prototype.parse=function(t,e,i,n){var s,o=0,r=0;if(!t)return[];(t=(t=t.replace(Ct," ")).replace(Ot,"\n")).indexOf("\t")>=0&&(t=t.replace(zt,(function(e,i){var n;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(n=" ".slice((i-o-r)%4),r=i-o+1,n)}))),s=new bt(t,this,e,i,n),this.tokenize(s,s.line,s.lineMax)};for(var It=[],Nt=0;Nt<256;Nt++)It.push(0);function Et(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function Dt(t,e){var i,n,s,o=e,r=!0,a=!0,l=t.posMax,c=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<l&&t.src.charCodeAt(o)===c;)o++;return o>=l&&(r=!1),(s=o-e)>=4?r=a=!1:((32===(n=o<l?t.src.charCodeAt(o):-1)||10===n)&&(r=!1),(32===i||10===i)&&(a=!1),95===c&&(Et(i)&&(r=!1),Et(n)&&(a=!1))),{can_open:r,can_close:a,delims:s}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){It[t.charCodeAt(0)]=1}));var _t=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Pt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Rt=["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"],Ft=/^<([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])?)*)>/,Bt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function qt(t,e){return t=t.source,e=e||"",function i(n,s){return n?(s=s.source||s,t=t.replace(n,s),i):new RegExp(t,e)}}var Yt=qt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Ut=qt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Yt)(),Zt=qt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Ut)(),Jt=qt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Zt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Vt=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,$t=/^&([a-z][a-z0-9]{1,31});/i;var Ht=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Lt(t.src.charCodeAt(i));)i++;return i!==t.pos&&(e||(t.pending+=t.src.slice(t.pos,i)),t.pos=i,!0)}],["newline",function(t,e){var i,n,s=t.pos;if(10!==t.src.charCodeAt(s))return!1;if(i=t.pending.length-1,n=t.posMax,!e)if(i>=0&&32===t.pending.charCodeAt(i))if(i>=1&&32===t.pending.charCodeAt(i-1)){for(var o=i-2;o>=0;o--)if(32!==t.pending.charCodeAt(o)){t.pending=t.pending.substring(0,o+1);break}t.push({type:"hardbreak",level:t.level})}else t.pending=t.pending.slice(0,-1),t.push({type:"softbreak",level:t.level});else t.push({type:"softbreak",level:t.level});for(s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}],["escape",function(t,e){var i,n=t.pos,s=t.posMax;if(92!==t.src.charCodeAt(n))return!1;if(++n<s){if((i=t.src.charCodeAt(n))<256&&0!==It[i])return e||(t.pending+=t.src[n]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var i,n,s,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,n=t.posMax;a<n&&96===t.src.charCodeAt(a);)a++;for(s=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<n&&96===t.src.charCodeAt(r);)r++;if(r-o===s.length)return e||t.push({type:"code",content:t.src.slice(a,o).replace(/[ \n]+/g," ").trim(),block:!1,level:t.level}),t.pos=r,!0}return e||(t.pending+=s),t.pos+=s.length,!0}],["del",function(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(126!==t.src.charCodeAt(l)||e||l+4>=a||126!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),126===o)||126===r||32===r||10===r)return!1;for(n=l+2;n<a&&126===t.src.charCodeAt(n);)n++;if(n>l+3)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(126===t.src.charCodeAt(t.pos)&&126===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),126!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&126!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"del_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"del_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["ins",function(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(43!==t.src.charCodeAt(l)||e||l+4>=a||43!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),43===o)||43===r||32===r||10===r)return!1;for(n=l+2;n<a&&43===t.src.charCodeAt(n);)n++;if(n!==l+2)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(43===t.src.charCodeAt(t.pos)&&43===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),43!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&43!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"ins_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"ins_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["mark",function(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(61!==t.src.charCodeAt(l)||e||l+4>=a||61!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),61===o)||61===r||32===r||10===r)return!1;for(n=l+2;n<a&&61===t.src.charCodeAt(n);)n++;if(n!==l+2)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(61===t.src.charCodeAt(t.pos)&&61===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),61!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&61!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"mark_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"mark_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["emphasis",function(t,e){var i,n,s,o,r,a,l,c=t.posMax,u=t.pos,h=t.src.charCodeAt(u);if(95!==h&&42!==h||e)return!1;if(i=(l=Dt(t,u)).delims,!l.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(u,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=u+i,a=[i];t.pos<c;)if(t.src.charCodeAt(t.pos)!==h)t.parser.skipToken(t);else{if(n=(l=Dt(t,t.pos)).delims,l.can_close){for(o=a.pop(),r=n;o!==r;){if(r<o){a.push(o-r);break}if(r-=o,0===a.length)break;t.pos+=o,o=a.pop()}if(0===a.length){i=o,s=!0;break}t.pos+=n;continue}l.can_open&&a.push(n),t.pos+=n}return s?(t.posMax=t.pos,t.pos=u+i,e||((2===i||3===i)&&t.push({type:"strong_open",level:t.level++}),(1===i||3===i)&&t.push({type:"em_open",level:t.level++}),t.parser.tokenize(t),(1===i||3===i)&&t.push({type:"em_close",level:--t.level}),(2===i||3===i)&&t.push({type:"strong_close",level:--t.level})),t.pos=t.posMax+i,t.posMax=c,!0):(t.pos=u,!1)}],["sub",function(t,e){var i,n,s=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sub",level:t.level,content:n.replace(_t,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["sup",function(t,e){var i,n,s=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sup",level:t.level,content:n.replace(Pt,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["links",function(t,e){var i,n,s,o,r,a,l,c,u=!1,h=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(u=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(n=Q(t,p))<0))return!1;if((a=n+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a>=d)return!1;for(p=a,tt(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&p!==a&&et(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=h,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=Q(t,a))>=0?s=t.src.slice(p,a++):a=p-1),s||(typeof s>"u"&&(a=n+1),s=t.src.slice(i,n)),!(l=t.env.references[it(s)]))return t.pos=h,!1;o=l.href,r=l.title}return e||(t.pos=i,t.posMax=n,u?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,n-i),level:t.level}):(t.push({type:"link_open",href:o,title:r,level:t.level++}),t.linkLevel++,t.parser.tokenize(t),t.linkLevel--,t.push({type:"link_close",level:--t.level}))),t.pos=a,t.posMax=d,!0}],["footnote_inline",function(t,e){var i,n,s,o,r=t.posMax,a=t.pos;return!(a+2>=r||94!==t.src.charCodeAt(a)||91!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting||(i=a+2,n=Q(t,a+1),n<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),s=t.env.footnotes.list.length,t.pos=i,t.posMax=n,t.push({type:"footnote_ref",id:s,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[s]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=n+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var i,n,s,o,r=t.posMax,a=t.pos;if(a+3>r||!t.env.footnotes||!t.env.footnotes.refs||91!==t.src.charCodeAt(a)||94!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting)return!1;for(n=a+2;n<r;n++){if(32===t.src.charCodeAt(n)||10===t.src.charCodeAt(n))return!1;if(93===t.src.charCodeAt(n))break}return!(n===a+2||n>=r||(n++,i=t.src.slice(a+2,n-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(s=t.env.footnotes.list.length,t.env.footnotes.list[s]={label:i,count:0},t.env.footnotes.refs[":"+i]=s):s=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[s].count,t.env.footnotes.list[s].count++,t.push({type:"footnote_ref",id:s,subId:o,level:t.level})),t.pos=n,t.posMax=r,!0)}],["autolink",function(t,e){var i,n,s,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((n=i.match(Bt))?!(Rt.indexOf(n[1].toLowerCase())<0||(o=n[0].slice(1,-1),r=X(o),!t.parser.validateLink(o)))&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=n[0].length,!0):!!(s=i.match(Ft))&&(r=X("mailto:"+(o=s[0].slice(1,-1))),!!t.parser.validateLink(r)&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=s[0].length,!0)))}],["htmltag",function(t,e){var i,n,s,o=t.pos;return!(!t.options.html||(s=t.posMax,60!==t.src.charCodeAt(o)||o+2>=s)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!function(t){var e=32|t;return e>=97&&e<=122}(i))||(n=t.src.slice(o).match(Jt),!n))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+n[0].length),level:t.level}),t.pos+=n[0].length,!0)}],["entity",function(t,e){var i,n,s=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(s))return!1;if(s+1<o)if(35===t.src.charCodeAt(s+1)){if(n=t.src.slice(s).match(Vt))return e||(i="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),t.pending+=E(i)?D(i):D(65533)),t.pos+=n[0].length,!0}else if(n=t.src.slice(s).match($t)){var r=O(n[1]);if(n[1]!==r)return e||(t.pending+=r),t.pos+=n[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function Gt(){this.ruler=new G;for(var t=0;t<Ht.length;t++)this.ruler.push(Ht[t][0],Ht[t][1]);this.validateLink=Kt}function Kt(t){var e=t.trim().toLowerCase();return!(-1!==(e=F(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}Gt.prototype.skipToken=function(t){var e,i,n=this.ruler.getRules(""),s=n.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<s;e++)if(n[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},Gt.prototype.tokenize=function(t){for(var e,i,n=this.ruler.getRules(""),s=n.length,o=t.posMax;t.pos<o;){for(i=0;i<s&&!(e=n[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},Gt.prototype.parse=function(t,e,i,n){var s=new K(t,this,e,i,n);this.tokenize(s)};var Qt={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 Wt(t,e,i){this.src=e,this.env=i,this.options=t.options,this.tokens=[],this.inlineMode=!1,this.inline=t.inline,this.block=t.block,this.renderer=t.renderer,this.typographer=t.typographer}function Xt(t,e){"string"!=typeof t&&(e=t,t="default"),e&&null!=e.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 Gt,this.block=new Tt,this.core=new gt,this.renderer=new H,this.ruler=new G,this.options={},this.configure(Qt[t]),this.set(e||{})}Xt.prototype.set=function(t){L(this.options,t)},Xt.prototype.configure=function(t){var e=this;if(!t)throw new Error("Wrong `remarkable` preset, check name/content");t.options&&e.set(t.options),t.components&&Object.keys(t.components).forEach((function(i){t.components[i].rules&&e[i].ruler.enable(t.components[i].rules,!0)}))},Xt.prototype.use=function(t,e){return t(this,e),this},Xt.prototype.parse=function(t,e){var i=new Wt(this,t,e);return this.core.process(i),i.tokens},Xt.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},Xt.prototype.parseInline=function(t,e){var i=new Wt(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},Xt.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class te{static createNew(){const t=window.hljs;return t?new Xt({highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(i,e).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!0}):new Xt}}class ee{static parseConfig(t,e,i,n){var s;const o={files:e};if("object"==typeof n){const{files:e,request:r,button:a}=n;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(s=e.infoModal)&&s.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||t.headers||t.method||t.url)&&(o.request={headers:(null==r?void 0:r.headers)||t.headers,method:(null==r?void 0:r.method)||t.method,url:(null==r?void 0:r.url)||t.url})}return o}static processMixedFiles(t,e,i){if(i){const n={acceptedFormats:""};t.fileTypes.mixedFiles=ee.parseConfig(t.requestSettings,n,e,i)}}static processMicrophone(t,e,i,n){var s,o,r,a,l,c;const u={acceptedFormats:"audio/*",...(null==(s=t.fileTypes.audio)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=ee.parseConfig(t.requestSettings,u,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):n||(t.fileTypes.audio=ee.parseConfig(t.requestSettings,u,e,i)))}static processAudioConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"audio/*",...(null==n?void 0:n.files)||{}};t.fileTypes.audio=ee.parseConfig(t.requestSettings,s,e,i)}static processGifConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/gif",...(null==n?void 0:n.files)||{}};t.fileTypes.gifs=ee.parseConfig(t.requestSettings,s,e,i)}static processCamera(t,e,i,n){var s,o,r,a;const l={acceptedFormats:"image/*",...(null==(s=t.fileTypes.images)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=ee.parseConfig(t.requestSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):n||(t.fileTypes.images=ee.parseConfig(t.requestSettings,l,e,i)))}static processImagesConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/*",...(null==n?void 0:n.files)||{}};t.fileTypes.images=ee.parseConfig(t.requestSettings,s,e,i)}static populateDefaultFileIO(t,e){var i,n;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(n=t.files).maxNumberOfFiles??(n.maxNumberOfFiles=1))}static set(t,e,i){ee.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),ee.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const n=te.createNew();ee.processImagesConfig(e,n,t.images,null==i?void 0:i.images),ee.processCamera(e,n,t.camera,t.images),ee.processGifConfig(e,n,t.gifs,null==i?void 0:i.gifs),ee.processAudioConfig(e,n,t.audio,null==i?void 0:i.audio),ee.processMicrophone(e,n,t.microphone,t.audio),ee.processMixedFiles(e,n,t.mixedFiles)}}class ie{constructor(t,e,i){var n,s,o,r;this.rawBody={},this.validateConfigKey=!1,this.canSendMessage=ie.canSendMessage,this.requestSettings={},this.fileTypes={},this._isStream=!1,this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(n=t.request)?void 0:n.additionalBodyProps),this._isStream=!!t.stream,this.totalMessagesMaxCharLength=null==(s=null==t?void 0:t.requestBodyLimits)?void 0:s.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,ee.set(t,this,e),t.request&&(this.requestSettings=t.request),this.demo&&((r=this.requestSettings).url??(r.url=j.URL)),this._directServiceRequiresFiles=!!e&&Object.keys(e).length>0,this.requestSettings.websocket&&T.setup(this,this.requestSettings.websocket)}static canSendMessage(t,e){return!(!t||""===t.trim())||!!(e&&e.length>0)}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const n=new FormData;i.forEach((t=>n.append("files",t))),Object.keys(t).forEach((e=>n.append(e,String(t[e]))));let s=0;return e.forEach((t=>{t.text&&n.append(`message${s+=1}`,JSON.stringify(t))})),n}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.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}callServiceAPI(t,e,i,n,s){var o,r,a,l;const c={messages:e,...this.rawBody};let u=!1;null!=(o=this.requestSettings.headers)&&o["Content-Type"]||((r=this.requestSettings).headers??(r.headers={}),(a=this.requestSettings.headers)["Content-Type"]??(a["Content-Type"]="application/json"),u=!0),this._isStream?A.requestStream(this,c,t,n.onOpen,n.onClose,n.abortStream):A.request(this,c,t,i.onFinish),u&&(null==(l=this.requestSettings.headers)||delete l["Content-Type"])}callApiWithFiles(t,e,i,n,s){const o=ie.createCustomFormDataBody(t,n,s),r=this.requestSettings,a=this.getServiceIOByType(s[0]);this.requestSettings=(null==a?void 0:a.request)||this.requestSettings,A.request(this,o,e,i.onFinish,!1),this.requestSettings=r}callAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=S.processMessages(t,e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.websocket){const t={messages:s,...this.rawBody};T.sendWebsocket(this.websocket,this,t,e,i.onFinish,!1)}else t.files&&!this._directServiceRequiresFiles?this.callApiWithFiles(this.rawBody,e,i,s,t.files):this.callServiceAPI(e,s,i,n,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result}}class ne extends ie{constructor(t,e,i,n,s){var o;super(t,s),this.insertKeyPlaceholderText="API Key",this.getKeyLink="",Object.assign(this.rawBody,null==(o=t.request)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,n&&this.setApiKeyProperties(n),this.requestSettings=this.buildRequestSettings(this.key||"",t.request)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateConfigKey=t.validateKeyProperty)}buildRequestSettings(t,e){const i=e??{};return i.headers=this.buildHeadersFunc(t),i}keyAuthenticated(t,e){this.requestSettings=this.buildRequestSettings(e,this.requestSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:n,handleVerificationResult:s,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);A.verifyKey(t,i,a,n,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,s,r)}}class se{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?se.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,se.waitForPropertiesToBeUpdatedBeforeRender(t))}}const oe=class extends HTMLElement{constructor(){super(),this._waitingToRender_=!1,this._propUpdated_=!1,Object.keys(oe._attributeToProperty_).forEach((t=>{this.constructPropertyAccessors(oe._attributeToProperty_[t])}))}static get observedAttributes(){return Object.keys(oe._attributes_)||[]}constructPropertyAccessors(t){let e;Object.defineProperty(this,t,{get:function(){return e},set:function(t){e=t,se.attemptRender(this)}})}attributeChangedCallback(t,e,i){if(console.log(i),console.log(typeof i),e===i)return;const n=oe._attributes_[t](i);this[oe._attributeToProperty_[t]]=n}onRender(){}};let re=oe;re._attributes_={},re._attributeToProperty_={};class ae{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const le=class{static changeVisibility(t,e,i,n){n.target.id===le.VISIBLE_ICON_ID?(e.style.display="none",i.style.display="block",t.type="password"):(e.style.display="block",i.style.display="none",t.type="text")}static createIconElement(t,e){const i=ae.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(t){const e=document.createElement("div");e.id="visibility-icon-container";const i=le.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n',le.VISIBLE_ICON_ID);i.style.display="none",e.appendChild(i);const n=le.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',"not-visible-icon");return e.appendChild(n),e.onclick=le.changeVisibility.bind(this,t,i,n),e}};let ce=le;ce.VISIBLE_ICON_ID="visible-icon";class ue{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t){const e=document.createElement("div");e.id="insert-key-help-text-container";const i=document.createElement("div");i.id="insert-key-help-text-contents";const n=ue.createFailText();if(i.appendChild(n),t){const e=ue.createHelpLink(t);i.appendChild(e)}const s=ue.createCautionText();return i.appendChild(s),e.appendChild(i),{helpTextContainerElement:e,failTextElement:n}}static onFail(t,e,i,n){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=n,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-ring"></div>'}static verifyKey(t,e,i){const n=t.value.trim();i.verifyKey(n,e)}static addVerificationEvents(t,e,i,s,o){const r={onSuccess:s,onFail:ue.onFail.bind(this,t,e,i),onLoad:ue.onLoad.bind(this,t,e)},a=ue.verifyKey.bind(this,t,r,o);e.onclick=a,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===n.ENTER&&a()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=ue.onInputFocus,e.appendChild(i),e}static createContents(t,e){const i=document.createElement("div");i.id="insert-key-contents";const n=ue.createInput(e.insertKeyPlaceholderText),s=n.children[0],o=ce.create(s);n.appendChild(o),i.appendChild(n);const r=ue.createStartButton(),{helpTextContainerElement:a,failTextElement:l}=ue.createHelpTextContainer(e.getKeyLink);return i.appendChild(r),i.appendChild(a),ue.addVerificationEvents(s,r,l,t,e),i}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const n=ue.createContents(t,e);return i.appendChild(n),i}static render(t,e,i){const n=ue.createElements(e,i);t.replaceChildren(n)}}class he{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;Array.isArray(s.error)&&"Error in `parameters`: field required"===s.error[0]?i(e):n(w)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:he.handleVerificationResult}}}const de=class extends ne{constructor(t,e,i,n,s,o){super(t,he.buildKeyVerificationDetails(),he.buildHeaders,s,o),this.insertKeyPlaceholderText="Hugging Face Token",this.getKeyLink="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${de.URL_PREFIX}${i}`,this.textInputPlaceholderText=e,"object"==typeof n&&(n.model&&(this.url=`${de.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return n.options??(n.options={}),n.options.wait_for_model=!0,{inputs:s,...n}}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");const o=this.preprocessBody(this.rawBody,e,s);A.request(this,o,t,i.onFinish)}};let pe=de;pe.URL_PREFIX="https://api-inference.huggingface.co/models/";class me extends pe{constructor(t,e,i,n,s,o){super(t,e,i,n,s,o),this.isTextInputDisabled=!0,this.canSendMessage=me.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");A.poll(this,s[0],t,i.onFinish,!1)}}class fe extends me{constructor(t){var e,i,n;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(n=t.directConnection)?void 0:n.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class ve extends me{constructor(t){var e,i,n;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(n=t.directConnection)?void 0:n.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const ge="data:image/png;base64,";class be{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){t.message?n(w):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:be.handleVerificationResult}}}class we extends ne{constructor(t,e,i,n,s){super(t,e,i,n,s),this.insertKeyPlaceholderText="Stability AI API Key",this.getKeyLink="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class ye extends we{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,be.buildKeyVerificationDetails(),be.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/upscale`),ye.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=ye.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s)throw new Error("Image was not found");const o=this.createFormDataBody(this.rawBody,s[0]);M.temporarilyRemoveHeader(this.requestSettings,A.request.bind(this,this,o,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ge}${t.base64}`,type:"image"})))}}}class xe extends we{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,be.buildKeyVerificationDetails(),be.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/masking`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),void 0!==s.mask_source&&null!==s.mask_source&&(this._maskSource=s.mask_source),xe.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=xe.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,n){const s=new FormData;return s.append("init_image",e),s.append("mask_source",String(this._maskSource)),s.append("mask_image",i),n&&""!==n&&s.append("text_prompts[0][text]",n),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}callServiceAPI(t,e,i,n,s){var o,r;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s||!s[0]||!s[1])throw new Error("Image was not found");const a=null==(r=null==(o=e[e.length-1])?void 0:o.text)?void 0:r.trim(),l=this.createFormDataBody(this.rawBody,s[0],s[1],a);M.temporarilyRemoveHeader(this.requestSettings,A.request.bind(this,this,l,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ge}${t.base64}`,type:"image"})))}}}class Me extends me{constructor(t){var e,i,n;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(n=t.directConnection)?void 0:n.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class ke extends pe{constructor(t){var e,i,n;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].generated_text||""}}}class je extends pe{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",s,null==(n=t.directConnection)?void 0:n.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=s.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class Ae extends pe{constructor(t){var e,i,n;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].summary_text||""}}}class Se extends pe{constructor(t){var e,i,n;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(n=t.directConnection)?void 0:n.huggingFace),void 0===this.maxMessages&&(this.maxMessages=-1)}processMessages(t){const e=t[t.length-1].text,i=t.slice(0,t.length-1);if(!e)return;return{past_user_inputs:i.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:i.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:e}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.processMessages(e);if(n)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:n.past_user_inputs,generated_responses:n.generated_responses,text:n.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class Te extends we{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,be.buildKeyVerificationDetails(),be.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI - Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Te.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Te.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const n=new FormData;return n.append("init_image",e),i&&""!==i&&n.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}callServiceAPI(t,e,i,n,s){var o,r;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s)throw new Error("Image was not found");const a=null==(r=null==(o=e[e.length-1])?void 0:o.text)?void 0:r.trim(),l=this.createFormDataBody(this.rawBody,s[0],a);M.temporarilyRemoveHeader(this.requestSettings,A.request.bind(this,this,l,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ge}${t.base64}`,type:"image"})))}}}class ze extends pe{constructor(t){var e,i,n;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].translation_text||""}}}class Oe extends we{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,be.buildKeyVerificationDetails(),be.buildHeaders,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI - Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.textToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Oe.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Oe.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n={text:e};return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e[e.length-1].text);A.request(this,s,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ge}${t.base64}`,type:"image"})))}}}class Ce extends pe{constructor(t){var e,i,n;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(n=t.directConnection)?void 0:n.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].sequence||""}}}class Le{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,n){"invalid request: prompt must be at least 1 token long"===t.message?i(e):n(w)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:Le.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Ie extends ne{constructor(t,e,i,n,s){super(t,Le.buildKeyVerificationDetails(),Le.buildHeaders,s),this.insertKeyPlaceholderText="Cohere API Key",this.getKeyLink="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,n&&"object"==typeof n&&Object.assign(this.rawBody,n)}}class Ne extends Ie{constructor(t){var e,i,n;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{prompt:n,...i}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);A.request(this,n,t,i.onFinish)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}class Ee extends Ie{constructor(t){var e,i,n;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{text:n,...i}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);A.request(this,n,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}class De{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,n){t.error?n(w):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:De.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,n){var s;"401"===(null==(s=t.error)?void 0:s.code)?n(w):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:De.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,n){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):n(w)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>De.buildTranslationHeaders(t,e),handleVerificationResult:De.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class _e extends ne{constructor(t,e,i,n,s){super(t,De.buildLanguageKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class Pe extends _e{constructor(t){var e,i,n,s;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(n=t.directConnection)?void 0:n.azure;super(t,De.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(s=this.rawBody).language??(s.language="en"),Object.assign(this.rawBody,o),this.url=`${o.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);A.request(this,n,t,i.onFinish),this.messages=t,this.completionsHandlers=i}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),n={method:"GET",headers:null==(e=this.requestSettings)?void 0:e.headers};A.executePollRequest(this,i,n,this.messages,this.completionsHandlers.onFinish)}return{pollingInAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}}const Re=class{static generateDefaultBody(t){return{model:t}}static build(t,e){const i=Re.generateDefaultBody(t);return e&&"boolean"!=typeof e?Object.assign(i,e):i}};let Fe=Re;Fe.GPT_COMPLETIONS_DAVINCI_MODEL="text-davinci-003",Fe.GPT_CHAT_TURBO_MODEL="gpt-3.5-turbo";const Be=class{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(w):n(y):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:Be.handleVerificationResult}}};let qe=Be;qe.CONVERSE_MAX_CHAR_LENGTH=13352,qe.FILE_MAX_CHAR_LENGTH=1e3;class Ye extends ne{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,qe.buildKeyVerificationDetails(),qe.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/completions",this.permittedErrorPrefixes=["Incorrect"],this._maxCharLength=qe.CONVERSE_MAX_CHAR_LENGTH,this.full_transaction_max_tokens=4e3,this.numberOfCharsPerToken=3.5;const r=null==(e=null==n?void 0:n.openAI)?void 0:e.completions;null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit),"object"==typeof r&&Object.assign(this.rawBody,r),(i=this.rawBody).model??(i.model=Fe.GPT_COMPLETIONS_DAVINCI_MODEL)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(!n)return;const s=n.substring(0,this._maxCharLength),o=i.max_tokens||this.full_transaction_max_tokens-s.length/this.numberOfCharsPerToken;return{prompt:s,max_tokens:Math.floor(o),...i}}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e);this._isStream||s.stream?(s.stream=!0,A.requestStream(this,s,t,n.onOpen,n.onClose,n.abortStream)):A.request(this,s,t,i.onFinish)}async extractResultData(t){var e;if(t.error)throw t.error.message;return{text:(null==(e=t.choices[0])?void 0:e.text)||""}}}class Ue{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},n=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let s;for(;!s;){const t=await(await fetch(n,{headers:i})).json();if("completed"===t.status)s=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return s}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(w):n(y):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:Ue.handleVerificationResult}}}class Ze extends ne{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Ue.buildKeyVerificationDetails(),Ue.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.getKeyLink="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=Ze.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");A.request(this,s[0],t,i.onFinish,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const n=null==(i=null==(e=this.requestSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await Ue.poll(n,t.upload_url)).text}}}class Je extends ne{constructor(t,e,i,n,s){super(t,De.buildSpeechKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const Ve=class extends Je{constructor(t){var e,i,n,s,o,r;const a=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.textToSpeech,l=null==(n=t.directConnection)?void 0:n.azure;super(t,De.buildTextToSpeechHeaders.bind({},(null==a?void 0:a.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),a.region,l),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${Ve.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",Object.assign(this.rawBody,a),(s=this.rawBody).lang??(s.lang="en-US"),(o=this.rawBody).name??(o.name="en-US-JennyNeural"),(r=this.rawBody).gender??(r.gender="Female"),this.url=`https://${a.region}.tts.speech.microsoft.com/cognitiveservices/v1`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);A.request(this,n,t,i.onFinish,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};let $e=Ve;$e.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";const He=class extends Je{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.speechToText,o=null==(n=t.directConnection)?void 0:n.azure;super(t,De.buildSpeechToTextHeaders,s.region,o,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${He.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.canSendMessage=He.canFileSendMessage;const r=s.lang||"en-US";this.url=`https://${s.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${r}&format=detailed`,this.recordAudio=void 0}static canFileSendMessage(t,e){return!(null==e||!e[0])}callServiceAPI(t,e,i,n,s){var o,r;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");null!=(r=this.requestSettings)&&r.headers&&(this.requestSettings.headers["Content-Type"]=s[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),A.request(this,s[0],t,i.onFinish,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};let Ge=He;Ge.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";class Ke extends ne{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(n=t.directConnection)?void 0:n.azure;super(t,De.buildTranslationKeyVerificationDetails(s.region),De.buildTranslationHeaders.bind({},null==s?void 0:s.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${s.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(e);A.request(this,n,t,i.onFinish)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}const Qe=class extends ne{constructor(t){var e;const{directConnection:i,textInput:n}=t,s=null==i?void 0:i.openAI;super(t,qe.buildKeyVerificationDetails(),qe.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI Images</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"],this._maxCharLength=qe.FILE_MAX_CHAR_LENGTH,null!=n&&n.characterLimit&&(this._maxCharLength=n.characterLimit);const o=null==(e=null==i?void 0:i.openAI)?void 0:e.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=Qe.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const n=new FormData;return n.append("image",e),i&&n.append("mask",i),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),n}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));if(e&&""!==e){const t=e.substring(0,this._maxCharLength);i.prompt=t}return i}callApiWithImage(t,e,i,n){var s,o;let r;const a=null==(o=null==(s=e[e.length-1])?void 0:s.text)?void 0:o.trim();if(n[1]||a&&""!==a){this.url=Qe.IMAGE_EDIT_URL;const t=this.preprocessBody(this.rawBody,a);r=Qe.createFormDataBody(t,n[0],n[1])}else this.url=Qe.IMAGE_VARIATIONS_URL,r=Qe.createFormDataBody(this.rawBody,n[0]);M.temporarilyRemoveHeader(this.requestSettings,A.request.bind(this,this,r,t,i.onFinish),!1)}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(t,e,i,s);else{if(!this.requestSettings)throw new Error("Request settings have not been set up");this.url=Qe.IMAGE_GENERATION_URL;const n=this.preprocessBody(this.rawBody,e[e.length-1].text);A.request(this,n,t,i.onFinish)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${ge}${t.b64_json}`,type:"image"}))}}};let We=Qe;We.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",We.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",We.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";const Xe=class extends ne{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,qe.buildKeyVerificationDetails(),qe.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/api-reference/audio/create">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this._maxCharLength=qe.FILE_MAX_CHAR_LENGTH,this._service_url=Xe.AUDIO_TRANSCRIPTIONS_URL,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const r=null==(e=null==n?void 0:n.openAI)?void 0:e.audio;"object"==typeof r&&(this.processConfig(r),Xe.cleanConfig(r),Object.assign(this.rawBody,r)),(i=this.rawBody).model??(i.model=Xe.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=Xe.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(t){null!=t&&t.type&&"translation"===t.type&&(this._service_url=Xe.AUDIO_TRANSLATIONS_URL,delete t.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e,i){var n,s;const o=JSON.parse(JSON.stringify(t)),r=null==(s=null==(n=e[e.length-i.length+1])?void 0:n.text)?void 0:s.trim();if(r&&""!==r){const t=r.substring(0,this._maxCharLength);o.prompt=t}return o}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.requestSettings.url||this._service_url;const r=this.preprocessBody(this.rawBody,e,s),a=Xe.createFormDataBody(r,s[0]);M.temporarilyRemoveHeader(this.requestSettings,A.request.bind(this,this,a,t,i.onFinish),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};let ti=Xe;ti.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",ti.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",ti.DEFAULT_MODEL="whisper-1";class ei extends ne{constructor(t){var e,i,n,s;const o=null==(e=t.directConnection)?void 0:e.openAI;super(t,qe.buildKeyVerificationDetails(),qe.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this._systemMessage=ei.generateSystemMessage("You are a helpful assistant.");const r=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.chat;"object"==typeof r&&(r.systemPrompt&&(this._systemMessage=ei.generateSystemMessage(r.systemPrompt)),this.cleanConfig(r),Object.assign(this.rawBody,r)),void 0===this.maxMessages&&(this.maxMessages=-1),(s=this.rawBody).model??(s.model=Fe.GPT_CHAT_TURBO_MODEL)}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.systemPrompt}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.totalMessagesMaxCharLength||qe.CONVERSE_MAX_CHAR_LENGTH,s=S.getCharacterLimitMessages(e,n-this._systemMessage.content.length).map((t=>({content:t.text,role:"ai"===t.role?"assistant":"user"})));return i.messages=[this._systemMessage,...s],i}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e);this._isStream||s.stream?(s.stream=!0,A.requestStream(this,s,t,n.onOpen,n.onClose,n.abortStream)):A.request(this,s,t,i.onFinish)}async extractResultData(t){if(t.error)throw t.error.message;return t.choices[0].delta?{text:t.choices[0].delta.content||""}:t.choices[0].message?{text:t.choices[0].message.content}:{text:""}}}class ii extends Ie{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,null==(n=t.directConnection)?void 0:n.cohere),this.username="USER","object"==typeof s&&(s.user_name&&(this.username=s.user_name),this.cleanConfig(s),Object.assign(this.rawBody,s)),void 0===this.maxMessages&&(this.maxMessages=-1)}cleanConfig(t){delete t.user_name}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return i.query=e[e.length-1].text,i.chat_history=e.slice(0,e.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":this.username}))),i}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);A.request(this,n,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class ni{static create(t){const{directConnection:e}=t;if(e){if(e.openAI)return e.openAI.images?new We(t):e.openAI.audio?new ti(t):e.openAI.completions?new Ye(t):new ei(t);if(e.assemblyAI)return new Ze(t);if(e.cohere)return e.cohere.chat?new ii(t):e.cohere.summarization?new Ee(t):new Ne(t);if(e.huggingFace)return e.huggingFace.textGeneration?new ke(t):e.huggingFace.summarization?new Ae(t):e.huggingFace.translation?new ze(t):e.huggingFace.fillMask?new Ce(t):e.huggingFace.questionAnswer?new je(t):e.huggingFace.audioSpeechRecognition?new Me(t):e.huggingFace.audioClassification?new fe(t):e.huggingFace.imageClassification?new ve(t):new Se(t);if(e.azure){if(e.azure.speechToText)return new Ge(t);if(e.azure.textToSpeech)return new $e(t);if(e.azure.summarization)return new Pe(t);if(e.azure.translation)return new Ke(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new Te(t):e.stabilityAI.imageToImageUpscale?new ye(t):e.stabilityAI.imageToImageMasking?new xe(t):new Oe(t);if(e.demo)return new ie(t,void 0,e.demo)}return new ie(t)}}const si=class{static appendStyleSheetToHead(){const t=document.getElementsByTagName("head")[0];if(!Array.from(t.getElementsByTagName("link")).some((t=>t.getAttribute("href")===si.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=si.FONT_URL,t.appendChild(e)}}};let oi=si;function ri(t){return function(e,i){console.log(t),console.log(e),console.log(i),console.log("-------")}}oi.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap";class ai{static onNewMessage(t,e,i){const n=JSON.parse(JSON.stringify({message:e,isInitial:i}));t.onNewMessage(n),t.dispatchEvent(new CustomEvent("new-message",{detail:n}))}static onRender(t){t.onComponentRender(),t.dispatchEvent(new CustomEvent("render"))}}const li=class{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(t){const e=t.scrollHeight,i=t.clientHeight;return t.scrollTop>=e-i-li.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}};let ci=li;ci.CODE_SNIPPET_GENERATION_JUMP=.5;const ui=class{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(t,e){const i={};setTimeout((()=>{if("object"==typeof t&&(t.lang&&(i.lang=t.lang),t.pitch&&(i.pitch=t.pitch),t.rate&&(i.rate=t.rate),t.volume&&(i.volume=t.volume),t.voiceName)){const e=window.speechSynthesis.getVoices().find((e=>{var i;return e.name.toLocaleLowerCase()===(null==(i=t.voiceName)?void 0:i.toLocaleLowerCase())}));e&&(i.voice=e)}e(i)}),ui.LOAD_VOICES_MS)}};let hi=ui;hi.LOAD_VOICES_MS=200;class di{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static set(t,e){var i,n,s,o;if(null!=(n=null==(i=null==e?void 0:e.loading)?void 0:i.bubble)&&n.color){const i=di.colorToHex(null==(o=null==(s=null==e?void 0:e.loading)?void 0:s.bubble)?void 0:o.color);t.style.setProperty("--message-dots-color",i),t.style.setProperty("--message-dots-color-fade",`${i}33`)}else t.style.setProperty("--message-dots-color","#848484"),t.style.setProperty("--message-dots-color-fade","#55555533")}}class pi{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],n="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(n.style,i.media)}}static applySideStyles(t,e,i,n){n&&(pi.applyCustomStylesToElements(t,i,n.shared),e?pi.applyCustomStylesToElements(t,i,n.ai):pi.applyCustomStylesToElements(t,i,n.user))}static isMessageSideStyles(t){return!!(t.ai||t.shared||t.user)}static applyCustomStyles(t,e,i,n,s){var o;s&&t.default!==s?pi.isMessageSideStyles(s)?(pi.applySideStyles(e,i,n,t.default),pi.applySideStyles(e,i,n,s)):(pi.applyCustomStylesToElements(e,n,null==(o=t.default)?void 0:o.shared),pi.applyCustomStylesToElements(e,n,s)):pi.applySideStyles(e,i,n,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,n={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,s,o,r;n.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",n.innerContainer[t]=(null==(s=i.innerContainer)?void 0:s[t])||"",n.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",n.media[t]=(null==(r=i.media)?void 0:r[t])||""})),n}}class mi{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=mi.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=mi.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}}const fi=class{static updateMessages(t,e,i,n,s,o=!1){var r;t.applyCustomStyles(e,s,!0,null==(r=t.messageStyles)?void 0:r[n]),t.elementRef.scrollTop=t.elementRef.scrollHeight;const a=yi.createMessageContent(s,void 0,i);t.messages.push(a),t.sendClientUpdate(a,o)}static wrapInLink(t,e){const i=document.createElement("a");return i.href=e,i.target="_blank",i.appendChild(t),i}static processContent(t,e){return!e||e.startsWith("data")?t:fi.wrapInLink(t,e)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(t,e){if(t.startsWith("data"))fi.waitToLoadThenScroll(e);else try{fetch(t,{mode:"no-cors"}).catch((()=>{})).finally((()=>{fi.waitToLoadThenScroll(e)}))}catch{e.scrollTop=e.scrollHeight}}};let vi=fi;vi.DEFAULT_FILE_NAME="file";class gi{static createImage(t,e){const i=new Image;return i.src=t.src,vi.scrollDownOnImageLoad(i.src,e),vi.processContent(i,i.src)}static async addNewImageMessage(t,e,i,n=!1){const s=gi.createImage(e,t.elementRef),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(s),o.bubbleElement.classList.add("image-message"),t.elementRef.appendChild(o.outerContainer),vi.updateMessages(t,o,e,"image",i,n)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,o.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e?"audio-player-safari-left":"audio-player-safari-right")),i}static addNewAudioMessage(t,e,i,n=!1){const s=gi.createAudioElement(e,i),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(s),o.bubbleElement.classList.add("audio-message"),t.elementRef.appendChild(o.outerContainer),vi.updateMessages(t,o,e,"audio",i,n)}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const n=ae.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>');n.classList.add("any-file-message-icon"),i.appendChild(n);const s=document.createElement("div");return s.classList.add("any-file-message-text"),s.textContent=t.name||vi.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(s),vi.processContent(e,t.src)}static addNewAnyFileMessage(t,e,i,n=!1){const s=t.createNewMessageElement("",i),o=gi.createAnyFile(e);s.bubbleElement.classList.add("any-file-message-bubble"),s.bubbleElement.appendChild(o),t.elementRef.appendChild(s.outerContainer),vi.updateMessages(t,s,e,"file",i,n)}}class bi{static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(t,e,i,n){var s,o,r;null!=(s=i.default)&&s.styles&&bi.applyCustomStylesToElements(t,e,i.default.styles),n?null!=(o=i.ai)&&o.styles&&bi.applyCustomStylesToElements(t,e,i.ai.styles):null!=(r=i.user)&&r.styles&&bi.applyCustomStylesToElements(t,e,i.user.styles)}static createAvatar(t,e){var i,n,s,o;const r=document.createElement("img");r.src=t?(null==(i=null==e?void 0:e.ai)?void 0:i.src)||(null==(n=null==e?void 0:e.default)?void 0:n.src)||"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8c3ZnIGZpbGw9IiMwMDAwMDAiIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIAoJCXZpZXdCb3g9IjAgMCAzMiAzMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8cGF0aCBkPSJNMjMsMzAuMzZIOWMtMi40MDQsMC00LjM2LTEuOTU2LTQuMzYtNC4zNlYxNWMwLTIuNDA0LDEuOTU2LTQuMzYsNC4zNi00LjM2aDMuNjU5CgkJYzAuMTY3LTEuNTY2LDEuNDE1LTIuODEzLDIuOTgxLTIuOTgxVjUuMzMzYy0xLjEzMS0wLjE3NC0yLTEuMTU0LTItMi4zMzNjMC0xLjMwMSwxLjA1OS0yLjM2LDIuMzYtMi4zNgoJCWMxLjMwMiwwLDIuMzYsMS4wNTksMi4zNiwyLjM2YzAsMS4xNzktMC44NjksMi4xNTktMiwyLjMzM1Y3LjY2YzEuNTY2LDAuMTY3LDIuODE0LDEuNDE1LDIuOTgxLDIuOTgxSDIzCgkJYzIuNDA0LDAsNC4zNiwxLjk1Niw0LjM2LDQuMzZ2MTFDMjcuMzYsMjguNDA0LDI1LjQwNCwzMC4zNiwyMywzMC4zNnogTTksMTEuMzZjLTIuMDA3LDAtMy42NCwxLjYzMy0zLjY0LDMuNjR2MTEKCQljMCwyLjAwNywxLjYzMywzLjY0LDMuNjQsMy42NGgxNGMyLjAwNywwLDMuNjQtMS42MzMsMy42NC0zLjY0VjE1YzAtMi4wMDctMS42MzMtMy42NC0zLjY0LTMuNjRIOXogTTEzLjM4NCwxMC42NGg1LjIzMQoJCUMxOC40MzksOS4zNTQsMTcuMzM0LDguMzYsMTYsOC4zNkMxNC42NjcsOC4zNiwxMy41NjEsOS4zNTQsMTMuMzg0LDEwLjY0eiBNMTYsMS4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NAoJCVMxNS4wOTYsNC42NCwxNiw0LjY0YzAuOTA0LDAsMS42NC0wLjczNiwxLjY0LTEuNjRTMTYuOTA0LDEuMzYsMTYsMS4zNnogTTIwLDI3LjM2aC04Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2CgkJczEuMDU5LTIuMzYsMi4zNi0yLjM2aDhjMS4zMDIsMCwyLjM2LDEuMDU5LDIuMzYsMi4zNlMyMS4zMDIsMjcuMzYsMjAsMjcuMzZ6IE0xMiwyMy4zNmMtMC45MDQsMC0xLjY0LDAuNzM1LTEuNjQsMS42NAoJCXMwLjczNiwxLjY0LDEuNjQsMS42NGg4YzAuOTA0LDAsMS42NC0wLjczNSwxLjY0LTEuNjRzLTAuNzM1LTEuNjQtMS42NC0xLjY0SDEyeiBNMzEsMjMuODZoLTJjLTAuMTk5LDAtMC4zNi0wLjE2MS0wLjM2LTAuMzZWMTUKCQljMC0wLjE5OSwwLjE2MS0wLjM2LDAuMzYtMC4zNmgyYzAuMTk5LDAsMC4zNiwwLjE2MSwwLjM2LDAuMzZ2OC41QzMxLjM2LDIzLjY5OSwzMS4xOTksMjMuODYsMzEsMjMuODZ6IE0yOS4zNiwyMy4xNGgxLjI3OXYtNy43OAoJCUgyOS4zNlYyMy4xNHogTTMsMjMuODZIMWMtMC4xOTksMC0wLjM2LTAuMTYxLTAuMzYtMC4zNlYxNWMwLTAuMTk5LDAuMTYxLTAuMzYsMC4zNi0wLjM2aDJjMC4xOTksMCwwLjM2LDAuMTYxLDAuMzYsMC4zNnY4LjUKCQlDMy4zNiwyMy42OTksMy4xOTksMjMuODYsMywyMy44NnogTTEuMzYsMjMuMTRoMS4yOHYtNy43OEgxLjM2VjIzLjE0eiBNMjAsMjAuMzZjLTEuMzAyLDAtMi4zNi0xLjA1OS0yLjM2LTIuMzYKCQlzMS4wNTktMi4zNiwyLjM2LTIuMzZzMi4zNiwxLjA1OSwyLjM2LDIuMzZDMjIuMzYsMTkuMzAyLDIxLjMwMiwyMC4zNiwyMCwyMC4zNnogTTIwLDE2LjM2Yy0wLjkwNCwwLTEuNjQsMC43MzYtMS42NCwxLjY0CgkJczAuNzM1LDEuNjQsMS42NCwxLjY0czEuNjQtMC43MzUsMS42NC0xLjY0UzIwLjkwNCwxNi4zNiwyMCwxNi4zNnogTTEyLDIwLjM2Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2czEuMDU5LTIuMzYsMi4zNi0yLjM2CgkJczIuMzYsMS4wNTksMi4zNiwyLjM2QzE0LjM2LDE5LjMwMiwxMy4zMDEsMjAuMzYsMTIsMjAuMzZ6IE0xMiwxNi4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NHMwLjczNiwxLjY0LDEuNjQsMS42NAoJCXMxLjY0LTAuNzM1LDEuNjQtMS42NFMxMi45MDQsMTYuMzYsMTIsMTYuMzZ6Ii8+Cgk8cmVjdCBzdHlsZT0iZmlsbDpub25lOyIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIi8+Cjwvc3ZnPg==":(null==(s=null==e?void 0:e.user)?void 0:s.src)||(null==(o=null==e?void 0:e.default)?void 0:o.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==",r.classList.add("avatar");const a=document.createElement("div");return a.classList.add("avatar-container"),a.appendChild(r),e&&bi.applyCustomStyles(a,r,e,t),a}static getPosition(t,e){var i,n,s,o,r,a;let l=t?null==(n=null==(i=null==e?void 0:e.ai)?void 0:i.styles)?void 0:n.position:null==(o=null==(s=null==e?void 0:e.user)?void 0:s.styles)?void 0:o.position;return l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t?"left":"right"),l}static add(t,e,i){const n="boolean"==typeof i?void 0:i,s=bi.createAvatar(e,n),o=bi.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class wi{static getPosition(t,e){var i,n,s;let o=t?null==(i=null==e?void 0:e.ai)?void 0:i.position:null==(n=null==e?void 0:e.user)?void 0:n.position;return o||(o=null==(s=null==e?void 0:e.default)?void 0:s.position),o||(o=t?"left":"right"),o}static applyStyle(t,e,i){var n,s,o;Object.assign(t.style,null==(n=i.default)?void 0:n.style,e?null==(s=i.ai)?void 0:s.style:null==(o=i.user)?void 0:o.style)}static getNameText(t,e){var i,n,s,o;return t?(null==(i=e.ai)?void 0:i.text)||(null==(n=e.default)?void 0:n.text)||"AI":(null==(s=e.user)?void 0:s.text)||(null==(o=e.default)?void 0:o.text)||"User"}static createName(t,e){const i=document.createElement("div");return i.classList.add("name"),i.textContent=wi.getNameText(t,e),wi.applyStyle(i,t,e),i}static add(t,e,i){const n="boolean"==typeof i?{}:i,s=wi.createName(e,n),o=wi.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class yi{constructor(t,e,i){var n,s;this._messageElementRefs=[],this._streamedText="",this.messages=[];const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._remarkable=te.createNew(),this.elementRef=yi.createContainerElement(),this.messageStyles=t.messageStyles,this._avatars=t.avatars,this._names=t.names,this._errorMessageOverrides=null==(n=t.errorMessages)?void 0:n.overrides,this._onNewMessage=ai.onNewMessage.bind(this,t),this._displayLoadingMessage=yi.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.populateIntroPanel(i,r,t.introPanelStyle),t.introMessage&&this.addIntroductoryMessage(t.introMessage),t.initialMessages&&this.populateInitialMessages(t.initialMessages),this.displayServiceErrorMessages=null==(s=t.errorMessages)?void 0:s.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.refreshMessages=this.refreshTextMessages.bind(this),a&&this.prepareDemo(a),t.textToSpeech&&hi.processConfig(t.textToSpeech,(t=>{this._textToSpeech=t}))}static getDisplayLoadingMessage(t,e){return!e.websocket&&(t.displayLoadingBubble??!0)}prepareDemo(t){"object"==typeof t&&(t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),t.displayLoadingBubble&&this.addLoadingMessage())}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addIntroductoryMessage(t){var e;const i=this.createAndAppendNewMessageElement(t,!0);this.applyCustomStyles(i,!0,!1,null==(e=this.messageStyles)?void 0:e.intro)}populateInitialMessages(t){t.forEach((t=>{t.text?this.addNewMessage({text:t.text},"ai"===t.role,!0,!0):t.file&&this.addNewMessage({files:[t.file]},"ai"===t.role,!0,!0)})),setTimeout((()=>this.elementRef.scrollTop=this.elementRef.scrollHeight))}applyCustomStyles(t,e,i,n){this.messageStyles&&pi.applyCustomStyles(this.messageStyles,t,e,i,n)}addInnerContainerElements(t,e,i){return t.classList.add("message-bubble",i?"ai-message-text":"user-message-text"),t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e),this._avatars&&bi.add(t,i,this._avatars),this._names&&wi.add(t,i,this._names),{bubbleElement:t}}static createMessageContent(t,e,i){return i?{role:t?"ai":"user",file:i}:{role:t?"ai":"user",text:e||""}}static createBaseElements(){const t=document.createElement("div"),e=document.createElement("div");e.classList.add("inner-message-container"),t.appendChild(e),t.classList.add("outer-message-container");const i=document.createElement("div");return i.classList.add("message-bubble"),e.appendChild(i),{outerContainer:t,innerContainer:e,bubbleElement:i}}createMessageElements(t,e){const i=yi.createBaseElements(),{outerContainer:n,innerContainer:s,bubbleElement:o}=i;return n.appendChild(s),this.addInnerContainerElements(o,t,e),this._messageElementRefs.push(i),i}createNewMessageElement(t,e){var i;null==(i=this._introPanel)||i.hide();const n=this._messageElementRefs[this._messageElementRefs.length-1];return null!=n&&n.bubbleElement.classList.contains("loading-message-text")&&(n.outerContainer.remove(),this._messageElementRefs.pop()),this.createMessageElements(t,e)}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),this.elementRef.scrollTop=this.elementRef.scrollHeight,i}static editEmptyMessageElement(t){t.textContent=".",t.style.color="#00000000"}addNewTextMessage(t,e,i,n=!1){const s=this.createAndAppendNewMessageElement(t,e);this.applyCustomStyles(s,e,!1);const o=yi.createMessageContent(e,t);return 0===t.trim().length&&yi.editEmptyMessageElement(s.bubbleElement),this.messages.push(o),i&&this.sendClientUpdate(o,n),s}addNewMessage(t,e,i,n=!1){void 0!==t.text&&null!==t.text?(this.addNewTextMessage(t.text,e,i,n),!n&&this._textToSpeech&&e&&hi.speak(t.text,this._textToSpeech)):t.files&&t.files.forEach((t=>{var i,s;"audio"===t.type||null!=(i=t.src)&&i.startsWith("data:audio")?gi.addNewAudioMessage(this,t,e,n):"image"===t.type||"gif"===t.type||null!=(s=t.src)&&s.startsWith("data:image")?gi.addNewImageMessage(this,t,e,n):gi.addNewAnyFileMessage(this,t,e,n)}))}sendClientUpdate(t,e=!1){var i;null==(i=this._onNewMessage)||i.call(this,t,e)}removeMessageOnError(){var t;const e=null==(t=this._messageElementRefs[this._messageElementRefs.length-1])?void 0:t.bubbleElement;(null!=e&&e.classList.contains("streamed-message")&&""===e.textContent||null!=e&&e.classList.contains("loading-message-text"))&&(e.remove(),this._messageElementRefs.pop())}addNewErrorMessage(t,e){var i,n,s,o;this.removeMessageOnError();const r=yi.createBaseElements(),{outerContainer:a,bubbleElement:l}=r;l.classList.add("error-message-text");const c=this.getPermittedMessage(e)||(null==(i=this._errorMessageOverrides)?void 0:i[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.";l.innerHTML=c;const u=pi.extractParticularSharedStyles(["fontSize","fontFamily"],null==(s=this.messageStyles)?void 0:s.default);pi.applyCustomStylesToElements(r,!1,u),pi.applyCustomStylesToElements(r,!1,null==(o=this.messageStyles)?void 0:o.error),this.elementRef.appendChild(a),this.elementRef.scrollTop=this.elementRef.scrollHeight,this._textToSpeech&&hi.speak(c,this._textToSpeech),this._streamedText=""}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}getPermittedMessage(t){if(t){if(this.displayServiceErrorMessages)return t;if("string"==typeof t&&this._permittedErrorPrefixes){const e=yi.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t);if(e)return e}else if(Array.isArray(t)&&this._permittedErrorPrefixes)for(let e=0;e<t.length;e+=1){const i=yi.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t[e]);if(i)return i}}}isLastMessageError(){var t,e,i,n,s;return null==(s=null==(n=null==(i=null==(e=null==(t=this.elementRef.children[this.elementRef.children.length-1])?void 0:t.children)?void 0:e[0])?void 0:i.children)?void 0:n[0])?void 0:s.classList.contains("error-message-text")}addLoadingMessage(){var t;if(!this._displayLoadingMessage)return;const e=this.createMessageElements("",!0),{outerContainer:i,bubbleElement:n}=e;n.classList.add("loading-message-text");const s=document.createElement("div");s.classList.add("dots-flashing"),n.appendChild(s),this.applyCustomStyles(e,!0,!1,null==(t=this.messageStyles)?void 0:t.loading),di.set(n,this.messageStyles),this.elementRef.appendChild(i),this.elementRef.scrollTop=this.elementRef.scrollHeight}addNewStreamedMessage(){const{bubbleElement:t}=this.addNewTextMessage("",!0,!1);return t.classList.add("streamed-message"),this.elementRef.scrollTop=this.elementRef.scrollHeight,t}updateStreamedMessage(t,e){var i,n,s,o,r;const a=ci.isScrollbarAtBottomOfElement(this.elementRef);if(0!==t.trim().length){const t=null==(i=this.messageStyles)?void 0:i.default;e.style.color=(null==(s=null==(n=null==t?void 0:t.ai)?void 0:n.bubble)?void 0:s.color)||(null==(r=null==(o=null==t?void 0:t.shared)?void 0:o.bubble)?void 0:r.color)||""}this._streamedText+=t,e.innerHTML=this._remarkable.render(this._streamedText),a&&(this.elementRef.scrollTop=this.elementRef.scrollHeight)}finaliseStreamedMessage(){this.messages[this.messages.length-1].text=this._streamedText,this.sendClientUpdate(yi.createMessageContent(!0,this._streamedText),!1),this._textToSpeech&&hi.speak(this._streamedText,this._textToSpeech),this._streamedText=""}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new mi(t,e,i),this._introPanel._elementRef&&this.elementRef.appendChild(this._introPanel._elementRef))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{this.addNewMessage({files:[{src:i.result,type:t.type}]},!1,!0),e(!0)}}else{const i=t.file.name||vi.DEFAULT_FILE_NAME;this.addNewMessage({files:[{name:i,type:"any"}]},!1,!0),e(!0)}})))))}refreshTextMessages(){this._remarkable=te.createNew(),this.messages.forEach(((t,e)=>{t.text&&(this._messageElementRefs[e].bubbleElement.innerHTML=this._remarkable.render(t.text))}))}}const xi=class{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(t,e,i){0===i["outside-right"].length&&i["outside-left"].length>0?(t[0].classList.add(xi.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),e.classList.add(xi.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===i["outside-left"].length&&i["outside-right"].length>0&&(t[3].classList.add(xi.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),e.classList.add(xi.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(t,e,i){if(!(i["inside-left"].length>0||i["inside-right"].length>0)){if(0===i["outside-right"].length&&i["outside-left"].length>0)return t[0].classList.add(xi.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),e.classList.add(xi.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===i["outside-left"].length&&i["outside-right"].length>0)return t[3].classList.add(xi.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),e.classList.add(xi.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(t,e,i,n){!!xi.adjustOutsideSubmit(e,i,n)||xi.adjustForOutsideButton(e,i,n),xi.adjustInputPadding(t,n)}};let Mi=xi;Mi.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Mi.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Mi.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Mi.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";class ki{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const n=ki.getContainerIndex(i);t[n].appendChild(e),3===n&&e.classList.add("outside-right")}}const ji=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class Ai{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?Ai.createTextElement(t):ae.createSVGElement(t)}static createCustomElement(t,e){var i,n,s,o;const r=t[e];return null!=(i=null==r?void 0:r.text)&&i.content?Ai.createElement(null==(n=null==r?void 0:r.text)?void 0:n.content,!0):null!=(s=null==r?void 0:r.svg)&&s.content?Ai.createElement(null==(o=null==r?void 0:r.svg)?void 0:o.content,!1):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let n;return i&&(n=Ai.createCustomElement(i,e)),Ai.processElement(t,n),n}static create(t,e,i){const n={};if(!i)return Ai.processElement(t),n;const s=Ai.createSpecificStateElement(t,e[0],i);n[e[0]]=s;let o=s;return e.slice(1).forEach((t=>{o=Ai.createCustomElement(i,t)||o,n[t]=o})),n}}class Si{static unsetAllCSS(t,e){var i,n;e.container&&s.unsetAllCSSMouseStates(t,e.container),null!=(i=e.svg)&&i.styles&&s.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&s.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var i,n;e.container&&s.unsetActivityCSSMouseStates(t,e.container),null!=(i=e.svg)&&i.styles&&s.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&s.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var n,s,o,r,a;Object.assign(t.style,null==(n=e.container)?void 0:n[i]),Object.assign(t.children[0].style,null==(o=null==(s=e.svg)?void 0:s.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){Si.setElementsCSS(t,e,"default"),"default"!==i&&(Si.setElementsCSS(t,e,"hover"),"hover"!==i&&Si.setElementsCSS(t,e,"click"))}}class Ti{constructor(t,e,i,n){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=n}buttonMouseLeave(t){this._mouseState.state="default",t&&(Si.unsetAllCSS(this.elementRef,t),Si.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&Si.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&Si.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&Si.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],n=i&&this._customStyles[i];n&&Si.unsetActionCSS(this.elementRef,n)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&Si.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class zi{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];zi.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,n=!1){const s=n?t:t[i?"nextSibling":"previousSibling"];s?(t.dispatchEvent(new MouseEvent("mouseleave")),s.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),zi.focusItemWhenOnEdge(e,i))}}class Oi{static mouseUp(t,e){const i=e.target;s.unsetAllCSSMouseStates(i,t),Object.assign(i.style,t.default),Object.assign(i.style,t.hover)}static mouseDown(t,e){const i=e.target;Object.assign(i.style,t.click)}static mouseLeave(t,e){const i=e.target;s.unsetAllCSSMouseStates(i,t),Object.assign(i.style,t.default)}static mouseEnter(t,e){const i=e.target;Object.assign(i.style,t.hover)}static add(t,e){t.addEventListener("mouseenter",Oi.mouseEnter.bind(this,e)),t.addEventListener("mouseleave",Oi.mouseLeave.bind(this,e)),t.addEventListener("mousedown",Oi.mouseDown.bind(this,e)),t.addEventListener("mouseup",Oi.mouseUp.bind(this,e))}}class Ci{static addItemEvents(t,e,i,n){Oi.add(e,n),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(t,e,i,n){const s=t.children[0];s.classList.contains("text-button")?e.appendChild(Ci.createItemText(s.textContent,null==n?void 0:n.text)):(e.appendChild(Ci.createItemIcon(t,null==n?void 0:n.iconContainer)),e.appendChild(Ci.createItemText(i,null==n?void 0:n.text)))}static createItem(t,e,i){var n;const{elementRef:o,dropupText:r}=e,a=document.createElement("div");Object.assign(a.style,null==(n=null==i?void 0:i.item)?void 0:n.default),Ci.populateItem(o,a,r,i),a.classList.add("dropup-menu-item");const l=s.generateStateful((null==i?void 0:i.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return Ci.addItemEvents(t,a,o,l),a}}class Li{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=Li.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=Ci.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){window.addEventListener("click",(e=>{var i;t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()})),window.addEventListener("keydown",(t=>{var e,i,s;this._isOpen&&(t.key===n.ESCAPE?(this.close(),null==(e=this.highlightedItem)||e.dispatchEvent(new MouseEvent("mouseleave"))):t.key===n.ENTER?(null==(i=this.highlightedItem)||i.click(),null==(s=this.highlightedItem)||s.dispatchEvent(new MouseEvent("mouseleave"))):t.key===n.ARROW_DOWN?zi.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):t.key===n.ARROW_UP&&zi.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}))}}class Ii extends Ti{constructor(t,e){var i;super(Ii.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const n=this.createInnerElements(this._customStyles);this._menu=new Li(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=Ii.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(t)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(t){return{styles:this.createInnerElement(Ii.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ai.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){const t=ae.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>');return t.id="dropup-icon",t}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(t){t.addEventListener("click",(t=>{t.target.classList.contains("dropup-icon")||this._menu.close()}))}static getPosition(t,e){var i,n;return null!=(i=null==e?void 0:e.button)&&i.position?null==(n=null==e?void 0:e.button)?void 0:n.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class Ni{static addToDropup(t,e,i,n){const s=new Ii(i,n);ji.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),n=e["dropup-menu"][i];n&&(s.addItem(n.button),e["dropup-menu"].splice(i,1))}));const o=Ii.getPosition(e,n);ki.addButton(t,s.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const n=i;e[n].forEach((e=>{ki.addButton(t,e.button.elementRef,n)}))}))}static setPosition(t,e,i){const n={...t[e],buttonType:e};i.push(n),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=Ni.createPositionsObj();Object.keys(t).forEach((i=>{var n;const s=null==(n=t[i])?void 0:n.button.position;s&&Ni.setPosition(t,i,e[s])})),0===e["inside-right"].length&&t.submit&&Ni.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?Ni.setPosition(t,"submit",e["outside-right"]):t.microphone?Ni.setPosition(t,"microphone",e["outside-right"]):t.camera&&Ni.setPosition(t,"camera",e["outside-right"])),t.submit&&Ni.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&Ni.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?ji.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&Ni.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,n){const s=Ni.generatePositions(e);return Ni.addToSideContainer(t,s),s["dropup-menu"].length>0&&Ni.addToDropup(t,s,i,n),s}}const Ei={images:{id:"upload-images-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',dropupText:"File"}};class Di{constructor(t,e,i){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",t.maxNumberOfFiles&&(this._fileCountLimit=t.maxNumberOfFiles),this._toggleContainerDisplay=e,this._fileAttachmentsContainerRef=i,t.acceptedFormats&&(this._acceptedFormat=t.acceptedFormats)}attemptAddFile(t,e){return!!Di.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const n=i[e].trim();if(t.type===n)return!0;if(n.startsWith(".")){const e=n.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(n))return!0;if(n.endsWith("/*")&&t.type.startsWith(n.slice(0,-2)))return!0}}return!1}addAttachmentBasedOnType(t,e,i){if(t.type.startsWith("image")){const n=Di.createImageAttachment(e);this.addFileAttachment(t,"image",n,i)}else if(t.type.startsWith("audio")){const n=Ri.createAudioAttachment(e);this.addFileAttachment(t,"audio",n,i)}else{const e=Di.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),o.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const n=document.createElement("div");return n.classList.add("file-attachment-text-container"),n.appendChild(i),i.textContent=t,e.appendChild(n),e}addFileAttachment(t,e,i,n){const s=Di.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(s,e[0])}else this._fileAttachmentsContainerRef.appendChild(s);const o={file:t,attachmentContainerElement:s,fileType:e};return n&&(o.removeButton=this.createRemoveAttachmentButton(o),s.appendChild(o.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(o),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,o}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){const e=this._attachments.findIndex((e=>e===t)),i=this._attachments[e].attachmentContainerElement;this._attachments.splice(e,1),Ri.stopAttachmentPlayback(i),i.remove(),this._toggleContainerDisplay(!1)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const _i='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',Pi=class extends Di{constructor(t,e,i){super(t,e,i)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),o.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?ci.cloneElement(t):t,n=document.createElement("audio");n.src=e;const s=ae.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>');s.classList.add("attachment-icon","play-icon");const o=ae.createSVGElement(_i);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(s),n.onplay=()=>{i.replaceChildren(o)},n.onpause=()=>{i.replaceChildren(s),n.currentTime=0},n.onended=()=>{i.replaceChildren(s)},i.onclick=()=>{n.paused?n.play():n.pause()}}static createAudioAttachment(t){const e=Pi.createAudioContainer();return Pi.addAudioElements(e,t),e}createTimer(t,e){let i=0;const n=void 0!==e&&e<Pi.TIMER_LIMIT_S?e:Pi.TIMER_LIMIT_S;return setInterval((()=>{var e;i+=1,i===n&&(null==(e=this.stopPlaceholderCallback)||e.call(this),this.clearTimer()),600===i&&t.classList.add("audio-placeholder-text-4-digits");const s=Math.floor(i/60),o=(i%60).toString().padStart(2,"0");t.textContent=`${s}:${o}`}),1e3)}createPlaceholderAudioAttachment(t){const e=Pi.createAudioContainer(),i=document.createElement("div");i.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(i);const s=ae.createSVGElement(_i);return s.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),i.textContent="0:00",this._activePlaceholderTimer=this.createTimer(i,t),e.appendChild(n),this.addPlaceholderAudioAttachmentEvents(e,s,n),e}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(t,e){const i=this._activePlaceholderAttachment;i&&(i.file=t,Pi.addAudioElements(i.attachmentContainerElement.children[0],e),i.removeButton=this.createRemoveAttachmentButton(i),i.attachmentContainerElement.appendChild(i.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,n;null!=(n=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&n.classList.contains("stop-icon")&&t.children[0].click()}};let Ri=Pi;Ri.TIMER_LIMIT_S=5999;class Fi{static create(t,e,i,n){return"audio"===n?new Ri(t,e,i):new Di(t,e,i)}}class Bi{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e){const i=Fi.create(t,this.toggleContainerDisplay.bind(this),this.elementRef,e);return this._fileAttachmentsTypes.push(i),i}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let n=0;n<e.length&&!e[n].attemptAddFile(t,i.target.result);n+=1);}}))}addFilesToAnyType(t){Bi.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const qi=class{constructor(t,e,i){this._isOpen=!1,this._contentRef=qi.createModalContent(e,null==i?void 0:i.backgroundColor),this._buttonPanel=qi.createButtonPanel(null==i?void 0:i.backgroundColor),this._elementRef=qi.createContainer(this._contentRef,i),this._elementRef.appendChild(this._buttonPanel),t.appendChild(this._elementRef),this._backgroundPanelRef=qi.createDarkBackgroundPanel(),t.appendChild(this._backgroundPanelRef),this.addWindowEvents()}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>this._buttonPanel.appendChild(t)))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=ae.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),qi.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(t,e,i){const n=e?qi.createSVGButton(t):qi.createTextButton(t);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==i||i()}),140)},n}static createTextModalFunc(t,e,i){var n;if("object"==typeof e&&null!=(n=e.files)&&n.infoModal){const n=new qi(t,["modal-content"],e.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,i),n.openTextModal.bind(n,e.infoModalTextMarkUp||"")}}addWindowEvents(){window.addEventListener("keydown",(t=>{var e,i;this._isOpen&&(t.key===n.ESCAPE?(this.close(),null==(e=this.extensionCloseCallback)||e.call(this)):t.key===n.ENTER&&(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)))}))}};let Yi=qi;Yi.MODAL_CLOSE_TIMEOUT_MS=190;class Ui extends Ti{constructor(t,e,i,n,s,o){var r,a,l,c,u,h;super(Ui.createButtonElement(),null==(r=i.button)?void 0:r.position,i.button,o);const d=this.createInnerElements(n,s,this._customStyles);this._inputElement=Ui.createInputElement(null==(a=null==i?void 0:i.files)?void 0:a.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(d.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(c=null==(l=i.files)?void 0:l.infoModal)?void 0:c.openModalOnce)||null==(h=null==(u=i.files)?void 0:u.infoModal)?void 0:h.openModalOnce}createInnerElements(t,e,i){const n=Ui.createSVGIconElement(t,e);return{styles:this.createInnerElement(n,"styles",i)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){Bi.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}createInnerElement(t,e,i){return Ai.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=ae.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),n=Yi.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,n)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class Zi{static create(t,e,i){const n=Zi.createElement(i);Zi.addEvents(n,t,e),t.appendChild(n)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),Zi.display(t)},t.ondragleave=e=>{e.preventDefault(),Zi.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),Zi.uploadFile(i,e),Zi.hide(t)}}static uploadFile(t,e){var i;const n=null==(i=e.dataTransfer)?void 0:i.files;n&&t.addFilesToAnyType(Array.from(n))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class Ji extends Ti{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(Ji.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=Ji.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return Ai.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=ae.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg height="1.4em" width="1.4em" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"\n\t viewBox="0 0 490.9 490.9" xml:space="preserve">\n\t<g>\n\t\t<g>\n\t\t\t<path d="M245.5,322.9c53,0,96.2-43.2,96.2-96.2V96.2c0-53-43.2-96.2-96.2-96.2s-96.2,43.2-96.2,96.2v130.5\n\t\t\t\tC149.3,279.8,192.5,322.9,245.5,322.9z M173.8,96.2c0-39.5,32.2-71.7,71.7-71.7s71.7,32.2,71.7,71.7v130.5\n\t\t\t\tc0,39.5-32.2,71.7-71.7,71.7s-71.7-32.2-71.7-71.7V96.2z"/>\n\t\t\t<path d="M94.4,214.5c-6.8,0-12.3,5.5-12.3,12.3c0,85.9,66.7,156.6,151.1,162.8v76.7h-63.9c-6.8,0-12.3,5.5-12.3,12.3\n\t\t\t\ts5.5,12.3,12.3,12.3h152.3c6.8,0,12.3-5.5,12.3-12.3s-5.5-12.3-12.3-12.3h-63.9v-76.7c84.4-6.3,151.1-76.9,151.1-162.8\n\t\t\t\tc0-6.8-5.5-12.3-12.3-12.3s-12.3,5.5-12.3,12.3c0,76.6-62.3,138.9-138.9,138.9s-138.9-62.3-138.9-138.9\n\t\t\t\tC106.6,220,101.2,214.5,94.4,214.5z"/>\n\t\t</g>\n\t</g>\n</svg>\n');return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}var Vi={},$i={},Hi={},Gi={},Ki={};Object.defineProperty(Ki,"u",{value:!0}),Ki.Text=void 0;class Qi{static capitalize(t){return t.replace(Qi.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(Qi.DOUBLE_LINE,"<p></p>").replace(Qi.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}Ki.Text=Qi,Qi.FIRST_CHAR_REGEX=/\S/,Qi.DOUBLE_LINE=/\n\n/g,Qi.ONE_LINE=/\n/g,Object.defineProperty(Gi,"u",{value:!0}),Gi.Translate=void 0;const Wi=Ki;Gi.Translate=class{static translate(t,e){const i=Wi.Text.breakupIntoWordsArr(t);for(let t=0;t<i.length;t+=1)e[i[t]]&&(i[t]=e[i[t]]);return i.join("")}},Object.defineProperty(Hi,"u",{value:!0}),Hi.WebSpeechTranscript=void 0;const Xi=Gi;Hi.WebSpeechTranscript=class{static extract(t,e,i){let n="";for(let s=t.resultIndex;s<t.results.length;++s){let o=t.results[s][0].transcript;i&&(o=Xi.Translate.translate(o,i)),t.results[s].isFinal?e+=o:n+=o}return{interimTranscript:n,finalTranscript:e,newText:n||e}}static extractSafari(t,e,i){let n="";for(let e=t.resultIndex;e<t.results.length;++e){let s=t.results[e][0].transcript;i&&(s=Xi.Translate.translate(s,i)),n+=s}return{interimTranscript:"",finalTranscript:n,newText:n}}};var tn={};Object.defineProperty(tn,"u",{value:!0}),tn.Browser=void 0;class en{}tn.Browser=en,en.IS_SAFARI=()=>(void 0===en._IS_SAFARI&&(en._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),en._IS_SAFARI);var nn={},sn={};Object.defineProperty(sn,"u",{value:!0}),sn.EventListeners=void 0;class on{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&on.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==on.KEY_DOWN_TIMEOUT&&clearTimeout(on.KEY_DOWN_TIMEOUT),on.KEY_DOWN_TIMEOUT=setTimeout((()=>{on.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=on.getElementIfFocusedOnAvailable(t,e.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(t,e){const i=void 0===(null==e?void 0:e.insertInCursorLocation)||(null==e?void 0:e.insertInCursorLocation);null!=e&&e.element&&i&&(t.mouseDownEvent=on.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=on.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=on.keyDownWindow.bind(t,e),document.addEventListener("keydown",t.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}sn.EventListeners=on,on.KEY_DOWN_TIMEOUT=null;var rn={};Object.defineProperty(rn,"u",{value:!0}),rn.PreResultUtils=void 0;rn.PreResultUtils=class{static process(t,e,i,n,s){const o=null==n?void 0:n(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(s):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}};var an={},ln={};Object.defineProperty(ln,"u",{value:!0}),ln.AutoScroll=void 0;class cn{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML="&nbsp;")}static scrollGeneric(t,e){t.isCursorAtEnd?e.scrollTop=e.scrollHeight:t.scrollingSpan.scrollIntoView({block:"nearest"})}static scrollSafariPrimitiveToEnd(t){t.scrollLeft=t.scrollWidth,t.scrollTop=t.scrollHeight}static isElementOverflown(t){return t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth}static isRequired(t,e){return t&&cn.isElementOverflown(e)}}ln.AutoScroll=cn;var un={};Object.defineProperty(un,"u",{value:!0}),un.Elements=void 0;un.Elements=class{static isPrimitiveElement(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName}static createInterimSpan(){const t=document.createElement("span");return t.style.color="grey",t.style.pointerEvents="none",t}static createGenericSpan(){const t=document.createElement("span");return t.style.pointerEvents="none",t}static appendSpans(t,e){if(t.spansPopulated=!0,t.insertInCursorLocation&&document.activeElement===e){const e=window.getSelection();if(null!=e&&e.focusNode){const i=e.getRangeAt(0);return i.insertNode(t.scrollingSpan),i.insertNode(t.interimSpan),i.insertNode(t.finalSpan),i.collapse(!1),e.removeAllRanges(),void e.addRange(i)}}e.appendChild(t.finalSpan),e.appendChild(t.interimSpan),e.appendChild(t.scrollingSpan)}static applyCustomColors(t,e){e.interim&&(t.interimSpan.style.color=e.interim),e.final&&(t.finalSpan.style.color=e.final)}static isInsideShadowDOM(t){return t.getRootNode()instanceof ShadowRoot}};var hn={};Object.defineProperty(hn,"u",{value:!0}),hn.Cursor=void 0;class dn{static setOffsetForGeneric(t,e,i=0){let n=0;for(let s=0;s<t.childNodes.length;s+=1){const o=t.childNodes[s];if(o.childNodes.length>0){const t=dn.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const n=document.createRange();n.setStart(o,e-i),n.collapse(!0);const s=window.getSelection();return null==s||s.removeAllRanges(),null==s||s.addRange(n),t.focus(),-1}i+=o.textContent.length,n+=o.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(t,e){const i=window.getSelection();if(i){const n=dn.getGenericElementCursorOffset(t,i,!0);console.log(n),setTimeout((()=>{}),100),dn.setOffsetForGeneric(t,n+e)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let n=0;if(e.rangeCount>0){const s=e.getRangeAt(0),o=s.cloneRange();o.selectNodeContents(t),i?o.setEnd(s.startContainer,s.startOffset):o.setEnd(s.endContainer,s.endOffset),n=o.toString().length}return n}}hn.Cursor=dn,Object.defineProperty(an,"u",{value:!0}),an.CommandUtils=void 0;const pn=ln,mn=un,fn=tn,vn=hn,gn=Ki;class bn{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?gn.Text.breakupIntoWordsArr(t):t}static process(t){var e;return!0===(null===(e=t.settings)||void 0===e?void 0:e.caseSensitive)?t:Object.keys(t).reduce(((e,i)=>{const n=t[i];return e[i]="string"==typeof n?bn.processCommand(n,t.settings):n,e}),{})}static toggleCommandModeOn(t){var e;t.isWaitingForCommand=!0,null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!0)}static toggleCommandModeOff(t){var e;t.isWaitingForCommand&&(null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!1),t.isWaitingForCommand=!1)}static setText(t,e,i,n){bn.toggleCommandModeOff(t),mn.Elements.isPrimitiveElement(n)?(n.value=i,t.isTargetInShadow||vn.Cursor.setOffsetForPrimitive(n,i.length,!0),fn.Browser.IS_SAFARI()&&t.autoScroll&&pn.AutoScroll.scrollSafariPrimitiveToEnd(n)):(n.textContent=i,t.isTargetInShadow||vn.Cursor.focusEndOfGeneric(n),setTimeout((()=>pn.AutoScroll.scrollGeneric(t,n)))),t.resetRecording(e)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const n=t;for(let t=i.length-1;t>=0;t-=1){let e=t,s=n.length-1;for(;i[e]===n[s]&&s>=0;)e-=1,s-=1;if(s<0)return!0}return!1}static execCommand(t,e,i,n,s){var o,r,a;const l=t.commands;if(!l||!n||!i)return;const c=!0===(null===(o=l.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),u=gn.Text.breakupIntoWordsArr(c),h=!1===(null===(r=l.settings)||void 0===r?void 0:r.substrings)?bn.checkIfMatchesWord:bn.checkIfMatchesSubstring;if(l.commandMode&&h(l.commandMode,c,u))return t.setInterimColorToFinal(),setTimeout((()=>bn.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!l.commandMode||t.isWaitingForCommand){if(l.stop&&h(l.stop,c,u))return bn.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(l.pause&&h(l.pause,c,u))return bn.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(l.resume&&h(l.resume,c,u))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),bn.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(l.reset&&h(l.reset,c,u))return void 0!==s&&bn.setText(t,i,s,n),{doNotProcessTranscription:!0};if(l.removeAllText&&h(l.removeAllText,c,u))return bn.setText(t,i,"",n),{doNotProcessTranscription:!0}}}}an.CommandUtils=bn;var wn={};Object.defineProperty(wn,"u",{value:!0}),wn.Highlight=void 0;const yn=un,xn=hn;class Mn{static setStateForPrimitive(t,e){let i,n;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(n=e.selectionEnd),t.isHighlighted=i!==n}static setStateForGeneric(t,e){const i=window.getSelection();if(null!=i&&i.focusNode){const n=xn.Cursor.getGenericElementCursorOffset(e,i,!0),s=xn.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=n!==s}}static setState(t,e){document.activeElement===e&&(yn.Elements.isPrimitiveElement(e)?Mn.setStateForPrimitive(t,e):Mn.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const n=xn.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),xn.Cursor.setOffsetForGeneric(e,n),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,n=e.selectionEnd,s=e.value;if(i&&n){const o=s.substring(0,i)+s.substring(n);e.value=o,xn.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}wn.Highlight=Mn;var kn={};Object.defineProperty(kn,"u",{value:!0}),kn.Padding=void 0;const jn=un,An=hn,Sn=Ki;class Tn{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,n=e.value[i-1],s=null===e.selectionEnd?i:e.selectionEnd,o=e.value[s];return Sn.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),Sn.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===s)}const i=e.value[e.value.length-1];Sn.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,n,s;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=An.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],l=An.Cursor.getGenericElementCursorOffset(e,o,!1),c=null===(n=e.textContent)||void 0===n?void 0:n[l];return Sn.Text.isCharDefined(a)&&(t.startPadding=" "),Sn.Text.isCharDefined(c)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(s=e.textContent)||void 0===s?void 0:s.length)===l)}}const o=e.innerText.charAt(e.innerText.length-1);Sn.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){jn.Elements.isPrimitiveElement(e)?Tn.setStateForPrimitiveElement(t,e):Tn.setStateForGenericElement(t,e)}static adjustStateAfterRecodingPrimitiveElement(t,e){t.primitiveTextRecorded=!0,t.insertInCursorLocation&&document.activeElement===e&&(null!==e.selectionEnd&&(t.endPadding=t.endPadding+e.value.slice(e.selectionEnd)),null!==e.selectionStart)?t.startPadding=e.value.slice(0,e.selectionStart)+t.startPadding:t.startPadding=e.value+t.startPadding}static adjustSateForNoTextPrimitiveElement(t){1===t.numberOfSpacesBeforeNewText&&(t.startPadding=t.startPadding.substring(0,t.startPadding.length-1),t.numberOfSpacesBeforeNewText=0),1===t.numberOfSpacesAfterNewText&&(t.endPadding=t.endPadding.substring(1),t.numberOfSpacesAfterNewText=0)}}kn.Padding=Tn,Object.defineProperty(nn,"u",{value:!0}),nn.Speech=void 0;const zn=sn,On=rn,Cn=an,Ln=ln,In=wn,Nn=un,En=kn,Dn=tn,_n=hn,Pn=Ki;nn.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=Nn.Elements.createInterimSpan(),this.finalSpan=Nn.Elements.createGenericSpan(),this.scrollingSpan=Nn.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()}prepareBeforeStart(t){var e,i;if(null!=t&&t.element)if(zn.EventListeners.add(this,t),Array.isArray(t.element)){const e=t.element.find((t=>t===document.activeElement))||t.element[0];if(!e)return;this.prepare(e)}else this.prepare(t.element);void 0!==(null==t?void 0:t.displayInterimResults)&&(this._displayInterimResults=t.displayInterimResults),null!=t&&t.textColor&&(this._finalTextColor=null===(e=null==t?void 0:t.textColor)||void 0===e?void 0:e.final,Nn.Elements.applyCustomColors(this,t.textColor)),void 0!==(null==t?void 0:t.insertInCursorLocation)&&(this.insertInCursorLocation=t.insertInCursorLocation),void 0!==(null==t?void 0:t.autoScroll)&&(this.autoScroll=t.autoScroll),this._onResult=null==t?void 0:t.onResult,this._onPreResult=null==t?void 0:t.onPreResult,this._onStart=null==t?void 0:t.onStart,this._onStop=null==t?void 0:t.onStop,this._onError=null==t?void 0:t.onError,this.onCommandModeTrigger=null==t?void 0:t.onCommandModeTrigger,this.onPauseTrigger=null==t?void 0:t.onPauseTrigger,this._options=t,null!==(i=this._options)&&void 0!==i&&i.commands&&(this.commands=Cn.CommandUtils.process(this._options.commands))}prepare(t){En.Padding.setState(this,t),In.Highlight.setState(this,t),this.isTargetInShadow=Nn.Elements.isInsideShadowDOM(t),Nn.Elements.isPrimitiveElement(t)?(this._primitiveElement=t,this._originalText=this._primitiveElement.value):(this._genericElement=t,this._originalText=this._genericElement.textContent)}resetRecording(t){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(t,!0)}updateElements(t,e,i){var n;const s=Pn.Text.capitalize(e);if(this.finalTranscript===s&&""===t)return;On.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&Cn.CommandUtils.execCommand(this,i,this._options,this._primitiveElement||this._genericElement,this._originalText);if(o){if(o.doNotProcessTranscription)return;t="",i=""}if(this.isPaused||this.isWaitingForCommand)return;null===(n=this._onResult)||void 0===n||n.call(this,i,""===t),this.finalTranscript=s,this._displayInterimResults||(t="");const r=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,r):this._genericElement&&this.updateGenericElement(this._genericElement,t,r)}updatePrimitiveElement(t,e,i){this.isHighlighted&&In.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||En.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&En.Padding.adjustSateForNoTextPrimitiveElement(this);const n=this.startPadding+this.finalTranscript+e;if(t.value=n+this.endPadding,!this.isTargetInShadow){const e=n.length+this.numberOfSpacesAfterNewText;_n.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&Dn.Browser.IS_SAFARI()&&this.isCursorAtEnd&&Ln.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&In.Highlight.removeForGeneric(this,t),this.spansPopulated||Nn.Elements.appendSpans(this,t);const n=(i?"":this.startPadding)+Pn.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=n;const s=Ln.AutoScroll.isRequired(this.autoScroll,t);Ln.AutoScroll.changeStateIfNeeded(this,s);const o=Pn.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,Dn.Browser.IS_SAFARI()&&this.insertInCursorLocation&&_n.Cursor.setOffsetForSafariGeneric(t,n.length+o.length),s&&Ln.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=Nn.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=Nn.Elements.createInterimSpan(),this.scrollingSpan=Nn.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),zn.EventListeners.remove(this)}setInterimColorToFinal(){this.interimSpan.style.color=this._finalTextColor||"black"}resetState(t){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,t||(this.stopTimeout=void 0)}setStateOnStart(){var t;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:null===(t=this._onStart)||void 0===t||t.call(this)}setStateOnStop(){var t;this.recognizing=!1,this.isRestarting||null===(t=this._onStop)||void 0===t||t.call(this)}setStateOnError(t){var e;null===(e=this._onError)||void 0===e||e.call(this,t),this.recognizing=!1}},Object.defineProperty($i,"u",{value:!0}),$i.WebSpeech=void 0;const Rn=Hi,Fn=tn,Bn=nn;class qn extends Bn.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=Fn.Browser.IS_SAFARI()?Rn.WebSpeechTranscript.extractSafari:Rn.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(t),this.instantiateService(t),null===(e=this._service)||void 0===e||e.start(),this._translations=null==t?void 0:t.translations)}validate(){return!!qn.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=qn.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{Fn.Browser.IS_SAFARI()&&"Another request is started"===t.message||"aborted"===t.error&&this.isRestarting||"no-speech"!==t.error&&this.error(t.message||t.error)},this._service.onaudioend=()=>{this.setStateOnStop()},this._service.onend=()=>{this._stopping=!1},this._service.onresult=t=>{if(typeof t.results>"u"&&this._service)this._service.onend=null,this._service.stop();else if(this._extractText&&!this._stopping){const{interimTranscript:e,finalTranscript:i,newText:n}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,n)}})}stop(t){var e;this._stopping=!0,null===(e=this._service)||void 0===e||e.stop(),this.finalise(t)}static getAPI(){return window.webkitSpeechRecognition||window.SpeechRecognition}error(t){console.error(t),this.setStateOnError(t),this.stop()}}$i.WebSpeech=qn;var Yn={};Object.defineProperty(Yn,"u",{value:!0}),Yn.GlobalState=void 0;class Un{static doubleClickDetector(){return!!Un.doubleClickPending||(Un.doubleClickPending=!0,setTimeout((()=>{Un.doubleClickPending=!1}),300),!1)}}Yn.GlobalState=Un,Un.doubleClickPending=!1;var Zn={},Jn={};Object.defineProperty(Jn,"u",{value:!0}),Jn.PreventConnectionStop=void 0;Jn.PreventConnectionStop=class{static applyPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!0,t._manualConnectionStopPrevention=setTimeout((()=>{t.cannotBeStopped=!1}),800)}static clearPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!1}};var Vn={},$n={};Object.defineProperty($n,"u",{value:!0}),$n.README_URL=void 0,$n.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(Vn,"u",{value:!0}),Vn.AzureSpeechConfig=void 0;const Hn=$n;class Gn{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${Hn.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${Hn.README_URL}`),!1):(t(`Please provide subscription details - more info: ${Hn.README_URL}`),!1)}static async getNewSpeechConfig(t,e){if(e.region)return e.subscriptionKey?t.fromSubscription(e.subscriptionKey.trim(),e.region.trim()):e.token?t.fromAuthorizationToken(e.token.trim(),e.region.trim()):e.retrieveToken?e.retrieveToken().then((i=>e.region?t.fromAuthorizationToken((null==i?void 0:i.trim())||"",e.region.trim()):null)).catch((t=>(console.error(t),null))):null}static process(t,e){e.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,e){const i=await Gn.getNewSpeechConfig(t,e);return i&&Gn.process(i,e),i}}Vn.AzureSpeechConfig=Gn;var Kn={};Object.defineProperty(Kn,"u",{value:!0}),Kn.StopTimeout=void 0;class Qn{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||Qn.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),Qn.set(t)}}Kn.StopTimeout=Qn,Qn.DEFAULT_MS=2e4;var Wn={};Object.defineProperty(Wn,"u",{value:!0}),Wn.AzureTranscript=void 0;const Xn=Gi;Wn.AzureTranscript=class{static extract(t,e,i,n){return n&&(t=Xn.Translate.translate(t,n)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}},Object.defineProperty(Zn,"u",{value:!0}),Zn.Azure=void 0;const ts=Jn,es=Vn,is=Kn,ns=Wn,ss=nn;class os extends ss.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&is.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||ts.PreventConnectionStop.applyPrevention(this)}async startAsync(t){var e;this.validate(t)&&(await this.instantiateService(t),this._translations=null==t?void 0:t.translations,null===(e=this._service)||void 0===e||e.startContinuousRecognitionAsync((()=>{}),this.error))}validate(t){return os.getAPI()?es.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=os.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),n=await es.AzureSpeechConfig.get(e.SpeechConfig,t);if(n){const s=new e.SpeechRecognizer(n,i);this.setEvents(s),this._service=s,t.retrieveToken&&this.retrieveTokenInterval(t.retrieveToken)}else this.error("Unable to contact Azure server")}setEvents(t){t.recognizing=this.onRecognizing.bind(this),t.recognized=this.onRecognized.bind(this),t.sessionStarted=this.onSessionStarted.bind(this),t.canceled=this.onCanceled.bind(this),t.sessionStopped=this.onSessionStopped.bind(this)}onRecognizing(t,e){if(this._stopping)return;const{interimTranscript:i,finalTranscript:n,newText:s}=ns.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);is.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,n,s)}onRecognized(t,e){const i=e.result;switch(i.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(i.text&&!this._stopping){const{interimTranscript:t,finalTranscript:e,newText:n}=ns.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);is.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,n),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){ts.PreventConnectionStop.clearPrevention(this),this.setStateOnStart()}onSessionStopped(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}retrieveTokenInterval(t){this._retrieveTokenInterval=setInterval((()=>{null==t||t().then((t=>{this._service&&(this._service.authorizationToken=(null==t?void 0:t.trim())||"")})).catch((t=>{this.error(t)}))}),1e4)}stop(t){var e;!t&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,null===(e=this._service)||void 0===e||e.stopContinuousRecognitionAsync(),this.finalise(t)}static getAPI(){return window.SpeechSDK}moduleNotFound(){console.error("speech recognition module not found:"),console.error("please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: <script src=\"https://aka.ms/csspeech/jsbrowserpackageraw\"><\/script>"),this.setStateOnError("speech recognition module not found")}error(t){this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),console.error(t),this.setStateOnError(t),this.stop()}}Zn.Azure=os,Object.defineProperty(Vi,"u",{value:!0});const rs=$i,as=an,ls=Yn,cs=Zn;class us{static toggle(t,e){var i,n;const s=t.toLocaleLowerCase().trim();null!==(i=ls.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===s?us.startWebSpeech(e):"azure"===s?us.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(n=null==e?void 0:e.onError)||void 0===n||n.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){us.stop()||(ls.GlobalState.service=new rs.WebSpeech,ls.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!rs.WebSpeech.getAPI()}static startAzure(t){var e;us.stop()||null!==(e=ls.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(ls.GlobalState.service=new cs.Azure,ls.GlobalState.service.start(t))}static stop(){var t;return!!ls.GlobalState.doubleClickDetector()||(!(null===(t=ls.GlobalState.service)||void 0===t)&&t.recognizing&&ls.GlobalState.service.stop(),!1)}static endCommandMode(){ls.GlobalState.service&&as.CommandUtils.toggleCommandModeOff(ls.GlobalState.service)}}var hs=Vi.default=us;class ds extends Ji{constructor(t,e,i){var n;super("object"==typeof t.speechToText?null==(n=t.speechToText)?void 0:n.button:{});const{serviceName:s,processedConfig:o}=ds.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==s||hs.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,s,o)}else this.changeToUnsupported()}static processConfiguration(t,e){var i;const n="object"==typeof e?e:{},s="object"==typeof n.webSpeech?n.webSpeech:{},o=n.azure||{},r={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,...s,...o},a=null==(i=n.commands)?void 0:i.submit;return a&&(r.onPreResult=e=>e.toLowerCase().includes(a)?(setTimeout((()=>{var e;return null==(e=t.submit)?void 0:e.call(t)})),hs.endCommandMode(),{restart:!0,removeNewText:!0}):null),{serviceName:ds.getServiceName(n),processedConfig:r}}static getServiceName(t){return t.webSpeech?"webspeech":t.azure?"azure":"webspeech"}buttonClick(t,e,i,n){t.removeTextIfPlaceholder(),hs.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:this.onError.bind(this),onStart:this.changeToActive.bind(this),onStop:this.changeToDefault.bind(this),onCommandModeTrigger:this.onCommandModeTrigger.bind(this),...n})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}}class ps{static getFileName(t,e){const i=new Date;return`${t}-${String(i.getHours()).padStart(2,"0")}-${String(i.getMinutes()).padStart(2,"0")}-${String(i.getSeconds()).padStart(2,"0")}.${e}`}}class ms extends Ji{constructor(t,e){var i,n;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(n=e.files)?void 0:n.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=ps.getFileName(this._newFilePrefix||"audio",this._extension),n=new File([e],i,{type:e.type}),s=new FileReader;s.readAsDataURL(n),s.onload=t=>{this._audioType.completePlaceholderAttachment(n,t.target.result)}}}class fs{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}}class vs extends Ti{constructor(t,e,i,n,s){var o;super(vs.createButtonContainerElement(),null==(o=t.submitButtonStyles)?void 0:o.position,t.submitButtonStyles),this._isRequestInProgress=!1,this._isLoadingActive=!1,this._isSVGLoadingIconOverriden=!1,this._messages=i,this._inputElementRef=e,this._fileAttachments=s,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._serviceIO=n,this.attemptOverwriteLoadingStyle(t),this.changeToSubmitIcon()}createInnerElements(){const{submit:t,loading:e,stop:i}=Ai.create(this.elementRef,["submit","loading","stop"],this._customStyles);return{submit:t||vs.createSubmitIconElement(),loading:e||vs.createLoadingIconElement(),stop:i||vs.createStopIconElement()}}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=ae.createSVGElement('<?xml version="1.0" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">\n<svg xmlns="http://www.w3.org/2000/svg" stroke="currentColor" fill="none" stroke-width="1" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="14"></line>\n <polygon points="22 2 15 22 11 14 2 10 22 2"></polygon>\n</svg>\n');return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("dots-jumping"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}attemptOverwriteLoadingStyle(t){var e,i,n,s,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(s=null==(n=this._customStyles)?void 0:n.loading)?void 0:s.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}submitFromInput(){var t;if(this._inputElementRef.classList.contains("text-input-placeholder"))this.submit(!1,"");else{const e=null==(t=this._inputElementRef.textContent)?void 0:t.trim();this.submit(!1,e)}}async submit(t,e){var i,n;let s,o;t||(await this._fileAttachments.completePlaceholders(),s=this._fileAttachments.getAllFileData(),o=null==s?void 0:s.map((t=>t.file)));const r=""===e?void 0:e;if(this._isRequestInProgress)return;if(null!=(i=this._serviceIO.deepChat)&&i.validateMessageBeforeSending){if(!this._serviceIO.deepChat.validateMessageBeforeSending(r,o))return}else if(!this._serviceIO.canSendMessage(r,o))return;this.changeToLoadingIcon(),""!==e&&this._messages.addNewMessage({text:e},!1,!0),s&&await this._messages.addMultipleFiles(s),this._messages.addLoadingMessage(),t||u.clear(this._inputElementRef);const a={onFinish:this.changeToSubmitIcon.bind(this)},l={onOpen:this.changeToStopIcon.bind(this),onClose:this.changeToSubmitIcon.bind(this),abortStream:this._abortStream},c={text:r,files:o};this._serviceIO.callAPI(c,this._messages,a,l),t||null==(n=this._fileAttachments)||n.removeAllFiles()}stopStream(){this._abortStream.abort(),this.changeToSubmitIcon()}changeToStopIcon(){this.elementRef.classList.remove("loading-button"),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this._isLoadingActive=!1}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.add("loading-button"),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this._isRequestInProgress=!0,this._isLoadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.remove("loading-button"),this.elementRef.replaceChildren(this._innerElements.submit),fs.resetSubmit(this,this._isLoadingActive),this.elementRef.onclick=this.submitFromInput.bind(this),this._isRequestInProgress=!1,this._isLoadingActive=!1}}class gs extends Yi{constructor(t,e,i,n){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:s,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=s,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=ae.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n'),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==n?void 0:n.format)&&(this._format="image/jpeg"),null!=n&&n.dimensions&&(this._dimensions=n.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=Yi.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n');e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const n=Yi.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return n.classList.add("modal-svg-submit-button"),this.addButtons(e,n),this.addButtonEvents(e,i,n,t),{captureButton:e,submitButton:n}}addButtonEvents(t,e,i,n){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&Bi.addFilesToType([t],[n]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),Yi.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),n=new Blob([i],{type:this._format}),s="image/jpeg"===this._format?"jpeg":"png",o=ps.getFileName(this._newFilePrefix||"photo",s);return new File([n],o,{type:n.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,n){const s=new gs(t,e,i,n);return s.openCameraModal.bind(s,s)}}class bs extends Ti{constructor(t,e,i){var n;super(bs.createButtonElement(),null==(n=null==i?void 0:i.button)?void 0:n.position,(null==i?void 0:i.button)||{},"Photo");const s=this.createInnerElements(this._customStyles);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(s.styles),this.reapplyStateStyle("styles")}createInnerElements(t){return{styles:this.createInnerElement(bs.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ai.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=ae.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>');return t.id="camera-icon",t}addClickEvent(t,e,i,n){const s=gs.createCameraModalFunc(t,e,i,n);this.elementRef.onclick=s}}class ws{constructor(t,e,i,n){this.elementRef=ws.createPanelElement(t.inputAreaStyle);const s=new u(i,t.textInput),o={},r=this.createFileUploadComponents(t,i,n,o);t.speechToText&&!o.microphone&&(o.microphone={button:new ds(t,s,e.addNewErrorMessage.bind(e))});const a=new vs(t,s.inputElementRef,e,i,r);s.submit=a.submitFromInput.bind(a),t.submitUserMessage=a.submit.bind(a,!0),o.submit={button:a},ws.addElements(this.elementRef,s,o,n,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,n){var s,o,r,a;const l=new Bi(this.elementRef,t.attachmentContainerStyle,e.demo);if(ws.createUploadButtons(e.fileTypes||{},l,i,n),null!=(s=e.camera)&&s.files){const t=(null==(o=n.images)?void 0:o.fileType)||l.addType(e.camera.files,"images");n.camera={button:new bs(i,t,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const t=(null==(a=n.audio)?void 0:a.fileType)||l.addType(e.recordAudio.files,"audio");n.microphone={button:new ms(t,e.recordAudio)}}return Zi.isEnabled(l,t.dragAndDrop)&&Zi.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,n){Object.keys(t).forEach((s=>{const o=s,r=t[o];if(r.files){const t=e.addType(r.files,o),{id:s,svgString:a,dropupText:l}=Ei[o],c=new Ui(i,t,r,s,a,l);n[o]={button:c,fileType:t}}}))}static addElements(t,e,i,n,s,o){ci.addElements(t,e.elementRef);const r=ki.create(),a=Ni.addButtons(r,i,n,o);Mi.set(e.inputElementRef,r,s.elementRef,a),ki.add(t,r)}}class ys{static createElements(t,e,i){const n=document.createElement("div");n.id="chat-view";const s=new yi(t,e,i);e.websocket&&T.assignListeners(e,s);const o=new ws(t,s,e,n);return ci.addElements(n,s.elementRef,o.elementRef),n}static render(t,e,i,n){const s=ys.createElements(t,i,n);e.replaceChildren(s)}}var xs=Object.defineProperty,Ms=Object.getOwnPropertyDescriptor,ks=(t,e,i,n)=>{for(var s,o=n>1?void 0:n?Ms(e,i):e,r=t.length-1;r>=0;r--)(s=t[r])&&(o=(n?s(e,i,o):s(o))||o);return n&&o&&xs(e,i,o),o};class js extends re{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>{h.focusFromParentElement(this._elementRef)},this.refreshMessages=()=>{},this.onNewMessage=()=>{},this.onComponentRender=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,oi.appendStyleSheetToHead(),this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),i.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#large-loading-ring{display:inline-block;width:50px;height:50px}#large-loading-ring:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:large-loading-ring 1.4s linear infinite}@keyframes large-loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-ring{display:inline-block;width:16px;height:16px}#loading-ring:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-ring 1.2s linear infinite}@keyframes loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}.intro-panel{position:absolute;display:flex;justify-content:center;inset:0px;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;width:90%;margin-left:auto;margin-right:auto;max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.loading-message-text{width:1em;padding:.6em .75em .6em 1.3em}.message-bubble>p{line-height:1.26em}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message-bubble{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;user-select:none}.not-removable-attachment-icon{inset:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;inset:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.dots-jumping{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:dots-jumping 1.5s infinite linear;bottom:-.7em}@keyframes dots-jumping{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.dots-flashing{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite linear alternate;animation-delay:.5s}.dots-flashing:before,.dots-flashing:after{content:"";display:inline-block;position:absolute;top:0}.dots-flashing:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:0s}.dots-flashing:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:1s}@keyframes dots-flashing{0%{background-color:var(--message-dots-color)}50%,to{background-color:var(--message-dots-color-fade)}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.loading-button{background-color:#fff;cursor:auto}.loading-button:hover,.loading-button:active{background-color:#fff}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;user-select:none}.text-input-placeholder{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0px}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item>*{pointer-events:none}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}:host{all:initial;display:table-cell}#container{height:350px;width:320px;border:1px solid #cacaca;font-family:Inter,sans-serif,Avenir,Helvetica,Arial;font-size:.9rem;background-color:#fff;position:relative;overflow:hidden}\n',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateConfigKey=!1),this.onRender()}onRender(){var n,s;this._activeService??(this._activeService=ni.create(this)),this._activeService&&(this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(i.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),Object.assign(this._elementRef.style,this.containerStyle),this._activeService.key&&this._activeService.validateConfigKey?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof ne&&this._activeService.key||null!=(n=this.request)&&n.url||null!=(s=this.directConnection)&&s.demo?(this._childElement??(this._childElement=this.children[0]),ys.render(this,this._elementRef,this._activeService,this._childElement)):this._activeService instanceof ne?ue.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):t.render(this._elementRef,'Please define "request" with a "url"'),this._hasBeenRendered=!0,ai.onRender(this))}}ks([ri("object")],js.prototype,"directConnection",2),ks([ri("object")],js.prototype,"request",2),ks([ri("boolean")],js.prototype,"stream",2),ks([ri("object")],js.prototype,"requestBodyLimits",2),ks([ri("function")],js.prototype,"requestInterceptor",2),ks([ri("function")],js.prototype,"responseInterceptor",2),ks([ri("function")],js.prototype,"validateMessageBeforeSending",2),ks([ri("object")],js.prototype,"containerStyle",2),ks([ri("object")],js.prototype,"attachmentContainerStyle",2),ks([ri("object")],js.prototype,"dropupStyles",2),ks([ri("object")],js.prototype,"inputAreaStyle",2),ks([ri("object")],js.prototype,"textInput",2),ks([ri("object")],js.prototype,"submitButtonStyles",2),ks([ri("string")],js.prototype,"auxiliaryStyle",2),ks([ri("array")],js.prototype,"initialMessages",2),ks([ri("string")],js.prototype,"introMessage",2),ks([ri("object")],js.prototype,"avatars",2),ks([ri("object")],js.prototype,"names",2),ks([ri("boolean")],js.prototype,"displayLoadingBubble",2),ks([ri("object")],js.prototype,"errorMessages",2),ks([ri("object")],js.prototype,"messageStyles",2),ks([ri("object")],js.prototype,"textToSpeech",2),ks([ri("object")],js.prototype,"speechToText",2),ks([ri("object")],js.prototype,"images",2),ks([ri("object")],js.prototype,"gifs",2),ks([ri("object")],js.prototype,"camera",2),ks([ri("object")],js.prototype,"audio",2),ks([ri("object")],js.prototype,"microphone",2),ks([ri("object")],js.prototype,"mixedFiles",2),ks([ri("object")],js.prototype,"dragAndDrop",2),ks([ri("object")],js.prototype,"introPanelStyle",2),ks([ri("function")],js.prototype,"onNewMessage",2),ks([ri("function")],js.prototype,"onComponentRender",2),customElements.define("deep-chat",js);export{js as DeepChat};
1
+ class ErrorView{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class ValidateKeyPropertyView{static onLoad(t){t.innerHTML='<div id="large-loading-ring"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(t,e,i){const n=ValidateKeyPropertyView.createElements(),s={onSuccess:e,onFail:ErrorView.render.bind(this,t,"Your 'key' has failed authentication"),onLoad:ValidateKeyPropertyView.onLoad.bind(this,n)};i.key&&i.verifyKey(i.key,s),t.replaceChildren(n)}}class WebComponentStyleUtils{static apply(t,e){if(e)try{WebComponentStyleUtils.applyStyleSheet(t,e)}catch{WebComponentStyleUtils.addStyleElement(t,e)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}}var KEYBOARD_KEY=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(KEYBOARD_KEY||{});class StyleUtils{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&StyleUtils.unsetStyle(t,e.click),e.hover&&StyleUtils.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){StyleUtils.unsetActivityCSSMouseStates(t,e),e.default&&StyleUtils.unsetStyle(t,e.default)}static generateStateful(t,e,i){const n=t.default||{},s=Object.assign(JSON.parse(JSON.stringify({...n,...e})),null==t?void 0:t.hover);return{default:n,hover:s,click:Object.assign(JSON.parse(JSON.stringify({...s,...i})),null==t?void 0:t.click)}}}let Browser$1=class{};Browser$1.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),Browser$1.IS_CHROMIUM=window.chrome;class PasteUtils{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const n=null==(e=t.clipboardData)?void 0:e.getData("text/plain");null==(i=document.execCommand)||i.call(document,"insertHTML",!1,n)}}const _InputLimit=class{static add(t,e){t.addEventListener("keydown",_InputLimit.onKeyDown.bind(this,e)),t.oninput=_InputLimit.onInput.bind(this,e)}static onKeyDown(t,e){const i=e.target.textContent;i&&i.length>=t&&!_InputLimit.PERMITTED_KEYS.has(e.key)&&!_InputLimit.isKeyCombinationPermitted(e)&&e.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e){const i=e.target,n=i.textContent;n&&n.length>t&&(i.textContent=n.substring(0,t),FocusUtils.focusEndOfInput(i))}};let InputLimit=_InputLimit;InputLimit.PERMITTED_KEYS=new Set([KEYBOARD_KEY.BACKSPACE,KEYBOARD_KEY.DELETE,KEYBOARD_KEY.ARROW_RIGHT,KEYBOARD_KEY.ARROW_LEFT,KEYBOARD_KEY.ARROW_DOWN,KEYBOARD_KEY.ARROW_UP,KEYBOARD_KEY.META,KEYBOARD_KEY.CONTROL,KEYBOARD_KEY.ENTER]);const _TextInputEl=class{constructor(t,e){var i;const n=_TextInputEl.processConfig(t,e);this.elementRef=_TextInputEl.createContainerElement(null==(i=null==n?void 0:n.styles)?void 0:i.container),this.inputElementRef=this.createInputElement(n),this._config=n,this.elementRef.appendChild(this.inputElementRef),null!=e&&e.characterLimit&&InputLimit.add(this.inputElementRef,null==e?void 0:e.characterLimit)}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}static clear(t){const e=window.scrollY;t.classList.contains("text-input-disabled")||(t.textContent=""),Browser$1.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(t){var e,i,n;const s=document.createElement("div");return s.id=_TextInputEl.TEXT_INPUT_ID,s.classList.add("text-input-styling","text-input-placeholder"),s.innerText=(null==(e=null==t?void 0:t.placeholder)?void 0:e.text)||"Ask me anything!",Browser$1.IS_CHROMIUM&&_TextInputEl.preventAutomaticScrollUpOnNewLine(s),"boolean"==typeof(null==t?void 0:t.disabled)&&!0===t.disabled?(s.contentEditable="false",s.classList.add("text-input-disabled")):(s.contentEditable="true",s.onfocus=this.onFocus.bind(this),s.addEventListener("keydown",this.onKeydown.bind(this)),s.onpaste=PasteUtils.sanitizePastedTextContent),Object.assign(s.style,null==(i=null==t?void 0:t.styles)?void 0:i.text),Object.assign(s.style,null==(n=null==t?void 0:t.placeholder)?void 0:n.style),s}removeTextIfPlaceholder(){var t,e,i,n;this.inputElementRef.classList.contains("text-input-placeholder")&&!this.inputElementRef.classList.contains("text-input-disabled")&&(null!=(t=this._config.placeholder)&&t.style&&(StyleUtils.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(i=this._config)?void 0:i.styles)?void 0:n.text)),_TextInputEl.clear(this.inputElementRef),this.inputElementRef.classList.remove("text-input-placeholder"))}static toggleEditability(t,e){t.contentEditable=e?"true":"false"}onFocus(){Browser$1.IS_SAFARI?setTimeout((()=>{this.removeTextIfPlaceholder()})):this.removeTextIfPlaceholder()}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}onKeydown(t){var e;t.key===KEYBOARD_KEY.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}};let TextInputEl=_TextInputEl;TextInputEl.TEXT_INPUT_ID="text-input";class FocusUtils{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${TextInputEl.TEXT_INPUT_ID}`);e&&FocusUtils.focusEndOfInput(e)}}async function getBytes(t,e){const i=t.getReader();let n;for(;!(n=await i.read()).done;)e(n.value)}function getLines(t){let e,i,n,s=!1;return function(o){void 0===e?(e=o,i=0,n=-1):e=concat(e,o);const r=e.length;let a=0;for(;i<r;){s&&(10===e[i]&&(a=++i),s=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===n&&(n=i-a);break;case 13:s=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),n),a=i,n=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}function getMessages(t,e,i){let n=newMessage();const s=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(n),n=newMessage();else if(r>0){const i=s.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),l=s.decode(o.subarray(a));switch(i){case"data":n.data=n.data?n.data+"\n"+l:l;break;case"event":n.event=l;break;case"id":t(n.id=l);break;case"retry":const i=parseInt(l,10);isNaN(i)||e(n.retry=i)}}}}function concat(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function newMessage(){return{data:"",event:"",id:"",retry:void 0}}var __rest=globalThis&&globalThis.__rest||function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const EventStreamContentType="text/event-stream",DefaultRetryInterval=1e3,LastEventId="last-event-id";function fetchEventSource(t,e){var{signal:i,headers:n,onopen:s,onmessage:o,onclose:r,onerror:a,openWhenHidden:l,fetch:c}=e,u=__rest(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,h)=>{const d=Object.assign({},n);let p;function m(){p.abort(),document.hidden||w()}d.accept||(d.accept=EventStreamContentType),l||document.addEventListener("visibilitychange",m);let g=DefaultRetryInterval,v=0;function f(){document.removeEventListener("visibilitychange",m),window.clearTimeout(v),p.abort()}null==i||i.addEventListener("abort",(()=>{f(),e()}));const b=c??window.fetch,y=s??defaultOnOpen;async function w(){var i;p=new AbortController;try{const i=await b(t,Object.assign(Object.assign({},u),{headers:d,signal:p.signal}));await y(i),await getBytes(i.body,getLines(getMessages((t=>{t?d[LastEventId]=t:delete d[LastEventId]}),(t=>{g=t}),o))),null==r||r(),f(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:g;window.clearTimeout(v),v=window.setTimeout(w,e)}catch(t){f(),h(t)}}}w()}))}function defaultOnOpen(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(EventStreamContentType))throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${e}`)}const ErrorMessages={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect"},_RequestUtils=class{static temporarilyRemoveHeader(t,e,i){if(null==t||!t.headers)throw new Error("Request settings have not been set up");const n=t.headers[_RequestUtils.CONTENT_TYPE];delete t.headers[_RequestUtils.CONTENT_TYPE],e(i),t.headers[_RequestUtils.CONTENT_TYPE]=n}static displayError(t,e){if(console.error(e),"object"==typeof e)return 0===Object.keys(e).length?t.addNewErrorMessage("service","Service error, please try again."):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}};let RequestUtils=_RequestUtils;RequestUtils.CONTENT_TYPE="Content-Type";const _Demo=class{static generateResponseForOneMessage(t){if(t.file)return"image"===t.file.type?"That is a nice image!":"audio"===t.file.type?"I like the sound of that!":"gif"===t.file.type?"That is a nice gif!":"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!"}static generateResponse(t){const e=[];for(let i=t.messages.length-1;i>=0&&"ai"!==t.messages[i].role;i-=1)e.push(t.messages[i]);if(1===e.length)return _Demo.generateResponseForOneMessage(t.messages[t.messages.length-1]);const i=t.messages.findIndex((t=>t.text));return-1!==i&&e.splice(i,1),1===e.length?_Demo.generateResponseForOneMessage(t.messages[t.messages.length-1]):"Wow, very cool files!"}static request(t,e,i){const n=_Demo.generateResponse(t);setTimeout((()=>{const s={text:n},o=(null==i?void 0:i(s))||s;t.addNewMessage(o,!0,!0),e()}),400)}static requestStream(t,e,i){const n=_Demo.generateResponse(t).split(" ");setTimeout((()=>{const s=t.addNewStreamedMessage();e(),_Demo.populateMessages(s,n,t,i)}),400)}static populateMessages(t,e,i,n,s=0){setTimeout((()=>{const o=e[s];o?(i.updateStreamedMessage(`${o} `,t),_Demo.populateMessages(t,e,i,n,s+1)):(i.finaliseStreamedMessage(),n())}),70)}};let Demo=_Demo;Demo.URL="deep-chat-demo";class HTTPRequest{static request(t,e,i,n,s=!0){var o,r,a,l,c,u;const h={body:e,headers:null==(o=t.requestSettings)?void 0:o.headers},{body:d,headers:p}=(null==(a=(r=t.deepChat).requestInterceptor)?void 0:a.call(r,h))||h;if((null==(l=t.requestSettings)?void 0:l.url)===Demo.URL)return Demo.request(i,n,t.deepChat.responseInterceptor);let m=!0;fetch((null==(c=t.requestSettings)?void 0:c.url)||t.url||"",{method:(null==(u=t.requestSettings)?void 0:u.method)||"POST",headers:p,body:s?JSON.stringify(d):d}).then((t=>(m=!!t.ok,t))).then((t=>HTTPRequest.processResponseByType(t))).then((async e=>{var s,o;if(!t.extractResultData)return;const r=await t.extractResultData((null==(o=(s=t.deepChat).responseInterceptor)?void 0:o.call(s,e))||e);if(!m)throw e;r.pollingInAnotherRequest||(i.addNewMessage(r,!0,!0),n())})).catch((t=>{RequestUtils.displayError(i,t),n()}))}static requestStream(t,e,i,n,s,o,r=!0){var a,l,c,u,h,d;const p={body:e,headers:null==(a=t.requestSettings)?void 0:a.headers},{body:m,headers:g}=(null==(c=(l=t.deepChat).requestInterceptor)?void 0:c.call(l,p))||p;if((null==(u=t.requestSettings)?void 0:u.url)===Demo.URL)return Demo.requestStream(i,n,s);let v=null;fetchEventSource((null==(h=t.requestSettings)?void 0:h.url)||t.url||"",{method:(null==(d=t.requestSettings)?void 0:d.method)||"POST",headers:g,body:r?JSON.stringify(m):m,openWhenHidden:!0,async onopen(t){if(t.ok)return v=i.addNewStreamedMessage(),n();throw await HTTPRequest.processResponseByType(t)},onmessage(e){var n;if(console.log(e),JSON.stringify(e.data)!==JSON.stringify("[DONE]")){const s=JSON.parse(e.data);null==(n=t.extractResultData)||n.call(t,s).then((t=>{v&&i.updateStreamedMessage(t.text,v)}))}},onerror(t){throw s(),t},onclose(){i.finaliseStreamedMessage(),s()},signal:o.signal}).catch((e=>{var n;null==(n=t.extractResultData)||n.call(t,e).then((()=>{RequestUtils.displayError(i,e)})).catch((t=>{RequestUtils.displayError(i,t)}))}))}static executePollRequest(t,e,i,n,s){console.log("polling"),fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData((null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{HTTPRequest.executePollRequest(t,e,i,n,s)}),l.timeoutMS):(console.log("finished polling"),n.addNewMessage(l,!0,!0),s())})).catch((t=>{RequestUtils.displayError(n,t),s()}))}static poll(t,e,i,n,s=!0){var o,r,a,l,c;const u={body:e,headers:null==(o=t.requestSettings)?void 0:o.headers},{body:h,headers:d}=(null==(a=(r=t.deepChat).requestInterceptor)?void 0:a.call(r,u))||u,p=(null==(l=t.requestSettings)?void 0:l.url)||t.url||"",m={method:(null==(c=t.requestSettings)?void 0:c.method)||"POST",body:s?JSON.stringify(h):h,headers:d};HTTPRequest.executePollRequest(t,p,m,i,n)}static verifyKey(t,e,i,n,s,o,r,a,l){if(""===t)return o(ErrorMessages.INVALID_KEY);r(),fetch(e,{method:n,headers:i,body:l||null}).then((t=>HTTPRequest.processResponseByType(t))).then((e=>{a(e,t,s,o)})).catch((t=>{o(ErrorMessages.CONNECTION_FAILED),console.error(t)}))}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}}class MessageLimitUtils{static getCharacterLimitMessages(t,e){var i;let n=0,s=t.length-1;for(;s>=0;s-=1){const o=null==(i=t[s])?void 0:i.text;if(void 0!==o&&(n+=o.length,n>e)){t[s].text=o.substring(0,o.length-(n-e));break}}return t.slice(Math.max(s,0))}static getRequestMessages(t,e){var i;const n=[];let s=(null==(i=t.files)?void 0:i.length)||0,o=!!t.text;for(let t=e.length-1;t>=0;t-=1){const i=e[t];if(n.push(i),i.file?s-=1:i.text&&(o=!1),0===s&&!o)break}return n}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i,n){return void 0!==i?i>0&&(e=MessageLimitUtils.getMaxMessages(e,i)):e=MessageLimitUtils.getRequestMessages(t,e),void 0===n?e:MessageLimitUtils.getCharacterLimitMessages(e,n)}}class Websocket{static setup(t,e){if(t.requestSettings.url!==Demo.URL){const i="boolean"!=typeof e?e:void 0;t.websocket=Websocket.connect(t.requestSettings.url,i),t.permittedErrorPrefixes=["Connection error"]}}static connect(t,e){return new WebSocket(t||"",e)}static assignListeners(t,e){t.websocket&&(t.websocket.onmessage=async i=>{var n,s;if(t.extractResultData)try{const o=JSON.parse(i.data),r=await t.extractResultData((null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,o))||o);e.addNewMessage(r,!0,!0)}catch(t){RequestUtils.displayError(e,t)}},t.websocket.onerror=t=>{console.error(t),e.addNewErrorMessage("service","Connection error")},t.websocket.onclose=()=>{console.error("Connection closed"),e.isLastMessageError()||e.addNewErrorMessage("service","Connection error")})}static sendWebsocket(t,e,i,n,s,o=!0){var r,a,l,c;const u={body:i,headers:null==(r=e.requestSettings)?void 0:r.headers},{body:h}=(null==(l=(a=e.deepChat).requestInterceptor)?void 0:l.call(a,u))||u,d=o?JSON.stringify(h):h;if((null==(c=e.requestSettings)?void 0:c.url)===Demo.URL)return Demo.request(n,s,e.deepChat.responseInterceptor);t.readyState!==t.OPEN?(console.error("Connection is not open"),n.addNewErrorMessage("service","Connection error")):t.send(JSON.stringify(d))}}var textarea;function decodeEntity(t){return(textarea=textarea||document.createElement("textarea")).innerHTML="&"+t+";",textarea.value}var hasOwn=Object.prototype.hasOwnProperty;function has(t,e){return!!t&&hasOwn.call(t,e)}function assign(t){return[].slice.call(arguments,1).forEach((function(e){if(e){if("object"!=typeof e)throw new TypeError(e+"must be object");Object.keys(e).forEach((function(i){t[i]=e[i]}))}})),t}var UNESCAPE_MD_RE=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function unescapeMd(t){return t.indexOf("\\")<0?t:t.replace(UNESCAPE_MD_RE,"$1")}function isValidEntityCode(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||65535==(65535&t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function fromCodePoint(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var NAMED_ENTITY_RE=/&([a-z#][a-z0-9]{1,31});/gi,DIGITAL_ENTITY_TEST_RE=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function replaceEntityPattern(t,e){var i=0,n=decodeEntity(e);return e!==n?n:35===e.charCodeAt(0)&&DIGITAL_ENTITY_TEST_RE.test(e)&&isValidEntityCode(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?fromCodePoint(i):t}function replaceEntities(t){return t.indexOf("&")<0?t:t.replace(NAMED_ENTITY_RE,replaceEntityPattern)}var HTML_ESCAPE_TEST_RE=/[&<>"]/,HTML_ESCAPE_REPLACE_RE=/[&<>"]/g,HTML_REPLACEMENTS={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function replaceUnsafeChar(t){return HTML_REPLACEMENTS[t]}function escapeHtml(t){return HTML_ESCAPE_TEST_RE.test(t)?t.replace(HTML_ESCAPE_REPLACE_RE,replaceUnsafeChar):t}var rules={};function nextToken(t,e){return++e>=t.length-2?e:"paragraph_open"===t[e].type&&t[e].tight&&"inline"===t[e+1].type&&0===t[e+1].content.length&&"paragraph_close"===t[e+2].type&&t[e+2].tight?nextToken(t,e+2):e}rules.blockquote_open=function(){return"<blockquote>\n"},rules.blockquote_close=function(t,e){return"</blockquote>"+getBreak(t,e)},rules.code=function(t,e){return t[e].block?"<pre><code>"+escapeHtml(t[e].content)+"</code></pre>"+getBreak(t,e):"<code>"+escapeHtml(t[e].content)+"</code>"},rules.fence=function(t,e,i,n,s){var o,r,a=t[e],l="",c=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),has(s.rules.fence_custom,o[0]))return s.rules.fence_custom[o[0]](t,e,i,n,s);l=' class="'+c+escapeHtml(replaceEntities(unescapeMd(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||escapeHtml(a.content))+"</code></pre>"+getBreak(t,e)},rules.fence_custom={},rules.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},rules.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},rules.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+getBreak(t,e)},rules.bullet_list_open=function(){return"<ul>\n"},rules.bullet_list_close=function(t,e){return"</ul>"+getBreak(t,e)},rules.list_item_open=function(){return"<li>"},rules.list_item_close=function(){return"</li>\n"},rules.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},rules.ordered_list_close=function(t,e){return"</ol>"+getBreak(t,e)},rules.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},rules.paragraph_close=function(t,e){var i=!(t[e].tight&&e&&"inline"===t[e-1].type&&!t[e-1].content);return(t[e].tight?"":"</p>")+(i?getBreak(t,e):"")},rules.link_open=function(t,e,i){var n=t[e].title?' title="'+escapeHtml(replaceEntities(t[e].title))+'"':"",s=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+escapeHtml(t[e].href)+'"'+n+s+">"},rules.link_close=function(){return"</a>"},rules.image=function(t,e,i){var n=' src="'+escapeHtml(t[e].src)+'"',s=t[e].title?' title="'+escapeHtml(replaceEntities(t[e].title))+'"':"";return"<img"+n+(' alt="'+(t[e].alt?escapeHtml(replaceEntities(unescapeMd(t[e].alt))):"")+'"')+s+(i.xhtmlOut?" /":"")+">"},rules.table_open=function(){return"<table>\n"},rules.table_close=function(){return"</table>\n"},rules.thead_open=function(){return"<thead>\n"},rules.thead_close=function(){return"</thead>\n"},rules.tbody_open=function(){return"<tbody>\n"},rules.tbody_close=function(){return"</tbody>\n"},rules.tr_open=function(){return"<tr>"},rules.tr_close=function(){return"</tr>\n"},rules.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},rules.th_close=function(){return"</th>"},rules.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},rules.td_close=function(){return"</td>"},rules.strong_open=function(){return"<strong>"},rules.strong_close=function(){return"</strong>"},rules.em_open=function(){return"<em>"},rules.em_close=function(){return"</em>"},rules.del_open=function(){return"<del>"},rules.del_close=function(){return"</del>"},rules.ins_open=function(){return"<ins>"},rules.ins_close=function(){return"</ins>"},rules.mark_open=function(){return"<mark>"},rules.mark_close=function(){return"</mark>"},rules.sub=function(t,e){return"<sub>"+escapeHtml(t[e].content)+"</sub>"},rules.sup=function(t,e){return"<sup>"+escapeHtml(t[e].content)+"</sup>"},rules.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},rules.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},rules.text=function(t,e){return escapeHtml(t[e].content)},rules.htmlblock=function(t,e){return t[e].content},rules.htmltag=function(t,e){return t[e].content},rules.abbr_open=function(t,e){return'<abbr title="'+escapeHtml(replaceEntities(t[e].title))+'">'},rules.abbr_close=function(){return"</abbr>"},rules.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),n="fnref"+i;return t[e].subId>0&&(n+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+n+'">['+i+"]</a></sup>"},rules.footnote_block_open=function(t,e,i){return(i.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},rules.footnote_block_close=function(){return"</ol>\n</section>\n"},rules.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},rules.footnote_close=function(){return"</li>\n"},rules.footnote_anchor=function(t,e){var i="fnref"+Number(t[e].id+1).toString();return t[e].subId>0&&(i+=":"+t[e].subId),' <a href="#'+i+'" class="footnote-backref">↩</a>'},rules.dl_open=function(){return"<dl>\n"},rules.dt_open=function(){return"<dt>"},rules.dd_open=function(){return"<dd>"},rules.dl_close=function(){return"</dl>\n"},rules.dt_close=function(){return"</dt>\n"},rules.dd_close=function(){return"</dd>\n"};var getBreak=rules.getBreak=function(t,e){return(e=nextToken(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function Renderer(){this.rules=assign({},rules),this.getBreak=rules.getBreak}function Ruler(){this.t=[],this.i=null}function block(t){t.inlineMode?t.tokens.push({type:"inline",content:t.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):t.block.parse(t.src,t.options,t.env,t.tokens)}function StateInline(t,e,i,n,s){this.src=t,this.env=n,this.options=i,this.parser=e,this.tokens=s,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0}function parseLinkLabel(t,e){var i,n,s,o=-1,r=t.posMax,a=t.pos,l=t.isInLabel;if(t.isInLabel)return-1;if(t.labelUnmatchedScopes)return t.labelUnmatchedScopes--,-1;for(t.pos=e+1,t.isInLabel=!0,i=1;t.pos<r;){if(91===(s=t.src.charCodeAt(t.pos)))i++;else if(93===s&&0===--i){n=!0;break}t.parser.skipToken(t)}return n?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=l,o}function parseAbbr(t,e,i,n){var s,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=parseLinkLabel(s=new StateInline(t,e,i,n,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&10!==s.src.charCodeAt(r);r++);return l=t.slice(2,o),0===(c=t.slice(o+2,r).trim()).length?-1:(n.abbreviations||(n.abbreviations={}),typeof n.abbreviations[":"+l]>"u"&&(n.abbreviations[":"+l]=c),r)}function abbr(t){var e,i,n,s,o=t.tokens;if(!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("paragraph_open"===o[e-1].type&&"inline"===o[e].type&&"paragraph_close"===o[e+1].type){for(n=o[e].content;n.length&&!((s=parseAbbr(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}function normalizeLink(t){var e=replaceEntities(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function parseLinkDestination(t,e){var i,n,s,o=e,r=t.posMax;if(60===t.src.charCodeAt(e)){for(e++;e<r;){if(10===(i=t.src.charCodeAt(e)))return!1;if(62===i)return s=normalizeLink(unescapeMd(t.src.slice(o+1,e))),!!t.parser.validateLink(s)&&(t.pos=e+1,t.linkContent=s,!0);92===i&&e+1<r?e+=2:e++}return!1}for(n=0;e<r&&!(32===(i=t.src.charCodeAt(e))||i<32||127===i);)if(92===i&&e+1<r)e+=2;else{if(40===i&&++n>1||41===i&&--n<0)break;e++}return!(o===e||(s=unescapeMd(t.src.slice(o,e)),!t.parser.validateLink(s)))&&(t.linkContent=s,t.pos=e,!0)}function parseLinkTitle(t,e){var i,n=e,s=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<s;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=unescapeMd(t.src.slice(n+1,e)),!0;92===i&&e+1<s?e+=2:e++}return!1}function normalizeReference(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function parseReference(t,e,i,n){var s,o,r,a,l,c,u,h,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=parseLinkLabel(s=new StateInline(t,e,i,n,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&(32===(l=s.src.charCodeAt(r))||10===l);r++);if(!parseLinkDestination(s,r))return-1;for(u=s.linkContent,c=r=s.pos,r+=1;r<a&&(32===(l=s.src.charCodeAt(r))||10===l);r++);for(r<a&&c!==r&&parseLinkTitle(s,r)?(h=s.linkContent,r=s.pos):(h="",r=c);r<a&&32===s.src.charCodeAt(r);)r++;return r<a&&10!==s.src.charCodeAt(r)?-1:(d=normalizeReference(t.slice(1,o)),typeof n.references[d]>"u"&&(n.references[d]={title:h,href:u}),r)}function references(t){var e,i,n,s,o=t.tokens;if(t.env.references=t.env.references||{},!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("inline"===o[e].type&&"paragraph_open"===o[e-1].type&&"paragraph_close"===o[e+1].type){for(n=o[e].content;n.length&&!((s=parseReference(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}function inline(t){var e,i,n,s=t.tokens;for(i=0,n=s.length;i<n;i++)"inline"===(e=s[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}function footnote_block(t){var e,i,n,s,o,r,a,l,c,u=0,h=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(h=!0,l=[],c=t.label,!1):"footnote_reference_close"===t.type?(h=!1,d[":"+c]=l,!1):(h&&l.push(t),!h)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:u++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:u++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:u++}),a.push({type:"inline",content:"",level:u,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--u})):r[e].label&&(a=d[":"+r[e].label]),t.tokens=t.tokens.concat(a),o="paragraph_close"===t.tokens[t.tokens.length-1].type?t.tokens.pop():null,s=r[e].count>0?r[e].count:1,n=0;n<s;n++)t.tokens.push({type:"footnote_anchor",id:e,subId:n,level:u});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--u})}t.tokens.push({type:"footnote_block_close",level:--u})}}Renderer.prototype.renderInline=function(t,e,i){for(var n=this.rules,s=t.length,o=0,r="";s--;)r+=n[t[o].type](t,o++,e,i,this);return r},Renderer.prototype.render=function(t,e,i){for(var n=this.rules,s=t.length,o=-1,r="";++o<s;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=n[t[o].type](t,o,e,i,this);return r},Ruler.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},Ruler.prototype.l=function(){var t=this,e=[""];t.t.forEach((function(t){t.enabled&&t.alt.forEach((function(t){e.indexOf(t)<0&&e.push(t)}))})),t.i={},e.forEach((function(e){t.i[e]=[],t.t.forEach((function(i){i.enabled&&(e&&i.alt.indexOf(e)<0||t.i[e].push(i.fn))}))}))},Ruler.prototype.at=function(t,e,i){var n=this.o(t),s=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t[n].fn=e,this.t[n].alt=s.alt||[],this.i=null},Ruler.prototype.before=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},Ruler.prototype.after=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},Ruler.prototype.push=function(t,e,i){var n=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:n.alt||[]}),this.i=null},Ruler.prototype.enable=function(t,e){t=Array.isArray(t)?t:[t],e&&this.t.forEach((function(t){t.enabled=!1})),t.forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!0}),this),this.i=null},Ruler.prototype.disable=function(t){(t=Array.isArray(t)?t:[t]).forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!1}),this),this.i=null},Ruler.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},StateInline.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},StateInline.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},StateInline.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},StateInline.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var PUNCT_CHARS=" \n()[]'\".,!?-";function regEscape(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}function abbr2(t){var e,i,n,s,o,r,a,l,c,u,h,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+PUNCT_CHARS.split("").map(regEscape).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(regEscape).join("|")+")($|["+PUNCT_CHARS.split("").map(regEscape).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),u=t.env.abbrRegExp,i=0,n=p.length;i<n;i++)if("inline"===p[i].type)for(e=(s=p[i].children).length-1;e>=0;e--)if("text"===(o=s[e]).type){for(l=0,r=o.content,u.lastIndex=0,c=o.level,a=[];h=u.exec(r);)u.lastIndex>l&&a.push({type:"text",content:r.slice(l,h.index+h[1].length),level:c}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+h[2]],level:c++}),a.push({type:"text",content:h[2],level:c}),a.push({type:"abbr_close",level:--c}),l=u.lastIndex-h[3].length;a.length&&(l<r.length&&a.push({type:"text",content:r.slice(l),level:c}),p[i].children=s=[].concat(s.slice(0,e),a,s.slice(e+1)))}}var RARE_RE=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,SCOPED_ABBR_RE=/\((c|tm|r|p)\)/gi,SCOPED_ABBR={c:"©",r:"®",p:"§",tm:"™"};function replaceScopedAbbr(t){return t.indexOf("(")<0?t:t.replace(SCOPED_ABBR_RE,(function(t,e){return SCOPED_ABBR[e.toLowerCase()]}))}function replace(t){var e,i,n,s,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(s=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=s[e]).type&&(n=replaceScopedAbbr(n=i.content),RARE_RE.test(n)&&(n=n.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")),i.content=n)}var QUOTE_TEST_RE=/['"]/,QUOTE_RE=/['"]/g,PUNCT_RE=/[-\s()\[\]]/,APOSTROPHE="’";function isLetter(t,e){return!(e<0||e>=t.length)&&!PUNCT_RE.test(t[e])}function replaceAt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}function smartquotes(t){var e,i,n,s,o,r,a,l,c,u,h,d,p,m,g,v,f;if(t.options.typographer)for(f=[],g=t.tokens.length-1;g>=0;g--)if("inline"===t.tokens[g].type)for(v=t.tokens[g].children,f.length=0,e=0;e<v.length;e++)if("text"===(i=v[e]).type&&!QUOTE_TEST_RE.test(i.text)){for(a=v[e].level,p=f.length-1;p>=0&&!(f[p].level<=a);p--);f.length=p+1,o=0,r=(n=i.content).length;t:for(;o<r&&(QUOTE_RE.lastIndex=o,s=QUOTE_RE.exec(n),s);)if(l=!isLetter(n,s.index-1),o=s.index+1,m="'"===s[0],(c=!isLetter(n,o))||l){if(h=!c,d=!l)for(p=f.length-1;p>=0&&(u=f[p],!(f[p].level<a));p--)if(u.single===m&&f[p].level===a){u=f[p],m?(v[u.token].content=replaceAt(v[u.token].content,u.pos,t.options.quotes[2]),i.content=replaceAt(i.content,s.index,t.options.quotes[3])):(v[u.token].content=replaceAt(v[u.token].content,u.pos,t.options.quotes[0]),i.content=replaceAt(i.content,s.index,t.options.quotes[1])),f.length=p;continue t}h?f.push({token:e,pos:s.index,single:m,level:a}):d&&m&&(i.content=replaceAt(i.content,s.index,APOSTROPHE))}else m&&(i.content=replaceAt(i.content,s.index,APOSTROPHE))}}var _rules=[["block",block],["abbr",abbr],["references",references],["inline",inline],["footnote_tail",footnote_block],["abbr2",abbr2],["replacements",replace],["smartquotes",smartquotes]];function Core(){this.options={},this.ruler=new Ruler;for(var t=0;t<_rules.length;t++)this.ruler.push(_rules[t][0],_rules[t][1])}function StateBlock(t,e,i,n,s){var o,r,a,l,c,u,h;for(this.src=t,this.parser=e,this.options=i,this.env=n,this.tokens=s,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",u=0,h=!1,a=l=u=0,c=(r=this.src).length;l<c;l++){if(o=r.charCodeAt(l),!h){if(32===o){u++;continue}h=!0}(10===o||l===c-1)&&(10!==o&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(u),h=!1,u=0,a=l+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function code(t,e,i){var n,s;if(t.tShift[e]-t.blkIndent<4)return!1;for(s=n=e+1;n<i;)if(t.isEmpty(n))n++;else{if(!(t.tShift[n]-t.blkIndent>=4))break;s=++n}return t.line=n,t.tokens.push({type:"code",content:t.getLines(e,s,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}function fences(t,e,i,n){var s,o,r,a,l,c=!1,u=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(u+3>h||126!==(s=t.src.charCodeAt(u))&&96!==s||(l=u,(o=(u=t.skipChars(u,s))-l)<3)||(r=t.src.slice(u,h).trim()).indexOf("`")>=0)return!1;if(n)return!0;for(a=e;!(++a>=i||(u=l=t.bMarks[a]+t.tShift[a],h=t.eMarks[a],u<h&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(u)!==s||t.tShift[a]-t.blkIndent>=4||(u=t.skipChars(u,s),u-l<o||(u=t.skipSpaces(u),u<h)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0}function blockquote(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,g=t.bMarks[e]+t.tShift[e],v=t.eMarks[e];if(g>v||62!==t.src.charCodeAt(g++)||t.level>=t.options.maxNesting)return!1;if(n)return!0;for(32===t.src.charCodeAt(g)&&g++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=g,o=(g=g<v?t.skipSpaces(g):g)>=v,r=[t.tShift[e]],t.tShift[e]=g-t.bMarks[e],h=t.parser.ruler.getRules("blockquote"),s=e+1;s<i&&!((g=t.bMarks[s]+t.tShift[s])>=(v=t.eMarks[s]));s++)if(62!==t.src.charCodeAt(g++)){if(o)break;for(m=!1,d=0,p=h.length;d<p;d++)if(h[d](t,s,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[s]),r.push(t.tShift[s]),t.tShift[s]=-1337}else 32===t.src.charCodeAt(g)&&g++,a.push(t.bMarks[s]),t.bMarks[s]=g,o=(g=g<v?t.skipSpaces(g):g)>=v,r.push(t.tShift[s]),t.tShift[s]=g-t.bMarks[s];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:u=[e,0],level:t.level++}),t.parser.tokenize(t,e,s),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,u[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0}function hr(t,e,i,n){var s,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(s=t.src.charCodeAt(a++))&&45!==s&&95!==s)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==s&&32!==r)return!1;r===s&&o++}return!(o<3)&&(n||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)}function skipBulletListMarker(t,e){var i,n,s;return(n=t.bMarks[e]+t.tShift[e])>=(s=t.eMarks[e])||42!==(i=t.src.charCodeAt(n++))&&45!==i&&43!==i||n<s&&32!==t.src.charCodeAt(n)?-1:n}function skipOrderedListMarker(t,e){var i,n=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];if(n+1>=s||((i=t.src.charCodeAt(n++))<48||i>57))return-1;for(;;){if(n>=s)return-1;if(!((i=t.src.charCodeAt(n++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return n<s&&32!==t.src.charCodeAt(n)?-1:n}function markTightParagraphs(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}function list(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,g,v,f,b,y,w,I,x,S,_,T=!0;if((h=skipOrderedListMarker(t,e))>=0)g=!0;else{if(!((h=skipBulletListMarker(t,e))>=0))return!1;g=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(h-1),n)return!0;for(f=t.tokens.length,g?(u=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(u,h-u-1)),t.tokens.push({type:"ordered_list_open",order:p,lines:y=[e,0],level:t.level++})):t.tokens.push({type:"bullet_list_open",lines:y=[e,0],level:t.level++}),s=e,b=!1,I=t.parser.ruler.getRules("list");s<i&&((d=(v=t.skipSpaces(h))>=t.eMarks[s]?1:v-h)>4&&(d=1),d<1&&(d=1),o=h-t.bMarks[s]+d,t.tokens.push({type:"list_item_open",lines:w=[e,0],level:t.level++}),a=t.blkIndent,l=t.tight,r=t.tShift[e],c=t.parentType,t.tShift[e]=v-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(T=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),s=e=t.line,w[1]=s,v=t.bMarks[e],!(s>=i||t.isEmpty(s)||t.tShift[s]<t.blkIndent));){for(_=!1,x=0,S=I.length;x<S;x++)if(I[x](t,s,i,!0)){_=!0;break}if(_)break;if(g){if((h=skipOrderedListMarker(t,s))<0)break}else if((h=skipBulletListMarker(t,s))<0)break;if(m!==t.src.charCodeAt(h-1))break}return t.tokens.push({type:g?"ordered_list_close":"bullet_list_close",level:--t.level}),y[1]=s,t.line=s,T&&markTightParagraphs(t,f),!0}function footnote(t,e,i,n){var s,o,r,a,l,c=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(c+4>u||91!==t.src.charCodeAt(c)||94!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting)return!1;for(a=c+2;a<u;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===c+2||a+1>=u||58!==t.src.charCodeAt(++a))&&(n||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),l=t.src.slice(c+2,a-2),t.env.footnotes.refs[":"+l]=-1,t.tokens.push({type:"footnote_reference_open",label:l,level:t.level++}),s=t.bMarks[e],o=t.tShift[e],r=t.parentType,t.tShift[e]=t.skipSpaces(a)-a,t.bMarks[e]=a,t.blkIndent+=4,t.parentType="footnote",t.tShift[e]<t.blkIndent&&(t.tShift[e]+=t.blkIndent,t.bMarks[e]-=t.blkIndent),t.parser.tokenize(t,e,i,!0),t.parentType=r,t.blkIndent-=4,t.tShift[e]=o,t.bMarks[e]=s,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)}function heading(t,e,i,n){var s,o,r,a=t.bMarks[e]+t.tShift[e],l=t.eMarks[e];if(a>=l||(35!==(s=t.src.charCodeAt(a))||a>=l))return!1;for(o=1,s=t.src.charCodeAt(++a);35===s&&a<l&&o<=6;)o++,s=t.src.charCodeAt(++a);return!(o>6||a<l&&32!==s)&&(n||(l=t.skipCharsBack(l,32,a),(r=t.skipCharsBack(l,35,a))>a&&32===t.src.charCodeAt(r-1)&&(l=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<l&&t.tokens.push({type:"inline",content:t.src.slice(a,l).trim(),level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"heading_close",hLevel:o,level:t.level})),!0)}function lheading(t,e,i){var n,s,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(s=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],s>=o)||(n=t.src.charCodeAt(s),45!==n&&61!==n)||(s=t.skipChars(s,n),s=t.skipSpaces(s),s<o))&&(s=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===n?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(s,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===n?1:2,level:t.level}),!0)}Core.prototype.process=function(t){var e,i,n;for(e=0,i=(n=this.ruler.getRules("")).length;e<i;e++)n[e](t)},StateBlock.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},StateBlock.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},StateBlock.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},StateBlock.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},StateBlock.prototype.skipCharsBack=function(t,e,i){if(t<=i)return t;for(;t>i;)if(e!==this.src.charCodeAt(--t))return t+1;return t},StateBlock.prototype.getLines=function(t,e,i,n){var s,o,r,a,l,c=t;if(t>=e)return"";if(c+1===e)return o=this.bMarks[c]+Math.min(this.tShift[c],i),r=n?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,r);for(a=new Array(e-t),s=0;c<e;c++,s++)(l=this.tShift[c])>i&&(l=i),l<0&&(l=0),o=this.bMarks[c]+l,r=c+1<e||n?this.eMarks[c]+1:this.eMarks[c],a[s]=this.src.slice(o,r);return a.join("")};var html_blocks={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach((function(t){html_blocks[t]=!0}));var HTML_TAG_OPEN_RE=/^<([a-zA-Z]{1,15})[\s\/>]/,HTML_TAG_CLOSE_RE=/^<\/([a-zA-Z]{1,15})[\s>]/;function isLetter$1(t){var e=32|t;return e>=97&&e<=122}function htmlblock(t,e,i,n){var s,o,r,a=t.bMarks[e],l=t.eMarks[e],c=t.tShift[e];if(a+=c,!t.options.html||c>3||a+2>=l||60!==t.src.charCodeAt(a))return!1;if(33===(s=t.src.charCodeAt(a+1))||63===s){if(n)return!0}else{if(47!==s&&!isLetter$1(s))return!1;if(47===s){if(!(o=t.src.slice(a,l).match(HTML_TAG_CLOSE_RE)))return!1}else if(!(o=t.src.slice(a,l).match(HTML_TAG_OPEN_RE)))return!1;if(!0!==html_blocks[o[1].toLowerCase()])return!1;if(n)return!0}for(r=e+1;r<t.lineMax&&!t.isEmpty(r);)r++;return t.line=r,t.tokens.push({type:"htmlblock",level:t.level,lines:[e,t.line],content:t.getLines(e,r,0,!0)}),!0}function getLine(t,e){var i=t.bMarks[e]+t.blkIndent,n=t.eMarks[e];return t.src.substr(i,n-i)}function table(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m;if(e+2>i||(l=e+1,t.tShift[l]<t.blkIndent)||(r=t.bMarks[l]+t.tShift[l])>=t.eMarks[l]||124!==(s=t.src.charCodeAt(r))&&45!==s&&58!==s||(o=getLine(t,e+1),!/^[-:| ]+$/.test(o))||(c=o.split("|"))<=2)return!1;for(h=[],a=0;a<c.length;a++){if(!(d=c[a].trim())){if(0===a||a===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?h.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?h.push("left"):h.push("")}if(-1===(o=getLine(t,e).trim()).indexOf("|")||(c=o.replace(/^\||\|$/g,"").split("|"),h.length!==c.length))return!1;if(n)return!0;for(t.tokens.push({type:"table_open",lines:p=[e,0],level:t.level++}),t.tokens.push({type:"thead_open",lines:[e,e+1],level:t.level++}),t.tokens.push({type:"tr_open",lines:[e,e+1],level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"th_open",align:h[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:t.level,children:[]}),t.tokens.push({type:"th_close",level:--t.level});for(t.tokens.push({type:"tr_close",level:--t.level}),t.tokens.push({type:"thead_close",level:--t.level}),t.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:t.level++}),l=e+2;l<i&&!(t.tShift[l]<t.blkIndent||(o=getLine(t,l).trim(),-1===o.indexOf("|")));l++){for(c=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"td_open",align:h[a],level:t.level++}),u=c[a].substring(124===c[a].charCodeAt(0)?1:0,124===c[a].charCodeAt(c[a].length-1)?c[a].length-1:c[a].length).trim(),t.tokens.push({type:"inline",content:u,level:t.level,children:[]}),t.tokens.push({type:"td_close",level:--t.level});t.tokens.push({type:"tr_close",level:--t.level})}return t.tokens.push({type:"tbody_close",level:--t.level}),t.tokens.push({type:"table_close",level:--t.level}),p[1]=m[1]=l,t.line=l,!0}function skipMarker(t,e){var i,n,s=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return s>=o||126!==(n=t.src.charCodeAt(s++))&&58!==n||s===(i=t.skipSpaces(s))||i>=o?-1:i}function markTightParagraphs$1(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}function deflist(t,e,i,n){var s,o,r,a,l,c,u,h,d,p,m,g,v,f;if(n)return!(t.ddIndent<0)&&skipMarker(t,e)>=0;if(u=e+1,t.isEmpty(u)&&++u>i||t.tShift[u]<t.blkIndent||(s=skipMarker(t,u))<0||t.level>=t.options.maxNesting)return!1;c=t.tokens.length,t.tokens.push({type:"dl_open",lines:l=[e,0],level:t.level++}),r=e,o=u;t:for(;;){for(f=!0,v=!1,t.tokens.push({type:"dt_open",lines:[r,r],level:t.level++}),t.tokens.push({type:"inline",content:t.getLines(r,r+1,t.blkIndent,!1).trim(),level:t.level+1,lines:[r,r],children:[]}),t.tokens.push({type:"dt_close",level:--t.level});;){if(t.tokens.push({type:"dd_open",lines:a=[u,0],level:t.level++}),g=t.tight,d=t.ddIndent,h=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=s-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||v)&&(f=!1),v=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=g,t.parentType=p,t.blkIndent=h,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=u=t.line,u>=i||t.tShift[u]<t.blkIndent)break t;if((s=skipMarker(t,u))<0)break;o=u}if(u>=i||(r=u,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(s=skipMarker(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),l[1]=u,t.line=u,f&&markTightParagraphs$1(t,c),!0}function paragraph(t,e){var i,n,s,o,r,a,l=e+1;if(l<(i=t.lineMax)&&!t.isEmpty(l))for(a=t.parser.ruler.getRules("paragraph");l<i&&!t.isEmpty(l);l++)if(!(t.tShift[l]-t.blkIndent>3)){for(s=!1,o=0,r=a.length;o<r;o++)if(a[o](t,l,i,!0)){s=!0;break}if(s)break}return n=t.getLines(e,l,t.blkIndent,!1).trim(),t.line=l,n.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:n,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}var _rules$1=[["code",code],["fences",fences,["paragraph","blockquote","list"]],["blockquote",blockquote,["paragraph","blockquote","list"]],["hr",hr,["paragraph","blockquote","list"]],["list",list,["paragraph","blockquote"]],["footnote",footnote,["paragraph"]],["heading",heading,["paragraph","blockquote"]],["lheading",lheading],["htmlblock",htmlblock,["paragraph","blockquote"]],["table",table,["paragraph"]],["deflist",deflist,["paragraph"]],["paragraph",paragraph]];function ParserBlock(){this.ruler=new Ruler;for(var t=0;t<_rules$1.length;t++)this.ruler.push(_rules$1[t][0],_rules$1[t][1],{alt:(_rules$1[t][2]||[]).slice()})}ParserBlock.prototype.tokenize=function(t,e,i){for(var n,s=this.ruler.getRules(""),o=s.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(n=0;n<o&&!s[n](t,r,i,!1);n++);if(t.tight=!a,t.isEmpty(t.line-1)&&(a=!0),(r=t.line)<i&&t.isEmpty(r)){if(a=!0,++r<i&&"list"===t.parentType&&t.isEmpty(r))break;t.line=r}}};var TABS_SCAN_RE=/[\n\t]/g,NEWLINES_RE=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,SPACES_RE=/\u00a0/g;function isTerminatorChar(t){switch(t){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}function text$1(t,e){for(var i=t.pos;i<t.posMax&&!isTerminatorChar(t.src.charCodeAt(i));)i++;return i!==t.pos&&(e||(t.pending+=t.src.slice(t.pos,i)),t.pos=i,!0)}function newline(t,e){var i,n,s=t.pos;if(10!==t.src.charCodeAt(s))return!1;if(i=t.pending.length-1,n=t.posMax,!e)if(i>=0&&32===t.pending.charCodeAt(i))if(i>=1&&32===t.pending.charCodeAt(i-1)){for(var o=i-2;o>=0;o--)if(32!==t.pending.charCodeAt(o)){t.pending=t.pending.substring(0,o+1);break}t.push({type:"hardbreak",level:t.level})}else t.pending=t.pending.slice(0,-1),t.push({type:"softbreak",level:t.level});else t.push({type:"softbreak",level:t.level});for(s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}ParserBlock.prototype.parse=function(t,e,i,n){var s,o=0,r=0;if(!t)return[];(t=(t=t.replace(SPACES_RE," ")).replace(NEWLINES_RE,"\n")).indexOf("\t")>=0&&(t=t.replace(TABS_SCAN_RE,(function(e,i){var n;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(n=" ".slice((i-o-r)%4),r=i-o+1,n)}))),s=new StateBlock(t,this,e,i,n),this.tokenize(s,s.line,s.lineMax)};for(var ESCAPED=[],i=0;i<256;i++)ESCAPED.push(0);function escape(t,e){var i,n=t.pos,s=t.posMax;if(92!==t.src.charCodeAt(n))return!1;if(++n<s){if((i=t.src.charCodeAt(n))<256&&0!==ESCAPED[i])return e||(t.pending+=t.src[n]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}}return e||(t.pending+="\\"),t.pos++,!0}function backticks(t,e){var i,n,s,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,n=t.posMax;a<n&&96===t.src.charCodeAt(a);)a++;for(s=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<n&&96===t.src.charCodeAt(r);)r++;if(r-o===s.length)return e||t.push({type:"code",content:t.src.slice(a,o).replace(/[ \n]+/g," ").trim(),block:!1,level:t.level}),t.pos=r,!0}return e||(t.pending+=s),t.pos+=s.length,!0}function del(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(126!==t.src.charCodeAt(l)||e||l+4>=a||126!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),126===o)||126===r||32===r||10===r)return!1;for(n=l+2;n<a&&126===t.src.charCodeAt(n);)n++;if(n>l+3)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(126===t.src.charCodeAt(t.pos)&&126===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),126!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&126!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"del_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"del_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}function ins(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(43!==t.src.charCodeAt(l)||e||l+4>=a||43!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),43===o)||43===r||32===r||10===r)return!1;for(n=l+2;n<a&&43===t.src.charCodeAt(n);)n++;if(n!==l+2)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(43===t.src.charCodeAt(t.pos)&&43===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),43!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&43!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"ins_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"ins_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}function mark(t,e){var i,n,s,o,r,a=t.posMax,l=t.pos;if(61!==t.src.charCodeAt(l)||e||l+4>=a||61!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),61===o)||61===r||32===r||10===r)return!1;for(n=l+2;n<a&&61===t.src.charCodeAt(n);)n++;if(n!==l+2)return t.pos+=n-l,e||(t.pending+=t.src.slice(l,n)),!0;for(t.pos=l+2,s=1;t.pos+1<a;){if(61===t.src.charCodeAt(t.pos)&&61===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),61!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&61!==o&&(32!==o&&10!==o?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"mark_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"mark_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}function isAlphaNum(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function scanDelims(t,e){var i,n,s,o=e,r=!0,a=!0,l=t.posMax,c=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<l&&t.src.charCodeAt(o)===c;)o++;return o>=l&&(r=!1),(s=o-e)>=4?r=a=!1:((32===(n=o<l?t.src.charCodeAt(o):-1)||10===n)&&(r=!1),(32===i||10===i)&&(a=!1),95===c&&(isAlphaNum(i)&&(r=!1),isAlphaNum(n)&&(a=!1))),{can_open:r,can_close:a,delims:s}}function emphasis(t,e){var i,n,s,o,r,a,l,c=t.posMax,u=t.pos,h=t.src.charCodeAt(u);if(95!==h&&42!==h||e)return!1;if(i=(l=scanDelims(t,u)).delims,!l.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(u,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=u+i,a=[i];t.pos<c;)if(t.src.charCodeAt(t.pos)!==h)t.parser.skipToken(t);else{if(n=(l=scanDelims(t,t.pos)).delims,l.can_close){for(o=a.pop(),r=n;o!==r;){if(r<o){a.push(o-r);break}if(r-=o,0===a.length)break;t.pos+=o,o=a.pop()}if(0===a.length){i=o,s=!0;break}t.pos+=n;continue}l.can_open&&a.push(n),t.pos+=n}return s?(t.posMax=t.pos,t.pos=u+i,e||((2===i||3===i)&&t.push({type:"strong_open",level:t.level++}),(1===i||3===i)&&t.push({type:"em_open",level:t.level++}),t.parser.tokenize(t),(1===i||3===i)&&t.push({type:"em_close",level:--t.level}),(2===i||3===i)&&t.push({type:"strong_close",level:--t.level})),t.pos=t.posMax+i,t.posMax=c,!0):(t.pos=u,!1)}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){ESCAPED[t.charCodeAt(0)]=1}));var UNESCAPE_RE=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function sub(t,e){var i,n,s=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sub",level:t.level,content:n.replace(UNESCAPE_RE,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}var UNESCAPE_RE$1=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function sup(t,e){var i,n,s=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sup",level:t.level,content:n.replace(UNESCAPE_RE$1,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}function links(t,e){var i,n,s,o,r,a,l,c,u=!1,h=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(u=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(n=parseLinkLabel(t,p))<0))return!1;if((a=n+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a>=d)return!1;for(p=a,parseLinkDestination(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&p!==a&&parseLinkTitle(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=h,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=parseLinkLabel(t,a))>=0?s=t.src.slice(p,a++):a=p-1),s||(typeof s>"u"&&(a=n+1),s=t.src.slice(i,n)),!(l=t.env.references[normalizeReference(s)]))return t.pos=h,!1;o=l.href,r=l.title}return e||(t.pos=i,t.posMax=n,u?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,n-i),level:t.level}):(t.push({type:"link_open",href:o,title:r,level:t.level++}),t.linkLevel++,t.parser.tokenize(t),t.linkLevel--,t.push({type:"link_close",level:--t.level}))),t.pos=a,t.posMax=d,!0}function footnote_inline(t,e){var i,n,s,o,r=t.posMax,a=t.pos;return!(a+2>=r||94!==t.src.charCodeAt(a)||91!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting||(i=a+2,n=parseLinkLabel(t,a+1),n<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),s=t.env.footnotes.list.length,t.pos=i,t.posMax=n,t.push({type:"footnote_ref",id:s,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[s]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=n+1,t.posMax=r,!0)}function footnote_ref(t,e){var i,n,s,o,r=t.posMax,a=t.pos;if(a+3>r||!t.env.footnotes||!t.env.footnotes.refs||91!==t.src.charCodeAt(a)||94!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting)return!1;for(n=a+2;n<r;n++){if(32===t.src.charCodeAt(n)||10===t.src.charCodeAt(n))return!1;if(93===t.src.charCodeAt(n))break}return!(n===a+2||n>=r||(n++,i=t.src.slice(a+2,n-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(s=t.env.footnotes.list.length,t.env.footnotes.list[s]={label:i,count:0},t.env.footnotes.refs[":"+i]=s):s=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[s].count,t.env.footnotes.list[s].count++,t.push({type:"footnote_ref",id:s,subId:o,level:t.level})),t.pos=n,t.posMax=r,!0)}var url_schemas=["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"],EMAIL_RE=/^<([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])?)*)>/,AUTOLINK_RE=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function autolink(t,e){var i,n,s,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((n=i.match(AUTOLINK_RE))?!(url_schemas.indexOf(n[1].toLowerCase())<0||(o=n[0].slice(1,-1),r=normalizeLink(o),!t.parser.validateLink(o)))&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=n[0].length,!0):!!(s=i.match(EMAIL_RE))&&(r=normalizeLink("mailto:"+(o=s[0].slice(1,-1))),!!t.parser.validateLink(r)&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=s[0].length,!0)))}function replace$1(t,e){return t=t.source,e=e||"",function i(n,s){return n?(s=s.source||s,t=t.replace(n,s),i):new RegExp(t,e)}}var attr_name=/[a-zA-Z_:][a-zA-Z0-9:._-]*/,unquoted=/[^"'=<>`\x00-\x20]+/,single_quoted=/'[^']*'/,double_quoted=/"[^"]*"/,attr_value=replace$1(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",unquoted)("single_quoted",single_quoted)("double_quoted",double_quoted)(),attribute=replace$1(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",attr_name)("attr_value",attr_value)(),open_tag=replace$1(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",attribute)(),close_tag=/<\/[A-Za-z][A-Za-z0-9]*\s*>/,comment=/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/,processing=/<[?].*?[?]>/,declaration=/<![A-Z]+\s+[^>]*>/,cdata=/<!\[CDATA\[[\s\S]*?\]\]>/,HTML_TAG_RE=replace$1(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",open_tag)("close_tag",close_tag)("comment",comment)("processing",processing)("declaration",declaration)("cdata",cdata)();function isLetter$2(t){var e=32|t;return e>=97&&e<=122}function htmltag(t,e){var i,n,s,o=t.pos;return!(!t.options.html||(s=t.posMax,60!==t.src.charCodeAt(o)||o+2>=s)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!isLetter$2(i))||(n=t.src.slice(o).match(HTML_TAG_RE),!n))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+n[0].length),level:t.level}),t.pos+=n[0].length,!0)}var DIGITAL_RE=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,NAMED_RE=/^&([a-z][a-z0-9]{1,31});/i;function entity(t,e){var i,n,s=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(s))return!1;if(s+1<o)if(35===t.src.charCodeAt(s+1)){if(n=t.src.slice(s).match(DIGITAL_RE))return e||(i="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),t.pending+=isValidEntityCode(i)?fromCodePoint(i):fromCodePoint(65533)),t.pos+=n[0].length,!0}else if(n=t.src.slice(s).match(NAMED_RE)){var r=decodeEntity(n[1]);if(n[1]!==r)return e||(t.pending+=r),t.pos+=n[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}var _rules$2=[["text",text$1],["newline",newline],["escape",escape],["backticks",backticks],["del",del],["ins",ins],["mark",mark],["emphasis",emphasis],["sub",sub],["sup",sup],["links",links],["footnote_inline",footnote_inline],["footnote_ref",footnote_ref],["autolink",autolink],["htmltag",htmltag],["entity",entity]];function ParserInline(){this.ruler=new Ruler;for(var t=0;t<_rules$2.length;t++)this.ruler.push(_rules$2[t][0],_rules$2[t][1]);this.validateLink=validateLink}function validateLink(t){var e=t.trim().toLowerCase();return!(-1!==(e=replaceEntities(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}ParserInline.prototype.skipToken=function(t){var e,i,n=this.ruler.getRules(""),s=n.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<s;e++)if(n[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},ParserInline.prototype.tokenize=function(t){for(var e,i,n=this.ruler.getRules(""),s=n.length,o=t.posMax;t.pos<o;){for(i=0;i<s&&!(e=n[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},ParserInline.prototype.parse=function(t,e,i,n){var s=new StateInline(t,this,e,i,n);this.tokenize(s)};var defaultConfig={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"]}}},fullConfig={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{},block:{},inline:{}}},commonmarkConfig={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"]}}},config={default:defaultConfig,full:fullConfig,commonmark:commonmarkConfig};function StateCore(t,e,i){this.src=e,this.env=i,this.options=t.options,this.tokens=[],this.inlineMode=!1,this.inline=t.inline,this.block=t.block,this.renderer=t.renderer,this.typographer=t.typographer}function Remarkable(t,e){"string"!=typeof t&&(e=t,t="default"),e&&null!=e.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 ParserInline,this.block=new ParserBlock,this.core=new Core,this.renderer=new Renderer,this.ruler=new Ruler,this.options={},this.configure(config[t]),this.set(e||{})}Remarkable.prototype.set=function(t){assign(this.options,t)},Remarkable.prototype.configure=function(t){var e=this;if(!t)throw new Error("Wrong `remarkable` preset, check name/content");t.options&&e.set(t.options),t.components&&Object.keys(t.components).forEach((function(i){t.components[i].rules&&e[i].ruler.enable(t.components[i].rules,!0)}))},Remarkable.prototype.use=function(t,e){return t(this,e),this},Remarkable.prototype.parse=function(t,e){var i=new StateCore(this,t,e);return this.core.process(i),i.tokens},Remarkable.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},Remarkable.prototype.parseInline=function(t,e){var i=new StateCore(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},Remarkable.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class RemarkableConfig{static createNew(){const t=window.hljs;return t?new Remarkable({highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(i,e).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!0}):new Remarkable}}class SetFileTypes{static parseConfig(t,e,i,n){var s;const o={files:e};if("object"==typeof n){const{files:e,request:r,button:a}=n;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(s=e.infoModal)&&s.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||t.headers||t.method||t.url)&&(o.request={headers:(null==r?void 0:r.headers)||t.headers,method:(null==r?void 0:r.method)||t.method,url:(null==r?void 0:r.url)||t.url})}return o}static processMixedFiles(t,e,i){if(i){const n={acceptedFormats:""};t.fileTypes.mixedFiles=SetFileTypes.parseConfig(t.requestSettings,n,e,i)}}static processMicrophone(t,e,i,n){var s,o,r,a,l,c;const u={acceptedFormats:"audio/*",...(null==(s=t.fileTypes.audio)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=SetFileTypes.parseConfig(t.requestSettings,u,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):n||(t.fileTypes.audio=SetFileTypes.parseConfig(t.requestSettings,u,e,i)))}static processAudioConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"audio/*",...(null==n?void 0:n.files)||{}};t.fileTypes.audio=SetFileTypes.parseConfig(t.requestSettings,s,e,i)}static processGifConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/gif",...(null==n?void 0:n.files)||{}};t.fileTypes.gifs=SetFileTypes.parseConfig(t.requestSettings,s,e,i)}static processCamera(t,e,i,n){var s,o,r,a;const l={acceptedFormats:"image/*",...(null==(s=t.fileTypes.images)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=SetFileTypes.parseConfig(t.requestSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):n||(t.fileTypes.images=SetFileTypes.parseConfig(t.requestSettings,l,e,i)))}static processImagesConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/*",...(null==n?void 0:n.files)||{}};t.fileTypes.images=SetFileTypes.parseConfig(t.requestSettings,s,e,i)}static populateDefaultFileIO(t,e){var i,n;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(n=t.files).maxNumberOfFiles??(n.maxNumberOfFiles=1))}static set(t,e,i){SetFileTypes.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),SetFileTypes.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const n=RemarkableConfig.createNew();SetFileTypes.processImagesConfig(e,n,t.images,null==i?void 0:i.images),SetFileTypes.processCamera(e,n,t.camera,t.images),SetFileTypes.processGifConfig(e,n,t.gifs,null==i?void 0:i.gifs),SetFileTypes.processAudioConfig(e,n,t.audio,null==i?void 0:i.audio),SetFileTypes.processMicrophone(e,n,t.microphone,t.audio),SetFileTypes.processMixedFiles(e,n,t.mixedFiles)}}class BaseServiceIO{constructor(t,e,i){var n,s,o,r;this.rawBody={},this.validateConfigKey=!1,this.canSendMessage=BaseServiceIO.canSendMessage,this.requestSettings={},this.fileTypes={},this._isStream=!1,this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(n=t.request)?void 0:n.additionalBodyProps),this._isStream=!!t.stream,this.totalMessagesMaxCharLength=null==(s=null==t?void 0:t.requestBodyLimits)?void 0:s.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,SetFileTypes.set(t,this,e),t.request&&(this.requestSettings=t.request),this.demo&&((r=this.requestSettings).url??(r.url=Demo.URL)),this._directServiceRequiresFiles=!!e&&Object.keys(e).length>0,this.requestSettings.websocket&&Websocket.setup(this,this.requestSettings.websocket)}static canSendMessage(t,e){return!(!t||""===t.trim())||!!(e&&e.length>0)}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const n=new FormData;i.forEach((t=>n.append("files",t))),Object.keys(t).forEach((e=>n.append(e,String(t[e]))));let s=0;return e.forEach((t=>{t.text&&n.append(`message${s+=1}`,JSON.stringify(t))})),n}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.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}callServiceAPI(t,e,i,n,s){var o,r,a,l;const c={messages:e,...this.rawBody};let u=!1;null!=(o=this.requestSettings.headers)&&o["Content-Type"]||((r=this.requestSettings).headers??(r.headers={}),(a=this.requestSettings.headers)["Content-Type"]??(a["Content-Type"]="application/json"),u=!0),this._isStream?HTTPRequest.requestStream(this,c,t,n.onOpen,n.onClose,n.abortStream):HTTPRequest.request(this,c,t,i.onFinish),u&&(null==(l=this.requestSettings.headers)||delete l["Content-Type"])}callApiWithFiles(t,e,i,n,s){const o=BaseServiceIO.createCustomFormDataBody(t,n,s),r=this.requestSettings,a=this.getServiceIOByType(s[0]);this.requestSettings=(null==a?void 0:a.request)||this.requestSettings,HTTPRequest.request(this,o,e,i.onFinish,!1),this.requestSettings=r}callAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=MessageLimitUtils.processMessages(t,e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.websocket){const t={messages:s,...this.rawBody};Websocket.sendWebsocket(this.websocket,this,t,e,i.onFinish,!1)}else t.files&&!this._directServiceRequiresFiles?this.callApiWithFiles(this.rawBody,e,i,s,t.files):this.callServiceAPI(e,s,i,n,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result}}class DirectServiceIO extends BaseServiceIO{constructor(t,e,i,n,s){var o;super(t,s),this.insertKeyPlaceholderText="API Key",this.getKeyLink="",Object.assign(this.rawBody,null==(o=t.request)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,n&&this.setApiKeyProperties(n),this.requestSettings=this.buildRequestSettings(this.key||"",t.request)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateConfigKey=t.validateKeyProperty)}buildRequestSettings(t,e){const i=e??{};return i.headers=this.buildHeadersFunc(t),i}keyAuthenticated(t,e){this.requestSettings=this.buildRequestSettings(e,this.requestSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:n,handleVerificationResult:s,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);HTTPRequest.verifyKey(t,i,a,n,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,s,r)}}class RenderControl{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?RenderControl.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,RenderControl.waitForPropertiesToBeUpdatedBeforeRender(t))}}const _InternalHTML=class extends HTMLElement{constructor(){super(),this._waitingToRender_=!1,this._propUpdated_=!1,Object.keys(_InternalHTML._attributeToProperty_).forEach((t=>{this.constructPropertyAccessors(_InternalHTML._attributeToProperty_[t])}))}static get observedAttributes(){return Object.keys(_InternalHTML._attributes_)||[]}constructPropertyAccessors(t){let e;Object.defineProperty(this,t,{get:function(){return e},set:function(t){e=t,RenderControl.attemptRender(this)}})}attributeChangedCallback(t,e,i){if(console.log(i),console.log(typeof i),e===i)return;const n=_InternalHTML._attributes_[t](i);this[_InternalHTML._attributeToProperty_[t]]=n}onRender(){}};let InternalHTML=_InternalHTML;InternalHTML._attributes_={},InternalHTML._attributeToProperty_={};const NOT_VISIBLE_ICON_STRING='<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',VISIBLE_ICON_STRING='<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n';class SVGIconUtils{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const _VisibilityIcon=class{static changeVisibility(t,e,i,n){n.target.id===_VisibilityIcon.VISIBLE_ICON_ID?(e.style.display="none",i.style.display="block",t.type="password"):(e.style.display="block",i.style.display="none",t.type="text")}static createIconElement(t,e){const i=SVGIconUtils.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(t){const e=document.createElement("div");e.id="visibility-icon-container";const i=_VisibilityIcon.createIconElement(VISIBLE_ICON_STRING,_VisibilityIcon.VISIBLE_ICON_ID);i.style.display="none",e.appendChild(i);const n=_VisibilityIcon.createIconElement(NOT_VISIBLE_ICON_STRING,"not-visible-icon");return e.appendChild(n),e.onclick=_VisibilityIcon.changeVisibility.bind(this,t,i,n),e}};let VisibilityIcon=_VisibilityIcon;VisibilityIcon.VISIBLE_ICON_ID="visible-icon";class InsertKeyView{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t){const e=document.createElement("div");e.id="insert-key-help-text-container";const i=document.createElement("div");i.id="insert-key-help-text-contents";const n=InsertKeyView.createFailText();if(i.appendChild(n),t){const e=InsertKeyView.createHelpLink(t);i.appendChild(e)}const s=InsertKeyView.createCautionText();return i.appendChild(s),e.appendChild(i),{helpTextContainerElement:e,failTextElement:n}}static onFail(t,e,i,n){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=n,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-ring"></div>'}static verifyKey(t,e,i){const n=t.value.trim();i.verifyKey(n,e)}static addVerificationEvents(t,e,i,n,s){const o={onSuccess:n,onFail:InsertKeyView.onFail.bind(this,t,e,i),onLoad:InsertKeyView.onLoad.bind(this,t,e)},r=InsertKeyView.verifyKey.bind(this,t,o,s);e.onclick=r,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===KEYBOARD_KEY.ENTER&&r()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=InsertKeyView.onInputFocus,e.appendChild(i),e}static createContents(t,e){const i=document.createElement("div");i.id="insert-key-contents";const n=InsertKeyView.createInput(e.insertKeyPlaceholderText),s=n.children[0],o=VisibilityIcon.create(s);n.appendChild(o),i.appendChild(n);const r=InsertKeyView.createStartButton(),{helpTextContainerElement:a,failTextElement:l}=InsertKeyView.createHelpTextContainer(e.getKeyLink);return i.appendChild(r),i.appendChild(a),InsertKeyView.addVerificationEvents(s,r,l,t,e),i}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const n=InsertKeyView.createContents(t,e);return i.appendChild(n),i}static render(t,e,i){const n=InsertKeyView.createElements(e,i);t.replaceChildren(n)}}class HuggingFaceUtils{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;Array.isArray(s.error)&&"Error in `parameters`: field required"===s.error[0]?i(e):n(ErrorMessages.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:HuggingFaceUtils.handleVerificationResult}}}const _HuggingFaceIO=class extends DirectServiceIO{constructor(t,e,i,n,s,o){super(t,HuggingFaceUtils.buildKeyVerificationDetails(),HuggingFaceUtils.buildHeaders,s,o),this.insertKeyPlaceholderText="Hugging Face Token",this.getKeyLink="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${_HuggingFaceIO.URL_PREFIX}${i}`,this.textInputPlaceholderText=e,"object"==typeof n&&(n.model&&(this.url=`${_HuggingFaceIO.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return n.options??(n.options={}),n.options.wait_for_model=!0,{inputs:s,...n}}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");const o=this.preprocessBody(this.rawBody,e,s);HTTPRequest.request(this,o,t,i.onFinish)}};let HuggingFaceIO=_HuggingFaceIO;HuggingFaceIO.URL_PREFIX="https://api-inference.huggingface.co/models/";class HuggingFaceFileIO extends HuggingFaceIO{constructor(t,e,i,n,s,o){super(t,e,i,n,s,o),this.isTextInputDisabled=!0,this.canSendMessage=HuggingFaceFileIO.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");HTTPRequest.poll(this,s[0],t,i.onFinish,!1)}}class HuggingFaceAudioClassificationIO extends HuggingFaceFileIO{constructor(t){var e,i,n;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(n=t.directConnection)?void 0:n.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class HuggingFaceImageClassificationIO extends HuggingFaceFileIO{constructor(t){var e,i,n;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(n=t.directConnection)?void 0:n.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const BASE_64_PREFIX="data:image/png;base64,";class StabilityAIUtils{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){t.message?n(ErrorMessages.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:StabilityAIUtils.handleVerificationResult}}}class StabilityAIIO extends DirectServiceIO{constructor(t,e,i,n,s){super(t,e,i,n,s),this.insertKeyPlaceholderText="Stability AI API Key",this.getKeyLink="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class StabilityAIImageToImageUpscaleIO extends StabilityAIIO{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,StabilityAIUtils.buildKeyVerificationDetails(),StabilityAIUtils.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/upscale`),StabilityAIImageToImageUpscaleIO.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=StabilityAIImageToImageUpscaleIO.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}callServiceAPI(t,e,i,n,s){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s)throw new Error("Image was not found");const o=this.createFormDataBody(this.rawBody,s[0]);RequestUtils.temporarilyRemoveHeader(this.requestSettings,HTTPRequest.request.bind(this,this,o,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${BASE_64_PREFIX}${t.base64}`,type:"image"})))}}}class StabilityAIImageToImageMaskingIO extends StabilityAIIO{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,StabilityAIUtils.buildKeyVerificationDetails(),StabilityAIUtils.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/masking`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),void 0!==s.mask_source&&null!==s.mask_source&&(this._maskSource=s.mask_source),StabilityAIImageToImageMaskingIO.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=StabilityAIImageToImageMaskingIO.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,n){const s=new FormData;return s.append("init_image",e),s.append("mask_source",String(this._maskSource)),s.append("mask_image",i),n&&""!==n&&s.append("text_prompts[0][text]",n),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}callServiceAPI(t,e,i,n,s){var o,r;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s||!s[0]||!s[1])throw new Error("Image was not found");const a=null==(r=null==(o=e[e.length-1])?void 0:o.text)?void 0:r.trim(),l=this.createFormDataBody(this.rawBody,s[0],s[1],a);RequestUtils.temporarilyRemoveHeader(this.requestSettings,HTTPRequest.request.bind(this,this,l,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${BASE_64_PREFIX}${t.base64}`,type:"image"})))}}}class HuggingFaceAudioRecognitionIO extends HuggingFaceFileIO{constructor(t){var e,i,n;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(n=t.directConnection)?void 0:n.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class HuggingFaceTextGenerationIO extends HuggingFaceIO{constructor(t){var e,i,n;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].generated_text||""}}}class HuggingFaceQuestionAnswerIO extends HuggingFaceIO{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",s,null==(n=t.directConnection)?void 0:n.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=s.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class HuggingFaceSummarizationIO extends HuggingFaceIO{constructor(t){var e,i,n;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].summary_text||""}}}class HuggingFaceConversationIO extends HuggingFaceIO{constructor(t){var e,i,n;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(n=t.directConnection)?void 0:n.huggingFace),void 0===this.maxMessages&&(this.maxMessages=-1)}processMessages(t){const e=t[t.length-1].text,i=t.slice(0,t.length-1);if(!e)return;return{past_user_inputs:i.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:i.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:e}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.processMessages(e);if(n)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:n.past_user_inputs,generated_responses:n.generated_responses,text:n.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class StabilityAIImageToImageIO extends StabilityAIIO{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,StabilityAIUtils.buildKeyVerificationDetails(),StabilityAIUtils.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI - Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),StabilityAIImageToImageIO.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=StabilityAIImageToImageIO.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const n=new FormData;return n.append("init_image",e),i&&""!==i&&n.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}callServiceAPI(t,e,i,n,s){var o,r;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!s)throw new Error("Image was not found");const a=null==(r=null==(o=e[e.length-1])?void 0:o.text)?void 0:r.trim(),l=this.createFormDataBody(this.rawBody,s[0],a);RequestUtils.temporarilyRemoveHeader(this.requestSettings,HTTPRequest.request.bind(this,this,l,t,i.onFinish),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${BASE_64_PREFIX}${t.base64}`,type:"image"})))}}}class HuggingFaceTranslationIO extends HuggingFaceIO{constructor(t){var e,i,n;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].translation_text||""}}}class StabilityAITextToImageIO extends StabilityAIIO{constructor(t){var e;const{directConnection:i}=t,n=null==i?void 0:i.stabilityAI;super(t,StabilityAIUtils.buildKeyVerificationDetails(),StabilityAIUtils.buildHeaders,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI - Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.textToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),StabilityAITextToImageIO.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=StabilityAITextToImageIO.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n={text:e};return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e[e.length-1].text);HTTPRequest.request(this,s,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${BASE_64_PREFIX}${t.base64}`,type:"image"})))}}}class HuggingFaceFillMaskIO extends HuggingFaceIO{constructor(t){var e,i,n;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(n=t.directConnection)?void 0:n.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].sequence||""}}}class CohereUtils{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,n){"invalid request: prompt must be at least 1 token long"===t.message?i(e):n(ErrorMessages.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:CohereUtils.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class CohereIO extends DirectServiceIO{constructor(t,e,i,n,s){super(t,CohereUtils.buildKeyVerificationDetails(),CohereUtils.buildHeaders,s),this.insertKeyPlaceholderText="Cohere API Key",this.getKeyLink="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,n&&"object"==typeof n&&Object.assign(this.rawBody,n)}}class CohereTextGenerationIO extends CohereIO{constructor(t){var e,i,n;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{prompt:n,...i}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);HTTPRequest.request(this,n,t,i.onFinish)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}class CohereSummarizationIO extends CohereIO{constructor(t){var e,i,n;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{text:n,...i}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);HTTPRequest.request(this,n,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}class AzureUtils{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,n){t.error?n(ErrorMessages.INVALID_KEY):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:AzureUtils.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,n){var s;"401"===(null==(s=t.error)?void 0:s.code)?n(ErrorMessages.INVALID_KEY):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:AzureUtils.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,n){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):n(ErrorMessages.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>AzureUtils.buildTranslationHeaders(t,e),handleVerificationResult:AzureUtils.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class AzureLanguageIO extends DirectServiceIO{constructor(t,e,i,n,s){super(t,AzureUtils.buildLanguageKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class AzureSummarizationIO extends AzureLanguageIO{constructor(t){var e,i,n,s;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(n=t.directConnection)?void 0:n.azure;super(t,AzureUtils.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(s=this.rawBody).language??(s.language="en"),Object.assign(this.rawBody,o),this.url=`${o.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);HTTPRequest.request(this,n,t,i.onFinish),this.messages=t,this.completionsHandlers=i}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),n={method:"GET",headers:null==(e=this.requestSettings)?void 0:e.headers};HTTPRequest.executePollRequest(this,i,n,this.messages,this.completionsHandlers.onFinish)}return{pollingInAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}}const _OpenAIConverseBaseBody=class{static generateDefaultBody(t){return{model:t}}static build(t,e){const i=_OpenAIConverseBaseBody.generateDefaultBody(t);return e&&"boolean"!=typeof e?Object.assign(i,e):i}};let OpenAIConverseBaseBody=_OpenAIConverseBaseBody;OpenAIConverseBaseBody.GPT_COMPLETIONS_DAVINCI_MODEL="text-davinci-003",OpenAIConverseBaseBody.GPT_CHAT_TURBO_MODEL="gpt-3.5-turbo";const _OpenAIUtils=class{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(ErrorMessages.INVALID_KEY):n(ErrorMessages.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:_OpenAIUtils.handleVerificationResult}}};let OpenAIUtils=_OpenAIUtils;OpenAIUtils.CONVERSE_MAX_CHAR_LENGTH=13352,OpenAIUtils.FILE_MAX_CHAR_LENGTH=1e3;class OpenAICompletionsIO extends DirectServiceIO{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,OpenAIUtils.buildKeyVerificationDetails(),OpenAIUtils.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/completions",this.permittedErrorPrefixes=["Incorrect"],this._maxCharLength=OpenAIUtils.CONVERSE_MAX_CHAR_LENGTH,this.full_transaction_max_tokens=4e3,this.numberOfCharsPerToken=3.5;const r=null==(e=null==n?void 0:n.openAI)?void 0:e.completions;null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit),"object"==typeof r&&Object.assign(this.rawBody,r),(i=this.rawBody).model??(i.model=OpenAIConverseBaseBody.GPT_COMPLETIONS_DAVINCI_MODEL)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(!n)return;const s=n.substring(0,this._maxCharLength),o=i.max_tokens||this.full_transaction_max_tokens-s.length/this.numberOfCharsPerToken;return{prompt:s,max_tokens:Math.floor(o),...i}}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e);this._isStream||s.stream?(s.stream=!0,HTTPRequest.requestStream(this,s,t,n.onOpen,n.onClose,n.abortStream)):HTTPRequest.request(this,s,t,i.onFinish)}async extractResultData(t){var e;if(t.error)throw t.error.message;return{text:(null==(e=t.choices[0])?void 0:e.text)||""}}}class AssemblyAIUtils{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},n=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let s;for(;!s;){const t=await(await fetch(n,{headers:i})).json();if("completed"===t.status)s=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return s}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(ErrorMessages.INVALID_KEY):n(ErrorMessages.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:AssemblyAIUtils.handleVerificationResult}}}class AssemblyAIAudioIO extends DirectServiceIO{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,AssemblyAIUtils.buildKeyVerificationDetails(),AssemblyAIUtils.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.getKeyLink="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=AssemblyAIAudioIO.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");HTTPRequest.request(this,s[0],t,i.onFinish,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const n=null==(i=null==(e=this.requestSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await AssemblyAIUtils.poll(n,t.upload_url)).text}}}class AzureSpeechIO extends DirectServiceIO{constructor(t,e,i,n,s){super(t,AzureUtils.buildSpeechKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const _AzureTextToSpeechIO=class extends AzureSpeechIO{constructor(t){var e,i,n,s,o,r;const a=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.textToSpeech,l=null==(n=t.directConnection)?void 0:n.azure;super(t,AzureUtils.buildTextToSpeechHeaders.bind({},(null==a?void 0:a.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),a.region,l),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${_AzureTextToSpeechIO.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",Object.assign(this.rawBody,a),(s=this.rawBody).lang??(s.lang="en-US"),(o=this.rawBody).name??(o.name="en-US-JennyNeural"),(r=this.rawBody).gender??(r.gender="Female"),this.url=`https://${a.region}.tts.speech.microsoft.com/cognitiveservices/v1`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);HTTPRequest.request(this,n,t,i.onFinish,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};let AzureTextToSpeechIO=_AzureTextToSpeechIO;AzureTextToSpeechIO.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";const _AzureSpeechToTextIO=class extends AzureSpeechIO{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.speechToText,o=null==(n=t.directConnection)?void 0:n.azure;super(t,AzureUtils.buildSpeechToTextHeaders,s.region,o,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${_AzureSpeechToTextIO.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.canSendMessage=_AzureSpeechToTextIO.canFileSendMessage;const r=s.lang||"en-US";this.url=`https://${s.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${r}&format=detailed`,this.recordAudio=void 0}static canFileSendMessage(t,e){return!(null==e||!e[0])}callServiceAPI(t,e,i,n,s){var o,r;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");null!=(r=this.requestSettings)&&r.headers&&(this.requestSettings.headers["Content-Type"]=s[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),HTTPRequest.request(this,s[0],t,i.onFinish,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};let AzureSpeechToTextIO=_AzureSpeechToTextIO;AzureSpeechToTextIO.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";class AzureTranslationIO extends DirectServiceIO{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(n=t.directConnection)?void 0:n.azure;super(t,AzureUtils.buildTranslationKeyVerificationDetails(s.region),AzureUtils.buildTranslationHeaders.bind({},null==s?void 0:s.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${s.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(e);HTTPRequest.request(this,n,t,i.onFinish)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}const _OpenAIImagesIO=class extends DirectServiceIO{constructor(t){var e;const{directConnection:i,textInput:n}=t,s=null==i?void 0:i.openAI;super(t,OpenAIUtils.buildKeyVerificationDetails(),OpenAIUtils.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI Images</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"],this._maxCharLength=OpenAIUtils.FILE_MAX_CHAR_LENGTH,null!=n&&n.characterLimit&&(this._maxCharLength=n.characterLimit);const o=null==(e=null==i?void 0:i.openAI)?void 0:e.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=_OpenAIImagesIO.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const n=new FormData;return n.append("image",e),i&&n.append("mask",i),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),n}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));if(e&&""!==e){const t=e.substring(0,this._maxCharLength);i.prompt=t}return i}callApiWithImage(t,e,i,n){var s,o;let r;const a=null==(o=null==(s=e[e.length-1])?void 0:s.text)?void 0:o.trim();if(n[1]||a&&""!==a){this.url=_OpenAIImagesIO.IMAGE_EDIT_URL;const t=this.preprocessBody(this.rawBody,a);r=_OpenAIImagesIO.createFormDataBody(t,n[0],n[1])}else this.url=_OpenAIImagesIO.IMAGE_VARIATIONS_URL,r=_OpenAIImagesIO.createFormDataBody(this.rawBody,n[0]);RequestUtils.temporarilyRemoveHeader(this.requestSettings,HTTPRequest.request.bind(this,this,r,t,i.onFinish),!1)}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(t,e,i,s);else{if(!this.requestSettings)throw new Error("Request settings have not been set up");this.url=_OpenAIImagesIO.IMAGE_GENERATION_URL;const n=this.preprocessBody(this.rawBody,e[e.length-1].text);HTTPRequest.request(this,n,t,i.onFinish)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${BASE_64_PREFIX}${t.b64_json}`,type:"image"}))}}};let OpenAIImagesIO=_OpenAIImagesIO;OpenAIImagesIO.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",OpenAIImagesIO.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",OpenAIImagesIO.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";const _OpenAIAudioIO=class extends DirectServiceIO{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,OpenAIUtils.buildKeyVerificationDetails(),OpenAIUtils.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/api-reference/audio/create">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this._maxCharLength=OpenAIUtils.FILE_MAX_CHAR_LENGTH,this._service_url=_OpenAIAudioIO.AUDIO_TRANSCRIPTIONS_URL,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const r=null==(e=null==n?void 0:n.openAI)?void 0:e.audio;"object"==typeof r&&(this.processConfig(r),_OpenAIAudioIO.cleanConfig(r),Object.assign(this.rawBody,r)),(i=this.rawBody).model??(i.model=_OpenAIAudioIO.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=_OpenAIAudioIO.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(t){null!=t&&t.type&&"translation"===t.type&&(this._service_url=_OpenAIAudioIO.AUDIO_TRANSLATIONS_URL,delete t.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e,i){var n,s;const o=JSON.parse(JSON.stringify(t)),r=null==(s=null==(n=e[e.length-i.length+1])?void 0:n.text)?void 0:s.trim();if(r&&""!==r){const t=r.substring(0,this._maxCharLength);o.prompt=t}return o}callServiceAPI(t,e,i,n,s){var o;if(null==(o=this.requestSettings)||!o.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.requestSettings.url||this._service_url;const r=this.preprocessBody(this.rawBody,e,s),a=_OpenAIAudioIO.createFormDataBody(r,s[0]);RequestUtils.temporarilyRemoveHeader(this.requestSettings,HTTPRequest.request.bind(this,this,a,t,i.onFinish),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};let OpenAIAudioIO=_OpenAIAudioIO;OpenAIAudioIO.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",OpenAIAudioIO.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",OpenAIAudioIO.DEFAULT_MODEL="whisper-1";class OpenAIChatIO extends DirectServiceIO{constructor(t){var e,i,n,s;const o=null==(e=t.directConnection)?void 0:e.openAI;super(t,OpenAIUtils.buildKeyVerificationDetails(),OpenAIUtils.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this._systemMessage=OpenAIChatIO.generateSystemMessage("You are a helpful assistant.");const r=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.chat;"object"==typeof r&&(r.systemPrompt&&(this._systemMessage=OpenAIChatIO.generateSystemMessage(r.systemPrompt)),this.cleanConfig(r),Object.assign(this.rawBody,r)),void 0===this.maxMessages&&(this.maxMessages=-1),(s=this.rawBody).model??(s.model=OpenAIConverseBaseBody.GPT_CHAT_TURBO_MODEL)}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.systemPrompt}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.totalMessagesMaxCharLength||OpenAIUtils.CONVERSE_MAX_CHAR_LENGTH,s=MessageLimitUtils.getCharacterLimitMessages(e,n-this._systemMessage.content.length).map((t=>({content:t.text,role:"ai"===t.role?"assistant":"user"})));return i.messages=[this._systemMessage,...s],i}callServiceAPI(t,e,i,n){if(!this.requestSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e);this._isStream||s.stream?(s.stream=!0,HTTPRequest.requestStream(this,s,t,n.onOpen,n.onClose,n.abortStream)):HTTPRequest.request(this,s,t,i.onFinish)}async extractResultData(t){if(t.error)throw t.error.message;return t.choices[0].delta?{text:t.choices[0].delta.content||""}:t.choices[0].message?{text:t.choices[0].message.content}:{text:""}}}class CohereChatIO extends CohereIO{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,null==(n=t.directConnection)?void 0:n.cohere),this.username="USER","object"==typeof s&&(s.user_name&&(this.username=s.user_name),this.cleanConfig(s),Object.assign(this.rawBody,s)),void 0===this.maxMessages&&(this.maxMessages=-1)}cleanConfig(t){delete t.user_name}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return i.query=e[e.length-1].text,i.chat_history=e.slice(0,e.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":this.username}))),i}callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e);HTTPRequest.request(this,n,t,i.onFinish)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class ServiceIOFactory{static create(t){const{directConnection:e}=t;if(e){if(e.openAI)return e.openAI.images?new OpenAIImagesIO(t):e.openAI.audio?new OpenAIAudioIO(t):e.openAI.completions?new OpenAICompletionsIO(t):new OpenAIChatIO(t);if(e.assemblyAI)return new AssemblyAIAudioIO(t);if(e.cohere)return e.cohere.chat?new CohereChatIO(t):e.cohere.summarization?new CohereSummarizationIO(t):new CohereTextGenerationIO(t);if(e.huggingFace)return e.huggingFace.textGeneration?new HuggingFaceTextGenerationIO(t):e.huggingFace.summarization?new HuggingFaceSummarizationIO(t):e.huggingFace.translation?new HuggingFaceTranslationIO(t):e.huggingFace.fillMask?new HuggingFaceFillMaskIO(t):e.huggingFace.questionAnswer?new HuggingFaceQuestionAnswerIO(t):e.huggingFace.audioSpeechRecognition?new HuggingFaceAudioRecognitionIO(t):e.huggingFace.audioClassification?new HuggingFaceAudioClassificationIO(t):e.huggingFace.imageClassification?new HuggingFaceImageClassificationIO(t):new HuggingFaceConversationIO(t);if(e.azure){if(e.azure.speechToText)return new AzureSpeechToTextIO(t);if(e.azure.textToSpeech)return new AzureTextToSpeechIO(t);if(e.azure.summarization)return new AzureSummarizationIO(t);if(e.azure.translation)return new AzureTranslationIO(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new StabilityAIImageToImageIO(t):e.stabilityAI.imageToImageUpscale?new StabilityAIImageToImageUpscaleIO(t):e.stabilityAI.imageToImageMasking?new StabilityAIImageToImageMaskingIO(t):new StabilityAITextToImageIO(t);if(e.demo)return new BaseServiceIO(t,void 0,e.demo)}return new BaseServiceIO(t)}}const _GoogleFont=class{static appendStyleSheetToHead(){const t=document.getElementsByTagName("head")[0];if(!Array.from(t.getElementsByTagName("link")).some((t=>t.getAttribute("href")===_GoogleFont.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=_GoogleFont.FONT_URL,t.appendChild(e)}}};let GoogleFont=_GoogleFont;GoogleFont.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap";class TypeConverters{}function Property(t){return function(e,i){Object.defineProperty(e,i,{});const n=e.constructor,s=i.toLocaleLowerCase();n._attributes_[s]=TypeConverters.attibutes[t],n._attributeToProperty_[s]=i}}TypeConverters.attibutes={string:t=>t,number:t=>parseFloat(t),boolean:t=>"true"===t,object:t=>JSON.parse(t),array:t=>JSON.parse(t),function:value=>eval(value)};class FireEvents{static onNewMessage(t,e,i){const n=JSON.parse(JSON.stringify({message:e,isInitial:i}));t.onNewMessage(n),t.dispatchEvent(new CustomEvent("new-message",{detail:n}))}static onRender(t){t.onComponentRender(),t.dispatchEvent(new CustomEvent("render"))}}const _ElementUtils=class{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(t){const e=t.scrollHeight,i=t.clientHeight;return t.scrollTop>=e-i-_ElementUtils.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}};let ElementUtils=_ElementUtils;ElementUtils.CODE_SNIPPET_GENERATION_JUMP=.5;const _TextToSpeech=class{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(t,e){const i={};setTimeout((()=>{if("object"==typeof t&&(t.lang&&(i.lang=t.lang),t.pitch&&(i.pitch=t.pitch),t.rate&&(i.rate=t.rate),t.volume&&(i.volume=t.volume),t.voiceName)){const e=window.speechSynthesis.getVoices().find((e=>{var i;return e.name.toLocaleLowerCase()===(null==(i=t.voiceName)?void 0:i.toLocaleLowerCase())}));e&&(i.voice=e)}e(i)}),_TextToSpeech.LOAD_VOICES_MS)}};let TextToSpeech=_TextToSpeech;TextToSpeech.LOAD_VOICES_MS=200;class LoadingMessageDotsStyle{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static set(t,e){var i,n,s,o;if(null!=(n=null==(i=null==e?void 0:e.loading)?void 0:i.bubble)&&n.color){const i=LoadingMessageDotsStyle.colorToHex(null==(o=null==(s=null==e?void 0:e.loading)?void 0:s.bubble)?void 0:o.color);t.style.setProperty("--message-dots-color",i),t.style.setProperty("--message-dots-color-fade",`${i}33`)}else t.style.setProperty("--message-dots-color","#848484"),t.style.setProperty("--message-dots-color-fade","#55555533")}}class MessageStyleUtils{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],n="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(n.style,i.media)}}static applySideStyles(t,e,i,n){n&&(MessageStyleUtils.applyCustomStylesToElements(t,i,n.shared),e?MessageStyleUtils.applyCustomStylesToElements(t,i,n.ai):MessageStyleUtils.applyCustomStylesToElements(t,i,n.user))}static isMessageSideStyles(t){return!!(t.ai||t.shared||t.user)}static applyCustomStyles(t,e,i,n,s){var o;s&&t.default!==s?MessageStyleUtils.isMessageSideStyles(s)?(MessageStyleUtils.applySideStyles(e,i,n,t.default),MessageStyleUtils.applySideStyles(e,i,n,s)):(MessageStyleUtils.applyCustomStylesToElements(e,n,null==(o=t.default)?void 0:o.shared),MessageStyleUtils.applyCustomStylesToElements(e,n,s)):MessageStyleUtils.applySideStyles(e,i,n,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,n={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,s,o,r;n.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",n.innerContainer[t]=(null==(s=i.innerContainer)?void 0:s[t])||"",n.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",n.media[t]=(null==(r=i.media)?void 0:r[t])||""})),n}}class IntroPanel{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=IntroPanel.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=IntroPanel.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}}const _FileMessageUtils=class{static updateMessages(t,e,i,n,s,o=!1){var r;t.applyCustomStyles(e,s,!0,null==(r=t.messageStyles)?void 0:r[n]),t.elementRef.scrollTop=t.elementRef.scrollHeight;const a=Messages.createMessageContent(s,void 0,i);t.messages.push(a),t.sendClientUpdate(a,o)}static wrapInLink(t,e){const i=document.createElement("a");return i.href=e,i.target="_blank",i.appendChild(t),i}static processContent(t,e){return!e||e.startsWith("data")?t:_FileMessageUtils.wrapInLink(t,e)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(t,e){if(t.startsWith("data"))_FileMessageUtils.waitToLoadThenScroll(e);else try{fetch(t,{mode:"no-cors"}).catch((()=>{})).finally((()=>{_FileMessageUtils.waitToLoadThenScroll(e)}))}catch{e.scrollTop=e.scrollHeight}}};let FileMessageUtils=_FileMessageUtils;FileMessageUtils.DEFAULT_FILE_NAME="file";const FILE_ICON_STRING='<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>';class FileMessages{static createImage(t,e){const i=new Image;return i.src=t.src,FileMessageUtils.scrollDownOnImageLoad(i.src,e),FileMessageUtils.processContent(i,i.src)}static async addNewImageMessage(t,e,i,n=!1){const s=FileMessages.createImage(e,t.elementRef),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(s),o.bubbleElement.classList.add("image-message"),t.elementRef.appendChild(o.outerContainer),FileMessageUtils.updateMessages(t,o,e,"image",i,n)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,Browser$1.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e?"audio-player-safari-left":"audio-player-safari-right")),i}static addNewAudioMessage(t,e,i,n=!1){const s=FileMessages.createAudioElement(e,i),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(s),o.bubbleElement.classList.add("audio-message"),t.elementRef.appendChild(o.outerContainer),FileMessageUtils.updateMessages(t,o,e,"audio",i,n)}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const n=SVGIconUtils.createSVGElement(FILE_ICON_STRING);n.classList.add("any-file-message-icon"),i.appendChild(n);const s=document.createElement("div");return s.classList.add("any-file-message-text"),s.textContent=t.name||FileMessageUtils.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(s),FileMessageUtils.processContent(e,t.src)}static addNewAnyFileMessage(t,e,i,n=!1){const s=t.createNewMessageElement("",i),o=FileMessages.createAnyFile(e);s.bubbleElement.classList.add("any-file-message-bubble"),s.bubbleElement.appendChild(o),t.elementRef.appendChild(s.outerContainer),FileMessageUtils.updateMessages(t,s,e,"file",i,n)}}const aiLogoUrl="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8c3ZnIGZpbGw9IiMwMDAwMDAiIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIAoJCXZpZXdCb3g9IjAgMCAzMiAzMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8cGF0aCBkPSJNMjMsMzAuMzZIOWMtMi40MDQsMC00LjM2LTEuOTU2LTQuMzYtNC4zNlYxNWMwLTIuNDA0LDEuOTU2LTQuMzYsNC4zNi00LjM2aDMuNjU5CgkJYzAuMTY3LTEuNTY2LDEuNDE1LTIuODEzLDIuOTgxLTIuOTgxVjUuMzMzYy0xLjEzMS0wLjE3NC0yLTEuMTU0LTItMi4zMzNjMC0xLjMwMSwxLjA1OS0yLjM2LDIuMzYtMi4zNgoJCWMxLjMwMiwwLDIuMzYsMS4wNTksMi4zNiwyLjM2YzAsMS4xNzktMC44NjksMi4xNTktMiwyLjMzM1Y3LjY2YzEuNTY2LDAuMTY3LDIuODE0LDEuNDE1LDIuOTgxLDIuOTgxSDIzCgkJYzIuNDA0LDAsNC4zNiwxLjk1Niw0LjM2LDQuMzZ2MTFDMjcuMzYsMjguNDA0LDI1LjQwNCwzMC4zNiwyMywzMC4zNnogTTksMTEuMzZjLTIuMDA3LDAtMy42NCwxLjYzMy0zLjY0LDMuNjR2MTEKCQljMCwyLjAwNywxLjYzMywzLjY0LDMuNjQsMy42NGgxNGMyLjAwNywwLDMuNjQtMS42MzMsMy42NC0zLjY0VjE1YzAtMi4wMDctMS42MzMtMy42NC0zLjY0LTMuNjRIOXogTTEzLjM4NCwxMC42NGg1LjIzMQoJCUMxOC40MzksOS4zNTQsMTcuMzM0LDguMzYsMTYsOC4zNkMxNC42NjcsOC4zNiwxMy41NjEsOS4zNTQsMTMuMzg0LDEwLjY0eiBNMTYsMS4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NAoJCVMxNS4wOTYsNC42NCwxNiw0LjY0YzAuOTA0LDAsMS42NC0wLjczNiwxLjY0LTEuNjRTMTYuOTA0LDEuMzYsMTYsMS4zNnogTTIwLDI3LjM2aC04Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2CgkJczEuMDU5LTIuMzYsMi4zNi0yLjM2aDhjMS4zMDIsMCwyLjM2LDEuMDU5LDIuMzYsMi4zNlMyMS4zMDIsMjcuMzYsMjAsMjcuMzZ6IE0xMiwyMy4zNmMtMC45MDQsMC0xLjY0LDAuNzM1LTEuNjQsMS42NAoJCXMwLjczNiwxLjY0LDEuNjQsMS42NGg4YzAuOTA0LDAsMS42NC0wLjczNSwxLjY0LTEuNjRzLTAuNzM1LTEuNjQtMS42NC0xLjY0SDEyeiBNMzEsMjMuODZoLTJjLTAuMTk5LDAtMC4zNi0wLjE2MS0wLjM2LTAuMzZWMTUKCQljMC0wLjE5OSwwLjE2MS0wLjM2LDAuMzYtMC4zNmgyYzAuMTk5LDAsMC4zNiwwLjE2MSwwLjM2LDAuMzZ2OC41QzMxLjM2LDIzLjY5OSwzMS4xOTksMjMuODYsMzEsMjMuODZ6IE0yOS4zNiwyMy4xNGgxLjI3OXYtNy43OAoJCUgyOS4zNlYyMy4xNHogTTMsMjMuODZIMWMtMC4xOTksMC0wLjM2LTAuMTYxLTAuMzYtMC4zNlYxNWMwLTAuMTk5LDAuMTYxLTAuMzYsMC4zNi0wLjM2aDJjMC4xOTksMCwwLjM2LDAuMTYxLDAuMzYsMC4zNnY4LjUKCQlDMy4zNiwyMy42OTksMy4xOTksMjMuODYsMywyMy44NnogTTEuMzYsMjMuMTRoMS4yOHYtNy43OEgxLjM2VjIzLjE0eiBNMjAsMjAuMzZjLTEuMzAyLDAtMi4zNi0xLjA1OS0yLjM2LTIuMzYKCQlzMS4wNTktMi4zNiwyLjM2LTIuMzZzMi4zNiwxLjA1OSwyLjM2LDIuMzZDMjIuMzYsMTkuMzAyLDIxLjMwMiwyMC4zNiwyMCwyMC4zNnogTTIwLDE2LjM2Yy0wLjkwNCwwLTEuNjQsMC43MzYtMS42NCwxLjY0CgkJczAuNzM1LDEuNjQsMS42NCwxLjY0czEuNjQtMC43MzUsMS42NC0xLjY0UzIwLjkwNCwxNi4zNiwyMCwxNi4zNnogTTEyLDIwLjM2Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2czEuMDU5LTIuMzYsMi4zNi0yLjM2CgkJczIuMzYsMS4wNTksMi4zNiwyLjM2QzE0LjM2LDE5LjMwMiwxMy4zMDEsMjAuMzYsMTIsMjAuMzZ6IE0xMiwxNi4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NHMwLjczNiwxLjY0LDEuNjQsMS42NAoJCXMxLjY0LTAuNzM1LDEuNjQtMS42NFMxMi45MDQsMTYuMzYsMTIsMTYuMzZ6Ii8+Cgk8cmVjdCBzdHlsZT0iZmlsbDpub25lOyIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIi8+Cjwvc3ZnPg==",avatarUrl="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==";class AvatarEl{static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(t,e,i,n){var s,o,r;null!=(s=i.default)&&s.styles&&AvatarEl.applyCustomStylesToElements(t,e,i.default.styles),n?null!=(o=i.ai)&&o.styles&&AvatarEl.applyCustomStylesToElements(t,e,i.ai.styles):null!=(r=i.user)&&r.styles&&AvatarEl.applyCustomStylesToElements(t,e,i.user.styles)}static createAvatar(t,e){var i,n,s,o;const r=document.createElement("img");r.src=t?(null==(i=null==e?void 0:e.ai)?void 0:i.src)||(null==(n=null==e?void 0:e.default)?void 0:n.src)||aiLogoUrl:(null==(s=null==e?void 0:e.user)?void 0:s.src)||(null==(o=null==e?void 0:e.default)?void 0:o.src)||avatarUrl,r.classList.add("avatar");const a=document.createElement("div");return a.classList.add("avatar-container"),a.appendChild(r),e&&AvatarEl.applyCustomStyles(a,r,e,t),a}static getPosition(t,e){var i,n,s,o,r,a;let l=t?null==(n=null==(i=null==e?void 0:e.ai)?void 0:i.styles)?void 0:n.position:null==(o=null==(s=null==e?void 0:e.user)?void 0:s.styles)?void 0:o.position;return l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t?"left":"right"),l}static add(t,e,i){const n="boolean"==typeof i?void 0:i,s=AvatarEl.createAvatar(e,n),o=AvatarEl.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class Name{static getPosition(t,e){var i,n,s;let o=t?null==(i=null==e?void 0:e.ai)?void 0:i.position:null==(n=null==e?void 0:e.user)?void 0:n.position;return o||(o=null==(s=null==e?void 0:e.default)?void 0:s.position),o||(o=t?"left":"right"),o}static applyStyle(t,e,i){var n,s,o;Object.assign(t.style,null==(n=i.default)?void 0:n.style,e?null==(s=i.ai)?void 0:s.style:null==(o=i.user)?void 0:o.style)}static getNameText(t,e){var i,n,s,o;return t?(null==(i=e.ai)?void 0:i.text)||(null==(n=e.default)?void 0:n.text)||"AI":(null==(s=e.user)?void 0:s.text)||(null==(o=e.default)?void 0:o.text)||"User"}static createName(t,e){const i=document.createElement("div");return i.classList.add("name"),i.textContent=Name.getNameText(t,e),Name.applyStyle(i,t,e),i}static add(t,e,i){const n="boolean"==typeof i?{}:i,s=Name.createName(e,n),o=Name.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class Messages{constructor(t,e,i){var n,s;this._messageElementRefs=[],this._streamedText="",this.messages=[];const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._remarkable=RemarkableConfig.createNew(),this.elementRef=Messages.createContainerElement(),this.messageStyles=t.messageStyles,this._avatars=t.avatars,this._names=t.names,this._errorMessageOverrides=null==(n=t.errorMessages)?void 0:n.overrides,this._onNewMessage=FireEvents.onNewMessage.bind(this,t),this._displayLoadingMessage=Messages.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.populateIntroPanel(i,r,t.introPanelStyle),t.introMessage&&this.addIntroductoryMessage(t.introMessage),t.initialMessages&&this.populateInitialMessages(t.initialMessages),this.displayServiceErrorMessages=null==(s=t.errorMessages)?void 0:s.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.refreshMessages=this.refreshTextMessages.bind(this),a&&this.prepareDemo(a),t.textToSpeech&&TextToSpeech.processConfig(t.textToSpeech,(t=>{this._textToSpeech=t}))}static getDisplayLoadingMessage(t,e){return!e.websocket&&(t.displayLoadingBubble??!0)}prepareDemo(t){"object"==typeof t&&(t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),t.displayLoadingBubble&&this.addLoadingMessage())}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addIntroductoryMessage(t){var e;const i=this.createAndAppendNewMessageElement(t,!0);this.applyCustomStyles(i,!0,!1,null==(e=this.messageStyles)?void 0:e.intro)}populateInitialMessages(t){t.forEach((t=>{t.text?this.addNewMessage({text:t.text},"ai"===t.role,!0,!0):t.file&&this.addNewMessage({files:[t.file]},"ai"===t.role,!0,!0)})),setTimeout((()=>this.elementRef.scrollTop=this.elementRef.scrollHeight))}applyCustomStyles(t,e,i,n){this.messageStyles&&MessageStyleUtils.applyCustomStyles(this.messageStyles,t,e,i,n)}addInnerContainerElements(t,e,i){return t.classList.add("message-bubble",i?"ai-message-text":"user-message-text"),t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e),this._avatars&&AvatarEl.add(t,i,this._avatars),this._names&&Name.add(t,i,this._names),{bubbleElement:t}}static createMessageContent(t,e,i){return i?{role:t?"ai":"user",file:i}:{role:t?"ai":"user",text:e||""}}static createBaseElements(){const t=document.createElement("div"),e=document.createElement("div");e.classList.add("inner-message-container"),t.appendChild(e),t.classList.add("outer-message-container");const i=document.createElement("div");return i.classList.add("message-bubble"),e.appendChild(i),{outerContainer:t,innerContainer:e,bubbleElement:i}}createMessageElements(t,e){const i=Messages.createBaseElements(),{outerContainer:n,innerContainer:s,bubbleElement:o}=i;return n.appendChild(s),this.addInnerContainerElements(o,t,e),this._messageElementRefs.push(i),i}createNewMessageElement(t,e){var i;null==(i=this._introPanel)||i.hide();const n=this._messageElementRefs[this._messageElementRefs.length-1];return null!=n&&n.bubbleElement.classList.contains("loading-message-text")&&(n.outerContainer.remove(),this._messageElementRefs.pop()),this.createMessageElements(t,e)}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),this.elementRef.scrollTop=this.elementRef.scrollHeight,i}static editEmptyMessageElement(t){t.textContent=".",t.style.color="#00000000"}addNewTextMessage(t,e,i,n=!1){const s=this.createAndAppendNewMessageElement(t,e);this.applyCustomStyles(s,e,!1);const o=Messages.createMessageContent(e,t);return 0===t.trim().length&&Messages.editEmptyMessageElement(s.bubbleElement),this.messages.push(o),i&&this.sendClientUpdate(o,n),s}addNewMessage(t,e,i,n=!1){void 0!==t.text&&null!==t.text?(this.addNewTextMessage(t.text,e,i,n),!n&&this._textToSpeech&&e&&TextToSpeech.speak(t.text,this._textToSpeech)):t.files&&t.files.forEach((t=>{var i,s;"audio"===t.type||null!=(i=t.src)&&i.startsWith("data:audio")?FileMessages.addNewAudioMessage(this,t,e,n):"image"===t.type||"gif"===t.type||null!=(s=t.src)&&s.startsWith("data:image")?FileMessages.addNewImageMessage(this,t,e,n):FileMessages.addNewAnyFileMessage(this,t,e,n)}))}sendClientUpdate(t,e=!1){var i;null==(i=this._onNewMessage)||i.call(this,t,e)}removeMessageOnError(){var t;const e=null==(t=this._messageElementRefs[this._messageElementRefs.length-1])?void 0:t.bubbleElement;(null!=e&&e.classList.contains("streamed-message")&&""===e.textContent||null!=e&&e.classList.contains("loading-message-text"))&&(e.remove(),this._messageElementRefs.pop())}addNewErrorMessage(t,e){var i,n,s,o;this.removeMessageOnError();const r=Messages.createBaseElements(),{outerContainer:a,bubbleElement:l}=r;l.classList.add("error-message-text");const c=this.getPermittedMessage(e)||(null==(i=this._errorMessageOverrides)?void 0:i[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.";l.innerHTML=c;const u=MessageStyleUtils.extractParticularSharedStyles(["fontSize","fontFamily"],null==(s=this.messageStyles)?void 0:s.default);MessageStyleUtils.applyCustomStylesToElements(r,!1,u),MessageStyleUtils.applyCustomStylesToElements(r,!1,null==(o=this.messageStyles)?void 0:o.error),this.elementRef.appendChild(a),this.elementRef.scrollTop=this.elementRef.scrollHeight,this._textToSpeech&&TextToSpeech.speak(c,this._textToSpeech),this._streamedText=""}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}getPermittedMessage(t){if(t){if(this.displayServiceErrorMessages)return t;if("string"==typeof t&&this._permittedErrorPrefixes){const e=Messages.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t);if(e)return e}else if(Array.isArray(t)&&this._permittedErrorPrefixes)for(let e=0;e<t.length;e+=1){const i=Messages.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t[e]);if(i)return i}}}isLastMessageError(){var t,e,i,n,s;return null==(s=null==(n=null==(i=null==(e=null==(t=this.elementRef.children[this.elementRef.children.length-1])?void 0:t.children)?void 0:e[0])?void 0:i.children)?void 0:n[0])?void 0:s.classList.contains("error-message-text")}addLoadingMessage(){var t;if(!this._displayLoadingMessage)return;const e=this.createMessageElements("",!0),{outerContainer:i,bubbleElement:n}=e;n.classList.add("loading-message-text");const s=document.createElement("div");s.classList.add("dots-flashing"),n.appendChild(s),this.applyCustomStyles(e,!0,!1,null==(t=this.messageStyles)?void 0:t.loading),LoadingMessageDotsStyle.set(n,this.messageStyles),this.elementRef.appendChild(i),this.elementRef.scrollTop=this.elementRef.scrollHeight}addNewStreamedMessage(){const{bubbleElement:t}=this.addNewTextMessage("",!0,!1);return t.classList.add("streamed-message"),this.elementRef.scrollTop=this.elementRef.scrollHeight,t}updateStreamedMessage(t,e){var i,n,s,o,r;const a=ElementUtils.isScrollbarAtBottomOfElement(this.elementRef);if(0!==t.trim().length){const t=null==(i=this.messageStyles)?void 0:i.default;e.style.color=(null==(s=null==(n=null==t?void 0:t.ai)?void 0:n.bubble)?void 0:s.color)||(null==(r=null==(o=null==t?void 0:t.shared)?void 0:o.bubble)?void 0:r.color)||""}this._streamedText+=t,e.innerHTML=this._remarkable.render(this._streamedText),a&&(this.elementRef.scrollTop=this.elementRef.scrollHeight)}finaliseStreamedMessage(){this.messages[this.messages.length-1].text=this._streamedText,this.sendClientUpdate(Messages.createMessageContent(!0,this._streamedText),!1),this._textToSpeech&&TextToSpeech.speak(this._streamedText,this._textToSpeech),this._streamedText=""}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new IntroPanel(t,e,i),this._introPanel._elementRef&&this.elementRef.appendChild(this._introPanel._elementRef))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{this.addNewMessage({files:[{src:i.result,type:t.type}]},!1,!0),e(!0)}}else{const i=t.file.name||FileMessageUtils.DEFAULT_FILE_NAME;this.addNewMessage({files:[{name:i,type:"any"}]},!1,!0),e(!0)}})))))}refreshTextMessages(){this._remarkable=RemarkableConfig.createNew(),this.messages.forEach(((t,e)=>{t.text&&(this._messageElementRefs[e].bubbleElement.innerHTML=this._remarkable.render(t.text))}))}}const _InputButtonStyleAdjustments=class{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(t,e,i){0===i["outside-right"].length&&i["outside-left"].length>0?(t[0].classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),e.classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===i["outside-left"].length&&i["outside-right"].length>0&&(t[3].classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),e.classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(t,e,i){if(!(i["inside-left"].length>0||i["inside-right"].length>0)){if(0===i["outside-right"].length&&i["outside-left"].length>0)return t[0].classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),e.classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===i["outside-left"].length&&i["outside-right"].length>0)return t[3].classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),e.classList.add(_InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(t,e,i,n){!!_InputButtonStyleAdjustments.adjustOutsideSubmit(e,i,n)||_InputButtonStyleAdjustments.adjustForOutsideButton(e,i,n),_InputButtonStyleAdjustments.adjustInputPadding(t,n)}};let InputButtonStyleAdjustments=_InputButtonStyleAdjustments;InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",InputButtonStyleAdjustments.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",InputButtonStyleAdjustments.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";class ButtonContainers{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const n=ButtonContainers.getContainerIndex(i);t[n].appendChild(e),3===n&&e.classList.add("outside-right")}}const BUTTON_ORDER=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class CustomButtonInnerElements{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?CustomButtonInnerElements.createTextElement(t):SVGIconUtils.createSVGElement(t)}static createCustomElement(t,e){var i,n,s,o;const r=t[e];return null!=(i=null==r?void 0:r.text)&&i.content?CustomButtonInnerElements.createElement(null==(n=null==r?void 0:r.text)?void 0:n.content,!0):null!=(s=null==r?void 0:r.svg)&&s.content?CustomButtonInnerElements.createElement(null==(o=null==r?void 0:r.svg)?void 0:o.content,!1):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let n;return i&&(n=CustomButtonInnerElements.createCustomElement(i,e)),CustomButtonInnerElements.processElement(t,n),n}static create(t,e,i){const n={};if(!i)return CustomButtonInnerElements.processElement(t),n;const s=CustomButtonInnerElements.createSpecificStateElement(t,e[0],i);n[e[0]]=s;let o=s;return e.slice(1).forEach((t=>{o=CustomButtonInnerElements.createCustomElement(i,t)||o,n[t]=o})),n}}const PLUS_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>';class ButtonCSS{static unsetAllCSS(t,e){var i,n;e.container&&StyleUtils.unsetAllCSSMouseStates(t,e.container),null!=(i=e.svg)&&i.styles&&StyleUtils.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&StyleUtils.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var i,n;e.container&&StyleUtils.unsetActivityCSSMouseStates(t,e.container),null!=(i=e.svg)&&i.styles&&StyleUtils.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&StyleUtils.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var n,s,o,r,a;Object.assign(t.style,null==(n=e.container)?void 0:n[i]),Object.assign(t.children[0].style,null==(o=null==(s=e.svg)?void 0:s.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){ButtonCSS.setElementsCSS(t,e,"default"),"default"!==i&&(ButtonCSS.setElementsCSS(t,e,"hover"),"hover"!==i&&ButtonCSS.setElementsCSS(t,e,"click"))}}class InputButton{constructor(t,e,i,n){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=n}buttonMouseLeave(t){this._mouseState.state="default",t&&(ButtonCSS.unsetAllCSS(this.elementRef,t),ButtonCSS.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&ButtonCSS.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&ButtonCSS.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&ButtonCSS.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],n=i&&this._customStyles[i];n&&ButtonCSS.unsetActionCSS(this.elementRef,n)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&ButtonCSS.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class DropupItemNavigation{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];DropupItemNavigation.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,n=!1){const s=n?t:t[i?"nextSibling":"previousSibling"];s?(t.dispatchEvent(new MouseEvent("mouseleave")),s.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),DropupItemNavigation.focusItemWhenOnEdge(e,i))}}class StatefulEvents{static mouseUp(t,e){const i=e.target;StyleUtils.unsetAllCSSMouseStates(i,t),Object.assign(i.style,t.default),Object.assign(i.style,t.hover)}static mouseDown(t,e){const i=e.target;Object.assign(i.style,t.click)}static mouseLeave(t,e){const i=e.target;StyleUtils.unsetAllCSSMouseStates(i,t),Object.assign(i.style,t.default)}static mouseEnter(t,e){const i=e.target;Object.assign(i.style,t.hover)}static add(t,e){t.addEventListener("mouseenter",StatefulEvents.mouseEnter.bind(this,e)),t.addEventListener("mouseleave",StatefulEvents.mouseLeave.bind(this,e)),t.addEventListener("mousedown",StatefulEvents.mouseDown.bind(this,e)),t.addEventListener("mouseup",StatefulEvents.mouseUp.bind(this,e))}}class DropupItem{static addItemEvents(t,e,i,n){StatefulEvents.add(e,n),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(t,e,i,n){const s=t.children[0];s.classList.contains("text-button")?e.appendChild(DropupItem.createItemText(s.textContent,null==n?void 0:n.text)):(e.appendChild(DropupItem.createItemIcon(t,null==n?void 0:n.iconContainer)),e.appendChild(DropupItem.createItemText(i,null==n?void 0:n.text)))}static createItem(t,e,i){var n;const{elementRef:s,dropupText:o}=e,r=document.createElement("div");Object.assign(r.style,null==(n=null==i?void 0:i.item)?void 0:n.default),DropupItem.populateItem(s,r,o,i),r.classList.add("dropup-menu-item");const a=StyleUtils.generateStateful((null==i?void 0:i.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return DropupItem.addItemEvents(t,r,s,a),r}}class DropupMenu{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=DropupMenu.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=DropupItem.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){window.addEventListener("click",(e=>{var i;t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()})),window.addEventListener("keydown",(t=>{var e,i,n;this._isOpen&&(t.key===KEYBOARD_KEY.ESCAPE?(this.close(),null==(e=this.highlightedItem)||e.dispatchEvent(new MouseEvent("mouseleave"))):t.key===KEYBOARD_KEY.ENTER?(null==(i=this.highlightedItem)||i.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):t.key===KEYBOARD_KEY.ARROW_DOWN?DropupItemNavigation.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):t.key===KEYBOARD_KEY.ARROW_UP&&DropupItemNavigation.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}))}}class Dropup extends InputButton{constructor(t,e){var i;super(Dropup.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const n=this.createInnerElements(this._customStyles);this._menu=new DropupMenu(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=Dropup.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(t)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(t){return{styles:this.createInnerElement(Dropup.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return CustomButtonInnerElements.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){const t=SVGIconUtils.createSVGElement(PLUS_ICON_STRING);return t.id="dropup-icon",t}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(t){t.addEventListener("click",(t=>{t.target.classList.contains("dropup-icon")||this._menu.close()}))}static getPosition(t,e){var i,n;return null!=(i=null==e?void 0:e.button)&&i.position?null==(n=null==e?void 0:e.button)?void 0:n.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class InputButtonPositions{static addToDropup(t,e,i,n){const s=new Dropup(i,n);BUTTON_ORDER.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),n=e["dropup-menu"][i];n&&(s.addItem(n.button),e["dropup-menu"].splice(i,1))}));const o=Dropup.getPosition(e,n);ButtonContainers.addButton(t,s.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const n=i;e[n].forEach((e=>{ButtonContainers.addButton(t,e.button.elementRef,n)}))}))}static setPosition(t,e,i){const n={...t[e],buttonType:e};i.push(n),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=InputButtonPositions.createPositionsObj();Object.keys(t).forEach((i=>{var n;const s=null==(n=t[i])?void 0:n.button.position;s&&InputButtonPositions.setPosition(t,i,e[s])})),0===e["inside-right"].length&&t.submit&&InputButtonPositions.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?InputButtonPositions.setPosition(t,"submit",e["outside-right"]):t.microphone?InputButtonPositions.setPosition(t,"microphone",e["outside-right"]):t.camera&&InputButtonPositions.setPosition(t,"camera",e["outside-right"])),t.submit&&InputButtonPositions.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&InputButtonPositions.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?BUTTON_ORDER.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&InputButtonPositions.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,n){const s=InputButtonPositions.generatePositions(e);return InputButtonPositions.addToSideContainer(t,s),s["dropup-menu"].length>0&&InputButtonPositions.addToDropup(t,s,i,n),s}}const MIXED_FILES_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',IMAGE_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',AUDIO_ICON_STRING='<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',GIF_ICON_STRING='<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',FILE_TYPE_BUTTON_ICONS={images:{id:"upload-images-icon",svgString:IMAGE_ICON_STRING,dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:GIF_ICON_STRING,dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:AUDIO_ICON_STRING,dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:MIXED_FILES_ICON_STRING,dropupText:"File"}};class FileAttachmentsType{constructor(t,e,i){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",t.maxNumberOfFiles&&(this._fileCountLimit=t.maxNumberOfFiles),this._toggleContainerDisplay=e,this._fileAttachmentsContainerRef=i,t.acceptedFormats&&(this._acceptedFormat=t.acceptedFormats)}attemptAddFile(t,e){return!!FileAttachmentsType.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const n=i[e].trim();if(t.type===n)return!0;if(n.startsWith(".")){const e=n.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(n))return!0;if(n.endsWith("/*")&&t.type.startsWith(n.slice(0,-2)))return!0}}return!1}addAttachmentBasedOnType(t,e,i){if(t.type.startsWith("image")){const n=FileAttachmentsType.createImageAttachment(e);this.addFileAttachment(t,"image",n,i)}else if(t.type.startsWith("audio")){const n=AudioFileAttachmentType.createAudioAttachment(e);this.addFileAttachment(t,"audio",n,i)}else{const e=FileAttachmentsType.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),Browser$1.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const n=document.createElement("div");return n.classList.add("file-attachment-text-container"),n.appendChild(i),i.textContent=t,e.appendChild(n),e}addFileAttachment(t,e,i,n){const s=FileAttachmentsType.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(s,e[0])}else this._fileAttachmentsContainerRef.appendChild(s);const o={file:t,attachmentContainerElement:s,fileType:e};return n&&(o.removeButton=this.createRemoveAttachmentButton(o),s.appendChild(o.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(o),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,o}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){const e=this._attachments.findIndex((e=>e===t)),i=this._attachments[e].attachmentContainerElement;this._attachments.splice(e,1),AudioFileAttachmentType.stopAttachmentPlayback(i),i.remove(),this._toggleContainerDisplay(!1)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const PLAY_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>',STOP_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',_AudioFileAttachmentType=class extends FileAttachmentsType{constructor(t,e,i){super(t,e,i)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),Browser$1.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?ElementUtils.cloneElement(t):t,n=document.createElement("audio");n.src=e;const s=SVGIconUtils.createSVGElement(PLAY_ICON_STRING);s.classList.add("attachment-icon","play-icon");const o=SVGIconUtils.createSVGElement(STOP_ICON_STRING);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(s),n.onplay=()=>{i.replaceChildren(o)},n.onpause=()=>{i.replaceChildren(s),n.currentTime=0},n.onended=()=>{i.replaceChildren(s)},i.onclick=()=>{n.paused?n.play():n.pause()}}static createAudioAttachment(t){const e=_AudioFileAttachmentType.createAudioContainer();return _AudioFileAttachmentType.addAudioElements(e,t),e}createTimer(t,e){let i=0;const n=void 0!==e&&e<_AudioFileAttachmentType.TIMER_LIMIT_S?e:_AudioFileAttachmentType.TIMER_LIMIT_S;return setInterval((()=>{var e;i+=1,i===n&&(null==(e=this.stopPlaceholderCallback)||e.call(this),this.clearTimer()),600===i&&t.classList.add("audio-placeholder-text-4-digits");const s=Math.floor(i/60),o=(i%60).toString().padStart(2,"0");t.textContent=`${s}:${o}`}),1e3)}createPlaceholderAudioAttachment(t){const e=_AudioFileAttachmentType.createAudioContainer(),i=document.createElement("div");i.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(i);const s=SVGIconUtils.createSVGElement(STOP_ICON_STRING);return s.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),i.textContent="0:00",this._activePlaceholderTimer=this.createTimer(i,t),e.appendChild(n),this.addPlaceholderAudioAttachmentEvents(e,s,n),e}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(t,e){const i=this._activePlaceholderAttachment;i&&(i.file=t,_AudioFileAttachmentType.addAudioElements(i.attachmentContainerElement.children[0],e),i.removeButton=this.createRemoveAttachmentButton(i),i.attachmentContainerElement.appendChild(i.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,n;null!=(n=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&n.classList.contains("stop-icon")&&t.children[0].click()}};let AudioFileAttachmentType=_AudioFileAttachmentType;AudioFileAttachmentType.TIMER_LIMIT_S=5999;class FileAttachmentTypeFactory{static create(t,e,i,n){return"audio"===n?new AudioFileAttachmentType(t,e,i):new FileAttachmentsType(t,e,i)}}class FileAttachments{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e){const i=FileAttachmentTypeFactory.create(t,this.toggleContainerDisplay.bind(this),this.elementRef,e);return this._fileAttachmentsTypes.push(i),i}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let n=0;n<e.length&&!e[n].attemptAddFile(t,i.target.result);n+=1);}}))}addFilesToAnyType(t){FileAttachments.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const _Modal=class{constructor(t,e,i){this._isOpen=!1,this._contentRef=_Modal.createModalContent(e,null==i?void 0:i.backgroundColor),this._buttonPanel=_Modal.createButtonPanel(null==i?void 0:i.backgroundColor),this._elementRef=_Modal.createContainer(this._contentRef,i),this._elementRef.appendChild(this._buttonPanel),t.appendChild(this._elementRef),this._backgroundPanelRef=_Modal.createDarkBackgroundPanel(),t.appendChild(this._backgroundPanelRef),this.addWindowEvents()}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>this._buttonPanel.appendChild(t)))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=SVGIconUtils.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),_Modal.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(t,e,i){const n=e?_Modal.createSVGButton(t):_Modal.createTextButton(t);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==i||i()}),140)},n}static createTextModalFunc(t,e,i){var n;if("object"==typeof e&&null!=(n=e.files)&&n.infoModal){const n=new _Modal(t,["modal-content"],e.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,i),n.openTextModal.bind(n,e.infoModalTextMarkUp||"")}}addWindowEvents(){window.addEventListener("keydown",(t=>{var e,i;this._isOpen&&(t.key===KEYBOARD_KEY.ESCAPE?(this.close(),null==(e=this.extensionCloseCallback)||e.call(this)):t.key===KEYBOARD_KEY.ENTER&&(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)))}))}};let Modal=_Modal;Modal.MODAL_CLOSE_TIMEOUT_MS=190;class UploadFileButton extends InputButton{constructor(t,e,i,n,s,o){var r,a,l,c,u,h;super(UploadFileButton.createButtonElement(),null==(r=i.button)?void 0:r.position,i.button,o);const d=this.createInnerElements(n,s,this._customStyles);this._inputElement=UploadFileButton.createInputElement(null==(a=null==i?void 0:i.files)?void 0:a.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(d.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(c=null==(l=i.files)?void 0:l.infoModal)?void 0:c.openModalOnce)||null==(h=null==(u=i.files)?void 0:u.infoModal)?void 0:h.openModalOnce}createInnerElements(t,e,i){const n=UploadFileButton.createSVGIconElement(t,e);return{styles:this.createInnerElement(n,"styles",i)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){FileAttachments.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}createInnerElement(t,e,i){return CustomButtonInnerElements.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=SVGIconUtils.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),n=Modal.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,n)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class DragAndDrop{static create(t,e,i){const n=DragAndDrop.createElement(i);DragAndDrop.addEvents(n,t,e),t.appendChild(n)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),DragAndDrop.display(t)},t.ondragleave=e=>{e.preventDefault(),DragAndDrop.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),DragAndDrop.uploadFile(i,e),DragAndDrop.hide(t)}}static uploadFile(t,e){var i;const n=null==(i=e.dataTransfer)?void 0:i.files;n&&t.addFilesToAnyType(Array.from(n))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}const MICROPHONE_ICON_STRING='<?xml version="1.0" encoding="iso-8859-1"?>\n<svg height="1.4em" width="1.4em" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"\n\t viewBox="0 0 490.9 490.9" xml:space="preserve">\n\t<g>\n\t\t<g>\n\t\t\t<path d="M245.5,322.9c53,0,96.2-43.2,96.2-96.2V96.2c0-53-43.2-96.2-96.2-96.2s-96.2,43.2-96.2,96.2v130.5\n\t\t\t\tC149.3,279.8,192.5,322.9,245.5,322.9z M173.8,96.2c0-39.5,32.2-71.7,71.7-71.7s71.7,32.2,71.7,71.7v130.5\n\t\t\t\tc0,39.5-32.2,71.7-71.7,71.7s-71.7-32.2-71.7-71.7V96.2z"/>\n\t\t\t<path d="M94.4,214.5c-6.8,0-12.3,5.5-12.3,12.3c0,85.9,66.7,156.6,151.1,162.8v76.7h-63.9c-6.8,0-12.3,5.5-12.3,12.3\n\t\t\t\ts5.5,12.3,12.3,12.3h152.3c6.8,0,12.3-5.5,12.3-12.3s-5.5-12.3-12.3-12.3h-63.9v-76.7c84.4-6.3,151.1-76.9,151.1-162.8\n\t\t\t\tc0-6.8-5.5-12.3-12.3-12.3s-12.3,5.5-12.3,12.3c0,76.6-62.3,138.9-138.9,138.9s-138.9-62.3-138.9-138.9\n\t\t\t\tC106.6,220,101.2,214.5,94.4,214.5z"/>\n\t\t</g>\n\t</g>\n</svg>\n';class MicrophoneButton extends InputButton{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(MicrophoneButton.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=MicrophoneButton.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return CustomButtonInnerElements.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=SVGIconUtils.createSVGElement(MICROPHONE_ICON_STRING);return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}var dist={},webSpeech={},webSpeechTranscript={},translate={},text={};Object.defineProperty(text,"u",{value:!0}),text.Text=void 0;class Text{static capitalize(t){return t.replace(Text.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(Text.DOUBLE_LINE,"<p></p>").replace(Text.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}text.Text=Text,Text.FIRST_CHAR_REGEX=/\S/,Text.DOUBLE_LINE=/\n\n/g,Text.ONE_LINE=/\n/g,Object.defineProperty(translate,"u",{value:!0}),translate.Translate=void 0;const text_1$3=text;class Translate{static translate(t,e){const i=text_1$3.Text.breakupIntoWordsArr(t);for(let t=0;t<i.length;t+=1)e[i[t]]&&(i[t]=e[i[t]]);return i.join("")}}translate.Translate=Translate,Object.defineProperty(webSpeechTranscript,"u",{value:!0}),webSpeechTranscript.WebSpeechTranscript=void 0;const translate_1$1=translate;class WebSpeechTranscript{static extract(t,e,i){let n="";for(let s=t.resultIndex;s<t.results.length;++s){let o=t.results[s][0].transcript;i&&(o=translate_1$1.Translate.translate(o,i)),t.results[s].isFinal?e+=o:n+=o}return{interimTranscript:n,finalTranscript:e,newText:n||e}}static extractSafari(t,e,i){let n="";for(let e=t.resultIndex;e<t.results.length;++e){let s=t.results[e][0].transcript;i&&(s=translate_1$1.Translate.translate(s,i)),n+=s}return{interimTranscript:"",finalTranscript:n,newText:n}}}webSpeechTranscript.WebSpeechTranscript=WebSpeechTranscript;var browser={};Object.defineProperty(browser,"u",{value:!0}),browser.Browser=void 0;class Browser{}browser.Browser=Browser,Browser.IS_SAFARI=()=>(void 0===Browser._IS_SAFARI&&(Browser._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),Browser._IS_SAFARI);var speech={},eventListeners={};Object.defineProperty(eventListeners,"u",{value:!0}),eventListeners.EventListeners=void 0;class EventListeners{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&EventListeners.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==EventListeners.KEY_DOWN_TIMEOUT&&clearTimeout(EventListeners.KEY_DOWN_TIMEOUT),EventListeners.KEY_DOWN_TIMEOUT=setTimeout((()=>{EventListeners.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=EventListeners.getElementIfFocusedOnAvailable(t,e.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(t,e){const i=void 0===(null==e?void 0:e.insertInCursorLocation)||(null==e?void 0:e.insertInCursorLocation);null!=e&&e.element&&i&&(t.mouseDownEvent=EventListeners.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=EventListeners.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=EventListeners.keyDownWindow.bind(t,e),document.addEventListener("keydown",t.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}eventListeners.EventListeners=EventListeners,EventListeners.KEY_DOWN_TIMEOUT=null;var preResultUtils={};Object.defineProperty(preResultUtils,"u",{value:!0}),preResultUtils.PreResultUtils=void 0;class PreResultUtils{static process(t,e,i,n,s){const o=null==n?void 0:n(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(s):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}}preResultUtils.PreResultUtils=PreResultUtils;var commandUtils={},autoScroll={};Object.defineProperty(autoScroll,"u",{value:!0}),autoScroll.AutoScroll=void 0;class AutoScroll{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML="&nbsp;")}static scrollGeneric(t,e){t.isCursorAtEnd?e.scrollTop=e.scrollHeight:t.scrollingSpan.scrollIntoView({block:"nearest"})}static scrollSafariPrimitiveToEnd(t){t.scrollLeft=t.scrollWidth,t.scrollTop=t.scrollHeight}static isElementOverflown(t){return t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth}static isRequired(t,e){return t&&AutoScroll.isElementOverflown(e)}}autoScroll.AutoScroll=AutoScroll;var elements={};Object.defineProperty(elements,"u",{value:!0}),elements.Elements=void 0;class Elements{static isPrimitiveElement(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName}static createInterimSpan(){const t=document.createElement("span");return t.style.color="grey",t.style.pointerEvents="none",t}static createGenericSpan(){const t=document.createElement("span");return t.style.pointerEvents="none",t}static appendSpans(t,e){if(t.spansPopulated=!0,t.insertInCursorLocation&&document.activeElement===e){const e=window.getSelection();if(null!=e&&e.focusNode){const i=e.getRangeAt(0);return i.insertNode(t.scrollingSpan),i.insertNode(t.interimSpan),i.insertNode(t.finalSpan),i.collapse(!1),e.removeAllRanges(),void e.addRange(i)}}e.appendChild(t.finalSpan),e.appendChild(t.interimSpan),e.appendChild(t.scrollingSpan)}static applyCustomColors(t,e){e.interim&&(t.interimSpan.style.color=e.interim),e.final&&(t.finalSpan.style.color=e.final)}static isInsideShadowDOM(t){return t.getRootNode()instanceof ShadowRoot}}elements.Elements=Elements;var cursor={};Object.defineProperty(cursor,"u",{value:!0}),cursor.Cursor=void 0;class Cursor{static setOffsetForGeneric(t,e,i=0){let n=0;for(let s=0;s<t.childNodes.length;s+=1){const o=t.childNodes[s];if(o.childNodes.length>0){const t=Cursor.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const n=document.createRange();n.setStart(o,e-i),n.collapse(!0);const s=window.getSelection();return null==s||s.removeAllRanges(),null==s||s.addRange(n),t.focus(),-1}i+=o.textContent.length,n+=o.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(t,e){const i=window.getSelection();if(i){const n=Cursor.getGenericElementCursorOffset(t,i,!0);console.log(n),setTimeout((()=>{}),100),Cursor.setOffsetForGeneric(t,n+e)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let n=0;if(e.rangeCount>0){const s=e.getRangeAt(0),o=s.cloneRange();o.selectNodeContents(t),i?o.setEnd(s.startContainer,s.startOffset):o.setEnd(s.endContainer,s.endOffset),n=o.toString().length}return n}}cursor.Cursor=Cursor,Object.defineProperty(commandUtils,"u",{value:!0}),commandUtils.CommandUtils=void 0;const autoScroll_1$1=autoScroll,elements_1$3=elements,browser_1$2=browser,cursor_1$3=cursor,text_1$2=text;class CommandUtils{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?text_1$2.Text.breakupIntoWordsArr(t):t}static process(t){var e;return!0===(null===(e=t.settings)||void 0===e?void 0:e.caseSensitive)?t:Object.keys(t).reduce(((e,i)=>{const n=t[i];return e[i]="string"==typeof n?CommandUtils.processCommand(n,t.settings):n,e}),{})}static toggleCommandModeOn(t){var e;t.isWaitingForCommand=!0,null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!0)}static toggleCommandModeOff(t){var e;t.isWaitingForCommand&&(null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!1),t.isWaitingForCommand=!1)}static setText(t,e,i,n){CommandUtils.toggleCommandModeOff(t),elements_1$3.Elements.isPrimitiveElement(n)?(n.value=i,t.isTargetInShadow||cursor_1$3.Cursor.setOffsetForPrimitive(n,i.length,!0),browser_1$2.Browser.IS_SAFARI()&&t.autoScroll&&autoScroll_1$1.AutoScroll.scrollSafariPrimitiveToEnd(n)):(n.textContent=i,t.isTargetInShadow||cursor_1$3.Cursor.focusEndOfGeneric(n),setTimeout((()=>autoScroll_1$1.AutoScroll.scrollGeneric(t,n)))),t.resetRecording(e)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const n=t;for(let t=i.length-1;t>=0;t-=1){let e=t,s=n.length-1;for(;i[e]===n[s]&&s>=0;)e-=1,s-=1;if(s<0)return!0}return!1}static execCommand(t,e,i,n,s){var o,r,a;const l=t.commands;if(!l||!n||!i)return;const c=!0===(null===(o=l.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),u=text_1$2.Text.breakupIntoWordsArr(c),h=!1===(null===(r=l.settings)||void 0===r?void 0:r.substrings)?CommandUtils.checkIfMatchesWord:CommandUtils.checkIfMatchesSubstring;if(l.commandMode&&h(l.commandMode,c,u))return t.setInterimColorToFinal(),setTimeout((()=>CommandUtils.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!l.commandMode||t.isWaitingForCommand){if(l.stop&&h(l.stop,c,u))return CommandUtils.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(l.pause&&h(l.pause,c,u))return CommandUtils.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(l.resume&&h(l.resume,c,u))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),CommandUtils.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(l.reset&&h(l.reset,c,u))return void 0!==s&&CommandUtils.setText(t,i,s,n),{doNotProcessTranscription:!0};if(l.removeAllText&&h(l.removeAllText,c,u))return CommandUtils.setText(t,i,"",n),{doNotProcessTranscription:!0}}}}commandUtils.CommandUtils=CommandUtils;var highlight={};Object.defineProperty(highlight,"u",{value:!0}),highlight.Highlight=void 0;const elements_1$2=elements,cursor_1$2=cursor;class Highlight{static setStateForPrimitive(t,e){let i,n;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(n=e.selectionEnd),t.isHighlighted=i!==n}static setStateForGeneric(t,e){const i=window.getSelection();if(null!=i&&i.focusNode){const n=cursor_1$2.Cursor.getGenericElementCursorOffset(e,i,!0),s=cursor_1$2.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=n!==s}}static setState(t,e){document.activeElement===e&&(elements_1$2.Elements.isPrimitiveElement(e)?Highlight.setStateForPrimitive(t,e):Highlight.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const n=cursor_1$2.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),cursor_1$2.Cursor.setOffsetForGeneric(e,n),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,n=e.selectionEnd,s=e.value;if(i&&n){const o=s.substring(0,i)+s.substring(n);e.value=o,cursor_1$2.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}highlight.Highlight=Highlight;var padding={};Object.defineProperty(padding,"u",{value:!0}),padding.Padding=void 0;const elements_1$1=elements,cursor_1$1=cursor,text_1$1=text;class Padding{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,n=e.value[i-1],s=null===e.selectionEnd?i:e.selectionEnd,o=e.value[s];return text_1$1.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),text_1$1.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===s)}const i=e.value[e.value.length-1];text_1$1.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,n,s;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=cursor_1$1.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],l=cursor_1$1.Cursor.getGenericElementCursorOffset(e,o,!1),c=null===(n=e.textContent)||void 0===n?void 0:n[l];return text_1$1.Text.isCharDefined(a)&&(t.startPadding=" "),text_1$1.Text.isCharDefined(c)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(s=e.textContent)||void 0===s?void 0:s.length)===l)}}const o=e.innerText.charAt(e.innerText.length-1);text_1$1.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){elements_1$1.Elements.isPrimitiveElement(e)?Padding.setStateForPrimitiveElement(t,e):Padding.setStateForGenericElement(t,e)}static adjustStateAfterRecodingPrimitiveElement(t,e){t.primitiveTextRecorded=!0,t.insertInCursorLocation&&document.activeElement===e&&(null!==e.selectionEnd&&(t.endPadding=t.endPadding+e.value.slice(e.selectionEnd)),null!==e.selectionStart)?t.startPadding=e.value.slice(0,e.selectionStart)+t.startPadding:t.startPadding=e.value+t.startPadding}static adjustSateForNoTextPrimitiveElement(t){1===t.numberOfSpacesBeforeNewText&&(t.startPadding=t.startPadding.substring(0,t.startPadding.length-1),t.numberOfSpacesBeforeNewText=0),1===t.numberOfSpacesAfterNewText&&(t.endPadding=t.endPadding.substring(1),t.numberOfSpacesAfterNewText=0)}}padding.Padding=Padding,Object.defineProperty(speech,"u",{value:!0}),speech.Speech=void 0;const eventListeners_1=eventListeners,preResultUtils_1=preResultUtils,commandUtils_1$1=commandUtils,autoScroll_1=autoScroll,highlight_1=highlight,elements_1=elements,padding_1=padding,browser_1$1=browser,cursor_1=cursor,text_1=text;class Speech{constructor(){this.finalTranscript="",this.interimSpan=elements_1.Elements.createInterimSpan(),this.finalSpan=elements_1.Elements.createGenericSpan(),this.scrollingSpan=elements_1.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()}prepareBeforeStart(t){var e,i;if(null!=t&&t.element)if(eventListeners_1.EventListeners.add(this,t),Array.isArray(t.element)){const e=t.element.find((t=>t===document.activeElement))||t.element[0];if(!e)return;this.prepare(e)}else this.prepare(t.element);void 0!==(null==t?void 0:t.displayInterimResults)&&(this._displayInterimResults=t.displayInterimResults),null!=t&&t.textColor&&(this._finalTextColor=null===(e=null==t?void 0:t.textColor)||void 0===e?void 0:e.final,elements_1.Elements.applyCustomColors(this,t.textColor)),void 0!==(null==t?void 0:t.insertInCursorLocation)&&(this.insertInCursorLocation=t.insertInCursorLocation),void 0!==(null==t?void 0:t.autoScroll)&&(this.autoScroll=t.autoScroll),this._onResult=null==t?void 0:t.onResult,this._onPreResult=null==t?void 0:t.onPreResult,this._onStart=null==t?void 0:t.onStart,this._onStop=null==t?void 0:t.onStop,this._onError=null==t?void 0:t.onError,this.onCommandModeTrigger=null==t?void 0:t.onCommandModeTrigger,this.onPauseTrigger=null==t?void 0:t.onPauseTrigger,this._options=t,null!==(i=this._options)&&void 0!==i&&i.commands&&(this.commands=commandUtils_1$1.CommandUtils.process(this._options.commands))}prepare(t){padding_1.Padding.setState(this,t),highlight_1.Highlight.setState(this,t),this.isTargetInShadow=elements_1.Elements.isInsideShadowDOM(t),elements_1.Elements.isPrimitiveElement(t)?(this._primitiveElement=t,this._originalText=this._primitiveElement.value):(this._genericElement=t,this._originalText=this._genericElement.textContent)}resetRecording(t){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(t,!0)}updateElements(t,e,i){var n;const s=text_1.Text.capitalize(e);if(this.finalTranscript===s&&""===t)return;preResultUtils_1.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&commandUtils_1$1.CommandUtils.execCommand(this,i,this._options,this._primitiveElement||this._genericElement,this._originalText);if(o){if(o.doNotProcessTranscription)return;t="",i=""}if(this.isPaused||this.isWaitingForCommand)return;null===(n=this._onResult)||void 0===n||n.call(this,i,""===t),this.finalTranscript=s,this._displayInterimResults||(t="");const r=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,r):this._genericElement&&this.updateGenericElement(this._genericElement,t,r)}updatePrimitiveElement(t,e,i){this.isHighlighted&&highlight_1.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||padding_1.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&padding_1.Padding.adjustSateForNoTextPrimitiveElement(this);const n=this.startPadding+this.finalTranscript+e;if(t.value=n+this.endPadding,!this.isTargetInShadow){const e=n.length+this.numberOfSpacesAfterNewText;cursor_1.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&browser_1$1.Browser.IS_SAFARI()&&this.isCursorAtEnd&&autoScroll_1.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&highlight_1.Highlight.removeForGeneric(this,t),this.spansPopulated||elements_1.Elements.appendSpans(this,t);const n=(i?"":this.startPadding)+text_1.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=n;const s=autoScroll_1.AutoScroll.isRequired(this.autoScroll,t);autoScroll_1.AutoScroll.changeStateIfNeeded(this,s);const o=text_1.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,browser_1$1.Browser.IS_SAFARI()&&this.insertInCursorLocation&&cursor_1.Cursor.setOffsetForSafariGeneric(t,n.length+o.length),s&&autoScroll_1.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=elements_1.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=elements_1.Elements.createInterimSpan(),this.scrollingSpan=elements_1.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),eventListeners_1.EventListeners.remove(this)}setInterimColorToFinal(){this.interimSpan.style.color=this._finalTextColor||"black"}resetState(t){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,t||(this.stopTimeout=void 0)}setStateOnStart(){var t;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:null===(t=this._onStart)||void 0===t||t.call(this)}setStateOnStop(){var t;this.recognizing=!1,this.isRestarting||null===(t=this._onStop)||void 0===t||t.call(this)}setStateOnError(t){var e;null===(e=this._onError)||void 0===e||e.call(this,t),this.recognizing=!1}}speech.Speech=Speech,Object.defineProperty(webSpeech,"u",{value:!0}),webSpeech.WebSpeech=void 0;const webSpeechTranscript_1=webSpeechTranscript,browser_1=browser,speech_1$1=speech;class WebSpeech extends speech_1$1.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=browser_1.Browser.IS_SAFARI()?webSpeechTranscript_1.WebSpeechTranscript.extractSafari:webSpeechTranscript_1.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(t),this.instantiateService(t),null===(e=this._service)||void 0===e||e.start(),this._translations=null==t?void 0:t.translations)}validate(){return!!WebSpeech.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=WebSpeech.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{browser_1.Browser.IS_SAFARI()&&"Another request is started"===t.message||"aborted"===t.error&&this.isRestarting||"no-speech"!==t.error&&this.error(t.message||t.error)},this._service.onaudioend=()=>{this.setStateOnStop()},this._service.onend=()=>{this._stopping=!1},this._service.onresult=t=>{if(typeof t.results>"u"&&this._service)this._service.onend=null,this._service.stop();else if(this._extractText&&!this._stopping){const{interimTranscript:e,finalTranscript:i,newText:n}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,n)}})}stop(t){var e;this._stopping=!0,null===(e=this._service)||void 0===e||e.stop(),this.finalise(t)}static getAPI(){return window.webkitSpeechRecognition||window.SpeechRecognition}error(t){console.error(t),this.setStateOnError(t),this.stop()}}webSpeech.WebSpeech=WebSpeech;var globalState={};Object.defineProperty(globalState,"u",{value:!0}),globalState.GlobalState=void 0;class GlobalState{static doubleClickDetector(){return!!GlobalState.doubleClickPending||(GlobalState.doubleClickPending=!0,setTimeout((()=>{GlobalState.doubleClickPending=!1}),300),!1)}}globalState.GlobalState=GlobalState,GlobalState.doubleClickPending=!1;var azure={},preventConnectionStop={};Object.defineProperty(preventConnectionStop,"u",{value:!0}),preventConnectionStop.PreventConnectionStop=void 0;class PreventConnectionStop{static applyPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!0,t._manualConnectionStopPrevention=setTimeout((()=>{t.cannotBeStopped=!1}),800)}static clearPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!1}}preventConnectionStop.PreventConnectionStop=PreventConnectionStop;var azureSpeechConfig={},readme={};Object.defineProperty(readme,"u",{value:!0}),readme.README_URL=void 0,readme.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(azureSpeechConfig,"u",{value:!0}),azureSpeechConfig.AzureSpeechConfig=void 0;const readme_1=readme;class AzureSpeechConfig{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${readme_1.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${readme_1.README_URL}`),!1):(t(`Please provide subscription details - more info: ${readme_1.README_URL}`),!1)}static async getNewSpeechConfig(t,e){if(e.region)return e.subscriptionKey?t.fromSubscription(e.subscriptionKey.trim(),e.region.trim()):e.token?t.fromAuthorizationToken(e.token.trim(),e.region.trim()):e.retrieveToken?e.retrieveToken().then((i=>e.region?t.fromAuthorizationToken((null==i?void 0:i.trim())||"",e.region.trim()):null)).catch((t=>(console.error(t),null))):null}static process(t,e){e.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,e){const i=await AzureSpeechConfig.getNewSpeechConfig(t,e);return i&&AzureSpeechConfig.process(i,e),i}}azureSpeechConfig.AzureSpeechConfig=AzureSpeechConfig;var stopTimeout={};Object.defineProperty(stopTimeout,"u",{value:!0}),stopTimeout.StopTimeout=void 0;class StopTimeout{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||StopTimeout.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),StopTimeout.set(t)}}stopTimeout.StopTimeout=StopTimeout,StopTimeout.DEFAULT_MS=2e4;var azureTranscript={};Object.defineProperty(azureTranscript,"u",{value:!0}),azureTranscript.AzureTranscript=void 0;const translate_1=translate;class AzureTranscript{static extract(t,e,i,n){return n&&(t=translate_1.Translate.translate(t,n)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}}azureTranscript.AzureTranscript=AzureTranscript,Object.defineProperty(azure,"u",{value:!0}),azure.Azure=void 0;const preventConnectionStop_1=preventConnectionStop,azureSpeechConfig_1=azureSpeechConfig,stopTimeout_1=stopTimeout,azureTranscript_1=azureTranscript,speech_1=speech;class Azure extends speech_1.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&stopTimeout_1.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||preventConnectionStop_1.PreventConnectionStop.applyPrevention(this)}async startAsync(t){var e;this.validate(t)&&(await this.instantiateService(t),this._translations=null==t?void 0:t.translations,null===(e=this._service)||void 0===e||e.startContinuousRecognitionAsync((()=>{}),this.error))}validate(t){return Azure.getAPI()?azureSpeechConfig_1.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=Azure.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),n=await azureSpeechConfig_1.AzureSpeechConfig.get(e.SpeechConfig,t);if(n){const s=new e.SpeechRecognizer(n,i);this.setEvents(s),this._service=s,t.retrieveToken&&this.retrieveTokenInterval(t.retrieveToken)}else this.error("Unable to contact Azure server")}setEvents(t){t.recognizing=this.onRecognizing.bind(this),t.recognized=this.onRecognized.bind(this),t.sessionStarted=this.onSessionStarted.bind(this),t.canceled=this.onCanceled.bind(this),t.sessionStopped=this.onSessionStopped.bind(this)}onRecognizing(t,e){if(this._stopping)return;const{interimTranscript:i,finalTranscript:n,newText:s}=azureTranscript_1.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);stopTimeout_1.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,n,s)}onRecognized(t,e){const i=e.result;switch(i.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(i.text&&!this._stopping){const{interimTranscript:t,finalTranscript:e,newText:n}=azureTranscript_1.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);stopTimeout_1.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,n),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){preventConnectionStop_1.PreventConnectionStop.clearPrevention(this),this.setStateOnStart()}onSessionStopped(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}retrieveTokenInterval(t){this._retrieveTokenInterval=setInterval((()=>{null==t||t().then((t=>{this._service&&(this._service.authorizationToken=(null==t?void 0:t.trim())||"")})).catch((t=>{this.error(t)}))}),1e4)}stop(t){var e;!t&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,null===(e=this._service)||void 0===e||e.stopContinuousRecognitionAsync(),this.finalise(t)}static getAPI(){return window.SpeechSDK}moduleNotFound(){console.error("speech recognition module not found:"),console.error("please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: <script src=\"https://aka.ms/csspeech/jsbrowserpackageraw\"><\/script>"),this.setStateOnError("speech recognition module not found")}error(t){this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),console.error(t),this.setStateOnError(t),this.stop()}}azure.Azure=Azure,Object.defineProperty(dist,"u",{value:!0});const webSpeech_1=webSpeech,commandUtils_1=commandUtils,globalState_1=globalState,azure_1=azure;class SpeechToElement{static toggle(t,e){var i,n;const s=t.toLocaleLowerCase().trim();null!==(i=globalState_1.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===s?SpeechToElement.startWebSpeech(e):"azure"===s?SpeechToElement.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(n=null==e?void 0:e.onError)||void 0===n||n.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){SpeechToElement.stop()||(globalState_1.GlobalState.service=new webSpeech_1.WebSpeech,globalState_1.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!webSpeech_1.WebSpeech.getAPI()}static startAzure(t){var e;SpeechToElement.stop()||null!==(e=globalState_1.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(globalState_1.GlobalState.service=new azure_1.Azure,globalState_1.GlobalState.service.start(t))}static stop(){var t;return!!globalState_1.GlobalState.doubleClickDetector()||(!(null===(t=globalState_1.GlobalState.service)||void 0===t)&&t.recognizing&&globalState_1.GlobalState.service.stop(),!1)}static endCommandMode(){globalState_1.GlobalState.service&&commandUtils_1.CommandUtils.toggleCommandModeOff(globalState_1.GlobalState.service)}}var _default=dist.default=SpeechToElement;class SpeechToText extends MicrophoneButton{constructor(t,e,i){var n;super("object"==typeof t.speechToText?null==(n=t.speechToText)?void 0:n.button:{});const{serviceName:s,processedConfig:o}=SpeechToText.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==s||_default.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,s,o)}else this.changeToUnsupported()}static processConfiguration(t,e){var i;const n="object"==typeof e?e:{},s="object"==typeof n.webSpeech?n.webSpeech:{},o=n.azure||{},r={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,...s,...o},a=null==(i=n.commands)?void 0:i.submit;return a&&(r.onPreResult=e=>e.toLowerCase().includes(a)?(setTimeout((()=>{var e;return null==(e=t.submit)?void 0:e.call(t)})),_default.endCommandMode(),{restart:!0,removeNewText:!0}):null),{serviceName:SpeechToText.getServiceName(n),processedConfig:r}}static getServiceName(t){return t.webSpeech?"webspeech":t.azure?"azure":"webspeech"}buttonClick(t,e,i,n){t.removeTextIfPlaceholder(),_default.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:this.onError.bind(this),onStart:this.changeToActive.bind(this),onStop:this.changeToDefault.bind(this),onCommandModeTrigger:this.onCommandModeTrigger.bind(this),...n})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}}class NewFileName{static getFileName(t,e){const i=new Date;return`${t}-${String(i.getHours()).padStart(2,"0")}-${String(i.getMinutes()).padStart(2,"0")}-${String(i.getSeconds()).padStart(2,"0")}.${e}`}}class RecordAudio extends MicrophoneButton{constructor(t,e){var i,n;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(n=e.files)?void 0:n.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=NewFileName.getFileName(this._newFilePrefix||"audio",this._extension),n=new File([e],i,{type:e.type}),s=new FileReader;s.readAsDataURL(n),s.onload=t=>{this._audioType.completePlaceholderAttachment(n,t.target.result)}}}const SUBMIT_ICON_STRING='<?xml version="1.0" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">\n<svg xmlns="http://www.w3.org/2000/svg" stroke="currentColor" fill="none" stroke-width="1" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="14"></line>\n <polygon points="22 2 15 22 11 14 2 10 22 2"></polygon>\n</svg>\n';class SubmitButtonStateStyle{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}}class SubmitButton extends InputButton{constructor(t,e,i,n,s){var o;super(SubmitButton.createButtonContainerElement(),null==(o=t.submitButtonStyles)?void 0:o.position,t.submitButtonStyles),this._isRequestInProgress=!1,this._isLoadingActive=!1,this._isSVGLoadingIconOverriden=!1,this._messages=i,this._inputElementRef=e,this._fileAttachments=s,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._serviceIO=n,this.attemptOverwriteLoadingStyle(t),this.changeToSubmitIcon()}createInnerElements(){const{submit:t,loading:e,stop:i}=CustomButtonInnerElements.create(this.elementRef,["submit","loading","stop"],this._customStyles);return{submit:t||SubmitButton.createSubmitIconElement(),loading:e||SubmitButton.createLoadingIconElement(),stop:i||SubmitButton.createStopIconElement()}}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=SVGIconUtils.createSVGElement(SUBMIT_ICON_STRING);return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("dots-jumping"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}attemptOverwriteLoadingStyle(t){var e,i,n,s,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(s=null==(n=this._customStyles)?void 0:n.loading)?void 0:s.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}submitFromInput(){var t;if(this._inputElementRef.classList.contains("text-input-placeholder"))this.submit(!1,"");else{const e=null==(t=this._inputElementRef.textContent)?void 0:t.trim();this.submit(!1,e)}}async submit(t,e){var i,n;let s,o;t||(await this._fileAttachments.completePlaceholders(),s=this._fileAttachments.getAllFileData(),o=null==s?void 0:s.map((t=>t.file)));const r=""===e?void 0:e;if(this._isRequestInProgress)return;if(null!=(i=this._serviceIO.deepChat)&&i.validateMessageBeforeSending){if(!this._serviceIO.deepChat.validateMessageBeforeSending(r,o))return}else if(!this._serviceIO.canSendMessage(r,o))return;this.changeToLoadingIcon(),""!==e&&this._messages.addNewMessage({text:e},!1,!0),s&&await this._messages.addMultipleFiles(s),this._messages.addLoadingMessage(),t||TextInputEl.clear(this._inputElementRef);const a={onFinish:this.changeToSubmitIcon.bind(this)},l={onOpen:this.changeToStopIcon.bind(this),onClose:this.changeToSubmitIcon.bind(this),abortStream:this._abortStream},c={text:r,files:o};this._serviceIO.callAPI(c,this._messages,a,l),t||null==(n=this._fileAttachments)||n.removeAllFiles()}stopStream(){this._abortStream.abort(),this.changeToSubmitIcon()}changeToStopIcon(){this.elementRef.classList.remove("loading-button"),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this._isLoadingActive=!1}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.add("loading-button"),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this._isRequestInProgress=!0,this._isLoadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.remove("loading-button"),this.elementRef.replaceChildren(this._innerElements.submit),SubmitButtonStateStyle.resetSubmit(this,this._isLoadingActive),this.elementRef.onclick=this.submitFromInput.bind(this),this._isRequestInProgress=!1,this._isLoadingActive=!1}}const REFRESH_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n',CAPTURE_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n',CLOSE_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',TICK_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>';class CameraModal extends Modal{constructor(t,e,i,n){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:s,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=s,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=SVGIconUtils.createSVGElement(REFRESH_ICON_STRING),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==n?void 0:n.format)&&(this._format="image/jpeg"),null!=n&&n.dimensions&&(this._dimensions=n.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=Modal.createSVGButton(CAPTURE_ICON_STRING);e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton(CLOSE_ICON_STRING,!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const n=Modal.createSVGButton(TICK_ICON_STRING);return n.classList.add("modal-svg-submit-button"),this.addButtons(e,n),this.addButtonEvents(e,i,n,t),{captureButton:e,submitButton:n}}addButtonEvents(t,e,i,n){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&FileAttachments.addFilesToType([t],[n]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),Modal.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),n=new Blob([i],{type:this._format}),s="image/jpeg"===this._format?"jpeg":"png",o=NewFileName.getFileName(this._newFilePrefix||"photo",s);return new File([n],o,{type:n.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,n){const s=new CameraModal(t,e,i,n);return s.openCameraModal.bind(s,s)}}const CAMERA_ICON_STRING='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>';class CameraButton extends InputButton{constructor(t,e,i){var n;super(CameraButton.createButtonElement(),null==(n=null==i?void 0:i.button)?void 0:n.position,(null==i?void 0:i.button)||{},"Photo");const s=this.createInnerElements(this._customStyles);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(s.styles),this.reapplyStateStyle("styles")}createInnerElements(t){return{styles:this.createInnerElement(CameraButton.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return CustomButtonInnerElements.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=SVGIconUtils.createSVGElement(CAMERA_ICON_STRING);return t.id="camera-icon",t}addClickEvent(t,e,i,n){const s=CameraModal.createCameraModalFunc(t,e,i,n);this.elementRef.onclick=s}}class Input{constructor(t,e,i,n){this.elementRef=Input.createPanelElement(t.inputAreaStyle);const s=new TextInputEl(i,t.textInput),o={},r=this.createFileUploadComponents(t,i,n,o);t.speechToText&&!o.microphone&&(o.microphone={button:new SpeechToText(t,s,e.addNewErrorMessage.bind(e))});const a=new SubmitButton(t,s.inputElementRef,e,i,r);s.submit=a.submitFromInput.bind(a),t.submitUserMessage=a.submit.bind(a,!0),o.submit={button:a},Input.addElements(this.elementRef,s,o,n,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,n){var s,o,r,a;const l=new FileAttachments(this.elementRef,t.attachmentContainerStyle,e.demo);if(Input.createUploadButtons(e.fileTypes||{},l,i,n),null!=(s=e.camera)&&s.files){const t=(null==(o=n.images)?void 0:o.fileType)||l.addType(e.camera.files,"images");n.camera={button:new CameraButton(i,t,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const t=(null==(a=n.audio)?void 0:a.fileType)||l.addType(e.recordAudio.files,"audio");n.microphone={button:new RecordAudio(t,e.recordAudio)}}return DragAndDrop.isEnabled(l,t.dragAndDrop)&&DragAndDrop.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,n){Object.keys(t).forEach((s=>{const o=s,r=t[o];if(r.files){const t=e.addType(r.files,o),{id:s,svgString:a,dropupText:l}=FILE_TYPE_BUTTON_ICONS[o],c=new UploadFileButton(i,t,r,s,a,l);n[o]={button:c,fileType:t}}}))}static addElements(t,e,i,n,s,o){ElementUtils.addElements(t,e.elementRef);const r=ButtonContainers.create(),a=InputButtonPositions.addButtons(r,i,n,o);InputButtonStyleAdjustments.set(e.inputElementRef,r,s.elementRef,a),ButtonContainers.add(t,r)}}class ChatView{static createElements(t,e,i){const n=document.createElement("div");n.id="chat-view";const s=new Messages(t,e,i);e.websocket&&Websocket.assignListeners(e,s);const o=new Input(t,s,e,n);return ElementUtils.addElements(n,s.elementRef,o.elementRef),n}static render(t,e,i,n){const s=ChatView.createElements(t,i,n);e.replaceChildren(s)}}const style='#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#large-loading-ring{display:inline-block;width:50px;height:50px}#large-loading-ring:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:large-loading-ring 1.4s linear infinite}@keyframes large-loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-ring{display:inline-block;width:16px;height:16px}#loading-ring:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-ring 1.2s linear infinite}@keyframes loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}.intro-panel{position:absolute;display:flex;justify-content:center;inset:0px;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;width:90%;margin-left:auto;margin-right:auto;max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.loading-message-text{width:1em;padding:.6em .75em .6em 1.3em}.message-bubble>p{line-height:1.26em}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message-bubble{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;user-select:none}.not-removable-attachment-icon{inset:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;inset:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.dots-jumping{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:dots-jumping 1.5s infinite linear;bottom:-.7em}@keyframes dots-jumping{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.dots-flashing{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite linear alternate;animation-delay:.5s}.dots-flashing:before,.dots-flashing:after{content:"";display:inline-block;position:absolute;top:0}.dots-flashing:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:0s}.dots-flashing:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:1s}@keyframes dots-flashing{0%{background-color:var(--message-dots-color)}50%,to{background-color:var(--message-dots-color-fade)}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.loading-button{background-color:#fff;cursor:auto}.loading-button:hover,.loading-button:active{background-color:#fff}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;user-select:none}.text-input-placeholder{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0px}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item>*{pointer-events:none}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}:host{all:initial;display:table-cell}#container{height:350px;width:320px;border:1px solid #cacaca;font-family:Inter,sans-serif,Avenir,Helvetica,Arial;font-size:.9rem;background-color:#fff;position:relative;overflow:hidden}\n';var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,i,n)=>{for(var s,o=n>1?void 0:n?__getOwnPropDesc(e,i):e,r=t.length-1;r>=0;r--)(s=t[r])&&(o=(n?s(e,i,o):s(o))||o);return n&&o&&__defProp(e,i,o),o};class DeepChat extends InternalHTML{constructor(){super(),this.initialMessages=void 0,this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>{FocusUtils.focusFromParentElement(this._elementRef)},this.refreshMessages=()=>{},this.onNewMessage=()=>{},this.onComponentRender=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,GoogleFont.appendStyleSheetToHead(),this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),WebComponentStyleUtils.apply(style,this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateConfigKey=!1),this.onRender()}onRender(){var t,e;this._activeService??(this._activeService=ServiceIOFactory.create(this)),this._activeService&&(this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(WebComponentStyleUtils.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),Object.assign(this._elementRef.style,this.containerStyle),this._activeService.key&&this._activeService.validateConfigKey?ValidateKeyPropertyView.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof DirectServiceIO&&this._activeService.key||null!=(t=this.request)&&t.url||null!=(e=this.directConnection)&&e.demo?(this._childElement??(this._childElement=this.children[0]),ChatView.render(this,this._elementRef,this._activeService,this._childElement)):this._activeService instanceof DirectServiceIO?InsertKeyView.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):ErrorView.render(this._elementRef,'Please define "request" with a "url"'),this._hasBeenRendered=!0,FireEvents.onRender(this))}}__decorateClass([Property("object")],DeepChat.prototype,"directConnection",2),__decorateClass([Property("object")],DeepChat.prototype,"request",2),__decorateClass([Property("boolean")],DeepChat.prototype,"stream",2),__decorateClass([Property("object")],DeepChat.prototype,"requestBodyLimits",2),__decorateClass([Property("function")],DeepChat.prototype,"requestInterceptor",2),__decorateClass([Property("function")],DeepChat.prototype,"responseInterceptor",2),__decorateClass([Property("function")],DeepChat.prototype,"validateMessageBeforeSending",2),__decorateClass([Property("object")],DeepChat.prototype,"containerStyle",2),__decorateClass([Property("object")],DeepChat.prototype,"attachmentContainerStyle",2),__decorateClass([Property("object")],DeepChat.prototype,"dropupStyles",2),__decorateClass([Property("object")],DeepChat.prototype,"inputAreaStyle",2),__decorateClass([Property("object")],DeepChat.prototype,"textInput",2),__decorateClass([Property("object")],DeepChat.prototype,"submitButtonStyles",2),__decorateClass([Property("string")],DeepChat.prototype,"auxiliaryStyle",2),__decorateClass([Property("array")],DeepChat.prototype,"initialMessages",2),__decorateClass([Property("string")],DeepChat.prototype,"introMessage",2),__decorateClass([Property("object")],DeepChat.prototype,"avatars",2),__decorateClass([Property("object")],DeepChat.prototype,"names",2),__decorateClass([Property("boolean")],DeepChat.prototype,"displayLoadingBubble",2),__decorateClass([Property("object")],DeepChat.prototype,"errorMessages",2),__decorateClass([Property("object")],DeepChat.prototype,"messageStyles",2),__decorateClass([Property("object")],DeepChat.prototype,"textToSpeech",2),__decorateClass([Property("object")],DeepChat.prototype,"speechToText",2),__decorateClass([Property("object")],DeepChat.prototype,"images",2),__decorateClass([Property("object")],DeepChat.prototype,"gifs",2),__decorateClass([Property("object")],DeepChat.prototype,"camera",2),__decorateClass([Property("object")],DeepChat.prototype,"audio",2),__decorateClass([Property("object")],DeepChat.prototype,"microphone",2),__decorateClass([Property("object")],DeepChat.prototype,"mixedFiles",2),__decorateClass([Property("object")],DeepChat.prototype,"dragAndDrop",2),__decorateClass([Property("object")],DeepChat.prototype,"introPanelStyle",2),__decorateClass([Property("function")],DeepChat.prototype,"onNewMessage",2),__decorateClass([Property("function")],DeepChat.prototype,"onComponentRender",2),customElements.define("deep-chat",DeepChat);export{DeepChat};