UNPKG

@speechmatics/real-time-client

Version:
2 lines (1 loc) 4.22 kB
(function(i,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(i=typeof globalThis<"u"?globalThis:i||self,d(i.BrowserAudioInput={}))})(this,function(i){var d=class extends EventTarget{dispatchTypedEvent(t,e){return super.dispatchEvent(e)}},S=Object.defineProperty,f=(t,e,s)=>e in t?S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,c=(t,e,s)=>f(t,typeof e!="symbol"?e+"":e,s);class h extends Event{constructor(e){super("socketStateChange"),this.socketState=e}}class m extends Event{constructor(e){super("receiveMessage"),this.data=e}}class l extends Event{constructor(e){super("sendMessage"),this.data=e}}class E extends d{constructor(e={}){super(),c(this,"url"),c(this,"appId"),c(this,"enableLegacy"),c(this,"timeout"),c(this,"socket"),c(this,"lastAudioAddedSeqNo",0),this.url=e.url??"wss://eu2.rt.speechmatics.com/v2",this.appId=e.appId,this.enableLegacy=e.enableLegacy??!1,this.timeout=e.connectionTimeout??1e4}get socketState(){if(this.socket)return{[WebSocket.CONNECTING]:"connecting",[WebSocket.OPEN]:"open",[WebSocket.CLOSING]:"closing",[WebSocket.CLOSED]:"closed"}[this.socket.readyState]}async connect(e){return new Promise((s,o)=>{const a=new URL(this.url);a.searchParams.append("jwt",e),this.appId&&a.searchParams.append("sm-app",this.appId),this.enableLegacy&&a.searchParams.append("sm-enable-legacy-rt","true"),this.socket=new WebSocket(a.toString()),this.dispatchTypedEvent("socketStateChange",new h(this.socketState)),this.socket.addEventListener("open",()=>{s()},{once:!0}),this.socket.addEventListener("error",n=>{this.dispatchTypedEvent("socketStateChange",new h(this.socketState)),o(n)}),this.socket.addEventListener("close",()=>{this.dispatchTypedEvent("socketStateChange",new h(this.socketState))}),this.socket.addEventListener("message",n=>{const r=JSON.parse(n.data);if(!k(r)){console.warn("message does not look like a valid message: ",JSON.stringify(r));return}r.message==="AudioAdded"&&(this.lastAudioAddedSeqNo=r.seq_no),this.dispatchTypedEvent("receiveMessage",new m(r))})})}sendMessage(e){if(!this.socket)throw new g("Client socket not initialized");this.socket.send(JSON.stringify(e)),this.dispatchTypedEvent("sendMessage",new l(e))}sendAudio(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new g("Socket not ready to receive audio");this.socket.send(e)}async getSpeakers(e={}){this.sendMessage({message:"GetSpeakers",final:e.final});const s=new Promise((o,a)=>{this.addEventListener("receiveMessage",({data:n})=>{n.message==="SpeakersResult"?o(n):n.message==="Error"&&a(new Error(n.type))}),this.addEventListener("socketStateChange",n=>{n.socketState==="closed"&&a(new Error("Socket closed"))})});return e.timeout?Promise.race([s,p(e.timeout,"SpeakersResult")]):s}async start(e,s){await this.connect(e);const o=new Promise((a,n)=>{this.addEventListener("receiveMessage",({data:u})=>{u.message==="RecognitionStarted"?a(u):u.message==="Error"&&n(new Error(u.type))});const r={audio_format:v,...s,message:"StartRecognition"};this.sendMessage(r)});return Promise.race([o,p(this.timeout,"RecognitionStarted")])}async stopRecognition({noTimeout:e}={}){const s=new Promise(o=>{this.addEventListener("receiveMessage",({data:a})=>{a.message==="EndOfTranscript"&&(this.socket?.close(),o())}),this.sendMessage({message:"EndOfStream",last_seq_no:this.lastAudioAddedSeqNo})});if(!e)return Promise.race([s,p(this.timeout,"EndOfTranscript")])}setRecognitionConfig(e){this.sendMessage({message:"SetRecognitionConfig",transcription_config:e})}forceEndOfUtterance(e){this.sendMessage({message:"ForceEndOfUtterance",channel:e})}}function k(t){return!(typeof t!="object"||t===null||!("message"in t)||typeof t.message!="string")}const v={type:"file"};class g extends Error{constructor(e,s){super(e,s),this.name="SpeechmaticsRealtimeError"}}function p(t,e){return new Promise((s,o)=>{setTimeout(()=>o(new g(`Timed out after ${t}ms waiting for ${e}`)),t)})}async function y(t="eu2"){return(await fetch(`https://${t}.rt.speechmatics.com/v1/discovery/features`)).json()}i.RealtimeClient=E,i.ReceiveMessageEvent=m,i.SendMessageEvent=l,i.SocketStateChangeEvent=h,i.SpeechmaticsRealtimeError=g,i.getFeatures=y});