osh-js
Version:
OSH javascript Toolkit
402 lines • 355 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
!function (e) { if ("object" == typeof exports && "undefined" != typeof module)
module.exports = e();
else if ("function" == typeof define && define.amd)
define([], e);
else {
("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).mqtt = e();
} }(function () { return function () { return function e(t, r, n) { function i(s, a) { if (!r[s]) {
if (!t[s]) {
var l = "function" == typeof require && require;
if (!a && l)
return l(s, !0);
if (o)
return o(s, !0);
var u = new Error("Cannot find module '" + s + "'");
throw u.code = "MODULE_NOT_FOUND", u;
}
var c = r[s] = { exports: {} };
t[s][0].call(c.exports, function (e) { return i(t[s][1][e] || e); }, c, c.exports, e, t, r, n);
} return r[s].exports; } for (var o = "function" == typeof require && require, s = 0; s < n.length; s++)
i(n[s]); return i; }; }()({ 1: [function (e, t, r) { (function (r, n) { (function () {
"use strict";
var i = e("events").EventEmitter, o = e("./store"), s = e("./topic-alias-recv"), a = e("./topic-alias-send"), l = e("mqtt-packet"), u = e("./default-message-id-provider"), c = e("readable-stream").Writable, h = e("inherits"), f = e("reinterval"), p = e("rfdc/default"), d = e("./validations"), g = e("xtend"), y = e("debug")("mqttjs:client"), b = r ? r.nextTick : function (e) { setTimeout(e, 0); }, m = n.setImmediate || function (e) { b(e); }, v = { keepalive: 60, reschedulePings: !0, protocolId: "MQTT", protocolVersion: 4, reconnectPeriod: 1e3, connectTimeout: 3e4, clean: !0, resubscribe: !0 }, w = ["ECONNREFUSED", "EADDRINUSE", "ECONNRESET", "ENOTFOUND"], _ = { 0: "", 1: "Unacceptable protocol version", 2: "Identifier rejected", 3: "Server unavailable", 4: "Bad username or password", 5: "Not authorized", 16: "No matching subscribers", 17: "No subscription existed", 128: "Unspecified error", 129: "Malformed Packet", 130: "Protocol Error", 131: "Implementation specific error", 132: "Unsupported Protocol Version", 133: "Client Identifier not valid", 134: "Bad User Name or Password", 135: "Not authorized", 136: "Server unavailable", 137: "Server busy", 138: "Banned", 139: "Server shutting down", 140: "Bad authentication method", 141: "Keep Alive timeout", 142: "Session taken over", 143: "Topic Filter invalid", 144: "Topic Name invalid", 145: "Packet identifier in use", 146: "Packet Identifier not found", 147: "Receive Maximum exceeded", 148: "Topic Alias invalid", 149: "Packet too large", 150: "Message rate too high", 151: "Quota exceeded", 152: "Administrative action", 153: "Payload format invalid", 154: "Retain not supported", 155: "QoS not supported", 156: "Use another server", 157: "Server moved", 158: "Shared Subscriptions not supported", 159: "Connection rate exceeded", 160: "Maximum connect time", 161: "Subscription Identifiers not supported", 162: "Wildcard Subscriptions not supported" };
function k(e, t) { var r; t.properties && (r = t.properties.topicAlias); var n = t.topic.toString(); if (0 === n.length) {
if (void 0 === r)
return new Error("Unregistered Topic Alias");
if (void 0 === (n = e.topicAliasSend.getTopicByAlias(r)))
return new Error("Unregistered Topic Alias");
t.topic = n;
} r && delete t.properties.topicAlias; }
function S(e, t, r) { y("sendPacket :: packet: %O", t), y("sendPacket :: emitting `packetsend`"), e.emit("packetsend", t), y("sendPacket :: writing to stream"); var n = l.writeToStream(t, e.stream, e.options); y("sendPacket :: writeToStream result %s", n), !n && r ? (y("sendPacket :: handle events on `drain` once through callback."), e.stream.once("drain", r)) : r && (y("sendPacket :: invoking cb"), r()); }
function E(e, t, r, n) { y("storeAndSend :: store packet with cmd %s to outgoingStore", t.cmd); var i, o = t; if ("publish" === o.cmd && (o = p(t), i = k(e, o)))
return r && r(i); e.outgoingStore.put(o, function (i) { if (i)
return r && r(i); n(), S(e, t, r); }); }
function C(e) { y("nop ::", e); }
function T(e, t) { var r; var n = this; if (!(this instanceof T))
return new T(e, t); for (r in this.options = t || {}, v)
void 0 === this.options[r] ? this.options[r] = v[r] : this.options[r] = t[r]; y("MqttClient :: options.protocol", t.protocol), y("MqttClient :: options.protocolVersion", t.protocolVersion), y("MqttClient :: options.username", t.username), y("MqttClient :: options.keepalive", t.keepalive), y("MqttClient :: options.reconnectPeriod", t.reconnectPeriod), y("MqttClient :: options.rejectUnauthorized", t.rejectUnauthorized), y("MqttClient :: options.topicAliasMaximum", t.topicAliasMaximum), this.options.clientId = "string" == typeof t.clientId ? t.clientId : "mqttjs_" + Math.random().toString(16).substr(2, 8), y("MqttClient :: clientId", this.options.clientId), this.options.customHandleAcks = 5 === t.protocolVersion && t.customHandleAcks ? t.customHandleAcks : function () { arguments[3](0); }, this.streamBuilder = e, this.messageIdProvider = void 0 === this.options.messageIdProvider ? new u : this.options.messageIdProvider, this.outgoingStore = t.outgoingStore || new o, this.incomingStore = t.incomingStore || new o, this.queueQoSZero = void 0 === t.queueQoSZero || t.queueQoSZero, this._resubscribeTopics = {}, this.messageIdToTopic = {}, this.pingTimer = null, this.connected = !1, this.disconnecting = !1, this.queue = [], this.connackTimer = null, this.reconnectTimer = null, this._storeProcessing = !1, this._packetIdsDuringStoreProcessing = {}, this._storeProcessingQueue = [], this.outgoing = {}, this._firstConnection = !0, t.topicAliasMaximum > 0 && (t.topicAliasMaximum > 65535 ? y("MqttClient :: options.topicAliasMaximum is out of range") : this.topicAliasRecv = new s(t.topicAliasMaximum)), this.on("connect", function () { var e = this.queue; y("connect :: sending queued packets"), function t() { var r = e.shift(); y("deliver :: entry %o", r); var i = null; if (!r)
return void n._resubscribe(); i = r.packet, y("deliver :: call _sendPacket for %o", i); var o = !0; i.messageId && 0 !== i.messageId && (n.messageIdProvider.register(i.messageId) || (o = !1)), o ? n._sendPacket(i, function (e) { r.cb && r.cb(e), t(); }) : (y("messageId: %d has already used. The message is skipped and removed.", i.messageId), t()); }(); }), this.on("close", function () { y("close :: connected set to `false`"), this.connected = !1, y("close :: clearing connackTimer"), clearTimeout(this.connackTimer), y("close :: clearing ping timer"), null !== n.pingTimer && (n.pingTimer.clear(), n.pingTimer = null), this.topicAliasRecv && this.topicAliasRecv.clear(), y("close :: calling _setupReconnect"), this._setupReconnect(); }), i.call(this), y("MqttClient :: setting up stream"), this._setupStream(); }
h(T, i), T.prototype._setupStream = function () {
var _this = this;
var e = this, t = new c, r = l.parser(this.options);
var n = null;
var i = [];
function o() { if (i.length)
b(s);
else {
var e_1 = n;
n = null, e_1();
} }
function s() { y("work :: getting next packet in queue"); var t = i.shift(); if (t)
y("work :: packet pulled from queue"), e._handlePacket(t, o);
else {
y("work :: no packets in queue");
var e_2 = n;
n = null, y("work :: done flag is %s", !!e_2), e_2 && e_2();
} }
y("_setupStream :: calling method to clear reconnect"), this._clearReconnect(), y("_setupStream :: using streamBuilder provided to client to create stream"), this.stream = this.streamBuilder(this), r.on("packet", function (e) { y("parser :: on packet push to packets array."), i.push(e); }), t._write = function (e, t, i) { n = i, y("writable stream :: parsing buffer"), r.parse(e), s(); }, y("_setupStream :: pipe stream to writable stream"), this.stream.pipe(t), this.stream.on("error", function (t) { y("streamErrorHandler :: error", t.message), w.includes(t.code) ? (y("streamErrorHandler :: emitting error"), e.emit("error", t)) : C(t); }), this.stream.on("close", function () { var t; y("(%s)stream :: on close", e.options.clientId), (t = e.outgoing) && (y("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"), Object.keys(t).forEach(function (e) { t[e].volatile && "function" == typeof t[e].cb && (t[e].cb(new Error("Connection closed")), delete t[e]); })), y("stream: emit close to MqttClient"), e.emit("close"); }), y("_setupStream: sending packet `connect`");
var a = Object.create(this.options);
if (a.cmd = "connect", this.topicAliasRecv && (a.properties || (a.properties = {}), this.topicAliasRecv && (a.properties.topicAliasMaximum = this.topicAliasRecv.max)), S(this, a), r.on("error", this.emit.bind(this, "error")), this.options.properties) {
if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData)
return e.end(function () { return _this.emit("error", new Error("Packet has no Authentication Method")); }), this;
if (this.options.properties.authenticationMethod && this.options.authPacket && "object" == typeof this.options.authPacket) {
S(this, g({ cmd: "auth", reasonCode: 0 }, this.options.authPacket));
}
}
this.stream.setMaxListeners(1e3), clearTimeout(this.connackTimer), this.connackTimer = setTimeout(function () { y("!!connectTimeout hit!! Calling _cleanUp with force `true`"), e._cleanUp(!0); }, this.options.connectTimeout);
}, T.prototype._handlePacket = function (e, t) { var r = this.options; if (5 === r.protocolVersion && r.properties && r.properties.maximumPacketSize && r.properties.maximumPacketSize < e.length)
return this.emit("error", new Error("exceeding packets size " + e.cmd)), this.end({ reasonCode: 149, properties: { reasonString: "Maximum packet size was exceeded" } }), this; switch (y("_handlePacket :: emitting packetreceive"), this.emit("packetreceive", e), e.cmd) {
case "publish":
this._handlePublish(e, t);
break;
case "puback":
case "pubrec":
case "pubcomp":
case "suback":
case "unsuback":
this._handleAck(e), t();
break;
case "pubrel":
this._handlePubrel(e, t);
break;
case "connack":
this._handleConnack(e), t();
break;
case "auth":
this._handleAuth(e), t();
break;
case "pingresp":
this._handlePingresp(e), t();
break;
case "disconnect": this._handleDisconnect(e), t();
} }, T.prototype._checkDisconnecting = function (e) { return this.disconnecting && (e ? e(new Error("client disconnecting")) : this.emit("error", new Error("client disconnecting"))), this.disconnecting; }, T.prototype.publish = function (e, t, r, n) { y("publish :: message `%s` to topic `%s`", t, e); var i = this.options; "function" == typeof r && (n = r, r = null); if (r = g({ qos: 0, retain: !1, dup: !1 }, r), this._checkDisconnecting(n))
return this; var o = this, s = function () { var s = 0; if ((1 === r.qos || 2 === r.qos) && null === (s = o._nextId()))
return y("No messageId left"), !1; var a = { cmd: "publish", topic: e, payload: t, qos: r.qos, retain: r.retain, messageId: s, dup: r.dup }; switch (5 === i.protocolVersion && (a.properties = r.properties), y("publish :: qos", r.qos), r.qos) {
case 1:
case 2:
o.outgoing[a.messageId] = { volatile: !1, cb: n || C }, y("MqttClient:publish: packet cmd: %s", a.cmd), o._sendPacket(a, void 0, r.cbStorePut);
break;
default: y("MqttClient:publish: packet cmd: %s", a.cmd), o._sendPacket(a, n, r.cbStorePut);
} return !0; }; return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !s()) && this._storeProcessingQueue.push({ invoke: s, cbStorePut: r.cbStorePut, callback: n }), this; }, T.prototype.subscribe = function () { var e = this, t = new Array(arguments.length); for (var e_3 = 0; e_3 < arguments.length; e_3++)
t[e_3] = arguments[e_3]; var r = []; var n = t.shift(); var i = n.resubscribe; var o = t.pop() || C, s = t.pop(); var a = this.options.protocolVersion; delete n.resubscribe, "string" == typeof n && (n = [n]), "function" != typeof o && (s = o, o = C); var l = d.validateTopics(n); if (null !== l)
return m(o, new Error("Invalid topic " + l)), this; if (this._checkDisconnecting(o))
return y("subscribe: discconecting true"), this; var u = { qos: 0 }; if (5 === a && (u.nl = !1, u.rap = !1, u.rh = 0), s = g(u, s), Array.isArray(n) ? n.forEach(function (t) { if (y("subscribe: array topic %s", t), !Object.prototype.hasOwnProperty.call(e._resubscribeTopics, t) || e._resubscribeTopics[t].qos < s.qos || i) {
var e_4 = { topic: t, qos: s.qos };
5 === a && (e_4.nl = s.nl, e_4.rap = s.rap, e_4.rh = s.rh, e_4.properties = s.properties), y("subscribe: pushing topic `%s` and qos `%s` to subs list", e_4.topic, e_4.qos), r.push(e_4);
} }) : Object.keys(n).forEach(function (t) { if (y("subscribe: object topic %s", t), !Object.prototype.hasOwnProperty.call(e._resubscribeTopics, t) || e._resubscribeTopics[t].qos < n[t].qos || i) {
var e_5 = { topic: t, qos: n[t].qos };
5 === a && (e_5.nl = n[t].nl, e_5.rap = n[t].rap, e_5.rh = n[t].rh, e_5.properties = s.properties), y("subscribe: pushing `%s` to subs list", e_5), r.push(e_5);
} }), !r.length)
return o(null, []), this; var c = function () { var t = e._nextId(); if (null === t)
return y("No messageId left"), !1; var n = { cmd: "subscribe", subscriptions: r, qos: 1, retain: !1, dup: !1, messageId: t }; if (s.properties && (n.properties = s.properties), e.options.resubscribe) {
y("subscribe :: resubscribe true");
var t_1 = [];
r.forEach(function (r) { if (e.options.reconnectPeriod > 0) {
var n_1 = { qos: r.qos };
5 === a && (n_1.nl = r.nl || !1, n_1.rap = r.rap || !1, n_1.rh = r.rh || 0, n_1.properties = r.properties), e._resubscribeTopics[r.topic] = n_1, t_1.push(r.topic);
} }), e.messageIdToTopic[n.messageId] = t_1;
} return e.outgoing[n.messageId] = { volatile: !0, cb: function (e, t) { if (!e) {
var e_6 = t.granted;
for (var t_2 = 0; t_2 < e_6.length; t_2 += 1)
r[t_2].qos = e_6[t_2];
} o(e, r); } }, y("subscribe :: call _sendPacket"), e._sendPacket(n), !0; }; return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !c()) && this._storeProcessingQueue.push({ invoke: c, callback: o }), this; }, T.prototype.unsubscribe = function () { var e = this, t = new Array(arguments.length); for (var e_7 = 0; e_7 < arguments.length; e_7++)
t[e_7] = arguments[e_7]; var r = t.shift(), n = t.pop() || C, i = t.pop(); "string" == typeof r && (r = [r]), "function" != typeof n && (i = n, n = C); var o = d.validateTopics(r); if (null !== o)
return m(n, new Error("Invalid topic " + o)), this; if (e._checkDisconnecting(n))
return this; var s = function () { var t = e._nextId(); if (null === t)
return y("No messageId left"), !1; var o = { cmd: "unsubscribe", qos: 1, messageId: t }; return "string" == typeof r ? o.unsubscriptions = [r] : Array.isArray(r) && (o.unsubscriptions = r), e.options.resubscribe && o.unsubscriptions.forEach(function (t) { delete e._resubscribeTopics[t]; }), "object" == typeof i && i.properties && (o.properties = i.properties), e.outgoing[o.messageId] = { volatile: !0, cb: n }, y("unsubscribe: call _sendPacket"), e._sendPacket(o), !0; }; return (this._storeProcessing || this._storeProcessingQueue.length > 0 || !s()) && this._storeProcessingQueue.push({ invoke: s, callback: n }), this; }, T.prototype.end = function (e, t, r) { var n = this; function i() { y("end :: (%s) :: finish :: calling _cleanUp with force %s", n.options.clientId, e), n._cleanUp(e, function () { y("end :: finish :: calling process.nextTick on closeStores"), b(function () { y("end :: closeStores: closing incoming and outgoing stores"), n.disconnected = !0, n.incomingStore.close(function (e) { n.outgoingStore.close(function (t) { if (y("end :: closeStores: emitting end"), n.emit("end"), r) {
var n_2 = e || t;
y("end :: closeStores: invoking callback with args"), r(n_2);
} }); }), n._deferredReconnect && n._deferredReconnect(); }.bind(n)); }, t); } return y("end :: (%s)", this.options.clientId), null != e && "boolean" == typeof e || (r = t || C, t = e, e = !1, "object" != typeof t && (r = t, t = null, "function" != typeof r && (r = C))), "object" != typeof t && (r = t, t = null), y("end :: cb? %s", !!r), r = r || C, this.disconnecting ? (r(), this) : (this._clearReconnect(), this.disconnecting = !0, !e && Object.keys(this.outgoing).length > 0 ? (y("end :: (%s) :: calling finish in 10ms once outgoing is empty", n.options.clientId), this.once("outgoingEmpty", setTimeout.bind(null, i, 10))) : (y("end :: (%s) :: immediately calling finish", n.options.clientId), i()), this); }, T.prototype.removeOutgoingMessage = function (e) { var t = this.outgoing[e] ? this.outgoing[e].cb : null; return delete this.outgoing[e], this.outgoingStore.del({ messageId: e }, function () { t(new Error("Message removed")); }), this; }, T.prototype.reconnect = function (e) { y("client reconnect"); var t = this, r = function () { e ? (t.options.incomingStore = e.incomingStore, t.options.outgoingStore = e.outgoingStore) : (t.options.incomingStore = null, t.options.outgoingStore = null), t.incomingStore = t.options.incomingStore || new o, t.outgoingStore = t.options.outgoingStore || new o, t.disconnecting = !1, t.disconnected = !1, t._deferredReconnect = null, t._reconnect(); }; return this.disconnecting && !this.disconnected ? this._deferredReconnect = r : r(), this; }, T.prototype._reconnect = function () {
var _this = this;
y("_reconnect: emitting reconnect to client"), this.emit("reconnect"), this.connected ? (this.end(function () { _this._setupStream(); }), y("client already connected. disconnecting first.")) : (y("_reconnect: calling _setupStream"), this._setupStream());
}, T.prototype._setupReconnect = function () { var e = this; !e.disconnecting && !e.reconnectTimer && e.options.reconnectPeriod > 0 ? (this.reconnecting || (y("_setupReconnect :: emit `offline` state"), this.emit("offline"), y("_setupReconnect :: set `reconnecting` to `true`"), this.reconnecting = !0), y("_setupReconnect :: setting reconnectTimer for %d ms", e.options.reconnectPeriod), e.reconnectTimer = setInterval(function () { y("reconnectTimer :: reconnect triggered!"), e._reconnect(); }, e.options.reconnectPeriod)) : y("_setupReconnect :: doing nothing..."); }, T.prototype._clearReconnect = function () { y("_clearReconnect : clearing reconnect timer"), this.reconnectTimer && (clearInterval(this.reconnectTimer), this.reconnectTimer = null); }, T.prototype._cleanUp = function (e, t) { var r = arguments[2]; if (t && (y("_cleanUp :: done callback provided for on stream close"), this.stream.on("close", t)), y("_cleanUp :: forced? %s", e), e)
0 === this.options.reconnectPeriod && this.options.clean && (n = this.outgoing) && (y("flush: queue exists? %b", !!n), Object.keys(n).forEach(function (e) { "function" == typeof n[e].cb && (n[e].cb(new Error("Connection closed")), delete n[e]); })), y("_cleanUp :: (%s) :: destroying stream", this.options.clientId), this.stream.destroy();
else {
var e_8 = g({ cmd: "disconnect" }, r);
y("_cleanUp :: (%s) :: call _sendPacket with disconnect packet", this.options.clientId), this._sendPacket(e_8, m.bind(null, this.stream.end.bind(this.stream)));
} var n; this.disconnecting || (y("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."), this._clearReconnect(), this._setupReconnect()), null !== this.pingTimer && (y("_cleanUp :: clearing pingTimer"), this.pingTimer.clear(), this.pingTimer = null), t && !this.connected && (y("_cleanUp :: (%s) :: removing stream `done` callback `close` listener", this.options.clientId), this.stream.removeListener("close", t), t()); }, T.prototype._sendPacket = function (e, t, r) { y("_sendPacket :: (%s) :: start", this.options.clientId), r = r || C, t = t || C; var n = function (e, t) { if (5 === e.options.protocolVersion && "publish" === t.cmd) {
var r_1;
t.properties && (r_1 = t.properties.topicAlias);
var n_3 = t.topic.toString();
if (e.topicAliasSend)
if (r_1) {
if (0 !== n_3.length && (y("applyTopicAlias :: register topic: %s - alias: %d", n_3, r_1), !e.topicAliasSend.put(n_3, r_1)))
return y("applyTopicAlias :: error out of range. topic: %s - alias: %d", n_3, r_1), new Error("Sending Topic Alias out of range");
}
else
0 !== n_3.length && (e.options.autoAssignTopicAlias ? (r_1 = e.topicAliasSend.getAliasByTopic(n_3)) ? (t.topic = "", t.properties = __assign(__assign({}, t.properties), { topicAlias: r_1 }), y("applyTopicAlias :: auto assign(use) topic: %s - alias: %d", n_3, r_1)) : (r_1 = e.topicAliasSend.getLruAlias(), e.topicAliasSend.put(n_3, r_1), t.properties = __assign(__assign({}, t.properties), { topicAlias: r_1 }), y("applyTopicAlias :: auto assign topic: %s - alias: %d", n_3, r_1)) : e.options.autoUseTopicAlias && (r_1 = e.topicAliasSend.getAliasByTopic(n_3)) && (t.topic = "", t.properties = __assign(__assign({}, t.properties), { topicAlias: r_1 }), y("applyTopicAlias :: auto use topic: %s - alias: %d", n_3, r_1)));
else if (r_1)
return y("applyTopicAlias :: error out of range. topic: %s - alias: %d", n_3, r_1), new Error("Sending Topic Alias out of range");
} }(this, e); if (n)
t(n);
else {
if (!this.connected)
return "auth" === e.cmd ? (this._shiftPingInterval(), void S(this, e, t)) : (y("_sendPacket :: client not connected. Storing packet offline."), void this._storePacket(e, t, r));
switch (this._shiftPingInterval(), e.cmd) {
case "publish": break;
case "pubrel": return void E(this, e, t, r);
default: return void S(this, e, t);
}
switch (e.qos) {
case 2:
case 1:
E(this, e, t, r);
break;
case 0:
default: S(this, e, t);
}
y("_sendPacket :: (%s) :: end", this.options.clientId);
} }, T.prototype._storePacket = function (e, t, r) { y("_storePacket :: packet: %o", e), y("_storePacket :: cb? %s", !!t), r = r || C; var n = e; if ("publish" === n.cmd) {
var r_2 = k(this, n = p(e));
if (r_2)
return t && t(r_2);
} 0 === (n.qos || 0) && this.queueQoSZero || "publish" !== n.cmd ? this.queue.push({ packet: n, cb: t }) : n.qos > 0 ? (t = this.outgoing[n.messageId] ? this.outgoing[n.messageId].cb : null, this.outgoingStore.put(n, function (e) { if (e)
return t && t(e); r(); })) : t && t(new Error("No connection to broker")); }, T.prototype._setupPingTimer = function () { y("_setupPingTimer :: keepalive %d (seconds)", this.options.keepalive); var e = this; !this.pingTimer && this.options.keepalive && (this.pingResp = !0, this.pingTimer = f(function () { e._checkPing(); }, 1e3 * this.options.keepalive)); }, T.prototype._shiftPingInterval = function () { this.pingTimer && this.options.keepalive && this.options.reschedulePings && this.pingTimer.reschedule(1e3 * this.options.keepalive); }, T.prototype._checkPing = function () { y("_checkPing :: checking ping..."), this.pingResp ? (y("_checkPing :: ping response received. Clearing flag and sending `pingreq`"), this.pingResp = !1, this._sendPacket({ cmd: "pingreq" })) : (y("_checkPing :: calling _cleanUp with force true"), this._cleanUp(!0)); }, T.prototype._handlePingresp = function () { this.pingResp = !0; }, T.prototype._handleConnack = function (e) { y("_handleConnack"); var t = this.options, r = 5 === t.protocolVersion ? e.reasonCode : e.returnCode; if (clearTimeout(this.connackTimer), delete this.topicAliasSend, e.properties) {
if (e.properties.topicAliasMaximum) {
if (e.properties.topicAliasMaximum > 65535)
return void this.emit("error", new Error("topicAliasMaximum from broker is out of range"));
e.properties.topicAliasMaximum > 0 && (this.topicAliasSend = new a(e.properties.topicAliasMaximum));
}
e.properties.serverKeepAlive && t.keepalive && (t.keepalive = e.properties.serverKeepAlive, this._shiftPingInterval()), e.properties.maximumPacketSize && (t.properties || (t.properties = {}), t.properties.maximumPacketSize = e.properties.maximumPacketSize);
} if (0 === r)
this.reconnecting = !1, this._onConnect(e);
else if (r > 0) {
var e_9 = new Error("Connection refused: " + _[r]);
e_9.code = r, this.emit("error", e_9);
} }, T.prototype._handleAuth = function (e) { var t = this.options.protocolVersion, r = 5 === t ? e.reasonCode : e.returnCode; if (5 !== t) {
var e_10 = new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:" + t);
return e_10.code = r, void this.emit("error", e_10);
} var n = this; this.handleAuth(e, function (e, t) { if (e)
n.emit("error", e);
else if (24 === r)
n.reconnecting = !1, n._sendPacket(t);
else {
var t_3 = new Error("Connection refused: " + _[r]);
e.code = r, n.emit("error", t_3);
} }); }, T.prototype.handleAuth = function (e, t) { t(); }, T.prototype._handlePublish = function (e, t) { y("_handlePublish: packet %o", e), t = void 0 !== t ? t : C; var r = e.topic.toString(); var n = e.payload, i = e.qos, o = e.messageId, s = this, a = this.options, l = [0, 16, 128, 131, 135, 144, 145, 151, 153]; if (5 === this.options.protocolVersion) {
var t_4;
if (e.properties && (t_4 = e.properties.topicAlias), void 0 !== t_4)
if (0 === r.length) {
if (!(t_4 > 0 && t_4 <= 65535))
return y("_handlePublish :: topic alias out of range. alias: %d", t_4), void this.emit("error", new Error("Received Topic Alias is out of range"));
{
var e_11 = this.topicAliasRecv.getTopicByAlias(t_4);
if (!e_11)
return y("_handlePublish :: unregistered topic alias. alias: %d", t_4), void this.emit("error", new Error("Received unregistered Topic Alias"));
y("_handlePublish :: topic complemented by alias. topic: %s - alias: %d", r = e_11, t_4);
}
}
else {
if (!this.topicAliasRecv.put(r, t_4))
return y("_handlePublish :: topic alias out of range. alias: %d", t_4), void this.emit("error", new Error("Received Topic Alias is out of range"));
y("_handlePublish :: registered topic: %s - alias: %d", r, t_4);
}
} switch (y("_handlePublish: qos %d", i), i) {
case 2:
a.customHandleAcks(r, n, e, function (r, n) { return r instanceof Error || (n = r, r = null), r ? s.emit("error", r) : -1 === l.indexOf(n) ? s.emit("error", new Error("Wrong reason code for pubrec")) : void (n ? s._sendPacket({ cmd: "pubrec", messageId: o, reasonCode: n }, t) : s.incomingStore.put(e, function () { s._sendPacket({ cmd: "pubrec", messageId: o }, t); })); });
break;
case 1:
a.customHandleAcks(r, n, e, function (i, a) { return i instanceof Error || (a = i, i = null), i ? s.emit("error", i) : -1 === l.indexOf(a) ? s.emit("error", new Error("Wrong reason code for puback")) : (a || s.emit("message", r, n, e), void s.handleMessage(e, function (e) { if (e)
return t && t(e); s._sendPacket({ cmd: "puback", messageId: o, reasonCode: a }, t); })); });
break;
case 0:
this.emit("message", r, n, e), this.handleMessage(e, t);
break;
default: y("_handlePublish: unknown QoS. Doing nothing.");
} }, T.prototype.handleMessage = function (e, t) { t(); }, T.prototype._handleAck = function (e) { var t = e.messageId, r = e.cmd; var n = null; var i = this.outgoing[t] ? this.outgoing[t].cb : null, o = this; var s; if (i) {
switch ((y("_handleAck :: packet type", r), r)) {
case "pubcomp":
case "puback": {
var r_3 = e.reasonCode;
r_3 && r_3 > 0 && 16 !== r_3 && ((s = new Error("Publish error: " + _[r_3])).code = r_3, i(s, e)), delete this.outgoing[t], this.outgoingStore.del(e, i), this.messageIdProvider.deallocate(t), this._invokeStoreProcessingQueue();
break;
}
case "pubrec": {
n = { cmd: "pubrel", qos: 2, messageId: t };
var r_4 = e.reasonCode;
r_4 && r_4 > 0 && 16 !== r_4 ? ((s = new Error("Publish error: " + _[r_4])).code = r_4, i(s, e)) : this._sendPacket(n);
break;
}
case "suback":
delete this.outgoing[t], this.messageIdProvider.deallocate(t);
for (var r_5 = 0; r_5 < e.granted.length; r_5++)
if (0 != (128 & e.granted[r_5])) {
var e_12 = this.messageIdToTopic[t];
e_12 && e_12.forEach(function (e) { delete o._resubscribeTopics[e]; });
}
this._invokeStoreProcessingQueue(), i(null, e);
break;
case "unsuback":
delete this.outgoing[t], this.messageIdProvider.deallocate(t), this._invokeStoreProcessingQueue(), i(null);
break;
default: o.emit("error", new Error("unrecognized packet type"));
}
this.disconnecting && 0 === Object.keys(this.outgoing).length && this.emit("outgoingEmpty");
}
else
y("_handleAck :: Server sent an ack in error. Ignoring."); }, T.prototype._handlePubrel = function (e, t) { y("handling pubrel packet"), t = void 0 !== t ? t : C; var r = this, n = { cmd: "pubcomp", messageId: e.messageId }; r.incomingStore.get(e, function (e, i) { e ? r._sendPacket(n, t) : (r.emit("message", i.topic, i.payload, i), r.handleMessage(i, function (e) { if (e)
return t(e); r.incomingStore.del(i, C), r._sendPacket(n, t); })); }); }, T.prototype._handleDisconnect = function (e) { this.emit("disconnect", e); }, T.prototype._nextId = function () { return this.messageIdProvider.allocate(); }, T.prototype.getLastMessageId = function () { return this.messageIdProvider.getLastAllocated(); }, T.prototype._resubscribe = function () { y("_resubscribe"); var e = Object.keys(this._resubscribeTopics); if (!this._firstConnection && (this.options.clean || 5 === this.options.protocolVersion && !this.connackPacket.sessionPresent) && e.length > 0)
if (this.options.resubscribe)
if (5 === this.options.protocolVersion) {
y("_resubscribe: protocolVersion 5");
for (var t_5 = 0; t_5 < e.length; t_5++) {
var r_6 = {};
r_6[e[t_5]] = this._resubscribeTopics[e[t_5]], r_6.resubscribe = !0, this.subscribe(r_6, { properties: r_6[e[t_5]].properties });
}
}
else
this._resubscribeTopics.resubscribe = !0, this.subscribe(this._resubscribeTopics);
else
this._resubscribeTopics = {}; this._firstConnection = !1; }, T.prototype._onConnect = function (e) { if (this.disconnected)
return void this.emit("connect", e); var t = this; this.connackPacket = e, this.messageIdProvider.clear(), this._setupPingTimer(), this.connected = !0, function r() { var n = t.outgoingStore.createStream(); function i() { t._storeProcessing = !1, t._packetIdsDuringStoreProcessing = {}; } function o() { n.destroy(), n = null, t._flushStoreProcessingQueue(), i(); } t.once("close", o), n.on("error", function (e) { i(), t._flushStoreProcessingQueue(), t.removeListener("close", o), t.emit("error", e); }), n.on("end", function () { var n = !0; for (var e_13 in t._packetIdsDuringStoreProcessing)
if (!t._packetIdsDuringStoreProcessing[e_13]) {
n = !1;
break;
} n ? (i(), t.removeListener("close", o), t._invokeAllStoreProcessingQueue(), t.emit("connect", e)) : r(); }), function e() { if (!n)
return; t._storeProcessing = !0; var r = n.read(1); var i; r ? t._packetIdsDuringStoreProcessing[r.messageId] ? e() : t.disconnecting || t.reconnectTimer ? n.destroy && n.destroy() : (i = t.outgoing[r.messageId] ? t.outgoing[r.messageId].cb : null, t.outgoing[r.messageId] = { volatile: !1, cb: function (t, r) { i && i(t, r), e(); } }, t._packetIdsDuringStoreProcessing[r.messageId] = !0, t.messageIdProvider.register(r.messageId) ? t._sendPacket(r) : y("messageId: %d has already used.", r.messageId)) : n.once("readable", e); }(); }(); }, T.prototype._invokeStoreProcessingQueue = function () { if (this._storeProcessingQueue.length > 0) {
var e_14 = this._storeProcessingQueue[0];
if (e_14 && e_14.invoke())
return this._storeProcessingQueue.shift(), !0;
} return !1; }, T.prototype._invokeAllStoreProcessingQueue = function () { for (; this._invokeStoreProcessingQueue();)
; }, T.prototype._flushStoreProcessingQueue = function () { for (var _a = 0, _b = this._storeProcessingQueue; _a < _b.length; _a++) {
var e_15 = _b[_a];
e_15.cbStorePut && e_15.cbStorePut(new Error("Connection closed")), e_15.callback && e_15.callback(new Error("Connection closed"));
} this._storeProcessingQueue.splice(0); }, t.exports = T;
}).call(this); }).call(this, e("_process"), "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); }, { "./default-message-id-provider": 7, "./store": 8, "./topic-alias-recv": 9, "./topic-alias-send": 10, "./validations": 11, _process: 50, debug: 18, events: 22, inherits: 24, "mqtt-packet": 40, "readable-stream": 69, reinterval: 70, "rfdc/default": 71, xtend: 81 }], 2: [function (e, t, r) { (function (r) { (function () {
"use strict";
var n = e("readable-stream").Transform, i = e("duplexify");
var o, s, a, l = !1;
t.exports = function (e, t) { if (t.hostname = t.hostname || t.host, !t.hostname)
throw new Error("Could not determine host. Specify host manually."); var u = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt"; !function (e) { e.hostname || (e.hostname = "localhost"), e.path || (e.path = "/"), e.wsOptions || (e.wsOptions = {}); }(t); var c = function (e, t) { var r = "alis" === e.protocol ? "wss" : "ws"; var n = r + "://" + e.hostname + e.path; return e.port && 80 !== e.port && 443 !== e.port && (n = r + "://" + e.hostname + ":" + e.port + e.path), "function" == typeof e.transformWsUrl && (n = e.transformWsUrl(n, e, t)), n; }(t, e); return (o = t.my).connectSocket({ url: c, protocols: u }), s = function () { var e = new n; return e._write = function (e, t, r) { o.sendSocketMessage({ data: e.buffer, success: function () { r(); }, fail: function () { r(new Error); } }); }, e._flush = function (e) { o.closeSocket({ success: function () { e(); } }); }, e; }(), a = i.obj(), l || (l = !0, o.onSocketOpen(function () { a.setReadable(s), a.setWritable(s), a.emit("connect"); }), o.onSocketMessage(function (e) { if ("string" == typeof e.data) {
var t_6 = r.from(e.data, "base64");
s.push(t_6);
}
else {
var t_7 = new FileReader;
t_7.addEventListener("load", function () { var e = t_7.result; e = e instanceof ArrayBuffer ? r.from(e) : r.from(e, "utf8"), s.push(e); }), t_7.readAsArrayBuffer(e.data);
} }), o.onSocketClose(function () { a.end(), a.destroy(); }), o.onSocketError(function (e) { a.destroy(e); })), a; };
}).call(this); }).call(this, e("buffer").Buffer); }, { buffer: 17, duplexify: 20, "readable-stream": 69 }], 3: [function (e, t, r) {
"use strict";
var n = e("net"), i = e("debug")("mqttjs:tcp");
t.exports = function (e, t) { t.port = t.port || 1883, t.hostname = t.hostname || t.host || "localhost"; var r = t.port, o = t.hostname; return i("port %d and host %s", r, o), n.createConnection(r, o); };
}, { debug: 18, net: 16 }], 4: [function (e, t, r) {
"use strict";
var n = e("tls"), i = e("net"), o = e("debug")("mqttjs:tls");
t.exports = function (e, t) { t.port = t.port || 8883, t.host = t.hostname || t.host || "localhost", 0 === i.isIP(t.host) && (t.servername = t.host), t.rejectUnauthorized = !1 !== t.rejectUnauthorized, delete t.path, o("port %d host %s rejectUnauthorized %b", t.port, t.host, t.rejectUnauthorized); var r = n.connect(t); function s(n) { t.rejectUnauthorized && e.emit("error", n), r.end(); } return r.on("secureConnect", function () { t.rejectUnauthorized && !r.authorized ? r.emit("error", new Error("TLS not authorized")) : r.removeListener("error", s); }), r.on("error", s), r; };
}, { debug: 18, net: 16, tls: 16 }], 5: [function (e, t, r) { (function (r, n) { (function () {
"use strict";
var i = e("ws"), o = e("debug")("mqttjs:ws"), s = e("duplexify"), a = e("readable-stream").Transform, l = ["rejectUnauthorized", "ca", "cert", "key", "pfx", "passphrase"], u = void 0 !== r && "browser" === r.title || "function" == typeof __webpack_require__;
function c(e, t) { var r = e.protocol + "://" + e.hostname + ":" + e.port + e.path; return "function" == typeof e.transformWsUrl && (r = e.transformWsUrl(r, e, t)), r; }
function h(e) { var t = e; return e.hostname || (t.hostname = "localhost"), e.port || ("wss" === e.protocol ? t.port = 443 : t.port = 80), e.path || (t.path = "/"), e.wsOptions || (t.wsOptions = {}), u || "wss" !== e.protocol || l.forEach(function (r) { Object.prototype.hasOwnProperty.call(e, r) && !Object.prototype.hasOwnProperty.call(e.wsOptions, r) && (t.wsOptions[r] = e[r]); }), t; }
t.exports = u ? function (e, t) { var r; o("browserStreamBuilder"); var i = function (e) { var t = h(e); if (t.hostname || (t.hostname = t.host), !t.hostname) {
if ("undefined" == typeof document)
throw new Error("Could not determine host. Specify host manually.");
var e_16 = new URL(document.URL);
t.hostname = e_16.hostname, t.port || (t.port = e_16.port);
} return void 0 === t.objectMode && (t.objectMode = !(!0 === t.binary || void 0 === t.binary)), t; }(t).browserBufferSize || 524288, l = t.browserBufferTimeout || 1e3, u = !t.objectMode, f = function (e, t) { var r = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt", n = c(t, e), i = new WebSocket(n, [r]); return i.binaryType = "arraybuffer", i; }(e, t), p = function (e, t, r) { var n = new a({ objectModeMode: e.objectMode }); return n._write = t, n._flush = r, n; }(t, function e(t, r, o) { f.bufferedAmount > i && setTimeout(e, l, t, r, o), u && "string" == typeof t && (t = n.from(t, "utf8")); try {
f.send(t);
}
catch (e) {
return o(e);
} o(); }, function (e) { f.close(), e(); }); t.objectMode || (p._writev = v), p.on("close", function () { f.close(); }); var d = void 0 !== f.addEventListener; function g() { r.setReadable(p), r.setWritable(p), r.emit("connect"); } function y() { r.end(), r.destroy(); } function b(e) { r.destroy(e); } function m(e) { var t = e.data; t = t instanceof ArrayBuffer ? n.from(t) : n.from(t, "utf8"), p.push(t); } function v(e, t) { var r = new Array(e.length); for (var t_8 = 0; t_8 < e.length; t_8++)
"string" == typeof e[t_8].chunk ? r[t_8] = n.from(e[t_8], "utf8") : r[t_8] = e[t_8].chunk; this._write(n.concat(r), "binary", t); } return f.readyState === f.OPEN ? r = p : (r = r = s(void 0, void 0, t), t.objectMode || (r._writev = v), d ? f.addEventListener("open", g) : f.onopen = g), r.socket = f, d ? (f.addEventListener("close", y), f.addEventListener("error", b), f.addEventListener("message", m)) : (f.onclose = y, f.onerror = b, f.onmessage = m), r; } : function (e, t) { o("streamBuilder"); var r = h(t), n = c(r, e), s = function (e, t, r) { o("createWebSocket"), o("protocol: " + r.protocolId + " " + r.protocolVersion); var n = "MQIsdp" === r.protocolId && 3 === r.protocolVersion ? "mqttv3.1" : "mqtt"; return o("creating new Websocket for url: " + t + " and protocol: " + n), new i(t, [n], r.wsOptions); }(0, n, r), a = i.createWebSocketStream(s, r.wsOptions); return a.url = n, s.on("close", function () { a.destroy(); }), a; };
}).call(this); }).call(this, e("_process"), e("buffer").Buffer); }, { _process: 50, buffer: 17, debug: 18, duplexify: 20, "readable-stream": 69, ws: 80 }], 6: [function (e, t, r) { (function (r) { (function () {
"use strict";
var n = e("readable-stream").Transform, i = e("duplexify");
var o, s, a;
t.exports = function (e, t) { if (t.hostname = t.hostname || t.host, !t.hostname)
throw new Error("Could not determine host. Specify host manually."); var l = "MQIsdp" === t.protocolId && 3 === t.protocolVersion ? "mqttv3.1" : "mqtt"; !function (e) { e.hostname || (e.hostname = "localhost"), e.path || (e.path = "/"), e.wsOptions || (e.wsOptions = {}); }(t); var u = function (e, t) { var r = "wxs" === e.protocol ? "wss" : "ws"; var n = r + "://" + e.hostname + e.path; return e.port && 80 !== e.port && 443 !== e.port && (n = r + "://" + e.hostname + ":" + e.port + e.path), "function" == typeof e.transformWsUrl && (n = e.transformWsUrl(n, e, t)), n; }(t, e); o = wx.connectSocket({ url: u, protocols: [l] }), s = function () { var e = new n; return e._write = function (e, t, r) { o.send({ data: e.buffer, success: function () { r(); }, fail: function (e) { r(new Error(e)); } }); }, e._flush = function (e) { o.close({ success: function () { e(); } }); }, e; }(), (a = i.obj())._destroy = function (e, t) { o.close({ success: function () { t && t(e); } }); }; var c = a.destroy; return a.destroy = function () { a.destroy = c; var e = this; setTimeout(function () { o.close({ fail: function () { e._destroy(new Error); } }); }, 0); }.bind(a), o.onOpen(function () { a.setReadable(s), a.setWritable(s), a.emit("connect"); }), o.onMessage(function (e) { var t = e.data; t = t instanceof ArrayBuffer ? r.from(t) : r.from(t, "utf8"), s.push(t); }), o.onClose(function () { a.end(), a.destroy(); }), o.onError(function (e) { a.destroy(new Error(e.errMsg)); }), a; };
}).call(this); }).call(this, e("buffer").Buffer); }, { buffer: 17, duplexify: 20, "readable-stream": 69 }], 7: [function (e, t, r) {
"use strict";
function n() { if (!(this instanceof n))
return new n; this.nextId = Math.max(1, Math.floor(65535 * Math.random())); }
n.prototype.allocate = function () { var e = this.nextId++; return 65536 === this.nextId && (this.nextId = 1), e; }, n.prototype.getLastAllocated = function () { return 1 === this.nextId ? 65535 : this.nextId - 1; }, n.prototype.register = function (e) { return !0; }, n.prototype.deallocate = function (e) { }, n.prototype.clear = function () { }, t.exports = n;
}, {}], 8: [function (e, t, r) {
"use strict";
var n = e("xtend"), i = e("readable-stream").Readable, o = { objectMode: !0 }, s = { clean: !0 };
function a(e) { if (!(this instanceof a))
return new a(e); this.options = e || {}, this.options = n(s, e), this._inflights = new Map; }
a.prototype.put = function (e, t) { return this._inflights.set(e.messageId, e), t && t(), this; }, a.prototype.createStream = function () { var e = new i(o), t = []; var r = !1, n = 0; return this._inflights.forEach(function (e, r) { t.push(e); }), e._read = function () { !r && n < t.length ? this.push(t[n++]) : this.push(null); }, e.destroy = function () { if (r)
return; var e = this; r = !0, setTimeout(function () { e.emit("clos