UNPKG

primvoices-react

Version:
65 lines (56 loc) 33.7 kB
(function(x,b){typeof exports=="object"&&typeof module<"u"?b(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],b):(x=typeof globalThis<"u"?globalThis:x||self,b(x["primvoices-react"]={},x.React))})(this,function(x,b){"use strict";var It=Object.defineProperty;var Dt=(x,b,D)=>b in x?It(x,b,{enumerable:!0,configurable:!0,writable:!0,value:D}):x[b]=D;var d=(x,b,D)=>(Dt(x,typeof b!="symbol"?b+"":b,D),D);let D;const $e=new Uint8Array(16);function ze(){if(!D&&(D=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!D))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return D($e)}const R=[];for(let c=0;c<256;++c)R.push((c+256).toString(16).slice(1));function Ye(c,t=0){return R[c[t+0]]+R[c[t+1]]+R[c[t+2]]+R[c[t+3]]+"-"+R[c[t+4]]+R[c[t+5]]+"-"+R[c[t+6]]+R[c[t+7]]+"-"+R[c[t+8]]+R[c[t+9]]+"-"+R[c[t+10]]+R[c[t+11]]+R[c[t+12]]+R[c[t+13]]+R[c[t+14]]+R[c[t+15]]}const le={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function de(c,t,r){if(le.randomUUID&&!t&&!c)return le.randomUUID();c=c||{};const i=c.random||(c.rng||ze)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let s=0;s<16;++s)t[r+s]=i[s];return t}return Ye(i)}const Ge=132,fe=32635,Je=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];function Ke(c){let t,r,i,s;return t=c>>8&128,t!=0&&(c=-c),c=c+Ge,c>fe&&(c=fe),r=Je[c>>7&255],i=c>>r+3&15,s=~(t|r<<4|i),s}function He(c){let t=new Uint8Array(c.length);for(let r=0;r<c.length;r++)t[r]=Ke(c[r]);return t}class Xe{constructor(){d(this,"LOG_LEVELS",{DEBUG:0,INFO:1,WARN:2,ERROR:3});d(this,"DEFAULT_LOG_LEVEL",this.LOG_LEVELS.INFO);d(this,"logLevel",this.DEFAULT_LOG_LEVEL)}setLogLevel(t){this.logLevel=this.LOG_LEVELS[t]}debug(t,...r){this.logLevel<=this.LOG_LEVELS.DEBUG&&console.log(t,...r)}info(t,...r){this.logLevel<=this.LOG_LEVELS.INFO&&console.log(t,...r)}warn(t,...r){this.logLevel<=this.LOG_LEVELS.WARN&&console.warn(t,...r)}error(t,...r){this.logLevel<=this.LOG_LEVELS.ERROR&&console.error(t,...r)}}const v=new Xe;class he{constructor(t){d(this,"socket",null);d(this,"audioContext",null);d(this,"mediaStream",null);d(this,"microphoneSource",null);d(this,"audioWorklet",null);d(this,"analyser",null);d(this,"audioQueue",[]);d(this,"currentAudioSource",null);d(this,"debugQueue",[]);d(this,"workletInitialized",!1);d(this,"isListening",!1);d(this,"isConnected",!1);d(this,"isPlaying",!1);d(this,"callSid","");d(this,"streamSid","");d(this,"config");d(this,"speechDetected",!1);d(this,"statsInterval",null);d(this,"initialAgentId");d(this,"initialEnvironment");d(this,"redirected",!1);d(this,"scheduledSources",[]);d(this,"nextPlaybackTime",0);d(this,"scheduledMarkTimers",[]);d(this,"scheduleTimer",null);d(this,"minPrebufferSeconds",.25);d(this,"scheduleHorizonSeconds",1);d(this,"onConnectionOpen",null);d(this,"onConnectionClose",null);d(this,"onConnectionError",null);d(this,"onStartListening",null);d(this,"onStopListening",null);d(this,"onPlayStart",null);d(this,"onPlayStop",null);d(this,"onAudioStats",null);d(this,"onDebugMessage",null);d(this,"lastRedirectKey",null);this.config={apiUrl:"https://api.primvoices.com",logLevel:"ERROR",customParameters:{},...t},this.initialAgentId=this.config.agentId,this.initialEnvironment=this.config.environment,v.setLogLevel(this.config.logLevel||"ERROR"),this.initAudioContext()}setCallbacks({onOpen:t,onClose:r,onError:i,onListeningStart:s,onListeningStop:a,onAudioStart:p,onAudioStop:u,onAudioStats:g,onDebugMessage:k}){this.onConnectionOpen=t||null,this.onConnectionClose=r||null,this.onConnectionError=i||null,this.onStartListening=s||null,this.onStopListening=a||null,this.onPlayStart=p||null,this.onPlayStop=u||null,this.onAudioStats=g||null,this.onDebugMessage=k||null}async getAgentConfiguration(){const t=new URLSearchParams;return t.set("inputType","mic"),t.set("environment",this.config.environment||""),this.config.customParameters&&Object.entries(this.config.customParameters).forEach(([s,a])=>{t.set(`custom_${s}`,a)}),(await(await fetch(`${this.config.apiUrl}/v1/agents/${this.config.agentId}/call?${t.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})})).json()).data}async connect(){if(this.callSid=de(),this.streamSid=de(),this.clearDebugQueue(),this.socket&&this.socket.close(),!this.config.agentId)throw new Error("agentId is required");if(!this.config.serverUrl){const r=await this.getAgentConfiguration();v.info("[WebSocketClient] Agent configuration:",r),this.config.serverUrl=r.url,this.config.customParameters=r.parameters}let t=this.config.serverUrl;if(this.config.canary){const r=t.includes("?")?"&":"?";t=`${t}${r}canary=true`}return this.socket=new WebSocket(t),v.info(`[WebSocketClient] Connecting to ${t}`),v.info(`[WebSocketClient] Session IDs: call=${this.callSid}, stream=${this.streamSid}`),new Promise((r,i)=>{if(!this.socket){i(new Error("WebSocket not initialized"));return}this.socket.onopen=()=>{var p;this.isConnected=!0;const s={...this.config.customParameters||{},agentId:this.config.agentId,environment:this.config.environment||"",inputType:"mic",origin:this.config.origin||""},a={start:{streamSid:this.streamSid,callSid:this.callSid,customParameters:s}};(p=this.socket)==null||p.send(JSON.stringify(a)),v.info("[WebSocketClient] Connection established"),v.info("[WebSocketClient] Sent start message:",a),this.onConnectionOpen&&this.onConnectionOpen(),r()},this.socket.onclose=()=>{this.isConnected=!1,v.info("[WebSocketClient] Connection closed"),this.onConnectionClose&&this.onConnectionClose(),this.stopListening()},this.socket.onerror=s=>{v.error("[WebSocketClient] WebSocket error:",s),this.onConnectionError&&this.onConnectionError()},this.socket.onmessage=s=>{try{const a=JSON.parse(s.data);a.event==="media"?this.handleAudioMessage(a):a.event==="clear"?this.handleClearMessage(a):a.event==="mark"?this.handleMarkMessage(a):a.event==="debug"?this.handleDebugMessage(a):a.event==="control"&&this.handleControlMessage(a)}catch(a){v.error("[WebSocketClient] Error parsing message:",a)}}})}handleAudioMessage(t){if(!t.media||!t.media.payload)return;const r=t.media.payload,i=atob(r),s=new Uint8Array(i.length);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);let a;if(s.length%2!==0){const u=new ArrayBuffer(s.length+s.length%2);new Uint8Array(u).set(s),a=new Int16Array(u)}else{const u=new ArrayBuffer(s.length);new Uint8Array(u).set(s),a=new Int16Array(u)}const p=new Float32Array(a.length);for(let u=0;u<a.length;u++)p[u]=a[u]/32768;this.addToAudioQueue(p,24e3)}handleClearMessage(t){v.info("[WebSocketClient] Received clear message:",t),this.audioQueue.forEach(r=>{r.mark&&this.socket&&this.socket.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify({event:"mark",mark:r.mark,streamSid:this.streamSid})),v.debug(`[WebSocketClient] Sent mark event: ${r}`))}),this.clearAudioQueue()}handleMarkMessage(t){var i;v.info(`[WebSocketClient] Received mark event: ${(i=t.mark)==null?void 0:i.name}`);const r={mark:t.mark};this.addToAudioQueue(new Float32Array(0),24e3,r)}handleDebugMessage(t){v.info("[WebSocketClient] Received debug message:",t),this.debugQueue.push(t),this.onDebugMessage&&this.onDebugMessage(this.debugQueue)}async handleControlMessage(t){var r,i,s;try{if(t.name==="redirect"){const a=(r=t==null?void 0:t.data)==null?void 0:r.agentId,p=((i=t==null?void 0:t.data)==null?void 0:i.environment)||this.config.environment||"";if(!a)return;const u=`${a}|${p||""}`;if(a===this.config.agentId&&(p||"")===(this.config.environment||"")&&this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)||this.lastRedirectKey===u)return;this.stopListening(),this.clearAudioQueue(),(s=this.socket)==null||s.close(),this.config.agentId=a,this.config.environment=p||this.config.environment,this.redirected=!0,this.lastRedirectKey=u,this.connect().then(()=>this.startListening()).catch(k=>v.error("[WebSocketClient] Error during redirect reconnect:",k))}}catch(a){v.error("[WebSocketClient] Error handling control message:",a)}}async initAudioContext(){try{if(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.audioContext.audioWorklet&&!this.workletInitialized){const t=` class AudioProcessor extends AudioWorkletProcessor { constructor() { super(); this.port.onmessage = this.handleMessage.bind(this); } handleMessage(event) { if (event.data.command === "stop") { // Handle stop command if needed } } process(inputs, outputs, parameters) { // Get input data from the microphone const input = inputs[0]; if (input.length > 0 && input[0].length > 0) { const audioData = input[0]; // Send audio data to the main thread this.port.postMessage({ audioData: audioData }); } // Return true to keep the processor alive return true; } } registerProcessor("audio-processor", AudioProcessor); `,r=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(r);await this.audioContext.audioWorklet.addModule(i),URL.revokeObjectURL(i),this.workletInitialized=!0,v.info("[WebSocketClient] Audio worklet initialized")}}catch(t){v.error("[WebSocketClient] Error initializing audio context:",t)}}async startListening(){var t;if(!(this.isListening||!this.isConnected))try{if(((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await this.audioContext.resume(),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),!this.audioContext)throw new Error("Audio context not initialized");if(this.microphoneSource=this.audioContext.createMediaStreamSource(this.mediaStream),this.workletInitialized)this.audioWorklet=new AudioWorkletNode(this.audioContext,"audio-processor"),this.microphoneSource.connect(this.audioWorklet),this.analyser&&this.microphoneSource.connect(this.analyser),this.audioWorklet.port.onmessage=r=>{r.data.audioData&&this.isListening&&this.processAudioData(r.data.audioData)};else{v.warn("[WebSocketClient] Using ScriptProcessorNode fallback");const r=4096,i=this.audioContext.createScriptProcessor(r,1,1);this.microphoneSource.connect(i),i.connect(this.audioContext.destination),this.analyser&&this.microphoneSource.connect(this.analyser),i.onaudioprocess=s=>{if(this.isListening){const a=s.inputBuffer.getChannelData(0);this.processAudioData(a)}}}this.isListening=!0,this.startAudioStatsMonitoring(),this.onStartListening&&this.onStartListening(),v.info("[WebSocketClient] Started listening")}catch(r){v.error("[WebSocketClient] Error starting microphone:",r),this.isListening=!1}}stopListening(){this.isListening&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.microphoneSource&&(this.microphoneSource.disconnect(),this.microphoneSource=null),this.audioWorklet&&(this.audioWorklet.disconnect(),this.audioWorklet=null),this.isListening=!1,this.stopAudioStatsMonitoring(),this.onStopListening&&this.onStopListening(),v.info("[WebSocketClient] Stopped listening"))}sendTextEvent(t){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){v.error("[WebSocketClient] Cannot send text message: WebSocket is not open");return}this.socket.send(JSON.stringify({event:"text",text:t}))}disconnect(){this.stopListening(),this.clearAudioQueue(),this.stopAudioStatsMonitoring(),this.socket&&(this.socket.close(),this.socket=null),this.isConnected=!1,this.lastRedirectKey=null,this.redirected&&(this.config.agentId=this.initialAgentId,this.config.environment=this.initialEnvironment,this.config.customParameters={...this.config.customParameters||{},agentId:this.config.agentId,environment:this.config.environment||"",inputType:"mic"},this.redirected=!1,v.info(`[WebSocketClient] Restored initial agent after redirect: agent=${this.config.agentId} env=${this.config.environment}`)),this.onConnectionClose&&this.onConnectionClose()}processAudioData(t){var r;if(!(!this.socket||this.socket.readyState!==WebSocket.OPEN))try{const i=((r=this.audioContext)==null?void 0:r.sampleRate)||48e3,s=16e3,a=t.some(S=>Math.abs(S)>.01);v.debug(`[WebSocketClient] Processing audio frame: ${t.length} samples at ${i}Hz ${a?"(has sound)":"(silent)"}`);const p=this.downsampleBuffer(t,i,s);v.debug(`[WebSocketClient] Downsampled to ${p.length} samples at ${s}Hz`);const u=He(p);v.debug(`[WebSocketClient] Converted to μ-law format: ${u.length} bytes`);const g=this.arrayBufferToBase64(u.buffer),k={event:"media",streamSid:this.streamSid,media:{payload:g}};this.socket.send(JSON.stringify(k)),v.debug(`[WebSocketClient] Sent μ-law encoded audio: ${g.length} base64 chars`)}catch(i){v.error("[WebSocketClient] Error processing or sending audio:",i)}}arrayBufferToBase64(t){const r=new Uint8Array(t);let i="";for(let s=0;s<r.byteLength;s++)i+=String.fromCharCode(r[s]);return btoa(i)}downsampleBuffer(t,r,i){if(i>r)throw new Error("downsampling rate should be lower than original sample rate");const s=r/i,a=Math.round(t.length/s),p=new Int16Array(a);let u=0;for(let g=0;g<a;g++){const k=Math.round((g+1)*s);let S=0,w=0;for(let P=u;P<k&&P<t.length;P++)S+=t[P],w++;p[g]=w>0?Math.round(S/w*32767):0,u=k}return p}addToAudioQueue(t,r=16e3,i){this.audioQueue.push({data:t,sampleRate:r,mark:i}),this.schedulePlayback()}clearAudioQueue(){if(this.audioQueue=[],this.currentAudioSource){try{this.currentAudioSource.stop()}catch{}try{this.currentAudioSource.disconnect()}catch{}this.currentAudioSource=null}this.scheduledSources.forEach(t=>{try{t.stop()}catch{}try{t.disconnect()}catch{}}),this.scheduledSources=[],this.scheduledMarkTimers.forEach(t=>clearTimeout(t)),this.scheduledMarkTimers=[],this.scheduleTimer&&(clearInterval(this.scheduleTimer),this.scheduleTimer=null),this.nextPlaybackTime=0,this.isPlaying=!1}clearDebugQueue(){this.debugQueue=[],this.onDebugMessage&&this.onDebugMessage([])}playNextInQueue(){if(!this.audioContext||this.audioQueue.length===0){this.isPlaying=!1,this.isListening||this.stopAudioStatsMonitoring(),this.onPlayStop&&this.onPlayStop();return}this.schedulePlayback()}getBufferedSecondsInQueue(){return this.audioQueue.reduce((t,r)=>r.mark||r.data.length===0||r.sampleRate<=0?t:t+r.data.length/r.sampleRate,0)}schedulePlayback(){if(this.audioContext){if(!this.isPlaying){const t=this.getBufferedSecondsInQueue();if(t<=0||t<this.minPrebufferSeconds)return;const r=Math.max(this.audioContext.currentTime+.02,this.audioContext.currentTime+this.minPrebufferSeconds);this.nextPlaybackTime=r,this.isPlaying=!0,this.statsInterval||this.startAudioStatsMonitoring(),this.onPlayStart&&this.onPlayStart(),this.scheduleTimer||(this.scheduleTimer=window.setInterval(()=>{this.scheduleFromQueue()},50))}this.scheduleFromQueue()}}scheduleFromQueue(){if(this.audioContext)for(;this.audioQueue.length>0&&!(this.nextPlaybackTime-this.audioContext.currentTime>this.scheduleHorizonSeconds);){const r=this.audioQueue.shift();if(!r)break;const{data:i,sampleRate:s,mark:a}=r;if(a){const S=Math.max(0,(this.nextPlaybackTime-this.audioContext.currentTime)*1e3),w=window.setTimeout(()=>{var P;this.socket&&this.socket.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify({event:"mark",streamSid:this.streamSid,mark:a.mark})),v.debug(`[WebSocketClient] Sent mark event (scheduled): ${(P=a.mark)==null?void 0:P.name}`))},S);this.scheduledMarkTimers.push(w);continue}if(i.length===0||s<=0)continue;const p=this.audioContext.createBuffer(1,i.length,s);p.getChannelData(0).set(i);const u=this.audioContext.createBufferSource();u.buffer=p,this.analyser&&u.connect(this.analyser),u.connect(this.audioContext.destination),u.onended=()=>{this.scheduledSources=this.scheduledSources.filter(S=>S!==u);try{u.disconnect()}catch{}this.scheduleFromQueue(),this.scheduledSources.length===0&&this.audioQueue.length===0&&(this.isPlaying=!1,this.isListening||this.stopAudioStatsMonitoring(),this.onPlayStop&&this.onPlayStop(),this.scheduleTimer&&(clearInterval(this.scheduleTimer),this.scheduleTimer=null))};const g=Math.max(this.audioContext.currentTime+.005,this.nextPlaybackTime);try{u.start(g)}catch{u.start()}this.scheduledSources.push(u);const k=p.duration;this.nextPlaybackTime=g+k,this.currentAudioSource=u}}getAudioLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.frequencyBinCount);this.analyser.getByteFrequencyData(t);let r=0;for(let i=0;i<t.length;i++)r+=t[i];return r/t.length/255}startAudioStatsMonitoring(){this.statsInterval&&clearInterval(this.statsInterval),this.statsInterval=window.setInterval(()=>{const t=this.getAudioLevel(),r=t>.1;this.onAudioStats&&this.onAudioStats({level:t,isSpeaking:r,isPlayback:this.isPlaying}),r!==this.speechDetected&&(this.speechDetected=r)},100)}stopAudioStatsMonitoring(){this.statsInterval&&!this.isListening&&!this.isPlaying&&(clearInterval(this.statsInterval),this.statsInterval=null)}isCurrentlyConnected(){return this.isConnected}isCurrentlyListening(){return this.isListening}isCurrentlyPlaying(){return this.isPlaying}}var X={exports:{}},V={};/** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var ge;function qe(){if(ge)return V;ge=1;var c=b,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,s=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function p(u,g,k){var S,w={},P=null,A=null;k!==void 0&&(P=""+k),g.key!==void 0&&(P=""+g.key),g.ref!==void 0&&(A=g.ref);for(S in g)i.call(g,S)&&!a.hasOwnProperty(S)&&(w[S]=g[S]);if(u&&u.defaultProps)for(S in g=u.defaultProps,g)w[S]===void 0&&(w[S]=g[S]);return{$$typeof:t,type:u,key:P,ref:A,props:w,_owner:s.current}}return V.Fragment=r,V.jsx=p,V.jsxs=p,V}var B={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var me;function Ze(){return me||(me=1,process.env.NODE_ENV!=="production"&&function(){var c=b,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),p=Symbol.for("react.provider"),u=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),k=Symbol.for("react.suspense"),S=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),A=Symbol.for("react.offscreen"),Y=Symbol.iterator,q="@@iterator";function pe(e){if(e===null||typeof e!="object")return null;var n=Y&&e[Y]||e[q];return typeof n=="function"?n:null}var j=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function T(e){{for(var n=arguments.length,o=new Array(n>1?n-1:0),l=1;l<n;l++)o[l-1]=arguments[l];ye("error",e,o)}}function ye(e,n,o){{var l=j.ReactDebugCurrentFrame,m=l.getStackAddendum();m!==""&&(n+="%s",o=o.concat([m]));var y=o.map(function(h){return String(h)});y.unshift("Warning: "+n),Function.prototype.apply.call(console[e],console,y)}}var Se=!1,Z=!1,I=!1,ee=!1,rt=!1,be;be=Symbol.for("react.module.reference");function it(e){return!!(typeof e=="string"||typeof e=="function"||e===i||e===a||rt||e===s||e===k||e===S||ee||e===A||Se||Z||I||typeof e=="object"&&e!==null&&(e.$$typeof===P||e.$$typeof===w||e.$$typeof===p||e.$$typeof===u||e.$$typeof===g||e.$$typeof===be||e.getModuleId!==void 0))}function ot(e,n,o){var l=e.displayName;if(l)return l;var m=n.displayName||n.name||"";return m!==""?o+"("+m+")":o}function Ce(e){return e.displayName||"Context"}function W(e){if(e==null)return null;if(typeof e.tag=="number"&&T("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case i:return"Fragment";case r:return"Portal";case a:return"Profiler";case s:return"StrictMode";case k:return"Suspense";case S:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case u:var n=e;return Ce(n)+".Consumer";case p:var o=e;return Ce(o._context)+".Provider";case g:return ot(e,e.render,"ForwardRef");case w:var l=e.displayName||null;return l!==null?l:W(e.type)||"Memo";case P:{var m=e,y=m._payload,h=m._init;try{return W(h(y))}catch{return null}}}return null}var M=Object.assign,Q=0,ke,Ee,Re,we,Pe,Te,xe;function _e(){}_e.__reactDisabledLog=!0;function st(){{if(Q===0){ke=console.log,Ee=console.info,Re=console.warn,we=console.error,Pe=console.group,Te=console.groupCollapsed,xe=console.groupEnd;var e={configurable:!0,enumerable:!0,value:_e,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Q++}}function at(){{if(Q--,Q===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:M({},e,{value:ke}),info:M({},e,{value:Ee}),warn:M({},e,{value:Re}),error:M({},e,{value:we}),group:M({},e,{value:Pe}),groupCollapsed:M({},e,{value:Te}),groupEnd:M({},e,{value:xe})})}Q<0&&T("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var te=j.ReactCurrentDispatcher,ne;function G(e,n,o){{if(ne===void 0)try{throw Error()}catch(m){var l=m.stack.trim().match(/\n( *(at )?)/);ne=l&&l[1]||""}return` `+ne+e}}var re=!1,J;{var ct=typeof WeakMap=="function"?WeakMap:Map;J=new ct}function Ae(e,n){if(!e||re)return"";{var o=J.get(e);if(o!==void 0)return o}var l;re=!0;var m=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var y;y=te.current,te.current=null,st();try{if(n){var h=function(){throw Error()};if(Object.defineProperty(h.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(h,[])}catch(L){l=L}Reflect.construct(e,[],h)}else{try{h.call()}catch(L){l=L}e.call(h.prototype)}}else{try{throw Error()}catch(L){l=L}e()}}catch(L){if(L&&l&&typeof L.stack=="string"){for(var f=L.stack.split(` `),_=l.stack.split(` `),C=f.length-1,E=_.length-1;C>=1&&E>=0&&f[C]!==_[E];)E--;for(;C>=1&&E>=0;C--,E--)if(f[C]!==_[E]){if(C!==1||E!==1)do if(C--,E--,E<0||f[C]!==_[E]){var O=` `+f[C].replace(" at new "," at ");return e.displayName&&O.includes("<anonymous>")&&(O=O.replace("<anonymous>",e.displayName)),typeof e=="function"&&J.set(e,O),O}while(C>=1&&E>=0);break}}}finally{re=!1,te.current=y,at(),Error.prepareStackTrace=m}var N=e?e.displayName||e.name:"",F=N?G(N):"";return typeof e=="function"&&J.set(e,F),F}function ut(e,n,o){return Ae(e,!1)}function lt(e){var n=e.prototype;return!!(n&&n.isReactComponent)}function K(e,n,o){if(e==null)return"";if(typeof e=="function")return Ae(e,lt(e));if(typeof e=="string")return G(e);switch(e){case k:return G("Suspense");case S:return G("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case g:return ut(e.render);case w:return K(e.type,n,o);case P:{var l=e,m=l._payload,y=l._init;try{return K(y(m),n,o)}catch{}}}return""}var $=Object.prototype.hasOwnProperty,Le={},Oe=j.ReactDebugCurrentFrame;function H(e){if(e){var n=e._owner,o=K(e.type,e._source,n?n.type:null);Oe.setExtraStackFrame(o)}else Oe.setExtraStackFrame(null)}function dt(e,n,o,l,m){{var y=Function.call.bind($);for(var h in e)if(y(e,h)){var f=void 0;try{if(typeof e[h]!="function"){var _=Error((l||"React class")+": "+o+" type `"+h+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[h]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw _.name="Invariant Violation",_}f=e[h](n,h,l,o,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(C){f=C}f&&!(f instanceof Error)&&(H(m),T("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",l||"React class",o,h,typeof f),H(null)),f instanceof Error&&!(f.message in Le)&&(Le[f.message]=!0,H(m),T("Failed %s type: %s",o,f.message),H(null))}}}var ft=Array.isArray;function ie(e){return ft(e)}function ht(e){{var n=typeof Symbol=="function"&&Symbol.toStringTag,o=n&&e[Symbol.toStringTag]||e.constructor.name||"Object";return o}}function gt(e){try{return Ie(e),!1}catch{return!0}}function Ie(e){return""+e}function De(e){if(gt(e))return T("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ht(e)),Ie(e)}var z=j.ReactCurrentOwner,mt={key:!0,ref:!0,__self:!0,__source:!0},We,je,oe;oe={};function vt(e){if($.call(e,"ref")){var n=Object.getOwnPropertyDescriptor(e,"ref").get;if(n&&n.isReactWarning)return!1}return e.ref!==void 0}function pt(e){if($.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function yt(e,n){if(typeof e.ref=="string"&&z.current&&n&&z.current.stateNode!==n){var o=W(z.current.type);oe[o]||(T('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',W(z.current.type),e.ref),oe[o]=!0)}}function St(e,n){{var o=function(){We||(We=!0,T("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",n))};o.isReactWarning=!0,Object.defineProperty(e,"key",{get:o,configurable:!0})}}function bt(e,n){{var o=function(){je||(je=!0,T("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",n))};o.isReactWarning=!0,Object.defineProperty(e,"ref",{get:o,configurable:!0})}}var Ct=function(e,n,o,l,m,y,h){var f={$$typeof:t,type:e,key:n,ref:o,props:h,_owner:y};return f._store={},Object.defineProperty(f._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(f,"_self",{configurable:!1,enumerable:!1,writable:!1,value:l}),Object.defineProperty(f,"_source",{configurable:!1,enumerable:!1,writable:!1,value:m}),Object.freeze&&(Object.freeze(f.props),Object.freeze(f)),f};function kt(e,n,o,l,m){{var y,h={},f=null,_=null;o!==void 0&&(De(o),f=""+o),pt(n)&&(De(n.key),f=""+n.key),vt(n)&&(_=n.ref,yt(n,m));for(y in n)$.call(n,y)&&!mt.hasOwnProperty(y)&&(h[y]=n[y]);if(e&&e.defaultProps){var C=e.defaultProps;for(y in C)h[y]===void 0&&(h[y]=C[y])}if(f||_){var E=typeof e=="function"?e.displayName||e.name||"Unknown":e;f&&St(h,E),_&&bt(h,E)}return Ct(e,f,_,m,l,z.current,h)}}var se=j.ReactCurrentOwner,Me=j.ReactDebugCurrentFrame;function U(e){if(e){var n=e._owner,o=K(e.type,e._source,n?n.type:null);Me.setExtraStackFrame(o)}else Me.setExtraStackFrame(null)}var ae;ae=!1;function ce(e){return typeof e=="object"&&e!==null&&e.$$typeof===t}function Fe(){{if(se.current){var e=W(se.current.type);if(e)return` Check the render method of \``+e+"`."}return""}}function Et(e){{if(e!==void 0){var n=e.fileName.replace(/^.*[\\\/]/,""),o=e.lineNumber;return` Check your code at `+n+":"+o+"."}return""}}var Ue={};function Rt(e){{var n=Fe();if(!n){var o=typeof e=="string"?e:e.displayName||e.name;o&&(n=` Check the top-level render call using <`+o+">.")}return n}}function Ne(e,n){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var o=Rt(n);if(Ue[o])return;Ue[o]=!0;var l="";e&&e._owner&&e._owner!==se.current&&(l=" It was passed a child from "+W(e._owner.type)+"."),U(e),T('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',o,l),U(null)}}function Ve(e,n){{if(typeof e!="object")return;if(ie(e))for(var o=0;o<e.length;o++){var l=e[o];ce(l)&&Ne(l,n)}else if(ce(e))e._store&&(e._store.validated=!0);else if(e){var m=pe(e);if(typeof m=="function"&&m!==e.entries)for(var y=m.call(e),h;!(h=y.next()).done;)ce(h.value)&&Ne(h.value,n)}}}function wt(e){{var n=e.type;if(n==null||typeof n=="string")return;var o;if(typeof n=="function")o=n.propTypes;else if(typeof n=="object"&&(n.$$typeof===g||n.$$typeof===w))o=n.propTypes;else return;if(o){var l=W(n);dt(o,e.props,"prop",l,e)}else if(n.PropTypes!==void 0&&!ae){ae=!0;var m=W(n);T("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",m||"Unknown")}typeof n.getDefaultProps=="function"&&!n.getDefaultProps.isReactClassApproved&&T("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Pt(e){{for(var n=Object.keys(e.props),o=0;o<n.length;o++){var l=n[o];if(l!=="children"&&l!=="key"){U(e),T("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",l),U(null);break}}e.ref!==null&&(U(e),T("Invalid attribute `ref` supplied to `React.Fragment`."),U(null))}}var Be={};function Qe(e,n,o,l,m,y){{var h=it(e);if(!h){var f="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(f+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var _=Et(m);_?f+=_:f+=Fe();var C;e===null?C="null":ie(e)?C="array":e!==void 0&&e.$$typeof===t?(C="<"+(W(e.type)||"Unknown")+" />",f=" Did you accidentally export a JSX literal instead of a component?"):C=typeof e,T("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",C,f)}var E=kt(e,n,o,m,y);if(E==null)return E;if(h){var O=n.children;if(O!==void 0)if(l)if(ie(O)){for(var N=0;N<O.length;N++)Ve(O[N],e);Object.freeze&&Object.freeze(O)}else T("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Ve(O,e)}if($.call(n,"key")){var F=W(e),L=Object.keys(n).filter(function(Ot){return Ot!=="key"}),ue=L.length>0?"{key: someKey, "+L.join(": ..., ")+": ...}":"{key: someKey}";if(!Be[F+ue]){var Lt=L.length>0?"{"+L.join(": ..., ")+": ...}":"{}";T(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,ue,F,Lt,F),Be[F+ue]=!0}}return e===i?Pt(E):wt(E),E}}function Tt(e,n,o){return Qe(e,n,o,!0)}function xt(e,n,o){return Qe(e,n,o,!1)}var _t=xt,At=Tt;B.Fragment=i,B.jsx=_t,B.jsxs=At}()),B}process.env.NODE_ENV==="production"?X.exports=qe():X.exports=Ze();var et=X.exports;const ve=b.createContext({connect:async()=>{},disconnect:async()=>{},startListening:async()=>{},stopListening:async()=>{},sendTextEvent:async c=>{},isConnected:!1,isListening:!1,isPlaying:!1,audioStats:null,debugMessages:[],error:null}),tt=()=>b.useContext(ve),nt=({children:c,config:t,autoConnect:r=!1})=>{const i=b.useRef(null),[s,a]=b.useState(!1),[p,u]=b.useState(!1),[g,k]=b.useState(!1),[S,w]=b.useState(null),[P,A]=b.useState(null),[Y,q]=b.useState([]);b.useEffect(()=>{try{return i.current=new he(t),i.current.setCallbacks({onOpen:()=>{a(!0),A(null)},onClose:()=>{a(!1)},onError:()=>{A("Connection error occurred")},onListeningStart:()=>{u(!0)},onListeningStop:()=>{u(!1)},onAudioStart:()=>{k(!0)},onAudioStop:()=>{k(!1)},onAudioStats:I=>{w(I)},onDebugMessage:I=>{q([...I])}}),r&&i.current.connect(),()=>{i.current&&(i.current.disconnect(),i.current=null)}}catch(I){A("Failed to initialize client"),console.error("Error initializing PrimVoices client:",I)}},[t,r]);const Z={connect:async()=>{if(i.current)try{await i.current.connect()}catch{A("Failed to connect")}else A("Client not initialized")},disconnect:async()=>{i.current&&await i.current.disconnect()},startListening:async()=>{if(i.current)try{await i.current.startListening()}catch{A("Failed to start microphone")}else A("Client not initialized")},stopListening:async()=>{i.current&&await i.current.stopListening()},sendTextEvent:async I=>{if(i.current&&s)try{await i.current.sendTextEvent(I)}catch(ee){A("Failed to send message"),console.error("Error sending text message:",ee)}else A("Client not connected")},isConnected:s,isListening:p,isPlaying:g,audioStats:S,debugMessages:Y,error:P};return et.jsx(ve.Provider,{value:Z,children:c})};x.PrimVoicesProvider=nt,x.WebSocketClient=he,x.usePrimVoices=tt,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=index.umd.js.map