forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevtoolBackend.js
More file actions
105 lines (93 loc) · 2.71 KB
/
DevtoolBackend.js
File metadata and controls
105 lines (93 loc) · 2.71 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
const WebSocket = require('ws')
class DevtoolBackend {
constructor(options) {
this.options = options
this.onError = this.onError.bind(this)
this.onClientConnection = this.onClientConnection.bind(this)
this.onDevtoolConnection = this.onDevtoolConnection.bind(this)
this.onConnection = this.onConnection.bind(this)
this.onClientMessage = this.onClientMessage.bind(this)
this.onDevtoolMessage = this.onDevtoolMessage.bind(this)
this.devtoolServer = new WebSocket.Server(
{
port: options.port,
},
() => {}
)
this.devtoolServer.on('connection', this.onConnection)
this.devtoolServer.on('error', this.onError)
}
onConnection(ws, req) {
// devtools connects with ?devtools=1 in url
if (req.url.indexOf("devtools") !== -1) {
this.onDevtoolConnection(ws, req)
} else {
this.onClientConnection(ws, req)
}
}
onDevtoolConnection(ws) {
this.devtoolSocket = ws
this.devtoolSocket.on('message', this.onDevtoolMessage)
}
async onDevtoolMessage(message) {
const parsedMessage = JSON.parse(message)
switch (parsedMessage.type) {
case 'storage:get':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.get(parsedMessage.data.key)
)
break
case 'storage:set':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.set(parsedMessage.data.key, parsedMessage.data.data)
)
break
case 'storage:clear':
this.evaluateDevtoolMessage(parsedMessage, () =>
this.options.storage.clear()
)
break
case 'relaunch':
this.options.onRelaunch()
break
case 'connect':
console.log('TODO: connect'); // TODO: Let devtools know that they are connected to server?
// this.createClientServer(parsedMessage.data)
break
default:
this.clientSocket.send(JSON.stringify(parsedMessage.data))
}
}
onError(e) {
console.log('TODO: onError',e);
// this.devtoolServer.emit('port:exists')
}
onClientConnection(ws) {
this.clientSocket = ws
this.clientSocket.on('message', this.onClientMessage)
}
onClientMessage(message) {
this.devtoolSocket.send(`
{
"type": "message",
"data": ${message}
}
`)
}
async evaluateDevtoolMessage(message, cb) {
const result = await cb()
if ('evaluate' in message) {
this.devtoolSocket.send(
JSON.stringify({
type: 'evaluated',
data: {
id: message.evaluate,
data: result,
},
})
)
}
}
}
DevtoolBackend.create = (options) => new DevtoolBackend(options)
module.exports = DevtoolBackend