primvoices-react
Version:
React client for the PrimVoices Agents API
1,483 lines (1,474 loc) • 44.1 kB
JavaScript
var St = Object.defineProperty;
var bt = (a, t, o) => t in a ? St(a, t, { enumerable: !0, configurable: !0, writable: !0, value: o }) : a[t] = o;
var h = (a, t, o) => (bt(a, typeof t != "symbol" ? t + "" : t, o), o);
import Ne, { createContext as Ct, useContext as Et, useRef as kt, useState as F, useEffect as Rt } from "react";
let q;
const wt = new Uint8Array(16);
function _t() {
if (!q && (q = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !q))
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
return q(wt);
}
const k = [];
for (let a = 0; a < 256; ++a)
k.push((a + 256).toString(16).slice(1));
function At(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 Lt = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), je = {
randomUUID: Lt
};
function Me(a, t, o) {
if (je.randomUUID && !t && !a)
return je.randomUUID();
a = a || {};
const r = a.random || (a.rng || _t)();
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 At(r);
}
const Pt = 132, Fe = 32635, xt = [
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 Ot(a) {
let t, o, r, s;
return t = a >> 8 & 128, t != 0 && (a = -a), a = a + Pt, a > Fe && (a = Fe), o = xt[a >> 7 & 255], r = a >> o + 3 & 15, s = ~(t | o << 4 | r), s;
}
function Tt(a) {
let t = new Uint8Array(a.length);
for (let o = 0; o < a.length; o++)
t[o] = Ot(a[o]);
return t;
}
class Dt {
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 Dt();
class Wt {
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);
// Callbacks
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();
}
/**
* Set callbacks for different events
*/
setCallbacks({
onOpen: t,
onClose: o,
onError: r,
onListeningStart: s,
onListeningStop: g,
onAudioStart: C,
onAudioStop: l,
onAudioStats: p,
onDebugMessage: R
}) {
this.onConnectionOpen = t || null, this.onConnectionClose = o || null, this.onConnectionError = r || null, this.onStartListening = s || null, this.onStopListening = g || null, this.onPlayStart = C || null, this.onPlayStop = l || null, this.onAudioStats = p || null, this.onDebugMessage = R || 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;
}
/**
* Initialize the WebSocket connection
*/
async connect() {
if (this.callSid = Me(), this.streamSid = Me(), 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);
}
};
});
}
/**
* Handle audio data received from the server
*/
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 C = new Float32Array(g.length);
for (let l = 0; l < g.length; l++)
C[l] = g[l] / 32768;
this.addToAudioQueue(C, 24e3);
}
handleClearMessage(t) {
y.info("[WebSocketClient] Received clear message:", t), this.clearAudioQueue();
}
/**
* Handle mark events received from the server
* These marks will be associated with the next audio chunk received
*/
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);
}
/**
* Handle debug messages received from the server
*/
handleDebugMessage(t) {
y.info("[WebSocketClient] Received debug message:", t), this.debugQueue.push(t), this.onDebugMessage && this.onDebugMessage(this.debugQueue);
}
/**
* Initialize the audio context and related components
*/
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);
}
}
/**
* Start capturing audio from the microphone and sending it to the server
*/
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;
}
}
/**
* Stop capturing audio from the microphone
*/
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"));
}
/**
* Send a text message to the server
*/
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 }));
}
/**
* Close the WebSocket connection and clean up resources
*/
disconnect() {
this.stopListening(), this.clearAudioQueue(), this.stopAudioStatsMonitoring(), this.socket && (this.socket.close(), this.socket = null), this.isConnected = !1, this.onConnectionClose && this.onConnectionClose();
}
/**
* Process captured audio data and send it to the server
*/
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((S) => Math.abs(S) > 0.01);
y.debug(`[WebSocketClient] Processing audio frame: ${t.length} samples at ${r}Hz ${g ? "(has sound)" : "(silent)"}`);
const C = this.downsampleBuffer(t, r, s);
y.debug(`[WebSocketClient] Downsampled to ${C.length} samples at ${s}Hz`);
const l = Tt(C);
y.debug(`[WebSocketClient] Converted to μ-law format: ${l.length} bytes`);
const p = this.arrayBufferToBase64(l.buffer), R = {
event: "media",
streamSid: this.streamSid,
media: {
payload: p
}
};
this.socket.send(JSON.stringify(R)), y.debug(`[WebSocketClient] Sent μ-law encoded audio: ${p.length} base64 chars`);
} catch (r) {
y.error("[WebSocketClient] Error processing or sending audio:", r);
}
}
/**
* Convert array buffer to base64
*/
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);
}
/**
* Downsample audio buffer - matches audio.ts implementation
*/
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), C = new Int16Array(g);
let l = 0;
for (let p = 0; p < g; p++) {
const R = Math.round((p + 1) * s);
let S = 0, w = 0;
for (let A = l; A < R && A < t.length; A++)
S += t[A], w++;
C[p] = w > 0 ? Math.round(S / w * 32767) : 0, l = R;
}
return C;
}
/**
* Add audio data to the playback queue
*/
addToAudioQueue(t, o = 16e3, r) {
this.audioQueue.push({ data: t, sampleRate: o, mark: r }), this.isPlaying || this.playNextInQueue();
}
/**
* Clear the audio playback queue and stop any current playback
*/
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;
}
/**
* Clear the debug queue
*/
clearDebugQueue() {
this.debugQueue = [], this.onDebugMessage && this.onDebugMessage([]);
}
/**
* Play the next audio chunk in the queue
*/
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();
}
/**
* Get the current audio level (volume) from the analyzer
* This works for both microphone input and audio playback, depending on what"s currently active
*/
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;
}
/**
* Start monitoring audio levels for speech detection
*/
startAudioStatsMonitoring() {
this.statsInterval && clearInterval(this.statsInterval), this.statsInterval = window.setInterval(() => {
const t = this.getAudioLevel(), o = t > 0.1;
this.onAudioStats && this.onAudioStats({
level: t,
isSpeaking: o,
isPlayback: this.isPlaying
// Indicate if these stats are from playback
}), o !== this.speechDetected && (this.speechDetected = o);
}, 100);
}
/**
* Stop audio stats monitoring
*/
stopAudioStatsMonitoring() {
this.statsInterval && !this.isListening && !this.isPlaying && (clearInterval(this.statsInterval), this.statsInterval = null);
}
/**
* Utility methods to check current state
*/
isCurrentlyConnected() {
return this.isConnected;
}
isCurrentlyListening() {
return this.isListening;
}
isCurrentlyPlaying() {
return this.isPlaying;
}
}
var ue = { 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 Ue;
function It() {
if (Ue)
return V;
Ue = 1;
var a = Ne, 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 C(l, p, R) {
var S, w = {}, A = null, L = null;
R !== void 0 && (A = "" + R), p.key !== void 0 && (A = "" + p.key), p.ref !== void 0 && (L = p.ref);
for (S in p)
r.call(p, S) && !g.hasOwnProperty(S) && (w[S] = p[S]);
if (l && l.defaultProps)
for (S in p = l.defaultProps, p)
w[S] === void 0 && (w[S] = p[S]);
return { $$typeof: t, type: l, key: A, ref: L, props: w, _owner: s.current };
}
return V.Fragment = o, V.jsx = C, V.jsxs = C, 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 $e;
function jt() {
return $e || ($e = 1, process.env.NODE_ENV !== "production" && function() {
var a = Ne, 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"), C = Symbol.for("react.provider"), l = Symbol.for("react.context"), p = Symbol.for("react.forward_ref"), R = Symbol.for("react.suspense"), S = Symbol.for("react.suspense_list"), w = Symbol.for("react.memo"), A = Symbol.for("react.lazy"), L = Symbol.for("react.offscreen"), Y = Symbol.iterator, K = "@@iterator";
function ce(e) {
if (e === null || typeof e != "object")
return null;
var n = Y && e[Y] || e[K];
return typeof n == "function" ? n : null;
}
var D = a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
function E(e) {
{
for (var n = arguments.length, i = new Array(n > 1 ? n - 1 : 0), u = 1; u < n; u++)
i[u - 1] = arguments[u];
le("error", e, i);
}
}
function le(e, n, i) {
{
var u = D.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 fe = !1, H = !1, O = !1, X = !1, Be = !1, de;
de = Symbol.for("react.module.reference");
function Ye(e) {
return !!(typeof e == "string" || typeof e == "function" || e === r || e === g || Be || e === s || e === R || e === S || X || e === L || fe || H || O || typeof e == "object" && e !== null && (e.$$typeof === A || e.$$typeof === w || e.$$typeof === C || e.$$typeof === l || e.$$typeof === p || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
e.$$typeof === de || e.getModuleId !== void 0));
}
function Qe(e, n, i) {
var u = e.displayName;
if (u)
return u;
var d = n.displayName || n.name || "";
return d !== "" ? i + "(" + d + ")" : i;
}
function he(e) {
return e.displayName || "Context";
}
function T(e) {
if (e == null)
return null;
if (typeof e.tag == "number" && E("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 R:
return "Suspense";
case S:
return "SuspenseList";
}
if (typeof e == "object")
switch (e.$$typeof) {
case l:
var n = e;
return he(n) + ".Consumer";
case C:
var i = e;
return he(i._context) + ".Provider";
case p:
return Qe(e, e.render, "ForwardRef");
case w:
var u = e.displayName || null;
return u !== null ? u : T(e.type) || "Memo";
case A: {
var d = e, v = d._payload, f = d._init;
try {
return T(f(v));
} catch {
return null;
}
}
}
return null;
}
var W = Object.assign, U = 0, ge, pe, ve, ye, me, Se, be;
function Ce() {
}
Ce.__reactDisabledLog = !0;
function ze() {
{
if (U === 0) {
ge = console.log, pe = console.info, ve = console.warn, ye = console.error, me = console.group, Se = console.groupCollapsed, be = console.groupEnd;
var e = {
configurable: !0,
enumerable: !0,
value: Ce,
writable: !0
};
Object.defineProperties(console, {
info: e,
log: e,
warn: e,
error: e,
group: e,
groupCollapsed: e,
groupEnd: e
});
}
U++;
}
}
function Ge() {
{
if (U--, U === 0) {
var e = {
configurable: !0,
enumerable: !0,
writable: !0
};
Object.defineProperties(console, {
log: W({}, e, {
value: ge
}),
info: W({}, e, {
value: pe
}),
warn: W({}, e, {
value: ve
}),
error: W({}, e, {
value: ye
}),
group: W({}, e, {
value: me
}),
groupCollapsed: W({}, e, {
value: Se
}),
groupEnd: W({}, e, {
value: be
})
});
}
U < 0 && E("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
}
}
var Z = D.ReactCurrentDispatcher, ee;
function Q(e, n, i) {
{
if (ee === void 0)
try {
throw Error();
} catch (d) {
var u = d.stack.trim().match(/\n( *(at )?)/);
ee = u && u[1] || "";
}
return `
` + ee + e;
}
}
var te = !1, z;
{
var Je = typeof WeakMap == "function" ? WeakMap : Map;
z = new Je();
}
function Ee(e, n) {
if (!e || te)
return "";
{
var i = z.get(e);
if (i !== void 0)
return i;
}
var u;
te = !0;
var d = Error.prepareStackTrace;
Error.prepareStackTrace = void 0;
var v;
v = Z.current, Z.current = null, ze();
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 (P) {
u = P;
}
Reflect.construct(e, [], f);
} else {
try {
f.call();
} catch (P) {
u = P;
}
e.call(f.prototype);
}
} else {
try {
throw Error();
} catch (P) {
u = P;
}
e();
}
} catch (P) {
if (P && u && typeof P.stack == "string") {
for (var c = P.stack.split(`
`), _ = u.stack.split(`
`), m = c.length - 1, b = _.length - 1; m >= 1 && b >= 0 && c[m] !== _[b]; )
b--;
for (; m >= 1 && b >= 0; m--, b--)
if (c[m] !== _[b]) {
if (m !== 1 || b !== 1)
do
if (m--, b--, b < 0 || c[m] !== _[b]) {
var x = `
` + c[m].replace(" at new ", " at ");
return e.displayName && x.includes("<anonymous>") && (x = x.replace("<anonymous>", e.displayName)), typeof e == "function" && z.set(e, x), x;
}
while (m >= 1 && b >= 0);
break;
}
}
} finally {
te = !1, Z.current = v, Ge(), Error.prepareStackTrace = d;
}
var M = e ? e.displayName || e.name : "", I = M ? Q(M) : "";
return typeof e == "function" && z.set(e, I), I;
}
function qe(e, n, i) {
return Ee(e, !1);
}
function Ke(e) {
var n = e.prototype;
return !!(n && n.isReactComponent);
}
function G(e, n, i) {
if (e == null)
return "";
if (typeof e == "function")
return Ee(e, Ke(e));
if (typeof e == "string")
return Q(e);
switch (e) {
case R:
return Q("Suspense");
case S:
return Q("SuspenseList");
}
if (typeof e == "object")
switch (e.$$typeof) {
case p:
return qe(e.render);
case w:
return G(e.type, n, i);
case A: {
var u = e, d = u._payload, v = u._init;
try {
return G(v(d), n, i);
} catch {
}
}
}
return "";
}
var $ = Object.prototype.hasOwnProperty, ke = {}, Re = D.ReactDebugCurrentFrame;
function J(e) {
if (e) {
var n = e._owner, i = G(e.type, e._source, n ? n.type : null);
Re.setExtraStackFrame(i);
} else
Re.setExtraStackFrame(null);
}
function He(e, n, i, u, d) {
{
var v = Function.call.bind($);
for (var f in e)
if (v(e, f)) {
var c = void 0;
try {
if (typeof e[f] != "function") {
var _ = 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 _.name = "Invariant Violation", _;
}
c = e[f](n, f, u, i, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
} catch (m) {
c = m;
}
c && !(c instanceof Error) && (J(d), E("%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), J(null)), c instanceof Error && !(c.message in ke) && (ke[c.message] = !0, J(d), E("Failed %s type: %s", i, c.message), J(null));
}
}
}
var Xe = Array.isArray;
function ne(e) {
return Xe(e);
}
function Ze(e) {
{
var n = typeof Symbol == "function" && Symbol.toStringTag, i = n && e[Symbol.toStringTag] || e.constructor.name || "Object";
return i;
}
}
function et(e) {
try {
return we(e), !1;
} catch {
return !0;
}
}
function we(e) {
return "" + e;
}
function _e(e) {
if (et(e))
return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", Ze(e)), we(e);
}
var N = D.ReactCurrentOwner, tt = {
key: !0,
ref: !0,
__self: !0,
__source: !0
}, Ae, Le, re;
re = {};
function nt(e) {
if ($.call(e, "ref")) {
var n = Object.getOwnPropertyDescriptor(e, "ref").get;
if (n && n.isReactWarning)
return !1;
}
return e.ref !== void 0;
}
function rt(e) {
if ($.call(e, "key")) {
var n = Object.getOwnPropertyDescriptor(e, "key").get;
if (n && n.isReactWarning)
return !1;
}
return e.key !== void 0;
}
function it(e, n) {
if (typeof e.ref == "string" && N.current && n && N.current.stateNode !== n) {
var i = T(N.current.type);
re[i] || (E('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', T(N.current.type), e.ref), re[i] = !0);
}
}
function ot(e, n) {
{
var i = function() {
Ae || (Ae = !0, E("%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 st(e, n) {
{
var i = function() {
Le || (Le = !0, E("%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 at = function(e, n, i, u, d, v, f) {
var c = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: t,
// Built-in properties that belong on the element
type: e,
key: n,
ref: i,
props: f,
// Record the component responsible for creating this element.
_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 ut(e, n, i, u, d) {
{
var v, f = {}, c = null, _ = null;
i !== void 0 && (_e(i), c = "" + i), rt(n) && (_e(n.key), c = "" + n.key), nt(n) && (_ = n.ref, it(n, d));
for (v in n)
$.call(n, v) && !tt.hasOwnProperty(v) && (f[v] = n[v]);
if (e && e.defaultProps) {
var m = e.defaultProps;
for (v in m)
f[v] === void 0 && (f[v] = m[v]);
}
if (c || _) {
var b = typeof e == "function" ? e.displayName || e.name || "Unknown" : e;
c && ot(f, b), _ && st(f, b);
}
return at(e, c, _, d, u, N.current, f);
}
}
var ie = D.ReactCurrentOwner, Pe = D.ReactDebugCurrentFrame;
function j(e) {
if (e) {
var n = e._owner, i = G(e.type, e._source, n ? n.type : null);
Pe.setExtraStackFrame(i);
} else
Pe.setExtraStackFrame(null);
}
var oe;
oe = !1;
function se(e) {
return typeof e == "object" && e !== null && e.$$typeof === t;
}
function xe() {
{
if (ie.current) {
var e = T(ie.current.type);
if (e)
return `
Check the render method of \`` + e + "`.";
}
return "";
}
}
function ct(e) {
{
if (e !== void 0) {
var n = e.fileName.replace(/^.*[\\\/]/, ""), i = e.lineNumber;
return `
Check your code at ` + n + ":" + i + ".";
}
return "";
}
}
var Oe = {};
function lt(e) {
{
var n = xe();
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 Te(e, n) {
{
if (!e._store || e._store.validated || e.key != null)
return;
e._store.validated = !0;
var i = lt(n);
if (Oe[i])
return;
Oe[i] = !0;
var u = "";
e && e._owner && e._owner !== ie.current && (u = " It was passed a child from " + T(e._owner.type) + "."), j(e), E('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), j(null);
}
}
function De(e, n) {
{
if (typeof e != "object")
return;
if (ne(e))
for (var i = 0; i < e.length; i++) {
var u = e[i];
se(u) && Te(u, n);
}
else if (se(e))
e._store && (e._store.validated = !0);
else if (e) {
var d = ce(e);
if (typeof d == "function" && d !== e.entries)
for (var v = d.call(e), f; !(f = v.next()).done; )
se(f.value) && Te(f.value, n);
}
}
}
function ft(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 || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
n.$$typeof === w))
i = n.propTypes;
else
return;
if (i) {
var u = T(n);
He(i, e.props, "prop", u, e);
} else if (n.PropTypes !== void 0 && !oe) {
oe = !0;
var d = T(n);
E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", d || "Unknown");
}
typeof n.getDefaultProps == "function" && !n.getDefaultProps.isReactClassApproved && E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
}
}
function dt(e) {
{
for (var n = Object.keys(e.props), i = 0; i < n.length; i++) {
var u = n[i];
if (u !== "children" && u !== "key") {
j(e), E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", u), j(null);
break;
}
}
e.ref !== null && (j(e), E("Invalid attribute `ref` supplied to `React.Fragment`."), j(null));
}
}
var We = {};
function Ie(e, n, i, u, d, v) {
{
var f = Ye(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 _ = ct(d);
_ ? c += _ : c += xe();
var m;
e === null ? m = "null" : ne(e) ? m = "array" : e !== void 0 && e.$$typeof === t ? (m = "<" + (T(e.type) || "Unknown") + " />", c = " Did you accidentally export a JSX literal instead of a component?") : m = typeof e, E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", m, c);
}
var b = ut(e, n, i, d, v);
if (b == null)
return b;
if (f) {
var x = n.children;
if (x !== void 0)
if (u)
if (ne(x)) {
for (var M = 0; M < x.length; M++)
De(x[M], e);
Object.freeze && Object.freeze(x);
} else
E("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
De(x, e);
}
if ($.call(n, "key")) {
var I = T(e), P = Object.keys(n).filter(function(mt) {
return mt !== "key";
}), ae = P.length > 0 ? "{key: someKey, " + P.join(": ..., ") + ": ...}" : "{key: someKey}";
if (!We[I + ae]) {
var yt = P.length > 0 ? "{" + P.join(": ..., ") + ": ...}" : "{}";
E(`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} />`, ae, I, yt, I), We[I + ae] = !0;
}
}
return e === r ? dt(b) : ft(b), b;
}
}
function ht(e, n, i) {
return Ie(e, n, i, !0);
}
function gt(e, n, i) {
return Ie(e, n, i, !1);
}
var pt = gt, vt = ht;
B.Fragment = r, B.jsx = pt, B.jsxs = vt;
}()), B;
}
process.env.NODE_ENV === "production" ? ue.exports = It() : ue.exports = jt();
var Mt = ue.exports;
const Ve = Ct({
connect: async () => {
},
disconnect: async () => {
},
startListening: async () => {
},
stopListening: async () => {
},
sendTextEvent: async (a) => {
},
isConnected: !1,
isListening: !1,
isPlaying: !1,
audioStats: null,
debugMessages: [],
error: null
}), $t = () => Et(Ve), Nt = ({
children: a,
config: t,
autoConnect: o = !1
}) => {
const r = kt(null), [s, g] = F(!1), [C, l] = F(!1), [p, R] = F(!1), [S, w] = F(null), [A, L] = F(null), [Y, K] = F([]);
Rt(() => {
try {
return r.current = new Wt(t), r.current.setCallbacks({
onOpen: () => {
g(!0), L(null);
},
onClose: () => {
g(!1);
},
onError: () => {
L("Connection error occurred");
},
onListeningStart: () => {
l(!0);
},
onListeningStop: () => {
l(!1);
},
onAudioStart: () => {
R(!0);
},
onAudioStop: () => {
R(!1);
},
onAudioStats: (O) => {
w(O);
},
onDebugMessage: (O) => {
K([...O]);
}
}), o && r.current.connect(), () => {
r.current && (r.current.disconnect(), r.current = null);
};
} catch (O) {
L("Failed to initialize client"), console.error("Error initializing PrimVoices client:", O);
}
}, [t, o]);
const H = {
connect: async () => {
if (r.current)
try {
await r.current.connect();
} catch {
L("Failed to connect");
}
else
L("Client not initialized");
},
disconnect: async () => {
r.current && await r.current.disconnect();
},
startListening: async () => {
if (r.current)
try {
await r.current.startListening();
} catch {
L("Failed to start microphone");
}
else
L("Client not initialized");
},
stopListening: async () => {
r.current && await r.current.stopListening();
},
sendTextEvent: async (O) => {
if (r.current && s)
try {
await r.current.sendTextEvent(O);
} catch (X) {
L("Failed to send message"), console.error("Error sending text message:", X);
}
else
L("Client not connected");
},
isConnected: s,
isListening: C,
isPlaying: p,
audioStats: S,
debugMessages: Y,
error: A
};
return /* @__PURE__ */ Mt.jsx(Ve.Provider, { value: H, children: a });
};
export {
Nt as PrimVoicesProvider,
Wt as WebSocketClient,
$t as usePrimVoices
};
//# sourceMappingURL=index.es.js.map