/
index.ts
316 lines (271 loc) · 6.87 KB
/
index.ts
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
import type { Ref } from 'vue-demi'
import { ref, watch } from 'vue-demi'
import type { Fn, MaybeRefOrGetter } from '@vueuse/shared'
import { isClient, isWorker, toRef, tryOnScopeDispose, useIntervalFn } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
export type WebSocketStatus = 'OPEN' | 'CONNECTING' | 'CLOSED'
const DEFAULT_PING_MESSAGE = 'ping'
export interface UseWebSocketOptions {
onConnected?: (ws: WebSocket) => void
onDisconnected?: (ws: WebSocket, event: CloseEvent) => void
onError?: (ws: WebSocket, event: Event) => void
onMessage?: (ws: WebSocket, event: MessageEvent) => void
/**
* Send heartbeat for every x milliseconds passed
*
* @default false
*/
heartbeat?: boolean | {
/**
* Message for the heartbeat
*
* @default 'ping'
*/
message?: string | ArrayBuffer | Blob
/**
* Interval, in milliseconds
*
* @default 1000
*/
interval?: number
/**
* Heartbeat response timeout, in milliseconds
*
* @default 1000
*/
pongTimeout?: number
}
/**
* Enabled auto reconnect
*
* @default false
*/
autoReconnect?: boolean | {
/**
* Maximum retry times.
*
* Or you can pass a predicate function (which returns true if you want to retry).
*
* @default -1
*/
retries?: number | (() => boolean)
/**
* Delay for reconnect, in milliseconds
*
* @default 1000
*/
delay?: number
/**
* On maximum retry times reached.
*/
onFailed?: Fn
}
/**
* Automatically open a connection
*
* @default true
*/
immediate?: boolean
/**
* Automatically close a connection
*
* @default true
*/
autoClose?: boolean
/**
* List of one or more sub-protocol strings
*
* @default []
*/
protocols?: string[]
}
export interface UseWebSocketReturn<T> {
/**
* Reference to the latest data received via the websocket,
* can be watched to respond to incoming messages
*/
data: Ref<T | null>
/**
* The current websocket status, can be only one of:
* 'OPEN', 'CONNECTING', 'CLOSED'
*/
status: Ref<WebSocketStatus>
/**
* Closes the websocket connection gracefully.
*/
close: WebSocket['close']
/**
* Reopen the websocket connection.
* If there the current one is active, will close it before opening a new one.
*/
open: Fn
/**
* Sends data through the websocket connection.
*
* @param data
* @param useBuffer when the socket is not yet open, store the data into the buffer and sent them one connected. Default to true.
*/
send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => boolean
/**
* Reference to the WebSocket instance.
*/
ws: Ref<WebSocket | undefined>
}
function resolveNestedOptions<T>(options: T | true): T {
if (options === true)
return {} as T
return options
}
/**
* Reactive WebSocket client.
*
* @see https://vueuse.org/useWebSocket
* @param url
*/
export function useWebSocket<Data = any>(
url: MaybeRefOrGetter<string | URL | undefined>,
options: UseWebSocketOptions = {},
): UseWebSocketReturn<Data> {
const {
onConnected,
onDisconnected,
onError,
onMessage,
immediate = true,
autoClose = true,
protocols = [],
} = options
const data: Ref<Data | null> = ref(null)
const status = ref<WebSocketStatus>('CLOSED')
const wsRef = ref<WebSocket | undefined>()
const urlRef = toRef(url)
let heartbeatPause: Fn | undefined
let heartbeatResume: Fn | undefined
let explicitlyClosed = false
let retried = 0
let bufferedData: (string | ArrayBuffer | Blob)[] = []
let pongTimeoutWait: ReturnType<typeof setTimeout> | undefined
const _sendBuffer = () => {
if (bufferedData.length && wsRef.value && status.value === 'OPEN') {
for (const buffer of bufferedData)
wsRef.value.send(buffer)
bufferedData = []
}
}
const resetHeartbeat = () => {
clearTimeout(pongTimeoutWait)
pongTimeoutWait = undefined
}
// Status code 1000 -> Normal Closure https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
const close: WebSocket['close'] = (code = 1000, reason) => {
if (!isClient || !wsRef.value)
return
explicitlyClosed = true
resetHeartbeat()
heartbeatPause?.()
wsRef.value.close(code, reason)
wsRef.value = undefined
}
const send = (data: string | ArrayBuffer | Blob, useBuffer = true) => {
if (!wsRef.value || status.value !== 'OPEN') {
if (useBuffer)
bufferedData.push(data)
return false
}
_sendBuffer()
wsRef.value.send(data)
return true
}
const _init = () => {
if (explicitlyClosed || typeof urlRef.value === 'undefined')
return
const ws = new WebSocket(urlRef.value, protocols)
wsRef.value = ws
status.value = 'CONNECTING'
ws.onopen = () => {
status.value = 'OPEN'
onConnected?.(ws!)
heartbeatResume?.()
_sendBuffer()
}
ws.onclose = (ev) => {
status.value = 'CLOSED'
onDisconnected?.(ws, ev)
if (!explicitlyClosed && options.autoReconnect) {
const {
retries = -1,
delay = 1000,
onFailed,
} = resolveNestedOptions(options.autoReconnect)
retried += 1
if (typeof retries === 'number' && (retries < 0 || retried < retries))
setTimeout(_init, delay)
else if (typeof retries === 'function' && retries())
setTimeout(_init, delay)
else
onFailed?.()
}
}
ws.onerror = (e) => {
onError?.(ws!, e)
}
ws.onmessage = (e: MessageEvent) => {
if (options.heartbeat) {
resetHeartbeat()
const {
message = DEFAULT_PING_MESSAGE,
} = resolveNestedOptions(options.heartbeat)
if (e.data === message)
return
}
data.value = e.data
onMessage?.(ws!, e)
}
}
if (options.heartbeat) {
const {
message = DEFAULT_PING_MESSAGE,
interval = 1000,
pongTimeout = 1000,
} = resolveNestedOptions(options.heartbeat)
const { pause, resume } = useIntervalFn(
() => {
send(message, false)
if (pongTimeoutWait != null)
return
pongTimeoutWait = setTimeout(() => {
// auto-reconnect will be trigger with ws.onclose()
close()
explicitlyClosed = false
}, pongTimeout)
},
interval,
{ immediate: false },
)
heartbeatPause = pause
heartbeatResume = resume
}
if (autoClose) {
if (isClient)
useEventListener('beforeunload', () => close())
tryOnScopeDispose(close)
}
const open = () => {
if (!isClient && !isWorker)
return
close()
explicitlyClosed = false
retried = 0
_init()
}
if (immediate)
watch(urlRef, open, { immediate: true })
return {
data,
status,
close,
send,
open,
ws: wsRef,
}
}