mqtt 5.0.0-beta.2 → 5.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/connect/ws.js CHANGED
@@ -1,257 +1,265 @@
1
- 'use strict'
2
-
3
1
  const { Buffer } = require('buffer')
4
2
  const WS = require('ws')
5
3
  const debug = require('debug')('mqttjs:ws')
6
4
  const duplexify = require('duplexify')
7
- const Transform = require('readable-stream').Transform
8
- const IS_BROWSER = require('../is-browser').IS_BROWSER
5
+ const { Transform } = require('readable-stream')
6
+ const { IS_BROWSER } = require('../is-browser')
9
7
 
10
8
  const WSS_OPTIONS = [
11
- 'rejectUnauthorized',
12
- 'ca',
13
- 'cert',
14
- 'key',
15
- 'pfx',
16
- 'passphrase'
9
+ 'rejectUnauthorized',
10
+ 'ca',
11
+ 'cert',
12
+ 'key',
13
+ 'pfx',
14
+ 'passphrase',
17
15
  ]
18
16
 
19
- function buildUrl (opts, client) {
20
- let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
21
- if (typeof (opts.transformWsUrl) === 'function') {
22
- url = opts.transformWsUrl(url, opts, client)
23
- }
24
- return url
17
+ function buildUrl(opts, client) {
18
+ let url = `${opts.protocol}://${opts.hostname}:${opts.port}${opts.path}`
19
+ if (typeof opts.transformWsUrl === 'function') {
20
+ url = opts.transformWsUrl(url, opts, client)
21
+ }
22
+ return url
25
23
  }
26
24
 
27
- function setDefaultOpts (opts) {
28
- const options = opts
29
- if (!opts.hostname) {
30
- options.hostname = 'localhost'
31
- }
32
- if (!opts.port) {
33
- if (opts.protocol === 'wss') {
34
- options.port = 443
35
- } else {
36
- options.port = 80
37
- }
38
- }
39
- if (!opts.path) {
40
- options.path = '/'
41
- }
42
-
43
- if (!opts.wsOptions) {
44
- options.wsOptions = {}
45
- }
46
- if (!IS_BROWSER && opts.protocol === 'wss') {
47
- // Add cert/key/ca etc options
48
- WSS_OPTIONS.forEach(function (prop) {
49
- if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {
50
- options.wsOptions[prop] = opts[prop]
51
- }
52
- })
53
- }
54
-
55
- return options
25
+ function setDefaultOpts(opts) {
26
+ const options = opts
27
+ if (!opts.hostname) {
28
+ options.hostname = 'localhost'
29
+ }
30
+ if (!opts.port) {
31
+ if (opts.protocol === 'wss') {
32
+ options.port = 443
33
+ } else {
34
+ options.port = 80
35
+ }
36
+ }
37
+ if (!opts.path) {
38
+ options.path = '/'
39
+ }
40
+
41
+ if (!opts.wsOptions) {
42
+ options.wsOptions = {}
43
+ }
44
+ if (!IS_BROWSER && opts.protocol === 'wss') {
45
+ // Add cert/key/ca etc options
46
+ WSS_OPTIONS.forEach((prop) => {
47
+ if (
48
+ Object.prototype.hasOwnProperty.call(opts, prop) &&
49
+ !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)
50
+ ) {
51
+ options.wsOptions[prop] = opts[prop]
52
+ }
53
+ })
54
+ }
55
+
56
+ return options
56
57
  }
57
58
 
58
- function setDefaultBrowserOpts (opts) {
59
- const options = setDefaultOpts(opts)
60
-
61
- if (!options.hostname) {
62
- options.hostname = options.host
63
- }
64
-
65
- if (!options.hostname) {
66
- // Throwing an error in a Web Worker if no `hostname` is given, because we
67
- // can not determine the `hostname` automatically. If connecting to
68
- // localhost, please supply the `hostname` as an argument.
69
- if (typeof (document) === 'undefined') {
70
- throw new Error('Could not determine host. Specify host manually.')
71
- }
72
- const parsed = new URL(document.URL)
73
- options.hostname = parsed.hostname
74
-
75
- if (!options.port) {
76
- options.port = parsed.port
77
- }
78
- }
79
-
80
- // objectMode should be defined for logic
81
- if (options.objectMode === undefined) {
82
- options.objectMode = !(options.binary === true || options.binary === undefined)
83
- }
84
-
85
- return options
59
+ function setDefaultBrowserOpts(opts) {
60
+ const options = setDefaultOpts(opts)
61
+
62
+ if (!options.hostname) {
63
+ options.hostname = options.host
64
+ }
65
+
66
+ if (!options.hostname) {
67
+ // Throwing an error in a Web Worker if no `hostname` is given, because we
68
+ // can not determine the `hostname` automatically. If connecting to
69
+ // localhost, please supply the `hostname` as an argument.
70
+ if (typeof document === 'undefined') {
71
+ throw new Error('Could not determine host. Specify host manually.')
72
+ }
73
+ const parsed = new URL(document.URL)
74
+ options.hostname = parsed.hostname
75
+
76
+ if (!options.port) {
77
+ options.port = parsed.port
78
+ }
79
+ }
80
+
81
+ // objectMode should be defined for logic
82
+ if (options.objectMode === undefined) {
83
+ options.objectMode = !(
84
+ options.binary === true || options.binary === undefined
85
+ )
86
+ }
87
+
88
+ return options
86
89
  }
87
90
 
88
- function createWebSocket (client, url, opts) {
89
- debug('createWebSocket')
90
- debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)
91
- const websocketSubProtocol =
92
- (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
93
- ? 'mqttv3.1'
94
- : 'mqtt'
95
-
96
- debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)
97
- const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
98
- return socket
91
+ function createWebSocket(client, url, opts) {
92
+ debug('createWebSocket')
93
+ debug(`protocol: ${opts.protocolId} ${opts.protocolVersion}`)
94
+ const websocketSubProtocol =
95
+ opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
96
+ ? 'mqttv3.1'
97
+ : 'mqtt'
98
+
99
+ debug(
100
+ `creating new Websocket for url: ${url} and protocol: ${websocketSubProtocol}`,
101
+ )
102
+ const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
103
+ return socket
99
104
  }
100
105
 
101
- function createBrowserWebSocket (client, opts) {
102
- const websocketSubProtocol =
103
- (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
104
- ? 'mqttv3.1'
105
- : 'mqtt'
106
-
107
- const url = buildUrl(opts, client)
108
- /* global WebSocket */
109
- const socket = new WebSocket(url, [websocketSubProtocol])
110
- socket.binaryType = 'arraybuffer'
111
- return socket
106
+ function createBrowserWebSocket(client, opts) {
107
+ const websocketSubProtocol =
108
+ opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
109
+ ? 'mqttv3.1'
110
+ : 'mqtt'
111
+
112
+ const url = buildUrl(opts, client)
113
+ const socket = new WebSocket(url, [websocketSubProtocol])
114
+ socket.binaryType = 'arraybuffer'
115
+ return socket
112
116
  }
113
117
 
114
- function streamBuilder (client, opts) {
115
- debug('streamBuilder')
116
- const options = setDefaultOpts(opts)
117
- const url = buildUrl(options, client)
118
- const socket = createWebSocket(client, url, options)
119
- const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
120
- webSocketStream.url = url
121
- socket.on('close', () => { webSocketStream.destroy() })
122
- return webSocketStream
118
+ function streamBuilder(client, opts) {
119
+ debug('streamBuilder')
120
+ const options = setDefaultOpts(opts)
121
+ const url = buildUrl(options, client)
122
+ const socket = createWebSocket(client, url, options)
123
+ const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
124
+ webSocketStream.url = url
125
+ socket.on('close', () => {
126
+ webSocketStream.destroy()
127
+ })
128
+ return webSocketStream
123
129
  }
124
130
 
125
- function browserStreamBuilder (client, opts) {
126
- debug('browserStreamBuilder')
127
- let stream
128
- const options = setDefaultBrowserOpts(opts)
129
- // sets the maximum socket buffer size before throttling
130
- const bufferSize = options.browserBufferSize || 1024 * 512
131
-
132
- const bufferTimeout = opts.browserBufferTimeout || 1000
133
-
134
- const coerceToBuffer = !opts.objectMode
135
-
136
- const socket = createBrowserWebSocket(client, opts)
137
-
138
- const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
139
-
140
- if (!opts.objectMode) {
141
- proxy._writev = writev
142
- }
143
- proxy.on('close', () => { socket.close() })
144
-
145
- const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')
146
-
147
- // was already open when passed in
148
- if (socket.readyState === socket.OPEN) {
149
- stream = proxy
150
- } else {
151
- stream = stream = duplexify(undefined, undefined, opts)
152
- if (!opts.objectMode) {
153
- stream._writev = writev
154
- }
155
-
156
- if (eventListenerSupport) {
157
- socket.addEventListener('open', onopen)
158
- } else {
159
- socket.onopen = onopen
160
- }
161
- }
162
-
163
- stream.socket = socket
164
-
165
- if (eventListenerSupport) {
166
- socket.addEventListener('close', onclose)
167
- socket.addEventListener('error', onerror)
168
- socket.addEventListener('message', onmessage)
169
- } else {
170
- socket.onclose = onclose
171
- socket.onerror = onerror
172
- socket.onmessage = onmessage
173
- }
174
-
175
- // methods for browserStreamBuilder
176
-
177
- function buildProxy (options, socketWrite, socketEnd) {
178
- const proxy = new Transform({
179
- objectModeMode: options.objectMode
180
- })
181
-
182
- proxy._write = socketWrite
183
- proxy._flush = socketEnd
184
-
185
- return proxy
186
- }
187
-
188
- function onopen () {
189
- stream.setReadable(proxy)
190
- stream.setWritable(proxy)
191
- stream.emit('connect')
192
- }
193
-
194
- function onclose () {
195
- stream.end()
196
- stream.destroy()
197
- }
198
-
199
- function onerror (err) {
200
- stream.destroy(err)
201
- }
202
-
203
- function onmessage (event) {
204
- let data = event.data
205
- if (data instanceof ArrayBuffer) data = Buffer.from(data)
206
- else data = Buffer.from(data, 'utf8')
207
- proxy.push(data)
208
- }
209
-
210
- // this is to be enabled only if objectMode is false
211
- function writev (chunks, cb) {
212
- const buffers = new Array(chunks.length)
213
- for (let i = 0; i < chunks.length; i++) {
214
- if (typeof chunks[i].chunk === 'string') {
215
- buffers[i] = Buffer.from(chunks[i], 'utf8')
216
- } else {
217
- buffers[i] = chunks[i].chunk
218
- }
219
- }
220
-
221
- this._write(Buffer.concat(buffers), 'binary', cb)
222
- }
223
-
224
- function socketWriteBrowser (chunk, enc, next) {
225
- if (socket.bufferedAmount > bufferSize) {
226
- // throttle data until buffered amount is reduced.
227
- setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
228
- }
229
-
230
- if (coerceToBuffer && typeof chunk === 'string') {
231
- chunk = Buffer.from(chunk, 'utf8')
232
- }
233
-
234
- try {
235
- socket.send(chunk)
236
- } catch (err) {
237
- return next(err)
238
- }
239
-
240
- next()
241
- }
242
-
243
- function socketEndBrowser (done) {
244
- socket.close()
245
- done()
246
- }
247
-
248
- // end methods for browserStreamBuilder
249
-
250
- return stream
131
+ function browserStreamBuilder(client, opts) {
132
+ debug('browserStreamBuilder')
133
+ let stream
134
+ const options = setDefaultBrowserOpts(opts)
135
+ // sets the maximum socket buffer size before throttling
136
+ const bufferSize = options.browserBufferSize || 1024 * 512
137
+
138
+ const bufferTimeout = opts.browserBufferTimeout || 1000
139
+
140
+ const coerceToBuffer = !opts.objectMode
141
+
142
+ const socket = createBrowserWebSocket(client, opts)
143
+
144
+ const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
145
+
146
+ if (!opts.objectMode) {
147
+ proxy._writev = writev
148
+ }
149
+ proxy.on('close', () => {
150
+ socket.close()
151
+ })
152
+
153
+ const eventListenerSupport = typeof socket.addEventListener !== 'undefined'
154
+
155
+ // was already open when passed in
156
+ if (socket.readyState === socket.OPEN) {
157
+ stream = proxy
158
+ } else {
159
+ stream = duplexify(undefined, undefined, opts)
160
+ if (!opts.objectMode) {
161
+ stream._writev = writev
162
+ }
163
+
164
+ if (eventListenerSupport) {
165
+ socket.addEventListener('open', onOpen)
166
+ } else {
167
+ socket.onopen = onOpen
168
+ }
169
+ }
170
+
171
+ stream.socket = socket
172
+
173
+ if (eventListenerSupport) {
174
+ socket.addEventListener('close', onclose)
175
+ socket.addEventListener('error', onerror)
176
+ socket.addEventListener('message', onmessage)
177
+ } else {
178
+ socket.onclose = onclose
179
+ socket.onerror = onerror
180
+ socket.onmessage = onmessage
181
+ }
182
+
183
+ // methods for browserStreamBuilder
184
+
185
+ function buildProxy(pOptions, socketWrite, socketEnd) {
186
+ const _proxy = new Transform({
187
+ objectModeMode: pOptions.objectMode,
188
+ })
189
+
190
+ _proxy._write = socketWrite
191
+ _proxy._flush = socketEnd
192
+
193
+ return _proxy
194
+ }
195
+
196
+ function onOpen() {
197
+ stream.setReadable(proxy)
198
+ stream.setWritable(proxy)
199
+ stream.emit('connect')
200
+ }
201
+
202
+ function onclose() {
203
+ stream.end()
204
+ stream.destroy()
205
+ }
206
+
207
+ function onerror(err) {
208
+ stream.destroy(err)
209
+ }
210
+
211
+ function onmessage(event) {
212
+ let { data } = event
213
+ if (data instanceof ArrayBuffer) data = Buffer.from(data)
214
+ else data = Buffer.from(data, 'utf8')
215
+ proxy.push(data)
216
+ }
217
+
218
+ // this is to be enabled only if objectMode is false
219
+ function writev(chunks, cb) {
220
+ const buffers = new Array(chunks.length)
221
+ for (let i = 0; i < chunks.length; i++) {
222
+ if (typeof chunks[i].chunk === 'string') {
223
+ buffers[i] = Buffer.from(chunks[i], 'utf8')
224
+ } else {
225
+ buffers[i] = chunks[i].chunk
226
+ }
227
+ }
228
+
229
+ this._write(Buffer.concat(buffers), 'binary', cb)
230
+ }
231
+
232
+ function socketWriteBrowser(chunk, enc, next) {
233
+ if (socket.bufferedAmount > bufferSize) {
234
+ // throttle data until buffered amount is reduced.
235
+ setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
236
+ }
237
+
238
+ if (coerceToBuffer && typeof chunk === 'string') {
239
+ chunk = Buffer.from(chunk, 'utf8')
240
+ }
241
+
242
+ try {
243
+ socket.send(chunk)
244
+ } catch (err) {
245
+ return next(err)
246
+ }
247
+
248
+ next()
249
+ }
250
+
251
+ function socketEndBrowser(done) {
252
+ socket.close()
253
+ done()
254
+ }
255
+
256
+ // end methods for browserStreamBuilder
257
+
258
+ return stream
251
259
  }
252
260
 
253
261
  if (IS_BROWSER) {
254
- module.exports = browserStreamBuilder
262
+ module.exports = browserStreamBuilder
255
263
  } else {
256
- module.exports = streamBuilder
264
+ module.exports = streamBuilder
257
265
  }