-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSocket.ts
More file actions
197 lines (173 loc) · 7.06 KB
/
Copy pathSocket.ts
File metadata and controls
197 lines (173 loc) · 7.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/**
* This file was auto-generated by Fern from our API Definition.
*/
import * as core from "../../../../core/index.js";
import * as Corti from "../../../index.js";
import { TranscribeConfigMessage } from "../../../../serialization/types/TranscribeConfigMessage.js";
import { TranscribeFlushMessage } from "../../../../serialization/types/TranscribeFlushMessage.js";
import { TranscribeEndMessage } from "../../../../serialization/types/TranscribeEndMessage.js";
import { fromJson } from "../../../../core/json.js";
import * as serializers from "../../../../serialization/index.js";
export declare namespace TranscribeSocket {
export interface Args {
socket: core.ReconnectingWebSocket;
}
export type Response =
| Corti.TranscribeConfigStatusMessage
| Corti.TranscribeUsageMessage
| Corti.TranscribeFlushedMessage
| Corti.TranscribeEndedMessage
| Corti.TranscribeErrorMessage
| Corti.TranscribeTranscriptMessage
| Corti.TranscribeCommandMessage;
type EventHandlers = {
open?: () => void;
message?: (message: Response) => void;
close?: (event: core.CloseEvent) => void;
error?: (error: Error) => void;
};
}
export class TranscribeSocket {
public readonly socket: core.ReconnectingWebSocket;
protected readonly eventHandlers: TranscribeSocket.EventHandlers = {};
private handleOpen: () => void = () => {
this.eventHandlers.open?.();
};
private handleMessage: (event: { data: string }) => void = (event) => {
const data = fromJson(event.data);
const parsedResponse = serializers.TranscribeSocketResponse.parse(data, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
omitUndefined: true,
});
if (parsedResponse.ok) {
this.eventHandlers.message?.(parsedResponse.value);
} else {
this.eventHandlers.error?.(new Error("Received unknown message type"));
}
};
private handleClose: (event: core.CloseEvent) => void = (event) => {
this.eventHandlers.close?.(event);
};
private handleError: (event: core.ErrorEvent) => void = (event) => {
const message = event.message;
this.eventHandlers.error?.(new Error(message));
};
constructor(args: TranscribeSocket.Args) {
this.socket = args.socket;
this.socket.addEventListener("open", this.handleOpen);
this.socket.addEventListener("message", this.handleMessage);
this.socket.addEventListener("close", this.handleClose);
this.socket.addEventListener("error", this.handleError);
}
/** The current state of the connection; this is one of the readyState constants. */
get readyState(): number {
return this.socket.readyState;
}
/**
* @param event - The event to attach to.
* @param callback - The callback to run when the event is triggered.
* Usage:
* ```typescript
* this.on('open', () => {
* console.log('The websocket is open');
* });
* ```
*/
public on<T extends keyof TranscribeSocket.EventHandlers>(event: T, callback: TranscribeSocket.EventHandlers[T]) {
this.eventHandlers[event] = callback;
}
public sendConfiguration(message: Corti.TranscribeConfigMessage): void {
this.assertSocketIsOpen();
const jsonPayload = TranscribeConfigMessage.jsonOrThrow(message, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
omitUndefined: true,
});
this.socket.send(JSON.stringify(jsonPayload));
}
public sendAudio(message: string): void {
this.assertSocketIsOpen();
const jsonPayload = core.serialization
.string()
.jsonOrThrow(message, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
omitUndefined: true,
});
this.socket.send(JSON.stringify(jsonPayload));
}
public sendFlush(message: Corti.TranscribeFlushMessage): void {
this.assertSocketIsOpen();
const jsonPayload = TranscribeFlushMessage.jsonOrThrow(message, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
omitUndefined: true,
});
this.socket.send(JSON.stringify(jsonPayload));
}
public sendEnd(message: Corti.TranscribeEndMessage): void {
this.assertSocketIsOpen();
const jsonPayload = TranscribeEndMessage.jsonOrThrow(message, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
omitUndefined: true,
});
this.socket.send(JSON.stringify(jsonPayload));
}
/** Connect to the websocket and register event handlers. */
public connect(): TranscribeSocket {
this.socket.reconnect();
this.socket.addEventListener("open", this.handleOpen);
this.socket.addEventListener("message", this.handleMessage);
this.socket.addEventListener("close", this.handleClose);
this.socket.addEventListener("error", this.handleError);
return this;
}
/** Close the websocket and unregister event handlers. */
public close(): void {
this.socket.close();
this.handleClose({ code: 1000 } as CloseEvent);
this.socket.removeEventListener("open", this.handleOpen);
this.socket.removeEventListener("message", this.handleMessage);
this.socket.removeEventListener("close", this.handleClose);
this.socket.removeEventListener("error", this.handleError);
}
/** Returns a promise that resolves when the websocket is open. */
public async waitForOpen(): Promise<core.ReconnectingWebSocket> {
if (this.socket.readyState === core.ReconnectingWebSocket.OPEN) {
return this.socket;
}
return new Promise((resolve, reject) => {
this.socket.addEventListener("open", () => {
resolve(this.socket);
});
this.socket.addEventListener("error", (event: unknown) => {
reject(event);
});
});
}
/** Asserts that the websocket is open. */
private assertSocketIsOpen(): void {
if (!this.socket) {
throw new Error("Socket is not connected.");
}
if (this.socket.readyState !== core.ReconnectingWebSocket.OPEN) {
throw new Error("Socket is not open.");
}
}
/** Send a binary payload to the websocket. */
protected sendBinary(payload: ArrayBufferLike | Blob | ArrayBufferView): void {
this.socket.send(payload);
}
}