@liip/liipgpt 3.14.0-rc.8 → 3.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chat/{chat-logic.svelte-ZWeWjJUU.js → chat-logic.svelte-hd47X3w3.js} +1 -1
- package/chat/{chat-panel-C3-EMtq_.js → chat-panel-CnJITRAx.js} +2 -2
- package/chat/{context-menu-D5odUEca.js → context-menu-DH67dP8S.js} +1 -1
- package/chat/{embed-buttons-BeVL-8y6.js → embed-buttons-CmtERkFx.js} +1 -1
- package/chat/{embed-combobox-4CAsoOjC.js → embed-combobox-Bhc2kelu.js} +1 -1
- package/chat/{fake-typing-html-DPkuXOHm.js → fake-typing-html-tsXUPRbS.js} +1 -1
- package/chat/liipgpt-chat.iife.js +2 -2
- package/chat/liipgpt-chat.js +3 -3
- package/chat/{menu-trigger-Cuu5xtMu.js → menu-trigger-Cfd-RPvo.js} +1 -1
- package/chat/{selectors-DvEzt7TH.js → selectors-CW0sK2NE.js} +1 -1
- package/chat/{transition-C-GmcvBc.js → transition-ntZQtJY1.js} +1 -1
- package/configurator/_app/env.js +1 -1
- package/configurator/_app/immutable/chunks/3-PKoknK.js +1 -0
- package/configurator/_app/immutable/chunks/{YOH2G2iz.js → B-Biam5E.js} +1 -1
- package/configurator/_app/immutable/chunks/{DVoW2IJZ2.js → B90HPtFX2.js} +1 -1
- package/configurator/_app/immutable/chunks/{DPuwLy6I.js → C57s_a4s.js} +2 -2
- package/configurator/_app/immutable/chunks/C6zVetzL2.js +2 -0
- package/configurator/_app/immutable/chunks/{C4l7RRn2.js → CCRsz3Cq.js} +1 -1
- package/configurator/_app/immutable/chunks/{DgswhBqn2.js → CKQKer202.js} +1 -1
- package/configurator/_app/immutable/chunks/{Djmbd3Ed.js → C_Kt29nP.js} +1 -1
- package/configurator/_app/immutable/chunks/{CW8c3Z5e2.js → Cihuaehn2.js} +1 -1
- package/configurator/_app/immutable/chunks/{Dk8xIq6p2.js → D-QExoGk2.js} +1 -1
- package/configurator/_app/immutable/chunks/D0mVOhkG.js +1 -0
- package/configurator/_app/immutable/chunks/{CWG30fYe.js → D8Mbx1aL.js} +1 -1
- package/configurator/_app/immutable/chunks/{D5b1xIAm.js → D96zbh9g.js} +1 -1
- package/configurator/_app/immutable/chunks/{BMivt9VD2.js → DgBOADWO2.js} +1 -1
- package/configurator/_app/immutable/chunks/{Cqa89i-_.js → DwtB5Nu2.js} +1 -1
- package/configurator/_app/immutable/chunks/{BoRo9o--.js → otcMOlHV.js} +1 -1
- package/configurator/_app/immutable/chunks/{B4ROOhtb2.js → q5EYe7vB2.js} +3 -3
- package/configurator/_app/immutable/entry/{app.CcuvgSxg.js → app.CqMp7M7Z.js} +2 -2
- package/configurator/_app/immutable/entry/start.IPJ3KCZ_.js +1 -0
- package/configurator/_app/immutable/nodes/{0.B1FQTCsu.js → 0.C3BS1E4u.js} +1 -1
- package/configurator/_app/immutable/nodes/{1.Ck6Ov61G.js → 1.BI0jtTlM.js} +1 -1
- package/configurator/_app/immutable/nodes/{2.CGZBQn_E.js → 2.D4p-rkZA.js} +3 -3
- package/configurator/_app/immutable/nodes/{3.D-z5IVuY.js → 3._lyZCdqa.js} +1 -1
- package/configurator/_app/version.json +1 -1
- package/configurator/index.html +6 -6
- package/configurator/sidebar.html +6 -6
- package/package.json +1 -1
- package/configurator/_app/immutable/chunks/D8-gl1YT.js +0 -1
- package/configurator/_app/immutable/chunks/DV_97jct2.js +0 -2
- package/configurator/_app/immutable/chunks/DoBOh2hq.js +0 -1
- package/configurator/_app/immutable/entry/start.uMPWJBuj.js +0 -1
|
@@ -59,4 +59,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
59
59
|
`+i:t[r]=i)}.bind(this)),t.id!==null&&t.id.indexOf(`\0`)===-1&&(this.lastEventId=t.id),t.retry!==null&&/^[0-9]+$/.test(t.retry)&&(this.reconnectDelay=parseInt(t.retry,10)),t.data===null)return null;let n=new CustomEvent(t.event||`message`);return n.id=t.id,n.data=t.data||``,n.lastEventId=this.lastEventId,n},this._onReadyStateChange=function(){if(this.xhr&&this.xhr.readyState===XMLHttpRequest.HEADERS_RECEIVED){let e={},t=this.xhr.getAllResponseHeaders().trim().split(`\r
|
|
60
60
|
`);for(let n of t){let[t,...r]=n.split(`:`),i=r.join(`:`).trim();e[t.trim().toLowerCase()]=e[t.trim().toLowerCase()]||[],e[t.trim().toLowerCase()].push(i)}let n=new CustomEvent(`open`);n.responseCode=this.xhr.status,n.headers=e,this.dispatchEvent(n),this._setReadyState(X.OPEN)}},this.stream=function(){if(!this.xhr){this._setReadyState(X.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener(`progress`,this._onStreamProgress.bind(this)),this.xhr.addEventListener(`load`,this._onStreamLoaded.bind(this)),this.xhr.addEventListener(`readystatechange`,this._onReadyStateChange.bind(this)),this.xhr.addEventListener(`error`,this._onStreamFailure.bind(this)),this.xhr.addEventListener(`abort`,this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url);for(let e in this.headers)this.xhr.setRequestHeader(e,this.headers[e]);this.useLastEventId&&this.lastEventId.length>0&&this.xhr.setRequestHeader(`Last-Event-ID`,this.lastEventId),this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)}},this.close=function(){this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.autoReconnect=!1,this.xhr&&this.xhr.abort()},(t.start===void 0||t.start)&&this.stream()};X.INITIALIZING=-1,X.CONNECTING=0,X.OPEN=1,X.CLOSED=2;var Ni=class{eventSource;triggeredOnClose=!1;constructor(e,t,n){this.options=t,this.payload=n;let r={headers:{"content-type":`application/json`}};n&&(r.payload=JSON.stringify(n)),t.apiKey&&(r.headers[`api-key`]=t.apiKey),this.eventSource=new(t.EventSource??X)(e,r),this.eventSource.onmessage=e=>{try{let n=JSON.parse(e.data);t.onMessage(n)}catch(e){t.onError(new CustomEvent(`parse-error`,{detail:e}))}},this.eventSource.onerror=e=>{t.onError(e),this.isClosed()&&this.close()}}isClosed(){return this.eventSource.readyState===EventSource.CLOSED}close(){this.isClosed()||this.eventSource.close(),this.triggeredOnClose||(this.triggeredOnClose=!0,this.options.onClose())}},Pi=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),Fi=class{constructor(e){this.options=e}getDefaultHeaders(e={}){let t={"Content-Type":`application/json`,...e};return this.options.apiKey&&(t[`api-key`]=this.options.apiKey),t}get speechRecognitionApiKey(){return this.options.speechRecognitionApiKey}async subscribeSse(e,t={},n){let r=Pi(t);return this.options.apiKey&&(n.apiKey=this.options.apiKey),new Ni(`${this.options.apiUrl}${e}`,n,r)}async fetchData(e,t,n={},r={}){let i=`${this.options.apiUrl}${e}?${new URLSearchParams(Pi(n)).toString()}`,a={...r,headers:this.getDefaultHeaders(r?.headers)},o=await fetch(i,a);if(!o.ok){let e=await o.text();throw Error(`API request failed: ${o.status} - ${e}`)}let s=await o.json(),c=t.safeParse(s);if(this.options.strict){if(!c.success)throw console.error(`Server response has wrong type:
|
|
61
61
|
`,{error:c.error,url:i,opts:a,data:s}),Error(`Server response has wrong type: ${c.error.message}`);return c.data}else return c.success||console.warn(`Server response has wrong type:
|
|
62
|
-
`,{error:c.error,url:i,opts:a,data:s}),s}async postData(e,t){let n=await fetch(`${this.options.apiUrl}${e}`,{method:`POST`,headers:this.getDefaultHeaders(),body:JSON.stringify(t)});if(!n.ok){let e=await n.text();throw Error(`${n.status} - ${e}`)}return n}async postFormData(e,t){let n=await fetch(`${this.options.apiUrl}${e}`,{method:`POST`,body:t});if(!n.ok){let e=await n.text();throw Error(`${n.status} - ${e}`)}return n}},Ii=K({links:ei(ii([K({url:q(Kr()),title:q(G()),considered:q(Qr()),orgMetadata:q(K({authors:q(ei(G()))})),type:q(G()),date:q(pi()),similarity:q(Jr()),content:q(G()),fromFullTextSearch:q(Qr()),rerank:q(K({index:q(Xr()),adjustment:q(Jr()),score:q(Jr()),similarityOld:q(Jr())}))}),mi]))}),Li=e=>{if(`metadata`in e)return e;console.warn(`Please upgrade your backend you are currently using an old api feature.`);let t=e.orgMetadata??{};e?.fromFullTextSearch&&(t.fromFullTextSearch=e?.fromFullTextSearch),e?.rerank&&(t.rerank=e?.rerank);let n=[],r=e.title??``;if(e.title&&e.title.includes(` > `)){let t=e.title.split(` > `);r=t.pop()??``,n=t}return{url:e.url??``,title:r,score:e.similarity||0,breadcrumbs:n,metadata:t,description:e.content,date:e.date}},Ri=class{id;constructor(e){this.chatResponseData=e,this.id=this.chatResponseData.id}async isReadyForFeedback(){return await this.chatResponseData.readyForFeedback.toPromise(),!0}subscribe(e,t){return this.chatResponseData.readableStore.subscribe(e,t)}getContent(){return this.chatResponseData.content.toPromise()}abort(){return this.chatResponseData.abort()}async thumbsUp(){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.thumbsUp(this.id,this.chatResponseData.question)}async thumbsDown(){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.thumbsDown(this.id,this.chatResponseData.question)}async feedback(e){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.feedback(this.id,this.chatResponseData.question,e)}};function zi(){let e,t;return{promise:new Promise((n,r)=>{t=n,e=r}),reject:e,resolve:t}}var Bi=class{promise;resolve;reject;constructor(){let{promise:e,resolve:t,reject:n}=zi();this.promise=e,this.resolve=t,this.reject=n}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}toPromise(){return this.promise}[Symbol.toStringTag]=`Flag`},Vi=class{hasValue=new Bi;currentValue;setValue(e){this.currentValue=e,this.hasValue.resolve()}cleanup(e){this.hasValue.reject(e)}getCurrentValue(){return this.currentValue}async toPromise(){return await this.hasValue,this.currentValue}then(e,t){return this.toPromise().then(e,t)}catch(e){return this.toPromise().catch(e)}finally(e){return this.toPromise().finally(e)}[Symbol.toStringTag]=`FutureValue`},Hi=e=>{try{return new URL(e).hostname}catch{return e}};function Ui(e){return e.replace(/<[^>]*>/g,``).replace(/ /g,` `).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var Wi=({citationId:e,url:t,considered:n,title:r,description:i,summary:a})=>{let o=Hi(t),s=i||a;return{...e?{citationId:e}:{},url:t,considered:n,referenceIndex:{},score:0,metadata:{},display:{card:{title:r,description:s,badge:t},listItem:{title:r,badge:o}}}},Gi=class{store;content=new Vi;backendSendsMappedRefs=!1;constructor(e){this.options=e,this.store=o({id:e.id,state:`loading`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:``,html:``,text:``},references:{all:[],used:[],unused:[]},retrievalQuestion:e.userQuestion})}pushError(e,t){this.options.onError?.(e,t),this.store.update(t=>({...t,errors:[...t.errors,e]}))}updateRequestId(e){this.store.update(t=>({...t,id:e}))}updateText(e){this.store.update(t=>{let n=t.message.markdown+e,r=this.options.markdownRenderer.toHTML(n,t.references);return{...t,state:`streaming`,message:{markdown:n,html:r,text:``}}})}finishMessage(){this.store.update(e=>{let t={...e,state:`done`};return t.references.unused=t.references.all.filter(e=>e.referenceIndex.used===void 0),t.message.text=Ui(t.message.html),this.options?.onFinish?.(t),this.content.setValue(t),t})}addReference(e){this.store.update(t=>{let n=t.references.all,r=n.length,i=[...n,{...e,referenceIndex:{all:r}}];return{...t,references:{used:t.references.used,all:i}}})}addMappedReference(e){this.backendSendsMappedRefs=!0,this.addReference(e)}addOldReference(e){this.backendSendsMappedRefs||this.addReference(Wi(e))}updateRetrievalQuestion(e){this.store.update(t=>({...t,retrievalQuestion:e}))}setNoFeedback(){this.store.update(e=>({...e,noFeedback:!0}))}getReadableStore(){return{subscribe:this.store.subscribe}}getPromise(){return this.content.toPromise()}},Ki=7,qi=8,Ji=160,Yi=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===`<`){let r=e.indexOf(`>`,n);if(r!==-1){t.push({type:`tag`,value:e.slice(n,r+1)}),n=r+1;continue}}if(/\s/.test(r)){let r=n;for(;r<e.length&&/\s/.test(e[r]);)r++;t.push({type:`space`,value:e.slice(n,r)}),n=r;continue}let i=n;for(;i<e.length&&!/\s/.test(e[i])&&e[i]!==`<`;)i++;t.push({type:`word`,value:e.slice(n,i)}),n=i}return t},Xi=e=>{let t=Yi(e),n=[],r=``,i=!1;for(let e of t)e.type===`space`&&i?(n.push(r),r=e.value,i=!1):(r+=e.value,e.type===`word`&&(i=!0));return r&&n.push(r),n},Zi=e=>Math.max(qi,Math.min(Ji,e.length*Ki)),Qi=class{queue=[];timeoutId=null;isProcessing=!1;constructor(e){this.onText=e}ingestText(e){let t=Xi(e);if(t.length>=5){for(let e of t)this.queue.push({kind:`text`,chunk:e,delayMs:Zi(e)});this.kickoff();return}this.runAfterTyping(()=>this.onText(e))}runAfterTyping(e){if(this.queue.length===0&&!this.isProcessing){e();return}this.queue.push({kind:`fn`,fn:e}),this.kickoff()}runWithWarmup(e){this.queue.push({kind:`fn`,fn:e}),this.kickoff()}clear(){this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.queue=[],this.isProcessing=!1}kickoff(){this.isProcessing||this.timeoutId!==null||(this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.processNext()},750))}processNext(){let e=this.queue.shift();if(!e){this.isProcessing=!1;return}this.isProcessing=!0,e.kind===`text`?(this.onText(e.chunk),this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.processNext()},e.delayMs)):(e.fn(),this.processNext())}},$i=class{constructor(e){this.results=e}},ea=45e3,ta=class{internalData;renderers=new Map;markedExtensions=[];_newTabSrText;chatTimeout;constructor(e){this.chatTimeout=e.chatTimeout??ea;let t=new Fi({apiUrl:e.apiUrl,apiKey:e.apiKey,speechRecognitionApiKey:e.speechRecognitionApiKey,strict:e.strict??!1,EventSource:e.EventSource??EventSource});this.internalData={restClient:t,metadata:Mi(t,e.startParameters),searchResponseMap:new Map,chatResponseMap:new Map,conversationMap:new Map}}setMarkedExtensions(...e){this.markedExtensions=e}setNewTabSrText(e){this._newTabSrText=e}getMetadata(){return this.internalData.metadata}createConversationId(){let e=Di();return this.renderers.set(e,new Dn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText})),e}chat(e,t,n={}){let r=new Vi,i=Di(),a=new Bi,o=new Gi({id:i,onError:(e,t)=>{n.onError?.(e,t)},onFinish:e=>{r.setValue(e)},markdownRenderer:this.renderers.get(e)??new Dn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText}),userQuestion:t}),s=async()=>{await a,!(f&&!c.getCurrentValue())&&(await c).close()},c=new Vi,l=new Qi(e=>o.updateText(e)),u=n.timeout??this.chatTimeout,d,f=!1,p=()=>{d!==void 0&&clearTimeout(d),d=void 0},m=()=>{f=!0,d=void 0,console.error(`No SSE activity for ${u}ms, giving up on chat request ${i}`),l.clear(),o.pushError(`sse-error`);let e=c.getCurrentValue();if(e){e.close();return}o.finishMessage(),a.resolve()},ee=()=>{p(),u>0&&!f&&(d=setTimeout(m,u))};ee(),(async()=>{let s=await this.internalData.metadata;if(s.mode===`maintenance`)throw Error(`Can not chat in maintenance mode`);let u=await this.internalData.restClient.subscribeSse(`/assistant/sse`,{query:t,uID:s.userId,cID:e,rID:i,lang:n.lang,feature:n.features?.join(`,`),referrer:n.referrer,source:n.source,...n.selectorValues??{},...n.mode?{mode:n.mode}:{},...n.cache?{cache:!0}:{},...n.predefinedQuestionId?{predefinedQuestionId:n.predefinedQuestionId}:{},...n.switchQuestionId?{switchQuestionId:n.switchQuestionId}:{},chat:`true`,version:`2`},{onClose:()=>{p(),l.clear(),o.finishMessage(),a.resolve(),r.cleanup()},onMessage:t=>{let r=t;switch(ee(),r.type){case`error`:l.runAfterTyping(()=>o.pushError(r.error,r.message));break;case`id`:r.for===`request`&&i!==r.id&&console.warn(`Unexpected request id "${r.id}" expected "${i}"`),r.for===`conversation`&&e!==r.id&&console.warn(`Unexpected conversation id "${r.id}" expected "${e}"`);break;case`state`:r.state===`history-entry-initialized`&&a.resolve();break;case`text`:l.ingestText(r.text);break;case`done`:case`answer-done`:p(),l.runAfterTyping(()=>{o.finishMessage(),a.resolve(),c.then(e=>e.close())});break;case`unexpected-call`:l.runAfterTyping(()=>{console.error(`unexpected-call:`,r),o.pushError(`unexpected-call`)});break;case`jsonld-component`:case`mapped-reference`:l.runAfterTyping(()=>o.addMappedReference(r.reference));break;case`reference`:l.runAfterTyping(()=>o.addOldReference(r.reference));break;case`retrieval-question`:l.runAfterTyping(()=>o.updateRetrievalQuestion(r.question));break;case`no-feedback`:l.runAfterTyping(()=>o.setNoFeedback());break;case`component`:l.runWithWarmup(()=>n.onEmbed?.(r));break}l.runAfterTyping(()=>n.onMessage?.(r))},onError:e=>{console.error(` sse-error:`,e),!(`data`in e&&!e.data&&`responseCode`in e&&e.responseCode===0)&&o.pushError(`sse-error`)}});c.setValue(u),f&&u.close()})();let h=new Ri({question:t,id:i,content:r,readableStore:o.getReadableStore(),readyForFeedback:a,abort:s,liipgptClientPrimitive:this});return this.internalData.chatResponseMap.set(h.id,h),h}async thumbs(e,t,n){if((await this.internalData.metadata).mode!==`ready`)throw Error(`Can not post feedback unless we are in ready mode`);let r={feedback:n,rID:e,query:t};await this.internalData.restClient.postData(`/quickfeedback`,r)}thumbsUp(e,t){return this.thumbs(e,t,`positive`)}thumbsDown(e,t){return this.thumbs(e,t,`negative`)}async feedback(e,t,n){let r=await this.internalData.metadata;if(r.mode!==`ready`)throw Error(`Can not post feedback unless we are in ready mode`);if(n.message){let i={body:n.message,email:n.email,rID:e,uID:r.userId,query:t};await this.internalData.restClient.postData(`/feedback`,i)}n.classification&&await this.internalData.restClient.postData(`/classification`,{impact:n.classification.impact,quality:n.classification.quality,rID:e})}async submitAnswerForm(e){let t=await this.internalData.metadata;if(t.mode!==`ready`)throw Error(`Can not submit the answer form unless we are in ready mode`);let n={receiverEmail:e.receiverEmail,fields:e.fields,query:e.question,answer:e.answer,rID:e.requestId,uID:t.userId,lang:e.lang};await this.internalData.restClient.postData(`/customform`,n)}async userAction(e,t={}){let n=await this.internalData.metadata;if(n.mode!==`ready`)throw Error(`Can not post user action unless we are in ready mode`);let r={uID:n.userId,cID:t.conversationId,lang:t.lang,userAction:e};await this.internalData.restClient.postData(`/assistant/userAction`,r)}async search(e,t={}){let n=await this.internalData.metadata,r=n.mode===`ready`?n.userId:void 0,{links:i}=await this.internalData.restClient.fetchData(`/assistant/search`,Ii,{modelId:t.model,lang:t.language,query:e,mapResults:`true`,uID:r});return new $i(i.map(Li))}async getChatConfig(){return this.internalData.restClient.fetchData(`/chatconfig`,vi)}async getChatHistory(e,t){try{let n=await this.internalData.restClient.postData(`/chathistory`,{cID:e,uID:t}),r=hi.safeParse(await n.json());return r.success?r.data:[]}catch(e){return console.error(`Failed to load chat history:`,e),[]}}async getPredefinedQuestions(e){return(await this.internalData.restClient.fetchData(`/topics/questions`,gi,e)).predefinedQuestions}async transcribeAudio(e,t={}){let n=await this.internalData.metadata,r=t.lang||`de-CH`;if(n.mode===`maintenance`)throw Error(`Can not transcribe audio in maintenance mode`);try{let t=(e=>e.includes(`mp4`)?`mp4`:e.includes(`webm`)?`webm`:(e.includes(`wav`),`wav`))(e.type),n=new FormData;return n.append(`file`,e,`audio.${t}`),n.append(`lang`,r),n.append(`type`,e.type),{transcript:await(await this.internalData.restClient.postFormData(`/speech?key=${this.internalData.restClient.speechRecognitionApiKey||``}&lang=${r}`,n)).text()||``,error:void 0}}catch(e){return console.error(`Error transcribing audio:`,e),{transcript:``,error:e instanceof Error?e.message:`Unknown error`}}}},na=(e,t)=>{try{let n=new URL(e),r=new URL(t);return n.origin===r.origin&&n.pathname===r.pathname}catch{return!1}},ra=e=>{try{return new URL(e).origin===window.location.origin}catch{return!1}},ia=()=>`${window.location.protocol}//${window.location.host}${window.location.pathname}`;function aa(e,{embedded:t}){let n=e??`all`;if(n===`none`)return;if(t||n===`location`)return ia();let r=na(document.referrer,window.location.href)?``:document.referrer;if(r&&!(n===`own`&&!ra(r)))return r}var oa=f(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}}));function sa(...e){return e.filter(Boolean).join(` `)}var ca=typeof document<`u`,la=typeof window<`u`?window:void 0;typeof window<`u`&&window.document,typeof window<`u`&&window.navigator,typeof window<`u`&&window.location;function ua(e){let t=e.activeElement;for(;t?.shadowRoot;){let e=t.shadowRoot.activeElement;if(e===t)break;t=e}return t}var da=class extends Map{#e=new Map;#t=t(0);#n=t(0);#r=_||-1;constructor(e){if(super(),e){for(var[t,n]of e)super.set(t,n);this.#n.v=super.size}}#i(e){return _===this.#r?t(e):ie(e)}has(e){var t=this.#e,n=t.get(e);if(n===void 0)if(super.has(e))n=this.#i(0),t.set(e,n);else return g(this.#t),!1;return g(n),!0}forEach(e,t){this.#a(),super.forEach(e,t)}get(e){var t=this.#e,n=t.get(e);if(n===void 0)if(super.has(e))n=this.#i(0),t.set(e,n);else{g(this.#t);return}return g(n),super.get(e)}set(e,t){var r=this.#e,i=r.get(e),a=super.get(e),o=super.set(e,t),s=this.#t;if(i===void 0)i=this.#i(0),r.set(e,i),c(this.#n,super.size),n(s);else if(a!==t){n(i);var l=s.reactions===null?null:new Set(s.reactions);(l===null||!i.reactions?.every(e=>l.has(e)))&&n(s)}return o}delete(e){var t=this.#e,r=t.get(e),i=super.delete(e);return r!==void 0&&(t.delete(e),c(r,-1)),i&&(c(this.#n,super.size),n(this.#t)),i}clear(){if(super.size!==0){super.clear();var e=this.#e;c(this.#n,0);for(var t of e.values())c(t,-1);n(this.#t),e.clear()}}#a(){g(this.#t);var e=this.#e;if(this.#n.v!==e.size){for(var t of super.keys())if(!e.has(t)){var n=this.#i(0);e.set(t,n)}}for([,n]of this.#e)g(n)}keys(){return g(this.#t),super.keys()}values(){return this.#a(),super.values()}entries(){return this.#a(),super.entries()}[Symbol.iterator](){return this.entries()}get size(){return g(this.#n),super.size}};new class{#e;#t;constructor(e={}){let{window:t=la,document:n=t?.document}=e;t!==void 0&&(this.#e=n,this.#t=l(e=>{let n=te(t,`focusin`,e),r=te(t,`focusout`,e);return()=>{n(),r()}}))}get current(){return this.#t?.(),this.#e?ua(this.#e):null}};function fa(e){return typeof e==`function`}var pa=class{#e;#t;constructor(e){this.#e=e,this.#t=Symbol(e)}get key(){return this.#t}exists(){return me(this.#t)}get(){let e=d(this.#t);if(e===void 0)throw Error(`Context "${this.#e}" not found`);return e}getOr(e){let t=d(this.#t);return t===void 0?e:t}set(e){return a(this.#t,e)}};function ma(e,t){switch(e){case`post`:pe(t);break;case`pre`:ee(t);break}}function ha(e,t,n,r={}){let{lazy:i=!1}=r,a=!i,o=Array.isArray(e)?[]:void 0;ma(t,()=>{let t=Array.isArray(e)?e.map(e=>e()):e();if(!a){a=!0,o=t;return}let r=oe(()=>n(t,o));return o=t,r})}function ga(e,t,n){let r=p(()=>{let i=!1;ha(e,t,(e,t)=>{if(i){r();return}let a=n(e,t);return i=!0,a},{lazy:!0})});pe(()=>r)}function _a(e,t,n){ha(e,`post`,t,n)}function va(e,t,n){ha(e,`pre`,t,n)}_a.pre=va;function ya(e,t){ga(e,`post`,t)}function ba(e,t){ga(e,`pre`,t)}ya.pre=ba;function xa(e){return fa(e)?e():e}var Sa=class{#e={width:0,height:0};#t=!1;#n;#r;#i;#a=s(()=>(g(this.#s)?.(),this.getSize().width));#o=s(()=>(g(this.#s)?.(),this.getSize().height));#s=s(()=>{let e=xa(this.#r);if(e)return l(t=>{if(!this.#i)return;let n=new this.#i.ResizeObserver(e=>{this.#t=!0;for(let t of e){let e=this.#n.box===`content-box`?t.contentBoxSize:t.borderBoxSize,n=Array.isArray(e)?e:[e];this.#e.width=n.reduce((e,t)=>Math.max(e,t.inlineSize),0),this.#e.height=n.reduce((e,t)=>Math.max(e,t.blockSize),0)}t()});return n.observe(e),()=>{this.#t=!1,n.disconnect()}})});constructor(e,t={box:`border-box`}){this.#i=t.window??la,this.#n=t,this.#r=e,this.#e={width:0,height:0}}calculateSize(){let e=xa(this.#r);if(!e||!this.#i)return;let t=e.offsetWidth,n=e.offsetHeight;if(this.#n.box===`border-box`)return{width:t,height:n};let r=this.#i.getComputedStyle(e),i=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight),a=parseFloat(r.paddingTop)+parseFloat(r.paddingBottom),o=parseFloat(r.borderLeftWidth)+parseFloat(r.borderRightWidth),s=parseFloat(r.borderTopWidth)+parseFloat(r.borderBottomWidth);return{width:t-i-o,height:n-a-s}}getSize(){return this.#t?this.#e:this.calculateSize()??this.#e}get current(){return g(this.#s)?.(),this.getSize()}get width(){return g(this.#a)}get height(){return g(this.#o)}},Ca=class{#e=()=>void 0;#t=s(()=>this.#e());constructor(e,t){let n;t!==void 0&&(n=t),this.#e=()=>{try{return n}finally{n=e()}}}get current(){return g(this.#t)}};function wa(e,t){let n,r=null;return(...i)=>new Promise(a=>{r&&r(void 0),r=a,clearTimeout(n),n=setTimeout(async()=>{let t=await e(...i);r&&=(r(t),null)},t)})}function Ta(e,t){let n=0,r=null;return(...i)=>{let a=Date.now();return n&&a-n<t?r??Promise.resolve(void 0):(n=a,r=e(...i),r)}}function Ea(e,n,i={},a){let{lazy:o=!1,once:s=!1,initialValue:l,debounce:u,throttle:d}=i,f=t(r(l)),p=t(!1),m=t(void 0),ee=t(r([])),h=()=>{g(ee).forEach(e=>e()),c(ee,[],!0)},te=e=>{c(ee,[...g(ee),e],!0)},ne=async(e,t,r=!1)=>{try{c(p,!0),c(m,void 0),h();let i=new AbortController;te(()=>i.abort());let a=await n(e,t,{data:g(f),refetching:r,onCleanup:te,signal:i.signal});return c(f,a,!0),a}catch(e){e instanceof DOMException&&e.name===`AbortError`||c(m,e,!0);return}finally{c(p,!1)}},_=u?wa(ne,u):d?Ta(ne,d):ne,re=Array.isArray(e)?e:[e],ie;return a((t,n)=>{s&&ie||(ie=t,_(Array.isArray(e)?t:t[0],Array.isArray(e)?n:n?.[0]))},{lazy:o}),{get current(){return g(f)},get loading(){return g(p)},get error(){return g(m)},mutate:e=>{c(f,e,!0)},refetch:t=>{let n=re.map(e=>e());return _(Array.isArray(e)?n:n[0],Array.isArray(e)?n:n[0],t??!0)}}}function Da(e,t,n){return Ea(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];_a(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}function Oa(e,t,n){return Ea(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];_a.pre(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}Da.pre=Oa,new pa(`richColorsContext`);var ka=new pa(`<Toaster/>`),Aa=0;function ja(e){return typeof e?.id==`number`||typeof e?.id==`string`&&e.id.length>0?e.id:Aa++}var Ma=class{#e=t(r([]));get toasts(){return g(this.#e)}set toasts(e){c(this.#e,e,!0)}#t=t(r([]));get heights(){return g(this.#t)}set heights(e){c(this.#t,e,!0)}#n=new Map;#r=e=>{let t=this.toasts.findIndex(t=>t.id===e);return t===-1?null:t};#i=e=>this.heights.findIndex(t=>t.toastId===e);addToast=e=>{ca&&this.toasts.unshift(e)};updateToast=({id:e,data:t,type:n,message:r})=>{let i=this.toasts.findIndex(t=>t.id===e),a=this.toasts[i];this.toasts[i]={...a,...t,id:e,title:r,type:n,dismiss:!1,delete:!1,updated:!0}};markDismissed=e=>{let t=this.#r(e);if(t===null)return;let n=this.toasts[t];n&&(!n.dismiss||!n.delete)&&(this.toasts[t]={...n,dismiss:!0,delete:!0})};scheduleRemoval=(e,t)=>{this.cancelRemoval(e),this.#n.set(e,setTimeout(()=>{this.#n.delete(e),this.remove(e)},t))};cancelRemoval=e=>{let t=this.#n.get(e);t!==void 0&&(clearTimeout(t),this.#n.delete(e))};create=e=>{let{message:t,...n}=e,r=ja(e),i=e.dismissible===void 0?e.dismissable===void 0?!0:e.dismissable:e.dismissible,a=e.type===void 0?`default`:e.type;return oe(()=>{this.cancelRemoval(r);let o=this.toasts.find(e=>e.id===r);o?.dismiss||o?.delete?(this.remove(r),this.addToast({...n,id:r,title:t,dismissible:i,type:a,updated:!0})):o?this.updateToast({id:r,data:e,type:a,message:t,dismissible:i}):this.addToast({...n,id:r,title:t,dismissible:i,type:a})}),r};dismiss=e=>(oe(()=>{if(e===void 0){this.toasts=this.toasts.map(e=>e.dismiss?e:{...e,dismiss:!0});return}let t=this.toasts.findIndex(t=>t.id===e);this.toasts[t]&&(this.toasts[t]={...this.toasts[t],dismiss:!0})}),e);remove=e=>{if(e===void 0){this.toasts=[];return}let t=this.#r(e);if(t!==null)return this.toasts.splice(t,1),e};message=(e,t)=>this.create({...t,type:`default`,message:e});error=(e,t)=>this.create({...t,type:`error`,message:e});success=(e,t)=>this.create({...t,type:`success`,message:e});info=(e,t)=>this.create({...t,type:`info`,message:e});warning=(e,t)=>this.create({...t,type:`warning`,message:e});loading=(e,t)=>this.create({...t,type:`loading`,message:e});promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:typeof t.loading==`string`?t.loading:t.loading()}));let r=e instanceof Promise?e:e(),i=n!==void 0;return r.then(e=>{if(typeof e==`object`&&e&&`ok`in e&&typeof e.ok==`boolean`&&!e.ok){i=!1;let t=Na(e);this.create({id:n,type:`error`,message:t})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?t.success(e):t.success;this.create({id:n,type:`success`,message:r})}}).catch(e=>{if(t.error!==void 0){i=!1;let r=typeof t.error==`function`?t.error(e):t.error;this.create({id:n,type:`error`,message:r})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally?.()}),n};custom=(e,t)=>{let n=ja(t);return this.create({component:e,...t,id:n}),n};removeHeight=e=>{this.heights=this.heights.filter(t=>t.toastId!==e)};setHeight=e=>{oe(()=>{let t=this.#i(e.toastId);if(t!==-1){this.heights[t]=e;return}let n=new Map(this.toasts.map((e,t)=>[e.id,t])),r=n.get(e.toastId)??-1,i=this.heights.findIndex(e=>(n.get(e.toastId)??1/0)>r);i===-1?this.heights.push(e):this.heights.splice(i,0,e)})};reset=()=>{this.toasts=[],this.heights=[],this.#n.forEach(e=>clearTimeout(e)),this.#n.clear()}};function Na(e){return e&&typeof e==`object`&&`status`in e?`HTTP error! Status: ${e.status}`:`Error! ${e}`}var Z=new Ma;function Pa(e,t){return Z.message(e,t)}var Fa=class{#e=s(()=>Z.toasts.filter(e=>!e.dismiss));get toasts(){return g(this.#e)}},Ia=Object.assign(Pa,{success:Z.success,info:Z.info,warning:Z.warning,error:Z.error,custom:Z.custom,message:Z.message,promise:Z.promise,dismiss:Z.dismiss,loading:Z.loading,getActiveToasts:()=>Z.toasts.filter(e=>!e.dismiss)}),La=e=>{let t=new Set;Object.getOwnPropertyNames(e).forEach(e=>t.add(e));let n=Object.getPrototypeOf(e);for(;n&&n!==Object.prototype;)Object.getOwnPropertyNames(n).forEach(e=>t.add(e)),n=Object.getPrototypeOf(n);return Array.from(t)},Ra=(e,t)=>{let n={};return t.forEach(t=>{n[t]=e[t]}),n},za=console.warn,Ba=()=>{},Va=(e,t)=>oe(()=>{console.warn=Ba;let n=i(t?Ra(e,t):e);return console.warn=za,n}),Ha=e=>e&&typeof e.then==`function`,Ua=class{config;self;devtools;stateKeys;constructor(e,t){this.config=e,this.self=t,typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&(this.stateKeys=La(this.config.state),this.devtools=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:this.config.name??`updatelogic`}),this.devtools.init(this.createStateSnapshot()),this.devtools.subscribe(e=>{e.type===`DISPATCH`&&e.state}))}createStateSnapshot(){return Va(this.config.state,this.stateKeys)}sendStart(e,t){this.devtools.send({type:`→ ${e}`,args:t},this.createStateSnapshot())}sendError(e,t,n){this.devtools.send({type:`❌ ${e}`,args:t,error:n},this.createStateSnapshot())}sendSuccess(e,t,n){this.devtools.send({type:`✓ ${e}`,args:t,return:n},this.createStateSnapshot())}isIncluded(e){return this.config.excludeInDevTools?!this.config.excludeInDevTools.includes(e):!0}createProxyFunction(e,t){let n=this.devtools&&this.isIncluded(e);return typeof t==`function`?(...r)=>{if(!n)return oe(()=>t.call(this.self,...r));let i=Va(r);this.sendStart(e,i);try{let n=oe(()=>t.call(this.self,...r));return Ha(n)?n.then(t=>(this.sendSuccess(e,i,t),t),t=>{throw this.sendError(e,i,t),t}):(this.sendSuccess(e,i,n),n)}catch(t){throw this.sendError(e,i,t),t}}:t}},Wa=(e,t)=>{let n={},r=new Ua(e,n);return Object.keys(t).forEach(e=>{if(e===`state`||e===`name`)return;let i=t[e];n[e]=r.createProxyFunction(e,i)}),n};async function Ga(){if(typeof navigator>`u`||!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return!1;try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>e.kind===`audioinput`)}catch(e){return console.error(`Error checking for microphone:`,e),!1}}function Ka(){return typeof window>`u`||!window.MediaRecorder?null:MediaRecorder.isTypeSupported(`audio/mp4`)?`audio/mp4`:MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:MediaRecorder.isTypeSupported(`audio/wav`)?`audio/wav`:null}function qa(){return typeof window>`u`?!1:!!(window.MediaRecorder&&Ka())}function Ja(){if(typeof window>`u`)return!1;if(`ontouchstart`in window||navigator.maxTouchPoints>0)return!0;let e=navigator.msMaxTouchPoints;return!!(`msMaxTouchPoints`in navigator&&e&&e>0)}function Ya(){return typeof window>`u`?!1:!!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||Ja())}var Xa=class{mediaRecorder=null;audioChunks=[];started=!1;starting=!1;stream=null;options;audioContext=null;analyser=null;dataArray=null;volumeUpdateInterval=null;constructor(e={}){this.options=e}async start(){if(this.started||this.starting){console.warn(`AudioRecorder: Start already in progress or already started`);return}if(!qa()||!navigator.mediaDevices){let e=Error(`MediaRecorder not supported or no microphone access`);throw this.options.onError?.(e),e}try{if(this.starting=!0,this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1}),!this.starting){this.stopStream(this.stream);return}this.mediaRecorder&&this.mediaRecorder.state!==`inactive`&&(console.warn(`AudioRecorder: MediaRecorder already active, stopping previous recording`),this.mediaRecorder.stop(),this.cleanup()),this.started=!0,this.starting=!1;let e=Ka();if(!e)throw Error(`No supported media type found`);let t={mimeType:e};this.mediaRecorder=new MediaRecorder(this.stream,t),this.audioChunks=[],this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&this.audioChunks.push(e.data)},this.mediaRecorder.onstop=async()=>{let t=this.audioChunks.length>0?new Blob(this.audioChunks,{type:e}):null;await this.options.onDataAvailable?.(t),this.options.onStop?.(),this.cleanup()},this.mediaRecorder.onerror=e=>{let t=Error(`MediaRecorder error: ${e}`);this.options.onError?.(t),this.cleanup()},this.mediaRecorder.start(),this.setupVolumeAnalysis(this.stream),this.options.onStart?.()}catch(e){this.started=!1,this.starting=!1;let t=e instanceof Error?e:Error(String(e));throw this.options.onError?.(t),t}}stop(){this.started=!1,this.starting=!1,this.volumeUpdateInterval&&=(clearInterval(this.volumeUpdateInterval),null),this.mediaRecorder&&this.mediaRecorder.state!==`inactive`?this.mediaRecorder.stop():(this.stream&&this.stopStream(this.stream),this.cleanup())}setupVolumeAnalysis(e){if(this.options.onVolumeChange)try{this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8;let t=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser),this.startVolumeMonitoring()}catch(e){console.warn(`Failed to set up volume analysis:`,e)}}startVolumeMonitoring(){!this.analyser||!this.dataArray||!this.options.onVolumeChange||(this.volumeUpdateInterval=window.setInterval(()=>{if(!this.analyser||!this.dataArray||!this.started)return;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t]*this.dataArray[t];let t=Math.sqrt(e/this.dataArray.length)/255;t=(t*3)**.7;let n=Math.min(100,Math.max(0,Math.round(t*100)));this.options.onVolumeChange?.(n)},100))}get recording(){return this.started&&this.mediaRecorder?.state===`recording`}get isStarting(){return this.starting}stopStream(e){e.getTracks().forEach(e=>e.stop())}cleanup(){this.volumeUpdateInterval&&=(clearInterval(this.volumeUpdateInterval),null),this.audioContext&&=(this.audioContext.close().catch(console.warn),null),this.analyser=null,this.dataArray=null,this.stream&&=(this.stopStream(this.stream),null),this.mediaRecorder=null,this.audioChunks=[],this.started=!1,this.starting=!1}static isSupported(){return qa()}static getSupportedMediaType(){return Ka()}},Za=lt(),Qa=(e,t)=>{if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){t.textContent=e.value;return}if(e instanceof HTMLSelectElement&&t instanceof HTMLSelectElement){Array.from(e.options).forEach((e,n)=>{t.options[n]&&(t.options[n].selected=e.selected)});return}e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&(t.setAttribute(`value`,e.value),(e.type===`checkbox`||e.type===`radio`)&&(e.checked?t.setAttribute(`checked`,`checked`):t.removeAttribute(`checked`)))},$a=e=>{let t=e.cloneNode(!0);if(!(t instanceof Element))return``;let n=`input, textarea, select`,r=e.querySelectorAll(n),i=t.querySelectorAll(n);return r.forEach((e,t)=>{let n=i[t];n&&Qa(e,n)}),Za.sanitize(t.outerHTML,{FORBID_TAGS:[`style`,`script`],FORBID_ATTR:[`style`,`class`]})},eo=e=>{if(!e?.length)return[];let t=e.join(`,`),n=document.querySelectorAll(t);return Array.from(n,$a)},to=`liipgpt:context`,no=()=>localStorage.getItem(to),ro=[{type:`email`,check:e=>/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/.test(e)},{type:`creditCard`,check:e=>/\b(?:\d[ -]*?){13,16}\b/.test(e)},{type:`ahv`,check:e=>/\b756[.\s-]?\d{2,4}[.\s-]?\d{2,4}[.\s-]?\d{2}\b/.test(e)},{type:`phoneSwiss`,check:e=>/\b0(?:\s*\d){2}(?:\s*\/\s*)?(?:\s*\d){7,}\b/.test(e)},{type:`phoneInternational`,check:e=>/(?:\+|00)(?:\s*\d){10,}\b/.test(e)},{type:`swissPassport`,check:e=>/\b[A-HJ-NP-Z](?=.*\d)[A-HJ-NP-Z0-9]{7}\b/.test(e)},{type:`longNumber`,check:e=>/\b\d{9,}\b/.test(e)}],io=e=>{for(let t of ro)if(t.check(e))return t.type},ao=`liipgpt:selectorValues`,oo=`liipgpt:selectorKnownDefaults`,so=()=>{try{let e=Y.getItem(ao),t=Y.getItem(oo);return e?{values:JSON.parse(e),knownDefaults:t?JSON.parse(t):{}}:null}catch{return null}},co=e=>{let t={};for(let n of e)t[n.settingName]=n.defaultValues??(n.allowEmpty?[]:[n.values[0]]).filter(Boolean);return t},lo=(e,t)=>{try{let n=co(t);Y.setItem(ao,JSON.stringify(e)),Y.setItem(oo,JSON.stringify(n))}catch(e){console.error(`Failed to save selector values:`,e)}},uo=e=>{try{let t=so();if(!t)return;delete t.values[e],delete t.knownDefaults[e],Y.setItem(ao,JSON.stringify(t.values)),Y.setItem(oo,JSON.stringify(t.knownDefaults))}catch(e){console.error(`Failed to clear selector saved state:`,e)}},fo=e=>{let t=so(),n=e.map(e=>{let n=e.defaultValues??(e.allowEmpty?[]:[e.values[0]]).filter(Boolean);if(!t?.values[e.settingName])return[e.settingName,n];let r=t.values[e.settingName],i=t.knownDefaults[e.settingName]||[],a=r.filter(t=>e.values.includes(t)),o=i.filter(e=>!n.includes(e)),s=a.filter(e=>!o.includes(e)),c=n.filter(e=>!i.includes(e)&&!s.includes(e)),l=[...s,...c];return l.length===0&&!e.allowEmpty?[e.settingName,n]:[e.settingName,l]});return Object.fromEntries(n)},po=class extends Error{constructor(e){super(e),this.name=`UnreachableError`}},mo=u({chatState:()=>h,logic:()=>ko}),ho=e(re(),1),go=e(oa(),1),_o=(e,t)=>{if(!e)return;let n=t.find(t=>t.id===e);return n||console.warn(`autofire-predefined-question-id="${e}" did not match any loaded predefined question. Falling back to default routing.`),n},vo=(e,t,n,r,i)=>{if(e&&!t)return{name:`consent-page`};let a=new URLSearchParams(window.location.search),o=a.get(`q`),s=a.get(`id`)??void 0,c=a.get(`sid`)??void 0;return o?{name:`chat-page`,query:o,predefinedQuestionId:s,switchQuestionId:c}:i?{name:`chat-page`,query:i}:r?{name:`chat-page`,query:r.question,predefinedQuestionId:r.id}:n?{name:`chat-page`}:{name:`start-page`}},yo=`follow-up-q`,bo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),xo=()=>{let e=new URLSearchParams(window.location.hash.replace(/^#/,``)).get(`cID`)??void 0;return{cID:e&&bo(e)?e:void 0,followUpQuestion:new URLSearchParams(window.location.search).get(yo)?.trim()||void 0}},So=()=>{let e=new URLSearchParams(window.location.search);if(!e.has(yo))return;e.delete(yo);let t=e.toString();history.replaceState(null,``,`${window.location.pathname}${t?`?${t}`:``}${window.location.hash}`)},Co=e=>{if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t;console.warn(`additional-start-parameters must be a JSON object. Received: ${e}`);return}catch(t){console.warn(`Failed to parse additional-start-parameters as JSON: ${e}`,t);return}},wo=e=>{let t=Co(e);return t?(e=>Array.isArray(e)?e.map(String):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(Boolean):[])(t.scopeAvailableSlugs).length===1:!1},To=e=>e?e.map(e=>({id:Ti(),...e})):[],Q,$,Eo,Do=new Set,Oo=async e=>{if(Do.has(e))return;let t=(await de([e]))[e];if(t){let n=h.data.chatConfig.translations[e]??{};h.data.chatConfig.translations[e]=(0,ho.default)(t,n)}Do.add(e)},ko=Wa({name:`chat-logic`,state:h,excludeInDevTools:[`onInput`]},{async init(e){$=e;let t=$.speechRecognitionApiKey||void 0;Q=new ta({apiUrl:$.apiUrl,apiKey:$.apiKey,speechRecognitionApiKey:t,strict:!0,startParameters:Co($.additionalStartParameters)});try{let e=await Q.getChatConfig();window.CHAT_CONFIG_OVERRIDE&&Object.assign(e,window.CHAT_CONFIG_OVERRIDE);let t=(await Q.getMetadata()).mode===`maintenance`;t&&this.showErrorToast(`maintenance`);let n=fe($.lang,v(e.supportedLanguages));Do.add(n);let r=se(e,await de([n]));$.inlineLayout!==void 0&&(r.inlineLayout=$.inlineLayout),$.forceChatPage!==void 0&&(r.forceChatPage=$.forceChatPage);let i=n;ne(i,h.targets.mainElement);let a=await this.getPredefinedQuestions(i),o=r.translations[i]?.ariaOpensInNewTab;o&&Q.setNewTabSrText(o);let s=[];if(r.renderKatex){let e=await import(`https://esm.sh/marked-katex-extension@5.1.5`).catch(e=>{console.error(`Couldn't load marked-katex-extension:`,e)});e&&(Q.setMarkedExtensions(e.default({nonStandard:!0,output:`mathml`})),s.push(`https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css`))}let c=Object.keys(r.fullTheme),l=!1;if(r.forceConsent)try{l=Y.getItem(`liipgpt:termsAccepted`)===`true`}catch(e){console.warn(`Failed to load terms acceptance from storage:`,e)}let u=_o($.autofirePredefinedQuestionId,a);h.data={currentConversationState:`idle`,chatConfig:r,language:i,predefinedQuestions:a,isInMaintenance:t,history:To(r.messageAdditions.init),selectedColorScheme:ce(),has2ColorSchemes:c.length===2,currentColorScheme:m(c),conversationFeedbackId:void 0,conversationFeedbackIsOpen:!1,answerFormMessageId:void 0,openedPopup:void 0,props:$,flyoutIsOpen:!1,questionHasPii:void 0,chatInputValue:``,selectorValues:fo(r.selectorsConfig),selectorsIsOpen:!1,predefinedQuestionId:void 0,switchQuestionId:void 0,currentReferencesAsideId:void 0,ariaLiveStatusMessage:void 0,ariaLiveStatusMessageClearingTimeout:void 0,wasReferencesAsideClosed:!1,isAsideMobile:!0,route:vo(r.forceConsent??!1,l,r.forceChatPage??!1,u,$.question),additionalStylesheets:s,hasOpenedOverlays:!1,isInlineLayoutContained:!1,termsAccepted:l,selectedTopic:void 0},window.LIIPGPT_LISTENERS?.route?.(h.data.route),window.LIIPGPT_LISTENERS?.conversation?.(h.data.currentConversationState),h.data.selectorsIsOpen=h.data.chatConfig.showExpandedSelectors??!1,h.initialized=!0,this.checkForOpenedPopup(),window.addEventListener(`hashchange`,()=>{this.checkForOpenedPopup()}),await this.startFromHandoverOrRoute(()=>this.goto(vo(r.forceConsent??!1,l,r.forceChatPage??!1,u,$.question),!0))}catch(e){throw Ia.error(e instanceof Error?e.message:`Failed to load the chatbot. Please reload the page.`,{duration:1e4,unstyled:!0,classes:{toast:`toast`}}),e}},setTarget(e,t){h.targets[e]=t},goto(e,t=!1){if(!(!t&&(0,go.default)(h.data.route,e)))switch(h.data.route=e,window.LIIPGPT_LISTENERS?.route?.(e),e.name){case`consent-page`:break;case`start-page`:e.prefill&&(h.data.chatInputValue=e.prefill);break;case`chat-page`:if(h.data.chatInputValue=e.query??``,h.data.predefinedQuestionId=e.predefinedQuestionId,h.data.switchQuestionId=e.switchQuestionId,e.query&&(this.onSubmit(),h.data.chatConfig.addQueryToUrlParams)){let t=new URLSearchParams(window.location.search);t.set(`q`,e.query),e.predefinedQuestionId?t.set(`id`,e.predefinedQuestionId):t.delete(`id`),e.switchQuestionId?t.set(`sid`,e.switchQuestionId):t.delete(`sid`),history.pushState(null,``,`?${t.toString()}${window.location.hash}`)}break}},getSelectorConfig(e){let t=h.data.chatConfig.selectorsConfig.find(t=>t.settingName===e);if(!t)throw Error(`Setting ${e} not found`);return t},getPrettifiedSelectorValues(){let e=Object.entries(h.data.selectorValues).map(([e,t])=>{let n;try{n=this.getSelectorConfig(e)}catch(t){console.error(`Error getting selector config for ${e}: ${t}`);return}return n.type===`single-select`?[e,t[0]]:[e,t]}).filter(e=>!!e);return Object.fromEntries(e)},setSelectorValue(e,t){let n=this.getSelectorConfig(e);if(!n){console.warn(`Trying to set setting ${e} but it is not defined in the chat config`);return}if(n.type===`single-select`&&t.length>1){console.warn(`Trying to set multiple values for single-select setting ${e}`);return}h.data.selectorValues[e]=t,lo(h.data.selectorValues,h.data.chatConfig.selectorsConfig)},resetSelectorToDefaults(e){let t=this.getSelectorConfig(e);if(!t){console.warn(`Trying to reset setting ${e} but it is not defined in the chat config`);return}let n=t.defaultValues??(t.allowEmpty?[]:[t.values[0]]).filter(Boolean);return uo(e),h.data.selectorValues[e]=n,lo(h.data.selectorValues,h.data.chatConfig.selectorsConfig),n},async getPredefinedQuestions(e){if($?.hidePredefinedQuestions)return[];try{return Q.getPredefinedQuestions({url:window.location.origin+window.location.pathname,language:e})}catch(e){return console.warn(`Failed to load predefined questions:`,e),[]}},setColorScheme(e){h.data.selectedColorScheme=e,h.data.currentColorScheme=ue(e),this.setAriaLiveStatusMessage(e===`dark`?h.t.ariaDarkSelected:h.t.ariaLightSelected)},async abort(){await Eo?.abort()},changeConversationState(e){h.data.currentConversationState=e,window.LIIPGPT_LISTENERS?.conversation?.(e)},onInput(e){h.data.chatConfig.blockPII&&(h.data.questionHasPii=io(e)),h.data.chatInputValue=e,h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0},onSubmit(e=!1,t,n=!1){let r=eo(h.data.chatConfig.parentPageContext?.extractSelectors);if(h.data.questionHasPii){console.warn(`Question contains PII, not submitting:`,h.data.questionHasPii);return}let i=h.data.chatConfig.questionPrefix?`${h.data.chatConfig.questionPrefix} ${h.data.chatInputValue}`:h.data.chatInputValue;n||(h.data.history.push(...To(h.data.chatConfig.messageAdditions.user.before)),h.data.history.push({type:`user`,time:new Date().toISOString(),message:h.data.chatInputValue}),h.data.history.push(...To(h.data.chatConfig.messageAdditions.user.after)));let a=h.data.history.push(...To(h.data.chatConfig.messageAdditions.bot.before));h.data.history.push({id:`UNRESOLVED`,state:`loading`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:``,html:``,text:``},references:{all:[],used:[],unused:[]}});let o=!1,s=!1,c={features:$.features?$.features.trim().split(`,`):[`formatting`],mode:$.mode||void 0,cache:$.cache||void 0,onError:(e,t)=>{this.showErrorToast(e,t),window.LIIPGPT_LISTENERS?.error?.(e,t),(e===`pii-detected`||e===`blocked`)&&this.editLatestQuestion()},onMessage:e=>{e.type===`topic-selected`&&(h.data.selectedTopic={label:e.label,placeholder:e.placeholder,locked:wo($.additionalStartParameters)}),e.type===`state`&&e.state!==`history-entry-initialized`&&!s&&(s=!0,this.setAriaLiveStatusMessage(h.t.ariaQuestionSent))},lang:h.data.language,selectorValues:{...this.getPrettifiedSelectorValues(),context:no(),...t},predefinedQuestionId:h.data.predefinedQuestionId,switchQuestionId:h.data.switchQuestionId,onEmbed:e=>{let t=h.data.history[a];t&&t.type===`bot`&&!t.message.markdown?(h.data.history[a]={...e,id:t.id??Ti()},o=!0):h.data.history.push({...e,id:Ti()})}};h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0,r.length&&(c.selectorValues.parentPageContextHtml=r),c.referrer=aa(h.data.chatConfig.sendReferrer,{embedded:!!h.data.props.flyout}),h.data.props.source?c.source=h.data.props.source:h.data.props.flyout&&(c.source=`flyout`),h.data.currentConversationId||(h.data.currentConversationId=Q.createConversationId());let l=Q.chat(h.data.currentConversationId,i,c);Eo=l,h.data.lastChatResponseId=l.id,h.data.currentConversationState!==`searching`&&this.changeConversationState(`searching`);let u=!1,d,f=!!h.data.currentReferencesAsideId;(e&&f||!e&&h.data.chatConfig.showReferencesByDefault)&&(h.data.isAsideMobile||this.openReferencesAside(l.id)),l.subscribe(e=>{if(!o&&h.data.history[a]&&(h.data.history[a]={question:h.data.chatInputValue,...e}),h.data.chatConfig.addRetrievalQuestionToUrlParams&&e.retrievalQuestion){let t=new URLSearchParams(window.location.search);t.get(`search`)!==e.retrievalQuestion&&(t.set(`search`,e.retrievalQuestion),history.replaceState(null,``,`?${t.toString()}${window.location.hash}`))}h.data.chatConfig.showReferencesByDefault&&!h.data.wasReferencesAsideClosed&&h.data.currentReferencesAsideId!==e.id&&!h.data.isAsideMobile&&this.openReferencesAside(e.id),e.state===`streaming`&&h.data.currentConversationState!==`answering`&&this.changeConversationState(`answering`),e.state===`done`&&(this.changeConversationState(`idle`),u||(u=!0,this.setAriaLiveStatusMessage(`${h.t.ariaAnswerReady} ... ${e.message.text} ... ${h.data.selectedTopic?h.t.ariaAnswerFinishedWithSelectedTopic:h.t.ariaAnswerFinished}`),h.data.history.push(...To(h.data.chatConfig.messageAdditions.bot.after))),h.data.currentReferencesAsideId&&e.references.used.length>0?(clearTimeout(d),d=setTimeout(()=>{this.openReferencesAside(e.id)},100)):this.closeReferencesAside())}),h.data.chatInputValue=``},async onStartSpeechRecognition(){try{if(!await Ga()){this.showErrorToast(`speech-not-supported`);return}if(await navigator.mediaDevices.getUserMedia({audio:!0}),Xa.isSupported())h.data.chatInputValue=``,h.currentAudioRecorder=new Xa({onDataAvailable:async e=>{h.isTranscribing=!0,await this.handleTranscription(e)},onError:()=>{this.showErrorToast(`speech-microphone-access-denied`),h.currentAudioRecorder=null,h.isTranscribing=!1},onVolumeChange:e=>{h.currentAudioVolume=e}}),h.currentAudioRecorder.start();else{this.showErrorToast(`speech-not-supported`);return}}catch(e){throw this.showErrorToast(`speech-microphone-access-denied`),h.currentAudioRecorder=null,h.isTranscribing=!1,e}},editLatestQuestion(){let e=h.data.history.findLastIndex(e=>e?.type===`user`);if(e===-1){console.error(`No last user question, available`);return}let t=h.data.history.splice(e)[0];h.data.chatInputValue=t.message},onStopSpeechRecognition(){if(h.currentAudioRecorder){let e=h.currentAudioRecorder;h.currentAudioRecorder=null,e.stop()}h.currentAudioVolume=0},async handleTranscription(e){if(!e){console.warn(`No audio data received`);return}try{let t=await Q.transcribeAudio(e,{lang:h.data.language});if(t.error){this.showErrorToast(`speech-transcription-failed`);return}if(t.transcript.trim()){if(h.data.chatConfig.blockPII&&(h.data.questionHasPii=io(t.transcript.trim()),h.data.questionHasPii))return;h.data.chatInputValue=t.transcript.trim()}else this.showErrorToast(`speech-no-text-detected`)}catch(e){console.error(`Speech transcription error:`,e),this.showErrorToast(`speech-transcription-failed`)}finally{h.currentAudioRecorder=null,h.isTranscribing=!1,h.currentAudioVolume=0}},async startFromHandoverOrRoute(e){let{cID:t,followUpQuestion:n}=xo();if(!t){e();return}let r=await this.rehydrateFromSearchSummaryHandover(t);n?(h.data.route={name:`chat-page`},h.data.chatInputValue=n,this.onSubmit(!0)):r||e(),So()},async rehydrateFromSearchSummaryHandover(e){h.data.currentConversationId=e;let t=await Q.getMetadata(),n=t.mode===`ready`?t.userId:void 0,r=n?await Q.getChatHistory(e,n):[];if(r.length===0)return h.data.currentConversationId=void 0,!1;let i={all:[],used:[],unused:[]},a=new Dn({newTabSrText:h.t.ariaOpensInNewTab}),o=[];for(let{question:e,answer:t}of r)o.push({type:`user`,time:new Date().toISOString(),message:e,id:Ti()}),o.push({id:Ti(),state:`done`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:t,html:a.toHTML(t,i),text:t},references:{all:[],used:[],unused:[]}});return h.data.history=[...To(h.data.chatConfig.messageAdditions.init),...o],h.data.route={name:`chat-page`},!0},async onStartConversation(e,t,n){await this.abort(),h.data.history=To(h.data.chatConfig.messageAdditions.init),h.data.currentConversationId=Q.createConversationId(),this.goto({name:`chat-page`,query:e,predefinedQuestionId:t,switchQuestionId:n})},async onNewConversation(){await this.abort();let e=h.data.currentConversationId;if(h.data.currentConversationId=void 0,h.data.currentReferencesAsideId=void 0,h.data.history=To(h.data.chatConfig.messageAdditions.init),h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0,h.data.selectedTopic=void 0,h.data.chatConfig.addQueryToUrlParams){let e=new URLSearchParams(window.location.search);e.delete(`q`),e.delete(`id`),e.delete(`sid`),history.pushState(null,``,`?${e.toString()}${window.location.hash}`)}this.goto({name:`start-page`}),e&&Q.userAction(`newDiscussion`,{conversationId:e,lang:h.data.language}).catch(e=>{console.error(`Failed to notify backend of new discussion:`,e)})},async onChangeTopic(){let e=h.data.chatConfig.selectedTopicResetPredefinedQuestionId;if(!e){console.warn("No selectedTopicResetPredefinedQuestionId available to reset the selected topic. Set it in the `Config DB` in the backend, in a `generalConfig` default set.");return}await this.abort(),h.data.selectedTopic=void 0,h.data.predefinedQuestionId=e,h.data.switchQuestionId=void 0,h.data.chatInputValue=``,this.onSubmit(!0,void 0,!0)},showSuccessToast(e){Ia.success(h.t[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},showErrorToast(e,t){let n=t?.trim()?t:h.errorTranslations[e];Ia.error(n,{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},async submitFeedback(e){try{let t=h.data.conversationFeedbackId||h.data.lastChatResponseId;if(!t)throw new po(`Tried to give feedback with no id.`);let n=h.data.history.find(e=>e.type===`bot`&&e.id===t);await Q.feedback(t,n?.question??``,e),setTimeout(()=>{this.showSuccessToast(`thankYouForFeedback`)},500)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},toggleReferencesAside(e){h.data.currentReferencesAsideId===e?this.closeReferencesAside():this.openReferencesAside(e)},openReferencesAside(e){h.data.chatConfig.referencesLayout!==`inline`&&(h.data.currentReferencesAsideId=e,this.setOpenOverlay(!0))},closeReferencesAside(){h.data.currentReferencesAsideId=void 0,h.data.wasReferencesAsideClosed=!0,this.setOpenOverlay(!1)},setAsideMobile(e){h.data.isAsideMobile=e},openFlyout(){h.data.flyoutIsOpen=!0},closeFlyout(){h.data.flyoutIsOpen=!1},openConversationFeedback(){h.data.conversationFeedbackIsOpen=!0,this.setOpenOverlay(!0)},openMessageFeedback(e){h.data.conversationFeedbackId=e},closeFeedback(){h.data.conversationFeedbackIsOpen=!1,h.data.conversationFeedbackId=void 0,this.setOpenOverlay(!1)},openAnswerForm(e){h.data.answerFormMessageId=e,this.setOpenOverlay(!0)},closeAnswerForm(){h.data.answerFormMessageId=void 0,this.setOpenOverlay(!1)},async submitAnswerForm(e){try{let t=h.data.chatConfig.answerForm,n=h.data.answerFormMessageId;if(!t)throw new po(`Tried to submit the answer form with no answerForm config.`);if(!n)throw new po(`Tried to submit the answer form with no message id.`);let r=h.data.history.findIndex(e=>e.type===`bot`&&e.id===n),i=r===-1?void 0:h.data.history[r],a=h.data.history.slice(0,r===-1?void 0:r).findLast(e=>e.type===`user`)?.message,o=i?.question||a||(i?.type===`bot`?i.retrievalQuestion??``:``);await Q.submitAnswerForm({receiverEmail:t.receiverEmail,fields:t.fields.map(t=>({name:t.name,value:e[t.name]??``})),question:o,answer:i?.type===`bot`?i.message.text:``,requestId:n,lang:h.data.language}),setTimeout(()=>{this.showSuccessToast(`answerFormThankYou`)},500)}catch(e){console.error(`Answer form submission failed:`,e),this.showErrorToast(`answer-form-failed`)}},setOpenOverlay(e){h.data.hasOpenedOverlays=e},setAriaLiveStatusMessage(e){h.data.ariaLiveStatusMessage=e,clearTimeout(h.data.ariaLiveStatusMessageClearingTimeout),h.data.ariaLiveStatusMessageClearingTimeout=setTimeout(()=>{h.data.ariaLiveStatusMessage=``},h.ariaLiveMessagesClearingTimeoutDuration)},closePopup(){window.location.hash=``},checkForOpenedPopup(){let e=window.location.hash.slice(1),t=h.t.popups?.find(t=>t.hash===e);t?h.data.openedPopup=t:h.data.openedPopup=void 0},async thumbs(e,t){try{let n=h.data.history.find(t=>t.type===`bot`&&t.id===e),r=n?.type===`bot`?n:void 0;if(r?.feedback===t)return;t===`up`?await Q.thumbsUp(e,n?.question??``):await Q.thumbsDown(e,n?.question??``);let i=!r?.feedback;r&&(r.feedback=t),i&&this.showSuccessToast(`thankYouForFeedback`)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},async onLanguageChange(e){let t=ae(e,h.data.chatConfig.supportedLanguages);if(await Oo(t),h.data.language=t,ne(h.data.language,h.targets.mainElement),h.data.predefinedQuestions=await this.getPredefinedQuestions(h.data.language),this.setAriaLiveStatusMessage(h.t.ariaLanguageChanged),h.data.chatConfig.reflectLanguageInPath){let e=new URL(window.location.href);e.pathname=`/${h.data.language}`,window.history.replaceState({},``,e.toString())}},async acceptTerms(){h.data.termsAccepted=!0;try{Y.setItem(`liipgpt:termsAccepted`,`true`)}catch(e){console.warn(`Failed to save terms acceptance to storage:`,e)}this.closePopup(),await le(),this.goto(vo(h.data.chatConfig.forceConsent??!1,!0,h.data.chatConfig.forceChatPage??!1,_o(h.data.props.autofirePredefinedQuestionId,h.data.predefinedQuestions),h.data.props.question))},updateChatInput(e){h.data.chatInputValue=e}});export{Ti as _,Fa as a,Ca as c,pa as d,da as f,Ui as g,Xi as h,Ya as i,Sa as l,Zi as m,ko as n,Z as o,sa as p,Xa as r,ka as s,mo as t,_a as u};
|
|
62
|
+
`,{error:c.error,url:i,opts:a,data:s}),s}async postData(e,t){let n=await fetch(`${this.options.apiUrl}${e}`,{method:`POST`,headers:this.getDefaultHeaders(),body:JSON.stringify(t)});if(!n.ok){let e=await n.text();throw Error(`${n.status} - ${e}`)}return n}async postFormData(e,t){let n=await fetch(`${this.options.apiUrl}${e}`,{method:`POST`,body:t});if(!n.ok){let e=await n.text();throw Error(`${n.status} - ${e}`)}return n}},Ii=K({links:ei(ii([K({url:q(Kr()),title:q(G()),considered:q(Qr()),orgMetadata:q(K({authors:q(ei(G()))})),type:q(G()),date:q(pi()),similarity:q(Jr()),content:q(G()),fromFullTextSearch:q(Qr()),rerank:q(K({index:q(Xr()),adjustment:q(Jr()),score:q(Jr()),similarityOld:q(Jr())}))}),mi]))}),Li=e=>{if(`metadata`in e)return e;console.warn(`Please upgrade your backend you are currently using an old api feature.`);let t=e.orgMetadata??{};e?.fromFullTextSearch&&(t.fromFullTextSearch=e?.fromFullTextSearch),e?.rerank&&(t.rerank=e?.rerank);let n=[],r=e.title??``;if(e.title&&e.title.includes(` > `)){let t=e.title.split(` > `);r=t.pop()??``,n=t}return{url:e.url??``,title:r,score:e.similarity||0,breadcrumbs:n,metadata:t,description:e.content,date:e.date}},Ri=class{id;constructor(e){this.chatResponseData=e,this.id=this.chatResponseData.id}async isReadyForFeedback(){return await this.chatResponseData.readyForFeedback.toPromise(),!0}subscribe(e,t){return this.chatResponseData.readableStore.subscribe(e,t)}getContent(){return this.chatResponseData.content.toPromise()}abort(){return this.chatResponseData.abort()}async thumbsUp(){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.thumbsUp(this.id,this.chatResponseData.question)}async thumbsDown(){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.thumbsDown(this.id,this.chatResponseData.question)}async feedback(e){await this.isReadyForFeedback(),await this.chatResponseData.liipgptClientPrimitive.feedback(this.id,this.chatResponseData.question,e)}};function zi(){let e,t;return{promise:new Promise((n,r)=>{t=n,e=r}),reject:e,resolve:t}}var Bi=class{promise;resolve;reject;constructor(){let{promise:e,resolve:t,reject:n}=zi();this.promise=e,this.resolve=t,this.reject=n}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}toPromise(){return this.promise}[Symbol.toStringTag]=`Flag`},Vi=class{hasValue=new Bi;currentValue;setValue(e){this.currentValue=e,this.hasValue.resolve()}cleanup(e){this.hasValue.reject(e)}getCurrentValue(){return this.currentValue}async toPromise(){return await this.hasValue,this.currentValue}then(e,t){return this.toPromise().then(e,t)}catch(e){return this.toPromise().catch(e)}finally(e){return this.toPromise().finally(e)}[Symbol.toStringTag]=`FutureValue`},Hi=e=>{try{return new URL(e).hostname}catch{return e}};function Ui(e){return e.replace(/<[^>]*>/g,``).replace(/ /g,` `).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var Wi=({citationId:e,url:t,considered:n,title:r,description:i,summary:a})=>{let o=Hi(t),s=i||a;return{...e?{citationId:e}:{},url:t,considered:n,referenceIndex:{},score:0,metadata:{},display:{card:{title:r,description:s,badge:t},listItem:{title:r,badge:o}}}},Gi=class{store;content=new Vi;backendSendsMappedRefs=!1;constructor(e){this.options=e,this.store=o({id:e.id,state:`loading`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:``,html:``,text:``},references:{all:[],used:[],unused:[]},retrievalQuestion:e.userQuestion})}pushError(e,t){this.options.onError?.(e,t),this.store.update(t=>({...t,errors:[...t.errors,e]}))}updateRequestId(e){this.store.update(t=>({...t,id:e}))}updateText(e){this.store.update(t=>{let n=t.message.markdown+e,r=this.options.markdownRenderer.toHTML(n,t.references);return{...t,state:`streaming`,message:{markdown:n,html:r,text:``}}})}finishMessage(){this.store.update(e=>{let t={...e,state:`done`};return t.references.unused=t.references.all.filter(e=>e.referenceIndex.used===void 0),t.message.text=Ui(t.message.html),this.options?.onFinish?.(t),this.content.setValue(t),t})}addReference(e){this.store.update(t=>{let n=t.references.all,r=n.length,i=[...n,{...e,referenceIndex:{all:r}}];return{...t,references:{used:t.references.used,all:i}}})}addMappedReference(e){this.backendSendsMappedRefs=!0,this.addReference(e)}addOldReference(e){this.backendSendsMappedRefs||this.addReference(Wi(e))}updateRetrievalQuestion(e){this.store.update(t=>({...t,retrievalQuestion:e}))}setNoFeedback(){this.store.update(e=>({...e,noFeedback:!0}))}getReadableStore(){return{subscribe:this.store.subscribe}}getPromise(){return this.content.toPromise()}},Ki=7,qi=8,Ji=160,Yi=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===`<`){let r=e.indexOf(`>`,n);if(r!==-1){t.push({type:`tag`,value:e.slice(n,r+1)}),n=r+1;continue}}if(/\s/.test(r)){let r=n;for(;r<e.length&&/\s/.test(e[r]);)r++;t.push({type:`space`,value:e.slice(n,r)}),n=r;continue}let i=n;for(;i<e.length&&!/\s/.test(e[i])&&e[i]!==`<`;)i++;t.push({type:`word`,value:e.slice(n,i)}),n=i}return t},Xi=e=>{let t=Yi(e),n=[],r=``,i=!1;for(let e of t)e.type===`space`&&i?(n.push(r),r=e.value,i=!1):(r+=e.value,e.type===`word`&&(i=!0));return r&&n.push(r),n},Zi=e=>Math.max(qi,Math.min(Ji,e.length*Ki)),Qi=class{queue=[];timeoutId=null;isProcessing=!1;constructor(e){this.onText=e}ingestText(e){let t=Xi(e);if(t.length>=5){for(let e of t)this.queue.push({kind:`text`,chunk:e,delayMs:Zi(e)});this.kickoff();return}this.runAfterTyping(()=>this.onText(e))}runAfterTyping(e){if(this.queue.length===0&&!this.isProcessing){e();return}this.queue.push({kind:`fn`,fn:e}),this.kickoff()}runWithWarmup(e){this.queue.push({kind:`fn`,fn:e}),this.kickoff()}clear(){this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.queue=[],this.isProcessing=!1}kickoff(){this.isProcessing||this.timeoutId!==null||(this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.processNext()},750))}processNext(){let e=this.queue.shift();if(!e){this.isProcessing=!1;return}this.isProcessing=!0,e.kind===`text`?(this.onText(e.chunk),this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.processNext()},e.delayMs)):(e.fn(),this.processNext())}},$i=class{constructor(e){this.results=e}},ea=45e3,ta=class{internalData;renderers=new Map;markedExtensions=[];_newTabSrText;chatTimeout;constructor(e){this.chatTimeout=e.chatTimeout??ea;let t=new Fi({apiUrl:e.apiUrl,apiKey:e.apiKey,speechRecognitionApiKey:e.speechRecognitionApiKey,strict:e.strict??!1,EventSource:e.EventSource??EventSource});this.internalData={restClient:t,metadata:Mi(t,e.startParameters),searchResponseMap:new Map,chatResponseMap:new Map,conversationMap:new Map}}setMarkedExtensions(...e){this.markedExtensions=e}setNewTabSrText(e){this._newTabSrText=e}getMetadata(){return this.internalData.metadata}createConversationId(){let e=Di();return this.renderers.set(e,new Dn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText})),e}chat(e,t,n={}){let r=new Vi,i=Di(),a=new Bi,o=new Gi({id:i,onError:(e,t)=>{n.onError?.(e,t)},onFinish:e=>{r.setValue(e)},markdownRenderer:this.renderers.get(e)??new Dn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText}),userQuestion:t}),s=async()=>{await a,!(f&&!c.getCurrentValue())&&(await c).close()},c=new Vi,l=new Qi(e=>o.updateText(e)),u=n.timeout??this.chatTimeout,d,f=!1,p=()=>{d!==void 0&&clearTimeout(d),d=void 0},m=()=>{f=!0,d=void 0,console.error(`No SSE activity for ${u}ms, giving up on chat request ${i}`),l.clear(),o.pushError(`sse-error`);let e=c.getCurrentValue();if(e){e.close();return}o.finishMessage(),a.resolve()},ee=()=>{p(),u>0&&!f&&(d=setTimeout(m,u))};ee(),(async()=>{let s=await this.internalData.metadata;if(s.mode===`maintenance`)throw Error(`Can not chat in maintenance mode`);let u=await this.internalData.restClient.subscribeSse(`/assistant/sse`,{query:t,uID:s.userId,cID:e,rID:i,lang:n.lang,feature:n.features?.join(`,`),referrer:n.referrer,source:n.source,...n.selectorValues??{},...n.mode?{mode:n.mode}:{},...n.cache?{cache:!0}:{},...n.predefinedQuestionId?{predefinedQuestionId:n.predefinedQuestionId}:{},...n.switchQuestionId?{switchQuestionId:n.switchQuestionId}:{},chat:`true`,version:`2`},{onClose:()=>{p(),l.clear(),o.finishMessage(),a.resolve(),r.cleanup()},onMessage:t=>{let r=t;switch(ee(),r.type){case`error`:l.runAfterTyping(()=>o.pushError(r.error,r.message));break;case`id`:r.for===`request`&&i!==r.id&&console.warn(`Unexpected request id "${r.id}" expected "${i}"`),r.for===`conversation`&&e!==r.id&&console.warn(`Unexpected conversation id "${r.id}" expected "${e}"`);break;case`state`:r.state===`history-entry-initialized`&&a.resolve();break;case`text`:l.ingestText(r.text);break;case`done`:case`answer-done`:p(),l.runAfterTyping(()=>{o.finishMessage(),a.resolve(),c.then(e=>e.close())});break;case`unexpected-call`:l.runAfterTyping(()=>{console.error(`unexpected-call:`,r),o.pushError(`unexpected-call`)});break;case`jsonld-component`:case`mapped-reference`:l.runAfterTyping(()=>o.addMappedReference(r.reference));break;case`reference`:l.runAfterTyping(()=>o.addOldReference(r.reference));break;case`retrieval-question`:l.runAfterTyping(()=>o.updateRetrievalQuestion(r.question));break;case`no-feedback`:l.runAfterTyping(()=>o.setNoFeedback());break;case`component`:l.runWithWarmup(()=>n.onEmbed?.(r));break}l.runAfterTyping(()=>n.onMessage?.(r))},onError:e=>{console.error(` sse-error:`,e),!(`data`in e&&!e.data&&`responseCode`in e&&e.responseCode===0)&&o.pushError(`sse-error`)}});c.setValue(u),f&&u.close()})();let h=new Ri({question:t,id:i,content:r,readableStore:o.getReadableStore(),readyForFeedback:a,abort:s,liipgptClientPrimitive:this});return this.internalData.chatResponseMap.set(h.id,h),h}async thumbs(e,t,n){if((await this.internalData.metadata).mode!==`ready`)throw Error(`Can not post feedback unless we are in ready mode`);let r={feedback:n,rID:e,query:t};await this.internalData.restClient.postData(`/quickfeedback`,r)}thumbsUp(e,t){return this.thumbs(e,t,`positive`)}thumbsDown(e,t){return this.thumbs(e,t,`negative`)}async feedback(e,t,n){let r=await this.internalData.metadata;if(r.mode!==`ready`)throw Error(`Can not post feedback unless we are in ready mode`);if(n.message){let i={body:n.message,email:n.email,rID:e,uID:r.userId,query:t};await this.internalData.restClient.postData(`/feedback`,i)}n.classification&&await this.internalData.restClient.postData(`/classification`,{impact:n.classification.impact,quality:n.classification.quality,rID:e})}async submitAnswerForm(e){let t=await this.internalData.metadata;if(t.mode!==`ready`)throw Error(`Can not submit the answer form unless we are in ready mode`);let n={receiverEmail:e.receiverEmail,fields:e.fields,query:e.question,answer:e.answer,rID:e.requestId,uID:t.userId,lang:e.lang};await this.internalData.restClient.postData(`/customform`,n)}async userAction(e,t={}){let n=await this.internalData.metadata;if(n.mode!==`ready`)throw Error(`Can not post user action unless we are in ready mode`);let r={uID:n.userId,cID:t.conversationId,lang:t.lang,userAction:e};await this.internalData.restClient.postData(`/assistant/userAction`,r)}async search(e,t={}){let n=await this.internalData.metadata,r=n.mode===`ready`?n.userId:void 0,{links:i}=await this.internalData.restClient.fetchData(`/assistant/search`,Ii,{modelId:t.model,lang:t.language,query:e,mapResults:`true`,uID:r});return new $i(i.map(Li))}async getChatConfig(){return this.internalData.restClient.fetchData(`/chatconfig`,vi)}async getChatHistory(e,t){try{let n=await this.internalData.restClient.postData(`/chathistory`,{cID:e,uID:t}),r=hi.safeParse(await n.json());return r.success?r.data:[]}catch(e){return console.error(`Failed to load chat history:`,e),[]}}async getPredefinedQuestions(e){return(await this.internalData.restClient.fetchData(`/topics/questions`,gi,e)).predefinedQuestions}async transcribeAudio(e,t={}){let n=await this.internalData.metadata,r=t.lang||`de-CH`;if(n.mode===`maintenance`)throw Error(`Can not transcribe audio in maintenance mode`);try{let t=(e=>e.includes(`mp4`)?`mp4`:e.includes(`webm`)?`webm`:(e.includes(`wav`),`wav`))(e.type),n=new FormData;return n.append(`file`,e,`audio.${t}`),n.append(`lang`,r),n.append(`type`,e.type),{transcript:await(await this.internalData.restClient.postFormData(`/speech?key=${this.internalData.restClient.speechRecognitionApiKey||``}&lang=${r}`,n)).text()||``,error:void 0}}catch(e){return console.error(`Error transcribing audio:`,e),{transcript:``,error:e instanceof Error?e.message:`Unknown error`}}}},na=(e,t)=>{try{let n=new URL(e),r=new URL(t);return n.origin===r.origin&&n.pathname===r.pathname}catch{return!1}},ra=e=>{try{return new URL(e).origin===window.location.origin}catch{return!1}},ia=()=>`${window.location.protocol}//${window.location.host}${window.location.pathname}`;function aa(e,{embedded:t}){let n=e??`all`;if(n===`none`)return;if(t||n===`location`)return ia();let r=na(document.referrer,window.location.href)?``:document.referrer;if(r&&!(n===`own`&&!ra(r)))return r}var oa=f(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}}));function sa(...e){return e.filter(Boolean).join(` `)}var ca=typeof document<`u`,la=typeof window<`u`?window:void 0;typeof window<`u`&&window.document,typeof window<`u`&&window.navigator,typeof window<`u`&&window.location;function ua(e){let t=e.activeElement;for(;t?.shadowRoot;){let e=t.shadowRoot.activeElement;if(e===t)break;t=e}return t}var da=class extends Map{#e=new Map;#t=t(0);#n=t(0);#r=_||-1;constructor(e){if(super(),e){for(var[t,n]of e)super.set(t,n);this.#n.v=super.size}}#i(e){return _===this.#r?t(e):ie(e)}has(e){var t=this.#e,n=t.get(e);if(n===void 0)if(super.has(e))n=this.#i(0),t.set(e,n);else return g(this.#t),!1;return g(n),!0}forEach(e,t){this.#a(),super.forEach(e,t)}get(e){var t=this.#e,n=t.get(e);if(n===void 0)if(super.has(e))n=this.#i(0),t.set(e,n);else{g(this.#t);return}return g(n),super.get(e)}set(e,t){var r=this.#e,i=r.get(e),a=super.get(e),o=super.set(e,t),s=this.#t;if(i===void 0)i=this.#i(0),r.set(e,i),c(this.#n,super.size),n(s);else if(a!==t){n(i);var l=s.reactions===null?null:new Set(s.reactions);(l===null||!i.reactions?.every(e=>l.has(e)))&&n(s)}return o}delete(e){var t=this.#e,r=t.get(e),i=super.delete(e);return r!==void 0&&(t.delete(e),c(r,-1)),i&&(c(this.#n,super.size),n(this.#t)),i}clear(){if(super.size!==0){super.clear();var e=this.#e;c(this.#n,0);for(var t of e.values())c(t,-1);n(this.#t),e.clear()}}#a(){g(this.#t);var e=this.#e;if(this.#n.v!==e.size){for(var t of super.keys())if(!e.has(t)){var n=this.#i(0);e.set(t,n)}}for([,n]of this.#e)g(n)}keys(){return g(this.#t),super.keys()}values(){return this.#a(),super.values()}entries(){return this.#a(),super.entries()}[Symbol.iterator](){return this.entries()}get size(){return g(this.#n),super.size}};new class{#e;#t;constructor(e={}){let{window:t=la,document:n=t?.document}=e;t!==void 0&&(this.#e=n,this.#t=l(e=>{let n=te(t,`focusin`,e),r=te(t,`focusout`,e);return()=>{n(),r()}}))}get current(){return this.#t?.(),this.#e?ua(this.#e):null}};function fa(e){return typeof e==`function`}var pa=class{#e;#t;constructor(e){this.#e=e,this.#t=Symbol(e)}get key(){return this.#t}exists(){return me(this.#t)}get(){let e=d(this.#t);if(e===void 0)throw Error(`Context "${this.#e}" not found`);return e}getOr(e){let t=d(this.#t);return t===void 0?e:t}set(e){return a(this.#t,e)}};function ma(e,t){switch(e){case`post`:pe(t);break;case`pre`:ee(t);break}}function ha(e,t,n,r={}){let{lazy:i=!1}=r,a=!i,o=Array.isArray(e)?[]:void 0;ma(t,()=>{let t=Array.isArray(e)?e.map(e=>e()):e();if(!a){a=!0,o=t;return}let r=oe(()=>n(t,o));return o=t,r})}function ga(e,t,n){let r=p(()=>{let i=!1;ha(e,t,(e,t)=>{if(i){r();return}let a=n(e,t);return i=!0,a},{lazy:!0})});pe(()=>r)}function _a(e,t,n){ha(e,`post`,t,n)}function va(e,t,n){ha(e,`pre`,t,n)}_a.pre=va;function ya(e,t){ga(e,`post`,t)}function ba(e,t){ga(e,`pre`,t)}ya.pre=ba;function xa(e){return fa(e)?e():e}var Sa=class{#e={width:0,height:0};#t=!1;#n;#r;#i;#a=s(()=>(g(this.#s)?.(),this.getSize().width));#o=s(()=>(g(this.#s)?.(),this.getSize().height));#s=s(()=>{let e=xa(this.#r);if(e)return l(t=>{if(!this.#i)return;let n=new this.#i.ResizeObserver(e=>{this.#t=!0;for(let t of e){let e=this.#n.box===`content-box`?t.contentBoxSize:t.borderBoxSize,n=Array.isArray(e)?e:[e];this.#e.width=n.reduce((e,t)=>Math.max(e,t.inlineSize),0),this.#e.height=n.reduce((e,t)=>Math.max(e,t.blockSize),0)}t()});return n.observe(e),()=>{this.#t=!1,n.disconnect()}})});constructor(e,t={box:`border-box`}){this.#i=t.window??la,this.#n=t,this.#r=e,this.#e={width:0,height:0}}calculateSize(){let e=xa(this.#r);if(!e||!this.#i)return;let t=e.offsetWidth,n=e.offsetHeight;if(this.#n.box===`border-box`)return{width:t,height:n};let r=this.#i.getComputedStyle(e),i=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight),a=parseFloat(r.paddingTop)+parseFloat(r.paddingBottom),o=parseFloat(r.borderLeftWidth)+parseFloat(r.borderRightWidth),s=parseFloat(r.borderTopWidth)+parseFloat(r.borderBottomWidth);return{width:t-i-o,height:n-a-s}}getSize(){return this.#t?this.#e:this.calculateSize()??this.#e}get current(){return g(this.#s)?.(),this.getSize()}get width(){return g(this.#a)}get height(){return g(this.#o)}},Ca=class{#e=()=>void 0;#t=s(()=>this.#e());constructor(e,t){let n;t!==void 0&&(n=t),this.#e=()=>{try{return n}finally{n=e()}}}get current(){return g(this.#t)}};function wa(e,t){let n,r=null;return(...i)=>new Promise(a=>{r&&r(void 0),r=a,clearTimeout(n),n=setTimeout(async()=>{let t=await e(...i);r&&=(r(t),null)},t)})}function Ta(e,t){let n=0,r=null;return(...i)=>{let a=Date.now();return n&&a-n<t?r??Promise.resolve(void 0):(n=a,r=e(...i),r)}}function Ea(e,n,i={},a){let{lazy:o=!1,once:s=!1,initialValue:l,debounce:u,throttle:d}=i,f=t(r(l)),p=t(!1),m=t(void 0),ee=t(r([])),h=()=>{g(ee).forEach(e=>e()),c(ee,[],!0)},te=e=>{c(ee,[...g(ee),e],!0)},ne=async(e,t,r=!1)=>{try{c(p,!0),c(m,void 0),h();let i=new AbortController;te(()=>i.abort());let a=await n(e,t,{data:g(f),refetching:r,onCleanup:te,signal:i.signal});return c(f,a,!0),a}catch(e){e instanceof DOMException&&e.name===`AbortError`||c(m,e,!0);return}finally{c(p,!1)}},_=u?wa(ne,u):d?Ta(ne,d):ne,re=Array.isArray(e)?e:[e],ie;return a((t,n)=>{s&&ie||(ie=t,_(Array.isArray(e)?t:t[0],Array.isArray(e)?n:n?.[0]))},{lazy:o}),{get current(){return g(f)},get loading(){return g(p)},get error(){return g(m)},mutate:e=>{c(f,e,!0)},refetch:t=>{let n=re.map(e=>e());return _(Array.isArray(e)?n:n[0],Array.isArray(e)?n:n[0],t??!0)}}}function Da(e,t,n){return Ea(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];_a(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}function Oa(e,t,n){return Ea(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];_a.pre(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}Da.pre=Oa,new pa(`richColorsContext`);var ka=new pa(`<Toaster/>`),Aa=0;function ja(e){return typeof e?.id==`number`||typeof e?.id==`string`&&e.id.length>0?e.id:Aa++}var Ma=class{#e=t(r([]));get toasts(){return g(this.#e)}set toasts(e){c(this.#e,e,!0)}#t=t(r([]));get heights(){return g(this.#t)}set heights(e){c(this.#t,e,!0)}#n=new Map;#r=e=>{let t=this.toasts.findIndex(t=>t.id===e);return t===-1?null:t};#i=e=>this.heights.findIndex(t=>t.toastId===e);addToast=e=>{ca&&this.toasts.unshift(e)};updateToast=({id:e,data:t,type:n,message:r})=>{let i=this.toasts.findIndex(t=>t.id===e),a=this.toasts[i];this.toasts[i]={...a,...t,id:e,title:r,type:n,dismiss:!1,delete:!1,updated:!0}};markDismissed=e=>{let t=this.#r(e);if(t===null)return;let n=this.toasts[t];n&&(!n.dismiss||!n.delete)&&(this.toasts[t]={...n,dismiss:!0,delete:!0})};scheduleRemoval=(e,t)=>{this.cancelRemoval(e),this.#n.set(e,setTimeout(()=>{this.#n.delete(e),this.remove(e)},t))};cancelRemoval=e=>{let t=this.#n.get(e);t!==void 0&&(clearTimeout(t),this.#n.delete(e))};create=e=>{let{message:t,...n}=e,r=ja(e),i=e.dismissible===void 0?e.dismissable===void 0?!0:e.dismissable:e.dismissible,a=e.type===void 0?`default`:e.type;return oe(()=>{this.cancelRemoval(r);let o=this.toasts.find(e=>e.id===r);o?.dismiss||o?.delete?(this.remove(r),this.addToast({...n,id:r,title:t,dismissible:i,type:a,updated:!0})):o?this.updateToast({id:r,data:e,type:a,message:t,dismissible:i}):this.addToast({...n,id:r,title:t,dismissible:i,type:a})}),r};dismiss=e=>(oe(()=>{if(e===void 0){this.toasts=this.toasts.map(e=>e.dismiss?e:{...e,dismiss:!0});return}let t=this.toasts.findIndex(t=>t.id===e);this.toasts[t]&&(this.toasts[t]={...this.toasts[t],dismiss:!0})}),e);remove=e=>{if(e===void 0){this.toasts=[];return}let t=this.#r(e);if(t!==null)return this.toasts.splice(t,1),e};message=(e,t)=>this.create({...t,type:`default`,message:e});error=(e,t)=>this.create({...t,type:`error`,message:e});success=(e,t)=>this.create({...t,type:`success`,message:e});info=(e,t)=>this.create({...t,type:`info`,message:e});warning=(e,t)=>this.create({...t,type:`warning`,message:e});loading=(e,t)=>this.create({...t,type:`loading`,message:e});promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:typeof t.loading==`string`?t.loading:t.loading()}));let r=e instanceof Promise?e:e(),i=n!==void 0;return r.then(e=>{if(typeof e==`object`&&e&&`ok`in e&&typeof e.ok==`boolean`&&!e.ok){i=!1;let t=Na(e);this.create({id:n,type:`error`,message:t})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?t.success(e):t.success;this.create({id:n,type:`success`,message:r})}}).catch(e=>{if(t.error!==void 0){i=!1;let r=typeof t.error==`function`?t.error(e):t.error;this.create({id:n,type:`error`,message:r})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally?.()}),n};custom=(e,t)=>{let n=ja(t);return this.create({component:e,...t,id:n}),n};removeHeight=e=>{this.heights=this.heights.filter(t=>t.toastId!==e)};setHeight=e=>{oe(()=>{let t=this.#i(e.toastId);if(t!==-1){this.heights[t]=e;return}let n=new Map(this.toasts.map((e,t)=>[e.id,t])),r=n.get(e.toastId)??-1,i=this.heights.findIndex(e=>(n.get(e.toastId)??1/0)>r);i===-1?this.heights.push(e):this.heights.splice(i,0,e)})};reset=()=>{this.toasts=[],this.heights=[],this.#n.forEach(e=>clearTimeout(e)),this.#n.clear()}};function Na(e){return e&&typeof e==`object`&&`status`in e?`HTTP error! Status: ${e.status}`:`Error! ${e}`}var Z=new Ma;function Pa(e,t){return Z.message(e,t)}var Fa=class{#e=s(()=>Z.toasts.filter(e=>!e.dismiss));get toasts(){return g(this.#e)}},Ia=Object.assign(Pa,{success:Z.success,info:Z.info,warning:Z.warning,error:Z.error,custom:Z.custom,message:Z.message,promise:Z.promise,dismiss:Z.dismiss,loading:Z.loading,getActiveToasts:()=>Z.toasts.filter(e=>!e.dismiss)}),La=e=>{let t=new Set;Object.getOwnPropertyNames(e).forEach(e=>t.add(e));let n=Object.getPrototypeOf(e);for(;n&&n!==Object.prototype;)Object.getOwnPropertyNames(n).forEach(e=>t.add(e)),n=Object.getPrototypeOf(n);return Array.from(t)},Ra=(e,t)=>{let n={};return t.forEach(t=>{n[t]=e[t]}),n},za=console.warn,Ba=()=>{},Va=(e,t)=>oe(()=>{console.warn=Ba;let n=i(t?Ra(e,t):e);return console.warn=za,n}),Ha=e=>e&&typeof e.then==`function`,Ua=class{config;self;devtools;stateKeys;constructor(e,t){this.config=e,this.self=t,typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&(this.stateKeys=La(this.config.state),this.devtools=window.__REDUX_DEVTOOLS_EXTENSION__.connect({name:this.config.name??`updatelogic`}),this.devtools.init(this.createStateSnapshot()),this.devtools.subscribe(e=>{e.type===`DISPATCH`&&e.state}))}createStateSnapshot(){return Va(this.config.state,this.stateKeys)}sendStart(e,t){this.devtools.send({type:`→ ${e}`,args:t},this.createStateSnapshot())}sendError(e,t,n){this.devtools.send({type:`❌ ${e}`,args:t,error:n},this.createStateSnapshot())}sendSuccess(e,t,n){this.devtools.send({type:`✓ ${e}`,args:t,return:n},this.createStateSnapshot())}isIncluded(e){return this.config.excludeInDevTools?!this.config.excludeInDevTools.includes(e):!0}createProxyFunction(e,t){let n=this.devtools&&this.isIncluded(e);return typeof t==`function`?(...r)=>{if(!n)return oe(()=>t.call(this.self,...r));let i=Va(r);this.sendStart(e,i);try{let n=oe(()=>t.call(this.self,...r));return Ha(n)?n.then(t=>(this.sendSuccess(e,i,t),t),t=>{throw this.sendError(e,i,t),t}):(this.sendSuccess(e,i,n),n)}catch(t){throw this.sendError(e,i,t),t}}:t}},Wa=(e,t)=>{let n={},r=new Ua(e,n);return Object.keys(t).forEach(e=>{if(e===`state`||e===`name`)return;let i=t[e];n[e]=r.createProxyFunction(e,i)}),n};async function Ga(){if(typeof navigator>`u`||!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return!1;try{return(await navigator.mediaDevices.enumerateDevices()).some(e=>e.kind===`audioinput`)}catch(e){return console.error(`Error checking for microphone:`,e),!1}}function Ka(){return typeof window>`u`||!window.MediaRecorder?null:MediaRecorder.isTypeSupported(`audio/mp4`)?`audio/mp4`:MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:MediaRecorder.isTypeSupported(`audio/wav`)?`audio/wav`:null}function qa(){return typeof window>`u`?!1:!!(window.MediaRecorder&&Ka())}function Ja(){if(typeof window>`u`)return!1;if(`ontouchstart`in window||navigator.maxTouchPoints>0)return!0;let e=navigator.msMaxTouchPoints;return!!(`msMaxTouchPoints`in navigator&&e&&e>0)}function Ya(){return typeof window>`u`?!1:!!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||Ja())}var Xa=class{mediaRecorder=null;audioChunks=[];started=!1;starting=!1;stream=null;options;audioContext=null;analyser=null;dataArray=null;volumeUpdateInterval=null;constructor(e={}){this.options=e}async start(){if(this.started||this.starting){console.warn(`AudioRecorder: Start already in progress or already started`);return}if(!qa()||!navigator.mediaDevices){let e=Error(`MediaRecorder not supported or no microphone access`);throw this.options.onError?.(e),e}try{if(this.starting=!0,this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1}),!this.starting){this.stopStream(this.stream);return}this.mediaRecorder&&this.mediaRecorder.state!==`inactive`&&(console.warn(`AudioRecorder: MediaRecorder already active, stopping previous recording`),this.mediaRecorder.stop(),this.cleanup()),this.started=!0,this.starting=!1;let e=Ka();if(!e)throw Error(`No supported media type found`);let t={mimeType:e};this.mediaRecorder=new MediaRecorder(this.stream,t),this.audioChunks=[],this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&this.audioChunks.push(e.data)},this.mediaRecorder.onstop=async()=>{let t=this.audioChunks.length>0?new Blob(this.audioChunks,{type:e}):null;await this.options.onDataAvailable?.(t),this.options.onStop?.(),this.cleanup()},this.mediaRecorder.onerror=e=>{let t=Error(`MediaRecorder error: ${e}`);this.options.onError?.(t),this.cleanup()},this.mediaRecorder.start(),this.setupVolumeAnalysis(this.stream),this.options.onStart?.()}catch(e){this.started=!1,this.starting=!1;let t=e instanceof Error?e:Error(String(e));throw this.options.onError?.(t),t}}stop(){this.started=!1,this.starting=!1,this.volumeUpdateInterval&&=(clearInterval(this.volumeUpdateInterval),null),this.mediaRecorder&&this.mediaRecorder.state!==`inactive`?this.mediaRecorder.stop():(this.stream&&this.stopStream(this.stream),this.cleanup())}setupVolumeAnalysis(e){if(this.options.onVolumeChange)try{this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8;let t=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser),this.startVolumeMonitoring()}catch(e){console.warn(`Failed to set up volume analysis:`,e)}}startVolumeMonitoring(){!this.analyser||!this.dataArray||!this.options.onVolumeChange||(this.volumeUpdateInterval=window.setInterval(()=>{if(!this.analyser||!this.dataArray||!this.started)return;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t]*this.dataArray[t];let t=Math.sqrt(e/this.dataArray.length)/255;t=(t*3)**.7;let n=Math.min(100,Math.max(0,Math.round(t*100)));this.options.onVolumeChange?.(n)},100))}get recording(){return this.started&&this.mediaRecorder?.state===`recording`}get isStarting(){return this.starting}stopStream(e){e.getTracks().forEach(e=>e.stop())}cleanup(){this.volumeUpdateInterval&&=(clearInterval(this.volumeUpdateInterval),null),this.audioContext&&=(this.audioContext.close().catch(console.warn),null),this.analyser=null,this.dataArray=null,this.stream&&=(this.stopStream(this.stream),null),this.mediaRecorder=null,this.audioChunks=[],this.started=!1,this.starting=!1}static isSupported(){return qa()}static getSupportedMediaType(){return Ka()}},Za=lt(),Qa=(e,t)=>{if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){t.textContent=e.value;return}if(e instanceof HTMLSelectElement&&t instanceof HTMLSelectElement){Array.from(e.options).forEach((e,n)=>{t.options[n]&&(t.options[n].selected=e.selected)});return}e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&(t.setAttribute(`value`,e.value),(e.type===`checkbox`||e.type===`radio`)&&(e.checked?t.setAttribute(`checked`,`checked`):t.removeAttribute(`checked`)))},$a=e=>{let t=e.cloneNode(!0);if(!(t instanceof Element))return``;let n=`input, textarea, select`,r=e.querySelectorAll(n),i=t.querySelectorAll(n);return r.forEach((e,t)=>{let n=i[t];n&&Qa(e,n)}),Za.sanitize(t.outerHTML,{FORBID_TAGS:[`style`,`script`],FORBID_ATTR:[`style`,`class`]})},eo=e=>{if(!e?.length)return[];let t=e.join(`,`),n=document.querySelectorAll(t);return Array.from(n,$a)},to=`liipgpt:context`,no=()=>localStorage.getItem(to),ro=[{type:`email`,check:e=>/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/.test(e)},{type:`creditCard`,check:e=>/\b(?:\d[ -]*?){13,16}\b/.test(e)},{type:`ahv`,check:e=>/\b756[.\s-]?\d{2,4}[.\s-]?\d{2,4}[.\s-]?\d{2}\b/.test(e)},{type:`phoneSwiss`,check:e=>/\b0(?:\s*\d){2}(?:\s*\/\s*)?(?:\s*\d){7,}\b/.test(e)},{type:`phoneInternational`,check:e=>/(?:\+|00)(?:\s*\d){10,}\b/.test(e)},{type:`swissPassport`,check:e=>/\b[A-HJ-NP-Z](?=.*\d)[A-HJ-NP-Z0-9]{7}\b/.test(e)},{type:`longNumber`,check:e=>/\b\d{9,}\b/.test(e)}],io=e=>{for(let t of ro)if(t.check(e))return t.type},ao=`liipgpt:selectorValues`,oo=`liipgpt:selectorKnownDefaults`,so=()=>{try{let e=Y.getItem(ao),t=Y.getItem(oo);return e?{values:JSON.parse(e),knownDefaults:t?JSON.parse(t):{}}:null}catch{return null}},co=e=>{let t={};for(let n of e)t[n.settingName]=n.defaultValues??(n.allowEmpty?[]:[n.values[0]]).filter(Boolean);return t},lo=(e,t)=>{try{let n=co(t);Y.setItem(ao,JSON.stringify(e)),Y.setItem(oo,JSON.stringify(n))}catch(e){console.error(`Failed to save selector values:`,e)}},uo=e=>{try{let t=so();if(!t)return;delete t.values[e],delete t.knownDefaults[e],Y.setItem(ao,JSON.stringify(t.values)),Y.setItem(oo,JSON.stringify(t.knownDefaults))}catch(e){console.error(`Failed to clear selector saved state:`,e)}},fo=e=>{let t=so(),n=e.map(e=>{let n=e.defaultValues??(e.allowEmpty?[]:[e.values[0]]).filter(Boolean);if(!t?.values[e.settingName])return[e.settingName,n];let r=t.values[e.settingName],i=t.knownDefaults[e.settingName]||[],a=r.filter(t=>e.values.includes(t)),o=i.filter(e=>!n.includes(e)),s=a.filter(e=>!o.includes(e)),c=n.filter(e=>!i.includes(e)&&!s.includes(e)),l=[...s,...c];return l.length===0&&!e.allowEmpty?[e.settingName,n]:[e.settingName,l]});return Object.fromEntries(n)},po=class extends Error{constructor(e){super(e),this.name=`UnreachableError`}},mo=u({chatState:()=>h,logic:()=>ko}),ho=e(re(),1),go=e(oa(),1),_o=(e,t)=>{if(!e)return;let n=t.find(t=>t.id===e);return n||console.warn(`autofire-predefined-question-id="${e}" did not match any loaded predefined question. Falling back to default routing.`),n},vo=(e,t,n,r,i)=>{if(e&&!t)return{name:`consent-page`};let a=new URLSearchParams(window.location.search),o=a.get(`q`),s=a.get(`id`)??void 0,c=a.get(`sid`)??void 0;return o?{name:`chat-page`,query:o,predefinedQuestionId:s,switchQuestionId:c}:i?{name:`chat-page`,query:i}:r?{name:`chat-page`,query:r.question,predefinedQuestionId:r.id}:n?{name:`chat-page`}:{name:`start-page`}},yo=`follow-up-q`,bo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),xo=()=>{let e=new URLSearchParams(window.location.hash.replace(/^#/,``)).get(`cID`)??void 0;return{cID:e&&bo(e)?e:void 0,followUpQuestion:new URLSearchParams(window.location.search).get(yo)?.trim()||void 0}},So=()=>{let e=new URLSearchParams(window.location.search);if(!e.has(yo))return;e.delete(yo);let t=e.toString();history.replaceState(null,``,`${window.location.pathname}${t?`?${t}`:``}${window.location.hash}`)},Co=e=>{if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t;console.warn(`additional-start-parameters must be a JSON object. Received: ${e}`);return}catch(t){console.warn(`Failed to parse additional-start-parameters as JSON: ${e}`,t);return}},wo=e=>{let t=Co(e);return t?(e=>Array.isArray(e)?e.map(String):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(Boolean):[])(t.scopeAvailableSlugs).length===1:!1},To=e=>e?e.map(e=>({id:Ti(),...e})):[],Q,$,Eo,Do=new Set,Oo=async e=>{if(Do.has(e))return;let t=(await de([e]))[e];if(t){let n=h.data.chatConfig.translations[e]??{};h.data.chatConfig.translations[e]=(0,ho.default)(t,n)}Do.add(e)},ko=Wa({name:`chat-logic`,state:h,excludeInDevTools:[`onInput`]},{async init(e){$=e;let t=$.speechRecognitionApiKey||void 0;Q=new ta({apiUrl:$.apiUrl,apiKey:$.apiKey,speechRecognitionApiKey:t,strict:!0,startParameters:Co($.additionalStartParameters)});try{let e=await Q.getChatConfig();window.CHAT_CONFIG_OVERRIDE&&Object.assign(e,window.CHAT_CONFIG_OVERRIDE);let t=(await Q.getMetadata()).mode===`maintenance`,n=fe($.lang,v(e.supportedLanguages));Do.clear(),Do.add(n);let r=se(e,await de([n]));$.inlineLayout!==void 0&&(r.inlineLayout=$.inlineLayout),$.forceChatPage!==void 0&&(r.forceChatPage=$.forceChatPage);let i=n;ne(i,h.targets.mainElement);let a=await this.getPredefinedQuestions(i),o=r.translations[i]?.ariaOpensInNewTab;o&&Q.setNewTabSrText(o);let s=[];if(r.renderKatex){let e=await import(`https://esm.sh/marked-katex-extension@5.1.5`).catch(e=>{console.error(`Couldn't load marked-katex-extension:`,e)});e&&(Q.setMarkedExtensions(e.default({nonStandard:!0,output:`mathml`})),s.push(`https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css`))}let c=Object.keys(r.fullTheme),l=!1;if(r.forceConsent)try{l=Y.getItem(`liipgpt:termsAccepted`)===`true`}catch(e){console.warn(`Failed to load terms acceptance from storage:`,e)}let u=_o($.autofirePredefinedQuestionId,a);h.data={currentConversationState:`idle`,chatConfig:r,language:i,predefinedQuestions:a,isInMaintenance:t,history:To(r.messageAdditions.init),selectedColorScheme:ce(),has2ColorSchemes:c.length===2,currentColorScheme:m(c),conversationFeedbackId:void 0,conversationFeedbackIsOpen:!1,answerFormMessageId:void 0,openedPopup:void 0,props:$,flyoutIsOpen:!1,questionHasPii:void 0,chatInputValue:``,selectorValues:fo(r.selectorsConfig),selectorsIsOpen:!1,predefinedQuestionId:void 0,switchQuestionId:void 0,currentReferencesAsideId:void 0,ariaLiveStatusMessage:void 0,ariaLiveStatusMessageClearingTimeout:void 0,wasReferencesAsideClosed:!1,isAsideMobile:!0,route:vo(r.forceConsent??!1,l,r.forceChatPage??!1,u,$.question),additionalStylesheets:s,hasOpenedOverlays:!1,isInlineLayoutContained:!1,termsAccepted:l,selectedTopic:void 0},window.LIIPGPT_LISTENERS?.route?.(h.data.route),window.LIIPGPT_LISTENERS?.conversation?.(h.data.currentConversationState),h.data.selectorsIsOpen=h.data.chatConfig.showExpandedSelectors??!1,h.initialized=!0,t&&this.showErrorToast(`maintenance`),this.checkForOpenedPopup(),window.addEventListener(`hashchange`,()=>{this.checkForOpenedPopup()}),await this.startFromHandoverOrRoute(()=>this.goto(vo(r.forceConsent??!1,l,r.forceChatPage??!1,u,$.question),!0))}catch(e){throw Ia.error(e instanceof Error?e.message:`Failed to load the chatbot. Please reload the page.`,{duration:1e4,unstyled:!0,classes:{toast:`toast`}}),e}},setTarget(e,t){h.targets[e]=t},goto(e,t=!1){if(!(!t&&(0,go.default)(h.data.route,e)))switch(h.data.route=e,window.LIIPGPT_LISTENERS?.route?.(e),e.name){case`consent-page`:break;case`start-page`:e.prefill&&(h.data.chatInputValue=e.prefill);break;case`chat-page`:if(h.data.chatInputValue=e.query??``,h.data.predefinedQuestionId=e.predefinedQuestionId,h.data.switchQuestionId=e.switchQuestionId,e.query&&(this.onSubmit(),h.data.chatConfig.addQueryToUrlParams)){let t=new URLSearchParams(window.location.search);t.set(`q`,e.query),e.predefinedQuestionId?t.set(`id`,e.predefinedQuestionId):t.delete(`id`),e.switchQuestionId?t.set(`sid`,e.switchQuestionId):t.delete(`sid`),history.pushState(null,``,`?${t.toString()}${window.location.hash}`)}break}},getSelectorConfig(e){let t=h.data.chatConfig.selectorsConfig.find(t=>t.settingName===e);if(!t)throw Error(`Setting ${e} not found`);return t},getPrettifiedSelectorValues(){let e=Object.entries(h.data.selectorValues).map(([e,t])=>{let n;try{n=this.getSelectorConfig(e)}catch(t){console.error(`Error getting selector config for ${e}: ${t}`);return}return n.type===`single-select`?[e,t[0]]:[e,t]}).filter(e=>!!e);return Object.fromEntries(e)},setSelectorValue(e,t){let n=this.getSelectorConfig(e);if(!n){console.warn(`Trying to set setting ${e} but it is not defined in the chat config`);return}if(n.type===`single-select`&&t.length>1){console.warn(`Trying to set multiple values for single-select setting ${e}`);return}h.data.selectorValues[e]=t,lo(h.data.selectorValues,h.data.chatConfig.selectorsConfig)},resetSelectorToDefaults(e){let t=this.getSelectorConfig(e);if(!t){console.warn(`Trying to reset setting ${e} but it is not defined in the chat config`);return}let n=t.defaultValues??(t.allowEmpty?[]:[t.values[0]]).filter(Boolean);return uo(e),h.data.selectorValues[e]=n,lo(h.data.selectorValues,h.data.chatConfig.selectorsConfig),n},async getPredefinedQuestions(e){if($?.hidePredefinedQuestions)return[];try{return Q.getPredefinedQuestions({url:window.location.origin+window.location.pathname,language:e})}catch(e){return console.warn(`Failed to load predefined questions:`,e),[]}},setColorScheme(e){h.data.selectedColorScheme=e,h.data.currentColorScheme=ue(e),this.setAriaLiveStatusMessage(e===`dark`?h.t.ariaDarkSelected:h.t.ariaLightSelected)},async abort(){await Eo?.abort()},changeConversationState(e){h.data.currentConversationState=e,window.LIIPGPT_LISTENERS?.conversation?.(e)},onInput(e){h.data.chatConfig.blockPII&&(h.data.questionHasPii=io(e)),h.data.chatInputValue=e,h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0},onSubmit(e=!1,t,n=!1){let r=eo(h.data.chatConfig.parentPageContext?.extractSelectors);if(h.data.questionHasPii){console.warn(`Question contains PII, not submitting:`,h.data.questionHasPii);return}let i=h.data.chatConfig.questionPrefix?`${h.data.chatConfig.questionPrefix} ${h.data.chatInputValue}`:h.data.chatInputValue;n||(h.data.history.push(...To(h.data.chatConfig.messageAdditions.user.before)),h.data.history.push({type:`user`,time:new Date().toISOString(),message:h.data.chatInputValue}),h.data.history.push(...To(h.data.chatConfig.messageAdditions.user.after)));let a=h.data.history.push(...To(h.data.chatConfig.messageAdditions.bot.before));h.data.history.push({id:`UNRESOLVED`,state:`loading`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:``,html:``,text:``},references:{all:[],used:[],unused:[]}});let o=!1,s=!1,c={features:$.features?$.features.trim().split(`,`):[`formatting`],mode:$.mode||void 0,cache:$.cache||void 0,onError:(e,t)=>{this.showErrorToast(e,t),window.LIIPGPT_LISTENERS?.error?.(e,t),(e===`pii-detected`||e===`blocked`)&&this.editLatestQuestion()},onMessage:e=>{e.type===`topic-selected`&&(h.data.selectedTopic={label:e.label,placeholder:e.placeholder,locked:wo($.additionalStartParameters)}),e.type===`state`&&e.state!==`history-entry-initialized`&&!s&&(s=!0,this.setAriaLiveStatusMessage(h.t.ariaQuestionSent))},lang:h.data.language,selectorValues:{...this.getPrettifiedSelectorValues(),context:no(),...t},predefinedQuestionId:h.data.predefinedQuestionId,switchQuestionId:h.data.switchQuestionId,onEmbed:e=>{let t=h.data.history[a];t&&t.type===`bot`&&!t.message.markdown?(h.data.history[a]={...e,id:t.id??Ti()},o=!0):h.data.history.push({...e,id:Ti()})}};h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0,r.length&&(c.selectorValues.parentPageContextHtml=r),c.referrer=aa(h.data.chatConfig.sendReferrer,{embedded:!!h.data.props.flyout}),h.data.props.source?c.source=h.data.props.source:h.data.props.flyout&&(c.source=`flyout`),h.data.currentConversationId||(h.data.currentConversationId=Q.createConversationId());let l=Q.chat(h.data.currentConversationId,i,c);Eo=l,h.data.lastChatResponseId=l.id,h.data.currentConversationState!==`searching`&&this.changeConversationState(`searching`);let u=!1,d,f=!!h.data.currentReferencesAsideId;(e&&f||!e&&h.data.chatConfig.showReferencesByDefault)&&(h.data.isAsideMobile||this.openReferencesAside(l.id)),l.subscribe(e=>{if(!o&&h.data.history[a]&&(h.data.history[a]={question:h.data.chatInputValue,...e}),h.data.chatConfig.addRetrievalQuestionToUrlParams&&e.retrievalQuestion){let t=new URLSearchParams(window.location.search);t.get(`search`)!==e.retrievalQuestion&&(t.set(`search`,e.retrievalQuestion),history.replaceState(null,``,`?${t.toString()}${window.location.hash}`))}h.data.chatConfig.showReferencesByDefault&&!h.data.wasReferencesAsideClosed&&h.data.currentReferencesAsideId!==e.id&&!h.data.isAsideMobile&&this.openReferencesAside(e.id),e.state===`streaming`&&h.data.currentConversationState!==`answering`&&this.changeConversationState(`answering`),e.state===`done`&&(this.changeConversationState(`idle`),u||(u=!0,this.setAriaLiveStatusMessage(`${h.t.ariaAnswerReady} ... ${e.message.text} ... ${h.data.selectedTopic?h.t.ariaAnswerFinishedWithSelectedTopic:h.t.ariaAnswerFinished}`),h.data.history.push(...To(h.data.chatConfig.messageAdditions.bot.after))),h.data.currentReferencesAsideId&&e.references.used.length>0?(clearTimeout(d),d=setTimeout(()=>{this.openReferencesAside(e.id)},100)):this.closeReferencesAside())}),h.data.chatInputValue=``},async onStartSpeechRecognition(){try{if(!await Ga()){this.showErrorToast(`speech-not-supported`);return}if(await navigator.mediaDevices.getUserMedia({audio:!0}),Xa.isSupported())h.data.chatInputValue=``,h.currentAudioRecorder=new Xa({onDataAvailable:async e=>{h.isTranscribing=!0,await this.handleTranscription(e)},onError:()=>{this.showErrorToast(`speech-microphone-access-denied`),h.currentAudioRecorder=null,h.isTranscribing=!1},onVolumeChange:e=>{h.currentAudioVolume=e}}),h.currentAudioRecorder.start();else{this.showErrorToast(`speech-not-supported`);return}}catch(e){throw this.showErrorToast(`speech-microphone-access-denied`),h.currentAudioRecorder=null,h.isTranscribing=!1,e}},editLatestQuestion(){let e=h.data.history.findLastIndex(e=>e?.type===`user`);if(e===-1){console.error(`No last user question, available`);return}let t=h.data.history.splice(e)[0];h.data.chatInputValue=t.message},onStopSpeechRecognition(){if(h.currentAudioRecorder){let e=h.currentAudioRecorder;h.currentAudioRecorder=null,e.stop()}h.currentAudioVolume=0},async handleTranscription(e){if(!e){console.warn(`No audio data received`);return}try{let t=await Q.transcribeAudio(e,{lang:h.data.language});if(t.error){this.showErrorToast(`speech-transcription-failed`);return}if(t.transcript.trim()){if(h.data.chatConfig.blockPII&&(h.data.questionHasPii=io(t.transcript.trim()),h.data.questionHasPii))return;h.data.chatInputValue=t.transcript.trim()}else this.showErrorToast(`speech-no-text-detected`)}catch(e){console.error(`Speech transcription error:`,e),this.showErrorToast(`speech-transcription-failed`)}finally{h.currentAudioRecorder=null,h.isTranscribing=!1,h.currentAudioVolume=0}},async startFromHandoverOrRoute(e){let{cID:t,followUpQuestion:n}=xo();if(!t){e();return}let r=await this.rehydrateFromSearchSummaryHandover(t);n?(h.data.route={name:`chat-page`},h.data.chatInputValue=n,this.onSubmit(!0)):r||e(),So()},async rehydrateFromSearchSummaryHandover(e){h.data.currentConversationId=e;let t=await Q.getMetadata(),n=t.mode===`ready`?t.userId:void 0,r=n?await Q.getChatHistory(e,n):[];if(r.length===0)return h.data.currentConversationId=void 0,!1;let i={all:[],used:[],unused:[]},a=new Dn({newTabSrText:h.t.ariaOpensInNewTab}),o=[];for(let{question:e,answer:t}of r)o.push({type:`user`,time:new Date().toISOString(),message:e,id:Ti()}),o.push({id:Ti(),state:`done`,errors:[],type:`bot`,time:new Date().toISOString(),message:{markdown:t,html:a.toHTML(t,i),text:t},references:{all:[],used:[],unused:[]}});return h.data.history=[...To(h.data.chatConfig.messageAdditions.init),...o],h.data.route={name:`chat-page`},!0},async onStartConversation(e,t,n){await this.abort(),h.data.history=To(h.data.chatConfig.messageAdditions.init),h.data.currentConversationId=Q.createConversationId(),this.goto({name:`chat-page`,query:e,predefinedQuestionId:t,switchQuestionId:n})},async onNewConversation(){await this.abort();let e=h.data.currentConversationId;if(h.data.currentConversationId=void 0,h.data.currentReferencesAsideId=void 0,h.data.history=To(h.data.chatConfig.messageAdditions.init),h.data.predefinedQuestionId=void 0,h.data.switchQuestionId=void 0,h.data.selectedTopic=void 0,h.data.chatConfig.addQueryToUrlParams){let e=new URLSearchParams(window.location.search);e.delete(`q`),e.delete(`id`),e.delete(`sid`),history.pushState(null,``,`?${e.toString()}${window.location.hash}`)}let t=_o(h.data.props.autofirePredefinedQuestionId,h.data.predefinedQuestions);t?this.goto({name:`chat-page`,query:t.question,predefinedQuestionId:t.id},!0):this.goto({name:`start-page`}),e&&Q.userAction(`newDiscussion`,{conversationId:e,lang:h.data.language}).catch(e=>{console.error(`Failed to notify backend of new discussion:`,e)})},async onChangeTopic(){let e=h.data.chatConfig.selectedTopicResetPredefinedQuestionId;if(!e){console.warn("No selectedTopicResetPredefinedQuestionId available to reset the selected topic. Set it in the `Config DB` in the backend, in a `generalConfig` default set.");return}await this.abort(),h.data.selectedTopic=void 0,h.data.predefinedQuestionId=e,h.data.switchQuestionId=void 0,h.data.chatInputValue=``,this.onSubmit(!0,void 0,!0)},showSuccessToast(e){Ia.success(h.t[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},showErrorToast(e,t){let n=t?.trim()?t:h.errorTranslations[e];Ia.error(n,{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},async submitFeedback(e){try{let t=h.data.conversationFeedbackId||h.data.lastChatResponseId;if(!t)throw new po(`Tried to give feedback with no id.`);let n=h.data.history.find(e=>e.type===`bot`&&e.id===t);await Q.feedback(t,n?.question??``,e),setTimeout(()=>{this.showSuccessToast(`thankYouForFeedback`)},500)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},toggleReferencesAside(e){h.data.currentReferencesAsideId===e?this.closeReferencesAside():this.openReferencesAside(e)},openReferencesAside(e){h.data.chatConfig.referencesLayout!==`inline`&&(h.data.currentReferencesAsideId=e,this.setOpenOverlay(!0))},closeReferencesAside(){h.data.currentReferencesAsideId=void 0,h.data.wasReferencesAsideClosed=!0,this.setOpenOverlay(!1)},setAsideMobile(e){h.data.isAsideMobile=e},openFlyout(){h.data.flyoutIsOpen=!0},closeFlyout(){h.data.flyoutIsOpen=!1},openConversationFeedback(){h.data.conversationFeedbackIsOpen=!0,this.setOpenOverlay(!0)},openMessageFeedback(e){h.data.conversationFeedbackId=e},closeFeedback(){h.data.conversationFeedbackIsOpen=!1,h.data.conversationFeedbackId=void 0,this.setOpenOverlay(!1)},openAnswerForm(e){h.data.answerFormMessageId=e,this.setOpenOverlay(!0)},closeAnswerForm(){h.data.answerFormMessageId=void 0,this.setOpenOverlay(!1)},async submitAnswerForm(e){try{let t=h.data.chatConfig.answerForm,n=h.data.answerFormMessageId;if(!t)throw new po(`Tried to submit the answer form with no answerForm config.`);if(!n)throw new po(`Tried to submit the answer form with no message id.`);let r=h.data.history.findIndex(e=>e.type===`bot`&&e.id===n),i=r===-1?void 0:h.data.history[r],a=h.data.history.slice(0,r===-1?void 0:r).findLast(e=>e.type===`user`)?.message,o=i?.question||a||(i?.type===`bot`?i.retrievalQuestion??``:``);await Q.submitAnswerForm({receiverEmail:t.receiverEmail,fields:t.fields.map(t=>({name:t.name,value:e[t.name]??``})),question:o,answer:i?.type===`bot`?i.message.text:``,requestId:n,lang:h.data.language}),setTimeout(()=>{this.showSuccessToast(`answerFormThankYou`)},500)}catch(e){console.error(`Answer form submission failed:`,e),this.showErrorToast(`answer-form-failed`)}},setOpenOverlay(e){h.data.hasOpenedOverlays=e},setAriaLiveStatusMessage(e){h.data.ariaLiveStatusMessage=e,clearTimeout(h.data.ariaLiveStatusMessageClearingTimeout),h.data.ariaLiveStatusMessageClearingTimeout=setTimeout(()=>{h.data.ariaLiveStatusMessage=``},h.ariaLiveMessagesClearingTimeoutDuration)},closePopup(){window.location.hash=``},checkForOpenedPopup(){let e=window.location.hash.slice(1),t=h.t.popups?.find(t=>t.hash===e);t?h.data.openedPopup=t:h.data.openedPopup=void 0},async thumbs(e,t){try{let n=h.data.history.find(t=>t.type===`bot`&&t.id===e),r=n?.type===`bot`?n:void 0;if(r?.feedback===t)return;t===`up`?await Q.thumbsUp(e,n?.question??``):await Q.thumbsDown(e,n?.question??``);let i=!r?.feedback;r&&(r.feedback=t),i&&this.showSuccessToast(`thankYouForFeedback`)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},async onLanguageChange(e){let t=ae(e,h.data.chatConfig.supportedLanguages);if(await Oo(t),h.data.language=t,ne(h.data.language,h.targets.mainElement),h.data.predefinedQuestions=await this.getPredefinedQuestions(h.data.language),this.setAriaLiveStatusMessage(h.t.ariaLanguageChanged),h.data.chatConfig.reflectLanguageInPath){let e=new URL(window.location.href);e.pathname=`/${h.data.language}`,window.history.replaceState({},``,e.toString())}},async acceptTerms(){h.data.termsAccepted=!0;try{Y.setItem(`liipgpt:termsAccepted`,`true`)}catch(e){console.warn(`Failed to save terms acceptance to storage:`,e)}this.closePopup(),await le(),this.goto(vo(h.data.chatConfig.forceConsent??!1,!0,h.data.chatConfig.forceChatPage??!1,_o(h.data.props.autofirePredefinedQuestionId,h.data.predefinedQuestions),h.data.props.question))},updateChatInput(e){h.data.chatInputValue=e}});export{Ti as _,Fa as a,Ca as c,pa as d,da as f,Ui as g,Xi as h,Ya as i,Sa as l,Zi as m,ko as n,Z as o,sa as p,Xa as r,ka as s,mo as t,_a as u};
|