-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrpc-websocket.ts
More file actions
296 lines (238 loc) · 8.69 KB
/
trpc-websocket.ts
File metadata and controls
296 lines (238 loc) · 8.69 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// (global as any).WebSocket = SocketIOWebSocket;
// const wsClient = createWSClient({
// url: 'http://your-socket-server-url',
// });
// const shardProxyClient = createTRPCProxyClient<Shard.Router>({
// links: [
// wsLink({
// client: wsClient,
// }),
// ],
// transformer,
// });
// or:
// const socket = io('http://localhost:3000');
// const wrappedSocket = new SocketIOWebSocket(socket);
// // Adding an event listener
// wrappedSocket.addEventListener('customEvent', (data) => {
// console.log('Received customEvent:', data);
// });
// // Removing an event listener
// wrappedSocket.removeEventListener('customEvent', listener);
// // Sending a message
// wrappedSocket.send('Hello, World!');
import { io as socketIOClient, Socket } from 'socket.io-client';
type Listener = (event: Event) => void;
function createCloseEvent(code?: number, reason?: string): CloseEvent {
if (typeof CloseEvent === 'function') {
return new CloseEvent('close', { code, reason });
}
return { type: 'close', code: code ?? 1000, reason: reason ?? '' } as CloseEvent;
}
function createErrorEvent(error: unknown): Event {
if (typeof ErrorEvent === 'function') {
const message = error instanceof Error ? error.message : String(error ?? 'unknown error');
return new ErrorEvent('error', { error, message });
}
return { type: 'error', error } as Event;
}
function createEvent(type: string): Event {
if (typeof Event === 'function') {
return new Event(type);
}
return { type } as Event;
}
function createMessageEvent(data: unknown): MessageEvent {
if (typeof MessageEvent === 'function') {
return new MessageEvent('message', { data });
}
return { type: 'message', data } as MessageEvent;
}
const NATIVE_WEBSOCKET_EVENTS = new Set(['open', 'message', 'error', 'close']);
export default class SocketIOWebSocket implements WebSocket {
private ioSocket: Socket;
private eventListeners: Map<string, Function[]>;
private closeNotified = false;
private closedByClient = false;
// WebSocket properties
public readonly url: string;
public readonly protocol: string;
public readonly extensions: string = ''; // Socket.IO doesn't support WebSocket extensions
public readyState: number; // Translate Socket.IO states to WebSocket states
public bufferedAmount: number = 0; // Socket.IO doesn't expose this
public binaryType: BinaryType = 'blob'; // Not directly supported by Socket.IO, adjust as needed
public static readonly CONNECTING = 0;
public static readonly OPEN = 1;
public static readonly CLOSING = 2;
public static readonly CLOSED = 3;
public readonly CONNECTING = SocketIOWebSocket.CONNECTING;
public readonly OPEN = SocketIOWebSocket.OPEN;
public readonly CLOSING = SocketIOWebSocket.CLOSING;
public readonly CLOSED = SocketIOWebSocket.CLOSED;
constructor(url: string) {
console.log('SocketIOWebSocket.constructor');
this.ioSocket = socketIOClient(url, {
transports: ['websocket'],
upgrade: false,
autoConnect: false,
// pingInterval: 5000,
// pingTimeout: 20000
// extraHeaders: {
// "my-custom-header": "1234"
// }
});
// WebSocket interface compatibility
this.binaryType = 'blob';
this.readyState = SocketIOWebSocket.CONNECTING;
this.ioSocket.on('connect', () => {
console.log('SocketIOWebSocket.connect');
if (this.closedByClient) {
return;
}
this.readyState = SocketIOWebSocket.OPEN;
this.closeNotified = false;
const openEvent = createEvent('open');
if (this.onopen) this.onopen(openEvent);
this.dispatchListenerEvent('open', openEvent);
});
this.ioSocket.on('disconnect', (reason?: string) => {
console.log('SocketIOWebSocket.disconnect');
this.readyState = SocketIOWebSocket.CLOSED;
this.notifyClose(createCloseEvent(undefined, reason));
});
const handleMessage = (data: any) => {
console.log('SocketIOWebSocket.message');
if (this.readyState !== SocketIOWebSocket.OPEN) {
return;
}
const messageEvent = createMessageEvent(data);
if (this.onmessage) this.onmessage(messageEvent);
this.dispatchListenerEvent('message', messageEvent as unknown as Event);
};
this.ioSocket.on('message', handleMessage);
this.ioSocket.on('trpc', handleMessage);
this.ioSocket.on('error', (err: any) => {
console.log('SocketIOWebSocket.error');
if (this.closedByClient && this.readyState === SocketIOWebSocket.CLOSED) {
return;
}
const errorEvent = createErrorEvent(err);
if (this.onerror) this.onerror(errorEvent);
this.dispatchListenerEvent('error', errorEvent);
});
this.ioSocket.on('connect_error', (err: any) => {
console.log('SocketIOWebSocket.connect_error');
if (this.closedByClient && this.readyState === SocketIOWebSocket.CLOSED) {
return;
}
const errorEvent = createErrorEvent(err);
if (this.onerror) this.onerror(errorEvent);
this.dispatchListenerEvent('error', errorEvent);
});
this.eventListeners = new Map<string, Function[]>();
this.ioSocket.connect?.();
}
public onopen: ((event: Event) => void) | null = null;
public onmessage: ((event: MessageEvent) => void) | null = null;
public onerror: ((event: Event) => void) | null = null;
public onclose: ((event: CloseEvent) => void) | null = null;
public close(code?: number, reason?: string): void {
console.log('SocketIOWebSocket.close');
if (this.readyState === SocketIOWebSocket.CLOSING || this.readyState === SocketIOWebSocket.CLOSED) {
return;
}
this.readyState = SocketIOWebSocket.CLOSING;
this.closedByClient = true;
this.ioSocket.close();
this.readyState = SocketIOWebSocket.CLOSED;
this.notifyClose(createCloseEvent(code, reason));
}
private notifyClose(event: CloseEvent): void {
if (this.closeNotified) return;
this.closeNotified = true;
if (this.onclose) this.onclose(event);
this.dispatchListenerEvent('close', event as unknown as Event);
}
private dispatchListenerEvent(eventType: string, event: Event): void {
const listeners = this.eventListeners.get(eventType);
if (!listeners) {
return;
}
for (const listener of [...listeners]) {
try {
listener(event);
} catch (error) {
console.error('SocketIOWebSocket listener error', error);
}
}
}
public send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {
console.log('SocketIOWebSocket.send', data);
if (this.readyState !== SocketIOWebSocket.OPEN) {
throw new Error('SocketIOWebSocket is not open');
}
this.ioSocket.emit('trpc', data);
}
public dispatchEvent(event: Event): boolean {
console.log('SocketIOWebSocket.dispatchEvent', event);
if (!event || typeof event.type !== 'string') {
return false;
}
switch (event.type) {
case 'open':
if (this.onopen) this.onopen(event);
break;
case 'message':
if (this.onmessage) this.onmessage(event as unknown as MessageEvent);
break;
case 'error':
if (this.onerror) this.onerror(event);
break;
case 'close':
if (this.onclose) this.onclose(event as unknown as CloseEvent);
break;
default:
break;
}
this.dispatchListenerEvent(event.type, event);
return true;
}
// // Dispatch event (not part of WebSocket interface, but for internal use)
// private dispatchEvent(event: string, ...args: any[]) {
// if (this.eventListeners.has(event)) {
// for (const listener of this.eventListeners.get(event)!) {
// listener(...args);
// }
// }
// }
public addEventListener(event: string, listener: Listener) {
console.log('SocketIOWebSocket.addEventListener', event);
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
const listeners = this.eventListeners.get(event)!;
if (listeners.includes(listener)) {
return;
}
listeners.push(listener);
if (!NATIVE_WEBSOCKET_EVENTS.has(event)) {
this.ioSocket.on(event, listener as (...args: any[]) => void);
}
}
public removeEventListener(event: string, listener: Listener) {
console.log('SocketIOWebSocket.removeEventListener', event);
if (this.eventListeners.has(event)) {
const listeners = this.eventListeners.get(event)!;
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
if (!NATIVE_WEBSOCKET_EVENTS.has(event)) {
this.ioSocket.off(event, listener as (...args: any[]) => void);
}
}
if (listeners.length === 0) {
this.eventListeners.delete(event);
}
}
}
}