@cliniq360/eigi-chat 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/eigi-chat.js CHANGED
@@ -45,4 +45,4 @@ var Ct={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24
45
45
  * https://github.com/lancedikson/bowser
46
46
  * MIT License | (c) Dustin Diaz 2012-2015
47
47
  * MIT License | (c) Denis Demchenko 2015-2019
48
- */class $u{static getParser(e,t=!1){if("string"!=typeof e)throw new Error("UserAgent should be a string");return new Vu(e,t)}static parse(e){return new Vu(e).getResult()}static get BROWSER_MAP(){return Nu}static get ENGINE_MAP(){return Iu}static get OS_MAP(){return ju}static get PLATFORMS_MAP(){return Lu}}function Wu(e,t){return Object.keys(t).forEach(function(n){"default"===n||"__esModule"===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})}),e}function qu(e){return e&&e.__esModule?e.default:e}function Hu(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var Ju={},Qu={};Hu(Qu,"PipecatClient",()=>Vd);var Gu;Gu=JSON.parse('{"name":"@pipecat-ai/client-js","version":"1.5.0","license":"BSD-2-Clause","main":"dist/index.js","module":"dist/index.module.js","types":"dist/index.d.ts","source":"index.ts","repository":{"type":"git","url":"git+https://github.com/pipecat-ai/pipecat-client-web.git"},"files":["dist","package.json","README.md"],"scripts":{"build":"jest --silent --passWithNoTests && parcel build --no-cache","dev":"parcel watch","lint":"eslint . --report-unused-disable-directives --max-warnings 0","test":"jest"},"jest":{"preset":"ts-jest","testEnvironment":"jsdom"},"devDependencies":{"@jest/globals":"^29.7.0","@types/clone-deep":"^4.0.4","@types/jest":"^29.5.12","@types/uuid":"^10.0.0","eslint":"^9.11.1","eslint-config-prettier":"^9.1.0","eslint-plugin-simple-import-sort":"^12.1.1","jest":"^29.7.0","jest-environment-jsdom":"^30.0.2","ts-jest":"^29.2.5"},"dependencies":{"@types/events":"^3.0.3","bowser":"^2.11.0","clone-deep":"^4.0.1","events":"^3.3.0","typed-emitter":"^2.1.0","uuid":"^10.0.0"}}');var Yu,Ku,Xu={},Zu={};Hu(Zu,"TransportStateEnum",()=>Yu),(Ku=Yu||(Yu={})).DISCONNECTED="disconnected",Ku.INITIALIZING="initializing",Ku.INITIALIZED="initialized",Ku.AUTHENTICATING="authenticating",Ku.AUTHENTICATED="authenticated",Ku.CONNECTING="connecting",Ku.CONNECTED="connected",Ku.READY="ready",Ku.DISCONNECTING="disconnecting",Ku.ERROR="error";var ed={};Hu(ed,"RTVIError",()=>td),Hu(ed,"ConnectionTimeoutError",()=>nd),Hu(ed,"StartBotError",()=>rd),Hu(ed,"TransportStartError",()=>id),Hu(ed,"InvalidTransportParamsError",()=>ad),Hu(ed,"BotNotReadyError",()=>od),Hu(ed,"BotAlreadyStartedError",()=>sd),Hu(ed,"UnsupportedFeatureError",()=>ld),Hu(ed,"DeviceError",()=>cd);class td extends Error{constructor(e,t){super(e),this.status=t}}class nd extends td{constructor(e){super(null!=e?e:"Bot did not enter ready state within the specified timeout period.")}}class rd extends td{constructor(e,t){super(null!=e?e:"Failed to connect / invalid auth bundle from base url",null!=t?t:500),this.error="invalid-request-error"}}class id extends td{constructor(e){super(null!=e?e:"Unable to connect to transport")}}class ad extends td{constructor(e){super(null!=e?e:"Invalid transport connection parameters")}}class od extends td{constructor(e){super(null!=e?e:"Attempt to call action on transport when not in 'ready' state.")}}class sd extends td{constructor(e){super(null!=e?e:"Pipecat client has already been started. Please call disconnect() before starting again.")}}class ld extends td{constructor(e,t,n){let r=`${e} not supported${n?`: ${n}`:""}`;t&&(r=`${t} does not support ${e}${n?`: ${n}`:""}`),super(r),this.feature=e}}class cd extends td{constructor(e,t,n,r){super(null!=n?n:`Device error for ${e.join(", ")}: ${t}`),this.devices=e,this.type=t,this.details=r}}var ud,dd,fd={};Hu(fd,"RTVIEvent",()=>ud),(dd=ud||(ud={})).Connected="connected",dd.Disconnected="disconnected",dd.TransportStateChanged="transportStateChanged",dd.BotStarted="botStarted",dd.BotConnected="botConnected",dd.BotReady="botReady",dd.BotDisconnected="botDisconnected",dd.Error="error",dd.ServerMessage="serverMessage",dd.ServerResponse="serverResponse",dd.MessageError="messageError",dd.Metrics="metrics",dd.BotStartedSpeaking="botStartedSpeaking",dd.BotStoppedSpeaking="botStoppedSpeaking",dd.UserStartedSpeaking="userStartedSpeaking",dd.UserStoppedSpeaking="userStoppedSpeaking",dd.UserTranscript="userTranscript",dd.BotOutput="botOutput",dd.BotTranscript="botTranscript",dd.BotLlmText="botLlmText",dd.BotLlmStarted="botLlmStarted",dd.BotLlmStopped="botLlmStopped",dd.LLMFunctionCall="llmFunctionCall",dd.BotLlmSearchResponse="botLlmSearchResponse",dd.BotTtsText="botTtsText",dd.BotTtsStarted="botTtsStarted",dd.BotTtsStopped="botTtsStopped",dd.ParticipantConnected="participantConnected",dd.ParticipantLeft="participantLeft",dd.TrackStarted="trackStarted",dd.TrackStopped="trackStopped",dd.ScreenTrackStarted="screenTrackStarted",dd.ScreenTrackStopped="screenTrackStopped",dd.ScreenShareError="screenShareError",dd.LocalAudioLevel="localAudioLevel",dd.RemoteAudioLevel="remoteAudioLevel",dd.AvailableCamsUpdated="availableCamsUpdated",dd.AvailableMicsUpdated="availableMicsUpdated",dd.AvailableSpeakersUpdated="availableSpeakersUpdated",dd.CamUpdated="camUpdated",dd.MicUpdated="micUpdated",dd.SpeakerUpdated="speakerUpdated",dd.DeviceError="deviceError";var pd={};Hu(pd,"RTVI_PROTOCOL_VERSION",()=>hd),Hu(pd,"RTVI_MESSAGE_LABEL",()=>md),Hu(pd,"RTVIMessageType",()=>gd),Hu(pd,"AggregationType",()=>yd),Hu(pd,"setAboutClient",()=>kd),Hu(pd,"RTVIMessage",()=>Sd);const hd="1.0.0",md="rtvi-ai";var gd,vd,yd,bd;let wd;function kd(e){wd=wd?l(l({},wd),e):e}(vd=gd||(gd={})).CLIENT_READY="client-ready",vd.DISCONNECT_BOT="disconnect-bot",vd.CLIENT_MESSAGE="client-message",vd.SEND_TEXT="send-text",vd.APPEND_TO_CONTEXT="append-to-context",vd.BOT_READY="bot-ready",vd.ERROR="error",vd.METRICS="metrics",vd.SERVER_MESSAGE="server-message",vd.SERVER_RESPONSE="server-response",vd.ERROR_RESPONSE="error-response",vd.APPEND_TO_CONTEXT_RESULT="append-to-context-result",vd.USER_TRANSCRIPTION="user-transcription",vd.BOT_OUTPUT="bot-output",vd.BOT_TRANSCRIPTION="bot-transcription",vd.USER_STARTED_SPEAKING="user-started-speaking",vd.USER_STOPPED_SPEAKING="user-stopped-speaking",vd.BOT_STARTED_SPEAKING="bot-started-speaking",vd.BOT_STOPPED_SPEAKING="bot-stopped-speaking",vd.USER_LLM_TEXT="user-llm-text",vd.BOT_LLM_TEXT="bot-llm-text",vd.BOT_LLM_STARTED="bot-llm-started",vd.BOT_LLM_STOPPED="bot-llm-stopped",vd.LLM_FUNCTION_CALL="llm-function-call",vd.LLM_FUNCTION_CALL_RESULT="llm-function-call-result",vd.BOT_LLM_SEARCH_RESPONSE="bot-llm-search-response",vd.BOT_TTS_TEXT="bot-tts-text",vd.BOT_TTS_STARTED="bot-tts-started",vd.BOT_TTS_STOPPED="bot-tts-stopped",(bd=yd||(yd={})).WORD="word",bd.SENTENCE="sentence";class Sd{constructor(e,t,n){this.label=md,this.type=e,this.data=t,this.id=n||Au().slice(0,8)}static clientReady(){return new Sd(gd.CLIENT_READY,{version:hd,about:wd||{library:Gu.name,library_version:Gu.version}})}static disconnectBot(){return new Sd(gd.DISCONNECT_BOT,{})}static error(e,t=!1){return new Sd(gd.ERROR,{message:e,fatal:t})}}function _d(e,t,n){const r=n.value;return n.value=function(...e){if("ready"===this.state)return r.apply(this,e);throw new od(`Attempt to call ${t.toString()} when transport not in ready state. Await connect() first.`)},n}function xd(e,t,n){const r=n.value,i=["authenticating","connecting","connected","ready"];return n.value=function(...e){if(i.includes(this.state))throw new sd(`Attempt to call ${t.toString()} when client already started. Please call disconnect() before starting again.`);return r.apply(this,e)},n}Wu(Xu,Zu),Wu(Xu,ed),Wu(Xu,fd),Wu(Xu,pd);var Ed={};Hu(Ed,"MessageDispatcher",()=>Od);var Cd,Td,Md={};Hu(Md,"LogLevel",()=>Cd),Hu(Md,"logger",()=>Ad),(Td=Cd||(Cd={}))[Td.NONE=0]="NONE",Td[Td.ERROR=1]="ERROR",Td[Td.WARN=2]="WARN",Td[Td.INFO=3]="INFO",Td[Td.DEBUG=4]="DEBUG";class Pd{constructor(){this.level=Cd.DEBUG}static getInstance(){return Pd.instance||(Pd.instance=new Pd),Pd.instance}setLevel(e){this.level=e}debug(...e){this.level>=Cd.DEBUG&&console.debug(...e)}info(...e){this.level>=Cd.INFO&&console.info(...e)}warn(...e){this.level>=Cd.WARN&&console.warn(...e)}error(...e){this.level>=Cd.ERROR&&console.error(...e)}}const Ad=Pd.getInstance();class Od{constructor(e){this._queue=new Array,this._gcInterval=void 0,this._queue=[],this._sendMethod=e}disconnect(){this.clearQueue(),clearInterval(this._gcInterval),this._gcInterval=void 0}dispatch(e,t=gd.CLIENT_MESSAGE,n=1e4){this._gcInterval||(this._gcInterval=setInterval(()=>{this._gc()},2e3));const r=new Sd(t,e),i=new Promise((e,t)=>{this._queue.push({message:r,timestamp:Date.now(),timeout:n,resolve:e,reject:t})});Ad.debug("[MessageDispatcher] dispatch",r);try{this._sendMethod(r)}catch(lr){return Ad.error("[MessageDispatcher] Error sending message",lr),Promise.reject(lr)}return this._gc(),i}clearQueue(){this._queue=[]}_resolveReject(e,t=!0){const n=this._queue.find(t=>t.message.id===e.id);return n&&(t?(Ad.debug("[MessageDispatcher] Resolve",e),n.resolve(e)):(Ad.debug("[MessageDispatcher] Reject",e),n.reject(e)),this._queue=this._queue.filter(t=>t.message.id!==e.id),Ad.debug("[MessageDispatcher] Queue",this._queue)),e}resolve(e){return this._resolveReject(e,!0)}reject(e){return this._resolveReject(e,!1)}_gc(){const e=[];this._queue=this._queue.filter(t=>{const n=Date.now()-t.timestamp<t.timeout;return n||e.push(t),n}),e.forEach(e=>{e.message.type===gd.CLIENT_MESSAGE&&e.reject(new Sd(gd.ERROR_RESPONSE,{error:"Timed out waiting for response",msgType:e.message.data.t,data:e.message.data.d,fatal:!1}))}),Ad.debug("[MessageDispatcher] GC",this._queue)}}var Nd={};function Ld(e){if("object"==typeof e&&null!==e&&Object.keys(e).includes("endpoint")){const t=e.endpoint;return"string"==typeof t||t instanceof URL||"undefined"!=typeof Request&&t instanceof Request}return!1}function jd(e,t){return d(this,null,function*(){let n;return t||(t=new AbortController),new Promise((r,i)=>{d(null,null,function*(){var a;e.timeout&&(n=setTimeout(()=>d(null,null,function*(){t.abort(),i(new Error("Timed out"))}),e.timeout)),Ad.debug(`[Pipecat Client] Fetching from ${e.endpoint}`),fetch(e.endpoint,{method:"POST",mode:"cors",headers:new Headers(l({"Content-Type":"application/json"},Object.fromEntries((null!=(a=e.headers)?a:new Headers).entries()))),body:JSON.stringify(e.requestData),signal:null==t?void 0:t.signal}).then(t=>{Ad.debug(`[Pipecat Client] Received response from ${e.endpoint}`,t),t.ok||i(t),t.json().then(e=>r(e))}).catch(e=>{Ad.error(`[Pipecat Client] Error fetching: ${e}`),i(e)}).finally(()=>{n&&clearTimeout(n)})})})})}Hu(Nd,"isAPIRequest",()=>Ld),Hu(Nd,"makeRequest",()=>jd);var Id={};Hu(Id,"Transport",()=>Rd),Hu(Id,"TransportWrapper",()=>Fd);class Rd{constructor(){this._state="disconnected"}connect(e){this._abortController=new AbortController;let t=e;try{t=this._validateConnectionParams(e)}catch(lr){throw new td(`Invalid connection params: ${lr.message}. Please check your connection params and try again.`)}return this._connect(t)}get startBotParams(){return this._startBotParams}set startBotParams(e){this._startBotParams=e}disconnect(){return this._abortController&&this._abortController.abort(),this._disconnect()}}class Fd{constructor(e){this._transport=e,this._proxy=new Proxy(this._transport,{get:(e,t,n)=>{if("function"==typeof e[t]){let n;switch(String(t)){case"initialize":n="Direct calls to initialize() are disabled and used internally by the PipecatClient.";break;case"initDevices":n="Direct calls to initDevices() are disabled. Please use the PipecatClient.initDevices() wrapper or let PipecatClient.connect() call it for you.";break;case"sendReadyMessage":n="Direct calls to sendReadyMessage() are disabled and used internally by the PipecatClient.";break;case"connect":n="Direct calls to connect() are disabled. Please use the PipecatClient.connect() wrapper.";break;case"disconnect":n="Direct calls to disconnect() are disabled. Please use the PipecatClient.disconnect() wrapper."}return n?()=>{throw new Error(n)}:(...n)=>e[t](...n)}return Reflect.get(e,t,n)}})}get proxy(){return this._proxy}}var Dd={};function Bd(){var e,t,n,r,i,a;let o={library:Gu.name,library_version:Gu.version,platform_details:{}},s=null;if(null==(e=null==window?void 0:window.navigator)?void 0:e.userAgent)try{s=$u.parse(window.navigator.userAgent)}catch(l){}return(null==(t=null==s?void 0:s.browser)?void 0:t.name)&&(o.platform_details.browser=s.browser.name),"Safari"!==(null==(n=null==s?void 0:s.browser)?void 0:n.name)||s.browser.version?(null==(r=null==s?void 0:s.browser)?void 0:r.version)&&(o.platform_details.browser_version=s.browser.version):o.platform_details.browser_version="Web View",(null==(i=null==s?void 0:s.platform)?void 0:i.type)&&(o.platform_details.platform_type=s.platform.type),(null==(a=null==s?void 0:s.engine)?void 0:a.name)&&(o.platform_details.engine=s.engine.name),(null==s?void 0:s.os)&&(o.platform=s.os.name,o.platform_version=s.os.version),o}Hu(Dd,"learnAboutClient",()=>Bd);var zd=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o};class Ud extends _u{}class Vd extends Ud{constructor(e){var t,n,r;super(),this._functionCallCallbacks={},this._botTranscriptionWarned=!1,kd(Bd()),this._transport=e.transport,this._transportWrapper=new Fd(this._transport);const i=c(l({},e.callbacks),{onMessageError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onMessageError)||r.call(n,t),this.emit(ud.MessageError,t)},onError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onError)||r.call(n,t);try{this.emit(ud.Error,t)}catch(lr){Ad.debug("Could not emit error",t)}const i=t.data;(null==i?void 0:i.fatal)&&(Ad.error("Fatal error reported. Disconnecting..."),this.disconnect())},onConnected:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onConnected)||n.call(t),this.emit(ud.Connected)},onDisconnected:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onDisconnected)||n.call(t),this.emit(ud.Disconnected)},onTransportStateChanged:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onTransportStateChanged)||r.call(n,t),this.emit(ud.TransportStateChanged,t)},onParticipantJoined:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onParticipantJoined)||r.call(n,t),this.emit(ud.ParticipantConnected,t)},onParticipantLeft:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onParticipantLeft)||r.call(n,t),this.emit(ud.ParticipantLeft,t)},onTrackStarted:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onTrackStarted)||i.call(r,t,n),this.emit(ud.TrackStarted,t,n)},onTrackStopped:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onTrackStopped)||i.call(r,t,n),this.emit(ud.TrackStopped,t,n)},onScreenTrackStarted:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onScreenTrackStarted)||i.call(r,t,n),this.emit(ud.ScreenTrackStarted,t,n)},onScreenTrackStopped:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onScreenTrackStopped)||i.call(r,t,n),this.emit(ud.ScreenTrackStopped,t,n)},onScreenShareError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onScreenShareError)||r.call(n,t),this.emit(ud.ScreenShareError,t)},onAvailableCamsUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableCamsUpdated)||r.call(n,t),this.emit(ud.AvailableCamsUpdated,t)},onAvailableMicsUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableMicsUpdated)||r.call(n,t),this.emit(ud.AvailableMicsUpdated,t)},onAvailableSpeakersUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableSpeakersUpdated)||r.call(n,t),this.emit(ud.AvailableSpeakersUpdated,t)},onCamUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onCamUpdated)||r.call(n,t),this.emit(ud.CamUpdated,t)},onMicUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onMicUpdated)||r.call(n,t),this.emit(ud.MicUpdated,t)},onSpeakerUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onSpeakerUpdated)||r.call(n,t),this.emit(ud.SpeakerUpdated,t)},onDeviceError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onDeviceError)||r.call(n,t),this.emit(ud.DeviceError,t)},onBotStarted:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotStarted)||r.call(n,t),this.emit(ud.BotStarted,t)},onBotConnected:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotConnected)||r.call(n,t),this.emit(ud.BotConnected,t)},onBotReady:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotReady)||r.call(n,t),this.emit(ud.BotReady,t)},onBotDisconnected:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotDisconnected)||r.call(n,t),this.emit(ud.BotDisconnected,t)},onBotStartedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotStartedSpeaking)||n.call(t),this.emit(ud.BotStartedSpeaking)},onBotStoppedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotStoppedSpeaking)||n.call(t),this.emit(ud.BotStoppedSpeaking)},onRemoteAudioLevel:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onRemoteAudioLevel)||i.call(r,t,n),this.emit(ud.RemoteAudioLevel,t,n)},onUserStartedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onUserStartedSpeaking)||n.call(t),this.emit(ud.UserStartedSpeaking)},onUserStoppedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onUserStoppedSpeaking)||n.call(t),this.emit(ud.UserStoppedSpeaking)},onLocalAudioLevel:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onLocalAudioLevel)||r.call(n,t),this.emit(ud.LocalAudioLevel,t)},onUserTranscript:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onUserTranscript)||r.call(n,t),this.emit(ud.UserTranscript,t)},onBotOutput:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotOutput)||r.call(n,t),this.emit(ud.BotOutput,t)},onBotTranscript:t=>{var n,r;this._botTranscriptionWarned||(Ad.warn("[Pipecat Client] Bot transcription is deprecated. Please use the onBotOutput instead."),this._botTranscriptionWarned=!0),null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotTranscript)||r.call(n,t),this.emit(ud.BotTranscript,t)},onBotLlmText:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotLlmText)||r.call(n,t),this.emit(ud.BotLlmText,t)},onBotLlmStarted:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotLlmStarted)||n.call(t),this.emit(ud.BotLlmStarted)},onBotLlmStopped:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotLlmStopped)||n.call(t),this.emit(ud.BotLlmStopped)},onBotTtsText:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotTtsText)||r.call(n,t),this.emit(ud.BotTtsText,t)},onBotTtsStarted:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotTtsStarted)||n.call(t),this.emit(ud.BotTtsStarted)},onBotTtsStopped:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotTtsStopped)||n.call(t),this.emit(ud.BotTtsStopped)}});this._options=c(l({},e),{callbacks:i,enableMic:null==(t=e.enableMic)||t,enableCam:null!=(n=e.enableCam)&&n,enableScreenShare:null!=(r=e.enableScreenShare)&&r}),this._initialize(),Ad.debug("[Pipecat Client] Initialized",this.version)}setLogLevel(e){Ad.setLevel(e)}initDevices(){return d(this,null,function*(){Ad.debug("[Pipecat Client] Initializing devices..."),yield this._transport.initDevices()})}startBot(e){return d(this,null,function*(){var t,n,r,i,a,o;let s;this._transport.state="authenticating",this._transport.startBotParams=e,this._abortController=new AbortController;try{s=yield jd(e,this._abortController)}catch(lr){let a,o="An unknown error occurred while starting the bot.";if(lr instanceof Response){const r=yield lr.json();o=null!=(n=null!=(t=r.info)?t:r.detail)?n:lr.statusText,a=lr.status}else lr instanceof Error&&(o=lr.message);throw null==(i=null==(r=this._options.callbacks)?void 0:r.onError)||i.call(r,new Sd(gd.ERROR_RESPONSE,{message:o,fatal:!0})),new rd(o,a)}return this._transport.state="authenticated",null==(o=null==(a=this._options.callbacks)?void 0:a.onBotStarted)||o.call(a,s),s})}connect(e){return d(this,null,function*(){return e&&Ld(e)?(Ad.warn("Calling connect with an API endpoint is deprecated. Use startBotAndConnect() instead."),this.startBotAndConnect(e)):new Promise((t,n)=>{(()=>{d(this,null,function*(){this._connectResolve=t,"disconnected"===this._transport.state&&(yield this._transport.initDevices());try{yield this._transport.connect(e),yield this._transport.sendReadyMessage()}catch(lr){return this.disconnect(),void n(lr)}})})()})})}startBotAndConnect(e){return d(this,null,function*(){"disconnected"===this._transport.state&&(yield this._transport.initDevices());const t=yield this.startBot(e);return this.connect(t)})}disconnect(){return d(this,null,function*(){yield this._transport.disconnect(),this._messageDispatcher.disconnect()})}_initialize(){this._transport.initialize(this._options,this.handleMessage.bind(this)),this._messageDispatcher=new Od(this._transport.sendMessage.bind(this._transport))}get connected(){return["connected","ready"].includes(this._transport.state)}get transport(){return this._transportWrapper.proxy}get state(){return this._transport.state}get version(){return qu(Gu).version}getAllMics(){return d(this,null,function*(){return yield this._transport.getAllMics()})}getAllCams(){return d(this,null,function*(){return yield this._transport.getAllCams()})}getAllSpeakers(){return d(this,null,function*(){return yield this._transport.getAllSpeakers()})}get selectedMic(){return this._transport.selectedMic}get selectedCam(){return this._transport.selectedCam}get selectedSpeaker(){return this._transport.selectedSpeaker}updateMic(e){this._transport.updateMic(e)}updateCam(e){this._transport.updateCam(e)}updateSpeaker(e){this._transport.updateSpeaker(e)}enableMic(e){this._transport.enableMic(e)}get isMicEnabled(){return this._transport.isMicEnabled}enableCam(e){this._transport.enableCam(e)}get isCamEnabled(){return this._transport.isCamEnabled}tracks(){return this._transport.tracks()}enableScreenShare(e){return this._transport.enableScreenShare(e)}get isSharingScreen(){return this._transport.isSharingScreen}sendClientMessage(e,t){this._transport.sendMessage(new Sd(gd.CLIENT_MESSAGE,{t:e,d:t}))}sendClientRequest(e,t,n){return d(this,null,function*(){const r={t:e,d:t};return(yield this._messageDispatcher.dispatch(r,gd.CLIENT_MESSAGE,n)).data.d})}registerFunctionCallHandler(e,t){this._functionCallCallbacks[e]=t}unregisterFunctionCallHandler(e){delete this._functionCallCallbacks[e]}unregisterAllFunctionCallHandlers(){this._functionCallCallbacks={}}appendToContext(e){return d(this,null,function*(){return Ad.warn("appendToContext() is deprecated. Use sendText() instead."),yield this._transport.sendMessage(new Sd(gd.APPEND_TO_CONTEXT,{role:e.role,content:e.content,run_immediately:e.run_immediately})),!0})}sendText(e){return d(this,arguments,function*(e,t={}){yield this._transport.sendMessage(new Sd(gd.SEND_TEXT,{content:e,options:t}))})}disconnectBot(){this._transport.sendMessage(new Sd(gd.DISCONNECT_BOT,{}))}handleMessage(e){var t,n,r,i,a,o,s,l,c,u,d,f,p,h,m,g,v,y,b,w,k,S,_,x,E,C,T,M,P,A,O,N,L,j,I,R,F,D,B,z,U;switch(Ad.debug("[RTVI Message]",e),e.type){case gd.BOT_READY:{const i=e.data,a=i.version?i.version.split(".").map(Number):[0,0,0];Ad.debug(`[Pipecat Client] Bot is ready. Version: ${i.version}`),a[0]<1&&Ad.warn("[Pipecat Client] Bot version is less than 1.0.0, which may not be compatible with this client."),null==(t=this._connectResolve)||t.call(this,e.data),null==(r=null==(n=this._options.callbacks)?void 0:n.onBotReady)||r.call(n,e.data);break}case gd.ERROR:null==(a=null==(i=this._options.callbacks)?void 0:i.onError)||a.call(i,e);break;case gd.SERVER_RESPONSE:this._messageDispatcher.resolve(e);break;case gd.ERROR_RESPONSE:{const t=this._messageDispatcher.reject(e);null==(s=null==(o=this._options.callbacks)?void 0:o.onMessageError)||s.call(o,t);break}case gd.USER_STARTED_SPEAKING:null==(c=null==(l=this._options.callbacks)?void 0:l.onUserStartedSpeaking)||c.call(l);break;case gd.USER_STOPPED_SPEAKING:null==(d=null==(u=this._options.callbacks)?void 0:u.onUserStoppedSpeaking)||d.call(u);break;case gd.BOT_STARTED_SPEAKING:null==(p=null==(f=this._options.callbacks)?void 0:f.onBotStartedSpeaking)||p.call(f);break;case gd.BOT_STOPPED_SPEAKING:null==(m=null==(h=this._options.callbacks)?void 0:h.onBotStoppedSpeaking)||m.call(h);break;case gd.USER_TRANSCRIPTION:{const t=e.data;null==(v=null==(g=this._options.callbacks)?void 0:g.onUserTranscript)||v.call(g,t);break}case gd.BOT_OUTPUT:null==(b=null==(y=this._options.callbacks)?void 0:y.onBotOutput)||b.call(y,e.data);break;case gd.BOT_TRANSCRIPTION:null==(k=null==(w=this._options.callbacks)?void 0:w.onBotTranscript)||k.call(w,e.data);break;case gd.BOT_LLM_TEXT:null==(_=null==(S=this._options.callbacks)?void 0:S.onBotLlmText)||_.call(S,e.data);break;case gd.BOT_LLM_STARTED:null==(E=null==(x=this._options.callbacks)?void 0:x.onBotLlmStarted)||E.call(x);break;case gd.BOT_LLM_STOPPED:null==(T=null==(C=this._options.callbacks)?void 0:C.onBotLlmStopped)||T.call(C);break;case gd.BOT_TTS_TEXT:null==(P=null==(M=this._options.callbacks)?void 0:M.onBotTtsText)||P.call(M,e.data);break;case gd.BOT_TTS_STARTED:null==(O=null==(A=this._options.callbacks)?void 0:A.onBotTtsStarted)||O.call(A);break;case gd.BOT_TTS_STOPPED:null==(L=null==(N=this._options.callbacks)?void 0:N.onBotTtsStopped)||L.call(N);break;case gd.METRICS:null==(I=null==(j=this._options.callbacks)?void 0:j.onMetrics)||I.call(j,e.data),this.emit(ud.Metrics,e.data);break;case gd.SERVER_MESSAGE:null==(F=null==(R=this._options.callbacks)?void 0:R.onServerMessage)||F.call(R,e.data),this.emit(ud.ServerMessage,e.data);break;case gd.LLM_FUNCTION_CALL:{const t=e.data,n=this._functionCallCallbacks[t.function_name];if(n){n({functionName:t.function_name,arguments:t.args}).then(e=>{null!=e&&this._transport.sendMessage(new Sd(gd.LLM_FUNCTION_CALL_RESULT,{function_name:t.function_name,tool_call_id:t.tool_call_id,arguments:t.args,result:e}))})}null==(B=null==(D=this._options.callbacks)?void 0:D.onLLMFunctionCall)||B.call(D,t),this.emit(ud.LLMFunctionCall,t);break}case gd.BOT_LLM_SEARCH_RESPONSE:{const t=e.data;null==(U=null==(z=this._options.callbacks)?void 0:z.onBotLlmSearchResponse)||U.call(z,t),this.emit(ud.BotLlmSearchResponse,t);break}default:Ad.debug("[Pipecat Client] Unrecognized message type",e.type)}}}function $d(e){return e&&e.__esModule?e.default:e}function Wd(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}zd([xd],Vd.prototype,"startBot",null),zd([xd],Vd.prototype,"connect",null),zd([xd],Vd.prototype,"startBotAndConnect",null),zd([_d],Vd.prototype,"sendClientMessage",null),zd([_d],Vd.prototype,"sendClientRequest",null),zd([_d],Vd.prototype,"appendToContext",null),zd([_d],Vd.prototype,"sendText",null),zd([_d],Vd.prototype,"disconnectBot",null),Wu(Ju,Qu),Wu(Ju,Ed),Wu(Ju,Md),Wu(Ju,Nd),Wu(Ju,Id),Wu(Ju,Dd);var qd={};Wd(qd,"DailyRTVIMessageType",()=>lf),Wd(qd,"DailyTransport",()=>df);class Hd{static floatTo16BitPCM(e){const t=new ArrayBuffer(2*e.length),n=new DataView(t);let r=0;for(let i=0;i<e.length;i++,r+=2){let t=Math.max(-1,Math.min(1,e[i]));n.setInt16(r,t<0?32768*t:32767*t,!0)}return t}static mergeBuffers(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}_packData(e,t){return[new Uint8Array([t,t>>8]),new Uint8Array([t,t>>8,t>>16,t>>24])][e]}pack(e,t){if(!(null==t?void 0:t.bitsPerSample))throw new Error('Missing "bitsPerSample"');if(!(null==t?void 0:t.channels))throw new Error('Missing "channels"');if(!(null==t?void 0:t.data))throw new Error('Missing "data"');const{bitsPerSample:n,channels:r,data:i}=t,a=["RIFF",this._packData(1,52),"WAVE","fmt ",this._packData(1,16),this._packData(0,1),this._packData(0,r.length),this._packData(1,e),this._packData(1,e*r.length*n/8),this._packData(0,r.length*n/8),this._packData(0,n),"data",this._packData(1,r[0].length*r.length*n/8),i],o=new Blob(a,{type:"audio/mpeg"});return{blob:o,url:URL.createObjectURL(o),channelCount:r.length,sampleRate:e,duration:i.byteLength/(r.length*e*2)}}}globalThis.WavPacker=Hd;const Jd=[4186.01,4434.92,4698.63,4978.03,5274.04,5587.65,5919.91,6271.93,6644.88,7040,7458.62,7902.13],Qd=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Gd=[],Yd=[];for(let _f=1;_f<=8;_f++)for(let e=0;e<Jd.length;e++){const t=Jd[e];Gd.push(t/Math.pow(2,8-_f)),Yd.push(Qd[e]+_f)}const Kd=[32,2e3],Xd=Gd.filter((e,t)=>Gd[t]>Kd[0]&&Gd[t]<Kd[1]),Zd=Yd.filter((e,t)=>Gd[t]>Kd[0]&&Gd[t]<Kd[1]);class ef{static getFrequencies(e,t,n,r="frequency",i=-100,a=-30){n||(n=new Float32Array(e.frequencyBinCount),e.getFloatFrequencyData(n));const o=t/2,s=1/n.length*o;let l,c,u;if("music"===r||"voice"===r){const e="voice"===r?Xd:Gd,t=Array(e.length).fill(i);for(let r=0;r<n.length;r++){const i=r*s,a=n[r];for(let n=e.length-1;n>=0;n--)if(i>e[n]){t[n]=Math.max(t[n],a);break}}l=t,c="voice"===r?Xd:Gd,u="voice"===r?Zd:Yd}else l=Array.from(n),c=l.map((e,t)=>s*t),u=c.map(e=>`${e.toFixed(2)} Hz`);const d=l.map(e=>Math.max(0,Math.min((e-i)/(a-i),1)));return{values:new Float32Array(d),frequencies:c,labels:u}}constructor(e,t=null){if(this.fftResults=[],t){const{length:n,sampleRate:r}=t,i=new OfflineAudioContext({length:n,sampleRate:r}),a=i.createBufferSource();a.buffer=t;const o=i.createAnalyser();o.fftSize=8192,o.smoothingTimeConstant=.1,a.connect(o);const s=1/60,l=n/r,c=e=>{const t=s*e;t<l&&i.suspend(t).then(()=>{const t=new Float32Array(o.frequencyBinCount);o.getFloatFrequencyData(t),this.fftResults.push(t),c(e+1)}),1===e?i.startRendering():i.resume()};a.start(0),c(1),this.audio=e,this.context=i,this.analyser=o,this.sampleRate=r,this.audioBuffer=t}else{const t=new AudioContext,n=t.createMediaElementSource(e),r=t.createAnalyser();r.fftSize=8192,r.smoothingTimeConstant=.1,n.connect(r),r.connect(t.destination),this.audio=e,this.context=t,this.analyser=r,this.sampleRate=this.context.sampleRate,this.audioBuffer=null}}getFrequencies(e="frequency",t=-100,n=-30){let r=null;if(this.audioBuffer&&this.fftResults.length){const e=this.audio.currentTime/this.audio.duration,t=Math.min(e*this.fftResults.length|0,this.fftResults.length-1);r=this.fftResults[t]}return ef.getFrequencies(this.analyser,this.sampleRate,r,e,t,n)}resumeIfSuspended(){return d(this,null,function*(){return"suspended"===this.context.state&&(yield this.context.resume()),!0})}}globalThis.AudioAnalysis=ef;const tf=new Blob(["\nclass StreamProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.hasStarted = false;\n this.hasInterrupted = false;\n this.outputBuffers = [];\n this.bufferLength = 128;\n this.write = { buffer: new Float32Array(this.bufferLength), trackId: null };\n this.writeOffset = 0;\n this.trackSampleOffsets = {};\n this.port.onmessage = (event) => {\n if (event.data) {\n const payload = event.data;\n if (payload.event === 'write') {\n const int16Array = payload.buffer;\n const float32Array = new Float32Array(int16Array.length);\n for (let i = 0; i < int16Array.length; i++) {\n float32Array[i] = int16Array[i] / 0x8000; // Convert Int16 to Float32\n }\n this.writeData(float32Array, payload.trackId);\n } else if (\n payload.event === 'offset' ||\n payload.event === 'interrupt'\n ) {\n const requestId = payload.requestId;\n const trackId = this.write.trackId;\n const offset = this.trackSampleOffsets[trackId] || 0;\n this.port.postMessage({\n event: 'offset',\n requestId,\n trackId,\n offset,\n });\n if (payload.event === 'interrupt') {\n this.hasInterrupted = true;\n }\n } else {\n throw new Error(`Unhandled event \"${payload.event}\"`);\n }\n }\n };\n }\n\n writeData(float32Array, trackId = null) {\n let { buffer } = this.write;\n let offset = this.writeOffset;\n for (let i = 0; i < float32Array.length; i++) {\n buffer[offset++] = float32Array[i];\n if (offset >= buffer.length) {\n this.outputBuffers.push(this.write);\n this.write = { buffer: new Float32Array(this.bufferLength), trackId };\n buffer = this.write.buffer;\n offset = 0;\n }\n }\n this.writeOffset = offset;\n return true;\n }\n\n process(inputs, outputs, parameters) {\n const output = outputs[0];\n const outputChannelData = output[0];\n const outputBuffers = this.outputBuffers;\n if (this.hasInterrupted) {\n this.port.postMessage({ event: 'stop' });\n return false;\n } else if (outputBuffers.length) {\n this.hasStarted = true;\n const { buffer, trackId } = outputBuffers.shift();\n for (let i = 0; i < outputChannelData.length; i++) {\n outputChannelData[i] = buffer[i] || 0;\n }\n if (trackId) {\n this.trackSampleOffsets[trackId] =\n this.trackSampleOffsets[trackId] || 0;\n this.trackSampleOffsets[trackId] += buffer.length;\n }\n return true;\n } else if (this.hasStarted) {\n this.port.postMessage({ event: 'stop' });\n return false;\n } else {\n return true;\n }\n }\n}\n\nregisterProcessor('stream_processor', StreamProcessor);\n"],{type:"application/javascript"}),nf=URL.createObjectURL(tf);globalThis.WavStreamPlayer=class{constructor({sampleRate:e=44100}={}){this.scriptSrc=nf,this.sampleRate=e,this.context=null,this.stream=null,this.analyser=null,this.trackSampleOffsets={},this.interruptedTrackIds={}}connect(){return d(this,null,function*(){this.context=new AudioContext({sampleRate:this.sampleRate}),this._speakerID&&this.context.setSinkId(this._speakerID),"suspended"===this.context.state&&(yield this.context.resume());try{yield this.context.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const e=this.context.createAnalyser();return e.fftSize=8192,e.smoothingTimeConstant=.1,this.analyser=e,!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.analyser)throw new Error("Not connected, please call .connect() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}updateSpeaker(e){return d(this,null,function*(){const t=this._speakerID;if(this._speakerID=e,this.context)try{"default"===e?yield this.context.setSinkId():yield this.context.setSinkId(e)}catch(lr){console.error(`Could not set sinkId to ${e}: ${lr}`),this._speakerID=t}})}_start(){const e=new AudioWorkletNode(this.context,"stream_processor");return e.connect(this.context.destination),e.port.onmessage=t=>{const{event:n}=t.data;if("stop"===n)e.disconnect(),this.stream=null;else if("offset"===n){const{requestId:e,trackId:n,offset:r}=t.data,i=r/this.sampleRate;this.trackSampleOffsets[e]={trackId:n,offset:r,currentTime:i}}},this.analyser.disconnect(),e.connect(this.analyser),this.stream=e,!0}add16BitPCM(e,t="default"){if("string"!=typeof t)throw new Error("trackId must be a string");if(this.interruptedTrackIds[t])return;let n;if(this.stream||this._start(),e instanceof Int16Array)n=e;else{if(!(e instanceof ArrayBuffer))throw new Error("argument must be Int16Array or ArrayBuffer");n=new Int16Array(e)}return this.stream.port.postMessage({event:"write",buffer:n,trackId:t}),n}getTrackSampleOffset(e=!1){return d(this,null,function*(){if(!this.stream)return null;const t=crypto.randomUUID();let n;for(this.stream.port.postMessage({event:e?"interrupt":"offset",requestId:t});!n;)n=this.trackSampleOffsets[t],yield new Promise(e=>setTimeout(()=>e(),1));const{trackId:r}=n;return e&&r&&(this.interruptedTrackIds[r]=!0),n})}interrupt(){return d(this,null,function*(){return this.getTrackSampleOffset(!0)})}};const rf=new Blob(["\nclass AudioProcessor extends AudioWorkletProcessor {\n\n constructor() {\n super();\n this.port.onmessage = this.receive.bind(this);\n this.initialize();\n }\n\n initialize() {\n this.foundAudio = false;\n this.recording = false;\n this.chunks = [];\n }\n\n /**\n * Concatenates sampled chunks into channels\n * Format is chunk[Left[], Right[]]\n */\n readChannelData(chunks, channel = -1, maxChannels = 9) {\n let channelLimit;\n if (channel !== -1) {\n if (chunks[0] && chunks[0].length - 1 < channel) {\n throw new Error(\n `Channel ${channel} out of range: max ${chunks[0].length}`\n );\n }\n channelLimit = channel + 1;\n } else {\n channel = 0;\n channelLimit = Math.min(chunks[0] ? chunks[0].length : 1, maxChannels);\n }\n const channels = [];\n for (let n = channel; n < channelLimit; n++) {\n const length = chunks.reduce((sum, chunk) => {\n return sum + chunk[n].length;\n }, 0);\n const buffers = chunks.map((chunk) => chunk[n]);\n const result = new Float32Array(length);\n let offset = 0;\n for (let i = 0; i < buffers.length; i++) {\n result.set(buffers[i], offset);\n offset += buffers[i].length;\n }\n channels[n] = result;\n }\n return channels;\n }\n\n /**\n * Combines parallel audio data into correct format,\n * channels[Left[], Right[]] to float32Array[LRLRLRLR...]\n */\n formatAudioData(channels) {\n if (channels.length === 1) {\n // Simple case is only one channel\n const float32Array = channels[0].slice();\n const meanValues = channels[0].slice();\n return { float32Array, meanValues };\n } else {\n const float32Array = new Float32Array(\n channels[0].length * channels.length\n );\n const meanValues = new Float32Array(channels[0].length);\n for (let i = 0; i < channels[0].length; i++) {\n const offset = i * channels.length;\n let meanValue = 0;\n for (let n = 0; n < channels.length; n++) {\n float32Array[offset + n] = channels[n][i];\n meanValue += channels[n][i];\n }\n meanValues[i] = meanValue / channels.length;\n }\n return { float32Array, meanValues };\n }\n }\n\n /**\n * Converts 32-bit float data to 16-bit integers\n */\n floatTo16BitPCM(float32Array) {\n const buffer = new ArrayBuffer(float32Array.length * 2);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < float32Array.length; i++, offset += 2) {\n let s = Math.max(-1, Math.min(1, float32Array[i]));\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n\n /**\n * Retrieves the most recent amplitude values from the audio stream\n * @param {number} channel\n */\n getValues(channel = -1) {\n const channels = this.readChannelData(this.chunks, channel);\n const { meanValues } = this.formatAudioData(channels);\n return { meanValues, channels };\n }\n\n /**\n * Exports chunks as an audio/wav file\n */\n export() {\n const channels = this.readChannelData(this.chunks);\n const { float32Array, meanValues } = this.formatAudioData(channels);\n const audioData = this.floatTo16BitPCM(float32Array);\n return {\n meanValues: meanValues,\n audio: {\n bitsPerSample: 16,\n channels: channels,\n data: audioData,\n },\n };\n }\n\n receive(e) {\n const { event, id } = e.data;\n let receiptData = {};\n switch (event) {\n case 'start':\n this.recording = true;\n break;\n case 'stop':\n this.recording = false;\n break;\n case 'clear':\n this.initialize();\n break;\n case 'export':\n receiptData = this.export();\n break;\n case 'read':\n receiptData = this.getValues();\n break;\n default:\n break;\n }\n // Always send back receipt\n this.port.postMessage({ event: 'receipt', id, data: receiptData });\n }\n\n sendChunk(chunk) {\n const channels = this.readChannelData([chunk]);\n const { float32Array, meanValues } = this.formatAudioData(channels);\n const rawAudioData = this.floatTo16BitPCM(float32Array);\n const monoAudioData = this.floatTo16BitPCM(meanValues);\n this.port.postMessage({\n event: 'chunk',\n data: {\n mono: monoAudioData,\n raw: rawAudioData,\n },\n });\n }\n\n process(inputList, outputList, parameters) {\n // Copy input to output (e.g. speakers)\n // Note that this creates choppy sounds with Mac products\n const sourceLimit = Math.min(inputList.length, outputList.length);\n for (let inputNum = 0; inputNum < sourceLimit; inputNum++) {\n const input = inputList[inputNum];\n const output = outputList[inputNum];\n const channelCount = Math.min(input.length, output.length);\n for (let channelNum = 0; channelNum < channelCount; channelNum++) {\n input[channelNum].forEach((sample, i) => {\n output[channelNum][i] = sample;\n });\n }\n }\n const inputs = inputList[0];\n // There's latency at the beginning of a stream before recording starts\n // Make sure we actually receive audio data before we start storing chunks\n let sliceIndex = 0;\n if (!this.foundAudio) {\n for (const channel of inputs) {\n sliceIndex = 0; // reset for each channel\n if (this.foundAudio) {\n break;\n }\n if (channel) {\n for (const value of channel) {\n if (value !== 0) {\n // find only one non-zero entry in any channel\n this.foundAudio = true;\n break;\n } else {\n sliceIndex++;\n }\n }\n }\n }\n }\n if (inputs && inputs[0] && this.foundAudio && this.recording) {\n // We need to copy the TypedArray, because the `process`\n // internals will reuse the same buffer to hold each input\n const chunk = inputs.map((input) => input.slice(sliceIndex));\n this.chunks.push(chunk);\n this.sendChunk(chunk);\n }\n return true;\n }\n}\n\nregisterProcessor('audio_processor', AudioProcessor);\n"],{type:"application/javascript"}),af=URL.createObjectURL(rf);globalThis.WavRecorder=class{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:n=!1}={}){this.scriptSrc=af,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!n,this._deviceChangeCallback=null,this._deviceErrorCallback=null,this._devices=[],this.deviceSelection=null,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}static decode(e,t=44100,n=-1){return d(this,null,function*(){const r=new AudioContext({sampleRate:t});let i,a;if(e instanceof Blob){if(-1!==n)throw new Error('Can not specify "fromSampleRate" when reading from Blob');a=e,i=yield a.arrayBuffer()}else if(e instanceof ArrayBuffer){if(-1!==n)throw new Error('Can not specify "fromSampleRate" when reading from ArrayBuffer');i=e,a=new Blob([i],{type:"audio/wav"})}else{let t,r;if(e instanceof Int16Array){r=e,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768}else if(e instanceof Float32Array)t=e;else{if(!(e instanceof Array))throw new Error('"audioData" must be one of: Blob, Float32Arrray, Int16Array, ArrayBuffer, Array<number>');t=new Float32Array(e)}if(-1===n)throw new Error('Must specify "fromSampleRate" when reading from Float32Array, In16Array or Array');if(n<3e3)throw new Error('Minimum "fromSampleRate" is 3000 (3kHz)');r||(r=Hd.floatTo16BitPCM(t));const o={bitsPerSample:16,channels:[t],data:r};a=(new Hd).pack(n,o).blob,i=yield a.arrayBuffer()}const o=yield r.decodeAudioData(i),s=o.getChannelData(0);return{blob:a,url:URL.createObjectURL(a),values:s,audioBuffer:o}})}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}_event(e){return d(this,arguments,function*(e,t={},n=null){if(!(n=n||this.processor))throw new Error("Can not send events without recording first");const r={event:e,id:this._lastEventId++,data:t};n.port.postMessage(r);const i=(new Date).valueOf();for(;!this.eventReceipts[r.id];){if((new Date).valueOf()-i>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);yield new Promise(e=>setTimeout(()=>e(!0),1))}const a=this.eventReceipts[r.id];return delete this.eventReceipts[r.id],a})}listenForDeviceChange(e){if(null===e&&this._deviceChangeCallback)navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeCallback),this._deviceChangeCallback=null;else if(null!==e){let t=0,n=[];const r=e=>e.map(e=>e.deviceId).sort().join(","),i=()=>d(this,null,function*(){let i=++t;const a=yield this.listDevices();i===t&&r(n)!==r(a)&&(n=a,e(a.slice()))});navigator.mediaDevices.addEventListener("devicechange",i),i(),this._deviceChangeCallback=i}return!0}listenForDeviceErrors(e){this._deviceErrorCallback=e}requestPermission(){return d(this,null,function*(){const e=yield navigator.permissions.query({name:"microphone"});if("denied"===e.state)this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:new Error("Microphone access denied")});else if("prompt"===e.state)try{const e=yield navigator.mediaDevices.getUserMedia({audio:!0});e.getTracks().forEach(e=>e.stop())}catch(lr){console.error("Error accessing microphone."),this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:lr})}return!0})}listDevices(){return d(this,null,function*(){if(!navigator.mediaDevices||!("enumerateDevices"in navigator.mediaDevices))throw new Error("Could not request user devices");yield this.requestPermission();return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind)})}begin(e){return d(this,null,function*(){var t;if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!navigator.mediaDevices||!("getUserMedia"in navigator.mediaDevices))throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic","cam"],type:"undefined-mediadevices"}),new Error("Could not request user media");e=null!=e?e:null==(t=this.deviceSelection)?void 0:t.deviceId;try{const t={audio:!0};e&&(t.audio={deviceId:{exact:e}}),this.stream=yield navigator.mediaDevices.getUserMedia(t)}catch(s){throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:s}),new Error("Could not start media stream")}this.listDevices().then(t=>{e=this.stream.getAudioTracks()[0].getSettings().deviceId,console.log("find current device",t,e,this.stream.getAudioTracks()[0].getSettings()),this.deviceSelection=t.find(t=>t.deviceId===e),console.log("current device",this.deviceSelection)});const n=new AudioContext({sampleRate:this.sampleRate}),r=n.createMediaStreamSource(this.stream);try{yield n.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const i=new AudioWorkletNode(n,"audio_processor");i.port.onmessage=e=>{const{event:t,id:n,data:r}=e.data;if("receipt"===t)this.eventReceipts[n]=r;else if("chunk"===t)if(this._chunkProcessorSize){const e=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:Hd.mergeBuffers(e.raw,r.raw),mono:Hd.mergeBuffers(e.mono,r.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(r)};const a=r.connect(i),o=n.createAnalyser();return o.fftSize=8192,o.smoothingTimeConstant=.1,a.connect(o),this.outputToSpeakers&&(console.warn("Warning: Output to speakers may affect sound quality,\nespecially due to system audio feedback preventative measures.\nuse only for debugging"),o.connect(n.destination)),this.source=r,this.node=a,this.analyser=o,this.processor=i,console.log("begin completed"),!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}pause(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!this.recording)throw new Error("Already paused: please call .record() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),yield this._event("stop"),this.recording=!1,!0})}record(e=()=>{},t=8192){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(this.recording)throw new Error("Already recording: please call .pause() first");if("function"!=typeof e)throw new Error("chunkProcessor must be a function");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),yield this._event("start"),this.recording=!0,!0})}clear(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return yield this._event("clear"),!0})}read(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");this.log("Reading ...");return yield this._event("read")})}save(e=!1){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=yield this._event("export");return(new Hd).pack(this.sampleRate,t.audio)})}end(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),yield this._event("stop"),this.recording=!1;this.stream.getTracks().forEach(e=>e.stop()),this.log("Exporting ...");const t=yield this._event("export",{},e);this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null;return(new Hd).pack(this.sampleRate,t.audio)})}quit(){return d(this,null,function*(){return this.listenForDeviceChange(null),this.deviceSelection=null,this.processor&&(yield this.end()),!0})}};class of{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:n=!1}={}){this.scriptSrc=af,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!n,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}_event(e){return d(this,arguments,function*(e,t={},n=null){if(!(n=n||this.processor))throw new Error("Can not send events without recording first");const r={event:e,id:this._lastEventId++,data:t};n.port.postMessage(r);const i=(new Date).valueOf();for(;!this.eventReceipts[r.id];){if((new Date).valueOf()-i>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);yield new Promise(e=>setTimeout(()=>e(!0),1))}const a=this.eventReceipts[r.id];return delete this.eventReceipts[r.id],a})}begin(e){return d(this,null,function*(){if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!e||"audio"!==e.kind)throw new Error("No audio track provided");this.stream=new MediaStream([e]);const t=new AudioContext({sampleRate:this.sampleRate}),n=t.createMediaStreamSource(this.stream);try{yield t.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const r=new AudioWorkletNode(t,"audio_processor");r.port.onmessage=e=>{const{event:t,id:n,data:r}=e.data;if("receipt"===t)this.eventReceipts[n]=r;else if("chunk"===t)if(this._chunkProcessorSize){const e=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:Hd.mergeBuffers(e.raw,r.raw),mono:Hd.mergeBuffers(e.mono,r.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(r)};const i=n.connect(r),a=t.createAnalyser();return a.fftSize=8192,a.smoothingTimeConstant=.1,i.connect(a),this.outputToSpeakers&&(console.warn("Warning: Output to speakers may affect sound quality,\nespecially due to system audio feedback preventative measures.\nuse only for debugging"),a.connect(t.destination)),this.source=n,this.node=i,this.analyser=a,this.processor=r,!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}pause(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!this.recording)throw new Error("Already paused: please call .record() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),yield this._event("stop"),this.recording=!1,!0})}record(e=()=>{},t=8192){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(this.recording)throw new Error("Already recording: HELLO please call .pause() first");if("function"!=typeof e)throw new Error("chunkProcessor must be a function");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),yield this._event("start"),this.recording=!0,!0})}clear(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return yield this._event("clear"),!0})}read(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");this.log("Reading ...");return yield this._event("read")})}save(e=!1){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=yield this._event("export");return(new Hd).pack(this.sampleRate,t.audio)})}end(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),yield this._event("stop"),this.recording=!1,this.log("Exporting ...");const t=yield this._event("export",{},e);this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null;return(new Hd).pack(this.sampleRate,t.audio)})}quit(){return d(this,null,function*(){return this.listenForDeviceChange(null),this.processor&&(yield this.end()),!0})}}globalThis.WavRecorder=WavRecorder;var sf,lf,cf;sf=JSON.parse('{"name":"@pipecat-ai/daily-transport","version":"1.5.0","license":"BSD-2-Clause","main":"dist/index.js","module":"dist/index.module.js","types":"dist/index.d.ts","source":"src/index.ts","repository":{"type":"git","url":"git+https://github.com/pipecat-ai/pipecat-client-web-transports.git"},"files":["dist","package.json","README.md"],"scripts":{"build":"parcel build --no-cache","dev":"parcel watch","lint":"eslint . --ext ts --report-unused-disable-directives --max-warnings 0"},"devDependencies":{"@pipecat-ai/client-js":"^1.5.0","eslint":"9.39.1","eslint-config-prettier":"^9.1.0","eslint-plugin-simple-import-sort":"^12.1.1"},"peerDependencies":{"@pipecat-ai/client-js":"~1.5.0"},"dependencies":{"@daily-co/daily-js":"^0.84.0"},"description":"Pipecat Daily Transport Package","author":"Daily.co","bugs":{"url":"https://github.com/pipecat-ai/pipecat-client-web-transports/issues"},"homepage":"https://github.com/pipecat-ai/pipecat-client-web-transports/blob/main/transports/daily-webrtc/README.md"}'),(cf=lf||(lf={})).AUDIO_BUFFERING_STARTED="audio-buffering-started",cf.AUDIO_BUFFERING_STOPPED="audio-buffering-stopped";class uf{constructor(e){this._daily=e,this._proxy=new Proxy(this._daily,{get:(e,t,n)=>{if("function"==typeof e[t]){let n;switch(String(t)){case"preAuth":n="Calls to preAuth() are disabled. Please use Transport.preAuth()";break;case"startCamera":n="Calls to startCamera() are disabled. Please use PipecatClient.initDevices()";break;case"join":n="Calls to join() are disabled. Please use PipecatClient.connect()";break;case"leave":n="Calls to leave() are disabled. Please use PipecatClient.disconnect()";break;case"destroy":n="Calls to destroy() are disabled."}return n?()=>{throw new Error(n)}:(...n)=>e[t](...n)}return Reflect.get(e,t,n)}})}get proxy(){return this._proxy}}class df extends Rd{constructor(e={}){var t;super(),this._botId="",this._selectedCam={},this._selectedMic={},this._selectedSpeaker={},this._currentAudioTrack=null,this._audioQueue=[],this._callbacks={};const n=e,{bufferLocalAudioUntilBotReady:r}=n,i=u(n,["bufferLocalAudioUntilBotReady"]);this._dailyFactoryOptions=i,void 0===(null==(t=this._dailyFactoryOptions.dailyConfig)?void 0:t.useDevicePreferenceCookies)&&(null==this._dailyFactoryOptions.dailyConfig&&(this._dailyFactoryOptions.dailyConfig={}),this._dailyFactoryOptions.dailyConfig.useDevicePreferenceCookies=!0),this._bufferLocalAudioUntilBotReady=r||!1,this._daily=qc.createCallObject(c(l({},this._dailyFactoryOptions),{allowMultipleCallInstances:!0})),this._dailyWrapper=new uf(this._daily)}setupRecorder(){this._mediaStreamRecorder=new of({sampleRate:df.RECORDER_SAMPLE_RATE})}handleUserAudioStream(e){this._audioQueue.push(e)}flushAudioQueue(){if(0!==this._audioQueue.length)for(Ad.debug(`Will flush audio queue: ${this._audioQueue.length}`);this._audioQueue.length>0;){const e=[];for(;e.length<10&&this._audioQueue.length>0;){const t=this._audioQueue.shift();t&&e.push(t)}e.length>0&&this._sendAudioBatch(e)}}_sendAudioBatch(e){const t={id:"raw-audio-batch",label:"rtvi-ai",type:"raw-audio-batch",data:{base64AudioBatch:e.map(e=>{const t=new Uint8Array(e);return btoa(String.fromCharCode(...t))}),sampleRate:df.RECORDER_SAMPLE_RATE,numChannels:1}};this.sendMessage(t)}initialize(e,t){var n,r,i;this._bufferLocalAudioUntilBotReady&&this.setupRecorder(),this._callbacks=null!=(n=e.callbacks)?n:{},this._onMessage=t,null!=this._dailyFactoryOptions.startVideoOff&&null==e.enableCam||(this._dailyFactoryOptions.startVideoOff=!(null!=(r=e.enableCam)&&r)),null!=this._dailyFactoryOptions.startAudioOff&&null==e.enableMic||(this._dailyFactoryOptions.startAudioOff=!(null==(i=e.enableMic)||i)),this.attachEventListeners(),this.state="disconnected",Ad.debug("[Daily Transport] Initialized",$d(sf).version)}get dailyCallClient(){return this._dailyWrapper.proxy}get state(){return this._state}set state(e){var t,n;this._state!==e&&(this._state=e,null==(n=(t=this._callbacks).onTransportStateChanged)||n.call(t,e))}getSessionInfo(){return this._daily.meetingSessionSummary()}getAllCams(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"videoinput"===e.kind)})}updateCam(e){this._daily.setInputDevicesAsync({videoDeviceId:e}).then(e=>{this._selectedCam=e.camera})}get selectedCam(){return this._selectedCam}getAllMics(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"audioinput"===e.kind)})}updateMic(e){this._daily.setInputDevicesAsync({audioDeviceId:e}).then(e=>{this._selectedMic=e.mic})}get selectedMic(){return this._selectedMic}getAllSpeakers(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"audiooutput"===e.kind)})}updateSpeaker(e){this._daily.setOutputDeviceAsync({outputDeviceId:e}).then(e=>{this._selectedSpeaker=e.speaker}).catch(e=>{var t,n,r;null==(r=(n=this._callbacks).onDeviceError)||r.call(n,new cd(["speaker"],null!=(t=e.type)?t:"unknown",e.message))})}get selectedSpeaker(){return this._selectedSpeaker}enableMic(e){this._daily.setLocalAudio(e)}get isMicEnabled(){return this._daily.localAudio()}enableCam(e){this._daily.setLocalVideo(e)}get isCamEnabled(){return this._daily.localVideo()}enableScreenShare(e){e?this._daily.startScreenShare():this._daily.stopScreenShare()}get isSharingScreen(){return this._daily.localScreenAudio()||this._daily.localScreenVideo()}tracks(){var e,t,n,r,i,a,o,s,l,c,u,d,f,p,h,m,g;const v=null!=(e=this._daily.participants())?e:{},y=null==v?void 0:v[this._botId],b={local:{audio:null==(r=null==(n=null==(t=null==v?void 0:v.local)?void 0:t.tracks)?void 0:n.audio)?void 0:r.persistentTrack,screenAudio:null==(o=null==(a=null==(i=null==v?void 0:v.local)?void 0:i.tracks)?void 0:a.screenAudio)?void 0:o.persistentTrack,screenVideo:null==(c=null==(l=null==(s=null==v?void 0:v.local)?void 0:s.tracks)?void 0:l.screenVideo)?void 0:c.persistentTrack,video:null==(f=null==(d=null==(u=null==v?void 0:v.local)?void 0:u.tracks)?void 0:d.video)?void 0:f.persistentTrack}};return y&&(b.bot={audio:null==(h=null==(p=null==y?void 0:y.tracks)?void 0:p.audio)?void 0:h.persistentTrack,video:null==(g=null==(m=null==y?void 0:y.tracks)?void 0:m.video)?void 0:g.persistentTrack}),b}startRecording(){return d(this,null,function*(){var e,t;try{Ad.info("[Daily Transport] Initializing recording"),yield this._mediaStreamRecorder.record(e=>{this.handleUserAudioStream(e.mono)},df.RECORDER_CHUNK_SIZE),null==(t=(e=this._callbacks).onAudioBufferingStarted)||t.call(e),Ad.info("[Daily Transport] Recording Initialized")}catch(lr){lr.message.includes("Already recording")||Ad.error("Error starting recording",lr)}})}preAuth(e){return d(this,null,function*(){this._dailyFactoryOptions=e,yield this._daily.preAuth(e)})}initDevices(){return d(this,null,function*(){var e,t,n,r,i,a,o,s,l,c,u,d;if(!this._daily)throw new td("Transport instance not initialized");this.state="initializing";const f=yield this._daily.startCamera(this._dailyFactoryOptions),{devices:p}=yield this._daily.enumerateDevices(),h=p.filter(e=>"videoinput"===e.kind),m=p.filter(e=>"audioinput"===e.kind),g=p.filter(e=>"audiooutput"===e.kind);this._selectedCam=f.camera,this._selectedMic=f.mic,this._selectedSpeaker=f.speaker,null==(t=(e=this._callbacks).onAvailableCamsUpdated)||t.call(e,h),null==(r=(n=this._callbacks).onAvailableMicsUpdated)||r.call(n,m),null==(a=(i=this._callbacks).onAvailableSpeakersUpdated)||a.call(i,g),null==(s=(o=this._callbacks).onCamUpdated)||s.call(o,f.camera),null==(c=(l=this._callbacks).onMicUpdated)||c.call(l,f.mic),null==(d=(u=this._callbacks).onSpeakerUpdated)||d.call(u,f.speaker),this._daily.isLocalAudioLevelObserverRunning()||(yield this._daily.startLocalAudioLevelObserver(100)),this._daily.isRemoteParticipantsAudioLevelObserverRunning()||(yield this._daily.startRemoteParticipantsAudioLevelObserver(100)),this.state="initialized"})}_validateConnectionParams(e){if(null==e)return;if("object"!=typeof e)throw new td("Invalid connection parameters");const t=e;return t.room_url?(t.url=t.room_url,delete t.room_url):t.dailyRoom&&(t.url=t.dailyRoom,delete t.dailyRoom),t.dailyToken&&(t.token=t.dailyToken,delete t.dailyToken),t.token||delete t.token,t}_connect(e){return d(this,null,function*(){var t,n,r;if(!this._daily)throw new td("Transport instance not initialized");e&&(this._dailyFactoryOptions=l(l({},this._dailyFactoryOptions),e)),this.state="connecting";try{yield this._daily.join(this._dailyFactoryOptions)}catch(lr){throw Ad.error("Failed to join room",lr),this.state="error",new id}(null==(t=this._abortController)?void 0:t.signal.aborted)||(this.state="connected",null==(r=(n=this._callbacks).onConnected)||r.call(n))})}sendReadyMessage(){return d(this,null,function*(){return new Promise(e=>{var t,n;const r=()=>{this.state="ready",this.flushAudioQueue(),this.sendMessage(Sd.clientReady()),this.stopRecording(),e()};for(const a in this._daily.participants()){const i=this._daily.participants()[a];if(!i.local&&(null==(n=null==(t=i.tracks)?void 0:t.audio)?void 0:n.persistentTrack))return r(),void e()}const i=e=>{var t;(null==(t=e.participant)?void 0:t.local)||(this._daily.off("track-started",i),(()=>{const e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||/Macintosh/.test(e)&&"ontouchend"in document})()?(Ad.debug("[Daily Transport] iOS device detected, adding 0.5 second delay before sending ready message"),setTimeout(r,500)):r())};this._daily.on("track-started",i)})})}stopRecording(){var e,t;this._mediaStreamRecorder&&"ended"!==this._mediaStreamRecorder.getStatus()&&(this._mediaStreamRecorder.end(),null==(t=(e=this._callbacks).onAudioBufferingStopped)||t.call(e))}attachEventListeners(){this._daily.on("available-devices-updated",this.handleAvailableDevicesUpdated.bind(this)),this._daily.on("selected-devices-updated",this.handleSelectedDevicesUpdated.bind(this)),this._daily.on("camera-error",this.handleDeviceError.bind(this)),this._daily.on("track-started",this.handleTrackStarted.bind(this)),this._daily.on("track-stopped",this.handleTrackStopped.bind(this)),this._daily.on("participant-joined",this.handleParticipantJoined.bind(this)),this._daily.on("participant-left",this.handleParticipantLeft.bind(this)),this._daily.on("local-audio-level",this.handleLocalAudioLevel.bind(this)),this._daily.on("remote-participants-audio-level",this.handleRemoteAudioLevel.bind(this)),this._daily.on("app-message",this.handleAppMessage.bind(this)),this._daily.on("left-meeting",this.handleLeftMeeting.bind(this)),this._daily.on("error",this.handleFatalError.bind(this)),this._daily.on("nonfatal-error",this.handleNonFatalError.bind(this))}_disconnect(){return d(this,null,function*(){this.state="disconnecting",this._daily.stopLocalAudioLevelObserver(),this._daily.stopRemoteParticipantsAudioLevelObserver(),this._audioQueue=[],this._currentAudioTrack=null,this.stopRecording(),yield this._daily.leave()})}sendMessage(e){this._daily.sendAppMessage(e,"*")}handleAppMessage(e){"rtvi-ai"===e.data.label&&this._onMessage({id:e.data.id,type:e.data.type,data:e.data.data})}handleAvailableDevicesUpdated(e){var t,n,r,i,a,o;null==(n=(t=this._callbacks).onAvailableCamsUpdated)||n.call(t,e.availableDevices.filter(e=>"videoinput"===e.kind)),null==(i=(r=this._callbacks).onAvailableMicsUpdated)||i.call(r,e.availableDevices.filter(e=>"audioinput"===e.kind)),null==(o=(a=this._callbacks).onAvailableSpeakersUpdated)||o.call(a,e.availableDevices.filter(e=>"audiooutput"===e.kind))}handleSelectedDevicesUpdated(e){var t,n,r,i,a,o,s,l,c;(null==(t=this._selectedCam)?void 0:t.deviceId)!==e.devices.camera&&(this._selectedCam=e.devices.camera,null==(r=(n=this._callbacks).onCamUpdated)||r.call(n,e.devices.camera)),(null==(i=this._selectedMic)?void 0:i.deviceId)!==e.devices.mic&&(this._selectedMic=e.devices.mic,null==(o=(a=this._callbacks).onMicUpdated)||o.call(a,e.devices.mic)),(null==(s=this._selectedSpeaker)?void 0:s.deviceId)!==e.devices.speaker&&(this._selectedSpeaker=e.devices.speaker,null==(c=(l=this._callbacks).onSpeakerUpdated)||c.call(l,e.devices.speaker))}handleDeviceError(e){var t,n;null==(n=(t=this._callbacks).onDeviceError)||n.call(t,(e=>{const t=[];switch(e.type){case"permissions":return e.blockedMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg,{blockedBy:e.blockedBy});case"not-found":return e.missingMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg);case"constraints":return e.failedMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg,{reason:e.reason});case"cam-in-use":return t.push("cam"),new cd(t,"in-use",e.msg);case"mic-in-use":return t.push("mic"),new cd(t,"in-use",e.msg);case"cam-mic-in-use":return t.push("cam"),t.push("mic"),new cd(t,"in-use",e.msg);default:return t.push("cam"),t.push("mic"),new cd(t,e.type,e.msg)}})(e.error))}handleLocalAudioTrack(e){return d(this,null,function*(){if("ready"==this.state||!this._bufferLocalAudioUntilBotReady)return;switch(this._mediaStreamRecorder.getStatus()){case"ended":try{yield this._mediaStreamRecorder.begin(e),yield this.startRecording()}catch(lr){}break;case"paused":yield this.startRecording();break;default:if(this._currentAudioTrack!==e)try{yield this._mediaStreamRecorder.end(),yield this._mediaStreamRecorder.begin(e),yield this.startRecording()}catch(lr){}else Ad.warn("track-started event received for current track and already recording")}this._currentAudioTrack=e})}handleTrackStarted(e){var t,n,r,i,a;"screenAudio"===e.type||"screenVideo"===e.type?null==(n=(t=this._callbacks).onScreenTrackStarted)||n.call(t,e.track,e.participant?ff(e.participant):void 0):((null==(r=e.participant)?void 0:r.local)&&"audio"===e.track.kind&&this.handleLocalAudioTrack(e.track),null==(a=(i=this._callbacks).onTrackStarted)||a.call(i,e.track,e.participant?ff(e.participant):void 0))}handleTrackStopped(e){var t,n,r,i;"screenAudio"===e.type||"screenVideo"===e.type?null==(n=(t=this._callbacks).onScreenTrackStopped)||n.call(t,e.track,e.participant?ff(e.participant):void 0):null==(i=(r=this._callbacks).onTrackStopped)||i.call(r,e.track,e.participant?ff(e.participant):void 0)}handleParticipantJoined(e){var t,n,r,i;const a=ff(e.participant);null==(n=(t=this._callbacks).onParticipantJoined)||n.call(t,a),a.local||(this._botId=e.participant.session_id,null==(i=(r=this._callbacks).onBotConnected)||i.call(r,a))}handleParticipantLeft(e){var t,n,r,i;const a=ff(e.participant);null==(n=(t=this._callbacks).onParticipantLeft)||n.call(t,a),a.local||(this._botId="",null==(i=(r=this._callbacks).onBotDisconnected)||i.call(r,a))}handleLocalAudioLevel(e){var t,n;null==(n=(t=this._callbacks).onLocalAudioLevel)||n.call(t,e.audioLevel)}handleRemoteAudioLevel(e){var t,n;const r=this._daily.participants(),i=Object.keys(e.participantsAudioLevel);for(let a=0;a<i.length;a++){const o=i[a],s=e.participantsAudioLevel[o];null==(n=(t=this._callbacks).onRemoteAudioLevel)||n.call(t,s,ff(r[o]))}}handleLeftMeeting(){var e,t;this.state="disconnected",this._botId="",null==(t=(e=this._callbacks).onDisconnected)||t.call(e)}handleFatalError(e){var t,n;Ad.error("Daily fatal error",e.errorMsg),this.state="error",this._botId="",null==(n=(t=this._callbacks).onError)||n.call(t,Sd.error(e.errorMsg,!0))}handleNonFatalError(e){var t,n;if("screen-share-error"===e.type)null==(n=(t=this._callbacks).onScreenShareError)||n.call(t,e.errorMsg)}}df.RECORDER_SAMPLE_RATE=16e3,df.RECORDER_CHUNK_SIZE=512;const ff=e=>({id:e.user_id,local:e.local,name:e.user_name});function pf(e,t,n={}){const{pipecatClient:r,connectionState:i,isBotReady:a,isMicEnabled:o,isUserSpeaking:s,remoteAudioStream:u,addMessage:f,setPipecatClient:p,setConnectionState:h,setIsBotReady:m,setIsMicEnabled:g,setIsUserSpeaking:v,setRemoteAudioStream:y}=H(),b=x.useRef(null),w=x.useRef(!1),k=x.useRef(null),S=x.useRef(!1);x.useEffect(()=>{const e=b.current;if(e&&u)try{e.srcObject=u,e.volume=1;const t=e.play();t&&t.then(()=>{}).catch(e=>{})}catch(t){}return()=>{e&&(e.srcObject=null)}},[u]);const _=x.useCallback(()=>d(null,null,function*(){var r;if(!S.current&&"disconnected"===i){S.current=!0,h("connecting");try{if(!e||!t)throw new Error("Missing agent ID or prompt token");const r={agent_id:e,conversation_metadata:c(l({},n),{agent_id:e}),prompt_access_token:t,conversation_visibility:!1,conversation_config_type:"VOICE"},i=yield function(e){return d(this,null,function*(){const t=`${Q}/v1/widgets/sessions/daily`,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Prompt-Token":e.prompt_access_token},body:JSON.stringify(e)});if(!n.ok){const e=yield n.json().catch(()=>({}));throw new Error(e.detail||e.message||`HTTP ${n.status}`)}const r=yield n.json();return r.conversation_id,r})}(r);if(!(null==i?void 0:i.dailyRoom)||!(null==i?void 0:i.dailyToken))throw new Error("Invalid response from server");const{dailyRoom:a,dailyToken:s,conversation_id:u}=i,b=new Vd({transport:new df,enableMic:o,enableCam:!1,timeout:3e4,callbacks:{onTransportStateChanged:e=>{h(e)},onConnected:()=>{f({type:"separator",text:"Voice call started"})},onBotReady:e=>{m(!0),h("ready")},onBotStartedSpeaking:()=>{m(e=>e||(h("ready"),!0))},onDisconnected:()=>{h("disconnected"),m(!1),w.current||f({type:"separator",text:"Call disconnected"})},onTrackStarted:(e,t)=>{if("audio"===e.kind&&!(null==t?void 0:t.local)){const t=new MediaStream([e]);y(t)}},onUserStartedSpeaking:()=>{v(!0)},onUserStoppedSpeaking:()=>{v(!1)},onUserTranscript:e=>{(null==e?void 0:e.final)&&(null==e?void 0:e.text)&&(e.text,f({type:"user",text:e.text,isTranscript:!0}))},onBotTranscript:e=>{var t;const n=(null==(t=null==e?void 0:e.text)?void 0:t.trim())||"";n&&f({type:"assistant",text:n,isTranscript:!0})},onMicStateChanged:e=>{g(e)},onError:e=>{var t,n;const r=(null==(t=null==e?void 0:e.data)?void 0:t.error)||(null==e?void 0:e.message)||"";r.includes("validation error")||r.includes("FunctionResponse")||!(null==(n=null==e?void 0:e.data)?void 0:n.fatal)?(f({type:"separator",text:"Agent disconnected"}),E()):(h("error"),f({type:"system",text:`Error: ${r}`}))}}});p(b),k.current=b,yield b.initDevices(),yield b.connect({url:a,token:s})}catch(a){S.current=!1,h("error");let e="Failed to start call";e=(null==(r=a.message)?void 0:r.includes("Failed to fetch"))?"Cannot reach server":"NotAllowedError"===a.name?"Microphone access denied":"NotFoundError"===a.name?"No microphone found":a.message,f({type:"system",text:`❌ ${e}`})}}}),[e,t,n,i,o,h,p,m,g,y,f]),E=x.useCallback(()=>d(null,null,function*(){var e;try{if(f({type:"separator",text:"Voice call ended"}),w.current=!0,S.current=!1,r&&"disconnected"!==i&&(yield r.disconnect()),null==(e=b.current)?void 0:e.srcObject){b.current.srcObject.getTracks().forEach(e=>e.stop()),b.current.srcObject=null}y(null),p(null),k.current=null,h("disconnected"),m(!1),setTimeout(()=>{w.current=!1},500)}catch(t){S.current=!1,p(null),k.current=null,h("disconnected"),m(!1)}}),[r,i,p,h,m,y,f]),C=x.useCallback(()=>{if(r&&a)try{const e=!o;r.enableMic(e),g(e)}catch(e){}},[r,o,a,g]),T=x.useCallback(e=>d(null,null,function*(){if(r)if(a)try{yield r.sendText(e),f({type:"user",text:e,isTranscript:!1})}catch(t){f({type:"system",text:`Error: ${t.message||"Failed to send text"}`})}else f({type:"system",text:"Please wait for the bot to be ready before sending text"})}),[r,a,f]);return x.useEffect(()=>()=>{var e;const t=k.current;if(t&&(w.current=!0,t.disconnect().catch(e=>{})),null==(e=b.current)?void 0:e.srcObject){b.current.srcObject.getTracks().forEach(e=>e.stop())}},[]),{connectionState:i,isBotReady:a,isMicEnabled:o,isUserSpeaking:s,startCall:_,endCall:E,toggleMic:C,sendTextDuringCall:T,remoteAudioRef:b}}function hf({agentId:e,agentName:t,avatarUrl:n,promptToken:r,metadata:i,showTranscripts:a=!0,idlePromptMessages:o=[],onClose:s,className:l}){const{messages:c}=H(),[u,d]=x.useState(""),[f,p]=x.useState(0),h=x.useRef(null),{connectionState:m,isBotReady:g,isMicEnabled:v,isUserSpeaking:y,startCall:w,endCall:k,toggleMic:S,sendTextDuringCall:_,remoteAudioRef:E}=pf(e,r,i);x.useEffect(()=>("disconnected"===m&&w(),()=>{"disconnected"!==m&&k()}),[]);const C="connecting"===m||!g,T="ready"===m||"connected"===m,M="error"===m;x.useEffect(()=>{var e;null==(e=h.current)||e.scrollIntoView({behavior:"smooth"})},[c]),x.useEffect(()=>{if(!C||!(null==o?void 0:o.length))return;const e=setInterval(()=>{p(e=>(e+1)%o.length)},3e3);return()=>clearInterval(e)},[C,o]);const P=T&&y?{text:"Transcribing",animate:!0}:null,A=M?"error":C?"connecting":v?"listening":"muted",O=c.filter(e=>e.isTranscript||"separator"===e.type||"system"===e.type||"user"===e.type||"assistant"===e.type);return b.jsxs("div",{className:yt("flex flex-col h-full w-full animate-fade-in min-h-0 relative",l),style:{backgroundColor:"var(--widget-background, #FFFFFF)",fontFamily:"var(--widget-font-family, system-ui)"},children:[b.jsx("audio",{ref:E,autoPlay:!0,playsInline:!0,style:{display:"none"}}),b.jsx("button",{onClick:()=>{k(),s()},className:"absolute top-4 right-4 p-2 rounded-full hover:opacity-80 transition-opacity z-10",style:{color:"var(--widget-icon-secondary, #6B7280)"},"aria-label":"Close",children:b.jsx(Ft,{className:"h-6 w-6"})}),C&&b.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-6",children:[b.jsx("div",{className:"mb-6",children:b.jsx(qn,{loading:!0,size:180,strokeWidth:4,gap:6,children:b.jsx(_t,{src:n,alt:t,size:"2xl",className:"shadow-lg"})})}),b.jsx("h2",{className:"text-xl font-semibold mb-2",style:{color:"var(--widget-text-primary, #111827)"},children:t}),b.jsx("p",{className:"text-sm mb-6",style:{color:"var(--widget-status-connecting, #F59E0B)"},children:"Connecting..."}),(null==o?void 0:o.length)>0&&b.jsx("div",{className:"text-center px-4 py-3 rounded-lg max-w-xs animate-fade-in",style:{backgroundColor:"var(--widget-idle-prompt-bg, #F3F4F6)",color:"var(--widget-idle-prompt-text, #6B7280)"},children:b.jsx("p",{className:"text-sm",children:o[f]})},f)]}),!C&&b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 shrink-0",style:{backgroundColor:"var(--widget-header-bg, #F9FAFB)",borderBottom:"1px solid var(--widget-header-border, #E5E7EB)"},children:[b.jsxs("div",{className:"flex-1 flex items-center gap-3",children:[b.jsxs("div",{className:"relative",children:[b.jsx(_t,{src:n,alt:t,size:"sm"}),A&&b.jsx("span",{className:yt("absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2",("listening"===A||"connecting"===A)&&"animate-pulse"),style:{backgroundColor:"listening"===A?"var(--widget-status-success, #10B981)":"connecting"===A?"var(--widget-status-warning, #F59E0B)":"var(--widget-status-error, #EF4444)",borderColor:"var(--widget-header-bg, #F9FAFB)"}})]}),b.jsxs("div",{children:[b.jsx("h2",{className:"text-sm font-semibold leading-tight",style:{color:"var(--widget-header-text, #111827)"},children:t}),A&&b.jsxs("span",{className:"text-xs",style:{color:"listening"===A?"var(--widget-status-success, #10B981)":"error"===A?"var(--widget-status-error, #EF4444)":"var(--widget-text-muted, #9CA3AF)"},children:["listening"===A&&"Listening...","connecting"===A&&"Connecting...","muted"===A&&"Muted","error"===A&&"Connection failed"]})]})]}),b.jsx("div",{className:"w-9"})]}),b.jsx(Fn,{className:"flex-1 min-h-0",children:b.jsxs("div",{className:"p-4 space-y-3 min-h-full",children:[0===O.length&&!P&&b.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:b.jsx("p",{className:"text-sm",style:{color:"var(--widget-text-muted, #9CA3AF)"},children:"Start Conversation"})}),O.map(e=>b.jsx(mf,{message:e},e.id)),P&&b.jsx("div",{className:"flex justify-end",children:b.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-2xl rounded-br-md text-sm",style:{backgroundColor:"var(--widget-user-message-bg, #3B82F6)",color:"var(--widget-user-message-text, #FFFFFF)"},children:[b.jsx("span",{children:P.text}),b.jsxs("span",{className:"flex gap-1",children:[b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"0ms"}}),b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"150ms"}}),b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"300ms"}})]})]})}),b.jsx("div",{ref:h})]})}),b.jsxs("div",{className:"shrink-0",style:{borderTop:"1px solid var(--widget-border, #E5E7EB)",backgroundColor:"var(--widget-background, #FFFFFF)"},children:[b.jsxs("form",{onSubmit:e=>{e.preventDefault(),u.trim()&&T&&(_(u.trim()),d(""))},className:"flex items-center gap-2 px-4 py-2",children:[b.jsx("input",{type:"text",value:u,onChange:e=>d(e.target.value),placeholder:"Type a message...",disabled:!T,className:"flex-1 h-10 px-4 rounded-full outline-none transition-all text-sm",style:{backgroundColor:"var(--widget-input-bg, #F9FAFB)",color:"var(--widget-input-text, #111827)",border:"1px solid var(--widget-input-border, #E5E7EB)",fontFamily:"var(--widget-font-family, inherit)"}}),b.jsx(St,{type:"submit",variant:"ghost",size:"icon",disabled:!u.trim()||!T,className:"shrink-0 rounded-full h-10 w-10",children:b.jsx(Rt,{className:"h-4 w-4"})})]}),b.jsxs("div",{className:"flex justify-center gap-4 px-4 pt-2",style:{paddingBottom:"max(1rem, env(safe-area-inset-bottom, 0px))"},children:[b.jsx(St,{onClick:S,variant:v?"secondary":"outline",size:"icon-lg",className:"rounded-full h-12 w-12",disabled:!T,style:{backgroundColor:v?"var(--widget-button-secondary-bg, #F3F4F6)":"transparent",borderColor:v?void 0:"var(--widget-border, #E5E7EB)"},children:v?b.jsx(jt,{className:"h-5 w-5",style:{color:"var(--widget-text-primary, #111827)"}}):b.jsx(Lt,{className:"h-5 w-5",style:{color:"var(--widget-text-muted, #9CA3AF)"}})}),b.jsx(St,{onClick:()=>{k(),s()},variant:"destructive",size:"icon-lg",className:"rounded-full h-12 w-12",children:b.jsx(It,{className:"h-5 w-5"})})]})]})]})]})}function mf({message:e}){const t="user"===e.type;e.type;const n="separator"===e.type,r="system"===e.type;return n?b.jsx("div",{className:"flex items-center justify-center py-1",children:b.jsx("div",{className:"px-3 py-1 rounded-full text-xs",style:{backgroundColor:"var(--widget-system-message-bg, #F3F4F6)",color:"var(--widget-text-muted, #9CA3AF)"},children:e.text})}):r?b.jsx("div",{className:"flex justify-center",children:b.jsx("div",{className:"max-w-[85%] px-4 py-2 rounded-lg text-sm",style:{backgroundColor:"var(--widget-status-error-bg, #FEE2E2)",color:"var(--widget-status-error, #DC2626)"},children:e.text})}):b.jsx("div",{className:yt("flex",t?"justify-end":"justify-start"),children:b.jsx("div",{className:yt("max-w-[80%] px-4 py-2.5 text-sm leading-relaxed",t?"rounded-2xl rounded-br-md":"rounded-2xl rounded-bl-md"),style:{backgroundColor:t?"var(--widget-user-message-bg, #3B82F6)":"var(--widget-bot-message-bg, #F3F4F6)",color:t?"var(--widget-user-message-text, #FFFFFF)":"var(--widget-bot-message-text, #111827)"},children:e.text})})}function gf({agentName:e,avatarUrl:t,variablesConfig:n=[],onSubmit:r,onClose:i,className:a}){const[o,s]=x.useState(()=>n.reduce((e,{key:t})=>c(l({},e),{[t]:""}),{})),[u,d]=x.useState({}),f=x.useMemo(()=>n.filter(e=>e.required).map(e=>e.key),[n]),p=x.useCallback(e=>e.split(/[_-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),[]),h=x.useCallback((e,t)=>{s(n=>c(l({},n),{[e]:t})),u[e]&&d(t=>c(l({},t),{[e]:null}))},[u]),m=x.useCallback(()=>{const e={};let t=!1;if(f.forEach(n=>{o[n]&&""!==o[n].trim()||(e[n]=`${p(n)} is required`,t=!0)}),t)return void d(e);const n=Object.fromEntries(Object.entries(o).filter(([e,t])=>t&&""!==t.trim()));r(n)},[o,f,p,r]),g=x.useCallback((e,t)=>{"Enter"===e.key&&t&&m()},[m]);return b.jsxs("div",{className:yt("flex flex-col h-full w-full animate-fade-in relative min-h-0",a),style:{backgroundColor:"var(--widget-background, #FFFFFF)",fontFamily:"var(--widget-font-family, system-ui)"},children:[b.jsx("button",{onClick:i,className:"absolute top-4 right-4 p-2 rounded-full hover:opacity-80 transition-opacity z-10",style:{color:"var(--widget-icon-secondary, #6B7280)"},"aria-label":"Close",children:b.jsx(Ft,{className:"h-6 w-6"})}),b.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:b.jsxs("div",{className:"flex flex-col items-center px-6 py-8 pt-14",children:[b.jsx(_t,{src:t,alt:e,size:"xl",className:"mb-4 shadow-lg"}),b.jsx("h1",{className:"text-xl font-semibold mb-2 text-center",style:{color:"var(--widget-text-primary, #111827)"},children:"Before we start"}),b.jsxs("p",{className:"text-sm mb-6 text-center max-w-sm",style:{color:"var(--widget-text-secondary, #6B7280)"},children:["Please provide the following information to personalize your experience with ",b.jsx("span",{className:"font-medium",children:e})]}),b.jsx("div",{className:"w-full max-w-md space-y-4",children:n.map(({key:e,required:t},r)=>b.jsxs("div",{className:"space-y-1",children:[b.jsxs("label",{htmlFor:`var-${e}`,className:"block text-sm font-medium",style:{color:"var(--widget-text-primary, #111827)"},children:[p(e),t&&b.jsx("span",{className:"ml-1",style:{color:"var(--widget-status-error, #DC2626)"},children:"*"}),!t&&b.jsx("span",{className:"ml-1 text-xs font-normal",style:{color:"var(--widget-text-muted, #9CA3AF)"},children:"(optional)"})]}),b.jsx("input",{id:`var-${e}`,type:"text",value:o[e],onChange:t=>h(e,t.target.value),onKeyDown:e=>g(e,r===n.length-1),placeholder:`Enter ${p(e).toLowerCase()}`,className:"w-full px-4 py-3 rounded-lg text-sm outline-none transition-colors",style:{backgroundColor:"var(--widget-input-bg, #FFFFFF)",color:"var(--widget-input-text, #111827)",border:u[e]?"2px solid var(--widget-border-error, #DC2626)":"1px solid var(--widget-input-border, #E5E7EB)"},autoFocus:0===r}),u[e]&&b.jsx("p",{className:"text-xs",style:{color:"var(--widget-status-error, #DC2626)"},children:u[e]})]},e))})]})}),b.jsx("div",{className:"p-6 pb-safe shrink-0",style:{borderTop:"1px solid var(--widget-border, #E5E7EB)",paddingBottom:"max(1.5rem, env(safe-area-inset-bottom, 0px))"},children:b.jsx("div",{className:"max-w-md mx-auto",children:b.jsxs(St,{onClick:m,variant:"default",size:"xl",className:"w-full",children:["Continue",b.jsx(Pt,{className:"h-5 w-5 ml-2"})]})})})]})}function vf({agentId:e,metadata:t={},widgetElement:n}){const{isOpen:r,currentScreen:i,setScreen:a,closeDialog:o,dynamicVariables:s,pendingScreen:c,setDynamicVariables:u,setPendingScreen:f}=H(),{agentName:p,avatarUrl:h,promptToken:m,themeConfig:g,tncConfig:v,interfaceConfig:y,appearanceConfig:w,dynamicVariablesConfig:k,isLoading:S,error:_}=function(e){var t,n,r;const{agentConfig:i,configLoading:a,configError:o,setAgentId:s,setAgentConfig:l,setConfigLoading:c,setConfigError:u}=H(),f=x.useRef(null),p=x.useRef(!1);x.useEffect(()=>{d(null,null,function*(){if(e){if(!(p.current||f.current===e&&i)){f.current&&f.current!==e&&(l(null),f.current=null);try{p.current=!0,c(!0),u(null),s(e);const t=yield Y(e);if(!t||!t.widget_config)throw new Error("Invalid agent configuration structure");l(t),f.current=e}catch(_){u(_.message||"Failed to load configuration")}finally{p.current=!1,c(!1)}}}else u("Agent ID is required")})},[e,i,s,l,c,u]);const h=x.useCallback(()=>d(null,null,function*(){if(e)try{f.current=null,p.current=!0,c(!0),u(null);const t=yield Y(e);if(!t||!t.widget_config)throw new Error("Invalid agent configuration structure");l(t),f.current=e}catch(_){u(_.message||"Failed to load configuration")}finally{p.current=!1,c(!1)}else u("Agent ID is required")}),[e,l,c,u]),m=(null==i?void 0:i.widget_config)||{},g=((null==i?void 0:i.dynamic_variables_keys)||[]).map(e=>({key:e,required:!0})),v=(null==(t=m.widget_dynamic_variables)?void 0:t.variables)||[],y=new Set(v.map(e=>e.key)),b=[...g.filter(e=>!y.has(e.key)),...v];return{agentConfig:i,agentName:(null==i?void 0:i.agent_name)||"AI Assistant",promptToken:(null==i?void 0:i.prompt_access_token)||null,dynamicVariablesConfig:b,interfaceConfig:m.widget_interface||{},appearanceConfig:m.widget_appearance||{},avatarConfig:m.widget_avatar||{},themeConfig:m.widget_theme||{},tncConfig:m.widget_tnc_config||{},avatarUrl:(null==(r=null==(n=null==i?void 0:i.MediaFiles)?void 0:n.find(e=>"avatar"===e.fileType))?void 0:r.mediaUrl)||null,isLoading:a,error:o,refresh:h}}(e),E=(null==k?void 0:k.length)>0&&0===Object.keys(s).length,C=x.useCallback(e=>{E?(f(e),a("variables")):a(e)},[E,f,a]),T=x.useCallback(e=>{u(e),c&&(a(c),f(null))},[c,u,a,f]),M=l(l({},t),s);if(x.useEffect(()=>{!r||S||!E||"chat"!==i&&"talk"!==i||(f(i),a("variables"))},[r,S,E,i,f,a]),!r)return null;if(S)return b.jsx(yf,{children:b.jsx(bf,{children:b.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:[b.jsx(Ot,{className:"h-12 w-12 animate-spin",style:{color:"var(--widget-primary-color, #3B82F6)"}}),b.jsx("p",{className:"text-sm",style:{color:"var(--widget-text-secondary, #6B7280)"},children:"Loading..."})]})})});if(_)return b.jsx(yf,{children:b.jsx(bf,{children:b.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 p-6",children:[b.jsx("div",{className:"text-4xl",role:"img","aria-label":"Error",children:"😕"}),b.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--widget-text-primary, #111827)"},children:"Something went wrong"}),b.jsx("p",{className:"text-sm text-center",style:{color:"var(--widget-text-secondary, #6B7280)"},children:_}),b.jsx("button",{onClick:o,className:"mt-4 px-6 py-2 rounded-lg text-sm font-medium",style:{backgroundColor:"var(--widget-button-secondary-bg, #F3F4F6)",color:"var(--widget-button-secondary-text, #374151)"},children:"Close"})]})})});return b.jsxs(yf,{onClick:o,children:[b.jsx(Z,{theme:g,widgetElement:n}),b.jsx(bf,{onClick:e=>e.stopPropagation(),children:(()=>{switch(i){case"variables":return b.jsx(gf,{agentName:p,avatarUrl:h,variablesConfig:k,onSubmit:T,onClose:o});case"chat":return b.jsx($n,{agentId:e,agentName:p,promptToken:m,metadata:M,onClose:o,onSwitchToTalk:()=>a("talk")});case"talk":return b.jsx(hf,{agentId:e,agentName:p,avatarUrl:h,promptToken:m,metadata:M,showTranscripts:y.realtime_transcript_of_the_call,idlePromptMessages:w.idle_prompt_messages,onClose:o});default:return b.jsx(Dt,{agentName:p,avatarUrl:h,tncEnabled:v.tnc_enabled,tncContent:v.tnc_content,onTalk:()=>C("talk"),onChat:()=>C("chat"),onClose:o})}})()})]})}function yf({children:e,onClick:t}){return b.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center animate-fade-in",style:{backgroundColor:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(4px)"},onClick:t,children:e})}function bf({children:e,onClick:t,className:n}){return b.jsx("div",{className:yt("relative w-full h-full overflow-hidden animate-scale-in","sm:max-w-lg sm:max-h-[90vh] sm:h-[700px] sm:rounded-2xl",n),style:{backgroundColor:"var(--widget-background, #FFFFFF)",boxShadow:"var(--widget-shadow-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"},onClick:t,children:e})}const wf='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:var(--widget-font-family),system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.-bottom-0\\.5{bottom:-.125rem}.-right-0\\.5{right:-.125rem}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.z-\\[9999\\]{z-index:9999}.mx-auto{margin-left:auto;margin-right:auto}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.aspect-square{aspect-ratio:1 / 1}.h-1\\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\\.5{height:.625rem}.h-24{height:6rem}.h-3{height:.75rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.min-h-0{min-height:0px}.min-h-\\[200px\\]{min-height:200px}.min-h-full{min-height:100%}.w-1\\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\\.5{width:.625rem}.w-24{width:6rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-full{width:100%}.max-w-\\[80\\%\\]{max-width:80%}.max-w-\\[85\\%\\]{max-width:85%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\\[inherit\\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-bl-md{border-bottom-left-radius:.375rem}.rounded-br-md{border-bottom-right-radius:.375rem}.border{border-width:1px}.border-2{border-width:2px}.border-l{border-left-width:1px}.border-t{border-top-width:1px}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-current{background-color:currentColor}.bg-transparent{background-color:transparent}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\\[1px\\]{padding:1px}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pt-14{padding-top:3.5rem}.pt-2{padding-top:.5rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.italic{font-style:italic}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.underline-offset-4{text-underline-offset:4px}.opacity-50{opacity:.5}.opacity-80{opacity:.8}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-2{--tw-ring-offset-width: 2px}.ring-offset-4{--tw-ring-offset-width: 4px}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}*,*:before,*:after{box-sizing:border-box}html{scroll-behavior:smooth}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--widget-border, #e5e7eb);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--widget-text-muted, #9ca3af)}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes slideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideDown{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes scaleIn{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-4px)}}.animate-fade-in{animation:fadeIn .3s ease-out}.animate-slide-up{animation:slideUp .4s ease-out}.animate-slide-down{animation:slideDown .4s ease-out}.animate-scale-in{animation:scaleIn .3s ease-out}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}.animate-spin{animation:spin 1s linear infinite}.animate-bounce{animation:bounce .6s ease-in-out infinite}@keyframes loaderSpin{0%{transform:rotate(-90deg)}to{transform:rotate(270deg)}}@keyframes loaderDash{0%{stroke-dashoffset:478}50%{stroke-dashoffset:120}to{stroke-dashoffset:478}}.animate-loader-spin{animation:loaderSpin 1.5s linear infinite,loaderDash 2s ease-in-out infinite;transform-origin:center}.pb-safe{padding-bottom:env(safe-area-inset-bottom,0px)}.pt-safe{padding-top:env(safe-area-inset-top,0px)}.px-safe{padding-left:env(safe-area-inset-left,0px);padding-right:env(safe-area-inset-right,0px)}.hover\\:underline:hover{text-decoration-line:underline}.hover\\:opacity-80:hover{opacity:.8}.hover\\:opacity-90:hover{opacity:.9}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.disabled\\:pointer-events-none:disabled{pointer-events:none}.disabled\\:opacity-50:disabled{opacity:.5}@media(min-width:640px){.sm\\:h-\\[700px\\]{height:700px}.sm\\:max-h-\\[90vh\\]{max-height:90vh}.sm\\:max-w-lg{max-width:32rem}.sm\\:rounded-2xl{border-radius:1rem}}';class kf extends HTMLElement{constructor(){super(),this.root=null,this.shadow=null,this.themeStyleSheet=null,this.agentId=null,this.metadata={}}injectThemeCSS(e){if(this.shadow&&e)try{if(this.themeStyleSheet){const e=this.shadow.adoptedStyleSheets.indexOf(this.themeStyleSheet);e>-1&&(this.shadow.adoptedStyleSheets=this.shadow.adoptedStyleSheets.filter((t,n)=>n!==e))}const t=new CSSStyleSheet;t.replaceSync(e),this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,t],this.themeStyleSheet=t}catch(t){const n=document.createElement("style");n.setAttribute("data-eigi-theme","true"),n.textContent=e;const r=this.shadow.querySelector("[data-eigi-theme]");r&&r.remove(),this.shadow.appendChild(n)}}connectedCallback(){this.agentId=this.getAttribute("agent-id");const e=this.getAttribute("metadata");if(e)try{this.metadata=JSON.parse(e)}catch(lr){}if(!this.agentId)return;const t=this.attachShadow({mode:"open"});this.shadow=t;try{const e=new CSSStyleSheet;e.replaceSync(wf),t.adoptedStyleSheets=[e]}catch(r){const e=document.createElement("style");e.textContent=wf,t.appendChild(e)}const n=document.createElement("div");n.id="eigi-chat-root",t.appendChild(n),this.root=V.createRoot(n),this.render(),this.agentId,"undefined"!=typeof window&&window.EigiChat&&(window.EigiChat._element=this,window.EigiChat._agentId=this.agentId,window.EigiChat._metadata=this.metadata,H.getState().setAgentId(this.agentId))}render(){this.root&&this.root.render(b.jsx(E.StrictMode,{children:b.jsx(vf,{agentId:this.agentId,metadata:this.metadata,widgetElement:this})}))}disconnectedCallback(){this.root&&(this.root.unmount(),this.root=null)}static get observedAttributes(){return["agent-id","metadata","action"]}attributeChangedCallback(e,t,n){if(t!==n)if("agent-id"===e)this.agentId=n,this.render();else if("metadata"===e){try{this.metadata=JSON.parse(n)}catch(lr){}this.render()}else"action"===e&&this.handleAction(n)}handleAction(e){if(!e)return;const t=H.getState();switch(e){case"open":t.openDialog();break;case"close":t.closeDialog();break;case"toggle":t.toggleDialog();break;case"openChat":t.openChat();break;case"openTalk":t.openTalk()}setTimeout(()=>{this.removeAttribute("action")},100)}}"undefined"==typeof window||customElements.get("eigi-chat")||customElements.define("eigi-chat",kf);const Sf={_element:null,_agentId:null,_metadata:{},init({agentId:e,metadata:t={}}={}){e&&(this._agentId=e,this._metadata=t,H.getState().setAgentId(e),this._element?(this._element.setAttribute("agent-id",e),Object.keys(t).length>0&&this._element.setAttribute("metadata",JSON.stringify(t))):(this._element=document.createElement("eigi-chat"),this._element.setAttribute("agent-id",e),Object.keys(t).length>0&&this._element.setAttribute("metadata",JSON.stringify(t)),document.body.appendChild(this._element)))},open(){this._ensureInitialized(),H.getState().openDialog()},close(){H.getState().closeDialog()},toggle(){H.getState().toggleDialog()},isOpen:()=>H.getState().isOpen,openChat(){this._ensureInitialized(),H.getState().openChat()},openTalk(){this._ensureInitialized(),H.getState().openTalk()},_ensureInitialized(){!this._element&&this._agentId?this.init({agentId:this._agentId,metadata:this._metadata}):this._agentId}};if("undefined"!=typeof window){const e=document.querySelectorAll("script[data-agent-id]"),t=e[e.length-1];if(t){const e=t.getAttribute("data-agent-id"),n=t.getAttribute("data-metadata");let r={};if(n)try{r=JSON.parse(n)}catch(lr){}e&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Sf.init({agentId:e,metadata:r})}):Sf.init({agentId:e,metadata:r}))}window.EigiChat=Sf}return e.EigiChatAPI=Sf,e.EigiChatElement=kf,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});"undefined"!=typeof window&&window.EigiChatInternal&&(window.EigiChat=window.EigiChatInternal.EigiChatAPI,window.EigiChatElement=window.EigiChatInternal.EigiChatElement);
48
+ */class $u{static getParser(e,t=!1){if("string"!=typeof e)throw new Error("UserAgent should be a string");return new Vu(e,t)}static parse(e){return new Vu(e).getResult()}static get BROWSER_MAP(){return Nu}static get ENGINE_MAP(){return Iu}static get OS_MAP(){return ju}static get PLATFORMS_MAP(){return Lu}}function Wu(e,t){return Object.keys(t).forEach(function(n){"default"===n||"__esModule"===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})}),e}function qu(e){return e&&e.__esModule?e.default:e}function Hu(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var Ju={},Qu={};Hu(Qu,"PipecatClient",()=>Vd);var Gu;Gu=JSON.parse('{"name":"@pipecat-ai/client-js","version":"1.5.0","license":"BSD-2-Clause","main":"dist/index.js","module":"dist/index.module.js","types":"dist/index.d.ts","source":"index.ts","repository":{"type":"git","url":"git+https://github.com/pipecat-ai/pipecat-client-web.git"},"files":["dist","package.json","README.md"],"scripts":{"build":"jest --silent --passWithNoTests && parcel build --no-cache","dev":"parcel watch","lint":"eslint . --report-unused-disable-directives --max-warnings 0","test":"jest"},"jest":{"preset":"ts-jest","testEnvironment":"jsdom"},"devDependencies":{"@jest/globals":"^29.7.0","@types/clone-deep":"^4.0.4","@types/jest":"^29.5.12","@types/uuid":"^10.0.0","eslint":"^9.11.1","eslint-config-prettier":"^9.1.0","eslint-plugin-simple-import-sort":"^12.1.1","jest":"^29.7.0","jest-environment-jsdom":"^30.0.2","ts-jest":"^29.2.5"},"dependencies":{"@types/events":"^3.0.3","bowser":"^2.11.0","clone-deep":"^4.0.1","events":"^3.3.0","typed-emitter":"^2.1.0","uuid":"^10.0.0"}}');var Yu,Ku,Xu={},Zu={};Hu(Zu,"TransportStateEnum",()=>Yu),(Ku=Yu||(Yu={})).DISCONNECTED="disconnected",Ku.INITIALIZING="initializing",Ku.INITIALIZED="initialized",Ku.AUTHENTICATING="authenticating",Ku.AUTHENTICATED="authenticated",Ku.CONNECTING="connecting",Ku.CONNECTED="connected",Ku.READY="ready",Ku.DISCONNECTING="disconnecting",Ku.ERROR="error";var ed={};Hu(ed,"RTVIError",()=>td),Hu(ed,"ConnectionTimeoutError",()=>nd),Hu(ed,"StartBotError",()=>rd),Hu(ed,"TransportStartError",()=>id),Hu(ed,"InvalidTransportParamsError",()=>ad),Hu(ed,"BotNotReadyError",()=>od),Hu(ed,"BotAlreadyStartedError",()=>sd),Hu(ed,"UnsupportedFeatureError",()=>ld),Hu(ed,"DeviceError",()=>cd);class td extends Error{constructor(e,t){super(e),this.status=t}}class nd extends td{constructor(e){super(null!=e?e:"Bot did not enter ready state within the specified timeout period.")}}class rd extends td{constructor(e,t){super(null!=e?e:"Failed to connect / invalid auth bundle from base url",null!=t?t:500),this.error="invalid-request-error"}}class id extends td{constructor(e){super(null!=e?e:"Unable to connect to transport")}}class ad extends td{constructor(e){super(null!=e?e:"Invalid transport connection parameters")}}class od extends td{constructor(e){super(null!=e?e:"Attempt to call action on transport when not in 'ready' state.")}}class sd extends td{constructor(e){super(null!=e?e:"Pipecat client has already been started. Please call disconnect() before starting again.")}}class ld extends td{constructor(e,t,n){let r=`${e} not supported${n?`: ${n}`:""}`;t&&(r=`${t} does not support ${e}${n?`: ${n}`:""}`),super(r),this.feature=e}}class cd extends td{constructor(e,t,n,r){super(null!=n?n:`Device error for ${e.join(", ")}: ${t}`),this.devices=e,this.type=t,this.details=r}}var ud,dd,fd={};Hu(fd,"RTVIEvent",()=>ud),(dd=ud||(ud={})).Connected="connected",dd.Disconnected="disconnected",dd.TransportStateChanged="transportStateChanged",dd.BotStarted="botStarted",dd.BotConnected="botConnected",dd.BotReady="botReady",dd.BotDisconnected="botDisconnected",dd.Error="error",dd.ServerMessage="serverMessage",dd.ServerResponse="serverResponse",dd.MessageError="messageError",dd.Metrics="metrics",dd.BotStartedSpeaking="botStartedSpeaking",dd.BotStoppedSpeaking="botStoppedSpeaking",dd.UserStartedSpeaking="userStartedSpeaking",dd.UserStoppedSpeaking="userStoppedSpeaking",dd.UserTranscript="userTranscript",dd.BotOutput="botOutput",dd.BotTranscript="botTranscript",dd.BotLlmText="botLlmText",dd.BotLlmStarted="botLlmStarted",dd.BotLlmStopped="botLlmStopped",dd.LLMFunctionCall="llmFunctionCall",dd.BotLlmSearchResponse="botLlmSearchResponse",dd.BotTtsText="botTtsText",dd.BotTtsStarted="botTtsStarted",dd.BotTtsStopped="botTtsStopped",dd.ParticipantConnected="participantConnected",dd.ParticipantLeft="participantLeft",dd.TrackStarted="trackStarted",dd.TrackStopped="trackStopped",dd.ScreenTrackStarted="screenTrackStarted",dd.ScreenTrackStopped="screenTrackStopped",dd.ScreenShareError="screenShareError",dd.LocalAudioLevel="localAudioLevel",dd.RemoteAudioLevel="remoteAudioLevel",dd.AvailableCamsUpdated="availableCamsUpdated",dd.AvailableMicsUpdated="availableMicsUpdated",dd.AvailableSpeakersUpdated="availableSpeakersUpdated",dd.CamUpdated="camUpdated",dd.MicUpdated="micUpdated",dd.SpeakerUpdated="speakerUpdated",dd.DeviceError="deviceError";var pd={};Hu(pd,"RTVI_PROTOCOL_VERSION",()=>hd),Hu(pd,"RTVI_MESSAGE_LABEL",()=>md),Hu(pd,"RTVIMessageType",()=>gd),Hu(pd,"AggregationType",()=>yd),Hu(pd,"setAboutClient",()=>kd),Hu(pd,"RTVIMessage",()=>Sd);const hd="1.0.0",md="rtvi-ai";var gd,vd,yd,bd;let wd;function kd(e){wd=wd?l(l({},wd),e):e}(vd=gd||(gd={})).CLIENT_READY="client-ready",vd.DISCONNECT_BOT="disconnect-bot",vd.CLIENT_MESSAGE="client-message",vd.SEND_TEXT="send-text",vd.APPEND_TO_CONTEXT="append-to-context",vd.BOT_READY="bot-ready",vd.ERROR="error",vd.METRICS="metrics",vd.SERVER_MESSAGE="server-message",vd.SERVER_RESPONSE="server-response",vd.ERROR_RESPONSE="error-response",vd.APPEND_TO_CONTEXT_RESULT="append-to-context-result",vd.USER_TRANSCRIPTION="user-transcription",vd.BOT_OUTPUT="bot-output",vd.BOT_TRANSCRIPTION="bot-transcription",vd.USER_STARTED_SPEAKING="user-started-speaking",vd.USER_STOPPED_SPEAKING="user-stopped-speaking",vd.BOT_STARTED_SPEAKING="bot-started-speaking",vd.BOT_STOPPED_SPEAKING="bot-stopped-speaking",vd.USER_LLM_TEXT="user-llm-text",vd.BOT_LLM_TEXT="bot-llm-text",vd.BOT_LLM_STARTED="bot-llm-started",vd.BOT_LLM_STOPPED="bot-llm-stopped",vd.LLM_FUNCTION_CALL="llm-function-call",vd.LLM_FUNCTION_CALL_RESULT="llm-function-call-result",vd.BOT_LLM_SEARCH_RESPONSE="bot-llm-search-response",vd.BOT_TTS_TEXT="bot-tts-text",vd.BOT_TTS_STARTED="bot-tts-started",vd.BOT_TTS_STOPPED="bot-tts-stopped",(bd=yd||(yd={})).WORD="word",bd.SENTENCE="sentence";class Sd{constructor(e,t,n){this.label=md,this.type=e,this.data=t,this.id=n||Au().slice(0,8)}static clientReady(){return new Sd(gd.CLIENT_READY,{version:hd,about:wd||{library:Gu.name,library_version:Gu.version}})}static disconnectBot(){return new Sd(gd.DISCONNECT_BOT,{})}static error(e,t=!1){return new Sd(gd.ERROR,{message:e,fatal:t})}}function _d(e,t,n){const r=n.value;return n.value=function(...e){if("ready"===this.state)return r.apply(this,e);throw new od(`Attempt to call ${t.toString()} when transport not in ready state. Await connect() first.`)},n}function xd(e,t,n){const r=n.value,i=["authenticating","connecting","connected","ready"];return n.value=function(...e){if(i.includes(this.state))throw new sd(`Attempt to call ${t.toString()} when client already started. Please call disconnect() before starting again.`);return r.apply(this,e)},n}Wu(Xu,Zu),Wu(Xu,ed),Wu(Xu,fd),Wu(Xu,pd);var Ed={};Hu(Ed,"MessageDispatcher",()=>Od);var Cd,Td,Md={};Hu(Md,"LogLevel",()=>Cd),Hu(Md,"logger",()=>Ad),(Td=Cd||(Cd={}))[Td.NONE=0]="NONE",Td[Td.ERROR=1]="ERROR",Td[Td.WARN=2]="WARN",Td[Td.INFO=3]="INFO",Td[Td.DEBUG=4]="DEBUG";class Pd{constructor(){this.level=Cd.DEBUG}static getInstance(){return Pd.instance||(Pd.instance=new Pd),Pd.instance}setLevel(e){this.level=e}debug(...e){this.level>=Cd.DEBUG&&console.debug(...e)}info(...e){this.level>=Cd.INFO&&console.info(...e)}warn(...e){this.level>=Cd.WARN&&console.warn(...e)}error(...e){this.level>=Cd.ERROR&&console.error(...e)}}const Ad=Pd.getInstance();class Od{constructor(e){this._queue=new Array,this._gcInterval=void 0,this._queue=[],this._sendMethod=e}disconnect(){this.clearQueue(),clearInterval(this._gcInterval),this._gcInterval=void 0}dispatch(e,t=gd.CLIENT_MESSAGE,n=1e4){this._gcInterval||(this._gcInterval=setInterval(()=>{this._gc()},2e3));const r=new Sd(t,e),i=new Promise((e,t)=>{this._queue.push({message:r,timestamp:Date.now(),timeout:n,resolve:e,reject:t})});Ad.debug("[MessageDispatcher] dispatch",r);try{this._sendMethod(r)}catch(lr){return Ad.error("[MessageDispatcher] Error sending message",lr),Promise.reject(lr)}return this._gc(),i}clearQueue(){this._queue=[]}_resolveReject(e,t=!0){const n=this._queue.find(t=>t.message.id===e.id);return n&&(t?(Ad.debug("[MessageDispatcher] Resolve",e),n.resolve(e)):(Ad.debug("[MessageDispatcher] Reject",e),n.reject(e)),this._queue=this._queue.filter(t=>t.message.id!==e.id),Ad.debug("[MessageDispatcher] Queue",this._queue)),e}resolve(e){return this._resolveReject(e,!0)}reject(e){return this._resolveReject(e,!1)}_gc(){const e=[];this._queue=this._queue.filter(t=>{const n=Date.now()-t.timestamp<t.timeout;return n||e.push(t),n}),e.forEach(e=>{e.message.type===gd.CLIENT_MESSAGE&&e.reject(new Sd(gd.ERROR_RESPONSE,{error:"Timed out waiting for response",msgType:e.message.data.t,data:e.message.data.d,fatal:!1}))}),Ad.debug("[MessageDispatcher] GC",this._queue)}}var Nd={};function Ld(e){if("object"==typeof e&&null!==e&&Object.keys(e).includes("endpoint")){const t=e.endpoint;return"string"==typeof t||t instanceof URL||"undefined"!=typeof Request&&t instanceof Request}return!1}function jd(e,t){return d(this,null,function*(){let n;return t||(t=new AbortController),new Promise((r,i)=>{d(null,null,function*(){var a;e.timeout&&(n=setTimeout(()=>d(null,null,function*(){t.abort(),i(new Error("Timed out"))}),e.timeout)),Ad.debug(`[Pipecat Client] Fetching from ${e.endpoint}`),fetch(e.endpoint,{method:"POST",mode:"cors",headers:new Headers(l({"Content-Type":"application/json"},Object.fromEntries((null!=(a=e.headers)?a:new Headers).entries()))),body:JSON.stringify(e.requestData),signal:null==t?void 0:t.signal}).then(t=>{Ad.debug(`[Pipecat Client] Received response from ${e.endpoint}`,t),t.ok||i(t),t.json().then(e=>r(e))}).catch(e=>{Ad.error(`[Pipecat Client] Error fetching: ${e}`),i(e)}).finally(()=>{n&&clearTimeout(n)})})})})}Hu(Nd,"isAPIRequest",()=>Ld),Hu(Nd,"makeRequest",()=>jd);var Id={};Hu(Id,"Transport",()=>Rd),Hu(Id,"TransportWrapper",()=>Fd);class Rd{constructor(){this._state="disconnected"}connect(e){this._abortController=new AbortController;let t=e;try{t=this._validateConnectionParams(e)}catch(lr){throw new td(`Invalid connection params: ${lr.message}. Please check your connection params and try again.`)}return this._connect(t)}get startBotParams(){return this._startBotParams}set startBotParams(e){this._startBotParams=e}disconnect(){return this._abortController&&this._abortController.abort(),this._disconnect()}}class Fd{constructor(e){this._transport=e,this._proxy=new Proxy(this._transport,{get:(e,t,n)=>{if("function"==typeof e[t]){let n;switch(String(t)){case"initialize":n="Direct calls to initialize() are disabled and used internally by the PipecatClient.";break;case"initDevices":n="Direct calls to initDevices() are disabled. Please use the PipecatClient.initDevices() wrapper or let PipecatClient.connect() call it for you.";break;case"sendReadyMessage":n="Direct calls to sendReadyMessage() are disabled and used internally by the PipecatClient.";break;case"connect":n="Direct calls to connect() are disabled. Please use the PipecatClient.connect() wrapper.";break;case"disconnect":n="Direct calls to disconnect() are disabled. Please use the PipecatClient.disconnect() wrapper."}return n?()=>{throw new Error(n)}:(...n)=>e[t](...n)}return Reflect.get(e,t,n)}})}get proxy(){return this._proxy}}var Dd={};function Bd(){var e,t,n,r,i,a;let o={library:Gu.name,library_version:Gu.version,platform_details:{}},s=null;if(null==(e=null==window?void 0:window.navigator)?void 0:e.userAgent)try{s=$u.parse(window.navigator.userAgent)}catch(l){}return(null==(t=null==s?void 0:s.browser)?void 0:t.name)&&(o.platform_details.browser=s.browser.name),"Safari"!==(null==(n=null==s?void 0:s.browser)?void 0:n.name)||s.browser.version?(null==(r=null==s?void 0:s.browser)?void 0:r.version)&&(o.platform_details.browser_version=s.browser.version):o.platform_details.browser_version="Web View",(null==(i=null==s?void 0:s.platform)?void 0:i.type)&&(o.platform_details.platform_type=s.platform.type),(null==(a=null==s?void 0:s.engine)?void 0:a.name)&&(o.platform_details.engine=s.engine.name),(null==s?void 0:s.os)&&(o.platform=s.os.name,o.platform_version=s.os.version),o}Hu(Dd,"learnAboutClient",()=>Bd);var zd=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o};class Ud extends _u{}class Vd extends Ud{constructor(e){var t,n,r;super(),this._functionCallCallbacks={},this._botTranscriptionWarned=!1,kd(Bd()),this._transport=e.transport,this._transportWrapper=new Fd(this._transport);const i=c(l({},e.callbacks),{onMessageError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onMessageError)||r.call(n,t),this.emit(ud.MessageError,t)},onError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onError)||r.call(n,t);try{this.emit(ud.Error,t)}catch(lr){Ad.debug("Could not emit error",t)}const i=t.data;(null==i?void 0:i.fatal)&&(Ad.error("Fatal error reported. Disconnecting..."),this.disconnect())},onConnected:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onConnected)||n.call(t),this.emit(ud.Connected)},onDisconnected:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onDisconnected)||n.call(t),this.emit(ud.Disconnected)},onTransportStateChanged:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onTransportStateChanged)||r.call(n,t),this.emit(ud.TransportStateChanged,t)},onParticipantJoined:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onParticipantJoined)||r.call(n,t),this.emit(ud.ParticipantConnected,t)},onParticipantLeft:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onParticipantLeft)||r.call(n,t),this.emit(ud.ParticipantLeft,t)},onTrackStarted:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onTrackStarted)||i.call(r,t,n),this.emit(ud.TrackStarted,t,n)},onTrackStopped:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onTrackStopped)||i.call(r,t,n),this.emit(ud.TrackStopped,t,n)},onScreenTrackStarted:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onScreenTrackStarted)||i.call(r,t,n),this.emit(ud.ScreenTrackStarted,t,n)},onScreenTrackStopped:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onScreenTrackStopped)||i.call(r,t,n),this.emit(ud.ScreenTrackStopped,t,n)},onScreenShareError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onScreenShareError)||r.call(n,t),this.emit(ud.ScreenShareError,t)},onAvailableCamsUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableCamsUpdated)||r.call(n,t),this.emit(ud.AvailableCamsUpdated,t)},onAvailableMicsUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableMicsUpdated)||r.call(n,t),this.emit(ud.AvailableMicsUpdated,t)},onAvailableSpeakersUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onAvailableSpeakersUpdated)||r.call(n,t),this.emit(ud.AvailableSpeakersUpdated,t)},onCamUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onCamUpdated)||r.call(n,t),this.emit(ud.CamUpdated,t)},onMicUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onMicUpdated)||r.call(n,t),this.emit(ud.MicUpdated,t)},onSpeakerUpdated:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onSpeakerUpdated)||r.call(n,t),this.emit(ud.SpeakerUpdated,t)},onDeviceError:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onDeviceError)||r.call(n,t),this.emit(ud.DeviceError,t)},onBotStarted:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotStarted)||r.call(n,t),this.emit(ud.BotStarted,t)},onBotConnected:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotConnected)||r.call(n,t),this.emit(ud.BotConnected,t)},onBotReady:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotReady)||r.call(n,t),this.emit(ud.BotReady,t)},onBotDisconnected:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotDisconnected)||r.call(n,t),this.emit(ud.BotDisconnected,t)},onBotStartedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotStartedSpeaking)||n.call(t),this.emit(ud.BotStartedSpeaking)},onBotStoppedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotStoppedSpeaking)||n.call(t),this.emit(ud.BotStoppedSpeaking)},onRemoteAudioLevel:(t,n)=>{var r,i;null==(i=null==(r=null==e?void 0:e.callbacks)?void 0:r.onRemoteAudioLevel)||i.call(r,t,n),this.emit(ud.RemoteAudioLevel,t,n)},onUserStartedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onUserStartedSpeaking)||n.call(t),this.emit(ud.UserStartedSpeaking)},onUserStoppedSpeaking:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onUserStoppedSpeaking)||n.call(t),this.emit(ud.UserStoppedSpeaking)},onLocalAudioLevel:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onLocalAudioLevel)||r.call(n,t),this.emit(ud.LocalAudioLevel,t)},onUserTranscript:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onUserTranscript)||r.call(n,t),this.emit(ud.UserTranscript,t)},onBotOutput:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotOutput)||r.call(n,t),this.emit(ud.BotOutput,t)},onBotTranscript:t=>{var n,r;this._botTranscriptionWarned||(Ad.warn("[Pipecat Client] Bot transcription is deprecated. Please use the onBotOutput instead."),this._botTranscriptionWarned=!0),null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotTranscript)||r.call(n,t),this.emit(ud.BotTranscript,t)},onBotLlmText:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotLlmText)||r.call(n,t),this.emit(ud.BotLlmText,t)},onBotLlmStarted:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotLlmStarted)||n.call(t),this.emit(ud.BotLlmStarted)},onBotLlmStopped:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotLlmStopped)||n.call(t),this.emit(ud.BotLlmStopped)},onBotTtsText:t=>{var n,r;null==(r=null==(n=null==e?void 0:e.callbacks)?void 0:n.onBotTtsText)||r.call(n,t),this.emit(ud.BotTtsText,t)},onBotTtsStarted:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotTtsStarted)||n.call(t),this.emit(ud.BotTtsStarted)},onBotTtsStopped:()=>{var t,n;null==(n=null==(t=null==e?void 0:e.callbacks)?void 0:t.onBotTtsStopped)||n.call(t),this.emit(ud.BotTtsStopped)}});this._options=c(l({},e),{callbacks:i,enableMic:null==(t=e.enableMic)||t,enableCam:null!=(n=e.enableCam)&&n,enableScreenShare:null!=(r=e.enableScreenShare)&&r}),this._initialize(),Ad.debug("[Pipecat Client] Initialized",this.version)}setLogLevel(e){Ad.setLevel(e)}initDevices(){return d(this,null,function*(){Ad.debug("[Pipecat Client] Initializing devices..."),yield this._transport.initDevices()})}startBot(e){return d(this,null,function*(){var t,n,r,i,a,o;let s;this._transport.state="authenticating",this._transport.startBotParams=e,this._abortController=new AbortController;try{s=yield jd(e,this._abortController)}catch(lr){let a,o="An unknown error occurred while starting the bot.";if(lr instanceof Response){const r=yield lr.json();o=null!=(n=null!=(t=r.info)?t:r.detail)?n:lr.statusText,a=lr.status}else lr instanceof Error&&(o=lr.message);throw null==(i=null==(r=this._options.callbacks)?void 0:r.onError)||i.call(r,new Sd(gd.ERROR_RESPONSE,{message:o,fatal:!0})),new rd(o,a)}return this._transport.state="authenticated",null==(o=null==(a=this._options.callbacks)?void 0:a.onBotStarted)||o.call(a,s),s})}connect(e){return d(this,null,function*(){return e&&Ld(e)?(Ad.warn("Calling connect with an API endpoint is deprecated. Use startBotAndConnect() instead."),this.startBotAndConnect(e)):new Promise((t,n)=>{(()=>{d(this,null,function*(){this._connectResolve=t,"disconnected"===this._transport.state&&(yield this._transport.initDevices());try{yield this._transport.connect(e),yield this._transport.sendReadyMessage()}catch(lr){return this.disconnect(),void n(lr)}})})()})})}startBotAndConnect(e){return d(this,null,function*(){"disconnected"===this._transport.state&&(yield this._transport.initDevices());const t=yield this.startBot(e);return this.connect(t)})}disconnect(){return d(this,null,function*(){yield this._transport.disconnect(),this._messageDispatcher.disconnect()})}_initialize(){this._transport.initialize(this._options,this.handleMessage.bind(this)),this._messageDispatcher=new Od(this._transport.sendMessage.bind(this._transport))}get connected(){return["connected","ready"].includes(this._transport.state)}get transport(){return this._transportWrapper.proxy}get state(){return this._transport.state}get version(){return qu(Gu).version}getAllMics(){return d(this,null,function*(){return yield this._transport.getAllMics()})}getAllCams(){return d(this,null,function*(){return yield this._transport.getAllCams()})}getAllSpeakers(){return d(this,null,function*(){return yield this._transport.getAllSpeakers()})}get selectedMic(){return this._transport.selectedMic}get selectedCam(){return this._transport.selectedCam}get selectedSpeaker(){return this._transport.selectedSpeaker}updateMic(e){this._transport.updateMic(e)}updateCam(e){this._transport.updateCam(e)}updateSpeaker(e){this._transport.updateSpeaker(e)}enableMic(e){this._transport.enableMic(e)}get isMicEnabled(){return this._transport.isMicEnabled}enableCam(e){this._transport.enableCam(e)}get isCamEnabled(){return this._transport.isCamEnabled}tracks(){return this._transport.tracks()}enableScreenShare(e){return this._transport.enableScreenShare(e)}get isSharingScreen(){return this._transport.isSharingScreen}sendClientMessage(e,t){this._transport.sendMessage(new Sd(gd.CLIENT_MESSAGE,{t:e,d:t}))}sendClientRequest(e,t,n){return d(this,null,function*(){const r={t:e,d:t};return(yield this._messageDispatcher.dispatch(r,gd.CLIENT_MESSAGE,n)).data.d})}registerFunctionCallHandler(e,t){this._functionCallCallbacks[e]=t}unregisterFunctionCallHandler(e){delete this._functionCallCallbacks[e]}unregisterAllFunctionCallHandlers(){this._functionCallCallbacks={}}appendToContext(e){return d(this,null,function*(){return Ad.warn("appendToContext() is deprecated. Use sendText() instead."),yield this._transport.sendMessage(new Sd(gd.APPEND_TO_CONTEXT,{role:e.role,content:e.content,run_immediately:e.run_immediately})),!0})}sendText(e){return d(this,arguments,function*(e,t={}){yield this._transport.sendMessage(new Sd(gd.SEND_TEXT,{content:e,options:t}))})}disconnectBot(){this._transport.sendMessage(new Sd(gd.DISCONNECT_BOT,{}))}handleMessage(e){var t,n,r,i,a,o,s,l,c,u,d,f,p,h,m,g,v,y,b,w,k,S,_,x,E,C,T,M,P,A,O,N,L,j,I,R,F,D,B,z,U;switch(Ad.debug("[RTVI Message]",e),e.type){case gd.BOT_READY:{const i=e.data,a=i.version?i.version.split(".").map(Number):[0,0,0];Ad.debug(`[Pipecat Client] Bot is ready. Version: ${i.version}`),a[0]<1&&Ad.warn("[Pipecat Client] Bot version is less than 1.0.0, which may not be compatible with this client."),null==(t=this._connectResolve)||t.call(this,e.data),null==(r=null==(n=this._options.callbacks)?void 0:n.onBotReady)||r.call(n,e.data);break}case gd.ERROR:null==(a=null==(i=this._options.callbacks)?void 0:i.onError)||a.call(i,e);break;case gd.SERVER_RESPONSE:this._messageDispatcher.resolve(e);break;case gd.ERROR_RESPONSE:{const t=this._messageDispatcher.reject(e);null==(s=null==(o=this._options.callbacks)?void 0:o.onMessageError)||s.call(o,t);break}case gd.USER_STARTED_SPEAKING:null==(c=null==(l=this._options.callbacks)?void 0:l.onUserStartedSpeaking)||c.call(l);break;case gd.USER_STOPPED_SPEAKING:null==(d=null==(u=this._options.callbacks)?void 0:u.onUserStoppedSpeaking)||d.call(u);break;case gd.BOT_STARTED_SPEAKING:null==(p=null==(f=this._options.callbacks)?void 0:f.onBotStartedSpeaking)||p.call(f);break;case gd.BOT_STOPPED_SPEAKING:null==(m=null==(h=this._options.callbacks)?void 0:h.onBotStoppedSpeaking)||m.call(h);break;case gd.USER_TRANSCRIPTION:{const t=e.data;null==(v=null==(g=this._options.callbacks)?void 0:g.onUserTranscript)||v.call(g,t);break}case gd.BOT_OUTPUT:null==(b=null==(y=this._options.callbacks)?void 0:y.onBotOutput)||b.call(y,e.data);break;case gd.BOT_TRANSCRIPTION:null==(k=null==(w=this._options.callbacks)?void 0:w.onBotTranscript)||k.call(w,e.data);break;case gd.BOT_LLM_TEXT:null==(_=null==(S=this._options.callbacks)?void 0:S.onBotLlmText)||_.call(S,e.data);break;case gd.BOT_LLM_STARTED:null==(E=null==(x=this._options.callbacks)?void 0:x.onBotLlmStarted)||E.call(x);break;case gd.BOT_LLM_STOPPED:null==(T=null==(C=this._options.callbacks)?void 0:C.onBotLlmStopped)||T.call(C);break;case gd.BOT_TTS_TEXT:null==(P=null==(M=this._options.callbacks)?void 0:M.onBotTtsText)||P.call(M,e.data);break;case gd.BOT_TTS_STARTED:null==(O=null==(A=this._options.callbacks)?void 0:A.onBotTtsStarted)||O.call(A);break;case gd.BOT_TTS_STOPPED:null==(L=null==(N=this._options.callbacks)?void 0:N.onBotTtsStopped)||L.call(N);break;case gd.METRICS:null==(I=null==(j=this._options.callbacks)?void 0:j.onMetrics)||I.call(j,e.data),this.emit(ud.Metrics,e.data);break;case gd.SERVER_MESSAGE:null==(F=null==(R=this._options.callbacks)?void 0:R.onServerMessage)||F.call(R,e.data),this.emit(ud.ServerMessage,e.data);break;case gd.LLM_FUNCTION_CALL:{const t=e.data,n=this._functionCallCallbacks[t.function_name];if(n){n({functionName:t.function_name,arguments:t.args}).then(e=>{null!=e&&this._transport.sendMessage(new Sd(gd.LLM_FUNCTION_CALL_RESULT,{function_name:t.function_name,tool_call_id:t.tool_call_id,arguments:t.args,result:e}))})}null==(B=null==(D=this._options.callbacks)?void 0:D.onLLMFunctionCall)||B.call(D,t),this.emit(ud.LLMFunctionCall,t);break}case gd.BOT_LLM_SEARCH_RESPONSE:{const t=e.data;null==(U=null==(z=this._options.callbacks)?void 0:z.onBotLlmSearchResponse)||U.call(z,t),this.emit(ud.BotLlmSearchResponse,t);break}default:Ad.debug("[Pipecat Client] Unrecognized message type",e.type)}}}function $d(e){return e&&e.__esModule?e.default:e}function Wd(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}zd([xd],Vd.prototype,"startBot",null),zd([xd],Vd.prototype,"connect",null),zd([xd],Vd.prototype,"startBotAndConnect",null),zd([_d],Vd.prototype,"sendClientMessage",null),zd([_d],Vd.prototype,"sendClientRequest",null),zd([_d],Vd.prototype,"appendToContext",null),zd([_d],Vd.prototype,"sendText",null),zd([_d],Vd.prototype,"disconnectBot",null),Wu(Ju,Qu),Wu(Ju,Ed),Wu(Ju,Md),Wu(Ju,Nd),Wu(Ju,Id),Wu(Ju,Dd);var qd={};Wd(qd,"DailyRTVIMessageType",()=>lf),Wd(qd,"DailyTransport",()=>df);class Hd{static floatTo16BitPCM(e){const t=new ArrayBuffer(2*e.length),n=new DataView(t);let r=0;for(let i=0;i<e.length;i++,r+=2){let t=Math.max(-1,Math.min(1,e[i]));n.setInt16(r,t<0?32768*t:32767*t,!0)}return t}static mergeBuffers(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}_packData(e,t){return[new Uint8Array([t,t>>8]),new Uint8Array([t,t>>8,t>>16,t>>24])][e]}pack(e,t){if(!(null==t?void 0:t.bitsPerSample))throw new Error('Missing "bitsPerSample"');if(!(null==t?void 0:t.channels))throw new Error('Missing "channels"');if(!(null==t?void 0:t.data))throw new Error('Missing "data"');const{bitsPerSample:n,channels:r,data:i}=t,a=["RIFF",this._packData(1,52),"WAVE","fmt ",this._packData(1,16),this._packData(0,1),this._packData(0,r.length),this._packData(1,e),this._packData(1,e*r.length*n/8),this._packData(0,r.length*n/8),this._packData(0,n),"data",this._packData(1,r[0].length*r.length*n/8),i],o=new Blob(a,{type:"audio/mpeg"});return{blob:o,url:URL.createObjectURL(o),channelCount:r.length,sampleRate:e,duration:i.byteLength/(r.length*e*2)}}}globalThis.WavPacker=Hd;const Jd=[4186.01,4434.92,4698.63,4978.03,5274.04,5587.65,5919.91,6271.93,6644.88,7040,7458.62,7902.13],Qd=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Gd=[],Yd=[];for(let _f=1;_f<=8;_f++)for(let e=0;e<Jd.length;e++){const t=Jd[e];Gd.push(t/Math.pow(2,8-_f)),Yd.push(Qd[e]+_f)}const Kd=[32,2e3],Xd=Gd.filter((e,t)=>Gd[t]>Kd[0]&&Gd[t]<Kd[1]),Zd=Yd.filter((e,t)=>Gd[t]>Kd[0]&&Gd[t]<Kd[1]);class ef{static getFrequencies(e,t,n,r="frequency",i=-100,a=-30){n||(n=new Float32Array(e.frequencyBinCount),e.getFloatFrequencyData(n));const o=t/2,s=1/n.length*o;let l,c,u;if("music"===r||"voice"===r){const e="voice"===r?Xd:Gd,t=Array(e.length).fill(i);for(let r=0;r<n.length;r++){const i=r*s,a=n[r];for(let n=e.length-1;n>=0;n--)if(i>e[n]){t[n]=Math.max(t[n],a);break}}l=t,c="voice"===r?Xd:Gd,u="voice"===r?Zd:Yd}else l=Array.from(n),c=l.map((e,t)=>s*t),u=c.map(e=>`${e.toFixed(2)} Hz`);const d=l.map(e=>Math.max(0,Math.min((e-i)/(a-i),1)));return{values:new Float32Array(d),frequencies:c,labels:u}}constructor(e,t=null){if(this.fftResults=[],t){const{length:n,sampleRate:r}=t,i=new OfflineAudioContext({length:n,sampleRate:r}),a=i.createBufferSource();a.buffer=t;const o=i.createAnalyser();o.fftSize=8192,o.smoothingTimeConstant=.1,a.connect(o);const s=1/60,l=n/r,c=e=>{const t=s*e;t<l&&i.suspend(t).then(()=>{const t=new Float32Array(o.frequencyBinCount);o.getFloatFrequencyData(t),this.fftResults.push(t),c(e+1)}),1===e?i.startRendering():i.resume()};a.start(0),c(1),this.audio=e,this.context=i,this.analyser=o,this.sampleRate=r,this.audioBuffer=t}else{const t=new AudioContext,n=t.createMediaElementSource(e),r=t.createAnalyser();r.fftSize=8192,r.smoothingTimeConstant=.1,n.connect(r),r.connect(t.destination),this.audio=e,this.context=t,this.analyser=r,this.sampleRate=this.context.sampleRate,this.audioBuffer=null}}getFrequencies(e="frequency",t=-100,n=-30){let r=null;if(this.audioBuffer&&this.fftResults.length){const e=this.audio.currentTime/this.audio.duration,t=Math.min(e*this.fftResults.length|0,this.fftResults.length-1);r=this.fftResults[t]}return ef.getFrequencies(this.analyser,this.sampleRate,r,e,t,n)}resumeIfSuspended(){return d(this,null,function*(){return"suspended"===this.context.state&&(yield this.context.resume()),!0})}}globalThis.AudioAnalysis=ef;const tf=new Blob(["\nclass StreamProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.hasStarted = false;\n this.hasInterrupted = false;\n this.outputBuffers = [];\n this.bufferLength = 128;\n this.write = { buffer: new Float32Array(this.bufferLength), trackId: null };\n this.writeOffset = 0;\n this.trackSampleOffsets = {};\n this.port.onmessage = (event) => {\n if (event.data) {\n const payload = event.data;\n if (payload.event === 'write') {\n const int16Array = payload.buffer;\n const float32Array = new Float32Array(int16Array.length);\n for (let i = 0; i < int16Array.length; i++) {\n float32Array[i] = int16Array[i] / 0x8000; // Convert Int16 to Float32\n }\n this.writeData(float32Array, payload.trackId);\n } else if (\n payload.event === 'offset' ||\n payload.event === 'interrupt'\n ) {\n const requestId = payload.requestId;\n const trackId = this.write.trackId;\n const offset = this.trackSampleOffsets[trackId] || 0;\n this.port.postMessage({\n event: 'offset',\n requestId,\n trackId,\n offset,\n });\n if (payload.event === 'interrupt') {\n this.hasInterrupted = true;\n }\n } else {\n throw new Error(`Unhandled event \"${payload.event}\"`);\n }\n }\n };\n }\n\n writeData(float32Array, trackId = null) {\n let { buffer } = this.write;\n let offset = this.writeOffset;\n for (let i = 0; i < float32Array.length; i++) {\n buffer[offset++] = float32Array[i];\n if (offset >= buffer.length) {\n this.outputBuffers.push(this.write);\n this.write = { buffer: new Float32Array(this.bufferLength), trackId };\n buffer = this.write.buffer;\n offset = 0;\n }\n }\n this.writeOffset = offset;\n return true;\n }\n\n process(inputs, outputs, parameters) {\n const output = outputs[0];\n const outputChannelData = output[0];\n const outputBuffers = this.outputBuffers;\n if (this.hasInterrupted) {\n this.port.postMessage({ event: 'stop' });\n return false;\n } else if (outputBuffers.length) {\n this.hasStarted = true;\n const { buffer, trackId } = outputBuffers.shift();\n for (let i = 0; i < outputChannelData.length; i++) {\n outputChannelData[i] = buffer[i] || 0;\n }\n if (trackId) {\n this.trackSampleOffsets[trackId] =\n this.trackSampleOffsets[trackId] || 0;\n this.trackSampleOffsets[trackId] += buffer.length;\n }\n return true;\n } else if (this.hasStarted) {\n this.port.postMessage({ event: 'stop' });\n return false;\n } else {\n return true;\n }\n }\n}\n\nregisterProcessor('stream_processor', StreamProcessor);\n"],{type:"application/javascript"}),nf=URL.createObjectURL(tf);globalThis.WavStreamPlayer=class{constructor({sampleRate:e=44100}={}){this.scriptSrc=nf,this.sampleRate=e,this.context=null,this.stream=null,this.analyser=null,this.trackSampleOffsets={},this.interruptedTrackIds={}}connect(){return d(this,null,function*(){this.context=new AudioContext({sampleRate:this.sampleRate}),this._speakerID&&this.context.setSinkId(this._speakerID),"suspended"===this.context.state&&(yield this.context.resume());try{yield this.context.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const e=this.context.createAnalyser();return e.fftSize=8192,e.smoothingTimeConstant=.1,this.analyser=e,!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.analyser)throw new Error("Not connected, please call .connect() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}updateSpeaker(e){return d(this,null,function*(){const t=this._speakerID;if(this._speakerID=e,this.context)try{"default"===e?yield this.context.setSinkId():yield this.context.setSinkId(e)}catch(lr){console.error(`Could not set sinkId to ${e}: ${lr}`),this._speakerID=t}})}_start(){const e=new AudioWorkletNode(this.context,"stream_processor");return e.connect(this.context.destination),e.port.onmessage=t=>{const{event:n}=t.data;if("stop"===n)e.disconnect(),this.stream=null;else if("offset"===n){const{requestId:e,trackId:n,offset:r}=t.data,i=r/this.sampleRate;this.trackSampleOffsets[e]={trackId:n,offset:r,currentTime:i}}},this.analyser.disconnect(),e.connect(this.analyser),this.stream=e,!0}add16BitPCM(e,t="default"){if("string"!=typeof t)throw new Error("trackId must be a string");if(this.interruptedTrackIds[t])return;let n;if(this.stream||this._start(),e instanceof Int16Array)n=e;else{if(!(e instanceof ArrayBuffer))throw new Error("argument must be Int16Array or ArrayBuffer");n=new Int16Array(e)}return this.stream.port.postMessage({event:"write",buffer:n,trackId:t}),n}getTrackSampleOffset(e=!1){return d(this,null,function*(){if(!this.stream)return null;const t=crypto.randomUUID();let n;for(this.stream.port.postMessage({event:e?"interrupt":"offset",requestId:t});!n;)n=this.trackSampleOffsets[t],yield new Promise(e=>setTimeout(()=>e(),1));const{trackId:r}=n;return e&&r&&(this.interruptedTrackIds[r]=!0),n})}interrupt(){return d(this,null,function*(){return this.getTrackSampleOffset(!0)})}};const rf=new Blob(["\nclass AudioProcessor extends AudioWorkletProcessor {\n\n constructor() {\n super();\n this.port.onmessage = this.receive.bind(this);\n this.initialize();\n }\n\n initialize() {\n this.foundAudio = false;\n this.recording = false;\n this.chunks = [];\n }\n\n /**\n * Concatenates sampled chunks into channels\n * Format is chunk[Left[], Right[]]\n */\n readChannelData(chunks, channel = -1, maxChannels = 9) {\n let channelLimit;\n if (channel !== -1) {\n if (chunks[0] && chunks[0].length - 1 < channel) {\n throw new Error(\n `Channel ${channel} out of range: max ${chunks[0].length}`\n );\n }\n channelLimit = channel + 1;\n } else {\n channel = 0;\n channelLimit = Math.min(chunks[0] ? chunks[0].length : 1, maxChannels);\n }\n const channels = [];\n for (let n = channel; n < channelLimit; n++) {\n const length = chunks.reduce((sum, chunk) => {\n return sum + chunk[n].length;\n }, 0);\n const buffers = chunks.map((chunk) => chunk[n]);\n const result = new Float32Array(length);\n let offset = 0;\n for (let i = 0; i < buffers.length; i++) {\n result.set(buffers[i], offset);\n offset += buffers[i].length;\n }\n channels[n] = result;\n }\n return channels;\n }\n\n /**\n * Combines parallel audio data into correct format,\n * channels[Left[], Right[]] to float32Array[LRLRLRLR...]\n */\n formatAudioData(channels) {\n if (channels.length === 1) {\n // Simple case is only one channel\n const float32Array = channels[0].slice();\n const meanValues = channels[0].slice();\n return { float32Array, meanValues };\n } else {\n const float32Array = new Float32Array(\n channels[0].length * channels.length\n );\n const meanValues = new Float32Array(channels[0].length);\n for (let i = 0; i < channels[0].length; i++) {\n const offset = i * channels.length;\n let meanValue = 0;\n for (let n = 0; n < channels.length; n++) {\n float32Array[offset + n] = channels[n][i];\n meanValue += channels[n][i];\n }\n meanValues[i] = meanValue / channels.length;\n }\n return { float32Array, meanValues };\n }\n }\n\n /**\n * Converts 32-bit float data to 16-bit integers\n */\n floatTo16BitPCM(float32Array) {\n const buffer = new ArrayBuffer(float32Array.length * 2);\n const view = new DataView(buffer);\n let offset = 0;\n for (let i = 0; i < float32Array.length; i++, offset += 2) {\n let s = Math.max(-1, Math.min(1, float32Array[i]));\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n\n /**\n * Retrieves the most recent amplitude values from the audio stream\n * @param {number} channel\n */\n getValues(channel = -1) {\n const channels = this.readChannelData(this.chunks, channel);\n const { meanValues } = this.formatAudioData(channels);\n return { meanValues, channels };\n }\n\n /**\n * Exports chunks as an audio/wav file\n */\n export() {\n const channels = this.readChannelData(this.chunks);\n const { float32Array, meanValues } = this.formatAudioData(channels);\n const audioData = this.floatTo16BitPCM(float32Array);\n return {\n meanValues: meanValues,\n audio: {\n bitsPerSample: 16,\n channels: channels,\n data: audioData,\n },\n };\n }\n\n receive(e) {\n const { event, id } = e.data;\n let receiptData = {};\n switch (event) {\n case 'start':\n this.recording = true;\n break;\n case 'stop':\n this.recording = false;\n break;\n case 'clear':\n this.initialize();\n break;\n case 'export':\n receiptData = this.export();\n break;\n case 'read':\n receiptData = this.getValues();\n break;\n default:\n break;\n }\n // Always send back receipt\n this.port.postMessage({ event: 'receipt', id, data: receiptData });\n }\n\n sendChunk(chunk) {\n const channels = this.readChannelData([chunk]);\n const { float32Array, meanValues } = this.formatAudioData(channels);\n const rawAudioData = this.floatTo16BitPCM(float32Array);\n const monoAudioData = this.floatTo16BitPCM(meanValues);\n this.port.postMessage({\n event: 'chunk',\n data: {\n mono: monoAudioData,\n raw: rawAudioData,\n },\n });\n }\n\n process(inputList, outputList, parameters) {\n // Copy input to output (e.g. speakers)\n // Note that this creates choppy sounds with Mac products\n const sourceLimit = Math.min(inputList.length, outputList.length);\n for (let inputNum = 0; inputNum < sourceLimit; inputNum++) {\n const input = inputList[inputNum];\n const output = outputList[inputNum];\n const channelCount = Math.min(input.length, output.length);\n for (let channelNum = 0; channelNum < channelCount; channelNum++) {\n input[channelNum].forEach((sample, i) => {\n output[channelNum][i] = sample;\n });\n }\n }\n const inputs = inputList[0];\n // There's latency at the beginning of a stream before recording starts\n // Make sure we actually receive audio data before we start storing chunks\n let sliceIndex = 0;\n if (!this.foundAudio) {\n for (const channel of inputs) {\n sliceIndex = 0; // reset for each channel\n if (this.foundAudio) {\n break;\n }\n if (channel) {\n for (const value of channel) {\n if (value !== 0) {\n // find only one non-zero entry in any channel\n this.foundAudio = true;\n break;\n } else {\n sliceIndex++;\n }\n }\n }\n }\n }\n if (inputs && inputs[0] && this.foundAudio && this.recording) {\n // We need to copy the TypedArray, because the `process`\n // internals will reuse the same buffer to hold each input\n const chunk = inputs.map((input) => input.slice(sliceIndex));\n this.chunks.push(chunk);\n this.sendChunk(chunk);\n }\n return true;\n }\n}\n\nregisterProcessor('audio_processor', AudioProcessor);\n"],{type:"application/javascript"}),af=URL.createObjectURL(rf);globalThis.WavRecorder=class{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:n=!1}={}){this.scriptSrc=af,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!n,this._deviceChangeCallback=null,this._deviceErrorCallback=null,this._devices=[],this.deviceSelection=null,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}static decode(e,t=44100,n=-1){return d(this,null,function*(){const r=new AudioContext({sampleRate:t});let i,a;if(e instanceof Blob){if(-1!==n)throw new Error('Can not specify "fromSampleRate" when reading from Blob');a=e,i=yield a.arrayBuffer()}else if(e instanceof ArrayBuffer){if(-1!==n)throw new Error('Can not specify "fromSampleRate" when reading from ArrayBuffer');i=e,a=new Blob([i],{type:"audio/wav"})}else{let t,r;if(e instanceof Int16Array){r=e,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768}else if(e instanceof Float32Array)t=e;else{if(!(e instanceof Array))throw new Error('"audioData" must be one of: Blob, Float32Arrray, Int16Array, ArrayBuffer, Array<number>');t=new Float32Array(e)}if(-1===n)throw new Error('Must specify "fromSampleRate" when reading from Float32Array, In16Array or Array');if(n<3e3)throw new Error('Minimum "fromSampleRate" is 3000 (3kHz)');r||(r=Hd.floatTo16BitPCM(t));const o={bitsPerSample:16,channels:[t],data:r};a=(new Hd).pack(n,o).blob,i=yield a.arrayBuffer()}const o=yield r.decodeAudioData(i),s=o.getChannelData(0);return{blob:a,url:URL.createObjectURL(a),values:s,audioBuffer:o}})}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}_event(e){return d(this,arguments,function*(e,t={},n=null){if(!(n=n||this.processor))throw new Error("Can not send events without recording first");const r={event:e,id:this._lastEventId++,data:t};n.port.postMessage(r);const i=(new Date).valueOf();for(;!this.eventReceipts[r.id];){if((new Date).valueOf()-i>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);yield new Promise(e=>setTimeout(()=>e(!0),1))}const a=this.eventReceipts[r.id];return delete this.eventReceipts[r.id],a})}listenForDeviceChange(e){if(null===e&&this._deviceChangeCallback)navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeCallback),this._deviceChangeCallback=null;else if(null!==e){let t=0,n=[];const r=e=>e.map(e=>e.deviceId).sort().join(","),i=()=>d(this,null,function*(){let i=++t;const a=yield this.listDevices();i===t&&r(n)!==r(a)&&(n=a,e(a.slice()))});navigator.mediaDevices.addEventListener("devicechange",i),i(),this._deviceChangeCallback=i}return!0}listenForDeviceErrors(e){this._deviceErrorCallback=e}requestPermission(){return d(this,null,function*(){const e=yield navigator.permissions.query({name:"microphone"});if("denied"===e.state)this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:new Error("Microphone access denied")});else if("prompt"===e.state)try{const e=yield navigator.mediaDevices.getUserMedia({audio:!0});e.getTracks().forEach(e=>e.stop())}catch(lr){console.error("Error accessing microphone."),this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:lr})}return!0})}listDevices(){return d(this,null,function*(){if(!navigator.mediaDevices||!("enumerateDevices"in navigator.mediaDevices))throw new Error("Could not request user devices");yield this.requestPermission();return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind)})}begin(e){return d(this,null,function*(){var t;if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!navigator.mediaDevices||!("getUserMedia"in navigator.mediaDevices))throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic","cam"],type:"undefined-mediadevices"}),new Error("Could not request user media");e=null!=e?e:null==(t=this.deviceSelection)?void 0:t.deviceId;try{const t={audio:!0};e&&(t.audio={deviceId:{exact:e}}),this.stream=yield navigator.mediaDevices.getUserMedia(t)}catch(s){throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:s}),new Error("Could not start media stream")}this.listDevices().then(t=>{e=this.stream.getAudioTracks()[0].getSettings().deviceId,console.log("find current device",t,e,this.stream.getAudioTracks()[0].getSettings()),this.deviceSelection=t.find(t=>t.deviceId===e),console.log("current device",this.deviceSelection)});const n=new AudioContext({sampleRate:this.sampleRate}),r=n.createMediaStreamSource(this.stream);try{yield n.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const i=new AudioWorkletNode(n,"audio_processor");i.port.onmessage=e=>{const{event:t,id:n,data:r}=e.data;if("receipt"===t)this.eventReceipts[n]=r;else if("chunk"===t)if(this._chunkProcessorSize){const e=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:Hd.mergeBuffers(e.raw,r.raw),mono:Hd.mergeBuffers(e.mono,r.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(r)};const a=r.connect(i),o=n.createAnalyser();return o.fftSize=8192,o.smoothingTimeConstant=.1,a.connect(o),this.outputToSpeakers&&(console.warn("Warning: Output to speakers may affect sound quality,\nespecially due to system audio feedback preventative measures.\nuse only for debugging"),o.connect(n.destination)),this.source=r,this.node=a,this.analyser=o,this.processor=i,console.log("begin completed"),!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}pause(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!this.recording)throw new Error("Already paused: please call .record() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),yield this._event("stop"),this.recording=!1,!0})}record(e=()=>{},t=8192){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(this.recording)throw new Error("Already recording: please call .pause() first");if("function"!=typeof e)throw new Error("chunkProcessor must be a function");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),yield this._event("start"),this.recording=!0,!0})}clear(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return yield this._event("clear"),!0})}read(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");this.log("Reading ...");return yield this._event("read")})}save(e=!1){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=yield this._event("export");return(new Hd).pack(this.sampleRate,t.audio)})}end(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),yield this._event("stop"),this.recording=!1;this.stream.getTracks().forEach(e=>e.stop()),this.log("Exporting ...");const t=yield this._event("export",{},e);this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null;return(new Hd).pack(this.sampleRate,t.audio)})}quit(){return d(this,null,function*(){return this.listenForDeviceChange(null),this.deviceSelection=null,this.processor&&(yield this.end()),!0})}};class of{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:n=!1}={}){this.scriptSrc=af,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!n,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}_event(e){return d(this,arguments,function*(e,t={},n=null){if(!(n=n||this.processor))throw new Error("Can not send events without recording first");const r={event:e,id:this._lastEventId++,data:t};n.port.postMessage(r);const i=(new Date).valueOf();for(;!this.eventReceipts[r.id];){if((new Date).valueOf()-i>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);yield new Promise(e=>setTimeout(()=>e(!0),1))}const a=this.eventReceipts[r.id];return delete this.eventReceipts[r.id],a})}begin(e){return d(this,null,function*(){if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!e||"audio"!==e.kind)throw new Error("No audio track provided");this.stream=new MediaStream([e]);const t=new AudioContext({sampleRate:this.sampleRate}),n=t.createMediaStreamSource(this.stream);try{yield t.audioWorklet.addModule(this.scriptSrc)}catch(lr){throw console.error(lr),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const r=new AudioWorkletNode(t,"audio_processor");r.port.onmessage=e=>{const{event:t,id:n,data:r}=e.data;if("receipt"===t)this.eventReceipts[n]=r;else if("chunk"===t)if(this._chunkProcessorSize){const e=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:Hd.mergeBuffers(e.raw,r.raw),mono:Hd.mergeBuffers(e.mono,r.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(r)};const i=n.connect(r),a=t.createAnalyser();return a.fftSize=8192,a.smoothingTimeConstant=.1,i.connect(a),this.outputToSpeakers&&(console.warn("Warning: Output to speakers may affect sound quality,\nespecially due to system audio feedback preventative measures.\nuse only for debugging"),a.connect(t.destination)),this.source=n,this.node=i,this.analyser=a,this.processor=r,!0})}getFrequencies(e="frequency",t=-100,n=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return ef.getFrequencies(this.analyser,this.sampleRate,null,e,t,n)}pause(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!this.recording)throw new Error("Already paused: please call .record() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),yield this._event("stop"),this.recording=!1,!0})}record(e=()=>{},t=8192){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(this.recording)throw new Error("Already recording: HELLO please call .pause() first");if("function"!=typeof e)throw new Error("chunkProcessor must be a function");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),yield this._event("start"),this.recording=!0,!0})}clear(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return yield this._event("clear"),!0})}read(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");this.log("Reading ...");return yield this._event("read")})}save(e=!1){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=yield this._event("export");return(new Hd).pack(this.sampleRate,t.audio)})}end(){return d(this,null,function*(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),yield this._event("stop"),this.recording=!1,this.log("Exporting ...");const t=yield this._event("export",{},e);this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null;return(new Hd).pack(this.sampleRate,t.audio)})}quit(){return d(this,null,function*(){return this.listenForDeviceChange(null),this.processor&&(yield this.end()),!0})}}globalThis.WavRecorder=WavRecorder;var sf,lf,cf;sf=JSON.parse('{"name":"@pipecat-ai/daily-transport","version":"1.5.0","license":"BSD-2-Clause","main":"dist/index.js","module":"dist/index.module.js","types":"dist/index.d.ts","source":"src/index.ts","repository":{"type":"git","url":"git+https://github.com/pipecat-ai/pipecat-client-web-transports.git"},"files":["dist","package.json","README.md"],"scripts":{"build":"parcel build --no-cache","dev":"parcel watch","lint":"eslint . --ext ts --report-unused-disable-directives --max-warnings 0"},"devDependencies":{"@pipecat-ai/client-js":"^1.5.0","eslint":"9.39.1","eslint-config-prettier":"^9.1.0","eslint-plugin-simple-import-sort":"^12.1.1"},"peerDependencies":{"@pipecat-ai/client-js":"~1.5.0"},"dependencies":{"@daily-co/daily-js":"^0.84.0"},"description":"Pipecat Daily Transport Package","author":"Daily.co","bugs":{"url":"https://github.com/pipecat-ai/pipecat-client-web-transports/issues"},"homepage":"https://github.com/pipecat-ai/pipecat-client-web-transports/blob/main/transports/daily-webrtc/README.md"}'),(cf=lf||(lf={})).AUDIO_BUFFERING_STARTED="audio-buffering-started",cf.AUDIO_BUFFERING_STOPPED="audio-buffering-stopped";class uf{constructor(e){this._daily=e,this._proxy=new Proxy(this._daily,{get:(e,t,n)=>{if("function"==typeof e[t]){let n;switch(String(t)){case"preAuth":n="Calls to preAuth() are disabled. Please use Transport.preAuth()";break;case"startCamera":n="Calls to startCamera() are disabled. Please use PipecatClient.initDevices()";break;case"join":n="Calls to join() are disabled. Please use PipecatClient.connect()";break;case"leave":n="Calls to leave() are disabled. Please use PipecatClient.disconnect()";break;case"destroy":n="Calls to destroy() are disabled."}return n?()=>{throw new Error(n)}:(...n)=>e[t](...n)}return Reflect.get(e,t,n)}})}get proxy(){return this._proxy}}class df extends Rd{constructor(e={}){var t;super(),this._botId="",this._selectedCam={},this._selectedMic={},this._selectedSpeaker={},this._currentAudioTrack=null,this._audioQueue=[],this._callbacks={};const n=e,{bufferLocalAudioUntilBotReady:r}=n,i=u(n,["bufferLocalAudioUntilBotReady"]);this._dailyFactoryOptions=i,void 0===(null==(t=this._dailyFactoryOptions.dailyConfig)?void 0:t.useDevicePreferenceCookies)&&(null==this._dailyFactoryOptions.dailyConfig&&(this._dailyFactoryOptions.dailyConfig={}),this._dailyFactoryOptions.dailyConfig.useDevicePreferenceCookies=!0),this._bufferLocalAudioUntilBotReady=r||!1,this._daily=qc.createCallObject(c(l({},this._dailyFactoryOptions),{allowMultipleCallInstances:!0})),this._dailyWrapper=new uf(this._daily)}setupRecorder(){this._mediaStreamRecorder=new of({sampleRate:df.RECORDER_SAMPLE_RATE})}handleUserAudioStream(e){this._audioQueue.push(e)}flushAudioQueue(){if(0!==this._audioQueue.length)for(Ad.debug(`Will flush audio queue: ${this._audioQueue.length}`);this._audioQueue.length>0;){const e=[];for(;e.length<10&&this._audioQueue.length>0;){const t=this._audioQueue.shift();t&&e.push(t)}e.length>0&&this._sendAudioBatch(e)}}_sendAudioBatch(e){const t={id:"raw-audio-batch",label:"rtvi-ai",type:"raw-audio-batch",data:{base64AudioBatch:e.map(e=>{const t=new Uint8Array(e);return btoa(String.fromCharCode(...t))}),sampleRate:df.RECORDER_SAMPLE_RATE,numChannels:1}};this.sendMessage(t)}initialize(e,t){var n,r,i;this._bufferLocalAudioUntilBotReady&&this.setupRecorder(),this._callbacks=null!=(n=e.callbacks)?n:{},this._onMessage=t,null!=this._dailyFactoryOptions.startVideoOff&&null==e.enableCam||(this._dailyFactoryOptions.startVideoOff=!(null!=(r=e.enableCam)&&r)),null!=this._dailyFactoryOptions.startAudioOff&&null==e.enableMic||(this._dailyFactoryOptions.startAudioOff=!(null==(i=e.enableMic)||i)),this.attachEventListeners(),this.state="disconnected",Ad.debug("[Daily Transport] Initialized",$d(sf).version)}get dailyCallClient(){return this._dailyWrapper.proxy}get state(){return this._state}set state(e){var t,n;this._state!==e&&(this._state=e,null==(n=(t=this._callbacks).onTransportStateChanged)||n.call(t,e))}getSessionInfo(){return this._daily.meetingSessionSummary()}getAllCams(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"videoinput"===e.kind)})}updateCam(e){this._daily.setInputDevicesAsync({videoDeviceId:e}).then(e=>{this._selectedCam=e.camera})}get selectedCam(){return this._selectedCam}getAllMics(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"audioinput"===e.kind)})}updateMic(e){this._daily.setInputDevicesAsync({audioDeviceId:e}).then(e=>{this._selectedMic=e.mic})}get selectedMic(){return this._selectedMic}getAllSpeakers(){return d(this,null,function*(){const{devices:e}=yield this._daily.enumerateDevices();return e.filter(e=>"audiooutput"===e.kind)})}updateSpeaker(e){this._daily.setOutputDeviceAsync({outputDeviceId:e}).then(e=>{this._selectedSpeaker=e.speaker}).catch(e=>{var t,n,r;null==(r=(n=this._callbacks).onDeviceError)||r.call(n,new cd(["speaker"],null!=(t=e.type)?t:"unknown",e.message))})}get selectedSpeaker(){return this._selectedSpeaker}enableMic(e){this._daily.setLocalAudio(e)}get isMicEnabled(){return this._daily.localAudio()}enableCam(e){this._daily.setLocalVideo(e)}get isCamEnabled(){return this._daily.localVideo()}enableScreenShare(e){e?this._daily.startScreenShare():this._daily.stopScreenShare()}get isSharingScreen(){return this._daily.localScreenAudio()||this._daily.localScreenVideo()}tracks(){var e,t,n,r,i,a,o,s,l,c,u,d,f,p,h,m,g;const v=null!=(e=this._daily.participants())?e:{},y=null==v?void 0:v[this._botId],b={local:{audio:null==(r=null==(n=null==(t=null==v?void 0:v.local)?void 0:t.tracks)?void 0:n.audio)?void 0:r.persistentTrack,screenAudio:null==(o=null==(a=null==(i=null==v?void 0:v.local)?void 0:i.tracks)?void 0:a.screenAudio)?void 0:o.persistentTrack,screenVideo:null==(c=null==(l=null==(s=null==v?void 0:v.local)?void 0:s.tracks)?void 0:l.screenVideo)?void 0:c.persistentTrack,video:null==(f=null==(d=null==(u=null==v?void 0:v.local)?void 0:u.tracks)?void 0:d.video)?void 0:f.persistentTrack}};return y&&(b.bot={audio:null==(h=null==(p=null==y?void 0:y.tracks)?void 0:p.audio)?void 0:h.persistentTrack,video:null==(g=null==(m=null==y?void 0:y.tracks)?void 0:m.video)?void 0:g.persistentTrack}),b}startRecording(){return d(this,null,function*(){var e,t;try{Ad.info("[Daily Transport] Initializing recording"),yield this._mediaStreamRecorder.record(e=>{this.handleUserAudioStream(e.mono)},df.RECORDER_CHUNK_SIZE),null==(t=(e=this._callbacks).onAudioBufferingStarted)||t.call(e),Ad.info("[Daily Transport] Recording Initialized")}catch(lr){lr.message.includes("Already recording")||Ad.error("Error starting recording",lr)}})}preAuth(e){return d(this,null,function*(){this._dailyFactoryOptions=e,yield this._daily.preAuth(e)})}initDevices(){return d(this,null,function*(){var e,t,n,r,i,a,o,s,l,c,u,d;if(!this._daily)throw new td("Transport instance not initialized");this.state="initializing";const f=yield this._daily.startCamera(this._dailyFactoryOptions),{devices:p}=yield this._daily.enumerateDevices(),h=p.filter(e=>"videoinput"===e.kind),m=p.filter(e=>"audioinput"===e.kind),g=p.filter(e=>"audiooutput"===e.kind);this._selectedCam=f.camera,this._selectedMic=f.mic,this._selectedSpeaker=f.speaker,null==(t=(e=this._callbacks).onAvailableCamsUpdated)||t.call(e,h),null==(r=(n=this._callbacks).onAvailableMicsUpdated)||r.call(n,m),null==(a=(i=this._callbacks).onAvailableSpeakersUpdated)||a.call(i,g),null==(s=(o=this._callbacks).onCamUpdated)||s.call(o,f.camera),null==(c=(l=this._callbacks).onMicUpdated)||c.call(l,f.mic),null==(d=(u=this._callbacks).onSpeakerUpdated)||d.call(u,f.speaker),this._daily.isLocalAudioLevelObserverRunning()||(yield this._daily.startLocalAudioLevelObserver(100)),this._daily.isRemoteParticipantsAudioLevelObserverRunning()||(yield this._daily.startRemoteParticipantsAudioLevelObserver(100)),this.state="initialized"})}_validateConnectionParams(e){if(null==e)return;if("object"!=typeof e)throw new td("Invalid connection parameters");const t=e;return t.room_url?(t.url=t.room_url,delete t.room_url):t.dailyRoom&&(t.url=t.dailyRoom,delete t.dailyRoom),t.dailyToken&&(t.token=t.dailyToken,delete t.dailyToken),t.token||delete t.token,t}_connect(e){return d(this,null,function*(){var t,n,r;if(!this._daily)throw new td("Transport instance not initialized");e&&(this._dailyFactoryOptions=l(l({},this._dailyFactoryOptions),e)),this.state="connecting";try{yield this._daily.join(this._dailyFactoryOptions)}catch(lr){throw Ad.error("Failed to join room",lr),this.state="error",new id}(null==(t=this._abortController)?void 0:t.signal.aborted)||(this.state="connected",null==(r=(n=this._callbacks).onConnected)||r.call(n))})}sendReadyMessage(){return d(this,null,function*(){return new Promise(e=>{var t,n;const r=()=>{this.state="ready",this.flushAudioQueue(),this.sendMessage(Sd.clientReady()),this.stopRecording(),e()};for(const a in this._daily.participants()){const i=this._daily.participants()[a];if(!i.local&&(null==(n=null==(t=i.tracks)?void 0:t.audio)?void 0:n.persistentTrack))return r(),void e()}const i=e=>{var t;(null==(t=e.participant)?void 0:t.local)||(this._daily.off("track-started",i),(()=>{const e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||/Macintosh/.test(e)&&"ontouchend"in document})()?(Ad.debug("[Daily Transport] iOS device detected, adding 0.5 second delay before sending ready message"),setTimeout(r,500)):r())};this._daily.on("track-started",i)})})}stopRecording(){var e,t;this._mediaStreamRecorder&&"ended"!==this._mediaStreamRecorder.getStatus()&&(this._mediaStreamRecorder.end(),null==(t=(e=this._callbacks).onAudioBufferingStopped)||t.call(e))}attachEventListeners(){this._daily.on("available-devices-updated",this.handleAvailableDevicesUpdated.bind(this)),this._daily.on("selected-devices-updated",this.handleSelectedDevicesUpdated.bind(this)),this._daily.on("camera-error",this.handleDeviceError.bind(this)),this._daily.on("track-started",this.handleTrackStarted.bind(this)),this._daily.on("track-stopped",this.handleTrackStopped.bind(this)),this._daily.on("participant-joined",this.handleParticipantJoined.bind(this)),this._daily.on("participant-left",this.handleParticipantLeft.bind(this)),this._daily.on("local-audio-level",this.handleLocalAudioLevel.bind(this)),this._daily.on("remote-participants-audio-level",this.handleRemoteAudioLevel.bind(this)),this._daily.on("app-message",this.handleAppMessage.bind(this)),this._daily.on("left-meeting",this.handleLeftMeeting.bind(this)),this._daily.on("error",this.handleFatalError.bind(this)),this._daily.on("nonfatal-error",this.handleNonFatalError.bind(this))}_disconnect(){return d(this,null,function*(){this.state="disconnecting",this._daily.stopLocalAudioLevelObserver(),this._daily.stopRemoteParticipantsAudioLevelObserver(),this._audioQueue=[],this._currentAudioTrack=null,this.stopRecording(),yield this._daily.leave()})}sendMessage(e){this._daily.sendAppMessage(e,"*")}handleAppMessage(e){"rtvi-ai"===e.data.label&&this._onMessage({id:e.data.id,type:e.data.type,data:e.data.data})}handleAvailableDevicesUpdated(e){var t,n,r,i,a,o;null==(n=(t=this._callbacks).onAvailableCamsUpdated)||n.call(t,e.availableDevices.filter(e=>"videoinput"===e.kind)),null==(i=(r=this._callbacks).onAvailableMicsUpdated)||i.call(r,e.availableDevices.filter(e=>"audioinput"===e.kind)),null==(o=(a=this._callbacks).onAvailableSpeakersUpdated)||o.call(a,e.availableDevices.filter(e=>"audiooutput"===e.kind))}handleSelectedDevicesUpdated(e){var t,n,r,i,a,o,s,l,c;(null==(t=this._selectedCam)?void 0:t.deviceId)!==e.devices.camera&&(this._selectedCam=e.devices.camera,null==(r=(n=this._callbacks).onCamUpdated)||r.call(n,e.devices.camera)),(null==(i=this._selectedMic)?void 0:i.deviceId)!==e.devices.mic&&(this._selectedMic=e.devices.mic,null==(o=(a=this._callbacks).onMicUpdated)||o.call(a,e.devices.mic)),(null==(s=this._selectedSpeaker)?void 0:s.deviceId)!==e.devices.speaker&&(this._selectedSpeaker=e.devices.speaker,null==(c=(l=this._callbacks).onSpeakerUpdated)||c.call(l,e.devices.speaker))}handleDeviceError(e){var t,n;null==(n=(t=this._callbacks).onDeviceError)||n.call(t,(e=>{const t=[];switch(e.type){case"permissions":return e.blockedMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg,{blockedBy:e.blockedBy});case"not-found":return e.missingMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg);case"constraints":return e.failedMedia.forEach(e=>{t.push("video"===e?"cam":"mic")}),new cd(t,e.type,e.msg,{reason:e.reason});case"cam-in-use":return t.push("cam"),new cd(t,"in-use",e.msg);case"mic-in-use":return t.push("mic"),new cd(t,"in-use",e.msg);case"cam-mic-in-use":return t.push("cam"),t.push("mic"),new cd(t,"in-use",e.msg);default:return t.push("cam"),t.push("mic"),new cd(t,e.type,e.msg)}})(e.error))}handleLocalAudioTrack(e){return d(this,null,function*(){if("ready"==this.state||!this._bufferLocalAudioUntilBotReady)return;switch(this._mediaStreamRecorder.getStatus()){case"ended":try{yield this._mediaStreamRecorder.begin(e),yield this.startRecording()}catch(lr){}break;case"paused":yield this.startRecording();break;default:if(this._currentAudioTrack!==e)try{yield this._mediaStreamRecorder.end(),yield this._mediaStreamRecorder.begin(e),yield this.startRecording()}catch(lr){}else Ad.warn("track-started event received for current track and already recording")}this._currentAudioTrack=e})}handleTrackStarted(e){var t,n,r,i,a;"screenAudio"===e.type||"screenVideo"===e.type?null==(n=(t=this._callbacks).onScreenTrackStarted)||n.call(t,e.track,e.participant?ff(e.participant):void 0):((null==(r=e.participant)?void 0:r.local)&&"audio"===e.track.kind&&this.handleLocalAudioTrack(e.track),null==(a=(i=this._callbacks).onTrackStarted)||a.call(i,e.track,e.participant?ff(e.participant):void 0))}handleTrackStopped(e){var t,n,r,i;"screenAudio"===e.type||"screenVideo"===e.type?null==(n=(t=this._callbacks).onScreenTrackStopped)||n.call(t,e.track,e.participant?ff(e.participant):void 0):null==(i=(r=this._callbacks).onTrackStopped)||i.call(r,e.track,e.participant?ff(e.participant):void 0)}handleParticipantJoined(e){var t,n,r,i;const a=ff(e.participant);null==(n=(t=this._callbacks).onParticipantJoined)||n.call(t,a),a.local||(this._botId=e.participant.session_id,null==(i=(r=this._callbacks).onBotConnected)||i.call(r,a))}handleParticipantLeft(e){var t,n,r,i;const a=ff(e.participant);null==(n=(t=this._callbacks).onParticipantLeft)||n.call(t,a),a.local||(this._botId="",null==(i=(r=this._callbacks).onBotDisconnected)||i.call(r,a))}handleLocalAudioLevel(e){var t,n;null==(n=(t=this._callbacks).onLocalAudioLevel)||n.call(t,e.audioLevel)}handleRemoteAudioLevel(e){var t,n;const r=this._daily.participants(),i=Object.keys(e.participantsAudioLevel);for(let a=0;a<i.length;a++){const o=i[a],s=e.participantsAudioLevel[o];null==(n=(t=this._callbacks).onRemoteAudioLevel)||n.call(t,s,ff(r[o]))}}handleLeftMeeting(){var e,t;this.state="disconnected",this._botId="",null==(t=(e=this._callbacks).onDisconnected)||t.call(e)}handleFatalError(e){var t,n;Ad.error("Daily fatal error",e.errorMsg),this.state="error",this._botId="",null==(n=(t=this._callbacks).onError)||n.call(t,Sd.error(e.errorMsg,!0))}handleNonFatalError(e){var t,n;if("screen-share-error"===e.type)null==(n=(t=this._callbacks).onScreenShareError)||n.call(t,e.errorMsg)}}df.RECORDER_SAMPLE_RATE=16e3,df.RECORDER_CHUNK_SIZE=512;const ff=e=>({id:e.user_id,local:e.local,name:e.user_name});function pf(e,t,n={}){const{pipecatClient:r,connectionState:i,isBotReady:a,isMicEnabled:o,isUserSpeaking:s,remoteAudioStream:u,addMessage:f,setPipecatClient:p,setConnectionState:h,setIsBotReady:m,setIsMicEnabled:g,setIsUserSpeaking:v,setRemoteAudioStream:y}=H(),b=x.useRef(null),w=x.useRef(!1),k=x.useRef(null),S=x.useRef(!1);x.useEffect(()=>{const e=b.current;if(e&&u)try{e.srcObject=u,e.volume=1;const t=e.play();t&&t.then(()=>{}).catch(e=>{})}catch(t){}return()=>{e&&(e.srcObject=null)}},[u]);const _=x.useCallback(()=>d(null,null,function*(){var r;if(!S.current&&"disconnected"===i){S.current=!0,h("connecting");try{if(!e||!t)throw new Error("Missing agent ID or prompt token");const r={agent_id:e,conversation_metadata:c(l({},n),{agent_id:e}),prompt_access_token:t,conversation_visibility:!1,conversation_config_type:"VOICE"},i=yield function(e){return d(this,null,function*(){const t=`${Q}/v1/widgets/sessions/daily`,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Prompt-Token":e.prompt_access_token},body:JSON.stringify(e)});if(!n.ok){const e=yield n.json().catch(()=>({}));throw new Error(e.detail||e.message||`HTTP ${n.status}`)}const r=yield n.json();return r.conversation_id,r})}(r);if(!(null==i?void 0:i.dailyRoom)||!(null==i?void 0:i.dailyToken))throw new Error("Invalid response from server");const{dailyRoom:a,dailyToken:s,conversation_id:u}=i,b=new Vd({transport:new df,enableMic:o,enableCam:!1,timeout:3e4,callbacks:{onTransportStateChanged:e=>{h(e)},onConnected:()=>{f({type:"separator",text:"Voice call started"})},onBotReady:e=>{m(!0),h("ready")},onBotStartedSpeaking:()=>{m(e=>e||(h("ready"),!0))},onDisconnected:()=>{h("disconnected"),m(!1),w.current||f({type:"separator",text:"Call disconnected"})},onTrackStarted:(e,t)=>{if("audio"===e.kind&&!(null==t?void 0:t.local)){const t=new MediaStream([e]);y(t)}},onUserStartedSpeaking:()=>{v(!0)},onUserStoppedSpeaking:()=>{v(!1)},onUserTranscript:e=>{(null==e?void 0:e.final)&&(null==e?void 0:e.text)&&(e.text,f({type:"user",text:e.text,isTranscript:!0}))},onBotTranscript:e=>{var t;const n=(null==(t=null==e?void 0:e.text)?void 0:t.trim())||"";n&&f({type:"assistant",text:n,isTranscript:!0})},onMicStateChanged:e=>{g(e)},onError:e=>{var t,n;const r=(null==(t=null==e?void 0:e.data)?void 0:t.error)||(null==e?void 0:e.message)||"";r.includes("validation error")||r.includes("FunctionResponse")||!(null==(n=null==e?void 0:e.data)?void 0:n.fatal)?(f({type:"separator",text:"Agent disconnected"}),E()):(h("error"),f({type:"system",text:`Error: ${r}`}))}}});p(b),k.current=b,yield b.initDevices(),yield b.connect({url:a,token:s})}catch(a){S.current=!1,h("error");let e="Failed to start call";e=(null==(r=a.message)?void 0:r.includes("Failed to fetch"))?"Cannot reach server":"NotAllowedError"===a.name?"Microphone access denied":"NotFoundError"===a.name?"No microphone found":a.message,f({type:"system",text:`❌ ${e}`})}}}),[e,t,n,i,o,h,p,m,g,y,f]),E=x.useCallback(()=>d(null,null,function*(){var e;try{if(f({type:"separator",text:"Voice call ended"}),w.current=!0,S.current=!1,r&&"disconnected"!==i&&(yield r.disconnect()),null==(e=b.current)?void 0:e.srcObject){b.current.srcObject.getTracks().forEach(e=>e.stop()),b.current.srcObject=null}y(null),p(null),k.current=null,h("disconnected"),m(!1),setTimeout(()=>{w.current=!1},500)}catch(t){S.current=!1,p(null),k.current=null,h("disconnected"),m(!1)}}),[r,i,p,h,m,y,f]),C=x.useCallback(()=>{if(r&&a)try{const e=!o;r.enableMic(e),g(e)}catch(e){}},[r,o,a,g]),T=x.useCallback(e=>d(null,null,function*(){if(r)if(a)try{yield r.sendText(e),f({type:"user",text:e,isTranscript:!1})}catch(t){f({type:"system",text:`Error: ${t.message||"Failed to send text"}`})}else f({type:"system",text:"Please wait for the bot to be ready before sending text"})}),[r,a,f]);return x.useEffect(()=>()=>{var e;const t=k.current;if(t&&(w.current=!0,t.disconnect().catch(e=>{})),null==(e=b.current)?void 0:e.srcObject){b.current.srcObject.getTracks().forEach(e=>e.stop())}},[]),{connectionState:i,isBotReady:a,isMicEnabled:o,isUserSpeaking:s,startCall:_,endCall:E,toggleMic:C,sendTextDuringCall:T,remoteAudioRef:b}}function hf({agentId:e,agentName:t,avatarUrl:n,promptToken:r,metadata:i,showTranscripts:a=!0,idlePromptMessages:o=[],onClose:s,className:l}){const{messages:c}=H(),[u,d]=x.useState(""),[f,p]=x.useState(0),h=x.useRef(null),{connectionState:m,isBotReady:g,isMicEnabled:v,isUserSpeaking:y,startCall:w,endCall:k,toggleMic:S,sendTextDuringCall:_,remoteAudioRef:E}=pf(e,r,i);x.useEffect(()=>("disconnected"===m&&w(),()=>{"disconnected"!==m&&k()}),[]);const C="connecting"===m||!g,T="ready"===m||"connected"===m,M="error"===m;x.useEffect(()=>{var e;null==(e=h.current)||e.scrollIntoView({behavior:"smooth"})},[c]),x.useEffect(()=>{if(!C||!(null==o?void 0:o.length))return;const e=setInterval(()=>{p(e=>(e+1)%o.length)},3e3);return()=>clearInterval(e)},[C,o]);const P=T&&y?{text:"Transcribing",animate:!0}:null,A=M?"error":C?"connecting":v?"listening":"muted",O=c.filter(e=>e.isTranscript||"separator"===e.type||"system"===e.type||"user"===e.type||"assistant"===e.type);return b.jsxs("div",{className:yt("flex flex-col h-full w-full animate-fade-in min-h-0 relative",l),style:{backgroundColor:"var(--widget-background, #FFFFFF)",fontFamily:"var(--widget-font-family, system-ui)"},children:[b.jsx("audio",{ref:E,autoPlay:!0,playsInline:!0,style:{display:"none"}}),b.jsx("button",{onClick:()=>{k(),s()},className:"absolute top-4 right-4 p-2 rounded-full hover:opacity-80 transition-opacity z-10",style:{color:"var(--widget-icon-secondary, #6B7280)"},"aria-label":"Close",children:b.jsx(Ft,{className:"h-6 w-6"})}),C&&b.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-6",children:[b.jsx("div",{className:"mb-6",children:b.jsx(qn,{loading:!0,size:180,strokeWidth:4,gap:6,children:b.jsx(_t,{src:n,alt:t,size:"2xl",className:"shadow-lg"})})}),b.jsx("h2",{className:"text-xl font-semibold mb-2",style:{color:"var(--widget-text-primary, #111827)"},children:t}),b.jsx("p",{className:"text-sm mb-6",style:{color:"var(--widget-status-connecting, #F59E0B)"},children:"Connecting..."}),(null==o?void 0:o.length)>0&&b.jsx("div",{className:"text-center px-4 py-3 rounded-lg max-w-xs animate-fade-in",style:{backgroundColor:"var(--widget-idle-prompt-bg, #F3F4F6)",color:"var(--widget-idle-prompt-text, #6B7280)"},children:b.jsx("p",{className:"text-sm",children:o[f]})},f)]}),!C&&b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 shrink-0",style:{backgroundColor:"var(--widget-header-bg, #F9FAFB)",borderBottom:"1px solid var(--widget-header-border, #E5E7EB)"},children:[b.jsxs("div",{className:"flex-1 flex items-center gap-3",children:[b.jsxs("div",{className:"relative",children:[b.jsx(_t,{src:n,alt:t,size:"sm"}),A&&b.jsx("span",{className:yt("absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2",("listening"===A||"connecting"===A)&&"animate-pulse"),style:{backgroundColor:"listening"===A?"var(--widget-status-success, #10B981)":"connecting"===A?"var(--widget-status-warning, #F59E0B)":"var(--widget-status-error, #EF4444)",borderColor:"var(--widget-header-bg, #F9FAFB)"}})]}),b.jsxs("div",{children:[b.jsx("h2",{className:"text-sm font-semibold leading-tight",style:{color:"var(--widget-header-text, #111827)"},children:t}),A&&b.jsxs("span",{className:"text-xs",style:{color:"listening"===A?"var(--widget-status-success, #10B981)":"error"===A?"var(--widget-status-error, #EF4444)":"var(--widget-text-muted, #9CA3AF)"},children:["listening"===A&&"Listening...","connecting"===A&&"Connecting...","muted"===A&&"Muted","error"===A&&"Connection failed"]})]})]}),b.jsx("div",{className:"w-9"})]}),b.jsx(Fn,{className:"flex-1 min-h-0",children:b.jsxs("div",{className:"p-4 space-y-3 min-h-full",children:[0===O.length&&!P&&b.jsx("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:b.jsx("p",{className:"text-sm",style:{color:"var(--widget-text-muted, #9CA3AF)"},children:"Start Conversation"})}),O.map(e=>b.jsx(mf,{message:e},e.id)),P&&b.jsx("div",{className:"flex justify-end",children:b.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-2xl rounded-br-md text-sm",style:{backgroundColor:"var(--widget-user-message-bg, #3B82F6)",color:"var(--widget-user-message-text, #FFFFFF)"},children:[b.jsx("span",{children:P.text}),b.jsxs("span",{className:"flex gap-1",children:[b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"0ms"}}),b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"150ms"}}),b.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current animate-bounce",style:{animationDelay:"300ms"}})]})]})}),b.jsx("div",{ref:h})]})}),b.jsxs("div",{className:"shrink-0",style:{borderTop:"1px solid var(--widget-border, #E5E7EB)",backgroundColor:"var(--widget-background, #FFFFFF)"},children:[b.jsxs("form",{onSubmit:e=>{e.preventDefault(),u.trim()&&T&&(_(u.trim()),d(""))},className:"flex items-center gap-2 px-4 py-2",children:[b.jsx("input",{type:"text",value:u,onChange:e=>d(e.target.value),placeholder:"Type a message...",disabled:!T,className:"flex-1 h-10 px-4 rounded-full outline-none transition-all text-sm",style:{backgroundColor:"var(--widget-input-bg, #F9FAFB)",color:"var(--widget-input-text, #111827)",border:"1px solid var(--widget-input-border, #E5E7EB)",fontFamily:"var(--widget-font-family, inherit)"}}),b.jsx(St,{type:"submit",variant:"ghost",size:"icon",disabled:!u.trim()||!T,className:"shrink-0 rounded-full h-10 w-10",children:b.jsx(Rt,{className:"h-4 w-4"})})]}),b.jsxs("div",{className:"flex justify-center gap-4 px-4 pt-2",style:{paddingBottom:"max(1rem, env(safe-area-inset-bottom, 0px))"},children:[b.jsx(St,{onClick:S,variant:v?"secondary":"outline",size:"icon-lg",className:"rounded-full h-12 w-12",disabled:!T,style:{backgroundColor:v?"var(--widget-button-secondary-bg, #F3F4F6)":"transparent",borderColor:v?void 0:"var(--widget-border, #E5E7EB)"},children:v?b.jsx(jt,{className:"h-5 w-5",style:{color:"var(--widget-text-primary, #111827)"}}):b.jsx(Lt,{className:"h-5 w-5",style:{color:"var(--widget-text-muted, #9CA3AF)"}})}),b.jsx(St,{onClick:()=>{k(),s()},variant:"destructive",size:"icon-lg",className:"rounded-full h-12 w-12",children:b.jsx(It,{className:"h-5 w-5"})})]})]})]})]})}function mf({message:e}){const t="user"===e.type;e.type;const n="separator"===e.type,r="system"===e.type;return n?b.jsx("div",{className:"flex items-center justify-center py-1",children:b.jsx("div",{className:"px-3 py-1 rounded-full text-xs",style:{backgroundColor:"var(--widget-system-message-bg, #F3F4F6)",color:"var(--widget-text-muted, #9CA3AF)"},children:e.text})}):r?b.jsx("div",{className:"flex justify-center",children:b.jsx("div",{className:"max-w-[85%] px-4 py-2 rounded-lg text-sm",style:{backgroundColor:"var(--widget-status-error-bg, #FEE2E2)",color:"var(--widget-status-error, #DC2626)"},children:e.text})}):b.jsx("div",{className:yt("flex",t?"justify-end":"justify-start"),children:b.jsx("div",{className:yt("max-w-[80%] px-4 py-2.5 text-sm leading-relaxed",t?"rounded-2xl rounded-br-md":"rounded-2xl rounded-bl-md"),style:{backgroundColor:t?"var(--widget-user-message-bg, #3B82F6)":"var(--widget-bot-message-bg, #F3F4F6)",color:t?"var(--widget-user-message-text, #FFFFFF)":"var(--widget-bot-message-text, #111827)"},children:e.text})})}function gf({agentName:e,avatarUrl:t,variablesConfig:n=[],onSubmit:r,onClose:i,className:a}){const[o,s]=x.useState(()=>n.reduce((e,{key:t})=>c(l({},e),{[t]:""}),{})),[u,d]=x.useState({}),f=x.useMemo(()=>n.filter(e=>e.required).map(e=>e.key),[n]),p=x.useCallback(e=>e.split(/[_-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),[]),h=x.useCallback((e,t)=>{s(n=>c(l({},n),{[e]:t})),u[e]&&d(t=>c(l({},t),{[e]:null}))},[u]),m=x.useCallback(()=>{const e={};let t=!1;if(f.forEach(n=>{o[n]&&""!==o[n].trim()||(e[n]=`${p(n)} is required`,t=!0)}),t)return void d(e);const n=Object.fromEntries(Object.entries(o).filter(([e,t])=>t&&""!==t.trim()));r(n)},[o,f,p,r]),g=x.useCallback((e,t)=>{"Enter"===e.key&&t&&m()},[m]);return b.jsxs("div",{className:yt("flex flex-col h-full w-full animate-fade-in relative min-h-0",a),style:{backgroundColor:"var(--widget-background, #FFFFFF)",fontFamily:"var(--widget-font-family, system-ui)"},children:[b.jsx("button",{onClick:i,className:"absolute top-4 right-4 p-2 rounded-full hover:opacity-80 transition-opacity z-10",style:{color:"var(--widget-icon-secondary, #6B7280)"},"aria-label":"Close",children:b.jsx(Ft,{className:"h-6 w-6"})}),b.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:b.jsxs("div",{className:"flex flex-col items-center px-6 py-8 pt-14",children:[b.jsx(_t,{src:t,alt:e,size:"xl",className:"mb-4 shadow-lg"}),b.jsx("h1",{className:"text-xl font-semibold mb-2 text-center",style:{color:"var(--widget-text-primary, #111827)"},children:"Before we start"}),b.jsxs("p",{className:"text-sm mb-6 text-center max-w-sm",style:{color:"var(--widget-text-secondary, #6B7280)"},children:["Please provide the following information to personalize your experience with ",b.jsx("span",{className:"font-medium",children:e})]}),b.jsx("div",{className:"w-full max-w-md space-y-4",children:n.map(({key:e,required:t},r)=>b.jsxs("div",{className:"space-y-1",children:[b.jsxs("label",{htmlFor:`var-${e}`,className:"block text-sm font-medium",style:{color:"var(--widget-text-primary, #111827)"},children:[p(e),t&&b.jsx("span",{className:"ml-1",style:{color:"var(--widget-status-error, #DC2626)"},children:"*"}),!t&&b.jsx("span",{className:"ml-1 text-xs font-normal",style:{color:"var(--widget-text-muted, #9CA3AF)"},children:"(optional)"})]}),b.jsx("input",{id:`var-${e}`,type:"text",value:o[e],onChange:t=>h(e,t.target.value),onKeyDown:e=>g(e,r===n.length-1),placeholder:`Enter ${p(e).toLowerCase()}`,className:"w-full px-4 py-3 rounded-lg text-sm outline-none transition-colors",style:{backgroundColor:"var(--widget-input-bg, #FFFFFF)",color:"var(--widget-input-text, #111827)",border:u[e]?"2px solid var(--widget-border-error, #DC2626)":"1px solid var(--widget-input-border, #E5E7EB)"},autoFocus:0===r}),u[e]&&b.jsx("p",{className:"text-xs",style:{color:"var(--widget-status-error, #DC2626)"},children:u[e]})]},e))})]})}),b.jsx("div",{className:"p-6 pb-safe shrink-0",style:{borderTop:"1px solid var(--widget-border, #E5E7EB)",paddingBottom:"max(1.5rem, env(safe-area-inset-bottom, 0px))"},children:b.jsx("div",{className:"max-w-md mx-auto",children:b.jsxs(St,{onClick:m,variant:"default",size:"xl",className:"w-full",children:["Continue",b.jsx(Pt,{className:"h-5 w-5 ml-2"})]})})})]})}function vf({agentId:e,metadata:t={},widgetElement:n}){const{isOpen:r,currentScreen:i,setScreen:a,closeDialog:o,dynamicVariables:s,pendingScreen:c,setDynamicVariables:u,setPendingScreen:f}=H(),{agentName:p,avatarUrl:h,promptToken:m,themeConfig:g,tncConfig:v,interfaceConfig:y,appearanceConfig:w,dynamicVariablesConfig:k,isLoading:S,error:_}=function(e){var t,n,r;const{agentConfig:i,configLoading:a,configError:o,setAgentId:s,setAgentConfig:l,setConfigLoading:c,setConfigError:u}=H(),f=x.useRef(null),p=x.useRef(!1);x.useEffect(()=>{d(null,null,function*(){if(e){if(!(p.current||f.current===e&&i)){f.current&&f.current!==e&&(l(null),f.current=null);try{p.current=!0,c(!0),u(null),s(e);const t=yield Y(e);if(!t||!t.widget_config)throw new Error("Invalid agent configuration structure");l(t),f.current=e}catch(_){u(_.message||"Failed to load configuration")}finally{p.current=!1,c(!1)}}}else u("Agent ID is required")})},[e,i,s,l,c,u]);const h=x.useCallback(()=>d(null,null,function*(){if(e)try{f.current=null,p.current=!0,c(!0),u(null);const t=yield Y(e);if(!t||!t.widget_config)throw new Error("Invalid agent configuration structure");l(t),f.current=e}catch(_){u(_.message||"Failed to load configuration")}finally{p.current=!1,c(!1)}else u("Agent ID is required")}),[e,l,c,u]),m=(null==i?void 0:i.widget_config)||{},g=((null==i?void 0:i.dynamic_variables_keys)||[]).map(e=>({key:e,required:!0})),v=(null==(t=m.widget_dynamic_variables)?void 0:t.variables)||[],y=new Set(v.map(e=>e.key)),b=[...g.filter(e=>!y.has(e.key)),...v];return{agentConfig:i,agentName:(null==i?void 0:i.agent_name)||"AI Assistant",promptToken:(null==i?void 0:i.prompt_access_token)||null,dynamicVariablesConfig:b,interfaceConfig:m.widget_interface||{},appearanceConfig:m.widget_appearance||{},avatarConfig:m.widget_avatar||{},themeConfig:m.widget_theme||{},tncConfig:m.widget_tnc_config||{},avatarUrl:(null==(r=null==(n=null==i?void 0:i.MediaFiles)?void 0:n.find(e=>"avatar"===e.fileType))?void 0:r.mediaUrl)||null,isLoading:a,error:o,refresh:h}}(e),E=(null==k?void 0:k.length)>0&&0===Object.keys(s).length,C=x.useCallback(e=>{E?(f(e),a("variables")):a(e)},[E,f,a]),T=x.useCallback(e=>{u(e),c&&(a(c),f(null))},[c,u,a,f]),M=l(l({},t),s);if(x.useEffect(()=>{!r||S||!E||"chat"!==i&&"talk"!==i||(f(i),a("variables"))},[r,S,E,i,f,a]),!r)return null;if(S)return b.jsx(yf,{children:b.jsx(bf,{children:b.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:[b.jsx(Ot,{className:"h-12 w-12 animate-spin",style:{color:"var(--widget-primary-color, #3B82F6)"}}),b.jsx("p",{className:"text-sm",style:{color:"var(--widget-text-secondary, #6B7280)"},children:"Loading..."})]})})});if(_)return b.jsx(yf,{children:b.jsx(bf,{children:b.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 p-6",children:[b.jsx("div",{className:"text-4xl",role:"img","aria-label":"Error",children:"😕"}),b.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--widget-text-primary, #111827)"},children:"Something went wrong"}),b.jsx("p",{className:"text-sm text-center",style:{color:"var(--widget-text-secondary, #6B7280)"},children:_}),b.jsx("button",{onClick:o,className:"mt-4 px-6 py-2 rounded-lg text-sm font-medium",style:{backgroundColor:"var(--widget-button-secondary-bg, #F3F4F6)",color:"var(--widget-button-secondary-text, #374151)"},children:"Close"})]})})});return b.jsxs(yf,{onClick:o,children:[b.jsx(Z,{theme:g,widgetElement:n}),b.jsx(bf,{onClick:e=>e.stopPropagation(),children:(()=>{switch(i){case"variables":return b.jsx(gf,{agentName:p,avatarUrl:h,variablesConfig:k,onSubmit:T,onClose:o});case"chat":return b.jsx($n,{agentId:e,agentName:p,promptToken:m,metadata:M,onClose:o,onSwitchToTalk:()=>a("talk")});case"talk":return b.jsx(hf,{agentId:e,agentName:p,avatarUrl:h,promptToken:m,metadata:M,showTranscripts:y.realtime_transcript_of_the_call,idlePromptMessages:w.idle_prompt_messages,onClose:o});default:return b.jsx(Dt,{agentName:p,avatarUrl:h,tncEnabled:v.tnc_enabled,tncContent:v.tnc_content,onTalk:()=>C("talk"),onChat:()=>C("chat"),onClose:o})}})()})]})}function yf({children:e,onClick:t}){return b.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center animate-fade-in",style:{backgroundColor:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(4px)"},onClick:t,children:e})}function bf({children:e,onClick:t,className:n}){return b.jsx("div",{className:yt("relative w-full h-full overflow-hidden animate-scale-in","sm:max-w-lg sm:max-h-[90vh] sm:h-[700px] sm:rounded-2xl",n),style:{backgroundColor:"var(--widget-background, #FFFFFF)",boxShadow:"var(--widget-shadow-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"},onClick:t,children:e})}const wf='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:var(--widget-font-family),system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.-bottom-0\\.5{bottom:-.125rem}.-right-0\\.5{right:-.125rem}.right-4{right:1rem}.top-4{top:1rem}.z-10{z-index:10}.z-\\[9999\\]{z-index:9999}.mx-auto{margin-left:auto;margin-right:auto}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.aspect-square{aspect-ratio:1 / 1}.h-1\\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\\.5{height:.625rem}.h-24{height:6rem}.h-3{height:.75rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.min-h-0{min-height:0px}.min-h-\\[200px\\]{min-height:200px}.min-h-full{min-height:100%}.w-1\\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\\.5{width:.625rem}.w-24{width:6rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-full{width:100%}.max-w-\\[80\\%\\]{max-width:80%}.max-w-\\[85\\%\\]{max-width:85%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.animate-bounce{animation:bounce 1s infinite}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\\[inherit\\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-bl-md{border-bottom-left-radius:.375rem}.rounded-br-md{border-bottom-right-radius:.375rem}.border{border-width:1px}.border-2{border-width:2px}.border-l{border-left-width:1px}.border-t{border-top-width:1px}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-current{background-color:currentColor}.bg-transparent{background-color:transparent}.object-cover{-o-object-fit:cover;object-fit:cover}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\\[1px\\]{padding:1px}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pt-14{padding-top:3.5rem}.pt-2{padding-top:.5rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.italic{font-style:italic}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.underline-offset-4{text-underline-offset:4px}.opacity-50{opacity:.5}.opacity-80{opacity:.8}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-2{--tw-ring-offset-width: 2px}.ring-offset-4{--tw-ring-offset-width: 4px}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}*,*:before,*:after{box-sizing:border-box}html{scroll-behavior:smooth}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--widget-border, #e5e7eb);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--widget-text-muted, #9ca3af)}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes slideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes slideDown{0%{opacity:0;transform:translateY(-20px)}to{opacity:1;transform:translateY(0)}}@keyframes scaleIn{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-4px)}}.animate-fade-in{animation:fadeIn .3s ease-out}.animate-slide-up{animation:slideUp .4s ease-out}.animate-slide-down{animation:slideDown .4s ease-out}.animate-scale-in{animation:scaleIn .3s ease-out}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}.animate-spin{animation:spin 1s linear infinite}.animate-bounce{animation:bounce .6s ease-in-out infinite}@keyframes loaderSpin{0%{transform:rotate(-90deg)}to{transform:rotate(270deg)}}@keyframes loaderDash{0%{stroke-dashoffset:478}50%{stroke-dashoffset:120}to{stroke-dashoffset:478}}.animate-loader-spin{animation:loaderSpin 1.5s linear infinite,loaderDash 2s ease-in-out infinite;transform-origin:center}.pb-safe{padding-bottom:env(safe-area-inset-bottom,0px)}.pt-safe{padding-top:env(safe-area-inset-top,0px)}.px-safe{padding-left:env(safe-area-inset-left,0px);padding-right:env(safe-area-inset-right,0px)}.hover\\:underline:hover{text-decoration-line:underline}.hover\\:opacity-80:hover{opacity:.8}.hover\\:opacity-90:hover{opacity:.9}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.disabled\\:pointer-events-none:disabled{pointer-events:none}.disabled\\:opacity-50:disabled{opacity:.5}@media(min-width:640px){.sm\\:h-\\[700px\\]{height:700px}.sm\\:max-h-\\[90vh\\]{max-height:90vh}.sm\\:max-w-lg{max-width:32rem}.sm\\:rounded-2xl{border-radius:1rem}}';class kf extends HTMLElement{constructor(){super(),this.root=null,this.shadow=null,this.themeStyleSheet=null,this.agentId=null,this.metadata={}}injectThemeCSS(e){if(this.shadow&&e)try{if(this.themeStyleSheet){const e=this.shadow.adoptedStyleSheets.indexOf(this.themeStyleSheet);e>-1&&(this.shadow.adoptedStyleSheets=this.shadow.adoptedStyleSheets.filter((t,n)=>n!==e))}const t=new CSSStyleSheet;t.replaceSync(e),this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,t],this.themeStyleSheet=t}catch(t){const n=document.createElement("style");n.setAttribute("data-eigi-theme","true"),n.textContent=e;const r=this.shadow.querySelector("[data-eigi-theme]");r&&r.remove(),this.shadow.appendChild(n)}}connectedCallback(){this.agentId=this.getAttribute("agent-id");const e=this.getAttribute("metadata");if(e)try{this.metadata=JSON.parse(e)}catch(lr){}if(!this.agentId)return;const t=this.attachShadow({mode:"open"});this.shadow=t;try{const e=new CSSStyleSheet;e.replaceSync(wf),t.adoptedStyleSheets=[e]}catch(r){const e=document.createElement("style");e.textContent=wf,t.appendChild(e)}const n=document.createElement("div");n.id="eigi-chat-root",t.appendChild(n),this.root=V.createRoot(n),this.render(),this.agentId,"undefined"!=typeof window&&window.EigiChat&&(window.EigiChat._element=this,window.EigiChat._agentId=this.agentId,window.EigiChat._metadata=this.metadata,H.getState().setAgentId(this.agentId))}render(){this.root&&this.root.render(b.jsx(E.StrictMode,{children:b.jsx(vf,{agentId:this.agentId,metadata:this.metadata,widgetElement:this})}))}disconnectedCallback(){this.root&&(this.root.unmount(),this.root=null)}static get observedAttributes(){return["agent-id","metadata","action"]}attributeChangedCallback(e,t,n){if(t!==n)if("agent-id"===e)this.agentId=n,this.render();else if("metadata"===e){try{this.metadata=JSON.parse(n)}catch(lr){}this.render()}else"action"===e&&this.handleAction(n)}handleAction(e){if(!e)return;const t=H.getState();switch(e){case"open":t.openDialog();break;case"close":t.closeDialog();break;case"toggle":t.toggleDialog();break;case"openChat":t.openChat();break;case"openTalk":t.openTalk()}setTimeout(()=>{this.removeAttribute("action")},100)}}"undefined"==typeof window||customElements.get("eigi-chat")||customElements.define("eigi-chat",kf);const Sf={_element:null,_agentId:null,_metadata:{},init({agentId:e,metadata:t={}}={}){e&&(this._agentId=e,this._metadata=t,H.getState().setAgentId(e),this._element?(this._element.setAttribute("agent-id",e),Object.keys(t).length>0&&this._element.setAttribute("metadata",JSON.stringify(t))):(this._element=document.createElement("eigi-chat"),this._element.setAttribute("agent-id",e),Object.keys(t).length>0&&this._element.setAttribute("metadata",JSON.stringify(t)),document.body.appendChild(this._element)))},open(){this._element,this._agentId,this._ensureInitialized(),this._element&&H.getState().openDialog()},close(){H.getState().closeDialog()},toggle(){H.getState().toggleDialog()},isOpen:()=>H.getState().isOpen,openChat(){this._ensureInitialized(),H.getState().openChat()},openTalk(){this._ensureInitialized(),H.getState().openTalk()},_ensureInitialized(){if(!this._element&&this._agentId)this.init({agentId:this._agentId,metadata:this._metadata});else if(!this._element){const e=document.querySelector("eigi-chat");if(e){this._element=e,this._agentId=e.getAttribute("agent-id");const t=e.getAttribute("metadata");if(t)try{this._metadata=JSON.parse(t)}catch(lr){}H.getState().setAgentId(this._agentId)}else this._agentId}}};if("undefined"!=typeof window){const e=document.querySelectorAll("script[data-agent-id]"),t=e[e.length-1];if(t){const e=t.getAttribute("data-agent-id"),n=t.getAttribute("data-metadata");let r={};if(n)try{r=JSON.parse(n)}catch(lr){}e&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Sf.init({agentId:e,metadata:r})}):Sf.init({agentId:e,metadata:r}))}window.EigiChat=Sf,console.log("[EigiChat] API ready. Use window.EigiChat.open() to open the dialog.")}return e.EigiChatAPI=Sf,e.EigiChatElement=kf,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});"undefined"!=typeof window&&window.EigiChatInternal&&(window.EigiChat=window.EigiChatInternal.EigiChatAPI,window.EigiChatElement=window.EigiChatInternal.EigiChatElement);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cliniq360/eigi-chat",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "description": "Embeddable AI chat dialog with voice and text capabilities",
5
5
  "type": "module",
6
6
  "main": "./dist/eigi-chat.js",