@liforma/client 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/next/index.js +467 -379
  3. package/dist/next/index.js.map +1 -1
  4. package/dist/next/next/createLiformaSessionRouteHandler.d.ts +8 -0
  5. package/dist/next/next/createLiformaSessionRouteHandler.d.ts.map +1 -1
  6. package/dist/next/next/index.d.ts +8 -1
  7. package/dist/next/next/index.d.ts.map +1 -1
  8. package/dist/next/v2/api/captureAttribution.d.ts +10 -0
  9. package/dist/next/v2/api/captureAttribution.d.ts.map +1 -0
  10. package/dist/next/v2/api/mintPublicSession.d.ts +1 -0
  11. package/dist/next/v2/api/mintPublicSession.d.ts.map +1 -1
  12. package/dist/next/v2/api/sessionEndpointRequest.d.ts +1 -0
  13. package/dist/next/v2/api/sessionEndpointRequest.d.ts.map +1 -1
  14. package/dist/next/v2/embed/fullWindowHost.d.ts +20 -0
  15. package/dist/next/v2/embed/fullWindowHost.d.ts.map +1 -0
  16. package/dist/next/v2/embed/iframeHost.d.ts +4 -1
  17. package/dist/next/v2/embed/iframeHost.d.ts.map +1 -1
  18. package/dist/next/v2/embed/protocol.d.ts +18 -1
  19. package/dist/next/v2/embed/protocol.d.ts.map +1 -1
  20. package/dist/next/v2/experience.d.ts +14 -2
  21. package/dist/next/v2/experience.d.ts.map +1 -1
  22. package/dist/next/v2/types/sessionInteraction.d.ts +49 -0
  23. package/dist/next/v2/types/sessionInteraction.d.ts.map +1 -1
  24. package/dist/npm/index.js +559 -477
  25. package/dist/npm/index.js.map +1 -1
  26. package/dist/npm/v2/api/captureAttribution.d.ts +10 -0
  27. package/dist/npm/v2/api/captureAttribution.d.ts.map +1 -0
  28. package/dist/npm/v2/api/mintPublicSession.d.ts +1 -0
  29. package/dist/npm/v2/api/mintPublicSession.d.ts.map +1 -1
  30. package/dist/npm/v2/api/sessionEndpointRequest.d.ts +1 -0
  31. package/dist/npm/v2/api/sessionEndpointRequest.d.ts.map +1 -1
  32. package/dist/npm/v2/embed/fullWindowHost.d.ts +20 -0
  33. package/dist/npm/v2/embed/fullWindowHost.d.ts.map +1 -0
  34. package/dist/npm/v2/embed/iframeHost.d.ts +4 -1
  35. package/dist/npm/v2/embed/iframeHost.d.ts.map +1 -1
  36. package/dist/npm/v2/embed/protocol.d.ts +18 -1
  37. package/dist/npm/v2/embed/protocol.d.ts.map +1 -1
  38. package/dist/npm/v2/experience.d.ts +14 -2
  39. package/dist/npm/v2/experience.d.ts.map +1 -1
  40. package/dist/npm/v2/index.d.ts +1 -1
  41. package/dist/npm/v2/index.d.ts.map +1 -1
  42. package/dist/npm/v2/npm.d.ts +2 -1
  43. package/dist/npm/v2/npm.d.ts.map +1 -1
  44. package/dist/npm/v2/types/sessionInteraction.d.ts +49 -0
  45. package/dist/npm/v2/types/sessionInteraction.d.ts.map +1 -1
  46. package/dist/npm/v2/types/sessionManifestSchema.d.ts +9 -0
  47. package/dist/npm/v2/types/sessionManifestSchema.d.ts.map +1 -1
  48. package/dist/react/component/experienceComponentLaunch.d.ts.map +1 -1
  49. package/dist/react/component/experienceComponentRuntime.d.ts +1 -0
  50. package/dist/react/component/experienceComponentRuntime.d.ts.map +1 -1
  51. package/dist/react/component/experienceComponentTypes.d.ts +7 -0
  52. package/dist/react/component/experienceComponentTypes.d.ts.map +1 -1
  53. package/dist/react/index.js +710 -621
  54. package/dist/react/index.js.map +1 -1
  55. package/dist/react/react/Experience.d.ts.map +1 -1
  56. package/dist/react/v2/api/captureAttribution.d.ts +10 -0
  57. package/dist/react/v2/api/captureAttribution.d.ts.map +1 -0
  58. package/dist/react/v2/api/mintPublicSession.d.ts +1 -0
  59. package/dist/react/v2/api/mintPublicSession.d.ts.map +1 -1
  60. package/dist/react/v2/api/sessionEndpointRequest.d.ts +1 -0
  61. package/dist/react/v2/api/sessionEndpointRequest.d.ts.map +1 -1
  62. package/dist/react/v2/embed/fullWindowHost.d.ts +20 -0
  63. package/dist/react/v2/embed/fullWindowHost.d.ts.map +1 -0
  64. package/dist/react/v2/embed/iframeHost.d.ts +4 -1
  65. package/dist/react/v2/embed/iframeHost.d.ts.map +1 -1
  66. package/dist/react/v2/embed/protocol.d.ts +18 -1
  67. package/dist/react/v2/embed/protocol.d.ts.map +1 -1
  68. package/dist/react/v2/experience.d.ts +14 -2
  69. package/dist/react/v2/experience.d.ts.map +1 -1
  70. package/dist/react/v2/types/sessionInteraction.d.ts +49 -0
  71. package/dist/react/v2/types/sessionInteraction.d.ts.map +1 -1
  72. package/dist/sdk/v2/client.js +6 -6
  73. package/dist/sdk/v2/client.js.map +1 -1
  74. package/dist/svelte/Experience.svelte +10 -0
  75. package/dist/svelte/Experience.svelte.d.ts +1 -0
  76. package/package.json +1 -1
