@liforma/client 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/next/index.js +676 -565
- package/dist/next/index.js.map +1 -1
- package/dist/next/next/createLiformaSessionRouteHandler.d.ts +0 -1
- package/dist/next/next/createLiformaSessionRouteHandler.d.ts.map +1 -1
- package/dist/next/react/ExperienceThumbnail.d.ts +1 -0
- package/dist/next/react/ExperienceThumbnail.d.ts.map +1 -1
- package/dist/next/thumbnail/styles.d.ts.map +1 -1
- package/dist/next/thumbnail/toGalleryThumbUrl.d.ts.map +1 -1
- package/dist/next/thumbnail/types.d.ts +2 -0
- package/dist/next/thumbnail/types.d.ts.map +1 -1
- package/dist/next/v2/api/mintPublicSession.d.ts +2 -2
- package/dist/next/v2/api/mintPublicSession.d.ts.map +1 -1
- package/dist/next/v2/api/sessionEndpointRequest.d.ts +2 -2
- package/dist/next/v2/api/sessionEndpointRequest.d.ts.map +1 -1
- package/dist/next/v2/embed/iframeHost.d.ts +1 -3
- package/dist/next/v2/embed/iframeHost.d.ts.map +1 -1
- package/dist/next/v2/errors/LiformaError.d.ts +23 -0
- package/dist/next/v2/errors/LiformaError.d.ts.map +1 -0
- package/dist/next/v2/experience.d.ts +7 -9
- package/dist/next/v2/experience.d.ts.map +1 -1
- package/dist/next/v2/experienceEvents.d.ts +21 -15
- package/dist/next/v2/experienceEvents.d.ts.map +1 -1
- package/dist/next/v2/types/sessionLaunch.d.ts +28 -5
- package/dist/next/v2/types/sessionLaunch.d.ts.map +1 -1
- package/dist/next/v2/types/sessionManifest.d.ts +8 -0
- package/dist/next/v2/types/sessionManifest.d.ts.map +1 -1
- package/dist/next/widget/mountExperienceWidget.d.ts.map +1 -1
- package/dist/npm/index.js +585 -472
- package/dist/npm/index.js.map +1 -1
- package/dist/npm/thumbnail/styles.d.ts.map +1 -1
- package/dist/npm/thumbnail/toGalleryThumbUrl.d.ts.map +1 -1
- package/dist/npm/thumbnail/types.d.ts +2 -0
- package/dist/npm/thumbnail/types.d.ts.map +1 -1
- package/dist/npm/v2/api/mintPublicSession.d.ts +2 -2
- package/dist/npm/v2/api/mintPublicSession.d.ts.map +1 -1
- package/dist/npm/v2/api/sessionEndpointRequest.d.ts +2 -2
- package/dist/npm/v2/api/sessionEndpointRequest.d.ts.map +1 -1
- package/dist/npm/v2/embed/iframeHost.d.ts +1 -3
- package/dist/npm/v2/embed/iframeHost.d.ts.map +1 -1
- package/dist/npm/v2/errors/LiformaError.d.ts +23 -0
- package/dist/npm/v2/errors/LiformaError.d.ts.map +1 -0
- package/dist/npm/v2/experience.d.ts +7 -9
- package/dist/npm/v2/experience.d.ts.map +1 -1
- package/dist/npm/v2/experienceEvents.d.ts +21 -15
- package/dist/npm/v2/experienceEvents.d.ts.map +1 -1
- package/dist/npm/v2/index.d.ts +4 -2
- package/dist/npm/v2/index.d.ts.map +1 -1
- package/dist/npm/v2/liforma-experience-thumbnail.d.ts.map +1 -1
- package/dist/npm/v2/liforma-experience-widget.d.ts.map +1 -1
- package/dist/npm/v2/npm.d.ts +5 -3
- package/dist/npm/v2/npm.d.ts.map +1 -1
- package/dist/npm/v2/types/index.d.ts +2 -2
- package/dist/npm/v2/types/index.d.ts.map +1 -1
- package/dist/npm/v2/types/sessionLaunch.d.ts +28 -5
- package/dist/npm/v2/types/sessionLaunch.d.ts.map +1 -1
- package/dist/npm/v2/types/sessionManifest.d.ts +8 -0
- package/dist/npm/v2/types/sessionManifest.d.ts.map +1 -1
- package/dist/npm/v2/types/sessionManifestSchema.d.ts +7 -0
- package/dist/npm/v2/types/sessionManifestSchema.d.ts.map +1 -1
- package/dist/npm/widget/mountExperienceWidget.d.ts.map +1 -1
- package/dist/react/component/experienceComponentLaunch.d.ts.map +1 -1
- package/dist/react/component/experienceComponentRuntime.d.ts +0 -2
- package/dist/react/component/experienceComponentRuntime.d.ts.map +1 -1
- package/dist/react/component/experienceComponentTypes.d.ts +1 -5
- package/dist/react/component/experienceComponentTypes.d.ts.map +1 -1
- package/dist/react/index.js +775 -665
- package/dist/react/index.js.map +1 -1
- package/dist/react/react/Experience.d.ts.map +1 -1
- package/dist/react/react/ExperienceThumbnail.d.ts +1 -0
- package/dist/react/react/ExperienceThumbnail.d.ts.map +1 -1
- package/dist/react/thumbnail/styles.d.ts.map +1 -1
- package/dist/react/thumbnail/toGalleryThumbUrl.d.ts.map +1 -1
- package/dist/react/thumbnail/types.d.ts +2 -0
- package/dist/react/thumbnail/types.d.ts.map +1 -1
- package/dist/react/v2/api/mintPublicSession.d.ts +2 -2
- package/dist/react/v2/api/mintPublicSession.d.ts.map +1 -1
- package/dist/react/v2/api/sessionEndpointRequest.d.ts +2 -2
- package/dist/react/v2/api/sessionEndpointRequest.d.ts.map +1 -1
- package/dist/react/v2/embed/iframeHost.d.ts +1 -3
- package/dist/react/v2/embed/iframeHost.d.ts.map +1 -1
- package/dist/react/v2/errors/LiformaError.d.ts +23 -0
- package/dist/react/v2/errors/LiformaError.d.ts.map +1 -0
- package/dist/react/v2/experience.d.ts +7 -9
- package/dist/react/v2/experience.d.ts.map +1 -1
- package/dist/react/v2/experienceEvents.d.ts +21 -15
- package/dist/react/v2/experienceEvents.d.ts.map +1 -1
- package/dist/react/v2/types/sessionLaunch.d.ts +28 -5
- package/dist/react/v2/types/sessionLaunch.d.ts.map +1 -1
- package/dist/react/v2/types/sessionManifest.d.ts +8 -0
- package/dist/react/v2/types/sessionManifest.d.ts.map +1 -1
- package/dist/react/widget/mountExperienceWidget.d.ts.map +1 -1
- package/dist/sdk/v2/client.js +36 -13
- package/dist/sdk/v2/client.js.map +1 -1
- package/dist/svelte/Experience.svelte +0 -6
- package/dist/svelte/ExperienceThumbnail.svelte +8 -1
- package/dist/svelte/ExperienceThumbnail.svelte.d.ts +1 -0
- package/package.json +3 -1
package/dist/sdk/v2/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Liforma=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(){if(globalThis.__LIFORMA_STACK===`local`)return!0;if(typeof location>`u`)return!1;try{return new URLSearchParams(location.search).get(`stack`)===`local`}catch{return!1}}var n=`https://api.liforma.ai`,r=`http://localhost:3001`;function i(){let e=globalThis.__LIFORMA_API_BASE_URL;if(e?.trim())return e.trim().replace(/\/$/,``);if(typeof document>`u`)return null;let t=(document.querySelector(`script[data-liforma-sdk][src*="client.js"]`)??document.querySelector(`script[src*="/sdk/v2/client.js"]`))?.getAttribute(`data-api-base-url`)?.trim();return t?t.replace(/\/$/,``):null}function a(){return i()||(t()?r:n)}function o(e){let t=e.locale?.trim();if(t)return t;let n=e.language?.trim();if(n)return n;if(typeof navigator<`u`&&navigator.language?.trim())return navigator.language.trim()}function s(e){let t=e.secondaryLocale?.trim(),n=e.learningLocale?.trim();if(t&&n&&t!==n)throw Error(`secondaryLocale and learningLocale disagree; pass only one or make them equal.`);return t||n||void 0}function c(e,t){let n=e.trim();if(!n)throw Error(`sessionEndpoint must not be empty.`);if(typeof location>`u`)throw Error(`sessionEndpoint is only available in a browser.`);let r=new URL(n,location.href);if(r.origin!==location.origin)throw Error(`sessionEndpoint must be same-origin.`);let i=t.experienceId.trim();if(!i)throw Error(`sessionEndpoint requires experienceId.`);let a=o(t),c=s(t);return{url:r.toString(),init:{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({experienceId:i,...a?{locale:a}:{},...c?{secondaryLocale:c}:{},...t.mode?{mode:t.mode}:{},...t.responseMode?{responseMode:t.responseMode}:{},...t.speechInputMode?{speechInputMode:t.speechInputMode}:{},...t.speechOnly===void 0?{}:{speechOnly:t.speechOnly}})}}}function l(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function u(e){return typeof e==`boolean`}function d(e){return!l(e)||!u(e.avatar)||!u(e.speechInput)||!u(e.speechOutput)||!u(e.tools)||!u(e.externalAudio)?null:{avatar:e.avatar,speechInput:e.speechInput,speechOutput:e.speechOutput,tools:e.tools,externalAudio:e.externalAudio}}function f(e){if(!l(e))throw Error(`Session Launch response is missing session.`);let t=typeof e.id==`string`?e.id.trim():``,n=typeof e.experienceId==`string`?e.experienceId.trim():``,r=typeof e.experienceRevisionId==`string`?e.experienceRevisionId.trim():``,i=typeof e.expiresAt==`string`?e.expiresAt.trim():``,a=typeof e.locale==`string`?e.locale.trim():``,o=typeof e.secondaryLocale==`string`&&e.secondaryLocale.trim()?e.secondaryLocale.trim():void 0,s=e.mode===`conversation`||e.mode===`presenter`?e.mode:null,c=d(e.capabilities);if(!t||!n||!r||!i||!a||!s||!c)throw Error(`Session Launch response has an invalid session object.`);return{id:t,experienceId:n,experienceRevisionId:r,expiresAt:i,locale:a,...o?{secondaryLocale:o}:{},mode:s,capabilities:c}}function p(e){if(!l(e))throw Error(`Session Launch response must be a JSON object.`);let t=typeof e.launch==`string`?e.launch.trim():``;if(!t)throw Error(`Session Launch response is missing launch.`);return{session:f(e.session),launch:t}}function m(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function h(e,t,n){let r;try{r=JSON.parse(n)}catch{}let i=m(),a=r?.message?.trim(),o=r?.code;if(o===`origin_not_allowed`||/^Origin not allowed/i.test(a??``)&&i){if(a&&a.includes(e)&&a.includes(`allowed origin`))return a;let t=r?.origin??i??`(unknown origin)`;return`Your origin ${t} is not an allowed origin for experience ${e}. If you own this experience, sign in to the Liforma developer portal (app.liforma.ai), open Workspace → Settings → Origins, add ${t} to the list of allowed origins, and ensure “Allow public client-only embeds” is enabled.`}return o===`browser_embeds_disabled`||/^Browser embeds are not enabled/i.test(a??``)?a&&a.includes(`Allow public client-only embeds`)?a:`Browser embeds are not enabled for experience ${e}. If you own this experience, sign in to the Liforma developer portal (app.liforma.ai), open Workspace → Settings → Origins, and enable “Allow public client-only embeds”.`:o===`experience_unavailable`||/^Experience is not available\.?$/i.test(a??``)||/^Unknown experience\.?$/i.test(a??``)?a&&a.includes(`No playable experience found`)?a:`No playable experience found for “${e}”. Check that the experience id is correct (it should look like exp_…), and that the experience exists and is published in the Liforma developer portal (app.liforma.ai). Deleted, archived, and unpublished experiences cannot be started from a browser embed.`:a||n.trim().slice(0,500)||`Browser session mint failed (${t})`}function g(e){let t=e?.locale?.trim();if(t)return t;let n=e?.language?.trim();if(n)return n;if(typeof navigator<`u`&&navigator.language?.trim())return navigator.language.trim()}function _(e){let t=e?.secondaryLocale?.trim(),n=e?.learningLocale?.trim();if(t&&n&&t!==n)throw Error(`secondaryLocale and learningLocale disagree; pass only one or make them equal.`);return t||n||void 0}function ee(e,t){let n={experienceId:e},r=g(t);r&&(n.locale=r);let i=_(t);return i&&(n.secondaryLocale=i),t?.mode&&(n.mode=t.mode),t?.responseMode&&(n.responseMode=t.responseMode),t?.speechInputMode&&(n.speechInputMode=t.speechInputMode),t?.speechOnly!==void 0&&(n.speechOnly=t.speechOnly),n}async function v(e,t){let n=a(),r=await fetch(`${n}/v1/browser-sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(ee(e,t))});if(!r.ok){let t=await r.text();throw Error(h(e,r.status,t))}let i;try{i=await r.json()}catch{throw Error(`Browser session mint returned invalid JSON.`)}return p(i)}async function y(e,t){let n=c(e,t),r=new AbortController,i=()=>r.abort(t.signal?.reason);t.signal?.aborted?i():t.signal?.addEventListener(`abort`,i,{once:!0});let a=globalThis.setTimeout(()=>r.abort(new DOMException(`Session endpoint timed out.`,`TimeoutError`)),t.timeoutMs??3e4),o;try{o=await fetch(n.url,{...n.init,signal:r.signal})}finally{globalThis.clearTimeout(a),t.signal?.removeEventListener(`abort`,i)}if(!o.ok){let e=await o.text(),t=e.slice(0,500)||`Session endpoint failed (${o.status})`;try{let n=JSON.parse(e);n.message&&(t=n.message)}catch{}throw Error(t)}if(!o.headers.get(`content-type`)?.toLowerCase().includes(`application/json`))throw Error(`Session endpoint must return a JSON Session Launch response.`);let s;try{s=await o.json()}catch{throw Error(`Session endpoint returned invalid JSON.`)}return p(s)}function b(e){return typeof e!=`object`||!e?!1:typeof e[Symbol.asyncIterator]==`function`}function x(e){if(typeof e==`string`){let t=e.trim();if(!t)throw Error(`conversationProcessor returned empty text.`);return{text:t}}let t=e.text.trim();if(!t)throw Error(`conversationProcessor returned empty text.`);return{text:t,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}}async function te(e,t){let n=await e(t);return b(n)?{kind:`stream`,stream:n}:{kind:`complete`,speech:x(n)}}var S=`3002`;function C(e){let t=new URL(e);return t.hostname===`localhost`||t.hostname===`127.0.0.1`?`Cannot connect to the Liforma player at ${e} — nothing is listening on port ${t.port||S}. Start the player dev server in player.liforma.ai (npm run dev).`:`Cannot connect to the Liforma player at ${e}. The embed did not load; check your network connection and player URL configuration.`}async function w(e,t){try{await fetch(e,{method:`GET`,mode:`no-cors`,signal:AbortSignal.timeout(8e3)})}catch{throw Error(C(t))}}function T(e,t,n,r){try{r&&r.length>0?e.postMessage(t,n,r):e.postMessage(t,n)}catch(e){throw e instanceof DOMException&&e.name===`SecurityError`?Error(C(n),{cause:e}):e}}var E=new Set([1,2]);function ne(e){return typeof e==`number`&&E.has(e)}var D=new Set([`close`,`stateUpdate`,`commandResult`,`userTranscript`,`characterSpeechStarted`,`characterSpeechEnded`,`conversationUpdate`,`listeningState`,`userSpeechStarted`,`userSpeechEnded`,`modeChange`,`activityChange`,`message`,`started`,`widgetReady`,`widgetExpand`,`widgetCollapse`,`widgetAudioSettings`,`widgetDragStart`,`widgetDragMove`,`widgetDragEnd`]);function re(e){if(!e||typeof e!=`object`)return null;let t=e;if(!ne(t.schemaVersion)||!t.type||!D.has(t.type))return null;if(t.type===`widgetReady`||t.type===`widgetExpand`||t.type===`widgetCollapse`)return t;if(t.type===`widgetAudioSettings`){let e=t.payload;return!e||typeof e!=`object`||typeof e.open!=`boolean`?null:t}if(t.type===`widgetDragStart`||t.type===`widgetDragEnd`){let e=t.payload;return!e||typeof e!=`object`||typeof e.pointerId!=`number`||!Number.isFinite(e.pointerId)?null:t}if(t.type===`widgetDragMove`){let e=t.payload;if(!e||typeof e!=`object`)return null;let{pointerId:n,dx:r,dy:i}=e;return typeof n!=`number`||!Number.isFinite(n)||typeof r!=`number`||!Number.isFinite(r)||typeof i!=`number`||!Number.isFinite(i)?null:t}return!t.payload||typeof t.payload!=`object`?null:t}function O(e,t,n){let r=e.trim();if(!r)throw Error(`createLaunchMessage requires a non-empty launch string.`);return{type:`launch`,schemaVersion:2,payload:{launch:r,...t===void 0?{}:{session:t},...n?{startButton:n}:{}}}}function k(){return{type:`parentHello`,schemaVersion:2}}function A(e){return{type:`widgetSetChrome`,schemaVersion:2,payload:{mode:e}}}function j(){return{type:`widgetToggleAudioSettings`,schemaVersion:2,payload:{}}}function M(e){return e}function N(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cmd_${crypto.randomUUID().replace(/-/g,``).slice(0,12)}`:`cmd_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}var ie=3e4;function P(e){let t=e.container;getComputedStyle(t).position===`static`&&(t.style.position=`relative`);let n=document.createElement(`iframe`);n.src=e.src,n.title=`Liforma experience`,n.setAttribute(`allow`,`microphone; autoplay; clipboard-read; clipboard-write`),n.style.cssText=e.transparent?`display:block;position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;`:`display:block;position:absolute;inset:0;width:100%;height:100%;border:0;background:#030508;`,e.transparent&&n.setAttribute(`allowtransparency`,`true`);let r=!1,i=new Map,a=new Promise((t,r)=>{let i=()=>{o(),w(e.src,e.playerOrigin).then(t,r)},a=()=>{o(),r(Error(C(e.playerOrigin)))},o=()=>{n.removeEventListener(`load`,i),n.removeEventListener(`error`,a)};n.addEventListener(`load`,i),n.addEventListener(`error`,a)}),o=t=>{if(r||t.source!==n.contentWindow||t.origin!==e.playerOrigin)return;let a=re(t.data);if(a)switch(a.type){case`close`:e.onClose?.(a.payload);break;case`stateUpdate`:e.onPlayerStatusChange?.(a.payload.state),e.onStateUpdate?.(a.payload.state);break;case`commandResult`:{let e=i.get(a.payload.correlationId);if(!e)return;i.delete(a.payload.correlationId),a.payload.ok?e.resolve(a.payload.result):e.reject(Error(a.payload.error??`Command failed.`));break}case`userTranscript`:e.onUserTranscript?.(a.payload);break;case`characterSpeechStarted`:e.onCharacterSpeechStarted?.(a.payload);break;case`characterSpeechEnded`:e.onCharacterSpeechEnded?.(a.payload);break;case`conversationUpdate`:e.onConversationUpdate?.(a.payload.conversation);break;case`listeningState`:e.onListeningState?.(a.payload.listening);break;case`userSpeechStarted`:e.onUserSpeechStarted?.(a.payload);break;case`userSpeechEnded`:e.onUserSpeechEnded?.(a.payload);break;case`modeChange`:e.onActivityChange?.(M(a.payload.mode)),e.onModeChange?.(a.payload.mode);break;case`activityChange`:e.onActivityChange?.(a.payload.activity),(a.payload.activity===`listening`||a.payload.activity===`thinking`||a.payload.activity===`speaking`)&&e.onModeChange?.(a.payload.activity);break;case`message`:e.onMessage?.(a.payload);break;case`started`:e.onStarted?.(a.payload);break;case`widgetReady`:e.onWidgetReady?.();break;case`widgetExpand`:e.onWidgetExpand?.();break;case`widgetCollapse`:e.onWidgetCollapse?.();break;case`widgetAudioSettings`:e.onWidgetAudioSettings?.(a.payload.open);break;case`widgetDragStart`:e.onWidgetDragStart?.(a.payload);break;case`widgetDragMove`:e.onWidgetDragMove?.(a.payload);break;case`widgetDragEnd`:e.onWidgetDragEnd?.(a.payload);break}};if(window.addEventListener(`message`,o),t.replaceChildren(n),t.clientHeight<2&&!t.style.minHeight){let e=getComputedStyle(t).minHeight;(e===`0px`||e===`auto`)&&(t.style.minHeight=`480px`)}let s=(t,i)=>{if(r)return;let a=n.contentWindow;if(!a)throw Error(C(e.playerOrigin));T(a,t,e.playerOrigin,i)},c=(e,t=12e4,n)=>{let r=e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload?e.payload.correlationId:N();return e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload||e.type!==`parentHello`&&e.payload&&(e.payload.correlationId=r),new Promise((a,o)=>{i.set(r,{resolve:e=>a(e),reject:o}),s(e,n),setTimeout(()=>{i.has(r)&&(i.delete(r),o(Error(`Timed out waiting for player command result.`)))},t)})};return{waitForLoad(){return a},postParentHello(){s(k())},postLaunch(t,i,a){if(r)return;let o=n.contentWindow;if(!o)throw Error(`Liforma embed iframe is not ready.`);let s=O(t,i,a),c=()=>{r||T(o,s,e.playerOrigin)};c();for(let e=1;e<=12;e+=1)window.setTimeout(c,e*75)},postManifest(e){if(typeof e==`string`){this.postLaunch(e);return}if(e&&typeof e==`object`&&typeof e.launch==`string`){let t=String(e.launch),n=e.session;this.postLaunch(t,n);return}throw Error(`postManifest is deprecated; use postLaunch with an opaque launch string from SessionLaunchResponse.`)},postWidgetSetChrome(e){s(A(e))},postWidgetToggleAudioSettings(){s(j())},speak(e){return c({type:`speak`,schemaVersion:2,payload:{correlationId:N(),text:e.text,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}})},startListening(){return c({type:`startListening`,schemaVersion:2,payload:{correlationId:N()}})},stopListening(){return c({type:`stopListening`,schemaVersion:2,payload:{correlationId:N()}})},listenOnce(e){return c({type:`listenOnce`,schemaVersion:2,payload:{correlationId:N(),...e?.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}})},async speakProcessorStream(e,t){let n=N(),r=N(),i=(await c({type:`speakStreamStart`,schemaVersion:2,payload:{correlationId:n,...t?.characterId?{characterId:t.characterId}:{},...t?.behavior?{behavior:t.behavior}:{}}})).streamId;try{for await(let n of e){if(t?.signal?.aborted)throw new DOMException(`Processor stream aborted.`,`AbortError`);n&&s({type:`speakStreamChunk`,schemaVersion:2,payload:{streamId:i,text:n}})}if(t?.signal?.aborted)throw new DOMException(`Processor stream aborted.`,`AbortError`);return await c({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch(e){try{await c({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch{}throw e}},speechPlay(e){let t=N(),n=[];return(e.source.kind===`pcm`||e.source.kind===`encoded`)&&n.push(e.source.data),c({type:`speechPlay`,schemaVersion:2,payload:{correlationId:t,source:e.source,...e.characterId?{characterId:e.characterId}:{},...e.transcript===void 0?{}:{transcript:e.transcript},...e.history?{history:e.history}:{},...e.queue?{queue:e.queue}:{}}},12e4,n)},speechUtteranceBegin(e){return c({type:`speechUtteranceBegin`,schemaVersion:2,payload:{correlationId:N(),utteranceId:e.utteranceId,format:e.format,queue:e.queue,...e.characterId?{characterId:e.characterId}:{},...e.transcript===void 0?{}:{transcript:e.transcript}}})},speechUtteranceWrite(e){return c({type:`speechUtteranceWrite`,schemaVersion:2,payload:{correlationId:N(),utteranceId:e.utteranceId,audio:e.audio,byteLength:e.byteLength}},ie,[e.audio])},speechUtteranceSetTranscript(e){return c({type:`speechUtteranceSetTranscript`,schemaVersion:2,payload:{correlationId:N(),utteranceId:e.utteranceId,transcript:e.transcript}})},speechUtteranceClose(e){return c({type:`speechUtteranceClose`,schemaVersion:2,payload:{correlationId:N(),utteranceId:e.utteranceId,...e.transcript===void 0?{}:{transcript:e.transcript},...e.history?{history:e.history}:{}}})},speechUtteranceCancel(e){return c({type:`speechUtteranceCancel`,schemaVersion:2,payload:{correlationId:N(),utteranceId:e.utteranceId}})},speechInterrupt(e){return c({type:`speechInterrupt`,schemaVersion:2,payload:{correlationId:N(),...e}})},getConversation(){return c({type:`getConversation`,schemaVersion:2,payload:{correlationId:N()}})},destroy(){if(!r){r=!0;for(let e of i.values())e.reject(Error(`Iframe host destroyed.`));i.clear(),window.removeEventListener(`message`,o),n.remove()}}}}function ae(e){let t,n=!1,r=!1,i=()=>{r||!n||t===void 0||(r=!0,e(t))};return{setValue(e){t=e,i()},markReady(){n=!0,i()}}}var oe=`https://player.liforma.ai/embed`,se=`http://localhost:3002/embed`;function F(){let e=globalThis.__LIFORMA_PLAYER_EMBED_URL;if(e?.trim())return e.trim().replace(/\/$/,``);if(typeof document>`u`)return null;let t=(document.querySelector(`script[data-liforma-sdk][src*="client.js"]`)??document.querySelector(`script[src*="/sdk/v2/client.js"]`))?.getAttribute(`data-player-embed-url`)?.trim();return t?t.replace(/\/$/,``):null}function I(){let e=F();return e?e.endsWith(`/embed`)?e:`${e}/embed`:t()?se:oe}function ce(e,t,n,r,i,a,o){let s=(e??I()).replace(/\/$/,``),c=s.endsWith(`/embed`)?s:`${s}/embed`,l=new URL(c),u=n?.trim();u&&l.searchParams.set(`locationId`,u);let d=r?.trim();return d&&l.searchParams.set(`avatarId`,d),i===`face`&&l.searchParams.set(`fit`,`face`),a===`widget`&&l.searchParams.set(`ui`,`widget`),o&&l.searchParams.set(`close`,`1`),t&&l.searchParams.set(`debug`,`true`),le(l.toString())}function le(e){if(typeof location>`u`)return e;let t=new URL(e);return t.searchParams.set(`parentOrigin`,location.origin),t.toString()}function ue(e){return new URL(e).origin}function de(){return{ready:new Set,started:new Set,userTranscript:new Set,userSpeechStarted:new Set,userSpeechEnded:new Set,characterSpeechStarted:new Set,characterSpeechEnded:new Set,conversationUpdate:new Set,message:new Set,listeningState:new Set,activityChange:new Set,modeChange:new Set,conversationProcessorError:new Set}}function fe(e,t,n){return e[t].add(n),()=>e[t].delete(n)}function L(e,t,n){for(let r of e[t])r(n)}function R(e){for(let t of Object.keys(e))e[t].clear()}function pe(e){return`data`in e&&`format`in e&&e.format!=null&&!(`track`in e)}function me(e){return`url`in e&&typeof e.url==`string`}function z(e){if(!(`track`in e))return!1;let t=e.track;return typeof t!=`object`||!t?!1:typeof MediaStreamTrack<`u`&&t instanceof MediaStreamTrack?!0:`kind`in t&&`readyState`in t}function he(e){return!pe(e)&&!me(e)&&!z(e)&&`encoding`in e&&typeof e.encoding==`string`}var B=[8e3,16e3,22050,24e3,44100,48e3],V={MAX_CHUNK_BYTES:64*1024,RECOMMENDED_CHUNK_MS_MIN:20,RECOMMENDED_CHUNK_MS_MAX:200,MAX_BUFFERED_AUDIO_MS:8e3,PLAYBACK_JITTER_BUFFER_MS:150,PLAYBACK_JITTER_BUFFER_MS_MIN:80,PLAYBACK_JITTER_BUFFER_MS_MAX:250,MAX_UTTERANCE_DURATION_MS:9e4,MAX_PENDING_WRITES:8,DEFAULT_WRITE_TIMEOUT_MS:5e3},H=class extends Error{operation;requiredCapability;name=`UnsupportedSpeechOperationError`;constructor(e,t){super(`Speech operation "${e}" requires capability "${t}".`),this.operation=e,this.requiredCapability=t}},U=class extends Error{name=`SpeechUtteranceClosedError`;constructor(e=`Cannot write to a closed or cancelled speech utterance.`){super(e)}},W=class extends Error{name=`SpeechRuntimeError`;constructor(e,t){super(e,t)}},ge=class extends Error{name=`SpeechBufferTimeoutError`;constructor(e=`Timed out waiting for speech buffer capacity.`){super(e)}};function G(e=`none`){return{mode:e,trackedDurationMs:0,fallbackDurationMs:0}}function K(e){return B.includes(e)}function _e(e){if(e.encoding!==`pcm_s16le`)throw new W(`Unsupported audio encoding: ${e.encoding}`);if(e.channels!==1)throw new W(`Unsupported channel count: ${e.channels}`);if(!K(e.sampleRate))throw new W(`Unsupported sample rate: ${e.sampleRate}`)}function ve(e){if(pe(e)){_e(e.format);return}if(me(e)){if(!e.url.trim())throw new W(`Audio URL must be non-empty.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new W(`Unsupported sample rate: ${e.sampleRate}`);return}if(z(e)){if(e.track.kind!==`audio`)throw new W(`speech.play track must be an audio MediaStreamTrack.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new W(`Unsupported sample rate: ${e.sampleRate}`);return}if(he(e)){let t=e.encoding.trim().toLowerCase();if(!t)throw new W(`Encoded audio MIME type is required.`);if(t===`pcm_s16le`)throw new W(`Use format: { encoding: "pcm_s16le", … } for raw PCM.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new W(`Unsupported sample rate: ${e.sampleRate}`);return}throw new W(`Unsupported speech.play audio shape.`)}function ye(e){if(e.format)return _e(e.format),e.format;if(e.track){let t={encoding:`pcm_s16le`,sampleRate:e.sampleRate??24e3,channels:1};return _e(t),t}throw new W(`createUtterance requires format or track.`)}function be(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){return e===`replace-active`||e===`replace-all`?`interrupt`:`enqueue`}function Se(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);for(let t=0;t<e.length;t++){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}function q(e,t,n,r,i){let a=-.5*e+1.5*t-1.5*n+.5*r,o=e-2.5*t+2*n-.5*r,s=-.5*e+.5*n,c=t;return((a*i+o)*i+s)*i+c}function Ce(e,t){if(!(e>0)||!(t>0))throw Error(`Resampler rates must be positive`);if(e===t)return{fromRate:e,toRate:t,push(e){return e},flush(){return new Float32Array}};let n=e/t,r=new Float32Array,i=0;return{fromRate:e,toRate:t,push(e){if(e.length===0)return new Float32Array;let t=new Float32Array(r.length+e.length);if(t.set(r),t.set(e,r.length),r=t,r.length<4)return new Float32Array;let a=[];for(;i+2<r.length-1;){let e=Math.floor(i),t=i-e,o=Math.max(0,e-1),s=Math.min(r.length-1,e+1),c=Math.min(r.length-1,e+2);a.push(q(r[o],r[e],r[s],r[c],t)),i+=n}let o=Math.max(0,Math.floor(i)-1);return o>0&&(r=r.subarray(o),i-=o),a.length?Float32Array.from(a):new Float32Array},flush(){return r.length===0?new Float32Array:(r=new Float32Array,i=0,new Float32Array)}}}var we=`liforma-pcm-capture`,Te=`
|
|
1
|
+
var Liforma=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(){if(globalThis.__LIFORMA_STACK===`local`)return!0;if(typeof location>`u`)return!1;try{return new URLSearchParams(location.search).get(`stack`)===`local`}catch{return!1}}var n=`https://api.liforma.ai`,r=`http://localhost:3001`;function i(){let e=globalThis.__LIFORMA_API_BASE_URL;if(e?.trim())return e.trim().replace(/\/$/,``);if(typeof document>`u`)return null;let t=(document.querySelector(`script[data-liforma-sdk][src*="client.js"]`)??document.querySelector(`script[src*="/sdk/v2/client.js"]`))?.getAttribute(`data-api-base-url`)?.trim();return t?t.replace(/\/$/,``):null}function a(){return i()||(t()?r:n)}var o=class extends Error{code;requestId;status;details;constructor(e,t){super(e,t?.cause===void 0?void 0:{cause:t.cause}),this.name=`LiformaError`,this.code=t?.code?.trim()||`UNKNOWN`,this.requestId=t?.requestId?.trim()||void 0,this.status=t?.status,this.details=t?.details}};function s(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function c(e,t,n){let r=n?.get(`Liforma-Request-Id`)?.trim()||void 0,i;try{i=JSON.parse(t)}catch{}let a=i?.error&&typeof i.error==`object`?i.error:void 0,c=a?.code??i?.code,l=a?.message??i?.message,u=a?.requestId??i?.requestId??r,d=typeof c==`string`&&c.trim()?c.trim():`HTTP_ERROR`,f=typeof l==`string`&&l.trim()?l.trim():t.trim().slice(0,500)||`Request failed (${e})`,p=typeof u==`string`&&u.trim()?u.trim():r,{code:m,message:h,requestId:g,..._}=s(a)??s(i)??{};return new o(f,{code:d,requestId:p,status:e,details:Object.keys(_).length>0?_:void 0})}function l(e){let t=e.locale?.trim();if(t)return t;let n=e.language?.trim();if(n)return n;if(typeof navigator<`u`&&navigator.language?.trim())return navigator.language.trim()}function u(e){let t=e.secondaryLocale?.trim(),n=e.learningLocale?.trim();if(t&&n&&t!==n)throw Error(`secondaryLocale and learningLocale disagree; pass only one or make them equal.`);return t||n||void 0}function d(e,t){let n=e.trim();if(!n)throw Error(`sessionEndpoint must not be empty.`);if(typeof location>`u`)throw Error(`sessionEndpoint is only available in a browser.`);let r=new URL(n,location.href);if(r.origin!==location.origin)throw Error(`sessionEndpoint must be same-origin.`);let i=t.experienceId.trim();if(!i)throw Error(`sessionEndpoint requires experienceId.`);let a=l(t),o=u(t),s=t.idempotencyKey?.trim();return{url:r.toString(),init:{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,...s?{"Idempotency-Key":s}:{}},body:JSON.stringify({experienceId:i,...a?{locale:a}:{},...o?{secondaryLocale:o}:{},...t.mode?{mode:t.mode}:{},...t.speechInputMode?{speechInputMode:t.speechInputMode}:{},...t.speechOnly===void 0?{}:{speechOnly:t.speechOnly}})}}}function f(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function p(e){return typeof e==`boolean`}function m(e){if(!f(e))return null;let t=e.speech,n=e.conversation,r=e.avatar,i=e.tools;return!f(t)||!f(n)||!f(r)||!f(i)||!p(t.input)||!p(t.output)||!p(t.externalAudio)||!p(n.managed)||!p(r.enabled)||!p(i.enabled)?null:{speech:{input:t.input,output:t.output,externalAudio:t.externalAudio},conversation:{managed:n.managed},avatar:{enabled:r.enabled},tools:{enabled:i.enabled}}}function h(e){return!f(e)||!p(e.avatar)||!p(e.speechInput)||!p(e.speechOutput)||!p(e.tools)||!p(e.externalAudio)?null:{speech:{input:e.speechInput,output:e.speechOutput,externalAudio:e.externalAudio},conversation:{managed:!0},avatar:{enabled:e.avatar},tools:{enabled:e.tools}}}function g(e){return m(e)??h(e)}function _(e){if(!f(e))throw Error(`Session Launch response is missing session.`);let t=typeof e.id==`string`?e.id.trim():``,n=typeof e.experienceId==`string`?e.experienceId.trim():``,r=typeof e.experienceRevisionId==`string`?e.experienceRevisionId.trim():``,i=typeof e.expiresAt==`string`?e.expiresAt.trim():``,a=typeof e.locale==`string`?e.locale.trim():``,o=typeof e.secondaryLocale==`string`&&e.secondaryLocale.trim()?e.secondaryLocale.trim():void 0,s=e.mode===`conversation`||e.mode===`presenter`?e.mode:null,c=g(e.capabilities),l=ee(e.localeVoiceFallbacks),u=e.status===`active`||e.status===`ended`?e.status:void 0,d=typeof e.createdAt==`string`&&e.createdAt.trim()?e.createdAt.trim():void 0;if(!t||!n||!r||!i||!a||!s||!c)throw Error(`Session Launch response has an invalid session object.`);return{id:t,experienceId:n,experienceRevisionId:r,expiresAt:i,locale:a,...o?{secondaryLocale:o}:{},mode:s,capabilities:c,...l?{localeVoiceFallbacks:l}:{},...u?{status:u}:{},...d?{createdAt:d}:{}}}function ee(e){if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(!f(n))continue;let e=n.axis===`locale`||n.axis===`secondaryLocale`?n.axis:null,r=typeof n.requested==`string`?n.requested.trim():``,i=typeof n.resolved==`string`?n.resolved.trim():``;!e||!r||!i||n.reason!==`voice_unsupported`||t.push({axis:e,requested:r,resolved:i,reason:`voice_unsupported`})}return t.length>0?t:void 0}function v(e){let t=e.localeVoiceFallbacks;if(t?.length)for(let e of t){let t=e.axis===`secondaryLocale`?`secondaryLocale`:`locale`;console.warn(`[liforma] Session ${t} fell back to ${e.resolved} because the voice does not support ${e.requested}.`)}}function y(e){if(!f(e))throw Error(`Session Launch response must be a JSON object.`);let t=typeof e.launch==`string`?e.launch.trim():``;if(!t)throw Error(`Session Launch response is missing launch.`);let n=_(e.session);return v(n),{session:n,launch:t}}function b(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function x(e){return e?e.trim().toUpperCase().replace(/-/g,`_`):``}function te(e,t){let n=b(),r=x(t.code),i=t.message.trim(),a=t.details??{};if(r===`ORIGIN_NOT_ALLOWED`||/^Origin not allowed/i.test(i)&&n){if(i.includes(e)&&i.includes(`allowed origin`))return t;let r=typeof a.origin==`string`&&a.origin||n||`(unknown origin)`;return new o(`Your origin ${r} is not an allowed origin for experience ${e}. If you own this experience, sign in to the Liforma developer portal (app.liforma.ai), open Workspace → Settings → Origins, add ${r} to the list of allowed origins, and ensure “Allow public client-only embeds” is enabled.`,{code:`ORIGIN_NOT_ALLOWED`,requestId:t.requestId,status:t.status,details:a})}return r===`BROWSER_EMBEDS_DISABLED`||/^Browser embeds are not enabled/i.test(i)?i.includes(`Allow public client-only embeds`)?t:new o(`Browser embeds are not enabled for experience ${e}. If you own this experience, sign in to the Liforma developer portal (app.liforma.ai), open Workspace → Settings → Origins, and enable “Allow public client-only embeds”.`,{code:`BROWSER_EMBEDS_DISABLED`,requestId:t.requestId,status:t.status,details:a}):r===`EXPERIENCE_UNAVAILABLE`||/^Experience is not available\.?$/i.test(i)||/^Unknown experience\.?$/i.test(i)?i.includes(`No playable experience found`)?t:new o(`No playable experience found for “${e}”. Check that the experience id is correct (it should look like exp_…), and that the experience exists and is published in the Liforma developer portal (app.liforma.ai). Deleted, archived, and unpublished experiences cannot be started from a browser embed.`,{code:`EXPERIENCE_UNAVAILABLE`,requestId:t.requestId,status:t.status,details:a}):t}function S(e){let t=e?.locale?.trim();if(t)return t;let n=e?.language?.trim();if(n)return n;if(typeof navigator<`u`&&navigator.language?.trim())return navigator.language.trim()}function C(e){let t=e?.secondaryLocale?.trim(),n=e?.learningLocale?.trim();if(t&&n&&t!==n)throw new o(`secondaryLocale and learningLocale disagree; pass only one or make them equal.`,{code:`INVALID_BODY`});return t||n||void 0}function w(e,t){let n={experienceId:e},r=S(t);r&&(n.locale=r);let i=C(t);return i&&(n.secondaryLocale=i),t?.mode&&(n.mode=t.mode),t?.speechInputMode&&(n.speechInputMode=t.speechInputMode),t?.speechOnly!==void 0&&(n.speechOnly=t.speechOnly),n}async function T(e,t){let n=a(),r=t?.idempotencyKey?.trim(),i=await fetch(`${n}/v1/browser-sessions`,{method:`POST`,headers:{"Content-Type":`application/json`,...r?{"Idempotency-Key":r}:{}},body:JSON.stringify(w(e,t))});if(!i.ok){let t=await i.text();throw te(e,c(i.status,t,i.headers))}let s;try{s=await i.json()}catch{throw new o(`Browser session mint returned invalid JSON.`,{code:`INVALID_RESPONSE`,status:i.status,requestId:i.headers.get(`Liforma-Request-Id`)??void 0})}return y(s)}async function E(e,t){let n=d(e,t),r=new AbortController,i=()=>r.abort(t.signal?.reason);t.signal?.aborted?i():t.signal?.addEventListener(`abort`,i,{once:!0});let a=globalThis.setTimeout(()=>r.abort(new DOMException(`Session endpoint timed out.`,`TimeoutError`)),t.timeoutMs??3e4),s;try{s=await fetch(n.url,{...n.init,signal:r.signal})}finally{globalThis.clearTimeout(a),t.signal?.removeEventListener(`abort`,i)}if(!s.ok){let e=await s.text();throw c(s.status,e,s.headers)}if(!s.headers.get(`content-type`)?.toLowerCase().includes(`application/json`))throw new o(`Session endpoint must return a JSON Session Launch response.`,{code:`INVALID_RESPONSE`,status:s.status,requestId:s.headers.get(`Liforma-Request-Id`)??void 0});let l;try{l=await s.json()}catch{throw new o(`Session endpoint returned invalid JSON.`,{code:`INVALID_RESPONSE`,status:s.status,requestId:s.headers.get(`Liforma-Request-Id`)??void 0})}return y(l)}function ne(e){return typeof e!=`object`||!e?!1:typeof e[Symbol.asyncIterator]==`function`}function D(e){if(typeof e==`string`){let t=e.trim();if(!t)throw Error(`conversationProcessor returned empty text.`);return{text:t}}let t=e.text.trim();if(!t)throw Error(`conversationProcessor returned empty text.`);return{text:t,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}}async function re(e,t){let n=await e(t);return ne(n)?{kind:`stream`,stream:n}:{kind:`complete`,speech:D(n)}}var O=`3002`;function k(e){let t=new URL(e);return t.hostname===`localhost`||t.hostname===`127.0.0.1`?`Cannot connect to the Liforma player at ${e} — nothing is listening on port ${t.port||O}. Start the player dev server in player.liforma.ai (npm run dev).`:`Cannot connect to the Liforma player at ${e}. The embed did not load; check your network connection and player URL configuration.`}async function A(e,t){try{await fetch(e,{method:`GET`,mode:`no-cors`,signal:AbortSignal.timeout(8e3)})}catch{throw Error(k(t))}}function j(e,t,n,r){try{r&&r.length>0?e.postMessage(t,n,r):e.postMessage(t,n)}catch(e){throw e instanceof DOMException&&e.name===`SecurityError`?Error(k(n),{cause:e}):e}}var M=new Set([1,2]);function ie(e){return typeof e==`number`&&M.has(e)}var ae=new Set([`close`,`stateUpdate`,`commandResult`,`userTranscript`,`characterSpeechStarted`,`characterSpeechEnded`,`conversationUpdate`,`listeningState`,`userSpeechStarted`,`userSpeechEnded`,`modeChange`,`activityChange`,`message`,`started`,`widgetReady`,`widgetExpand`,`widgetCollapse`,`widgetAudioSettings`,`widgetDragStart`,`widgetDragMove`,`widgetDragEnd`]);function N(e){if(!e||typeof e!=`object`)return null;let t=e;if(!ie(t.schemaVersion)||!t.type||!ae.has(t.type))return null;if(t.type===`widgetReady`||t.type===`widgetExpand`||t.type===`widgetCollapse`)return t;if(t.type===`widgetAudioSettings`){let e=t.payload;return!e||typeof e!=`object`||typeof e.open!=`boolean`?null:t}if(t.type===`widgetDragStart`||t.type===`widgetDragEnd`){let e=t.payload;return!e||typeof e!=`object`||typeof e.pointerId!=`number`||!Number.isFinite(e.pointerId)?null:t}if(t.type===`widgetDragMove`){let e=t.payload;if(!e||typeof e!=`object`)return null;let{pointerId:n,dx:r,dy:i}=e;return typeof n!=`number`||!Number.isFinite(n)||typeof r!=`number`||!Number.isFinite(r)||typeof i!=`number`||!Number.isFinite(i)?null:t}return!t.payload||typeof t.payload!=`object`?null:t}function P(e,t,n){let r=e.trim();if(!r)throw Error(`createLaunchMessage requires a non-empty launch string.`);return{type:`launch`,schemaVersion:2,payload:{launch:r,...t===void 0?{}:{session:t},...n?{startButton:n}:{}}}}function oe(){return{type:`parentHello`,schemaVersion:2}}function se(e){return{type:`widgetSetChrome`,schemaVersion:2,payload:{mode:e}}}function F(){return{type:`widgetToggleAudioSettings`,schemaVersion:2,payload:{}}}function I(e){return e}function L(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cmd_${crypto.randomUUID().replace(/-/g,``).slice(0,12)}`:`cmd_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}var ce=3e4;function le(e){let t=e.container;getComputedStyle(t).position===`static`&&(t.style.position=`relative`);let n=document.createElement(`iframe`);n.src=e.src,n.title=`Liforma experience`,n.setAttribute(`allow`,`microphone; autoplay; clipboard-read; clipboard-write`),n.style.cssText=e.transparent?`display:block;position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;`:`display:block;position:absolute;inset:0;width:100%;height:100%;border:0;background:#030508;`,e.transparent&&n.setAttribute(`allowtransparency`,`true`);let r=!1,i=new Map,a=new Promise((t,r)=>{let i=()=>{o(),A(e.src,e.playerOrigin).then(t,r)},a=()=>{o(),r(Error(k(e.playerOrigin)))},o=()=>{n.removeEventListener(`load`,i),n.removeEventListener(`error`,a)};n.addEventListener(`load`,i),n.addEventListener(`error`,a)}),o=t=>{if(r||t.source!==n.contentWindow||t.origin!==e.playerOrigin)return;let a=N(t.data);if(a)switch(a.type){case`close`:e.onClose?.(a.payload);break;case`stateUpdate`:e.onPlayerStatusChange?.(a.payload.state),e.onStateUpdate?.(a.payload.state);break;case`commandResult`:{let e=i.get(a.payload.correlationId);if(!e)return;i.delete(a.payload.correlationId),a.payload.ok?e.resolve(a.payload.result):e.reject(Error(a.payload.error??`Command failed.`));break}case`userTranscript`:e.onUserTranscript?.(a.payload);break;case`characterSpeechStarted`:e.onCharacterSpeechStarted?.(a.payload);break;case`characterSpeechEnded`:e.onCharacterSpeechEnded?.(a.payload);break;case`conversationUpdate`:e.onConversationUpdate?.(a.payload.conversation);break;case`listeningState`:e.onListeningState?.(a.payload.listening);break;case`userSpeechStarted`:e.onUserSpeechStarted?.(a.payload);break;case`userSpeechEnded`:e.onUserSpeechEnded?.(a.payload);break;case`modeChange`:e.onActivityChange?.(I(a.payload.mode));break;case`activityChange`:e.onActivityChange?.(a.payload.activity);break;case`message`:e.onMessage?.(a.payload);break;case`started`:e.onStarted?.(a.payload);break;case`widgetReady`:e.onWidgetReady?.();break;case`widgetExpand`:e.onWidgetExpand?.();break;case`widgetCollapse`:e.onWidgetCollapse?.();break;case`widgetAudioSettings`:e.onWidgetAudioSettings?.(a.payload.open);break;case`widgetDragStart`:e.onWidgetDragStart?.(a.payload);break;case`widgetDragMove`:e.onWidgetDragMove?.(a.payload);break;case`widgetDragEnd`:e.onWidgetDragEnd?.(a.payload);break}};if(window.addEventListener(`message`,o),t.replaceChildren(n),t.clientHeight<2&&!t.style.minHeight){let e=getComputedStyle(t).minHeight;(e===`0px`||e===`auto`)&&(t.style.minHeight=`480px`)}let s=(t,i)=>{if(r)return;let a=n.contentWindow;if(!a)throw Error(k(e.playerOrigin));j(a,t,e.playerOrigin,i)},c=(e,t=12e4,n)=>{let r=e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload?e.payload.correlationId:L();return e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload||e.type!==`parentHello`&&e.payload&&(e.payload.correlationId=r),new Promise((a,o)=>{i.set(r,{resolve:e=>a(e),reject:o}),s(e,n),setTimeout(()=>{i.has(r)&&(i.delete(r),o(Error(`Timed out waiting for player command result.`)))},t)})};return{waitForLoad(){return a},postParentHello(){s(oe())},postLaunch(t,i,a){if(r)return;let o=n.contentWindow;if(!o)throw Error(`Liforma embed iframe is not ready.`);let s=P(t,i,a),c=()=>{r||j(o,s,e.playerOrigin)};c();for(let e=1;e<=12;e+=1)window.setTimeout(c,e*75)},postManifest(e){if(typeof e==`string`){this.postLaunch(e);return}if(e&&typeof e==`object`&&typeof e.launch==`string`){let t=String(e.launch),n=e.session;this.postLaunch(t,n);return}throw Error(`postManifest is deprecated; use postLaunch with an opaque launch string from SessionLaunchResponse.`)},postWidgetSetChrome(e){s(se(e))},postWidgetToggleAudioSettings(){s(F())},speak(e){return c({type:`speak`,schemaVersion:2,payload:{correlationId:L(),text:e.text,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}})},startListening(){return c({type:`startListening`,schemaVersion:2,payload:{correlationId:L()}})},stopListening(){return c({type:`stopListening`,schemaVersion:2,payload:{correlationId:L()}})},listenOnce(e){return c({type:`listenOnce`,schemaVersion:2,payload:{correlationId:L(),...e?.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}})},async speakProcessorStream(e,t){let n=L(),r=L(),i=(await c({type:`speakStreamStart`,schemaVersion:2,payload:{correlationId:n,...t?.characterId?{characterId:t.characterId}:{},...t?.behavior?{behavior:t.behavior}:{}}})).streamId;try{for await(let n of e){if(t?.signal?.aborted)throw new DOMException(`Processor stream aborted.`,`AbortError`);n&&s({type:`speakStreamChunk`,schemaVersion:2,payload:{streamId:i,text:n}})}if(t?.signal?.aborted)throw new DOMException(`Processor stream aborted.`,`AbortError`);return await c({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch(e){try{await c({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch{}throw e}},speechPlay(e){let t=L(),n=[];return(e.source.kind===`pcm`||e.source.kind===`encoded`)&&n.push(e.source.data),c({type:`speechPlay`,schemaVersion:2,payload:{correlationId:t,source:e.source,...e.characterId?{characterId:e.characterId}:{},...e.transcript===void 0?{}:{transcript:e.transcript},...e.history?{history:e.history}:{},...e.queue?{queue:e.queue}:{}}},12e4,n)},speechUtteranceBegin(e){return c({type:`speechUtteranceBegin`,schemaVersion:2,payload:{correlationId:L(),utteranceId:e.utteranceId,format:e.format,queue:e.queue,...e.characterId?{characterId:e.characterId}:{},...e.transcript===void 0?{}:{transcript:e.transcript}}})},speechUtteranceWrite(e){return c({type:`speechUtteranceWrite`,schemaVersion:2,payload:{correlationId:L(),utteranceId:e.utteranceId,audio:e.audio,byteLength:e.byteLength}},ce,[e.audio])},speechUtteranceSetTranscript(e){return c({type:`speechUtteranceSetTranscript`,schemaVersion:2,payload:{correlationId:L(),utteranceId:e.utteranceId,transcript:e.transcript}})},speechUtteranceClose(e){return c({type:`speechUtteranceClose`,schemaVersion:2,payload:{correlationId:L(),utteranceId:e.utteranceId,...e.transcript===void 0?{}:{transcript:e.transcript},...e.history?{history:e.history}:{}}})},speechUtteranceCancel(e){return c({type:`speechUtteranceCancel`,schemaVersion:2,payload:{correlationId:L(),utteranceId:e.utteranceId}})},speechInterrupt(e){return c({type:`speechInterrupt`,schemaVersion:2,payload:{correlationId:L(),...e}})},getConversation(){return c({type:`getConversation`,schemaVersion:2,payload:{correlationId:L()}})},destroy(){if(!r){r=!0;for(let e of i.values())e.reject(Error(`Iframe host destroyed.`));i.clear(),window.removeEventListener(`message`,o),n.remove()}}}}function ue(e){let t,n=!1,r=!1,i=()=>{r||!n||t===void 0||(r=!0,e(t))};return{setValue(e){t=e,i()},markReady(){n=!0,i()}}}var de=`https://player.liforma.ai/embed`,fe=`http://localhost:3002/embed`;function R(){let e=globalThis.__LIFORMA_PLAYER_EMBED_URL;if(e?.trim())return e.trim().replace(/\/$/,``);if(typeof document>`u`)return null;let t=(document.querySelector(`script[data-liforma-sdk][src*="client.js"]`)??document.querySelector(`script[src*="/sdk/v2/client.js"]`))?.getAttribute(`data-player-embed-url`)?.trim();return t?t.replace(/\/$/,``):null}function pe(){let e=R();return e?e.endsWith(`/embed`)?e:`${e}/embed`:t()?fe:de}function me(e,t,n,r,i,a,o){let s=(e??pe()).replace(/\/$/,``),c=s.endsWith(`/embed`)?s:`${s}/embed`,l=new URL(c),u=n?.trim();u&&l.searchParams.set(`locationId`,u);let d=r?.trim();return d&&l.searchParams.set(`avatarId`,d),i===`face`&&l.searchParams.set(`fit`,`face`),a===`widget`&&l.searchParams.set(`ui`,`widget`),o&&l.searchParams.set(`close`,`1`),t&&l.searchParams.set(`debug`,`true`),he(l.toString())}function he(e){if(typeof location>`u`)return e;let t=new URL(e);return t.searchParams.set(`parentOrigin`,location.origin),t.toString()}function ge(e){return new URL(e).origin}function z(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`evt_${crypto.randomUUID().replace(/-/g,``).slice(0,12)}`:`evt_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function _e(e,t,n){return{id:z(),type:e,sessionId:t,timestamp:new Date().toISOString(),data:n}}function ve(){return{ready:new Set,started:new Set,userTranscript:new Set,userSpeechStarted:new Set,userSpeechEnded:new Set,characterSpeechStarted:new Set,characterSpeechEnded:new Set,conversationUpdate:new Set,message:new Set,listeningState:new Set,activityChange:new Set,conversationProcessorError:new Set}}function ye(e,t,n){return e[t].add(n),()=>e[t].delete(n)}function be(e,t,n){for(let r of e[t])r(n)}function xe(e){for(let t of Object.keys(e))e[t].clear()}function B(e){return`data`in e&&`format`in e&&e.format!=null&&!(`track`in e)}function V(e){return`url`in e&&typeof e.url==`string`}function H(e){if(!(`track`in e))return!1;let t=e.track;return typeof t!=`object`||!t?!1:typeof MediaStreamTrack<`u`&&t instanceof MediaStreamTrack?!0:`kind`in t&&`readyState`in t}function Se(e){return!B(e)&&!V(e)&&!H(e)&&`encoding`in e&&typeof e.encoding==`string`}var Ce=[8e3,16e3,22050,24e3,44100,48e3],U={MAX_CHUNK_BYTES:64*1024,RECOMMENDED_CHUNK_MS_MIN:20,RECOMMENDED_CHUNK_MS_MAX:200,MAX_BUFFERED_AUDIO_MS:8e3,PLAYBACK_JITTER_BUFFER_MS:150,PLAYBACK_JITTER_BUFFER_MS_MIN:80,PLAYBACK_JITTER_BUFFER_MS_MAX:250,MAX_UTTERANCE_DURATION_MS:9e4,MAX_PENDING_WRITES:8,DEFAULT_WRITE_TIMEOUT_MS:5e3},we=class extends Error{operation;requiredCapability;name=`UnsupportedSpeechOperationError`;constructor(e,t){super(`Speech operation "${e}" requires capability "${t}".`),this.operation=e,this.requiredCapability=t}},W=class extends Error{name=`SpeechUtteranceClosedError`;constructor(e=`Cannot write to a closed or cancelled speech utterance.`){super(e)}},G=class extends Error{name=`SpeechRuntimeError`;constructor(e,t){super(e,t)}},Te=class extends Error{name=`SpeechBufferTimeoutError`;constructor(e=`Timed out waiting for speech buffer capacity.`){super(e)}};function Ee(e=`none`){return{mode:e,trackedDurationMs:0,fallbackDurationMs:0}}function K(e){return Ce.includes(e)}function De(e){if(e.encoding!==`pcm_s16le`)throw new G(`Unsupported audio encoding: ${e.encoding}`);if(e.channels!==1)throw new G(`Unsupported channel count: ${e.channels}`);if(!K(e.sampleRate))throw new G(`Unsupported sample rate: ${e.sampleRate}`)}function q(e){if(B(e)){De(e.format);return}if(V(e)){if(!e.url.trim())throw new G(`Audio URL must be non-empty.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new G(`Unsupported sample rate: ${e.sampleRate}`);return}if(H(e)){if(e.track.kind!==`audio`)throw new G(`speech.play track must be an audio MediaStreamTrack.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new G(`Unsupported sample rate: ${e.sampleRate}`);return}if(Se(e)){let t=e.encoding.trim().toLowerCase();if(!t)throw new G(`Encoded audio MIME type is required.`);if(t===`pcm_s16le`)throw new G(`Use format: { encoding: "pcm_s16le", … } for raw PCM.`);if(e.sampleRate!==void 0&&!K(e.sampleRate))throw new G(`Unsupported sample rate: ${e.sampleRate}`);return}throw new G(`Unsupported speech.play audio shape.`)}function Oe(e){if(e.format)return De(e.format),e.format;if(e.track){let t={encoding:`pcm_s16le`,sampleRate:e.sampleRate??24e3,channels:1};return De(t),t}throw new G(`createUtterance requires format or track.`)}function J(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function ke(e){return e===`replace-active`||e===`replace-all`?`interrupt`:`enqueue`}function Ae(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);for(let t=0;t<e.length;t++){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}function je(e,t,n,r,i){let a=-.5*e+1.5*t-1.5*n+.5*r,o=e-2.5*t+2*n-.5*r,s=-.5*e+.5*n,c=t;return((a*i+o)*i+s)*i+c}function Me(e,t){if(!(e>0)||!(t>0))throw Error(`Resampler rates must be positive`);if(e===t)return{fromRate:e,toRate:t,push(e){return e},flush(){return new Float32Array}};let n=e/t,r=new Float32Array,i=0;return{fromRate:e,toRate:t,push(e){if(e.length===0)return new Float32Array;let t=new Float32Array(r.length+e.length);if(t.set(r),t.set(e,r.length),r=t,r.length<4)return new Float32Array;let a=[];for(;i+2<r.length-1;){let e=Math.floor(i),t=i-e,o=Math.max(0,e-1),s=Math.min(r.length-1,e+1),c=Math.min(r.length-1,e+2);a.push(je(r[o],r[e],r[s],r[c],t)),i+=n}let o=Math.max(0,Math.floor(i)-1);return o>0&&(r=r.subarray(o),i-=o),a.length?Float32Array.from(a):new Float32Array},flush(){return r.length===0?new Float32Array:(r=new Float32Array,i=0,new Float32Array)}}}var Ne=`liforma-pcm-capture`,Pe=`
|
|
2
2
|
class LiformaPcmCaptureProcessor extends AudioWorkletProcessor {
|
|
3
3
|
process(inputs) {
|
|
4
4
|
const ch = inputs[0] && inputs[0][0];
|
|
@@ -10,8 +10,8 @@ class LiformaPcmCaptureProcessor extends AudioWorkletProcessor {
|
|
|
10
10
|
return true;
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
registerProcessor('${
|
|
14
|
-
`,Ee=null;function J(){return Ee||=URL.createObjectURL(new Blob([Te],{type:`application/javascript`})),Ee}function De(){return window.AudioContext||window.webkitAudioContext||null}async function Oe(e){let{mediaStream:t,targetSampleRate:n,onPcm:r,shouldSend:i,onLog:a}=e,o=De();if(!o)throw Error(`Web Audio is required for audio capture`);let s=new o,c=s.createMediaStreamSource(t),l=s.createGain();l.gain.value=0;let u=s.sampleRate,d=Ce(u,n),f=!1,p=!1,m=e=>{if(f||i&&!i())return;let t=d.push(e);t.length!==0&&r(Se(t))},h=()=>void 0;return await(async()=>{if(typeof s.audioWorklet?.addModule!=`function`)return!1;try{await s.audioWorklet.addModule(J());let e=new AudioWorkletNode(s,we,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]});return e.port.onmessage=e=>{e.data instanceof Float32Array&&m(e.data)},c.connect(e),e.connect(l),l.connect(s.destination),h=()=>{e.port.onmessage=null;try{e.disconnect()}catch{}try{c.disconnect()}catch{}try{l.disconnect()}catch{}},p=!0,!0}catch{return!1}})()?a?.(`Mic/track capture via AudioWorklet at ${u} Hz → ${n} Hz`):((()=>{let e=s.createScriptProcessor?.bind(s);if(!e)throw Error(`Neither AudioWorklet nor ScriptProcessor is available`);let t=e(4096,1,1);t.onaudioprocess=e=>{m(e.inputBuffer.getChannelData(0))},c.connect(t),t.connect(l),l.connect(s.destination),h=()=>{t.onaudioprocess=null;try{t.disconnect()}catch{}try{c.disconnect()}catch{}try{l.disconnect()}catch{}},p=!1})(),a?.(`Mic/track capture via ScriptProcessor at ${u} Hz → ${n} Hz`,`warn`)),s.state===`suspended`&&await s.resume().catch(()=>void 0),{fromSampleRate:u,usingWorklet:p,stop(){f||(f=!0,d.flush(),h(),s.close().catch(()=>void 0))}}}async function ke(e){let{track:t,utterance:n,sampleRate:r,signal:i}=e;if(typeof MediaStreamTrack>`u`||!(t instanceof MediaStreamTrack))throw new W(`MediaStreamTrack is not available in this environment.`);if(t.kind!==`audio`)throw new W(`speech.play track must be an audio MediaStreamTrack.`);if(t.readyState===`ended`||i?.aborted)return;let a=new MediaStream([t]),o=Promise.resolve(),s=!1,c=null,l=()=>{s||(s=!0,c?.stop(),c=null)};try{c=await Oe({mediaStream:a,targetSampleRate:r,shouldSend:()=>!s&&!i?.aborted,onPcm:e=>{if(s||i?.aborted)return;let t=be(e);o=o.then(async()=>{if(s||i?.aborted)return;let e=0;for(;e<t.byteLength;){let r=Math.min(e+V.MAX_CHUNK_BYTES,t.byteLength);if((r-e)%2==1&&--r,r<=e)break;let i=t.subarray(e,r);e=r,i.byteLength!==0&&await n.write(i)}}).catch(()=>{l()})}})}catch(e){throw l(),new W(`MediaStreamTrack capture failed: ${e instanceof Error?e.message:String(e)}`)}await new Promise(e=>{let r=()=>{l(),o.finally(e)};t.addEventListener(`ended`,r,{once:!0}),i?.addEventListener(`abort`,()=>{n.cancel().catch(()=>void 0),r()},{once:!0}),(t.readyState===`ended`||i?.aborted)&&r()})}async function Ae(e,t){if(z(e))throw new W(`MediaStreamTrack play is handled on the host before embed.`);if(pe(e)){let t=be(e.data);if(t.byteLength&1)throw new W(`PCM byte length must be even.`);return{kind:`pcm`,data:t.slice().buffer,format:e.format}}if(me(e))return{kind:`url`,url:e.url.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}};if(!he(e))throw new W(`Unsupported speech.play audio shape.`);let n;if(typeof Blob<`u`&&e.data instanceof Blob){if(t?.aborted)throw new DOMException(`Play aborted.`,`AbortError`);n=new Uint8Array(await e.data.arrayBuffer())}else n=be(e.data);return{kind:`encoded`,data:n.slice().buffer,encoding:e.encoding.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}}}function je(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`utt_${crypto.randomUUID().replace(/-/g,``).slice(0,12)}`:`utt_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function Y(e,t=`completed`){return{utteranceId:e.speechId,characterId:e.characterId,status:t,durationMs:e.durationMs,transcript:e.text,animation:{mode:`tracked`,trackedDurationMs:e.durationMs,fallbackDurationMs:0}}}function X(e){return e instanceof Error?e:new W(String(e))}function Me(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}var Ne=class{id;characterId;result;format;host;signal;settleResolve;settleReject;settled=!1;closed=!1;writeChain=Promise.resolve();pendingWriteCount=0;pendingWriteWaiters=[];bufferedMs=0;sampleRate;beginPromise;constructor(e){this.id=e.id,this.characterId=e.characterId,this.format=e.format,this.host=e.host,this.signal=e.signal,this.sampleRate=e.format.sampleRate,this.result=new Promise((e,t)=>{this.settleResolve=e,this.settleReject=t}),this.result.catch(()=>void 0);let t=this.requireHost();this.beginPromise=t.speechUtteranceBegin({utteranceId:this.id,format:this.format,characterId:this.characterId,queue:e.queue,...e.transcript===void 0?{}:{transcript:e.transcript}}).catch(e=>{throw this.fail(X(e)),X(e)}),this.signal?.addEventListener(`abort`,()=>{this.cancel()},{once:!0})}async write(e,t){if(this.closed||this.settled||(await this.beginPromise.catch(()=>void 0),this.closed||this.settled))throw new U;let n=be(e);if(n.byteLength&1)throw new W(`PCM chunk byte length must be even (complete s16 samples).`);if(n.byteLength>V.MAX_CHUNK_BYTES)throw new W(`PCM chunk exceeds MAX_CHUNK_BYTES (${V.MAX_CHUNK_BYTES}).`);if(n.byteLength===0)return;let r=t?.timeoutMs??V.DEFAULT_WRITE_TIMEOUT_MS;await this.acquireWriteSlot(r);let i=n.byteLength/2/this.sampleRate*1e3;if(this.bufferedMs+i>V.MAX_UTTERANCE_DURATION_MS)throw this.releaseWriteSlot(),new W(`Utterance exceeds MAX_UTTERANCE_DURATION_MS.`);let a=async()=>{if(this.closed||this.settled)throw new U;let e=this.requireHost(),t=n.slice(),i=e.speechUtteranceWrite({utteranceId:this.id,audio:t.buffer,byteLength:t.byteLength}),a=await Promise.race([i,new Promise((e,t)=>{setTimeout(()=>t(new ge),r)})]);this.bufferedMs=Math.max(0,a.bufferedMs)},o=this.writeChain.then(a,a);this.writeChain=o.then(()=>void 0,()=>void 0);try{await o}finally{this.releaseWriteSlot()}}async setTranscript(e){if(this.closed||this.settled||(await this.beginPromise.catch(()=>void 0),this.closed||this.settled))throw new U;await this.requireHost().speechUtteranceSetTranscript({utteranceId:this.id,transcript:e})}async close(e){if(this.settled)return this.result;this.closed=!0,await this.beginPromise.catch(()=>void 0),await this.writeChain.catch(()=>void 0);try{let t=await this.requireHost().speechUtteranceClose({utteranceId:this.id,transcript:e?.transcript,history:e?.history??`none`});return this.resolve(t),t}catch(e){let t=X(e);throw this.fail(t),t}}async cancel(){if(this.settled)return this.result;this.closed=!0;try{let e=this.host.getIframeHost();if(e){let t=await e.speechUtteranceCancel({utteranceId:this.id});return this.resolve(t),t}let t={utteranceId:this.id,characterId:this.characterId,status:`cancelled`,durationMs:0,animation:G(`none`)};return this.resolve(t),t}catch(e){let t=X(e);throw this.fail(t),t}}adoptExternalResult(e){this.resolve(e)}requireHost(){let e=this.host.getIframeHost();if(!e)throw new W(`Speech session is not attached.`);return e}resolve(e){this.settled||(this.settled=!0,this.settleResolve(Object.freeze(e)),this.flushWriteWaiters(new U))}fail(e){this.settled||(this.settled=!0,this.settleReject(e),this.flushWriteWaiters(e))}async acquireWriteSlot(e){if(this.pendingWriteCount<V.MAX_PENDING_WRITES){this.pendingWriteCount+=1;return}await new Promise((t,n)=>{let r=setTimeout(()=>{n(new ge)},e);this.pendingWriteWaiters.push({resolve:()=>{clearTimeout(r),this.pendingWriteCount+=1,t()},reject:e=>{clearTimeout(r),n(e)}})})}releaseWriteSlot(){this.pendingWriteCount=Math.max(0,this.pendingWriteCount-1),this.pendingWriteWaiters.shift()?.resolve()}flushWriteWaiters(e){for(;this.pendingWriteWaiters.length>0;)this.pendingWriteWaiters.shift()?.reject(e)}};function Pe(e){let t=null,n=(t,n)=>{if(!e.getCapabilities()[n])throw new H(t,n)},r={async speak(r){if(e.assertSessionStarted(),n(`speak`,`textSpeech`),r.signal?.aborted)throw new DOMException(`Speak aborted.`,`AbortError`);let i=xe(r.queue??`append`);i===`interrupt`&&(e.onProcessorInterrupt?.(),t&&=(t.cancel(),null));let a=e.getIframeHost();if(!a)throw new W(`Speech session is not attached.`);let o=a.speak({text:r.text,characterId:r.characterId,behavior:i});if(r.signal){let t=r.signal;return await new Promise((n,i)=>{let s=()=>{a.speechInterrupt({scope:`active`}).catch(()=>void 0),i(new DOMException(`Speak aborted.`,`AbortError`))};if(t.aborted){s();return}t.addEventListener(`abort`,s,{once:!0}),o.then(e=>{t.removeEventListener(`abort`,s),n(Y(e,`completed`))},a=>{if(t.removeEventListener(`abort`,s),Me(a)){n({utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:G(`none`)});return}i(X(a))})})}try{return Y(await o,`completed`)}catch(t){if(Me(t))return{utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:G(`none`)};throw X(t)}},async play(i){if(e.assertSessionStarted(),n(`play`,`externalSpeechAudio`),ve(i.audio),i.signal?.aborted)throw new DOMException(`Play aborted.`,`AbortError`);let a=i.queue??`append`;if((a===`replace-active`||a===`replace-all`)&&(e.onProcessorInterrupt?.(),t&&=(t.cancel(),null)),z(i.audio)){let e=i.audio.sampleRate??24e3;return r.createUtterance({format:{encoding:`pcm_s16le`,sampleRate:e,channels:1},track:i.audio.track,characterId:i.characterId,queue:a===`append`?`replace-active`:a,signal:i.signal}).result}let o=e.getIframeHost();if(!o)throw new W(`Speech session is not attached.`);let s=await Ae(i.audio,i.signal);return o.speechPlay({source:s,characterId:i.characterId,transcript:i.transcript,history:i.history??`none`,queue:a,signal:i.signal})},createUtterance(r){e.assertSessionStarted(),n(`createUtterance`,`externalSpeechAudio`);let i=ye(r);if(r.track&&r.track.kind!==`audio`)throw new W(`createUtterance track must be an audio MediaStreamTrack.`);let a=r.queue??`replace-active`;if(a!==`replace-active`&&a!==`replace-all`)throw new W(`createUtterance queue must be replace-active or replace-all.`);e.onProcessorInterrupt?.(),t&&=(t.cancel(),null);let o=new Ne({id:je(),characterId:r.characterId??e.getActiveCharacterId(),format:i,queue:a,host:e,...r.transcript===void 0?{}:{transcript:r.transcript},signal:r.signal});return t=o,o.result.finally(()=>{t===o&&(t=null)}),r.track&&(async()=>{try{if(await ke({track:r.track,utterance:o,sampleRate:i.sampleRate,signal:r.signal}),r.signal?.aborted)return;await o.close({history:`none`})}catch{await o.cancel().catch(()=>void 0)}})(),o},async interrupt(n){e.assertSessionStarted(),e.onProcessorInterrupt?.();let r=e.getIframeHost();if(!r)return[];let i=await r.speechInterrupt(n??{scope:`active`});if(t){let e=i.find(e=>e.utteranceId===t.id);e&&t.adoptExternalResult(e),t=null}return i}};return r}function Fe(e){return!!(e.showClose===!0||e.returnUrl?.trim()||e.closeButton===!0||e.closeButton&&typeof e.closeButton==`object`&&e.closeButton.visible!==!1)}var Ie=class e{bootstrap;conversationProcessor;iframeHost=null;attachInFlight=null;endpointAbortController=null;processorAbortController=null;processorChain=Promise.resolve();resolvedSession;launchToken;attachReturnUrl=null;closed=!1;attached=!1;closeHandlers=[];eventRegistry=de();readyEvent=null;startedEvent=null;conversationCache=[];speech;constructor(e){this.bootstrap=e,this.conversationProcessor=e.conversationProcessor??null,this.resolvedSession=e.kind===`launch`?e.session??null:null,this.launchToken=e.kind===`launch`?e.launch:null,this.speech=Pe({getIframeHost:()=>this.iframeHost,assertSessionStarted:()=>this.assertSessionStarted(),getCapabilities:()=>Le(this.resolvedSession),getActiveCharacterId:()=>`character_unknown`,onProcessorInterrupt:()=>{this.processorAbortController?.abort(),this.processorAbortController=null}})}static async startSession(t){if(`launch`in t&&typeof t.launch==`string`){let n=t.launch.trim();if(!n)throw Error(`StartSessionOptions.launch must be a non-empty string.`);return new e({kind:`launch`,launch:n,session:t.session,embedBaseUrl:t.embedBaseUrl,debug:t.debug,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor})}if(`sessionEndpoint`in t)return new e({kind:`sessionEndpoint`,experienceId:t.experienceId,sessionEndpoint:t.sessionEndpoint,locale:t.locale,secondaryLocale:t.secondaryLocale,learningLocale:t.learningLocale,language:t.language,locationId:t.locationId,avatarId:t.avatarId,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,responseMode:t.responseMode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor});if(`experienceId`in t)return new e({kind:`public`,experienceId:t.experienceId,locale:t.locale,secondaryLocale:t.secondaryLocale,learningLocale:t.learningLocale,language:t.language,locationId:t.locationId,avatarId:t.avatarId,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,responseMode:t.responseMode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor});throw Error(`Experience.startSession requires experienceId, sessionEndpoint, or launch.`)}getSession(){return this.resolvedSession}getManifest(){return null}on(e,t){let n=fe(this.eventRegistry,e,t);return e===`ready`&&this.readyEvent&&queueMicrotask(()=>t(this.readyEvent)),e===`started`&&this.startedEvent&&queueMicrotask(()=>t(this.startedEvent)),n}async attach(e){if(this.closed)throw Error(`Session has ended.`);if(!e.container)throw Error(`Experience.attach requires a DOM container element.`);return this.attached&&this.iframeHost?this.createPlayerFacade():(this.attachInFlight||=this.attachInternal(e).finally(()=>{this.attachInFlight=null}),this.attachInFlight)}async attachInternal(e){if(this.closed)throw Error(`Session has ended.`);if(this.attached&&this.iframeHost)return this.createPlayerFacade();this.iframeHost&&=(this.iframeHost.destroy(),null),this.attachReturnUrl=e.returnUrl?.trim()||null;let t=this.bootstrap.embedBaseUrl??I(),n=this.bootstrap.debug===!0,r=this.bootstrap.speechOnly===!0,i=ce(t,n,r||this.bootstrap.kind===`launch`?void 0:this.bootstrap.locationId,r||this.bootstrap.kind===`launch`?void 0:this.bootstrap.avatarId,e.fit,this.bootstrap.ui,Fe(e)),a=ue(i),o=null,s=new Promise(e=>{o=e}),c=null,l=new Promise(e=>{c=e}),u=ae(e=>{this.readyEvent||(this.readyEvent={session:e},L(this.eventRegistry,`ready`,this.readyEvent))}),d=this.bootstrap.onUserTranscript,f=P({container:e.container,src:i,playerOrigin:a,transparent:this.bootstrap.ui===`widget`,onClose:e=>{let t=e.returnUrl||!this.attachReturnUrl?e:{...e,returnUrl:this.attachReturnUrl};for(let e of this.closeHandlers)e(t)},onPlayerStatusChange:t=>{e.onPlayerStatusChange?.(t),e.onStateUpdate?.(t),t===`loading`&&o&&(o(),o=null),t===`ready`&&c&&(c(),c=null),t===`ready`&&u.markReady()},onUserTranscript:e=>{L(this.eventRegistry,`userTranscript`,e),d?.(e),this.queueProcessorTurn(e)},onUserSpeechStarted:e=>{L(this.eventRegistry,`userSpeechStarted`,e)},onUserSpeechEnded:e=>{L(this.eventRegistry,`userSpeechEnded`,e)},onCharacterSpeechStarted:e=>{L(this.eventRegistry,`characterSpeechStarted`,e)},onCharacterSpeechEnded:e=>{L(this.eventRegistry,`characterSpeechEnded`,e)},onListeningState:e=>{L(this.eventRegistry,`listeningState`,e)},onActivityChange:e=>{L(this.eventRegistry,`activityChange`,e),(e===`listening`||e===`thinking`||e===`speaking`)&&L(this.eventRegistry,`modeChange`,e)},onMessage:e=>{L(this.eventRegistry,`message`,e)},onStarted:e=>{this.startedEvent||(this.startedEvent=e,L(this.eventRegistry,`started`,e),this.bootstrap.onStart?.(e))},onConversationUpdate:e=>{this.conversationCache=e,L(this.eventRegistry,`conversationUpdate`,e)},onWidgetReady:()=>e.onWidgetReady?.(),onWidgetExpand:()=>e.onWidgetExpand?.(),onWidgetCollapse:()=>e.onWidgetCollapse?.(),onWidgetAudioSettings:t=>e.onWidgetAudioSettings?.(t),onWidgetDragStart:t=>e.onWidgetDragStart?.(t),onWidgetDragMove:t=>e.onWidgetDragMove?.(t),onWidgetDragEnd:t=>e.onWidgetDragEnd?.(t)});this.iframeHost=f;let p=this.resolveMintInteraction(),m=this.bootstrap.kind===`sessionEndpoint`?(this.endpointAbortController=new AbortController,y(this.bootstrap.sessionEndpoint,{experienceId:this.bootstrap.experienceId,locale:this.bootstrap.locale,secondaryLocale:this.bootstrap.secondaryLocale,learningLocale:this.bootstrap.learningLocale,language:this.bootstrap.language,mode:p.mode,responseMode:p.responseMode,speechInputMode:p.speechInputMode,speechOnly:this.bootstrap.speechOnly,signal:this.endpointAbortController.signal})):this.bootstrap.kind===`public`?v(this.bootstrap.experienceId,{locale:this.bootstrap.locale,secondaryLocale:this.bootstrap.secondaryLocale,learningLocale:this.bootstrap.learningLocale,language:this.bootstrap.language,mode:p.mode,responseMode:p.responseMode,speechInputMode:p.speechInputMode,speechOnly:this.bootstrap.speechOnly}):Promise.resolve(this.bootstrap.session?{session:this.bootstrap.session,launch:this.bootstrap.launch}:null),h;try{[,h]=await Promise.all([f.waitForLoad(),m])}catch(e){throw f.destroy(),this.iframeHost===f&&(this.iframeHost=null),e}finally{this.endpointAbortController=null}f.postParentHello();let g=h?.launch??(this.bootstrap.kind===`launch`?this.bootstrap.launch:null),_=h?.session??(this.bootstrap.kind===`launch`?this.bootstrap.session:void 0);if(!g)throw f.destroy(),this.iframeHost===f&&(this.iframeHost=null),Error(`Session Launch response did not include a launch token.`);return this.launchToken=g,_?(this.resolvedSession=_,f.postLaunch(g,_,e.startButton),u.setValue(_)):f.postLaunch(g,void 0,e.startButton),await Promise.race([s,new Promise((e,t)=>{setTimeout(()=>t(Error(`Timed out waiting for player loading UI.`)),12e4)})]),await Promise.race([l,new Promise((e,t)=>{setTimeout(()=>t(Error(`Timed out waiting for player ready state.`)),12e4)})]),this.attached=!0,this.createPlayerFacade()}async startListening(){this.assertSessionStarted(),await this.iframeHost.startListening()}async stopListening(){return this.assertSessionStarted(),this.iframeHost.stopListening()}async listenOnce(e){return this.assertSessionStarted(),this.iframeHost.listenOnce({timeoutMs:e?.timeoutMs})}getConversation(){return this.conversationCache}setWidgetChrome(e){this.iframeHost?.postWidgetSetChrome(e)}toggleAudioSettings(){this.iframeHost?.postWidgetToggleAudioSettings()}getLastTurn(){if(this.conversationCache.length===0)return[];let e=this.conversationCache[this.conversationCache.length-1].turnId;return this.conversationCache.filter(t=>t.turnId===e)}async end(){this.close()}destroy(){this.closed||(this.closed=!0,this.processorAbortController?.abort(),this.processorAbortController=null,this.endpointAbortController?.abort(),this.endpointAbortController=null,this.attachInFlight=null,this.iframeHost?.destroy(),this.iframeHost=null,R(this.eventRegistry),this.readyEvent=null,this.startedEvent=null,this.closeHandlers.length=0,this.attached=!1)}resolveMintInteraction(){if(this.bootstrap.kind===`launch`)return{};let e=this.conversationProcessor!==null;return{mode:this.bootstrap.mode,responseMode:e?`custom`:this.bootstrap.responseMode,speechInputMode:this.bootstrap.speechInputMode}}queueProcessorTurn(e){if(!e.isFinal||!e.text.trim()||!this.conversationProcessor)return;let t=this.conversationProcessor;this.processorAbortController?.abort(),this.processorAbortController=new AbortController;let n=this.processorAbortController.signal;this.processorChain=this.processorChain.then(async()=>{if(!n.aborted)try{let r=await te(t,{utteranceId:e.utteranceId,text:e.text,conversation:this.conversationCache,signal:n});if(n.aborted)return;if(r.kind===`complete`){let e=r.speech;await this.speech.speak({text:e.text,...e.characterId?{characterId:e.characterId}:{},queue:e.behavior===`interrupt`?`replace-active`:`append`});return}await this.iframeHost.speakProcessorStream(r.stream,{signal:n})}catch(t){if(n.aborted)return;let r=t instanceof Error?t.message:String(t);L(this.eventRegistry,`conversationProcessorError`,{utteranceId:e.utteranceId,message:r})}})}assertAttached(){if(!this.attached||!this.iframeHost)throw Error(`Call Experience.attach() before using speech APIs.`)}assertSessionStarted(){if(this.assertAttached(),!this.startedEvent)throw Error(`Session has not started. Wait for the player start button and the started event before using speak() or listening APIs.`)}close(){this.closed||(this.closed=!0,this.endpointAbortController?.abort(),this.endpointAbortController=null,this.attachInFlight=null,this.iframeHost?.destroy(),this.iframeHost=null,this.attached=!1)}createPlayerFacade(){return{close:()=>{this.close()},destroy:()=>{this.destroy()},on:(e,t)=>{e===`close`&&this.closeHandlers.push(t)}}}};function Le(e){return e?{textSpeech:e.capabilities.speechOutput,externalSpeechAudio:e.capabilities.externalAudio}:{textSpeech:!0,externalSpeechAudio:!0}}function Re(e,t){let n=e.trim();if(!n)return null;if(/^https?:\/\//i.test(n))try{return new URL(n)}catch{return null}let r=t.replace(/\/$/,``),i=n.startsWith(`/`)?n:`/${n}`;try{return new URL(i,`${r}/`)}catch{return null}}function ze(e){try{if(document.referrer){let e=new URL(document.referrer);if(e.origin===window.location.origin&&e.pathname!==window.location.pathname)return`${e.pathname}${e.search}${e.hash}`}}catch{}return e}function Be(e,t=`/meet`){if(e.reason!==`user`)return;let n=Re(e.returnUrl?.trim()||ze(t),window.location.origin);n?.protocol.startsWith(`http`)&&window.location.assign(n.toString())}var Ve=/\b(exp_[A-Za-z0-9][A-Za-z0-9_-]{2,127})\b/,He=/(?:Your origin|origin)\s+(\S+)\s+is not an allowed origin/i;function Ue(e){return e instanceof Error?e.message:String(e)}function We(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function Ge(e){return Ve.exec(e)?.[1]}function Ke(e){return He.exec(e)?.[1]}function qe(e,t){let n=Ue(e).trim()||`Unknown error`,r=t?.experienceId?.trim()||Ge(n)||void 0,i=t?.origin?.trim()||Ke(n)||We()||void 0;return/No playable experience found/i.test(n)||/^Experience is not available\.?$/i.test(n)||/^Unknown experience\.?$/i.test(n)||/experience_unavailable/i.test(n)?{kind:`not_found`,title:`The application tried to load an avatar experience that doesn’t exist.`,detail:`Experience with id ${r??`the requested experience`} does not exist`,technicalMessage:n,experienceId:r,origin:i}:/origin_not_allowed/i.test(n)||/is not an allowed origin/i.test(n)||/^Origin not allowed/i.test(n)?{kind:`origin_not_allowed`,title:`The application tried to load an avatar experience from a website that isn’t allowed.`,detail:`Origin ${i??`this page`} is not allowed for experience ${r??`the requested experience`}`,technicalMessage:n,experienceId:r,origin:i}:/browser_embeds_disabled/i.test(n)||/^Browser embeds are not enabled/i.test(n)?{kind:`browser_embeds_disabled`,title:`The application tried to load an avatar experience that isn’t enabled for browser embeds.`,detail:`Browser embeds are not enabled for experience ${r??`the requested experience`}`,technicalMessage:n,experienceId:r,origin:i}:{kind:`generic`,title:`This avatar experience couldn’t be started.`,detail:n,technicalMessage:n,experienceId:r,origin:i}}var Je=`liforma-experience-load-error-styles`;function Ye(){if(typeof document>`u`||document.getElementById(`liforma-experience-load-error-styles`))return;let e=document.createElement(`style`);e.id=Je,e.textContent=Xe,document.head.append(e)}var Xe=`
|
|
13
|
+
registerProcessor('${Ne}', LiformaPcmCaptureProcessor);
|
|
14
|
+
`,Fe=null;function Ie(){return Fe||=URL.createObjectURL(new Blob([Pe],{type:`application/javascript`})),Fe}function Le(){return window.AudioContext||window.webkitAudioContext||null}async function Re(e){let{mediaStream:t,targetSampleRate:n,onPcm:r,shouldSend:i,onLog:a}=e,o=Le();if(!o)throw Error(`Web Audio is required for audio capture`);let s=new o,c=s.createMediaStreamSource(t),l=s.createGain();l.gain.value=0;let u=s.sampleRate,d=Me(u,n),f=!1,p=!1,m=e=>{if(f||i&&!i())return;let t=d.push(e);t.length!==0&&r(Ae(t))},h=()=>void 0;return await(async()=>{if(typeof s.audioWorklet?.addModule!=`function`)return!1;try{await s.audioWorklet.addModule(Ie());let e=new AudioWorkletNode(s,Ne,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]});return e.port.onmessage=e=>{e.data instanceof Float32Array&&m(e.data)},c.connect(e),e.connect(l),l.connect(s.destination),h=()=>{e.port.onmessage=null;try{e.disconnect()}catch{}try{c.disconnect()}catch{}try{l.disconnect()}catch{}},p=!0,!0}catch{return!1}})()?a?.(`Mic/track capture via AudioWorklet at ${u} Hz → ${n} Hz`):((()=>{let e=s.createScriptProcessor?.bind(s);if(!e)throw Error(`Neither AudioWorklet nor ScriptProcessor is available`);let t=e(4096,1,1);t.onaudioprocess=e=>{m(e.inputBuffer.getChannelData(0))},c.connect(t),t.connect(l),l.connect(s.destination),h=()=>{t.onaudioprocess=null;try{t.disconnect()}catch{}try{c.disconnect()}catch{}try{l.disconnect()}catch{}},p=!1})(),a?.(`Mic/track capture via ScriptProcessor at ${u} Hz → ${n} Hz`,`warn`)),s.state===`suspended`&&await s.resume().catch(()=>void 0),{fromSampleRate:u,usingWorklet:p,stop(){f||(f=!0,d.flush(),h(),s.close().catch(()=>void 0))}}}async function ze(e){let{track:t,utterance:n,sampleRate:r,signal:i}=e;if(typeof MediaStreamTrack>`u`||!(t instanceof MediaStreamTrack))throw new G(`MediaStreamTrack is not available in this environment.`);if(t.kind!==`audio`)throw new G(`speech.play track must be an audio MediaStreamTrack.`);if(t.readyState===`ended`||i?.aborted)return;let a=new MediaStream([t]),o=Promise.resolve(),s=!1,c=null,l=()=>{s||(s=!0,c?.stop(),c=null)};try{c=await Re({mediaStream:a,targetSampleRate:r,shouldSend:()=>!s&&!i?.aborted,onPcm:e=>{if(s||i?.aborted)return;let t=J(e);o=o.then(async()=>{if(s||i?.aborted)return;let e=0;for(;e<t.byteLength;){let r=Math.min(e+U.MAX_CHUNK_BYTES,t.byteLength);if((r-e)%2==1&&--r,r<=e)break;let i=t.subarray(e,r);e=r,i.byteLength!==0&&await n.write(i)}}).catch(()=>{l()})}})}catch(e){throw l(),new G(`MediaStreamTrack capture failed: ${e instanceof Error?e.message:String(e)}`)}await new Promise(e=>{let r=()=>{l(),o.finally(e)};t.addEventListener(`ended`,r,{once:!0}),i?.addEventListener(`abort`,()=>{n.cancel().catch(()=>void 0),r()},{once:!0}),(t.readyState===`ended`||i?.aborted)&&r()})}async function Be(e,t){if(H(e))throw new G(`MediaStreamTrack play is handled on the host before embed.`);if(B(e)){let t=J(e.data);if(t.byteLength&1)throw new G(`PCM byte length must be even.`);return{kind:`pcm`,data:t.slice().buffer,format:e.format}}if(V(e))return{kind:`url`,url:e.url.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}};if(!Se(e))throw new G(`Unsupported speech.play audio shape.`);let n;if(typeof Blob<`u`&&e.data instanceof Blob){if(t?.aborted)throw new DOMException(`Play aborted.`,`AbortError`);n=new Uint8Array(await e.data.arrayBuffer())}else n=J(e.data);return{kind:`encoded`,data:n.slice().buffer,encoding:e.encoding.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}}}function Ve(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`utt_${crypto.randomUUID().replace(/-/g,``).slice(0,12)}`:`utt_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function He(e,t=`completed`){return{utteranceId:e.speechId,characterId:e.characterId,status:t,durationMs:e.durationMs,transcript:e.text,animation:{mode:`tracked`,trackedDurationMs:e.durationMs,fallbackDurationMs:0}}}function Y(e){return e instanceof Error?e:new G(String(e))}function Ue(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}var We=class{id;characterId;result;format;host;signal;settleResolve;settleReject;settled=!1;closed=!1;writeChain=Promise.resolve();pendingWriteCount=0;pendingWriteWaiters=[];bufferedMs=0;sampleRate;beginPromise;constructor(e){this.id=e.id,this.characterId=e.characterId,this.format=e.format,this.host=e.host,this.signal=e.signal,this.sampleRate=e.format.sampleRate,this.result=new Promise((e,t)=>{this.settleResolve=e,this.settleReject=t}),this.result.catch(()=>void 0);let t=this.requireHost();this.beginPromise=t.speechUtteranceBegin({utteranceId:this.id,format:this.format,characterId:this.characterId,queue:e.queue,...e.transcript===void 0?{}:{transcript:e.transcript}}).catch(e=>{throw this.fail(Y(e)),Y(e)}),this.signal?.addEventListener(`abort`,()=>{this.cancel()},{once:!0})}async write(e,t){if(this.closed||this.settled||(await this.beginPromise.catch(()=>void 0),this.closed||this.settled))throw new W;let n=J(e);if(n.byteLength&1)throw new G(`PCM chunk byte length must be even (complete s16 samples).`);if(n.byteLength>U.MAX_CHUNK_BYTES)throw new G(`PCM chunk exceeds MAX_CHUNK_BYTES (${U.MAX_CHUNK_BYTES}).`);if(n.byteLength===0)return;let r=t?.timeoutMs??U.DEFAULT_WRITE_TIMEOUT_MS;await this.acquireWriteSlot(r);let i=n.byteLength/2/this.sampleRate*1e3;if(this.bufferedMs+i>U.MAX_UTTERANCE_DURATION_MS)throw this.releaseWriteSlot(),new G(`Utterance exceeds MAX_UTTERANCE_DURATION_MS.`);let a=async()=>{if(this.closed||this.settled)throw new W;let e=this.requireHost(),t=n.slice(),i=e.speechUtteranceWrite({utteranceId:this.id,audio:t.buffer,byteLength:t.byteLength}),a=await Promise.race([i,new Promise((e,t)=>{setTimeout(()=>t(new Te),r)})]);this.bufferedMs=Math.max(0,a.bufferedMs)},o=this.writeChain.then(a,a);this.writeChain=o.then(()=>void 0,()=>void 0);try{await o}finally{this.releaseWriteSlot()}}async setTranscript(e){if(this.closed||this.settled||(await this.beginPromise.catch(()=>void 0),this.closed||this.settled))throw new W;await this.requireHost().speechUtteranceSetTranscript({utteranceId:this.id,transcript:e})}async close(e){if(this.settled)return this.result;this.closed=!0,await this.beginPromise.catch(()=>void 0),await this.writeChain.catch(()=>void 0);try{let t=await this.requireHost().speechUtteranceClose({utteranceId:this.id,transcript:e?.transcript,history:e?.history??`none`});return this.resolve(t),t}catch(e){let t=Y(e);throw this.fail(t),t}}async cancel(){if(this.settled)return this.result;this.closed=!0;try{let e=this.host.getIframeHost();if(e){let t=await e.speechUtteranceCancel({utteranceId:this.id});return this.resolve(t),t}let t={utteranceId:this.id,characterId:this.characterId,status:`cancelled`,durationMs:0,animation:Ee(`none`)};return this.resolve(t),t}catch(e){let t=Y(e);throw this.fail(t),t}}adoptExternalResult(e){this.resolve(e)}requireHost(){let e=this.host.getIframeHost();if(!e)throw new G(`Speech session is not attached.`);return e}resolve(e){this.settled||(this.settled=!0,this.settleResolve(Object.freeze(e)),this.flushWriteWaiters(new W))}fail(e){this.settled||(this.settled=!0,this.settleReject(e),this.flushWriteWaiters(e))}async acquireWriteSlot(e){if(this.pendingWriteCount<U.MAX_PENDING_WRITES){this.pendingWriteCount+=1;return}await new Promise((t,n)=>{let r=setTimeout(()=>{n(new Te)},e);this.pendingWriteWaiters.push({resolve:()=>{clearTimeout(r),this.pendingWriteCount+=1,t()},reject:e=>{clearTimeout(r),n(e)}})})}releaseWriteSlot(){this.pendingWriteCount=Math.max(0,this.pendingWriteCount-1),this.pendingWriteWaiters.shift()?.resolve()}flushWriteWaiters(e){for(;this.pendingWriteWaiters.length>0;)this.pendingWriteWaiters.shift()?.reject(e)}};function Ge(e){let t=null,n=(t,n)=>{if(!e.getCapabilities()[n])throw new we(t,n)},r={async speak(r){if(e.assertSessionStarted(),n(`speak`,`textSpeech`),r.signal?.aborted)throw new DOMException(`Speak aborted.`,`AbortError`);let i=ke(r.queue??`append`);i===`interrupt`&&(e.onProcessorInterrupt?.(),t&&=(t.cancel(),null));let a=e.getIframeHost();if(!a)throw new G(`Speech session is not attached.`);let o=a.speak({text:r.text,characterId:r.characterId,behavior:i});if(r.signal){let t=r.signal;return await new Promise((n,i)=>{let s=()=>{a.speechInterrupt({scope:`active`}).catch(()=>void 0),i(new DOMException(`Speak aborted.`,`AbortError`))};if(t.aborted){s();return}t.addEventListener(`abort`,s,{once:!0}),o.then(e=>{t.removeEventListener(`abort`,s),n(He(e,`completed`))},a=>{if(t.removeEventListener(`abort`,s),Ue(a)){n({utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:Ee(`none`)});return}i(Y(a))})})}try{return He(await o,`completed`)}catch(t){if(Ue(t))return{utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:Ee(`none`)};throw Y(t)}},async play(i){if(e.assertSessionStarted(),n(`play`,`externalSpeechAudio`),q(i.audio),i.signal?.aborted)throw new DOMException(`Play aborted.`,`AbortError`);let a=i.queue??`append`;if((a===`replace-active`||a===`replace-all`)&&(e.onProcessorInterrupt?.(),t&&=(t.cancel(),null)),H(i.audio)){let e=i.audio.sampleRate??24e3;return r.createUtterance({format:{encoding:`pcm_s16le`,sampleRate:e,channels:1},track:i.audio.track,characterId:i.characterId,queue:a===`append`?`replace-active`:a,signal:i.signal}).result}let o=e.getIframeHost();if(!o)throw new G(`Speech session is not attached.`);let s=await Be(i.audio,i.signal);return o.speechPlay({source:s,characterId:i.characterId,transcript:i.transcript,history:i.history??`none`,queue:a,signal:i.signal})},createUtterance(r){e.assertSessionStarted(),n(`createUtterance`,`externalSpeechAudio`);let i=Oe(r);if(r.track&&r.track.kind!==`audio`)throw new G(`createUtterance track must be an audio MediaStreamTrack.`);let a=r.queue??`replace-active`;if(a!==`replace-active`&&a!==`replace-all`)throw new G(`createUtterance queue must be replace-active or replace-all.`);e.onProcessorInterrupt?.(),t&&=(t.cancel(),null);let o=new We({id:Ve(),characterId:r.characterId??e.getActiveCharacterId(),format:i,queue:a,host:e,...r.transcript===void 0?{}:{transcript:r.transcript},signal:r.signal});return t=o,o.result.finally(()=>{t===o&&(t=null)}),r.track&&(async()=>{try{if(await ze({track:r.track,utterance:o,sampleRate:i.sampleRate,signal:r.signal}),r.signal?.aborted)return;await o.close({history:`none`})}catch{await o.cancel().catch(()=>void 0)}})(),o},async interrupt(n){e.assertSessionStarted(),e.onProcessorInterrupt?.();let r=e.getIframeHost();if(!r)return[];let i=await r.speechInterrupt(n??{scope:`active`});if(t){let e=i.find(e=>e.utteranceId===t.id);e&&t.adoptExternalResult(e),t=null}return i}};return r}function Ke(e){return!!(e.showClose===!0||e.returnUrl?.trim()||e.closeButton===!0||e.closeButton&&typeof e.closeButton==`object`&&e.closeButton.visible!==!1)}var qe=class e{bootstrap;conversationProcessor;iframeHost=null;attachInFlight=null;endpointAbortController=null;processorAbortController=null;processorChain=Promise.resolve();resolvedSession;launchToken;attachReturnUrl=null;closed=!1;attached=!1;closeHandlers=[];eventRegistry=ve();readyEnvelope=null;startedEnvelope=null;conversationCache=[];speech;constructor(e){this.bootstrap=e,this.conversationProcessor=e.conversationProcessor??null,this.resolvedSession=e.kind===`launch`?e.session??null:null,this.launchToken=e.kind===`launch`?e.launch:null,this.speech=Ge({getIframeHost:()=>this.iframeHost,assertSessionStarted:()=>this.assertSessionStarted(),getCapabilities:()=>Je(this.resolvedSession),getActiveCharacterId:()=>`character_unknown`,onProcessorInterrupt:()=>{this.processorAbortController?.abort(),this.processorAbortController=null}})}static async startSession(t){if(`launch`in t&&typeof t.launch==`string`){let n=t.launch.trim();if(!n)throw Error(`StartSessionOptions.launch must be a non-empty string.`);return new e({kind:`launch`,launch:n,session:t.session,embedBaseUrl:t.embedBaseUrl,debug:t.debug,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor})}if(`sessionEndpoint`in t)return new e({kind:`sessionEndpoint`,experienceId:t.experienceId,sessionEndpoint:t.sessionEndpoint,locale:t.locale,secondaryLocale:t.secondaryLocale,learningLocale:t.learningLocale,language:t.language,locationId:t.locationId,avatarId:t.avatarId,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor});if(`experienceId`in t)return new e({kind:`public`,experienceId:t.experienceId,locale:t.locale,secondaryLocale:t.secondaryLocale,learningLocale:t.learningLocale,language:t.language,locationId:t.locationId,avatarId:t.avatarId,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,ui:t.ui,onStart:t.onStart,onUserTranscript:t.onUserTranscript,conversationProcessor:t.conversationProcessor});throw Error(`Experience.startSession requires experienceId, sessionEndpoint, or launch.`)}getSession(){return this.resolvedSession}getManifest(){return null}on(e,t){let n=ye(this.eventRegistry,e,t);return e===`ready`&&this.readyEnvelope&&queueMicrotask(()=>t(this.readyEnvelope)),e===`started`&&this.startedEnvelope&&queueMicrotask(()=>t(this.startedEnvelope)),n}async attach(e){if(this.closed)throw Error(`Session has ended.`);if(!e.container)throw Error(`Experience.attach requires a DOM container element.`);return this.attached&&this.iframeHost?this.createPlayerFacade():(this.attachInFlight||=this.attachInternal(e).finally(()=>{this.attachInFlight=null}),this.attachInFlight)}async attachInternal(e){if(this.closed)throw Error(`Session has ended.`);if(this.attached&&this.iframeHost)return this.createPlayerFacade();this.iframeHost&&=(this.iframeHost.destroy(),null),this.attachReturnUrl=e.returnUrl?.trim()||null;let t=this.bootstrap.embedBaseUrl??pe(),n=this.bootstrap.debug===!0,r=this.bootstrap.speechOnly===!0,i=me(t,n,r||this.bootstrap.kind===`launch`?void 0:this.bootstrap.locationId,r||this.bootstrap.kind===`launch`?void 0:this.bootstrap.avatarId,e.fit,this.bootstrap.ui,Ke(e)),a=ge(i),o=null,s=new Promise(e=>{o=e}),c=null,l=new Promise(e=>{c=e}),u=ue(e=>{this.readyEnvelope||=(this.resolvedSession=e,this.emitWrapped(`ready`,{session:e}))}),d=this.bootstrap.onUserTranscript,f=le({container:e.container,src:i,playerOrigin:a,transparent:this.bootstrap.ui===`widget`,onClose:e=>{let t=e.returnUrl||!this.attachReturnUrl?e:{...e,returnUrl:this.attachReturnUrl};for(let e of this.closeHandlers)e(t)},onPlayerStatusChange:t=>{e.onPlayerStatusChange?.(t),e.onStateUpdate?.(t),t===`loading`&&o&&(o(),o=null),t===`ready`&&c&&(c(),c=null),t===`ready`&&u.markReady()},onUserTranscript:e=>{this.emitWrapped(`userTranscript`,e),d?.(e),this.queueProcessorTurn(e)},onUserSpeechStarted:e=>{this.emitWrapped(`userSpeechStarted`,e)},onUserSpeechEnded:e=>{this.emitWrapped(`userSpeechEnded`,e)},onCharacterSpeechStarted:e=>{this.emitWrapped(`characterSpeechStarted`,e)},onCharacterSpeechEnded:e=>{this.emitWrapped(`characterSpeechEnded`,e)},onListeningState:e=>{this.emitWrapped(`listeningState`,e)},onActivityChange:e=>{this.emitWrapped(`activityChange`,e)},onMessage:e=>{this.emitWrapped(`message`,e)},onStarted:e=>{this.startedEnvelope||(this.startedEnvelope=this.emitWrapped(`started`,e),this.bootstrap.onStart?.(e))},onConversationUpdate:e=>{this.conversationCache=e,this.emitWrapped(`conversationUpdate`,e)},onWidgetReady:()=>e.onWidgetReady?.(),onWidgetExpand:()=>e.onWidgetExpand?.(),onWidgetCollapse:()=>e.onWidgetCollapse?.(),onWidgetAudioSettings:t=>e.onWidgetAudioSettings?.(t),onWidgetDragStart:t=>e.onWidgetDragStart?.(t),onWidgetDragMove:t=>e.onWidgetDragMove?.(t),onWidgetDragEnd:t=>e.onWidgetDragEnd?.(t)});this.iframeHost=f;let p=this.resolveMintInteraction(),m=this.bootstrap.kind===`sessionEndpoint`?(this.endpointAbortController=new AbortController,E(this.bootstrap.sessionEndpoint,{experienceId:this.bootstrap.experienceId,locale:this.bootstrap.locale,secondaryLocale:this.bootstrap.secondaryLocale,learningLocale:this.bootstrap.learningLocale,language:this.bootstrap.language,mode:p.mode,speechInputMode:p.speechInputMode,speechOnly:this.bootstrap.speechOnly,signal:this.endpointAbortController.signal})):this.bootstrap.kind===`public`?T(this.bootstrap.experienceId,{locale:this.bootstrap.locale,secondaryLocale:this.bootstrap.secondaryLocale,learningLocale:this.bootstrap.learningLocale,language:this.bootstrap.language,mode:p.mode,speechInputMode:p.speechInputMode,speechOnly:this.bootstrap.speechOnly}):Promise.resolve(this.bootstrap.session?{session:this.bootstrap.session,launch:this.bootstrap.launch}:null),h;try{[,h]=await Promise.all([f.waitForLoad(),m])}catch(e){throw f.destroy(),this.iframeHost===f&&(this.iframeHost=null),e}finally{this.endpointAbortController=null}f.postParentHello();let g=h?.launch??(this.bootstrap.kind===`launch`?this.bootstrap.launch:null),_=h?.session??(this.bootstrap.kind===`launch`?this.bootstrap.session:void 0);if(!g)throw f.destroy(),this.iframeHost===f&&(this.iframeHost=null),Error(`Session Launch response did not include a launch token.`);return this.launchToken=g,_?(this.resolvedSession=_,this.bootstrap.kind===`launch`&&v(_),f.postLaunch(g,_,e.startButton),u.setValue(_)):f.postLaunch(g,void 0,e.startButton),await Promise.race([s,new Promise((e,t)=>{setTimeout(()=>t(Error(`Timed out waiting for player loading UI.`)),12e4)})]),await Promise.race([l,new Promise((e,t)=>{setTimeout(()=>t(Error(`Timed out waiting for player ready state.`)),12e4)})]),this.attached=!0,this.createPlayerFacade()}async startListening(){this.assertSessionStarted(),await this.iframeHost.startListening()}async stopListening(){return this.assertSessionStarted(),this.iframeHost.stopListening()}async listenOnce(e){return this.assertSessionStarted(),this.iframeHost.listenOnce({timeoutMs:e?.timeoutMs})}getConversation(){return this.conversationCache}setWidgetChrome(e){this.iframeHost?.postWidgetSetChrome(e)}toggleAudioSettings(){this.iframeHost?.postWidgetToggleAudioSettings()}getLastTurn(){if(this.conversationCache.length===0)return[];let e=this.conversationCache[this.conversationCache.length-1].turnId;return this.conversationCache.filter(t=>t.turnId===e)}async end(){this.close()}destroy(){this.closed||(this.closed=!0,this.processorAbortController?.abort(),this.processorAbortController=null,this.endpointAbortController?.abort(),this.endpointAbortController=null,this.attachInFlight=null,this.iframeHost?.destroy(),this.iframeHost=null,xe(this.eventRegistry),this.readyEnvelope=null,this.startedEnvelope=null,this.closeHandlers.length=0,this.attached=!1)}resolveMintInteraction(){return this.bootstrap.kind===`launch`?{}:{mode:this.bootstrap.mode,speechInputMode:this.bootstrap.speechInputMode}}getSessionId(){return this.resolvedSession?.id??``}emitWrapped(e,t){let n=_e(e,this.getSessionId(),t);return be(this.eventRegistry,e,n),n}queueProcessorTurn(e){if(!e.isFinal||!e.text.trim()||!this.conversationProcessor)return;let t=this.conversationProcessor;this.processorAbortController?.abort(),this.processorAbortController=new AbortController;let n=this.processorAbortController.signal;this.processorChain=this.processorChain.then(async()=>{if(!n.aborted)try{let r=await re(t,{utteranceId:e.utteranceId,text:e.text,conversation:this.conversationCache,signal:n});if(n.aborted)return;if(r.kind===`complete`){let e=r.speech;await this.speech.speak({text:e.text,...e.characterId?{characterId:e.characterId}:{},queue:e.behavior===`interrupt`?`replace-active`:`append`});return}await this.iframeHost.speakProcessorStream(r.stream,{signal:n})}catch(t){if(n.aborted)return;let r=t instanceof Error?t.message:String(t);this.emitWrapped(`conversationProcessorError`,{utteranceId:e.utteranceId,message:r})}})}assertAttached(){if(!this.attached||!this.iframeHost)throw Error(`Call Experience.attach() before using speech APIs.`)}assertSessionStarted(){if(this.assertAttached(),!this.startedEnvelope)throw Error(`Session has not started. Wait for the player start button and the started event before using speak() or listening APIs.`)}close(){this.closed||(this.closed=!0,this.endpointAbortController?.abort(),this.endpointAbortController=null,this.attachInFlight=null,this.iframeHost?.destroy(),this.iframeHost=null,this.attached=!1)}createPlayerFacade(){return{close:()=>{this.close()},destroy:()=>{this.destroy()},on:(e,t)=>{e===`close`&&this.closeHandlers.push(t)}}}};function Je(e){return e?{textSpeech:e.capabilities.speech.output,externalSpeechAudio:e.capabilities.speech.externalAudio}:{textSpeech:!0,externalSpeechAudio:!0}}function Ye(e,t){let n=e.trim();if(!n)return null;if(/^https?:\/\//i.test(n))try{return new URL(n)}catch{return null}let r=t.replace(/\/$/,``),i=n.startsWith(`/`)?n:`/${n}`;try{return new URL(i,`${r}/`)}catch{return null}}function Xe(e){try{if(document.referrer){let e=new URL(document.referrer);if(e.origin===window.location.origin&&e.pathname!==window.location.pathname)return`${e.pathname}${e.search}${e.hash}`}}catch{}return e}function Ze(e,t=`/meet`){if(e.reason!==`user`)return;let n=Ye(e.returnUrl?.trim()||Xe(t),window.location.origin);n?.protocol.startsWith(`http`)&&window.location.assign(n.toString())}var Qe=/\b(exp_[A-Za-z0-9][A-Za-z0-9_-]{2,127})\b/,$e=/(?:Your origin|origin)\s+(\S+)\s+is not an allowed origin/i;function et(e){return e instanceof Error?e.message:String(e)}function tt(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function nt(e){return Qe.exec(e)?.[1]}function rt(e){return $e.exec(e)?.[1]}function it(e,t){let n=et(e).trim()||`Unknown error`,r=t?.experienceId?.trim()||nt(n)||void 0,i=t?.origin?.trim()||rt(n)||tt()||void 0;return/No playable experience found/i.test(n)||/^Experience is not available\.?$/i.test(n)||/^Unknown experience\.?$/i.test(n)||/experience_unavailable/i.test(n)?{kind:`not_found`,title:`The application tried to load an avatar experience that doesn’t exist.`,detail:`Experience with id ${r??`the requested experience`} does not exist`,technicalMessage:n,experienceId:r,origin:i}:/origin_not_allowed/i.test(n)||/is not an allowed origin/i.test(n)||/^Origin not allowed/i.test(n)?{kind:`origin_not_allowed`,title:`The application tried to load an avatar experience from a website that isn’t allowed.`,detail:`Origin ${i??`this page`} is not allowed for experience ${r??`the requested experience`}`,technicalMessage:n,experienceId:r,origin:i}:/browser_embeds_disabled/i.test(n)||/^Browser embeds are not enabled/i.test(n)?{kind:`browser_embeds_disabled`,title:`The application tried to load an avatar experience that isn’t enabled for browser embeds.`,detail:`Browser embeds are not enabled for experience ${r??`the requested experience`}`,technicalMessage:n,experienceId:r,origin:i}:{kind:`generic`,title:`This avatar experience couldn’t be started.`,detail:n,technicalMessage:n,experienceId:r,origin:i}}var at=`liforma-experience-load-error-styles`;function ot(){if(typeof document>`u`||document.getElementById(`liforma-experience-load-error-styles`))return;let e=document.createElement(`style`);e.id=at,e.textContent=st,document.head.append(e)}var st=`
|
|
15
15
|
.liforma-loading-screen {
|
|
16
16
|
inset: 0;
|
|
17
17
|
z-index: 20;
|
|
@@ -110,7 +110,7 @@ registerProcessor('${we}', LiformaPcmCaptureProcessor);
|
|
|
110
110
|
.liforma-loading-error-detail[hidden] {
|
|
111
111
|
display: none;
|
|
112
112
|
}
|
|
113
|
-
`;function
|
|
113
|
+
`;function ct(e,t){ot();let n=t,r=!1,i=document.createElement(`div`);i.className=`liforma-loading-screen liforma-loading-screen-absolute`,i.setAttribute(`role`,`alert`),i.setAttribute(`aria-live`,`assertive`);let a=document.createElement(`div`);a.className=`liforma-loading-card liforma-loading-card-error`;let o=document.createElement(`p`);o.className=`liforma-loading-kicker`,o.textContent=`Avatar experience`;let s=document.createElement(`p`);s.className=`liforma-loading-error-title`;let c=document.createElement(`button`);c.type=`button`,c.className=`liforma-loading-error-advanced`;let l=document.createElement(`p`);l.className=`liforma-loading-error-detail`,c.addEventListener(`click`,()=>{r=!r,u()}),a.append(o,s,c,l),i.append(a),e.append(i);function u(){s.textContent=n.title,l.textContent=n.detail,l.hidden=!r,c.textContent=r?`Hide details`:`Advanced`,c.setAttribute(`aria-expanded`,r?`true`:`false`)}return u(),{root:i,setPresentation(e){n=e,r=!1,u()},remove(){i.remove()}}}var lt=`liforma-experience`;function ut(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function dt(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function ft(e){let t=e?.trim();return t===`full`||t===`face`?t:void 0}var pt=class e extends HTMLElement{host=null;errorHost=null;errorOverlay=null;experience=null;bootstrapGeneration=0;static get observedAttributes(){return[`experience-id`,`locale`,`language`,`secondary-locale`,`learning-locale`,`session-endpoint`,`speech-only`,`mode`,`speech-input-mode`,`fit`]}connectedCallback(){this.style.display=`block`,this.style.position=`relative`,this.style.overflow=`hidden`,this.style.width||(this.style.width=`100%`),this.style.height||(this.style.height=`100%`);let e=getComputedStyle(this).minHeight;!this.style.minHeight&&(e===`0px`||e===`auto`)&&(this.style.minHeight=`480px`),this.errorHost||(this.errorHost=document.createElement(`div`),this.errorHost.style.cssText=`position:absolute;inset:0;z-index:20;pointer-events:none;`,this.append(this.errorHost)),this.host||(this.host=document.createElement(`div`),this.host.style.cssText=`position:absolute;inset:0;overflow:hidden;`,this.append(this.host)),this.bootstrap()}disconnectedCallback(){this.bootstrapGeneration+=1,this.experience?.destroy(),this.experience=null,this.clearError()}attributeChangedCallback(t,n,r){e.observedAttributes.includes(t)&&(n===r||!this.isConnected||(this.bootstrapGeneration+=1,this.experience?.destroy(),this.experience=null,this.clearError(),this.host&&this.host.replaceChildren(),this.bootstrap()))}async bootstrap(){let e=this.getAttribute(`experience-id`)?.trim(),t=this.getAttribute(`session-endpoint`)?.trim(),n=this.getAttribute(`locale`)?.trim()||void 0,r=this.getAttribute(`language`)?.trim()||void 0,i=this.getAttribute(`secondary-locale`)?.trim()||void 0,a=this.getAttribute(`learning-locale`)?.trim()||void 0,o=this.getAttribute(`speech-only`)===`true`,s=ut(this.getAttribute(`mode`)),c=dt(this.getAttribute(`speech-input-mode`)),l=ft(this.getAttribute(`fit`));if(!e||!this.host)return;let u=++this.bootstrapGeneration;this.clearError();try{let d={experienceId:e,locale:n,language:r,secondaryLocale:i,learningLocale:a,speechOnly:o,mode:s,speechInputMode:c},f=await qe.startSession(t?{...d,sessionEndpoint:t}:d);if(u!==this.bootstrapGeneration){f.destroy();return}this.experience=f;let p=await f.attach({container:this.host,...l?{fit:l}:{}});if(u!==this.bootstrapGeneration){f.destroy(),this.experience=null;return}p.on(`close`,e=>{this.dispatchEvent(new CustomEvent(`close`,{detail:e,bubbles:!0})),Ze(e)})}catch(t){if(u!==this.bootstrapGeneration)return;this.showError(t,e),console.error(`[liforma-experience]`,t),this.experience?.destroy(),this.experience=null}}showError(e,t){this.clearError(),this.errorHost&&(this.errorHost.style.pointerEvents=`auto`,this.errorOverlay=ct(this.errorHost,it(e,{experienceId:t})))}clearError(){this.errorOverlay?.remove(),this.errorOverlay=null,this.errorHost&&(this.errorHost.style.pointerEvents=`none`,this.errorHost.replaceChildren())}};typeof customElements<`u`&&!customElements.get(lt)&&customElements.define(lt,pt);var mt=/(\/avatars\/[^/]+\/)(\d+)(\/)/i,ht=/_CH(\.webp)/i,gt=/(-)(\d+x\d+)(\.webp)(\?|$)/i;function _t(e){let t=e.trim();if(!t)return t;let n=t.replace(mt,(e,t,n,r)=>n===`256`?`${t}${n}${r}`:`${t}256${r}`);return n=n.replace(ht,`_neutral$1`),n=n.replace(gt,(e,t,n,r,i)=>n===`256x256`?`${t}${n}${r}${i}`:`${t}256x256${r}${i}`),n}function vt(e){let t=e.avatarImage?.trim()||e.galleryThumb?.avatarImage?.trim()||``;if(!t)return null;let n=e.backgroundImage?.trim()||e.galleryThumb?.backgroundImage?.trim()||``,r=e.foregroundImage?.trim()||e.galleryThumb?.foregroundImage?.trim()||``,i=e.fallbackImage?.trim()||``;return{avatarImage:_t(t),...n?{backgroundImage:_t(n)}:{},...r?{foregroundImage:_t(r)}:{},...i?{fallbackImage:_t(i)}:{}}}var yt=`https://player.liforma.ai`,bt=`http://localhost:3002`;function xt(e){return e.href?.trim()?`anchor`:e.hasClickHandler?`button`:e.experienceId?.trim()?`anchor`:`presentational`}function St(e){let n=e?.trim();return n?n.replace(/\/$/,``):t()?bt:yt}function Ct(e){let t=e.experienceId.trim(),n=St(e.playerBaseUrl),r=new URL(`${n}/${encodeURIComponent(t)}`),i=e.returnUrl?.trim();return i&&r.searchParams.set(`returnUrl`,i),r.toString()}function wt(e){let t=e.href?.trim();if(t)return t;let n=e.experienceId?.trim();if(!n)return;let r=e.returnUrl?.trim();return!r&&e.useCurrentPageAsReturnUrl&&typeof window<`u`&&(r=window.location.href),Ct({experienceId:n,...r?{returnUrl:r}:{},playerBaseUrl:e.playerBaseUrl})}function Tt(){return typeof window>`u`?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}var X=0,Et=[];function Dt(){return Tt()?4:1/0}function Ot(){return Tt()?160:0}function kt(){let e=Dt();for(;X<e&&Et.length>0;){let e=Et.shift();if(!e||e.cancelled)continue;X+=1,e.start();let t=Ot();if(t<=0){X=Math.max(0,X-1);continue}window.setTimeout(()=>{X=Math.max(0,X-1),kt()},t)}}function At(e){if(!Tt())return e(),()=>{};let t={start:e,cancelled:!1};return Et.push(t),kt(),()=>{t.cancelled=!0}}function jt(){return Tt()?`96px 0px`:`280px 0px`}function Mt(e){let t=e.trim().split(/\s+/)[0]??`0px`,n=Number.parseFloat(t);return Number.isFinite(n)?Math.abs(n):280}function Nt(e,t){if(typeof window>`u`)return!1;let n=e.getBoundingClientRect();return n.bottom>=-t&&n.top<=window.innerHeight+t}function Pt(e,t){let{onVisibleChange:n}=t,r=t.rootMargin??jt(),i=Mt(r),a=!1,o=!1,s=null,c=()=>{o||(s?.(),s=At(()=>{s=null,o=!0,n(!0)}))},l=e=>{if(e!==a){if(a=e,e){c();return}s?.(),s=null,n(!1)}};if(typeof IntersectionObserver>`u`)return c(),()=>{s?.(),s=null};let u=new IntersectionObserver(e=>{l(e.some(e=>e.isIntersecting))},{root:null,rootMargin:r,threshold:0});return u.observe(e),Nt(e,i)&&l(!0),()=>{s?.(),s=null,u.disconnect()}}function Ft(e,t){let n=()=>t();return e.complete?queueMicrotask(n):(e.addEventListener(`load`,n,{once:!0}),e.addEventListener(`error`,n,{once:!0})),()=>{e.removeEventListener(`load`,n),e.removeEventListener(`error`,n)}}function It(){return typeof window>`u`||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}function Lt(e,t){return((e.top+e.height/2)/Math.max(t,1)-.5)*2}var Rt=new Set,zt=!1,Z=0;function Bt(){if(Z=0,Rt.size===0||typeof window>`u`)return;let e=window.innerHeight;for(let t of Rt){if(t.pointerActive?.())continue;let n=t.element.getBoundingClientRect();n.bottom<-64||n.top>e+64||t.onParallax(Lt(n,e))}}function Vt(){Z===0&&(Z=requestAnimationFrame(Bt))}function Ht(){zt||typeof window>`u`||(zt=!0,window.addEventListener(`scroll`,Vt,{passive:!0}),window.addEventListener(`resize`,Vt,{passive:!0}))}function Ut(){Rt.size>0||!zt||typeof window>`u`||(zt=!1,Z!==0&&(cancelAnimationFrame(Z),Z=0),window.removeEventListener(`scroll`,Vt),window.removeEventListener(`resize`,Vt))}function Wt(e,t){if(!It())return()=>{};let n={element:e,onParallax:t.onParallax,pointerActive:t.pointerActive};return Rt.add(n),Ht(),n.pointerActive?.()||t.onParallax(Lt(e.getBoundingClientRect(),window.innerHeight)),()=>{Rt.delete(n),Ut()}}function Gt(e){let t=0,n=0,r=!1,i=!1,a=!1,o=()=>{let a=r||i;e.classList.toggle(`liforma-et--parallax`,a),e.classList.toggle(`liforma-et--scroll-parallax`,i),e.style.setProperty(`--liforma-et-parallax-x`,String(t)),e.style.setProperty(`--liforma-et-parallax-y`,String(n))},s=Wt(e,{onParallax:e=>{i=!0,a||(t=e,n=0,o())},pointerActive:()=>a}),c=r=>{if(i)return;let a=e.getBoundingClientRect();a.width<=0||a.height<=0||(t=((r.clientX-a.left)/a.width-.5)*2,n=((r.clientY-a.top)/a.height-.5)*2,o())},l=e=>{a=!0,e.pointerType===`mouse`&&(r=!0),o()},u=()=>{let s=a;a=!1,r=!1,i&&s?(t=Lt(e.getBoundingClientRect(),window.innerHeight),n=0):i||(t=0,n=0),o()},d=e=>{e.pointerType===`mouse`&&(r=!0,o())},f=()=>{a||(r=!1,i||(t=0,n=0),o())};return e.addEventListener(`pointermove`,c),e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),e.addEventListener(`pointerenter`,d),e.addEventListener(`pointerleave`,f),()=>{s(),e.removeEventListener(`pointermove`,c),e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u),e.removeEventListener(`pointerenter`,d),e.removeEventListener(`pointerleave`,f),e.classList.remove(`liforma-et--parallax`,`liforma-et--scroll-parallax`),e.style.removeProperty(`--liforma-et-parallax-x`),e.style.removeProperty(`--liforma-et-parallax-y`)}}var Kt=`.liforma-et {
|
|
114
114
|
--liforma-et-parallax-x: 0;
|
|
115
115
|
--liforma-et-parallax-y: 0;
|
|
116
116
|
--liforma-et-bg-scale: 1;
|
|
@@ -198,8 +198,8 @@ button.liforma-et {
|
|
|
198
198
|
display: block;
|
|
199
199
|
width: 100%;
|
|
200
200
|
height: 100%;
|
|
201
|
-
object-fit:
|
|
202
|
-
object-position:
|
|
201
|
+
object-fit: contain;
|
|
202
|
+
object-position: center bottom;
|
|
203
203
|
transform: scale(var(--liforma-et-avatar-scale))
|
|
204
204
|
translate(
|
|
205
205
|
calc(var(--liforma-et-parallax-x) * var(--liforma-et-avatar-shift)),
|
|
@@ -211,9 +211,24 @@ button.liforma-et {
|
|
|
211
211
|
transform 160ms ease;
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
214
|
+
/* Gallery plates are typically square in a square tile — contain vs cover is a no-op
|
|
215
|
+
without a zoom. Scale the whole scene from the upper third so Face matches
|
|
216
|
+
player fit (location + avatar crop together). */
|
|
217
|
+
.liforma-et--fit-face {
|
|
218
|
+
--liforma-et-avatar-scale: 1.85;
|
|
219
|
+
--liforma-et-bg-scale: 1.85;
|
|
220
|
+
--liforma-et-fg-scale: 1.85;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
.liforma-et--fit-face .liforma-et__avatar,
|
|
224
|
+
.liforma-et--fit-face .liforma-et__background,
|
|
225
|
+
.liforma-et--fit-face .liforma-et__foreground {
|
|
226
|
+
transform-origin: 50% 18%;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
.liforma-et--fit-face .liforma-et__avatar {
|
|
230
|
+
object-fit: cover;
|
|
231
|
+
object-position: 50% 18%;
|
|
217
232
|
}
|
|
218
233
|
|
|
219
234
|
.liforma-et__foreground {
|
|
@@ -252,8 +267,10 @@ button.liforma-et {
|
|
|
252
267
|
will-change: transform;
|
|
253
268
|
}
|
|
254
269
|
|
|
255
|
-
.liforma-et--parallax
|
|
256
|
-
--liforma-et-avatar-scale: 1.
|
|
270
|
+
.liforma-et--parallax.liforma-et--fit-face {
|
|
271
|
+
--liforma-et-avatar-scale: 1.95;
|
|
272
|
+
--liforma-et-bg-scale: 1.95;
|
|
273
|
+
--liforma-et-fg-scale: 1.95;
|
|
257
274
|
--liforma-et-avatar-shift: 0px;
|
|
258
275
|
}
|
|
259
276
|
|
|
@@ -277,12 +294,18 @@ button.liforma-et {
|
|
|
277
294
|
--liforma-et-avatar-shift: 0px;
|
|
278
295
|
}
|
|
279
296
|
|
|
297
|
+
.liforma-et--parallax.liforma-et--fit-face {
|
|
298
|
+
--liforma-et-avatar-scale: 1.85;
|
|
299
|
+
--liforma-et-bg-scale: 1.85;
|
|
300
|
+
--liforma-et-fg-scale: 1.85;
|
|
301
|
+
}
|
|
302
|
+
|
|
280
303
|
.liforma-et__background,
|
|
281
304
|
.liforma-et__foreground,
|
|
282
305
|
.liforma-et__avatar {
|
|
283
306
|
transition: none;
|
|
284
307
|
}
|
|
285
|
-
}`,
|
|
308
|
+
}`,qt=!1;function Jt(e){if(typeof document>`u`||qt)return;if(document.querySelector(`style[data-liforma-et]`)){qt=!0;return}let t=document.createElement(`style`);t.setAttribute(`data-liforma-et`,``),t.textContent=e,document.head.appendChild(t),qt=!0}var Yt=`liforma-experience-thumbnail`;function Xt(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t.avatarImage==`string`)return t}catch{}}var Zt=class extends HTMLElement{static get observedAttributes(){return[`experience-id`,`gallery-thumb`,`avatar-image`,`background-image`,`foreground-image`,`fallback-image`,`alt`,`href`,`target`,`rel`,`return-url`,`player-base-url`,`parallax`,`fit`,`lazy`]}#e=null;#t=[];#n=!1;#r=!1;#i=!1;#a=!1;#o=0;#s=0;#c=!1;#l=!1;#u=!1;#d=!1;connectedCallback(){this.#m()}disconnectedCallback(){this.#f()}attributeChangedCallback(){this.isConnected&&this.#m()}#f(){for(let e of this.#t)e();this.#t=[],this.#e=null}#p(e,t){if(!this.hasAttribute(e))return t;let n=this.getAttribute(e);return n===null||n===``||n===`true`?!0:n===`false`?!1:t}#m(){this.#f();let e=this.shadowRoot??this.attachShadow({mode:`open`}),t=document.createElement(`style`);t.textContent=Kt,e.replaceChildren(t);let n=this.getAttribute(`alt`)?.trim()||`Experience`,r=this.getAttribute(`href`),i=this.getAttribute(`experience-id`),a=xt({href:r,hasClickHandler:this.hasAttribute(`onclick`)||typeof this.onclick==`function`,experienceId:i}),o=vt({galleryThumb:Xt(this.getAttribute(`gallery-thumb`)),avatarImage:this.getAttribute(`avatar-image`)??void 0,backgroundImage:this.getAttribute(`background-image`)??void 0,foregroundImage:this.getAttribute(`foreground-image`)??void 0,fallbackImage:this.getAttribute(`fallback-image`)??void 0});if(!o)return;let s=this.#p(`parallax`,!0),c=this.getAttribute(`fit`)?.trim()===`face`?`face`:`full`,l=this.#p(`lazy`,!0);this.#n=!l;let u=a===`anchor`&&!r?.trim()&&!!i?.trim(),d=wt({href:r??void 0,experienceId:i??void 0,returnUrl:this.getAttribute(`return-url`)??void 0,playerBaseUrl:this.getAttribute(`player-base-url`)??void 0,useCurrentPageAsReturnUrl:u&&!this.getAttribute(`return-url`)?.trim()}),f;if(a===`anchor`&&d){let e=document.createElement(`a`);e.href=d;let t=this.getAttribute(`target`),n=this.getAttribute(`rel`);t&&(e.target=t),n&&(e.rel=n),f=e}else if(a===`button`){let e=document.createElement(`button`);e.type=`button`,f=e}else f=document.createElement(`div`),f.setAttribute(`role`,`img`);f.className=`liforma-et`,f.setAttribute(`aria-label`,n),this.#e=f,e.appendChild(f);let p=()=>{let e=!!o.backgroundImage,t=s&&(this.#r||this.#a),n=this.#n&&(this.#u||this.#l||this.#d);f.className=[`liforma-et`,e?`liforma-et--scene`:``,c===`face`?`liforma-et--fit-face`:``,t?`liforma-et--parallax`:``,this.#a?`liforma-et--scroll-parallax`:``,this.#n&&!n?`liforma-et--loading`:``,n?`liforma-et--revealed`:``].filter(Boolean).join(` `),f.style.setProperty(`--liforma-et-parallax-x`,String(this.#o)),f.style.setProperty(`--liforma-et-parallax-y`,String(this.#s))},m=document.createElement(`span`);m.className=`liforma-et__placeholder`,m.setAttribute(`aria-hidden`,`true`),f.appendChild(m);let h=()=>{if(!this.#n)return;let e=this.#c&&o.fallbackImage?o.fallbackImage:o.avatarImage;if(o.backgroundImage&&!f.querySelector(`.liforma-et__background`)){let e=document.createElement(`img`);e.className=`liforma-et__background liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=o.backgroundImage,this.#t.push(Ft(e,()=>{this.#l=!0,e.classList.add(`liforma-et__media--ready`),p()})),f.appendChild(e)}let t=f.querySelector(`.liforma-et__avatar`);if(t||(t=document.createElement(`img`),t.className=`liforma-et__avatar liforma-et__media`,t.alt=``,t.decoding=`async`,t.addEventListener(`error`,()=>{o.fallbackImage&&!this.#c?(this.#c=!0,t.src=o.fallbackImage):(this.#u=!0,p())}),this.#t.push(Ft(t,()=>{this.#u=!0,t.classList.add(`liforma-et__media--ready`),p()})),f.appendChild(t)),t.src!==e&&(t.src=e),o.foregroundImage&&!f.querySelector(`.liforma-et__foreground`)){let e=document.createElement(`img`);e.className=`liforma-et__foreground liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=o.foregroundImage,this.#t.push(Ft(e,()=>{this.#d=!0,e.classList.add(`liforma-et__media--ready`),p()})),f.appendChild(e)}p()};if(l?this.#t.push(Pt(f,{onVisibleChange:e=>{e&&(this.#n=!0,h(),p())}})):h(),s){this.#t.push(Wt(f,{onParallax:e=>{this.#a=!0,this.#i||(this.#o=e,this.#s=0,p())},pointerActive:()=>this.#i}));let e=e=>{if(this.#a)return;let t=f.getBoundingClientRect();t.width<=0||t.height<=0||(this.#o=((e.clientX-t.left)/t.width-.5)*2,this.#s=((e.clientY-t.top)/t.height-.5)*2,p())},t=e=>{this.#i=!0,e.pointerType===`mouse`&&(this.#r=!0),p()},n=()=>{let e=this.#i;this.#i=!1,this.#r=!1,this.#a&&e?(this.#o=Lt(f.getBoundingClientRect(),window.innerHeight),this.#s=0):this.#a||(this.#o=0,this.#s=0),p()};f.addEventListener(`pointermove`,e),f.addEventListener(`pointerdown`,t),f.addEventListener(`pointerup`,n),f.addEventListener(`pointercancel`,n),f.addEventListener(`pointerenter`,e=>{e.pointerType===`mouse`&&(this.#r=!0,p())}),f.addEventListener(`pointerleave`,()=>{this.#i||(this.#r=!1,this.#a||(this.#o=0,this.#s=0),p())}),this.#t.push(()=>{f.removeEventListener(`pointermove`,e),f.removeEventListener(`pointerdown`,t),f.removeEventListener(`pointerup`,n),f.removeEventListener(`pointercancel`,n)})}f.addEventListener(`click`,e=>{if(u&&!this.getAttribute(`return-url`)?.trim()){let t=wt({experienceId:i??void 0,playerBaseUrl:this.getAttribute(`player-base-url`)??void 0,useCurrentPageAsReturnUrl:!0});t&&e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&(e.preventDefault(),window.location.assign(t))}}),p()}};customElements.get(Yt)||customElements.define(Yt,Zt);function Qt(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.avatarImage==`string`?t.avatarImage.trim():``;return n?{avatarImage:n,...typeof t.backgroundImage==`string`&&t.backgroundImage.trim()?{backgroundImage:t.backgroundImage.trim()}:{},...typeof t.foregroundImage==`string`&&t.foregroundImage.trim()?{foregroundImage:t.foregroundImage.trim()}:{}}:null}async function $t(e,t){let n=e.trim();if(!n)throw Error(`Experience preview requires experienceId.`);let r=(t?.apiBaseUrl??a()).replace(/\/$/,``),i=await fetch(`${r}/v1/experiences/${encodeURIComponent(n)}/preview`,{method:`GET`,headers:{Accept:`application/json`},signal:t?.signal});if(!i.ok){let e=`Experience preview failed (${i.status})`;try{let t=await i.json();t.message?.trim()&&(e=t.message.trim())}catch{}throw Error(e)}let o;try{o=await i.json()}catch{throw Error(`Experience preview returned invalid JSON.`)}if(!o||typeof o!=`object`)throw Error(`Experience preview returned an invalid payload.`);let s=o,c=typeof s.experienceId==`string`?s.experienceId.trim():n,l=typeof s.title==`string`?s.title.trim():``,u=Qt(s.galleryThumb);if(!u)throw Error(`Experience preview is missing gallery thumb images.`);return{experienceId:c||n,title:l||c||n,galleryThumb:u}}var en=`(min-width: 768px)`,tn=24,nn=.5,rn=1200,an=.85,on=9/16;function sn(){if(typeof window>`u`)return 800;let e=window.screen?.availHeight;return typeof e==`number`&&e>0?e:window.innerHeight}function cn(e=typeof window<`u`?window.innerWidth:1280,t=typeof window<`u`?window.innerHeight:800,n=tn,r=typeof window<`u`?sn():800){let i=Math.max(160,Math.min(t-n*2,t*an)),a=Math.max(120,e-n*2),o=Math.min(r*nn,rn,i),s=o*on;return s>a&&(s=a,o=s/on,o>i&&(o=i,s=o*on)),{width:Math.round(s),height:Math.round(o)}}function ln(e,t=typeof window<`u`?window.innerWidth:1280,n=typeof window<`u`?window.innerHeight:800,r=tn){return{left:Math.max(r,t-e.width-r),top:Math.max(r,n-e.height-r)}}function un(e,t,n,r=typeof window<`u`?window.innerWidth:1280,i=typeof window<`u`?window.innerHeight:800,a=tn){let o=Math.max(a,r-n.width-a),s=Math.max(a,i-n.height-a);return{left:Math.min(Math.max(a,e),o),top:Math.min(Math.max(a,t),s)}}function Q(e=typeof window<`u`?window.matchMedia.bind(window):()=>({matches:!0})){return e(en).matches}var dn=`
|
|
286
309
|
.liforma-ew {
|
|
287
310
|
box-sizing: border-box;
|
|
288
311
|
position: relative;
|
|
@@ -770,5 +793,5 @@ button.liforma-et {
|
|
|
770
793
|
transition: none;
|
|
771
794
|
}
|
|
772
795
|
}
|
|
773
|
-
`,en=`liforma-experience-widget-styles`;function tn(e=$t){if(typeof document>`u`)return;let t=document.getElementById(en);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=en,n.textContent=e,document.head.append(n)}function nn(e){return e===`bottom-right`||e===`bottom-left`?e:`static`}function rn(e){if(typeof e==`number`&&Number.isFinite(e))return`${e}px`;let t=typeof e==`string`?e.trim():``;return t?/^\d+(\.\d+)?$/.test(t)?`${t}px`:t:`16px`}function $(e){return e===`expanded`||e===`docked`}var an=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 0 0-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 0 0-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 0 0-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 0 0-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 0 0 1.066-2.573c-.94-1.543.826-3.31 2.37-2.37c1 .608 2.296.07 2.572-1.065"/><path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0-6 0"/></svg>`,on=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12l-4.9 4.89a1 1 0 1 0 1.42 1.42L12 13.41l4.89 4.9a1 1 0 0 0 1.42-1.42L13.41 12l4.9-4.89a1 1 0 0 0-.01-1.4Z"/></svg>`,sn=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 10h-4V6m6-2l-6 6m-8 4h4v4m0-4l-6 6"/></svg>`,cn=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h4v4m-6 2l6-6M8 20H4v-4m0 4l6-6"/></svg>`;function ln(e,t,n){Lt(Ft);let r=ot({galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage});if(!r)return e.replaceChildren(),null;let i=document.createElement(`div`);i.className=`liforma-et${r.backgroundImage?` liforma-et--scene`:``} liforma-et--revealed`,i.setAttribute(`aria-hidden`,`true`);let a=document.createElement(`span`);a.className=`liforma-et__placeholder`,a.setAttribute(`aria-hidden`,`true`),i.append(a);let o=e=>{e.classList.add(`liforma-et__media--ready`)};if(r.backgroundImage){let e=document.createElement(`img`);e.className=`liforma-et__background liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=r.backgroundImage,e.addEventListener(`load`,()=>o(e),{once:!0}),i.append(e)}let s=document.createElement(`img`);if(s.className=`liforma-et__avatar liforma-et__media`,s.alt=``,s.decoding=`async`,s.src=r.avatarImage,s.addEventListener(`load`,()=>o(s),{once:!0}),s.addEventListener(`error`,()=>{r.fallbackImage&&(s.src=r.fallbackImage)},{once:!0}),i.append(s),r.foregroundImage){let e=document.createElement(`img`);e.className=`liforma-et__foreground liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=r.foregroundImage,e.addEventListener(`load`,()=>o(e),{once:!0}),i.append(e)}return e.replaceChildren(i),n?.parallax===!1?()=>{}:Pt(i)}function un(e){return e.startButton?{...e.startButton,label:e.startButton.label??e.startButtonLabel??`Tap to talk`,placement:e.startButton.placement??`bottom-center`,variant:e.startButton.variant??`primary`}:{label:e.startButtonLabel??`Tap to talk`,placement:`bottom-center`,variant:`primary`}}function dn(e){let t=!1,n=()=>{t||e()},r=()=>{if(t)return;let e=window.requestIdleCallback;if(typeof e==`function`){let t=e(n,{timeout:3e3});i=()=>{window.cancelIdleCallback?.(t)};return}let r=window.setTimeout(n,1);i=()=>window.clearTimeout(r)},i=null;return document.readyState===`complete`?r():window.addEventListener(`load`,r,{once:!0}),()=>{t=!0,window.removeEventListener(`load`,r),i?.()}}function fn(e,t){tn($t);let n=t.experienceId?.trim();if(!n)throw Error(`ExperienceWidget requires experienceId.`);let r=t.prefetch??`onExpand`,i=nn(t.position),a=document.createElement(`div`);a.className=`liforma-ew`,a.dataset.state=`collapsed`,a.dataset.prefetch=r,a.dataset.position=i,a.style.setProperty(`--liforma-ew-max-w`,t.expandedMaxWidth??`100%`),a.style.setProperty(`--liforma-ew-max-h`,t.expandedMaxHeight??`100%`),i!==`static`&&a.style.setProperty(`--liforma-ew-offset`,rn(t.offset));let o=document.createElement(`button`);o.type=`button`,o.className=`liforma-ew__hit`,o.setAttribute(`aria-label`,t.alt),o.disabled=!0;let s=document.createElement(`div`);s.className=`liforma-ew__face`,o.append(s);let c=document.createElement(`div`);c.className=`liforma-ew__face-status`,c.textContent=`Loading…`,s.append(c);let l=document.createElement(`div`);l.className=`liforma-ew__warm`,l.hidden=!0,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`div`);u.className=`liforma-ew__overlay`,u.hidden=!0,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-modal`,`true`),u.setAttribute(`aria-label`,t.alt);let d=document.createElement(`button`);d.type=`button`,d.className=`liforma-ew__backdrop`,d.setAttribute(`aria-label`,`Close experience`);let f=document.createElement(`div`);f.className=`liforma-ew__panel`;let p=document.createElement(`div`);p.className=`liforma-ew__toolbar`,p.hidden=!0;let m=document.createElement(`span`);m.className=`liforma-ew__drag-grip`,m.setAttribute(`aria-hidden`,`true`);let h=document.createElement(`button`);h.type=`button`,h.className=`liforma-ew__icon-btn liforma-ew__dock-toggle`,h.innerHTML=sn,h.setAttribute(`aria-label`,`Reduce`);let g=document.createElement(`button`);g.type=`button`,g.className=`liforma-ew__icon-btn liforma-ew__settings`,g.innerHTML=an,g.setAttribute(`aria-label`,`Audio settings`),g.setAttribute(`aria-pressed`,`false`);let _=document.createElement(`button`);_.type=`button`,_.className=`liforma-ew__icon-btn liforma-ew__close`,_.innerHTML=on,_.setAttribute(`aria-label`,`Close`),p.append(m,h,g,_);let ee=document.createElement(`div`);ee.className=`liforma-ew__stage`;let v=document.createElement(`div`);v.className=`liforma-ew__status`,v.hidden=!0,f.append(ee,v),u.append(d,f),a.append(o,l,u,p),e.replaceChildren(a);let y=null,b=!1,x=!1,te=!1,S=!1,C=!1,w=!1,T=!1,E=0,ne=``,D=null,re=null,O=null,k=null,A=null,j=null,M=null,N=0,ie=0,P=null,ae=!1,oe=new AbortController,se=t.parallax!==!1,F=()=>{let e=a.dataset.state;return e===`expanded`||e===`docked`||e===`collapsed`?e:`collapsed`},I=()=>{O!==null&&(clearTimeout(O),O=null)},ce=()=>{k!==null&&(clearTimeout(k),k=null),a.classList.remove(`liforma-ew--layout-settling`)},le=()=>{for(let e of[f,l,p])e.style.removeProperty(`left`),e.style.removeProperty(`top`),e.style.removeProperty(`width`),e.style.removeProperty(`height`),e.style.removeProperty(`right`),e.style.removeProperty(`bottom`);p.classList.remove(`liforma-ew__toolbar--dragging`),a.classList.remove(`liforma-ew--dock-dragging`)},ue=(e,t,n,r)=>{let i=i=>{i.style.left=`${e}px`,i.style.top=`${t}px`,i.style.width=`${n}px`,i.style.height=`${r}px`,i.style.right=`auto`,i.style.bottom=`auto`};i(f),i(l);let a=p.offsetWidth||120;p.style.left=`${e+n-a-10}px`,p.style.top=`${t+10}px`,p.style.right=`auto`,p.style.bottom=`auto`,p.style.width=`auto`,p.style.height=`auto`},de=(e,t)=>{if(F()!==`docked`)return;let n=Xt(),r=Qt(e-N,t-ie,n);A=r.left,j=r.top,ue(r.left,r.top,n.width,n.height)},fe=(e,t)=>{if(F()!==`docked`||!Number.isFinite(e)||!Number.isFinite(t)||e===0&&t===0)return;let n=Xt(),r=A??f.getBoundingClientRect().left,i=j??f.getBoundingClientRect().top,a=Qt(r+e,i+t,n);A=a.left,j=a.top,ue(a.left,a.top,n.width,n.height)},L=e=>{P===`toolbar`&&(M===null||e.pointerId!==M||(e.preventDefault(),de(e.clientX,e.clientY)))},R=e=>{if(M===null||e&&e.pointerId!==M)return;let t=P;M=null,P=null,p.classList.remove(`liforma-ew__toolbar--dragging`),a.classList.remove(`liforma-ew--dock-dragging`),t===`toolbar`&&ae&&(ae=!1,window.removeEventListener(`pointermove`,L),window.removeEventListener(`pointerup`,R),window.removeEventListener(`pointercancel`,R))},pe=(e,t,n)=>{if(x||F()!==`docked`||!Q()||M!==null)return;M=n,P=`toolbar`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let r=f.getBoundingClientRect();N=e-r.left,ie=t-r.top,ae||(ae=!0,window.addEventListener(`pointermove`,L),window.addEventListener(`pointerup`,R),window.addEventListener(`pointercancel`,R))},me=e=>{if(x||F()!==`docked`||!Q()||M!==null)return;M=e.pointerId,P=`player`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let t=f.getBoundingClientRect();A=t.left,j=t.top},z=e=>{P===`player`&&(M===null||e.pointerId!==M||fe(e.dx,e.dy))},he=e=>{P===`player`&&(M===null||e.pointerId!==M||R())},B=()=>{let e=Q(),t=F();if(!e||t!==`expanded`&&t!==`docked`){h.hidden=!0;return}h.hidden=!1,t===`docked`?(h.innerHTML=cn,h.setAttribute(`aria-label`,`Maximize`)):(h.innerHTML=sn,h.setAttribute(`aria-label`,`Reduce`))},V=e=>{let t=Xt(),n=e&&A!==null&&j!==null?Qt(A,j,t):Zt(t);n=Qt(n.left,n.top,t),A=n.left,j=n.top,ue(n.left,n.top,t.width,t.height),B()},H=()=>{a.classList.remove(`liforma-ew--session-revealed`),requestAnimationFrame(()=>{requestAnimationFrame(()=>{x||!$(a.dataset.state)||a.classList.add(`liforma-ew--session-revealed`)})})},U=e=>{if(ce(),a.classList.remove(`liforma-ew--session-revealed`),a.classList.add(`liforma-ew--layout-settling`),e(),!T){a.classList.remove(`liforma-ew--layout-settling`);return}k=setTimeout(()=>{if(k=null,x||!$(a.dataset.state)){a.classList.remove(`liforma-ew--layout-settling`);return}a.classList.remove(`liforma-ew--layout-settling`),H()},220)},W=()=>(a.classList.add(`liforma-ew--session-concealing`),a.classList.remove(`liforma-ew--session-revealed`),new Promise(e=>{I(),O=setTimeout(()=>{O=null,a.classList.remove(`liforma-ew--session-concealing`),e()},280)})),ge={galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage},G=e=>{if(!e){v.hidden=!0,v.textContent=``;return}v.hidden=!1,v.textContent=e},K=e=>{if(!e){c.hidden=!0,c.textContent=``;return}c.hidden=!1,c.textContent=e,s.contains(c)||s.append(c)},_e=()=>{te=!0,o.disabled=!1,K(null),r===`onExpand`&&t.onPrefetchReady?.()},ve=()=>{S=!0,a.dataset.warm=`true`,l.hidden=!1,T||(o.tabIndex=-1,o.setAttribute(`aria-hidden`,`true`)),t.onPrefetchReady?.()},ye=e=>{D?.(),D=null;let t=ln(s,e,{parallax:se});return t?(D=t,!0):!1},be=()=>{if(ye(ge)){_e();return}K(`Loading…`),Ht(n,{signal:oe.signal}).then(e=>{if(!x){if(!ye({galleryThumb:e.galleryThumb}))throw Error(`Experience preview is missing gallery thumb images.`);_e()}}).catch(e=>{if(x||oe.signal.aborted)return;let n=e instanceof Error?e:Error(String(e));K(`Preview unavailable`),o.disabled=!0,t.onError?.(n),console.error(`[ExperienceWidget]`,n)})},xe=()=>({experienceId:n,ui:`widget`,...t.sessionEndpoint?{sessionEndpoint:t.sessionEndpoint}:{},...t.locale?{locale:t.locale}:{},...t.language?{language:t.language}:{},...t.mode?{mode:t.mode}:{},...t.speechInputMode?{speechInputMode:t.speechInputMode}:{},...t.speechOnly===void 0?{}:{speechOnly:t.speechOnly},...t.embedBaseUrl?{embedBaseUrl:t.embedBaseUrl}:{}}),Se=()=>({...t.fit?{fit:t.fit}:{},startButton:un(t)}),q=(e=!0)=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`true`),le(),a.dataset.state=`expanded`,G(null),typeof document<`u`&&(ne=document.body.style.overflow,document.body.style.overflow=`hidden`),B(),e&&t.onExpanded?.()},Ce=()=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`false`),a.dataset.state=`docked`,G(null),typeof document<`u`&&(document.body.style.overflow=ne),V(!0),B(),y?.setWidgetChrome(`docked`)},we=e=>{e.on(`started`,()=>{x||(T=!0,a.dataset.live=`true`,G(null),t.onStarted?.(),$(a.dataset.state)&&H())})},Te=()=>{ce(),u.hidden=!0,p.hidden=!0,le(),a.dataset.state=`collapsed`,a.classList.remove(`liforma-ew--session-revealed`),a.classList.remove(`liforma-ew--session-concealing`),g.setAttribute(`aria-pressed`,`false`),o.hidden=!1,o.tabIndex=0,o.removeAttribute(`aria-hidden`),te&&(o.disabled=!1),G(null),typeof document<`u`&&(document.body.style.overflow=ne),B()},Ee=()=>{I(),ce(),E+=1,b=!1,S=!1,C=!1,w=!1,T=!1;let e=y;y=null,e?.destroy(),ee.replaceChildren(),l.replaceChildren(),l.hidden=!0,delete a.dataset.warm,delete a.dataset.live,a.classList.remove(`liforma-ew--session-revealed`)},J=()=>{if(!x&&$(a.dataset.state)){if(R(),b=!1,y&&w){let e=y;(async()=>{T&&(await W(),x||y!==e)||(S&&e.setWidgetChrome(`collapsed`),Te(),T?(a.dataset.live=`true`,o.tabIndex=0,o.removeAttribute(`aria-hidden`),o.disabled=!1):S&&ve(),t.onCollapsed?.(),t.onClose?.())})();return}Ee(),Te(),t.onCollapsed?.(),t.onClose?.()}},De=()=>{x||Q()&&F()===`expanded`&&U(()=>{Ce()})},Oe=()=>{x||F()===`docked`&&(R(),U(()=>{le(),q(!1),y?.setWidgetChrome(`expanded`)}))},ke=()=>{!y||!T||(I(),a.classList.remove(`liforma-ew--session-revealed`),q(),y.setWidgetChrome(`expanded`),b=!1,H())},Ae=()=>{!y||!w||T||(I(),a.classList.remove(`liforma-ew--session-revealed`),q(),b=!1,S&&y.setWidgetChrome(`expanded`))},je=e=>{x||e!==E&&!T||(I(),a.classList.remove(`liforma-ew--session-revealed`),q(),b=!1,y?.setWidgetChrome(`expanded`),T&&H())},Y=()=>{if(x||C||S||y||$(a.dataset.state))return;C=!0;let e=E;l.hidden=!1,(async()=>{try{let t=await Ie.startSession(xe());if(x||e!==E){t.destroy();return}y=t,we(t);let n=await t.attach({container:l,...Se(),onWidgetReady:()=>{x||e!==E||(C=!1,w=!0,ve())},onWidgetExpand:()=>{je(e)},onWidgetAudioSettings:e=>{x||Pe(e)},onWidgetDragStart:e=>{x||me(e)},onWidgetDragMove:e=>{x||z(e)},onWidgetDragEnd:e=>{x||he(e)},onPlayerStatusChange:e=>{x||e===`error`&&$(a.dataset.state)&&G(`Could not load the experience.`)}});if(x||e!==E){t.destroy(),y===t&&(y=null);return}w=!0,n.on(`close`,()=>{x||J()})}catch(n){if(x||e!==E)return;C=!1,l.hidden=!0,l.replaceChildren(),y=null;let r=n instanceof Error?n:Error(String(n));t.onError?.(r),console.error(`[ExperienceWidget] warm prefetch failed`,r)}})()},X=()=>{if(x||b||!te||$(a.dataset.state))return;if(y&&T){ke();return}if(y&&w){Ae();return}let e=++E;b=!0,S=!1,C=!1,w=!1,T=!1,delete a.dataset.warm,delete a.dataset.live,l.hidden=!0,l.replaceChildren(),y&&=(y.destroy(),null),(async()=>{try{q();let t=await Ie.startSession(xe());if(x||e!==E){t.destroy();return}y=t,we(t);let n=await t.attach({container:ee,...Se(),onWidgetAudioSettings:e=>{x||Pe(e)},onWidgetDragStart:e=>{x||me(e)},onWidgetDragMove:e=>{x||z(e)},onWidgetDragEnd:e=>{x||he(e)},onPlayerStatusChange:e=>{x||(e===`error`?G(`Could not load the experience.`):$(a.dataset.state)&&G(null))}});if(x||e!==E){t.destroy(),y===t&&(y=null);return}w=!0,n.on(`close`,()=>{x||J()})}catch(n){if(x||e!==E)return;let r=n instanceof Error?n:Error(String(n));G(r.message),t.onError?.(r),console.error(`[ExperienceWidget]`,r)}finally{e===E&&(b=!1)}})()},Me=()=>{if(!(x||$(a.dataset.state))){if(y&&T){ke();return}if(y&&w){Ae();return}X()}},Ne=e=>{if(e.stopPropagation(),F()===`expanded`){De();return}F()===`docked`&&Oe()},Pe=e=>{g.setAttribute(`aria-pressed`,e?`true`:`false`)},Fe=e=>{e.stopPropagation(),$(a.dataset.state)&&y?.toggleAudioSettings()},Le=e=>{F()===`docked`&&Q()&&(e.target?.closest(`button`)||(e.preventDefault(),pe(e.clientX,e.clientY,e.pointerId)))},Re=e=>{e.key===`Escape`&&$(a.dataset.state)&&(e.preventDefault(),J())},ze=()=>{if(!x){if(F()===`docked`){if(!Q()){Oe();return}T?U(()=>{V(!0)}):V(!0);return}B()}},Be=typeof window<`u`?window.matchMedia(Ut):null,Ve=()=>{if(!x){if(F()===`docked`&&!Q()){Oe();return}B()}};return o.addEventListener(`click`,Me),d.addEventListener(`click`,J),_.addEventListener(`click`,e=>{e.stopPropagation(),J()}),h.addEventListener(`click`,Ne),g.addEventListener(`click`,Fe),p.addEventListener(`pointerdown`,Le),window.addEventListener(`keydown`,Re),window.addEventListener(`resize`,ze),Be?.addEventListener(`change`,Ve),be(),B(),r===`eager`?queueMicrotask(()=>{x||Y()}):r===`idle`&&(re=dn(()=>{x||Y()})),{root:a,expand:Me,collapse:J,dock:De,maximize:Oe,prefetch(){if(r===`onExpand`){Y();return}Y()},destroy(){x||(x=!0,R(),re?.(),re=null,oe.abort(),D?.(),D=null,window.removeEventListener(`keydown`,Re),window.removeEventListener(`resize`,ze),Be?.removeEventListener(`change`,Ve),Ee(),Te(),e.replaceChildren())}}}var pn=`liforma-experience-widget`;function mn(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.avatarImage==`string`)return t}catch{}}function hn(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function gn(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function _n(e){let t=e?.trim();return t===`full`||t===`face`?t:void 0}function vn(e){let t=e?.trim();return t===`en`||t===`es`?t:void 0}function yn(e){let t=e?.trim();return t===`bottom-right`||t===`bottom-left`?t:`static`}var bn=class extends HTMLElement{static get observedAttributes(){return[`experience-id`,`alt`,`gallery-thumb`,`avatar-image`,`background-image`,`foreground-image`,`fallback-image`,`prefetch`,`parallax`,`position`,`offset`,`session-endpoint`,`language`,`mode`,`speech-input-mode`,`speech-only`,`fit`,`expanded-max-width`,`expanded-max-height`,`start-button-label`]}#e=null;#t=null;connectedCallback(){this.#n(),this.#r()}disconnectedCallback(){this.#e?.destroy(),this.#e=null}attributeChangedCallback(){this.isConnected&&(this.#n(),this.#r())}#n(){if(yn(this.getAttribute(`position`))!==`static`){this.style.display=`contents`,this.style.removeProperty(`width`),this.style.removeProperty(`height`),this.style.removeProperty(`min-height`);return}if(this.style.display=`block`,this.style.width||=`100%`,this.style.height||=`100%`,!this.style.minHeight){let e=getComputedStyle(this).minHeight;(e===`0px`||e===`auto`)&&(this.style.minHeight=`224px`)}}#r(){this.#e?.destroy(),this.#e=null;let e=this.getAttribute(`experience-id`)?.trim(),t=this.getAttribute(`alt`)?.trim()||`Open experience`;if(!e)return;let n=yn(this.getAttribute(`position`));this.#t||(this.#t=document.createElement(`div`),this.replaceChildren(this.#t)),this.#t.style.cssText=n===`static`?`width:100%;height:100%;min-height:inherit;`:`display:contents;`;let r=this.getAttribute(`prefetch`)?.trim(),i=r===`idle`||r===`eager`||r===`onExpand`?r:`onExpand`,a=this.getAttribute(`speech-only`),o=this.getAttribute(`offset`);try{this.#e=fn(this.#t,{experienceId:e,alt:t,galleryThumb:mn(this.getAttribute(`gallery-thumb`)),avatarImage:this.getAttribute(`avatar-image`)??void 0,backgroundImage:this.getAttribute(`background-image`)??void 0,foregroundImage:this.getAttribute(`foreground-image`)??void 0,fallbackImage:this.getAttribute(`fallback-image`)??void 0,prefetch:i,parallax:this.getAttribute(`parallax`)!==`false`,position:n,offset:o===null?void 0:o,sessionEndpoint:this.getAttribute(`session-endpoint`)??void 0,language:vn(this.getAttribute(`language`)),mode:hn(this.getAttribute(`mode`)),speechInputMode:gn(this.getAttribute(`speech-input-mode`)),speechOnly:a===null?void 0:a===``||a===`true`,fit:_n(this.getAttribute(`fit`)),expandedMaxWidth:this.getAttribute(`expanded-max-width`)??void 0,expandedMaxHeight:this.getAttribute(`expanded-max-height`)??void 0,startButtonLabel:this.getAttribute(`start-button-label`)??void 0,onExpanded:()=>{this.dispatchEvent(new CustomEvent(`expanded`,{bubbles:!0}))},onCollapsed:()=>{this.dispatchEvent(new CustomEvent(`collapsed`,{bubbles:!0}))},onStarted:()=>{this.dispatchEvent(new CustomEvent(`started`,{bubbles:!0}))},onClose:()=>{this.dispatchEvent(new CustomEvent(`close`,{bubbles:!0}))},onError:e=>{this.dispatchEvent(new CustomEvent(`error`,{detail:e,bubbles:!0}))}})}catch(e){console.error(`[liforma-experience-widget]`,e)}}};return typeof customElements<`u`&&!customElements.get(pn)&&customElements.define(pn,bn),window.Liforma={Experience:Ie,sdkVersion:`v2`,features:{speakApi:!0,speechAudioApi:!0}},e.Experience=Ie,e.SPEECH_LIMITS=V,e.SpeechBufferTimeoutError=ge,e.SpeechRuntimeError=W,e.SpeechUtteranceClosedError=U,e.UnsupportedSpeechOperationError=H,e})({});
|
|
796
|
+
`,fn=`liforma-experience-widget-styles`;function pn(e=dn){if(typeof document>`u`)return;let t=document.getElementById(fn);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=fn,n.textContent=e,document.head.append(n)}function mn(e){return e===`bottom-right`||e===`bottom-left`?e:`static`}function hn(e){if(typeof e==`number`&&Number.isFinite(e))return`${e}px`;let t=typeof e==`string`?e.trim():``;return t?/^\d+(\.\d+)?$/.test(t)?`${t}px`:t:`16px`}function $(e){return e===`expanded`||e===`docked`}var gn=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 0 0-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 0 0-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 0 0-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 0 0-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 0 0 1.066-2.573c-.94-1.543.826-3.31 2.37-2.37c1 .608 2.296.07 2.572-1.065"/><path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0-6 0"/></svg>`,_n=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12l-4.9 4.89a1 1 0 1 0 1.42 1.42L12 13.41l4.89 4.9a1 1 0 0 0 1.42-1.42L13.41 12l4.9-4.89a1 1 0 0 0-.01-1.4Z"/></svg>`,vn=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 10h-4V6m6-2l-6 6m-8 4h4v4m0-4l-6 6"/></svg>`,yn=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h4v4m-6 2l6-6M8 20H4v-4m0 4l6-6"/></svg>`;function bn(e,t,n){Jt(Kt);let r=vt({galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage});if(!r)return e.replaceChildren(),null;let i=document.createElement(`div`);i.className=`liforma-et${r.backgroundImage?` liforma-et--scene`:``} liforma-et--revealed`,i.setAttribute(`aria-hidden`,`true`);let a=document.createElement(`span`);a.className=`liforma-et__placeholder`,a.setAttribute(`aria-hidden`,`true`),i.append(a);let o=e=>{e.classList.add(`liforma-et__media--ready`)};if(r.backgroundImage){let e=document.createElement(`img`);e.className=`liforma-et__background liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=r.backgroundImage,e.addEventListener(`load`,()=>o(e),{once:!0}),i.append(e)}let s=document.createElement(`img`);if(s.className=`liforma-et__avatar liforma-et__media`,s.alt=``,s.decoding=`async`,s.src=r.avatarImage,s.addEventListener(`load`,()=>o(s),{once:!0}),s.addEventListener(`error`,()=>{r.fallbackImage&&(s.src=r.fallbackImage)},{once:!0}),i.append(s),r.foregroundImage){let e=document.createElement(`img`);e.className=`liforma-et__foreground liforma-et__media`,e.alt=``,e.decoding=`async`,e.src=r.foregroundImage,e.addEventListener(`load`,()=>o(e),{once:!0}),i.append(e)}return e.replaceChildren(i),n?.parallax===!1?()=>{}:Gt(i)}function xn(e){return e.startButton?{...e.startButton,label:e.startButton.label??e.startButtonLabel??`Tap to talk`,placement:e.startButton.placement??`bottom-center`,variant:e.startButton.variant??`primary`}:{label:e.startButtonLabel??`Tap to talk`,placement:`bottom-center`,variant:`primary`}}function Sn(e){let t=!1,n=()=>{t||e()},r=()=>{if(t)return;let e=window.requestIdleCallback;if(typeof e==`function`){let t=e(n,{timeout:3e3});i=()=>{window.cancelIdleCallback?.(t)};return}let r=window.setTimeout(n,1);i=()=>window.clearTimeout(r)},i=null;return document.readyState===`complete`?r():window.addEventListener(`load`,r,{once:!0}),()=>{t=!0,window.removeEventListener(`load`,r),i?.()}}function Cn(e,t){pn(dn);let n=t.experienceId?.trim();if(!n)throw Error(`ExperienceWidget requires experienceId.`);let r=t.prefetch??`onExpand`,i=mn(t.position),a=document.createElement(`div`);a.className=`liforma-ew`,a.dataset.state=`collapsed`,a.dataset.prefetch=r,a.dataset.position=i,a.style.setProperty(`--liforma-ew-max-w`,t.expandedMaxWidth??`100%`),a.style.setProperty(`--liforma-ew-max-h`,t.expandedMaxHeight??`100%`),i!==`static`&&a.style.setProperty(`--liforma-ew-offset`,hn(t.offset));let o=document.createElement(`button`);o.type=`button`,o.className=`liforma-ew__hit`,o.setAttribute(`aria-label`,t.alt),o.disabled=!0;let s=document.createElement(`div`);s.className=`liforma-ew__face`,o.append(s);let c=document.createElement(`div`);c.className=`liforma-ew__face-status`,c.textContent=`Loading…`,s.append(c);let l=document.createElement(`div`);l.className=`liforma-ew__warm`,l.hidden=!0,l.setAttribute(`aria-hidden`,`true`);let u=document.createElement(`div`);u.className=`liforma-ew__overlay`,u.hidden=!0,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-modal`,`true`),u.setAttribute(`aria-label`,t.alt);let d=document.createElement(`button`);d.type=`button`,d.className=`liforma-ew__backdrop`,d.setAttribute(`aria-label`,`Close experience`);let f=document.createElement(`div`);f.className=`liforma-ew__panel`;let p=document.createElement(`div`);p.className=`liforma-ew__toolbar`,p.hidden=!0;let m=document.createElement(`span`);m.className=`liforma-ew__drag-grip`,m.setAttribute(`aria-hidden`,`true`);let h=document.createElement(`button`);h.type=`button`,h.className=`liforma-ew__icon-btn liforma-ew__dock-toggle`,h.innerHTML=vn,h.setAttribute(`aria-label`,`Reduce`);let g=document.createElement(`button`);g.type=`button`,g.className=`liforma-ew__icon-btn liforma-ew__settings`,g.innerHTML=gn,g.setAttribute(`aria-label`,`Audio settings`),g.setAttribute(`aria-pressed`,`false`);let _=document.createElement(`button`);_.type=`button`,_.className=`liforma-ew__icon-btn liforma-ew__close`,_.innerHTML=_n,_.setAttribute(`aria-label`,`Close`),p.append(m,h,g,_);let ee=document.createElement(`div`);ee.className=`liforma-ew__stage`;let v=document.createElement(`div`);v.className=`liforma-ew__status`,v.hidden=!0,f.append(ee,v),u.append(d,f),a.append(o,l,u,p),e.replaceChildren(a);let y=null,b=!1,x=!1,te=!1,S=!1,C=!1,w=!1,T=!1,E=0,ne=``,D=null,re=null,O=null,k=null,A=null,j=null,M=null,ie=0,ae=0,N=null,P=!1,oe=new AbortController,se=t.parallax!==!1,F=()=>{let e=a.dataset.state;return e===`expanded`||e===`docked`||e===`collapsed`?e:`collapsed`},I=()=>{O!==null&&(clearTimeout(O),O=null)},L=()=>{k!==null&&(clearTimeout(k),k=null),a.classList.remove(`liforma-ew--layout-settling`)},ce=()=>{for(let e of[f,l,p])e.style.removeProperty(`left`),e.style.removeProperty(`top`),e.style.removeProperty(`width`),e.style.removeProperty(`height`),e.style.removeProperty(`right`),e.style.removeProperty(`bottom`);p.classList.remove(`liforma-ew__toolbar--dragging`),a.classList.remove(`liforma-ew--dock-dragging`)},le=(e,t,n,r)=>{let i=i=>{i.style.left=`${e}px`,i.style.top=`${t}px`,i.style.width=`${n}px`,i.style.height=`${r}px`,i.style.right=`auto`,i.style.bottom=`auto`};i(f),i(l);let a=p.offsetWidth||120;p.style.left=`${e+n-a-10}px`,p.style.top=`${t+10}px`,p.style.right=`auto`,p.style.bottom=`auto`,p.style.width=`auto`,p.style.height=`auto`},ue=(e,t)=>{if(F()!==`docked`)return;let n=cn(),r=un(e-ie,t-ae,n);A=r.left,j=r.top,le(r.left,r.top,n.width,n.height)},de=(e,t)=>{if(F()!==`docked`||!Number.isFinite(e)||!Number.isFinite(t)||e===0&&t===0)return;let n=cn(),r=A??f.getBoundingClientRect().left,i=j??f.getBoundingClientRect().top,a=un(r+e,i+t,n);A=a.left,j=a.top,le(a.left,a.top,n.width,n.height)},fe=e=>{N===`toolbar`&&(M===null||e.pointerId!==M||(e.preventDefault(),ue(e.clientX,e.clientY)))},R=e=>{if(M===null||e&&e.pointerId!==M)return;let t=N;M=null,N=null,p.classList.remove(`liforma-ew__toolbar--dragging`),a.classList.remove(`liforma-ew--dock-dragging`),t===`toolbar`&&P&&(P=!1,window.removeEventListener(`pointermove`,fe),window.removeEventListener(`pointerup`,R),window.removeEventListener(`pointercancel`,R))},pe=(e,t,n)=>{if(x||F()!==`docked`||!Q()||M!==null)return;M=n,N=`toolbar`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let r=f.getBoundingClientRect();ie=e-r.left,ae=t-r.top,P||(P=!0,window.addEventListener(`pointermove`,fe),window.addEventListener(`pointerup`,R),window.addEventListener(`pointercancel`,R))},me=e=>{if(x||F()!==`docked`||!Q()||M!==null)return;M=e.pointerId,N=`player`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let t=f.getBoundingClientRect();A=t.left,j=t.top},he=e=>{N===`player`&&(M===null||e.pointerId!==M||de(e.dx,e.dy))},ge=e=>{N===`player`&&(M===null||e.pointerId!==M||R())},z=()=>{let e=Q(),t=F();if(!e||t!==`expanded`&&t!==`docked`){h.hidden=!0;return}h.hidden=!1,t===`docked`?(h.innerHTML=yn,h.setAttribute(`aria-label`,`Maximize`)):(h.innerHTML=vn,h.setAttribute(`aria-label`,`Reduce`))},_e=e=>{let t=cn(),n=e&&A!==null&&j!==null?un(A,j,t):ln(t);n=un(n.left,n.top,t),A=n.left,j=n.top,le(n.left,n.top,t.width,t.height),z()},ve=()=>{a.classList.remove(`liforma-ew--session-revealed`),requestAnimationFrame(()=>{requestAnimationFrame(()=>{x||!$(a.dataset.state)||a.classList.add(`liforma-ew--session-revealed`)})})},ye=e=>{if(L(),a.classList.remove(`liforma-ew--session-revealed`),a.classList.add(`liforma-ew--layout-settling`),e(),!T){a.classList.remove(`liforma-ew--layout-settling`);return}k=setTimeout(()=>{if(k=null,x||!$(a.dataset.state)){a.classList.remove(`liforma-ew--layout-settling`);return}a.classList.remove(`liforma-ew--layout-settling`),ve()},220)},be=()=>(a.classList.add(`liforma-ew--session-concealing`),a.classList.remove(`liforma-ew--session-revealed`),new Promise(e=>{I(),O=setTimeout(()=>{O=null,a.classList.remove(`liforma-ew--session-concealing`),e()},280)})),xe={galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage},B=e=>{if(!e){v.hidden=!0,v.textContent=``;return}v.hidden=!1,v.textContent=e},V=e=>{if(!e){c.hidden=!0,c.textContent=``;return}c.hidden=!1,c.textContent=e,s.contains(c)||s.append(c)},H=()=>{te=!0,o.disabled=!1,V(null),r===`onExpand`&&t.onPrefetchReady?.()},Se=()=>{S=!0,a.dataset.warm=`true`,l.hidden=!1,T||(o.tabIndex=-1,o.setAttribute(`aria-hidden`,`true`)),t.onPrefetchReady?.()},Ce=e=>{D?.(),D=null;let t=bn(s,e,{parallax:se});return t?(D=t,!0):!1},U=()=>{if(Ce(xe)){H();return}V(`Loading…`),$t(n,{signal:oe.signal}).then(e=>{if(!x){if(!Ce({galleryThumb:e.galleryThumb}))throw Error(`Experience preview is missing gallery thumb images.`);H()}}).catch(e=>{if(x||oe.signal.aborted)return;let n=e instanceof Error?e:Error(String(e));V(`Preview unavailable`),o.disabled=!0,t.onError?.(n),console.error(`[ExperienceWidget]`,n)})},we=()=>({experienceId:n,ui:`widget`,...t.sessionEndpoint?{sessionEndpoint:t.sessionEndpoint}:{},...t.locale?{locale:t.locale}:{},...t.language?{language:t.language}:{},...t.mode?{mode:t.mode}:{},...t.speechInputMode?{speechInputMode:t.speechInputMode}:{},...t.speechOnly===void 0?{}:{speechOnly:t.speechOnly},...t.embedBaseUrl?{embedBaseUrl:t.embedBaseUrl}:{}}),W=()=>({...t.fit?{fit:t.fit}:{},startButton:xn(t)}),G=(e=!0)=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`true`),ce(),a.dataset.state=`expanded`,B(null),typeof document<`u`&&(ne=document.body.style.overflow,document.body.style.overflow=`hidden`),z(),e&&t.onExpanded?.()},Te=()=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`false`),a.dataset.state=`docked`,B(null),typeof document<`u`&&(document.body.style.overflow=ne),_e(!0),z(),y?.setWidgetChrome(`docked`)},Ee=e=>{e.on(`started`,()=>{x||(T=!0,a.dataset.live=`true`,B(null),t.onStarted?.(),$(a.dataset.state)&&ve())})},K=()=>{L(),u.hidden=!0,p.hidden=!0,ce(),a.dataset.state=`collapsed`,a.classList.remove(`liforma-ew--session-revealed`),a.classList.remove(`liforma-ew--session-concealing`),g.setAttribute(`aria-pressed`,`false`),o.hidden=!1,o.tabIndex=0,o.removeAttribute(`aria-hidden`),te&&(o.disabled=!1),B(null),typeof document<`u`&&(document.body.style.overflow=ne),z()},De=()=>{I(),L(),E+=1,b=!1,S=!1,C=!1,w=!1,T=!1;let e=y;y=null,e?.destroy(),ee.replaceChildren(),l.replaceChildren(),l.hidden=!0,delete a.dataset.warm,delete a.dataset.live,a.classList.remove(`liforma-ew--session-revealed`)},q=()=>{if(!x&&$(a.dataset.state)){if(R(),b=!1,y&&w){let e=y;(async()=>{T&&(await be(),x||y!==e)||(S&&e.setWidgetChrome(`collapsed`),K(),T?(a.dataset.live=`true`,o.tabIndex=0,o.removeAttribute(`aria-hidden`),o.disabled=!1):S&&Se(),t.onCollapsed?.(),t.onClose?.())})();return}De(),K(),t.onCollapsed?.(),t.onClose?.()}},Oe=()=>{x||Q()&&F()===`expanded`&&ye(()=>{Te()})},J=()=>{x||F()===`docked`&&(R(),ye(()=>{ce(),G(!1),y?.setWidgetChrome(`expanded`)}))},ke=()=>{!y||!T||(I(),a.classList.remove(`liforma-ew--session-revealed`),G(),y.setWidgetChrome(`expanded`),b=!1,ve())},Ae=()=>{!y||!w||T||(I(),a.classList.remove(`liforma-ew--session-revealed`),G(),b=!1,S||y.setWidgetChrome(`expanded`))},je=e=>{x||e!==E&&!T||(I(),a.classList.remove(`liforma-ew--session-revealed`),G(),b=!1,T&&ve())},Me=()=>{if(x||C||S||y||$(a.dataset.state))return;C=!0;let e=E;l.hidden=!1,(async()=>{try{let t=await qe.startSession(we());if(x||e!==E){t.destroy();return}y=t,Ee(t);let n=await t.attach({container:l,...W(),onWidgetReady:()=>{x||e!==E||(C=!1,w=!0,$(a.dataset.state)?t.setWidgetChrome(`expanded`):Se())},onWidgetExpand:()=>{je(e)},onWidgetAudioSettings:e=>{x||Ie(e)},onWidgetDragStart:e=>{x||me(e)},onWidgetDragMove:e=>{x||he(e)},onWidgetDragEnd:e=>{x||ge(e)},onPlayerStatusChange:e=>{x||e===`error`&&$(a.dataset.state)&&B(`Could not load the experience.`)}});if(x||e!==E){t.destroy(),y===t&&(y=null);return}n.on(`close`,()=>{x||q()})}catch(n){if(x||e!==E)return;C=!1,l.hidden=!0,l.replaceChildren(),y=null;let r=n instanceof Error?n:Error(String(n));t.onError?.(r),console.error(`[ExperienceWidget] warm prefetch failed`,r)}})()},Ne=()=>{if(x||b||!te||$(a.dataset.state))return;if(y&&T){ke();return}if(y&&w){Ae();return}let e=++E;b=!0,S=!1,C=!1,w=!1,T=!1,delete a.dataset.warm,delete a.dataset.live,l.hidden=!0,l.replaceChildren(),y&&=(y.destroy(),null),(async()=>{try{G();let t=await qe.startSession(we());if(x||e!==E){t.destroy();return}y=t,Ee(t);let n=await t.attach({container:ee,...W(),onWidgetAudioSettings:e=>{x||Ie(e)},onWidgetDragStart:e=>{x||me(e)},onWidgetDragMove:e=>{x||he(e)},onWidgetDragEnd:e=>{x||ge(e)},onPlayerStatusChange:e=>{x||(e===`error`?B(`Could not load the experience.`):$(a.dataset.state)&&B(null))}});if(x||e!==E){t.destroy(),y===t&&(y=null);return}w=!0,t.setWidgetChrome(`expanded`),n.on(`close`,()=>{x||q()})}catch(n){if(x||e!==E)return;let r=n instanceof Error?n:Error(String(n));B(r.message),t.onError?.(r),console.error(`[ExperienceWidget]`,r)}finally{e===E&&(b=!1)}})()},Pe=()=>{if(!(x||$(a.dataset.state))){if(y&&T){ke();return}if(y&&w){Ae();return}if(C||y){G();return}Ne()}},Fe=e=>{if(e.stopPropagation(),F()===`expanded`){Oe();return}F()===`docked`&&J()},Ie=e=>{g.setAttribute(`aria-pressed`,e?`true`:`false`)},Le=e=>{e.stopPropagation(),$(a.dataset.state)&&y?.toggleAudioSettings()},Re=e=>{F()===`docked`&&Q()&&(e.target?.closest(`button`)||(e.preventDefault(),pe(e.clientX,e.clientY,e.pointerId)))},ze=e=>{e.key===`Escape`&&$(a.dataset.state)&&(e.preventDefault(),q())},Be=()=>{if(!x){if(F()===`docked`){if(!Q()){J();return}T?ye(()=>{_e(!0)}):_e(!0);return}z()}},Ve=typeof window<`u`?window.matchMedia(en):null,He=()=>{if(!x){if(F()===`docked`&&!Q()){J();return}z()}};return o.addEventListener(`click`,Pe),d.addEventListener(`click`,q),_.addEventListener(`click`,e=>{e.stopPropagation(),q()}),h.addEventListener(`click`,Fe),g.addEventListener(`click`,Le),p.addEventListener(`pointerdown`,Re),window.addEventListener(`keydown`,ze),window.addEventListener(`resize`,Be),Ve?.addEventListener(`change`,He),U(),z(),r===`eager`?queueMicrotask(()=>{x||Me()}):r===`idle`&&(re=Sn(()=>{x||Me()})),{root:a,expand:Pe,collapse:q,dock:Oe,maximize:J,prefetch(){if(r===`onExpand`){Me();return}Me()},destroy(){x||(x=!0,R(),re?.(),re=null,oe.abort(),D?.(),D=null,window.removeEventListener(`keydown`,ze),window.removeEventListener(`resize`,Be),Ve?.removeEventListener(`change`,He),De(),K(),e.replaceChildren())}}}var wn=`liforma-experience-widget`;function Tn(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.avatarImage==`string`)return t}catch{}}function En(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function Dn(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function On(e){let t=e?.trim();return t===`full`||t===`face`?t:void 0}function kn(e){let t=e?.trim();return t===`en`||t===`es`?t:void 0}function An(e){let t=e?.trim();return t===`bottom-right`||t===`bottom-left`?t:`static`}var jn=class extends HTMLElement{static get observedAttributes(){return[`experience-id`,`alt`,`gallery-thumb`,`avatar-image`,`background-image`,`foreground-image`,`fallback-image`,`prefetch`,`parallax`,`position`,`offset`,`session-endpoint`,`locale`,`secondary-locale`,`learning-locale`,`language`,`mode`,`speech-input-mode`,`speech-only`,`fit`,`expanded-max-width`,`expanded-max-height`,`start-button-label`]}#e=null;#t=null;connectedCallback(){this.#n(),this.#r()}disconnectedCallback(){this.#e?.destroy(),this.#e=null}attributeChangedCallback(){this.isConnected&&(this.#n(),this.#r())}#n(){if(An(this.getAttribute(`position`))!==`static`){this.style.display=`contents`,this.style.removeProperty(`width`),this.style.removeProperty(`height`),this.style.removeProperty(`min-height`);return}if(this.style.display=`block`,this.style.width||=`100%`,this.style.height||=`100%`,!this.style.minHeight){let e=getComputedStyle(this).minHeight;(e===`0px`||e===`auto`)&&(this.style.minHeight=`224px`)}}#r(){this.#e?.destroy(),this.#e=null;let e=this.getAttribute(`experience-id`)?.trim(),t=this.getAttribute(`alt`)?.trim()||`Open experience`;if(!e)return;let n=An(this.getAttribute(`position`));this.#t||(this.#t=document.createElement(`div`),this.replaceChildren(this.#t)),this.#t.style.cssText=n===`static`?`width:100%;height:100%;min-height:inherit;`:`display:contents;`;let r=this.getAttribute(`prefetch`)?.trim(),i=r===`idle`||r===`eager`||r===`onExpand`?r:`onExpand`,a=this.getAttribute(`speech-only`),o=this.getAttribute(`offset`);try{this.#e=Cn(this.#t,{experienceId:e,alt:t,galleryThumb:Tn(this.getAttribute(`gallery-thumb`)),avatarImage:this.getAttribute(`avatar-image`)??void 0,backgroundImage:this.getAttribute(`background-image`)??void 0,foregroundImage:this.getAttribute(`foreground-image`)??void 0,fallbackImage:this.getAttribute(`fallback-image`)??void 0,prefetch:i,parallax:this.getAttribute(`parallax`)!==`false`,position:n,offset:o===null?void 0:o,sessionEndpoint:this.getAttribute(`session-endpoint`)??void 0,locale:this.getAttribute(`locale`)?.trim()||void 0,secondaryLocale:this.getAttribute(`secondary-locale`)?.trim()||void 0,learningLocale:this.getAttribute(`learning-locale`)?.trim()||void 0,language:kn(this.getAttribute(`language`)),mode:En(this.getAttribute(`mode`)),speechInputMode:Dn(this.getAttribute(`speech-input-mode`)),speechOnly:a===null?void 0:a===``||a===`true`,fit:On(this.getAttribute(`fit`)),expandedMaxWidth:this.getAttribute(`expanded-max-width`)??void 0,expandedMaxHeight:this.getAttribute(`expanded-max-height`)??void 0,startButtonLabel:this.getAttribute(`start-button-label`)??void 0,onExpanded:()=>{this.dispatchEvent(new CustomEvent(`expanded`,{bubbles:!0}))},onCollapsed:()=>{this.dispatchEvent(new CustomEvent(`collapsed`,{bubbles:!0}))},onStarted:()=>{this.dispatchEvent(new CustomEvent(`started`,{bubbles:!0}))},onClose:()=>{this.dispatchEvent(new CustomEvent(`close`,{bubbles:!0}))},onError:e=>{this.dispatchEvent(new CustomEvent(`error`,{detail:e,bubbles:!0}))}})}catch(e){console.error(`[liforma-experience-widget]`,e)}}};return typeof customElements<`u`&&!customElements.get(wn)&&customElements.define(wn,jn),window.Liforma={Experience:qe,sdkVersion:`v2`,features:{speakApi:!0,speechAudioApi:!0}},e.Experience=qe,e.LiformaError=o,e.SPEECH_LIMITS=U,e.SpeechBufferTimeoutError=Te,e.SpeechRuntimeError=G,e.SpeechUtteranceClosedError=W,e.UnsupportedSpeechOperationError=we,e.liformaErrorFromResponse=c,e.warnLocaleVoiceFallbacks=v,e})({});
|
|
774
797
|
//# sourceMappingURL=client.js.map
|