-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathindex.ts
288 lines (253 loc) · 7.63 KB
/
index.ts
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
285
286
287
288
/* eslint-disable @typescript-eslint/no-var-requires */
import _debug from 'debug'
import url from 'url'
import MqttClient, {
IClientOptions,
MqttClientEventCallbacks,
MqttProtocol,
} from '../client'
import isBrowser from '../is-browser'
import { StreamBuilder } from '../shared'
// Handling the process.nextTick is not a function error in react-native applications.
if (typeof process?.nextTick !== 'function') {
process.nextTick = setImmediate
}
const debug = _debug('mqttjs')
let protocols: Record<string, StreamBuilder> = null
/**
* Parse the auth attribute and merge username and password in the options object.
*
* @param {Object} [opts] option object
*/
function parseAuthOptions(opts: IClientOptions) {
let matches: RegExpMatchArray | null
if (opts.auth) {
matches = opts.auth.match(/^(.+):(.+)$/)
if (matches) {
opts.username = matches[1]
opts.password = matches[2]
} else {
opts.username = opts.auth
}
}
}
/**
* connect - connect to an MQTT broker.
*/
function connect(brokerUrl: string): MqttClient
function connect(opts: IClientOptions): MqttClient
function connect(brokerUrl: string, opts?: IClientOptions): MqttClient
function connect(
brokerUrl: string | IClientOptions,
opts?: IClientOptions,
): MqttClient {
debug('connecting to an MQTT broker...')
if (typeof brokerUrl === 'object' && !opts) {
opts = brokerUrl
brokerUrl = ''
}
opts = opts || {}
// try to parse the broker url
if (brokerUrl && typeof brokerUrl === 'string') {
// eslint-disable-next-line
const parsedUrl = url.parse(brokerUrl, true)
const parsedOptions: Partial<IClientOptions> = {}
if (parsedUrl.port != null) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
parsedOptions.port = Number(parsedUrl.port)
}
parsedOptions.host = parsedUrl.hostname
parsedOptions.query = parsedUrl.query as Record<string, string>
parsedOptions.auth = parsedUrl.auth
parsedOptions.protocol = parsedUrl.protocol as MqttProtocol
parsedOptions.path = parsedUrl.path
parsedOptions.protocol = parsedOptions.protocol?.replace(
/:$/,
'',
) as MqttProtocol
opts = { ...parsedOptions, ...opts }
// when parsing an url expect the protocol to be set
if (!opts.protocol) {
throw new Error('Missing protocol')
}
}
opts.unixSocket = opts.unixSocket || opts.protocol?.includes('+unix')
if (opts.unixSocket) {
opts.protocol = opts.protocol.replace('+unix', '') as MqttProtocol
} else if (
!opts.protocol?.startsWith('ws') &&
!opts.protocol?.startsWith('wx')
) {
// consider path only with ws protocol or unix socket
// url.parse could return path (for example when url ends with a `/`)
// that could break the connection. See https://github.com/mqttjs/MQTT.js/pull/1874
delete opts.path
}
// merge in the auth options if supplied
parseAuthOptions(opts)
// support clientId passed in the query string of the url
if (opts.query && typeof opts.query.clientId === 'string') {
opts.clientId = opts.query.clientId
}
if (opts.cert && opts.key) {
if (opts.protocol) {
if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
switch (opts.protocol) {
case 'mqtt':
opts.protocol = 'mqtts'
break
case 'ws':
opts.protocol = 'wss'
break
case 'wx':
opts.protocol = 'wxs'
break
case 'ali':
opts.protocol = 'alis'
break
default:
throw new Error(
`Unknown protocol for secure connection: "${opts.protocol}"!`,
)
}
}
} else {
// A cert and key was provided, however no protocol was specified, so we will throw an error.
throw new Error('Missing secure protocol key')
}
}
// only loads the protocols once
if (!protocols) {
protocols = {}
if (!isBrowser && !opts.forceNativeWebSocket) {
protocols.ws = require('./ws').streamBuilder
protocols.wss = require('./ws').streamBuilder
protocols.mqtt = require('./tcp').default
protocols.tcp = require('./tcp').default
protocols.ssl = require('./tls').default
protocols.tls = protocols.ssl
protocols.mqtts = require('./tls').default
} else {
protocols.ws = require('./ws').browserStreamBuilder
protocols.wss = require('./ws').browserStreamBuilder
protocols.wx = require('./wx').default
protocols.wxs = require('./wx').default
protocols.ali = require('./ali').default
protocols.alis = require('./ali').default
}
}
if (!protocols[opts.protocol]) {
const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
// returns the first available protocol based on available protocols (that depends on environment)
// if no protocol is specified this will return mqtt on node and ws on browser
// if secure it will return mqtts on node and wss on browser
opts.protocol = [
'mqtt',
'mqtts',
'ws',
'wss',
'wx',
'wxs',
'ali',
'alis',
].filter((key, index) => {
if (isSecure && index % 2 === 0) {
// Skip insecure protocols when requesting a secure one.
return false
}
return typeof protocols[key] === 'function'
})[0] as MqttProtocol
}
if (opts.clean === false && !opts.clientId) {
throw new Error('Missing clientId for unclean clients')
}
if (opts.protocol) {
opts.defaultProtocol = opts.protocol
}
function wrapper(client: MqttClient) {
if (opts.servers) {
if (
!client._reconnectCount ||
client._reconnectCount === opts.servers.length
) {
client._reconnectCount = 0
}
opts.host = opts.servers[client._reconnectCount].host
opts.port = opts.servers[client._reconnectCount].port
opts.protocol = !opts.servers[client._reconnectCount].protocol
? opts.defaultProtocol
: opts.servers[client._reconnectCount].protocol
opts.hostname = opts.host
client._reconnectCount++
}
debug('calling streambuilder for', opts.protocol)
return protocols[opts.protocol](client, opts)
}
const client = new MqttClient(wrapper, opts)
client.on('error', () => {
/* Automatically set up client error handling */
})
return client
}
function connectAsync(brokerUrl: string): Promise<MqttClient>
function connectAsync(opts: IClientOptions): Promise<MqttClient>
function connectAsync(
brokerUrl: string,
opts?: IClientOptions,
): Promise<MqttClient>
function connectAsync(
brokerUrl: string,
opts: IClientOptions,
allowRetries: boolean,
): Promise<MqttClient>
function connectAsync(
brokerUrl: string | IClientOptions,
opts?: IClientOptions,
allowRetries = true,
): Promise<MqttClient> {
return new Promise((resolve, reject) => {
const client = connect(brokerUrl as string, opts)
const promiseResolutionListeners: Partial<MqttClientEventCallbacks> = {
connect: (connack) => {
removePromiseResolutionListeners()
resolve(client) // Resolve on connect
},
end: () => {
removePromiseResolutionListeners()
resolve(client) // Resolve on end
},
error: (err) => {
removePromiseResolutionListeners()
client.end()
reject(err) // Reject on error
},
}
// If retries are not allowed, reject on close
if (allowRetries === false) {
promiseResolutionListeners.close = () => {
promiseResolutionListeners.error(
new Error("Couldn't connect to server"),
)
}
}
// Remove listeners added to client by this promise
function removePromiseResolutionListeners() {
Object.keys(promiseResolutionListeners).forEach((eventName) => {
client.off(
eventName as keyof MqttClientEventCallbacks,
promiseResolutionListeners[eventName],
)
})
}
// Add listeners to client
Object.keys(promiseResolutionListeners).forEach((eventName) => {
client.on(
eventName as keyof MqttClientEventCallbacks,
promiseResolutionListeners[eventName],
)
})
})
}
export default connect
export { connectAsync }