-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathws.js
100 lines (90 loc) · 2.6 KB
/
ws.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
'use strict'
var WebSocket = require('ws')
var debug = require('debug')('mqttjs:ws')
var urlModule = require('url')
var WSS_OPTIONS = [
'rejectUnauthorized',
'ca',
'cert',
'key',
'pfx',
'passphrase'
]
// eslint-disable-next-line camelcase
var IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'
function buildUrl (opts, client) {
var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
if (typeof (opts.transformWsUrl) === 'function') {
url = opts.transformWsUrl(url, opts, client)
}
return url
}
function setDefaultOpts (opts) {
if (!opts.hostname) {
opts.hostname = 'localhost'
}
if (!opts.port) {
if (opts.protocol === 'wss') {
opts.port = 443
} else {
opts.port = 80
}
}
if (!opts.path) {
opts.path = '/'
}
if (!opts.wsOptions) {
opts.wsOptions = {}
}
if (!IS_BROWSER && opts.protocol === 'wss') {
// Add cert/key/ca etc options
WSS_OPTIONS.forEach(function (prop) {
if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
opts.wsOptions[prop] = opts[prop]
}
})
}
}
function createWebSocket (client, opts) {
debug('createWebSocket')
debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)
var websocketSubProtocol =
(opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
? 'mqttv3.1'
: 'mqtt'
setDefaultOpts(opts)
var url = buildUrl(opts, client)
debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)
var ws = new WebSocket(url, [websocketSubProtocol], opts.wsOptions)
var duplex = WebSocket.createWebSocketStream(ws, opts.wsOptions)
duplex.url = url
return duplex
}
function streamBuilder (client, opts) {
return createWebSocket(client, opts)
}
function browserStreamBuilder (client, opts) {
debug('browserStreamBuilder')
if (!opts.hostname) {
opts.hostname = opts.host
}
if (!opts.hostname) {
// Throwing an error in a Web Worker if no `hostname` is given, because we
// can not determine the `hostname` automatically. If connecting to
// localhost, please supply the `hostname` as an argument.
if (typeof (document) === 'undefined') {
throw new Error('Could not determine host. Specify host manually.')
}
var parsed = urlModule.parse(document.URL)
opts.hostname = parsed.hostname
if (!opts.port) {
opts.port = parsed.port
}
}
return createWebSocket(client, opts)
}
if (IS_BROWSER) {
module.exports = browserStreamBuilder
} else {
module.exports = streamBuilder
}