{"version":3,"sources":["webpack:///./node_modules/mqtt/lib/connect/tcp.js","webpack:///./node_modules/mqtt/lib/default-message-id-provider.js","webpack:///./node_modules/mqtt-packet/parser.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/lib/_stream_writable.js","webpack:///./node_modules/mqtt-packet/mqtt.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/lib/_stream_readable.js","webpack:///./node_modules/mqtt/node_modules/duplexify/index.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/lib/_stream_duplex.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/errors-browser.js","webpack:///./node_modules/mqtt-packet/writeToStream.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/lib/_stream_transform.js","webpack:///./node_modules/mqtt/node_modules/duplexify/node_modules/readable-stream/lib/_stream_passthrough.js","webpack:///./node_modules/mqtt-packet/generate.js","webpack:///./node_modules/mqtt/lib/connect/wx.js","webpack:///./node_modules/mqtt/lib/topic-alias-send.js","webpack:///./node_modules/mqtt-packet/packet.js","webpack:///./node_modules/mqtt/lib/validations.js","webpack:///./node_modules/mqtt-packet/constants.js","webpack:///./node_modules/mqtt/lib/connect/ali.js","webpack:///./node_modules/mqtt/lib/client.js","webpack:///./node_modules/mqtt/lib/topic-alias-recv.js","webpack:///./node_modules/mqtt/lib/connect/index.js","webpack:///./node_modules/mqtt/lib/store.js","webpack:///./node_modules/mqtt-packet/numbers.js","webpack:///./node_modules/mqtt/lib/connect/ws.js","webpack:///./node_modules/mqtt/lib/connect/tls.js"],"names":["net","debug","streamBuilder","client","opts","port","hostname","host","createConnection","module","exports","DefaultMessageIdProvider","this","nextId","Math","max","floor","random","prototype","allocate","id","getLastAllocated","register","messageId","deallocate","clear","bl","EventEmitter","Packet","constants","Parser","super","parser","constructor","opt","settings","_states","_resetState","packet","error","_list","_stateCounter","buf","append","length","zero","readUInt8","cmd","types","CMD_SHIFT","retain","RETAIN_MASK","qos","QOS_SHIFT","QOS_MASK","dup","DUP_MASK","consume","result","_parseVarByteNum","value","bytes","_pos","_parseConnect","_parseConnack","_parsePublish","_parseConfirmation","_parseSubscribe","_parseSuback","_parseUnsubscribe","_parseUnsuback","_parseDisconnect","_parseAuth","_emitError","Error","topic","payload","password","username","flags","protocolId","_parseString","protocolVersion","bridgeMode","USERNAME_MASK","PASSWORD_MASK","will","WILL_FLAG_MASK","WILL_RETAIN_MASK","WILL_QOS_MASK","WILL_QOS_SHIFT","clean","CLEAN_SESSION_MASK","keepalive","_parseNum","properties","_parseProperties","Object","getOwnPropertyNames","clientId","willProperties","_parseBuffer","sessionPresent","SESSIONPRESENT_MASK","reasonCode","returnCode","_parseMessageId","slice","options","rh","rap","nl","subscription","subscriptions","_parseByte","SUBSCRIBE_OPTIONS_QOS_MASK","SUBSCRIBE_OPTIONS_NL_SHIFT","SUBSCRIBE_OPTIONS_NL_MASK","SUBSCRIBE_OPTIONS_RAP_SHIFT","SUBSCRIBE_OPTIONS_RAP_MASK","SUBSCRIBE_OPTIONS_RH_SHIFT","SUBSCRIBE_OPTIONS_RH_MASK","push","granted","unsubscriptions","maybeBuffer","end","toString","name","readUInt16BE","readUInt32BE","fullInfoFlag","maxBytes","current","mul","padding","VARBYTEINT_MASK","VARBYTEINT_FIN_MASK","type","_parse4ByteNum","_parseStringPair","start","propertiesCodes","Array","isArray","_parseByType","propertiesTypes","create","currentUserProperty","currentValue","emit","err","CorkedRequest","state","_this","next","entry","finish","onCorkedFinish","Duplex","Writable","WritableState","internalUtil","deprecate","Stream","Buffer","OurUint8Array","global","window","self","Uint8Array","_uint8ArrayToBuffer","chunk","from","_isUint8Array","obj","isBuffer","realHasInstance","destroyImpl","_require","getHighWaterMark","_require$codes","codes","ERR_INVALID_ARG_TYPE","ERR_METHOD_NOT_IMPLEMENTED","ERR_MULTIPLE_CALLBACK","ERR_STREAM_CANNOT_PIPE","ERR_STREAM_DESTROYED","ERR_STREAM_NULL_VALUES","ERR_STREAM_WRITE_AFTER_END","ERR_UNKNOWN_ENCODING","errorOrDestroy","nop","stream","isDuplex","objectMode","writableObjectMode","highWaterMark","finalCalled","needDrain","ending","ended","finished","destroyed","noDecode","decodeStrings","defaultEncoding","writing","corked","sync","bufferProcessing","onwrite","er","writecb","writelen","bufferedRequest","lastBufferedRequest","pendingcb","prefinished","errorEmitted","emitClose","autoDestroy","bufferedRequestCount","corkedRequestsFree","call","_writableState","writable","write","_write","writev","_writev","destroy","_destroy","final","_final","writeAfterEnd","cb","process","nextTick","validChunk","decodeChunk","encoding","writeOrBuffer","isBuf","newChunk","len","ret","last","callback","doWrite","onwriteError","finishMaybe","onwriteStateUpdate","needFinish","clearBuffer","afterWrite","onwriteDrain","l","buffer","holder","count","allBuffers","callFinal","prefinish","need","rState","_readableState","endEmitted","endWritable","once","corkReq","getBuffer","out","defineProperty","get","_","Symbol","hasInstance","Function","object","pipe","cork","uncork","setDefaultEncoding","toLowerCase","indexOf","enumerable","undefined","set","_undestroy","undestroy","generate","writeToStream","Readable","ReadableState","EElistenerCount","emitter","listeners","debugUtil","debuglog","StringDecoder","createReadableStreamAsyncIterator","BufferList","ERR_STREAM_PUSH_AFTER_EOF","ERR_STREAM_UNSHIFT_AFTER_END_EVENT","kProxyEvents","prependListener","event","fn","_events","unshift","on","readableObjectMode","pipes","pipesCount","flowing","reading","needReadable","emittedReadable","readableListening","resumeScheduled","paused","awaitDrain","readingMore","decoder","readable","read","_read","readableAddChunk","addToFront","skipChunkCheck","onEofChunk","chunkInvalid","getPrototypeOf","addChunk","maybeReadMore","emitReadable","isPaused","setEncoding","enc","p","head","content","data","MAX_HWM","computeNewHighWaterMark","n","howMuchToRead","emitReadable_","flow","maybeReadMore_","pipeOnDrain","src","updateReadableListening","listenerCount","resume","nReadingNextTick","resume_","fromList","shift","join","first","concat","endReadable","endReadableNT","wState","xs","x","i","parseInt","nOrig","doRead","dest","pipeOpts","doEnd","stdout","stderr","endFn","onend","unpipe","onunpipe","unpipeInfo","hasUnpiped","cleanup","ondrain","cleanedUp","removeListener","onclose","onfinish","onerror","ondata","pause","dests","index","splice","ev","res","addListener","removeAllListeners","apply","arguments","wrap","method","bind","asyncIterator","_fromList","iterable","eos","inherits","SIGNAL_FLUSH","onuncork","_corked","_autoDestroy","destroyer","message","_ended","ws","noop","toStreams2","rs","Duplexify","_writable","_readable","_readable2","_forwardDestroy","_forwardEnd","_ondrain","_drained","_forwarding","_unwrite","_unread","setWritable","setReadable","unend","onreadable","_forward","_finish","objectKeys","keys","key","v","allowHalfOpen","onEndNT","_inheritsLoose","subClass","superClass","__proto__","createErrorType","code","Base","getMessage","arg1","arg2","arg3","NodeError","_Base","oneOf","expected","thing","map","String","startsWith","str","search","pos","substr","endsWith","this_len","substring","includes","TypeError","actual","determiner","msg","replace","arg","empty","allocUnsafe","zeroBuf","numbers","numCache","cache","generateNumber","generateCache","genBufVariableByteInt","generate4ByteBuffer","writeNumber","writeNumberCached","toGenerate","connect","connack","publish","confirmation","subscribe","suback","unsubscribe","unsuback","emptyPacket","disconnect","auth","byteLength","propertiesData","getProperties","providedUsername","isStringOrBuffer","protocol","CONNECT_HEADER","writeVarByteInt","writeStringOrBuffer","VERSION131","VERSION132","VERSION4","VERSION5","VERSION3","writeString","version","rc","CONNACK_HEADER","SESSIONPRESENT_HEADER","PUBLISH_HEADER","getPropertiesByMaximumPacketSize","ACKS","subs","itopic","iqos","SUBSCRIBE_HEADER","sub","jtopic","jqos","jnl","jrap","jrh","joptions","SUBSCRIBE_OPTIONS_QOS","SUBSCRIBE_OPTIONS_NL","SUBSCRIBE_OPTIONS_RAP","SUBSCRIBE_OPTIONS_RH","SUBACK_HEADER","unsubs","UNSUBSCRIBE_HEADER","j","EMPTY","writeNumberGenerated","varByteIntCache","num","VARBYTEINT_MAX","string","strlen","writeStringPair","number","generatedNumber","write4ByteNumber","generated4ByteBuffer","toWrite","writeProperties","propertiesLength","getLengthProperty","reduce","currentLength","propName","propLength","propValueLength","propValue","valueIndex","propertiesLengthLength","mayEmptyProps","maximumPacketSize","currentMayEmptyProp","writeProperty","forEach","hasOwnProperty","bufOrString","field","Transform","ERR_TRANSFORM_ALREADY_TRANSFORMING","ERR_TRANSFORM_WITH_LENGTH_0","afterTransform","ts","_transformState","transforming","writechunk","needTransform","writeencoding","transform","_transform","flush","_flush","done","err2","PassThrough","Accumulator","_array","_i","lengths","list","copy","duplexify","socketTask","proxy","buildProxy","send","success","fail","errMsg","close","setDefaultOpts","path","wsOptions","buildUrl","url","transformWsUrl","bindEventHandler","onOpen","onMessage","ArrayBuffer","onClose","onError","buildStream","websocketSubProtocol","wx","connectSocket","protocols","destroyRef","setTimeout","LruMap","NumberAllocator","TopicAliasSend","aliasToTopic","topicToAlias","numberAllocator","put","alias","use","getTopicByAlias","getAliasByTopic","reset","getLruAlias","firstVacant","validateTopic","parts","split","validateTopics","topics","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","k","CMD_MASK","sessionExpiryInterval","willDelayInterval","receiveMaximum","topicAliasMaximum","requestResponseInformation","requestProblemInformation","userProperties","authenticationMethod","authenticationData","payloadFormatIndicator","messageExpiryInterval","contentType","responseTopic","correlationData","maximumQoS","retainAvailable","assignedClientIdentifier","reasonString","wildcardSubscriptionAvailable","subscriptionIdentifiersAvailable","sharedSubscriptionAvailable","serverKeepAlive","responseInformation","serverReference","topicAlias","subscriptionIdentifier","prop","genHeader","alloc","writeUInt8","puback","pubcomp","pubrel","pubrec","QOS","pingreq","pingresp","my","isInitialized","sendSocketMessage","closeSocket","onSocketOpen","onSocketMessage","reader","FileReader","addEventListener","readAsArrayBuffer","onSocketClose","onSocketError","Store","TopicAliasRecv","mqttPacket","reInterval","clone","validations","xtend","setImmediate","defaultConnectOptions","reschedulePings","reconnectPeriod","connectTimeout","resubscribe","socketErrors","errors","16","17","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","defaultId","applyTopicAlias","topicAliasSend","autoAssignTopicAlias","autoUseTopicAlias","removeTopicAliasAndRecoverTopicName","sendPacket","queue","flushVolatile","volatile","storeAndSend","cbStorePut","storePacket","outgoingStore","MqttClient","that","rejectUnauthorized","customHandleAcks","messageIdProvider","incomingStore","queueQoSZero","_resubscribeTopics","messageIdToTopic","pingTimer","connected","disconnecting","connackTimer","reconnectTimer","_storeProcessing","_packetIdsDuringStoreProcessing","_storeProcessingQueue","outgoing","_firstConnection","topicAliasRecv","deliver","_resubscribe","_sendPacket","clearTimeout","_setupReconnect","_setupStream","completeParse","packets","nextTickWork","work","_handlePacket","streamErrorHandler","_clearReconnect","parse","connectPacket","authPacket","setMaxListeners","_cleanUp","_handlePublish","_handleAck","_handlePubrel","_handleConnack","_handleAuth","_handlePingresp","_handleDisconnect","_checkDisconnecting","defaultOpts","publishProc","_nextId","invoke","args","pop","invalidTopic","currentOpts","subscribeProc","unsubscribeProc","force","closeStores","disconnected","e1","e2","_deferredReconnect","removeOutgoingMessage","del","reconnect","f","_reconnect","reconnecting","setInterval","clearInterval","forced","_shiftPingInterval","_storePacket","_setupPingTimer","pingResp","_checkPing","reschedule","_onConnect","handleAuth","validReasonCodes","gotTopic","handleMessage","response","pubackRC","_invokeStoreProcessingQueue","pubrecRC","grantedI","comp","pub","getLastMessageId","_resubscribeTopicsKeys","connackPacket","topicI","resubscribeTopic","startStreamProcess","outStore","createStream","clearStoreProcessing","remove","_flushStoreProcessingQueue","storeDeliver","status","allProcessed","_invokeAllStoreProcessingQueue","parseAuthOptions","matches","match","brokerUrl","parsed","Number","query","cert","isSecure","filter","wrapper","servers","_reconnectCount","defaultProtocol","title","__webpack_require__","mqtt","tcp","ssl","tls","mqtts","wxs","ali","alis","wss","streamsOpts","defaultStoreOptions","_inflights","Map","values","delete","SubOk","subarray","generateBuffer","maxLength","digit","writeUInt32BE","WS","WSS_OPTIONS","IS_BROWSER","setDefaultBrowserOpts","URL","document","binary","createWebSocket","socket","createBrowserWebSocket","WebSocket","binaryType","webSocketStream","createWebSocketStream","browserStreamBuilder","bufferSize","browserBufferSize","bufferTimeout","browserBufferTimeout","coerceToBuffer","socketWriteBrowser","socketEndBrowser","eventListenerSupport","socketWrite","socketEnd","objectModeMode","onopen","onmessage","chunks","buffers","bufferedAmount","readyState","OPEN","buildBuilder","mqttClient","isIP","servername","connection","handleTLSerrors","authorized"],"mappings":"0HACA,MAAMA,EAAM,EAAQ,GACdC,EAAQ,EAAQ,OAAR,CAAiB,cAM/B,SAASC,EAAeC,EAAQC,GAC9BA,EAAKC,KAAOD,EAAKC,MAAQ,KACzBD,EAAKE,SAAWF,EAAKE,UAAYF,EAAKG,MAAQ,YAE9C,MAAMF,EAAOD,EAAKC,KACZE,EAAOH,EAAKE,SAGlB,OADAL,EAAM,sBAAuBI,EAAME,GAC5BP,EAAIQ,iBAAiBH,EAAME,GAGpCE,EAAOC,QAAUR,G,oCCbjB,SAASS,IACP,KAAMC,gBAAgBD,GACpB,OAAO,IAAIA,EAObC,KAAKC,OAASC,KAAKC,IAAI,EAAGD,KAAKE,MAAsB,MAAhBF,KAAKG,WAS5CN,EAAyBO,UAAUC,SAAW,WAE5C,MAAMC,EAAKR,KAAKC,SAKhB,OAHoB,QAAhBD,KAAKC,SACPD,KAAKC,OAAS,GAETO,GAQTT,EAAyBO,UAAUG,iBAAmB,WACpD,OAAwB,IAAhBT,KAAKC,OAAgB,MAASD,KAAKC,OAAS,GAStDF,EAAyBO,UAAUI,SAAW,SAAUC,GACtD,OAAO,GAQTZ,EAAyBO,UAAUM,WAAa,SAAUD,KAO1DZ,EAAyBO,UAAUO,MAAQ,aAG3ChB,EAAOC,QAAUC,G,uBCpEjB,MAAMe,EAAK,EAAQ,QACbC,EAAe,EAAQ,QACvBC,EAAS,EAAQ,QACjBC,EAAY,EAAQ,QACpB5B,EAAQ,EAAQ,OAAR,CAAiB,sBAE/B,MAAM6B,UAAeH,EACnB,cACEI,QACAnB,KAAKoB,OAASpB,KAAKqB,YAAYD,OAGjC,cAAeE,G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O1hB,QAAUA,EACjB0hB,EAAOxhB,QAAUA,EACjBwhB,EAAOmB,UAAYA,GA8Ed/uB,EAIPxL,EAAOC,QADL64B,EACeY,EAEAj6B,I,wDC9PnB,MAAMi4B,EAAM,EAAQ,GACdn4B,EAAM,EAAQ,GACdC,EAAQ,EAAQ,OAAR,CAAiB,cAE/B,SAASq7B,EAAcC,EAAYn7B,GACjCA,EAAKC,KAAOD,EAAKC,MAAQ,KACzBD,EAAKG,KAAOH,EAAKE,UAAYF,EAAKG,MAAQ,YAEd,IAAxBP,EAAIw7B,KAAKp7B,EAAKG,QAChBH,EAAKq7B,WAAar7B,EAAKG,MAGzBH,EAAKswB,oBAAiD,IAA5BtwB,EAAKswB,0BAExBtwB,EAAK0lB,KAEZ7lB,EAAM,wCAAyCG,EAAKC,KAAMD,EAAKG,KAAMH,EAAKswB,oBAE1E,MAAMgL,EAAavD,EAAI1Z,QAAQre,GAU/B,SAASu7B,EAAiBpyB,GAEpBnJ,EAAKswB,oBACP6K,EAAWjyB,KAAK,QAASC,GAQ3BmyB,EAAW5zB,MAIb,OAvBA4zB,EAAWnoB,GAAG,iBAAiB,WACzBnT,EAAKswB,qBAAuBgL,EAAWE,WACzCF,EAAWpyB,KAAK,QAAS,IAAI5E,MAAM,uBAEnCg3B,EAAWxjB,eAAe,QAASyjB,MAkBvCD,EAAWnoB,GAAG,QAASooB,GAChBD,EAGTj7B,EAAOC,QAAU46B","file":"js/chunk-vendors~d4fd7797.237750eb.js","sourcesContent":["'use strict'\nconst net = require('net')\nconst debug = require('debug')('mqttjs:tcp')\n\n/*\n variables port and host can be removed since\n you have all required information in opts object\n*/\nfunction streamBuilder (client, opts) {\n opts.port = opts.port || 1883\n opts.hostname = opts.hostname || opts.host || 'localhost'\n\n const port = opts.port\n const host = opts.hostname\n\n debug('port %d and host %s', port, host)\n return net.createConnection(port, host)\n}\n\nmodule.exports = streamBuilder\n","'use strict'\n\n/**\n * DefaultMessageAllocator constructor\n * @constructor\n */\nfunction DefaultMessageIdProvider () {\n if (!(this instanceof DefaultMessageIdProvider)) {\n return new DefaultMessageIdProvider()\n }\n\n /**\n * MessageIDs starting with 1\n * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810\n */\n this.nextId = Math.max(1, Math.floor(Math.random() * 65535))\n}\n\n/**\n * allocate\n *\n * Get the next messageId.\n * @return unsigned int\n */\nDefaultMessageIdProvider.prototype.allocate = function () {\n // id becomes current state of this.nextId and increments afterwards\n const id = this.nextId++\n // Ensure 16 bit unsigned int (max 65535, nextId got one higher)\n if (this.nextId === 65536) {\n this.nextId = 1\n }\n return id\n}\n\n/**\n * getLastAllocated\n * Get the last allocated messageId.\n * @return unsigned int\n */\nDefaultMessageIdProvider.prototype.getLastAllocated = function () {\n return (this.nextId === 1) ? 65535 : (this.nextId - 1)\n}\n\n/**\n * register\n * Register messageId. If success return true, otherwise return false.\n * @param { unsigned int } - messageId to register,\n * @return boolean\n */\nDefaultMessageIdProvider.prototype.register = function (messageId) {\n return true\n}\n\n/**\n * deallocate\n * Deallocate messageId.\n * @param { unsigned int } - messageId to deallocate,\n */\nDefaultMessageIdProvider.prototype.deallocate = function (messageId) {\n}\n\n/**\n * clear\n * Deallocate all messageIds.\n */\nDefaultMessageIdProvider.prototype.clear = function () {\n}\n\nmodule.exports = DefaultMessageIdProvider\n","const bl = require('bl')\nconst EventEmitter = require('events')\nconst Packet = require('./packet')\nconst constants = require('./constants')\nconst debug = require('debug')('mqtt-packet:parser')\n\nclass Parser extends EventEmitter {\n constructor () {\n super()\n this.parser = this.constructor.parser\n }\n\n static parser (opt) {\n if (!(this instanceof Parser)) return (new Parser()).parser(opt)\n\n this.settings = opt || {}\n\n this._states = [\n '_parseHeader',\n '_parseLength',\n '_parsePayload',\n '_newPacket'\n ]\n\n this._resetState()\n return this\n }\n\n _resetState () {\n debug('_resetState: resetting packet, error, _list, and _stateCounter')\n this.packet = new Packet()\n this.error = null\n this._list = bl()\n this._stateCounter = 0\n }\n\n parse (buf) {\n if (this.error) this._resetState()\n\n this._list.append(buf)\n debug('parse: current state: %s', this._states[this._stateCounter])\n while ((this.packet.length !== -1 || this._list.length > 0) &&\n this[this._states[this._stateCounter]]() &&\n !this.error) {\n this._stateCounter++\n debug('parse: state complete. _stateCounter is now: %d', this._stateCounter)\n debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length)\n if (this._stateCounter >= this._states.length) this._stateCounter = 0\n }\n debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length)\n return this._list.length\n }\n\n _parseHeader () {\n // There is at least one byte in the buffer\n const zero = this._list.readUInt8(0)\n this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]\n this.packet.retain = (zero & constants.RETAIN_MASK) !== 0\n this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK\n this.packet.dup = (zero & constants.DUP_MASK) !== 0\n debug('_parseHeader: packet: %o', this.packet)\n\n this._list.consume(1)\n\n return true\n }\n\n _parseLength () {\n // There is at least one byte in the list\n const result = this._parseVarByteNum(true)\n\n if (result) {\n this.packet.length = result.value\n this._list.consume(result.bytes)\n }\n debug('_parseLength %d', result.value)\n return !!result\n }\n\n _parsePayload () {\n debug('_parsePayload: payload %O', this._list)\n let result = false\n\n // Do we have a payload? Do we have enough data to complete the payload?\n // PINGs have no payload\n if (this.packet.length === 0 || this._list.length >= this.packet.length) {\n this._pos = 0\n\n switch (this.packet.cmd) {\n case 'connect':\n this._parseConnect()\n break\n case 'connack':\n this._parseConnack()\n break\n case 'publish':\n this._parsePublish()\n break\n case 'puback':\n case 'pubrec':\n case 'pubrel':\n case 'pubcomp':\n this._parseConfirmation()\n break\n case 'subscribe':\n this._parseSubscribe()\n break\n case 'suback':\n this._parseSuback()\n break\n case 'unsubscribe':\n this._parseUnsubscribe()\n break\n case 'unsuback':\n this._parseUnsuback()\n break\n case 'pingreq':\n case 'pingresp':\n // These are empty, nothing to do\n break\n case 'disconnect':\n this._parseDisconnect()\n break\n case 'auth':\n this._parseAuth()\n break\n default:\n this._emitError(new Error('Not supported'))\n }\n\n result = true\n }\n debug('_parsePayload complete result: %s', result)\n return result\n }\n\n _parseConnect () {\n debug('_parseConnect')\n let topic // Will topic\n let payload // Will payload\n let password // Password\n let username // Username\n const flags = {}\n const packet = this.packet\n\n // Parse protocolId\n const protocolId = this._parseString()\n\n if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))\n if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {\n return this._emitError(new Error('Invalid protocolId'))\n }\n\n packet.protocolId = protocolId\n\n // Parse constants version number\n if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))\n\n packet.protocolVersion = this._list.readUInt8(this._pos)\n\n if (packet.protocolVersion >= 128) {\n packet.bridgeMode = true\n packet.protocolVersion = packet.protocolVersion - 128\n }\n\n if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {\n return this._emitError(new Error('Invalid protocol version'))\n }\n\n this._pos++\n\n if (this._pos >= this._list.length) {\n return this._emitError(new Error('Packet too short'))\n }\n\n // Parse connect flags\n flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)\n flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)\n flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)\n\n if (flags.will) {\n packet.will = {}\n packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0\n packet.will.qos = (this._list.readUInt8(this._pos) &\n constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT\n }\n\n packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0\n this._pos++\n\n // Parse keepalive\n packet.keepalive = this._parseNum()\n if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))\n\n // parse properties\n if (packet.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n // Parse clientId\n const clientId = this._parseString()\n if (clientId === null) return this._emitError(new Error('Packet too short'))\n packet.clientId = clientId\n debug('_parseConnect: packet.clientId: %s', packet.clientId)\n\n if (flags.will) {\n if (packet.protocolVersion === 5) {\n const willProperties = this._parseProperties()\n if (Object.getOwnPropertyNames(willProperties).length) {\n packet.will.properties = willProperties\n }\n }\n // Parse will topic\n topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse will topic'))\n packet.will.topic = topic\n debug('_parseConnect: packet.will.topic: %s', packet.will.topic)\n\n // Parse will payload\n payload = this._parseBuffer()\n if (payload === null) return this._emitError(new Error('Cannot parse will payload'))\n packet.will.payload = payload\n debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload)\n }\n\n // Parse username\n if (flags.username) {\n username = this._parseString()\n if (username === null) return this._emitError(new Error('Cannot parse username'))\n packet.username = username\n debug('_parseConnect: packet.username: %s', packet.username)\n }\n\n // Parse password\n if (flags.password) {\n password = this._parseBuffer()\n if (password === null) return this._emitError(new Error('Cannot parse password'))\n packet.password = password\n }\n // need for right parse auth packet and self set up\n this.settings = packet\n debug('_parseConnect: complete')\n return packet\n }\n\n _parseConnack () {\n debug('_parseConnack')\n const packet = this.packet\n\n if (this._list.length < 1) return null\n packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)\n\n if (this.settings.protocolVersion === 5) {\n if (this._list.length >= 2) {\n packet.reasonCode = this._list.readUInt8(this._pos++)\n } else {\n packet.reasonCode = 0\n }\n } else {\n if (this._list.length < 2) return null\n packet.returnCode = this._list.readUInt8(this._pos++)\n }\n\n if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))\n // mqtt 5 properties\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n debug('_parseConnack: complete')\n }\n\n _parsePublish () {\n debug('_parsePublish')\n const packet = this.packet\n packet.topic = this._parseString()\n\n if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))\n\n // Parse messageId\n if (packet.qos > 0) if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n packet.payload = this._list.slice(this._pos, packet.length)\n debug('_parsePublish: payload from buffer list: %o', packet.payload)\n }\n\n _parseSubscribe () {\n debug('_parseSubscribe')\n const packet = this.packet\n let topic\n let options\n let qos\n let rh\n let rap\n let nl\n let subscription\n\n if (packet.qos !== 1) {\n return this._emitError(new Error('Wrong subscribe header'))\n }\n\n packet.subscriptions = []\n\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n while (this._pos < packet.length) {\n // Parse topic\n topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse topic'))\n if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))\n\n options = this._parseByte()\n qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK\n nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0\n rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0\n rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK\n\n subscription = { topic, qos }\n\n // mqtt 5 options\n if (this.settings.protocolVersion === 5) {\n subscription.nl = nl\n subscription.rap = rap\n subscription.rh = rh\n } else if (this.settings.bridgeMode) {\n subscription.rh = 0\n subscription.rap = true\n subscription.nl = true\n }\n\n // Push pair to subscriptions\n debug('_parseSubscribe: push subscription `%s` to subscription', subscription)\n packet.subscriptions.push(subscription)\n }\n }\n\n _parseSuback () {\n debug('_parseSuback')\n const packet = this.packet\n this.packet.granted = []\n\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n // Parse granted QoSes\n while (this._pos < this.packet.length) {\n this.packet.granted.push(this._list.readUInt8(this._pos++))\n }\n }\n\n _parseUnsubscribe () {\n debug('_parseUnsubscribe')\n const packet = this.packet\n\n packet.unsubscriptions = []\n\n // Parse messageId\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n while (this._pos < packet.length) {\n // Parse topic\n const topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse topic'))\n\n // Push topic to unsubscriptions\n debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic)\n packet.unsubscriptions.push(topic)\n }\n }\n\n _parseUnsuback () {\n debug('_parseUnsuback')\n const packet = this.packet\n if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n // Parse granted QoSes\n packet.granted = []\n while (this._pos < this.packet.length) {\n this.packet.granted.push(this._list.readUInt8(this._pos++))\n }\n }\n }\n\n // parse packets like puback, pubrec, pubrel, pubcomp\n _parseConfirmation () {\n debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd)\n const packet = this.packet\n\n this._parseMessageId()\n\n if (this.settings.protocolVersion === 5) {\n if (packet.length > 2) {\n // response code\n packet.reasonCode = this._parseByte()\n debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode)\n } else {\n packet.reasonCode = 0\n }\n\n if (packet.length > 3) {\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n }\n\n return true\n }\n\n // parse disconnect packet\n _parseDisconnect () {\n const packet = this.packet\n debug('_parseDisconnect')\n\n if (this.settings.protocolVersion === 5) {\n // response code\n if (this._list.length > 0) {\n packet.reasonCode = this._parseByte()\n } else {\n packet.reasonCode = 0\n }\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n debug('_parseDisconnect result: true')\n return true\n }\n\n // parse auth packet\n _parseAuth () {\n debug('_parseAuth')\n const packet = this.packet\n\n if (this.settings.protocolVersion !== 5) {\n return this._emitError(new Error('Not supported auth packet for this version MQTT'))\n }\n\n // response code\n packet.reasonCode = this._parseByte()\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n\n debug('_parseAuth: result: true')\n return true\n }\n\n _parseMessageId () {\n const packet = this.packet\n\n packet.messageId = this._parseNum()\n\n if (packet.messageId === null) {\n this._emitError(new Error('Cannot parse messageId'))\n return false\n }\n\n debug('_parseMessageId: packet.messageId %d', packet.messageId)\n return true\n }\n\n _parseString (maybeBuffer) {\n const length = this._parseNum()\n const end = length + this._pos\n\n if (length === -1 || end > this._list.length || end > this.packet.length) return null\n\n const result = this._list.toString('utf8', this._pos, end)\n this._pos += length\n debug('_parseString: result: %s', result)\n return result\n }\n\n _parseStringPair () {\n debug('_parseStringPair')\n return {\n name: this._parseString(),\n value: this._parseString()\n }\n }\n\n _parseBuffer () {\n const length = this._parseNum()\n const end = length + this._pos\n\n if (length === -1 || end > this._list.length || end > this.packet.length) return null\n\n const result = this._list.slice(this._pos, end)\n\n this._pos += length\n debug('_parseBuffer: result: %o', result)\n return result\n }\n\n _parseNum () {\n if (this._list.length - this._pos < 2) return -1\n\n const result = this._list.readUInt16BE(this._pos)\n this._pos += 2\n debug('_parseNum: result: %s', result)\n return result\n }\n\n _parse4ByteNum () {\n if (this._list.length - this._pos < 4) return -1\n\n const result = this._list.readUInt32BE(this._pos)\n this._pos += 4\n debug('_parse4ByteNum: result: %s', result)\n return result\n }\n\n _parseVarByteNum (fullInfoFlag) {\n debug('_parseVarByteNum')\n const maxBytes = 4\n let bytes = 0\n let mul = 1\n let value = 0\n let result = false\n let current\n const padding = this._pos ? this._pos : 0\n\n while (bytes < maxBytes && (padding + bytes) < this._list.length) {\n current = this._list.readUInt8(padding + bytes++)\n value += mul * (current & constants.VARBYTEINT_MASK)\n mul *= 0x80\n\n if ((current & constants.VARBYTEINT_FIN_MASK) === 0) {\n result = true\n break\n }\n if (this._list.length <= bytes) {\n break\n }\n }\n\n if (!result && bytes === maxBytes && this._list.length >= bytes) {\n this._emitError(new Error('Invalid variable byte integer'))\n }\n\n if (padding) {\n this._pos += bytes\n }\n\n result = result\n ? fullInfoFlag ? {\n bytes,\n value\n } : value\n : false\n\n debug('_parseVarByteNum: result: %o', result)\n return result\n }\n\n _parseByte () {\n let result\n if (this._pos < this._list.length) {\n result = this._list.readUInt8(this._pos)\n this._pos++\n }\n debug('_parseByte: result: %o', result)\n return result\n }\n\n _parseByType (type) {\n debug('_parseByType: type: %s', type)\n switch (type) {\n case 'byte': {\n return this._parseByte() !== 0\n }\n case 'int8': {\n return this._parseByte()\n }\n case 'int16': {\n return this._parseNum()\n }\n case 'int32': {\n return this._parse4ByteNum()\n }\n case 'var': {\n return this._parseVarByteNum()\n }\n case 'string': {\n return this._parseString()\n }\n case 'pair': {\n return this._parseStringPair()\n }\n case 'binary': {\n return this._parseBuffer()\n }\n }\n }\n\n _parseProperties () {\n debug('_parseProperties')\n const length = this._parseVarByteNum()\n const start = this._pos\n const end = start + length\n const result = {}\n while (this._pos < end) {\n const type = this._parseByte()\n if (!type) {\n this._emitError(new Error('Cannot parse property code type'))\n return false\n }\n const name = constants.propertiesCodes[type]\n if (!name) {\n this._emitError(new Error('Unknown property'))\n return false\n }\n // user properties process\n if (name === 'userProperties') {\n if (!result[name]) {\n result[name] = Object.create(null)\n }\n const currentUserProperty = this._parseByType(constants.propertiesTypes[name])\n if (result[name][currentUserProperty.name]) {\n if (Array.isArray(result[name][currentUserProperty.name])) {\n result[name][currentUserProperty.name].push(currentUserProperty.value)\n } else {\n const currentValue = result[name][currentUserProperty.name]\n result[name][currentUserProperty.name] = [currentValue]\n result[name][currentUserProperty.name].push(currentUserProperty.value)\n }\n } else {\n result[name][currentUserProperty.name] = currentUserProperty.value\n }\n continue\n }\n if (result[name]) {\n if (Array.isArray(result[name])) {\n result[name].push(this._parseByType(constants.propertiesTypes[name]))\n } else {\n result[name] = [result[name]]\n result[name].push(this._parseByType(constants.propertiesTypes[name]))\n }\n } else {\n result[name] = this._parseByType(constants.propertiesTypes[name])\n }\n }\n return result\n }\n\n _newPacket () {\n debug('_newPacket')\n if (this.packet) {\n this._list.consume(this.packet.length)\n debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length)\n this.emit('packet', this.packet)\n }\n debug('_newPacket: new packet')\n this.packet = new Packet()\n\n this._pos = 0\n\n return true\n }\n\n _emitError (err) {\n debug('_emitError')\n this.error = err\n this.emit('error', err)\n }\n}\n\nmodule.exports = Parser\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\nvar Buffer = require('buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\nvar destroyImpl = require('./internal/streams/destroy');\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nrequire('inherits')(Writable, Stream);\nfunction nop() {}\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = options.emitClose !== false;\n\n // Should .destroy() be called after 'finish' (and potentially 'end')\n this.autoDestroy = !!options.autoDestroy;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex);\n\n // legacy.\n this.writable = true;\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END();\n // TODO: defer error events consistently everywhere, not just the cb\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n return true;\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n return ret;\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n if (entry === null) state.lastBufferedRequest = null;\n }\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\nWritable.prototype._writev = null;\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n errorOrDestroy(stream, err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n return need;\n}\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","exports.parser = require('./parser').parser\nexports.generate = require('./generate')\nexports.writeToStream = require('./writeToStream')\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nmodule.exports = Readable;\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\nvar Buffer = require('buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\nvar debugUtil = require('util');\nvar debug;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/buffer_list');\nvar destroyImpl = require('./internal/streams/destroy');\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;\n\n// Lazy loaded to improve the startup performance.\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\nrequire('inherits')(Readable, Stream);\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true;\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = options.emitClose !== false;\n\n // Should .destroy() be called after 'end' (and potentially 'finish')\n this.autoDestroy = !!options.autoDestroy;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options);\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex);\n\n // legacy\n this.readable = true;\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n Stream.call(this);\n}\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n }\n\n // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n return er;\n}\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder;\n // If setEncoding(null), decoder.encoding equals utf8\n this._readableState.encoding = this._readableState.decoder.encoding;\n\n // Iterate over current buffer to convert already stored Buffers:\n var p = this._readableState.buffer.head;\n var content = '';\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n this._readableState.buffer.clear();\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n};\n\n// Don't raise the hwm > 1GB\nvar MAX_HWM = 0x40000000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n }\n\n // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n return dest;\n};\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0;\n\n // Try start flowing on next tick if stream isn't explicitly paused\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n return res;\n};\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n return res;\n};\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true;\n\n // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n state.paused = false;\n return this;\n};\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n if (!state.reading) {\n stream.read(0);\n }\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n this._readableState.paused = true;\n return this;\n};\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null);\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n return this;\n};\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n return createReadableStreamAsyncIterator(this);\n };\n}\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n});\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length);\n\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n return from(Readable, iterable, opts);\n };\n}\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","var stream = require('readable-stream')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar shift = require('stream-shift')\n\nvar SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)\n ? Buffer.from([0])\n : new Buffer([0])\n\nvar onuncork = function(self, fn) {\n if (self._corked) self.once('uncork', fn)\n else fn()\n}\n\nvar autoDestroy = function (self, err) {\n if (self._autoDestroy) self.destroy(err)\n}\n\nvar destroyer = function(self, end) {\n return function(err) {\n if (err) autoDestroy(self, err.message === 'premature close' ? null : err)\n else if (end && !self._ended) self.end()\n }\n}\n\nvar end = function(ws, fn) {\n if (!ws) return fn()\n if (ws._writableState && ws._writableState.finished) return fn()\n if (ws._writableState) return ws.end(fn)\n ws.end()\n fn()\n}\n\nvar noop = function() {}\n\nvar toStreams2 = function(rs) {\n return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)\n}\n\nvar Duplexify = function(writable, readable, opts) {\n if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)\n stream.Duplex.call(this, opts)\n\n this._writable = null\n this._readable = null\n this._readable2 = null\n\n this._autoDestroy = !opts || opts.autoDestroy !== false\n this._forwardDestroy = !opts || opts.destroy !== false\n this._forwardEnd = !opts || opts.end !== false\n this._corked = 1 // start corked\n this._ondrain = null\n this._drained = false\n this._forwarding = false\n this._unwrite = null\n this._unread = null\n this._ended = false\n\n this.destroyed = false\n\n if (writable) this.setWritable(writable)\n if (readable) this.setReadable(readable)\n}\n\ninherits(Duplexify, stream.Duplex)\n\nDuplexify.obj = function(writable, readable, opts) {\n if (!opts) opts = {}\n opts.objectMode = true\n opts.highWaterMark = 16\n return new Duplexify(writable, readable, opts)\n}\n\nDuplexify.prototype.cork = function() {\n if (++this._corked === 1) this.emit('cork')\n}\n\nDuplexify.prototype.uncork = function() {\n if (this._corked && --this._corked === 0) this.emit('uncork')\n}\n\nDuplexify.prototype.setWritable = function(writable) {\n if (this._unwrite) this._unwrite()\n\n if (this.destroyed) {\n if (writable && writable.destroy) writable.destroy()\n return\n }\n\n if (writable === null || writable === false) {\n this.end()\n return\n }\n\n var self = this\n var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))\n\n var ondrain = function() {\n var ondrain = self._ondrain\n self._ondrain = null\n if (ondrain) ondrain()\n }\n\n var clear = function() {\n self._writable.removeListener('drain', ondrain)\n unend()\n }\n\n if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks\n\n this._writable = writable\n this._writable.on('drain', ondrain)\n this._unwrite = clear\n\n this.uncork() // always uncork setWritable\n}\n\nDuplexify.prototype.setReadable = function(readable) {\n if (this._unread) this._unread()\n\n if (this.destroyed) {\n if (readable && readable.destroy) readable.destroy()\n return\n }\n\n if (readable === null || readable === false) {\n this.push(null)\n this.resume()\n return\n }\n\n var self = this\n var unend = eos(readable, {writable:false, readable:true}, destroyer(this))\n\n var onreadable = function() {\n self._forward()\n }\n\n var onend = function() {\n self.push(null)\n }\n\n var clear = function() {\n self._readable2.removeListener('readable', onreadable)\n self._readable2.removeListener('end', onend)\n unend()\n }\n\n this._drained = true\n this._readable = readable\n this._readable2 = readable._readableState ? readable : toStreams2(readable)\n this._readable2.on('readable', onreadable)\n this._readable2.on('end', onend)\n this._unread = clear\n\n this._forward()\n}\n\nDuplexify.prototype._read = function() {\n this._drained = true\n this._forward()\n}\n\nDuplexify.prototype._forward = function() {\n if (this._forwarding || !this._readable2 || !this._drained) return\n this._forwarding = true\n\n var data\n\n while (this._drained && (data = shift(this._readable2)) !== null) {\n if (this.destroyed) continue\n this._drained = this.push(data)\n }\n\n this._forwarding = false\n}\n\nDuplexify.prototype.destroy = function(err, cb) {\n if (!cb) cb = noop\n if (this.destroyed) return cb(null)\n this.destroyed = true\n\n var self = this\n process.nextTick(function() {\n self._destroy(err)\n cb(null)\n })\n}\n\nDuplexify.prototype._destroy = function(err) {\n if (err) {\n var ondrain = this._ondrain\n this._ondrain = null\n if (ondrain) ondrain(err)\n else this.emit('error', err)\n }\n\n if (this._forwardDestroy) {\n if (this._readable && this._readable.destroy) this._readable.destroy()\n if (this._writable && this._writable.destroy) this._writable.destroy()\n }\n\n this.emit('close')\n}\n\nDuplexify.prototype._write = function(data, enc, cb) {\n if (this.destroyed) return\n if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))\n if (data === SIGNAL_FLUSH) return this._finish(cb)\n if (!this._writable) return cb()\n\n if (this._writable.write(data) === false) this._ondrain = cb\n else if (!this.destroyed) cb()\n}\n\nDuplexify.prototype._finish = function(cb) {\n var self = this\n this.emit('preend')\n onuncork(this, function() {\n end(self._forwardEnd && self._writable, function() {\n // haxx to not emit prefinish twice\n if (self._writableState.prefinished === false) self._writableState.prefinished = true\n self.emit('prefinish')\n onuncork(self, cb)\n })\n })\n}\n\nDuplexify.prototype.end = function(data, enc, cb) {\n if (typeof data === 'function') return this.end(null, null, data)\n if (typeof enc === 'function') return this.end(data, null, enc)\n this._ended = true\n if (data) this.write(data)\n if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH)\n return stream.Writable.prototype.end.call(this, cb)\n}\n\nmodule.exports = Duplexify\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) keys.push(key);\n return keys;\n};\n/**/\n\nmodule.exports = Duplex;\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\nrequire('inherits')(Duplex, Readable);\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n process.nextTick(onEndNT, this);\n}\nfunction onEndNT(self) {\n self.end();\n}\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","'use strict';\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inheritsLoose(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;\n }\n\n return NodeError;\n }(Base);\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"';\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n }\n\n msg += \". Received type \".concat(typeof actual);\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented';\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\nmodule.exports.codes = codes;\n","const protocol = require('./constants')\nconst empty = Buffer.allocUnsafe(0)\nconst zeroBuf = Buffer.from([0])\nconst numbers = require('./numbers')\nconst nextTick = require('process-nextick-args').nextTick\nconst debug = require('debug')('mqtt-packet:writeToStream')\n\nconst numCache = numbers.cache\nconst generateNumber = numbers.generateNumber\nconst generateCache = numbers.generateCache\nconst genBufVariableByteInt = numbers.genBufVariableByteInt\nconst generate4ByteBuffer = numbers.generate4ByteBuffer\nlet writeNumber = writeNumberCached\nlet toGenerate = true\n\nfunction generate (packet, stream, opts) {\n debug('generate called')\n if (stream.cork) {\n stream.cork()\n nextTick(uncork, stream)\n }\n\n if (toGenerate) {\n toGenerate = false\n generateCache()\n }\n debug('generate: packet.cmd: %s', packet.cmd)\n switch (packet.cmd) {\n case 'connect':\n return connect(packet, stream, opts)\n case 'connack':\n return connack(packet, stream, opts)\n case 'publish':\n return publish(packet, stream, opts)\n case 'puback':\n case 'pubrec':\n case 'pubrel':\n case 'pubcomp':\n return confirmation(packet, stream, opts)\n case 'subscribe':\n return subscribe(packet, stream, opts)\n case 'suback':\n return suback(packet, stream, opts)\n case 'unsubscribe':\n return unsubscribe(packet, stream, opts)\n case 'unsuback':\n return unsuback(packet, stream, opts)\n case 'pingreq':\n case 'pingresp':\n return emptyPacket(packet, stream, opts)\n case 'disconnect':\n return disconnect(packet, stream, opts)\n case 'auth':\n return auth(packet, stream, opts)\n default:\n stream.emit('error', new Error('Unknown command'))\n return false\n }\n}\n/**\n * Controls numbers cache.\n * Set to \"false\" to allocate buffers on-the-flight instead of pre-generated cache\n */\nObject.defineProperty(generate, 'cacheNumbers', {\n get () {\n return writeNumber === writeNumberCached\n },\n set (value) {\n if (value) {\n if (!numCache || Object.keys(numCache).length === 0) toGenerate = true\n writeNumber = writeNumberCached\n } else {\n toGenerate = false\n writeNumber = writeNumberGenerated\n }\n }\n})\n\nfunction uncork (stream) {\n stream.uncork()\n}\n\nfunction connect (packet, stream, opts) {\n const settings = packet || {}\n const protocolId = settings.protocolId || 'MQTT'\n let protocolVersion = settings.protocolVersion || 4\n const will = settings.will\n let clean = settings.clean\n const keepalive = settings.keepalive || 0\n const clientId = settings.clientId || ''\n const username = settings.username\n const password = settings.password\n /* mqtt5 new oprions */\n const properties = settings.properties\n\n if (clean === undefined) clean = true\n\n let length = 0\n\n // Must be a string and non-falsy\n if (!protocolId ||\n (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {\n stream.emit('error', new Error('Invalid protocolId'))\n return false\n } else length += protocolId.length + 2\n\n // Must be 3 or 4 or 5\n if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {\n stream.emit('error', new Error('Invalid protocol version'))\n return false\n } else length += 1\n\n // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1\n if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&\n (clientId || protocolVersion >= 4) && (clientId || clean)) {\n length += Buffer.byteLength(clientId) + 2\n } else {\n if (protocolVersion < 4) {\n stream.emit('error', new Error('clientId must be supplied before 3.1.1'))\n return false\n }\n if ((clean * 1) === 0) {\n stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))\n return false\n }\n }\n\n // Must be a two byte number\n if (typeof keepalive !== 'number' ||\n keepalive < 0 ||\n keepalive > 65535 ||\n keepalive % 1 !== 0) {\n stream.emit('error', new Error('Invalid keepalive'))\n return false\n } else length += 2\n\n // Connect flags\n length += 1\n\n // Properties\n if (protocolVersion === 5) {\n var propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // If will exists...\n if (will) {\n // It must be an object\n if (typeof will !== 'object') {\n stream.emit('error', new Error('Invalid will'))\n return false\n }\n // It must have topic typeof string\n if (!will.topic || typeof will.topic !== 'string') {\n stream.emit('error', new Error('Invalid will topic'))\n return false\n } else {\n length += Buffer.byteLength(will.topic) + 2\n }\n\n // Payload\n length += 2 // payload length\n if (will.payload) {\n if (will.payload.length >= 0) {\n if (typeof will.payload === 'string') {\n length += Buffer.byteLength(will.payload)\n } else {\n length += will.payload.length\n }\n } else {\n stream.emit('error', new Error('Invalid will payload'))\n return false\n }\n }\n // will properties\n var willProperties = {}\n if (protocolVersion === 5) {\n willProperties = getProperties(stream, will.properties)\n if (!willProperties) { return false }\n length += willProperties.length\n }\n }\n\n // Username\n let providedUsername = false\n if (username != null) {\n if (isStringOrBuffer(username)) {\n providedUsername = true\n length += Buffer.byteLength(username) + 2\n } else {\n stream.emit('error', new Error('Invalid username'))\n return false\n }\n }\n\n // Password\n if (password != null) {\n if (!providedUsername) {\n stream.emit('error', new Error('Username is required to use password'))\n return false\n }\n\n if (isStringOrBuffer(password)) {\n length += byteLength(password) + 2\n } else {\n stream.emit('error', new Error('Invalid password'))\n return false\n }\n }\n\n // Generate header\n stream.write(protocol.CONNECT_HEADER)\n\n // Generate length\n writeVarByteInt(stream, length)\n\n // Generate protocol ID\n writeStringOrBuffer(stream, protocolId)\n\n if (settings.bridgeMode) {\n protocolVersion += 128\n }\n\n stream.write(\n protocolVersion === 131\n ? protocol.VERSION131\n : protocolVersion === 132\n ? protocol.VERSION132\n : protocolVersion === 4\n ? protocol.VERSION4\n : protocolVersion === 5\n ? protocol.VERSION5\n : protocol.VERSION3\n )\n\n // Connect flags\n let flags = 0\n flags |= (username != null) ? protocol.USERNAME_MASK : 0\n flags |= (password != null) ? protocol.PASSWORD_MASK : 0\n flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0\n flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0\n flags |= will ? protocol.WILL_FLAG_MASK : 0\n flags |= clean ? protocol.CLEAN_SESSION_MASK : 0\n\n stream.write(Buffer.from([flags]))\n\n // Keepalive\n writeNumber(stream, keepalive)\n\n // Properties\n if (protocolVersion === 5) {\n propertiesData.write()\n }\n\n // Client ID\n writeStringOrBuffer(stream, clientId)\n\n // Will\n if (will) {\n if (protocolVersion === 5) {\n willProperties.write()\n }\n writeString(stream, will.topic)\n writeStringOrBuffer(stream, will.payload)\n }\n\n // Username and password\n if (username != null) {\n writeStringOrBuffer(stream, username)\n }\n if (password != null) {\n writeStringOrBuffer(stream, password)\n }\n // This is a small packet that happens only once on a stream\n // We assume the stream is always free to receive more data after this\n return true\n}\n\nfunction connack (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const rc = version === 5 ? settings.reasonCode : settings.returnCode\n const properties = settings.properties\n let length = 2 // length of rc and sessionHeader\n\n // Check return code\n if (typeof rc !== 'number') {\n stream.emit('error', new Error('Invalid return code'))\n return false\n }\n // mqtt5 properties\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n stream.write(protocol.CONNACK_HEADER)\n // length\n writeVarByteInt(stream, length)\n stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)\n\n stream.write(Buffer.from([rc]))\n if (propertiesData != null) {\n propertiesData.write()\n }\n return true\n}\n\nfunction publish (packet, stream, opts) {\n debug('publish: packet: %o', packet)\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const qos = settings.qos || 0\n const retain = settings.retain ? protocol.RETAIN_MASK : 0\n const topic = settings.topic\n const payload = settings.payload || empty\n const id = settings.messageId\n const properties = settings.properties\n\n let length = 0\n\n // Topic must be a non-empty string or Buffer\n if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2\n else if (Buffer.isBuffer(topic)) length += topic.length + 2\n else {\n stream.emit('error', new Error('Invalid topic'))\n return false\n }\n\n // Get the payload length\n if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)\n else length += payload.length\n\n // Message ID must a number if qos > 0\n if (qos && typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else if (qos) length += 2\n\n // mqtt5 properties\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])\n\n // Remaining length\n writeVarByteInt(stream, length)\n\n // Topic\n writeNumber(stream, byteLength(topic))\n stream.write(topic)\n\n // Message ID\n if (qos > 0) writeNumber(stream, id)\n\n // Properties\n if (propertiesData != null) {\n propertiesData.write()\n }\n\n // Payload\n debug('publish: payload: %o', payload)\n return stream.write(payload)\n}\n\n/* Puback, pubrec, pubrel and pubcomp */\nfunction confirmation (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const type = settings.cmd || 'puback'\n const id = settings.messageId\n const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0\n let qos = 0\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 3 : 2\n\n if (type === 'pubrel') qos = 1\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1)\n if (typeof properties === 'object') {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n }\n\n // Header\n stream.write(protocol.ACKS[type][qos][dup][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // reason code in header\n if (version === 5) {\n stream.write(Buffer.from([reasonCode]))\n }\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n return true\n}\n\nfunction subscribe (packet, stream, opts) {\n debug('subscribe: packet: ')\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const id = settings.messageId\n const subs = settings.subscriptions\n const properties = settings.properties\n\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else length += 2\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Check subscriptions\n if (typeof subs === 'object' && subs.length) {\n for (let i = 0; i < subs.length; i += 1) {\n const itopic = subs[i].topic\n const iqos = subs[i].qos\n\n if (typeof itopic !== 'string') {\n stream.emit('error', new Error('Invalid subscriptions - invalid topic'))\n return false\n }\n if (typeof iqos !== 'number') {\n stream.emit('error', new Error('Invalid subscriptions - invalid qos'))\n return false\n }\n\n if (version === 5) {\n const nl = subs[i].nl || false\n if (typeof nl !== 'boolean') {\n stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))\n return false\n }\n const rap = subs[i].rap || false\n if (typeof rap !== 'boolean') {\n stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))\n return false\n }\n const rh = subs[i].rh || 0\n if (typeof rh !== 'number' || rh > 2) {\n stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))\n return false\n }\n }\n\n length += Buffer.byteLength(itopic) + 2 + 1\n }\n } else {\n stream.emit('error', new Error('Invalid subscriptions'))\n return false\n }\n\n // Generate header\n debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER)\n stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])\n\n // Generate length\n writeVarByteInt(stream, length)\n\n // Generate message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n let result = true\n\n // Generate subs\n for (const sub of subs) {\n const jtopic = sub.topic\n const jqos = sub.qos\n const jnl = +sub.nl\n const jrap = +sub.rap\n const jrh = sub.rh\n let joptions\n\n // Write topic string\n writeString(stream, jtopic)\n\n // options process\n joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]\n if (version === 5) {\n joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0\n joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0\n joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0\n }\n // Write options\n result = stream.write(Buffer.from([joptions]))\n }\n\n return result\n}\n\nfunction suback (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const granted = settings.granted\n const properties = settings.properties\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else length += 2\n\n // Check granted qos vector\n if (typeof granted === 'object' && granted.length) {\n for (let i = 0; i < granted.length; i += 1) {\n if (typeof granted[i] !== 'number') {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n length += 1\n }\n } else {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // header\n stream.write(protocol.SUBACK_HEADER)\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n return stream.write(Buffer.from(granted))\n}\n\nfunction unsubscribe (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const unsubs = settings.unsubscriptions\n const properties = settings.properties\n\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else {\n length += 2\n }\n // Check unsubs\n if (typeof unsubs === 'object' && unsubs.length) {\n for (let i = 0; i < unsubs.length; i += 1) {\n if (typeof unsubs[i] !== 'string') {\n stream.emit('error', new Error('Invalid unsubscriptions'))\n return false\n }\n length += Buffer.byteLength(unsubs[i]) + 2\n }\n } else {\n stream.emit('error', new Error('Invalid unsubscriptions'))\n return false\n }\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n // Unsubs\n let result = true\n for (let j = 0; j < unsubs.length; j++) {\n result = writeString(stream, unsubs[j])\n }\n\n return result\n}\n\nfunction unsuback (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const granted = settings.granted\n const properties = settings.properties\n const type = settings.cmd\n const qos = 0\n\n let length = 2\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n }\n\n // Check granted\n if (version === 5) {\n if (typeof granted === 'object' && granted.length) {\n for (let i = 0; i < granted.length; i += 1) {\n if (typeof granted[i] !== 'number') {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n length += 1\n }\n } else {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.ACKS[type][qos][dup][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n // payload\n if (version === 5) {\n stream.write(Buffer.from(granted))\n }\n return true\n}\n\nfunction emptyPacket (packet, stream, opts) {\n return stream.write(protocol.EMPTY[packet.cmd])\n}\n\nfunction disconnect (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 1 : 0\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(Buffer.from([protocol.codes.disconnect << 4]))\n\n // Length\n writeVarByteInt(stream, length)\n\n // reason code in header\n if (version === 5) {\n stream.write(Buffer.from([reasonCode]))\n }\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n return true\n}\n\nfunction auth (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 1 : 0\n\n if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))\n\n // properies mqtt 5\n const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n\n // Header\n stream.write(Buffer.from([protocol.codes.auth << 4]))\n\n // Length\n writeVarByteInt(stream, length)\n\n // reason code in header\n stream.write(Buffer.from([reasonCode]))\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n return true\n}\n\n/**\n * writeVarByteInt - write an MQTT style variable byte integer to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param length - length (>0)\n * @returns number of bytes written\n *\n * @api private\n */\n\nconst varByteIntCache = {}\nfunction writeVarByteInt (stream, num) {\n if (num > protocol.VARBYTEINT_MAX) {\n stream.emit('error', new Error(`Invalid variable byte integer: ${num}`))\n return false\n }\n\n let buffer = varByteIntCache[num]\n\n if (!buffer) {\n buffer = genBufVariableByteInt(num)\n if (num < 16384) varByteIntCache[num] = buffer\n }\n debug('writeVarByteInt: writing to stream: %o', buffer)\n return stream.write(buffer)\n}\n\n/**\n * writeString - write a utf8 string to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param string - string to write\n * @return number of bytes written\n *\n * @api private\n */\n\nfunction writeString (stream, string) {\n const strlen = Buffer.byteLength(string)\n writeNumber(stream, strlen)\n\n debug('writeString: %s', string)\n return stream.write(string, 'utf8')\n}\n\n/**\n * writeStringPair - write a utf8 string pairs to the buffer\n *\n * @param buffer - destination\n * @param name - string name to write\n * @param value - string value to write\n * @return number of bytes written\n *\n * @api private\n */\nfunction writeStringPair (stream, name, value) {\n writeString(stream, name)\n writeString(stream, value)\n}\n\n/**\n * writeNumber - write a two byte number to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param number - number to write\n * @return number of bytes written\n *\n * @api private\n */\nfunction writeNumberCached (stream, number) {\n debug('writeNumberCached: number: %d', number)\n debug('writeNumberCached: %o', numCache[number])\n return stream.write(numCache[number])\n}\nfunction writeNumberGenerated (stream, number) {\n const generatedNumber = generateNumber(number)\n debug('writeNumberGenerated: %o', generatedNumber)\n return stream.write(generatedNumber)\n}\nfunction write4ByteNumber (stream, number) {\n const generated4ByteBuffer = generate4ByteBuffer(number)\n debug('write4ByteNumber: %o', generated4ByteBuffer)\n return stream.write(generated4ByteBuffer)\n}\n/**\n * writeStringOrBuffer - write a String or Buffer with the its length prefix\n *\n * @param buffer - destination\n * @param pos - offset\n * @param toWrite - String or Buffer\n * @return number of bytes written\n */\nfunction writeStringOrBuffer (stream, toWrite) {\n if (typeof toWrite === 'string') {\n writeString(stream, toWrite)\n } else if (toWrite) {\n writeNumber(stream, toWrite.length)\n stream.write(toWrite)\n } else writeNumber(stream, 0)\n}\n\nfunction getProperties (stream, properties) {\n /* connect properties */\n if (typeof properties !== 'object' || properties.length != null) {\n return {\n length: 1,\n write () {\n writeProperties(stream, {}, 0)\n }\n }\n }\n let propertiesLength = 0\n function getLengthProperty (name, value) {\n const type = protocol.propertiesTypes[name]\n let length = 0\n switch (type) {\n case 'byte': {\n if (typeof value !== 'boolean') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 1\n break\n }\n case 'int8': {\n if (typeof value !== 'number' || value < 0 || value > 0xff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 1\n break\n }\n case 'binary': {\n if (value && value === null) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + Buffer.byteLength(value) + 2\n break\n }\n case 'int16': {\n if (typeof value !== 'number' || value < 0 || value > 0xffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 2\n break\n }\n case 'int32': {\n if (typeof value !== 'number' || value < 0 || value > 0xffffffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 4\n break\n }\n case 'var': {\n // var byte integer is max 24 bits packed in 32 bits\n if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + Buffer.byteLength(genBufVariableByteInt(value))\n break\n }\n case 'string': {\n if (typeof value !== 'string') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 2 + Buffer.byteLength(value.toString())\n break\n }\n case 'pair': {\n if (typeof value !== 'object') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += Object.getOwnPropertyNames(value).reduce((result, name) => {\n const currentValue = value[name]\n if (Array.isArray(currentValue)) {\n result += currentValue.reduce((currentLength, value) => {\n currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString())\n return currentLength\n }, 0)\n } else {\n result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())\n }\n return result\n }, 0)\n break\n }\n default: {\n stream.emit('error', new Error(`Invalid property ${name}: ${value}`))\n return false\n }\n }\n return length\n }\n if (properties) {\n for (const propName in properties) {\n let propLength = 0\n let propValueLength = 0\n const propValue = properties[propName]\n if (Array.isArray(propValue)) {\n for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) {\n propValueLength = getLengthProperty(propName, propValue[valueIndex])\n if (!propValueLength) { return false }\n propLength += propValueLength\n }\n } else {\n propValueLength = getLengthProperty(propName, propValue)\n if (!propValueLength) { return false }\n propLength = propValueLength\n }\n if (!propLength) return false\n propertiesLength += propLength\n }\n }\n const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength))\n\n return {\n length: propertiesLengthLength + propertiesLength,\n write () {\n writeProperties(stream, properties, propertiesLength)\n }\n }\n}\n\nfunction getPropertiesByMaximumPacketSize (stream, properties, opts, length) {\n const mayEmptyProps = ['reasonString', 'userProperties']\n const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0\n\n let propertiesData = getProperties(stream, properties)\n if (maximumPacketSize) {\n while (length + propertiesData.length > maximumPacketSize) {\n const currentMayEmptyProp = mayEmptyProps.shift()\n if (currentMayEmptyProp && properties[currentMayEmptyProp]) {\n delete properties[currentMayEmptyProp]\n propertiesData = getProperties(stream, properties)\n } else {\n return false\n }\n }\n }\n return propertiesData\n}\n\nfunction writeProperty (stream, propName, value) {\n const type = protocol.propertiesTypes[propName]\n switch (type) {\n case 'byte': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n stream.write(Buffer.from([+value]))\n break\n }\n case 'int8': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n stream.write(Buffer.from([value]))\n break\n }\n case 'binary': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringOrBuffer(stream, value)\n break\n }\n case 'int16': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeNumber(stream, value)\n break\n }\n case 'int32': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n write4ByteNumber(stream, value)\n break\n }\n case 'var': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeVarByteInt(stream, value)\n break\n }\n case 'string': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeString(stream, value)\n break\n }\n case 'pair': {\n Object.getOwnPropertyNames(value).forEach(name => {\n const currentValue = value[name]\n if (Array.isArray(currentValue)) {\n currentValue.forEach(value => {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringPair(stream, name.toString(), value.toString())\n })\n } else {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringPair(stream, name.toString(), currentValue.toString())\n }\n })\n break\n }\n default: {\n stream.emit('error', new Error(`Invalid property ${propName} value: ${value}`))\n return false\n }\n }\n}\n\nfunction writeProperties (stream, properties, propertiesLength) {\n /* write properties to stream */\n writeVarByteInt(stream, propertiesLength)\n for (const propName in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] !== null) {\n const value = properties[propName]\n if (Array.isArray(value)) {\n for (let valueIndex = 0; valueIndex < value.length; valueIndex++) {\n writeProperty(stream, propName, value[valueIndex])\n }\n } else {\n writeProperty(stream, propName, value)\n }\n }\n }\n}\n\nfunction byteLength (bufOrString) {\n if (!bufOrString) return 0\n else if (bufOrString instanceof Buffer) return bufOrString.length\n else return Buffer.byteLength(bufOrString)\n}\n\nfunction isStringOrBuffer (field) {\n return typeof field === 'string' || field instanceof Buffer\n}\n\nmodule.exports = generate\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\nvar Duplex = require('./_stream_duplex');\nrequire('inherits')(Transform, Duplex);\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null)\n // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\nfunction prefinish() {\n var _this = this;\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null)\n // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\nvar Transform = require('./_stream_transform');\nrequire('inherits')(PassThrough, Transform);\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","const writeToStream = require('./writeToStream')\nconst EventEmitter = require('events')\n\nfunction generate (packet, opts) {\n const stream = new Accumulator()\n writeToStream(packet, stream, opts)\n return stream.concat()\n}\n\nclass Accumulator extends EventEmitter {\n constructor () {\n super()\n this._array = new Array(20)\n this._i = 0\n }\n\n write (chunk) {\n this._array[this._i++] = chunk\n return true\n }\n\n concat () {\n let length = 0\n const lengths = new Array(this._array.length)\n const list = this._array\n let pos = 0\n let i\n\n for (i = 0; i < list.length && list[i] !== undefined; i++) {\n if (typeof list[i] !== 'string') lengths[i] = list[i].length\n else lengths[i] = Buffer.byteLength(list[i])\n\n length += lengths[i]\n }\n\n const result = Buffer.allocUnsafe(length)\n\n for (i = 0; i < list.length && list[i] !== undefined; i++) {\n if (typeof list[i] !== 'string') {\n list[i].copy(result, pos)\n pos += lengths[i]\n } else {\n result.write(list[i], pos)\n pos += lengths[i]\n }\n }\n\n return result\n }\n}\n\nmodule.exports = generate\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst Transform = require('readable-stream').Transform\nconst duplexify = require('duplexify')\n\n/* global wx */\nlet socketTask, proxy, stream\n\nfunction buildProxy () {\n const proxy = new Transform()\n proxy._write = function (chunk, encoding, next) {\n socketTask.send({\n data: chunk.buffer,\n success: function () {\n next()\n },\n fail: function (errMsg) {\n next(new Error(errMsg))\n }\n })\n }\n proxy._flush = function socketEnd (done) {\n socketTask.close({\n success: function () {\n done()\n }\n })\n }\n\n return proxy\n}\n\nfunction setDefaultOpts (opts) {\n if (!opts.hostname) {\n opts.hostname = 'localhost'\n }\n if (!opts.path) {\n opts.path = '/'\n }\n\n if (!opts.wsOptions) {\n opts.wsOptions = {}\n }\n}\n\nfunction buildUrl (opts, client) {\n const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'\n let url = protocol + '://' + opts.hostname + opts.path\n if (opts.port && opts.port !== 80 && opts.port !== 443) {\n url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n }\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction bindEventHandler () {\n socketTask.onOpen(function () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n })\n\n socketTask.onMessage(function (res) {\n let data = res.data\n\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n })\n\n socketTask.onClose(function () {\n stream.end()\n stream.destroy()\n })\n\n socketTask.onError(function (res) {\n stream.destroy(new Error(res.errMsg))\n })\n}\n\nfunction buildStream (client, opts) {\n opts.hostname = opts.hostname || opts.host\n\n if (!opts.hostname) {\n throw new Error('Could not determine host. Specify host manually.')\n }\n\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n setDefaultOpts(opts)\n\n const url = buildUrl(opts, client)\n socketTask = wx.connectSocket({\n url: url,\n protocols: [websocketSubProtocol]\n })\n\n proxy = buildProxy()\n stream = duplexify.obj()\n stream._destroy = function (err, cb) {\n socketTask.close({\n success: function () {\n cb && cb(err)\n }\n })\n }\n\n const destroyRef = stream.destroy\n stream.destroy = function () {\n stream.destroy = destroyRef\n\n const self = this\n setTimeout(function () {\n socketTask.close({\n fail: function () {\n self._destroy(new Error())\n }\n })\n }, 0)\n }.bind(stream)\n\n bindEventHandler()\n\n return stream\n}\n\nmodule.exports = buildStream\n","'use strict'\n\n/**\n * Module dependencies\n */\nconst LruMap = require('lru-cache')\nconst NumberAllocator = require('number-allocator').NumberAllocator\n\n/**\n * Topic Alias sending manager\n * This holds both topic to alias and alias to topic map\n * @param {Number} [max] - topic alias maximum entries\n */\nfunction TopicAliasSend (max) {\n if (!(this instanceof TopicAliasSend)) {\n return new TopicAliasSend(max)\n }\n\n if (max > 0) {\n this.aliasToTopic = new LruMap({ max: max })\n this.topicToAlias = {}\n this.numberAllocator = new NumberAllocator(1, max)\n this.max = max\n this.length = 0\n }\n}\n\n/**\n * Insert or update topic - alias entry.\n * @param {String} [topic] - topic\n * @param {Number} [alias] - topic alias\n * @returns {Boolean} - if success return true otherwise false\n */\nTopicAliasSend.prototype.put = function (topic, alias) {\n if (alias === 0 || alias > this.max) {\n return false\n }\n const entry = this.aliasToTopic.get(alias)\n if (entry) {\n delete this.topicToAlias[entry]\n }\n this.aliasToTopic.set(alias, topic)\n this.topicToAlias[topic] = alias\n this.numberAllocator.use(alias)\n this.length = this.aliasToTopic.length\n return true\n}\n\n/**\n * Get topic by alias\n * @param {Number} [alias] - topic alias\n * @returns {String} - if mapped topic exists return topic, otherwise return undefined\n */\nTopicAliasSend.prototype.getTopicByAlias = function (alias) {\n return this.aliasToTopic.get(alias)\n}\n\n/**\n * Get topic by alias\n * @param {String} [topic] - topic\n * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined\n */\nTopicAliasSend.prototype.getAliasByTopic = function (topic) {\n const alias = this.topicToAlias[topic]\n if (typeof alias !== 'undefined') {\n this.aliasToTopic.get(alias) // LRU update\n }\n return alias\n}\n\n/**\n * Clear all entries\n */\nTopicAliasSend.prototype.clear = function () {\n this.aliasToTopic.reset()\n this.topicToAlias = {}\n this.numberAllocator.clear()\n this.length = 0\n}\n\n/**\n * Get Least Recently Used (LRU) topic alias\n * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias\n */\nTopicAliasSend.prototype.getLruAlias = function () {\n const alias = this.numberAllocator.firstVacant()\n if (alias) return alias\n return this.aliasToTopic.keys()[this.aliasToTopic.length - 1]\n}\n\nmodule.exports = TopicAliasSend\n","class Packet {\n constructor () {\n this.cmd = null\n this.retain = false\n this.qos = 0\n this.dup = false\n this.length = -1\n this.topic = null\n this.payload = null\n }\n}\n\nmodule.exports = Packet\n","'use strict'\n\n/**\n * Validate a topic to see if it's valid or not.\n * A topic is valid if it follow below rules:\n * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'\n * - Rule #2: Part `#` must be located at the end of the mailbox\n *\n * @param {String} topic - A topic\n * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.\n */\nfunction validateTopic (topic) {\n const parts = topic.split('/')\n\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] === '+') {\n continue\n }\n\n if (parts[i] === '#') {\n // for Rule #2\n return i === parts.length - 1\n }\n\n if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Validate an array of topics to see if any of them is valid or not\n * @param {Array} topics - Array of topics\n * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one\n */\nfunction validateTopics (topics) {\n if (topics.length === 0) {\n return 'empty_topic_list'\n }\n for (let i = 0; i < topics.length; i++) {\n if (!validateTopic(topics[i])) {\n return topics[i]\n }\n }\n return null\n}\n\nmodule.exports = {\n validateTopics: validateTopics\n}\n","/* Protocol - protocol constants */\nconst protocol = module.exports\n\n/* Command code => mnemonic */\nprotocol.types = {\n 0: 'reserved',\n 1: 'connect',\n 2: 'connack',\n 3: 'publish',\n 4: 'puback',\n 5: 'pubrec',\n 6: 'pubrel',\n 7: 'pubcomp',\n 8: 'subscribe',\n 9: 'suback',\n 10: 'unsubscribe',\n 11: 'unsuback',\n 12: 'pingreq',\n 13: 'pingresp',\n 14: 'disconnect',\n 15: 'auth'\n}\n\n/* Mnemonic => Command code */\nprotocol.codes = {}\nfor (const k in protocol.types) {\n const v = protocol.types[k]\n protocol.codes[v] = k\n}\n\n/* Header */\nprotocol.CMD_SHIFT = 4\nprotocol.CMD_MASK = 0xF0\nprotocol.DUP_MASK = 0x08\nprotocol.QOS_MASK = 0x03\nprotocol.QOS_SHIFT = 1\nprotocol.RETAIN_MASK = 0x01\n\n/* Length */\nprotocol.VARBYTEINT_MASK = 0x7F\nprotocol.VARBYTEINT_FIN_MASK = 0x80\nprotocol.VARBYTEINT_MAX = 268435455\n\n/* Connack */\nprotocol.SESSIONPRESENT_MASK = 0x01\nprotocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])\nprotocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT])\n\n/* Connect */\nprotocol.USERNAME_MASK = 0x80\nprotocol.PASSWORD_MASK = 0x40\nprotocol.WILL_RETAIN_MASK = 0x20\nprotocol.WILL_QOS_MASK = 0x18\nprotocol.WILL_QOS_SHIFT = 3\nprotocol.WILL_FLAG_MASK = 0x04\nprotocol.CLEAN_SESSION_MASK = 0x02\nprotocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT])\n\n/* Properties */\nprotocol.properties = {\n sessionExpiryInterval: 17,\n willDelayInterval: 24,\n receiveMaximum: 33,\n maximumPacketSize: 39,\n topicAliasMaximum: 34,\n requestResponseInformation: 25,\n requestProblemInformation: 23,\n userProperties: 38,\n authenticationMethod: 21,\n authenticationData: 22,\n payloadFormatIndicator: 1,\n messageExpiryInterval: 2,\n contentType: 3,\n responseTopic: 8,\n correlationData: 9,\n maximumQoS: 36,\n retainAvailable: 37,\n assignedClientIdentifier: 18,\n reasonString: 31,\n wildcardSubscriptionAvailable: 40,\n subscriptionIdentifiersAvailable: 41,\n sharedSubscriptionAvailable: 42,\n serverKeepAlive: 19,\n responseInformation: 26,\n serverReference: 28,\n topicAlias: 35,\n subscriptionIdentifier: 11\n}\nprotocol.propertiesCodes = {}\nfor (const prop in protocol.properties) {\n const id = protocol.properties[prop]\n protocol.propertiesCodes[id] = prop\n}\nprotocol.propertiesTypes = {\n sessionExpiryInterval: 'int32',\n willDelayInterval: 'int32',\n receiveMaximum: 'int16',\n maximumPacketSize: 'int32',\n topicAliasMaximum: 'int16',\n requestResponseInformation: 'byte',\n requestProblemInformation: 'byte',\n userProperties: 'pair',\n authenticationMethod: 'string',\n authenticationData: 'binary',\n payloadFormatIndicator: 'byte',\n messageExpiryInterval: 'int32',\n contentType: 'string',\n responseTopic: 'string',\n correlationData: 'binary',\n maximumQoS: 'int8',\n retainAvailable: 'byte',\n assignedClientIdentifier: 'string',\n reasonString: 'string',\n wildcardSubscriptionAvailable: 'byte',\n subscriptionIdentifiersAvailable: 'byte',\n sharedSubscriptionAvailable: 'byte',\n serverKeepAlive: 'int16',\n responseInformation: 'string',\n serverReference: 'string',\n topicAlias: 'int16',\n subscriptionIdentifier: 'var'\n}\n\nfunction genHeader (type) {\n return [0, 1, 2].map(qos => {\n return [0, 1].map(dup => {\n return [0, 1].map(retain => {\n const buf = Buffer.alloc(1)\n buf.writeUInt8(\n protocol.codes[type] << protocol.CMD_SHIFT |\n (dup ? protocol.DUP_MASK : 0) |\n qos << protocol.QOS_SHIFT | retain, 0, true)\n return buf\n })\n })\n })\n}\n\n/* Publish */\nprotocol.PUBLISH_HEADER = genHeader('publish')\n\n/* Subscribe */\nprotocol.SUBSCRIBE_HEADER = genHeader('subscribe')\nprotocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03\nprotocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01\nprotocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2\nprotocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01\nprotocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3\nprotocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03\nprotocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4\nprotocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]\nprotocol.SUBSCRIBE_OPTIONS_NL = 0x04\nprotocol.SUBSCRIBE_OPTIONS_RAP = 0x08\nprotocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]\n\n/* Unsubscribe */\nprotocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')\n\n/* Confirmations */\nprotocol.ACKS = {\n unsuback: genHeader('unsuback'),\n puback: genHeader('puback'),\n pubcomp: genHeader('pubcomp'),\n pubrel: genHeader('pubrel'),\n pubrec: genHeader('pubrec')\n}\n\nprotocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT])\n\n/* Protocol versions */\nprotocol.VERSION3 = Buffer.from([3])\nprotocol.VERSION4 = Buffer.from([4])\nprotocol.VERSION5 = Buffer.from([5])\nprotocol.VERSION131 = Buffer.from([131])\nprotocol.VERSION132 = Buffer.from([132])\n\n/* QoS */\nprotocol.QOS = [0, 1, 2].map(qos => {\n return Buffer.from([qos])\n})\n\n/* Empty packets */\nprotocol.EMPTY = {\n pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]),\n pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]),\n disconnect: Buffer.from([protocol.codes.disconnect << 4, 0])\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst Transform = require('readable-stream').Transform\nconst duplexify = require('duplexify')\n\n/* global FileReader */\nlet my\nlet proxy\nlet stream\nlet isInitialized = false\n\nfunction buildProxy () {\n const proxy = new Transform()\n proxy._write = function (chunk, encoding, next) {\n my.sendSocketMessage({\n data: chunk.buffer,\n success: function () {\n next()\n },\n fail: function () {\n next(new Error())\n }\n })\n }\n proxy._flush = function socketEnd (done) {\n my.closeSocket({\n success: function () {\n done()\n }\n })\n }\n\n return proxy\n}\n\nfunction setDefaultOpts (opts) {\n if (!opts.hostname) {\n opts.hostname = 'localhost'\n }\n if (!opts.path) {\n opts.path = '/'\n }\n\n if (!opts.wsOptions) {\n opts.wsOptions = {}\n }\n}\n\nfunction buildUrl (opts, client) {\n const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'\n let url = protocol + '://' + opts.hostname + opts.path\n if (opts.port && opts.port !== 80 && opts.port !== 443) {\n url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n }\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction bindEventHandler () {\n if (isInitialized) return\n\n isInitialized = true\n\n my.onSocketOpen(function () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n })\n\n my.onSocketMessage(function (res) {\n if (typeof res.data === 'string') {\n const buffer = Buffer.from(res.data, 'base64')\n proxy.push(buffer)\n } else {\n const reader = new FileReader()\n reader.addEventListener('load', function () {\n let data = reader.result\n\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n })\n reader.readAsArrayBuffer(res.data)\n }\n })\n\n my.onSocketClose(function () {\n stream.end()\n stream.destroy()\n })\n\n my.onSocketError(function (res) {\n stream.destroy(res)\n })\n}\n\nfunction buildStream (client, opts) {\n opts.hostname = opts.hostname || opts.host\n\n if (!opts.hostname) {\n throw new Error('Could not determine host. Specify host manually.')\n }\n\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n setDefaultOpts(opts)\n\n const url = buildUrl(opts, client)\n my = opts.my\n my.connectSocket({\n url: url,\n protocols: websocketSubProtocol\n })\n\n proxy = buildProxy()\n stream = duplexify.obj()\n\n bindEventHandler()\n\n return stream\n}\n\nmodule.exports = buildStream\n","'use strict'\n\n/**\n * Module dependencies\n */\nconst EventEmitter = require('events').EventEmitter\nconst Store = require('./store')\nconst TopicAliasRecv = require('./topic-alias-recv')\nconst TopicAliasSend = require('./topic-alias-send')\nconst mqttPacket = require('mqtt-packet')\nconst DefaultMessageIdProvider = require('./default-message-id-provider')\nconst Writable = require('readable-stream').Writable\nconst inherits = require('inherits')\nconst reInterval = require('reinterval')\nconst clone = require('rfdc/default')\nconst validations = require('./validations')\nconst xtend = require('xtend')\nconst debug = require('debug')('mqttjs:client')\nconst nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }\nconst setImmediate = global.setImmediate || function (callback) {\n // works in node v0.8\n nextTick(callback)\n}\nconst defaultConnectOptions = {\n keepalive: 60,\n reschedulePings: true,\n protocolId: 'MQTT',\n protocolVersion: 4,\n reconnectPeriod: 1000,\n connectTimeout: 30 * 1000,\n clean: true,\n resubscribe: true\n}\n\nconst socketErrors = [\n 'ECONNREFUSED',\n 'EADDRINUSE',\n 'ECONNRESET',\n 'ENOTFOUND'\n]\n\n// Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.\n\nconst errors = {\n 0: '',\n 1: 'Unacceptable protocol version',\n 2: 'Identifier rejected',\n 3: 'Server unavailable',\n 4: 'Bad username or password',\n 5: 'Not authorized',\n 16: 'No matching subscribers',\n 17: 'No subscription existed',\n 128: 'Unspecified error',\n 129: 'Malformed Packet',\n 130: 'Protocol Error',\n 131: 'Implementation specific error',\n 132: 'Unsupported Protocol Version',\n 133: 'Client Identifier not valid',\n 134: 'Bad User Name or Password',\n 135: 'Not authorized',\n 136: 'Server unavailable',\n 137: 'Server busy',\n 138: 'Banned',\n 139: 'Server shutting down',\n 140: 'Bad authentication method',\n 141: 'Keep Alive timeout',\n 142: 'Session taken over',\n 143: 'Topic Filter invalid',\n 144: 'Topic Name invalid',\n 145: 'Packet identifier in use',\n 146: 'Packet Identifier not found',\n 147: 'Receive Maximum exceeded',\n 148: 'Topic Alias invalid',\n 149: 'Packet too large',\n 150: 'Message rate too high',\n 151: 'Quota exceeded',\n 152: 'Administrative action',\n 153: 'Payload format invalid',\n 154: 'Retain not supported',\n 155: 'QoS not supported',\n 156: 'Use another server',\n 157: 'Server moved',\n 158: 'Shared Subscriptions not supported',\n 159: 'Connection rate exceeded',\n 160: 'Maximum connect time',\n 161: 'Subscription Identifiers not supported',\n 162: 'Wildcard Subscriptions not supported'\n}\n\nfunction defaultId () {\n return 'mqttjs_' + Math.random().toString(16).substr(2, 8)\n}\n\nfunction applyTopicAlias (client, packet) {\n if (client.options.protocolVersion === 5) {\n if (packet.cmd === 'publish') {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n const topic = packet.topic.toString()\n if (client.topicAliasSend) {\n if (alias) {\n if (topic.length !== 0) {\n // register topic alias\n debug('applyTopicAlias :: register topic: %s - alias: %d', topic, alias)\n if (!client.topicAliasSend.put(topic, alias)) {\n debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)\n return new Error('Sending Topic Alias out of range')\n }\n }\n } else {\n if (topic.length !== 0) {\n if (client.options.autoAssignTopicAlias) {\n alias = client.topicAliasSend.getAliasByTopic(topic)\n if (alias) {\n packet.topic = ''\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)\n } else {\n alias = client.topicAliasSend.getLruAlias()\n client.topicAliasSend.put(topic, alias)\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias)\n }\n } else if (client.options.autoUseTopicAlias) {\n alias = client.topicAliasSend.getAliasByTopic(topic)\n if (alias) {\n packet.topic = ''\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias)\n }\n }\n }\n }\n } else if (alias) {\n debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)\n return new Error('Sending Topic Alias out of range')\n }\n }\n }\n}\n\nfunction removeTopicAliasAndRecoverTopicName (client, packet) {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n\n let topic = packet.topic.toString()\n if (topic.length === 0) {\n // restore topic from alias\n if (typeof alias === 'undefined') {\n return new Error('Unregistered Topic Alias')\n } else {\n topic = client.topicAliasSend.getTopicByAlias(alias)\n if (typeof topic === 'undefined') {\n return new Error('Unregistered Topic Alias')\n } else {\n packet.topic = topic\n }\n }\n }\n if (alias) {\n delete packet.properties.topicAlias\n }\n}\n\nfunction sendPacket (client, packet, cb) {\n debug('sendPacket :: packet: %O', packet)\n debug('sendPacket :: emitting `packetsend`')\n\n client.emit('packetsend', packet)\n\n debug('sendPacket :: writing to stream')\n const result = mqttPacket.writeToStream(packet, client.stream, client.options)\n debug('sendPacket :: writeToStream result %s', result)\n if (!result && cb && cb !== nop) {\n debug('sendPacket :: handle events on `drain` once through callback.')\n client.stream.once('drain', cb)\n } else if (cb) {\n debug('sendPacket :: invoking cb')\n cb()\n }\n}\n\nfunction flush (queue) {\n if (queue) {\n debug('flush: queue exists? %b', !!(queue))\n Object.keys(queue).forEach(function (messageId) {\n if (typeof queue[messageId].cb === 'function') {\n queue[messageId].cb(new Error('Connection closed'))\n // This is suspicious. Why do we only delete this if we have a callbck?\n // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.\n delete queue[messageId]\n }\n })\n }\n}\n\nfunction flushVolatile (queue) {\n if (queue) {\n debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')\n Object.keys(queue).forEach(function (messageId) {\n if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {\n queue[messageId].cb(new Error('Connection closed'))\n delete queue[messageId]\n }\n })\n }\n}\n\nfunction storeAndSend (client, packet, cb, cbStorePut) {\n debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)\n let storePacket = packet\n let err\n if (storePacket.cmd === 'publish') {\n // The original packet is for sending.\n // The cloned storePacket is for storing to resend on reconnect.\n // Topic Alias must not be used after disconnected.\n storePacket = clone(packet)\n err = removeTopicAliasAndRecoverTopicName(client, storePacket)\n if (err) {\n return cb && cb(err)\n }\n }\n client.outgoingStore.put(storePacket, function storedPacket (err) {\n if (err) {\n return cb && cb(err)\n }\n cbStorePut()\n sendPacket(client, packet, cb)\n })\n}\n\nfunction nop (error) {\n debug('nop ::', error)\n}\n\n/**\n * MqttClient constructor\n *\n * @param {Stream} stream - stream\n * @param {Object} [options] - connection options\n * (see Connection#connect)\n */\nfunction MqttClient (streamBuilder, options) {\n let k\n const that = this\n\n if (!(this instanceof MqttClient)) {\n return new MqttClient(streamBuilder, options)\n }\n\n this.options = options || {}\n\n // Defaults\n for (k in defaultConnectOptions) {\n if (typeof this.options[k] === 'undefined') {\n this.options[k] = defaultConnectOptions[k]\n } else {\n this.options[k] = options[k]\n }\n }\n\n debug('MqttClient :: options.protocol', options.protocol)\n debug('MqttClient :: options.protocolVersion', options.protocolVersion)\n debug('MqttClient :: options.username', options.username)\n debug('MqttClient :: options.keepalive', options.keepalive)\n debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)\n debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)\n debug('MqttClient :: options.topicAliasMaximum', options.topicAliasMaximum)\n\n this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()\n\n debug('MqttClient :: clientId', this.options.clientId)\n\n this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }\n\n this.streamBuilder = streamBuilder\n\n this.messageIdProvider = (typeof this.options.messageIdProvider === 'undefined') ? new DefaultMessageIdProvider() : this.options.messageIdProvider\n\n // Inflight message storages\n this.outgoingStore = options.outgoingStore || new Store()\n this.incomingStore = options.incomingStore || new Store()\n\n // Should QoS zero messages be queued when the connection is broken?\n this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero\n\n // map of subscribed topics to support reconnection\n this._resubscribeTopics = {}\n\n // map of a subscribe messageId and a topic\n this.messageIdToTopic = {}\n\n // Ping timer, setup in _setupPingTimer\n this.pingTimer = null\n // Is the client connected?\n this.connected = false\n // Are we disconnecting?\n this.disconnecting = false\n // Packet queue\n this.queue = []\n // connack timer\n this.connackTimer = null\n // Reconnect timer\n this.reconnectTimer = null\n // Is processing store?\n this._storeProcessing = false\n // Packet Ids are put into the store during store processing\n this._packetIdsDuringStoreProcessing = {}\n // Store processing queue\n this._storeProcessingQueue = []\n\n // Inflight callbacks\n this.outgoing = {}\n\n // True if connection is first time.\n this._firstConnection = true\n\n if (options.topicAliasMaximum > 0) {\n if (options.topicAliasMaximum > 0xffff) {\n debug('MqttClient :: options.topicAliasMaximum is out of range')\n } else {\n this.topicAliasRecv = new TopicAliasRecv(options.topicAliasMaximum)\n }\n }\n\n // Send queued packets\n this.on('connect', function () {\n const queue = this.queue\n\n function deliver () {\n const entry = queue.shift()\n debug('deliver :: entry %o', entry)\n let packet = null\n\n if (!entry) {\n that._resubscribe()\n return\n }\n\n packet = entry.packet\n debug('deliver :: call _sendPacket for %o', packet)\n let send = true\n if (packet.messageId && packet.messageId !== 0) {\n if (!that.messageIdProvider.register(packet.messageId)) {\n send = false\n }\n }\n if (send) {\n that._sendPacket(\n packet,\n function (err) {\n if (entry.cb) {\n entry.cb(err)\n }\n deliver()\n }\n )\n } else {\n debug('messageId: %d has already used. The message is skipped and removed.', packet.messageId)\n deliver()\n }\n }\n\n debug('connect :: sending queued packets')\n deliver()\n })\n\n this.on('close', function () {\n debug('close :: connected set to `false`')\n this.connected = false\n\n debug('close :: clearing connackTimer')\n clearTimeout(this.connackTimer)\n\n debug('close :: clearing ping timer')\n if (that.pingTimer !== null) {\n that.pingTimer.clear()\n that.pingTimer = null\n }\n\n if (this.topicAliasRecv) {\n this.topicAliasRecv.clear()\n }\n\n debug('close :: calling _setupReconnect')\n this._setupReconnect()\n })\n EventEmitter.call(this)\n\n debug('MqttClient :: setting up stream')\n this._setupStream()\n}\ninherits(MqttClient, EventEmitter)\n\n/**\n * setup the event handlers in the inner stream.\n *\n * @api private\n */\nMqttClient.prototype._setupStream = function () {\n const that = this\n const writable = new Writable()\n const parser = mqttPacket.parser(this.options)\n let completeParse = null\n const packets = []\n\n debug('_setupStream :: calling method to clear reconnect')\n this._clearReconnect()\n\n debug('_setupStream :: using streamBuilder provided to client to create stream')\n this.stream = this.streamBuilder(this)\n\n parser.on('packet', function (packet) {\n debug('parser :: on packet push to packets array.')\n packets.push(packet)\n })\n\n function nextTickWork () {\n if (packets.length) {\n nextTick(work)\n } else {\n const done = completeParse\n completeParse = null\n done()\n }\n }\n\n function work () {\n debug('work :: getting next packet in queue')\n const packet = packets.shift()\n\n if (packet) {\n debug('work :: packet pulled from queue')\n that._handlePacket(packet, nextTickWork)\n } else {\n debug('work :: no packets in queue')\n const done = completeParse\n completeParse = null\n debug('work :: done flag is %s', !!(done))\n if (done) done()\n }\n }\n\n writable._write = function (buf, enc, done) {\n completeParse = done\n debug('writable stream :: parsing buffer')\n parser.parse(buf)\n work()\n }\n\n function streamErrorHandler (error) {\n debug('streamErrorHandler :: error', error.message)\n if (socketErrors.includes(error.code)) {\n // handle error\n debug('streamErrorHandler :: emitting error')\n that.emit('error', error)\n } else {\n nop(error)\n }\n }\n\n debug('_setupStream :: pipe stream to writable stream')\n this.stream.pipe(writable)\n\n // Suppress connection errors\n this.stream.on('error', streamErrorHandler)\n\n // Echo stream close\n this.stream.on('close', function () {\n debug('(%s)stream :: on close', that.options.clientId)\n flushVolatile(that.outgoing)\n debug('stream: emit close to MqttClient')\n that.emit('close')\n })\n\n // Send a connect packet\n debug('_setupStream: sending packet `connect`')\n const connectPacket = Object.create(this.options)\n connectPacket.cmd = 'connect'\n if (this.topicAliasRecv) {\n if (!connectPacket.properties) {\n connectPacket.properties = {}\n }\n if (this.topicAliasRecv) {\n connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max\n }\n }\n // avoid message queue\n sendPacket(this, connectPacket)\n\n // Echo connection errors\n parser.on('error', this.emit.bind(this, 'error'))\n\n // auth\n if (this.options.properties) {\n if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {\n that.end(() =>\n this.emit('error', new Error('Packet has no Authentication Method')\n ))\n return this\n }\n if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {\n const authPacket = xtend({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket)\n sendPacket(this, authPacket)\n }\n }\n\n // many drain listeners are needed for qos 1 callbacks if the connection is intermittent\n this.stream.setMaxListeners(1000)\n\n clearTimeout(this.connackTimer)\n this.connackTimer = setTimeout(function () {\n debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')\n that._cleanUp(true)\n }, this.options.connectTimeout)\n}\n\nMqttClient.prototype._handlePacket = function (packet, done) {\n const options = this.options\n\n if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {\n this.emit('error', new Error('exceeding packets size ' + packet.cmd))\n this.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' } })\n return this\n }\n debug('_handlePacket :: emitting packetreceive')\n this.emit('packetreceive', packet)\n\n switch (packet.cmd) {\n case 'publish':\n this._handlePublish(packet, done)\n break\n case 'puback':\n case 'pubrec':\n case 'pubcomp':\n case 'suback':\n case 'unsuback':\n this._handleAck(packet)\n done()\n break\n case 'pubrel':\n this._handlePubrel(packet, done)\n break\n case 'connack':\n this._handleConnack(packet)\n done()\n break\n case 'auth':\n this._handleAuth(packet)\n done()\n break\n case 'pingresp':\n this._handlePingresp(packet)\n done()\n break\n case 'disconnect':\n this._handleDisconnect(packet)\n done()\n break\n default:\n // do nothing\n // maybe we should do an error handling\n // or just log it\n break\n }\n}\n\nMqttClient.prototype._checkDisconnecting = function (callback) {\n if (this.disconnecting) {\n if (callback && callback !== nop) {\n callback(new Error('client disconnecting'))\n } else {\n this.emit('error', new Error('client disconnecting'))\n }\n }\n return this.disconnecting\n}\n\n/**\n * publish - publish to \n *\n * @param {String} topic - topic to publish to\n * @param {String, Buffer} message - message to publish\n * @param {Object} [opts] - publish options, includes:\n * {Number} qos - qos level to publish on\n * {Boolean} retain - whether or not to retain the message\n * {Boolean} dup - whether or not mark a message as duplicate\n * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`\n * @param {Function} [callback] - function(err){}\n * called when publish succeeds or fails\n * @returns {MqttClient} this - for chaining\n * @api public\n *\n * @example client.publish('topic', 'message');\n * @example\n * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});\n * @example client.publish('topic', 'message', console.log);\n */\nMqttClient.prototype.publish = function (topic, message, opts, callback) {\n debug('publish :: message `%s` to topic `%s`', message, topic)\n const options = this.options\n\n // .publish(topic, payload, cb);\n if (typeof opts === 'function') {\n callback = opts\n opts = null\n }\n\n // default opts\n const defaultOpts = { qos: 0, retain: false, dup: false }\n opts = xtend(defaultOpts, opts)\n\n if (this._checkDisconnecting(callback)) {\n return this\n }\n\n const that = this\n const publishProc = function () {\n let messageId = 0\n if (opts.qos === 1 || opts.qos === 2) {\n messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n }\n const packet = {\n cmd: 'publish',\n topic: topic,\n payload: message,\n qos: opts.qos,\n retain: opts.retain,\n messageId: messageId,\n dup: opts.dup\n }\n\n if (options.protocolVersion === 5) {\n packet.properties = opts.properties\n }\n\n debug('publish :: qos', opts.qos)\n switch (opts.qos) {\n case 1:\n case 2:\n // Add to callbacks\n that.outgoing[packet.messageId] = {\n volatile: false,\n cb: callback || nop\n }\n debug('MqttClient:publish: packet cmd: %s', packet.cmd)\n that._sendPacket(packet, undefined, opts.cbStorePut)\n break\n default:\n debug('MqttClient:publish: packet cmd: %s', packet.cmd)\n that._sendPacket(packet, callback, opts.cbStorePut)\n break\n }\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: publishProc,\n cbStorePut: opts.cbStorePut,\n callback: callback\n }\n )\n }\n return this\n}\n\n/**\n * subscribe - subscribe to \n *\n * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}\n * @param {Object} [opts] - optional subscription options, includes:\n * {Number} qos - subscribe qos level\n * @param {Function} [callback] - function(err, granted){} where:\n * {Error} err - subscription error (none at the moment!)\n * {Array} granted - array of {topic: 't', qos: 0}\n * @returns {MqttClient} this - for chaining\n * @api public\n * @example client.subscribe('topic');\n * @example client.subscribe('topic', {qos: 1});\n * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);\n * @example client.subscribe('topic', console.log);\n */\nMqttClient.prototype.subscribe = function () {\n const that = this\n const args = new Array(arguments.length)\n for (let i = 0; i < arguments.length; i++) {\n args[i] = arguments[i]\n }\n const subs = []\n let obj = args.shift()\n const resubscribe = obj.resubscribe\n let callback = args.pop() || nop\n let opts = args.pop()\n const version = this.options.protocolVersion\n\n delete obj.resubscribe\n\n if (typeof obj === 'string') {\n obj = [obj]\n }\n\n if (typeof callback !== 'function') {\n opts = callback\n callback = nop\n }\n\n const invalidTopic = validations.validateTopics(obj)\n if (invalidTopic !== null) {\n setImmediate(callback, new Error('Invalid topic ' + invalidTopic))\n return this\n }\n\n if (this._checkDisconnecting(callback)) {\n debug('subscribe: discconecting true')\n return this\n }\n\n const defaultOpts = {\n qos: 0\n }\n if (version === 5) {\n defaultOpts.nl = false\n defaultOpts.rap = false\n defaultOpts.rh = 0\n }\n opts = xtend(defaultOpts, opts)\n\n if (Array.isArray(obj)) {\n obj.forEach(function (topic) {\n debug('subscribe: array topic %s', topic)\n if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||\n that._resubscribeTopics[topic].qos < opts.qos ||\n resubscribe) {\n const currentOpts = {\n topic: topic,\n qos: opts.qos\n }\n if (version === 5) {\n currentOpts.nl = opts.nl\n currentOpts.rap = opts.rap\n currentOpts.rh = opts.rh\n currentOpts.properties = opts.properties\n }\n debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)\n subs.push(currentOpts)\n }\n })\n } else {\n Object\n .keys(obj)\n .forEach(function (k) {\n debug('subscribe: object topic %s', k)\n if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||\n that._resubscribeTopics[k].qos < obj[k].qos ||\n resubscribe) {\n const currentOpts = {\n topic: k,\n qos: obj[k].qos\n }\n if (version === 5) {\n currentOpts.nl = obj[k].nl\n currentOpts.rap = obj[k].rap\n currentOpts.rh = obj[k].rh\n currentOpts.properties = opts.properties\n }\n debug('subscribe: pushing `%s` to subs list', currentOpts)\n subs.push(currentOpts)\n }\n })\n }\n\n if (!subs.length) {\n callback(null, [])\n return this\n }\n\n const subscribeProc = function () {\n const messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n\n const packet = {\n cmd: 'subscribe',\n subscriptions: subs,\n qos: 1,\n retain: false,\n dup: false,\n messageId: messageId\n }\n\n if (opts.properties) {\n packet.properties = opts.properties\n }\n\n // subscriptions to resubscribe to in case of disconnect\n if (that.options.resubscribe) {\n debug('subscribe :: resubscribe true')\n const topics = []\n subs.forEach(function (sub) {\n if (that.options.reconnectPeriod > 0) {\n const topic = { qos: sub.qos }\n if (version === 5) {\n topic.nl = sub.nl || false\n topic.rap = sub.rap || false\n topic.rh = sub.rh || 0\n topic.properties = sub.properties\n }\n that._resubscribeTopics[sub.topic] = topic\n topics.push(sub.topic)\n }\n })\n that.messageIdToTopic[packet.messageId] = topics\n }\n\n that.outgoing[packet.messageId] = {\n volatile: true,\n cb: function (err, packet) {\n if (!err) {\n const granted = packet.granted\n for (let i = 0; i < granted.length; i += 1) {\n subs[i].qos = granted[i]\n }\n }\n\n callback(err, subs)\n }\n }\n debug('subscribe :: call _sendPacket')\n that._sendPacket(packet)\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: subscribeProc,\n callback: callback\n }\n )\n }\n\n return this\n}\n\n/**\n * unsubscribe - unsubscribe from topic(s)\n *\n * @param {String, Array} topic - topics to unsubscribe from\n * @param {Object} [opts] - optional subscription options, includes:\n * {Object} properties - properties of unsubscribe packet\n * @param {Function} [callback] - callback fired on unsuback\n * @returns {MqttClient} this - for chaining\n * @api public\n * @example client.unsubscribe('topic');\n * @example client.unsubscribe('topic', console.log);\n */\nMqttClient.prototype.unsubscribe = function () {\n const that = this\n const args = new Array(arguments.length)\n for (let i = 0; i < arguments.length; i++) {\n args[i] = arguments[i]\n }\n let topic = args.shift()\n let callback = args.pop() || nop\n let opts = args.pop()\n if (typeof topic === 'string') {\n topic = [topic]\n }\n\n if (typeof callback !== 'function') {\n opts = callback\n callback = nop\n }\n\n const invalidTopic = validations.validateTopics(topic)\n if (invalidTopic !== null) {\n setImmediate(callback, new Error('Invalid topic ' + invalidTopic))\n return this\n }\n\n if (that._checkDisconnecting(callback)) {\n return this\n }\n\n const unsubscribeProc = function () {\n const messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n const packet = {\n cmd: 'unsubscribe',\n qos: 1,\n messageId: messageId\n }\n\n if (typeof topic === 'string') {\n packet.unsubscriptions = [topic]\n } else if (Array.isArray(topic)) {\n packet.unsubscriptions = topic\n }\n\n if (that.options.resubscribe) {\n packet.unsubscriptions.forEach(function (topic) {\n delete that._resubscribeTopics[topic]\n })\n }\n\n if (typeof opts === 'object' && opts.properties) {\n packet.properties = opts.properties\n }\n\n that.outgoing[packet.messageId] = {\n volatile: true,\n cb: callback\n }\n\n debug('unsubscribe: call _sendPacket')\n that._sendPacket(packet)\n\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: unsubscribeProc,\n callback: callback\n }\n )\n }\n\n return this\n}\n\n/**\n * end - close connection\n *\n * @returns {MqttClient} this - for chaining\n * @param {Boolean} force - do not wait for all in-flight messages to be acked\n * @param {Object} opts - added to the disconnect packet\n * @param {Function} cb - called when the client has been closed\n *\n * @api public\n */\nMqttClient.prototype.end = function (force, opts, cb) {\n const that = this\n\n debug('end :: (%s)', this.options.clientId)\n\n if (force == null || typeof force !== 'boolean') {\n cb = opts || nop\n opts = force\n force = false\n if (typeof opts !== 'object') {\n cb = opts\n opts = null\n if (typeof cb !== 'function') {\n cb = nop\n }\n }\n }\n\n if (typeof opts !== 'object') {\n cb = opts\n opts = null\n }\n\n debug('end :: cb? %s', !!cb)\n cb = cb || nop\n\n function closeStores () {\n debug('end :: closeStores: closing incoming and outgoing stores')\n that.disconnected = true\n that.incomingStore.close(function (e1) {\n that.outgoingStore.close(function (e2) {\n debug('end :: closeStores: emitting end')\n that.emit('end')\n if (cb) {\n const err = e1 || e2\n debug('end :: closeStores: invoking callback with args')\n cb(err)\n }\n })\n })\n if (that._deferredReconnect) {\n that._deferredReconnect()\n }\n }\n\n function finish () {\n // defer closesStores of an I/O cycle,\n // just to make sure things are\n // ok for websockets\n debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)\n that._cleanUp(force, () => {\n debug('end :: finish :: calling process.nextTick on closeStores')\n // const boundProcess = nextTick.bind(null, closeStores)\n nextTick(closeStores.bind(that))\n }, opts)\n }\n\n if (this.disconnecting) {\n cb()\n return this\n }\n\n this._clearReconnect()\n\n this.disconnecting = true\n\n if (!force && Object.keys(this.outgoing).length > 0) {\n // wait 10ms, just to be sure we received all of it\n debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)\n this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))\n } else {\n debug('end :: (%s) :: immediately calling finish', that.options.clientId)\n finish()\n }\n\n return this\n}\n\n/**\n * removeOutgoingMessage - remove a message in outgoing store\n * the outgoing callback will be called withe Error('Message removed') if the message is removed\n *\n * @param {Number} messageId - messageId to remove message\n * @returns {MqttClient} this - for chaining\n * @api public\n *\n * @example client.removeOutgoingMessage(client.getLastAllocated());\n */\nMqttClient.prototype.removeOutgoingMessage = function (messageId) {\n const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null\n delete this.outgoing[messageId]\n this.outgoingStore.del({ messageId: messageId }, function () {\n cb(new Error('Message removed'))\n })\n return this\n}\n\n/**\n * reconnect - connect again using the same options as connect()\n *\n * @param {Object} [opts] - optional reconnect options, includes:\n * {Store} incomingStore - a store for the incoming packets\n * {Store} outgoingStore - a store for the outgoing packets\n * if opts is not given, current stores are used\n * @returns {MqttClient} this - for chaining\n *\n * @api public\n */\nMqttClient.prototype.reconnect = function (opts) {\n debug('client reconnect')\n const that = this\n const f = function () {\n if (opts) {\n that.options.incomingStore = opts.incomingStore\n that.options.outgoingStore = opts.outgoingStore\n } else {\n that.options.incomingStore = null\n that.options.outgoingStore = null\n }\n that.incomingStore = that.options.incomingStore || new Store()\n that.outgoingStore = that.options.outgoingStore || new Store()\n that.disconnecting = false\n that.disconnected = false\n that._deferredReconnect = null\n that._reconnect()\n }\n\n if (this.disconnecting && !this.disconnected) {\n this._deferredReconnect = f\n } else {\n f()\n }\n return this\n}\n\n/**\n * _reconnect - implement reconnection\n * @api privateish\n */\nMqttClient.prototype._reconnect = function () {\n debug('_reconnect: emitting reconnect to client')\n this.emit('reconnect')\n if (this.connected) {\n this.end(() => { this._setupStream() })\n debug('client already connected. disconnecting first.')\n } else {\n debug('_reconnect: calling _setupStream')\n this._setupStream()\n }\n}\n\n/**\n * _setupReconnect - setup reconnect timer\n */\nMqttClient.prototype._setupReconnect = function () {\n const that = this\n\n if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {\n if (!this.reconnecting) {\n debug('_setupReconnect :: emit `offline` state')\n this.emit('offline')\n debug('_setupReconnect :: set `reconnecting` to `true`')\n this.reconnecting = true\n }\n debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)\n that.reconnectTimer = setInterval(function () {\n debug('reconnectTimer :: reconnect triggered!')\n that._reconnect()\n }, that.options.reconnectPeriod)\n } else {\n debug('_setupReconnect :: doing nothing...')\n }\n}\n\n/**\n * _clearReconnect - clear the reconnect timer\n */\nMqttClient.prototype._clearReconnect = function () {\n debug('_clearReconnect : clearing reconnect timer')\n if (this.reconnectTimer) {\n clearInterval(this.reconnectTimer)\n this.reconnectTimer = null\n }\n}\n\n/**\n * _cleanUp - clean up on connection end\n * @api private\n */\nMqttClient.prototype._cleanUp = function (forced, done) {\n const opts = arguments[2]\n if (done) {\n debug('_cleanUp :: done callback provided for on stream close')\n this.stream.on('close', done)\n }\n\n debug('_cleanUp :: forced? %s', forced)\n if (forced) {\n if ((this.options.reconnectPeriod === 0) && this.options.clean) {\n flush(this.outgoing)\n }\n debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)\n this.stream.destroy()\n } else {\n const packet = xtend({ cmd: 'disconnect' }, opts)\n debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)\n this._sendPacket(\n packet,\n setImmediate.bind(\n null,\n this.stream.end.bind(this.stream)\n )\n )\n }\n\n if (!this.disconnecting) {\n debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')\n this._clearReconnect()\n this._setupReconnect()\n }\n\n if (this.pingTimer !== null) {\n debug('_cleanUp :: clearing pingTimer')\n this.pingTimer.clear()\n this.pingTimer = null\n }\n\n if (done && !this.connected) {\n debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)\n this.stream.removeListener('close', done)\n done()\n }\n}\n\n/**\n * _sendPacket - send or queue a packet\n * @param {Object} packet - packet options\n * @param {Function} cb - callback when the packet is sent\n * @param {Function} cbStorePut - called when message is put into outgoingStore\n * @api private\n */\nMqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {\n debug('_sendPacket :: (%s) :: start', this.options.clientId)\n cbStorePut = cbStorePut || nop\n cb = cb || nop\n\n const err = applyTopicAlias(this, packet)\n if (err) {\n cb(err)\n return\n }\n\n if (!this.connected) {\n // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)\n if (packet.cmd === 'auth') {\n this._shiftPingInterval()\n sendPacket(this, packet, cb)\n return\n }\n\n debug('_sendPacket :: client not connected. Storing packet offline.')\n this._storePacket(packet, cb, cbStorePut)\n return\n }\n\n // When sending a packet, reschedule the ping timer\n this._shiftPingInterval()\n\n switch (packet.cmd) {\n case 'publish':\n break\n case 'pubrel':\n storeAndSend(this, packet, cb, cbStorePut)\n return\n default:\n sendPacket(this, packet, cb)\n return\n }\n\n switch (packet.qos) {\n case 2:\n case 1:\n storeAndSend(this, packet, cb, cbStorePut)\n break\n /**\n * no need of case here since it will be caught by default\n * and jshint comply that before default it must be a break\n * anyway it will result in -1 evaluation\n */\n case 0:\n /* falls through */\n default:\n sendPacket(this, packet, cb)\n break\n }\n debug('_sendPacket :: (%s) :: end', this.options.clientId)\n}\n\n/**\n * _storePacket - queue a packet\n * @param {Object} packet - packet options\n * @param {Function} cb - callback when the packet is sent\n * @param {Function} cbStorePut - called when message is put into outgoingStore\n * @api private\n */\nMqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {\n debug('_storePacket :: packet: %o', packet)\n debug('_storePacket :: cb? %s', !!cb)\n cbStorePut = cbStorePut || nop\n\n let storePacket = packet\n if (storePacket.cmd === 'publish') {\n // The original packet is for sending.\n // The cloned storePacket is for storing to resend on reconnect.\n // Topic Alias must not be used after disconnected.\n storePacket = clone(packet)\n const err = removeTopicAliasAndRecoverTopicName(this, storePacket)\n if (err) {\n return cb && cb(err)\n }\n }\n // check that the packet is not a qos of 0, or that the command is not a publish\n if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {\n this.queue.push({ packet: storePacket, cb: cb })\n } else if (storePacket.qos > 0) {\n cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null\n this.outgoingStore.put(storePacket, function (err) {\n if (err) {\n return cb && cb(err)\n }\n cbStorePut()\n })\n } else if (cb) {\n cb(new Error('No connection to broker'))\n }\n}\n\n/**\n * _setupPingTimer - setup the ping timer\n *\n * @api private\n */\nMqttClient.prototype._setupPingTimer = function () {\n debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)\n const that = this\n\n if (!this.pingTimer && this.options.keepalive) {\n this.pingResp = true\n this.pingTimer = reInterval(function () {\n that._checkPing()\n }, this.options.keepalive * 1000)\n }\n}\n\n/**\n * _shiftPingInterval - reschedule the ping interval\n *\n * @api private\n */\nMqttClient.prototype._shiftPingInterval = function () {\n if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {\n this.pingTimer.reschedule(this.options.keepalive * 1000)\n }\n}\n/**\n * _checkPing - check if a pingresp has come back, and ping the server again\n *\n * @api private\n */\nMqttClient.prototype._checkPing = function () {\n debug('_checkPing :: checking ping...')\n if (this.pingResp) {\n debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')\n this.pingResp = false\n this._sendPacket({ cmd: 'pingreq' })\n } else {\n // do a forced cleanup since socket will be in bad shape\n debug('_checkPing :: calling _cleanUp with force true')\n this._cleanUp(true)\n }\n}\n\n/**\n * _handlePingresp - handle a pingresp\n *\n * @api private\n */\nMqttClient.prototype._handlePingresp = function () {\n this.pingResp = true\n}\n\n/**\n * _handleConnack\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handleConnack = function (packet) {\n debug('_handleConnack')\n const options = this.options\n const version = options.protocolVersion\n const rc = version === 5 ? packet.reasonCode : packet.returnCode\n\n clearTimeout(this.connackTimer)\n delete this.topicAliasSend\n\n if (packet.properties) {\n if (packet.properties.topicAliasMaximum) {\n if (packet.properties.topicAliasMaximum > 0xffff) {\n this.emit('error', new Error('topicAliasMaximum from broker is out of range'))\n return\n }\n if (packet.properties.topicAliasMaximum > 0) {\n this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)\n }\n }\n if (packet.properties.serverKeepAlive && options.keepalive) {\n options.keepalive = packet.properties.serverKeepAlive\n this._shiftPingInterval()\n }\n if (packet.properties.maximumPacketSize) {\n if (!options.properties) { options.properties = {} }\n options.properties.maximumPacketSize = packet.properties.maximumPacketSize\n }\n }\n\n if (rc === 0) {\n this.reconnecting = false\n this._onConnect(packet)\n } else if (rc > 0) {\n const err = new Error('Connection refused: ' + errors[rc])\n err.code = rc\n this.emit('error', err)\n }\n}\n\nMqttClient.prototype._handleAuth = function (packet) {\n const options = this.options\n const version = options.protocolVersion\n const rc = version === 5 ? packet.reasonCode : packet.returnCode\n\n if (version !== 5) {\n const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)\n err.code = rc\n this.emit('error', err)\n return\n }\n\n const that = this\n this.handleAuth(packet, function (err, packet) {\n if (err) {\n that.emit('error', err)\n return\n }\n\n if (rc === 24) {\n that.reconnecting = false\n that._sendPacket(packet)\n } else {\n const error = new Error('Connection refused: ' + errors[rc])\n err.code = rc\n that.emit('error', error)\n }\n })\n}\n\n/**\n * @param packet the packet received by the broker\n * @return the auth packet to be returned to the broker\n * @api public\n */\nMqttClient.prototype.handleAuth = function (packet, callback) {\n callback()\n}\n\n/**\n * _handlePublish\n *\n * @param {Object} packet\n * @api private\n */\n/*\nthose late 2 case should be rewrite to comply with coding style:\n\ncase 1:\ncase 0:\n // do not wait sending a puback\n // no callback passed\n if (1 === qos) {\n this._sendPacket({\n cmd: 'puback',\n messageId: messageId\n });\n }\n // emit the message event for both qos 1 and 0\n this.emit('message', topic, message, packet);\n this.handleMessage(packet, done);\n break;\ndefault:\n // do nothing but every switch mus have a default\n // log or throw an error about unknown qos\n break;\n\nfor now i just suppressed the warnings\n*/\nMqttClient.prototype._handlePublish = function (packet, done) {\n debug('_handlePublish: packet %o', packet)\n done = typeof done !== 'undefined' ? done : nop\n let topic = packet.topic.toString()\n const message = packet.payload\n const qos = packet.qos\n const messageId = packet.messageId\n const that = this\n const options = this.options\n const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]\n if (this.options.protocolVersion === 5) {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n if (typeof alias !== 'undefined') {\n if (topic.length === 0) {\n if (alias > 0 && alias <= 0xffff) {\n const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)\n if (gotTopic) {\n topic = gotTopic\n debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)\n } else {\n debug('_handlePublish :: unregistered topic alias. alias: %d', alias)\n this.emit('error', new Error('Received unregistered Topic Alias'))\n return\n }\n } else {\n debug('_handlePublish :: topic alias out of range. alias: %d', alias)\n this.emit('error', new Error('Received Topic Alias is out of range'))\n return\n }\n } else {\n if (this.topicAliasRecv.put(topic, alias)) {\n debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)\n } else {\n debug('_handlePublish :: topic alias out of range. alias: %d', alias)\n this.emit('error', new Error('Received Topic Alias is out of range'))\n return\n }\n }\n }\n }\n debug('_handlePublish: qos %d', qos)\n switch (qos) {\n case 2: {\n options.customHandleAcks(topic, message, packet, function (error, code) {\n if (!(error instanceof Error)) {\n code = error\n error = null\n }\n if (error) { return that.emit('error', error) }\n if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }\n if (code) {\n that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)\n } else {\n that.incomingStore.put(packet, function () {\n that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)\n })\n }\n })\n break\n }\n case 1: {\n // emit the message event\n options.customHandleAcks(topic, message, packet, function (error, code) {\n if (!(error instanceof Error)) {\n code = error\n error = null\n }\n if (error) { return that.emit('error', error) }\n if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }\n if (!code) { that.emit('message', topic, message, packet) }\n that.handleMessage(packet, function (err) {\n if (err) {\n return done && done(err)\n }\n that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)\n })\n })\n break\n }\n case 0:\n // emit the message event\n this.emit('message', topic, message, packet)\n this.handleMessage(packet, done)\n break\n default:\n // do nothing\n debug('_handlePublish: unknown QoS. Doing nothing.')\n // log or throw an error about unknown qos\n break\n }\n}\n\n/**\n * Handle messages with backpressure support, one at a time.\n * Override at will.\n *\n * @param Packet packet the packet\n * @param Function callback call when finished\n * @api public\n */\nMqttClient.prototype.handleMessage = function (packet, callback) {\n callback()\n}\n\n/**\n * _handleAck\n *\n * @param {Object} packet\n * @api private\n */\n\nMqttClient.prototype._handleAck = function (packet) {\n /* eslint no-fallthrough: \"off\" */\n const messageId = packet.messageId\n const type = packet.cmd\n let response = null\n const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null\n const that = this\n let err\n\n // Checking `!cb` happens to work, but it's not technically \"correct\".\n //\n // Why? This code assumes that \"no callback\" is the same as that \"we're not\n // waiting for responses\" (puback, pubrec, pubcomp, suback, or unsuback).\n //\n // It would be better to check `if (!this.outgoing[messageId])` here, but\n // there's no reason to change it and risk (another) regression.\n //\n // The only reason this code works is becaues code in MqttClient.publish,\n // MqttClinet.subscribe, and MqttClient.unsubscribe ensures that we will\n // have a callback even if the user doesn't pass one in.)\n if (!cb) {\n debug('_handleAck :: Server sent an ack in error. Ignoring.')\n // Server sent an ack in error, ignore it.\n return\n }\n\n // Process\n debug('_handleAck :: packet type', type)\n switch (type) {\n case 'pubcomp':\n // same thing as puback for QoS 2\n case 'puback': {\n const pubackRC = packet.reasonCode\n // Callback - we're done\n if (pubackRC && pubackRC > 0 && pubackRC !== 16) {\n err = new Error('Publish error: ' + errors[pubackRC])\n err.code = pubackRC\n cb(err, packet)\n }\n delete this.outgoing[messageId]\n this.outgoingStore.del(packet, cb)\n this.messageIdProvider.deallocate(messageId)\n this._invokeStoreProcessingQueue()\n break\n }\n case 'pubrec': {\n response = {\n cmd: 'pubrel',\n qos: 2,\n messageId: messageId\n }\n const pubrecRC = packet.reasonCode\n\n if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {\n err = new Error('Publish error: ' + errors[pubrecRC])\n err.code = pubrecRC\n cb(err, packet)\n } else {\n this._sendPacket(response)\n }\n break\n }\n case 'suback': {\n delete this.outgoing[messageId]\n this.messageIdProvider.deallocate(messageId)\n for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {\n if ((packet.granted[grantedI] & 0x80) !== 0) {\n // suback with Failure status\n const topics = this.messageIdToTopic[messageId]\n if (topics) {\n topics.forEach(function (topic) {\n delete that._resubscribeTopics[topic]\n })\n }\n }\n }\n this._invokeStoreProcessingQueue()\n cb(null, packet)\n break\n }\n case 'unsuback': {\n delete this.outgoing[messageId]\n this.messageIdProvider.deallocate(messageId)\n this._invokeStoreProcessingQueue()\n cb(null)\n break\n }\n default:\n that.emit('error', new Error('unrecognized packet type'))\n }\n\n if (this.disconnecting &&\n Object.keys(this.outgoing).length === 0) {\n this.emit('outgoingEmpty')\n }\n}\n\n/**\n * _handlePubrel\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handlePubrel = function (packet, callback) {\n debug('handling pubrel packet')\n callback = typeof callback !== 'undefined' ? callback : nop\n const messageId = packet.messageId\n const that = this\n\n const comp = { cmd: 'pubcomp', messageId: messageId }\n\n that.incomingStore.get(packet, function (err, pub) {\n if (!err) {\n that.emit('message', pub.topic, pub.payload, pub)\n that.handleMessage(pub, function (err) {\n if (err) {\n return callback(err)\n }\n that.incomingStore.del(pub, nop)\n that._sendPacket(comp, callback)\n })\n } else {\n that._sendPacket(comp, callback)\n }\n })\n}\n\n/**\n * _handleDisconnect\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handleDisconnect = function (packet) {\n this.emit('disconnect', packet)\n}\n\n/**\n * _nextId\n * @return unsigned int\n */\nMqttClient.prototype._nextId = function () {\n return this.messageIdProvider.allocate()\n}\n\n/**\n * getLastMessageId\n * @return unsigned int\n */\nMqttClient.prototype.getLastMessageId = function () {\n return this.messageIdProvider.getLastAllocated()\n}\n\n/**\n * _resubscribe\n * @api private\n */\nMqttClient.prototype._resubscribe = function () {\n debug('_resubscribe')\n const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)\n if (!this._firstConnection &&\n (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&\n _resubscribeTopicsKeys.length > 0) {\n if (this.options.resubscribe) {\n if (this.options.protocolVersion === 5) {\n debug('_resubscribe: protocolVersion 5')\n for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {\n const resubscribeTopic = {}\n resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]\n resubscribeTopic.resubscribe = true\n this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })\n }\n } else {\n this._resubscribeTopics.resubscribe = true\n this.subscribe(this._resubscribeTopics)\n }\n } else {\n this._resubscribeTopics = {}\n }\n }\n\n this._firstConnection = false\n}\n\n/**\n * _onConnect\n *\n * @api private\n */\nMqttClient.prototype._onConnect = function (packet) {\n if (this.disconnected) {\n this.emit('connect', packet)\n return\n }\n\n const that = this\n\n this.connackPacket = packet\n this.messageIdProvider.clear()\n this._setupPingTimer()\n\n this.connected = true\n\n function startStreamProcess () {\n let outStore = that.outgoingStore.createStream()\n\n function clearStoreProcessing () {\n that._storeProcessing = false\n that._packetIdsDuringStoreProcessing = {}\n }\n\n that.once('close', remove)\n outStore.on('error', function (err) {\n clearStoreProcessing()\n that._flushStoreProcessingQueue()\n that.removeListener('close', remove)\n that.emit('error', err)\n })\n\n function remove () {\n outStore.destroy()\n outStore = null\n that._flushStoreProcessingQueue()\n clearStoreProcessing()\n }\n\n function storeDeliver () {\n // edge case, we wrapped this twice\n if (!outStore) {\n return\n }\n that._storeProcessing = true\n\n const packet = outStore.read(1)\n\n let cb\n\n if (!packet) {\n // read when data is available in the future\n outStore.once('readable', storeDeliver)\n return\n }\n\n // Skip already processed store packets\n if (that._packetIdsDuringStoreProcessing[packet.messageId]) {\n storeDeliver()\n return\n }\n\n // Avoid unnecessary stream read operations when disconnected\n if (!that.disconnecting && !that.reconnectTimer) {\n cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null\n that.outgoing[packet.messageId] = {\n volatile: false,\n cb: function (err, status) {\n // Ensure that the original callback passed in to publish gets invoked\n if (cb) {\n cb(err, status)\n }\n\n storeDeliver()\n }\n }\n that._packetIdsDuringStoreProcessing[packet.messageId] = true\n if (that.messageIdProvider.register(packet.messageId)) {\n that._sendPacket(packet)\n } else {\n debug('messageId: %d has already used.', packet.messageId)\n }\n } else if (outStore.destroy) {\n outStore.destroy()\n }\n }\n\n outStore.on('end', function () {\n let allProcessed = true\n for (const id in that._packetIdsDuringStoreProcessing) {\n if (!that._packetIdsDuringStoreProcessing[id]) {\n allProcessed = false\n break\n }\n }\n if (allProcessed) {\n clearStoreProcessing()\n that.removeListener('close', remove)\n that._invokeAllStoreProcessingQueue()\n that.emit('connect', packet)\n } else {\n startStreamProcess()\n }\n })\n storeDeliver()\n }\n // start flowing\n startStreamProcess()\n}\n\nMqttClient.prototype._invokeStoreProcessingQueue = function () {\n if (this._storeProcessingQueue.length > 0) {\n const f = this._storeProcessingQueue[0]\n if (f && f.invoke()) {\n this._storeProcessingQueue.shift()\n return true\n }\n }\n return false\n}\n\nMqttClient.prototype._invokeAllStoreProcessingQueue = function () {\n while (this._invokeStoreProcessingQueue()) { /* empty */ }\n}\n\nMqttClient.prototype._flushStoreProcessingQueue = function () {\n for (const f of this._storeProcessingQueue) {\n if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))\n if (f.callback) f.callback(new Error('Connection closed'))\n }\n this._storeProcessingQueue.splice(0)\n}\n\nmodule.exports = MqttClient\n","'use strict'\n\n/**\n * Topic Alias receiving manager\n * This holds alias to topic map\n * @param {Number} [max] - topic alias maximum entries\n */\nfunction TopicAliasRecv (max) {\n if (!(this instanceof TopicAliasRecv)) {\n return new TopicAliasRecv(max)\n }\n this.aliasToTopic = {}\n this.max = max\n}\n\n/**\n * Insert or update topic - alias entry.\n * @param {String} [topic] - topic\n * @param {Number} [alias] - topic alias\n * @returns {Boolean} - if success return true otherwise false\n */\nTopicAliasRecv.prototype.put = function (topic, alias) {\n if (alias === 0 || alias > this.max) {\n return false\n }\n this.aliasToTopic[alias] = topic\n this.length = Object.keys(this.aliasToTopic).length\n return true\n}\n\n/**\n * Get topic by alias\n * @param {String} [topic] - topic\n * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined\n */\nTopicAliasRecv.prototype.getTopicByAlias = function (alias) {\n return this.aliasToTopic[alias]\n}\n\n/**\n * Clear all entries\n */\nTopicAliasRecv.prototype.clear = function () {\n this.aliasToTopic = {}\n}\n\nmodule.exports = TopicAliasRecv\n","'use strict'\n\nconst MqttClient = require('../client')\nconst Store = require('../store')\nconst url = require('url')\nconst xtend = require('xtend')\nconst debug = require('debug')('mqttjs')\n\nconst protocols = {}\n\n// eslint-disable-next-line camelcase\nif ((typeof process !== 'undefined' && process.title !== 'browser') || typeof __webpack_require__ !== 'function') {\n protocols.mqtt = require('./tcp')\n protocols.tcp = require('./tcp')\n protocols.ssl = require('./tls')\n protocols.tls = require('./tls')\n protocols.mqtts = require('./tls')\n} else {\n protocols.wx = require('./wx')\n protocols.wxs = require('./wx')\n\n protocols.ali = require('./ali')\n protocols.alis = require('./ali')\n}\n\nprotocols.ws = require('./ws')\nprotocols.wss = require('./ws')\n\n/**\n * Parse the auth attribute and merge username and password in the options object.\n *\n * @param {Object} [opts] option object\n */\nfunction parseAuthOptions (opts) {\n let matches\n if (opts.auth) {\n matches = opts.auth.match(/^(.+):(.+)$/)\n if (matches) {\n opts.username = matches[1]\n opts.password = matches[2]\n } else {\n opts.username = opts.auth\n }\n }\n}\n\n/**\n * connect - connect to an MQTT broker.\n *\n * @param {String} [brokerUrl] - url of the broker, optional\n * @param {Object} opts - see MqttClient#constructor\n */\nfunction connect (brokerUrl, opts) {\n debug('connecting to an MQTT broker...')\n if ((typeof brokerUrl === 'object') && !opts) {\n opts = brokerUrl\n brokerUrl = null\n }\n\n opts = opts || {}\n\n if (brokerUrl) {\n // eslint-disable-next-line\n const parsed = url.parse(brokerUrl, true)\n if (parsed.port != null) {\n parsed.port = Number(parsed.port)\n }\n\n opts = xtend(parsed, opts)\n\n if (opts.protocol === null) {\n throw new Error('Missing protocol')\n }\n\n opts.protocol = opts.protocol.replace(/:$/, '')\n }\n\n // merge in the auth options if supplied\n parseAuthOptions(opts)\n\n // support clientId passed in the query string of the url\n if (opts.query && typeof opts.query.clientId === 'string') {\n opts.clientId = opts.query.clientId\n }\n\n if (opts.cert && opts.key) {\n if (opts.protocol) {\n if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {\n switch (opts.protocol) {\n case 'mqtt':\n opts.protocol = 'mqtts'\n break\n case 'ws':\n opts.protocol = 'wss'\n break\n case 'wx':\n opts.protocol = 'wxs'\n break\n case 'ali':\n opts.protocol = 'alis'\n break\n default:\n throw new Error('Unknown protocol for secure connection: \"' + opts.protocol + '\"!')\n }\n }\n } else {\n // A cert and key was provided, however no protocol was specified, so we will throw an error.\n throw new Error('Missing secure protocol key')\n }\n }\n\n if (!protocols[opts.protocol]) {\n const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1\n opts.protocol = [\n 'mqtt',\n 'mqtts',\n 'ws',\n 'wss',\n 'wx',\n 'wxs',\n 'ali',\n 'alis'\n ].filter(function (key, index) {\n if (isSecure && index % 2 === 0) {\n // Skip insecure protocols when requesting a secure one.\n return false\n }\n return (typeof protocols[key] === 'function')\n })[0]\n }\n\n if (opts.clean === false && !opts.clientId) {\n throw new Error('Missing clientId for unclean clients')\n }\n\n if (opts.protocol) {\n opts.defaultProtocol = opts.protocol\n }\n\n function wrapper (client) {\n if (opts.servers) {\n if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {\n client._reconnectCount = 0\n }\n\n opts.host = opts.servers[client._reconnectCount].host\n opts.port = opts.servers[client._reconnectCount].port\n opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)\n opts.hostname = opts.host\n\n client._reconnectCount++\n }\n\n debug('calling streambuilder for', opts.protocol)\n return protocols[opts.protocol](client, opts)\n }\n const client = new MqttClient(wrapper, opts)\n client.on('error', function () { /* Automatically set up client error handling */ })\n return client\n}\n\nmodule.exports = connect\nmodule.exports.connect = connect\nmodule.exports.MqttClient = MqttClient\nmodule.exports.Store = Store\n","'use strict'\n\n/**\n * Module dependencies\n */\nconst xtend = require('xtend')\n\nconst Readable = require('readable-stream').Readable\nconst streamsOpts = { objectMode: true }\nconst defaultStoreOptions = {\n clean: true\n}\n\n/**\n * In-memory implementation of the message store\n * This can actually be saved into files.\n *\n * @param {Object} [options] - store options\n */\nfunction Store (options) {\n if (!(this instanceof Store)) {\n return new Store(options)\n }\n\n this.options = options || {}\n\n // Defaults\n this.options = xtend(defaultStoreOptions, options)\n\n this._inflights = new Map()\n}\n\n/**\n * Adds a packet to the store, a packet is\n * anything that has a messageId property.\n *\n */\nStore.prototype.put = function (packet, cb) {\n this._inflights.set(packet.messageId, packet)\n\n if (cb) {\n cb()\n }\n\n return this\n}\n\n/**\n * Creates a stream with all the packets in the store\n *\n */\nStore.prototype.createStream = function () {\n const stream = new Readable(streamsOpts)\n const values = []\n let destroyed = false\n let i = 0\n\n this._inflights.forEach(function (value, key) {\n values.push(value)\n })\n\n stream._read = function () {\n if (!destroyed && i < values.length) {\n this.push(values[i++])\n } else {\n this.push(null)\n }\n }\n\n stream.destroy = function () {\n if (destroyed) {\n return\n }\n\n const self = this\n\n destroyed = true\n\n setTimeout(function () {\n self.emit('close')\n }, 0)\n }\n\n return stream\n}\n\n/**\n * deletes a packet from the store.\n */\nStore.prototype.del = function (packet, cb) {\n packet = this._inflights.get(packet.messageId)\n if (packet) {\n this._inflights.delete(packet.messageId)\n cb(null, packet)\n } else if (cb) {\n cb(new Error('missing packet'))\n }\n\n return this\n}\n\n/**\n * get a packet from the store.\n */\nStore.prototype.get = function (packet, cb) {\n packet = this._inflights.get(packet.messageId)\n if (packet) {\n cb(null, packet)\n } else if (cb) {\n cb(new Error('missing packet'))\n }\n\n return this\n}\n\n/**\n * Close the store\n */\nStore.prototype.close = function (cb) {\n if (this.options.clean) {\n this._inflights = null\n }\n if (cb) {\n cb()\n }\n}\n\nmodule.exports = Store\n","const max = 65536\nconst cache = {}\n\n// in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer\n// later versions return a Buffer\n// alternative is Buffer.slice but that creates a new buffer\n// creating new buffers takes time\n// SubOk is only false on node < 8\nconst SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1))\n\nfunction generateBuffer (i) {\n const buffer = Buffer.allocUnsafe(2)\n buffer.writeUInt8(i >> 8, 0)\n buffer.writeUInt8(i & 0x00FF, 0 + 1)\n\n return buffer\n}\n\nfunction generateCache () {\n for (let i = 0; i < max; i++) {\n cache[i] = generateBuffer(i)\n }\n}\n\nfunction genBufVariableByteInt (num) {\n const maxLength = 4 // max 4 bytes\n let digit = 0\n let pos = 0\n const buffer = Buffer.allocUnsafe(maxLength)\n\n do {\n digit = num % 128 | 0\n num = num / 128 | 0\n if (num > 0) digit = digit | 0x80\n\n buffer.writeUInt8(digit, pos++)\n } while (num > 0 && pos < maxLength)\n\n if (num > 0) {\n pos = 0\n }\n\n return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos)\n}\n\nfunction generate4ByteBuffer (num) {\n const buffer = Buffer.allocUnsafe(4)\n buffer.writeUInt32BE(num, 0)\n return buffer\n}\n\nmodule.exports = {\n cache,\n generateCache,\n generateNumber: generateBuffer,\n genBufVariableByteInt,\n generate4ByteBuffer\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst WS = require('ws')\nconst debug = require('debug')('mqttjs:ws')\nconst duplexify = require('duplexify')\nconst Transform = require('readable-stream').Transform\n\nconst WSS_OPTIONS = [\n 'rejectUnauthorized',\n 'ca',\n 'cert',\n 'key',\n 'pfx',\n 'passphrase'\n]\n// eslint-disable-next-line camelcase\nconst IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'\nfunction buildUrl (opts, client) {\n let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction setDefaultOpts (opts) {\n const options = opts\n if (!opts.hostname) {\n options.hostname = 'localhost'\n }\n if (!opts.port) {\n if (opts.protocol === 'wss') {\n options.port = 443\n } else {\n options.port = 80\n }\n }\n if (!opts.path) {\n options.path = '/'\n }\n\n if (!opts.wsOptions) {\n options.wsOptions = {}\n }\n if (!IS_BROWSER && opts.protocol === 'wss') {\n // Add cert/key/ca etc options\n WSS_OPTIONS.forEach(function (prop) {\n if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {\n options.wsOptions[prop] = opts[prop]\n }\n })\n }\n\n return options\n}\n\nfunction setDefaultBrowserOpts (opts) {\n const options = setDefaultOpts(opts)\n\n if (!options.hostname) {\n options.hostname = options.host\n }\n\n if (!options.hostname) {\n // Throwing an error in a Web Worker if no `hostname` is given, because we\n // can not determine the `hostname` automatically. If connecting to\n // localhost, please supply the `hostname` as an argument.\n if (typeof (document) === 'undefined') {\n throw new Error('Could not determine host. Specify host manually.')\n }\n const parsed = new URL(document.URL)\n options.hostname = parsed.hostname\n\n if (!options.port) {\n options.port = parsed.port\n }\n }\n\n // objectMode should be defined for logic\n if (options.objectMode === undefined) {\n options.objectMode = !(options.binary === true || options.binary === undefined)\n }\n\n return options\n}\n\nfunction createWebSocket (client, url, opts) {\n debug('createWebSocket')\n debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)\n const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)\n return socket\n}\n\nfunction createBrowserWebSocket (client, opts) {\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n const url = buildUrl(opts, client)\n /* global WebSocket */\n const socket = new WebSocket(url, [websocketSubProtocol])\n socket.binaryType = 'arraybuffer'\n return socket\n}\n\nfunction streamBuilder (client, opts) {\n debug('streamBuilder')\n const options = setDefaultOpts(opts)\n const url = buildUrl(options, client)\n const socket = createWebSocket(client, url, options)\n const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)\n webSocketStream.url = url\n socket.on('close', () => { webSocketStream.destroy() })\n return webSocketStream\n}\n\nfunction browserStreamBuilder (client, opts) {\n debug('browserStreamBuilder')\n let stream\n const options = setDefaultBrowserOpts(opts)\n // sets the maximum socket buffer size before throttling\n const bufferSize = options.browserBufferSize || 1024 * 512\n\n const bufferTimeout = opts.browserBufferTimeout || 1000\n\n const coerceToBuffer = !opts.objectMode\n\n const socket = createBrowserWebSocket(client, opts)\n\n const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)\n\n if (!opts.objectMode) {\n proxy._writev = writev\n }\n proxy.on('close', () => { socket.close() })\n\n const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')\n\n // was already open when passed in\n if (socket.readyState === socket.OPEN) {\n stream = proxy\n } else {\n stream = stream = duplexify(undefined, undefined, opts)\n if (!opts.objectMode) {\n stream._writev = writev\n }\n\n if (eventListenerSupport) {\n socket.addEventListener('open', onopen)\n } else {\n socket.onopen = onopen\n }\n }\n\n stream.socket = socket\n\n if (eventListenerSupport) {\n socket.addEventListener('close', onclose)\n socket.addEventListener('error', onerror)\n socket.addEventListener('message', onmessage)\n } else {\n socket.onclose = onclose\n socket.onerror = onerror\n socket.onmessage = onmessage\n }\n\n // methods for browserStreamBuilder\n\n function buildProxy (options, socketWrite, socketEnd) {\n const proxy = new Transform({\n objectModeMode: options.objectMode\n })\n\n proxy._write = socketWrite\n proxy._flush = socketEnd\n\n return proxy\n }\n\n function onopen () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n }\n\n function onclose () {\n stream.end()\n stream.destroy()\n }\n\n function onerror (err) {\n stream.destroy(err)\n }\n\n function onmessage (event) {\n let data = event.data\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n }\n\n // this is to be enabled only if objectMode is false\n function writev (chunks, cb) {\n const buffers = new Array(chunks.length)\n for (let i = 0; i < chunks.length; i++) {\n if (typeof chunks[i].chunk === 'string') {\n buffers[i] = Buffer.from(chunks[i], 'utf8')\n } else {\n buffers[i] = chunks[i].chunk\n }\n }\n\n this._write(Buffer.concat(buffers), 'binary', cb)\n }\n\n function socketWriteBrowser (chunk, enc, next) {\n if (socket.bufferedAmount > bufferSize) {\n // throttle data until buffered amount is reduced.\n setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)\n }\n\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8')\n }\n\n try {\n socket.send(chunk)\n } catch (err) {\n return next(err)\n }\n\n next()\n }\n\n function socketEndBrowser (done) {\n socket.close()\n done()\n }\n\n // end methods for browserStreamBuilder\n\n return stream\n}\n\nif (IS_BROWSER) {\n module.exports = browserStreamBuilder\n} else {\n module.exports = streamBuilder\n}\n","'use strict'\nconst tls = require('tls')\nconst net = require('net')\nconst debug = require('debug')('mqttjs:tls')\n\nfunction buildBuilder (mqttClient, opts) {\n opts.port = opts.port || 8883\n opts.host = opts.hostname || opts.host || 'localhost'\n\n if (net.isIP(opts.host) === 0) {\n opts.servername = opts.host\n }\n\n opts.rejectUnauthorized = opts.rejectUnauthorized !== false\n\n delete opts.path\n\n debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)\n\n const connection = tls.connect(opts)\n /* eslint no-use-before-define: [2, \"nofunc\"] */\n connection.on('secureConnect', function () {\n if (opts.rejectUnauthorized && !connection.authorized) {\n connection.emit('error', new Error('TLS not authorized'))\n } else {\n connection.removeListener('error', handleTLSerrors)\n }\n })\n\n function handleTLSerrors (err) {\n // How can I get verify this error is a tls error?\n if (opts.rejectUnauthorized) {\n mqttClient.emit('error', err)\n }\n\n // close this connection to match the behaviour of net\n // otherwise all we get is an error from the connection\n // and close event doesn't fire. This is a work around\n // to enable the reconnect code to work the same as with\n // net.createConnection\n connection.end()\n }\n\n connection.on('error', handleTLSerrors)\n return connection\n}\n\nmodule.exports = buildBuilder\n"],"sourceRoot":""}