text: (function webpackUniversalModuleDefinition(root, factory) {
  	if(typeof exports === 'object' && typeof module === 'object')
  		module.exports = factory();
  	else if(typeof define === 'function' && define.amd)
  		define([], factory);
  	else if(typeof exports === 'object')
  		exports["TencentIotSdk"] = factory();
  	else
  		root["TencentIotSdk"] = factory();
  })(window, function() {
  return /******/ (function(modules) { // webpackBootstrap
  /******/ 	// The module cache
  /******/ 	var installedModules = {};
  /******/
  /******/ 	// The require function
  /******/ 	function __webpack_require__(moduleId) {
  /******/
  /******/ 		// Check if module is in cache
  /******/ 		if(installedModules[moduleId]) {
  /******/ 			return installedModules[moduleId].exports;
  /******/ 		}
  /******/ 		// Create a new module (and put it into the cache)
  /******/ 		var module = installedModules[moduleId] = {
  /******/ 			i: moduleId,
  /******/ 			l: false,
  /******/ 			exports: {}
  /******/ 		};
  /******/
  /******/ 		// Execute the module function
  /******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  /******/
  /******/ 		// Flag the module as loaded
  /******/ 		module.l = true;
  /******/
  /******/ 		// Return the exports of the module
  /******/ 		return module.exports;
  /******/ 	}
  /******/
  /******/
  /******/ 	// expose the modules object (__webpack_modules__)
  /******/ 	__webpack_require__.m = modules;
  /******/
  /******/ 	// expose the module cache
  /******/ 	__webpack_require__.c = installedModules;
  /******/
  /******/ 	// define getter function for harmony exports
  /******/ 	__webpack_require__.d = function(exports, name, getter) {
  /******/ 		if(!__webpack_require__.o(exports, name)) {
  /******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
  /******/ 		}
  /******/ 	};
  /******/
  /******/ 	// define __esModule on exports
  /******/ 	__webpack_require__.r = function(exports) {
  /******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  /******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  /******/ 		}
  /******/ 		Object.defineProperty(exports, '__esModule', { value: true });
  /******/ 	};
  /******/
  /******/ 	// create a fake namespace object
  /******/ 	// mode & 1: value is a module id, require it
  /******/ 	// mode & 2: merge all properties of value into the ns
  /******/ 	// mode & 4: return value when already ns object
  /******/ 	// mode & 8|1: behave like require
  /******/ 	__webpack_require__.t = function(value, mode) {
  /******/ 		if(mode & 1) value = __webpack_require__(value);
  /******/ 		if(mode & 8) return value;
  /******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  /******/ 		var ns = Object.create(null);
  /******/ 		__webpack_require__.r(ns);
  /******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  /******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  /******/ 		return ns;
  /******/ 	};
  /******/
  /******/ 	// getDefaultExport function for compatibility with non-harmony modules
  /******/ 	__webpack_require__.n = function(module) {
  /******/ 		var getter = module && module.__esModule ?
  /******/ 			function getDefault() { return module['default']; } :
  /******/ 			function getModuleExports() { return module; };
  /******/ 		__webpack_require__.d(getter, 'a', getter);
  /******/ 		return getter;
  /******/ 	};
  /******/
  /******/ 	// Object.prototype.hasOwnProperty.call
  /******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  /******/
  /******/ 	// __webpack_public_path__
  /******/ 	__webpack_require__.p = "";
  /******/
  /******/
  /******/ 	// Load entry module and return exports
  /******/ 	return __webpack_require__(__webpack_require__.s = "./src/sdk.js");
  /******/ })
  /************************************************************************/
  /******/ ({
  
  /***/ "./node_modules/debug/node_modules/ms/index.js":
  /*!*****************************************************!*\
    !*** ./node_modules/debug/node_modules/ms/index.js ***!
    \*****************************************************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  
  /**
   * Helpers.
   */
  var s = 1000;
  var m = s * 60;
  var h = m * 60;
  var d = h * 24;
  var w = d * 7;
  var y = d * 365.25;
  /**
   * Parse or format the given `val`.
   *
   * Options:
   *
   *  - `long` verbose formatting [false]
   *
   * @param {String|Number} val
   * @param {Object} [options]
   * @throws {Error} throw an error if val is not a non-empty string or a number
   * @return {String|Number}
   * @api public
   */
  
  module.exports = function (val, options) {
    options = options || {};
  
    var type = _typeof(val);
  
    if (type === 'string' && val.length > 0) {
      return parse(val);
    } else if (type === 'number' && isNaN(val) === false) {
      return options.long ? fmtLong(val) : fmtShort(val);
    }
  
    throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
  };
  /**
   * Parse the given `str` and return milliseconds.
   *
   * @param {String} str
   * @return {Number}
   * @api private
   */
  
  
  function parse(str) {
    str = String(str);
  
    if (str.length > 100) {
      return;
    }
  
    var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
  
    if (!match) {
      return;
    }
  
    var n = parseFloat(match[1]);
    var type = (match[2] || 'ms').toLowerCase();
  
    switch (type) {
      case 'years':
      case 'year':
      case 'yrs':
      case 'yr':
      case 'y':
        return n * y;
  
      case 'weeks':
      case 'week':
      case 'w':
        return n * w;
  
      case 'days':
      case 'day':
      case 'd':
        return n * d;
  
      case 'hours':
      case 'hour':
      case 'hrs':
      case 'hr':
      case 'h':
        return n * h;
  
      case 'minutes':
      case 'minute':
      case 'mins':
      case 'min':
      case 'm':
        return n * m;
  
      case 'seconds':
      case 'second':
      case 'secs':
      case 'sec':
      case 's':
        return n * s;
  
      case 'milliseconds':
      case 'millisecond':
      case 'msecs':
      case 'msec':
      case 'ms':
        return n;
  
      default:
        return undefined;
    }
  }
  /**
   * Short format for `ms`.
   *
   * @param {Number} ms
   * @return {String}
   * @api private
   */
  
  
  function fmtShort(ms) {
    var msAbs = Math.abs(ms);
  
    if (msAbs >= d) {
      return Math.round(ms / d) + 'd';
    }
  
    if (msAbs >= h) {
      return Math.round(ms / h) + 'h';
    }
  
    if (msAbs >= m) {
      return Math.round(ms / m) + 'm';
    }
  
    if (msAbs >= s) {
      return Math.round(ms / s) + 's';
    }
  
    return ms + 'ms';
  }
  /**
   * Long format for `ms`.
   *
   * @param {Number} ms
   * @return {String}
   * @api private
   */
  
  
  function fmtLong(ms) {
    var msAbs = Math.abs(ms);
  
    if (msAbs >= d) {
      return plural(ms, msAbs, d, 'day');
    }
  
    if (msAbs >= h) {
      return plural(ms, msAbs, h, 'hour');
    }
  
    if (msAbs >= m) {
      return plural(ms, msAbs, m, 'minute');
    }
  
    if (msAbs >= s) {
      return plural(ms, msAbs, s, 'second');
    }
  
    return ms + ' ms';
  }
  /**
   * Pluralization helper.
   */
  
  
  function plural(ms, msAbs, n, name) {
    var isPlural = msAbs >= n * 1.5;
    return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  }
  
  /***/ }),
  
  /***/ "./node_modules/debug/src/browser.js":
  /*!*******************************************!*\
    !*** ./node_modules/debug/src/browser.js ***!
    \*******************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  "use strict";
  /* WEBPACK VAR INJECTION */(function(process) {
  
  function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
  
  function _typeof(obj) {
    if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
      _typeof = function _typeof(obj) {
        return _typeof2(obj);
      };
    } else {
      _typeof = function _typeof(obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
      };
    }
  
    return _typeof(obj);
  }
  /* eslint-env browser */
  
  /**
   * This is the web browser implementation of `debug()`.
   */
  
  
  exports.log = log;
  exports.formatArgs = formatArgs;
  exports.save = save;
  exports.load = load;
  exports.useColors = useColors;
  exports.storage = localstorage();
  /**
   * Colors.
   */
  
  exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  /**
   * Currently only WebKit-based Web Inspectors, Firefox >= v31,
   * and the Firebug extension (any Firefox version) are known
   * to support "%c" CSS customizations.
   *
   * TODO: add a `localStorage` variable to explicitly enable/disable colors
   */
  // eslint-disable-next-line complexity
  
  function useColors() {
    // NB: In an Electron preload script, document will be defined but not fully
    // initialized. Since we know we're in Chrome, we'll just detect this case
    // explicitly
    if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
      return true;
    } // Internet Explorer and Edge do not support colors.
  
  
    if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
      return false;
    } // Is webkit? http://stackoverflow.com/a/16459606/376773
    // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  
  
    return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
    typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
    typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  }
  /**
   * Colorize log arguments if enabled.
   *
   * @api public
   */
  
  
  function formatArgs(args) {
    args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  
    if (!this.useColors) {
      return;
    }
  
    var c = 'color: ' + this.color;
    args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
    // arguments passed either before or after the %c, so we need to
    // figure out the correct index to insert the CSS into
  
    var index = 0;
    var lastC = 0;
    args[0].replace(/%[a-zA-Z%]/g, function (match) {
      if (match === '%%') {
        return;
      }
  
      index++;
  
      if (match === '%c') {
        // We only are interested in the *last* %c
        // (the user may have provided their own)
        lastC = index;
      }
    });
    args.splice(lastC, 0, c);
  }
  /**
   * Invokes `console.log()` when available.
   * No-op when `console.log` is not a "function".
   *
   * @api public
   */
  
  
  function log() {
    var _console; // This hackery is required for IE8/9, where
    // the `console.log` function doesn't have 'apply'
  
  
    return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  }
  /**
   * Save `namespaces`.
   *
   * @param {String} namespaces
   * @api private
   */
  
  
  function save(namespaces) {
    try {
      if (namespaces) {
        exports.storage.setItem('debug', namespaces);
      } else {
        exports.storage.removeItem('debug');
      }
    } catch (error) {// Swallow
      // XXX (@Qix-) should we be logging these?
    }
  }
  /**
   * Load `namespaces`.
   *
   * @return {String} returns the previously persisted debug modes
   * @api private
   */
  
  
  function load() {
    var r;
  
    try {
      r = exports.storage.getItem('debug');
    } catch (error) {} // Swallow
    // XXX (@Qix-) should we be logging these?
    // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  
  
    if (!r && typeof process !== 'undefined' && 'env' in process) {
      r = process.env.DEBUG;
    }
  
    return r;
  }
  /**
   * Localstorage attempts to return the localstorage.
   *
   * This is necessary because safari throws
   * when a user disables cookies/localstorage
   * and you attempt to access it.
   *
   * @return {LocalStorage}
   * @api private
   */
  
  
  function localstorage() {
    try {
      // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
      // The Browser also has localStorage in the global context.
      return localStorage;
    } catch (error) {// Swallow
      // XXX (@Qix-) should we be logging these?
    }
  }
  
  module.exports = __webpack_require__(/*! ./common */ "./node_modules/debug/src/common.js")(exports);
  var formatters = module.exports.formatters;
  /**
   * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
   */
  
  formatters.j = function (v) {
    try {
      return JSON.stringify(v);
    } catch (error) {
      return '[UnexpectedJSONParseError]: ' + error.message;
    }
  };
  /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js")))
  
  /***/ }),
  
  /***/ "./node_modules/debug/src/common.js":
  /*!******************************************!*\
    !*** ./node_modules/debug/src/common.js ***!
    \******************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  "use strict";
  
  /**
   * This is the common logic for both the Node.js and web browser
   * implementations of `debug()`.
   */
  
  function setup(env) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce;
    createDebug.disable = disable;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = __webpack_require__(/*! ms */ "./node_modules/debug/node_modules/ms/index.js");
    Object.keys(env).forEach(function (key) {
      createDebug[key] = env[key];
    });
    /**
    * Active `debug` instances.
    */
  
    createDebug.instances = [];
    /**
    * The currently active debug mode names, and names to skip.
    */
  
    createDebug.names = [];
    createDebug.skips = [];
    /**
    * Map of special "%n" handling functions, for the debug "format" argument.
    *
    * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
    */
  
    createDebug.formatters = {};
    /**
    * Selects a color for a debug namespace
    * @param {String} namespace The namespace string for the for the debug instance to be colored
    * @return {Number|String} An ANSI color code for the given namespace
    * @api private
    */
  
    function selectColor(namespace) {
      var hash = 0;
  
      for (var i = 0; i < namespace.length; i++) {
        hash = (hash << 5) - hash + namespace.charCodeAt(i);
        hash |= 0; // Convert to 32bit integer
      }
  
      return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
    }
  
    createDebug.selectColor = selectColor;
    /**
    * Create a debugger with the given `namespace`.
    *
    * @param {String} namespace
    * @return {Function}
    * @api public
    */
  
    function createDebug(namespace) {
      var prevTime;
  
      function debug() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        } // Disabled?
  
  
        if (!debug.enabled) {
          return;
        }
  
        var self = debug; // Set `diff` timestamp
  
        var curr = Number(new Date());
        var ms = curr - (prevTime || curr);
        self.diff = ms;
        self.prev = prevTime;
        self.curr = curr;
        prevTime = curr;
        args[0] = createDebug.coerce(args[0]);
  
        if (typeof args[0] !== 'string') {
          // Anything else let's inspect with %O
          args.unshift('%O');
        } // Apply any `formatters` transformations
  
  
        var index = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
          // If we encounter an escaped % then don't increase the array index
          if (match === '%%') {
            return match;
          }
  
          index++;
          var formatter = createDebug.formatters[format];
  
          if (typeof formatter === 'function') {
            var val = args[index];
            match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  
            args.splice(index, 1);
            index--;
          }
  
          return match;
        }); // Apply env-specific formatting (colors, etc.)
  
        createDebug.formatArgs.call(self, args);
        var logFn = self.log || createDebug.log;
        logFn.apply(self, args);
      }
  
      debug.namespace = namespace;
      debug.enabled = createDebug.enabled(namespace);
      debug.useColors = createDebug.useColors();
      debug.color = selectColor(namespace);
      debug.destroy = destroy;
      debug.extend = extend; // Debug.formatArgs = formatArgs;
      // debug.rawLog = rawLog;
      // env-specific initialization logic for debug instances
  
      if (typeof createDebug.init === 'function') {
        createDebug.init(debug);
      }
  
      createDebug.instances.push(debug);
      return debug;
    }
  
    function destroy() {
      var index = createDebug.instances.indexOf(this);
  
      if (index !== -1) {
        createDebug.instances.splice(index, 1);
        return true;
      }
  
      return false;
    }
  
    function extend(namespace, delimiter) {
      return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
    }
    /**
    * Enables a debug mode by namespaces. This can include modes
    * separated by a colon and wildcards.
    *
    * @param {String} namespaces
    * @api public
    */
  
  
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.names = [];
      createDebug.skips = [];
      var i;
      var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
      var len = split.length;
  
      for (i = 0; i < len; i++) {
        if (!split[i]) {
          // ignore empty strings
          continue;
        }
  
        namespaces = split[i].replace(/\*/g, '.*?');
  
        if (namespaces[0] === '-') {
          createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
        } else {
          createDebug.names.push(new RegExp('^' + namespaces + '$'));
        }
      }
  
      for (i = 0; i < createDebug.instances.length; i++) {
        var instance = createDebug.instances[i];
        instance.enabled = createDebug.enabled(instance.namespace);
      }
    }
    /**
    * Disable debug output.
    *
    * @api public
    */
  
  
    function disable() {
      createDebug.enable('');
    }
    /**
    * Returns true if the given mode name is enabled, false otherwise.
    *
    * @param {String} name
    * @return {Boolean}
    * @api public
    */
  
  
    function enabled(name) {
      if (name[name.length - 1] === '*') {
        return true;
      }
  
      var i;
      var len;
  
      for (i = 0, len = createDebug.skips.length; i < len; i++) {
        if (createDebug.skips[i].test(name)) {
          return false;
        }
      }
  
      for (i = 0, len = createDebug.names.length; i < len; i++) {
        if (createDebug.names[i].test(name)) {
          return true;
        }
      }
  
      return false;
    }
    /**
    * Coerce `val`.
    *
    * @param {Mixed} val
    * @return {Mixed}
    * @api private
    */
  
  
    function coerce(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
  
      return val;
    }
  
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  
  module.exports = setup;
  
  /***/ }),
  
  /***/ "./node_modules/events/events.js":
  /*!***************************************!*\
    !*** ./node_modules/events/events.js ***!
    \***************************************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  
  // Copyright Joyent, Inc. and other Node contributors.
  //
  // Permission is hereby granted, free of charge, to any person obtaining a
  // copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to permit
  // persons to whom the Software is furnished to do so, subject to the
  // following conditions:
  //
  // The above copyright notice and this permission notice shall be included
  // in all copies or substantial portions of the Software.
  //
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  // USE OR OTHER DEALINGS IN THE SOFTWARE.
  function EventEmitter() {
    this._events = this._events || {};
    this._maxListeners = this._maxListeners || undefined;
  }
  
  module.exports = EventEmitter; // Backwards-compat with node 0.10.x
  
  EventEmitter.EventEmitter = EventEmitter;
  EventEmitter.prototype._events = undefined;
  EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are
  // added to it. This is a useful default which helps finding memory leaks.
  
  EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows
  // that to be increased. Set to zero for unlimited.
  
  EventEmitter.prototype.setMaxListeners = function (n) {
    if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number');
    this._maxListeners = n;
    return this;
  };
  
  EventEmitter.prototype.emit = function (type) {
    var er, handler, len, args, i, listeners;
    if (!this._events) this._events = {}; // If there is no 'error' event listener then throw.
  
    if (type === 'error') {
      if (!this._events.error || isObject(this._events.error) && !this._events.error.length) {
        er = arguments[1];
  
        if (er instanceof Error) {
          throw er; // Unhandled 'error' event
        } else {
          // At least give some kind of context to the user
          var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
          err.context = er;
          throw err;
        }
      }
    }
  
    handler = this._events[type];
    if (isUndefined(handler)) return false;
  
    if (isFunction(handler)) {
      switch (arguments.length) {
        // fast cases
        case 1:
          handler.call(this);
          break;
  
        case 2:
          handler.call(this, arguments[1]);
          break;
  
        case 3:
          handler.call(this, arguments[1], arguments[2]);
          break;
        // slower
  
        default:
          args = Array.prototype.slice.call(arguments, 1);
          handler.apply(this, args);
      }
    } else if (isObject(handler)) {
      args = Array.prototype.slice.call(arguments, 1);
      listeners = handler.slice();
      len = listeners.length;
  
      for (i = 0; i < len; i++) {
        listeners[i].apply(this, args);
      }
    }
  
    return true;
  };
  
  EventEmitter.prototype.addListener = function (type, listener) {
    var m;
    if (!isFunction(listener)) throw TypeError('listener must be a function');
    if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
  
    if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener);
    if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object.
      this._events[type] = listener;else if (isObject(this._events[type])) // If we've already got an array, just append.
      this._events[type].push(listener);else // Adding the second element, need to change to array.
      this._events[type] = [this._events[type], listener]; // Check for listener leak
  
    if (isObject(this._events[type]) && !this._events[type].warned) {
      if (!isUndefined(this._maxListeners)) {
        m = this._maxListeners;
      } else {
        m = EventEmitter.defaultMaxListeners;
      }
  
      if (m && m > 0 && this._events[type].length > m) {
        this._events[type].warned = true;
        console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length);
  
        if (typeof console.trace === 'function') {
          // not supported in IE 10
          console.trace();
        }
      }
    }
  
    return this;
  };
  
  EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  
  EventEmitter.prototype.once = function (type, listener) {
    if (!isFunction(listener)) throw TypeError('listener must be a function');
    var fired = false;
  
    function g() {
      this.removeListener(type, g);
  
      if (!fired) {
        fired = true;
        listener.apply(this, arguments);
      }
    }
  
    g.listener = listener;
    this.on(type, g);
    return this;
  }; // emits a 'removeListener' event iff the listener was removed
  
  
  EventEmitter.prototype.removeListener = function (type, listener) {
    var list, position, length, i;
    if (!isFunction(listener)) throw TypeError('listener must be a function');
    if (!this._events || !this._events[type]) return this;
    list = this._events[type];
    length = list.length;
    position = -1;
  
    if (list === listener || isFunction(list.listener) && list.listener === listener) {
      delete this._events[type];
      if (this._events.removeListener) this.emit('removeListener', type, listener);
    } else if (isObject(list)) {
      for (i = length; i-- > 0;) {
        if (list[i] === listener || list[i].listener && list[i].listener === listener) {
          position = i;
          break;
        }
      }
  
      if (position < 0) return this;
  
      if (list.length === 1) {
        list.length = 0;
        delete this._events[type];
      } else {
        list.splice(position, 1);
      }
  
      if (this._events.removeListener) this.emit('removeListener', type, listener);
    }
  
    return this;
  };
  
  EventEmitter.prototype.removeAllListeners = function (type) {
    var key, listeners;
    if (!this._events) return this; // not listening for removeListener, no need to emit
  
    if (!this._events.removeListener) {
      if (arguments.length === 0) this._events = {};else if (this._events[type]) delete this._events[type];
      return this;
    } // emit removeListener for all listeners on all events
  
  
    if (arguments.length === 0) {
      for (key in this._events) {
        if (key === 'removeListener') continue;
        this.removeAllListeners(key);
      }
  
      this.removeAllListeners('removeListener');
      this._events = {};
      return this;
    }
  
    listeners = this._events[type];
  
    if (isFunction(listeners)) {
      this.removeListener(type, listeners);
    } else if (listeners) {
      // LIFO order
      while (listeners.length) {
        this.removeListener(type, listeners[listeners.length - 1]);
      }
    }
  
    delete this._events[type];
    return this;
  };
  
  EventEmitter.prototype.listeners = function (type) {
    var ret;
    if (!this._events || !this._events[type]) ret = [];else if (isFunction(this._events[type])) ret = [this._events[type]];else ret = this._events[type].slice();
    return ret;
  };
  
  EventEmitter.prototype.listenerCount = function (type) {
    if (this._events) {
      var evlistener = this._events[type];
      if (isFunction(evlistener)) return 1;else if (evlistener) return evlistener.length;
    }
  
    return 0;
  };
  
  EventEmitter.listenerCount = function (emitter, type) {
    return emitter.listenerCount(type);
  };
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  
  function isObject(arg) {
    return _typeof(arg) === 'object' && arg !== null;
  }
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  
  /***/ }),
  
  /***/ "./node_modules/process/browser.js":
  /*!*****************************************!*\
    !*** ./node_modules/process/browser.js ***!
    \*****************************************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  // shim for using process in browser
  var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  // don't break things.  But we need to wrap it in a try catch in case it is
  // wrapped in strict mode code which doesn't define any globals.  It's inside a
  // function because try/catches deoptimize in certain engines.
  
  var cachedSetTimeout;
  var cachedClearTimeout;
  
  function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
  }
  
  function defaultClearTimeout() {
    throw new Error('clearTimeout has not been defined');
  }
  
  (function () {
    try {
      if (typeof setTimeout === 'function') {
        cachedSetTimeout = setTimeout;
      } else {
        cachedSetTimeout = defaultSetTimout;
      }
    } catch (e) {
      cachedSetTimeout = defaultSetTimout;
    }
  
    try {
      if (typeof clearTimeout === 'function') {
        cachedClearTimeout = clearTimeout;
      } else {
        cachedClearTimeout = defaultClearTimeout;
      }
    } catch (e) {
      cachedClearTimeout = defaultClearTimeout;
    }
  })();
  
  function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
      //normal enviroments in sane situations
      return setTimeout(fun, 0);
    } // if setTimeout wasn't available but was latter defined
  
  
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
      cachedSetTimeout = setTimeout;
      return setTimeout(fun, 0);
    }
  
    try {
      // when when somebody has screwed with setTimeout but no I.E. maddness
      return cachedSetTimeout(fun, 0);
    } catch (e) {
      try {
        // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
        return cachedSetTimeout.call(null, fun, 0);
      } catch (e) {
        // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
        return cachedSetTimeout.call(this, fun, 0);
      }
    }
  }
  
  function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
      //normal enviroments in sane situations
      return clearTimeout(marker);
    } // if clearTimeout wasn't available but was latter defined
  
  
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
      cachedClearTimeout = clearTimeout;
      return clearTimeout(marker);
    }
  
    try {
      // when when somebody has screwed with setTimeout but no I.E. maddness
      return cachedClearTimeout(marker);
    } catch (e) {
      try {
        // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
        return cachedClearTimeout.call(null, marker);
      } catch (e) {
        // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
        // Some versions of I.E. have different rules for clearTimeout vs setTimeout
        return cachedClearTimeout.call(this, marker);
      }
    }
  }
  
  var queue = [];
  var draining = false;
  var currentQueue;
  var queueIndex = -1;
  
  function cleanUpNextTick() {
    if (!draining || !currentQueue) {
      return;
    }
  
    draining = false;
  
    if (currentQueue.length) {
      queue = currentQueue.concat(queue);
    } else {
      queueIndex = -1;
    }
  
    if (queue.length) {
      drainQueue();
    }
  }
  
  function drainQueue() {
    if (draining) {
      return;
    }
  
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;
    var len = queue.length;
  
    while (len) {
      currentQueue = queue;
      queue = [];
  
      while (++queueIndex < len) {
        if (currentQueue) {
          currentQueue[queueIndex].run();
        }
      }
  
      queueIndex = -1;
      len = queue.length;
    }
  
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
  }
  
  process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
  
    if (arguments.length > 1) {
      for (var i = 1; i < arguments.length; i++) {
        args[i - 1] = arguments[i];
      }
    }
  
    queue.push(new Item(fun, args));
  
    if (queue.length === 1 && !draining) {
      runTimeout(drainQueue);
    }
  }; // v8 likes predictible objects
  
  
  function Item(fun, array) {
    this.fun = fun;
    this.array = array;
  }
  
  Item.prototype.run = function () {
    this.fun.apply(null, this.array);
  };
  
  process.title = 'browser';
  process.browser = true;
  process.env = {};
  process.argv = [];
  process.version = ''; // empty string to avoid regexp issues
  
  process.versions = {};
  
  function noop() {}
  
  process.on = noop;
  process.addListener = noop;
  process.once = noop;
  process.off = noop;
  process.removeListener = noop;
  process.removeAllListeners = noop;
  process.emit = noop;
  process.prependListener = noop;
  process.prependOnceListener = noop;
  
  process.listeners = function (name) {
    return [];
  };
  
  process.binding = function (name) {
    throw new Error('process.binding is not supported');
  };
  
  process.cwd = function () {
    return '/';
  };
  
  process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
  };
  
  process.umask = function () {
    return 0;
  };
  
  /***/ }),
  
  /***/ "./src/env_detect.js":
  /*!***************************!*\
    !*** ./src/env_detect.js ***!
    \***************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  /* WEBPACK VAR INJECTION */(function(process) {exports.isMiniProgram = function () {
    // 通过关键 api 是否存在来判断小程序环境
    try {
      return !!(wx && wx.request && wx.connectSocket);
    } catch (e) {
      return false;
    }
  }();
  
  exports.isBrowser = function () {
    try {
      return typeof window !== 'undefined' && typeof window.document !== 'undefined';
    } catch (e) {
      return false;
    }
  }();
  
  exports.isNode = function () {
    try {
      return !!process.versions.node;
    } catch (e) {
      return false;
    }
  }();
  
  exports.isRN = function () {
    try {
      return navigator.product === 'ReactNative';
    } catch (e) {
      return false;
    }
  }();
  /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/process/browser.js */ "./node_modules/process/browser.js")))
  
  /***/ }),
  
  /***/ "./src/error_code.js":
  /*!***************************!*\
    !*** ./src/error_code.js ***!
    \***************************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  exports.SMARTIOT_TIMEOUT = 'SMARTIOT_TIMEOUT';
  
  /***/ }),
  
  /***/ "./src/helper.js":
  /*!***********************!*\
    !*** ./src/helper.js ***!
    \***********************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  exports.throttle = function (func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};
  
    var later = function later() {
      previous = options.leading === false ? 0 : Date.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
  
    var throttled = function throttled() {
      var now = Date.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
  
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
  
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
  
      return result;
    };
  
    throttled.cancel = function () {
      clearTimeout(timeout);
      previous = 0;
      timeout = context = args = null;
    };
  
    return throttled;
  };
  
  /***/ }),
  
  /***/ "./src/iot_web_socket.js":
  /*!*******************************!*\
    !*** ./src/iot_web_socket.js ***!
    \*******************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  
  function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  
  function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  
  function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  
  function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  
  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  
  function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  
  var EventEmitter = __webpack_require__(/*! events */ "./node_modules/events/events.js");
  
  var MyWebSocket = __webpack_require__(/*! ./my_web_socket */ "./src/my_web_socket.js");
  
  var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")('iot:iot_web_socket');
  
  var helper = __webpack_require__(/*! ./helper */ "./src/helper.js");
  
  var errorCode = __webpack_require__(/*! ./error_code */ "./src/error_code.js");
  
  var IotWebSocket =
  /*#__PURE__*/
  function (_EventEmitter) {
    _inherits(IotWebSocket, _EventEmitter);
  
    function IotWebSocket(options) {
      var _this;
  
      _classCallCheck(this, IotWebSocket);
  
      _this = _possibleConstructorReturn(this, _getPrototypeOf(IotWebSocket).call(this));
      _this.options = options || {};
      _this.url = options.url || 'wss://ws.qcloudsmartiot.com/'; // 心跳的间隔时间
  
      _this.hearbeatInterval = _this.options.hearbeatInterval || 20 * 1000;
      _this.reconnectInterval = _this.options.reconnectInterval || 1 * 1000;
      _this.ws = null;
      _this.isOpen = false; // 用来标记一个唯一的 reqId，每次使用后自增
  
      _this.reqIdCount = 0; // 记录 reqId 对应的处理函数
  
      _this.reqIdCallbacks = {};
      _this.callTimeout = _this.options.callTimeout || 5000; // 记录绑定的所有函数，在重启的时候恢复
  
      _this.onOpenCallbacks = [];
      _this.onCloseCallbacks = [];
      _this.onMessageCallbacks = [];
      _this.onErrorCallbacks = []; // 保存 setInterval 的结果
  
      _this.heartbeatTimer = null; // 连接未建立前，将send调用的消息放在这里
  
      _this.sendQueue = []; // reconnect 每个间隔只处理一次调用
  
      _this.reconnect = helper.throttle(_this._reconnect, _this.reconnectInterval); // 手动关闭
  
      _this.manuallyClose = false;
  
      _this.init();
  
      return _this;
    }
  
    _createClass(IotWebSocket, [{
      key: "init",
      value: function init() {
        var self = this;
        self.ws = new MyWebSocket(self.url, self.options); // 批量注册用户设定的事件函数
  
        [['onOpen', self.onOpenCallbacks], ['onClose', self.onCloseCallbacks], ['onMessage', self.onMessageCallbacks], ['onError', self.onErrorCallbacks]].forEach(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
              eventName = _ref2[0],
              eventCallbacks = _ref2[1];
  
          eventCallbacks.forEach(function (cb) {
            self.ws[eventName](cb);
          });
        });
        self.ws.onMessage(function (event) {
          var data;
  
          try {
            data = JSON.parse(event.data);
          } catch (e) {
            console.log("onMessage parse event.data error: ".concat(event.data));
            return;
          }
  
          debug("on message data: %o", data);
  
          if (data.push) {
            self.emit('push', data);
          } else if (data.reqId !== void 0 && self.reqIdCallbacks[data.reqId]) {
            self.reqIdCallbacks[data.reqId](data); // 这些 reqIdCallback 都是一次性的，要及时删除防止内存泄露
  
            delete self.reqIdCallbacks[data.reqId];
          }
        });
        self.ws.onOpen(function () {
          self.isOpen = true;
          self.sendQueue.forEach(function (data) {
            self.send(data);
          });
          self.sendQueue = [];
          self.initHeartbeat();
        });
        self.ws.onClose(function () {
          if (self.manuallyClose) {
            return;
          }
  
          self.reconnect();
        });
        self.ws.onError(function (err) {
          console.error('websocket on error', err.message);
          self.reconnect();
        });
      }
    }, {
      key: "initHeartbeat",
      value: function initHeartbeat() {
        var self = this;
        this.heartbeatTimer = setInterval(function () {
          self.heartbeat();
        }, self.hearbeatInterval);
      }
    }, {
      key: "heartbeat",
      value: function heartbeat() {
        var self = this;
        self.call('Hello');
      }
    }, {
      key: "_reconnect",
      value: function _reconnect() {
        this.isOpen = false;
        debug("reconnect");
        clearInterval(this.heartbeatTimer);
        this.init();
      }
    }, {
      key: "call",
      value: function call(action, params) {
        debug("call action %o, params %o", action, params);
        var self = this;
        var reqId = self.reqIdCount++;
        var successP = new Promise(function (resolve, reject) {
          var message = JSON.stringify({
            action: action,
            reqId: reqId,
            params: params
          });
  
          self.reqIdCallbacks[reqId] = function (response) {
            resolve(response);
          };
  
          self.send(message);
        }); // 在成功和超时的promises之间，取最早返回的那个
  
        var timeoutP = new Promise(function (resolve, reject) {
          setTimeout(function () {
            var e = new Error("call timeout. action: ".concat(action));
            e.code = errorCode.SMARTIOT_TIMEOUT;
            delete self.reqIdCallbacks[reqId];
            reject(e);
          }, self.callTimeout);
        });
        return Promise.race([successP, timeoutP]);
      }
    }, {
      key: "send",
      value: function send(data) {
        var self = this;
  
        if (!self.isOpen) {
          self.sendQueue.push(data);
          return;
        }
  
        this.ws.send(data);
      }
    }, {
      key: "close",
      value: function close(reconnect) {
        debug("closing websocket");
        clearInterval(this.heartbeatTimer);
  
        if (!reconnect) {
          this.manuallyClose = true;
        }
  
        this.ws.close.apply(this.ws, arguments);
      }
    }, {
      key: "onOpen",
      value: function onOpen(callback) {
        this.onOpenCallbacks.push(callback);
        this.ws.onOpen(callback);
      }
    }, {
      key: "onClose",
      value: function onClose(callback) {
        this.onCloseCallbacks.push(callback);
        this.ws.onClose(callback);
      }
    }, {
      key: "onMessage",
      value: function onMessage(callback) {
        this.onMessageCallbacks.push(callback);
        this.ws.onMessage(callback);
      }
    }, {
      key: "onError",
      value: function onError(callback) {
        this.onErrorCallbacks.push(callback);
        this.ws.onError(callback);
      }
    }]);
  
    return IotWebSocket;
  }(EventEmitter);
  
  exports = module.exports = IotWebSocket;
  
  /***/ }),
  
  /***/ "./src/my_web_socket.js":
  /*!******************************!*\
    !*** ./src/my_web_socket.js ***!
    \******************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  
  /*
  这是一个websocket的同构层，同构了小程序，h5与node.js的websocket调用。
   */
  var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")('iot:my_web_socket');
  
  var envDetect = __webpack_require__(/*! ./env_detect */ "./src/env_detect.js");
  
  var wsLib;
  
  if (envDetect.isNode) {
    wsLib = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'ws'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
  }
  
  var MyWebSocket =
  /*#__PURE__*/
  function () {
    function MyWebSocket(url, options) {
      _classCallCheck(this, MyWebSocket);
  
      this.options = options || {};
      this.url = url;
      this.origin = this.options.origin;
      this.wxWs = null;
      this.ws = null;
      this.initWs();
    }
  
    _createClass(MyWebSocket, [{
      key: "initWs",
      value: function initWs() {
        if (envDetect.isMiniProgram) {
          this.wxWs = wx.connectSocket({
            url: this.url,
            header: {
              origin: this.origin
            }
          });
        } else if (envDetect.isNode) {
          this.ws = new wsLib(this.url, {
            origin: this.origin
          });
        } else if (envDetect.isBrowser || envDetect.isRN) {
          this.ws = new WebSocket(this.url);
        }
      }
    }, {
      key: "send",
      value: function send(data) {
        if (envDetect.isMiniProgram) {
          this.wxWs.send({
            data: data
          });
        } else {
          this.ws.send(data);
        }
      }
    }, {
      key: "close",
      value: function close(code, reason) {
        if (envDetect.isMiniProgram) {
          this.wxWs.close({
            code: code,
            reason: reason
          });
        } else {
          this.ws.close(code, reason);
        }
      }
    }, {
      key: "onOpen",
      value: function onOpen(callback) {
        if (envDetect.isMiniProgram) {
          this.wxWs.onOpen(callback);
        } else {
          this.ws.addEventListener('open', callback);
        }
      }
    }, {
      key: "onClose",
      value: function onClose(callback) {
        if (envDetect.isMiniProgram) {
          this.wxWs.onClose(callback);
        } else {
          this.ws.addEventListener('close', callback);
        }
      }
    }, {
      key: "onMessage",
      value: function onMessage(callback) {
        if (envDetect.isMiniProgram) {
          this.wxWs.onMessage(callback);
        } else {
          this.ws.addEventListener('message', callback);
        }
      }
    }, {
      key: "onError",
      value: function onError(callback) {
        if (envDetect.isMiniProgram) {
          this.wxWs.onError(callback);
        } else {
          this.ws.addEventListener('error', callback);
        }
      }
    }]);
  
    return MyWebSocket;
  }();
  
  exports = module.exports = MyWebSocket;
  
  /***/ }),
  
  /***/ "./src/request.js":
  /*!************************!*\
    !*** ./src/request.js ***!
    \************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  
  /*
  这是一个 http 请求的同构层，同构了小程序，h5与node.js的websocket调用。
   */
  var envDetect = __webpack_require__(/*! ./env_detect */ "./src/env_detect.js");
  
  var axios;
  
  if (!envDetect.isMiniProgram) {
    axios = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'axios'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
  }
  
  var Request =
  /*#__PURE__*/
  function () {
    function Request(options) {
      _classCallCheck(this, Request);
  
      options = options || {};
      this.axios = axios;
    }
  
    _createClass(Request, [{
      key: "request",
      value: function request(options) {
        var self = this;
        options = self.transformReuqestOptions(options);
  
        if (envDetect.isMiniProgram) {
          return new Promise(function (resolve, reject) {
            var wxOptions = Object.assign({}, {
              success: function success(res) {
                resolve(res);
              },
              fail: function fail(err) {
                reject(err);
              }
            }, options);
            wx.request(wxOptions);
          });
        } else {
          var axiosOptions = {
            url: options.url,
            headers: options.header,
            method: options.method
          };
  
          if (options.method === 'GET') {
            axiosOptions.params = options.data;
          } else if (options.method === 'POST' && options.header['content-type'] === 'application/json') {
            axiosOptions.data = options.data;
          }
  
          return this.axios.request(axiosOptions).then(function (response) {
            return {
              data: response.data,
              statusCode: response.status,
              header: response.headers
            };
          });
        }
      }
    }, {
      key: "transformReuqestOptions",
      value: function transformReuqestOptions(options) {
        if (options.method) {
          options.method = options.method.toUpperCase();
        } else {
          options.method = 'GET';
        }
  
        if (options.method === 'POST') {
          options.header = options.header || {};
          options.header['content-type'] = options.header['content-type'] || 'application/json';
        }
  
        return options;
      }
    }]);
  
    return Request;
  }();
  
  module.exports = Request;
  
  /***/ }),
  
  /***/ "./src/sdk.js":
  /*!********************!*\
    !*** ./src/sdk.js ***!
    \********************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  
  var Request = __webpack_require__(/*! ./request */ "./src/request.js");
  
  var MyWebSocket = __webpack_require__(/*! ./my_web_socket */ "./src/my_web_socket.js");
  
  var IotWebSocket = __webpack_require__(/*! ./iot_web_socket */ "./src/iot_web_socket.js");
  
  var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")('iot:sdk');
  
  var Sdk =
  /*#__PURE__*/
  function () {
    function Sdk(options) {
      _classCallCheck(this, Sdk);
  
      options = options || {};
  
      if (!options.AppKey) {
        throw new Error('must provide `AppKey`');
      }
  
      this.AppKey = options.AppKey;
      this.AccessToken = options.AccessToken;
      this.request = new Request();
      this.ws = new IotWebSocket(options.wsOptions);
      this.init();
    }
  
    _createClass(Sdk, [{
      key: "init",
      value: function init() {
        var self = this;
        self.ws.onOpen(function () {
          self.activePush().catch(function (err) {
            debug("onOpen activePush ".concat(err));
          });
        });
      }
    }, {
      key: "callYunApi",
      value: function callYunApi(options) {
        var self = this;
        var Action = options.Action;
        var ActionParams = flattenArray(options.ActionParams);
        var Version = options.Version;
        var Region = options.Region;
        var WithAccessToken = options.WithAccessToken === void 0 ? true : options.WithAccessToken; // AccessToken 的默认值逻辑
  
        if (!ActionParams.AccessToken && self.AccessToken && WithAccessToken) {
          ActionParams.AccessToken = self.AccessToken;
        }
  
        return self.ws.call('YunApi', {
          AppKey: self.AppKey,
          Action: Action,
          Version: Version,
          Region: Region,
          ActionParams: ActionParams
        }).then(function (response) {
          return response.data.Response;
        });
      }
    }, {
      key: "bindAccessToken",
      value: function bindAccessToken(AccessToken) {
        var self = this;
        self.AccessToken = AccessToken;
        self.activePush().catch(function (err) {
          debug("activePush activePush ".concat(err));
        });
      }
    }, {
      key: "unbindAccessToken",
      value: function unbindAccessToken() {
        var self = this;
        self.AccessToken = null;
      } // activePush是个幂等操作，多次调用也没事。
  
    }, {
      key: "activePush",
      value: function activePush() {
        var self = this;
  
        if (self.AppKey && self.AccessToken) {
          return self.ws.call('ActivePush', {
            AppKey: self.AppKey,
            AccessToken: self.AccessToken
          });
        }
  
        return Promise.reject(new Error('Please ensure `AppKey` and `AccessToken` exist'));
      }
    }, {
      key: "call",
      value: function call() {
        return this.ws.call.apply(this.ws, arguments);
      }
      /*
      fn(dataObj);
       */
  
    }, {
      key: "onPush",
      value: function onPush(fn) {
        var self = this;
        self.ws.on('push', fn);
      }
    }]);
  
    return Sdk;
  }();
  
  exports = module.exports = Sdk;
  exports.Request = Request;
  exports.MyWebSocket = MyWebSocket;
  exports.IotWebSocket = IotWebSocket;
  /*
  腾讯云云api专用的一个参数转换方法
  用于将 {a: [1, 2, 3]} 转成 { 'a.0': 1, 'a.1': 2, 'a.2': 3 }
   */
  
  function flattenArray(input) {
    var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    var output = {};
  
    for (var key in input) {
      var value = input[key];
  
      if (_typeof(value) === 'object') {
        Object.assign(output, flattenArray(value, "".concat(prefix).concat(key, ".")));
      } else {
        output["".concat(prefix).concat(key)] = value;
      }
    }
  
    return output;
  }
  
  /***/ })
  
  /******/ });
  });
  //# sourceMappingURL=iot_sdk.miniprogram.js.map