@@ -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)}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=v(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 v(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 y(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 b(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 y(n),{session:n,launch:t}}function x(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function S(e){return e?e.trim().toUpperCase().replace(/-/g,`_`):``}function ee(e,t){let n=x(),r=S(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 C(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 w(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 T(e,t){let n={experienceId:e},r=C(t);r&&(n.locale=r);let i=w(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 E(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(T(e,t))});if(!i.ok){let t=await i.text();throw ee(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 b(s)}async function D(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 b(l)}function te(e){return typeof e!=`object`||!e?!1:typeof e[Symbol.asyncIterator]==`function`}function O(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 ne(e,t){let n=await e(t);return te(n)?{kind:`stream`,stream:n}:{kind:`complete`,speech:O(n)}}var k=`3002`;function A(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||k}. 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 j(e,t){try{await fetch(e,{method:`GET`,mode:`no-cors`,signal:AbortSignal.timeout(8e3)})}catch{throw Error(A(t))}}function M(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(A(n),{cause:e}):e}}var N=new Set([1,2]);function re(e){return typeof e==`number`&&N.has(e)}var ie=new Set([`close`,`stateUpdate`,`commandResult`,`userTranscript`,`characterSpeechStarted`,`characterSpeechEnded`,`characterFocusChanged`,`conversationUpdate`,`listeningState`,`userSpeechStarted`,`userSpeechEnded`,`modeChange`,`activityChange`,`feedback`,`feedbackFailed`,`message`,`started`,`embedReady`,`widgetReady`,`widgetExpand`,`widgetCollapse`,`widgetAudioSettings`,`widgetDragStart`,`widgetDragMove`,`widgetDragEnd`]);function P(e){if(!e||typeof e!=`object`)return null;let t=e;if(!re(t.schemaVersion)||!t.type||!ie.has(t.type))return null;if(t.type===`embedReady`||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}let n=t.payload;return!n||typeof n!=`object`?null:t}function ae(e,t,n){let r=e.trim();if(!r)throw Error(`createLaunchMessage requires a non-empty launch string.`);let i=n?.startButton,a=n?.showFeedback;return{type:`launch`,schemaVersion:2,payload:{launch:r,...t===void 0?{}:{session:t},...i?{startButton:i}:{},...a===void 0?{}:{showFeedback:a}}}}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 ce(e){return e}function I(){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 le=3e4;function ue(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=null,o=0,s=0,c=[],l=null,u=null,d=new Promise((e,t)=>{l=e,u=t}),f=()=>{for(let e of c)window.clearTimeout(e);c.length=0},p=t=>{if(r)return;let i=Date.now();if(s>0&&i-s<250)return;s=i,f();let a=ae(t.launch,t.session,t.chrome),o=()=>{if(r)return;let t=n.contentWindow;t&&M(t,a,e.playerOrigin)};o();for(let e=1;e<=12;e+=1)c.push(window.setTimeout(o,e*75))},m=()=>{r||!a||p(a)},h=()=>{if(o+=1,o===1){j(e.src,e.playerOrigin).then(()=>l?.(),e=>u?.(e instanceof Error?e:Error(String(e))));return}s=0,m()},g=()=>{o>0||u?.(Error(A(e.playerOrigin)))};n.addEventListener(`load`,h),n.addEventListener(`error`,g);let _=t=>{if(r||t.source!==n.contentWindow||t.origin!==e.playerOrigin)return;let a=P(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`characterFocusChanged`:e.onCharacterFocusChanged?.(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?.(ce(a.payload.mode));break;case`activityChange`:e.onActivityChange?.(a.payload.activity);break;case`feedback`:e.onFeedback?.(a.payload);break;case`feedbackFailed`:e.onFeedbackFailed?.(a.payload);break;case`message`:e.onMessage?.(a.payload);break;case`started`:e.onStarted?.(a.payload);break;case`embedReady`:m();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`,_),t.replaceChildren(n),t.clientHeight<2&&!t.style.minHeight){let e=getComputedStyle(t).minHeight;(e===`0px`||e===`auto`)&&(t.style.minHeight=`480px`)}let v=(t,i)=>{if(r)return;let a=n.contentWindow;if(!a)throw Error(A(e.playerOrigin));M(a,t,e.playerOrigin,i)},y=(e,t=12e4,n)=>{let r=e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload?e.payload.correlationId:I();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}),v(e,n),setTimeout(()=>{i.has(r)&&(i.delete(r),o(Error(`Timed out waiting for player command result.`)))},t)})};return{waitForLoad(){return d},postParentHello(){v(oe())},postLaunch(e,t,n){r||(a={launch:e,session:t,chrome:n},s=0,p(a))},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){v(se(e))},postWidgetToggleAudioSettings(){v(F())},speak(e){return y({type:`speak`,schemaVersion:2,payload:{correlationId:I(),text:e.text,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}})},startListening(){return y({type:`startListening`,schemaVersion:2,payload:{correlationId:I()}})},stopListening(){return y({type:`stopListening`,schemaVersion:2,payload:{correlationId:I()}})},listenOnce(e){return y({type:`listenOnce`,schemaVersion:2,payload:{correlationId:I(),...e?.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}})},async speakProcessorStream(e,t){let n=I(),r=I(),i=(await y({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&&v({type:`speakStreamChunk`,schemaVersion:2,payload:{streamId:i,text:n}})}if(t?.signal?.aborted)throw new DOMException(`Processor stream aborted.`,`AbortError`);return await y({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch(e){try{await y({type:`speakStreamEnd`,schemaVersion:2,payload:{correlationId:r,streamId:i}})}catch{}throw e}},speechPlay(e){let t=I(),n=[];return(e.source.kind===`pcm`||e.source.kind===`encoded`)&&n.push(e.source.data),y({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 y({type:`speechUtteranceBegin`,schemaVersion:2,payload:{correlationId:I(),utteranceId:e.utteranceId,format:e.format,queue:e.queue,...e.characterId?{characterId:e.characterId}:{},...e.transcript===void 0?{}:{transcript:e.transcript}}})},speechUtteranceWrite(e){return y({type:`speechUtteranceWrite`,schemaVersion:2,payload:{correlationId:I(),utteranceId:e.utteranceId,audio:e.audio,byteLength:e.byteLength}},le,[e.audio])},speechUtteranceSetTranscript(e){return y({type:`speechUtteranceSetTranscript`,schemaVersion:2,payload:{correlationId:I(),utteranceId:e.utteranceId,transcript:e.transcript}})},speechUtteranceClose(e){return y({type:`speechUtteranceClose`,schemaVersion:2,payload:{correlationId:I(),utteranceId:e.utteranceId,...e.transcript===void 0?{}:{transcript:e.transcript},...e.history?{history:e.history}:{}}})},speechUtteranceCancel(e){return y({type:`speechUtteranceCancel`,schemaVersion:2,payload:{correlationId:I(),utteranceId:e.utteranceId}})},speechInterrupt(e){return y({type:`speechInterrupt`,schemaVersion:2,payload:{correlationId:I(),...e}})},getConversation(){return y({type:`getConversation`,schemaVersion:2,payload:{correlationId:I()}})},focusCharacter(e){return y({type:`focusCharacter`,schemaVersion:2,payload:{correlationId:I(),characterId:e}})},setFit(e){return y({type:`setFit`,schemaVersion:2,payload:{correlationId:I(),fit:e}})},destroy(){if(!r){r=!0;for(let e of i.values())e.reject(Error(`Iframe host destroyed.`));i.clear(),f(),a=null,n.removeEventListener(`load`,h),n.removeEventListener(`error`,g),window.removeEventListener(`message`,_),n.remove()}}}}function de(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 fe=`https://player.liforma.ai/embed`,pe=`http://localhost:3002/embed`;function L(){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 me(){let e=L();return e?e.endsWith(`/embed`)?e:`${e}/embed`:t()?pe:fe}function he(e,t){return e?.trim()||t?.trim()||void 0}function ge(e,t,n,r,i,a,o,s){let c=(e??me()).replace(/\/$/,``),l=c.endsWith(`/embed`)?c:`${c}/embed`,u=new URL(l),d=n?.trim();d&&(u.searchParams.set(`backdropId`,d),u.searchParams.set(`locationId`,d));let f=r?.trim();return f&&u.searchParams.set(`avatarId`,f),(i===`face`||i===`medium`)&&u.searchParams.set(`fit`,i),a===`widget`&&u.searchParams.set(`ui`,`widget`),o&&u.searchParams.set(`close`,`1`),t&&u.searchParams.set(`debug`,`true`),(s===2||s===3||s===4)&&u.searchParams.set(`cast`,String(s)),_e(u.toString())}function _e(e){if(typeof location>`u`)return e;let t=new URL(e);return t.searchParams.set(`parentOrigin`,location.origin),t.toString()}function R(e){return new URL(e).origin}function ve(){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 ye(e,t,n){return{id:ve(),type:e,sessionId:t,timestamp:new Date().toISOString(),data:n}}function be(){return{ready:new Set,started:new Set,userTranscript:new Set,userSpeechStarted:new Set,userSpeechEnded:new Set,characterSpeechStarted:new Set,characterSpeechEnded:new Set,characterFocusChanged:new Set,conversationUpdate:new Set,message:new Set,listeningState:new Set,activityChange:new Set,feedback:new Set,feedbackFailed:new Set,conversationProcessorError:new Set}}function xe(e,t,n){return e[t].add(n),()=>e[t].delete(n)}function Se(e,t,n){for(let r of e[t])r(n)}function z(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 Ce(e){return`url`in e&&typeof e.url==`string`}function V(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 we(e){return!B(e)&&!Ce(e)&&!V(e)&&`encoding`in e&&typeof e.encoding==`string`}var Te=[8e3,16e3,22050,24e3,44100,48e3],H={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},Ee=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)}},De=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 Te.includes(e)}function q(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 Oe(e){if(B(e)){q(e.format);return}if(Ce(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(V(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(we(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 ke(e){if(e.format)return q(e.format),e.format;if(e.track){let t={encoding:`pcm_s16le`,sampleRate:e.sampleRate??24e3,channels:1};return q(t),t}throw new W(`createUtterance requires format or track.`)}function J(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Ae(e){return e===`replace-active`||e===`replace-all`?`interrupt`:`enqueue`}function je(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 Me(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 Ne(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(Me(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 Pe=`liforma-pcm-capture`,Fe=`
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})}var l=128,u=/[\u0000-\u001f\u007f]/g;function d(e){if(!e)return;let t=e.replace(u,``).trim();if(t)return t.slice(0,l)}function f(e){let t=new URLSearchParams((e??``).startsWith(`?`)?(e??``).slice(1):e??``);return{...d(t.get(`utm_source`))?{utmSource:d(t.get(`utm_source`))}:{},...d(t.get(`utm_medium`))?{utmMedium:d(t.get(`utm_medium`))}:{},...d(t.get(`utm_campaign`))?{utmCampaign:d(t.get(`utm_campaign`))}:{},...d(t.get(`utm_content`))?{utmContent:d(t.get(`utm_content`))}:{},...d(t.get(`utm_term`))?{utmTerm:d(t.get(`utm_term`))}:{}}}function p(e){if(e===!1)return;if(e&&typeof e==`object`){let t={...d(e.utmSource)?{utmSource:d(e.utmSource)}:{},...d(e.utmMedium)?{utmMedium:d(e.utmMedium)}:{},...d(e.utmCampaign)?{utmCampaign:d(e.utmCampaign)}:{},...d(e.utmContent)?{utmContent:d(e.utmContent)}:{},...d(e.utmTerm)?{utmTerm:d(e.utmTerm)}:{},...d(e.referrer)?{referrer:d(e.referrer)}:{}};return Object.keys(t).length?t:void 0}if(typeof window>`u`)return;let t=f(window.location?.search),n=d(document.referrer||void 0),r={...t,...n?{referrer:n}:{}};return Object.keys(r).length?r:void 0}function m(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 h(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 g(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=m(t),o=h(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},...(()=>{let e=p(t.attribution);return e?{attribution:e}:{}})()})}}}function _(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function v(e){return typeof e==`boolean`}function y(e){if(!_(e))return null;let t=e.speech,n=e.conversation,r=e.avatar,i=e.tools;return!_(t)||!_(n)||!_(r)||!_(i)||!v(t.input)||!v(t.output)||!v(t.externalAudio)||!v(n.managed)||!v(r.enabled)||!v(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 b(e){return!_(e)||!v(e.avatar)||!v(e.speechInput)||!v(e.speechOutput)||!v(e.tools)||!v(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 x(e){return y(e)??b(e)}function S(e){if(!_(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=x(e.capabilities),l=C(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 C(e){if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(!_(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 w(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 T(e){if(!_(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=S(e.session);return w(n),{session:n,launch:t}}function E(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function D(e){return e?e.trim().toUpperCase().replace(/-/g,`_`):``}function O(e,t){let n=E(),r=D(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 ee(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 k(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 te(e,t){let n={experienceId:e},r=ee(t);r&&(n.locale=r);let i=k(t);i&&(n.secondaryLocale=i),t?.mode&&(n.mode=t.mode),t?.speechInputMode&&(n.speechInputMode=t.speechInputMode),t?.speechOnly!==void 0&&(n.speechOnly=t.speechOnly);let a=p(t?.attribution);return a&&(n.attribution=a),n}async function A(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(te(e,t))});if(!i.ok){let t=await i.text();throw O(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 T(s)}async function j(e,t){let n=g(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 T(l)}function M(e){return typeof e!=`object`||!e?!1:typeof e[Symbol.asyncIterator]==`function`}function N(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 P(e,t){let n=await e(t);return M(n)?{kind:`stream`,stream:n}:{kind:`complete`,speech:N(n)}}var ne=`3002`;function F(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||ne}. 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 I(e,t){try{await fetch(e,{method:`GET`,mode:`no-cors`,signal:AbortSignal.timeout(8e3)})}catch{throw Error(F(t))}}function L(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(F(n),{cause:e}):e}}var re=new Set([1,2]);function ie(e){return typeof e==`number`&&re.has(e)}var R=new Set(`close.stateUpdate.commandResult.userTranscript.characterSpeechStarted.characterSpeechEnded.characterFocusChanged.conversationUpdate.listeningState.userSpeechStarted.userSpeechEnded.modeChange.activityChange.feedback.feedbackFailed.message.started.embedReady.widgetReady.widgetExpand.widgetCollapse.widgetAudioSettings.widgetDragStart.widgetDragMove.widgetDragEnd.fullWindow`.split(`.`));function ae(e){if(!e||typeof e!=`object`)return null;let t=e;if(!ie(t.schemaVersion)||!t.type||!R.has(t.type))return null;if(t.type===`embedReady`||t.type===`widgetReady`||t.type===`widgetExpand`||t.type===`widgetCollapse`)return t;if(t.type===`fullWindow`){let e=t.payload;return!e||typeof e!=`object`||typeof e.active!=`boolean`?null: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}let n=t.payload;return!n||typeof n!=`object`?null:t}function oe(e,t,n){let r=e.trim();if(!r)throw Error(`createLaunchMessage requires a non-empty launch string.`);let i=n?.startButton,a=n?.theme,o=n?.showFeedback;return{type:`launch`,schemaVersion:2,payload:{launch:r,...t===void 0?{}:{session:t},...i?{startButton:i}:{},...a?{theme:a}:{},...o===void 0?{}:{showFeedback:o}}}}function se(){return{type:`parentHello`,schemaVersion:2}}function ce(e){return{type:`widgetSetChrome`,schemaVersion:2,payload:{mode:e}}}function le(){return{type:`widgetToggleAudioSettings`,schemaVersion:2,payload:{}}}var ue=`2147483000`;function de(e){let{style:t}=e;return{position:t.position,top:t.top,right:t.right,bottom:t.bottom,left:t.left,inset:t.inset,width:t.width,height:t.height,zIndex:t.zIndex,margin:t.margin,borderRadius:t.borderRadius,maxWidth:t.maxWidth,maxHeight:t.maxHeight}}function z(e){let{style:t}=e;t.position=`fixed`,t.top=`0`,t.right=`0`,t.bottom=`0`,t.left=`0`,t.inset=`0`,t.width=`100vw`,t.width=`100dvw`,t.height=`100vh`,t.height=`100dvh`,t.zIndex=ue,t.margin=`0`,t.borderRadius=`0`,t.maxWidth=`none`,t.maxHeight=`none`,e.dataset.liformaFullWindow=`1`}function fe(e,t){if(delete e.dataset.liformaFullWindow,!t){e.style.position=``,e.style.top=``,e.style.right=``,e.style.bottom=``,e.style.left=``,e.style.inset=``,e.style.width=``,e.style.height=``,e.style.zIndex=``,e.style.margin=``,e.style.borderRadius=``,e.style.maxWidth=``,e.style.maxHeight=``;return}let{style:n}=e;n.position=t.position,n.top=t.top,n.right=t.right,n.bottom=t.bottom,n.left=t.left,n.inset=t.inset,n.width=t.width,n.height=t.height,n.zIndex=t.zIndex,n.margin=t.margin,n.borderRadius=t.borderRadius,n.maxWidth=t.maxWidth,n.maxHeight=t.maxHeight}function pe(e){return e}function B(){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 me=3e4;function V(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=!1,a=null,o=t.closest(`.liforma-experience-shell`)instanceof HTMLElement?t.closest(`.liforma-experience-shell`):t,s=t=>{i!==t&&(i=t,t?(a=de(o),z(o)):(fe(o,a),a=null),e.onFullWindowChange?.(t))},c=new Map,l=null,u=0,d=0,f=[],p=null,m=null,h=new Promise((e,t)=>{p=e,m=t}),g=()=>{for(let e of f)window.clearTimeout(e);f.length=0},_=t=>{if(r)return;let i=Date.now();if(d>0&&i-d<250)return;d=i,g();let a=oe(t.launch,t.session,t.chrome),o=()=>{if(r)return;let t=n.contentWindow;t&&L(t,a,e.playerOrigin)};o();for(let e=1;e<=12;e+=1)f.push(window.setTimeout(o,e*75))},v=()=>{r||!l||_(l)},y=()=>{if(u+=1,u===1){I(e.src,e.playerOrigin).then(()=>p?.(),e=>m?.(e instanceof Error?e:Error(String(e))));return}d=0,v()},b=()=>{u>0||m?.(Error(F(e.playerOrigin)))};n.addEventListener(`load`,y),n.addEventListener(`error`,b);let x=t=>{if(r||t.source!==n.contentWindow||t.origin!==e.playerOrigin)return;let i=ae(t.data);if(i)switch(i.type){case`close`:e.onClose?.(i.payload);break;case`stateUpdate`:e.onPlayerStatusChange?.(i.payload.state),e.onStateUpdate?.(i.payload.state);break;case`commandResult`:{let e=c.get(i.payload.correlationId);if(!e)return;c.delete(i.payload.correlationId),i.payload.ok?e.resolve(i.payload.result):e.reject(Error(i.payload.error??`Command failed.`));break}case`userTranscript`:e.onUserTranscript?.(i.payload);break;case`characterSpeechStarted`:e.onCharacterSpeechStarted?.(i.payload);break;case`characterSpeechEnded`:e.onCharacterSpeechEnded?.(i.payload);break;case`characterFocusChanged`:e.onCharacterFocusChanged?.(i.payload);break;case`conversationUpdate`:e.onConversationUpdate?.(i.payload.conversation);break;case`listeningState`:e.onListeningState?.(i.payload.listening);break;case`userSpeechStarted`:e.onUserSpeechStarted?.(i.payload);break;case`userSpeechEnded`:e.onUserSpeechEnded?.(i.payload);break;case`modeChange`:e.onActivityChange?.(pe(i.payload.mode));break;case`activityChange`:e.onActivityChange?.(i.payload.activity);break;case`feedback`:e.onFeedback?.(i.payload);break;case`feedbackFailed`:e.onFeedbackFailed?.(i.payload);break;case`message`:e.onMessage?.(i.payload);break;case`started`:e.onStarted?.(i.payload);break;case`embedReady`:v();break;case`widgetReady`:e.onWidgetReady?.();break;case`widgetExpand`:e.onWidgetExpand?.();break;case`widgetCollapse`:e.onWidgetCollapse?.();break;case`widgetAudioSettings`:e.onWidgetAudioSettings?.(i.payload.open);break;case`widgetDragStart`:e.onWidgetDragStart?.(i.payload);break;case`widgetDragMove`:e.onWidgetDragMove?.(i.payload);break;case`widgetDragEnd`:e.onWidgetDragEnd?.(i.payload);break;case`fullWindow`:s(i.payload.active);break}};if(window.addEventListener(`message`,x),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(F(e.playerOrigin));L(a,t,e.playerOrigin,i)},C=(e,t=12e4,n)=>{let r=e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload?e.payload.correlationId:B();return e.type!==`parentHello`&&e.payload&&`correlationId`in e.payload||e.type!==`parentHello`&&e.payload&&(e.payload.correlationId=r),new Promise((i,a)=>{c.set(r,{resolve:e=>i(e),reject:a}),S(e,n),setTimeout(()=>{c.has(r)&&(c.delete(r),a(Error(`Timed out waiting for player command result.`)))},t)})};return{waitForLoad(){return h},postParentHello(){S(se())},postLaunch(e,t,n){r||(l={launch:e,session:t,chrome:n},d=0,_(l))},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(ce(e))},postWidgetToggleAudioSettings(){S(le())},speak(e){return C({type:`speak`,schemaVersion:2,payload:{correlationId:B(),text:e.text,...e.characterId?{characterId:e.characterId}:{},...e.behavior?{behavior:e.behavior}:{}}})},startListening(){return C({type:`startListening`,schemaVersion:2,payload:{correlationId:B()}})},stopListening(){return C({type:`stopListening`,schemaVersion:2,payload:{correlationId:B()}})},listenOnce(e){return C({type:`listenOnce`,schemaVersion:2,payload:{correlationId:B(),...e?.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}})},async speakProcessorStream(e,t){let n=B(),r=B(),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=B(),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:B(),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:B(),utteranceId:e.utteranceId,audio:e.audio,byteLength:e.byteLength}},me,[e.audio])},speechUtteranceSetTranscript(e){return C({type:`speechUtteranceSetTranscript`,schemaVersion:2,payload:{correlationId:B(),utteranceId:e.utteranceId,transcript:e.transcript}})},speechUtteranceClose(e){return C({type:`speechUtteranceClose`,schemaVersion:2,payload:{correlationId:B(),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:B(),utteranceId:e.utteranceId}})},speechInterrupt(e){return C({type:`speechInterrupt`,schemaVersion:2,payload:{correlationId:B(),...e}})},getConversation(){return C({type:`getConversation`,schemaVersion:2,payload:{correlationId:B()}})},focusCharacter(e){return C({type:`focusCharacter`,schemaVersion:2,payload:{correlationId:B(),characterId:e}})},setFit(e){return C({type:`setFit`,schemaVersion:2,payload:{correlationId:B(),fit:e}})},conversion(e){return C({type:`conversion`,schemaVersion:2,payload:{correlationId:B(),key:e}})},destroy(){if(!r){r=!0,i&&s(!1);for(let e of c.values())e.reject(Error(`Iframe host destroyed.`));c.clear(),g(),l=null,n.removeEventListener(`load`,y),n.removeEventListener(`error`,b),window.removeEventListener(`message`,x),n.remove()}}}}function he(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 ge=`https://player.liforma.ai/embed`,_e=`http://localhost:3002/embed`;function ve(){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 ye(){let e=ve();return e?e.endsWith(`/embed`)?e:`${e}/embed`:t()?_e:ge}function H(e,t){return e?.trim()||t?.trim()||void 0}function be(e,t,n,r,i,a,o,s){let c=(e??ye()).replace(/\/$/,``),l=c.endsWith(`/embed`)?c:`${c}/embed`,u=new URL(l),d=n?.trim();d&&(u.searchParams.set(`backdropId`,d),u.searchParams.set(`locationId`,d));let f=r?.trim();return f&&u.searchParams.set(`avatarId`,f),(i===`face`||i===`medium`)&&u.searchParams.set(`fit`,i),a===`widget`&&u.searchParams.set(`ui`,`widget`),o&&u.searchParams.set(`close`,`1`),t&&u.searchParams.set(`debug`,`true`),(s===2||s===3||s===4)&&u.searchParams.set(`cast`,String(s)),xe(u.toString())}function xe(e){if(typeof location>`u`)return e;let t=new URL(e);return t.searchParams.set(`parentOrigin`,location.origin),t.toString()}function Se(e){return new URL(e).origin}function Ce(){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 we(e,t,n){return{id:Ce(),type:e,sessionId:t,timestamp:new Date().toISOString(),data:n}}function Te(){return{ready:new Set,started:new Set,userTranscript:new Set,userSpeechStarted:new Set,userSpeechEnded:new Set,characterSpeechStarted:new Set,characterSpeechEnded:new Set,characterFocusChanged:new Set,conversationUpdate:new Set,message:new Set,listeningState:new Set,activityChange:new Set,feedback:new Set,feedbackFailed:new Set,conversationProcessorError:new Set}}function Ee(e,t,n){return e[t].add(n),()=>e[t].delete(n)}function U(e,t,n){for(let r of e[t])r(n)}function De(e){for(let t of Object.keys(e))e[t].clear()}function Oe(e){return`data`in e&&`format`in e&&e.format!=null&&!(`track`in e)}function W(e){return`url`in e&&typeof e.url==`string`}function G(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 K(e){return!Oe(e)&&!W(e)&&!G(e)&&`encoding`in e&&typeof e.encoding==`string`}var ke=[8e3,16e3,22050,24e3,44100,48e3],q={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},Ae=class extends Error{operation;requiredCapability;name=`UnsupportedSpeechOperationError`;constructor(e,t){super(`Speech operation "${e}" requires capability "${t}".`),this.operation=e,this.requiredCapability=t}},J=class extends Error{name=`SpeechUtteranceClosedError`;constructor(e=`Cannot write to a closed or cancelled speech utterance.`){super(e)}},Y=class extends Error{name=`SpeechRuntimeError`;constructor(e,t){super(e,t)}},X=class extends Error{name=`SpeechBufferTimeoutError`;constructor(e=`Timed out waiting for speech buffer capacity.`){super(e)}};function je(e=`none`){return{mode:e,trackedDurationMs:0,fallbackDurationMs:0}}function Me(e){return ke.includes(e)}function Ne(e){if(e.encoding!==`pcm_s16le`)throw new Y(`Unsupported audio encoding: ${e.encoding}`);if(e.channels!==1)throw new Y(`Unsupported channel count: ${e.channels}`);if(!Me(e.sampleRate))throw new Y(`Unsupported sample rate: ${e.sampleRate}`)}function Pe(e){if(Oe(e)){Ne(e.format);return}if(W(e)){if(!e.url.trim())throw new Y(`Audio URL must be non-empty.`);if(e.sampleRate!==void 0&&!Me(e.sampleRate))throw new Y(`Unsupported sample rate: ${e.sampleRate}`);return}if(G(e)){if(e.track.kind!==`audio`)throw new Y(`speech.play track must be an audio MediaStreamTrack.`);if(e.sampleRate!==void 0&&!Me(e.sampleRate))throw new Y(`Unsupported sample rate: ${e.sampleRate}`);return}if(K(e)){let t=e.encoding.trim().toLowerCase();if(!t)throw new Y(`Encoded audio MIME type is required.`);if(t===`pcm_s16le`)throw new Y(`Use format: { encoding: "pcm_s16le", … } for raw PCM.`);if(e.sampleRate!==void 0&&!Me(e.sampleRate))throw new Y(`Unsupported sample rate: ${e.sampleRate}`);return}throw new Y(`Unsupported speech.play audio shape.`)}function Fe(e){if(e.format)return Ne(e.format),e.format;if(e.track){let t={encoding:`pcm_s16le`,sampleRate:e.sampleRate??24e3,channels:1};return Ne(t),t}throw new Y(`createUtterance requires format or track.`)}function Ie(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Le(e){return e===`replace-active`||e===`replace-all`?`interrupt`:`enqueue`}function Re(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 ze(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 Be(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(ze(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 Ve=`liforma-pcm-capture`,He=`
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('${Pe}', LiformaPcmCaptureProcessor);
14
- `,Ie=null;function Le(){return Ie||=URL.createObjectURL(new Blob([Fe],{type:`application/javascript`})),Ie}function Re(){return window.AudioContext||window.webkitAudioContext||null}async function ze(e){let{mediaStream:t,targetSampleRate:n,onPcm:r,shouldSend:i,onLog:a}=e,o=Re();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=Ne(u,n),f=!1,p=!1,m=e=>{if(f||i&&!i())return;let t=d.push(e);t.length!==0&&r(je(t))},h=()=>void 0;return await(async()=>{if(typeof s.audioWorklet?.addModule!=`function`)return!1;try{await s.audioWorklet.addModule(Le());let e=new AudioWorkletNode(s,Pe,{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 Be(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 ze({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+H.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 Ve(e,t){if(V(e))throw new W(`MediaStreamTrack play is handled on the host before embed.`);if(B(e)){let t=J(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(Ce(e))return{kind:`url`,url:e.url.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}};if(!we(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=J(e.data);return{kind:`encoded`,data:n.slice().buffer,encoding:e.encoding.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}}}function He(){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 Ue(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 W(String(e))}function We(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}var Ge=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 U;let n=J(e);if(n.byteLength&1)throw new W(`PCM chunk byte length must be even (complete s16 samples).`);if(n.byteLength>H.MAX_CHUNK_BYTES)throw new W(`PCM chunk exceeds MAX_CHUNK_BYTES (${H.MAX_CHUNK_BYTES}).`);if(n.byteLength===0)return;let r=t?.timeoutMs??H.DEFAULT_WRITE_TIMEOUT_MS;await this.acquireWriteSlot(r);let i=n.byteLength/2/this.sampleRate*1e3;if(this.bufferedMs+i>H.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 De),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=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:G(`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 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<H.MAX_PENDING_WRITES){this.pendingWriteCount+=1;return}await new Promise((t,n)=>{let r=setTimeout(()=>{n(new De)},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 Ke(e){let t=null,n=(t,n)=>{if(!e.getCapabilities()[n])throw new Ee(t,n)},r={async speak(r){if(e.assertSessionStarted(),n(`speak`,`textSpeech`),r.signal?.aborted)throw new DOMException(`Speak aborted.`,`AbortError`);let i=Ae(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(Ue(e,`completed`))},a=>{if(t.removeEventListener(`abort`,s),We(a)){n({utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:G(`none`)});return}i(Y(a))})})}try{return Ue(await o,`completed`)}catch(t){if(We(t))return{utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:G(`none`)};throw Y(t)}},async play(i){if(e.assertSessionStarted(),n(`play`,`externalSpeechAudio`),Oe(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)),V(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 Ve(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=ke(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 Ge({id:He(),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 Be({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 qe(e){let t=e?.trim();return t===`full`||t===`face`||t===`medium`?t:void 0}function Je(e){return!!(e.showClose===!0||e.returnUrl?.trim()||e.closeButton===!0||e.closeButton&&typeof e.closeButton==`object`&&e.closeButton.visible!==!1)}var Ye=class e{bootstrap;conversationProcessor;iframeHost=null;attachInFlight=null;endpointAbortController=null;processorAbortController=null;processorChain=Promise.resolve();resolvedSession;launchToken;attachReturnUrl=null;closed=!1;attached=!1;pendingFit=null;closeHandlers=[];eventRegistry=be();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=Ke({getIframeHost:()=>this.iframeHost,assertSessionStarted:()=>this.assertSessionStarted(),getCapabilities:()=>Xe(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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,castSize:t.castSize,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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,castSize:t.castSize,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=xe(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??me(),n=this.bootstrap.debug===!0,r=this.bootstrap.speechOnly===!0,i=ge(t,n,r?void 0:he(this.bootstrap.backdropId,this.bootstrap.locationId),r?void 0:this.bootstrap.avatarId,e.fit,this.bootstrap.ui,Je(e),this.bootstrap.kind===`launch`?void 0:this.bootstrap.castSize),a=R(i),o=null,s=new Promise(e=>{o=e}),c=null,l=new Promise(e=>{c=e}),u=de(e=>{this.readyEnvelope||=(this.resolvedSession=e,this.emitWrapped(`ready`,{session:e}))}),d=this.bootstrap.onUserTranscript,f=ue({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)},onCharacterFocusChanged:e=>{this.emitWrapped(`characterFocusChanged`,e)},onListeningState:e=>{this.emitWrapped(`listeningState`,e)},onActivityChange:e=>{this.emitWrapped(`activityChange`,e)},onFeedback:e=>{this.emitWrapped(`feedback`,e)},onFeedbackFailed:e=>{this.emitWrapped(`feedbackFailed`,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,D(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`?E(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`&&y(_),f.postLaunch(g,_,{startButton:e.startButton,showFeedback:e.showFeedback}),u.setValue(_)):f.postLaunch(g,void 0,{startButton:e.startButton,showFeedback:e.showFeedback}),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.pendingFit&&await f.setFit(this.pendingFit),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()}async focusCharacter(e){this.assertSessionStarted(),await this.iframeHost.focusCharacter(e)}async setFit(e){let t=qe(e);if(!t)throw Error(`setFit requires "full", "medium", or "face".`);if(this.closed)throw Error(`Session has ended.`);this.pendingFit=t,!(!this.attached||!this.iframeHost)&&await this.iframeHost.setFit(t)}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,z(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=ye(e,this.getSessionId(),t);return Se(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 ne(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 Xe(e){return e?{textSpeech:e.capabilities.speech.output,externalSpeechAudio:e.capabilities.speech.externalAudio}:{textSpeech:!0,externalSpeechAudio:!0}}function Ze(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 Qe(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 $e(e,t=`/meet`){if(e.reason!==`user`)return;let n=Ze(e.returnUrl?.trim()||Qe(t),window.location.origin);n?.protocol.startsWith(`http`)&&window.location.assign(n.toString())}var et=/\b(exp_[A-Za-z0-9][A-Za-z0-9_-]{2,127})\b/,tt=/(?:Your origin|origin)\s+(\S+)\s+is not an allowed origin/i;function nt(e){return e instanceof Error?e.message:String(e)}function rt(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function it(e){return et.exec(e)?.[1]}function at(e){return tt.exec(e)?.[1]}function ot(e,t){let n=nt(e).trim()||`Unknown error`,r=t?.experienceId?.trim()||it(n)||void 0,i=t?.origin?.trim()||at(n)||rt()||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 st=`liforma-experience-load-error-styles`;function ct(){if(typeof document>`u`||document.getElementById(`liforma-experience-load-error-styles`))return;let e=document.createElement(`style`);e.id=st,e.textContent=lt,document.head.append(e)}var lt=`
13
+ registerProcessor('${Ve}', LiformaPcmCaptureProcessor);
14
+ `,Ue=null;function We(){return Ue||=URL.createObjectURL(new Blob([He],{type:`application/javascript`})),Ue}function Ge(){return window.AudioContext||window.webkitAudioContext||null}async function Ke(e){let{mediaStream:t,targetSampleRate:n,onPcm:r,shouldSend:i,onLog:a}=e,o=Ge();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=Be(u,n),f=!1,p=!1,m=e=>{if(f||i&&!i())return;let t=d.push(e);t.length!==0&&r(Re(t))},h=()=>void 0;return await(async()=>{if(typeof s.audioWorklet?.addModule!=`function`)return!1;try{await s.audioWorklet.addModule(We());let e=new AudioWorkletNode(s,Ve,{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 qe(e){let{track:t,utterance:n,sampleRate:r,signal:i}=e;if(typeof MediaStreamTrack>`u`||!(t instanceof MediaStreamTrack))throw new Y(`MediaStreamTrack is not available in this environment.`);if(t.kind!==`audio`)throw new Y(`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 Ke({mediaStream:a,targetSampleRate:r,shouldSend:()=>!s&&!i?.aborted,onPcm:e=>{if(s||i?.aborted)return;let t=Ie(e);o=o.then(async()=>{if(s||i?.aborted)return;let e=0;for(;e<t.byteLength;){let r=Math.min(e+q.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 Y(`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 Je(e,t){if(G(e))throw new Y(`MediaStreamTrack play is handled on the host before embed.`);if(Oe(e)){let t=Ie(e.data);if(t.byteLength&1)throw new Y(`PCM byte length must be even.`);return{kind:`pcm`,data:t.slice().buffer,format:e.format}}if(W(e))return{kind:`url`,url:e.url.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}};if(!K(e))throw new Y(`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=Ie(e.data);return{kind:`encoded`,data:n.slice().buffer,encoding:e.encoding.trim(),...e.sampleRate===void 0?{}:{sampleRate:e.sampleRate}}}function Ye(){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 Xe(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 Ze(e){return e instanceof Error?e:new Y(String(e))}function Qe(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`}var $e=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(Ze(e)),Ze(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 J;let n=Ie(e);if(n.byteLength&1)throw new Y(`PCM chunk byte length must be even (complete s16 samples).`);if(n.byteLength>q.MAX_CHUNK_BYTES)throw new Y(`PCM chunk exceeds MAX_CHUNK_BYTES (${q.MAX_CHUNK_BYTES}).`);if(n.byteLength===0)return;let r=t?.timeoutMs??q.DEFAULT_WRITE_TIMEOUT_MS;await this.acquireWriteSlot(r);let i=n.byteLength/2/this.sampleRate*1e3;if(this.bufferedMs+i>q.MAX_UTTERANCE_DURATION_MS)throw this.releaseWriteSlot(),new Y(`Utterance exceeds MAX_UTTERANCE_DURATION_MS.`);let a=async()=>{if(this.closed||this.settled)throw new J;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 X),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 J;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=Ze(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:je(`none`)};return this.resolve(t),t}catch(e){let t=Ze(e);throw this.fail(t),t}}adoptExternalResult(e){this.resolve(e)}requireHost(){let e=this.host.getIframeHost();if(!e)throw new Y(`Speech session is not attached.`);return e}resolve(e){this.settled||(this.settled=!0,this.settleResolve(Object.freeze(e)),this.flushWriteWaiters(new J))}fail(e){this.settled||(this.settled=!0,this.settleReject(e),this.flushWriteWaiters(e))}async acquireWriteSlot(e){if(this.pendingWriteCount<q.MAX_PENDING_WRITES){this.pendingWriteCount+=1;return}await new Promise((t,n)=>{let r=setTimeout(()=>{n(new X)},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 et(e){let t=null,n=(t,n)=>{if(!e.getCapabilities()[n])throw new Ae(t,n)},r={async speak(r){if(e.assertSessionStarted(),n(`speak`,`textSpeech`),r.signal?.aborted)throw new DOMException(`Speak aborted.`,`AbortError`);let i=Le(r.queue??`append`);i===`interrupt`&&(e.onProcessorInterrupt?.(),t&&=(t.cancel(),null));let a=e.getIframeHost();if(!a)throw new Y(`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(Xe(e,`completed`))},a=>{if(t.removeEventListener(`abort`,s),Qe(a)){n({utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:je(`none`)});return}i(Ze(a))})})}try{return Xe(await o,`completed`)}catch(t){if(Qe(t))return{utteranceId:`utt_interrupted`,characterId:r.characterId??e.getActiveCharacterId(),status:`interrupted`,durationMs:0,transcript:r.text,animation:je(`none`)};throw Ze(t)}},async play(i){if(e.assertSessionStarted(),n(`play`,`externalSpeechAudio`),Pe(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)),G(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 Y(`Speech session is not attached.`);let s=await Je(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=Fe(r);if(r.track&&r.track.kind!==`audio`)throw new Y(`createUtterance track must be an audio MediaStreamTrack.`);let a=r.queue??`replace-active`;if(a!==`replace-active`&&a!==`replace-all`)throw new Y(`createUtterance queue must be replace-active or replace-all.`);e.onProcessorInterrupt?.(),t&&=(t.cancel(),null);let o=new $e({id:Ye(),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 qe({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 tt(e){let t=e?.trim();return t===`full`||t===`face`||t===`medium`?t:void 0}function nt(e){return!!(e.showClose===!0||e.returnUrl?.trim()||e.closeButton===!0||e.closeButton&&typeof e.closeButton==`object`&&e.closeButton.visible!==!1)}var rt=class e{bootstrap;conversationProcessor;iframeHost=null;attachInFlight=null;endpointAbortController=null;processorAbortController=null;processorChain=Promise.resolve();resolvedSession;launchToken;attachReturnUrl=null;closed=!1;attached=!1;pendingFit=null;closeHandlers=[];eventRegistry=Te();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=et({getIframeHost:()=>this.iframeHost,assertSessionStarted:()=>this.assertSessionStarted(),getCapabilities:()=>it(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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,castSize:t.castSize,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,attribution:t.attribution,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,backdropId:t.backdropId,locationId:t.locationId,avatarId:t.avatarId,castSize:t.castSize,embedBaseUrl:t.embedBaseUrl,debug:t.debug,mode:t.mode,speechInputMode:t.speechInputMode,speechOnly:t.speechOnly,attribution:t.attribution,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=Ee(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??ye(),n=this.bootstrap.debug===!0,r=this.bootstrap.speechOnly===!0,i=be(t,n,r?void 0:H(this.bootstrap.backdropId,this.bootstrap.locationId),r?void 0:this.bootstrap.avatarId,e.fit,this.bootstrap.ui,nt(e),this.bootstrap.kind===`launch`?void 0:this.bootstrap.castSize),a=Se(i),o=null,s=new Promise(e=>{o=e}),c=null,l=new Promise(e=>{c=e}),u=he(e=>{this.readyEnvelope||=(this.resolvedSession=e,this.emitWrapped(`ready`,{session:e}))}),d=this.bootstrap.onUserTranscript,f=V({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)},onCharacterFocusChanged:e=>{this.emitWrapped(`characterFocusChanged`,e)},onListeningState:e=>{this.emitWrapped(`listeningState`,e)},onActivityChange:e=>{this.emitWrapped(`activityChange`,e)},onFeedback:e=>{this.emitWrapped(`feedback`,e)},onFeedbackFailed:e=>{this.emitWrapped(`feedbackFailed`,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,j(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,attribution:this.bootstrap.attribution,signal:this.endpointAbortController.signal})):this.bootstrap.kind===`public`?A(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,attribution:this.bootstrap.attribution}):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`&&w(_),f.postLaunch(g,_,{startButton:e.startButton,theme:e.theme,showFeedback:e.showFeedback}),u.setValue(_)):f.postLaunch(g,void 0,{startButton:e.startButton,theme:e.theme,showFeedback:e.showFeedback}),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.pendingFit&&await f.setFit(this.pendingFit),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()}async focusCharacter(e){this.assertSessionStarted(),await this.iframeHost.focusCharacter(e)}async setFit(e){let t=tt(e);if(!t)throw Error(`setFit requires "full", "medium", or "face".`);if(this.closed)throw Error(`Session has ended.`);this.pendingFit=t,!(!this.attached||!this.iframeHost)&&await this.iframeHost.setFit(t)}async conversion(e){if(this.closed)throw Error(`Session has ended.`);if(!this.iframeHost)throw Error(`conversion() requires attach() first.`);await this.iframeHost.conversion(e)}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,De(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=we(e,this.getSessionId(),t);return U(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 P(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 it(e){return e?{textSpeech:e.capabilities.speech.output,externalSpeechAudio:e.capabilities.speech.externalAudio}:{textSpeech:!0,externalSpeechAudio:!0}}function at(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 ot(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 st(e,t=`/meet`){if(e.reason!==`user`)return;let n=at(e.returnUrl?.trim()||ot(t),window.location.origin);n?.protocol.startsWith(`http`)&&window.location.assign(n.toString())}var ct=/\b(exp_[A-Za-z0-9][A-Za-z0-9_-]{2,127})\b/,lt=/(?:Your origin|origin)\s+(\S+)\s+is not an allowed origin/i;function ut(e){return e instanceof Error?e.message:String(e)}function dt(){try{if(typeof globalThis.location?.origin==`string`&&globalThis.location.origin)return globalThis.location.origin}catch{}}function ft(e){return ct.exec(e)?.[1]}function pt(e){return lt.exec(e)?.[1]}function mt(e,t){let n=ut(e).trim()||`Unknown error`,r=t?.experienceId?.trim()||ft(n)||void 0,i=t?.origin?.trim()||pt(n)||dt()||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 ht=`liforma-experience-load-error-styles`;function gt(){if(typeof document>`u`||document.getElementById(`liforma-experience-load-error-styles`))return;let e=document.createElement(`style`);e.id=ht,e.textContent=_t,document.head.append(e)}var _t=`
15
15
  .liforma-loading-screen {
16
16
  inset: 0;
17
17
  z-index: 20;
@@ -110,7 +110,7 @@ registerProcessor('${Pe}', LiformaPcmCaptureProcessor);
110
110
  .liforma-loading-error-detail[hidden] {
111
111
  display: none;
112
112
  }
113
- `;function ut(e,t){ct();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 dt=`liforma-experience`;function ft(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function pt(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function mt(e){return qe(e)}var ht=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){if(e.observedAttributes.includes(t)&&!(n===r||!this.isConnected)){if(t===`fit`){this.experience&&this.experience.setFit(mt(r)??`full`);return}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=ft(this.getAttribute(`mode`)),c=pt(this.getAttribute(`speech-input-mode`)),l=mt(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 Ye.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})),$e(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=ut(this.errorHost,ot(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(dt)&&customElements.define(dt,ht);function gt(e){return e===`face`?`liforma-et--fit-face`:e===`medium`?`liforma-et--fit-medium`:``}var _t=/(\/avatars\/[^/]+\/)(\d+)(\/)/i,vt=/_CH(\.webp)/i,yt=/(-)(\d+x\d+)(\.webp)(\?|$)/i;function bt(e){let t=e.trim();if(!t)return t;let n=t.replace(_t,(e,t,n,r)=>n===`256`?`${t}${n}${r}`:`${t}256${r}`);return n=n.replace(vt,`_neutral$1`),n=n.replace(yt,(e,t,n,r,i)=>n===`256x256`?`${t}${n}${r}${i}`:`${t}256x256${r}${i}`),n}function xt(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:bt(t),...n?{backgroundImage:bt(n)}:{},...r?{foregroundImage:bt(r)}:{},...i?{fallbackImage:bt(i)}:{}}}var St=`https://player.liforma.ai`,Ct=`http://localhost:3002`;function wt(e){return e.href?.trim()?`anchor`:e.hasClickHandler?`button`:e.experienceId?.trim()?`anchor`:`presentational`}function Tt(e){let n=e?.trim();return n?n.replace(/\/$/,``):t()?Ct:St}function Et(e){let t=e.experienceId.trim(),n=Tt(e.playerBaseUrl),r=new URL(`${n}/${encodeURIComponent(t)}`),i=e.returnUrl?.trim();return i&&r.searchParams.set(`returnUrl`,i),r.toString()}function Dt(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),Et({experienceId:n,...r?{returnUrl:r}:{},playerBaseUrl:e.playerBaseUrl})}function Ot(){return typeof window>`u`?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}var X=0,kt=[];function At(){return Ot()?4:1/0}function jt(){return Ot()?160:0}function Mt(){let e=At();for(;X<e&&kt.length>0;){let e=kt.shift();if(!e||e.cancelled)continue;X+=1,e.start();let t=jt();if(t<=0){X=Math.max(0,X-1);continue}window.setTimeout(()=>{X=Math.max(0,X-1),Mt()},t)}}function Nt(e){if(!Ot())return e(),()=>{};let t={start:e,cancelled:!1};return kt.push(t),Mt(),()=>{t.cancelled=!0}}function Pt(){return Ot()?`96px 0px`:`280px 0px`}function Ft(e){let t=e.trim().split(/\s+/)[0]??`0px`,n=Number.parseFloat(t);return Number.isFinite(n)?Math.abs(n):280}function It(e,t){if(typeof window>`u`)return!1;let n=e.getBoundingClientRect();return n.bottom>=-t&&n.top<=window.innerHeight+t}function Lt(e,t){let{onVisibleChange:n}=t,r=t.rootMargin??Pt(),i=Ft(r),a=!1,o=!1,s=null,c=()=>{o||(s?.(),s=Nt(()=>{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),It(e,i)&&l(!0),()=>{s?.(),s=null,u.disconnect()}}function Rt(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 zt(){return typeof window>`u`||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}function Bt(e,t){return((e.top+e.height/2)/Math.max(t,1)-.5)*2}var Vt=new Set,Ht=!1,Z=0;function Ut(){if(Z=0,Vt.size===0||typeof window>`u`)return;let e=window.innerHeight;for(let t of Vt){if(t.pointerActive?.())continue;let n=t.element.getBoundingClientRect();n.bottom<-64||n.top>e+64||t.onParallax(Bt(n,e))}}function Wt(){Z===0&&(Z=requestAnimationFrame(Ut))}function Gt(){Ht||typeof window>`u`||(Ht=!0,window.addEventListener(`scroll`,Wt,{passive:!0}),window.addEventListener(`resize`,Wt,{passive:!0}))}function Kt(){Vt.size>0||!Ht||typeof window>`u`||(Ht=!1,Z!==0&&(cancelAnimationFrame(Z),Z=0),window.removeEventListener(`scroll`,Wt),window.removeEventListener(`resize`,Wt))}function qt(e,t){if(!zt())return()=>{};let n={element:e,onParallax:t.onParallax,pointerActive:t.pointerActive};return Vt.add(n),Gt(),n.pointerActive?.()||t.onParallax(Bt(e.getBoundingClientRect(),window.innerHeight)),()=>{Vt.delete(n),Kt()}}function Jt(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=qt(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=Bt(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 Yt=`.liforma-et {
113
+ `;function vt(e,t){gt();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 yt=`liforma-experience`;function bt(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function xt(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function St(e){return tt(e)}var Ct=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){if(e.observedAttributes.includes(t)&&!(n===r||!this.isConnected)){if(t===`fit`){this.experience&&this.experience.setFit(St(r)??`full`);return}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=bt(this.getAttribute(`mode`)),c=xt(this.getAttribute(`speech-input-mode`)),l=St(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 rt.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})),st(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=vt(this.errorHost,mt(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(yt)&&customElements.define(yt,Ct);function wt(e){return e===`face`?`liforma-et--fit-face`:e===`medium`?`liforma-et--fit-medium`:``}var Tt=/(\/avatars\/[^/]+\/)(\d+)(\/)/i,Et=/_CH(\.webp)/i,Dt=/(-)(\d+x\d+)(\.webp)(\?|$)/i;function Ot(e){let t=e.trim();if(!t)return t;let n=t.replace(Tt,(e,t,n,r)=>n===`256`?`${t}${n}${r}`:`${t}256${r}`);return n=n.replace(Et,`_neutral$1`),n=n.replace(Dt,(e,t,n,r,i)=>n===`256x256`?`${t}${n}${r}${i}`:`${t}256x256${r}${i}`),n}function kt(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:Ot(t),...n?{backgroundImage:Ot(n)}:{},...r?{foregroundImage:Ot(r)}:{},...i?{fallbackImage:Ot(i)}:{}}}var At=`https://player.liforma.ai`,jt=`http://localhost:3002`;function Mt(e){return e.href?.trim()?`anchor`:e.hasClickHandler?`button`:e.experienceId?.trim()?`anchor`:`presentational`}function Nt(e){let n=e?.trim();return n?n.replace(/\/$/,``):t()?jt:At}function Pt(e){let t=e.experienceId.trim(),n=Nt(e.playerBaseUrl),r=new URL(`${n}/${encodeURIComponent(t)}`),i=e.returnUrl?.trim();return i&&r.searchParams.set(`returnUrl`,i),r.toString()}function Ft(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),Pt({experienceId:n,...r?{returnUrl:r}:{},playerBaseUrl:e.playerBaseUrl})}function It(){return typeof window>`u`?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}var Lt=0,Rt=[];function zt(){return It()?4:1/0}function Bt(){return It()?160:0}function Vt(){let e=zt();for(;Lt<e&&Rt.length>0;){let e=Rt.shift();if(!e||e.cancelled)continue;Lt+=1,e.start();let t=Bt();if(t<=0){Lt=Math.max(0,Lt-1);continue}window.setTimeout(()=>{Lt=Math.max(0,Lt-1),Vt()},t)}}function Ht(e){if(!It())return e(),()=>{};let t={start:e,cancelled:!1};return Rt.push(t),Vt(),()=>{t.cancelled=!0}}function Ut(){return It()?`96px 0px`:`280px 0px`}function Wt(e){let t=e.trim().split(/\s+/)[0]??`0px`,n=Number.parseFloat(t);return Number.isFinite(n)?Math.abs(n):280}function Gt(e,t){if(typeof window>`u`)return!1;let n=e.getBoundingClientRect();return n.bottom>=-t&&n.top<=window.innerHeight+t}function Kt(e,t){let{onVisibleChange:n}=t,r=t.rootMargin??Ut(),i=Wt(r),a=!1,o=!1,s=null,c=()=>{o||(s?.(),s=Ht(()=>{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),Gt(e,i)&&l(!0),()=>{s?.(),s=null,u.disconnect()}}function qt(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 Jt(){return typeof window>`u`||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?!1:window.matchMedia(`(hover: none), (pointer: coarse)`).matches}function Yt(e,t){return((e.top+e.height/2)/Math.max(t,1)-.5)*2}var Xt=new Set,Zt=!1,Z=0;function Qt(){if(Z=0,Xt.size===0||typeof window>`u`)return;let e=window.innerHeight;for(let t of Xt){if(t.pointerActive?.())continue;let n=t.element.getBoundingClientRect();n.bottom<-64||n.top>e+64||t.onParallax(Yt(n,e))}}function $t(){Z===0&&(Z=requestAnimationFrame(Qt))}function en(){Zt||typeof window>`u`||(Zt=!0,window.addEventListener(`scroll`,$t,{passive:!0}),window.addEventListener(`resize`,$t,{passive:!0}))}function tn(){Xt.size>0||!Zt||typeof window>`u`||(Zt=!1,Z!==0&&(cancelAnimationFrame(Z),Z=0),window.removeEventListener(`scroll`,$t),window.removeEventListener(`resize`,$t))}function nn(e,t){if(!Jt())return()=>{};let n={element:e,onParallax:t.onParallax,pointerActive:t.pointerActive};return Xt.add(n),en(),n.pointerActive?.()||t.onParallax(Yt(e.getBoundingClientRect(),window.innerHeight)),()=>{Xt.delete(n),tn()}}function rn(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=nn(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=Yt(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 an=`.liforma-et {
114
114
  --liforma-et-parallax-x: 0;
115
115
  --liforma-et-parallax-y: 0;
116
116
  --liforma-et-bg-scale: 1;
@@ -330,7 +330,7 @@ button.liforma-et {
330
330
  .liforma-et__avatar {
331
331
  transition: none;
332
332
  }
333
- }`,Xt=!1;function Zt(e){if(typeof document>`u`||Xt)return;if(document.querySelector(`style[data-liforma-et]`)){Xt=!0;return}let t=document.createElement(`style`);t.setAttribute(`data-liforma-et`,``),t.textContent=e,document.head.appendChild(t),Xt=!0}var Qt=`liforma-experience-thumbnail`;function $t(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t.avatarImage==`string`)return t}catch{}}var en=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=Yt,e.replaceChildren(t);let n=this.getAttribute(`alt`)?.trim()||`Experience`,r=this.getAttribute(`href`),i=this.getAttribute(`experience-id`),a=wt({href:r,hasClickHandler:this.hasAttribute(`onclick`)||typeof this.onclick==`function`,experienceId:i}),o=xt({galleryThumb:$t(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(),l=c===`face`||c===`medium`?c:`full`,u=this.#p(`lazy`,!0);this.#n=!u;let d=a===`anchor`&&!r?.trim()&&!!i?.trim(),f=Dt({href:r??void 0,experienceId:i??void 0,returnUrl:this.getAttribute(`return-url`)??void 0,playerBaseUrl:this.getAttribute(`player-base-url`)??void 0,useCurrentPageAsReturnUrl:d&&!this.getAttribute(`return-url`)?.trim()}),p;if(a===`anchor`&&f){let e=document.createElement(`a`);e.href=f;let t=this.getAttribute(`target`),n=this.getAttribute(`rel`);t&&(e.target=t),n&&(e.rel=n),p=e}else if(a===`button`){let e=document.createElement(`button`);e.type=`button`,p=e}else p=document.createElement(`div`),p.setAttribute(`role`,`img`);p.className=`liforma-et`,p.setAttribute(`aria-label`,n),this.#e=p,e.appendChild(p);let m=()=>{let e=!!o.backgroundImage,t=s&&(this.#r||this.#a),n=this.#n&&(this.#u||this.#l||this.#d);p.className=[`liforma-et`,e?`liforma-et--scene`:``,gt(l),t?`liforma-et--parallax`:``,this.#a?`liforma-et--scroll-parallax`:``,this.#n&&!n?`liforma-et--loading`:``,n?`liforma-et--revealed`:``].filter(Boolean).join(` `),p.style.setProperty(`--liforma-et-parallax-x`,String(this.#o)),p.style.setProperty(`--liforma-et-parallax-y`,String(this.#s))},h=document.createElement(`span`);h.className=`liforma-et__placeholder`,h.setAttribute(`aria-hidden`,`true`),p.appendChild(h);let g=()=>{if(!this.#n)return;let e=this.#c&&o.fallbackImage?o.fallbackImage:o.avatarImage;if(o.backgroundImage&&!p.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(Rt(e,()=>{this.#l=!0,e.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(e)}let t=p.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,m())}),this.#t.push(Rt(t,()=>{this.#u=!0,t.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(t)),t.src!==e&&(t.src=e),o.foregroundImage&&!p.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(Rt(e,()=>{this.#d=!0,e.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(e)}m()};if(u?this.#t.push(Lt(p,{onVisibleChange:e=>{e&&(this.#n=!0,g(),m())}})):g(),s){this.#t.push(qt(p,{onParallax:e=>{this.#a=!0,this.#i||(this.#o=e,this.#s=0,m())},pointerActive:()=>this.#i}));let e=e=>{if(this.#a)return;let t=p.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,m())},t=e=>{this.#i=!0,e.pointerType===`mouse`&&(this.#r=!0),m()},n=()=>{let e=this.#i;this.#i=!1,this.#r=!1,this.#a&&e?(this.#o=Bt(p.getBoundingClientRect(),window.innerHeight),this.#s=0):this.#a||(this.#o=0,this.#s=0),m()};p.addEventListener(`pointermove`,e),p.addEventListener(`pointerdown`,t),p.addEventListener(`pointerup`,n),p.addEventListener(`pointercancel`,n),p.addEventListener(`pointerenter`,e=>{e.pointerType===`mouse`&&(this.#r=!0,m())}),p.addEventListener(`pointerleave`,()=>{this.#i||(this.#r=!1,this.#a||(this.#o=0,this.#s=0),m())}),this.#t.push(()=>{p.removeEventListener(`pointermove`,e),p.removeEventListener(`pointerdown`,t),p.removeEventListener(`pointerup`,n),p.removeEventListener(`pointercancel`,n)})}p.addEventListener(`click`,e=>{if(d&&!this.getAttribute(`return-url`)?.trim()){let t=Dt({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))}}),m()}};customElements.get(Qt)||customElements.define(Qt,en);function tn(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 nn(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=tn(s.galleryThumb);if(!u)throw Error(`Experience preview is missing gallery thumb images.`);return{experienceId:c||n,title:l||c||n,galleryThumb:u}}var rn=`(min-width: 768px)`,an=24,on=.5,sn=1200,cn=.85,ln=9/16;function un(){if(typeof window>`u`)return 800;let e=window.screen?.availHeight;return typeof e==`number`&&e>0?e:window.innerHeight}function dn(e=typeof window<`u`?window.innerWidth:1280,t=typeof window<`u`?window.innerHeight:800,n=an,r=typeof window<`u`?un():800){let i=Math.max(160,Math.min(t-n*2,t*cn)),a=Math.max(120,e-n*2),o=Math.min(r*on,sn,i),s=o*ln;return s>a&&(s=a,o=s/ln,o>i&&(o=i,s=o*ln)),{width:Math.round(s),height:Math.round(o)}}function fn(e,t=typeof window<`u`?window.innerWidth:1280,n=typeof window<`u`?window.innerHeight:800,r=an){return{left:Math.max(r,t-e.width-r),top:Math.max(r,n-e.height-r)}}function pn(e,t,n,r=typeof window<`u`?window.innerWidth:1280,i=typeof window<`u`?window.innerHeight:800,a=an){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(rn).matches}var mn=`
333
+ }`,on=!1;function sn(e){if(typeof document>`u`||on)return;if(document.querySelector(`style[data-liforma-et]`)){on=!0;return}let t=document.createElement(`style`);t.setAttribute(`data-liforma-et`,``),t.textContent=e,document.head.appendChild(t),on=!0}var cn=`liforma-experience-thumbnail`;function ln(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t.avatarImage==`string`)return t}catch{}}var un=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=an,e.replaceChildren(t);let n=this.getAttribute(`alt`)?.trim()||`Experience`,r=this.getAttribute(`href`),i=this.getAttribute(`experience-id`),a=Mt({href:r,hasClickHandler:this.hasAttribute(`onclick`)||typeof this.onclick==`function`,experienceId:i}),o=kt({galleryThumb:ln(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(),l=c===`face`||c===`medium`?c:`full`,u=this.#p(`lazy`,!0);this.#n=!u;let d=a===`anchor`&&!r?.trim()&&!!i?.trim(),f=Ft({href:r??void 0,experienceId:i??void 0,returnUrl:this.getAttribute(`return-url`)??void 0,playerBaseUrl:this.getAttribute(`player-base-url`)??void 0,useCurrentPageAsReturnUrl:d&&!this.getAttribute(`return-url`)?.trim()}),p;if(a===`anchor`&&f){let e=document.createElement(`a`);e.href=f;let t=this.getAttribute(`target`),n=this.getAttribute(`rel`);t&&(e.target=t),n&&(e.rel=n),p=e}else if(a===`button`){let e=document.createElement(`button`);e.type=`button`,p=e}else p=document.createElement(`div`),p.setAttribute(`role`,`img`);p.className=`liforma-et`,p.setAttribute(`aria-label`,n),this.#e=p,e.appendChild(p);let m=()=>{let e=!!o.backgroundImage,t=s&&(this.#r||this.#a),n=this.#n&&(this.#u||this.#l||this.#d);p.className=[`liforma-et`,e?`liforma-et--scene`:``,wt(l),t?`liforma-et--parallax`:``,this.#a?`liforma-et--scroll-parallax`:``,this.#n&&!n?`liforma-et--loading`:``,n?`liforma-et--revealed`:``].filter(Boolean).join(` `),p.style.setProperty(`--liforma-et-parallax-x`,String(this.#o)),p.style.setProperty(`--liforma-et-parallax-y`,String(this.#s))},h=document.createElement(`span`);h.className=`liforma-et__placeholder`,h.setAttribute(`aria-hidden`,`true`),p.appendChild(h);let g=()=>{if(!this.#n)return;let e=this.#c&&o.fallbackImage?o.fallbackImage:o.avatarImage;if(o.backgroundImage&&!p.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(qt(e,()=>{this.#l=!0,e.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(e)}let t=p.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,m())}),this.#t.push(qt(t,()=>{this.#u=!0,t.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(t)),t.src!==e&&(t.src=e),o.foregroundImage&&!p.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(qt(e,()=>{this.#d=!0,e.classList.add(`liforma-et__media--ready`),m()})),p.appendChild(e)}m()};if(u?this.#t.push(Kt(p,{onVisibleChange:e=>{e&&(this.#n=!0,g(),m())}})):g(),s){this.#t.push(nn(p,{onParallax:e=>{this.#a=!0,this.#i||(this.#o=e,this.#s=0,m())},pointerActive:()=>this.#i}));let e=e=>{if(this.#a)return;let t=p.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,m())},t=e=>{this.#i=!0,e.pointerType===`mouse`&&(this.#r=!0),m()},n=()=>{let e=this.#i;this.#i=!1,this.#r=!1,this.#a&&e?(this.#o=Yt(p.getBoundingClientRect(),window.innerHeight),this.#s=0):this.#a||(this.#o=0,this.#s=0),m()};p.addEventListener(`pointermove`,e),p.addEventListener(`pointerdown`,t),p.addEventListener(`pointerup`,n),p.addEventListener(`pointercancel`,n),p.addEventListener(`pointerenter`,e=>{e.pointerType===`mouse`&&(this.#r=!0,m())}),p.addEventListener(`pointerleave`,()=>{this.#i||(this.#r=!1,this.#a||(this.#o=0,this.#s=0),m())}),this.#t.push(()=>{p.removeEventListener(`pointermove`,e),p.removeEventListener(`pointerdown`,t),p.removeEventListener(`pointerup`,n),p.removeEventListener(`pointercancel`,n)})}p.addEventListener(`click`,e=>{if(d&&!this.getAttribute(`return-url`)?.trim()){let t=Ft({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))}}),m()}};customElements.get(cn)||customElements.define(cn,un);function dn(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 fn(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=dn(s.galleryThumb);if(!u)throw Error(`Experience preview is missing gallery thumb images.`);return{experienceId:c||n,title:l||c||n,galleryThumb:u}}var pn=`(min-width: 768px)`,mn=24,hn=.5,gn=1200,_n=.85,vn=9/16;function yn(){if(typeof window>`u`)return 800;let e=window.screen?.availHeight;return typeof e==`number`&&e>0?e:window.innerHeight}function bn(e=typeof window<`u`?window.innerWidth:1280,t=typeof window<`u`?window.innerHeight:800,n=mn,r=typeof window<`u`?yn():800){let i=Math.max(160,Math.min(t-n*2,t*_n)),a=Math.max(120,e-n*2),o=Math.min(r*hn,gn,i),s=o*vn;return s>a&&(s=a,o=s/vn,o>i&&(o=i,s=o*vn)),{width:Math.round(s),height:Math.round(o)}}function xn(e,t=typeof window<`u`?window.innerWidth:1280,n=typeof window<`u`?window.innerHeight:800,r=mn){return{left:Math.max(r,t-e.width-r),top:Math.max(r,n-e.height-r)}}function Sn(e,t,n,r=typeof window<`u`?window.innerWidth:1280,i=typeof window<`u`?window.innerHeight:800,a=mn){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(pn).matches}var Cn=`
334
334
  .liforma-ew {
335
335
  box-sizing: border-box;
336
336
  position: relative;
@@ -818,5 +818,5 @@ button.liforma-et {
818
818
  transition: none;
819
819
  }
820
820
  }
821
- `,hn=`liforma-experience-widget-styles`;function gn(e=mn){if(typeof document>`u`)return;let t=document.getElementById(hn);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=hn,n.textContent=e,document.head.append(n)}function _n(e){return e===`bottom-right`||e===`bottom-left`?e:`static`}function vn(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 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="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>`,bn=`<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>`,xn=`<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>`,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="M16 4h4v4m-6 2l6-6M8 20H4v-4m0 4l6-6"/></svg>`;function Cn(e,t,n){Zt(Yt);let r=xt({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?()=>{}:Jt(i)}function wn(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 Tn(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 En(e,t){gn(mn);let n=t.experienceId?.trim();if(!n)throw Error(`ExperienceWidget requires experienceId.`);let r=t.prefetch??`onExpand`,i=_n(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`,vn(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=xn,h.setAttribute(`aria-label`,`Reduce`);let g=document.createElement(`button`);g.type=`button`,g.className=`liforma-ew__icon-btn liforma-ew__settings`,g.innerHTML=yn,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=bn,_.setAttribute(`aria-label`,`Close`),p.append(m,h,g,_);let v=document.createElement(`div`);v.className=`liforma-ew__stage`;let y=document.createElement(`div`);y.className=`liforma-ew__status`,y.hidden=!0,f.append(v,y),u.append(d,f),a.append(o,l,u,p),e.replaceChildren(a);let b=null,x=!1,S=!1,ee=!1,C=!1,w=!1,T=!1,E=!1,D=0,te=``,O=null,ne=null,k=null,A=null,j=null,M=null,N=null,re=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`},ce=()=>{k!==null&&(clearTimeout(k),k=null)},I=()=>{A!==null&&(clearTimeout(A),A=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=dn(),r=pn(e-re,t-ie,n);j=r.left,M=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=dn(),r=j??f.getBoundingClientRect().left,i=M??f.getBoundingClientRect().top,a=pn(r+e,i+t,n);j=a.left,M=a.top,ue(a.left,a.top,n.width,n.height)},pe=e=>{P===`toolbar`&&(N===null||e.pointerId!==N||(e.preventDefault(),de(e.clientX,e.clientY)))},L=e=>{if(N===null||e&&e.pointerId!==N)return;let t=P;N=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`,pe),window.removeEventListener(`pointerup`,L),window.removeEventListener(`pointercancel`,L))},me=(e,t,n)=>{if(S||F()!==`docked`||!Q()||N!==null)return;N=n,P=`toolbar`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let r=f.getBoundingClientRect();re=e-r.left,ie=t-r.top,ae||(ae=!0,window.addEventListener(`pointermove`,pe),window.addEventListener(`pointerup`,L),window.addEventListener(`pointercancel`,L))},he=e=>{if(S||F()!==`docked`||!Q()||N!==null)return;N=e.pointerId,P=`player`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let t=f.getBoundingClientRect();j=t.left,M=t.top},ge=e=>{P===`player`&&(N===null||e.pointerId!==N||fe(e.dx,e.dy))},_e=e=>{P===`player`&&(N===null||e.pointerId!==N||L())},R=()=>{let e=Q(),t=F();if(!e||t!==`expanded`&&t!==`docked`){h.hidden=!0;return}h.hidden=!1,t===`docked`?(h.innerHTML=Sn,h.setAttribute(`aria-label`,`Maximize`)):(h.innerHTML=xn,h.setAttribute(`aria-label`,`Reduce`))},ve=e=>{let t=dn(),n=e&&j!==null&&M!==null?pn(j,M,t):fn(t);n=pn(n.left,n.top,t),j=n.left,M=n.top,ue(n.left,n.top,t.width,t.height),R()},ye=()=>{a.classList.remove(`liforma-ew--session-revealed`),requestAnimationFrame(()=>{requestAnimationFrame(()=>{S||!$(a.dataset.state)||a.classList.add(`liforma-ew--session-revealed`)})})},be=e=>{if(I(),a.classList.remove(`liforma-ew--session-revealed`),a.classList.add(`liforma-ew--layout-settling`),e(),!E){a.classList.remove(`liforma-ew--layout-settling`);return}A=setTimeout(()=>{if(A=null,S||!$(a.dataset.state)){a.classList.remove(`liforma-ew--layout-settling`);return}a.classList.remove(`liforma-ew--layout-settling`),ye()},220)},xe=()=>(a.classList.add(`liforma-ew--session-concealing`),a.classList.remove(`liforma-ew--session-revealed`),new Promise(e=>{ce(),k=setTimeout(()=>{k=null,a.classList.remove(`liforma-ew--session-concealing`),e()},280)})),Se={galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage},z=e=>{if(!e){y.hidden=!0,y.textContent=``;return}y.hidden=!1,y.textContent=e},B=e=>{if(!e){c.hidden=!0,c.textContent=``;return}c.hidden=!1,c.textContent=e,s.contains(c)||s.append(c)},Ce=()=>{ee=!0,o.disabled=!1,B(null),r===`onExpand`&&t.onPrefetchReady?.()},V=()=>{C=!0,a.dataset.warm=`true`,l.hidden=!1,E||(o.tabIndex=-1,o.setAttribute(`aria-hidden`,`true`)),t.onPrefetchReady?.()},we=e=>{O?.(),O=null;let t=Cn(s,e,{parallax:se});return t?(O=t,!0):!1},Te=()=>{if(we(Se)){Ce();return}B(`Loading…`),nn(n,{signal:oe.signal}).then(e=>{if(!S){if(!we({galleryThumb:e.galleryThumb}))throw Error(`Experience preview is missing gallery thumb images.`);Ce()}}).catch(e=>{if(S||oe.signal.aborted)return;let n=e instanceof Error?e:Error(String(e));B(`Preview unavailable`),o.disabled=!0,t.onError?.(n),console.error(`[ExperienceWidget]`,n)})},H=()=>({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}:{}}),Ee=()=>({...t.fit?{fit:t.fit}:{},startButton:wn(t),...t.showFeedback===void 0?{}:{showFeedback:t.showFeedback}}),U=(e=!0)=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`true`),le(),a.dataset.state=`expanded`,z(null),typeof document<`u`&&(te=document.body.style.overflow,document.body.style.overflow=`hidden`),R(),e&&t.onExpanded?.()},W=()=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`false`),a.dataset.state=`docked`,z(null),typeof document<`u`&&(document.body.style.overflow=te),ve(!0),R(),b?.setWidgetChrome(`docked`)},De=e=>{e.on(`started`,()=>{S||(E=!0,a.dataset.live=`true`,z(null),t.onStarted?.(),$(a.dataset.state)&&ye())}),e.on(`feedback`,e=>{S||t.onFeedback?.(e)}),e.on(`feedbackFailed`,e=>{S||t.onFeedbackFailed?.(e)})},G=()=>{I(),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`),ee&&(o.disabled=!1),z(null),typeof document<`u`&&(document.body.style.overflow=te),R()},K=()=>{ce(),I(),D+=1,x=!1,C=!1,w=!1,T=!1,E=!1;let e=b;b=null,e?.destroy(),v.replaceChildren(),l.replaceChildren(),l.hidden=!0,delete a.dataset.warm,delete a.dataset.live,a.classList.remove(`liforma-ew--session-revealed`)},q=()=>{if(!S&&$(a.dataset.state)){if(L(),x=!1,b&&T){let e=b;(async()=>{E&&(await xe(),S||b!==e)||(C&&e.setWidgetChrome(`collapsed`),G(),E?(a.dataset.live=`true`,o.tabIndex=0,o.removeAttribute(`aria-hidden`),o.disabled=!1):C&&V(),t.onCollapsed?.(),t.onClose?.())})();return}K(),G(),t.onCollapsed?.(),t.onClose?.()}},Oe=()=>{S||Q()&&F()===`expanded`&&be(()=>{W()})},ke=()=>{S||F()===`docked`&&(L(),be(()=>{le(),U(!1),b?.setWidgetChrome(`expanded`)}))},J=()=>{!b||!E||(ce(),a.classList.remove(`liforma-ew--session-revealed`),U(),b.setWidgetChrome(`expanded`),x=!1,ye())},Ae=()=>{!b||!T||E||(ce(),a.classList.remove(`liforma-ew--session-revealed`),U(),x=!1,C||b.setWidgetChrome(`expanded`))},je=e=>{S||e!==D&&!E||(ce(),a.classList.remove(`liforma-ew--session-revealed`),U(),x=!1,E&&ye())},Me=()=>{if(S||w||C||b||$(a.dataset.state))return;w=!0;let e=D;l.hidden=!1,(async()=>{try{let t=await Ye.startSession(H());if(S||e!==D){t.destroy();return}b=t,De(t);let n=await t.attach({container:l,...Ee(),onWidgetReady:()=>{S||e!==D||(w=!1,T=!0,$(a.dataset.state)?t.setWidgetChrome(`expanded`):V())},onWidgetExpand:()=>{je(e)},onWidgetAudioSettings:e=>{S||Ie(e)},onWidgetDragStart:e=>{S||he(e)},onWidgetDragMove:e=>{S||ge(e)},onWidgetDragEnd:e=>{S||_e(e)},onPlayerStatusChange:e=>{S||e===`error`&&$(a.dataset.state)&&z(`Could not load the experience.`)}});if(S||e!==D){t.destroy(),b===t&&(b=null);return}n.on(`close`,()=>{S||q()})}catch(n){if(S||e!==D)return;w=!1,l.hidden=!0,l.replaceChildren(),b=null;let r=n instanceof Error?n:Error(String(n));t.onError?.(r),console.error(`[ExperienceWidget] warm prefetch failed`,r)}})()},Ne=()=>{if(S||x||!ee||$(a.dataset.state))return;if(b&&E){J();return}if(b&&T){Ae();return}let e=++D;x=!0,C=!1,w=!1,T=!1,E=!1,delete a.dataset.warm,delete a.dataset.live,l.hidden=!0,l.replaceChildren(),b&&=(b.destroy(),null),(async()=>{try{U();let t=await Ye.startSession(H());if(S||e!==D){t.destroy();return}b=t,De(t);let n=await t.attach({container:v,...Ee(),onWidgetAudioSettings:e=>{S||Ie(e)},onWidgetDragStart:e=>{S||he(e)},onWidgetDragMove:e=>{S||ge(e)},onWidgetDragEnd:e=>{S||_e(e)},onPlayerStatusChange:e=>{S||(e===`error`?z(`Could not load the experience.`):$(a.dataset.state)&&z(null))}});if(S||e!==D){t.destroy(),b===t&&(b=null);return}T=!0,t.setWidgetChrome(`expanded`),n.on(`close`,()=>{S||q()})}catch(n){if(S||e!==D)return;let r=n instanceof Error?n:Error(String(n));z(r.message),t.onError?.(r),console.error(`[ExperienceWidget]`,r)}finally{e===D&&(x=!1)}})()},Pe=()=>{if(!(S||$(a.dataset.state))){if(b&&E){J();return}if(b&&T){Ae();return}if(w||b){U();return}Ne()}},Fe=e=>{if(e.stopPropagation(),F()===`expanded`){Oe();return}F()===`docked`&&ke()},Ie=e=>{g.setAttribute(`aria-pressed`,e?`true`:`false`)},Le=e=>{e.stopPropagation(),$(a.dataset.state)&&b?.toggleAudioSettings()},Re=e=>{F()===`docked`&&Q()&&(e.target?.closest(`button`)||(e.preventDefault(),me(e.clientX,e.clientY,e.pointerId)))},ze=e=>{e.key===`Escape`&&$(a.dataset.state)&&(e.preventDefault(),q())},Be=()=>{if(!S){if(F()===`docked`){if(!Q()){ke();return}E?be(()=>{ve(!0)}):ve(!0);return}R()}},Ve=typeof window<`u`?window.matchMedia(rn):null,He=()=>{if(!S){if(F()===`docked`&&!Q()){ke();return}R()}};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),Te(),R(),r===`eager`?queueMicrotask(()=>{S||Me()}):r===`idle`&&(ne=Tn(()=>{S||Me()})),{root:a,expand:Pe,collapse:q,dock:Oe,maximize:ke,prefetch(){if(r===`onExpand`){Me();return}Me()},destroy(){S||(S=!0,L(),ne?.(),ne=null,oe.abort(),O?.(),O=null,window.removeEventListener(`keydown`,ze),window.removeEventListener(`resize`,Be),Ve?.removeEventListener(`change`,He),K(),G(),e.replaceChildren())}}}var Dn=`liforma-experience-widget`;function On(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.avatarImage==`string`)return t}catch{}}function kn(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function An(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function jn(e){return qe(e)}function Mn(e){let t=e?.trim();return t===`en`||t===`es`?t:void 0}function Nn(e){let t=e?.trim();return t===`bottom-right`||t===`bottom-left`?t:`static`}var Pn=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(Nn(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=Nn(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=En(this.#t,{experienceId:e,alt:t,galleryThumb:On(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:Mn(this.getAttribute(`language`)),mode:kn(this.getAttribute(`mode`)),speechInputMode:An(this.getAttribute(`speech-input-mode`)),speechOnly:a===null?void 0:a===``||a===`true`,fit:jn(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(Dn)&&customElements.define(Dn,Pn),window.Liforma={Experience:Ye,sdkVersion:`v2`,features:{speakApi:!0,speechAudioApi:!0}},e.Experience=Ye,e.LiformaError=o,e.SPEECH_LIMITS=H,e.SpeechBufferTimeoutError=De,e.SpeechRuntimeError=W,e.SpeechUtteranceClosedError=U,e.UnsupportedSpeechOperationError=Ee,e.liformaErrorFromResponse=c,e.warnLocaleVoiceFallbacks=y,e})({});
821
+ `,wn=`liforma-experience-widget-styles`;function Tn(e=Cn){if(typeof document>`u`)return;let t=document.getElementById(wn);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=wn,n.textContent=e,document.head.append(n)}function En(e){return e===`bottom-right`||e===`bottom-left`?e:`static`}function Dn(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 On=`<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>`,kn=`<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>`,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="M18 10h-4V6m6-2l-6 6m-8 4h4v4m0-4l-6 6"/></svg>`,jn=`<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 Mn(e,t,n){sn(an);let r=kt({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?()=>{}:rn(i)}function Nn(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 Pn(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(Cn);let n=t.experienceId?.trim();if(!n)throw Error(`ExperienceWidget requires experienceId.`);let r=t.prefetch??`onExpand`,i=En(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`,Dn(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=An,h.setAttribute(`aria-label`,`Reduce`);let g=document.createElement(`button`);g.type=`button`,g.className=`liforma-ew__icon-btn liforma-ew__settings`,g.innerHTML=On,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=kn,_.setAttribute(`aria-label`,`Close`),p.append(m,h,g,_);let v=document.createElement(`div`);v.className=`liforma-ew__stage`;let y=document.createElement(`div`);y.className=`liforma-ew__status`,y.hidden=!0,f.append(v,y),u.append(d,f),a.append(o,l,u,p),e.replaceChildren(a);let b=null,x=!1,S=!1,C=!1,w=!1,T=!1,E=!1,D=!1,O=0,ee=``,k=null,te=null,A=null,j=null,M=null,N=null,P=null,ne=0,F=0,I=null,L=!1,re=new AbortController,ie=t.parallax!==!1,R=()=>{let e=a.dataset.state;return e===`expanded`||e===`docked`||e===`collapsed`?e:`collapsed`},ae=()=>{A!==null&&(clearTimeout(A),A=null)},oe=()=>{j!==null&&(clearTimeout(j),j=null),a.classList.remove(`liforma-ew--layout-settling`)},se=()=>{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`)},ce=(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`},le=(e,t)=>{if(R()!==`docked`)return;let n=bn(),r=Sn(e-ne,t-F,n);M=r.left,N=r.top,ce(r.left,r.top,n.width,n.height)},ue=(e,t)=>{if(R()!==`docked`||!Number.isFinite(e)||!Number.isFinite(t)||e===0&&t===0)return;let n=bn(),r=M??f.getBoundingClientRect().left,i=N??f.getBoundingClientRect().top,a=Sn(r+e,i+t,n);M=a.left,N=a.top,ce(a.left,a.top,n.width,n.height)},de=e=>{I===`toolbar`&&(P===null||e.pointerId!==P||(e.preventDefault(),le(e.clientX,e.clientY)))},z=e=>{if(P===null||e&&e.pointerId!==P)return;let t=I;P=null,I=null,p.classList.remove(`liforma-ew__toolbar--dragging`),a.classList.remove(`liforma-ew--dock-dragging`),t===`toolbar`&&L&&(L=!1,window.removeEventListener(`pointermove`,de),window.removeEventListener(`pointerup`,z),window.removeEventListener(`pointercancel`,z))},fe=(e,t,n)=>{if(S||R()!==`docked`||!Q()||P!==null)return;P=n,I=`toolbar`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let r=f.getBoundingClientRect();ne=e-r.left,F=t-r.top,L||(L=!0,window.addEventListener(`pointermove`,de),window.addEventListener(`pointerup`,z),window.addEventListener(`pointercancel`,z))},pe=e=>{if(S||R()!==`docked`||!Q()||P!==null)return;P=e.pointerId,I=`player`,p.classList.add(`liforma-ew__toolbar--dragging`),a.classList.add(`liforma-ew--dock-dragging`);let t=f.getBoundingClientRect();M=t.left,N=t.top},B=e=>{I===`player`&&(P===null||e.pointerId!==P||ue(e.dx,e.dy))},me=e=>{I===`player`&&(P===null||e.pointerId!==P||z())},V=()=>{let e=Q(),t=R();if(!e||t!==`expanded`&&t!==`docked`){h.hidden=!0;return}h.hidden=!1,t===`docked`?(h.innerHTML=jn,h.setAttribute(`aria-label`,`Maximize`)):(h.innerHTML=An,h.setAttribute(`aria-label`,`Reduce`))},he=e=>{let t=bn(),n=e&&M!==null&&N!==null?Sn(M,N,t):xn(t);n=Sn(n.left,n.top,t),M=n.left,N=n.top,ce(n.left,n.top,t.width,t.height),V()},ge=()=>{a.classList.remove(`liforma-ew--session-revealed`),requestAnimationFrame(()=>{requestAnimationFrame(()=>{S||!$(a.dataset.state)||a.classList.add(`liforma-ew--session-revealed`)})})},_e=e=>{if(oe(),a.classList.remove(`liforma-ew--session-revealed`),a.classList.add(`liforma-ew--layout-settling`),e(),!D){a.classList.remove(`liforma-ew--layout-settling`);return}j=setTimeout(()=>{if(j=null,S||!$(a.dataset.state)){a.classList.remove(`liforma-ew--layout-settling`);return}a.classList.remove(`liforma-ew--layout-settling`),ge()},220)},ve=()=>(a.classList.add(`liforma-ew--session-concealing`),a.classList.remove(`liforma-ew--session-revealed`),new Promise(e=>{ae(),A=setTimeout(()=>{A=null,a.classList.remove(`liforma-ew--session-concealing`),e()},280)})),ye={galleryThumb:t.galleryThumb,avatarImage:t.avatarImage,backgroundImage:t.backgroundImage,foregroundImage:t.foregroundImage,fallbackImage:t.fallbackImage},H=e=>{if(!e){y.hidden=!0,y.textContent=``;return}y.hidden=!1,y.textContent=e},be=e=>{if(!e){c.hidden=!0,c.textContent=``;return}c.hidden=!1,c.textContent=e,s.contains(c)||s.append(c)},xe=()=>{C=!0,o.disabled=!1,be(null),r===`onExpand`&&t.onPrefetchReady?.()},Se=()=>{w=!0,a.dataset.warm=`true`,l.hidden=!1,D||(o.tabIndex=-1,o.setAttribute(`aria-hidden`,`true`)),t.onPrefetchReady?.()},Ce=e=>{k?.(),k=null;let t=Mn(s,e,{parallax:ie});return t?(k=t,!0):!1},we=()=>{if(Ce(ye)){xe();return}be(`Loading…`),fn(n,{signal:re.signal}).then(e=>{if(!S){if(!Ce({galleryThumb:e.galleryThumb}))throw Error(`Experience preview is missing gallery thumb images.`);xe()}}).catch(e=>{if(S||re.signal.aborted)return;let n=e instanceof Error?e:Error(String(e));be(`Preview unavailable`),o.disabled=!0,t.onError?.(n),console.error(`[ExperienceWidget]`,n)})},Te=()=>({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}:{}}),Ee=()=>({...t.fit?{fit:t.fit}:{},startButton:Nn(t),...t.showFeedback===void 0?{}:{showFeedback:t.showFeedback}}),U=(e=!0)=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`true`),se(),a.dataset.state=`expanded`,H(null),typeof document<`u`&&(ee=document.body.style.overflow,document.body.style.overflow=`hidden`),V(),e&&t.onExpanded?.()},De=()=>{o.hidden=!0,u.hidden=!1,p.hidden=!1,u.setAttribute(`aria-modal`,`false`),a.dataset.state=`docked`,H(null),typeof document<`u`&&(document.body.style.overflow=ee),he(!0),V(),b?.setWidgetChrome(`docked`)},Oe=e=>{e.on(`started`,()=>{S||(D=!0,a.dataset.live=`true`,H(null),t.onStarted?.(),$(a.dataset.state)&&ge())}),e.on(`feedback`,e=>{S||t.onFeedback?.(e)}),e.on(`feedbackFailed`,e=>{S||t.onFeedbackFailed?.(e)})},W=()=>{oe(),u.hidden=!0,p.hidden=!0,se(),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`),C&&(o.disabled=!1),H(null),typeof document<`u`&&(document.body.style.overflow=ee),V()},G=()=>{ae(),oe(),O+=1,x=!1,w=!1,T=!1,E=!1,D=!1;let e=b;b=null,e?.destroy(),v.replaceChildren(),l.replaceChildren(),l.hidden=!0,delete a.dataset.warm,delete a.dataset.live,a.classList.remove(`liforma-ew--session-revealed`)},K=()=>{if(!S&&$(a.dataset.state)){if(z(),x=!1,b&&E){let e=b;(async()=>{D&&(await ve(),S||b!==e)||(w&&e.setWidgetChrome(`collapsed`),W(),D?(a.dataset.live=`true`,o.tabIndex=0,o.removeAttribute(`aria-hidden`),o.disabled=!1):w&&Se(),t.onCollapsed?.(),t.onClose?.())})();return}G(),W(),t.onCollapsed?.(),t.onClose?.()}},ke=()=>{S||Q()&&R()===`expanded`&&_e(()=>{De()})},q=()=>{S||R()===`docked`&&(z(),_e(()=>{se(),U(!1),b?.setWidgetChrome(`expanded`)}))},Ae=()=>{!b||!D||(ae(),a.classList.remove(`liforma-ew--session-revealed`),U(),b.setWidgetChrome(`expanded`),x=!1,ge())},J=()=>{!b||!E||D||(ae(),a.classList.remove(`liforma-ew--session-revealed`),U(),x=!1,w||b.setWidgetChrome(`expanded`))},Y=e=>{S||e!==O&&!D||(ae(),a.classList.remove(`liforma-ew--session-revealed`),U(),x=!1,D&&ge())},X=()=>{if(S||T||w||b||$(a.dataset.state))return;T=!0;let e=O;l.hidden=!1,(async()=>{try{let t=await rt.startSession(Te());if(S||e!==O){t.destroy();return}b=t,Oe(t);let n=await t.attach({container:l,...Ee(),onWidgetReady:()=>{S||e!==O||(T=!1,E=!0,$(a.dataset.state)?t.setWidgetChrome(`expanded`):Se())},onWidgetExpand:()=>{Y(e)},onWidgetAudioSettings:e=>{S||Pe(e)},onWidgetDragStart:e=>{S||pe(e)},onWidgetDragMove:e=>{S||B(e)},onWidgetDragEnd:e=>{S||me(e)},onPlayerStatusChange:e=>{S||e===`error`&&$(a.dataset.state)&&H(`Could not load the experience.`)}});if(S||e!==O){t.destroy(),b===t&&(b=null);return}n.on(`close`,()=>{S||K()})}catch(n){if(S||e!==O)return;T=!1,l.hidden=!0,l.replaceChildren(),b=null;let r=n instanceof Error?n:Error(String(n));t.onError?.(r),console.error(`[ExperienceWidget] warm prefetch failed`,r)}})()},je=()=>{if(S||x||!C||$(a.dataset.state))return;if(b&&D){Ae();return}if(b&&E){J();return}let e=++O;x=!0,w=!1,T=!1,E=!1,D=!1,delete a.dataset.warm,delete a.dataset.live,l.hidden=!0,l.replaceChildren(),b&&=(b.destroy(),null),(async()=>{try{U();let t=await rt.startSession(Te());if(S||e!==O){t.destroy();return}b=t,Oe(t);let n=await t.attach({container:v,...Ee(),onWidgetAudioSettings:e=>{S||Pe(e)},onWidgetDragStart:e=>{S||pe(e)},onWidgetDragMove:e=>{S||B(e)},onWidgetDragEnd:e=>{S||me(e)},onPlayerStatusChange:e=>{S||(e===`error`?H(`Could not load the experience.`):$(a.dataset.state)&&H(null))}});if(S||e!==O){t.destroy(),b===t&&(b=null);return}E=!0,t.setWidgetChrome(`expanded`),n.on(`close`,()=>{S||K()})}catch(n){if(S||e!==O)return;let r=n instanceof Error?n:Error(String(n));H(r.message),t.onError?.(r),console.error(`[ExperienceWidget]`,r)}finally{e===O&&(x=!1)}})()},Me=()=>{if(!(S||$(a.dataset.state))){if(b&&D){Ae();return}if(b&&E){J();return}if(T||b){U();return}je()}},Ne=e=>{if(e.stopPropagation(),R()===`expanded`){ke();return}R()===`docked`&&q()},Pe=e=>{g.setAttribute(`aria-pressed`,e?`true`:`false`)},Fe=e=>{e.stopPropagation(),$(a.dataset.state)&&b?.toggleAudioSettings()},Ie=e=>{R()===`docked`&&Q()&&(e.target?.closest(`button`)||(e.preventDefault(),fe(e.clientX,e.clientY,e.pointerId)))},Le=e=>{e.key===`Escape`&&$(a.dataset.state)&&(e.preventDefault(),K())},Re=()=>{if(!S){if(R()===`docked`){if(!Q()){q();return}D?_e(()=>{he(!0)}):he(!0);return}V()}},ze=typeof window<`u`?window.matchMedia(pn):null,Be=()=>{if(!S){if(R()===`docked`&&!Q()){q();return}V()}};return o.addEventListener(`click`,Me),d.addEventListener(`click`,K),_.addEventListener(`click`,e=>{e.stopPropagation(),K()}),h.addEventListener(`click`,Ne),g.addEventListener(`click`,Fe),p.addEventListener(`pointerdown`,Ie),window.addEventListener(`keydown`,Le),window.addEventListener(`resize`,Re),ze?.addEventListener(`change`,Be),we(),V(),r===`eager`?queueMicrotask(()=>{S||X()}):r===`idle`&&(te=Pn(()=>{S||X()})),{root:a,expand:Me,collapse:K,dock:ke,maximize:q,prefetch(){if(r===`onExpand`){X();return}X()},destroy(){S||(S=!0,z(),te?.(),te=null,re.abort(),k?.(),k=null,window.removeEventListener(`keydown`,Le),window.removeEventListener(`resize`,Re),ze?.removeEventListener(`change`,Be),G(),W(),e.replaceChildren())}}}var In=`liforma-experience-widget`;function Ln(e){if(e?.trim())try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.avatarImage==`string`)return t}catch{}}function Rn(e){let t=e?.trim();return t===`conversation`||t===`presenter`?t:void 0}function zn(e){let t=e?.trim();return t===`auto`||t===`manual`||t===`off`?t:void 0}function Bn(e){return tt(e)}function Vn(e){let t=e?.trim();return t===`en`||t===`es`?t:void 0}function Hn(e){let t=e?.trim();return t===`bottom-right`||t===`bottom-left`?t:`static`}var Un=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(Hn(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=Hn(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:Ln(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:Vn(this.getAttribute(`language`)),mode:Rn(this.getAttribute(`mode`)),speechInputMode:zn(this.getAttribute(`speech-input-mode`)),speechOnly:a===null?void 0:a===``||a===`true`,fit:Bn(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(In)&&customElements.define(In,Un),window.Liforma={Experience:rt,sdkVersion:`v2`,features:{speakApi:!0,speechAudioApi:!0}},e.Experience=rt,e.LiformaError=o,e.SPEECH_LIMITS=q,e.SpeechBufferTimeoutError=X,e.SpeechRuntimeError=Y,e.SpeechUtteranceClosedError=J,e.UnsupportedSpeechOperationError=Ae,e.liformaErrorFromResponse=c,e.warnLocaleVoiceFallbacks=w,e})({});
822
822
  //# sourceMappingURL=client.js.map