-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwebsocket.ts
More file actions
369 lines (332 loc) · 11.9 KB
/
websocket.ts
File metadata and controls
369 lines (332 loc) · 11.9 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import { NativeBridge } from './bridge';
import { WebSocketEvent } from './common';
import { WebSocketPolyfill } from './websocket.definition';
type ArrayBufferView = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | DataView;
type BinaryType = 'blob' | 'arraybuffer';
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
const CLOSED = 3;
const CLOSE_NORMAL = 1000;
const openWebsockets = new Set<WebSocketPolyfill>();
// const WEBSOCKET_EVENTS = ['close', 'error', 'message', 'open'];
// type WebSocketEventDefinitions = {
// websocketOpen: [{ id: number; protocol: string }];
// websocketClosed: [{ id: number; code: number; reason: string }];
// websocketMessage: [
// { type: 'binary'; id: number; data: string } | { type: 'text'; id: number; data: string }
// // | {type: 'blob', id: number, data: BlobData},
// ];
// websocketFailed: [{ id: number; message: string }];
// };
interface ExtraWebsocketOptions {
headers: { origin?: string; [key: string]: unknown };
nativescript: { handleThreading: boolean };
pinnedCertificates?: string[];
[key: string]: unknown;
}
/**
* Browser-compatible WebSockets implementation.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
* See https://github.com/websockets/ws
*/
export class WebSocket implements WebSocketPolyfill {
private nativeBridge: NativeBridge;
static CONNECTING: number = CONNECTING;
static OPEN: number = OPEN;
static CLOSING: number = CLOSING;
static CLOSED: number = CLOSED;
static HANDLE_THREADING = true;
CONNECTING: number = CONNECTING;
OPEN: number = OPEN;
CLOSING: number = CLOSING;
CLOSED: number = CLOSED;
// _socketId: number;
// _eventEmitter: NativeEventEmitter<WebSocketEventDefinitions>;
// _subscriptions: Array<EventSubscription>;
_binaryType: BinaryType;
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
onclose?: Function;
onerror?: Function;
onmessage?: Function;
onopen?: Function;
/* eslint-enable @typescript-eslint/no-unsafe-function-type */
bufferedAmount?: number;
extension?: string;
protocol?: string;
readyState: number = CONNECTING;
url: string;
private listeners: Record<string, Map<EventListenerOrEventListenerObject, boolean | AddEventListenerOptions> | undefined> = {
open: new Map(),
close: new Map(),
error: new Map(),
message: new Map(),
};
constructor(url: string, protocols?: string | Array<string>, options?: ExtraWebsocketOptions) {
this.nativeBridge = new NativeBridge(this);
this.url = url;
if (typeof protocols === 'string') {
protocols = [protocols];
}
if (!Array.isArray(protocols)) {
protocols = [];
}
const { headers = {}, nativescript = { handleThreading: true }, pinnedCertificates, ...unrecognized } = options || ({} as ExtraWebsocketOptions);
this.nativeBridge.handleThreading = nativescript?.handleThreading ?? WebSocket.HANDLE_THREADING;
this._binaryType = 'arraybuffer';
// Preserve deprecated backwards compatibility for the 'origin' option
if (unrecognized && typeof unrecognized.origin === 'string') {
console.warn('Specifying `origin` as a WebSocket connection option is deprecated. Include it under `headers` instead.');
/* $FlowFixMe[prop-missing] (>=0.54.0 site=react_native_fb,react_native_
* oss) This comment suppresses an error found when Flow v0.54 was
* deployed. To see the error delete this comment and run Flow. */
headers.origin = unrecognized.origin;
/* $FlowFixMe[prop-missing] (>=0.54.0 site=react_native_fb,react_native_
* oss) This comment suppresses an error found when Flow v0.54 was
* deployed. To see the error delete this comment and run Flow. */
delete unrecognized.origin;
}
// Warn about and discard anything else
if (Object.keys(unrecognized).length > 0) {
console.warn('Unrecognized WebSocket connection option(s) `' + Object.keys(unrecognized).join('`, `') + '`. ' + 'Did you mean to put these under `headers`?');
}
// this._eventEmitter = new NativeEventEmitter(
// // T88715063: NativeEventEmitter only used this parameter on iOS. Now it uses it on all platforms, so this code was modified automatically to preserve its behavior
// // If you want to use the native module on other platforms, please remove this condition and test its behavior
// Platform.OS !== 'ios' ? null : NativeWebSocketModule,
// );
this._registerEvents();
this.nativeBridge.connect({ url, protocols, headers: { headers }, pinnedCertificates });
openWebsockets.add(this);
// NativeWebSocketModule.connect(url, protocols, {headers}, this._socketId);
}
addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void {
if (!callback) {
return;
}
this.listeners[type]?.set(callback, options ?? false);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void {
if (!callback) {
return;
}
if (this.listeners[type]?.has(callback)) {
this.listeners[type]?.delete(callback);
}
}
get binaryType(): BinaryType {
return this._binaryType;
}
set binaryType(binaryType: BinaryType) {
if (binaryType !== 'blob' && binaryType !== 'arraybuffer') {
throw new Error("binaryType must be either 'blob' or 'arraybuffer'");
}
// if (this._binaryType === 'blob' || binaryType === 'blob') {
// invariant(
// BlobManager.isAvailable,
// 'Native module BlobModule is required for blob support',
// );
// if (binaryType === 'blob') {
// BlobManager.addWebSocketHandler(this._socketId);
// } else {
// BlobManager.removeWebSocketHandler(this._socketId);
// }
// }
this._binaryType = binaryType;
}
close(code?: number, reason?: string): void {
if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {
return;
}
this.readyState = this.CLOSING;
this._close(code, reason);
}
send(data: string | ArrayBuffer | ArrayBufferView | Blob): void {
if (this.readyState === this.CONNECTING) {
throw new Error('INVALID_STATE_ERR');
}
// if (data instanceof Blob) {
// invariant(
// BlobManager.isAvailable,
// 'Native module BlobModule is required for blob support',
// );
// BlobManager.sendOverSocket(data, this._socketId);
// return;
// }
if (typeof data === 'string') {
this.nativeBridge.send(data);
// NativeWebSocketModule.send(data, this._socketId);
return;
}
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
this.nativeBridge.send(data);
// NativeWebSocketModule.sendBinary(binaryToBase64(data), this._socketId);
return;
}
throw new Error('Unsupported data type');
}
ping(): void {
if (this.readyState === this.CONNECTING) {
throw new Error('INVALID_STATE_ERR');
}
// NativeWebSocketModule.ping(this._socketId);
this.nativeBridge.sendPing();
}
dispatchEvent(event: WebSocketEvent) {
switch (event.type) {
case 'open':
this.onopen?.(event);
break;
case 'close':
this.onclose?.(event);
break;
case 'error':
this.onerror?.(event);
break;
case 'message':
this.onmessage?.(event);
break;
}
this.listeners[event.type]?.forEach((options, listener) => {
try {
if (typeof listener === 'function') {
listener(event as Event);
} else {
listener.handleEvent(event as Event);
}
if (typeof options !== 'boolean' && options.once) {
if (this.listeners[event.type]?.has(listener)) {
this.listeners[event.type]?.delete(listener);
}
}
} catch (e) {
// don't break events if listener throws
setTimeout(() => {
throw e;
});
}
});
}
_close(code?: number, reason?: string): void {
// See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
const statusCode = typeof code === 'number' ? code : CLOSE_NORMAL;
const closeReason = typeof reason === 'string' ? reason : '';
this.nativeBridge.closeWithCodeReason(statusCode, closeReason);
// NativeWebSocketModule.close(statusCode, closeReason, this._socketId);
// if (BlobManager.isAvailable && this._binaryType === 'blob') {
// BlobManager.removeWebSocketHandler(this._socketId);
// }
}
_unregisterEvents(): void {
// this._subscriptions.forEach(e => e.remove());
// this._subscriptions = [];
}
_websocketOpen(protocol: string) {
this.readyState = this.OPEN;
this.protocol = protocol;
this.dispatchEvent(new WebSocketEvent('open'));
}
_websocketClosed(code: number, reason: string, wasClean: boolean) {
this.readyState = this.CLOSED;
openWebsockets.delete(this);
this.dispatchEvent(
new WebSocketEvent('close', {
code: code,
reason: reason,
wasClean,
}),
);
}
_websocketMessage(message: string | ArrayBuffer | ArrayBufferView | Blob) {
this.dispatchEvent(new WebSocketEvent('message', { data: message }));
}
// _websocketPong(pongPayload: NSData) {}
_websocketFailed(error: string) {
this.readyState = this.CLOSED;
openWebsockets.delete(this);
this.dispatchEvent(
new WebSocketEvent('error', {
message: error,
}),
);
this.dispatchEvent(
new WebSocketEvent('close', {
message: error,
}),
);
this.close();
// this._unregisterEvents();
// this.close();
// }),
}
_registerEvents(): void {
// this._subscriptions = [
// this._eventEmitter.addListener('websocketMessage', ev => {
// if (ev.id !== this._socketId) {
// return;
// }
// let data = ev.data;
// switch (ev.type) {
// case 'binary':
// data = base64.toByteArray(ev.data).buffer;
// break;
// case 'blob':
// data = BlobManager.createFromOptions(ev.data);
// break;
// }
// this.dispatchEvent(new WebSocketEvent('message', {data}));
// }),
// this._eventEmitter.addListener('websocketOpen', ev => {
// if (ev.id !== this._socketId) {
// return;
// }
// this.readyState = this.OPEN;
// this.protocol = ev.protocol;
// this.dispatchEvent(new WebSocketEvent('open'));
// }),
// this._eventEmitter.addListener('websocketClosed', ev => {
// if (ev.id !== this._socketId) {
// return;
// }
// this.readyState = this.CLOSED;
// this.dispatchEvent(
// new WebSocketEvent('close', {
// code: ev.code,
// reason: ev.reason,
// }),
// );
// this._unregisterEvents();
// this.close();
// }),
// this._eventEmitter.addListener('websocketFailed', ev => {
// if (ev.id !== this._socketId) {
// return;
// }
// this.readyState = this.CLOSED;
// this.dispatchEvent(
// new WebSocketEvent('error', {
// message: ev.message,
// }),
// );
// this.dispatchEvent(
// new WebSocketEvent('close', {
// message: ev.message,
// }),
// );
// this._unregisterEvents();
// this.close();
// }),
// ];
}
}