UNPKG

primvoices-react

Version:
65 lines (56 loc) 30.2 kB
(function(_,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],m):(_=typeof globalThis<"u"?globalThis:_||self,m(_["primvoices-react"]={},_.React))})(this,function(_,m){"use strict";var Dt=Object.defineProperty;var Wt=(_,m,W)=>m in _?Dt(_,m,{enumerable:!0,configurable:!0,writable:!0,value:W}):_[m]=W;var h=(_,m,W)=>(Wt(_,typeof m!="symbol"?m+"":m,W),W);let W;const Qe=new Uint8Array(16);function ze(){if(!W&&(W=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!W))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return W(Qe)}const k=[];for(let a=0;a<256;++a)k.push((a+256).toString(16).slice(1));function Ge(a,t=0){return k[a[t+0]]+k[a[t+1]]+k[a[t+2]]+k[a[t+3]]+"-"+k[a[t+4]]+k[a[t+5]]+"-"+k[a[t+6]]+k[a[t+7]]+"-"+k[a[t+8]]+k[a[t+9]]+"-"+k[a[t+10]]+k[a[t+11]]+k[a[t+12]]+k[a[t+13]]+k[a[t+14]]+k[a[t+15]]}const le={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function fe(a,t,o){if(le.randomUUID&&!t&&!a)return le.randomUUID();a=a||{};const r=a.random||(a.rng||ze)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){o=o||0;for(let s=0;s<16;++s)t[o+s]=r[s];return t}return Ge(r)}const Je=132,de=32635,$e=[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(a){let t,o,r,s;return t=a>>8&128,t!=0&&(a=-a),a=a+Je,a>de&&(a=de),o=$e[a>>7&255],r=a>>o+3&15,s=~(t|o<<4|r),s}function He(a){let t=new Uint8Array(a.length);for(let o=0;o<a.length;o++)t[o]=Ke(a[o]);return t}class Xe{constructor(){h(this,"LOG_LEVELS",{DEBUG:0,INFO:1,WARN:2,ERROR:3});h(this,"DEFAULT_LOG_LEVEL",this.LOG_LEVELS.INFO);h(this,"logLevel",this.DEFAULT_LOG_LEVEL)}setLogLevel(t){this.logLevel=this.LOG_LEVELS[t]}debug(t,...o){this.logLevel<=this.LOG_LEVELS.DEBUG&&console.log(t,...o)}info(t,...o){this.logLevel<=this.LOG_LEVELS.INFO&&console.log(t,...o)}warn(t,...o){this.logLevel<=this.LOG_LEVELS.WARN&&console.warn(t,...o)}error(t,...o){this.logLevel<=this.LOG_LEVELS.ERROR&&console.error(t,...o)}}const y=new Xe;class he{constructor(t){h(this,"socket",null);h(this,"audioContext",null);h(this,"mediaStream",null);h(this,"microphoneSource",null);h(this,"audioWorklet",null);h(this,"analyser",null);h(this,"audioQueue",[]);h(this,"currentAudioSource",null);h(this,"debugQueue",[]);h(this,"workletInitialized",!1);h(this,"isListening",!1);h(this,"isConnected",!1);h(this,"isPlaying",!1);h(this,"callSid","");h(this,"streamSid","");h(this,"config");h(this,"speechDetected",!1);h(this,"statsInterval",null);h(this,"onConnectionOpen",null);h(this,"onConnectionClose",null);h(this,"onConnectionError",null);h(this,"onStartListening",null);h(this,"onStopListening",null);h(this,"onPlayStart",null);h(this,"onPlayStop",null);h(this,"onAudioStats",null);h(this,"onDebugMessage",null);this.config={apiUrl:"https://api.primvoices.com",logLevel:"ERROR",customParameters:{},...t},y.setLogLevel(this.config.logLevel||"ERROR"),this.initAudioContext()}setCallbacks({onOpen:t,onClose:o,onError:r,onListeningStart:s,onListeningStop:g,onAudioStart:E,onAudioStop:l,onAudioStats:p,onDebugMessage:w}){this.onConnectionOpen=t||null,this.onConnectionClose=o||null,this.onConnectionError=r||null,this.onStartListening=s||null,this.onStopListening=g||null,this.onPlayStart=E||null,this.onPlayStop=l||null,this.onAudioStats=p||null,this.onDebugMessage=w||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,g])=>{t.set(`custom_${s}`,g)}),(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=fe(),this.streamSid=fe(),this.clearDebugQueue(),this.socket&&this.socket.close(),!this.config.agentId)throw new Error("agentId is required");if(!this.config.serverUrl){const t=await this.getAgentConfiguration();y.info("[WebSocketClient] Agent configuration:",t),this.config.serverUrl=t.url,this.config.customParameters=t.parameters}return this.socket=new WebSocket(this.config.serverUrl),y.info(`[WebSocketClient] Connecting to ${this.config.serverUrl}`),y.info(`[WebSocketClient] Session IDs: call=${this.callSid}, stream=${this.streamSid}`),new Promise((t,o)=>{if(!this.socket){o(new Error("WebSocket not initialized"));return}this.socket.onopen=()=>{var s;this.isConnected=!0;const r={start:{streamSid:this.streamSid,callSid:this.callSid,customParameters:this.config.customParameters}};(s=this.socket)==null||s.send(JSON.stringify(r)),y.info("[WebSocketClient] Connection established"),y.info("[WebSocketClient] Sent start message:",r),this.onConnectionOpen&&this.onConnectionOpen(),t()},this.socket.onclose=()=>{this.isConnected=!1,y.info("[WebSocketClient] Connection closed"),this.onConnectionClose&&this.onConnectionClose(),this.stopListening()},this.socket.onerror=r=>{y.error("[WebSocketClient] WebSocket error:",r),this.onConnectionError&&this.onConnectionError()},this.socket.onmessage=r=>{try{const s=JSON.parse(r.data);s.event==="media"?this.handleAudioMessage(s):s.event==="clear"?this.handleClearMessage(s):s.event==="mark"?this.handleMarkMessage(s):s.event==="debug"&&this.handleDebugMessage(s)}catch(s){y.error("[WebSocketClient] Error parsing message:",s)}}})}handleAudioMessage(t){if(!t.media||!t.media.payload)return;const o=t.media.payload,r=atob(o),s=new Uint8Array(r.length);for(let l=0;l<r.length;l++)s[l]=r.charCodeAt(l);let g;if(s.length%2!==0){const l=new ArrayBuffer(s.length+s.length%2);new Uint8Array(l).set(s),g=new Int16Array(l)}else{const l=new ArrayBuffer(s.length);new Uint8Array(l).set(s),g=new Int16Array(l)}const E=new Float32Array(g.length);for(let l=0;l<g.length;l++)E[l]=g[l]/32768;this.addToAudioQueue(E,24e3)}handleClearMessage(t){y.info("[WebSocketClient] Received clear message:",t),this.clearAudioQueue()}handleMarkMessage(t){var r;y.info(`[WebSocketClient] Received mark event: ${(r=t.mark)==null?void 0:r.name}`);const o={mark:t.mark};this.addToAudioQueue(new Float32Array(0),24e3,o)}handleDebugMessage(t){y.info("[WebSocketClient] Received debug message:",t),this.debugQueue.push(t),this.onDebugMessage&&this.onDebugMessage(this.debugQueue)}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); `,o=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(o);await this.audioContext.audioWorklet.addModule(r),URL.revokeObjectURL(r),this.workletInitialized=!0,y.info("[WebSocketClient] Audio worklet initialized")}}catch(t){y.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=o=>{o.data.audioData&&this.isListening&&this.processAudioData(o.data.audioData)};else{y.warn("[WebSocketClient] Using ScriptProcessorNode fallback");const o=4096,r=this.audioContext.createScriptProcessor(o,1,1);this.microphoneSource.connect(r),r.connect(this.audioContext.destination),this.analyser&&this.microphoneSource.connect(this.analyser),r.onaudioprocess=s=>{if(this.isListening){const g=s.inputBuffer.getChannelData(0);this.processAudioData(g)}}}this.isListening=!0,this.startAudioStatsMonitoring(),this.onStartListening&&this.onStartListening(),y.info("[WebSocketClient] Started listening")}catch(o){y.error("[WebSocketClient] Error starting microphone:",o),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(),y.info("[WebSocketClient] Stopped listening"))}sendTextEvent(t){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){y.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.onConnectionClose&&this.onConnectionClose()}processAudioData(t){var o;if(!(!this.socket||this.socket.readyState!==WebSocket.OPEN))try{const r=((o=this.audioContext)==null?void 0:o.sampleRate)||48e3,s=16e3,g=t.some(b=>Math.abs(b)>.01);y.debug(`[WebSocketClient] Processing audio frame: ${t.length} samples at ${r}Hz ${g?"(has sound)":"(silent)"}`);const E=this.downsampleBuffer(t,r,s);y.debug(`[WebSocketClient] Downsampled to ${E.length} samples at ${s}Hz`);const l=He(E);y.debug(`[WebSocketClient] Converted to μ-law format: ${l.length} bytes`);const p=this.arrayBufferToBase64(l.buffer),w={event:"media",streamSid:this.streamSid,media:{payload:p}};this.socket.send(JSON.stringify(w)),y.debug(`[WebSocketClient] Sent μ-law encoded audio: ${p.length} base64 chars`)}catch(r){y.error("[WebSocketClient] Error processing or sending audio:",r)}}arrayBufferToBase64(t){const o=new Uint8Array(t);let r="";for(let s=0;s<o.byteLength;s++)r+=String.fromCharCode(o[s]);return btoa(r)}downsampleBuffer(t,o,r){if(r>o)throw new Error("downsampling rate should be lower than original sample rate");const s=o/r,g=Math.round(t.length/s),E=new Int16Array(g);let l=0;for(let p=0;p<g;p++){const w=Math.round((p+1)*s);let b=0,P=0;for(let L=l;L<w&&L<t.length;L++)b+=t[L],P++;E[p]=P>0?Math.round(b/P*32767):0,l=w}return E}addToAudioQueue(t,o=16e3,r){this.audioQueue.push({data:t,sampleRate:o,mark:r}),this.isPlaying||this.playNextInQueue()}clearAudioQueue(){if(this.audioQueue=[],this.currentAudioSource){if(this.analyser)try{this.currentAudioSource.disconnect(this.analyser)}catch{}try{this.currentAudioSource.stop(),this.currentAudioSource.disconnect()}catch{}this.currentAudioSource=null}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}const t=this.audioQueue.shift();if(!t)return;const{data:o,sampleRate:r,mark:s}=t;if(s){s&&this.socket&&this.socket.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify({event:"mark",streamSid:this.streamSid,mark:s.mark})),y.debug(`[WebSocketClient] Sent mark event: ${s}`)),this.playNextInQueue();return}const g=this.audioContext.createBuffer(1,o.length,r);g.getChannelData(0).set(o),this.currentAudioSource=this.audioContext.createBufferSource(),this.currentAudioSource.buffer=g,this.analyser&&this.currentAudioSource.connect(this.analyser),this.currentAudioSource.connect(this.audioContext.destination),this.currentAudioSource.onended=()=>{this.currentAudioSource&&(this.currentAudioSource.disconnect(),this.currentAudioSource=null),this.playNextInQueue()},this.currentAudioSource.start(),this.isPlaying=!0,this.statsInterval||this.startAudioStatsMonitoring(),this.onPlayStart&&this.audioQueue.length===0&&this.onPlayStart()}getAudioLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.frequencyBinCount);this.analyser.getByteFrequencyData(t);let o=0;for(let r=0;r<t.length;r++)o+=t[r];return o/t.length/255}startAudioStatsMonitoring(){this.statsInterval&&clearInterval(this.statsInterval),this.statsInterval=window.setInterval(()=>{const t=this.getAudioLevel(),o=t>.1;this.onAudioStats&&this.onAudioStats({level:t,isSpeaking:o,isPlayback:this.isPlaying}),o!==this.speechDetected&&(this.speechDetected=o)},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:{}},N={};/** * @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 N;ge=1;var a=m,t=Symbol.for("react.element"),o=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,g={key:!0,ref:!0,__self:!0,__source:!0};function E(l,p,w){var b,P={},L=null,x=null;w!==void 0&&(L=""+w),p.key!==void 0&&(L=""+p.key),p.ref!==void 0&&(x=p.ref);for(b in p)r.call(p,b)&&!g.hasOwnProperty(b)&&(P[b]=p[b]);if(l&&l.defaultProps)for(b in p=l.defaultProps,p)P[b]===void 0&&(P[b]=p[b]);return{$$typeof:t,type:l,key:L,ref:x,props:P,_owner:s.current}}return N.Fragment=o,N.jsx=E,N.jsxs=E,N}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 pe;function Ze(){return pe||(pe=1,process.env.NODE_ENV!=="production"&&function(){var a=m,t=Symbol.for("react.element"),o=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),g=Symbol.for("react.profiler"),E=Symbol.for("react.provider"),l=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),b=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),G=Symbol.iterator,q="@@iterator";function ye(e){if(e===null||typeof e!="object")return null;var n=G&&e[G]||e[q];return typeof n=="function"?n:null}var j=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function R(e){{for(var n=arguments.length,i=new Array(n>1?n-1:0),u=1;u<n;u++)i[u-1]=arguments[u];me("error",e,i)}}function me(e,n,i){{var u=j.ReactDebugCurrentFrame,d=u.getStackAddendum();d!==""&&(n+="%s",i=i.concat([d]));var v=i.map(function(f){return String(f)});v.unshift("Warning: "+n),Function.prototype.apply.call(console[e],console,v)}}var Se=!1,Z=!1,D=!1,ee=!1,rt=!1,be;be=Symbol.for("react.module.reference");function it(e){return!!(typeof e=="string"||typeof e=="function"||e===r||e===g||rt||e===s||e===w||e===b||ee||e===x||Se||Z||D||typeof e=="object"&&e!==null&&(e.$$typeof===L||e.$$typeof===P||e.$$typeof===E||e.$$typeof===l||e.$$typeof===p||e.$$typeof===be||e.getModuleId!==void 0))}function ot(e,n,i){var u=e.displayName;if(u)return u;var d=n.displayName||n.name||"";return d!==""?i+"("+d+")":i}function Ce(e){return e.displayName||"Context"}function I(e){if(e==null)return null;if(typeof e.tag=="number"&&R("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 r:return"Fragment";case o:return"Portal";case g:return"Profiler";case s:return"StrictMode";case w:return"Suspense";case b:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case l:var n=e;return Ce(n)+".Consumer";case E:var i=e;return Ce(i._context)+".Provider";case p:return ot(e,e.render,"ForwardRef");case P:var u=e.displayName||null;return u!==null?u:I(e.type)||"Memo";case L:{var d=e,v=d._payload,f=d._init;try{return I(f(v))}catch{return null}}}return null}var M=Object.assign,Y=0,Ee,ke,Re,we,_e,Pe,Ae;function Le(){}Le.__reactDisabledLog=!0;function st(){{if(Y===0){Ee=console.log,ke=console.info,Re=console.warn,we=console.error,_e=console.group,Pe=console.groupCollapsed,Ae=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Le,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Y++}}function at(){{if(Y--,Y===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:M({},e,{value:Ee}),info:M({},e,{value:ke}),warn:M({},e,{value:Re}),error:M({},e,{value:we}),group:M({},e,{value:_e}),groupCollapsed:M({},e,{value:Pe}),groupEnd:M({},e,{value:Ae})})}Y<0&&R("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var te=j.ReactCurrentDispatcher,ne;function J(e,n,i){{if(ne===void 0)try{throw Error()}catch(d){var u=d.stack.trim().match(/\n( *(at )?)/);ne=u&&u[1]||""}return` `+ne+e}}var re=!1,$;{var ut=typeof WeakMap=="function"?WeakMap:Map;$=new ut}function xe(e,n){if(!e||re)return"";{var i=$.get(e);if(i!==void 0)return i}var u;re=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var v;v=te.current,te.current=null,st();try{if(n){var f=function(){throw Error()};if(Object.defineProperty(f.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(f,[])}catch(O){u=O}Reflect.construct(e,[],f)}else{try{f.call()}catch(O){u=O}e.call(f.prototype)}}else{try{throw Error()}catch(O){u=O}e()}}catch(O){if(O&&u&&typeof O.stack=="string"){for(var c=O.stack.split(` `),A=u.stack.split(` `),S=c.length-1,C=A.length-1;S>=1&&C>=0&&c[S]!==A[C];)C--;for(;S>=1&&C>=0;S--,C--)if(c[S]!==A[C]){if(S!==1||C!==1)do if(S--,C--,C<0||c[S]!==A[C]){var T=` `+c[S].replace(" at new "," at ");return e.displayName&&T.includes("<anonymous>")&&(T=T.replace("<anonymous>",e.displayName)),typeof e=="function"&&$.set(e,T),T}while(S>=1&&C>=0);break}}}finally{re=!1,te.current=v,at(),Error.prepareStackTrace=d}var V=e?e.displayName||e.name:"",U=V?J(V):"";return typeof e=="function"&&$.set(e,U),U}function ct(e,n,i){return xe(e,!1)}function lt(e){var n=e.prototype;return!!(n&&n.isReactComponent)}function K(e,n,i){if(e==null)return"";if(typeof e=="function")return xe(e,lt(e));if(typeof e=="string")return J(e);switch(e){case w:return J("Suspense");case b:return J("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case p:return ct(e.render);case P:return K(e.type,n,i);case L:{var u=e,d=u._payload,v=u._init;try{return K(v(d),n,i)}catch{}}}return""}var Q=Object.prototype.hasOwnProperty,Oe={},Te=j.ReactDebugCurrentFrame;function H(e){if(e){var n=e._owner,i=K(e.type,e._source,n?n.type:null);Te.setExtraStackFrame(i)}else Te.setExtraStackFrame(null)}function ft(e,n,i,u,d){{var v=Function.call.bind(Q);for(var f in e)if(v(e,f)){var c=void 0;try{if(typeof e[f]!="function"){var A=Error((u||"React class")+": "+i+" type `"+f+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[f]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw A.name="Invariant Violation",A}c=e[f](n,f,u,i,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(S){c=S}c&&!(c instanceof Error)&&(H(d),R("%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).",u||"React class",i,f,typeof c),H(null)),c instanceof Error&&!(c.message in Oe)&&(Oe[c.message]=!0,H(d),R("Failed %s type: %s",i,c.message),H(null))}}}var dt=Array.isArray;function ie(e){return dt(e)}function ht(e){{var n=typeof Symbol=="function"&&Symbol.toStringTag,i=n&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i}}function gt(e){try{return De(e),!1}catch{return!0}}function De(e){return""+e}function We(e){if(gt(e))return R("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ht(e)),De(e)}var z=j.ReactCurrentOwner,pt={key:!0,ref:!0,__self:!0,__source:!0},Ie,je,oe;oe={};function vt(e){if(Q.call(e,"ref")){var n=Object.getOwnPropertyDescriptor(e,"ref").get;if(n&&n.isReactWarning)return!1}return e.ref!==void 0}function yt(e){if(Q.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function mt(e,n){if(typeof e.ref=="string"&&z.current&&n&&z.current.stateNode!==n){var i=I(z.current.type);oe[i]||(R('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',I(z.current.type),e.ref),oe[i]=!0)}}function St(e,n){{var i=function(){Ie||(Ie=!0,R("%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))};i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}}function bt(e,n){{var i=function(){je||(je=!0,R("%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))};i.isReactWarning=!0,Object.defineProperty(e,"ref",{get:i,configurable:!0})}}var Ct=function(e,n,i,u,d,v,f){var c={$$typeof:t,type:e,key:n,ref:i,props:f,_owner:v};return c._store={},Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_self",{configurable:!1,enumerable:!1,writable:!1,value:u}),Object.defineProperty(c,"_source",{configurable:!1,enumerable:!1,writable:!1,value:d}),Object.freeze&&(Object.freeze(c.props),Object.freeze(c)),c};function Et(e,n,i,u,d){{var v,f={},c=null,A=null;i!==void 0&&(We(i),c=""+i),yt(n)&&(We(n.key),c=""+n.key),vt(n)&&(A=n.ref,mt(n,d));for(v in n)Q.call(n,v)&&!pt.hasOwnProperty(v)&&(f[v]=n[v]);if(e&&e.defaultProps){var S=e.defaultProps;for(v in S)f[v]===void 0&&(f[v]=S[v])}if(c||A){var C=typeof e=="function"?e.displayName||e.name||"Unknown":e;c&&St(f,C),A&&bt(f,C)}return Ct(e,c,A,d,u,z.current,f)}}var se=j.ReactCurrentOwner,Me=j.ReactDebugCurrentFrame;function F(e){if(e){var n=e._owner,i=K(e.type,e._source,n?n.type:null);Me.setExtraStackFrame(i)}else Me.setExtraStackFrame(null)}var ae;ae=!1;function ue(e){return typeof e=="object"&&e!==null&&e.$$typeof===t}function Ue(){{if(se.current){var e=I(se.current.type);if(e)return` Check the render method of \``+e+"`."}return""}}function kt(e){{if(e!==void 0){var n=e.fileName.replace(/^.*[\\\/]/,""),i=e.lineNumber;return` Check your code at `+n+":"+i+"."}return""}}var Fe={};function Rt(e){{var n=Ue();if(!n){var i=typeof e=="string"?e:e.displayName||e.name;i&&(n=` Check the top-level render call using <`+i+">.")}return n}}function Ve(e,n){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var i=Rt(n);if(Fe[i])return;Fe[i]=!0;var u="";e&&e._owner&&e._owner!==se.current&&(u=" It was passed a child from "+I(e._owner.type)+"."),F(e),R('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',i,u),F(null)}}function Ne(e,n){{if(typeof e!="object")return;if(ie(e))for(var i=0;i<e.length;i++){var u=e[i];ue(u)&&Ve(u,n)}else if(ue(e))e._store&&(e._store.validated=!0);else if(e){var d=ye(e);if(typeof d=="function"&&d!==e.entries)for(var v=d.call(e),f;!(f=v.next()).done;)ue(f.value)&&Ve(f.value,n)}}}function wt(e){{var n=e.type;if(n==null||typeof n=="string")return;var i;if(typeof n=="function")i=n.propTypes;else if(typeof n=="object"&&(n.$$typeof===p||n.$$typeof===P))i=n.propTypes;else return;if(i){var u=I(n);ft(i,e.props,"prop",u,e)}else if(n.PropTypes!==void 0&&!ae){ae=!0;var d=I(n);R("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",d||"Unknown")}typeof n.getDefaultProps=="function"&&!n.getDefaultProps.isReactClassApproved&&R("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function _t(e){{for(var n=Object.keys(e.props),i=0;i<n.length;i++){var u=n[i];if(u!=="children"&&u!=="key"){F(e),R("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",u),F(null);break}}e.ref!==null&&(F(e),R("Invalid attribute `ref` supplied to `React.Fragment`."),F(null))}}var Be={};function Ye(e,n,i,u,d,v){{var f=it(e);if(!f){var c="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(c+=" 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 A=kt(d);A?c+=A:c+=Ue();var S;e===null?S="null":ie(e)?S="array":e!==void 0&&e.$$typeof===t?(S="<"+(I(e.type)||"Unknown")+" />",c=" Did you accidentally export a JSX literal instead of a component?"):S=typeof e,R("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",S,c)}var C=Et(e,n,i,d,v);if(C==null)return C;if(f){var T=n.children;if(T!==void 0)if(u)if(ie(T)){for(var V=0;V<T.length;V++)Ne(T[V],e);Object.freeze&&Object.freeze(T)}else R("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 Ne(T,e)}if(Q.call(n,"key")){var U=I(e),O=Object.keys(n).filter(function(Tt){return Tt!=="key"}),ce=O.length>0?"{key: someKey, "+O.join(": ..., ")+": ...}":"{key: someKey}";if(!Be[U+ce]){var Ot=O.length>0?"{"+O.join(": ..., ")+": ...}":"{}";R(`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} />`,ce,U,Ot,U),Be[U+ce]=!0}}return e===r?_t(C):wt(C),C}}function Pt(e,n,i){return Ye(e,n,i,!0)}function At(e,n,i){return Ye(e,n,i,!1)}var Lt=At,xt=Pt;B.Fragment=r,B.jsx=Lt,B.jsxs=xt}()),B}process.env.NODE_ENV==="production"?X.exports=qe():X.exports=Ze();var et=X.exports;const ve=m.createContext({connect:async()=>{},disconnect:async()=>{},startListening:async()=>{},stopListening:async()=>{},sendTextEvent:async a=>{},isConnected:!1,isListening:!1,isPlaying:!1,audioStats:null,debugMessages:[],error:null}),tt=()=>m.useContext(ve),nt=({children:a,config:t,autoConnect:o=!1})=>{const r=m.useRef(null),[s,g]=m.useState(!1),[E,l]=m.useState(!1),[p,w]=m.useState(!1),[b,P]=m.useState(null),[L,x]=m.useState(null),[G,q]=m.useState([]);m.useEffect(()=>{try{return r.current=new he(t),r.current.setCallbacks({onOpen:()=>{g(!0),x(null)},onClose:()=>{g(!1)},onError:()=>{x("Connection error occurred")},onListeningStart:()=>{l(!0)},onListeningStop:()=>{l(!1)},onAudioStart:()=>{w(!0)},onAudioStop:()=>{w(!1)},onAudioStats:D=>{P(D)},onDebugMessage:D=>{q([...D])}}),o&&r.current.connect(),()=>{r.current&&(r.current.disconnect(),r.current=null)}}catch(D){x("Failed to initialize client"),console.error("Error initializing PrimVoices client:",D)}},[t,o]);const Z={connect:async()=>{if(r.current)try{await r.current.connect()}catch{x("Failed to connect")}else x("Client not initialized")},disconnect:async()=>{r.current&&await r.current.disconnect()},startListening:async()=>{if(r.current)try{await r.current.startListening()}catch{x("Failed to start microphone")}else x("Client not initialized")},stopListening:async()=>{r.current&&await r.current.stopListening()},sendTextEvent:async D=>{if(r.current&&s)try{await r.current.sendTextEvent(D)}catch(ee){x("Failed to send message"),console.error("Error sending text message:",ee)}else x("Client not connected")},isConnected:s,isListening:E,isPlaying:p,audioStats:b,debugMessages:G,error:L};return et.jsx(ve.Provider,{value:Z,children:a})};_.PrimVoicesProvider=nt,_.WebSocketClient=he,_.usePrimVoices=tt,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=index.umd.js.map