-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathreload.js
284 lines (245 loc) · 9.96 KB
/
reload.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
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
// Requires
const path = require('path')
const fs = require('fs')
const http = require('http')
const https = require('https')
const ws = require('ws')
module.exports = function reload (app, opts, server) {
opts = opts || {}
var argumentCache = arguments
return new Promise(function (resolve, reject) {
// Parameters variables
const port = opts.port || 9856
const httpsOption = opts.https || null
const httpServerOrPort = server || port
const forceWss = opts.forceWss || false
const verboseLogging = opts.verbose || false
const webSocketServerWaitStart = opts.webSocketServerWaitStart || false
// Application variables
const RELOAD_FILE = path.join(__dirname, './reload-client.js')
let reloadCode = fs.readFileSync(RELOAD_FILE, 'utf8')
const route = opts.route ? processRoute(opts.route) : '/reload/reload.js'
// Websocket server variables
let wss
// General variables
const socketPortSpecified = server ? null : port
const connections = {}
let httpOrHttpsServer
if (argumentCache[0] === undefined) {
return reject(new Error('Lack of/invalid arguments provided to reload'))
} else {
if (typeof (argumentCache[0]) !== 'function' && (typeof (argumentCache[1]) !== 'object' || typeof (argumentCache[1]) !== 'undefined')) {
return reject(new Error('Lack of/invalid arguments provided to reload'))
}
}
if (typeof port !== 'number') {
return reject(new Error('Specified port is not of type number'))
}
if (typeof forceWss !== 'boolean') {
return reject(new Error('forceWss option specified is not of type boolean'))
}
if (typeof verboseLogging !== 'boolean') {
return reject(new Error('verboseLogging option specified is not of type boolean'))
}
if (typeof webSocketServerWaitStart !== 'boolean') {
return reject(new Error('webSocketServerWaitStart option specified is not of type boolean'))
}
// Application setup
setupClientSideCode()
setupExpressAppRouting().then(function () {
if (!webSocketServerWaitStart) {
startWebSocketServer().then(function (result) {
resolve(result, 'test')
}).catch(function (err) {
reject(err)
})
} else {
resolve(getReloadReturn())
}
}).catch(function (err) {
return reject(err)
})
function setupExpressAppRouting () {
return new Promise(function (resolve, reject) {
if (server === undefined) {
if (app.get) {
app.get(route, function (req, res) {
res.type('text/javascript')
res.send(reloadCode)
})
resolve()
} else {
reject(new Error('Could not attach route to express app. Be sure that app passed is actually an express app'))
}
} else {
resolve()
}
})
}
function setupClientSideCode () {
if (verboseLogging) {
reloadCode = reloadCode.replace('verboseLogging = false', 'verboseLogging = true')
}
const webSocketString = forceWss ? 'wss://$3' : 'ws$2://$3'
reloadCode = reloadCode.replace('socketUrl.replace()', 'socketUrl.replace(/(^http(s?):\\/\\/)(.*:)(.*)/,' + (socketPortSpecified ? '\'' + webSocketString + socketPortSpecified : '\'' + webSocketString + '$4') + '\')')
}
// Websocket server setup
function startWebSocketServer () {
const httpsOptions = {}
const WebSocketServer = ws.Server
return new Promise(function (resolve, reject) {
if (verboseLogging) {
console.log('Starting WebSocket Server')
}
if (socketPortSpecified) { // Use custom user specified port
wss = new WebSocketServer({ noServer: true })
if (httpsOption) { // HTTPS
if (httpsOption.p12) {
if (typeof httpsOption.p12.p12Path === 'string' && httpsOption.p12.p12Path.match(/\.\w{3}$/)) {
try {
httpsOptions.pfx = fs.readFileSync(httpsOption.p12.p12Path)
} catch (err) {
return reject(err)
}
} else {
httpsOptions.pfx = httpsOption.p12.p12Path
}
} else if (httpsOption.certAndKey) {
/* istanbul ignore else */
if (httpsOption.certAndKey.key) {
if (isCertString(httpsOption.certAndKey.key)) {
httpsOptions.key = httpsOption.certAndKey.key
} else {
try {
httpsOptions.key = fs.readFileSync(httpsOption.certAndKey.key)
} catch (err) {
return reject(err)
}
}
}
/* istanbul ignore else */
if (httpsOption.certAndKey.cert) {
if (isCertString(httpsOption.certAndKey.cert)) {
httpsOptions.cert = httpsOption.certAndKey.cert
} else {
try {
httpsOptions.cert = fs.readFileSync(httpsOption.certAndKey.cert)
} catch (err) {
return reject(err)
}
}
}
} else {
return reject(new Error('Could not initialize reload HTTPS setup incorrectly. Make sure to define a `p12` or `certAndKey` in the HTTPS options'))
}
/* istanbul ignore else */
if (httpsOption.passphrase) {
httpsOptions.passphrase = httpsOption.passphrase
}
httpOrHttpsServer = https.createServer(httpsOptions)
} else { // HTTP
httpOrHttpsServer = http.createServer()
}
httpOrHttpsServer.listen(port, function () {
resolve(getReloadReturn())
})
httpOrHttpsServer.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request)
})
})
// Keep track of connections so we can force shutdown the server
// https://stackoverflow.com/questions/14626636/how-do-i-shutdown-a-node-js-https-server-immediately/14636625#14636625
httpOrHttpsServer.on('connection', mapConnections)
} else { // Attach to server, using server's port. Kept here to support legacy arguments.
wss = new WebSocketServer({ server: httpServerOrPort })
resolve(getReloadReturn())
}
wss.on('connection', (ws) => {
if (verboseLogging) {
console.log('Reload client connected to server')
}
})
})
}
function sendMessage (message) {
if (verboseLogging) {
console.log('Sending message to ' + (wss.clients.size) + ' connection(s): ' + message)
}
wss.clients.forEach(function each (client) {
/* istanbul ignore else */
if (client.readyState === ws.OPEN) {
client.send(message)
}
})
}
// assign individual keys to connections when opened so they can be destroyed gracefully
function mapConnections (conn) {
const key = conn.remoteAddress + ':' + conn.remotePort
connections[key] = conn
// once the connection closes, remove
conn.on('close', function () {
delete connections[key]
})
}
function processRoute (route) {
// If reload.js is found in the route option strip it. We will concat it for user to ensure no case errors or order problems.
const reloadJsMatch = route.match(/reload\.js/i)
if (reloadJsMatch) {
route = route.split(reloadJsMatch)[0]
}
/*
* Concat their provided path (minus `reload.js` if they specified it) with a `/` if they didn't provide one and `reload.js. This allows for us to ensure case, order, and use of `/` is correct
* For example these route's are all valid:
* 1. `newRoutePath` -> Their route + `/` + reload.js
* 2. `newRoutePath/` -> Their route + reload.js
* 3. `newRoutePath/reload.js` -> (Strip reload.js above) so now: Their route + reload.js
* 4. `newRoutePath/rEload.js` -> (Strip reload.js above) so now: Their route + reload.js
* 5. `newRoutePathreload.js` -> (Strip reload.js above) so now: Their route + `/` + reload.js
* 6. `newRoutePath/reload.js/rEload.js/... reload.js n number of times -> (Strip above removes all reload.js occurrences at the end of the specified route) so now: Their route + 'reload.js`
*/
return route + (route.slice(-1) === '/' ? '' : '/') + 'reload.js'
}
function getReloadReturn () {
const tempObject = {
reload: function () {
sendMessage('reload')
},
wss: wss,
closeServer: function () {
return new Promise(function (resolve, reject) {
// Loop through all connections and terminate them for immediate server shutdown
for (const key in connections) {
connections[key].destroy()
}
httpOrHttpsServer.close(resolve)
})
}
}
// Only define the function and make it available if the WebSocket is waiting in the first place
if (webSocketServerWaitStart) {
tempObject.startWebSocketServer = startWebSocketServer
}
if (server) { // Private return API only used in command line version of reload
tempObject.reloadClientCode = function () {
return reloadCode
}
}
return tempObject
}
})
function isCertString (stringToTest) {
let testString = stringToTest
if (typeof testString !== 'string') {
testString = testString.toString()
}
const lastChar = testString.substring(testString.length - 1)
// A file path string won't have an end of line character at the end
// Looking for either \n or \r allows for nearly any OS someone could
// use, and a few that node doesn't work on.
if (lastChar === '\n' || lastChar === '\r') {
return true
}
return false
}
}