-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathwebSocket.js
203 lines (178 loc) · 4.32 KB
/
webSocket.js
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
/* global XMLHttpRequest */
import { PROXY_TARGET_HEADER } from './shared'
const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']
export default class WebSocket {
constructor (url, protocols, options) {
const id = initWebSocket(url, options)
const { pathname } = new URL(url)
this._url = url
this._socket = new global.WebSocket(`ws://${global.location.host}${pathname}?${PROXY_TARGET_HEADER}=${id}`, protocols)
this._socket.binaryType = 'arraybuffer'
this._socket.onopen = () => {
if (this.onopen) {
this.onopen({
target: this,
type: 'open',
response: (getWebSocketResponseResult(id) || [])[1] || null
})
}
}
this._socket.onclose = (event) => {
if (this.onclose) {
this.onclose({
target: this,
type: 'close',
code: event.code,
reason: event.reason,
wasClean: event.wasClean || false
})
}
}
this._socket.onerror = (event) => {
if (this.onerror) {
const result = getWebSocketResponseResult(id)
this.onerror({
target: this,
type: 'error',
message: 'message' in event
? event.message
: result && result[0] && result[0].message
? result[0].message
: null,
response: (result && result[1]) || null
})
}
}
this._socket.onmessage = (event) => {
if (this.onmessage) {
this.onmessage({
target: this,
type: 'message',
data: event.data
})
}
}
}
get url () {
return this._url
}
get readyState () {
return this._socket.readyState
}
get bufferedAmount () {
return this._socket.bufferedAmount
}
get binaryType () {
return this._socket.binaryType
}
set binaryType (type) {
if (type !== 'arraybuffer') {
throw new Error(`Could not change binaryType to ${type}. Only 'arraybuffer' is supported`)
}
this._socket.binaryType = type
}
get protocol () {
return this._socket.protocol
}
get extensions () {
return this._socket.extensions
}
get CONNECTING () {
return WebSocket.CONNECTING
}
get OPEN () {
return WebSocket.OPEN
}
get CLOSING () {
return WebSocket.CLOSING
}
get CLOSED () {
return WebSocket.CLOSED
}
send (data) {
this._socket.send(data)
}
close (code, reason) {
this._socket.close(code, reason)
}
}
for (let i = 0; i < readyStates.length; i++) {
WebSocket[readyStates[i]] = i
}
function fetchSync ({ method, url, headers, body, binaryResponse }) {
const req = new XMLHttpRequest()
req.withCredentials = true
if (binaryResponse) {
req.responseType = 'arraybuffer'
}
req.open(method, url, false)
if (headers) {
for (const [key, value] of Object.entries(headers)) {
req.setRequestHeader(key, value)
}
}
req.send(body)
const res = {
url,
status: req.status,
statusText: req.statusText,
headers: {},
body: null
}
const strokes = req.getAllResponseHeaders().split(/\r?\n/)
for (let i = 0; i < strokes.length; i++) {
const idx = strokes[i].indexOf(':')
const header = [
strokes[i].substring(0, idx).trim(),
strokes[i].substring(idx + 2)
]
if (header[0].length > 0) {
res.headers[header[0]] = header[1]
}
}
if (binaryResponse) {
res.body = req.response
} else {
res.body = req.responseText
}
return res
}
function initWebSocket (url, options) {
let id
try {
id = JSON.parse(fetchSync({
url: '/zen/ws',
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
...options,
url
})
}).body).id
} catch (e) {
id = null
}
if (id) {
return id
}
throw new Error('Could not init WebSocket. Check that dev server is running')
}
function getWebSocketResponseResult (id) {
const res = fetchSync({
url: `/zen/ws/${id}`,
method: 'GET'
})
if (res.status === 200 || res.status === 502) {
try {
const data = JSON.parse(res.body)
if (res.status === 200) {
return [null, data]
} else {
return [data, null]
}
} catch (e) {}
}
throw new Error('Could not fetch WebSocket response. Check that dev server is running')
}