UNPKG

6.07 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.connectAsync = void 0;
7const debug_1 = __importDefault(require("debug"));
8const url_1 = __importDefault(require("url"));
9const client_1 = __importDefault(require("../client"));
10const is_browser_1 = __importDefault(require("../is-browser"));
11if (typeof (process === null || process === void 0 ? void 0 : process.nextTick) !== 'function') {
12 process.nextTick = setImmediate;
13}
14const debug = (0, debug_1.default)('mqttjs');
15const protocols = {};
16if (!is_browser_1.default) {
17 protocols.mqtt = require('./tcp').default;
18 protocols.tcp = require('./tcp').default;
19 protocols.ssl = require('./tls').default;
20 protocols.tls = protocols.ssl;
21 protocols.mqtts = require('./tls').default;
22}
23else {
24 protocols.wx = require('./wx').default;
25 protocols.wxs = require('./wx').default;
26 protocols.ali = require('./ali').default;
27 protocols.alis = require('./ali').default;
28}
29protocols.ws = require('./ws').default;
30protocols.wss = require('./ws').default;
31function parseAuthOptions(opts) {
32 let matches;
33 if (opts.auth) {
34 matches = opts.auth.match(/^(.+):(.+)$/);
35 if (matches) {
36 opts.username = matches[1];
37 opts.password = matches[2];
38 }
39 else {
40 opts.username = opts.auth;
41 }
42 }
43}
44function connect(brokerUrl, opts) {
45 debug('connecting to an MQTT broker...');
46 if (typeof brokerUrl === 'object' && !opts) {
47 opts = brokerUrl;
48 brokerUrl = '';
49 }
50 opts = opts || {};
51 if (brokerUrl && typeof brokerUrl === 'string') {
52 const parsed = url_1.default.parse(brokerUrl, true);
53 if (parsed.port != null) {
54 parsed.port = Number(parsed.port);
55 }
56 opts = Object.assign(Object.assign({}, parsed), opts);
57 if (opts.protocol === null) {
58 throw new Error('Missing protocol');
59 }
60 opts.protocol = opts.protocol.replace(/:$/, '');
61 }
62 parseAuthOptions(opts);
63 if (opts.query && typeof opts.query.clientId === 'string') {
64 opts.clientId = opts.query.clientId;
65 }
66 if (opts.cert && opts.key) {
67 if (opts.protocol) {
68 if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
69 switch (opts.protocol) {
70 case 'mqtt':
71 opts.protocol = 'mqtts';
72 break;
73 case 'ws':
74 opts.protocol = 'wss';
75 break;
76 case 'wx':
77 opts.protocol = 'wxs';
78 break;
79 case 'ali':
80 opts.protocol = 'alis';
81 break;
82 default:
83 throw new Error(`Unknown protocol for secure connection: "${opts.protocol}"!`);
84 }
85 }
86 }
87 else {
88 throw new Error('Missing secure protocol key');
89 }
90 }
91 if (!protocols[opts.protocol]) {
92 const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1;
93 opts.protocol = [
94 'mqtt',
95 'mqtts',
96 'ws',
97 'wss',
98 'wx',
99 'wxs',
100 'ali',
101 'alis',
102 ].filter((key, index) => {
103 if (isSecure && index % 2 === 0) {
104 return false;
105 }
106 return typeof protocols[key] === 'function';
107 })[0];
108 }
109 if (opts.clean === false && !opts.clientId) {
110 throw new Error('Missing clientId for unclean clients');
111 }
112 if (opts.protocol) {
113 opts.defaultProtocol = opts.protocol;
114 }
115 function wrapper(client) {
116 if (opts.servers) {
117 if (!client._reconnectCount ||
118 client._reconnectCount === opts.servers.length) {
119 client._reconnectCount = 0;
120 }
121 opts.host = opts.servers[client._reconnectCount].host;
122 opts.port = opts.servers[client._reconnectCount].port;
123 opts.protocol = !opts.servers[client._reconnectCount].protocol
124 ? opts.defaultProtocol
125 : opts.servers[client._reconnectCount].protocol;
126 opts.hostname = opts.host;
127 client._reconnectCount++;
128 }
129 debug('calling streambuilder for', opts.protocol);
130 return protocols[opts.protocol](client, opts);
131 }
132 const client = new client_1.default(wrapper, opts);
133 client.on('error', () => {
134 });
135 return client;
136}
137function connectAsync(brokerUrl, opts, allowRetries = true) {
138 return new Promise((resolve, reject) => {
139 const client = connect(brokerUrl, opts);
140 const promiseResolutionListeners = {
141 connect: (connack) => {
142 removePromiseResolutionListeners();
143 resolve(client);
144 },
145 end: () => {
146 removePromiseResolutionListeners();
147 resolve(client);
148 },
149 error: (err) => {
150 removePromiseResolutionListeners();
151 client.end();
152 reject(err);
153 },
154 };
155 if (allowRetries === false) {
156 promiseResolutionListeners.close = () => {
157 promiseResolutionListeners.error(new Error("Couldn't connect to server"));
158 };
159 }
160 function removePromiseResolutionListeners() {
161 Object.keys(promiseResolutionListeners).forEach((eventName) => {
162 client.off(eventName, promiseResolutionListeners[eventName]);
163 });
164 }
165 Object.keys(promiseResolutionListeners).forEach((eventName) => {
166 client.on(eventName, promiseResolutionListeners[eventName]);
167 });
168 });
169}
170exports.connectAsync = connectAsync;
171exports.default = connect;
172//# sourceMappingURL=index.js.map
\No newline at end of file