-
Notifications
You must be signed in to change notification settings - Fork 27
/
browserMqtt.js
11950 lines (9988 loc) · 320 KB
/
browserMqtt.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mqtt = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process,global){
'use strict';
/**
* Module dependencies
*/
/*global setImmediate:true*/
var events = require('events'),
Store = require('./store'),
eos = require('end-of-stream'),
mqttPacket = require('mqtt-packet'),
Writable = require('readable-stream').Writable,
inherits = require('inherits'),
reInterval = require('reinterval'),
setImmediate = global.setImmediate || function (callback) {
// works in node v0.8
process.nextTick(callback);
},
defaultConnectOptions = {
keepalive: 10,
protocolId: 'MQTT',
protocolVersion: 4,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clean: true
};
function defaultId () {
return 'mqttjs_' + Math.random().toString(16).substr(2, 8);
}
function sendPacket (client, packet, cb) {
try {
var buf = mqttPacket.generate(packet);
if (!client.stream.write(buf) && cb) {
client.stream.once('drain', cb);
} else if (cb) {
cb();
}
} catch (err) {
if (cb) {
cb(err);
} else {
client.emit('error', err);
}
}
}
function storeAndSend (client, packet, cb) {
client.outgoingStore.put(packet, function storedPacket (err) {
if (err) {
return cb && cb(err);
}
sendPacket(client, packet, cb);
});
}
function nop () {}
/**
* MqttClient constructor
*
* @param {Stream} stream - stream
* @param {Object} [options] - connection options
* (see Connection#connect)
*/
function MqttClient (streamBuilder, options) {
var k,
that = this;
if (!(this instanceof MqttClient)) {
return new MqttClient(streamBuilder, options);
}
this.options = options || {};
// Defaults
for (k in defaultConnectOptions) {
if ('undefined' === typeof this.options[k]) {
this.options[k] = defaultConnectOptions[k];
} else {
this.options[k] = options[k];
}
}
this.options.clientId = this.options.clientId || defaultId();
this.streamBuilder = streamBuilder;
// Inflight message storages
this.outgoingStore = this.options.outgoingStore || new Store();
this.incomingStore = this.options.incomingStore || new Store();
// Ping timer, setup in _setupPingTimer
this.pingTimer = null;
// Is the client connected?
this.connected = false;
// Are we disconnecting?
this.disconnecting = false;
// Packet queue
this.queue = [];
// connack timer
this.connackTimer = null;
// Reconnect timer
this.reconnectTimer = null;
// MessageIDs starting with 1
this.nextId = Math.floor(Math.random() * 65535);
// Inflight callbacks
this.outgoing = {};
// Mark connected on connect
this.on('connect', function () {
this.connected = true;
var outStore = null;
outStore = this.outgoingStore.createStream();
// Control of stored messages
outStore.once('readable', function () {
function storeDeliver () {
var packet = outStore.read(1),
cb;
if (!packet) {
return;
}
// Avoid unnecesary stream read operations when disconnected
if (!that.disconnecting && !that.reconnectTimer && (0 < that.options.reconnectPeriod)) {
outStore.read(0);
cb = that.outgoing[packet.messageId];
that.outgoing[packet.messageId] = function () {
// Ensure that the original callback passed in to publish gets invoked
if (cb) {
cb();
}
// Ensure that the next message will only be read after callback is issued
storeDeliver();
};
that._sendPacket(packet);
} else if (outStore.destroy) {
outStore.destroy();
}
}
storeDeliver();
})
.on('error', this.emit.bind(this, 'error'));
});
// Mark disconnected on stream close
this.on('close', function () {
this.connected = false;
});
// Setup ping timer
this.on('connect', this._setupPingTimer);
// Send queued packets
this.on('connect', function () {
var queue = this.queue;
function deliver () {
var entry = queue.shift(),
packet = null;
if (!entry) {
return;
}
packet = entry.packet;
that._sendPacket(
packet,
function (err) {
if (entry.cb) {
entry.cb(err);
}
deliver();
}
);
}
deliver();
});
// Clear ping timer
this.on('close', function () {
if (null !== that.pingTimer) {
that.pingTimer.clear();
that.pingTimer = null;
}
});
// Setup reconnect timer on disconnect
this.on('close', this._setupReconnect);
events.EventEmitter.call(this);
this._setupStream();
}
inherits(MqttClient, events.EventEmitter);
/**
* setup the event handlers in the inner stream.
*
* @api private
*/
MqttClient.prototype._setupStream = function () {
var connectPacket,
that = this,
writable = new Writable(),
parser = mqttPacket.parser(this.options),
completeParse = null,
packets = [];
this._clearReconnect();
this.stream = this.streamBuilder(this);
parser.on('packet', function (packet) {
packets.push(packet);
});
function process () {
var packet = packets.shift(),
done = completeParse;
if (packet) {
that._handlePacket(packet, process);
} else {
completeParse = null;
done();
}
}
writable._write = function (buf, enc, done) {
completeParse = done;
parser.parse(buf);
process();
};
this.stream.pipe(writable);
// Suppress connection errors
this.stream.on('error', nop);
// Echo stream close
eos(this.stream, this.emit.bind(this, 'close'));
// Send a connect packet
connectPacket = Object.create(this.options);
connectPacket.cmd = 'connect';
// avoid message queue
sendPacket(this, connectPacket);
// Echo connection errors
parser.on('error', this.emit.bind(this, 'error'));
// many drain listeners are needed for qos 1 callbacks if the connection is intermittent
this.stream.setMaxListeners(1000);
clearTimeout(this.connackTimer);
this.connackTimer = setTimeout(function () {
that._cleanUp(true);
}, this.options.connectTimeout);
};
MqttClient.prototype._handlePacket = function (packet, done) {
switch (packet.cmd) {
case 'publish':
this._handlePublish(packet, done);
break;
case 'puback':
case 'pubrec':
case 'pubcomp':
case 'suback':
case 'unsuback':
this._handleAck(packet);
done();
break;
case 'pubrel':
this._handlePubrel(packet, done);
break;
case 'connack':
this._handleConnack(packet);
done();
break;
case 'pingresp':
this._handlePingresp(packet);
done();
break;
default:
// do nothing
// maybe we should do an error handling
// or just log it
break;
}
};
MqttClient.prototype._checkDisconnecting = function (callback) {
if (this.disconnecting) {
if (callback) {
callback(new Error('client disconnecting'));
} else {
this.emit(new Error('client disconnecting'));
}
}
return this.disconnecting;
};
/**
* publish - publish <message> to <topic>
*
* @param {String} topic - topic to publish to
* @param {String, Buffer} message - message to publish
* @param {Object} [opts] - publish options, includes:
* {Number} qos - qos level to publish on
* {Boolean} retain - whether or not to retain the message
* @param {Function} [callback] - function(err){}
* called when publish succeeds or fails
* @returns {MqttClient} this - for chaining
* @api public
*
* @example client.publish('topic', 'message');
* @example
* client.publish('topic', 'message', {qos: 1, retain: true});
* @example client.publish('topic', 'message', console.log);
*/
MqttClient.prototype.publish = function (topic, message, opts, callback) {
var packet;
// .publish(topic, payload, cb);
if ('function' === typeof opts) {
callback = opts;
opts = null;
}
// Default opts
if (!opts) {
opts = {qos: 0, retain: false};
}
if (this._checkDisconnecting(callback)) {
return this;
}
packet = {
cmd: 'publish',
topic: topic,
payload: message,
qos: opts.qos,
retain: opts.retain,
messageId: this._nextId()
};
switch (opts.qos) {
case 1:
case 2:
// Add to callbacks
this.outgoing[packet.messageId] = callback || nop;
this._sendPacket(packet);
break;
default:
this._sendPacket(packet, callback);
break;
}
return this;
};
/**
* subscribe - subscribe to <topic>
*
* @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
* @param {Object} [opts] - optional subscription options, includes:
* {Number} qos - subscribe qos level
* @param {Function} [callback] - function(err, granted){} where:
* {Error} err - subscription error (none at the moment!)
* {Array} granted - array of {topic: 't', qos: 0}
* @returns {MqttClient} this - for chaining
* @api public
* @example client.subscribe('topic');
* @example client.subscribe('topic', {qos: 1});
* @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
* @example client.subscribe('topic', console.log);
*/
MqttClient.prototype.subscribe = function () {
var packet,
args = Array.prototype.slice.call(arguments),
subs = [],
obj = args.shift(),
callback = args.pop() || nop,
opts = args.pop();
if ('string' === typeof obj) {
obj = [obj];
}
if ('function' !== typeof callback) {
opts = callback;
callback = nop;
}
if (this._checkDisconnecting(callback)) {
return this;
}
if (!opts) {
opts = { qos: 0 };
}
if (Array.isArray(obj)) {
obj.forEach(function (topic) {
subs.push({
topic: topic,
qos: opts.qos
});
});
} else {
Object
.keys(obj)
.forEach(function (k) {
subs.push({
topic: k,
qos: obj[k]
});
});
}
packet = {
cmd: 'subscribe',
subscriptions: subs,
qos: 1,
retain: false,
dup: false,
messageId: this._nextId()
};
this.outgoing[packet.messageId] = callback;
this._sendPacket(packet);
return this;
};
/**
* unsubscribe - unsubscribe from topic(s)
*
* @param {String, Array} topic - topics to unsubscribe from
* @param {Function} [callback] - callback fired on unsuback
* @returns {MqttClient} this - for chaining
* @api public
* @example client.unsubscribe('topic');
* @example client.unsubscribe('topic', console.log);
*/
MqttClient.prototype.unsubscribe = function (topic, callback) {
var packet = {
cmd: 'unsubscribe',
qos: 1,
messageId: this._nextId()
};
callback = callback || nop;
if (this._checkDisconnecting(callback)) {
return this;
}
if ('string' === typeof topic) {
packet.unsubscriptions = [topic];
} else if ('object' === typeof topic && topic.length) {
packet.unsubscriptions = topic;
}
this.outgoing[packet.messageId] = callback;
this._sendPacket(packet);
return this;
};
/**
* end - close connection
*
* @returns {MqttClient} this - for chaining
* @param {Boolean} force - do not wait for all in-flight messages to be acked
* @param {Function} cb - called when the client has been closed
*
* @api public
*/
MqttClient.prototype.end = function (force, cb) {
var that = this;
if ('function' === typeof force) {
cb = force;
force = false;
}
function closeStores () {
that.incomingStore.close(function () {
that.outgoingStore.close(cb);
});
}
function finish () {
that._cleanUp(force, closeStores);
}
if (this.disconnecting) {
return true;
}
this.disconnecting = true;
if (!force && 0 < Object.keys(this.outgoing).length) {
// wait 10ms, just to be sure we received all of it
this.once('outgoingEmpty', setTimeout.bind(null, finish, 10));
} else {
finish();
}
return this;
};
/**
* _reconnect - implement reconnection
* @api privateish
*/
MqttClient.prototype._reconnect = function () {
this.emit('reconnect');
this._setupStream();
};
/**
* _setupReconnect - setup reconnect timer
*/
MqttClient.prototype._setupReconnect = function () {
var that = this;
if (!that.disconnecting && !that.reconnectTimer && (0 < that.options.reconnectPeriod)) {
this.emit('offline');
that.reconnectTimer = setInterval(function () {
that._reconnect();
}, that.options.reconnectPeriod);
}
};
/**
* _clearReconnect - clear the reconnect timer
*/
MqttClient.prototype._clearReconnect = function () {
if (this.reconnectTimer) {
clearInterval(this.reconnectTimer);
this.reconnectTimer = false;
}
};
/**
* _cleanUp - clean up on connection end
* @api private
*/
MqttClient.prototype._cleanUp = function (forced, done) {
if (done) {
this.stream.on('close', done);
}
if (forced) {
this.stream.destroy();
} else {
this._sendPacket(
{ cmd: 'disconnect' },
setImmediate.bind(
null,
this.stream.end.bind(this.stream)
)
);
}
if (this.reconnectTimer) {
this._clearReconnect();
this._setupReconnect();
}
if (null !== this.pingTimer) {
this.pingTimer.clear();
this.pingTimer = null;
}
};
/**
* _sendPacket - send or queue a packet
* @param {String} type - packet type (see `protocol`)
* @param {Object} packet - packet options
* @param {Function} cb - callback when the packet is sent
* @api private
*/
MqttClient.prototype._sendPacket = function (packet, cb) {
if (!this.connected) {
return this.queue.push({ packet: packet, cb: cb });
}
// When sending a packet, reschedule the ping timer
this._shiftPingInterval();
switch (packet.qos) {
case 2:
case 1:
storeAndSend(this, packet, cb);
break;
/**
* no need of case here since it will be caught by default
* and jshint comply that before default it must be a break
* anyway it will result in -1 evaluation
*/
case 0:
/* falls through */
default:
sendPacket(this, packet, cb);
break;
}
};
/**
* _setupPingTimer - setup the ping timer
*
* @api private
*/
MqttClient.prototype._setupPingTimer = function () {
var that = this;
if (!this.pingTimer && this.options.keepalive) {
this.pingResp = true;
this.pingTimer = reInterval(function () {
that._checkPing();
}, this.options.keepalive * 1000);
}
};
/**
* _shiftPingInterval - reschedule the ping interval
*
* @api private
*/
MqttClient.prototype._shiftPingInterval = function () {
if (this.pingTimer && this.options.keepalive) {
this.pingTimer.reschedule(this.options.keepalive * 1000);
}
};
/**
* _checkPing - check if a pingresp has come back, and ping the server again
*
* @api private
*/
MqttClient.prototype._checkPing = function () {
if (this.pingResp) {
this.pingResp = false;
this._sendPacket({ cmd: 'pingreq' });
} else {
// do a forced cleanup since socket will be in bad shape
this._cleanUp(true);
}
};
/**
* _handlePingresp - handle a pingresp
*
* @api private
*/
MqttClient.prototype._handlePingresp = function () {
this.pingResp = true;
};
/**
* _handleConnack
*
* @param {Object} packet
* @api private
*/
MqttClient.prototype._handleConnack = function (packet) {
var rc = packet.returnCode,
// TODO: move to protocol
errors = [
'',
'Unacceptable protocol version',
'Identifier rejected',
'Server unavailable',
'Bad username or password',
'Not authorized'
];
clearTimeout(this.connackTimer);
if (0 === rc) {
this.emit('connect', packet);
} else if (0 < rc) {
this.emit('error',
new Error('Connection refused: ' + errors[rc]));
}
};
/**
* _handlePublish
*
* @param {Object} packet
* @api private
*/
/*
those late 2 case should be rewrite to comply with coding style:
case 1:
case 0:
// do not wait sending a puback
// no callback passed
if (1 === qos) {
this._sendPacket({
cmd: 'puback',
messageId: mid
});
}
// emit the message event for both qos 1 and 0
this.emit('message', topic, message, packet);
this.handleMessage(packet, done);
break;
default:
// do nothing but every switch mus have a default
// log or throw an error about unknown qos
break;
for now i just suppressed the warnings
*/
MqttClient.prototype._handlePublish = function (packet, done) {
var topic = packet.topic.toString(),
message = packet.payload,
qos = packet.qos,
mid = packet.messageId,
that = this;
switch (qos) {
case 2:
this.incomingStore.put(packet, function () {
that._sendPacket({cmd: 'pubrec', messageId: mid}, done);
});
break;
case 1:
// do not wait sending a puback
// no callback passed
this._sendPacket({
cmd: 'puback',
messageId: mid
});
/* falls through */
case 0:
// emit the message event for both qos 1 and 0
this.emit('message', topic, message, packet);
this.handleMessage(packet, done);
break;
default:
// do nothing
// log or throw an error about unknown qos
break;
}
};
/**
* Handle messages with backpressure support, one at a time.
* Override at will.
*
* @param Packet packet the packet
* @param Function callback call when finished
* @api public
*/
MqttClient.prototype.handleMessage = function (packet, callback) {
callback();
};
/**
* _handleAck
*
* @param {Object} packet
* @api private
*/
MqttClient.prototype._handleAck = function (packet) {
var mid = packet.messageId,
type = packet.cmd,
response = null,
cb = this.outgoing[mid],
that = this;
if (!cb) {
// Server sent an ack in error, ignore it.
return;
}
// Process
switch (type) {
case 'pubcomp':
// same thing as puback for QoS 2
case 'puback':
// Callback - we're done
delete this.outgoing[mid];
this.outgoingStore.del(packet, cb);
break;
case 'pubrec':
response = {
cmd: 'pubrel',
qos: 2,
messageId: mid
};
this._sendPacket(response);
break;
case 'suback':
delete this.outgoing[mid];
this.outgoingStore.del(packet, function (err, original) {
var i,
origSubs = original.subscriptions,
granted = packet.granted;
if (err) {
// missing packet, what should we do?
return that.emit('error', err);
}
for (i = 0; i < granted.length; i += 1) {
origSubs[i].qos = granted[i];
}
cb(null, origSubs);
});
break;
case 'unsuback':
delete this.outgoing[mid];
this.outgoingStore.del(packet, cb);
break;
default:
that.emit('error', new Error('unrecognized packet type'));
}
if (this.disconnecting &&
0 === Object.keys(this.outgoing).length) {
this.emit('outgoingEmpty');
}
};
/**
* _handlePubrel
*
* @param {Object} packet
* @api private
*/
MqttClient.prototype._handlePubrel = function (packet, callback) {
var mid = packet.messageId,
that = this;
that.incomingStore.get(packet, function (err, pub) {
if (err) {
return that.emit('error', err);
}
if ('pubrel' !== pub.cmd) {
that.emit('message', pub.topic, pub.payload, pub);
that.incomingStore.put(packet);
}
that._sendPacket({cmd: 'pubcomp', messageId: mid}, callback);
});
};
/**
* _nextId
*/
MqttClient.prototype._nextId = function () {
var id = this.nextId++;
// Ensure 16 bit unsigned int:
if (65535 === id) {
this.nextId = 1;
}
return id;
};
module.exports = MqttClient;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./store":5,"_process":66,"end-of-stream":7,"events":62,"inherits":10,"mqtt-packet":13,"readable-stream":26,"reinterval":27}],2:[function(require,module,exports){
'use strict';
var net = require('net');
/*
variables port and host can be removed since
you have all required information in opts object
*/
function buildBuilder (client, opts) {
var port, host;
opts.port = opts.port || 1883;
opts.hostname = opts.hostname || opts.host || 'localhost';
port = opts.port;
host = opts.hostname;
return net.createConnection(port, host);
}
module.exports = buildBuilder;
},{"net":57}],3:[function(require,module,exports){
'use strict';
var tls = require('tls');
function buildBuilder (mqttClient, opts) {
var connection;
opts.port = opts.port || 8883;
opts.host = opts.hostname || opts.host || 'localhost';
opts.rejectUnauthorized = false !== opts.rejectUnauthorized;
connection = tls.connect(opts);
/*eslint no-use-before-define: [2, "nofunc"]*/
connection.on('secureConnect', function () {
if (opts.rejectUnauthorized && !connection.authorized) {
connection.emit('error', new Error('TLS not authorized'));
} else {
connection.removeListener('error', handleTLSerrors);
}
});
/*
* to comply with strict rules, a function must be
* declared before it can be used
* so i moved it has to be moved before its first call
* later on maybe we can move all of them to the top of the file
* for now i just suppressed the warning
*/
/*jshint latedef:false*/
function handleTLSerrors (err) {
// How can I get verify this error is a tls error?
if (opts.rejectUnauthorized) {
mqttClient.emit('error', err);
}
// close this connection to match the behaviour of net
// otherwise all we get is an error from the connection
// and close event doesn't fire. This is a work around
// to enable the reconnect code to work the same as with
// net.createConnection
connection.end();
}
/*jshint latedef:false*/
connection.on('error', handleTLSerrors);
return connection;
}
module.exports = buildBuilder;
},{"tls":57}],4:[function(require,module,exports){
(function (process){
'use strict';
var websocket = require('websocket-stream'),
_URL = require('url');
function buildBuilder (client, opts) {
var wsOpt = {
protocol: 'mqttv3.1'
},
host = opts.hostname || 'localhost',
port = String(opts.port || 80),
path = opts.path || '/',
url = opts.protocol + '://' + host + ':' + port + path;
if ('wss' === opts.protocol) {
if (opts.hasOwnProperty('rejectUnauthorized')) {
wsOpt.rejectUnauthorized = opts.rejectUnauthorized;
}
}
return websocket(url, wsOpt);
}
function buildBuilderBrowser (mqttClient, opts) {
var url, parsed;
if ('undefined' !== typeof (document)) { // for Web Workers! P.S: typeof(document) !== undefined may be becoming the faster one these days.
parsed = _URL.parse(document.URL);
} else {
throw new Error('Could not determine host. Specify host manually.');
}
if (!opts.protocol) {
if ('https:' === parsed.protocol) {
opts.protocol = 'wss';
} else {
opts.protocol = 'ws';
}
}
if (!opts.hostname) {