@liip/liipgpt 3.6.0 → 3.6.1

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.
Files changed (32) hide show
  1. package/button/liipgpt-button.iife.js +25 -25
  2. package/chat/liipgpt-chat.iife.js +18 -18
  3. package/configurator/_app/env.js +1 -1
  4. package/configurator/_app/immutable/chunks/{zUel1ZW0.js → B5M3tt1h.js} +6 -6
  5. package/configurator/_app/immutable/chunks/{CFfgUb3G.js → BF-6zfFW.js} +1 -1
  6. package/configurator/_app/immutable/chunks/{CqPRQdP7.js → BLUZvgID.js} +1 -1
  7. package/configurator/_app/immutable/chunks/{Db3xJ3R_.js → BdBqI4to.js} +1 -1
  8. package/configurator/_app/immutable/chunks/{DUr69vGU.js → BgnzWwt-.js} +1 -1
  9. package/configurator/_app/immutable/chunks/{EDJuo58-.js → BpIo1_hS.js} +2 -2
  10. package/configurator/_app/immutable/chunks/{qE7I_Q4N.js → CwB4sTdn.js} +1 -1
  11. package/configurator/_app/immutable/chunks/DABlUYYh.js +1 -0
  12. package/configurator/_app/immutable/chunks/{BTwygYhA.js → DFfTn9KD.js} +1 -1
  13. package/configurator/_app/immutable/chunks/{BwV52vQs.js → DzLbPreo.js} +1 -1
  14. package/configurator/_app/immutable/chunks/{B2vNY6lx.js → dq9OZHm7.js} +2 -2
  15. package/configurator/_app/immutable/chunks/vVBttUZh.js +1 -0
  16. package/configurator/_app/immutable/entry/{app.BS_BNglT.js → app.BPWZQddg.js} +2 -2
  17. package/configurator/_app/immutable/entry/start.CpjUPnYE.js +1 -0
  18. package/configurator/_app/immutable/nodes/{0.D_2XXaJQ.js → 0.DxuzEfw5.js} +2 -2
  19. package/configurator/_app/immutable/nodes/{1.BnWVDJCZ.js → 1.B-APb2B8.js} +1 -1
  20. package/configurator/_app/immutable/nodes/{2.SUtdjb5A.js → 2.CfEhZdph.js} +3 -3
  21. package/configurator/_app/immutable/nodes/{3.Bo3t-YCM.js → 3.Bn5RTTEX.js} +1 -1
  22. package/configurator/_app/version.json +1 -1
  23. package/configurator/index.html +6 -6
  24. package/configurator/sidebar.html +6 -6
  25. package/index.cjs +4 -3
  26. package/index.d.ts +1 -0
  27. package/index.js +4 -3
  28. package/package.json +1 -1
  29. package/search-summary/liipgpt-search-summary.iife.js +2 -2
  30. package/configurator/_app/immutable/chunks/BGwzfQ_H.js +0 -1
  31. package/configurator/_app/immutable/chunks/CKDKLu5Y.js +0 -1
  32. package/configurator/_app/immutable/entry/start.B8ApCMix.js +0 -1
@@ -1 +1 @@
1
- import{r as e,t}from"./CibALFW0.js";import{At as n,Et as r,Ft as i,I as a,It as o,J as s,Lt as c,O as l,Ot as u,Pt as d,Rt as f,St as p,Vt as m,at as h,bt as g,ct as _,dt as v,g as y,ht as b,i as x,j as ee,jt as S,m as te,mt as C,o as w,q as ne,rt as T,s as re,st as E,wt as D}from"./C00ruT0L.js";import{t as O}from"./DjVmpym-.js";import{i as ie,n as ae,r as oe,t as se}from"./DFBUyDYh.js";import{d as ce,l as k,o as le,p as ue,u as de}from"./EDJuo58-.js";import{i as A,n as fe,t as pe}from"./CX0dfddQ.js";var me={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function he(e,t,n){e||={};let r=e.random??e.rng?.()??de();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return ce(r)}function j(e,t,n){return me.randomUUID&&!t&&!e?me.randomUUID():he(e,t,n)}var ge={de:{aborted:`Verbindung zum Server wurde unerwartet unterbrochen. Bitte versuchen Sie es erneut.`,"client-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,"server-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,"sse-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,blocked:`Ihre Anfrage wurde blockiert.`,"pii-detected":`Es wurden persönliche Daten erkannt. Bitte entfernen Sie diese und versuchen Sie es erneut.`,"incomplete-error":`Ein unbekannter Fehler ist aufgetreten. Die Antwort könnte unvollständig sein.`,"unexpected-call":`Ein unbekannter Fehler ist aufgetreten. Die Antwort könnte unvollständig sein.`,"quota-reached":`Kontingent überschritten. Bitte versuchen Sie es später erneut.`,"rate-limit":`Kontingent überschritten. Bitte versuchen Sie es später erneut.`,maintenance:`Der Chat ist derzeit nicht verfügbar. Bitte versuchen Sie es später erneut.`,"too-long":`Ihre Frage war zu lang, versuchen Sie es mit einer Kürzeren.`,"too-short":`Ihre Frage war zu kurz, versuchen Sie es mit einer Längeren.`,"feedback-failed":`Feedback senden fehlgeschlagen. Bitte versuchen Sie es erneut.`,"speech-not-supported":`Spracherkennung wird nicht unterstützt.`,"speech-transcription-failed":`Sprachtranskription fehlgeschlagen.`,"speech-no-text-detected":`Kein Text in der Spracheingabe erkannt.`,"speech-microphone-access-denied":`Mikrofonzugriff verweigert.`},en:{aborted:`Connection to the server was unexpectedly interrupted. Please try again.`,"client-error":`An unknown error has occurred. Please try again.`,"server-error":`An unknown error has occurred. Please try again.`,"sse-error":`An unknown error has occurred. Please try again.`,blocked:`Your request has been blocked.`,"pii-detected":`Personal data has been detected. Please remove it and try again.`,"incomplete-error":`An unknown error has occurred. The response might be incomplete.`,"unexpected-call":`An unknown error has occurred. The response might be incomplete.`,"quota-reached":`Quota exceeded. Please try again later.`,"rate-limit":`Quota exceeded. Please try again later.`,maintenance:`The chat is currently unavailable. Please try again later.`,"too-long":`Your question was too long, try a shorter one.`,"too-short":`Your question was too short, try a longer one.`,"feedback-failed":`Failed to send feedback. Please try again.`,"speech-not-supported":`Speech recognition is not supported.`,"speech-transcription-failed":`Speech transcription failed.`,"speech-no-text-detected":`No text detected in speech input.`,"speech-microphone-access-denied":`Microphone access denied.`},it:{aborted:`La connessione al server è stata interrotta inaspettatamente. Si prega di riprovare.`,"client-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,"server-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,"sse-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,blocked:`La tua richiesta è stata bloccata.`,"pii-detected":`Sono stati rilevati dati personali. Si prega di rimuoverli e riprovare.`,"incomplete-error":`Si è verificato un errore sconosciuto. La risposta potrebbe essere incompleta.`,"unexpected-call":`Si è verificato un errore sconosciuto. La risposta potrebbe essere incompleta.`,"quota-reached":`Quota superata. Si prega di riprovare più tardi.`,"rate-limit":`Quota superata. Si prega di riprovare più tardi.`,maintenance:`La chat non è attualmente disponibile. Si prega di riprovare più tardi.`,"too-long":`La tua domanda era troppo lunga, prova con una più breve.`,"too-short":`La tua domanda era troppo breve, prova con una più lunga.`,"feedback-failed":`Invio del feedback non riuscito. Si prega di riprovare.`,"speech-not-supported":`Il riconoscimento vocale non è supportato.`,"speech-transcription-failed":`Trascrizione vocale fallita.`,"speech-no-text-detected":`Nessun testo rilevato nell'input vocale.`,"speech-microphone-access-denied":`Accesso al microfono negato.`},fr:{aborted:`La connexion au serveur a été interrompue de façon inattendue. Veuillez réessayer.`,"client-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"server-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"sse-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"pii-detected":`Des données personnelles ont été détectées. Veuillez les supprimer et réessayer.`,blocked:`Votre demande a été bloquée.`,"incomplete-error":`Une erreur inconnue s'est produite. La réponse pourrait être incomplète.`,"unexpected-call":`Une erreur inconnue s'est produite. La réponse pourrait être incomplète.`,"quota-reached":`Quota dépassé. Veuillez réessayer plus tard.`,"rate-limit":`Quota dépassé. Veuillez réessayer plus tard.`,maintenance:`Le chat est actuellement indisponible. Veuillez réessayer plus tard.`,"too-long":`Votre question était trop longue, essayez d'en poser une plus courte.`,"too-short":`Votre question était trop courte, essayez d'en poser une plus longue.`,"feedback-failed":`Échec de l'envoi du feedback. Veuillez réessayer.`,"speech-not-supported":`La reconnaissance vocale n'est pas prise en charge.`,"speech-transcription-failed":`Échec de la transcription vocale.`,"speech-no-text-detected":`Aucun texte détecté dans l'entrée vocale.`,"speech-microphone-access-denied":`Accès au microphone refusé.`}},M={de:{email:`Bitte keine E-Mail Adressen eingeben`,creditCard:`Bitte keine Kreditkarteninformationen eingeben`,ahv:`Bitte keine AHV-Nummern eingeben`,phoneSwiss:`Bitte keine Telefonnummern eingeben`,phoneInternational:`Bitte keine Telefonnummern eingeben`,swissPassport:`Bitte keine Passinformationen eingeben`,longNumber:`Bitte keine langen Nummern eingeben`},en:{email:`Please do not enter email addresses`,creditCard:`Please do not enter credit card information`,ahv:`Please do not enter AHV numbers`,phoneSwiss:`Please do not enter phone numbers`,phoneInternational:`Please do not enter phone numbers`,swissPassport:`Please do not enter passport information`,longNumber:`Please do not enter long numbers`},it:{email:`Si prega di non inserire indirizzi email`,creditCard:`Si prega di non inserire informazioni sulla carta di credito`,ahv:`Si prega di non inserire numeri AVS`,phoneSwiss:`Si prega di non inserire numeri di telefono`,phoneInternational:`Si prega di non inserire numeri di telefono`,swissPassport:`Si prega di non inserire informazioni sul passaporto`,longNumber:`Si prega di non inserire numeri lunghi`},fr:{email:`Veuillez ne pas saisir d'adresses e-mail`,creditCard:`Veuillez ne pas saisir d'informations de carte de crédit`,ahv:`Veuillez ne pas saisir de numéros AVS`,phoneSwiss:`Veuillez ne pas saisir de numéros de téléphone`,phoneInternational:`Veuillez ne pas saisir de numéros de téléphone`,swissPassport:`Veuillez ne pas saisir d'informations de passeport`,longNumber:`Veuillez ne pas saisir de longs numéros`}},_e=t(((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 ve(...e){return e.filter(Boolean).join(` `)}var ye=typeof document<`u`,be=typeof window<`u`?window:void 0;typeof window<`u`&&window.document,typeof window<`u`&&window.navigator,typeof window<`u`&&window.location;function xe(e){let t=e.activeElement;for(;t?.shadowRoot;){let e=t.shadowRoot.activeElement;if(e===t)break;t=e}return t}new class{#e;#t;constructor(e={}){let{window:t=be,document:r=t?.document}=e;t!==void 0&&(this.#e=r,this.#t=n(e=>{let n=T(t,`focusin`,e),r=T(t,`focusout`,e);return()=>{n(),r()}}))}get current(){return this.#t?.(),this.#e?xe(this.#e):null}};var N=class{#e;#t;constructor(e){this.#e=e,this.#t=Symbol(e)}get key(){return this.#t}exists(){return i(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 f(this.#t,e)}};function Se(e,t){switch(e){case`post`:C(t);break;case`pre`:b(t);break}}function P(e,t,n,r={}){let{lazy:i=!1}=r,a=!i,o=Array.isArray(e)?[]:void 0;Se(t,()=>{let t=Array.isArray(e)?e.map(e=>e()):e();if(!a){a=!0,o=t;return}let r=_(()=>n(t,o));return o=t,r})}function F(e,t,n){let r=v(()=>{let i=!1;P(e,t,(e,t)=>{if(i){r();return}let a=n(e,t);return i=!0,a},{lazy:!0})});C(()=>r)}function I(e,t,n){P(e,`post`,t,n)}function Ce(e,t,n){P(e,`pre`,t,n)}I.pre=Ce;function we(e,t){F(e,`post`,t)}function Te(e,t){F(e,`pre`,t)}we.pre=Te;function Ee(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 De(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 Oe(e,t,n={},i){let{lazy:a=!1,once:o=!1,initialValue:s,debounce:c,throttle:l}=n,u=r(p(s)),d=r(!1),f=r(void 0),m=r(p([])),g=()=>{h(m).forEach(e=>e()),D(m,[],!0)},_=e=>{D(m,[...h(m),e],!0)},v=async(e,n,r=!1)=>{try{D(d,!0),D(f,void 0),g();let i=new AbortController;_(()=>i.abort());let a=await t(e,n,{data:h(u),refetching:r,onCleanup:_,signal:i.signal});return D(u,a,!0),a}catch(e){e instanceof DOMException&&e.name===`AbortError`||D(f,e,!0);return}finally{D(d,!1)}},y=c?Ee(v,c):l?De(v,l):v,b=Array.isArray(e)?e:[e],x;return i((t,n)=>{o&&x||(x=t,y(Array.isArray(e)?t:t[0],Array.isArray(e)?n:n?.[0]))},{lazy:a}),{get current(){return h(u)},get loading(){return h(d)},get error(){return h(f)},mutate:e=>{D(u,e,!0)},refetch:t=>{let n=b.map(e=>e());return y(Array.isArray(e)?n:n[0],Array.isArray(e)?n:n[0],t??!0)}}}function ke(e,t,n){return Oe(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];I(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}function Ae(e,t,n){return Oe(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];I.pre(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}ke.pre=Ae,new N(`richColorsContext`);var je=new N(`<Toaster/>`),Me=0,Ne=class{#e=r(p([]));get toasts(){return h(this.#e)}set toasts(e){D(this.#e,e,!0)}#t=r(p([]));get heights(){return h(this.#t)}set heights(e){D(this.#t,e,!0)}#n=e=>{let t=this.toasts.findIndex(t=>t.id===e);return t===-1?null:t};addToast=e=>{ye&&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,updated:!0}};create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id&&e.id?.length>0?e.id:Me++,i=e.dismissible===void 0?e.dismissable===void 0?!0:e.dismissable:e.dismissible,a=e.type===void 0?`default`:e.type;return _(()=>{this.toasts.find(e=>e.id===r)?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=>(_(()=>{if(e===void 0){this.toasts=this.toasts.map(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.#n(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=Pe(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=t?.id||Me++;return this.create({component:e,id:n,...t}),n};removeHeight=e=>{this.heights=this.heights.filter(t=>t.toastId!==e)};setHeight=e=>{let t=this.#n(e.toastId);if(t===null){this.heights.push(e);return}this.heights[t]=e};reset=()=>{this.toasts=[],this.heights=[]}};function Pe(e){return e&&typeof e==`object`&&`status`in e?`HTTP error! Status: ${e.status}`:`Error! ${e}`}var L=new Ne;function Fe(e,t){return L.create({message:e,...t})}var Ie=class{#e=u(()=>L.toasts.filter(e=>!e.dismiss));get toasts(){return h(this.#e)}},R=Object.assign(Fe,{success:L.success,info:L.info,warning:L.warning,error:L.error,custom:L.custom,message:L.message,promise:L.promise,dismiss:L.dismiss,loading:L.loading,getActiveToasts:()=>L.toasts.filter(e=>!e.dismiss)}),Le=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)},Re=(e,t)=>{let n={};return t.forEach(t=>{n[t]=e[t]}),n},ze=console.warn,Be=()=>{},Ve=(e,t)=>_(()=>{console.warn=Be;let n=m(t?Re(e,t):e);return console.warn=ze,n}),He=e=>e&&typeof e.then==`function`,Ue=class{config;self;devtools;stateKeys;constructor(e,t){this.config=e,this.self=t,typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&(this.stateKeys=Le(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 Ve(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 _(()=>t.call(this.self,...r));let i=Ve(r);this.sendStart(e,i);try{let n=_(()=>t.call(this.self,...r));return He(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}},We=(e,t)=>{let n={},r=new Ue(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 Ge(){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 z(){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 B(){return typeof window>`u`?!1:!!(window.MediaRecorder&&z())}function Ke(){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 V(){return typeof window>`u`?!1:!!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||Ke())}var H=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(!B()||!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=z();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 B()}static getSupportedMediaType(){return z()}},qe=ue(),Je=(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`)))},Ye=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&&Je(e,n)}),qe.sanitize(t.outerHTML,{FORBID_TAGS:[`style`,`script`],FORBID_ATTR:[`style`,`class`]})},Xe=e=>{if(!e?.length)return[];let t=e.join(`,`),n=document.querySelectorAll(t);return Array.from(n,Ye)},U=`liipgpt:context`,Ze=class{contextVersion=0;#e=r();get currentContext(){return h(this.#e)}set currentContext(e){D(this.#e,e,!0)}getFromLocalStorage(){let e=localStorage.getItem(U);if(e){let t;try{if(t=JSON.parse(e),t.version!==this.contextVersion){localStorage.removeItem(U);return}else return t.context}catch(e){console.error(`Failed to parse liipgpt:context`,e);return}}}storeToLocalStorage(){localStorage.setItem(`liipgpt:context`,JSON.stringify({version:X.data.chatConfig.contextVersion,context:this.currentContext}))}constructor(e){this.init=e,this.currentContext=this.getFromLocalStorage()??e.initialValue}getContext(){return m(this.currentContext)}setContextVersion(e){this.contextVersion=e}setContext(e){this.currentContext=e,this.storeToLocalStorage()}resetContext(){this.currentContext=this.init.initialValue,this.storeToLocalStorage()}updateContext(e){this.setContext(e(this.currentContext))}},Qe=()=>localStorage.getItem(U),$e=[{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\.\d{4}\.\d{4}\.\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)}],W=e=>{for(let t of $e)if(t.check(e))return t.type},G=`liipgpt:selectorValues`,K=`liipgpt:selectorKnownDefaults`,q=()=>{try{let e=k.getItem(G),t=k.getItem(K);return e?{values:JSON.parse(e),knownDefaults:t?JSON.parse(t):{}}:null}catch{return null}},et=e=>{let t={};for(let n of e)t[n.settingName]=n.defaultValues??(n.allowEmpty?[]:[n.values[0]]).filter(Boolean);return t},tt=(e,t)=>{try{let n=et(t);k.setItem(G,JSON.stringify(e)),k.setItem(K,JSON.stringify(n))}catch(e){console.error(`Failed to save selector values:`,e)}},nt=e=>{try{let t=q();if(!t)return;delete t.values[e],delete t.knownDefaults[e],k.setItem(G,JSON.stringify(t.values)),k.setItem(K,JSON.stringify(t.knownDefaults))}catch(e){console.error(`Failed to clear selector saved state:`,e)}},rt=e=>{let t=q(),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)},it=class extends Error{constructor(e){super(e),this.name=`UnreachableError`}},at=e(_e(),1),ot=(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},J=(e,t,n,r)=>{if(e&&!t)return{name:`consent-page`};let i=new URLSearchParams(window.location.search),a=i.get(`q`),o=i.get(`id`)??void 0,s=i.get(`sid`)??void 0;return a?{name:`chat-page`,query:a,predefinedQuestionId:o,switchQuestionId:s}:r?{name:`chat-page`,query:r.question,predefinedQuestionId:r.id}:n?{name:`chat-page`}:{name:`start-page`}},Y=e=>e?e.map(e=>({id:j(),...e})):[],X=new class{#e=r(p({}));get data(){return h(this.#e)}set data(e){D(this.#e,e,!0)}#t=r(p({}));get targets(){return h(this.#t)}set targets(e){D(this.#t,e,!0)}#n=r(!1);get initialized(){return h(this.#n)}set initialized(e){D(this.#n,e,!0)}#r=r(0);get currentAudioVolume(){return h(this.#r)}set currentAudioVolume(e){D(this.#r,e,!0)}ariaLiveMessagesClearingTimeoutDuration=350;#i=r(null);get currentAudioRecorder(){return h(this.#i)}set currentAudioRecorder(e){D(this.#i,e,!0)}#a=r(!1);get isTranscribing(){return h(this.#a)}set isTranscribing(e){D(this.#a,e,!0)}#o=u(()=>{if(!this.initialized)return[];let e=this.data.chatConfig.menu;return e?e[this.data.language]??[]:[]});get menu(){return h(this.#o)}set menu(e){D(this.#o,e)}#s=u(()=>this.initialized?this.data.chatConfig.translations[this.data.language]??{}:{});get t(){return h(this.#s)}set t(e){D(this.#s,e)}#c=u(()=>this.initialized?ge[this.data.language]??{}:ge.en??{});get errorTranslations(){return h(this.#c)}set errorTranslations(e){D(this.#c,e)}#l=u(()=>this.initialized?M[this.data.language]??{}:M.en??{});get piiTranslations(){return h(this.#l)}set piiTranslations(e){D(this.#l,e)}#u=u(()=>this.initialized?this.data.currentColorScheme:`light`);get colorScheme(){return h(this.#u)}set colorScheme(e){D(this.#u,e)}#d=u(()=>this.initialized?this.data.chatConfig.fullTheme[this.data.currentColorScheme]:{});get themeBase(){return h(this.#d)}set themeBase(e){D(this.#d,e)}#f=u(()=>this.themeBase.tokens);get theme(){return h(this.#f)}set theme(e){D(this.#f,e)}#p=u(()=>{if(!this.initialized)return[];let e=[];for(let t of this.data.chatConfig.selectorsConfig)t.allowEmpty||(this.data.selectorValues[t.settingName]||[]).length===0&&e.push(t.settingName);return e});get selectorsWithErrors(){return h(this.#p)}set selectorsWithErrors(e){D(this.#p,e)}},Z,Q,st,ct=We({name:`chat-logic`,state:X,excludeInDevTools:[`onInput`]},{async init(e){Q=e;let t=Q.speechRecognitionApiKey||void 0;Z=new le({apiUrl:Q.apiUrl,apiKey:Q.apiKey,speechRecognitionApiKey:t,strict:!0});try{let e=await Z.getChatConfig();window.CHAT_CONFIG_OVERRIDE&&Object.assign(e,window.CHAT_CONFIG_OVERRIDE);let t=(await Z.getMetadata()).mode===`maintenance`;t&&this.showErrorToast(`maintenance`);let n=ie(e);Q.inlineLayout!==void 0&&(n.inlineLayout=Q.inlineLayout),Q.forceChatPage!==void 0&&(n.forceChatPage=Q.forceChatPage);let r;r=Q.lang?fe(Q.lang,n.supportedLanguages):pe(n.supportedLanguages),A(r,X.targets.mainElement);let i=await this.getPredefinedQuestions(r),a=n.translations[r]?.ariaOpensInNewTab;a&&Z.setNewTabSrText(a);let o=[];if(n.renderKatex){let e=await O(()=>import(`https://esm.sh/marked-katex-extension@5.1.5`),[],import.meta.url).catch(e=>{console.error(`Couldn't load marked-katex-extension:`,e)});e&&(Z.setMarkedExtensions(e.default({nonStandard:!0,output:`mathml`})),o.push(`https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css`))}let s=Object.keys(n.fullTheme),c=!1;if(n.forceConsent)try{c=k.getItem(`liipgpt:termsAccepted`)===`true`}catch(e){console.warn(`Failed to load terms acceptance from storage:`,e)}let l=ot(Q.autofirePredefinedQuestionId,i);X.data={currentConversationState:`idle`,chatConfig:n,language:r,predefinedQuestions:i,isInMaintenance:t,history:Y(n.messageAdditions.init),selectedColorScheme:ae(),has2ColorSchemes:s.length===2,currentColorScheme:se(s),conversationFeedbackId:void 0,conversationFeedbackIsOpen:!1,openedPopup:void 0,props:Q,flyoutIsOpen:!1,questionHasPii:void 0,chatInputValue:``,selectorValues:rt(n.selectorsConfig),selectorsIsOpen:!1,predefinedQuestionId:void 0,switchQuestionId:void 0,currentReferencesAsideId:void 0,ariaLiveStatusMessage:void 0,ariaLiveStatusMessageClearingTimeout:void 0,wasReferencesAsideClosed:!1,isAsideMobile:!0,route:J(n.forceConsent??!1,c,n.forceChatPage??!1,l),additionalStylesheets:o,hasOpenedOverlays:!1,isInlineLayoutContained:!1,termsAccepted:c,selectedTopic:void 0},window.LIIPGPT_LISTENERS?.route?.(X.data.route),window.LIIPGPT_LISTENERS?.conversation?.(X.data.currentConversationState),X.data.selectorsIsOpen=X.data.chatConfig.showExpandedSelectors??!1,X.initialized=!0,this.checkForOpenedPopup(),window.addEventListener(`hashchange`,()=>{this.checkForOpenedPopup()}),this.goto(J(n.forceConsent??!1,c,n.forceChatPage??!1,l),!0)}catch(e){throw R.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){X.targets[e]=t},goto(e,t=!1){if(!(!t&&(0,at.default)(X.data.route,e)))switch(X.data.route=e,window.LIIPGPT_LISTENERS?.route?.(e),e.name){case`consent-page`:break;case`start-page`:e.prefill&&(X.data.chatInputValue=e.prefill);break;case`chat-page`:if(X.data.chatInputValue=e.query??``,X.data.predefinedQuestionId=e.predefinedQuestionId,X.data.switchQuestionId=e.switchQuestionId,e.query&&(this.onSubmit(),X.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()}`)}break}},getSelectorConfig(e){let t=X.data.chatConfig.selectorsConfig.find(t=>t.settingName===e);if(!t)throw Error(`Setting ${e} not found`);return t},getPrettifiedSelectorValues(){let e=Object.entries(X.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}X.data.selectorValues[e]=t,tt(X.data.selectorValues,X.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 nt(e),X.data.selectorValues[e]=n,tt(X.data.selectorValues,X.data.chatConfig.selectorsConfig),n},async getPredefinedQuestions(e){try{return Z.getPredefinedQuestions({url:window.location.origin+window.location.pathname,language:e})}catch(e){return console.warn(`Failed to load predefined questions:`,e),[]}},setColorScheme(e){X.data.selectedColorScheme=e,X.data.currentColorScheme=oe(e),this.setAriaLiveStatusMessage(e===`dark`?X.t.ariaDarkSelected:X.t.ariaLightSelected)},async abort(){await st?.abort()},changeConversationState(e){X.data.currentConversationState=e,window.LIIPGPT_LISTENERS?.conversation?.(e)},onInput(e){X.data.chatConfig.blockPII&&(X.data.questionHasPii=W(e)),X.data.chatInputValue=e,X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0},onSubmit(e=!1,t,n=!1){let r=Xe(X.data.chatConfig.parentPageContext?.extractSelectors);if(X.data.questionHasPii){console.warn(`Question contains PII, not submitting:`,X.data.questionHasPii);return}let i=X.data.chatConfig.questionPrefix?`${X.data.chatConfig.questionPrefix} ${X.data.chatInputValue}`:X.data.chatInputValue;n||(X.data.history.push(...Y(X.data.chatConfig.messageAdditions.user.before)),X.data.history.push({type:`user`,time:new Date().toISOString(),message:X.data.chatInputValue}),X.data.history.push(...Y(X.data.chatConfig.messageAdditions.user.after)));let a=X.data.history.push(...Y(X.data.chatConfig.messageAdditions.bot.before));X.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={features:Q.features?Q.features.trim().split(`,`):[`formatting`],onError:e=>{this.showErrorToast(e),window.LIIPGPT_LISTENERS?.error?.(e),(e===`pii-detected`||e===`blocked`)&&this.editLatestQuestion()},onMessage:e=>{e.type===`topic-selected`&&(X.data.selectedTopic={label:e.label,placeholder:e.placeholder})},lang:X.data.language,selectorValues:{...this.getPrettifiedSelectorValues(),context:Qe(),...t},predefinedQuestionId:X.data.predefinedQuestionId,switchQuestionId:X.data.switchQuestionId,onEmbed:e=>{let t=X.data.history[a];t&&t.type===`bot`&&!t.message.markdown?(X.data.history[a]={...e,id:t.id??j()},o=!0):X.data.history.push({...e,id:j()})}};X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0,r.length&&(s.selectorValues.parentPageContextHtml=r);let c=(e,t)=>{try{let n=new URL(e),r=new URL(t);return n.origin===r.origin&&n.pathname===r.pathname}catch{return!1}},l=X.data.chatConfig.sendReferrer??`all`;if([`all`,`own`,`location`].includes(l)){let e=l===`location`||X.data.props.flyout,t;t=e?`${window.location.protocol}//${window.location.host}${window.location.pathname}`:c(document.referrer,window.location.href)?null:document.referrer;let n=l===`own`&&!X.data.props.flyout&&t&&!t.startsWith(window.location.origin);s.referrer=t&&!n?t:void 0}X.data.currentConversationId||(X.data.currentConversationId=Z.createConversationId());let u=Z.chat(X.data.currentConversationId,i,s);st=u,X.data.lastChatResponseId=u.id,X.data.currentConversationState!==`searching`&&this.changeConversationState(`searching`),this.setAriaLiveStatusMessage(X.t.ariaQuestionSent);let d=!1,f,p=!!X.data.currentReferencesAsideId;(e&&p||!e&&X.data.chatConfig.showReferencesByDefault)&&(X.data.isAsideMobile||this.openReferencesAside(u.id)),u.subscribe(e=>{if(!o&&X.data.history[a]&&(X.data.history[a]={question:X.data.chatInputValue,...e}),X.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()}`))}X.data.chatConfig.showReferencesByDefault&&!X.data.wasReferencesAsideClosed&&X.data.currentReferencesAsideId!==e.id&&!X.data.isAsideMobile&&this.openReferencesAside(e.id),e.state===`streaming`&&X.data.currentConversationState!==`answering`&&this.changeConversationState(`answering`),e.state===`done`&&(this.changeConversationState(`idle`),d||(d=!0,this.setAriaLiveStatusMessage(`${X.t.ariaAnswerReady} ... ${e.message.text} ... ${X.t.ariaAnswerFinished}`),X.data.history.push(...Y(X.data.chatConfig.messageAdditions.bot.after))),X.data.currentReferencesAsideId&&e.references.used.length>0?(clearTimeout(f),f=setTimeout(()=>{this.openReferencesAside(e.id)},100)):this.closeReferencesAside())}),X.data.chatInputValue=``},async onStartSpeechRecognition(){try{if(!await Ge()){this.showErrorToast(`speech-not-supported`);return}if(await navigator.mediaDevices.getUserMedia({audio:!0}),H.isSupported())X.data.chatInputValue=``,X.currentAudioRecorder=new H({onDataAvailable:async e=>{X.isTranscribing=!0,await this.handleTranscription(e)},onError:()=>{this.showErrorToast(`speech-microphone-access-denied`),X.currentAudioRecorder=null,X.isTranscribing=!1},onVolumeChange:e=>{X.currentAudioVolume=e}}),X.currentAudioRecorder.start();else{this.showErrorToast(`speech-not-supported`);return}}catch(e){throw this.showErrorToast(`speech-microphone-access-denied`),X.currentAudioRecorder=null,X.isTranscribing=!1,e}},editLatestQuestion(){let e=X.data.history.findLastIndex(e=>e?.type===`user`);if(e===-1){console.error(`No last user question, available`);return}let t=X.data.history.splice(e)[0];X.data.chatInputValue=t.message},onStopSpeechRecognition(){if(X.currentAudioRecorder){let e=X.currentAudioRecorder;X.currentAudioRecorder=null,e.stop()}X.currentAudioVolume=0},async handleTranscription(e){if(!e){console.warn(`No audio data received`);return}try{let t=await Z.transcribeAudio(e,{lang:X.data.language});if(t.error){this.showErrorToast(`speech-transcription-failed`);return}if(t.transcript.trim()){if(X.data.chatConfig.blockPII&&(X.data.questionHasPii=W(t.transcript.trim()),X.data.questionHasPii))return;X.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{X.currentAudioRecorder=null,X.isTranscribing=!1,X.currentAudioVolume=0}},async onStartConversation(e,t,n){await this.abort(),X.data.history=Y(X.data.chatConfig.messageAdditions.init),X.data.currentConversationId=Z.createConversationId(),this.goto({name:`chat-page`,query:e,predefinedQuestionId:t,switchQuestionId:n})},async onNewConversation(){await this.abort();let e=X.data.currentConversationId;if(X.data.currentConversationId=void 0,X.data.currentReferencesAsideId=void 0,X.data.history=Y(X.data.chatConfig.messageAdditions.init),X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0,X.data.selectedTopic=void 0,X.data.chatConfig.addQueryToUrlParams){let e=new URLSearchParams(window.location.search);e.delete(`q`),e.delete(`id`),e.delete(`sid`),history.pushState(null,``,`?${e.toString()}`)}this.goto({name:`start-page`}),e&&Z.userAction(`newDiscussion`,{conversationId:e,lang:X.data.language}).catch(e=>{console.error(`Failed to notify backend of new discussion:`,e)})},async onChangeTopic(){let e=X.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(),X.data.selectedTopic=void 0,X.data.predefinedQuestionId=e,X.data.switchQuestionId=void 0,X.data.chatInputValue=``,this.onSubmit(!0,void 0,!0),V()||E().then(()=>X.targets.chatInput?.focus())},showSuccessToast(e){R.success(X.t[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},showErrorToast(e){R.error(X.errorTranslations[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},async submitFeedback(e){try{let t=X.data.conversationFeedbackId||X.data.lastChatResponseId;if(!t)throw new it(`Tried to give feedback with no id.`);let n=X.data.history.find(e=>e.type===`bot`&&e.id===t);await Z.feedback(t,n?.question??``,e),setTimeout(()=>{this.showSuccessToast(`thankYouForFeedback`)},500)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},toggleReferencesAside(e){X.data.currentReferencesAsideId===e?this.closeReferencesAside():this.openReferencesAside(e)},openReferencesAside(e){X.data.currentReferencesAsideId=e,this.setOpenOverlay(!0)},closeReferencesAside(){X.data.currentReferencesAsideId=void 0,X.data.wasReferencesAsideClosed=!0,this.setOpenOverlay(!1)},setAsideMobile(e){X.data.isAsideMobile=e},openFlyout(){X.data.flyoutIsOpen=!0},closeFlyout(){X.data.flyoutIsOpen=!1},openConversationFeedback(){X.data.conversationFeedbackIsOpen=!0,this.setOpenOverlay(!0)},openMessageFeedback(e){X.data.conversationFeedbackId=e},closeFeedback(){X.data.conversationFeedbackIsOpen=!1,X.data.conversationFeedbackId=void 0,this.setOpenOverlay(!1)},setOpenOverlay(e){X.data.hasOpenedOverlays=e},setAriaLiveStatusMessage(e){X.data.ariaLiveStatusMessage=e,clearTimeout(X.data.ariaLiveStatusMessageClearingTimeout),X.data.ariaLiveStatusMessageClearingTimeout=setTimeout(()=>{X.data.ariaLiveStatusMessage=``},X.ariaLiveMessagesClearingTimeoutDuration)},closePopup(){window.location.hash=``},checkForOpenedPopup(){let e=window.location.hash.slice(1),t=X.t.popups?.find(t=>t.hash===e);t?X.data.openedPopup=t:X.data.openedPopup=void 0},async thumbs(e,t){try{let n=X.data.history.find(t=>t.type===`bot`&&t.id===e);t===`up`?await Z.thumbsUp(e,n?.question??``):await Z.thumbsDown(e,n?.question??``),this.showSuccessToast(`thankYouForFeedback`)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},async onLanguageChange(e){if(X.data.language=fe(e,X.data.chatConfig.supportedLanguages),A(X.data.language,X.targets.mainElement),X.data.predefinedQuestions=await this.getPredefinedQuestions(X.data.language),this.setAriaLiveStatusMessage(X.t.ariaLanguageChanged),X.data.chatConfig.reflectLanguageInPath){let e=new URL(window.location.href);e.pathname=`/${X.data.language}`,window.history.replaceState({},``,e.toString())}},async acceptTerms(){X.data.termsAccepted=!0;try{k.setItem(`liipgpt:termsAccepted`,`true`)}catch(e){console.warn(`Failed to save terms acceptance to storage:`,e)}this.closePopup(),await E(),this.goto(J(X.data.chatConfig.forceConsent??!1,!0,X.data.chatConfig.forceChatPage??!1,ot(X.data.props.autofirePredefinedQuestionId,X.data.predefinedQuestions)))},updateChatInput(e){X.data.chatInputValue=e}});function $(e,t){c(t,!0);let n=w(t,`href`,7),r=w(t,`target`,7),i=w(t,`onclick`,7),d=w(t,`className`,23,()=>[]),f=w(t,`isStandalone`,7,!1),p=w(t,`children`,7),m=w(t,`type`,7,`button`),_=w(t,`use`,7),v=w(t,`class`,7),b=re(t,[`$$slots`,`$$events`,`$$legacy`,`$$host`,`href`,`target`,`onclick`,`className`,`isStandalone`,`children`,`type`,`use`,`class`]),x=u(()=>n()?`a`:`button`),C=u(()=>[...Array.isArray(d())?d():d()?[d()]:[],...v()?[v()]:[]]),T=()=>({}),E=u(()=>_()??T);var D={get href(){return n()},set href(e){n(e),S()},get target(){return r()},set target(e){r(e),S()},get onclick(){return i()},set onclick(e){i(e),S()},get className(){return d()},set className(e=[]){d(e),S()},get isStandalone(){return f()},set isStandalone(e=!1){f(e),S()},get children(){return p()},set children(e){p(e),S()},get type(){return m()},set type(e=`button`){m(e),S()},get use(){return _()},set use(e){_(e),S()},get class(){return v()},set class(e){v(e),S()}},O=s();return ee(g(O),()=>h(x),!1,(e,t)=>{l(e,e=>h(E)?.(e)),y(e,()=>({...b,onclick:n()?void 0:i(),type:n()?void 0:m(),href:n(),role:n()?`link`:`button`,target:n()?r():void 0,class:h(C),[te]:{"open-button--standalone":f()}}));var o=s();a(g(o),p),ne(t,o)}),ne(e,O),o(D)}x($,{href:{},target:{},onclick:{},className:{},isStandalone:{},children:{},type:{},use:{},class:{}},[],[],{mode:`open`});export{H as a,R as c,ve as d,j as f,Ze as i,L as l,X as n,V as o,ct as r,Ie as s,$ as t,je as u};
1
+ import{r as e,t}from"./CibALFW0.js";import{At as n,Et as r,Ft as i,I as a,It as o,J as s,Lt as c,O as l,Ot as u,Pt as d,Rt as f,St as p,Vt as m,at as h,bt as g,ct as _,dt as v,g as y,ht as b,i as x,j as ee,jt as S,m as te,mt as C,o as w,q as ne,rt as T,s as re,st as E,wt as D}from"./C00ruT0L.js";import{t as O}from"./DjVmpym-.js";import{i as ie,n as ae,r as oe,t as se}from"./DFBUyDYh.js";import{d as ce,l as k,o as le,p as ue,u as de}from"./BpIo1_hS.js";import{i as A,n as fe,t as pe}from"./CX0dfddQ.js";var me={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function he(e,t,n){e||={};let r=e.random??e.rng?.()??de();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return ce(r)}function j(e,t,n){return me.randomUUID&&!t&&!e?me.randomUUID():he(e,t,n)}var ge={de:{aborted:`Verbindung zum Server wurde unerwartet unterbrochen. Bitte versuchen Sie es erneut.`,"client-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,"server-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,"sse-error":`Ein unbekannter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.`,blocked:`Ihre Anfrage wurde blockiert.`,"pii-detected":`Es wurden persönliche Daten erkannt. Bitte entfernen Sie diese und versuchen Sie es erneut.`,"incomplete-error":`Ein unbekannter Fehler ist aufgetreten. Die Antwort könnte unvollständig sein.`,"unexpected-call":`Ein unbekannter Fehler ist aufgetreten. Die Antwort könnte unvollständig sein.`,"quota-reached":`Kontingent überschritten. Bitte versuchen Sie es später erneut.`,"rate-limit":`Kontingent überschritten. Bitte versuchen Sie es später erneut.`,maintenance:`Der Chat ist derzeit nicht verfügbar. Bitte versuchen Sie es später erneut.`,"too-long":`Ihre Frage war zu lang, versuchen Sie es mit einer Kürzeren.`,"too-short":`Ihre Frage war zu kurz, versuchen Sie es mit einer Längeren.`,"feedback-failed":`Feedback senden fehlgeschlagen. Bitte versuchen Sie es erneut.`,"speech-not-supported":`Spracherkennung wird nicht unterstützt.`,"speech-transcription-failed":`Sprachtranskription fehlgeschlagen.`,"speech-no-text-detected":`Kein Text in der Spracheingabe erkannt.`,"speech-microphone-access-denied":`Mikrofonzugriff verweigert.`},en:{aborted:`Connection to the server was unexpectedly interrupted. Please try again.`,"client-error":`An unknown error has occurred. Please try again.`,"server-error":`An unknown error has occurred. Please try again.`,"sse-error":`An unknown error has occurred. Please try again.`,blocked:`Your request has been blocked.`,"pii-detected":`Personal data has been detected. Please remove it and try again.`,"incomplete-error":`An unknown error has occurred. The response might be incomplete.`,"unexpected-call":`An unknown error has occurred. The response might be incomplete.`,"quota-reached":`Quota exceeded. Please try again later.`,"rate-limit":`Quota exceeded. Please try again later.`,maintenance:`The chat is currently unavailable. Please try again later.`,"too-long":`Your question was too long, try a shorter one.`,"too-short":`Your question was too short, try a longer one.`,"feedback-failed":`Failed to send feedback. Please try again.`,"speech-not-supported":`Speech recognition is not supported.`,"speech-transcription-failed":`Speech transcription failed.`,"speech-no-text-detected":`No text detected in speech input.`,"speech-microphone-access-denied":`Microphone access denied.`},it:{aborted:`La connessione al server è stata interrotta inaspettatamente. Si prega di riprovare.`,"client-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,"server-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,"sse-error":`Si è verificato un errore sconosciuto. Si prega di riprovare.`,blocked:`La tua richiesta è stata bloccata.`,"pii-detected":`Sono stati rilevati dati personali. Si prega di rimuoverli e riprovare.`,"incomplete-error":`Si è verificato un errore sconosciuto. La risposta potrebbe essere incompleta.`,"unexpected-call":`Si è verificato un errore sconosciuto. La risposta potrebbe essere incompleta.`,"quota-reached":`Quota superata. Si prega di riprovare più tardi.`,"rate-limit":`Quota superata. Si prega di riprovare più tardi.`,maintenance:`La chat non è attualmente disponibile. Si prega di riprovare più tardi.`,"too-long":`La tua domanda era troppo lunga, prova con una più breve.`,"too-short":`La tua domanda era troppo breve, prova con una più lunga.`,"feedback-failed":`Invio del feedback non riuscito. Si prega di riprovare.`,"speech-not-supported":`Il riconoscimento vocale non è supportato.`,"speech-transcription-failed":`Trascrizione vocale fallita.`,"speech-no-text-detected":`Nessun testo rilevato nell'input vocale.`,"speech-microphone-access-denied":`Accesso al microfono negato.`},fr:{aborted:`La connexion au serveur a été interrompue de façon inattendue. Veuillez réessayer.`,"client-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"server-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"sse-error":`Une erreur inconnue s'est produite. Veuillez réessayer.`,"pii-detected":`Des données personnelles ont été détectées. Veuillez les supprimer et réessayer.`,blocked:`Votre demande a été bloquée.`,"incomplete-error":`Une erreur inconnue s'est produite. La réponse pourrait être incomplète.`,"unexpected-call":`Une erreur inconnue s'est produite. La réponse pourrait être incomplète.`,"quota-reached":`Quota dépassé. Veuillez réessayer plus tard.`,"rate-limit":`Quota dépassé. Veuillez réessayer plus tard.`,maintenance:`Le chat est actuellement indisponible. Veuillez réessayer plus tard.`,"too-long":`Votre question était trop longue, essayez d'en poser une plus courte.`,"too-short":`Votre question était trop courte, essayez d'en poser une plus longue.`,"feedback-failed":`Échec de l'envoi du feedback. Veuillez réessayer.`,"speech-not-supported":`La reconnaissance vocale n'est pas prise en charge.`,"speech-transcription-failed":`Échec de la transcription vocale.`,"speech-no-text-detected":`Aucun texte détecté dans l'entrée vocale.`,"speech-microphone-access-denied":`Accès au microphone refusé.`}},M={de:{email:`Bitte keine E-Mail Adressen eingeben`,creditCard:`Bitte keine Kreditkarteninformationen eingeben`,ahv:`Bitte keine AHV-Nummern eingeben`,phoneSwiss:`Bitte keine Telefonnummern eingeben`,phoneInternational:`Bitte keine Telefonnummern eingeben`,swissPassport:`Bitte keine Passinformationen eingeben`,longNumber:`Bitte keine langen Nummern eingeben`},en:{email:`Please do not enter email addresses`,creditCard:`Please do not enter credit card information`,ahv:`Please do not enter AHV numbers`,phoneSwiss:`Please do not enter phone numbers`,phoneInternational:`Please do not enter phone numbers`,swissPassport:`Please do not enter passport information`,longNumber:`Please do not enter long numbers`},it:{email:`Si prega di non inserire indirizzi email`,creditCard:`Si prega di non inserire informazioni sulla carta di credito`,ahv:`Si prega di non inserire numeri AVS`,phoneSwiss:`Si prega di non inserire numeri di telefono`,phoneInternational:`Si prega di non inserire numeri di telefono`,swissPassport:`Si prega di non inserire informazioni sul passaporto`,longNumber:`Si prega di non inserire numeri lunghi`},fr:{email:`Veuillez ne pas saisir d'adresses e-mail`,creditCard:`Veuillez ne pas saisir d'informations de carte de crédit`,ahv:`Veuillez ne pas saisir de numéros AVS`,phoneSwiss:`Veuillez ne pas saisir de numéros de téléphone`,phoneInternational:`Veuillez ne pas saisir de numéros de téléphone`,swissPassport:`Veuillez ne pas saisir d'informations de passeport`,longNumber:`Veuillez ne pas saisir de longs numéros`}},_e=t(((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 ve(...e){return e.filter(Boolean).join(` `)}var ye=typeof document<`u`,be=typeof window<`u`?window:void 0;typeof window<`u`&&window.document,typeof window<`u`&&window.navigator,typeof window<`u`&&window.location;function xe(e){let t=e.activeElement;for(;t?.shadowRoot;){let e=t.shadowRoot.activeElement;if(e===t)break;t=e}return t}new class{#e;#t;constructor(e={}){let{window:t=be,document:r=t?.document}=e;t!==void 0&&(this.#e=r,this.#t=n(e=>{let n=T(t,`focusin`,e),r=T(t,`focusout`,e);return()=>{n(),r()}}))}get current(){return this.#t?.(),this.#e?xe(this.#e):null}};var N=class{#e;#t;constructor(e){this.#e=e,this.#t=Symbol(e)}get key(){return this.#t}exists(){return i(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 f(this.#t,e)}};function Se(e,t){switch(e){case`post`:C(t);break;case`pre`:b(t);break}}function P(e,t,n,r={}){let{lazy:i=!1}=r,a=!i,o=Array.isArray(e)?[]:void 0;Se(t,()=>{let t=Array.isArray(e)?e.map(e=>e()):e();if(!a){a=!0,o=t;return}let r=_(()=>n(t,o));return o=t,r})}function F(e,t,n){let r=v(()=>{let i=!1;P(e,t,(e,t)=>{if(i){r();return}let a=n(e,t);return i=!0,a},{lazy:!0})});C(()=>r)}function I(e,t,n){P(e,`post`,t,n)}function Ce(e,t,n){P(e,`pre`,t,n)}I.pre=Ce;function we(e,t){F(e,`post`,t)}function Te(e,t){F(e,`pre`,t)}we.pre=Te;function Ee(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 De(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 Oe(e,t,n={},i){let{lazy:a=!1,once:o=!1,initialValue:s,debounce:c,throttle:l}=n,u=r(p(s)),d=r(!1),f=r(void 0),m=r(p([])),g=()=>{h(m).forEach(e=>e()),D(m,[],!0)},_=e=>{D(m,[...h(m),e],!0)},v=async(e,n,r=!1)=>{try{D(d,!0),D(f,void 0),g();let i=new AbortController;_(()=>i.abort());let a=await t(e,n,{data:h(u),refetching:r,onCleanup:_,signal:i.signal});return D(u,a,!0),a}catch(e){e instanceof DOMException&&e.name===`AbortError`||D(f,e,!0);return}finally{D(d,!1)}},y=c?Ee(v,c):l?De(v,l):v,b=Array.isArray(e)?e:[e],x;return i((t,n)=>{o&&x||(x=t,y(Array.isArray(e)?t:t[0],Array.isArray(e)?n:n?.[0]))},{lazy:a}),{get current(){return h(u)},get loading(){return h(d)},get error(){return h(f)},mutate:e=>{D(u,e,!0)},refetch:t=>{let n=b.map(e=>e());return y(Array.isArray(e)?n:n[0],Array.isArray(e)?n:n[0],t??!0)}}}function ke(e,t,n){return Oe(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];I(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}function Ae(e,t,n){return Oe(e,t,n,(t,n)=>{let r=Array.isArray(e)?e:[e];I.pre(()=>r.map(e=>e()),(e,n)=>{t(e,n??[])},n)})}ke.pre=Ae,new N(`richColorsContext`);var je=new N(`<Toaster/>`),Me=0,Ne=class{#e=r(p([]));get toasts(){return h(this.#e)}set toasts(e){D(this.#e,e,!0)}#t=r(p([]));get heights(){return h(this.#t)}set heights(e){D(this.#t,e,!0)}#n=e=>{let t=this.toasts.findIndex(t=>t.id===e);return t===-1?null:t};addToast=e=>{ye&&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,updated:!0}};create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id&&e.id?.length>0?e.id:Me++,i=e.dismissible===void 0?e.dismissable===void 0?!0:e.dismissable:e.dismissible,a=e.type===void 0?`default`:e.type;return _(()=>{this.toasts.find(e=>e.id===r)?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=>(_(()=>{if(e===void 0){this.toasts=this.toasts.map(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.#n(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=Pe(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=t?.id||Me++;return this.create({component:e,id:n,...t}),n};removeHeight=e=>{this.heights=this.heights.filter(t=>t.toastId!==e)};setHeight=e=>{let t=this.#n(e.toastId);if(t===null){this.heights.push(e);return}this.heights[t]=e};reset=()=>{this.toasts=[],this.heights=[]}};function Pe(e){return e&&typeof e==`object`&&`status`in e?`HTTP error! Status: ${e.status}`:`Error! ${e}`}var L=new Ne;function Fe(e,t){return L.create({message:e,...t})}var Ie=class{#e=u(()=>L.toasts.filter(e=>!e.dismiss));get toasts(){return h(this.#e)}},R=Object.assign(Fe,{success:L.success,info:L.info,warning:L.warning,error:L.error,custom:L.custom,message:L.message,promise:L.promise,dismiss:L.dismiss,loading:L.loading,getActiveToasts:()=>L.toasts.filter(e=>!e.dismiss)}),Le=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)},Re=(e,t)=>{let n={};return t.forEach(t=>{n[t]=e[t]}),n},ze=console.warn,Be=()=>{},Ve=(e,t)=>_(()=>{console.warn=Be;let n=m(t?Re(e,t):e);return console.warn=ze,n}),He=e=>e&&typeof e.then==`function`,Ue=class{config;self;devtools;stateKeys;constructor(e,t){this.config=e,this.self=t,typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&(this.stateKeys=Le(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 Ve(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 _(()=>t.call(this.self,...r));let i=Ve(r);this.sendStart(e,i);try{let n=_(()=>t.call(this.self,...r));return He(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}},We=(e,t)=>{let n={},r=new Ue(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 Ge(){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 z(){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 B(){return typeof window>`u`?!1:!!(window.MediaRecorder&&z())}function Ke(){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 V(){return typeof window>`u`?!1:!!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||Ke())}var H=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(!B()||!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=z();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 B()}static getSupportedMediaType(){return z()}},qe=ue(),Je=(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`)))},Ye=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&&Je(e,n)}),qe.sanitize(t.outerHTML,{FORBID_TAGS:[`style`,`script`],FORBID_ATTR:[`style`,`class`]})},Xe=e=>{if(!e?.length)return[];let t=e.join(`,`),n=document.querySelectorAll(t);return Array.from(n,Ye)},U=`liipgpt:context`,Ze=class{contextVersion=0;#e=r();get currentContext(){return h(this.#e)}set currentContext(e){D(this.#e,e,!0)}getFromLocalStorage(){let e=localStorage.getItem(U);if(e){let t;try{if(t=JSON.parse(e),t.version!==this.contextVersion){localStorage.removeItem(U);return}else return t.context}catch(e){console.error(`Failed to parse liipgpt:context`,e);return}}}storeToLocalStorage(){localStorage.setItem(`liipgpt:context`,JSON.stringify({version:X.data.chatConfig.contextVersion,context:this.currentContext}))}constructor(e){this.init=e,this.currentContext=this.getFromLocalStorage()??e.initialValue}getContext(){return m(this.currentContext)}setContextVersion(e){this.contextVersion=e}setContext(e){this.currentContext=e,this.storeToLocalStorage()}resetContext(){this.currentContext=this.init.initialValue,this.storeToLocalStorage()}updateContext(e){this.setContext(e(this.currentContext))}},Qe=()=>localStorage.getItem(U),$e=[{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\.\d{4}\.\d{4}\.\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)}],W=e=>{for(let t of $e)if(t.check(e))return t.type},G=`liipgpt:selectorValues`,K=`liipgpt:selectorKnownDefaults`,q=()=>{try{let e=k.getItem(G),t=k.getItem(K);return e?{values:JSON.parse(e),knownDefaults:t?JSON.parse(t):{}}:null}catch{return null}},et=e=>{let t={};for(let n of e)t[n.settingName]=n.defaultValues??(n.allowEmpty?[]:[n.values[0]]).filter(Boolean);return t},tt=(e,t)=>{try{let n=et(t);k.setItem(G,JSON.stringify(e)),k.setItem(K,JSON.stringify(n))}catch(e){console.error(`Failed to save selector values:`,e)}},nt=e=>{try{let t=q();if(!t)return;delete t.values[e],delete t.knownDefaults[e],k.setItem(G,JSON.stringify(t.values)),k.setItem(K,JSON.stringify(t.knownDefaults))}catch(e){console.error(`Failed to clear selector saved state:`,e)}},rt=e=>{let t=q(),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)},it=class extends Error{constructor(e){super(e),this.name=`UnreachableError`}},at=e(_e(),1),ot=(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},J=(e,t,n,r)=>{if(e&&!t)return{name:`consent-page`};let i=new URLSearchParams(window.location.search),a=i.get(`q`),o=i.get(`id`)??void 0,s=i.get(`sid`)??void 0;return a?{name:`chat-page`,query:a,predefinedQuestionId:o,switchQuestionId:s}:r?{name:`chat-page`,query:r.question,predefinedQuestionId:r.id}:n?{name:`chat-page`}:{name:`start-page`}},st=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}},Y=e=>e?e.map(e=>({id:j(),...e})):[],X=new class{#e=r(p({}));get data(){return h(this.#e)}set data(e){D(this.#e,e,!0)}#t=r(p({}));get targets(){return h(this.#t)}set targets(e){D(this.#t,e,!0)}#n=r(!1);get initialized(){return h(this.#n)}set initialized(e){D(this.#n,e,!0)}#r=r(0);get currentAudioVolume(){return h(this.#r)}set currentAudioVolume(e){D(this.#r,e,!0)}ariaLiveMessagesClearingTimeoutDuration=350;#i=r(null);get currentAudioRecorder(){return h(this.#i)}set currentAudioRecorder(e){D(this.#i,e,!0)}#a=r(!1);get isTranscribing(){return h(this.#a)}set isTranscribing(e){D(this.#a,e,!0)}#o=u(()=>{if(!this.initialized)return[];let e=this.data.chatConfig.menu;return e?e[this.data.language]??[]:[]});get menu(){return h(this.#o)}set menu(e){D(this.#o,e)}#s=u(()=>this.initialized?this.data.chatConfig.translations[this.data.language]??{}:{});get t(){return h(this.#s)}set t(e){D(this.#s,e)}#c=u(()=>this.initialized?ge[this.data.language]??{}:ge.en??{});get errorTranslations(){return h(this.#c)}set errorTranslations(e){D(this.#c,e)}#l=u(()=>this.initialized?M[this.data.language]??{}:M.en??{});get piiTranslations(){return h(this.#l)}set piiTranslations(e){D(this.#l,e)}#u=u(()=>this.initialized?this.data.currentColorScheme:`light`);get colorScheme(){return h(this.#u)}set colorScheme(e){D(this.#u,e)}#d=u(()=>this.initialized?this.data.chatConfig.fullTheme[this.data.currentColorScheme]:{});get themeBase(){return h(this.#d)}set themeBase(e){D(this.#d,e)}#f=u(()=>this.themeBase.tokens);get theme(){return h(this.#f)}set theme(e){D(this.#f,e)}#p=u(()=>{if(!this.initialized)return[];let e=[];for(let t of this.data.chatConfig.selectorsConfig)t.allowEmpty||(this.data.selectorValues[t.settingName]||[]).length===0&&e.push(t.settingName);return e});get selectorsWithErrors(){return h(this.#p)}set selectorsWithErrors(e){D(this.#p,e)}},Z,Q,ct,lt=We({name:`chat-logic`,state:X,excludeInDevTools:[`onInput`]},{async init(e){Q=e;let t=Q.speechRecognitionApiKey||void 0;Z=new le({apiUrl:Q.apiUrl,apiKey:Q.apiKey,speechRecognitionApiKey:t,strict:!0,startParameters:st(Q.additionalStartParameters)});try{let e=await Z.getChatConfig();window.CHAT_CONFIG_OVERRIDE&&Object.assign(e,window.CHAT_CONFIG_OVERRIDE);let t=(await Z.getMetadata()).mode===`maintenance`;t&&this.showErrorToast(`maintenance`);let n=ie(e);Q.inlineLayout!==void 0&&(n.inlineLayout=Q.inlineLayout),Q.forceChatPage!==void 0&&(n.forceChatPage=Q.forceChatPage);let r;r=Q.lang?fe(Q.lang,n.supportedLanguages):pe(n.supportedLanguages),A(r,X.targets.mainElement);let i=await this.getPredefinedQuestions(r),a=n.translations[r]?.ariaOpensInNewTab;a&&Z.setNewTabSrText(a);let o=[];if(n.renderKatex){let e=await O(()=>import(`https://esm.sh/marked-katex-extension@5.1.5`),[],import.meta.url).catch(e=>{console.error(`Couldn't load marked-katex-extension:`,e)});e&&(Z.setMarkedExtensions(e.default({nonStandard:!0,output:`mathml`})),o.push(`https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css`))}let s=Object.keys(n.fullTheme),c=!1;if(n.forceConsent)try{c=k.getItem(`liipgpt:termsAccepted`)===`true`}catch(e){console.warn(`Failed to load terms acceptance from storage:`,e)}let l=ot(Q.autofirePredefinedQuestionId,i);X.data={currentConversationState:`idle`,chatConfig:n,language:r,predefinedQuestions:i,isInMaintenance:t,history:Y(n.messageAdditions.init),selectedColorScheme:ae(),has2ColorSchemes:s.length===2,currentColorScheme:se(s),conversationFeedbackId:void 0,conversationFeedbackIsOpen:!1,openedPopup:void 0,props:Q,flyoutIsOpen:!1,questionHasPii:void 0,chatInputValue:``,selectorValues:rt(n.selectorsConfig),selectorsIsOpen:!1,predefinedQuestionId:void 0,switchQuestionId:void 0,currentReferencesAsideId:void 0,ariaLiveStatusMessage:void 0,ariaLiveStatusMessageClearingTimeout:void 0,wasReferencesAsideClosed:!1,isAsideMobile:!0,route:J(n.forceConsent??!1,c,n.forceChatPage??!1,l),additionalStylesheets:o,hasOpenedOverlays:!1,isInlineLayoutContained:!1,termsAccepted:c,selectedTopic:void 0},window.LIIPGPT_LISTENERS?.route?.(X.data.route),window.LIIPGPT_LISTENERS?.conversation?.(X.data.currentConversationState),X.data.selectorsIsOpen=X.data.chatConfig.showExpandedSelectors??!1,X.initialized=!0,this.checkForOpenedPopup(),window.addEventListener(`hashchange`,()=>{this.checkForOpenedPopup()}),this.goto(J(n.forceConsent??!1,c,n.forceChatPage??!1,l),!0)}catch(e){throw R.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){X.targets[e]=t},goto(e,t=!1){if(!(!t&&(0,at.default)(X.data.route,e)))switch(X.data.route=e,window.LIIPGPT_LISTENERS?.route?.(e),e.name){case`consent-page`:break;case`start-page`:e.prefill&&(X.data.chatInputValue=e.prefill);break;case`chat-page`:if(X.data.chatInputValue=e.query??``,X.data.predefinedQuestionId=e.predefinedQuestionId,X.data.switchQuestionId=e.switchQuestionId,e.query&&(this.onSubmit(),X.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()}`)}break}},getSelectorConfig(e){let t=X.data.chatConfig.selectorsConfig.find(t=>t.settingName===e);if(!t)throw Error(`Setting ${e} not found`);return t},getPrettifiedSelectorValues(){let e=Object.entries(X.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}X.data.selectorValues[e]=t,tt(X.data.selectorValues,X.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 nt(e),X.data.selectorValues[e]=n,tt(X.data.selectorValues,X.data.chatConfig.selectorsConfig),n},async getPredefinedQuestions(e){try{return Z.getPredefinedQuestions({url:window.location.origin+window.location.pathname,language:e})}catch(e){return console.warn(`Failed to load predefined questions:`,e),[]}},setColorScheme(e){X.data.selectedColorScheme=e,X.data.currentColorScheme=oe(e),this.setAriaLiveStatusMessage(e===`dark`?X.t.ariaDarkSelected:X.t.ariaLightSelected)},async abort(){await ct?.abort()},changeConversationState(e){X.data.currentConversationState=e,window.LIIPGPT_LISTENERS?.conversation?.(e)},onInput(e){X.data.chatConfig.blockPII&&(X.data.questionHasPii=W(e)),X.data.chatInputValue=e,X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0},onSubmit(e=!1,t,n=!1){let r=Xe(X.data.chatConfig.parentPageContext?.extractSelectors);if(X.data.questionHasPii){console.warn(`Question contains PII, not submitting:`,X.data.questionHasPii);return}let i=X.data.chatConfig.questionPrefix?`${X.data.chatConfig.questionPrefix} ${X.data.chatInputValue}`:X.data.chatInputValue;n||(X.data.history.push(...Y(X.data.chatConfig.messageAdditions.user.before)),X.data.history.push({type:`user`,time:new Date().toISOString(),message:X.data.chatInputValue}),X.data.history.push(...Y(X.data.chatConfig.messageAdditions.user.after)));let a=X.data.history.push(...Y(X.data.chatConfig.messageAdditions.bot.before));X.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={features:Q.features?Q.features.trim().split(`,`):[`formatting`],onError:e=>{this.showErrorToast(e),window.LIIPGPT_LISTENERS?.error?.(e),(e===`pii-detected`||e===`blocked`)&&this.editLatestQuestion()},onMessage:e=>{e.type===`topic-selected`&&(X.data.selectedTopic={label:e.label,placeholder:e.placeholder})},lang:X.data.language,selectorValues:{...this.getPrettifiedSelectorValues(),context:Qe(),...t},predefinedQuestionId:X.data.predefinedQuestionId,switchQuestionId:X.data.switchQuestionId,onEmbed:e=>{let t=X.data.history[a];t&&t.type===`bot`&&!t.message.markdown?(X.data.history[a]={...e,id:t.id??j()},o=!0):X.data.history.push({...e,id:j()})}};X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0,r.length&&(s.selectorValues.parentPageContextHtml=r);let c=(e,t)=>{try{let n=new URL(e),r=new URL(t);return n.origin===r.origin&&n.pathname===r.pathname}catch{return!1}},l=X.data.chatConfig.sendReferrer??`all`;if([`all`,`own`,`location`].includes(l)){let e=l===`location`||X.data.props.flyout,t;t=e?`${window.location.protocol}//${window.location.host}${window.location.pathname}`:c(document.referrer,window.location.href)?null:document.referrer;let n=l===`own`&&!X.data.props.flyout&&t&&!t.startsWith(window.location.origin);s.referrer=t&&!n?t:void 0}X.data.currentConversationId||(X.data.currentConversationId=Z.createConversationId());let u=Z.chat(X.data.currentConversationId,i,s);ct=u,X.data.lastChatResponseId=u.id,X.data.currentConversationState!==`searching`&&this.changeConversationState(`searching`),this.setAriaLiveStatusMessage(X.t.ariaQuestionSent);let d=!1,f,p=!!X.data.currentReferencesAsideId;(e&&p||!e&&X.data.chatConfig.showReferencesByDefault)&&(X.data.isAsideMobile||this.openReferencesAside(u.id)),u.subscribe(e=>{if(!o&&X.data.history[a]&&(X.data.history[a]={question:X.data.chatInputValue,...e}),X.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()}`))}X.data.chatConfig.showReferencesByDefault&&!X.data.wasReferencesAsideClosed&&X.data.currentReferencesAsideId!==e.id&&!X.data.isAsideMobile&&this.openReferencesAside(e.id),e.state===`streaming`&&X.data.currentConversationState!==`answering`&&this.changeConversationState(`answering`),e.state===`done`&&(this.changeConversationState(`idle`),d||(d=!0,this.setAriaLiveStatusMessage(`${X.t.ariaAnswerReady} ... ${e.message.text} ... ${X.t.ariaAnswerFinished}`),X.data.history.push(...Y(X.data.chatConfig.messageAdditions.bot.after))),X.data.currentReferencesAsideId&&e.references.used.length>0?(clearTimeout(f),f=setTimeout(()=>{this.openReferencesAside(e.id)},100)):this.closeReferencesAside())}),X.data.chatInputValue=``},async onStartSpeechRecognition(){try{if(!await Ge()){this.showErrorToast(`speech-not-supported`);return}if(await navigator.mediaDevices.getUserMedia({audio:!0}),H.isSupported())X.data.chatInputValue=``,X.currentAudioRecorder=new H({onDataAvailable:async e=>{X.isTranscribing=!0,await this.handleTranscription(e)},onError:()=>{this.showErrorToast(`speech-microphone-access-denied`),X.currentAudioRecorder=null,X.isTranscribing=!1},onVolumeChange:e=>{X.currentAudioVolume=e}}),X.currentAudioRecorder.start();else{this.showErrorToast(`speech-not-supported`);return}}catch(e){throw this.showErrorToast(`speech-microphone-access-denied`),X.currentAudioRecorder=null,X.isTranscribing=!1,e}},editLatestQuestion(){let e=X.data.history.findLastIndex(e=>e?.type===`user`);if(e===-1){console.error(`No last user question, available`);return}let t=X.data.history.splice(e)[0];X.data.chatInputValue=t.message},onStopSpeechRecognition(){if(X.currentAudioRecorder){let e=X.currentAudioRecorder;X.currentAudioRecorder=null,e.stop()}X.currentAudioVolume=0},async handleTranscription(e){if(!e){console.warn(`No audio data received`);return}try{let t=await Z.transcribeAudio(e,{lang:X.data.language});if(t.error){this.showErrorToast(`speech-transcription-failed`);return}if(t.transcript.trim()){if(X.data.chatConfig.blockPII&&(X.data.questionHasPii=W(t.transcript.trim()),X.data.questionHasPii))return;X.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{X.currentAudioRecorder=null,X.isTranscribing=!1,X.currentAudioVolume=0}},async onStartConversation(e,t,n){await this.abort(),X.data.history=Y(X.data.chatConfig.messageAdditions.init),X.data.currentConversationId=Z.createConversationId(),this.goto({name:`chat-page`,query:e,predefinedQuestionId:t,switchQuestionId:n})},async onNewConversation(){await this.abort();let e=X.data.currentConversationId;if(X.data.currentConversationId=void 0,X.data.currentReferencesAsideId=void 0,X.data.history=Y(X.data.chatConfig.messageAdditions.init),X.data.predefinedQuestionId=void 0,X.data.switchQuestionId=void 0,X.data.selectedTopic=void 0,X.data.chatConfig.addQueryToUrlParams){let e=new URLSearchParams(window.location.search);e.delete(`q`),e.delete(`id`),e.delete(`sid`),history.pushState(null,``,`?${e.toString()}`)}this.goto({name:`start-page`}),e&&Z.userAction(`newDiscussion`,{conversationId:e,lang:X.data.language}).catch(e=>{console.error(`Failed to notify backend of new discussion:`,e)})},async onChangeTopic(){let e=X.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(),X.data.selectedTopic=void 0,X.data.predefinedQuestionId=e,X.data.switchQuestionId=void 0,X.data.chatInputValue=``,this.onSubmit(!0,void 0,!0),V()||E().then(()=>X.targets.chatInput?.focus())},showSuccessToast(e){R.success(X.t[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},showErrorToast(e){R.error(X.errorTranslations[e],{unstyled:!0,duration:3e3,classes:{toast:`toast`}})},async submitFeedback(e){try{let t=X.data.conversationFeedbackId||X.data.lastChatResponseId;if(!t)throw new it(`Tried to give feedback with no id.`);let n=X.data.history.find(e=>e.type===`bot`&&e.id===t);await Z.feedback(t,n?.question??``,e),setTimeout(()=>{this.showSuccessToast(`thankYouForFeedback`)},500)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},toggleReferencesAside(e){X.data.currentReferencesAsideId===e?this.closeReferencesAside():this.openReferencesAside(e)},openReferencesAside(e){X.data.currentReferencesAsideId=e,this.setOpenOverlay(!0)},closeReferencesAside(){X.data.currentReferencesAsideId=void 0,X.data.wasReferencesAsideClosed=!0,this.setOpenOverlay(!1)},setAsideMobile(e){X.data.isAsideMobile=e},openFlyout(){X.data.flyoutIsOpen=!0},closeFlyout(){X.data.flyoutIsOpen=!1},openConversationFeedback(){X.data.conversationFeedbackIsOpen=!0,this.setOpenOverlay(!0)},openMessageFeedback(e){X.data.conversationFeedbackId=e},closeFeedback(){X.data.conversationFeedbackIsOpen=!1,X.data.conversationFeedbackId=void 0,this.setOpenOverlay(!1)},setOpenOverlay(e){X.data.hasOpenedOverlays=e},setAriaLiveStatusMessage(e){X.data.ariaLiveStatusMessage=e,clearTimeout(X.data.ariaLiveStatusMessageClearingTimeout),X.data.ariaLiveStatusMessageClearingTimeout=setTimeout(()=>{X.data.ariaLiveStatusMessage=``},X.ariaLiveMessagesClearingTimeoutDuration)},closePopup(){window.location.hash=``},checkForOpenedPopup(){let e=window.location.hash.slice(1),t=X.t.popups?.find(t=>t.hash===e);t?X.data.openedPopup=t:X.data.openedPopup=void 0},async thumbs(e,t){try{let n=X.data.history.find(t=>t.type===`bot`&&t.id===e);t===`up`?await Z.thumbsUp(e,n?.question??``):await Z.thumbsDown(e,n?.question??``),this.showSuccessToast(`thankYouForFeedback`)}catch(e){console.error(`Feedback failed:`,e),this.showErrorToast(`feedback-failed`)}},async onLanguageChange(e){if(X.data.language=fe(e,X.data.chatConfig.supportedLanguages),A(X.data.language,X.targets.mainElement),X.data.predefinedQuestions=await this.getPredefinedQuestions(X.data.language),this.setAriaLiveStatusMessage(X.t.ariaLanguageChanged),X.data.chatConfig.reflectLanguageInPath){let e=new URL(window.location.href);e.pathname=`/${X.data.language}`,window.history.replaceState({},``,e.toString())}},async acceptTerms(){X.data.termsAccepted=!0;try{k.setItem(`liipgpt:termsAccepted`,`true`)}catch(e){console.warn(`Failed to save terms acceptance to storage:`,e)}this.closePopup(),await E(),this.goto(J(X.data.chatConfig.forceConsent??!1,!0,X.data.chatConfig.forceChatPage??!1,ot(X.data.props.autofirePredefinedQuestionId,X.data.predefinedQuestions)))},updateChatInput(e){X.data.chatInputValue=e}});function $(e,t){c(t,!0);let n=w(t,`href`,7),r=w(t,`target`,7),i=w(t,`onclick`,7),d=w(t,`className`,23,()=>[]),f=w(t,`isStandalone`,7,!1),p=w(t,`children`,7),m=w(t,`type`,7,`button`),_=w(t,`use`,7),v=w(t,`class`,7),b=re(t,[`$$slots`,`$$events`,`$$legacy`,`$$host`,`href`,`target`,`onclick`,`className`,`isStandalone`,`children`,`type`,`use`,`class`]),x=u(()=>n()?`a`:`button`),C=u(()=>[...Array.isArray(d())?d():d()?[d()]:[],...v()?[v()]:[]]),T=()=>({}),E=u(()=>_()??T);var D={get href(){return n()},set href(e){n(e),S()},get target(){return r()},set target(e){r(e),S()},get onclick(){return i()},set onclick(e){i(e),S()},get className(){return d()},set className(e=[]){d(e),S()},get isStandalone(){return f()},set isStandalone(e=!1){f(e),S()},get children(){return p()},set children(e){p(e),S()},get type(){return m()},set type(e=`button`){m(e),S()},get use(){return _()},set use(e){_(e),S()},get class(){return v()},set class(e){v(e),S()}},O=s();return ee(g(O),()=>h(x),!1,(e,t)=>{l(e,e=>h(E)?.(e)),y(e,()=>({...b,onclick:n()?void 0:i(),type:n()?void 0:m(),href:n(),role:n()?`link`:`button`,target:n()?r():void 0,class:h(C),[te]:{"open-button--standalone":f()}}));var o=s();a(g(o),p),ne(t,o)}),ne(e,O),o(D)}x($,{href:{},target:{},onclick:{},className:{},isStandalone:{},children:{},type:{},use:{},class:{}},[],[],{mode:`open`});export{H as a,R as c,ve as d,j as f,Ze as i,L as l,X as n,V as o,lt as r,Ie as s,$ as t,je as u};
@@ -54,8 +54,8 @@ ${e}</tr>
54
54
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
55
55
  `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${K(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=$t(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+K(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=$t(e);if(i===null)return K(n);e=i;let a=`<img src="${e}" alt="${n}"`;return t&&(a+=` title="${K(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:K(e.text)}},cn=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}},J=class e{options;renderer;textRenderer;constructor(e){this.options=e||A,this.options.renderer=this.options.renderer||new sn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cn}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e,t=!0){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=i,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(t!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`paragraph`,`text`].includes(e.type)){n+=t||``;continue}}let a=i;switch(a.type){case`space`:n+=this.renderer.space(a);continue;case`hr`:n+=this.renderer.hr(a);continue;case`heading`:n+=this.renderer.heading(a);continue;case`code`:n+=this.renderer.code(a);continue;case`table`:n+=this.renderer.table(a);continue;case`blockquote`:n+=this.renderer.blockquote(a);continue;case`list`:n+=this.renderer.list(a);continue;case`html`:n+=this.renderer.html(a);continue;case`paragraph`:n+=this.renderer.paragraph(a);continue;case`text`:{let i=a,o=this.renderer.text(i);for(;r+1<e.length&&e[r+1].type===`text`;)i=e[++r],o+=`
56
56
  `+this.renderer.text(i);t?n+=this.renderer.paragraph({type:`paragraph`,raw:o,text:o,tokens:[{type:`text`,raw:o,text:o,escaped:!0}]}):n+=o;continue}default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}parseInline(e,t=this.renderer){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},ln=class{options;block;constructor(e){this.options=e||A}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?q.lex:q.lexInline}provideParser(){return this.block?J.parse:J.parseInline}},un=class{defaults=k();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=J;Renderer=sn;TextRenderer=cn;Lexer=q;Tokenizer=on;Hooks=ln;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new sn(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new on(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new ln;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];ln.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async)return Promise.resolve(i.call(t,e)).then(e=>a.call(t,e));let n=i.call(t,e);return a.call(t,n)}:t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return q.lex(e,t??this.defaults)}parser(e,t){return J.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(t==null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));i.hooks&&(i.hooks.options=i,i.hooks.block=e);let o=i.hooks?i.hooks.provideLexer():e?q.lex:q.lexInline,s=i.hooks?i.hooks.provideParser():e?J.parse:J.parseInline;if(i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(t):t).then(e=>o(e,i)).then(e=>i.hooks?i.hooks.processAllTokens(e):e).then(e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then(()=>e):e).then(e=>s(e,i)).then(e=>i.hooks?i.hooks.postprocess(e):e).catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let e=o(t,i);i.hooks&&(e=i.hooks.processAllTokens(e)),i.walkTokens&&this.walkTokens(e,i.walkTokens);let n=s(e,i);return i.hooks&&(n=i.hooks.postprocess(n)),n}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
57
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+K(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Y=new un;function X(e,t){return Y.parse(e,t)}X.options=X.setOptions=function(e){return Y.setOptions(e),X.defaults=Y.defaults,st(X.defaults),X},X.getDefaults=k,X.defaults=A,X.use=function(...e){return Y.use(...e),X.defaults=Y.defaults,st(X.defaults),X},X.walkTokens=function(e,t){return Y.walkTokens(e,t)},X.parseInline=Y.parseInline,X.Parser=J,X.parser=J.parse,X.Renderer=sn,X.TextRenderer=cn,X.Lexer=q,X.lexer=q.lex,X.Tokenizer=on,X.Hooks=ln,X.parse=X,X.options,X.setOptions,X.use,X.walkTokens,X.parseInline,J.parse,q.lex;var dn=e=>(Object.getOwnPropertyNames(e).forEach(t=>{let n=e[t];n&&typeof n==`object`&&dn(n)}),Object.freeze(e)),fn=dn({all:[],used:[],unused:[]}),pn=(e,t)=>{let n=ot(e);return n.addHook(`uponSanitizeElement`,function(e,t){let n=t.tagName||e.nodeName.toLowerCase();n.startsWith(`liipgpt-`)&&(t.allowedTags[n]=!0)}),n.addHook(`afterSanitizeAttributes`,function(e){if(e.tagName!==`A`||!e.getAttribute(`href`)?.startsWith(`http`)||(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`),!t||e.querySelector(`.sr-only`)))return;let n=e.ownerDocument.createElement(`span`);n.className=`sr-only`,n.textContent=` ${t}`,e.appendChild(n)}),n},mn=class{marked;currentReferences=fn;lastUsedIndex=0;DomPurity;constructor(e={}){this.marked=new un({async:!1,breaks:!0}).use(this.createFootnoteExtension(),...e.extensions??[]),this.DomPurity=pn(e.window,e.newTabSrText)}createFootnoteExtension=()=>{let e=this;return{extensions:[{name:`footnote`,level:`inline`,start(e){return e.match(/\[\^(\d+)\]/)?.index},tokenizer(e){let t=/^\[\^(\d+)\]/.exec(e);if(t){let[e,n]=t;return{type:`footnote`,raw:e,refNumber:n}}},renderer(t){if(t.type===`footnote`){let n=parseInt(t.refNumber)-1,r=e.currentReferences.all[n];if(!r)return console.error(`Could not find ref with index:`,n),``;let i;return r?.referenceIndex.used?i=r.referenceIndex.used:(e.currentReferences.used.push(r),e.lastUsedIndex++,i=e.lastUsedIndex,r.referenceIndex.used=i),` <liipgpt-reference-number data-all-index="${n}" data-used-index="${i}" data-source="${JSON.stringify(r).replace(/"/g,`&quot;`)}"></liipgpt-reference-number>`}}}]}};parse(e){return this.DomPurity.sanitize(this.marked.parse(e),{USE_PROFILES:{html:!0,svg:!0,svgFilters:!0,mathMl:!0},FORBID_TAGS:[`hr`],ADD_ATTR:[`target`]})}toHTML(e,t){this.currentReferences=t;let n=this.parse(e);return this.currentReferences=fn,n}};function hn(){let e,t;return{promise:new Promise((n,r)=>{t=n,e=r}),reject:e,resolve:t}}var gn=class{promise;resolve;reject;constructor(){let{promise:e,resolve:t,reject:n}=hn();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`},_n=class{hasValue=new gn;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`},vn=e=>{try{return new URL(e).hostname}catch{return e}};function yn(e){return e.replace(/<[^>]*>/g,``).replace(/&nbsp;/g,` `).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`)}var bn=({url:e,considered:t,title:n,description:r,summary:i})=>{let a=vn(e);return{url:e,considered:t,referenceIndex:{},score:0,metadata:{},display:{card:{title:n,description:r||i,badge:e},listItem:{title:n,badge:a}}}},xn=class{store;content=new _n;backendSendsMappedRefs=!1;constructor(e){this.options=e,this.store=s({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){this.options.onError?.(e),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=yn(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(bn(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()}},Sn=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)}},Cn=class{latestRequest=new _n;state=s({state:`idle`});id;history=[];constructor(e){this.clientPrimitive=e,this.id=e.createConversationId()}subscribe(e){return this.state.subscribe(e)}chat(e,t={}){let n=this.clientPrimitive.chat(this.id,e,t);return this.history.push(n),this.latestRequest.setValue({question:e,response:n}),n}async abort(){let e=this.history.map(e=>e.abort());await Promise.all(e)}async thumbsUp(){let{question:e,response:t}=await this.latestRequest;await t.isReadyForFeedback(),await this.clientPrimitive.thumbsUp(t.id,e)}async thumbsDown(){let{question:e,response:t}=await this.latestRequest;await t.isReadyForFeedback(),await this.clientPrimitive.thumbsDown(t.id,e)}async feedback(e){let{question:t,response:n}=await this.latestRequest;await n.isReadyForFeedback(),await this.clientPrimitive.feedback(n.id,t,e)}},Z=[];for(let e=0;e<256;++e)Z.push((e+256).toString(16).slice(1));function wn(e,t=0){return(Z[e[t+0]]+Z[e[t+1]]+Z[e[t+2]]+Z[e[t+3]]+`-`+Z[e[t+4]]+Z[e[t+5]]+`-`+Z[e[t+6]]+Z[e[t+7]]+`-`+Z[e[t+8]]+Z[e[t+9]]+`-`+Z[e[t+10]]+Z[e[t+11]]+Z[e[t+12]]+Z[e[t+13]]+Z[e[t+14]]+Z[e[t+15]]).toLowerCase()}var Tn,En=new Uint8Array(16);function Dn(){if(!Tn){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Tn=crypto.getRandomValues.bind(crypto)}return Tn(En)}var On={};function kn(e,t,n){let r;if(e)r=jn(e.random??e.rng?.()??Dn(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Dn();An(On,e,i),r=jn(i,On.msecs,On.seq,t,n)}return t??wn(r)}function An(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function jn(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}var Mn=new Map,Nn=class{get length(){return Mn.size}clear(){Mn.clear()}getItem(e){return Mn.get(e)||null}key(e){return Array.from(Mn.keys())[e]||null}removeItem(e){Mn.delete(e)}setItem(e,t){Mn.set(e,String(t))}},Pn=globalThis.localStorage??new Nn,Fn=async e=>{try{let t=Pn.getItem(`liipgpt:uID`)||Pn.getItem(`uID`),n={method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({referrer:globalThis?.document?.referrer||null,uID:t})},r=await e.fetchData(`/login`,pe,{},n).catch(t=>(console.log(`Failed to /login use /log`,t),e.fetchData(`/log`,pe,{},n)));if(`maintenance`in r&&r.maintenance)return{mode:`maintenance`};if(!(`id`in r))throw Error(`Invalid response format: missing user id`);return Pn.setItem(`liipgpt:uID`,r.id),{mode:`ready`,userId:r.id}}catch(e){throw console.error(`Failed to fetch user data:`,e),e}},Q=function(e,t){if(!(this instanceof Q))return new Q(e,t);this.url=e,t||={},this.headers=t.headers||{},this.payload=t.payload===void 0?``:t.payload,this.method=t.method||this.payload&&`POST`||`GET`,this.withCredentials=!!t.withCredentials,this.debug=!!t.debug,this.autoReconnect=t.autoReconnect===void 0?!1:t.autoReconnect,this.reconnectDelay=t.reconnectDelay===void 0?3e3:t.reconnectDelay,this.maxRetries=t.maxRetries===void 0?null:t.maxRetries,this.retryCount=0,this.reconnectTimer=null,this.useLastEventId=t.useLastEventId===void 0?!0:t.useLastEventId,this.FIELD_SEPARATOR=`:`,this.listeners={},this.xhr=null,this.readyState=Q.INITIALIZING,this.progress=0,this.chunk=``,this.lastEventId=``,this._hasParsedBom=!1,this.addEventListener=function(e,t){this.listeners[e]===void 0&&(this.listeners[e]=[]),this.listeners[e].indexOf(t)===-1&&this.listeners[e].push(t)},this.removeEventListener=function(e,t){if(this.listeners[e]===void 0)return;let n=[];this.listeners[e].forEach(function(e){e!==t&&n.push(e)}),n.length===0?delete this.listeners[e]:this.listeners[e]=n},this.dispatchEvent=function(e){if(!e)return!0;this.debug&&console.debug(e),e.source=this;let t=`on`+e.type;return this.hasOwnProperty(t)&&(this[t].call(this,e),e.defaultPrevented)?!1:this.listeners[e.type]?this.listeners[e.type].every(function(t){return t(e),!e.defaultPrevented}):!0},this._markClosed=function(){if(this.xhr=null,this.progress=0,this.chunk=``,this._setReadyState(Q.CLOSED),this.autoReconnect){if(this.maxRetries!==null&&this.retryCount>=this.maxRetries){this.debug&&console.debug(`SSE max retries (${this.maxRetries}) reached, stopping reconnection attempts`),this.autoReconnect=!1,this.close();return}this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.debug&&console.debug(`SSE will attempt to reconnect in ${this.reconnectDelay}ms (attempt ${this.retryCount+1}${this.maxRetries?`/`+this.maxRetries:``})`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryCount++,this.stream()},this.reconnectDelay)}},this._setReadyState=function(e){let t=new CustomEvent(`readystatechange`);t.readyState=e,this.readyState=e,this.dispatchEvent(t)},this._onStreamFailure=function(e){let t=new CustomEvent(`error`);t.responseCode=e.currentTarget.status,t.data=e.currentTarget.response,this.dispatchEvent(t),this._markClosed()},this._onStreamAbort=function(){this.dispatchEvent(new CustomEvent(`abort`)),this._markClosed()},this._onStreamProgress=function(e){if(!this.xhr)return;if(this.xhr.status<200||this.xhr.status>=300){this._onStreamFailure(e);return}this.retryCount=0;let t=this.xhr.responseText.substring(this.progress);this.progress+=t.length,!this._hasParsedBom&&this.chunk.length===0&&(t.charCodeAt(0)===65279&&(t=t.substring(1)),this._hasParsedBom=!0);let n=(this.chunk+t).split(/(\r\n\r\n|\r\r|\n\n)/g),r=n.pop();n.forEach(function(e){e.trim().length>0&&this.dispatchEvent(this._parseEventChunk(e))}.bind(this)),this.chunk=r},this._onStreamLoaded=function(e){this._onStreamProgress(e),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=``,this._markClosed()},this._parseEventChunk=function(e){if(!e||e.length===0)return null;this.debug&&console.debug(e);let t={id:null,retry:null,data:null,event:null};if(e.split(/\n|\r\n|\r/).forEach(function(e){let n=e.indexOf(this.FIELD_SEPARATOR),r,i;if(n>0){let t=e[n+1]===` `?2:1;r=e.substring(0,n),i=e.substring(n+t)}else if(n<0)r=e,i=``;else return;r in t&&(r===`data`&&t[r]!==null?t.data+=`
57
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+K(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Y=new un;function X(e,t){return Y.parse(e,t)}X.options=X.setOptions=function(e){return Y.setOptions(e),X.defaults=Y.defaults,st(X.defaults),X},X.getDefaults=k,X.defaults=A,X.use=function(...e){return Y.use(...e),X.defaults=Y.defaults,st(X.defaults),X},X.walkTokens=function(e,t){return Y.walkTokens(e,t)},X.parseInline=Y.parseInline,X.Parser=J,X.parser=J.parse,X.Renderer=sn,X.TextRenderer=cn,X.Lexer=q,X.lexer=q.lex,X.Tokenizer=on,X.Hooks=ln,X.parse=X,X.options,X.setOptions,X.use,X.walkTokens,X.parseInline,J.parse,q.lex;var dn=e=>(Object.getOwnPropertyNames(e).forEach(t=>{let n=e[t];n&&typeof n==`object`&&dn(n)}),Object.freeze(e)),fn=dn({all:[],used:[],unused:[]}),pn=(e,t)=>{let n=ot(e);return n.addHook(`uponSanitizeElement`,function(e,t){let n=t.tagName||e.nodeName.toLowerCase();n.startsWith(`liipgpt-`)&&(t.allowedTags[n]=!0)}),n.addHook(`afterSanitizeAttributes`,function(e){if(e.tagName!==`A`||!e.getAttribute(`href`)?.startsWith(`http`)||(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`),!t||e.querySelector(`.sr-only`)))return;let n=e.ownerDocument.createElement(`span`);n.className=`sr-only`,n.textContent=` ${t}`,e.appendChild(n)}),n},mn=class{marked;currentReferences=fn;lastUsedIndex=0;DomPurity;constructor(e={}){this.marked=new un({async:!1,breaks:!0}).use(this.createFootnoteExtension(),...e.extensions??[]),this.DomPurity=pn(e.window,e.newTabSrText)}createFootnoteExtension=()=>{let e=this;return{extensions:[{name:`footnote`,level:`inline`,start(e){return e.match(/\[\^(\d+)\]/)?.index},tokenizer(e){let t=/^\[\^(\d+)\]/.exec(e);if(t){let[e,n]=t;return{type:`footnote`,raw:e,refNumber:n}}},renderer(t){if(t.type===`footnote`){let n=parseInt(t.refNumber)-1,r=e.currentReferences.all[n];if(!r)return console.error(`Could not find ref with index:`,n),``;let i;return r?.referenceIndex.used?i=r.referenceIndex.used:(e.currentReferences.used.push(r),e.lastUsedIndex++,i=e.lastUsedIndex,r.referenceIndex.used=i),` <liipgpt-reference-number data-all-index="${n}" data-used-index="${i}" data-source="${JSON.stringify(r).replace(/"/g,`&quot;`)}"></liipgpt-reference-number>`}}}]}};parse(e){return this.DomPurity.sanitize(this.marked.parse(e),{USE_PROFILES:{html:!0,svg:!0,svgFilters:!0,mathMl:!0},FORBID_TAGS:[`hr`],ADD_ATTR:[`target`]})}toHTML(e,t){this.currentReferences=t;let n=this.parse(e);return this.currentReferences=fn,n}};function hn(){let e,t;return{promise:new Promise((n,r)=>{t=n,e=r}),reject:e,resolve:t}}var gn=class{promise;resolve;reject;constructor(){let{promise:e,resolve:t,reject:n}=hn();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`},_n=class{hasValue=new gn;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`},vn=e=>{try{return new URL(e).hostname}catch{return e}};function yn(e){return e.replace(/<[^>]*>/g,``).replace(/&nbsp;/g,` `).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`)}var bn=({url:e,considered:t,title:n,description:r,summary:i})=>{let a=vn(e);return{url:e,considered:t,referenceIndex:{},score:0,metadata:{},display:{card:{title:n,description:r||i,badge:e},listItem:{title:n,badge:a}}}},xn=class{store;content=new _n;backendSendsMappedRefs=!1;constructor(e){this.options=e,this.store=s({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){this.options.onError?.(e),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=yn(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(bn(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()}},Sn=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)}},Cn=class{latestRequest=new _n;state=s({state:`idle`});id;history=[];constructor(e){this.clientPrimitive=e,this.id=e.createConversationId()}subscribe(e){return this.state.subscribe(e)}chat(e,t={}){let n=this.clientPrimitive.chat(this.id,e,t);return this.history.push(n),this.latestRequest.setValue({question:e,response:n}),n}async abort(){let e=this.history.map(e=>e.abort());await Promise.all(e)}async thumbsUp(){let{question:e,response:t}=await this.latestRequest;await t.isReadyForFeedback(),await this.clientPrimitive.thumbsUp(t.id,e)}async thumbsDown(){let{question:e,response:t}=await this.latestRequest;await t.isReadyForFeedback(),await this.clientPrimitive.thumbsDown(t.id,e)}async feedback(e){let{question:t,response:n}=await this.latestRequest;await n.isReadyForFeedback(),await this.clientPrimitive.feedback(n.id,t,e)}},Z=[];for(let e=0;e<256;++e)Z.push((e+256).toString(16).slice(1));function wn(e,t=0){return(Z[e[t+0]]+Z[e[t+1]]+Z[e[t+2]]+Z[e[t+3]]+`-`+Z[e[t+4]]+Z[e[t+5]]+`-`+Z[e[t+6]]+Z[e[t+7]]+`-`+Z[e[t+8]]+Z[e[t+9]]+`-`+Z[e[t+10]]+Z[e[t+11]]+Z[e[t+12]]+Z[e[t+13]]+Z[e[t+14]]+Z[e[t+15]]).toLowerCase()}var Tn,En=new Uint8Array(16);function Dn(){if(!Tn){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Tn=crypto.getRandomValues.bind(crypto)}return Tn(En)}var On={};function kn(e,t,n){let r;if(e)r=jn(e.random??e.rng?.()??Dn(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Dn();An(On,e,i),r=jn(i,On.msecs,On.seq,t,n)}return t??wn(r)}function An(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function jn(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}var Mn=new Map,Nn=class{get length(){return Mn.size}clear(){Mn.clear()}getItem(e){return Mn.get(e)||null}key(e){return Array.from(Mn.keys())[e]||null}removeItem(e){Mn.delete(e)}setItem(e,t){Mn.set(e,String(t))}},Pn=globalThis.localStorage??new Nn,Fn=async(e,t)=>{try{let n=Pn.getItem(`liipgpt:uID`)||Pn.getItem(`uID`),r={method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({referrer:globalThis?.document?.referrer||null,uID:n,...t?{startParameters:t}:{}})},i=await e.fetchData(`/login`,pe,{},r).catch(t=>(console.log(`Failed to /login use /log`,t),e.fetchData(`/log`,pe,{},r)));if(`maintenance`in i&&i.maintenance)return{mode:`maintenance`};if(!(`id`in i))throw Error(`Invalid response format: missing user id`);return Pn.setItem(`liipgpt:uID`,i.id),{mode:`ready`,userId:i.id}}catch(e){throw console.error(`Failed to fetch user data:`,e),e}},Q=function(e,t){if(!(this instanceof Q))return new Q(e,t);this.url=e,t||={},this.headers=t.headers||{},this.payload=t.payload===void 0?``:t.payload,this.method=t.method||this.payload&&`POST`||`GET`,this.withCredentials=!!t.withCredentials,this.debug=!!t.debug,this.autoReconnect=t.autoReconnect===void 0?!1:t.autoReconnect,this.reconnectDelay=t.reconnectDelay===void 0?3e3:t.reconnectDelay,this.maxRetries=t.maxRetries===void 0?null:t.maxRetries,this.retryCount=0,this.reconnectTimer=null,this.useLastEventId=t.useLastEventId===void 0?!0:t.useLastEventId,this.FIELD_SEPARATOR=`:`,this.listeners={},this.xhr=null,this.readyState=Q.INITIALIZING,this.progress=0,this.chunk=``,this.lastEventId=``,this._hasParsedBom=!1,this.addEventListener=function(e,t){this.listeners[e]===void 0&&(this.listeners[e]=[]),this.listeners[e].indexOf(t)===-1&&this.listeners[e].push(t)},this.removeEventListener=function(e,t){if(this.listeners[e]===void 0)return;let n=[];this.listeners[e].forEach(function(e){e!==t&&n.push(e)}),n.length===0?delete this.listeners[e]:this.listeners[e]=n},this.dispatchEvent=function(e){if(!e)return!0;this.debug&&console.debug(e),e.source=this;let t=`on`+e.type;return this.hasOwnProperty(t)&&(this[t].call(this,e),e.defaultPrevented)?!1:this.listeners[e.type]?this.listeners[e.type].every(function(t){return t(e),!e.defaultPrevented}):!0},this._markClosed=function(){if(this.xhr=null,this.progress=0,this.chunk=``,this._setReadyState(Q.CLOSED),this.autoReconnect){if(this.maxRetries!==null&&this.retryCount>=this.maxRetries){this.debug&&console.debug(`SSE max retries (${this.maxRetries}) reached, stopping reconnection attempts`),this.autoReconnect=!1,this.close();return}this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.debug&&console.debug(`SSE will attempt to reconnect in ${this.reconnectDelay}ms (attempt ${this.retryCount+1}${this.maxRetries?`/`+this.maxRetries:``})`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryCount++,this.stream()},this.reconnectDelay)}},this._setReadyState=function(e){let t=new CustomEvent(`readystatechange`);t.readyState=e,this.readyState=e,this.dispatchEvent(t)},this._onStreamFailure=function(e){let t=new CustomEvent(`error`);t.responseCode=e.currentTarget.status,t.data=e.currentTarget.response,this.dispatchEvent(t),this._markClosed()},this._onStreamAbort=function(){this.dispatchEvent(new CustomEvent(`abort`)),this._markClosed()},this._onStreamProgress=function(e){if(!this.xhr)return;if(this.xhr.status<200||this.xhr.status>=300){this._onStreamFailure(e);return}this.retryCount=0;let t=this.xhr.responseText.substring(this.progress);this.progress+=t.length,!this._hasParsedBom&&this.chunk.length===0&&(t.charCodeAt(0)===65279&&(t=t.substring(1)),this._hasParsedBom=!0);let n=(this.chunk+t).split(/(\r\n\r\n|\r\r|\n\n)/g),r=n.pop();n.forEach(function(e){e.trim().length>0&&this.dispatchEvent(this._parseEventChunk(e))}.bind(this)),this.chunk=r},this._onStreamLoaded=function(e){this._onStreamProgress(e),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=``,this._markClosed()},this._parseEventChunk=function(e){if(!e||e.length===0)return null;this.debug&&console.debug(e);let t={id:null,retry:null,data:null,event:null};if(e.split(/\n|\r\n|\r/).forEach(function(e){let n=e.indexOf(this.FIELD_SEPARATOR),r,i;if(n>0){let t=e[n+1]===` `?2:1;r=e.substring(0,n),i=e.substring(n+t)}else if(n<0)r=e,i=``;else return;r in t&&(r===`data`&&t[r]!==null?t.data+=`
58
58
  `+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
59
59
  `);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(Q.OPEN)}},this.stream=function(){if(!this.xhr){this._setReadyState(Q.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()};Q.INITIALIZING=-1,Q.CONNECTING=0,Q.OPEN=1,Q.CLOSED=2;var In=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??Q)(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())}},Ln=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),Rn=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=Ln(t);return this.options.apiKey&&(n.apiKey=this.options.apiKey),new In(`${this.options.apiUrl}${e}`,n,r)}async fetchData(e,t,n={},r={}){let i=`${this.options.apiUrl}${e}?${new URLSearchParams(Ln(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(),{success:c,data:l,error:u}=t.safeParse(s);if(this.options.strict){if(!c)throw console.error(`Server response has wrong type:
60
60
  `,{error:u,url:i,opts:a,data:s}),Error(`Server response has wrong type: ${u.message}`);return l}else return c||console.warn(`Server response has wrong type:
61
- `,{error:u,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}},zn=le({links:_(le({url:g().url().optional(),title:g().optional(),considered:ce().optional(),orgMetadata:le({authors:_(g()).optional()}).optional(),type:g().optional(),date:g().datetime().optional(),similarity:se().optional(),content:g().optional(),fromFullTextSearch:ce().optional(),rerank:le({index:se().int().optional(),adjustment:se().optional(),score:se().optional(),similarityOld:se().optional()}).optional()}).or(de))}),Bn=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}},Vn=7,Hn=8,Un=160,Wn=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},Gn=e=>{let t=Wn(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},Kn=e=>Math.max(Hn,Math.min(Un,e.length*Vn)),qn=class{queue=[];timeoutId=null;isProcessing=!1;constructor(e){this.onText=e}ingestText(e){let t=Gn(e);if(t.length>=5){for(let e of t)this.queue.push({kind:`text`,chunk:e,delayMs:Kn(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())}},Jn=class{constructor(e){this.results=e}},Yn=class{internalData;renderers=new Map;markedExtensions=[];_newTabSrText;constructor(e){let t=new Rn({apiUrl:e.apiUrl,apiKey:e.apiKey,speechRecognitionApiKey:e.speechRecognitionApiKey,strict:e.strict??!1,EventSource:e.EventSource??EventSource});this.internalData={restClient:t,metadata:Fn(t),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=kn();return this.renderers.set(e,new mn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText})),e}chat(e,t,n={}){let r=new _n,i=kn(),a=new gn,o=new xn({id:i,onError:e=>{n.onError?.(e)},onFinish:e=>{r.setValue(e)},markdownRenderer:this.renderers.get(e)??new mn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText}),userQuestion:t}),s=async()=>{await a,(await c).close()},c=new _n,l=new qn(e=>o.updateText(e));(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,...n.selectorValues??{},...n.predefinedQuestionId?{predefinedQuestionId:n.predefinedQuestionId}:{},...n.switchQuestionId?{switchQuestionId:n.switchQuestionId}:{},chat:`true`,version:`2`},{onClose:()=>{l.clear(),o.finishMessage(),a.resolve(),r.cleanup()},onMessage:t=>{let r=t;switch(r.type){case`error`:l.runAfterTyping(()=>o.pushError(r.error));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`: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`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)})();let u=new Sn({question:t,id:i,content:r,readableStore:o.getReadableStore(),readyForFeedback:a,abort:s,liipgptClientPrimitive:this});return this.internalData.chatResponseMap.set(u.id,u),u}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 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`,zn,{modelId:t.model,lang:t.language,query:e,mapResults:`true`,uID:r});return new Jn(i.map(Bn))}async getChatConfig(){return this.internalData.restClient.fetchData(`/chatconfig`,ue)}async getPredefinedQuestions(e){return(await this.internalData.restClient.fetchData(`/topics/questions`,fe,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`}}}},Xn=class{clientPrimitive;constructor(e){this.clientPrimitive=new Yn(e)}getMetadata(){return this.clientPrimitive.getMetadata()}createConversation(){return new Cn(this.clientPrimitive)}search(e,t={}){return this.clientPrimitive.search(e,t)}getChatConfig(){return this.clientPrimitive.getChatConfig()}getPredefinedQuestions(e){return this.clientPrimitive.getPredefinedQuestions(e)}},Zn=class extends Map{#e=new Map;#t=n(0);#n=n(0);#r=ne||-1;constructor(e){if(super(),e){for(var[t,n]of e)super.set(t,n);this.#n.v=super.size}}#i(e){return ne===this.#r?n(e):l(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 u(this.#t),!1;return u(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{u(this.#t);return}return u(n),super.get(e)}set(e,n){var r=this.#e,i=r.get(e),a=super.get(e),o=super.set(e,n),s=this.#t;if(i===void 0)i=this.#i(0),r.set(e,i),h(this.#n,super.size),t(s);else if(a!==n){t(i);var c=s.reactions===null?null:new Set(s.reactions);(c===null||!i.reactions?.every(e=>c.has(e)))&&t(s)}return o}delete(e){var n=this.#e,r=n.get(e),i=super.delete(e);return r!==void 0&&(n.delete(e),h(r,-1)),i&&(h(this.#n,super.size),t(this.#t)),i}clear(){if(super.size!==0){super.clear();var e=this.#e;h(this.#n,0);for(var n of e.values())h(n,-1);t(this.#t),e.clear()}}#a(){u(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)u(n)}keys(){return u(this.#t),super.keys()}values(){return this.#a(),super.values()}entries(){return this.#a(),super.entries()}[Symbol.iterator](){return this.entries()}get size(){return u(this.#n),super.size}},Qn=class{#e;#t;constructor(t,n){this.#e=t,this.#t=e(n)}get current(){return this.#t(),this.#e()}},$n=/\(.+\)/,er=new Set([`all`,`print`,`screen`,`and`,`or`,`not`,`only`]),tr=class extends Qn{constructor(e,t){let n=$n.test(e)||e.split(/[\s,]+/).some(e=>er.has(e.trim()))?e:`(${e})`,r=window.matchMedia(n);super(()=>r.matches,e=>m(r,`change`,e))}};function nr(e,t){o(t,!0);let n=ie(t,`css`,7),s=oe(t,[`$$slots`,`$$events`,`$$legacy`,`$$host`,`css`]),l=e=>{re(()=>{n()&&(e.innerHTML=n())})};var u={get css(){return n()},set css(e){n(e),te()}},p=a(),ne=d(p),m=e=>{var t=a();ee(d(t),()=>`style`,!1,(e,t)=>{c(e,e=>l?.(e)),f(e,()=>({...s}))}),ae(e,t)};return r(ne,e=>{n()&&e(m)}),ae(e,p),i(u)}p(nr,{css:{}},[],[],{mode:`open`});var rr=RegExp(`([\\p{Ll}\\d])(\\p{Lu})`,`gu`),ir=RegExp(`(\\p{Lu})([\\p{Lu}][\\p{Ll}])`,`gu`),ar=RegExp(`(\\d)(\\p{Ll})`,`gu`),or=RegExp(`(\\p{L})(\\d)`,`gu`),sr=/[^\p{L}\d]+/giu,cr=`$1\0$2`,lr=``;function ur(e,t){let n=e.trim();n=n.replace(rr,cr).replace(ir,cr),t?.separateNumbers&&(n=n.replace(ar,cr).replace(or,cr)),n=n.replace(sr,`\0`);let r=0,i=n.length;for(;n.charAt(r)===`\0`;)r++;if(r===i)return[];for(;n.charAt(i-1)===`\0`;)i--;return n.slice(r,i).split(/\0/g)}function dr(e,t){return Er(e,t?.prefixCharacters)+ur(e,t).map(Sr(t?.locale)).join(t?.delimiter??` `)}function fr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale),a=t?.mergeAmbiguousCharacters?wr(r,i):Tr(r,i);return n+ur(e,t).map((e,t)=>t===0?r(e):a(e,t)).join(t?.delimiter??``)}function pr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale),a=t?.mergeAmbiguousCharacters?wr(r,i):Tr(r,i);return n+ur(e,t).map(a).join(t?.delimiter??``)}function mr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale);return n+ur(e,t).map(wr(r,i)).join(t?.delimiter??` `)}function hr(e,t){return Er(e,t?.prefixCharacters)+ur(e,t).map(Cr(t?.locale)).join(t?.delimiter??`_`)}function gr(e,t){return dr(e,{delimiter:`.`,...t})}function _r(e,t){return dr(e,{delimiter:`-`,...t})}function vr(e,t){return dr(e,{delimiter:`/`,...t})}function yr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=wr(r,Cr(t?.locale));return n+ur(e,t).map((e,t)=>t===0?i(e):r(e)).join(t?.delimiter??` `)}function br(e,t){return dr(e,{delimiter:`_`,...t})}function xr(e,t){return mr(e,{delimiter:`-`,...t})}function Sr(e){return e===!1?e=>e.toLowerCase():t=>t.toLocaleLowerCase(e)}function Cr(e){return e===!1?e=>e.toUpperCase():t=>t.toLocaleUpperCase(e)}function wr(e,t){return n=>`${t(n[0])}${e(n.slice(1))}`}function Tr(e,t){return(n,r)=>{let i=n[0];return(r>0&&i>=`0`&&i<=`9`?`_`+i:t(i))+e(n.slice(1))}}function Er(e,t=lr){let n=``;for(let r=0;r<e.length;r++){let i=e.charAt(r);if(t.includes(i))n+=i;else break}return n}function Dr(e,t){let n=``;for(let r of e)n+=Math.random()>.5?r.toLocaleUpperCase(t):r.toLocaleLowerCase(t);return n}function Or(e,t){let n=``;for(let r of e){let e=r.toLocaleLowerCase(t);n+=r===e?r.toLocaleUpperCase(t):e}return n}var kr=/\b(?:an?d?|a[st]|because|but|by|en|for|i[fn]|neither|nor|o[fnr]|only|over|per|so|some|tha[tn]|the|to|up|upon|vs?\.?|versus|via|when|with|without|yet)\b/i,Ar=/[^\s:–—-]+|./g,jr=/\s/,Mr=/.(?=[A-Z]|\..)/,Nr=/[A-Za-z0-9\u00C0-\u00FF]/;function Pr(e){for(var t=``,n;(n=Ar.exec(e))!==null;){var r=n[0],i=n.index;if(!Mr.test(r)&&(!kr.test(r)||i===0||i+r.length===e.length)&&(e.charAt(i+r.length)!==`:`||jr.test(e.charAt(i+r.length+1)))){t+=r.replace(Nr,function(e){return e.toUpperCase()});continue}t+=r}return t}var Fr=fr,Ir=mr,Lr=hr,Rr=gr,zr=dr,Br=pr,Vr=vr,Hr=yr,Ur=br,Wr=xr,Gr=_r,Kr=Dr,qr=Or,Jr=Pr,Yr=e=>e.toUpperCase(),Xr=(e,t)=>e.toLocaleUpperCase(t),Zr=e=>e.toLowerCase(),Qr=(e,t)=>e.toLocaleLowerCase(t),$r=e=>e.charAt(0).toLowerCase()+e.slice(1),ei=e=>e.charAt(0).toUpperCase()+e.slice(1),ti=e=>e===e.toUpperCase(),ni=e=>e===e.toLowerCase(),$=class{};$.camel=Fr,$.capital=Ir,$.constant=Lr,$.dot=Rr,$.kebab=Gr,$.lower=Zr,$.lowerFirst=$r,$.localeLower=Qr,$.localeUpper=Xr,$.no=zr,$.pascal=Br,$.path=Vr,$.sentence=Hr,$.snake=Ur,$.sponge=Kr,$.swap=qr,$.title=Jr,$.train=Wr,$.upper=Yr,$.upperFirst=ei,$.isUpper=ti,$.isLower=ni;var ri=640,ii=1024,ai=null,oi=()=>{if(ai)return ai;if(!globalThis.document)return 16;let e=globalThis.document.querySelector(`:root`);return ai=Number(getComputedStyle(e).fontSize.slice(0,-2)),ai},si=({minRem:e,maxRem:t})=>{let n=oi(),r=ri/n,i=ii/n,a=(t-e)/(i-r);return`clamp( ${e}rem, ${-r*a+e}rem + ${a*100}cqw, ${t}rem )`},ci=e=>typeof e==`string`?e:typeof e==`number`?String(e):typeof e==`object`?e.minRem===e.maxRem?`${e.minRem}rem`:si(e):``,li=(e,t,n,r=!1)=>{let i=``;return n.forEach(n=>{let a=t[n];r&&!a&&n===`borderWidth`&&(a=`0px`),r&&!a&&n===`borderColor`&&(a=`transparent`),a&&(i+=`--${Gr(e)}-${Gr(n)}:${ci(a)}; `)}),i},ui=(e,t)=>Object.entries(t).map(([t,n])=>`--${e}-${Gr(t)}:${ci(n)}`).join(`; `)+`; `,di=(e,t)=>{let n=``;return n+=li(e,t,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`borderRadius`,`color`],!0),t.hover&&(n+=li(`${e}-hover`,t.hover,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`color`])),t.focus&&(n+=li(`${e}-focus`,t.focus,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`color`])),t.custom&&(n+=ui(e,t.custom)),n},fi=(e,t)=>Object.entries(t).map(([t,n])=>`--color-${e}-${t}:${n}`).join(`; `)+`; `,pi=e=>`--font-family: ${e?.family||`inherit`};`,mi=(e,t={})=>`${t.root??`.chat-app`} {${pi(e.font)} ${Object.entries(e.colors).map(([e,t])=>fi(e,t)).join(``)} ${ui(`base`,e.base)} ${Object.entries(e.components).map(([e,t])=>di(Gr(e),t)).join(``)}};`;export{Xn as a,Gn as c,wn as d,yn as f,Zn as i,Pn as l,nr as n,Yn as o,ot as p,tr as r,Kn as s,mi as t,Dn as u};
61
+ `,{error:u,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}},zn=le({links:_(le({url:g().url().optional(),title:g().optional(),considered:ce().optional(),orgMetadata:le({authors:_(g()).optional()}).optional(),type:g().optional(),date:g().datetime().optional(),similarity:se().optional(),content:g().optional(),fromFullTextSearch:ce().optional(),rerank:le({index:se().int().optional(),adjustment:se().optional(),score:se().optional(),similarityOld:se().optional()}).optional()}).or(de))}),Bn=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}},Vn=7,Hn=8,Un=160,Wn=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},Gn=e=>{let t=Wn(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},Kn=e=>Math.max(Hn,Math.min(Un,e.length*Vn)),qn=class{queue=[];timeoutId=null;isProcessing=!1;constructor(e){this.onText=e}ingestText(e){let t=Gn(e);if(t.length>=5){for(let e of t)this.queue.push({kind:`text`,chunk:e,delayMs:Kn(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())}},Jn=class{constructor(e){this.results=e}},Yn=class{internalData;renderers=new Map;markedExtensions=[];_newTabSrText;constructor(e){let t=new Rn({apiUrl:e.apiUrl,apiKey:e.apiKey,speechRecognitionApiKey:e.speechRecognitionApiKey,strict:e.strict??!1,EventSource:e.EventSource??EventSource});this.internalData={restClient:t,metadata:Fn(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=kn();return this.renderers.set(e,new mn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText})),e}chat(e,t,n={}){let r=new _n,i=kn(),a=new gn,o=new xn({id:i,onError:e=>{n.onError?.(e)},onFinish:e=>{r.setValue(e)},markdownRenderer:this.renderers.get(e)??new mn({extensions:this.markedExtensions,newTabSrText:this._newTabSrText}),userQuestion:t}),s=async()=>{await a,(await c).close()},c=new _n,l=new qn(e=>o.updateText(e));(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,...n.selectorValues??{},...n.predefinedQuestionId?{predefinedQuestionId:n.predefinedQuestionId}:{},...n.switchQuestionId?{switchQuestionId:n.switchQuestionId}:{},chat:`true`,version:`2`},{onClose:()=>{l.clear(),o.finishMessage(),a.resolve(),r.cleanup()},onMessage:t=>{let r=t;switch(r.type){case`error`:l.runAfterTyping(()=>o.pushError(r.error));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`: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`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)})();let u=new Sn({question:t,id:i,content:r,readableStore:o.getReadableStore(),readyForFeedback:a,abort:s,liipgptClientPrimitive:this});return this.internalData.chatResponseMap.set(u.id,u),u}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 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`,zn,{modelId:t.model,lang:t.language,query:e,mapResults:`true`,uID:r});return new Jn(i.map(Bn))}async getChatConfig(){return this.internalData.restClient.fetchData(`/chatconfig`,ue)}async getPredefinedQuestions(e){return(await this.internalData.restClient.fetchData(`/topics/questions`,fe,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`}}}},Xn=class{clientPrimitive;constructor(e){this.clientPrimitive=new Yn(e)}getMetadata(){return this.clientPrimitive.getMetadata()}createConversation(){return new Cn(this.clientPrimitive)}search(e,t={}){return this.clientPrimitive.search(e,t)}getChatConfig(){return this.clientPrimitive.getChatConfig()}getPredefinedQuestions(e){return this.clientPrimitive.getPredefinedQuestions(e)}},Zn=class extends Map{#e=new Map;#t=n(0);#n=n(0);#r=ne||-1;constructor(e){if(super(),e){for(var[t,n]of e)super.set(t,n);this.#n.v=super.size}}#i(e){return ne===this.#r?n(e):l(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 u(this.#t),!1;return u(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{u(this.#t);return}return u(n),super.get(e)}set(e,n){var r=this.#e,i=r.get(e),a=super.get(e),o=super.set(e,n),s=this.#t;if(i===void 0)i=this.#i(0),r.set(e,i),h(this.#n,super.size),t(s);else if(a!==n){t(i);var c=s.reactions===null?null:new Set(s.reactions);(c===null||!i.reactions?.every(e=>c.has(e)))&&t(s)}return o}delete(e){var n=this.#e,r=n.get(e),i=super.delete(e);return r!==void 0&&(n.delete(e),h(r,-1)),i&&(h(this.#n,super.size),t(this.#t)),i}clear(){if(super.size!==0){super.clear();var e=this.#e;h(this.#n,0);for(var n of e.values())h(n,-1);t(this.#t),e.clear()}}#a(){u(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)u(n)}keys(){return u(this.#t),super.keys()}values(){return this.#a(),super.values()}entries(){return this.#a(),super.entries()}[Symbol.iterator](){return this.entries()}get size(){return u(this.#n),super.size}},Qn=class{#e;#t;constructor(t,n){this.#e=t,this.#t=e(n)}get current(){return this.#t(),this.#e()}},$n=/\(.+\)/,er=new Set([`all`,`print`,`screen`,`and`,`or`,`not`,`only`]),tr=class extends Qn{constructor(e,t){let n=$n.test(e)||e.split(/[\s,]+/).some(e=>er.has(e.trim()))?e:`(${e})`,r=window.matchMedia(n);super(()=>r.matches,e=>m(r,`change`,e))}};function nr(e,t){o(t,!0);let n=ie(t,`css`,7),s=oe(t,[`$$slots`,`$$events`,`$$legacy`,`$$host`,`css`]),l=e=>{re(()=>{n()&&(e.innerHTML=n())})};var u={get css(){return n()},set css(e){n(e),te()}},p=a(),ne=d(p),m=e=>{var t=a();ee(d(t),()=>`style`,!1,(e,t)=>{c(e,e=>l?.(e)),f(e,()=>({...s}))}),ae(e,t)};return r(ne,e=>{n()&&e(m)}),ae(e,p),i(u)}p(nr,{css:{}},[],[],{mode:`open`});var rr=RegExp(`([\\p{Ll}\\d])(\\p{Lu})`,`gu`),ir=RegExp(`(\\p{Lu})([\\p{Lu}][\\p{Ll}])`,`gu`),ar=RegExp(`(\\d)(\\p{Ll})`,`gu`),or=RegExp(`(\\p{L})(\\d)`,`gu`),sr=/[^\p{L}\d]+/giu,cr=`$1\0$2`,lr=``;function ur(e,t){let n=e.trim();n=n.replace(rr,cr).replace(ir,cr),t?.separateNumbers&&(n=n.replace(ar,cr).replace(or,cr)),n=n.replace(sr,`\0`);let r=0,i=n.length;for(;n.charAt(r)===`\0`;)r++;if(r===i)return[];for(;n.charAt(i-1)===`\0`;)i--;return n.slice(r,i).split(/\0/g)}function dr(e,t){return Er(e,t?.prefixCharacters)+ur(e,t).map(Sr(t?.locale)).join(t?.delimiter??` `)}function fr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale),a=t?.mergeAmbiguousCharacters?wr(r,i):Tr(r,i);return n+ur(e,t).map((e,t)=>t===0?r(e):a(e,t)).join(t?.delimiter??``)}function pr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale),a=t?.mergeAmbiguousCharacters?wr(r,i):Tr(r,i);return n+ur(e,t).map(a).join(t?.delimiter??``)}function mr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=Cr(t?.locale);return n+ur(e,t).map(wr(r,i)).join(t?.delimiter??` `)}function hr(e,t){return Er(e,t?.prefixCharacters)+ur(e,t).map(Cr(t?.locale)).join(t?.delimiter??`_`)}function gr(e,t){return dr(e,{delimiter:`.`,...t})}function _r(e,t){return dr(e,{delimiter:`-`,...t})}function vr(e,t){return dr(e,{delimiter:`/`,...t})}function yr(e,t){let n=Er(e,t?.prefixCharacters),r=Sr(t?.locale),i=wr(r,Cr(t?.locale));return n+ur(e,t).map((e,t)=>t===0?i(e):r(e)).join(t?.delimiter??` `)}function br(e,t){return dr(e,{delimiter:`_`,...t})}function xr(e,t){return mr(e,{delimiter:`-`,...t})}function Sr(e){return e===!1?e=>e.toLowerCase():t=>t.toLocaleLowerCase(e)}function Cr(e){return e===!1?e=>e.toUpperCase():t=>t.toLocaleUpperCase(e)}function wr(e,t){return n=>`${t(n[0])}${e(n.slice(1))}`}function Tr(e,t){return(n,r)=>{let i=n[0];return(r>0&&i>=`0`&&i<=`9`?`_`+i:t(i))+e(n.slice(1))}}function Er(e,t=lr){let n=``;for(let r=0;r<e.length;r++){let i=e.charAt(r);if(t.includes(i))n+=i;else break}return n}function Dr(e,t){let n=``;for(let r of e)n+=Math.random()>.5?r.toLocaleUpperCase(t):r.toLocaleLowerCase(t);return n}function Or(e,t){let n=``;for(let r of e){let e=r.toLocaleLowerCase(t);n+=r===e?r.toLocaleUpperCase(t):e}return n}var kr=/\b(?:an?d?|a[st]|because|but|by|en|for|i[fn]|neither|nor|o[fnr]|only|over|per|so|some|tha[tn]|the|to|up|upon|vs?\.?|versus|via|when|with|without|yet)\b/i,Ar=/[^\s:–—-]+|./g,jr=/\s/,Mr=/.(?=[A-Z]|\..)/,Nr=/[A-Za-z0-9\u00C0-\u00FF]/;function Pr(e){for(var t=``,n;(n=Ar.exec(e))!==null;){var r=n[0],i=n.index;if(!Mr.test(r)&&(!kr.test(r)||i===0||i+r.length===e.length)&&(e.charAt(i+r.length)!==`:`||jr.test(e.charAt(i+r.length+1)))){t+=r.replace(Nr,function(e){return e.toUpperCase()});continue}t+=r}return t}var Fr=fr,Ir=mr,Lr=hr,Rr=gr,zr=dr,Br=pr,Vr=vr,Hr=yr,Ur=br,Wr=xr,Gr=_r,Kr=Dr,qr=Or,Jr=Pr,Yr=e=>e.toUpperCase(),Xr=(e,t)=>e.toLocaleUpperCase(t),Zr=e=>e.toLowerCase(),Qr=(e,t)=>e.toLocaleLowerCase(t),$r=e=>e.charAt(0).toLowerCase()+e.slice(1),ei=e=>e.charAt(0).toUpperCase()+e.slice(1),ti=e=>e===e.toUpperCase(),ni=e=>e===e.toLowerCase(),$=class{};$.camel=Fr,$.capital=Ir,$.constant=Lr,$.dot=Rr,$.kebab=Gr,$.lower=Zr,$.lowerFirst=$r,$.localeLower=Qr,$.localeUpper=Xr,$.no=zr,$.pascal=Br,$.path=Vr,$.sentence=Hr,$.snake=Ur,$.sponge=Kr,$.swap=qr,$.title=Jr,$.train=Wr,$.upper=Yr,$.upperFirst=ei,$.isUpper=ti,$.isLower=ni;var ri=640,ii=1024,ai=null,oi=()=>{if(ai)return ai;if(!globalThis.document)return 16;let e=globalThis.document.querySelector(`:root`);return ai=Number(getComputedStyle(e).fontSize.slice(0,-2)),ai},si=({minRem:e,maxRem:t})=>{let n=oi(),r=ri/n,i=ii/n,a=(t-e)/(i-r);return`clamp( ${e}rem, ${-r*a+e}rem + ${a*100}cqw, ${t}rem )`},ci=e=>typeof e==`string`?e:typeof e==`number`?String(e):typeof e==`object`?e.minRem===e.maxRem?`${e.minRem}rem`:si(e):``,li=(e,t,n,r=!1)=>{let i=``;return n.forEach(n=>{let a=t[n];r&&!a&&n===`borderWidth`&&(a=`0px`),r&&!a&&n===`borderColor`&&(a=`transparent`),a&&(i+=`--${Gr(e)}-${Gr(n)}:${ci(a)}; `)}),i},ui=(e,t)=>Object.entries(t).map(([t,n])=>`--${e}-${Gr(t)}:${ci(n)}`).join(`; `)+`; `,di=(e,t)=>{let n=``;return n+=li(e,t,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`borderRadius`,`color`],!0),t.hover&&(n+=li(`${e}-hover`,t.hover,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`color`])),t.focus&&(n+=li(`${e}-focus`,t.focus,[`background`,`borderWidth`,`borderColor`,`boxShadow`,`color`])),t.custom&&(n+=ui(e,t.custom)),n},fi=(e,t)=>Object.entries(t).map(([t,n])=>`--color-${e}-${t}:${n}`).join(`; `)+`; `,pi=e=>`--font-family: ${e?.family||`inherit`};`,mi=(e,t={})=>`${t.root??`.chat-app`} {${pi(e.font)} ${Object.entries(e.colors).map(([e,t])=>fi(e,t)).join(``)} ${ui(`base`,e.base)} ${Object.entries(e.components).map(([e,t])=>di(Gr(e),t)).join(``)}};`;export{Xn as a,Gn as c,wn as d,yn as f,Zn as i,Pn as l,nr as n,Yn as o,ot as p,tr as r,Kn as s,mi as t,Dn as u};
@@ -1,4 +1,4 @@
1
- import{H as e,It as t,J as n,Lt as r,Y as i,bt as a,et as o,i as s,jt as c,k as l,o as u,q as d,tt as f}from"./C00ruT0L.js";import{t as p}from"./CKDKLu5Y.js";import{t as m}from"./BwV52vQs.js";var h=(e,t)=>{let n=new URLSearchParams(m.url.searchParams);t===void 0?n.delete(e):n.set(e,String(t));let r=`?${n.toString()}`;window.top&&window.top.postMessage(`liipgpt-url:`+r,`*`),p(r,{replaceState:!0})},g=e=>{let t=new URLSearchParams(m.url.searchParams);for(let[n,r]of Object.entries(e))r===void 0?t.delete(n):t.set(n,String(r));let n=`?${t.toString()}`;window.top&&window.top.postMessage(`liipgpt-url:`+n,`*`),p(n,{replaceState:!0})},_=i(`<button type="button" class="sidebar-hide svelte-q6hwt7" aria-label="Hide sidebar">Hide sidebar</button>`),v=i(`<button type="button" class="sidebar-reopen svelte-q6hwt7" aria-label="Show sidebar"><span class="sidebar-reopen__label svelte-q6hwt7" aria-hidden="true">Show sidebar</span></button>`),y={hash:`svelte-q6hwt7`,code:`.sidebar-hide.svelte-q6hwt7 {display:block;padding:0.375rem 0.75rem;border:1px solid #e5e7eb;border-radius:0.375rem;background:#fff;color:#4b5563;font-weight:500;font-size:0.75rem;line-height:1.25;font-family:system-ui, sans-serif;cursor:pointer;}.sidebar-hide.svelte-q6hwt7:hover {background:#f3f4f6;color:#111827;}.sidebar-reopen.svelte-q6hwt7 {display:flex;z-index:50;position:fixed;bottom:5rem;left:0;align-items:center;justify-content:center;padding:0.5rem 0.25rem;border:1px solid #e5e7eb;border-left:none;border-radius:0 0.375rem 0.375rem 0;background:#fff;box-shadow:0 1px 3px 0 rgb(0 0 0 / 0.1),
1
+ import{H as e,It as t,J as n,Lt as r,Y as i,bt as a,et as o,i as s,jt as c,k as l,o as u,q as d,tt as f}from"./C00ruT0L.js";import{t as p}from"./DABlUYYh.js";import{t as m}from"./DzLbPreo.js";var h=(e,t)=>{let n=new URLSearchParams(m.url.searchParams);t===void 0?n.delete(e):n.set(e,String(t));let r=`?${n.toString()}`;window.top&&window.top.postMessage(`liipgpt-url:`+r,`*`),p(r,{replaceState:!0})},g=e=>{let t=new URLSearchParams(m.url.searchParams);for(let[n,r]of Object.entries(e))r===void 0?t.delete(n):t.set(n,String(r));let n=`?${t.toString()}`;window.top&&window.top.postMessage(`liipgpt-url:`+n,`*`),p(n,{replaceState:!0})},_=i(`<button type="button" class="sidebar-hide svelte-q6hwt7" aria-label="Hide sidebar">Hide sidebar</button>`),v=i(`<button type="button" class="sidebar-reopen svelte-q6hwt7" aria-label="Show sidebar"><span class="sidebar-reopen__label svelte-q6hwt7" aria-hidden="true">Show sidebar</span></button>`),y={hash:`svelte-q6hwt7`,code:`.sidebar-hide.svelte-q6hwt7 {display:block;padding:0.375rem 0.75rem;border:1px solid #e5e7eb;border-radius:0.375rem;background:#fff;color:#4b5563;font-weight:500;font-size:0.75rem;line-height:1.25;font-family:system-ui, sans-serif;cursor:pointer;}.sidebar-hide.svelte-q6hwt7:hover {background:#f3f4f6;color:#111827;}.sidebar-reopen.svelte-q6hwt7 {display:flex;z-index:50;position:fixed;bottom:5rem;left:0;align-items:center;justify-content:center;padding:0.5rem 0.25rem;border:1px solid #e5e7eb;border-left:none;border-radius:0 0.375rem 0.375rem 0;background:#fff;box-shadow:0 1px 3px 0 rgb(0 0 0 / 0.1),
2
2
  0 1px 2px -1px rgb(0 0 0 / 0.1);color:#4b5563;font-weight:500;font-size:0.6rem;font-family:system-ui, sans-serif;cursor:pointer;}.sidebar-reopen.svelte-q6hwt7:hover {background:#f3f4f6;color:#111827;}.sidebar-reopen__label.svelte-q6hwt7 {letter-spacing:0.04em;text-orientation:mixed;writing-mode:vertical-rl;}
3
3
 
4
4
  @media (prefers-color-scheme: dark) {.sidebar-hide.svelte-q6hwt7 {border-color:#4b5563;background:#1f2937;color:#d1d5db;}.sidebar-hide.svelte-q6hwt7:hover {background:#374151;color:#f3f4f6;}.sidebar-reopen.svelte-q6hwt7 {border-color:#4b5563;background:#1f2937;color:#d1d5db;}.sidebar-reopen.svelte-q6hwt7:hover {background:#374151;color:#f3f4f6;}
@@ -0,0 +1 @@
1
+ import{Et as e,Mt as t,at as n,ot as r,r as i,st as a,t as o,wt as s}from"./C00ruT0L.js";var c=class{constructor(e,t){this.status=e,typeof t==`string`?this.body={message:t}:t?this.body=t:this.body={message:`Error: ${e}`}}toString(){return JSON.stringify(this.body)}},l=class{constructor(e,t){this.status=e,this.location=t}},u=class extends Error{constructor(e,t,n){super(n),this.status=e,this.text=t}};new URL(`sveltekit-internal://`);function d(e,t){return e===`/`||t===`ignore`?e:t===`never`?e.endsWith(`/`)?e.slice(0,-1):e:t===`always`&&!e.endsWith(`/`)?e+`/`:e}function f(e){return e.split(`%25`).map(decodeURI).join(`%25`)}function p(e){for(let t in e)e[t]=decodeURIComponent(e[t]);return e}function m({href:e}){return e.split(`#`)[0]}function h(e,t,n,r=!1){let i=new URL(e);Object.defineProperty(i,`searchParams`,{value:new Proxy(i.searchParams,{get(e,r){if(r===`get`||r===`getAll`||r===`has`)return(t,...i)=>(n(t),e[r](t,...i));t();let i=Reflect.get(e,r);return typeof i==`function`?i.bind(e):i}}),enumerable:!0,configurable:!0});let a=[`href`,`pathname`,`search`,`toString`,`toJSON`];r&&a.push(`hash`);for(let n of a)Object.defineProperty(i,n,{get(){return t(),e[n]},enumerable:!0,configurable:!0});return i}function g(...e){let t=5381;for(let n of e)if(typeof n==`string`){let e=n.length;for(;e;)t=t*33^n.charCodeAt(--e)}else if(ArrayBuffer.isView(n)){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength),r=e.length;for(;r;)t=t*33^e[--r]}else throw TypeError(`value must be a string or TypedArray`);return(t>>>0).toString(36)}new TextEncoder,new TextDecoder;function _(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var ee=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||`GET`)!==`GET`&&v.delete(b(e)),ee(e,t));var v=new Map;function y(e,t){let n=b(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:e,...t}=JSON.parse(r.textContent),i=r.getAttribute(`data-ttl`);return i&&v.set(n,{body:e,init:t,ttl:1e3*Number(i)}),r.getAttribute(`data-b64`)!==null&&(e=_(e)),Promise.resolve(new Response(e,t))}return window.fetch(e,t)}function te(e,t,n){if(v.size>0){let t=b(e,n),r=v.get(t);if(r){if(performance.now()<r.ttl&&[`default`,`force-cache`,`only-if-cached`,void 0].includes(n?.cache))return new Response(r.body,r.init);v.delete(t)}}return window.fetch(t,n)}function b(e,t){let n=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){let e=[];t.headers&&e.push([...new Headers(t.headers)].join(`,`)),t.body&&(typeof t.body==`string`||ArrayBuffer.isView(t.body))&&e.push(t.body),n+=`[data-hash="${g(...e)}"]`}return n}var ne=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;function re(e){let t=[];return{pattern:e===`/`?/^\/$/:RegExp(`^${ae(e).map(e=>{let n=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(e);if(n)return t.push({name:n[1],matcher:n[2],optional:!1,rest:!0,chained:!0}),`(?:/([^]*))?`;let r=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(e);if(r)return t.push({name:r[1],matcher:r[2],optional:!0,rest:!1,chained:!0}),`(?:/([^/]+))?`;if(!e)return;let i=e.split(/\[(.+?)\](?!\])/);return`/`+i.map((e,n)=>{if(n%2){if(e.startsWith(`x+`))return se(String.fromCharCode(parseInt(e.slice(2),16)));if(e.startsWith(`u+`))return se(String.fromCharCode(...e.slice(2).split(`-`).map(e=>parseInt(e,16))));let[,r,a,o,s]=ne.exec(e);return t.push({name:o,matcher:s,optional:!!r,rest:!!a,chained:a?n===1&&i[0]===``:!1}),a?`([^]*?)`:r?`([^/]*)?`:`([^/]+?)`}return se(e)}).join(``)}).join(``)}/?$`),params:t}}function ie(e){return e!==``&&!/^\([^)]+\)$/.test(e)}function ae(e){return e.slice(1).split(`/`).filter(ie)}function oe(e,t,n){let r={},i=e.slice(1),a=i.filter(e=>e!==void 0),o=0;for(let e=0;e<t.length;e+=1){let s=t[e],c=i[e-o];if(s.chained&&s.rest&&o&&(c=i.slice(e-o,e+1).filter(e=>e).join(`/`),o=0),c===void 0)if(s.rest)c=``;else continue;if(!s.matcher||n[s.matcher](c)){r[s.name]=c;let n=t[e+1],l=i[e+1];n&&!n.rest&&n.optional&&l&&s.chained&&(o=0),!n&&!l&&Object.keys(r).length===a.length&&(o=0);continue}if(s.optional&&s.chained){o++;continue}return}if(!o)return r}function se(e){return e.normalize().replace(/[[\]]/g,`\\$&`).replace(/%/g,`%25`).replace(/\//g,`%2[Ff]`).replace(/\?/g,`%3[Ff]`).replace(/#/g,`%23`).replace(/[.*+?^${}()|\\]/g,`\\$&`)}function ce({nodes:e,server_loads:t,dictionary:n,matchers:r}){let i=new Set(t);return Object.entries(n).map(([t,[n,i,s]])=>{let{pattern:c,params:l}=re(t),u={id:t,exec:e=>{let t=c.exec(e);if(t)return oe(t,l,r)},errors:[1,...s||[]].map(t=>e[t]),layouts:[0,...i||[]].map(o),leaf:a(n)};return u.errors.length=u.layouts.length=Math.max(u.errors.length,u.layouts.length),u});function a(t){let n=t<0;return n&&(t=~t),[n,e[t]]}function o(t){return t===void 0?t:[i.has(t),e[t]]}}function le(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function ue(e,t,n=JSON.stringify){let r=n(t);try{sessionStorage[e]=r}catch{}}var x=globalThis.__sveltekit_ueip3m?.base??`/configurator`,de=globalThis.__sveltekit_ueip3m?.assets??x??``,fe=`1780471773329`,pe=`sveltekit:snapshot`,me=`sveltekit:scroll`,he=`sveltekit:states`,S=`sveltekit:history`,C=`sveltekit:navigation`,w={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},ge=location.origin;function _e(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){let e=document.getElementsByTagName(`base`);t=e.length?e[0].href:document.URL}return new URL(e,t)}function T(){return{x:pageXOffset,y:pageYOffset}}function E(e,t){return e.getAttribute(`data-sveltekit-${t}`)}var ve={...w,"":w.hover};function ye(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function be(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()===`A`&&e.hasAttribute(`href`))return e;e=ye(e)}}function xe(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){let e=location.hash.split(`#`)[1]||`/`;r.hash=`#${e}${r.hash}`}}catch{}let i=e instanceof SVGAElement?e.target.baseVal:e.target,a=!r||!!i||O(r,t,n)||(e.getAttribute(`rel`)||``).split(/\s+/).includes(`external`),o=r?.origin===ge&&e.hasAttribute(`download`);return{url:r,external:a,target:i,download:o}}function D(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=e;for(;s&&s!==document.documentElement;)r===null&&(r=E(s,`preload-code`)),i===null&&(i=E(s,`preload-data`)),t===null&&(t=E(s,`keepfocus`)),n===null&&(n=E(s,`noscroll`)),a===null&&(a=E(s,`reload`)),o===null&&(o=E(s,`replacestate`)),s=ye(s);function c(e){switch(e){case``:case`true`:return!0;case`off`:case`false`:return!1;default:return}}return{preload_code:ve[r??`off`],preload_data:ve[i??`off`],keepfocus:c(t),noscroll:c(n),reload:c(a),replace_state:c(o)}}function Se(e){let n=t(e),r=!0;function i(){r=!0,n.update(e=>e)}function a(e){r=!1,n.set(e)}function o(e){let t;return n.subscribe(n=>{(t===void 0||r&&n!==t)&&e(t=n)})}return{notify:i,set:a,subscribe:o}}var Ce={v:()=>{}};function we(){let{set:e,subscribe:n}=t(!1);async function r(){clearTimeout(void 0);try{let t=await fetch(`${de}/_app/version.json`,{headers:{pragma:`no-cache`,"cache-control":`no-cache`}});if(!t.ok)return!1;let n=(await t.json()).version!==fe;return n&&(e(!0),Ce.v(),clearTimeout(void 0)),n}catch{return!1}}return{subscribe:n,check:r}}function O(e,t,n){return e.origin!==ge||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function Te(e){}var Ee=new Set([`load`,`prerender`,`csr`,`ssr`,`trailingSlash`,`config`]);new Set([...Ee,`entries`]);var De=new Set([...Ee]);new Set([...De,`actions`,`entries`]);function Oe(e){return e.filter(e=>e!=null)}function ke(e){return e instanceof c||e instanceof u?e.status:500}function Ae(e){return e instanceof u?e.text:`Internal Error`}var k,A,j,je=i.toString().includes(`$$`)||/function \w+\(\) \{\}/.test(i.toString()),Me=`a:`;je?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(Me)},A={current:null},j={current:!1}):(k=new class{#e=e({});get data(){return n(this.#e)}set data(e){s(this.#e,e)}#t=e(null);get form(){return n(this.#t)}set form(e){s(this.#t,e)}#n=e(null);get error(){return n(this.#n)}set error(e){s(this.#n,e)}#r=e({});get params(){return n(this.#r)}set params(e){s(this.#r,e)}#i=e({id:null});get route(){return n(this.#i)}set route(e){s(this.#i,e)}#a=e({});get state(){return n(this.#a)}set state(e){s(this.#a,e)}#o=e(-1);get status(){return n(this.#o)}set status(e){s(this.#o,e)}#s=e(new URL(Me));get url(){return n(this.#s)}set url(e){s(this.#s,e)}},A=new class{#e=e(null);get current(){return n(this.#e)}set current(e){s(this.#e,e)}},j=new class{#e=e(!1);get current(){return n(this.#e)}set current(e){s(this.#e,e)}},Ce.v=()=>j.current=!0);function Ne(e){Object.assign(k,e)}var Pe={spanContext(){return Fe},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this},addLink(){return this},addLinks(){return this}},Fe={traceId:``,spanId:``,traceFlags:0},{onMount:Ie,tick:Le}=o,Re=new Set([`icon`,`shortcut icon`,`apple-touch-icon`]),M=null,N=le(`sveltekit:scroll`)??{},P=le(`sveltekit:snapshot`)??{},F={url:Se({}),page:Se({}),navigating:t(null),updated:we()};function ze(e){N[e]=T()}function Be(e,t){let n=e+1;for(;N[n];)delete N[n],n+=1;for(n=t+1;P[n];)delete P[n],n+=1}function I(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(()=>{})}async function Ve(){if(`serviceWorker`in navigator){let e=await navigator.serviceWorker.getRegistration(x||`/`);e&&await e.update()}}function He(){}var Ue,We,L,R,Ge,z,B=[],V=[],H=null;function Ke(){H?.fork?.then(e=>e?.discard()),H=null}var U=new Map,qe=new Set,Je=new Set,W=new Set,G={branch:[],error:null,url:null,nav:null},Ye=!1,K=!1,Xe=!0,q=!1,J=!1,Ze=!1,Qe=!1,$e,Y,X,Z,et=new Set,tt=new Map;async function nt(e,t,n){globalThis.__sveltekit_ueip3m?.data&&globalThis.__sveltekit_ueip3m.data,document.URL!==location.href&&(location.href=location.href),z=e,await e.hooks.init?.(),Ue=ce(e),R=document.documentElement,Ge=t,We=e.nodes[0],L=e.nodes[1],We(),L(),Y=history.state?.[S],X=history.state?.[C],Y||(Y=X=Date.now(),history.replaceState({...history.state,[S]:Y,[C]:X},``));let r=N[Y];function i(){r&&(history.scrollRestoration=`manual`,scrollTo(r.x,r.y))}n?(i(),await jt(Ge,n)):(await Q({type:`enter`,url:_e(z.hash?Lt(new URL(location.href)):location.href),replace_state:!0}),i()),At()}function rt(){B.length=0,Qe=!1}function it(e){V.some(e=>e?.snapshot)&&(P[e]=V.map(e=>e?.snapshot?.capture()))}function at(e){P[e]?.forEach((e,t)=>{V[t]?.snapshot?.restore(e)})}function ot(){ze(Y),ue(me,N),it(X),ue(pe,P)}async function st(e,t,n,r){let i;t.invalidateAll&&Ke(),await Q({type:`goto`,url:_e(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:n,nav_token:r,accept:()=>{t.invalidateAll&&(Qe=!0,i=[...tt.keys()]),t.invalidate&&t.invalidate.forEach(kt)}}),t.invalidateAll&&a().then(a).then(()=>{tt.forEach(({resource:e},t)=>{i?.includes(t)&&e.refresh?.()})})}async function ct(e){if(e.id!==H?.id){Ke();let t={};et.add(t),H={id:e.id,token:t,promise:vt({...e,preload:t}).then(e=>(et.delete(t),e.type===`loaded`&&e.state.error&&Ke(),e)),fork:null}}return H.promise}async function lt(e){let t=(await St(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(e=>e[1]()))}async function ut(e,t,n){let r={params:G.params,route:{id:G.route?.id??null},url:new URL(location.href)};G={...e.state,nav:r};let i=document.querySelector(`style[data-sveltekit]`);if(i&&i.remove(),Object.assign(k,e.props.page),$e=new z.root({target:t,props:{...e.props,stores:F,components:V},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),at(X),n){let e={from:null,to:{...r,scroll:N[Y]??T()},willUnload:!1,type:`enter`,complete:Promise.resolve()};W.forEach(t=>t(e))}K=!0}async function dt({url:e,params:t,branch:n,errors:r,status:i,error:a,route:o,form:s}){let c=`never`;if(x&&(e.pathname===x||e.pathname===x+`/`))c=`always`;else for(let e of n)e?.slash!==void 0&&(c=e.slash);e.pathname=d(e.pathname,c),e.search=e.search;let l={type:`loaded`,state:{url:e,params:t,branch:n,error:a,route:o},props:{constructors:Oe(n).map(e=>e.node.component),page:It(k)}};s!==void 0&&(l.props.form=s);let u={},f=!k,p=0;for(let e=0;e<Math.max(n.length,G.branch.length);e+=1){let t=n[e],r=G.branch[e];t?.data!==r?.data&&(f=!0),t&&(u={...u,...t.data},f&&(l.props[`data_${p}`]=u),p+=1)}return(!G.url||e.href!==G.url.href||G.error!==a||s!==void 0&&s!==k.form||f)&&(l.props.page={error:a,params:t,route:{id:o?.id??null},state:{},status:i,url:new URL(e),form:s??null,data:f?u:k.data}),l}async function ft({loader:e,parent:t,url:n,params:r,route:i,server_data_node:a}){let o=null,s=!0,c={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();if(l.universal?.load){function e(...e){for(let t of e){let{href:e}=new URL(t,n);c.dependencies.add(e)}}let u={tracing:{enabled:!1,root:Pe,current:Pe},route:new Proxy(i,{get:(e,t)=>(s&&(c.route=!0),e[t])}),params:new Proxy(r,{get:(e,t)=>(s&&c.params.add(t),e[t])}),data:a?.data??null,url:h(n,()=>{s&&(c.url=!0)},e=>{s&&c.search_params.add(e)},z.hash),async fetch(t,r){t instanceof Request&&(r={body:t.method===`GET`||t.method===`HEAD`?void 0:await t.blob(),cache:t.cache,credentials:t.credentials,headers:[...t.headers].length>0?t?.headers:void 0,integrity:t.integrity,keepalive:t.keepalive,method:t.method,mode:t.mode,redirect:t.redirect,referrer:t.referrer,referrerPolicy:t.referrerPolicy,signal:t.signal,...r});let{resolved:i,promise:a}=pt(t,r,n);return s&&e(i.href),a},setHeaders:()=>{},depends:e,parent(){return s&&(c.parent=!0),t()},untrack(e){s=!1;try{return e()}finally{s=!0}}};o=await l.universal.load.call(null,u)??null}return{node:l,loader:e,server:a,universal:l.universal?.load?{type:`data`,data:o,uses:c}:null,data:o??a?.data??null,slash:l.universal?.trailingSlash??a?.slash}}function pt(e,t,n){let r=e instanceof Request?e.url:e,i=new URL(r,n);return i.origin===n.origin&&(r=i.href.slice(n.origin.length)),{resolved:i,promise:K?te(r,i.href,t):y(r,t)}}function mt(e,t,n,r,i,a){if(Qe)return!0;if(!i)return!1;if(i.parent&&e||i.route&&t||i.url&&n)return!0;for(let e of i.search_params)if(r.has(e))return!0;for(let e of i.params)if(a[e]!==G.params[e])return!0;for(let e of i.dependencies)if(B.some(t=>t(new URL(e))))return!0;return!1}function ht(e,t){return e?.type===`data`?e:e?.type===`skip`?t??null:null}function gt(e,t){if(!e)return new Set(t.searchParams.keys());let n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(let r of n){let i=e.searchParams.getAll(r),a=t.searchParams.getAll(r);i.every(e=>a.includes(e))&&a.every(e=>i.includes(e))&&n.delete(r)}return n}function _t({error:e,url:t,route:n,params:r}){return{type:`loaded`,state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:It(k),constructors:[]}}}async function vt({id:e,invalidating:t,url:n,params:r,route:i,preload:a}){if(H?.id===e)return et.delete(H.token),H.promise;let{errors:o,layouts:s,leaf:u}=i,d=[...s,u];o.forEach(e=>e?.().catch(()=>{})),d.forEach(e=>e?.[1]().catch(()=>{}));let f=G.url?e!==wt(G.url):!1,p=G.route?i.id!==G.route.id:!1,m=gt(G.url,n),h=!1,g=d.map(async(e,t)=>{if(!e)return;let a=G.branch[t];return e[1]===a?.loader&&!mt(h,p,f,m,a.universal?.uses,r)?a:(h=!0,ft({loader:e[1],url:n,params:r,route:i,parent:async()=>{let e={};for(let n=0;n<t;n+=1)Object.assign(e,(await g[n])?.data);return e},server_data_node:ht(e[0]?{type:`skip`}:null,e[0]?a?.server:void 0)}))});for(let e of g)e.catch(()=>{});let _=[];for(let e=0;e<d.length;e+=1)if(d[e])try{_.push(await g[e])}catch(t){if(t instanceof l)return{type:`redirect`,location:t.location};if(et.has(a))return _t({error:await $(t,{params:r,url:n,route:{id:i.id}}),url:n,params:r,route:i});let s=ke(t),u;if((void 0)?.includes(t))s=t.status??s,u=t.error;else if(t instanceof c)u=t.body;else{if(await F.updated.check())return await Ve(),await I(n);u=await $(t,{params:r,url:n,route:{id:i.id}})}let d=await yt(e,_,o);return d?dt({url:n,params:r,branch:_.slice(0,d.idx).concat(d.node),errors:o,status:s,error:u,route:i}):await Et(n,{id:i.id},u,s)}else _.push(void 0);return dt({url:n,params:r,branch:_,errors:o,status:200,error:null,route:i,form:t?void 0:null})}async function yt(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)--r;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function bt({status:e,error:t,url:n,route:r}){let i={};try{return dt({url:n,params:i,branch:[await ft({loader:We,url:n,params:i,route:r,parent:()=>Promise.resolve({}),server_data_node:ht(null)}),{node:await L(),loader:L,universal:null,server:null,data:null}],status:e,error:t,errors:[],route:null})}catch(e){if(e instanceof l)return st(new URL(e.location,location.href),{},0);throw e}}async function xt(e){let t=e.href;if(U.has(t))return U.get(t);let n;try{let r=(async()=>{let t=await z.hooks.reroute({url:new URL(e),fetch:async(t,n)=>pt(t,n,e).promise})??e;if(typeof t==`string`){let n=new URL(e);z.hash?n.hash=t:n.pathname=t,t=n}return t})();U.set(t,r),n=await r}catch{U.delete(t);return}return n}async function St(e,t){if(e&&!O(e,x,z.hash)){let n=await xt(e);if(!n)return;let r=Ct(n);for(let n of Ue){let i=n.exec(r);if(i)return{id:wt(e),invalidating:t,route:n,params:p(i),url:e}}}}function Ct(e){return f(z.hash?e.hash.replace(/^#/,``).replace(/[?#].+/,``):e.pathname.slice(x.length))||`/`}function wt(e){return(z.hash?e.hash.replace(/^#/,``):e.pathname)+e.search}function Tt({url:e,type:t,intent:n,delta:r,event:i,scroll:a}){let o=!1,s=Ft(G,n,e,t,a??null);r!==void 0&&(s.navigation.delta=r),i!==void 0&&(s.navigation.event=i);let c={...s.navigation,cancel:()=>{o=!0,s.reject(Error(`navigation cancelled`))}};return q||qe.forEach(e=>e(c)),o?null:s}async function Q({type:e,url:t,popped:n,keepfocus:i,noscroll:o,replace_state:s,state:c={},redirect_count:l=0,nav_token:d={},accept:f=He,block:p=He,event:m}){let h=Z;Z=d;let g=await St(t,!1),_=e===`enter`?Ft(G,g,t,e):Tt({url:t,type:e,delta:n?.delta,intent:g,scroll:n?.scroll,event:m});if(!_){p(),Z===d&&(Z=h);return}let ee=Y,v=X;f(),q=!0,K&&_.navigation.type!==`enter`&&F.navigating.set(A.current=_.navigation);let y=g&&await vt(g);if(!y){if(O(t,x,z.hash))return await I(t,s);y=await Et(t,{id:null},await $(new u(404,`Not Found`,`Not found: ${t.pathname}`),{url:t,params:{},route:{id:null}}),404,s)}if(t=g?.url||t,Z!==d)return _.reject(Error(`navigation aborted`)),!1;if(y.type===`redirect`){if(l<20){await Q({type:e,url:new URL(y.location,t),popped:n,keepfocus:i,noscroll:o,replace_state:s,state:c,redirect_count:l+1,nav_token:d}),_.fulfil(void 0);return}y=await bt({status:500,error:await $(Error(`Redirect loop`),{url:t,params:{},route:{id:null}}),url:t,route:{id:null}})}else y.props.page.status>=400&&await F.updated.check()&&(await Ve(),await I(t,s));if(rt(),ze(ee),it(v),y.props.page.url.pathname!==t.pathname&&(t.pathname=y.props.page.url.pathname),c=n?n.state:c,!n){let e=s?0:1,n={[S]:Y+=e,[C]:X+=e,[he]:c};(s?history.replaceState:history.pushState).call(history,n,``,t),s||Be(Y,X)}let te=g&&H?.id===g.id?H.fork:null;H=null,y.props.page.state=c;let b;if(K){let e=(await Promise.all(Array.from(Je,e=>e(_.navigation)))).filter(e=>typeof e==`function`);if(e.length>0){function t(){e.forEach(e=>{W.delete(e)})}e.push(t),e.forEach(e=>{W.add(e)})}let n=_.navigation.to;G={...y.state,nav:{params:n.params,route:n.route,url:n.url}},y.props.page&&(y.props.page.url=t);let i=te&&await te;i?b=i.commit():(M=null,$e.$set(y.props),M&&Object.assign(y.props.page,M),Ne(y.props.page),b=r?.()),Ze=!0}else await ut(y,Ge,!1);let{activeElement:ne}=document;await b,await a(),await a();let re=null;if(Xe){let e=n?n.scroll:o?T():null;e?scrollTo(e.x,e.y):(re=t.hash&&document.getElementById(Rt(t)))?re.scrollIntoView():scrollTo(0,0)}let ie=document.activeElement!==ne&&document.activeElement!==document.body;!i&&!ie&&Pt(t,!re),Xe=!0,y.props.page&&(M&&Object.assign(y.props.page,M),Object.assign(k,y.props.page)),q=!1,e===`popstate`&&at(X),_.fulfil(void 0),_.navigation.to&&(_.navigation.to.scroll=T()),W.forEach(e=>e(_.navigation)),F.navigating.set(A.current=null)}async function Et(e,t,n,r,i){return e.origin===ge&&e.pathname===location.pathname&&!Ye?await bt({status:r,error:n,url:e,route:t}):await I(e,i)}function Dt(){let e,t={element:void 0,href:void 0},n;R.addEventListener(`mousemove`,t=>{let n=t.target;clearTimeout(e),e=setTimeout(()=>{a(n,w.hover)},20)});function r(e){e.defaultPrevented||a(e.composedPath()[0],w.tap)}R.addEventListener(`mousedown`,r),R.addEventListener(`touchstart`,r,{passive:!0});let i=new IntersectionObserver(e=>{for(let t of e)t.isIntersecting&&(lt(new URL(t.target.href)),i.unobserve(t.target))},{threshold:0});async function a(e,r){let i=be(e,R),a=i===t.element&&i?.href===t.href&&r>=n;if(!i||a)return;let{url:o,external:s,download:c}=xe(i,x,z.hash);if(s||c)return;let l=D(i),u=o&&wt(G.url)===wt(o);if(!(l.reload||u))if(r<=l.preload_data){t={element:i,href:i.href},n=w.tap;let e=await St(o,!1);if(!e)return;ct(e)}else r<=l.preload_code&&(t={element:i,href:i.href},n=r,lt(o))}function o(){i.disconnect();for(let e of R.querySelectorAll(`a`)){let{url:t,external:n,download:r}=xe(e,x,z.hash);if(n||r)continue;let a=D(e);a.reload||(a.preload_code===w.viewport&&i.observe(e),a.preload_code===w.eager&&lt(t))}}W.add(o),o()}function $(e,t){if(e instanceof c)return e.body;let n=ke(e),r=Ae(e);return z.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function Ot(e,t={}){return e=new URL(_e(e)),e.origin===ge?st(e,t,0):Promise.reject(Error(`goto: invalid URL`))}function kt(e){if(typeof e==`function`)B.push(e);else{let{href:t}=new URL(e,location.href);B.push(e=>e.href===t)}}function At(){history.scrollRestoration=`manual`,addEventListener(`beforeunload`,e=>{let t=!1;if(ot(),!q){let e=Ft(G,void 0,null,`leave`),n={...e.navigation,cancel:()=>{t=!0,e.reject(Error(`navigation cancelled`))}};qe.forEach(e=>e(n))}t?(e.preventDefault(),e.returnValue=``):history.scrollRestoration=`auto`}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&ot()}),navigator.connection?.saveData||Dt(),R.addEventListener(`click`,async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;let n=be(t.composedPath()[0],R);if(!n)return;let{url:r,external:i,target:a,download:o}=xe(n,x,z.hash);if(!r)return;if(a===`_parent`||a===`_top`){if(window.parent!==window)return}else if(a&&a!==`_self`)return;let s=D(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&!(r.protocol===`https:`||r.protocol===`http:`)||o)return;let[c,l]=(z.hash?r.hash.replace(/^#/,``):r.href).split(`#`),u=c===m(location);if(i||s.reload&&(!u||!l)){Tt({url:r,type:`link`,event:t})?q=!0:t.preventDefault();return}if(l!==void 0&&u){let[,i]=G.url.href.split(`#`);if(i===l){if(t.preventDefault(),l===``||l===`top`&&n.ownerDocument.getElementById(`top`)===null)scrollTo({top:0});else{let e=n.ownerDocument.getElementById(decodeURIComponent(l));e&&(e.scrollIntoView(),e.focus())}return}if(J=!0,ze(Y),e(r),!s.replace_state)return;J=!1}t.preventDefault(),await new Promise(e=>{requestAnimationFrame(()=>{setTimeout(e,0)}),setTimeout(e,100)}),await Q({type:`link`,url:r,keepfocus:s.keepfocus,noscroll:s.noscroll,replace_state:s.replace_state??r.href===location.href,event:t})}),R.addEventListener(`submit`,e=>{if(e.defaultPrevented)return;let t=HTMLFormElement.prototype.cloneNode.call(e.target),n=e.submitter;if((n?.formTarget||t.target)===`_blank`||(n?.formMethod||t.method)!==`get`)return;let r=new URL(n?.hasAttribute(`formaction`)&&n?.formAction||t.action);if(O(r,x,!1))return;let i=e.target,a=D(i);if(a.reload)return;e.preventDefault(),e.stopPropagation();let o=new FormData(i,n);r.search=new URLSearchParams(o).toString(),Q({type:`form`,url:r,keepfocus:a.keepfocus,noscroll:a.noscroll,replace_state:a.replace_state??r.href===location.href,event:e})}),addEventListener(`popstate`,async t=>{if(!Nt)if(t.state?.[`sveltekit:history`]){let n=t.state[S];if(Z={},n===Y)return;let r=N[n],i=t.state[`sveltekit:states`]??{},a=new URL(t.state[`sveltekit:pageurl`]??location.href),o=t.state[C],s=G.url?m(location)===m(G.url):!1;if(o===X&&(Ze||s)){i!==k.state&&(k.state=i),e(a),N[Y]=T(),r&&scrollTo(r.x,r.y),Y=n;return}let c=n-Y;await Q({type:`popstate`,url:a,popped:{state:i,scroll:r,delta:c},accept:()=>{Y=n,X=o},block:()=>{history.go(-c)},nav_token:Z,event:t})}else J||(e(new URL(location.href)),z.hash&&location.reload())}),addEventListener(`hashchange`,()=>{J&&(J=!1,history.replaceState({...history.state,[S]:++Y,[C]:X},``,location.href))});for(let e of document.querySelectorAll(`link`))Re.has(e.rel)&&(e.href=e.href);addEventListener(`pageshow`,e=>{e.persisted&&F.navigating.set(A.current=null)});function e(e){G.url=k.url=e,F.page.set(It(k)),F.page.notify()}}async function jt(e,{status:t=200,error:n,node_ids:r,params:i,route:a,server_route:o,data:s,form:c}){Ye=!0;let u=new URL(location.href),d;({params:i={},route:a={id:null}}=await St(u,!1)||{}),d=Ue.find(({id:e})=>e===a.id);let f,p=!0;try{let e=r.map(async(t,n)=>{let r=s[n];return r?.uses&&(r.uses=Mt(r.uses)),ft({loader:z.nodes[t],url:u,params:i,route:a,parent:async()=>{let t={};for(let r=0;r<n;r+=1)Object.assign(t,(await e[r]).data);return t},server_data_node:ht(r)})}),o=await Promise.all(e);if(d){let e=d.layouts;for(let t=0;t<e.length;t++)e[t]||o.splice(t,0,void 0)}f=await dt({url:u,params:i,branch:o,status:t,error:n,errors:d?.errors,form:c,route:d??null})}catch(t){if(t instanceof l){await I(new URL(t.location,location.href));return}f=await bt({status:ke(t),error:await $(t,{url:u,params:i,route:a}),url:u,route:a}),e.textContent=``,p=!1}f.props.page&&(f.props.page.state={}),await ut(f,e,p)}function Mt(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}var Nt=!1;function Pt(e,t=!0){let n=document.querySelector(`[autofocus]`);if(n)n.focus();else{let n=Rt(e);if(n&&document.getElementById(n)){let{x:r,y:i}=T();setTimeout(()=>{let a=history.state;Nt=!0,location.replace(new URL(`#${n}`,location.href)),history.replaceState(a,``,e),t&&scrollTo(r,i),Nt=!1})}else{let e=document.body,t=e.getAttribute(`tabindex`);e.tabIndex=-1,e.focus({preventScroll:!0,focusVisible:!1}),t===null?e.removeAttribute(`tabindex`):e.setAttribute(`tabindex`,t)}let r=getSelection();if(r&&r.type!==`None`){let e=[];for(let t=0;t<r.rangeCount;t+=1)e.push(r.getRangeAt(t));setTimeout(()=>{if(r.rangeCount===e.length){for(let t=0;t<r.rangeCount;t+=1){let n=e[t],i=r.getRangeAt(t);if(n.commonAncestorContainer!==i.commonAncestorContainer||n.startContainer!==i.startContainer||n.endContainer!==i.endContainer||n.startOffset!==i.startOffset||n.endOffset!==i.endOffset)return}r.removeAllRanges()}})}}}function Ft(e,t,n,r,i=null){let a,o,s=new Promise((e,t)=>{a=e,o=t});return s.catch(()=>{}),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:T()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:i},willUnload:!t,type:r,complete:s},fulfil:a,reject:o}}function It(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function Lt(e){let t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function Rt(e){let t;if(z.hash){let[,,n]=e.hash.split(`#`,3);t=n??``}else t=e.hash.slice(1);return decodeURIComponent(t)}export{k as a,A as i,nt as n,j as o,F as r,Te as s,Ot as t};
@@ -1 +1 @@
1
- import{Gt as e,It as t,Lt as n,Ot as r,at as i,c as a,i as o,jt as s,o as c}from"./C00ruT0L.js";import"./Bo0U8J3e.js";import"./CFKVnMbq.js";import"./DV91TmsB.js";import"./DFBUyDYh.js";import"./MRyhzcyW.js";import"./EDJuo58-.js";import"./CX0dfddQ.js";import"./DUr69vGU.js";import{t as l}from"./Db3xJ3R_.js";import{t as u}from"./BmUm-Ak4.js";function d(o,d){n(d,!0);let f=c(d,`onclick`,7),p=c(d,`buttonClass`,7),m=c(d,`buttonStyle`,7),h=c(d,`apiUrl`,7),g=c(d,`forceTheme`,7),_=c(d,`lang`,7),v=r(()=>({onclick:f(),buttonClass:p(),buttonStyle:m(),apiUrl:h(),forceTheme:g(),lang:_()}));return u(o,{silent:!0,body:(t,n=e)=>{l(t,a({host:d.$$host,get onError(){return n()}},()=>i(v)))},$$slots:{body:!0}}),t({get onclick(){return f()},set onclick(e){f(e),s()},get buttonClass(){return p()},set buttonClass(e){p(e),s()},get buttonStyle(){return m()},set buttonStyle(e){m(e),s()},get apiUrl(){return h()},set apiUrl(e){h(e),s()},get forceTheme(){return g()},set forceTheme(e){g(e),s()},get lang(){return _()},set lang(e){_(e),s()}})}customElements.define(`liipgpt-button`,o(d,{forceTheme:{attribute:`force-theme`,type:`String`},buttonClass:{attribute:`button-class`,type:`String`},buttonStyle:{attribute:`button-style`,type:`String`},apiUrl:{attribute:`api-url`,type:`String`},lang:{attribute:`lang`,type:`String`},onclick:{}},[],[],{mode:`open`}));export{d as LiipGPTButton};
1
+ import{Gt as e,It as t,Lt as n,Ot as r,at as i,c as a,i as o,jt as s,o as c}from"./C00ruT0L.js";import"./Bo0U8J3e.js";import"./CFKVnMbq.js";import"./DV91TmsB.js";import"./DFBUyDYh.js";import"./MRyhzcyW.js";import"./BpIo1_hS.js";import"./CX0dfddQ.js";import"./BgnzWwt-.js";import{t as l}from"./BdBqI4to.js";import{t as u}from"./BmUm-Ak4.js";function d(o,d){n(d,!0);let f=c(d,`onclick`,7),p=c(d,`buttonClass`,7),m=c(d,`buttonStyle`,7),h=c(d,`apiUrl`,7),g=c(d,`forceTheme`,7),_=c(d,`lang`,7),v=r(()=>({onclick:f(),buttonClass:p(),buttonStyle:m(),apiUrl:h(),forceTheme:g(),lang:_()}));return u(o,{silent:!0,body:(t,n=e)=>{l(t,a({host:d.$$host,get onError(){return n()}},()=>i(v)))},$$slots:{body:!0}}),t({get onclick(){return f()},set onclick(e){f(e),s()},get buttonClass(){return p()},set buttonClass(e){p(e),s()},get buttonStyle(){return m()},set buttonStyle(e){m(e),s()},get apiUrl(){return h()},set apiUrl(e){h(e),s()},get forceTheme(){return g()},set forceTheme(e){g(e),s()},get lang(){return _()},set lang(e){_(e),s()}})}customElements.define(`liipgpt-button`,o(d,{forceTheme:{attribute:`force-theme`,type:`String`},buttonClass:{attribute:`button-class`,type:`String`},buttonStyle:{attribute:`button-style`,type:`String`},apiUrl:{attribute:`api-url`,type:`String`},lang:{attribute:`lang`,type:`String`},onclick:{}},[],[],{mode:`open`}));export{d as LiipGPTButton};
@@ -1 +1 @@
1
- import"./C00ruT0L.js";import{a as e,i as t,r as n}from"./CKDKLu5Y.js";var r={get data(){return e.data},get error(){return e.error},get form(){return e.form},get params(){return e.params},get route(){return e.route},get state(){return e.state},get status(){return e.status},get url(){return e.url}};Object.defineProperty({get from(){return t.current?t.current.from:null},get to(){return t.current?t.current.to:null},get type(){return t.current?t.current.type:null},get willUnload(){return t.current?t.current.willUnload:null},get delta(){return t.current?t.current.delta:null},get complete(){return t.current?t.current.complete:null}},`current`,{get(){throw Error(`Replace navigating.current.<prop> with navigating.<prop>`)}}),n.updated.check;var i=r;export{i as t};
1
+ import"./C00ruT0L.js";import{a as e,i as t,r as n}from"./DABlUYYh.js";var r={get data(){return e.data},get error(){return e.error},get form(){return e.form},get params(){return e.params},get route(){return e.route},get state(){return e.state},get status(){return e.status},get url(){return e.url}};Object.defineProperty({get from(){return t.current?t.current.from:null},get to(){return t.current?t.current.to:null},get type(){return t.current?t.current.type:null},get willUnload(){return t.current?t.current.willUnload:null},get delta(){return t.current?t.current.delta:null},get complete(){return t.current?t.current.complete:null}},`current`,{get(){throw Error(`Replace navigating.current.<prop> with navigating.<prop>`)}}),n.updated.check;var i=r;export{i as t};