text: (function UMDish(name, context, definition, plugins) {
    context[name] = definition.call(context);
    for (var i = 0; i < plugins.length; i++) {
      plugins[i](context[name])
    }
    if (typeof module !== "undefined" && module.exports) {
      module.exports = context[name];
    } else if (typeof define === "function" && define.amd) {
      define(function reference() { return context[name]; });
    }
  })("Primus", this || {}, function wrapper() {
    var define, module, exports
      , Primus = (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  'use strict';
  
  /**
   * Create a function that will cleanup the instance.
   *
   * @param {Array|String} keys Properties on the instance that needs to be cleared.
   * @param {Object} options Additional configuration.
   * @returns {Function} Destroy function
   * @api public
   */
  module.exports = function demolish(keys, options) {
    var split = /[, ]+/;
  
    options = options ||  {};
    keys = keys || [];
  
    if ('string' === typeof keys) keys = keys.split(split);
  
    /**
     * Run addition cleanup hooks.
     *
     * @param {String} key Name of the clean up hook to run.
     * @param {Mixed} selfie Reference to the instance we're cleaning up.
     * @api private
     */
    function run(key, selfie) {
      if (!options[key]) return;
      if ('string' === typeof options[key]) options[key] = options[key].split(split);
      if ('function' === typeof options[key]) return options[key].call(selfie);
  
      for (var i = 0, type, what; i < options[key].length; i++) {
        what = options[key][i];
        type = typeof what;
  
        if ('function' === type) {
          what.call(selfie);
        } else if ('string' === type && 'function' === typeof selfie[what]) {
          selfie[what]();
        }
      }
    }
  
    /**
     * Destroy the instance completely and clean up all the existing references.
     *
     * @returns {Boolean}
     * @api public
     */
    return function destroy() {
      var selfie = this
        , i = 0
        , prop;
  
      if (selfie[keys[0]] === null) return false;
      run('before', selfie);
  
      for (; i < keys.length; i++) {
        prop = keys[i];
  
        if (selfie[prop]) {
          if ('function' === typeof selfie[prop].destroy) selfie[prop].destroy();
          selfie[prop] = null;
        }
      }
  
      if (selfie.emit) selfie.emit('destroy');
      run('after', selfie);
  
      return true;
    };
  };
  
  },{}],2:[function(_dereq_,module,exports){
  'use strict';
  
  /**
   * Returns a function that when invoked executes all the listeners of the
   * given event with the given arguments.
   *
   * @returns {Function} The function that emits all the things.
   * @api public
   */
  module.exports = function emits() {
    var self = this
      , parser;
  
    for (var i = 0, l = arguments.length, args = new Array(l); i < l; i++) {
      args[i] = arguments[i];
    }
  
    //
    // If the last argument is a function, assume that it's a parser.
    //
    if ('function' !== typeof args[args.length - 1]) return function emitter() {
      for (var i = 0, l = arguments.length, arg = new Array(l); i < l; i++) {
        arg[i] = arguments[i];
      }
  
      return self.emit.apply(self, args.concat(arg));
    };
  
    parser = args.pop();
  
    /**
     * The actual function that emits the given event. It returns a boolean
     * indicating if the event was emitted.
     *
     * @returns {Boolean}
     * @api public
     */
    return function emitter() {
      for (var i = 0, l = arguments.length, arg = new Array(l + 1); i < l; i++) {
        arg[i + 1] = arguments[i];
      }
  
      /**
       * Async completion method for the parser.
       *
       * @param {Error} err Optional error when parsing failed.
       * @param {Mixed} returned Emit instructions.
       * @api private
       */
      arg[0] = function next(err, returned) {
        if (err) return self.emit('error', err);
  
        arg = returned === undefined
          ? arg.slice(1) : returned === null
            ? [] : returned;
  
        self.emit.apply(self, args.concat(arg));
      };
  
      parser.apply(self, arg);
      return true;
    };
  };
  
  },{}],3:[function(_dereq_,module,exports){
  'use strict';
  
  var has = Object.prototype.hasOwnProperty
    , prefix = '~';
  
  /**
   * Constructor to create a storage for our `EE` objects.
   * An `Events` instance is a plain object whose properties are event names.
   *
   * @constructor
   * @private
   */
  function Events() {}
  
  //
  // We try to not inherit from `Object.prototype`. In some engines creating an
  // instance in this way is faster than calling `Object.create(null)` directly.
  // If `Object.create(null)` is not supported we prefix the event names with a
  // character to make sure that the built-in object properties are not
  // overridden or used as an attack vector.
  //
  if (Object.create) {
    Events.prototype = Object.create(null);
  
    //
    // This hack is needed because the `__proto__` property is still inherited in
    // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
    //
    if (!new Events().__proto__) prefix = false;
  }
  
  /**
   * Representation of a single event listener.
   *
   * @param {Function} fn The listener function.
   * @param {*} context The context to invoke the listener with.
   * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
   * @constructor
   * @private
   */
  function EE(fn, context, once) {
    this.fn = fn;
    this.context = context;
    this.once = once || false;
  }
  
  /**
   * Add a listener for a given event.
   *
   * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
   * @param {(String|Symbol)} event The event name.
   * @param {Function} fn The listener function.
   * @param {*} context The context to invoke the listener with.
   * @param {Boolean} once Specify if the listener is a one-time listener.
   * @returns {EventEmitter}
   * @private
   */
  function addListener(emitter, event, fn, context, once) {
    if (typeof fn !== 'function') {
      throw new TypeError('The listener must be a function');
    }
  
    var listener = new EE(fn, context || emitter, once)
      , evt = prefix ? prefix + event : event;
  
    if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
    else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
    else emitter._events[evt] = [emitter._events[evt], listener];
  
    return emitter;
  }
  
  /**
   * Clear event by name.
   *
   * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
   * @param {(String|Symbol)} evt The Event name.
   * @private
   */
  function clearEvent(emitter, evt) {
    if (--emitter._eventsCount === 0) emitter._events = new Events();
    else delete emitter._events[evt];
  }
  
  /**
   * Minimal `EventEmitter` interface that is molded against the Node.js
   * `EventEmitter` interface.
   *
   * @constructor
   * @public
   */
  function EventEmitter() {
    this._events = new Events();
    this._eventsCount = 0;
  }
  
  /**
   * Return an array listing the events for which the emitter has registered
   * listeners.
   *
   * @returns {Array}
   * @public
   */
  EventEmitter.prototype.eventNames = function eventNames() {
    var names = []
      , events
      , name;
  
    if (this._eventsCount === 0) return names;
  
    for (name in (events = this._events)) {
      if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
    }
  
    if (Object.getOwnPropertySymbols) {
      return names.concat(Object.getOwnPropertySymbols(events));
    }
  
    return names;
  };
  
  /**
   * Return the listeners registered for a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @returns {Array} The registered listeners.
   * @public
   */
  EventEmitter.prototype.listeners = function listeners(event) {
    var evt = prefix ? prefix + event : event
      , handlers = this._events[evt];
  
    if (!handlers) return [];
    if (handlers.fn) return [handlers.fn];
  
    for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
      ee[i] = handlers[i].fn;
    }
  
    return ee;
  };
  
  /**
   * Return the number of listeners listening to a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @returns {Number} The number of listeners.
   * @public
   */
  EventEmitter.prototype.listenerCount = function listenerCount(event) {
    var evt = prefix ? prefix + event : event
      , listeners = this._events[evt];
  
    if (!listeners) return 0;
    if (listeners.fn) return 1;
    return listeners.length;
  };
  
  /**
   * Calls each of the listeners registered for a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @returns {Boolean} `true` if the event had listeners, else `false`.
   * @public
   */
  EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
    var evt = prefix ? prefix + event : event;
  
    if (!this._events[evt]) return false;
  
    var listeners = this._events[evt]
      , len = arguments.length
      , args
      , i;
  
    if (listeners.fn) {
      if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  
      switch (len) {
        case 1: return listeners.fn.call(listeners.context), true;
        case 2: return listeners.fn.call(listeners.context, a1), true;
        case 3: return listeners.fn.call(listeners.context, a1, a2), true;
        case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
        case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
        case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
      }
  
      for (i = 1, args = new Array(len -1); i < len; i++) {
        args[i - 1] = arguments[i];
      }
  
      listeners.fn.apply(listeners.context, args);
    } else {
      var length = listeners.length
        , j;
  
      for (i = 0; i < length; i++) {
        if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  
        switch (len) {
          case 1: listeners[i].fn.call(listeners[i].context); break;
          case 2: listeners[i].fn.call(listeners[i].context, a1); break;
          case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
          case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
          default:
            if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
              args[j - 1] = arguments[j];
            }
  
            listeners[i].fn.apply(listeners[i].context, args);
        }
      }
    }
  
    return true;
  };
  
  /**
   * Add a listener for a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @param {Function} fn The listener function.
   * @param {*} [context=this] The context to invoke the listener with.
   * @returns {EventEmitter} `this`.
   * @public
   */
  EventEmitter.prototype.on = function on(event, fn, context) {
    return addListener(this, event, fn, context, false);
  };
  
  /**
   * Add a one-time listener for a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @param {Function} fn The listener function.
   * @param {*} [context=this] The context to invoke the listener with.
   * @returns {EventEmitter} `this`.
   * @public
   */
  EventEmitter.prototype.once = function once(event, fn, context) {
    return addListener(this, event, fn, context, true);
  };
  
  /**
   * Remove the listeners of a given event.
   *
   * @param {(String|Symbol)} event The event name.
   * @param {Function} fn Only remove the listeners that match this function.
   * @param {*} context Only remove the listeners that have this context.
   * @param {Boolean} once Only remove one-time listeners.
   * @returns {EventEmitter} `this`.
   * @public
   */
  EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
    var evt = prefix ? prefix + event : event;
  
    if (!this._events[evt]) return this;
    if (!fn) {
      clearEvent(this, evt);
      return this;
    }
  
    var listeners = this._events[evt];
  
    if (listeners.fn) {
      if (
        listeners.fn === fn &&
        (!once || listeners.once) &&
        (!context || listeners.context === context)
      ) {
        clearEvent(this, evt);
      }
    } else {
      for (var i = 0, events = [], length = listeners.length; i < length; i++) {
        if (
          listeners[i].fn !== fn ||
          (once && !listeners[i].once) ||
          (context && listeners[i].context !== context)
        ) {
          events.push(listeners[i]);
        }
      }
  
      //
      // Reset the array, or remove it completely if we have no more listeners.
      //
      if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
      else clearEvent(this, evt);
    }
  
    return this;
  };
  
  /**
   * Remove all listeners, or those of the specified event.
   *
   * @param {(String|Symbol)} [event] The event name.
   * @returns {EventEmitter} `this`.
   * @public
   */
  EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
    var evt;
  
    if (event) {
      evt = prefix ? prefix + event : event;
      if (this._events[evt]) clearEvent(this, evt);
    } else {
      this._events = new Events();
      this._eventsCount = 0;
    }
  
    return this;
  };
  
  //
  // Alias methods names because people roll like that.
  //
  EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  
  //
  // Expose the prefix.
  //
  EventEmitter.prefixed = prefix;
  
  //
  // Allow `EventEmitter` to be imported as module namespace.
  //
  EventEmitter.EventEmitter = EventEmitter;
  
  //
  // Expose the module.
  //
  if ('undefined' !== typeof module) {
    module.exports = EventEmitter;
  }
  
  },{}],4:[function(_dereq_,module,exports){
  if (typeof Object.create === 'function') {
    // implementation from standard node.js 'util' module
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
    };
  } else {
    // old school shim for old browsers
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      var TempCtor = function () {}
      TempCtor.prototype = superCtor.prototype
      ctor.prototype = new TempCtor()
      ctor.prototype.constructor = ctor
    }
  }
  
  },{}],5:[function(_dereq_,module,exports){
  'use strict';
  
  var regex = new RegExp('^((?:\\d+)?\\.?\\d+) *('+ [
    'milliseconds?',
    'msecs?',
    'ms',
    'seconds?',
    'secs?',
    's',
    'minutes?',
    'mins?',
    'm',
    'hours?',
    'hrs?',
    'h',
    'days?',
    'd',
    'weeks?',
    'wks?',
    'w',
    'years?',
    'yrs?',
    'y'
  ].join('|') +')?$', 'i');
  
  var second = 1000
    , minute = second * 60
    , hour = minute * 60
    , day = hour * 24
    , week = day * 7
    , year = day * 365;
  
  /**
   * Parse a time string and return the number value of it.
   *
   * @param {String} ms Time string.
   * @returns {Number}
   * @api private
   */
  module.exports = function millisecond(ms) {
    var type = typeof ms
      , amount
      , match;
  
    if ('number' === type) return ms;
    else if ('string' !== type || '0' === ms || !ms) return 0;
    else if (+ms) return +ms;
  
    //
    // We are vulnerable to the regular expression denial of service (ReDoS).
    // In order to mitigate this we don't parse the input string if it is too long.
    // See https://nodesecurity.io/advisories/46.
    //
    if (ms.length > 10000 || !(match = regex.exec(ms))) return 0;
  
    amount = parseFloat(match[1]);
  
    switch (match[2].toLowerCase()) {
      case 'years':
      case 'year':
      case 'yrs':
      case 'yr':
      case 'y':
        return amount * year;
  
      case 'weeks':
      case 'week':
      case 'wks':
      case 'wk':
      case 'w':
        return amount * week;
  
      case 'days':
      case 'day':
      case 'd':
        return amount * day;
  
      case 'hours':
      case 'hour':
      case 'hrs':
      case 'hr':
      case 'h':
        return amount * hour;
  
      case 'minutes':
      case 'minute':
      case 'mins':
      case 'min':
      case 'm':
        return amount * minute;
  
      case 'seconds':
      case 'second':
      case 'secs':
      case 'sec':
      case 's':
        return amount * second;
  
      default:
        return amount;
    }
  };
  
  },{}],6:[function(_dereq_,module,exports){
  'use strict';
  
  /**
   * Wrap callbacks to prevent double execution.
   *
   * @param {Function} fn Function that should only be called once.
   * @returns {Function} A wrapped callback which prevents execution.
   * @api public
   */
  module.exports = function one(fn) {
    var called = 0
      , value;
  
    /**
     * The function that prevents double execution.
     *
     * @api private
     */
    function onetime() {
      if (called) return value;
  
      called = 1;
      value = fn.apply(this, arguments);
      fn = null;
  
      return value;
    }
  
    //
    // To make debugging more easy we want to use the name of the supplied
    // function. So when you look at the functions that are assigned to event
    // listeners you don't see a load of `onetime` functions but actually the
    // names of the functions that this module will call.
    //
    onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name;
    return onetime;
  };
  
  },{}],7:[function(_dereq_,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; };
  
  },{}],8:[function(_dereq_,module,exports){
  'use strict';
  
  var has = Object.prototype.hasOwnProperty;
  
  /**
   * Decode a URI encoded string.
   *
   * @param {String} input The URI encoded string.
   * @returns {String} The decoded string.
   * @api private
   */
  function decode(input) {
    return decodeURIComponent(input.replace(/\+/g, ' '));
  }
  
  /**
   * Simple query string parser.
   *
   * @param {String} query The query string that needs to be parsed.
   * @returns {Object}
   * @api public
   */
  function querystring(query) {
    var parser = /([^=?&]+)=?([^&]*)/g
      , result = {}
      , part;
  
    while (part = parser.exec(query)) {
      var key = decode(part[1])
        , value = decode(part[2]);
  
      //
      // Prevent overriding of existing properties. This ensures that build-in
      // methods like `toString` or __proto__ are not overriden by malicious
      // querystrings.
      //
      if (key in result) continue;
      result[key] = value;
    }
  
    return result;
  }
  
  /**
   * Transform a query string to an object.
   *
   * @param {Object} obj Object that should be transformed.
   * @param {String} prefix Optional prefix.
   * @returns {String}
   * @api public
   */
  function querystringify(obj, prefix) {
    prefix = prefix || '';
  
    var pairs = [];
  
    //
    // Optionally prefix with a '?' if needed
    //
    if ('string' !== typeof prefix) prefix = '?';
  
    for (var key in obj) {
      if (has.call(obj, key)) {
        pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
      }
    }
  
    return pairs.length ? prefix + pairs.join('&') : '';
  }
  
  //
  // Expose the module.
  //
  exports.stringify = querystringify;
  exports.parse = querystring;
  
  },{}],9:[function(_dereq_,module,exports){
  'use strict';
  
  var EventEmitter = _dereq_('eventemitter3')
    , millisecond = _dereq_('millisecond')
    , destroy = _dereq_('demolish')
    , Tick = _dereq_('tick-tock')
    , one = _dereq_('one-time');
  
  /**
   * Returns sane defaults about a given value.
   *
   * @param {String} name Name of property we want.
   * @param {Recovery} selfie Recovery instance that got created.
   * @param {Object} opts User supplied options we want to check.
   * @returns {Number} Some default value.
   * @api private
   */
  function defaults(name, selfie, opts) {
    return millisecond(
      name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
    );
  }
  
  /**
   * Attempt to recover your connection with reconnection attempt.
   *
   * @constructor
   * @param {Object} options Configuration
   * @api public
   */
  function Recovery(options) {
    var recovery = this;
  
    if (!(recovery instanceof Recovery)) return new Recovery(options);
  
    options = options || {};
  
    recovery.attempt = null;        // Stores the current reconnect attempt.
    recovery._fn = null;            // Stores the callback.
  
    recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
    recovery.retries = defaults('retries', recovery, options);
    recovery.factor = defaults('factor', recovery, options);
    recovery.max = defaults('max', recovery, options);
    recovery.min = defaults('min', recovery, options);
    recovery.timers = new Tick(recovery);
  }
  
  Recovery.prototype = new EventEmitter();
  Recovery.prototype.constructor = Recovery;
  
  Recovery['reconnect timeout'] = '30 seconds';  // Maximum time to wait for an answer.
  Recovery.max = Infinity;                       // Maximum delay.
  Recovery.min = '500 ms';                       // Minimum delay.
  Recovery.retries = 10;                         // Maximum amount of retries.
  Recovery.factor = 2;                           // Exponential back off factor.
  
  /**
   * Start a new reconnect procedure.
   *
   * @returns {Recovery}
   * @api public
   */
  Recovery.prototype.reconnect = function reconnect() {
    var recovery = this;
  
    return recovery.backoff(function backedoff(err, opts) {
      opts.duration = (+new Date()) - opts.start;
  
      if (err) return recovery.emit('reconnect failed', err, opts);
  
      recovery.emit('reconnected', opts);
    }, recovery.attempt);
  };
  
  /**
   * Exponential back off algorithm for retry operations. It uses a randomized
   * retry so we don't DDOS our server when it goes down under pressure.
   *
   * @param {Function} fn Callback to be called after the timeout.
   * @param {Object} opts Options for configuring the timeout.
   * @returns {Recovery}
   * @api private
   */
  Recovery.prototype.backoff = function backoff(fn, opts) {
    var recovery = this;
  
    opts = opts || recovery.attempt || {};
  
    //
    // Bailout when we already have a back off process running. We shouldn't call
    // the callback then.
    //
    if (opts.backoff) return recovery;
  
    opts['reconnect timeout'] = defaults('reconnect timeout', recovery, opts);
    opts.retries = defaults('retries', recovery, opts);
    opts.factor = defaults('factor', recovery, opts);
    opts.max = defaults('max', recovery, opts);
    opts.min = defaults('min', recovery, opts);
  
    opts.start = +opts.start || +new Date();
    opts.duration = +opts.duration || 0;
    opts.attempt = +opts.attempt || 0;
  
    //
    // Bailout if we are about to make too much attempts.
    //
    if (opts.attempt === opts.retries) {
      fn.call(recovery, new Error('Unable to recover'), opts);
      return recovery;
    }
  
    //
    // Prevent duplicate back off attempts using the same options object and
    // increment our attempt as we're about to have another go at this thing.
    //
    opts.backoff = true;
    opts.attempt++;
  
    recovery.attempt = opts;
  
    //
    // Calculate the timeout, but make it randomly so we don't retry connections
    // at the same interval and defeat the purpose. This exponential back off is
    // based on the work of:
    //
    // http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html
    //
    opts.scheduled = opts.attempt !== 1
      ? Math.min(Math.round(
          (Math.random() + 1) * opts.min * Math.pow(opts.factor, opts.attempt - 1)
        ), opts.max)
      : opts.min;
  
    recovery.timers.setTimeout('reconnect', function delay() {
      opts.duration = (+new Date()) - opts.start;
      opts.backoff = false;
      recovery.timers.clear('reconnect, timeout');
  
      //
      // Create a `one` function which can only be called once. So we can use the
      // same function for different types of invocations to create a much better
      // and usable API.
      //
      var connect = recovery._fn = one(function connect(err) {
        recovery.reset();
  
        if (err) return recovery.backoff(fn, opts);
  
        fn.call(recovery, undefined, opts);
      });
  
      recovery.emit('reconnect', opts, connect);
      recovery.timers.setTimeout('timeout', function timeout() {
        var err = new Error('Failed to reconnect in a timely manner');
        opts.duration = (+new Date()) - opts.start;
  
        recovery.emit('reconnect timeout', err, opts);
        connect(err);
      }, opts['reconnect timeout']);
    }, opts.scheduled);
  
    //
    // Emit a `reconnecting` event with current reconnect options. This allows
    // them to update the UI and provide their users with feedback.
    //
    recovery.emit('reconnect scheduled', opts);
  
    return recovery;
  };
  
  /**
   * Check if the reconnection process is currently reconnecting.
   *
   * @returns {Boolean}
   * @api public
   */
  Recovery.prototype.reconnecting = function reconnecting() {
    return !!this.attempt;
  };
  
  /**
   * Tell our reconnection procedure that we're passed.
   *
   * @param {Error} err Reconnection failed.
   * @returns {Recovery}
   * @api public
   */
  Recovery.prototype.reconnected = function reconnected(err) {
    if (this._fn) this._fn(err);
    return this;
  };
  
  /**
   * Reset the reconnection attempt so it can be re-used again.
   *
   * @returns {Recovery}
   * @api public
   */
  Recovery.prototype.reset = function reset() {
    this._fn = this.attempt = null;
    this.timers.clear('reconnect, timeout');
  
    return this;
  };
  
  /**
   * Clean up the instance.
   *
   * @type {Function}
   * @returns {Boolean}
   * @api public
   */
  Recovery.prototype.destroy = destroy('timers attempt _fn');
  
  //
  // Expose the module.
  //
  module.exports = Recovery;
  
  },{"demolish":1,"eventemitter3":10,"millisecond":5,"one-time":6,"tick-tock":12}],10:[function(_dereq_,module,exports){
  'use strict';
  
  //
  // We store our EE objects in a plain object whose properties are event names.
  // If `Object.create(null)` is not supported we prefix the event names with a
  // `~` to make sure that the built-in object properties are not overridden or
  // used as an attack vector.
  // We also assume that `Object.create(null)` is available when the event name
  // is an ES6 Symbol.
  //
  var prefix = typeof Object.create !== 'function' ? '~' : false;
  
  /**
   * Representation of a single EventEmitter function.
   *
   * @param {Function} fn Event handler to be called.
   * @param {Mixed} context Context for function execution.
   * @param {Boolean} once Only emit once
   * @api private
   */
  function EE(fn, context, once) {
    this.fn = fn;
    this.context = context;
    this.once = once || false;
  }
  
  /**
   * Minimal EventEmitter interface that is molded against the Node.js
   * EventEmitter interface.
   *
   * @constructor
   * @api public
   */
  function EventEmitter() { /* Nothing to set */ }
  
  /**
   * Holds the assigned EventEmitters by name.
   *
   * @type {Object}
   * @private
   */
  EventEmitter.prototype._events = undefined;
  
  /**
   * Return a list of assigned event listeners.
   *
   * @param {String} event The events that should be listed.
   * @param {Boolean} exists We only need to know if there are listeners.
   * @returns {Array|Boolean}
   * @api public
   */
  EventEmitter.prototype.listeners = function listeners(event, exists) {
    var evt = prefix ? prefix + event : event
      , available = this._events && this._events[evt];
  
    if (exists) return !!available;
    if (!available) return [];
    if (available.fn) return [available.fn];
  
    for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
      ee[i] = available[i].fn;
    }
  
    return ee;
  };
  
  /**
   * Emit an event to all registered event listeners.
   *
   * @param {String} event The name of the event.
   * @returns {Boolean} Indication if we've emitted an event.
   * @api public
   */
  EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
    var evt = prefix ? prefix + event : event;
  
    if (!this._events || !this._events[evt]) return false;
  
    var listeners = this._events[evt]
      , len = arguments.length
      , args
      , i;
  
    if ('function' === typeof listeners.fn) {
      if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  
      switch (len) {
        case 1: return listeners.fn.call(listeners.context), true;
        case 2: return listeners.fn.call(listeners.context, a1), true;
        case 3: return listeners.fn.call(listeners.context, a1, a2), true;
        case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
        case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
        case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
      }
  
      for (i = 1, args = new Array(len -1); i < len; i++) {
        args[i - 1] = arguments[i];
      }
  
      listeners.fn.apply(listeners.context, args);
    } else {
      var length = listeners.length
        , j;
  
      for (i = 0; i < length; i++) {
        if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  
        switch (len) {
          case 1: listeners[i].fn.call(listeners[i].context); break;
          case 2: listeners[i].fn.call(listeners[i].context, a1); break;
          case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
          default:
            if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
              args[j - 1] = arguments[j];
            }
  
            listeners[i].fn.apply(listeners[i].context, args);
        }
      }
    }
  
    return true;
  };
  
  /**
   * Register a new EventListener for the given event.
   *
   * @param {String} event Name of the event.
   * @param {Functon} fn Callback function.
   * @param {Mixed} context The context of the function.
   * @api public
   */
  EventEmitter.prototype.on = function on(event, fn, context) {
    var listener = new EE(fn, context || this)
      , evt = prefix ? prefix + event : event;
  
    if (!this._events) this._events = prefix ? {} : Object.create(null);
    if (!this._events[evt]) this._events[evt] = listener;
    else {
      if (!this._events[evt].fn) this._events[evt].push(listener);
      else this._events[evt] = [
        this._events[evt], listener
      ];
    }
  
    return this;
  };
  
  /**
   * Add an EventListener that's only called once.
   *
   * @param {String} event Name of the event.
   * @param {Function} fn Callback function.
   * @param {Mixed} context The context of the function.
   * @api public
   */
  EventEmitter.prototype.once = function once(event, fn, context) {
    var listener = new EE(fn, context || this, true)
      , evt = prefix ? prefix + event : event;
  
    if (!this._events) this._events = prefix ? {} : Object.create(null);
    if (!this._events[evt]) this._events[evt] = listener;
    else {
      if (!this._events[evt].fn) this._events[evt].push(listener);
      else this._events[evt] = [
        this._events[evt], listener
      ];
    }
  
    return this;
  };
  
  /**
   * Remove event listeners.
   *
   * @param {String} event The event we want to remove.
   * @param {Function} fn The listener that we need to find.
   * @param {Mixed} context Only remove listeners matching this context.
   * @param {Boolean} once Only remove once listeners.
   * @api public
   */
  EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
    var evt = prefix ? prefix + event : event;
  
    if (!this._events || !this._events[evt]) return this;
  
    var listeners = this._events[evt]
      , events = [];
  
    if (fn) {
      if (listeners.fn) {
        if (
             listeners.fn !== fn
          || (once && !listeners.once)
          || (context && listeners.context !== context)
        ) {
          events.push(listeners);
        }
      } else {
        for (var i = 0, length = listeners.length; i < length; i++) {
          if (
               listeners[i].fn !== fn
            || (once && !listeners[i].once)
            || (context && listeners[i].context !== context)
          ) {
            events.push(listeners[i]);
          }
        }
      }
    }
  
    //
    // Reset the array, or remove it completely if we have no more listeners.
    //
    if (events.length) {
      this._events[evt] = events.length === 1 ? events[0] : events;
    } else {
      delete this._events[evt];
    }
  
    return this;
  };
  
  /**
   * Remove all listeners or only the listeners for the specified event.
   *
   * @param {String} event The event want to remove all listeners for.
   * @api public
   */
  EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
    if (!this._events) return this;
  
    if (event) delete this._events[prefix ? prefix + event : event];
    else this._events = prefix ? {} : Object.create(null);
  
    return this;
  };
  
  //
  // Alias methods names because people roll like that.
  //
  EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  
  //
  // This function doesn't apply anymore.
  //
  EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
    return this;
  };
  
  //
  // Expose the prefix.
  //
  EventEmitter.prefixed = prefix;
  
  //
  // Expose the module.
  //
  if ('undefined' !== typeof module) {
    module.exports = EventEmitter;
  }
  
  },{}],11:[function(_dereq_,module,exports){
  'use strict';
  
  /**
   * Check if we're required to add a port number.
   *
   * @see https://url.spec.whatwg.org/#default-port
   * @param {Number|String} port Port number we need to check
   * @param {String} protocol Protocol we need to check against.
   * @returns {Boolean} Is it a default port for the given protocol
   * @api private
   */
  module.exports = function required(port, protocol) {
    protocol = protocol.split(':')[0];
    port = +port;
  
    if (!port) return false;
  
    switch (protocol) {
      case 'http':
      case 'ws':
      return port !== 80;
  
      case 'https':
      case 'wss':
      return port !== 443;
  
      case 'ftp':
      return port !== 21;
  
      case 'gopher':
      return port !== 70;
  
      case 'file':
      return false;
    }
  
    return port !== 0;
  };
  
  },{}],12:[function(_dereq_,module,exports){
  (function (setImmediate,clearImmediate){
  'use strict';
  
  var has = Object.prototype.hasOwnProperty
    , ms = _dereq_('millisecond');
  
  /**
   * Timer instance.
   *
   * @constructor
   * @param {Object} timer New timer instance.
   * @param {Function} clear Clears the timer instance.
   * @param {Function} duration Duration of the timer.
   * @param {Function} fn The functions that need to be executed.
   * @api private
   */
  function Timer(timer, clear, duration, fn) {
    this.start = +(new Date());
    this.duration = duration;
    this.clear = clear;
    this.timer = timer;
    this.fns = [fn];
  }
  
  /**
   * Calculate the time left for a given timer.
   *
   * @returns {Number} Time in milliseconds.
   * @api public
   */
  Timer.prototype.remaining = function remaining() {
    return this.duration - this.taken();
  };
  
  /**
   * Calculate the amount of time it has taken since we've set the timer.
   *
   * @returns {Number}
   * @api public
   */
  Timer.prototype.taken = function taken() {
    return +(new Date()) - this.start;
  };
  
  /**
   * Custom wrappers for the various of clear{whatever} functions. We cannot
   * invoke them directly as this will cause thrown errors in Google Chrome with
   * an Illegal Invocation Error
   *
   * @see #2
   * @type {Function}
   * @api private
   */
  function unsetTimeout(id) { clearTimeout(id); }
  function unsetInterval(id) { clearInterval(id); }
  function unsetImmediate(id) { clearImmediate(id); }
  
  /**
   * Simple timer management.
   *
   * @constructor
   * @param {Mixed} context Context of the callbacks that we execute.
   * @api public
   */
  function Tick(context) {
    if (!(this instanceof Tick)) return new Tick(context);
  
    this.timers = {};
    this.context = context || this;
  }
  
  /**
   * Return a function which will just iterate over all assigned callbacks and
   * optionally clear the timers from memory if needed.
   *
   * @param {String} name Name of the timer we need to execute.
   * @param {Boolean} clear Also clear from memory.
   * @returns {Function}
   * @api private
   */
  Tick.prototype.tock = function ticktock(name, clear) {
    var tock = this;
  
    return function tickedtock() {
      if (!(name in tock.timers)) return;
  
      var timer = tock.timers[name]
        , fns = timer.fns.slice()
        , l = fns.length
        , i = 0;
  
      if (clear) tock.clear(name);
      else tock.start = +new Date();
  
      for (; i < l; i++) {
        fns[i].call(tock.context);
      }
    };
  };
  
  /**
   * Add a new timeout.
   *
   * @param {String} name Name of the timer.
   * @param {Function} fn Completion callback.
   * @param {Mixed} time Duration of the timer.
   * @returns {Tick}
   * @api public
   */
  Tick.prototype.setTimeout = function timeout(name, fn, time) {
    var tick = this
      , tock;
  
    if (tick.timers[name]) {
      tick.timers[name].fns.push(fn);
      return tick;
    }
  
    tock = ms(time);
    tick.timers[name] = new Timer(
      setTimeout(tick.tock(name, true), ms(time)),
      unsetTimeout,
      tock,
      fn
    );
  
    return tick;
  };
  
  /**
   * Add a new interval.
   *
   * @param {String} name Name of the timer.
   * @param {Function} fn Completion callback.
   * @param {Mixed} time Interval of the timer.
   * @returns {Tick}
   * @api public
   */
  Tick.prototype.setInterval = function interval(name, fn, time) {
    var tick = this
      , tock;
  
    if (tick.timers[name]) {
      tick.timers[name].fns.push(fn);
      return tick;
    }
  
    tock = ms(time);
    tick.timers[name] = new Timer(
      setInterval(tick.tock(name), ms(time)),
      unsetInterval,
      tock,
      fn
    );
  
    return tick;
  };
  
  /**
   * Add a new setImmediate.
   *
   * @param {String} name Name of the timer.
   * @param {Function} fn Completion callback.
   * @returns {Tick}
   * @api public
   */
  Tick.prototype.setImmediate = function immediate(name, fn) {
    var tick = this;
  
    if ('function' !== typeof setImmediate) return tick.setTimeout(name, fn, 0);
  
    if (tick.timers[name]) {
      tick.timers[name].fns.push(fn);
      return tick;
    }
  
    tick.timers[name] = new Timer(
      setImmediate(tick.tock(name, true)),
      unsetImmediate,
      0,
      fn
    );
  
    return tick;
  };
  
  /**
   * Check if we have a timer set.
   *
   * @param {String} name
   * @returns {Boolean}
   * @api public
   */
  Tick.prototype.active = function active(name) {
    return name in this.timers;
  };
  
  /**
   * Properly clean up all timeout references. If no arguments are supplied we
   * will attempt to clear every single timer that is present.
   *
   * @param {Arguments} ..args.. The names of the timeouts we need to clear
   * @returns {Tick}
   * @api public
   */
  Tick.prototype.clear = function clear() {
    var args = arguments.length ? arguments : []
      , tick = this
      , timer, i, l;
  
    if (args.length === 1 && 'string' === typeof args[0]) {
      args = args[0].split(/[, ]+/);
    }
  
    if (!args.length) {
      for (timer in tick.timers) {
        if (has.call(tick.timers, timer)) args.push(timer);
      }
    }
  
    for (i = 0, l = args.length; i < l; i++) {
      timer = tick.timers[args[i]];
  
      if (!timer) continue;
      timer.clear(timer.timer);
  
      timer.fns = timer.timer = timer.clear = null;
      delete tick.timers[args[i]];
    }
  
    return tick;
  };
  
  /**
   * Adjust a timeout or interval to a new duration.
   *
   * @returns {Tick}
   * @api public
   */
  Tick.prototype.adjust = function adjust(name, time) {
    var interval
      , tick = this
      , tock = ms(time)
      , timer = tick.timers[name];
  
    if (!timer) return tick;
  
    interval = timer.clear === unsetInterval;
    timer.clear(timer.timer);
    timer.start = +(new Date());
    timer.duration = tock;
    timer.timer = (interval ? setInterval : setTimeout)(tick.tock(name, !interval), tock);
  
    return tick;
  };
  
  /**
   * We will no longer use this module, prepare your self for global cleanups.
   *
   * @returns {Boolean}
   * @api public
   */
  Tick.prototype.end = Tick.prototype.destroy = function end() {
    if (!this.context) return false;
  
    this.clear();
    this.context = this.timers = null;
  
    return true;
  };
  
  //
  // Expose the timer factory.
  //
  Tick.Timer = Timer;
  module.exports = Tick;
  
  }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  },{"millisecond":5,"timers":13}],13:[function(_dereq_,module,exports){
  (function (setImmediate,clearImmediate){
  var nextTick = _dereq_('process/browser.js').nextTick;
  var apply = Function.prototype.apply;
  var slice = Array.prototype.slice;
  var immediateIds = {};
  var nextImmediateId = 0;
  
  // DOM APIs, for completeness
  
  exports.setTimeout = function() {
    return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  };
  exports.setInterval = function() {
    return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  };
  exports.clearTimeout =
  exports.clearInterval = function(timeout) { timeout.close(); };
  
  function Timeout(id, clearFn) {
    this._id = id;
    this._clearFn = clearFn;
  }
  Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  Timeout.prototype.close = function() {
    this._clearFn.call(window, this._id);
  };
  
  // Does not start the time, just sets up the members needed.
  exports.enroll = function(item, msecs) {
    clearTimeout(item._idleTimeoutId);
    item._idleTimeout = msecs;
  };
  
  exports.unenroll = function(item) {
    clearTimeout(item._idleTimeoutId);
    item._idleTimeout = -1;
  };
  
  exports._unrefActive = exports.active = function(item) {
    clearTimeout(item._idleTimeoutId);
  
    var msecs = item._idleTimeout;
    if (msecs >= 0) {
      item._idleTimeoutId = setTimeout(function onTimeout() {
        if (item._onTimeout)
          item._onTimeout();
      }, msecs);
    }
  };
  
  // That's not how node.js implements it but the exposed api is the same.
  exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
    var id = nextImmediateId++;
    var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  
    immediateIds[id] = true;
  
    nextTick(function onNextTick() {
      if (immediateIds[id]) {
        // fn.call() is faster so we optimize for the common use-case
        // @see http://jsperf.com/call-apply-segu
        if (args) {
          fn.apply(null, args);
        } else {
          fn.call(null);
        }
        // Prevent ids from leaking
        exports.clearImmediate(id);
      }
    });
  
    return id;
  };
  
  exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
    delete immediateIds[id];
  };
  }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  },{"process/browser.js":7,"timers":13}],14:[function(_dereq_,module,exports){
  (function (global){
  'use strict';
  
  var required = _dereq_('requires-port')
    , qs = _dereq_('querystringify')
    , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
    , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
  
  /**
   * These are the parse rules for the URL parser, it informs the parser
   * about:
   *
   * 0. The char it Needs to parse, if it's a string it should be done using
   *    indexOf, RegExp using exec and NaN means set as current value.
   * 1. The property we should set when parsing this value.
   * 2. Indication if it's backwards or forward parsing, when set as number it's
   *    the value of extra chars that should be split off.
   * 3. Inherit from location if non existing in the parser.
   * 4. `toLowerCase` the resulting value.
   */
  var rules = [
    ['#', 'hash'],                        // Extract from the back.
    ['?', 'query'],                       // Extract from the back.
    function sanitize(address) {          // Sanitize what is left of the address
      return address.replace('\\', '/');
    },
    ['/', 'pathname'],                    // Extract from the back.
    ['@', 'auth', 1],                     // Extract from the front.
    [NaN, 'host', undefined, 1, 1],       // Set left over value.
    [/:(\d+)$/, 'port', undefined, 1],    // RegExp the back.
    [NaN, 'hostname', undefined, 1, 1]    // Set left over.
  ];
  
  /**
   * These properties should not be copied or inherited from. This is only needed
   * for all non blob URL's as a blob URL does not include a hash, only the
   * origin.
   *
   * @type {Object}
   * @private
   */
  var ignore = { hash: 1, query: 1 };
  
  /**
   * The location object differs when your code is loaded through a normal page,
   * Worker or through a worker using a blob. And with the blobble begins the
   * trouble as the location object will contain the URL of the blob, not the
   * location of the page where our code is loaded in. The actual origin is
   * encoded in the `pathname` so we can thankfully generate a good "default"
   * location from it so we can generate proper relative URL's again.
   *
   * @param {Object|String} loc Optional default location object.
   * @returns {Object} lolcation object.
   * @public
   */
  function lolcation(loc) {
    var location = global && global.location || {};
    loc = loc || location;
  
    var finaldestination = {}
      , type = typeof loc
      , key;
  
    if ('blob:' === loc.protocol) {
      finaldestination = new Url(unescape(loc.pathname), {});
    } else if ('string' === type) {
      finaldestination = new Url(loc, {});
      for (key in ignore) delete finaldestination[key];
    } else if ('object' === type) {
      for (key in loc) {
        if (key in ignore) continue;
        finaldestination[key] = loc[key];
      }
  
      if (finaldestination.slashes === undefined) {
        finaldestination.slashes = slashes.test(loc.href);
      }
    }
  
    return finaldestination;
  }
  
  /**
   * @typedef ProtocolExtract
   * @type Object
   * @property {String} protocol Protocol matched in the URL, in lowercase.
   * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
   * @property {String} rest Rest of the URL that is not part of the protocol.
   */
  
  /**
   * Extract protocol information from a URL with/without double slash ("//").
   *
   * @param {String} address URL we want to extract from.
   * @return {ProtocolExtract} Extracted information.
   * @private
   */
  function extractProtocol(address) {
    var match = protocolre.exec(address);
  
    return {
      protocol: match[1] ? match[1].toLowerCase() : '',
      slashes: !!match[2],
      rest: match[3]
    };
  }
  
  /**
   * Resolve a relative URL pathname against a base URL pathname.
   *
   * @param {String} relative Pathname of the relative URL.
   * @param {String} base Pathname of the base URL.
   * @return {String} Resolved pathname.
   * @private
   */
  function resolve(relative, base) {
    var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
      , i = path.length
      , last = path[i - 1]
      , unshift = false
      , up = 0;
  
    while (i--) {
      if (path[i] === '.') {
        path.splice(i, 1);
      } else if (path[i] === '..') {
        path.splice(i, 1);
        up++;
      } else if (up) {
        if (i === 0) unshift = true;
        path.splice(i, 1);
        up--;
      }
    }
  
    if (unshift) path.unshift('');
    if (last === '.' || last === '..') path.push('');
  
    return path.join('/');
  }
  
  /**
   * The actual URL instance. Instead of returning an object we've opted-in to
   * create an actual constructor as it's much more memory efficient and
   * faster and it pleases my OCD.
   *
   * It is worth noting that we should not use `URL` as class name to prevent
   * clashes with the global URL instance that got introduced in browsers.
   *
   * @constructor
   * @param {String} address URL we want to parse.
   * @param {Object|String} location Location defaults for relative paths.
   * @param {Boolean|Function} parser Parser for the query string.
   * @private
   */
  function Url(address, location, parser) {
    if (!(this instanceof Url)) {
      return new Url(address, location, parser);
    }
  
    var relative, extracted, parse, instruction, index, key
      , instructions = rules.slice()
      , type = typeof location
      , url = this
      , i = 0;
  
    //
    // The following if statements allows this module two have compatibility with
    // 2 different API:
    //
    // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
    //    where the boolean indicates that the query string should also be parsed.
    //
    // 2. The `URL` interface of the browser which accepts a URL, object as
    //    arguments. The supplied object will be used as default values / fall-back
    //    for relative paths.
    //
    if ('object' !== type && 'string' !== type) {
      parser = location;
      location = null;
    }
  
    if (parser && 'function' !== typeof parser) parser = qs.parse;
  
    location = lolcation(location);
  
    //
    // Extract protocol information before running the instructions.
    //
    extracted = extractProtocol(address || '');
    relative = !extracted.protocol && !extracted.slashes;
    url.slashes = extracted.slashes || relative && location.slashes;
    url.protocol = extracted.protocol || location.protocol || '';
    address = extracted.rest;
  
    //
    // When the authority component is absent the URL starts with a path
    // component.
    //
    if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  
    for (; i < instructions.length; i++) {
      instruction = instructions[i];
  
      if (typeof instruction === 'function') {
        address = instruction(address);
        continue;
      }
  
      parse = instruction[0];
      key = instruction[1];
  
      if (parse !== parse) {
        url[key] = address;
      } else if ('string' === typeof parse) {
        if (~(index = address.indexOf(parse))) {
          if ('number' === typeof instruction[2]) {
            url[key] = address.slice(0, index);
            address = address.slice(index + instruction[2]);
          } else {
            url[key] = address.slice(index);
            address = address.slice(0, index);
          }
        }
      } else if ((index = parse.exec(address))) {
        url[key] = index[1];
        address = address.slice(0, index.index);
      }
  
      url[key] = url[key] || (
        relative && instruction[3] ? location[key] || '' : ''
      );
  
      //
      // Hostname, host and protocol should be lowercased so they can be used to
      // create a proper `origin`.
      //
      if (instruction[4]) url[key] = url[key].toLowerCase();
    }
  
    //
    // Also parse the supplied query string in to an object. If we're supplied
    // with a custom parser as function use that instead of the default build-in
    // parser.
    //
    if (parser) url.query = parser(url.query);
  
    //
    // If the URL is relative, resolve the pathname against the base URL.
    //
    if (
        relative
      && location.slashes
      && url.pathname.charAt(0) !== '/'
      && (url.pathname !== '' || location.pathname !== '')
    ) {
      url.pathname = resolve(url.pathname, location.pathname);
    }
  
    //
    // We should not add port numbers if they are already the default port number
    // for a given protocol. As the host also contains the port number we're going
    // override it with the hostname which contains no port number.
    //
    if (!required(url.port, url.protocol)) {
      url.host = url.hostname;
      url.port = '';
    }
  
    //
    // Parse down the `auth` for the username and password.
    //
    url.username = url.password = '';
    if (url.auth) {
      instruction = url.auth.split(':');
      url.username = instruction[0] || '';
      url.password = instruction[1] || '';
    }
  
    url.origin = url.protocol && url.host && url.protocol !== 'file:'
      ? url.protocol +'//'+ url.host
      : 'null';
  
    //
    // The href is just the compiled result.
    //
    url.href = url.toString();
  }
  
  /**
   * This is convenience method for changing properties in the URL instance to
   * insure that they all propagate correctly.
   *
   * @param {String} part          Property we need to adjust.
   * @param {Mixed} value          The newly assigned value.
   * @param {Boolean|Function} fn  When setting the query, it will be the function
   *                               used to parse the query.
   *                               When setting the protocol, double slash will be
   *                               removed from the final url if it is true.
   * @returns {URL} URL instance for chaining.
   * @public
   */
  function set(part, value, fn) {
    var url = this;
  
    switch (part) {
      case 'query':
        if ('string' === typeof value && value.length) {
          value = (fn || qs.parse)(value);
        }
  
        url[part] = value;
        break;
  
      case 'port':
        url[part] = value;
  
        if (!required(value, url.protocol)) {
          url.host = url.hostname;
          url[part] = '';
        } else if (value) {
          url.host = url.hostname +':'+ value;
        }
  
        break;
  
      case 'hostname':
        url[part] = value;
  
        if (url.port) value += ':'+ url.port;
        url.host = value;
        break;
  
      case 'host':
        url[part] = value;
  
        if (/:\d+$/.test(value)) {
          value = value.split(':');
          url.port = value.pop();
          url.hostname = value.join(':');
        } else {
          url.hostname = value;
          url.port = '';
        }
  
        break;
  
      case 'protocol':
        url.protocol = value.toLowerCase();
        url.slashes = !fn;
        break;
  
      case 'pathname':
      case 'hash':
        if (value) {
          var char = part === 'pathname' ? '/' : '#';
          url[part] = value.charAt(0) !== char ? char + value : value;
        } else {
          url[part] = value;
        }
        break;
  
      default:
        url[part] = value;
    }
  
    for (var i = 0; i < rules.length; i++) {
      var ins = rules[i];
  
      if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
    }
  
    url.origin = url.protocol && url.host && url.protocol !== 'file:'
      ? url.protocol +'//'+ url.host
      : 'null';
  
    url.href = url.toString();
  
    return url;
  }
  
  /**
   * Transform the properties back in to a valid and full URL string.
   *
   * @param {Function} stringify Optional query stringify function.
   * @returns {String} Compiled version of the URL.
   * @public
   */
  function toString(stringify) {
    if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  
    var query
      , url = this
      , protocol = url.protocol;
  
    if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  
    var result = protocol + (url.slashes ? '//' : '');
  
    if (url.username) {
      result += url.username;
      if (url.password) result += ':'+ url.password;
      result += '@';
    }
  
    result += url.host + url.pathname;
  
    query = 'object' === typeof url.query ? stringify(url.query) : url.query;
    if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  
    if (url.hash) result += url.hash;
  
    return result;
  }
  
  Url.prototype = { set: set, toString: toString };
  
  //
  // Expose the URL parser and some additional properties that might be useful for
  // others or testing.
  //
  Url.extractProtocol = extractProtocol;
  Url.location = lolcation;
  Url.qs = qs;
  
  module.exports = Url;
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"querystringify":8,"requires-port":11}],15:[function(_dereq_,module,exports){
  'use strict';
  
  var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
    , length = 64
    , map = {}
    , seed = 0
    , i = 0
    , prev;
  
  /**
   * Return a string representing the specified number.
   *
   * @param {Number} num The number to convert.
   * @returns {String} The string representation of the number.
   * @api public
   */
  function encode(num) {
    var encoded = '';
  
    do {
      encoded = alphabet[num % length] + encoded;
      num = Math.floor(num / length);
    } while (num > 0);
  
    return encoded;
  }
  
  /**
   * Return the integer value specified by the given string.
   *
   * @param {String} str The string to convert.
   * @returns {Number} The integer value represented by the string.
   * @api public
   */
  function decode(str) {
    var decoded = 0;
  
    for (i = 0; i < str.length; i++) {
      decoded = decoded * length + map[str.charAt(i)];
    }
  
    return decoded;
  }
  
  /**
   * Yeast: A tiny growing id generator.
   *
   * @returns {String} A unique id.
   * @api public
   */
  function yeast() {
    var now = encode(+new Date());
  
    if (now !== prev) return seed = 0, prev = now;
    return now +'.'+ encode(seed++);
  }
  
  //
  // Map each character to its index.
  //
  for (; i < length; i++) map[alphabet[i]] = i;
  
  //
  // Expose the `yeast`, `encode` and `decode` functions.
  //
  yeast.encode = encode;
  yeast.decode = decode;
  module.exports = yeast;
  
  },{}],16:[function(_dereq_,module,exports){
  /*globals require, define */
  'use strict';
  
  var EventEmitter = _dereq_('eventemitter3')
    , TickTock = _dereq_('tick-tock')
    , Recovery = _dereq_('recovery')
    , qs = _dereq_('querystringify')
    , inherits = _dereq_('inherits')
    , destroy = _dereq_('demolish')
    , yeast = _dereq_('yeast')
    , u2028 = /\u2028/g
    , u2029 = /\u2029/g;
  
  /**
   * Context assertion, ensure that some of our public Primus methods are called
   * with the correct context to ensure that
   *
   * @param {Primus} self The context of the function.
   * @param {String} method The method name.
   * @api private
   */
  function context(self, method) {
    if (self instanceof Primus) return;
  
    var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance');
  
    if ('function' !== typeof self.listeners || !self.listeners('error').length) {
      throw failure;
    }
  
    self.emit('error', failure);
  }
  
  //
  // Sets the default connection URL, it uses the default origin of the browser
  // when supported but degrades for older browsers. In Node.js, we cannot guess
  // where the user wants to connect to, so we just default to localhost.
  //
  var defaultUrl;
  
  try {
    if (location.origin) {
      defaultUrl = location.origin;
    } else {
      defaultUrl = location.protocol +'//'+ location.host;
    }
  } catch (e) {
    defaultUrl = 'http://127.0.0.1';
  }
  
  /**
   * Primus is a real-time library agnostic framework for establishing real-time
   * connections with servers.
   *
   * Options:
   * - reconnect, configuration for the reconnect process.
   * - manual, don't automatically call `.open` to start the connection.
   * - websockets, force the use of WebSockets, even when you should avoid them.
   * - timeout, connect timeout, server didn't respond in a timely manner.
   * - pingTimeout, The maximum amount of time to wait for the server to send a ping.
   * - network, Use network events as leading method for network connection drops.
   * - strategy, Reconnection strategies.
   * - transport, Transport options.
   * - url, uri, The URL to use connect with the server.
   *
   * @constructor
   * @param {String} url The URL of your server.
   * @param {Object} options The configuration.
   * @api public
   */
  function Primus(url, options) {
    if (!(this instanceof Primus)) return new Primus(url, options);
  
    Primus.Stream.call(this);
  
    if ('function' !== typeof this.client) {
      return this.critical(new Error(
        'The client library has not been compiled correctly, see '+
        'https://github.com/primus/primus#client-library for more details'
      ));
    }
  
    if ('object' === typeof url) {
      options = url;
      url = options.url || options.uri || defaultUrl;
    } else {
      options = options || {};
    }
  
    if ('ping' in options || 'pong' in options) {
      return this.critical(new Error(
        'The `ping` and `pong` options have been removed'
      ));
    }
  
    var primus = this;
  
    // The maximum number of messages that can be placed in queue.
    options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
  
    // Connection timeout duration.
    options.timeout = 'timeout' in options ? options.timeout : 10e3;
  
    // Stores the back off configuration.
    options.reconnect = 'reconnect' in options ? options.reconnect : {};
  
    // Heartbeat ping interval.
    options.pingTimeout = 'pingTimeout' in options ? options.pingTimeout : false;
  
    // Reconnect strategies.
    options.strategy = 'strategy' in options ? options.strategy : [];
  
    // Custom transport options.
    options.transport = 'transport' in options ? options.transport : {};
  
    primus.buffer = [];                           // Stores premature send data.
    primus.writable = true;                       // Silly stream compatibility.
    primus.readable = true;                       // Silly stream compatibility.
    primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
    primus.readyState = Primus.CLOSED;            // The readyState of the connection.
    primus.options = options;                     // Reference to the supplied options.
    primus.timers = new TickTock(this);           // Contains all our timers.
    primus.socket = null;                         // Reference to the internal connection.
    primus.disconnect = false;                    // Did we receive a disconnect packet?
    primus.transport = options.transport;         // Transport options.
    primus.transformers = {                       // Message transformers.
      outgoing: [],
      incoming: []
    };
  
    //
    // Create our reconnection instance.
    //
    primus.recovery = new Recovery(options.reconnect);
  
    //
    // Parse the reconnection strategy. It can have the following strategies:
    //
    // - timeout: Reconnect when we have a network timeout.
    // - disconnect: Reconnect when we have an unexpected disconnect.
    // - online: Reconnect when we're back online.
    //
    if ('string' === typeof options.strategy) {
      options.strategy = options.strategy.split(/\s?,\s?/g);
    }
  
    if (false === options.strategy) {
      //
      // Strategies are disabled, but we still need an empty array to join it in
      // to nothing.
      //
      options.strategy = [];
    } else if (!options.strategy.length) {
      options.strategy.push('disconnect', 'online');
  
      //
      // Timeout based reconnection should only be enabled conditionally. When
      // authorization is enabled it could trigger.
      //
      if (!this.authorization) options.strategy.push('timeout');
    }
  
    options.strategy = options.strategy.join(',').toLowerCase();
  
    //
    // Force the use of WebSockets, even when we've detected some potential
    // broken WebSocket implementation.
    //
    if ('websockets' in options) {
      primus.AVOID_WEBSOCKETS = !options.websockets;
    }
  
    //
    // Force or disable the use of NETWORK events as leading client side
    // disconnection detection.
    //
    if ('network' in options) {
      primus.NETWORK_EVENTS = options.network;
    }
  
    //
    // Check if the user wants to manually initialise a connection. If they don't,
    // we want to do it after a really small timeout so we give the users enough
    // time to listen for `error` events etc.
    //
    if (!options.manual) primus.timers.setTimeout('open', function open() {
      primus.timers.clear('open');
      primus.open();
    }, 0);
  
    primus.initialise(options);
  }
  
  /**
   * Simple require wrapper to make browserify, node and require.js play nice.
   *
   * @param {String} name The module to require.
   * @returns {Object|Undefined} The module that we required.
   * @api private
   */
  Primus.requires = Primus.require = function requires(name) {
    if ('function' !== typeof _dereq_) return undefined;
  
    return !('function' === typeof define && define.amd)
      ? _dereq_(name)
      : undefined;
  };
  
  //
  // It's possible that we're running in Node.js or in a Node.js compatible
  // environment. In this cases we try to inherit from the Stream base class.
  //
  try {
    Primus.Stream = Primus.requires('stream');
  } catch (e) { }
  
  if (!Primus.Stream) Primus.Stream = EventEmitter;
  
  inherits(Primus, Primus.Stream);
  
  /**
   * Primus readyStates, used internally to set the correct ready state.
   *
   * @type {Number}
   * @private
   */
  Primus.OPENING = 1;   // We're opening the connection.
  Primus.CLOSED  = 2;   // No active connection.
  Primus.OPEN    = 3;   // The connection is open.
  
  /**
   * Are we working with a potentially broken WebSockets implementation? This
   * boolean can be used by transformers to remove `WebSockets` from their
   * supported transports.
   *
   * @type {Boolean}
   * @private
   */
  Primus.prototype.AVOID_WEBSOCKETS = false;
  
  /**
   * Some browsers support registering emitting `online` and `offline` events when
   * the connection has been dropped on the client. We're going to detect it in
   * a simple `try {} catch (e) {}` statement so we don't have to do complicated
   * feature detection.
   *
   * @type {Boolean}
   * @private
   */
  Primus.prototype.NETWORK_EVENTS = false;
  Primus.prototype.online = true;
  
  try {
    if (
         Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator
      && (window.addEventListener || document.body.attachEvent)
    ) {
      if (!navigator.onLine) {
        Primus.prototype.online = false;
      }
    }
  } catch (e) { }
  
  /**
   * The Ark contains all our plugins definitions. It's namespaced by
   * name => plugin.
   *
   * @type {Object}
   * @private
   */
  Primus.prototype.ark = {};
  
  /**
   * Simple emit wrapper that returns a function that emits an event once it's
   * called. This makes it easier for transports to emit specific events.
   *
   * @returns {Function} A function that will emit the event when called.
   * @api public
   */
  Primus.prototype.emits = _dereq_('emits');
  
  /**
   * Return the given plugin.
   *
   * @param {String} name The name of the plugin.
   * @returns {Object|undefined} The plugin or undefined.
   * @api public
   */
  Primus.prototype.plugin = function plugin(name) {
    context(this, 'plugin');
  
    if (name) return this.ark[name];
  
    var plugins = {};
  
    for (name in this.ark) {
      plugins[name] = this.ark[name];
    }
  
    return plugins;
  };
  
  /**
   * Checks if the given event is an emitted event by Primus.
   *
   * @param {String} evt The event name.
   * @returns {Boolean} Indication of the event is reserved for internal use.
   * @api public
   */
  Primus.prototype.reserved = function reserved(evt) {
    return (/^(incoming|outgoing)::/).test(evt)
    || evt in this.reserved.events;
  };
  
  /**
   * The actual events that are used by the client.
   *
   * @type {Object}
   * @public
   */
  Primus.prototype.reserved.events = {
    'reconnect scheduled': 1,
    'reconnect timeout': 1,
    'readyStateChange': 1,
    'reconnect failed': 1,
    'reconnected': 1,
    'reconnect': 1,
    'offline': 1,
    'timeout': 1,
    'destroy': 1,
    'online': 1,
    'error': 1,
    'close': 1,
    'open': 1,
    'data': 1,
    'end': 1
  };
  
  /**
   * Initialise the Primus and setup all parsers and internal listeners.
   *
   * @param {Object} options The original options object.
   * @returns {Primus}
   * @api private
   */
  Primus.prototype.initialise = function initialise(options) {
    var primus = this;
  
    primus.recovery
    .on('reconnected', primus.emits('reconnected'))
    .on('reconnect failed', primus.emits('reconnect failed', function failed(next) {
      primus.emit('end');
      next();
    }))
    .on('reconnect timeout', primus.emits('reconnect timeout'))
    .on('reconnect scheduled', primus.emits('reconnect scheduled'))
    .on('reconnect', primus.emits('reconnect', function reconnect(next) {
      primus.emit('outgoing::reconnect');
      next();
    }));
  
    primus.on('outgoing::open', function opening() {
      var readyState = primus.readyState;
  
      primus.readyState = Primus.OPENING;
      if (readyState !== primus.readyState) {
        primus.emit('readyStateChange', 'opening');
      }
    });
  
    primus.on('incoming::open', function opened() {
      var readyState = primus.readyState;
  
      if (primus.recovery.reconnecting()) {
        primus.recovery.reconnected();
      }
  
      //
      // The connection has been opened so we should set our state to
      // (writ|read)able so our stream compatibility works as intended.
      //
      primus.writable = true;
      primus.readable = true;
  
      //
      // Make sure we are flagged as `online` as we've successfully opened the
      // connection.
      //
      if (!primus.online) {
        primus.online = true;
        primus.emit('online');
      }
  
      primus.readyState = Primus.OPEN;
      if (readyState !== primus.readyState) {
        primus.emit('readyStateChange', 'open');
      }
  
      primus.heartbeat();
  
      if (primus.buffer.length) {
        var data = primus.buffer.slice()
          , length = data.length
          , i = 0;
  
        primus.buffer.length = 0;
  
        for (; i < length; i++) {
          primus._write(data[i]);
        }
      }
  
      primus.emit('open');
    });
  
    primus.on('incoming::ping', function ping(time) {
      primus.online = true;
      primus.heartbeat();
      primus.emit('outgoing::pong', time);
      primus._write('primus::pong::'+ time);
    });
  
    primus.on('incoming::error', function error(e) {
      var connect = primus.timers.active('connect')
        , err = e;
  
      //
      // When the error is not an Error instance we try to normalize it.
      //
      if ('string' === typeof e) {
        err = new Error(e);
      } else if (!(e instanceof Error) && 'object' === typeof e) {
        //
        // BrowserChannel and SockJS returns an object which contains some
        // details of the error. In order to have a proper error we "copy" the
        // details in an Error instance.
        //
        err = new Error(e.message || e.reason);
        for (var key in e) {
          if (Object.prototype.hasOwnProperty.call(e, key))
            err[key] = e[key];
        }
      }
      //
      // We're still doing a reconnect attempt, it could be that we failed to
      // connect because the server was down. Failing connect attempts should
      // always emit an `error` event instead of a `open` event.
      //
      //
      if (primus.recovery.reconnecting()) return primus.recovery.reconnected(err);
      if (primus.listeners('error').length) primus.emit('error', err);
  
      //
      // We received an error while connecting, this most likely the result of an
      // unauthorized access to the server.
      //
      if (connect) {
        if (~primus.options.strategy.indexOf('timeout')) {
          primus.recovery.reconnect();
        } else {
          primus.end();
        }
      }
    });
  
    primus.on('incoming::data', function message(raw) {
      primus.decoder(raw, function decoding(err, data) {
        //
        // Do a "safe" emit('error') when we fail to parse a message. We don't
        // want to throw here as listening to errors should be optional.
        //
        if (err) return primus.listeners('error').length && primus.emit('error', err);
  
        //
        // Handle all "primus::" prefixed protocol messages.
        //
        if (primus.protocol(data)) return;
        primus.transforms(primus, primus, 'incoming', data, raw);
      });
    });
  
    primus.on('incoming::end', function end() {
      var readyState = primus.readyState;
  
      //
      // This `end` started with the receiving of a primus::server::close packet
      // which indicated that the user/developer on the server closed the
      // connection and it was not a result of a network disruption. So we should
      // kill the connection without doing a reconnect.
      //
      if (primus.disconnect) {
        primus.disconnect = false;
  
        return primus.end();
      }
  
      //
      // Always set the readyState to closed, and if we're still connecting, close
      // the connection so we're sure that everything after this if statement block
      // is only executed because our readyState is set to `open`.
      //
      primus.readyState = Primus.CLOSED;
      if (readyState !== primus.readyState) {
        primus.emit('readyStateChange', 'end');
      }
  
      if (primus.timers.active('connect')) primus.end();
      if (readyState !== Primus.OPEN) {
        return primus.recovery.reconnecting()
          ? primus.recovery.reconnect()
          : false;
      }
  
      this.writable = false;
      this.readable = false;
  
      //
      // Clear all timers in case we're not going to reconnect.
      //
      this.timers.clear();
  
      //
      // Fire the `close` event as an indication of connection disruption.
      // This is also fired by `primus#end` so it is emitted in all cases.
      //
      primus.emit('close');
  
      //
      // The disconnect was unintentional, probably because the server has
      // shutdown, so if the reconnection is enabled start a reconnect procedure.
      //
      if (~primus.options.strategy.indexOf('disconnect')) {
        return primus.recovery.reconnect();
      }
  
      primus.emit('outgoing::end');
      primus.emit('end');
    });
  
    //
    // Setup the real-time client.
    //
    primus.client();
  
    //
    // Process the potential plugins.
    //
    for (var plugin in primus.ark) {
      primus.ark[plugin].call(primus, primus, options);
    }
  
    //
    // NOTE: The following code is only required if we're supporting network
    // events as it requires access to browser globals.
    //
    if (!primus.NETWORK_EVENTS) return primus;
  
    /**
     * Handler for offline notifications.
     *
     * @api private
     */
    primus.offlineHandler = function offline() {
      if (!primus.online) return; // Already or still offline, bailout.
  
      primus.online = false;
      primus.emit('offline');
      primus.end();
  
      //
      // It is certainly possible that we're in a reconnection loop and that the
      // user goes offline. In this case we want to kill the existing attempt so
      // when the user goes online, it will attempt to reconnect freshly again.
      //
      primus.recovery.reset();
    };
  
    /**
     * Handler for online notifications.
     *
     * @api private
     */
    primus.onlineHandler = function online() {
      if (primus.online) return; // Already or still online, bailout.
  
      primus.online = true;
      primus.emit('online');
  
      if (~primus.options.strategy.indexOf('online')) {
        primus.recovery.reconnect();
      }
    };
  
    if (window.addEventListener) {
      window.addEventListener('offline', primus.offlineHandler, false);
      window.addEventListener('online', primus.onlineHandler, false);
    } else if (document.body.attachEvent){
      document.body.attachEvent('onoffline', primus.offlineHandler);
      document.body.attachEvent('ononline', primus.onlineHandler);
    }
  
    return primus;
  };
  
  /**
   * Really dead simple protocol parser. We simply assume that every message that
   * is prefixed with `primus::` could be used as some sort of protocol definition
   * for Primus.
   *
   * @param {String} msg The data.
   * @returns {Boolean} Is a protocol message.
   * @api private
   */
  Primus.prototype.protocol = function protocol(msg) {
    if (
         'string' !== typeof msg
      || msg.indexOf('primus::') !== 0
    ) return false;
  
    var last = msg.indexOf(':', 8)
      , value = msg.slice(last + 2);
  
    switch (msg.slice(8,  last)) {
      case 'ping':
        this.emit('incoming::ping', +value);
        break;
  
      case 'server':
        //
        // The server is closing the connection, forcefully disconnect so we don't
        // reconnect again.
        //
        if ('close' === value) {
          this.disconnect = true;
        }
        break;
  
      case 'id':
        this.emit('incoming::id', value);
        break;
  
      //
      // Unknown protocol, somebody is probably sending `primus::` prefixed
      // messages.
      //
      default:
        return false;
    }
  
    return true;
  };
  
  /**
   * Execute the set of message transformers from Primus on the incoming or
   * outgoing message.
   * This function and it's content should be in sync with Spark#transforms in
   * spark.js.
   *
   * @param {Primus} primus Reference to the Primus instance with message transformers.
   * @param {Spark|Primus} connection Connection that receives or sends data.
   * @param {String} type The type of message, 'incoming' or 'outgoing'.
   * @param {Mixed} data The data to send or that has been received.
   * @param {String} raw The raw encoded data.
   * @returns {Primus}
   * @api public
   */
  Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) {
    var packet = { data: data }
      , fns = primus.transformers[type];
  
    //
    // Iterate in series over the message transformers so we can allow optional
    // asynchronous execution of message transformers which could for example
    // retrieve additional data from the server, do extra decoding or even
    // message validation.
    //
    (function transform(index, done) {
      var transformer = fns[index++];
  
      if (!transformer) return done();
  
      if (1 === transformer.length) {
        if (false === transformer.call(connection, packet)) {
          //
          // When false is returned by an incoming transformer it means that's
          // being handled by the transformer and we should not emit the `data`
          // event.
          //
          return;
        }
  
        return transform(index, done);
      }
  
      transformer.call(connection, packet, function finished(err, arg) {
        if (err) return connection.emit('error', err);
        if (false === arg) return;
  
        transform(index, done);
      });
    }(0, function done() {
      //
      // We always emit 2 arguments for the data event, the first argument is the
      // parsed data and the second argument is the raw string that we received.
      // This allows you, for example, to do some validation on the parsed data
      // and then save the raw string in your database without the stringify
      // overhead.
      //
      if ('incoming' === type) return connection.emit('data', packet.data, raw);
  
      connection._write(packet.data);
    }));
  
    return this;
  };
  
  /**
   * Retrieve the current id from the server.
   *
   * @param {Function} fn Callback function.
   * @returns {Primus}
   * @api public
   */
  Primus.prototype.id = function id(fn) {
    if (this.socket && this.socket.id) return fn(this.socket.id);
  
    this._write('primus::id::');
    return this.once('incoming::id', fn);
  };
  
  /**
   * Establish a connection with the server. When this function is called we
   * assume that we don't have any open connections. If you do call it when you
   * have a connection open, it could cause duplicate connections.
   *
   * @returns {Primus}
   * @api public
   */
  Primus.prototype.open = function open() {
    context(this, 'open');
  
    //
    // Only start a `connection timeout` procedure if we're not reconnecting as
    // that shouldn't count as an initial connection. This should be started
    // before the connection is opened to capture failing connections and kill the
    // timeout.
    //
    if (!this.recovery.reconnecting() && this.options.timeout) this.timeout();
  
    this.emit('outgoing::open');
    return this;
  };
  
  /**
   * Send a new message.
   *
   * @param {Mixed} data The data that needs to be written.
   * @returns {Boolean} Always returns true as we don't support back pressure.
   * @api public
   */
  Primus.prototype.write = function write(data) {
    context(this, 'write');
    this.transforms(this, this, 'outgoing', data);
  
    return true;
  };
  
  /**
   * The actual message writer.
   *
   * @param {Mixed} data The message that needs to be written.
   * @returns {Boolean} Successful write to the underlaying transport.
   * @api private
   */
  Primus.prototype._write = function write(data) {
    var primus = this;
  
    //
    // The connection is closed, normally this would already be done in the
    // `spark.write` method, but as `_write` is used internally, we should also
    // add the same check here to prevent potential crashes by writing to a dead
    // socket.
    //
    if (Primus.OPEN !== primus.readyState) {
      //
      // If the buffer is at capacity, remove the first item.
      //
      if (this.buffer.length === this.options.queueSize) {
        this.buffer.splice(0, 1);
      }
  
      this.buffer.push(data);
      return false;
    }
  
    primus.encoder(data, function encoded(err, packet) {
      //
      // Do a "safe" emit('error') when we fail to parse a message. We don't
      // want to throw here as listening to errors should be optional.
      //
      if (err) return primus.listeners('error').length && primus.emit('error', err);
  
      //
      // Hack 1: \u2028 and \u2029 are allowed inside a JSON string, but JavaScript
      // defines them as newline separators. Unescaped control characters are not
      // allowed inside JSON strings, so this causes an error at parse time. We
      // work around this issue by escaping these characters. This can cause
      // errors with JSONP requests or if the string is just evaluated.
      //
      if ('string' === typeof packet) {
        if (~packet.indexOf('\u2028')) packet = packet.replace(u2028, '\\u2028');
        if (~packet.indexOf('\u2029')) packet = packet.replace(u2029, '\\u2029');
      }
  
      primus.emit('outgoing::data', packet);
    });
  
    return true;
  };
  
  /**
   * Set a timer that, upon expiration, closes the client.
   *
   * @returns {Primus}
   * @api private
   */
  Primus.prototype.heartbeat = function heartbeat() {
    if (!this.options.pingTimeout) return this;
  
    this.timers.clear('heartbeat');
    this.timers.setTimeout('heartbeat', function expired() {
      //
      // The network events already captured the offline event.
      //
      if (!this.online) return;
  
      this.online = false;
      this.emit('offline');
      this.emit('incoming::end');
    }, this.options.pingTimeout);
  
    return this;
  };
  
  /**
   * Start a connection timeout.
   *
   * @returns {Primus}
   * @api private
   */
  Primus.prototype.timeout = function timeout() {
    var primus = this;
  
    /**
     * Remove all references to the timeout listener as we've received an event
     * that can be used to determine state.
     *
     * @api private
     */
    function remove() {
      primus.removeListener('error', remove)
            .removeListener('open', remove)
            .removeListener('end', remove)
            .timers.clear('connect');
    }
  
    primus.timers.setTimeout('connect', function expired() {
      remove(); // Clean up old references.
  
      if (primus.readyState === Primus.OPEN || primus.recovery.reconnecting()) {
        return;
      }
  
      primus.emit('timeout');
  
      //
      // We failed to connect to the server.
      //
      if (~primus.options.strategy.indexOf('timeout')) {
        primus.recovery.reconnect();
      } else {
        primus.end();
      }
    }, primus.options.timeout);
  
    return primus.on('error', remove)
      .on('open', remove)
      .on('end', remove);
  };
  
  /**
   * Close the connection completely.
   *
   * @param {Mixed} data last packet of data.
   * @returns {Primus}
   * @api public
   */
  Primus.prototype.end = function end(data) {
    context(this, 'end');
  
    if (
        this.readyState === Primus.CLOSED
      && !this.timers.active('connect')
      && !this.timers.active('open')
    ) {
      //
      // If we are reconnecting stop the reconnection procedure.
      //
      if (this.recovery.reconnecting()) {
        this.recovery.reset();
        this.emit('end');
      }
  
      return this;
    }
  
    if (data !== undefined) this.write(data);
  
    this.writable = false;
    this.readable = false;
  
    var readyState = this.readyState;
    this.readyState = Primus.CLOSED;
  
    if (readyState !== this.readyState) {
      this.emit('readyStateChange', 'end');
    }
  
    this.timers.clear();
    this.emit('outgoing::end');
    this.emit('close');
    this.emit('end');
  
    return this;
  };
  
  /**
   * Completely demolish the Primus instance and forcefully nuke all references.
   *
   * @returns {Boolean}
   * @api public
   */
  Primus.prototype.destroy = destroy('url timers options recovery socket transport transformers', {
    before: 'end',
    after: ['removeAllListeners', function detach() {
      if (!this.NETWORK_EVENTS) return;
  
      if (window.addEventListener) {
        window.removeEventListener('offline', this.offlineHandler);
        window.removeEventListener('online', this.onlineHandler);
      } else if (document.body.attachEvent){
        document.body.detachEvent('onoffline', this.offlineHandler);
        document.body.detachEvent('ononline', this.onlineHandler);
      }
    }]
  });
  
  /**
   * Create a shallow clone of a given object.
   *
   * @param {Object} obj The object that needs to be cloned.
   * @returns {Object} Copy.
   * @api private
   */
  Primus.prototype.clone = function clone(obj) {
    return this.merge({}, obj);
  };
  
  /**
   * Merge different objects in to one target object.
   *
   * @param {Object} target The object where everything should be merged in.
   * @returns {Object} Original target with all merged objects.
   * @api private
   */
  Primus.prototype.merge = function merge(target) {
    for (var i = 1, key, obj; i < arguments.length; i++) {
      obj = arguments[i];
  
      for (key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key))
          target[key] = obj[key];
      }
    }
  
    return target;
  };
  
  /**
   * Parse the connection string.
   *
   * @type {Function}
   * @param {String} url Connection URL.
   * @returns {Object} Parsed connection.
   * @api private
   */
  Primus.prototype.parse = _dereq_('url-parse');
  
  /**
   * Parse a query string.
   *
   * @param {String} query The query string that needs to be parsed.
   * @returns {Object} Parsed query string.
   * @api private
   */
  Primus.prototype.querystring = qs.parse;
  /**
   * Transform a query string object back into string equiv.
   *
   * @param {Object} obj The query string object.
   * @returns {String}
   * @api private
   */
  Primus.prototype.querystringify = qs.stringify;
  
  /**
   * Generates a connection URI.
   *
   * @param {String} protocol The protocol that should used to crate the URI.
   * @returns {String|options} The URL.
   * @api private
   */
  Primus.prototype.uri = function uri(options) {
    var url = this.url
      , server = []
      , qsa = false;
  
    //
    // Query strings are only allowed when we've received clearance for it.
    //
    if (options.query) qsa = true;
  
    options = options || {};
    options.protocol = 'protocol' in options
      ? options.protocol
      : 'http:';
    options.query = url.query && qsa
      ? url.query.slice(1)
      : false;
    options.secure = 'secure' in options
      ? options.secure
      : url.protocol === 'https:' || url.protocol === 'wss:';
    options.auth = 'auth' in options
      ? options.auth
      : url.auth;
    options.pathname = 'pathname' in options
      ? options.pathname
      : this.pathname;
    options.port = 'port' in options
      ? +options.port
      : +url.port || (options.secure ? 443 : 80);
  
    //
    // We need to make sure that we create a unique connection URL every time to
    // prevent back forward cache from becoming an issue. We're doing this by
    // forcing an cache busting query string in to the URL.
    //
    var querystring = this.querystring(options.query || '');
    querystring._primuscb = yeast();
    options.query = this.querystringify(querystring);
  
    //
    // Allow transformation of the options before we construct a full URL from it.
    //
    this.emit('outgoing::url', options);
  
    //
    // Automatically suffix the protocol so we can supply `ws:` and `http:` and
    // it gets transformed correctly.
    //
    server.push(options.secure ? options.protocol.replace(':', 's:') : options.protocol, '');
  
    server.push(options.auth ? options.auth +'@'+ url.host : url.host);
  
    //
    // Pathnames are optional as some Transformers would just use the pathname
    // directly.
    //
    if (options.pathname) server.push(options.pathname.slice(1));
  
    //
    // Optionally add a search query.
    //
    if (qsa) server[server.length - 1] += '?'+ options.query;
    else delete options.query;
  
    if (options.object) return options;
    return server.join('/');
  };
  
  /**
   * Register a new message transformer. This allows you to easily manipulate incoming
   * and outgoing data which is particularity handy for plugins that want to send
   * meta data together with the messages.
   *
   * @param {String} type Incoming or outgoing
   * @param {Function} fn A new message transformer.
   * @returns {Primus}
   * @api public
   */
  Primus.prototype.transform = function transform(type, fn) {
    context(this, 'transform');
  
    if (!(type in this.transformers)) {
      return this.critical(new Error('Invalid transformer type'));
    }
  
    this.transformers[type].push(fn);
    return this;
  };
  
  /**
   * A critical error has occurred, if we have an `error` listener, emit it there.
   * If not, throw it, so we get a stack trace + proper error message.
   *
   * @param {Error} err The critical error.
   * @returns {Primus}
   * @api private
   */
  Primus.prototype.critical = function critical(err) {
    if (this.emit('error', err)) return this;
  
    throw err;
  };
  
  /**
   * Syntax sugar, adopt a Socket.IO like API.
   *
   * @param {String} url The URL we want to connect to.
   * @param {Object} options Connection options.
   * @returns {Primus}
   * @api public
   */
  Primus.connect = function connect(url, options) {
    return new Primus(url, options);
  };
  
  //
  // Expose the EventEmitter so it can be re-used by wrapping libraries we're also
  // exposing the Stream interface.
  //
  Primus.EventEmitter = EventEmitter;
  
  //
  // These libraries are automatically inserted at the server-side using the
  // Primus#library method.
  //
  Primus.prototype.client = function client() {
    var primus = this
      , socket;
  
    //
    // Select an available WebSocket factory.
    //
    var Factory = (function factory() {
      if ('undefined' !== typeof WebSocket) return WebSocket;
      if ('undefined' !== typeof MozWebSocket) return MozWebSocket;
  
      try { return Primus.requires('ws'); }
      catch (e) {}
  
      return undefined;
    })();
  
    if (!Factory) return primus.critical(new Error(
      'Missing required `ws` module. Please run `npm install --save ws`'
    ));
  
    //
    // Connect to the given URL.
    //
    primus.on('outgoing::open', function opening() {
      primus.emit('outgoing::end');
  
      //
      // FireFox will throw an error when we try to establish a connection from
      // a secure page to an unsecured WebSocket connection. This is inconsistent
      // behaviour between different browsers. This should ideally be solved in
      // Primus when we connect.
      //
      try {
        var options = {
          protocol: primus.url.protocol === 'ws+unix:' ? 'ws+unix:' : 'ws:',
          query: true
        };
  
        //
        // Only allow primus.transport object in Node.js, it will throw in
        // browsers with a TypeError if we supply to much arguments.
        //
        if (Factory.length === 3) {
          if ('ws+unix:' === options.protocol) {
            options.pathname = primus.url.pathname +':'+ primus.pathname;
          }
          primus.socket = socket = new Factory(
            primus.uri(options),  // URL
            [],                   // Sub protocols
            primus.transport      // options.
          );
        } else {
          primus.socket = socket = new Factory(primus.uri(options));
          socket.binaryType = 'arraybuffer';
        }
      } catch (e) { return primus.emit('error', e); }
  
      //
      // Setup the Event handlers.
      //
      socket.onopen = primus.emits('incoming::open');
      socket.onerror = primus.emits('incoming::error');
      socket.onclose = primus.emits('incoming::end');
      socket.onmessage = primus.emits('incoming::data', function parse(next, evt) {
        next(undefined, evt.data);
      });
    });
  
    //
    // We need to write a new message to the socket.
    //
    primus.on('outgoing::data', function write(message) {
      if (!socket || socket.readyState !== Factory.OPEN) return;
  
      try { socket.send(message); }
      catch (e) { primus.emit('incoming::error', e); }
    });
  
    //
    // Attempt to reconnect the socket.
    //
    primus.on('outgoing::reconnect', function reconnect() {
      primus.emit('outgoing::open');
    });
  
    //
    // We need to close the socket.
    //
    primus.on('outgoing::end', function close() {
      if (!socket) return;
  
      socket.onerror = socket.onopen = socket.onclose = socket.onmessage = function () {};
      socket.close();
      socket = null;
    });
  };
  Primus.prototype.authorization = false;
  Primus.prototype.pathname = "/primus";
  Primus.prototype.encoder = function encoder(data, fn) {
    var err;
  
    try { data = JSON.stringify(data); }
    catch (e) { err = e; }
  
    fn(err, data);
  };
  Primus.prototype.decoder = function decoder(data, fn) {
    var err;
  
    if ('string' !== typeof data) return fn(err, data);
  
    try { data = JSON.parse(data); }
    catch (e) { err = e; }
  
    fn(err, data);
  };
  Primus.prototype.version = "7.2.3";
  
  if (
       'undefined' !== typeof document
    && 'undefined' !== typeof navigator
  ) {
    //
    // Hack 2: If you press ESC in FireFox it will close all active connections.
    // Normally this makes sense, when your page is still loading. But versions
    // before FireFox 22 will close all connections including WebSocket connections
    // after page load. One way to prevent this is to do a `preventDefault()` and
    // cancel the operation before it bubbles up to the browsers default handler.
    // It needs to be added as `keydown` event, if it's added keyup it will not be
    // able to prevent the connection from being closed.
    //
    if (document.addEventListener) {
      document.addEventListener('keydown', function keydown(e) {
        if (e.keyCode !== 27 || !e.preventDefault) return;
  
        e.preventDefault();
      }, false);
    }
  
    //
    // Hack 3: This is a Mac/Apple bug only, when you're behind a reverse proxy or
    // have you network settings set to `automatic proxy discovery` the safari
    // browser will crash when the WebSocket constructor is initialised. There is
    // no way to detect the usage of these proxies available in JavaScript so we
    // need to do some nasty browser sniffing. This only affects Safari versions
    // lower then 5.1.4
    //
    var ua = (navigator.userAgent || '').toLowerCase()
      , parsed = ua.match(/.+(?:rv|it|ra|ie)[/: ](\d+)\.(\d+)(?:\.(\d+))?/) || []
      , version = +[parsed[1], parsed[2]].join('.');
  
    if (
         !~ua.indexOf('chrome')
      && ~ua.indexOf('safari')
      && version < 534.54
    ) {
      Primus.prototype.AVOID_WEBSOCKETS = true;
    }
  }
  
  //
  // Expose the library.
  //
  module.exports = Primus;
  
  },{"demolish":1,"emits":2,"eventemitter3":3,"inherits":4,"querystringify":8,"recovery":9,"tick-tock":12,"url-parse":14,"yeast":15}]},{},[16])(16)
  ;
  Primus.prototype.ark["graphql"] = function (primus, primusOpts) {
  
  (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  /**
   * @module 101/assign
   */
  
  /**
   * Copies enumerable and own properties from a source object(s) to a target object, aka extend.
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
   * I added functionality to support assign as a partial function
   * @function module:101/assign
   * @param {object} [target] - object which source objects are extending (being assigned to)
   * @param {object} sources... - objects whose properties are being assigned to the source object
   * @return {object} source with extended properties
   */
  module.exports = assign;
  
  function assign (target, firstSource) {
    if (arguments.length === 1) {
      firstSource = arguments[0];
      return function (target) {
        return assign(target, firstSource);
      };
    }
    if (target === undefined || target === null)
      throw new TypeError('Cannot convert first argument to object');
    var to = Object(target);
    for (var i = 1; i < arguments.length; i++) {
      var nextSource = arguments[i];
      if (nextSource === undefined || nextSource === null) continue;
      var keysArray = Object.keys(Object(nextSource));
      for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
        var nextKey = keysArray[nextIndex];
        Object.getOwnPropertyDescriptor(nextSource, nextKey);
        // I changed the following line to get 100% test coverage.
        // if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
        // I was unable to find a scenario where desc was undefined or that desc.enumerable was false:
        //   1) Object.defineProperty does not accept undefined as a desc
        //   2) Object.keys does not return non-enumerable keys.
        // Let me know if this is a cross browser thing.
        to[nextKey] = nextSource[nextKey];
      }
    }
    return to;
  }
  },{}],2:[function(require,module,exports){
  /**
   * @module 101/bind-all
   */
  
  var isFunction = require('./is-function');
  var keysIn = require('./keys-in');
  /**
   * Bind a passed object methods.
   * If methods name to bing are not specified, all the object methods are binded
   * @function module:101/bind-all
   *
   * @param {object} object - object to bind
   * @param {array|string} [methods] - array or space-separated string containing the names of the methods to bind
   * @return {object} the binded object
   */
  module.exports = bindAll;
  
  function bindAll (object, methods) {
    if (methods && !Array.isArray(methods)) {
      throw new TypeError('The second argument must be an array');
    }
  
    var keys = methods || keysIn(object);
  
    // Bind all the specified methods
    keys.forEach(function(key) {
      var target = object[key];
      // skip for non-functions and when the target does not exist
      if (!target || !isFunction(target)) { return; }
  
      object[key] = target.bind(object);
    });
  
    return object;
  }
  
  },{"./is-function":7,"./keys-in":9}],3:[function(require,module,exports){
  /**
   * @module 101/defaults
   */
  
  var isObject = require('./is-object');
  var isBoolean = require('./is-boolean');
  var exists = require('./exists');
  
  /**
   * Mixes in properties from source into target when
   * the property is not a property of `target`
   * @param  {Object} [target] Mix into
   * @param  {Object} source The defaults description
   * @return {Object}        THe resulting target
   */
  module.exports = defaults;
  
  function defaults (target, source, deep) {
    if (arguments.length === 1) {
      source = target;
      return function (target) {
        return defaults(target, source);
      };
    } else if (isBoolean(source)) {
      deep = source;
      source = target;
      return function (target) {
        return defaults(target, source, deep);
      };
    }
    target = target || {};
    deep = deep || false;
    if (!source) {
      return target;
    }
    return reduceObject(target, source, deep);
  }
  
  function reduceObject (target, source, deep) {
    return Object.keys(source).reduce(function (target, key) {
      if (isObject(target[key]) && isObject(source[key]) && deep) {
        reduceObject(target[key], source[key]);
        return target;
      }
      target[key] = exists(target[key]) ? target[key] : source[key];
      return target;
    }, target);
  }
  
  },{"./exists":5,"./is-boolean":6,"./is-object":8}],4:[function(require,module,exports){
  /**
   * @module 101/equals
   */
  
  /**
   * Functional implementation of Object.is with polyfill for browsers without implementations of Object.is
   * @function module:101/equals
   * @param {*} a - any value
   * @param {*} b - any value
   * @return {boolean} Object.is(a, b)
   */
  module.exports = function (a, b) {
    if (arguments.length === 1) {
      return equals.bind(null, a);
    }
    else {
      return equals(a, b);
    }
  };
  
  function equals (v1, v2) {
    if (Object.is) {
      return Object.is(v1, v2);
    }
    else {
      // ES6 Object.is polyfill
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
      if (v1 === 0 && v2 === 0) {
        return 1 / v1 === 1 / v2;
      }
      if (v1 !== v1) {
        return v2 !== v2;
      }
      return v1 === v2;
    }
  }
  
  },{}],5:[function(require,module,exports){
  /**
   * @module {function} 101/exists
   * @type {function}
   */
  
  /**
   * Returns false for null and undefined, true for everything else.
   * @function module:101/exists
   * @param val {*} - value to be existance checked
   * @return {boolean} whether the value exists or not
   */
  module.exports = exists;
  
  function exists (val) {
    return val !== undefined && val !== null;
  }
  },{}],6:[function(require,module,exports){
  /**
   * @module 101/is-boolean
   */
  
  /**
   * Functional version of val typeof 'boolean'
   * @function module:101/is-boolean
   * @param {*} val - value checked to be a boolean
   * @return {boolean} Whether the value is a boolean or not
   */
  module.exports = isBoolean;
  
  function isBoolean (val) {
    return typeof val === 'boolean';
  }
  },{}],7:[function(require,module,exports){
  /**
   * @module 101/is-function
   */
  
  /**
   * Functional version of val typeof 'function'
   * @function module:101/is-function
   * @param {*} val - value checked to be a function
   * @return {boolean} Whether the value is a function or not
   */
  module.exports = isFunction;
  
  function isFunction (v) {
    return typeof v === 'function';
  }
  },{}],8:[function(require,module,exports){
  /**
   * Functional version of a strict object check (Arrays and RegExps are not objects)
   * @module 101/is-object
   */
  
  /**
   * @function module:101/is-object
   * @param {*} val - value checked to be an object
   * @return {boolean} Whether the value is an object or not
   */
  var exists = require('./exists');
  
  module.exports = isObject;
  
  function isObject (val) {
    return typeof val === 'object' &&
      exists(val) &&
      !Array.isArray(val) &&
      !(val instanceof RegExp) &&
      !(val instanceof String) &&
      !(val instanceof Number);
  }
  },{"./exists":5}],9:[function(require,module,exports){
  /**
   * @module 101/keys-in
   */
  
  /**
   * Get all the keys compositing an object, including the `Object.prototype`
   * @function module:101/keys-in
   *
   * @param {object} object - the object from which to extract the keys
   * @return {array} array of keys
   */
  module.exports = keysIn;
  
  function keysIn(object) {
    if (!object) { return []; }
  
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
  
    return keys;
  }
  
  },{}],10:[function(require,module,exports){
  /**
   * @module 101/noop
   */
  
  /**
   * Does nothing - no operation
   */
  module.exports = function () {};
  },{}],11:[function(require,module,exports){
  /**
   * @module 101/not
   */
  
  var isFunction = require('./is-function');
  
  /**
   * Functional version of !
   * @function module:101/not
   * @param {*} val - value to inverse
   * @return {function} - function whose arguments and context are applied to fn and result is inversed
   */
  module.exports = not;
  
  function not (val) {
    if (isFunction(val)) {
      return function (/* args */) {
        return not(val.apply(this, arguments));
      };
    }
    else {
      return !val;
    }
  }
  },{"./is-function":7}],12:[function(require,module,exports){
  (function (global){
  'use strict';
  
  // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  // original notice:
  
  /*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   */
  function compare(a, b) {
    if (a === b) {
      return 0;
    }
  
    var x = a.length;
    var y = b.length;
  
    for (var i = 0, len = Math.min(x, y); i < len; ++i) {
      if (a[i] !== b[i]) {
        x = a[i];
        y = b[i];
        break;
      }
    }
  
    if (x < y) {
      return -1;
    }
    if (y < x) {
      return 1;
    }
    return 0;
  }
  function isBuffer(b) {
    if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
      return global.Buffer.isBuffer(b);
    }
    return !!(b != null && b._isBuffer);
  }
  
  // based on node assert, original notice:
  
  // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  //
  // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  //
  // Originally from narwhal.js (http://narwhaljs.org)
  // Copyright (c) 2009 Thomas Robinson <280north.com>
  //
  // 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 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.
  
  var util = require('util/');
  var hasOwn = Object.prototype.hasOwnProperty;
  var pSlice = Array.prototype.slice;
  var functionsHaveNames = (function () {
    return function foo() {}.name === 'foo';
  }());
  function pToString (obj) {
    return Object.prototype.toString.call(obj);
  }
  function isView(arrbuf) {
    if (isBuffer(arrbuf)) {
      return false;
    }
    if (typeof global.ArrayBuffer !== 'function') {
      return false;
    }
    if (typeof ArrayBuffer.isView === 'function') {
      return ArrayBuffer.isView(arrbuf);
    }
    if (!arrbuf) {
      return false;
    }
    if (arrbuf instanceof DataView) {
      return true;
    }
    if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
      return true;
    }
    return false;
  }
  // 1. The assert module provides functions that throw
  // AssertionError's when particular conditions are not met. The
  // assert module must conform to the following interface.
  
  var assert = module.exports = ok;
  
  // 2. The AssertionError is defined in assert.
  // new assert.AssertionError({ message: message,
  //                             actual: actual,
  //                             expected: expected })
  
  var regex = /\s*function\s+([^\(\s]*)\s*/;
  // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  function getName(func) {
    if (!util.isFunction(func)) {
      return;
    }
    if (functionsHaveNames) {
      return func.name;
    }
    var str = func.toString();
    var match = str.match(regex);
    return match && match[1];
  }
  assert.AssertionError = function AssertionError(options) {
    this.name = 'AssertionError';
    this.actual = options.actual;
    this.expected = options.expected;
    this.operator = options.operator;
    if (options.message) {
      this.message = options.message;
      this.generatedMessage = false;
    } else {
      this.message = getMessage(this);
      this.generatedMessage = true;
    }
    var stackStartFunction = options.stackStartFunction || fail;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, stackStartFunction);
    } else {
      // non v8 browsers so we can have a stacktrace
      var err = new Error();
      if (err.stack) {
        var out = err.stack;
  
        // try to strip useless frames
        var fn_name = getName(stackStartFunction);
        var idx = out.indexOf('\n' + fn_name);
        if (idx >= 0) {
          // once we have located the function frame
          // we need to strip out everything before it (and its line)
          var next_line = out.indexOf('\n', idx + 1);
          out = out.substring(next_line + 1);
        }
  
        this.stack = out;
      }
    }
  };
  
  // assert.AssertionError instanceof Error
  util.inherits(assert.AssertionError, Error);
  
  function truncate(s, n) {
    if (typeof s === 'string') {
      return s.length < n ? s : s.slice(0, n);
    } else {
      return s;
    }
  }
  function inspect(something) {
    if (functionsHaveNames || !util.isFunction(something)) {
      return util.inspect(something);
    }
    var rawname = getName(something);
    var name = rawname ? ': ' + rawname : '';
    return '[Function' +  name + ']';
  }
  function getMessage(self) {
    return truncate(inspect(self.actual), 128) + ' ' +
           self.operator + ' ' +
           truncate(inspect(self.expected), 128);
  }
  
  // At present only the three keys mentioned above are used and
  // understood by the spec. Implementations or sub modules can pass
  // other keys to the AssertionError's constructor - they will be
  // ignored.
  
  // 3. All of the following functions must throw an AssertionError
  // when a corresponding condition is not met, with a message that
  // may be undefined if not provided.  All assertion methods provide
  // both the actual and expected values to the assertion error for
  // display purposes.
  
  function fail(actual, expected, message, operator, stackStartFunction) {
    throw new assert.AssertionError({
      message: message,
      actual: actual,
      expected: expected,
      operator: operator,
      stackStartFunction: stackStartFunction
    });
  }
  
  // EXTENSION! allows for well behaved errors defined elsewhere.
  assert.fail = fail;
  
  // 4. Pure assertion tests whether a value is truthy, as determined
  // by !!guard.
  // assert.ok(guard, message_opt);
  // This statement is equivalent to assert.equal(true, !!guard,
  // message_opt);. To test strictly for the value true, use
  // assert.strictEqual(true, guard, message_opt);.
  
  function ok(value, message) {
    if (!value) fail(value, true, message, '==', assert.ok);
  }
  assert.ok = ok;
  
  // 5. The equality assertion tests shallow, coercive equality with
  // ==.
  // assert.equal(actual, expected, message_opt);
  
  assert.equal = function equal(actual, expected, message) {
    if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  };
  
  // 6. The non-equality assertion tests for whether two objects are not equal
  // with != assert.notEqual(actual, expected, message_opt);
  
  assert.notEqual = function notEqual(actual, expected, message) {
    if (actual == expected) {
      fail(actual, expected, message, '!=', assert.notEqual);
    }
  };
  
  // 7. The equivalence assertion tests a deep equality relation.
  // assert.deepEqual(actual, expected, message_opt);
  
  assert.deepEqual = function deepEqual(actual, expected, message) {
    if (!_deepEqual(actual, expected, false)) {
      fail(actual, expected, message, 'deepEqual', assert.deepEqual);
    }
  };
  
  assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
    if (!_deepEqual(actual, expected, true)) {
      fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
    }
  };
  
  function _deepEqual(actual, expected, strict, memos) {
    // 7.1. All identical values are equivalent, as determined by ===.
    if (actual === expected) {
      return true;
    } else if (isBuffer(actual) && isBuffer(expected)) {
      return compare(actual, expected) === 0;
  
    // 7.2. If the expected value is a Date object, the actual value is
    // equivalent if it is also a Date object that refers to the same time.
    } else if (util.isDate(actual) && util.isDate(expected)) {
      return actual.getTime() === expected.getTime();
  
    // 7.3 If the expected value is a RegExp object, the actual value is
    // equivalent if it is also a RegExp object with the same source and
    // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
    } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
      return actual.source === expected.source &&
             actual.global === expected.global &&
             actual.multiline === expected.multiline &&
             actual.lastIndex === expected.lastIndex &&
             actual.ignoreCase === expected.ignoreCase;
  
    // 7.4. Other pairs that do not both pass typeof value == 'object',
    // equivalence is determined by ==.
    } else if ((actual === null || typeof actual !== 'object') &&
               (expected === null || typeof expected !== 'object')) {
      return strict ? actual === expected : actual == expected;
  
    // If both values are instances of typed arrays, wrap their underlying
    // ArrayBuffers in a Buffer each to increase performance
    // This optimization requires the arrays to have the same type as checked by
    // Object.prototype.toString (aka pToString). Never perform binary
    // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
    // bit patterns are not identical.
    } else if (isView(actual) && isView(expected) &&
               pToString(actual) === pToString(expected) &&
               !(actual instanceof Float32Array ||
                 actual instanceof Float64Array)) {
      return compare(new Uint8Array(actual.buffer),
                     new Uint8Array(expected.buffer)) === 0;
  
    // 7.5 For all other Object pairs, including Array objects, equivalence is
    // determined by having the same number of owned properties (as verified
    // with Object.prototype.hasOwnProperty.call), the same set of keys
    // (although not necessarily the same order), equivalent values for every
    // corresponding key, and an identical 'prototype' property. Note: this
    // accounts for both named and indexed properties on Arrays.
    } else if (isBuffer(actual) !== isBuffer(expected)) {
      return false;
    } else {
      memos = memos || {actual: [], expected: []};
  
      var actualIndex = memos.actual.indexOf(actual);
      if (actualIndex !== -1) {
        if (actualIndex === memos.expected.indexOf(expected)) {
          return true;
        }
      }
  
      memos.actual.push(actual);
      memos.expected.push(expected);
  
      return objEquiv(actual, expected, strict, memos);
    }
  }
  
  function isArguments(object) {
    return Object.prototype.toString.call(object) == '[object Arguments]';
  }
  
  function objEquiv(a, b, strict, actualVisitedObjects) {
    if (a === null || a === undefined || b === null || b === undefined)
      return false;
    // if one is a primitive, the other must be same
    if (util.isPrimitive(a) || util.isPrimitive(b))
      return a === b;
    if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
      return false;
    var aIsArgs = isArguments(a);
    var bIsArgs = isArguments(b);
    if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
      return false;
    if (aIsArgs) {
      a = pSlice.call(a);
      b = pSlice.call(b);
      return _deepEqual(a, b, strict);
    }
    var ka = objectKeys(a);
    var kb = objectKeys(b);
    var key, i;
    // having the same number of owned properties (keys incorporates
    // hasOwnProperty)
    if (ka.length !== kb.length)
      return false;
    //the same set of keys (although not necessarily the same order),
    ka.sort();
    kb.sort();
    //~~~cheap key test
    for (i = ka.length - 1; i >= 0; i--) {
      if (ka[i] !== kb[i])
        return false;
    }
    //equivalent values for every corresponding key, and
    //~~~possibly expensive deep test
    for (i = ka.length - 1; i >= 0; i--) {
      key = ka[i];
      if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
        return false;
    }
    return true;
  }
  
  // 8. The non-equivalence assertion tests for any deep inequality.
  // assert.notDeepEqual(actual, expected, message_opt);
  
  assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
    if (_deepEqual(actual, expected, false)) {
      fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
    }
  };
  
  assert.notDeepStrictEqual = notDeepStrictEqual;
  function notDeepStrictEqual(actual, expected, message) {
    if (_deepEqual(actual, expected, true)) {
      fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
    }
  }
  
  
  // 9. The strict equality assertion tests strict equality, as determined by ===.
  // assert.strictEqual(actual, expected, message_opt);
  
  assert.strictEqual = function strictEqual(actual, expected, message) {
    if (actual !== expected) {
      fail(actual, expected, message, '===', assert.strictEqual);
    }
  };
  
  // 10. The strict non-equality assertion tests for strict inequality, as
  // determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
  
  assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
    if (actual === expected) {
      fail(actual, expected, message, '!==', assert.notStrictEqual);
    }
  };
  
  function expectedException(actual, expected) {
    if (!actual || !expected) {
      return false;
    }
  
    if (Object.prototype.toString.call(expected) == '[object RegExp]') {
      return expected.test(actual);
    }
  
    try {
      if (actual instanceof expected) {
        return true;
      }
    } catch (e) {
      // Ignore.  The instanceof check doesn't work for arrow functions.
    }
  
    if (Error.isPrototypeOf(expected)) {
      return false;
    }
  
    return expected.call({}, actual) === true;
  }
  
  function _tryBlock(block) {
    var error;
    try {
      block();
    } catch (e) {
      error = e;
    }
    return error;
  }
  
  function _throws(shouldThrow, block, expected, message) {
    var actual;
  
    if (typeof block !== 'function') {
      throw new TypeError('"block" argument must be a function');
    }
  
    if (typeof expected === 'string') {
      message = expected;
      expected = null;
    }
  
    actual = _tryBlock(block);
  
    message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
              (message ? ' ' + message : '.');
  
    if (shouldThrow && !actual) {
      fail(actual, expected, 'Missing expected exception' + message);
    }
  
    var userProvidedMessage = typeof message === 'string';
    var isUnwantedException = !shouldThrow && util.isError(actual);
    var isUnexpectedException = !shouldThrow && actual && !expected;
  
    if ((isUnwantedException &&
        userProvidedMessage &&
        expectedException(actual, expected)) ||
        isUnexpectedException) {
      fail(actual, expected, 'Got unwanted exception' + message);
    }
  
    if ((shouldThrow && actual && expected &&
        !expectedException(actual, expected)) || (!shouldThrow && actual)) {
      throw actual;
    }
  }
  
  // 11. Expected to throw an error:
  // assert.throws(block, Error_opt, message_opt);
  
  assert.throws = function(block, /*optional*/error, /*optional*/message) {
    _throws(true, block, error, message);
  };
  
  // EXTENSION! This is annoying to write outside this module.
  assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
    _throws(false, block, error, message);
  };
  
  assert.ifError = function(err) { if (err) throw err; };
  
  var objectKeys = Object.keys || function (obj) {
    var keys = [];
    for (var key in obj) {
      if (hasOwn.call(obj, key)) keys.push(key);
    }
    return keys;
  };
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"util/":81}],13:[function(require,module,exports){
  (function (process,global){
  "use strict"
  
  var next = (global.process && process.nextTick) || global.setImmediate || function (f) {
    setTimeout(f, 0)
  }
  
  module.exports = function maybe (cb, promise) {
    if (cb) {
      promise
        .then(function (result) {
          next(function () { cb(null, result) })
        }, function (err) {
          next(function () { cb(err) })
        })
      return undefined
    }
    else {
      return promise
    }
  }
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"_process":20}],14:[function(require,module,exports){
  /**
   * 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' : '');
  }
  
  },{}],15:[function(require,module,exports){
  (function (process){
  /* 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;
  	}
  
  	const 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
  	let index = 0;
  	let lastC = 0;
  	args[0].replace(/%[a-zA-Z%]/g, 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(...args) {
  	// This hackery is required for IE8/9, where
  	// the `console.log` function doesn't have 'apply'
  	return typeof console === 'object' &&
  		console.log &&
  		console.log(...args);
  }
  
  /**
   * 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() {
  	let 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 = require('./common')(exports);
  
  const {formatters} = module.exports;
  
  /**
   * 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;
  	}
  };
  
  }).call(this,require('_process'))
  },{"./common":16,"_process":20}],16:[function(require,module,exports){
  
  /**
   * 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 = require('ms');
  
  	Object.keys(env).forEach(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) {
  		let hash = 0;
  
  		for (let 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) {
  		let prevTime;
  
  		function debug(...args) {
  			// Disabled?
  			if (!debug.enabled) {
  				return;
  			}
  
  			const self = debug;
  
  			// Set `diff` timestamp
  			const curr = Number(new Date());
  			const 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
  			let index = 0;
  			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  				// If we encounter an escaped % then don't increase the array index
  				if (match === '%%') {
  					return match;
  				}
  				index++;
  				const formatter = createDebug.formatters[format];
  				if (typeof formatter === 'function') {
  					const 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);
  
  			const 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() {
  		const index = createDebug.instances.indexOf(this);
  		if (index !== -1) {
  			createDebug.instances.splice(index, 1);
  			return true;
  		}
  		return false;
  	}
  
  	function extend(namespace, delimiter) {
  		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  		newDebug.log = this.log;
  		return newDebug;
  	}
  
  	/**
  	* 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 = [];
  
  		let i;
  		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  		const 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++) {
  			const instance = createDebug.instances[i];
  			instance.enabled = createDebug.enabled(instance.namespace);
  		}
  	}
  
  	/**
  	* Disable debug output.
  	*
  	* @return {String} namespaces
  	* @api public
  	*/
  	function disable() {
  		const namespaces = [
  			...createDebug.names.map(toNamespace),
  			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  		].join(',');
  		createDebug.enable('');
  		return namespaces;
  	}
  
  	/**
  	* 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;
  		}
  
  		let i;
  		let 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;
  	}
  
  	/**
  	* Convert regexp to namespace
  	*
  	* @param {RegExp} regxep
  	* @return {String} namespace
  	* @api private
  	*/
  	function toNamespace(regexp) {
  		return regexp.toString()
  			.substring(2, regexp.toString().length - 2)
  			.replace(/\.\*\?$/, '*');
  	}
  
  	/**
  	* 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;
  
  },{"ms":14}],17:[function(require,module,exports){
  var exists = require('101/exists')
  var assign = require('101/assign')
  
  module.exports = errToJSON
  
  function errToJSON (err) {
    var keys = [
      'name',
      'message',
      'stack',
      'code',
      'errno',
      'syscall'
    ].concat(Object.keys(err))
    // cache Error.prototype.toJSON
    var cachedToJSON = Error.prototype.toJSON
    // stub Error.prototype.toJSON (converts nested errors to json)
    Error.prototype.toJSON = stubToJSON
    // convert to json
    var json = keys.reduce(function (json, key, i) {
      var val = err[key]
      if (exists(val)) {
        if (typeof val === 'object') {
          Error.prototype.toJSON
          val = JSON.parse(JSON.stringify(val))
        }
        json[key] = val
      }
      return json
    }, {})
    // restore Error.prototype.toJSON
    if (cachedToJSON === undefined) {
      delete Error.prototype.toJSON
    } else {
      Error.prototype.toJSON = cachedToJSON
    }
    return json
  }
  
  function stubToJSON () {
    return errToJSON(this)
  }
  
  module.exports.parse = parseErr
  
  function parseErr (json) {
    var err = new Error(json.message)
    var stack = err.stack
    assign(err, json)
    if (err.stack === stack) {
      // remove stacktrace generated by error constructor above
      err.stack = stack.slice(0, stack.indexOf('\n'))
    }
    return err
  }
  
  },{"101/assign":1,"101/exists":5}],18:[function(require,module,exports){
  // 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;
  }
  
  },{}],19:[function(require,module,exports){
  'use strict'
  
  var defaults = require('101/defaults')
  var noop = require('101/noop')
  var Observable = require('rxjs/Observable').Observable
  var StaticObservable = require('static-observable')
  // observable factories
  require('rxjs/add/observable/range')
  require('rxjs/add/observable/zip')
  // operators
  require('rxjs/add/operator/delay')
  require('rxjs/add/operator/mergeMap')
  require('rxjs/add/operator/retryWhen')
  
  /**
   * exponential backoff operator
   * @return {[type]} [description]
   */
  Observable.prototype.backoff = function (opts) {
    opts = opts || {}
    defaults(opts, {
      minTimeout: 1000,
      maxTimeout: 3000,
      factor: 3,
      retries: 2,
      onError: noop
    })
    return this.retryWhen(function (errorObs) {
      return Observable.zip(
        Observable.range(0, opts.retries + 1),
        errorObs
      ).mergeMap(function (zip) {
        var i = zip[0]
        var err = zip[1]
        var dontRetry = opts.onError(err, i === opts.retries, i + 1)
        if (dontRetry || i === opts.retries) {
          return StaticObservable.error(err)
        }
        var timeout = Math.min(
          opts.minTimeout * Math.pow(opts.factor, i),
          opts.maxTimeout
        )
        return StaticObservable.next(i).delay(timeout)
      })
    })
  }
  
  },{"101/defaults":3,"101/noop":10,"rxjs/Observable":23,"rxjs/add/observable/range":31,"rxjs/add/observable/zip":32,"rxjs/add/operator/delay":33,"rxjs/add/operator/mergeMap":34,"rxjs/add/operator/retryWhen":36,"static-observable":78}],20:[function(require,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; };
  
  },{}],21:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subscriber_1 = require('./Subscriber');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var InnerSubscriber = (function (_super) {
      __extends(InnerSubscriber, _super);
      function InnerSubscriber(parent, outerValue, outerIndex) {
          _super.call(this);
          this.parent = parent;
          this.outerValue = outerValue;
          this.outerIndex = outerIndex;
          this.index = 0;
      }
      InnerSubscriber.prototype._next = function (value) {
          this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
      };
      InnerSubscriber.prototype._error = function (error) {
          this.parent.notifyError(error, this);
          this.unsubscribe();
      };
      InnerSubscriber.prototype._complete = function () {
          this.parent.notifyComplete(this);
          this.unsubscribe();
      };
      return InnerSubscriber;
  }(Subscriber_1.Subscriber));
  exports.InnerSubscriber = InnerSubscriber;
  
  },{"./Subscriber":29}],22:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('./Observable');
  /**
   * Represents a push-based event or value that an {@link Observable} can emit.
   * This class is particularly useful for operators that manage notifications,
   * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
   * others. Besides wrapping the actual delivered value, it also annotates it
   * with metadata of, for instance, what type of push message it is (`next`,
   * `error`, or `complete`).
   *
   * @see {@link materialize}
   * @see {@link dematerialize}
   * @see {@link observeOn}
   *
   * @class Notification<T>
   */
  var Notification = (function () {
      function Notification(kind, value, error) {
          this.kind = kind;
          this.value = value;
          this.error = error;
          this.hasValue = kind === 'N';
      }
      /**
       * Delivers to the given `observer` the value wrapped by this Notification.
       * @param {Observer} observer
       * @return
       */
      Notification.prototype.observe = function (observer) {
          switch (this.kind) {
              case 'N':
                  return observer.next && observer.next(this.value);
              case 'E':
                  return observer.error && observer.error(this.error);
              case 'C':
                  return observer.complete && observer.complete();
          }
      };
      /**
       * Given some {@link Observer} callbacks, deliver the value represented by the
       * current Notification to the correctly corresponding callback.
       * @param {function(value: T): void} next An Observer `next` callback.
       * @param {function(err: any): void} [error] An Observer `error` callback.
       * @param {function(): void} [complete] An Observer `complete` callback.
       * @return {any}
       */
      Notification.prototype.do = function (next, error, complete) {
          var kind = this.kind;
          switch (kind) {
              case 'N':
                  return next && next(this.value);
              case 'E':
                  return error && error(this.error);
              case 'C':
                  return complete && complete();
          }
      };
      /**
       * Takes an Observer or its individual callback functions, and calls `observe`
       * or `do` methods accordingly.
       * @param {Observer|function(value: T): void} nextOrObserver An Observer or
       * the `next` callback.
       * @param {function(err: any): void} [error] An Observer `error` callback.
       * @param {function(): void} [complete] An Observer `complete` callback.
       * @return {any}
       */
      Notification.prototype.accept = function (nextOrObserver, error, complete) {
          if (nextOrObserver && typeof nextOrObserver.next === 'function') {
              return this.observe(nextOrObserver);
          }
          else {
              return this.do(nextOrObserver, error, complete);
          }
      };
      /**
       * Returns a simple Observable that just delivers the notification represented
       * by this Notification instance.
       * @return {any}
       */
      Notification.prototype.toObservable = function () {
          var kind = this.kind;
          switch (kind) {
              case 'N':
                  return Observable_1.Observable.of(this.value);
              case 'E':
                  return Observable_1.Observable.throw(this.error);
              case 'C':
                  return Observable_1.Observable.empty();
          }
          throw new Error('unexpected notification kind value');
      };
      /**
       * A shortcut to create a Notification instance of the type `next` from a
       * given value.
       * @param {T} value The `next` value.
       * @return {Notification<T>} The "next" Notification representing the
       * argument.
       */
      Notification.createNext = function (value) {
          if (typeof value !== 'undefined') {
              return new Notification('N', value);
          }
          return Notification.undefinedValueNotification;
      };
      /**
       * A shortcut to create a Notification instance of the type `error` from a
       * given error.
       * @param {any} [err] The `error` error.
       * @return {Notification<T>} The "error" Notification representing the
       * argument.
       */
      Notification.createError = function (err) {
          return new Notification('E', undefined, err);
      };
      /**
       * A shortcut to create a Notification instance of the type `complete`.
       * @return {Notification<any>} The valueless "complete" Notification.
       */
      Notification.createComplete = function () {
          return Notification.completeNotification;
      };
      Notification.completeNotification = new Notification('C');
      Notification.undefinedValueNotification = new Notification('N', undefined);
      return Notification;
  }());
  exports.Notification = Notification;
  
  },{"./Observable":23}],23:[function(require,module,exports){
  "use strict";
  var root_1 = require('./util/root');
  var toSubscriber_1 = require('./util/toSubscriber');
  var observable_1 = require('./symbol/observable');
  var pipe_1 = require('./util/pipe');
  /**
   * A representation of any set of values over any amount of time. This is the most basic building block
   * of RxJS.
   *
   * @class Observable<T>
   */
  var Observable = (function () {
      /**
       * @constructor
       * @param {Function} subscribe the function that is called when the Observable is
       * initially subscribed to. This function is given a Subscriber, to which new values
       * can be `next`ed, or an `error` method can be called to raise an error, or
       * `complete` can be called to notify of a successful completion.
       */
      function Observable(subscribe) {
          this._isScalar = false;
          if (subscribe) {
              this._subscribe = subscribe;
          }
      }
      /**
       * Creates a new Observable, with this Observable as the source, and the passed
       * operator defined as the new observable's operator.
       * @method lift
       * @param {Operator} operator the operator defining the operation to take on the observable
       * @return {Observable} a new observable with the Operator applied
       */
      Observable.prototype.lift = function (operator) {
          var observable = new Observable();
          observable.source = this;
          observable.operator = operator;
          return observable;
      };
      /**
       * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
       *
       * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
       *
       * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
       * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
       * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
       * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
       * thought.
       *
       * Apart from starting the execution of an Observable, this method allows you to listen for values
       * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
       * following ways.
       *
       * The first way is creating an object that implements {@link Observer} interface. It should have methods
       * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
       * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
       * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
       * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
       * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
       * be left uncaught.
       *
       * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
       * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
       * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
       * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
       * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
       * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
       *
       * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
       * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
       * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
       * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
       *
       * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
       * It is an Observable itself that decides when these functions will be called. For example {@link of}
       * by default emits all its values synchronously. Always check documentation for how given Observable
       * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
       *
       * @example <caption>Subscribe with an Observer</caption>
       * const sumObserver = {
       *   sum: 0,
       *   next(value) {
       *     console.log('Adding: ' + value);
       *     this.sum = this.sum + value;
       *   },
       *   error() { // We actually could just remove this method,
       *   },        // since we do not really care about errors right now.
       *   complete() {
       *     console.log('Sum equals: ' + this.sum);
       *   }
       * };
       *
       * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
       * .subscribe(sumObserver);
       *
       * // Logs:
       * // "Adding: 1"
       * // "Adding: 2"
       * // "Adding: 3"
       * // "Sum equals: 6"
       *
       *
       * @example <caption>Subscribe with functions</caption>
       * let sum = 0;
       *
       * Rx.Observable.of(1, 2, 3)
       * .subscribe(
       *   function(value) {
       *     console.log('Adding: ' + value);
       *     sum = sum + value;
       *   },
       *   undefined,
       *   function() {
       *     console.log('Sum equals: ' + sum);
       *   }
       * );
       *
       * // Logs:
       * // "Adding: 1"
       * // "Adding: 2"
       * // "Adding: 3"
       * // "Sum equals: 6"
       *
       *
       * @example <caption>Cancel a subscription</caption>
       * const subscription = Rx.Observable.interval(1000).subscribe(
       *   num => console.log(num),
       *   undefined,
       *   () => console.log('completed!') // Will not be called, even
       * );                                // when cancelling subscription
       *
       *
       * setTimeout(() => {
       *   subscription.unsubscribe();
       *   console.log('unsubscribed!');
       * }, 2500);
       *
       * // Logs:
       * // 0 after 1s
       * // 1 after 2s
       * // "unsubscribed!" after 2.5s
       *
       *
       * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
       *  or the first of three possible handlers, which is the handler for each value emitted from the subscribed
       *  Observable.
       * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
       *  the error will be thrown as unhandled.
       * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
       * @return {ISubscription} a subscription reference to the registered handlers
       * @method subscribe
       */
      Observable.prototype.subscribe = function (observerOrNext, error, complete) {
          var operator = this.operator;
          var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
          if (operator) {
              operator.call(sink, this.source);
          }
          else {
              sink.add(this.source || !sink.syncErrorThrowable ? this._subscribe(sink) : this._trySubscribe(sink));
          }
          if (sink.syncErrorThrowable) {
              sink.syncErrorThrowable = false;
              if (sink.syncErrorThrown) {
                  throw sink.syncErrorValue;
              }
          }
          return sink;
      };
      Observable.prototype._trySubscribe = function (sink) {
          try {
              return this._subscribe(sink);
          }
          catch (err) {
              sink.syncErrorThrown = true;
              sink.syncErrorValue = err;
              sink.error(err);
          }
      };
      /**
       * @method forEach
       * @param {Function} next a handler for each value emitted by the observable
       * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
       * @return {Promise} a promise that either resolves on observable completion or
       *  rejects with the handled error
       */
      Observable.prototype.forEach = function (next, PromiseCtor) {
          var _this = this;
          if (!PromiseCtor) {
              if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
                  PromiseCtor = root_1.root.Rx.config.Promise;
              }
              else if (root_1.root.Promise) {
                  PromiseCtor = root_1.root.Promise;
              }
          }
          if (!PromiseCtor) {
              throw new Error('no Promise impl found');
          }
          return new PromiseCtor(function (resolve, reject) {
              // Must be declared in a separate statement to avoid a RefernceError when
              // accessing subscription below in the closure due to Temporal Dead Zone.
              var subscription;
              subscription = _this.subscribe(function (value) {
                  if (subscription) {
                      // if there is a subscription, then we can surmise
                      // the next handling is asynchronous. Any errors thrown
                      // need to be rejected explicitly and unsubscribe must be
                      // called manually
                      try {
                          next(value);
                      }
                      catch (err) {
                          reject(err);
                          subscription.unsubscribe();
                      }
                  }
                  else {
                      // if there is NO subscription, then we're getting a nexted
                      // value synchronously during subscription. We can just call it.
                      // If it errors, Observable's `subscribe` will ensure the
                      // unsubscription logic is called, then synchronously rethrow the error.
                      // After that, Promise will trap the error and send it
                      // down the rejection path.
                      next(value);
                  }
              }, reject, resolve);
          });
      };
      Observable.prototype._subscribe = function (subscriber) {
          return this.source.subscribe(subscriber);
      };
      /**
       * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
       * @method Symbol.observable
       * @return {Observable} this instance of the observable
       */
      Observable.prototype[observable_1.observable] = function () {
          return this;
      };
      /* tslint:enable:max-line-length */
      /**
       * Used to stitch together functional operators into a chain.
       * @method pipe
       * @return {Observable} the Observable result of all of the operators having
       * been called in the order they were passed in.
       *
       * @example
       *
       * import { map, filter, scan } from 'rxjs/operators';
       *
       * Rx.Observable.interval(1000)
       *   .pipe(
       *     filter(x => x % 2 === 0),
       *     map(x => x + x),
       *     scan((acc, x) => acc + x)
       *   )
       *   .subscribe(x => console.log(x))
       */
      Observable.prototype.pipe = function () {
          var operations = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              operations[_i - 0] = arguments[_i];
          }
          if (operations.length === 0) {
              return this;
          }
          return pipe_1.pipeFromArray(operations)(this);
      };
      /* tslint:enable:max-line-length */
      Observable.prototype.toPromise = function (PromiseCtor) {
          var _this = this;
          if (!PromiseCtor) {
              if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
                  PromiseCtor = root_1.root.Rx.config.Promise;
              }
              else if (root_1.root.Promise) {
                  PromiseCtor = root_1.root.Promise;
              }
          }
          if (!PromiseCtor) {
              throw new Error('no Promise impl found');
          }
          return new PromiseCtor(function (resolve, reject) {
              var value;
              _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
          });
      };
      // HACK: Since TypeScript inherits static properties too, we have to
      // fight against TypeScript here so Subject can have a different static create signature
      /**
       * Creates a new cold Observable by calling the Observable constructor
       * @static true
       * @owner Observable
       * @method create
       * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
       * @return {Observable} a new cold observable
       */
      Observable.create = function (subscribe) {
          return new Observable(subscribe);
      };
      return Observable;
  }());
  exports.Observable = Observable;
  
  },{"./symbol/observable":60,"./util/pipe":73,"./util/root":74,"./util/toSubscriber":76}],24:[function(require,module,exports){
  "use strict";
  exports.empty = {
      closed: true,
      next: function (value) { },
      error: function (err) { throw err; },
      complete: function () { }
  };
  
  },{}],25:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subscriber_1 = require('./Subscriber');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var OuterSubscriber = (function (_super) {
      __extends(OuterSubscriber, _super);
      function OuterSubscriber() {
          _super.apply(this, arguments);
      }
      OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
          this.destination.next(innerValue);
      };
      OuterSubscriber.prototype.notifyError = function (error, innerSub) {
          this.destination.error(error);
      };
      OuterSubscriber.prototype.notifyComplete = function (innerSub) {
          this.destination.complete();
      };
      return OuterSubscriber;
  }(Subscriber_1.Subscriber));
  exports.OuterSubscriber = OuterSubscriber;
  
  },{"./Subscriber":29}],26:[function(require,module,exports){
  "use strict";
  /**
   * An execution context and a data structure to order tasks and schedule their
   * execution. Provides a notion of (potentially virtual) time, through the
   * `now()` getter method.
   *
   * Each unit of work in a Scheduler is called an {@link Action}.
   *
   * ```ts
   * class Scheduler {
   *   now(): number;
   *   schedule(work, delay?, state?): Subscription;
   * }
   * ```
   *
   * @class Scheduler
   */
  var Scheduler = (function () {
      function Scheduler(SchedulerAction, now) {
          if (now === void 0) { now = Scheduler.now; }
          this.SchedulerAction = SchedulerAction;
          this.now = now;
      }
      /**
       * Schedules a function, `work`, for execution. May happen at some point in
       * the future, according to the `delay` parameter, if specified. May be passed
       * some context object, `state`, which will be passed to the `work` function.
       *
       * The given arguments will be processed an stored as an Action object in a
       * queue of actions.
       *
       * @param {function(state: ?T): ?Subscription} work A function representing a
       * task, or some unit of work to be executed by the Scheduler.
       * @param {number} [delay] Time to wait before executing the work, where the
       * time unit is implicit and defined by the Scheduler itself.
       * @param {T} [state] Some contextual data that the `work` function uses when
       * called by the Scheduler.
       * @return {Subscription} A subscription in order to be able to unsubscribe
       * the scheduled work.
       */
      Scheduler.prototype.schedule = function (work, delay, state) {
          if (delay === void 0) { delay = 0; }
          return new this.SchedulerAction(this, work).schedule(state, delay);
      };
      Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
      return Scheduler;
  }());
  exports.Scheduler = Scheduler;
  
  },{}],27:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Observable_1 = require('./Observable');
  var Subscriber_1 = require('./Subscriber');
  var Subscription_1 = require('./Subscription');
  var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
  var SubjectSubscription_1 = require('./SubjectSubscription');
  var rxSubscriber_1 = require('./symbol/rxSubscriber');
  /**
   * @class SubjectSubscriber<T>
   */
  var SubjectSubscriber = (function (_super) {
      __extends(SubjectSubscriber, _super);
      function SubjectSubscriber(destination) {
          _super.call(this, destination);
          this.destination = destination;
      }
      return SubjectSubscriber;
  }(Subscriber_1.Subscriber));
  exports.SubjectSubscriber = SubjectSubscriber;
  /**
   * @class Subject<T>
   */
  var Subject = (function (_super) {
      __extends(Subject, _super);
      function Subject() {
          _super.call(this);
          this.observers = [];
          this.closed = false;
          this.isStopped = false;
          this.hasError = false;
          this.thrownError = null;
      }
      Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
          return new SubjectSubscriber(this);
      };
      Subject.prototype.lift = function (operator) {
          var subject = new AnonymousSubject(this, this);
          subject.operator = operator;
          return subject;
      };
      Subject.prototype.next = function (value) {
          if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
          }
          if (!this.isStopped) {
              var observers = this.observers;
              var len = observers.length;
              var copy = observers.slice();
              for (var i = 0; i < len; i++) {
                  copy[i].next(value);
              }
          }
      };
      Subject.prototype.error = function (err) {
          if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
          }
          this.hasError = true;
          this.thrownError = err;
          this.isStopped = true;
          var observers = this.observers;
          var len = observers.length;
          var copy = observers.slice();
          for (var i = 0; i < len; i++) {
              copy[i].error(err);
          }
          this.observers.length = 0;
      };
      Subject.prototype.complete = function () {
          if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
          }
          this.isStopped = true;
          var observers = this.observers;
          var len = observers.length;
          var copy = observers.slice();
          for (var i = 0; i < len; i++) {
              copy[i].complete();
          }
          this.observers.length = 0;
      };
      Subject.prototype.unsubscribe = function () {
          this.isStopped = true;
          this.closed = true;
          this.observers = null;
      };
      Subject.prototype._trySubscribe = function (subscriber) {
          if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
          }
          else {
              return _super.prototype._trySubscribe.call(this, subscriber);
          }
      };
      Subject.prototype._subscribe = function (subscriber) {
          if (this.closed) {
              throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
          }
          else if (this.hasError) {
              subscriber.error(this.thrownError);
              return Subscription_1.Subscription.EMPTY;
          }
          else if (this.isStopped) {
              subscriber.complete();
              return Subscription_1.Subscription.EMPTY;
          }
          else {
              this.observers.push(subscriber);
              return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
          }
      };
      Subject.prototype.asObservable = function () {
          var observable = new Observable_1.Observable();
          observable.source = this;
          return observable;
      };
      Subject.create = function (destination, source) {
          return new AnonymousSubject(destination, source);
      };
      return Subject;
  }(Observable_1.Observable));
  exports.Subject = Subject;
  /**
   * @class AnonymousSubject<T>
   */
  var AnonymousSubject = (function (_super) {
      __extends(AnonymousSubject, _super);
      function AnonymousSubject(destination, source) {
          _super.call(this);
          this.destination = destination;
          this.source = source;
      }
      AnonymousSubject.prototype.next = function (value) {
          var destination = this.destination;
          if (destination && destination.next) {
              destination.next(value);
          }
      };
      AnonymousSubject.prototype.error = function (err) {
          var destination = this.destination;
          if (destination && destination.error) {
              this.destination.error(err);
          }
      };
      AnonymousSubject.prototype.complete = function () {
          var destination = this.destination;
          if (destination && destination.complete) {
              this.destination.complete();
          }
      };
      AnonymousSubject.prototype._subscribe = function (subscriber) {
          var source = this.source;
          if (source) {
              return this.source.subscribe(subscriber);
          }
          else {
              return Subscription_1.Subscription.EMPTY;
          }
      };
      return AnonymousSubject;
  }(Subject));
  exports.AnonymousSubject = AnonymousSubject;
  
  },{"./Observable":23,"./SubjectSubscription":28,"./Subscriber":29,"./Subscription":30,"./symbol/rxSubscriber":61,"./util/ObjectUnsubscribedError":62}],28:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subscription_1 = require('./Subscription');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var SubjectSubscription = (function (_super) {
      __extends(SubjectSubscription, _super);
      function SubjectSubscription(subject, subscriber) {
          _super.call(this);
          this.subject = subject;
          this.subscriber = subscriber;
          this.closed = false;
      }
      SubjectSubscription.prototype.unsubscribe = function () {
          if (this.closed) {
              return;
          }
          this.closed = true;
          var subject = this.subject;
          var observers = subject.observers;
          this.subject = null;
          if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
              return;
          }
          var subscriberIndex = observers.indexOf(this.subscriber);
          if (subscriberIndex !== -1) {
              observers.splice(subscriberIndex, 1);
          }
      };
      return SubjectSubscription;
  }(Subscription_1.Subscription));
  exports.SubjectSubscription = SubjectSubscription;
  
  },{"./Subscription":30}],29:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var isFunction_1 = require('./util/isFunction');
  var Subscription_1 = require('./Subscription');
  var Observer_1 = require('./Observer');
  var rxSubscriber_1 = require('./symbol/rxSubscriber');
  /**
   * Implements the {@link Observer} interface and extends the
   * {@link Subscription} class. While the {@link Observer} is the public API for
   * consuming the values of an {@link Observable}, all Observers get converted to
   * a Subscriber, in order to provide Subscription-like capabilities such as
   * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
   * implementing operators, but it is rarely used as a public API.
   *
   * @class Subscriber<T>
   */
  var Subscriber = (function (_super) {
      __extends(Subscriber, _super);
      /**
       * @param {Observer|function(value: T): void} [destinationOrNext] A partially
       * defined Observer or a `next` callback function.
       * @param {function(e: ?any): void} [error] The `error` callback of an
       * Observer.
       * @param {function(): void} [complete] The `complete` callback of an
       * Observer.
       */
      function Subscriber(destinationOrNext, error, complete) {
          _super.call(this);
          this.syncErrorValue = null;
          this.syncErrorThrown = false;
          this.syncErrorThrowable = false;
          this.isStopped = false;
          switch (arguments.length) {
              case 0:
                  this.destination = Observer_1.empty;
                  break;
              case 1:
                  if (!destinationOrNext) {
                      this.destination = Observer_1.empty;
                      break;
                  }
                  if (typeof destinationOrNext === 'object') {
                      if (destinationOrNext instanceof Subscriber) {
                          this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                          this.destination = destinationOrNext;
                          this.destination.add(this);
                      }
                      else {
                          this.syncErrorThrowable = true;
                          this.destination = new SafeSubscriber(this, destinationOrNext);
                      }
                      break;
                  }
              default:
                  this.syncErrorThrowable = true;
                  this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
                  break;
          }
      }
      Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
      /**
       * A static factory for a Subscriber, given a (potentially partial) definition
       * of an Observer.
       * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
       * @param {function(e: ?any): void} [error] The `error` callback of an
       * Observer.
       * @param {function(): void} [complete] The `complete` callback of an
       * Observer.
       * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
       * Observer represented by the given arguments.
       */
      Subscriber.create = function (next, error, complete) {
          var subscriber = new Subscriber(next, error, complete);
          subscriber.syncErrorThrowable = false;
          return subscriber;
      };
      /**
       * The {@link Observer} callback to receive notifications of type `next` from
       * the Observable, with a value. The Observable may call this method 0 or more
       * times.
       * @param {T} [value] The `next` value.
       * @return {void}
       */
      Subscriber.prototype.next = function (value) {
          if (!this.isStopped) {
              this._next(value);
          }
      };
      /**
       * The {@link Observer} callback to receive notifications of type `error` from
       * the Observable, with an attached {@link Error}. Notifies the Observer that
       * the Observable has experienced an error condition.
       * @param {any} [err] The `error` exception.
       * @return {void}
       */
      Subscriber.prototype.error = function (err) {
          if (!this.isStopped) {
              this.isStopped = true;
              this._error(err);
          }
      };
      /**
       * The {@link Observer} callback to receive a valueless notification of type
       * `complete` from the Observable. Notifies the Observer that the Observable
       * has finished sending push-based notifications.
       * @return {void}
       */
      Subscriber.prototype.complete = function () {
          if (!this.isStopped) {
              this.isStopped = true;
              this._complete();
          }
      };
      Subscriber.prototype.unsubscribe = function () {
          if (this.closed) {
              return;
          }
          this.isStopped = true;
          _super.prototype.unsubscribe.call(this);
      };
      Subscriber.prototype._next = function (value) {
          this.destination.next(value);
      };
      Subscriber.prototype._error = function (err) {
          this.destination.error(err);
          this.unsubscribe();
      };
      Subscriber.prototype._complete = function () {
          this.destination.complete();
          this.unsubscribe();
      };
      Subscriber.prototype._unsubscribeAndRecycle = function () {
          var _a = this, _parent = _a._parent, _parents = _a._parents;
          this._parent = null;
          this._parents = null;
          this.unsubscribe();
          this.closed = false;
          this.isStopped = false;
          this._parent = _parent;
          this._parents = _parents;
          return this;
      };
      return Subscriber;
  }(Subscription_1.Subscription));
  exports.Subscriber = Subscriber;
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var SafeSubscriber = (function (_super) {
      __extends(SafeSubscriber, _super);
      function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
          _super.call(this);
          this._parentSubscriber = _parentSubscriber;
          var next;
          var context = this;
          if (isFunction_1.isFunction(observerOrNext)) {
              next = observerOrNext;
          }
          else if (observerOrNext) {
              next = observerOrNext.next;
              error = observerOrNext.error;
              complete = observerOrNext.complete;
              if (observerOrNext !== Observer_1.empty) {
                  context = Object.create(observerOrNext);
                  if (isFunction_1.isFunction(context.unsubscribe)) {
                      this.add(context.unsubscribe.bind(context));
                  }
                  context.unsubscribe = this.unsubscribe.bind(this);
              }
          }
          this._context = context;
          this._next = next;
          this._error = error;
          this._complete = complete;
      }
      SafeSubscriber.prototype.next = function (value) {
          if (!this.isStopped && this._next) {
              var _parentSubscriber = this._parentSubscriber;
              if (!_parentSubscriber.syncErrorThrowable) {
                  this.__tryOrUnsub(this._next, value);
              }
              else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                  this.unsubscribe();
              }
          }
      };
      SafeSubscriber.prototype.error = function (err) {
          if (!this.isStopped) {
              var _parentSubscriber = this._parentSubscriber;
              if (this._error) {
                  if (!_parentSubscriber.syncErrorThrowable) {
                      this.__tryOrUnsub(this._error, err);
                      this.unsubscribe();
                  }
                  else {
                      this.__tryOrSetError(_parentSubscriber, this._error, err);
                      this.unsubscribe();
                  }
              }
              else if (!_parentSubscriber.syncErrorThrowable) {
                  this.unsubscribe();
                  throw err;
              }
              else {
                  _parentSubscriber.syncErrorValue = err;
                  _parentSubscriber.syncErrorThrown = true;
                  this.unsubscribe();
              }
          }
      };
      SafeSubscriber.prototype.complete = function () {
          var _this = this;
          if (!this.isStopped) {
              var _parentSubscriber = this._parentSubscriber;
              if (this._complete) {
                  var wrappedComplete = function () { return _this._complete.call(_this._context); };
                  if (!_parentSubscriber.syncErrorThrowable) {
                      this.__tryOrUnsub(wrappedComplete);
                      this.unsubscribe();
                  }
                  else {
                      this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                      this.unsubscribe();
                  }
              }
              else {
                  this.unsubscribe();
              }
          }
      };
      SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
          try {
              fn.call(this._context, value);
          }
          catch (err) {
              this.unsubscribe();
              throw err;
          }
      };
      SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
          try {
              fn.call(this._context, value);
          }
          catch (err) {
              parent.syncErrorValue = err;
              parent.syncErrorThrown = true;
              return true;
          }
          return false;
      };
      SafeSubscriber.prototype._unsubscribe = function () {
          var _parentSubscriber = this._parentSubscriber;
          this._context = null;
          this._parentSubscriber = null;
          _parentSubscriber.unsubscribe();
      };
      return SafeSubscriber;
  }(Subscriber));
  
  },{"./Observer":24,"./Subscription":30,"./symbol/rxSubscriber":61,"./util/isFunction":68}],30:[function(require,module,exports){
  "use strict";
  var isArray_1 = require('./util/isArray');
  var isObject_1 = require('./util/isObject');
  var isFunction_1 = require('./util/isFunction');
  var tryCatch_1 = require('./util/tryCatch');
  var errorObject_1 = require('./util/errorObject');
  var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
  /**
   * Represents a disposable resource, such as the execution of an Observable. A
   * Subscription has one important method, `unsubscribe`, that takes no argument
   * and just disposes the resource held by the subscription.
   *
   * Additionally, subscriptions may be grouped together through the `add()`
   * method, which will attach a child Subscription to the current Subscription.
   * When a Subscription is unsubscribed, all its children (and its grandchildren)
   * will be unsubscribed as well.
   *
   * @class Subscription
   */
  var Subscription = (function () {
      /**
       * @param {function(): void} [unsubscribe] A function describing how to
       * perform the disposal of resources when the `unsubscribe` method is called.
       */
      function Subscription(unsubscribe) {
          /**
           * A flag to indicate whether this Subscription has already been unsubscribed.
           * @type {boolean}
           */
          this.closed = false;
          this._parent = null;
          this._parents = null;
          this._subscriptions = null;
          if (unsubscribe) {
              this._unsubscribe = unsubscribe;
          }
      }
      /**
       * Disposes the resources held by the subscription. May, for instance, cancel
       * an ongoing Observable execution or cancel any other type of work that
       * started when the Subscription was created.
       * @return {void}
       */
      Subscription.prototype.unsubscribe = function () {
          var hasErrors = false;
          var errors;
          if (this.closed) {
              return;
          }
          var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
          this.closed = true;
          this._parent = null;
          this._parents = null;
          // null out _subscriptions first so any child subscriptions that attempt
          // to remove themselves from this subscription will noop
          this._subscriptions = null;
          var index = -1;
          var len = _parents ? _parents.length : 0;
          // if this._parent is null, then so is this._parents, and we
          // don't have to remove ourselves from any parent subscriptions.
          while (_parent) {
              _parent.remove(this);
              // if this._parents is null or index >= len,
              // then _parent is set to null, and the loop exits
              _parent = ++index < len && _parents[index] || null;
          }
          if (isFunction_1.isFunction(_unsubscribe)) {
              var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
              if (trial === errorObject_1.errorObject) {
                  hasErrors = true;
                  errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
                      flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
              }
          }
          if (isArray_1.isArray(_subscriptions)) {
              index = -1;
              len = _subscriptions.length;
              while (++index < len) {
                  var sub = _subscriptions[index];
                  if (isObject_1.isObject(sub)) {
                      var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
                      if (trial === errorObject_1.errorObject) {
                          hasErrors = true;
                          errors = errors || [];
                          var err = errorObject_1.errorObject.e;
                          if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
                              errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
                          }
                          else {
                              errors.push(err);
                          }
                      }
                  }
              }
          }
          if (hasErrors) {
              throw new UnsubscriptionError_1.UnsubscriptionError(errors);
          }
      };
      /**
       * Adds a tear down to be called during the unsubscribe() of this
       * Subscription.
       *
       * If the tear down being added is a subscription that is already
       * unsubscribed, is the same reference `add` is being called on, or is
       * `Subscription.EMPTY`, it will not be added.
       *
       * If this subscription is already in an `closed` state, the passed
       * tear down logic will be executed immediately.
       *
       * @param {TeardownLogic} teardown The additional logic to execute on
       * teardown.
       * @return {Subscription} Returns the Subscription used or created to be
       * added to the inner subscriptions list. This Subscription can be used with
       * `remove()` to remove the passed teardown logic from the inner subscriptions
       * list.
       */
      Subscription.prototype.add = function (teardown) {
          if (!teardown || (teardown === Subscription.EMPTY)) {
              return Subscription.EMPTY;
          }
          if (teardown === this) {
              return this;
          }
          var subscription = teardown;
          switch (typeof teardown) {
              case 'function':
                  subscription = new Subscription(teardown);
              case 'object':
                  if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
                      return subscription;
                  }
                  else if (this.closed) {
                      subscription.unsubscribe();
                      return subscription;
                  }
                  else if (typeof subscription._addParent !== 'function' /* quack quack */) {
                      var tmp = subscription;
                      subscription = new Subscription();
                      subscription._subscriptions = [tmp];
                  }
                  break;
              default:
                  throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
          }
          var subscriptions = this._subscriptions || (this._subscriptions = []);
          subscriptions.push(subscription);
          subscription._addParent(this);
          return subscription;
      };
      /**
       * Removes a Subscription from the internal list of subscriptions that will
       * unsubscribe during the unsubscribe process of this Subscription.
       * @param {Subscription} subscription The subscription to remove.
       * @return {void}
       */
      Subscription.prototype.remove = function (subscription) {
          var subscriptions = this._subscriptions;
          if (subscriptions) {
              var subscriptionIndex = subscriptions.indexOf(subscription);
              if (subscriptionIndex !== -1) {
                  subscriptions.splice(subscriptionIndex, 1);
              }
          }
      };
      Subscription.prototype._addParent = function (parent) {
          var _a = this, _parent = _a._parent, _parents = _a._parents;
          if (!_parent || _parent === parent) {
              // If we don't have a parent, or the new parent is the same as the
              // current parent, then set this._parent to the new parent.
              this._parent = parent;
          }
          else if (!_parents) {
              // If there's already one parent, but not multiple, allocate an Array to
              // store the rest of the parent Subscriptions.
              this._parents = [parent];
          }
          else if (_parents.indexOf(parent) === -1) {
              // Only add the new parent to the _parents list if it's not already there.
              _parents.push(parent);
          }
      };
      Subscription.EMPTY = (function (empty) {
          empty.closed = true;
          return empty;
      }(new Subscription()));
      return Subscription;
  }());
  exports.Subscription = Subscription;
  function flattenUnsubscriptionErrors(errors) {
      return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
  }
  
  },{"./util/UnsubscriptionError":63,"./util/errorObject":64,"./util/isArray":65,"./util/isFunction":68,"./util/isObject":69,"./util/tryCatch":77}],31:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var range_1 = require('../../observable/range');
  Observable_1.Observable.range = range_1.range;
  
  },{"../../Observable":23,"../../observable/range":42}],32:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var zip_1 = require('../../observable/zip');
  Observable_1.Observable.zip = zip_1.zip;
  
  },{"../../Observable":23,"../../observable/zip":43}],33:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var delay_1 = require('../../operator/delay');
  Observable_1.Observable.prototype.delay = delay_1.delay;
  
  },{"../../Observable":23,"../../operator/delay":44}],34:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var mergeMap_1 = require('../../operator/mergeMap');
  Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
  Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
  
  },{"../../Observable":23,"../../operator/mergeMap":45}],35:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var publish_1 = require('../../operator/publish');
  Observable_1.Observable.prototype.publish = publish_1.publish;
  
  },{"../../Observable":23,"../../operator/publish":46}],36:[function(require,module,exports){
  "use strict";
  var Observable_1 = require('../../Observable');
  var retryWhen_1 = require('../../operator/retryWhen');
  Observable_1.Observable.prototype.retryWhen = retryWhen_1.retryWhen;
  
  },{"../../Observable":23,"../../operator/retryWhen":47}],37:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Observable_1 = require('../Observable');
  var ScalarObservable_1 = require('./ScalarObservable');
  var EmptyObservable_1 = require('./EmptyObservable');
  var isScheduler_1 = require('../util/isScheduler');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @extends {Ignored}
   * @hide true
   */
  var ArrayObservable = (function (_super) {
      __extends(ArrayObservable, _super);
      function ArrayObservable(array, scheduler) {
          _super.call(this);
          this.array = array;
          this.scheduler = scheduler;
          if (!scheduler && array.length === 1) {
              this._isScalar = true;
              this.value = array[0];
          }
      }
      ArrayObservable.create = function (array, scheduler) {
          return new ArrayObservable(array, scheduler);
      };
      /**
       * Creates an Observable that emits some values you specify as arguments,
       * immediately one after the other, and then emits a complete notification.
       *
       * <span class="informal">Emits the arguments you provide, then completes.
       * </span>
       *
       * <img src="./img/of.png" width="100%">
       *
       * This static operator is useful for creating a simple Observable that only
       * emits the arguments given, and the complete notification thereafter. It can
       * be used for composing with other Observables, such as with {@link concat}.
       * By default, it uses a `null` IScheduler, which means the `next`
       * notifications are sent synchronously, although with a different IScheduler
       * it is possible to determine when those notifications will be delivered.
       *
       * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
       * var numbers = Rx.Observable.of(10, 20, 30);
       * var letters = Rx.Observable.of('a', 'b', 'c');
       * var interval = Rx.Observable.interval(1000);
       * var result = numbers.concat(letters).concat(interval);
       * result.subscribe(x => console.log(x));
       *
       * @see {@link create}
       * @see {@link empty}
       * @see {@link never}
       * @see {@link throw}
       *
       * @param {...T} values Arguments that represent `next` values to be emitted.
       * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
       * the emissions of the `next` notifications.
       * @return {Observable<T>} An Observable that emits each given input value.
       * @static true
       * @name of
       * @owner Observable
       */
      ArrayObservable.of = function () {
          var array = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              array[_i - 0] = arguments[_i];
          }
          var scheduler = array[array.length - 1];
          if (isScheduler_1.isScheduler(scheduler)) {
              array.pop();
          }
          else {
              scheduler = null;
          }
          var len = array.length;
          if (len > 1) {
              return new ArrayObservable(array, scheduler);
          }
          else if (len === 1) {
              return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
          }
          else {
              return new EmptyObservable_1.EmptyObservable(scheduler);
          }
      };
      ArrayObservable.dispatch = function (state) {
          var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
          if (index >= count) {
              subscriber.complete();
              return;
          }
          subscriber.next(array[index]);
          if (subscriber.closed) {
              return;
          }
          state.index = index + 1;
          this.schedule(state);
      };
      ArrayObservable.prototype._subscribe = function (subscriber) {
          var index = 0;
          var array = this.array;
          var count = array.length;
          var scheduler = this.scheduler;
          if (scheduler) {
              return scheduler.schedule(ArrayObservable.dispatch, 0, {
                  array: array, index: index, count: count, subscriber: subscriber
              });
          }
          else {
              for (var i = 0; i < count && !subscriber.closed; i++) {
                  subscriber.next(array[i]);
              }
              subscriber.complete();
          }
      };
      return ArrayObservable;
  }(Observable_1.Observable));
  exports.ArrayObservable = ArrayObservable;
  
  },{"../Observable":23,"../util/isScheduler":71,"./EmptyObservable":39,"./ScalarObservable":41}],38:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subject_1 = require('../Subject');
  var Observable_1 = require('../Observable');
  var Subscriber_1 = require('../Subscriber');
  var Subscription_1 = require('../Subscription');
  var refCount_1 = require('../operators/refCount');
  /**
   * @class ConnectableObservable<T>
   */
  var ConnectableObservable = (function (_super) {
      __extends(ConnectableObservable, _super);
      function ConnectableObservable(source, subjectFactory) {
          _super.call(this);
          this.source = source;
          this.subjectFactory = subjectFactory;
          this._refCount = 0;
          this._isComplete = false;
      }
      ConnectableObservable.prototype._subscribe = function (subscriber) {
          return this.getSubject().subscribe(subscriber);
      };
      ConnectableObservable.prototype.getSubject = function () {
          var subject = this._subject;
          if (!subject || subject.isStopped) {
              this._subject = this.subjectFactory();
          }
          return this._subject;
      };
      ConnectableObservable.prototype.connect = function () {
          var connection = this._connection;
          if (!connection) {
              this._isComplete = false;
              connection = this._connection = new Subscription_1.Subscription();
              connection.add(this.source
                  .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
              if (connection.closed) {
                  this._connection = null;
                  connection = Subscription_1.Subscription.EMPTY;
              }
              else {
                  this._connection = connection;
              }
          }
          return connection;
      };
      ConnectableObservable.prototype.refCount = function () {
          return refCount_1.refCount()(this);
      };
      return ConnectableObservable;
  }(Observable_1.Observable));
  exports.ConnectableObservable = ConnectableObservable;
  var connectableProto = ConnectableObservable.prototype;
  exports.connectableObservableDescriptor = {
      operator: { value: null },
      _refCount: { value: 0, writable: true },
      _subject: { value: null, writable: true },
      _connection: { value: null, writable: true },
      _subscribe: { value: connectableProto._subscribe },
      _isComplete: { value: connectableProto._isComplete, writable: true },
      getSubject: { value: connectableProto.getSubject },
      connect: { value: connectableProto.connect },
      refCount: { value: connectableProto.refCount }
  };
  var ConnectableSubscriber = (function (_super) {
      __extends(ConnectableSubscriber, _super);
      function ConnectableSubscriber(destination, connectable) {
          _super.call(this, destination);
          this.connectable = connectable;
      }
      ConnectableSubscriber.prototype._error = function (err) {
          this._unsubscribe();
          _super.prototype._error.call(this, err);
      };
      ConnectableSubscriber.prototype._complete = function () {
          this.connectable._isComplete = true;
          this._unsubscribe();
          _super.prototype._complete.call(this);
      };
      ConnectableSubscriber.prototype._unsubscribe = function () {
          var connectable = this.connectable;
          if (connectable) {
              this.connectable = null;
              var connection = connectable._connection;
              connectable._refCount = 0;
              connectable._subject = null;
              connectable._connection = null;
              if (connection) {
                  connection.unsubscribe();
              }
          }
      };
      return ConnectableSubscriber;
  }(Subject_1.SubjectSubscriber));
  var RefCountOperator = (function () {
      function RefCountOperator(connectable) {
          this.connectable = connectable;
      }
      RefCountOperator.prototype.call = function (subscriber, source) {
          var connectable = this.connectable;
          connectable._refCount++;
          var refCounter = new RefCountSubscriber(subscriber, connectable);
          var subscription = source.subscribe(refCounter);
          if (!refCounter.closed) {
              refCounter.connection = connectable.connect();
          }
          return subscription;
      };
      return RefCountOperator;
  }());
  var RefCountSubscriber = (function (_super) {
      __extends(RefCountSubscriber, _super);
      function RefCountSubscriber(destination, connectable) {
          _super.call(this, destination);
          this.connectable = connectable;
      }
      RefCountSubscriber.prototype._unsubscribe = function () {
          var connectable = this.connectable;
          if (!connectable) {
              this.connection = null;
              return;
          }
          this.connectable = null;
          var refCount = connectable._refCount;
          if (refCount <= 0) {
              this.connection = null;
              return;
          }
          connectable._refCount = refCount - 1;
          if (refCount > 1) {
              this.connection = null;
              return;
          }
          ///
          // Compare the local RefCountSubscriber's connection Subscription to the
          // connection Subscription on the shared ConnectableObservable. In cases
          // where the ConnectableObservable source synchronously emits values, and
          // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
          // execution continues to here before the RefCountOperator has a chance to
          // supply the RefCountSubscriber with the shared connection Subscription.
          // For example:
          // ```
          // Observable.range(0, 10)
          //   .publish()
          //   .refCount()
          //   .take(5)
          //   .subscribe();
          // ```
          // In order to account for this case, RefCountSubscriber should only dispose
          // the ConnectableObservable's shared connection Subscription if the
          // connection Subscription exists, *and* either:
          //   a. RefCountSubscriber doesn't have a reference to the shared connection
          //      Subscription yet, or,
          //   b. RefCountSubscriber's connection Subscription reference is identical
          //      to the shared connection Subscription
          ///
          var connection = this.connection;
          var sharedConnection = connectable._connection;
          this.connection = null;
          if (sharedConnection && (!connection || sharedConnection === connection)) {
              sharedConnection.unsubscribe();
          }
      };
      return RefCountSubscriber;
  }(Subscriber_1.Subscriber));
  
  },{"../Observable":23,"../Subject":27,"../Subscriber":29,"../Subscription":30,"../operators/refCount":52}],39:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Observable_1 = require('../Observable');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @extends {Ignored}
   * @hide true
   */
  var EmptyObservable = (function (_super) {
      __extends(EmptyObservable, _super);
      function EmptyObservable(scheduler) {
          _super.call(this);
          this.scheduler = scheduler;
      }
      /**
       * Creates an Observable that emits no items to the Observer and immediately
       * emits a complete notification.
       *
       * <span class="informal">Just emits 'complete', and nothing else.
       * </span>
       *
       * <img src="./img/empty.png" width="100%">
       *
       * This static operator is useful for creating a simple Observable that only
       * emits the complete notification. It can be used for composing with other
       * Observables, such as in a {@link mergeMap}.
       *
       * @example <caption>Emit the number 7, then complete.</caption>
       * var result = Rx.Observable.empty().startWith(7);
       * result.subscribe(x => console.log(x));
       *
       * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
       * var interval = Rx.Observable.interval(1000);
       * var result = interval.mergeMap(x =>
       *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
       * );
       * result.subscribe(x => console.log(x));
       *
       * // Results in the following to the console:
       * // x is equal to the count on the interval eg(0,1,2,3,...)
       * // x will occur every 1000ms
       * // if x % 2 is equal to 1 print abc
       * // if x % 2 is not equal to 1 nothing will be output
       *
       * @see {@link create}
       * @see {@link never}
       * @see {@link of}
       * @see {@link throw}
       *
       * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
       * the emission of the complete notification.
       * @return {Observable} An "empty" Observable: emits only the complete
       * notification.
       * @static true
       * @name empty
       * @owner Observable
       */
      EmptyObservable.create = function (scheduler) {
          return new EmptyObservable(scheduler);
      };
      EmptyObservable.dispatch = function (arg) {
          var subscriber = arg.subscriber;
          subscriber.complete();
      };
      EmptyObservable.prototype._subscribe = function (subscriber) {
          var scheduler = this.scheduler;
          if (scheduler) {
              return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
          }
          else {
              subscriber.complete();
          }
      };
      return EmptyObservable;
  }(Observable_1.Observable));
  exports.EmptyObservable = EmptyObservable;
  
  },{"../Observable":23}],40:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Observable_1 = require('../Observable');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @extends {Ignored}
   * @hide true
   */
  var RangeObservable = (function (_super) {
      __extends(RangeObservable, _super);
      function RangeObservable(start, count, scheduler) {
          _super.call(this);
          this.start = start;
          this._count = count;
          this.scheduler = scheduler;
      }
      /**
       * Creates an Observable that emits a sequence of numbers within a specified
       * range.
       *
       * <span class="informal">Emits a sequence of numbers in a range.</span>
       *
       * <img src="./img/range.png" width="100%">
       *
       * `range` operator emits a range of sequential integers, in order, where you
       * select the `start` of the range and its `length`. By default, uses no
       * IScheduler and just delivers the notifications synchronously, but may use
       * an optional IScheduler to regulate those deliveries.
       *
       * @example <caption>Emits the numbers 1 to 10</caption>
       * var numbers = Rx.Observable.range(1, 10);
       * numbers.subscribe(x => console.log(x));
       *
       * @see {@link timer}
       * @see {@link interval}
       *
       * @param {number} [start=0] The value of the first integer in the sequence.
       * @param {number} [count=0] The number of sequential integers to generate.
       * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
       * the emissions of the notifications.
       * @return {Observable} An Observable of numbers that emits a finite range of
       * sequential integers.
       * @static true
       * @name range
       * @owner Observable
       */
      RangeObservable.create = function (start, count, scheduler) {
          if (start === void 0) { start = 0; }
          if (count === void 0) { count = 0; }
          return new RangeObservable(start, count, scheduler);
      };
      RangeObservable.dispatch = function (state) {
          var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
          if (index >= count) {
              subscriber.complete();
              return;
          }
          subscriber.next(start);
          if (subscriber.closed) {
              return;
          }
          state.index = index + 1;
          state.start = start + 1;
          this.schedule(state);
      };
      RangeObservable.prototype._subscribe = function (subscriber) {
          var index = 0;
          var start = this.start;
          var count = this._count;
          var scheduler = this.scheduler;
          if (scheduler) {
              return scheduler.schedule(RangeObservable.dispatch, 0, {
                  index: index, count: count, start: start, subscriber: subscriber
              });
          }
          else {
              do {
                  if (index++ >= count) {
                      subscriber.complete();
                      break;
                  }
                  subscriber.next(start++);
                  if (subscriber.closed) {
                      break;
                  }
              } while (true);
          }
      };
      return RangeObservable;
  }(Observable_1.Observable));
  exports.RangeObservable = RangeObservable;
  
  },{"../Observable":23}],41:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Observable_1 = require('../Observable');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @extends {Ignored}
   * @hide true
   */
  var ScalarObservable = (function (_super) {
      __extends(ScalarObservable, _super);
      function ScalarObservable(value, scheduler) {
          _super.call(this);
          this.value = value;
          this.scheduler = scheduler;
          this._isScalar = true;
          if (scheduler) {
              this._isScalar = false;
          }
      }
      ScalarObservable.create = function (value, scheduler) {
          return new ScalarObservable(value, scheduler);
      };
      ScalarObservable.dispatch = function (state) {
          var done = state.done, value = state.value, subscriber = state.subscriber;
          if (done) {
              subscriber.complete();
              return;
          }
          subscriber.next(value);
          if (subscriber.closed) {
              return;
          }
          state.done = true;
          this.schedule(state);
      };
      ScalarObservable.prototype._subscribe = function (subscriber) {
          var value = this.value;
          var scheduler = this.scheduler;
          if (scheduler) {
              return scheduler.schedule(ScalarObservable.dispatch, 0, {
                  done: false, value: value, subscriber: subscriber
              });
          }
          else {
              subscriber.next(value);
              if (!subscriber.closed) {
                  subscriber.complete();
              }
          }
      };
      return ScalarObservable;
  }(Observable_1.Observable));
  exports.ScalarObservable = ScalarObservable;
  
  },{"../Observable":23}],42:[function(require,module,exports){
  "use strict";
  var RangeObservable_1 = require('./RangeObservable');
  exports.range = RangeObservable_1.RangeObservable.create;
  
  },{"./RangeObservable":40}],43:[function(require,module,exports){
  "use strict";
  var zip_1 = require('../operators/zip');
  exports.zip = zip_1.zipStatic;
  
  },{"../operators/zip":54}],44:[function(require,module,exports){
  "use strict";
  var async_1 = require('../scheduler/async');
  var delay_1 = require('../operators/delay');
  /**
   * Delays the emission of items from the source Observable by a given timeout or
   * until a given Date.
   *
   * <span class="informal">Time shifts each item by some specified amount of
   * milliseconds.</span>
   *
   * <img src="./img/delay.png" width="100%">
   *
   * If the delay argument is a Number, this operator time shifts the source
   * Observable by that amount of time expressed in milliseconds. The relative
   * time intervals between the values are preserved.
   *
   * If the delay argument is a Date, this operator time shifts the start of the
   * Observable execution until the given date occurs.
   *
   * @example <caption>Delay each click by one second</caption>
   * var clicks = Rx.Observable.fromEvent(document, 'click');
   * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
   * delayedClicks.subscribe(x => console.log(x));
   *
   * @example <caption>Delay all clicks until a future date happens</caption>
   * var clicks = Rx.Observable.fromEvent(document, 'click');
   * var date = new Date('March 15, 2050 12:00:00'); // in the future
   * var delayedClicks = clicks.delay(date); // click emitted only after that date
   * delayedClicks.subscribe(x => console.log(x));
   *
   * @see {@link debounceTime}
   * @see {@link delayWhen}
   *
   * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
   * a `Date` until which the emission of the source items is delayed.
   * @param {Scheduler} [scheduler=async] The IScheduler to use for
   * managing the timers that handle the time-shift for each item.
   * @return {Observable} An Observable that delays the emissions of the source
   * Observable by the specified timeout or Date.
   * @method delay
   * @owner Observable
   */
  function delay(delay, scheduler) {
      if (scheduler === void 0) { scheduler = async_1.async; }
      return delay_1.delay(delay, scheduler)(this);
  }
  exports.delay = delay;
  
  },{"../operators/delay":48,"../scheduler/async":58}],45:[function(require,module,exports){
  "use strict";
  var mergeMap_1 = require('../operators/mergeMap');
  /* tslint:enable:max-line-length */
  /**
   * Projects each source value to an Observable which is merged in the output
   * Observable.
   *
   * <span class="informal">Maps each value to an Observable, then flattens all of
   * these inner Observables using {@link mergeAll}.</span>
   *
   * <img src="./img/mergeMap.png" width="100%">
   *
   * Returns an Observable that emits items based on applying a function that you
   * supply to each item emitted by the source Observable, where that function
   * returns an Observable, and then merging those resulting Observables and
   * emitting the results of this merger.
   *
   * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
   * var letters = Rx.Observable.of('a', 'b', 'c');
   * var result = letters.mergeMap(x =>
   *   Rx.Observable.interval(1000).map(i => x+i)
   * );
   * result.subscribe(x => console.log(x));
   *
   * // Results in the following:
   * // a0
   * // b0
   * // c0
   * // a1
   * // b1
   * // c1
   * // continues to list a,b,c with respective ascending integers
   *
   * @see {@link concatMap}
   * @see {@link exhaustMap}
   * @see {@link merge}
   * @see {@link mergeAll}
   * @see {@link mergeMapTo}
   * @see {@link mergeScan}
   * @see {@link switchMap}
   *
   * @param {function(value: T, ?index: number): ObservableInput} project A function
   * that, when applied to an item emitted by the source Observable, returns an
   * Observable.
   * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
   * A function to produce the value on the output Observable based on the values
   * and the indices of the source (outer) emission and the inner Observable
   * emission. The arguments passed to this function are:
   * - `outerValue`: the value that came from the source
   * - `innerValue`: the value that came from the projected Observable
   * - `outerIndex`: the "index" of the value that came from the source
   * - `innerIndex`: the "index" of the value from the projected Observable
   * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
   * Observables being subscribed to concurrently.
   * @return {Observable} An Observable that emits the result of applying the
   * projection function (and the optional `resultSelector`) to each item emitted
   * by the source Observable and merging the results of the Observables obtained
   * from this transformation.
   * @method mergeMap
   * @owner Observable
   */
  function mergeMap(project, resultSelector, concurrent) {
      if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
      return mergeMap_1.mergeMap(project, resultSelector, concurrent)(this);
  }
  exports.mergeMap = mergeMap;
  
  },{"../operators/mergeMap":49}],46:[function(require,module,exports){
  "use strict";
  var publish_1 = require('../operators/publish');
  /* tslint:enable:max-line-length */
  /**
   * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
   * before it begins emitting items to those Observers that have subscribed to it.
   *
   * <img src="./img/publish.png" width="100%">
   *
   * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
   * as needed, without causing multiple subscriptions to the source sequence.
   * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
   * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
   * @method publish
   * @owner Observable
   */
  function publish(selector) {
      return publish_1.publish(selector)(this);
  }
  exports.publish = publish;
  
  },{"../operators/publish":51}],47:[function(require,module,exports){
  "use strict";
  var retryWhen_1 = require('../operators/retryWhen');
  /**
   * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
   * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.
   * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child
   * subscription. Otherwise this method will resubscribe to the source Observable.
   *
   * <img src="./img/retryWhen.png" width="100%">
   *
   * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a
   * user can `complete` or `error`, aborting the retry.
   * @return {Observable} The source Observable modified with retry logic.
   * @method retryWhen
   * @owner Observable
   */
  function retryWhen(notifier) {
      return retryWhen_1.retryWhen(notifier)(this);
  }
  exports.retryWhen = retryWhen;
  
  },{"../operators/retryWhen":53}],48:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var async_1 = require('../scheduler/async');
  var isDate_1 = require('../util/isDate');
  var Subscriber_1 = require('../Subscriber');
  var Notification_1 = require('../Notification');
  /**
   * Delays the emission of items from the source Observable by a given timeout or
   * until a given Date.
   *
   * <span class="informal">Time shifts each item by some specified amount of
   * milliseconds.</span>
   *
   * <img src="./img/delay.png" width="100%">
   *
   * If the delay argument is a Number, this operator time shifts the source
   * Observable by that amount of time expressed in milliseconds. The relative
   * time intervals between the values are preserved.
   *
   * If the delay argument is a Date, this operator time shifts the start of the
   * Observable execution until the given date occurs.
   *
   * @example <caption>Delay each click by one second</caption>
   * var clicks = Rx.Observable.fromEvent(document, 'click');
   * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
   * delayedClicks.subscribe(x => console.log(x));
   *
   * @example <caption>Delay all clicks until a future date happens</caption>
   * var clicks = Rx.Observable.fromEvent(document, 'click');
   * var date = new Date('March 15, 2050 12:00:00'); // in the future
   * var delayedClicks = clicks.delay(date); // click emitted only after that date
   * delayedClicks.subscribe(x => console.log(x));
   *
   * @see {@link debounceTime}
   * @see {@link delayWhen}
   *
   * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
   * a `Date` until which the emission of the source items is delayed.
   * @param {Scheduler} [scheduler=async] The IScheduler to use for
   * managing the timers that handle the time-shift for each item.
   * @return {Observable} An Observable that delays the emissions of the source
   * Observable by the specified timeout or Date.
   * @method delay
   * @owner Observable
   */
  function delay(delay, scheduler) {
      if (scheduler === void 0) { scheduler = async_1.async; }
      var absoluteDelay = isDate_1.isDate(delay);
      var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
      return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
  }
  exports.delay = delay;
  var DelayOperator = (function () {
      function DelayOperator(delay, scheduler) {
          this.delay = delay;
          this.scheduler = scheduler;
      }
      DelayOperator.prototype.call = function (subscriber, source) {
          return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
      };
      return DelayOperator;
  }());
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var DelaySubscriber = (function (_super) {
      __extends(DelaySubscriber, _super);
      function DelaySubscriber(destination, delay, scheduler) {
          _super.call(this, destination);
          this.delay = delay;
          this.scheduler = scheduler;
          this.queue = [];
          this.active = false;
          this.errored = false;
      }
      DelaySubscriber.dispatch = function (state) {
          var source = state.source;
          var queue = source.queue;
          var scheduler = state.scheduler;
          var destination = state.destination;
          while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
              queue.shift().notification.observe(destination);
          }
          if (queue.length > 0) {
              var delay_1 = Math.max(0, queue[0].time - scheduler.now());
              this.schedule(state, delay_1);
          }
          else {
              source.active = false;
          }
      };
      DelaySubscriber.prototype._schedule = function (scheduler) {
          this.active = true;
          this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
              source: this, destination: this.destination, scheduler: scheduler
          }));
      };
      DelaySubscriber.prototype.scheduleNotification = function (notification) {
          if (this.errored === true) {
              return;
          }
          var scheduler = this.scheduler;
          var message = new DelayMessage(scheduler.now() + this.delay, notification);
          this.queue.push(message);
          if (this.active === false) {
              this._schedule(scheduler);
          }
      };
      DelaySubscriber.prototype._next = function (value) {
          this.scheduleNotification(Notification_1.Notification.createNext(value));
      };
      DelaySubscriber.prototype._error = function (err) {
          this.errored = true;
          this.queue = [];
          this.destination.error(err);
      };
      DelaySubscriber.prototype._complete = function () {
          this.scheduleNotification(Notification_1.Notification.createComplete());
      };
      return DelaySubscriber;
  }(Subscriber_1.Subscriber));
  var DelayMessage = (function () {
      function DelayMessage(time, notification) {
          this.time = time;
          this.notification = notification;
      }
      return DelayMessage;
  }());
  
  },{"../Notification":22,"../Subscriber":29,"../scheduler/async":58,"../util/isDate":67}],49:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var subscribeToResult_1 = require('../util/subscribeToResult');
  var OuterSubscriber_1 = require('../OuterSubscriber');
  /* tslint:enable:max-line-length */
  /**
   * Projects each source value to an Observable which is merged in the output
   * Observable.
   *
   * <span class="informal">Maps each value to an Observable, then flattens all of
   * these inner Observables using {@link mergeAll}.</span>
   *
   * <img src="./img/mergeMap.png" width="100%">
   *
   * Returns an Observable that emits items based on applying a function that you
   * supply to each item emitted by the source Observable, where that function
   * returns an Observable, and then merging those resulting Observables and
   * emitting the results of this merger.
   *
   * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
   * var letters = Rx.Observable.of('a', 'b', 'c');
   * var result = letters.mergeMap(x =>
   *   Rx.Observable.interval(1000).map(i => x+i)
   * );
   * result.subscribe(x => console.log(x));
   *
   * // Results in the following:
   * // a0
   * // b0
   * // c0
   * // a1
   * // b1
   * // c1
   * // continues to list a,b,c with respective ascending integers
   *
   * @see {@link concatMap}
   * @see {@link exhaustMap}
   * @see {@link merge}
   * @see {@link mergeAll}
   * @see {@link mergeMapTo}
   * @see {@link mergeScan}
   * @see {@link switchMap}
   *
   * @param {function(value: T, ?index: number): ObservableInput} project A function
   * that, when applied to an item emitted by the source Observable, returns an
   * Observable.
   * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
   * A function to produce the value on the output Observable based on the values
   * and the indices of the source (outer) emission and the inner Observable
   * emission. The arguments passed to this function are:
   * - `outerValue`: the value that came from the source
   * - `innerValue`: the value that came from the projected Observable
   * - `outerIndex`: the "index" of the value that came from the source
   * - `innerIndex`: the "index" of the value from the projected Observable
   * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
   * Observables being subscribed to concurrently.
   * @return {Observable} An Observable that emits the result of applying the
   * projection function (and the optional `resultSelector`) to each item emitted
   * by the source Observable and merging the results of the Observables obtained
   * from this transformation.
   * @method mergeMap
   * @owner Observable
   */
  function mergeMap(project, resultSelector, concurrent) {
      if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
      return function mergeMapOperatorFunction(source) {
          if (typeof resultSelector === 'number') {
              concurrent = resultSelector;
              resultSelector = null;
          }
          return source.lift(new MergeMapOperator(project, resultSelector, concurrent));
      };
  }
  exports.mergeMap = mergeMap;
  var MergeMapOperator = (function () {
      function MergeMapOperator(project, resultSelector, concurrent) {
          if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
          this.project = project;
          this.resultSelector = resultSelector;
          this.concurrent = concurrent;
      }
      MergeMapOperator.prototype.call = function (observer, source) {
          return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
      };
      return MergeMapOperator;
  }());
  exports.MergeMapOperator = MergeMapOperator;
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var MergeMapSubscriber = (function (_super) {
      __extends(MergeMapSubscriber, _super);
      function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
          if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
          _super.call(this, destination);
          this.project = project;
          this.resultSelector = resultSelector;
          this.concurrent = concurrent;
          this.hasCompleted = false;
          this.buffer = [];
          this.active = 0;
          this.index = 0;
      }
      MergeMapSubscriber.prototype._next = function (value) {
          if (this.active < this.concurrent) {
              this._tryNext(value);
          }
          else {
              this.buffer.push(value);
          }
      };
      MergeMapSubscriber.prototype._tryNext = function (value) {
          var result;
          var index = this.index++;
          try {
              result = this.project(value, index);
          }
          catch (err) {
              this.destination.error(err);
              return;
          }
          this.active++;
          this._innerSub(result, value, index);
      };
      MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
          this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
      };
      MergeMapSubscriber.prototype._complete = function () {
          this.hasCompleted = true;
          if (this.active === 0 && this.buffer.length === 0) {
              this.destination.complete();
          }
      };
      MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
          if (this.resultSelector) {
              this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
          }
          else {
              this.destination.next(innerValue);
          }
      };
      MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
          var result;
          try {
              result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
          }
          catch (err) {
              this.destination.error(err);
              return;
          }
          this.destination.next(result);
      };
      MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
          var buffer = this.buffer;
          this.remove(innerSub);
          this.active--;
          if (buffer.length > 0) {
              this._next(buffer.shift());
          }
          else if (this.active === 0 && this.hasCompleted) {
              this.destination.complete();
          }
      };
      return MergeMapSubscriber;
  }(OuterSubscriber_1.OuterSubscriber));
  exports.MergeMapSubscriber = MergeMapSubscriber;
  
  },{"../OuterSubscriber":25,"../util/subscribeToResult":75}],50:[function(require,module,exports){
  "use strict";
  var ConnectableObservable_1 = require('../observable/ConnectableObservable');
  /* tslint:enable:max-line-length */
  /**
   * Returns an Observable that emits the results of invoking a specified selector on items
   * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
   *
   * <img src="./img/multicast.png" width="100%">
   *
   * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
   * which the source sequence's elements will be multicast to the selector function
   * or Subject to push source elements into.
   * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
   * as many times as needed, without causing multiple subscriptions to the source stream.
   * Subscribers to the given source will receive all notifications of the source from the
   * time of the subscription forward.
   * @return {Observable} An Observable that emits the results of invoking the selector
   * on the items emitted by a `ConnectableObservable` that shares a single subscription to
   * the underlying stream.
   * @method multicast
   * @owner Observable
   */
  function multicast(subjectOrSubjectFactory, selector) {
      return function multicastOperatorFunction(source) {
          var subjectFactory;
          if (typeof subjectOrSubjectFactory === 'function') {
              subjectFactory = subjectOrSubjectFactory;
          }
          else {
              subjectFactory = function subjectFactory() {
                  return subjectOrSubjectFactory;
              };
          }
          if (typeof selector === 'function') {
              return source.lift(new MulticastOperator(subjectFactory, selector));
          }
          var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
          connectable.source = source;
          connectable.subjectFactory = subjectFactory;
          return connectable;
      };
  }
  exports.multicast = multicast;
  var MulticastOperator = (function () {
      function MulticastOperator(subjectFactory, selector) {
          this.subjectFactory = subjectFactory;
          this.selector = selector;
      }
      MulticastOperator.prototype.call = function (subscriber, source) {
          var selector = this.selector;
          var subject = this.subjectFactory();
          var subscription = selector(subject).subscribe(subscriber);
          subscription.add(source.subscribe(subject));
          return subscription;
      };
      return MulticastOperator;
  }());
  exports.MulticastOperator = MulticastOperator;
  
  },{"../observable/ConnectableObservable":38}],51:[function(require,module,exports){
  "use strict";
  var Subject_1 = require('../Subject');
  var multicast_1 = require('./multicast');
  /* tslint:enable:max-line-length */
  /**
   * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
   * before it begins emitting items to those Observers that have subscribed to it.
   *
   * <img src="./img/publish.png" width="100%">
   *
   * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
   * as needed, without causing multiple subscriptions to the source sequence.
   * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
   * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
   * @method publish
   * @owner Observable
   */
  function publish(selector) {
      return selector ?
          multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
          multicast_1.multicast(new Subject_1.Subject());
  }
  exports.publish = publish;
  
  },{"../Subject":27,"./multicast":50}],52:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subscriber_1 = require('../Subscriber');
  function refCount() {
      return function refCountOperatorFunction(source) {
          return source.lift(new RefCountOperator(source));
      };
  }
  exports.refCount = refCount;
  var RefCountOperator = (function () {
      function RefCountOperator(connectable) {
          this.connectable = connectable;
      }
      RefCountOperator.prototype.call = function (subscriber, source) {
          var connectable = this.connectable;
          connectable._refCount++;
          var refCounter = new RefCountSubscriber(subscriber, connectable);
          var subscription = source.subscribe(refCounter);
          if (!refCounter.closed) {
              refCounter.connection = connectable.connect();
          }
          return subscription;
      };
      return RefCountOperator;
  }());
  var RefCountSubscriber = (function (_super) {
      __extends(RefCountSubscriber, _super);
      function RefCountSubscriber(destination, connectable) {
          _super.call(this, destination);
          this.connectable = connectable;
      }
      RefCountSubscriber.prototype._unsubscribe = function () {
          var connectable = this.connectable;
          if (!connectable) {
              this.connection = null;
              return;
          }
          this.connectable = null;
          var refCount = connectable._refCount;
          if (refCount <= 0) {
              this.connection = null;
              return;
          }
          connectable._refCount = refCount - 1;
          if (refCount > 1) {
              this.connection = null;
              return;
          }
          ///
          // Compare the local RefCountSubscriber's connection Subscription to the
          // connection Subscription on the shared ConnectableObservable. In cases
          // where the ConnectableObservable source synchronously emits values, and
          // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
          // execution continues to here before the RefCountOperator has a chance to
          // supply the RefCountSubscriber with the shared connection Subscription.
          // For example:
          // ```
          // Observable.range(0, 10)
          //   .publish()
          //   .refCount()
          //   .take(5)
          //   .subscribe();
          // ```
          // In order to account for this case, RefCountSubscriber should only dispose
          // the ConnectableObservable's shared connection Subscription if the
          // connection Subscription exists, *and* either:
          //   a. RefCountSubscriber doesn't have a reference to the shared connection
          //      Subscription yet, or,
          //   b. RefCountSubscriber's connection Subscription reference is identical
          //      to the shared connection Subscription
          ///
          var connection = this.connection;
          var sharedConnection = connectable._connection;
          this.connection = null;
          if (sharedConnection && (!connection || sharedConnection === connection)) {
              sharedConnection.unsubscribe();
          }
      };
      return RefCountSubscriber;
  }(Subscriber_1.Subscriber));
  
  },{"../Subscriber":29}],53:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subject_1 = require('../Subject');
  var tryCatch_1 = require('../util/tryCatch');
  var errorObject_1 = require('../util/errorObject');
  var OuterSubscriber_1 = require('../OuterSubscriber');
  var subscribeToResult_1 = require('../util/subscribeToResult');
  /**
   * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
   * calls `error`, this method will emit the Throwable that caused the error to the Observable returned from `notifier`.
   * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child
   * subscription. Otherwise this method will resubscribe to the source Observable.
   *
   * <img src="./img/retryWhen.png" width="100%">
   *
   * @param {function(errors: Observable): Observable} notifier - Receives an Observable of notifications with which a
   * user can `complete` or `error`, aborting the retry.
   * @return {Observable} The source Observable modified with retry logic.
   * @method retryWhen
   * @owner Observable
   */
  function retryWhen(notifier) {
      return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
  }
  exports.retryWhen = retryWhen;
  var RetryWhenOperator = (function () {
      function RetryWhenOperator(notifier, source) {
          this.notifier = notifier;
          this.source = source;
      }
      RetryWhenOperator.prototype.call = function (subscriber, source) {
          return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
      };
      return RetryWhenOperator;
  }());
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var RetryWhenSubscriber = (function (_super) {
      __extends(RetryWhenSubscriber, _super);
      function RetryWhenSubscriber(destination, notifier, source) {
          _super.call(this, destination);
          this.notifier = notifier;
          this.source = source;
      }
      RetryWhenSubscriber.prototype.error = function (err) {
          if (!this.isStopped) {
              var errors = this.errors;
              var retries = this.retries;
              var retriesSubscription = this.retriesSubscription;
              if (!retries) {
                  errors = new Subject_1.Subject();
                  retries = tryCatch_1.tryCatch(this.notifier)(errors);
                  if (retries === errorObject_1.errorObject) {
                      return _super.prototype.error.call(this, errorObject_1.errorObject.e);
                  }
                  retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
              }
              else {
                  this.errors = null;
                  this.retriesSubscription = null;
              }
              this._unsubscribeAndRecycle();
              this.errors = errors;
              this.retries = retries;
              this.retriesSubscription = retriesSubscription;
              errors.next(err);
          }
      };
      RetryWhenSubscriber.prototype._unsubscribe = function () {
          var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
          if (errors) {
              errors.unsubscribe();
              this.errors = null;
          }
          if (retriesSubscription) {
              retriesSubscription.unsubscribe();
              this.retriesSubscription = null;
          }
          this.retries = null;
      };
      RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
          var _a = this, errors = _a.errors, retries = _a.retries, retriesSubscription = _a.retriesSubscription;
          this.errors = null;
          this.retries = null;
          this.retriesSubscription = null;
          this._unsubscribeAndRecycle();
          this.errors = errors;
          this.retries = retries;
          this.retriesSubscription = retriesSubscription;
          this.source.subscribe(this);
      };
      return RetryWhenSubscriber;
  }(OuterSubscriber_1.OuterSubscriber));
  
  },{"../OuterSubscriber":25,"../Subject":27,"../util/errorObject":64,"../util/subscribeToResult":75,"../util/tryCatch":77}],54:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var ArrayObservable_1 = require('../observable/ArrayObservable');
  var isArray_1 = require('../util/isArray');
  var Subscriber_1 = require('../Subscriber');
  var OuterSubscriber_1 = require('../OuterSubscriber');
  var subscribeToResult_1 = require('../util/subscribeToResult');
  var iterator_1 = require('../symbol/iterator');
  /* tslint:enable:max-line-length */
  /**
   * @param observables
   * @return {Observable<R>}
   * @method zip
   * @owner Observable
   */
  function zip() {
      var observables = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          observables[_i - 0] = arguments[_i];
      }
      return function zipOperatorFunction(source) {
          return source.lift.call(zipStatic.apply(void 0, [source].concat(observables)));
      };
  }
  exports.zip = zip;
  /* tslint:enable:max-line-length */
  /**
   * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
   * of its input Observables.
   *
   * If the latest parameter is a function, this function is used to compute the created value from the input values.
   * Otherwise, an array of the input values is returned.
   *
   * @example <caption>Combine age and name from different sources</caption>
   *
   * let age$ = Observable.of<number>(27, 25, 29);
   * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
   * let isDev$ = Observable.of<boolean>(true, true, false);
   *
   * Observable
   *     .zip(age$,
   *          name$,
   *          isDev$,
   *          (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
   *     .subscribe(x => console.log(x));
   *
   * // outputs
   * // { age: 27, name: 'Foo', isDev: true }
   * // { age: 25, name: 'Bar', isDev: true }
   * // { age: 29, name: 'Beer', isDev: false }
   *
   * @param observables
   * @return {Observable<R>}
   * @static true
   * @name zip
   * @owner Observable
   */
  function zipStatic() {
      var observables = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          observables[_i - 0] = arguments[_i];
      }
      var project = observables[observables.length - 1];
      if (typeof project === 'function') {
          observables.pop();
      }
      return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
  }
  exports.zipStatic = zipStatic;
  var ZipOperator = (function () {
      function ZipOperator(project) {
          this.project = project;
      }
      ZipOperator.prototype.call = function (subscriber, source) {
          return source.subscribe(new ZipSubscriber(subscriber, this.project));
      };
      return ZipOperator;
  }());
  exports.ZipOperator = ZipOperator;
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var ZipSubscriber = (function (_super) {
      __extends(ZipSubscriber, _super);
      function ZipSubscriber(destination, project, values) {
          if (values === void 0) { values = Object.create(null); }
          _super.call(this, destination);
          this.iterators = [];
          this.active = 0;
          this.project = (typeof project === 'function') ? project : null;
          this.values = values;
      }
      ZipSubscriber.prototype._next = function (value) {
          var iterators = this.iterators;
          if (isArray_1.isArray(value)) {
              iterators.push(new StaticArrayIterator(value));
          }
          else if (typeof value[iterator_1.iterator] === 'function') {
              iterators.push(new StaticIterator(value[iterator_1.iterator]()));
          }
          else {
              iterators.push(new ZipBufferIterator(this.destination, this, value));
          }
      };
      ZipSubscriber.prototype._complete = function () {
          var iterators = this.iterators;
          var len = iterators.length;
          if (len === 0) {
              this.destination.complete();
              return;
          }
          this.active = len;
          for (var i = 0; i < len; i++) {
              var iterator = iterators[i];
              if (iterator.stillUnsubscribed) {
                  this.add(iterator.subscribe(iterator, i));
              }
              else {
                  this.active--; // not an observable
              }
          }
      };
      ZipSubscriber.prototype.notifyInactive = function () {
          this.active--;
          if (this.active === 0) {
              this.destination.complete();
          }
      };
      ZipSubscriber.prototype.checkIterators = function () {
          var iterators = this.iterators;
          var len = iterators.length;
          var destination = this.destination;
          // abort if not all of them have values
          for (var i = 0; i < len; i++) {
              var iterator = iterators[i];
              if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
                  return;
              }
          }
          var shouldComplete = false;
          var args = [];
          for (var i = 0; i < len; i++) {
              var iterator = iterators[i];
              var result = iterator.next();
              // check to see if it's completed now that you've gotten
              // the next value.
              if (iterator.hasCompleted()) {
                  shouldComplete = true;
              }
              if (result.done) {
                  destination.complete();
                  return;
              }
              args.push(result.value);
          }
          if (this.project) {
              this._tryProject(args);
          }
          else {
              destination.next(args);
          }
          if (shouldComplete) {
              destination.complete();
          }
      };
      ZipSubscriber.prototype._tryProject = function (args) {
          var result;
          try {
              result = this.project.apply(this, args);
          }
          catch (err) {
              this.destination.error(err);
              return;
          }
          this.destination.next(result);
      };
      return ZipSubscriber;
  }(Subscriber_1.Subscriber));
  exports.ZipSubscriber = ZipSubscriber;
  var StaticIterator = (function () {
      function StaticIterator(iterator) {
          this.iterator = iterator;
          this.nextResult = iterator.next();
      }
      StaticIterator.prototype.hasValue = function () {
          return true;
      };
      StaticIterator.prototype.next = function () {
          var result = this.nextResult;
          this.nextResult = this.iterator.next();
          return result;
      };
      StaticIterator.prototype.hasCompleted = function () {
          var nextResult = this.nextResult;
          return nextResult && nextResult.done;
      };
      return StaticIterator;
  }());
  var StaticArrayIterator = (function () {
      function StaticArrayIterator(array) {
          this.array = array;
          this.index = 0;
          this.length = 0;
          this.length = array.length;
      }
      StaticArrayIterator.prototype[iterator_1.iterator] = function () {
          return this;
      };
      StaticArrayIterator.prototype.next = function (value) {
          var i = this.index++;
          var array = this.array;
          return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
      };
      StaticArrayIterator.prototype.hasValue = function () {
          return this.array.length > this.index;
      };
      StaticArrayIterator.prototype.hasCompleted = function () {
          return this.array.length === this.index;
      };
      return StaticArrayIterator;
  }());
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var ZipBufferIterator = (function (_super) {
      __extends(ZipBufferIterator, _super);
      function ZipBufferIterator(destination, parent, observable) {
          _super.call(this, destination);
          this.parent = parent;
          this.observable = observable;
          this.stillUnsubscribed = true;
          this.buffer = [];
          this.isComplete = false;
      }
      ZipBufferIterator.prototype[iterator_1.iterator] = function () {
          return this;
      };
      // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
      //    this is legit because `next()` will never be called by a subscription in this case.
      ZipBufferIterator.prototype.next = function () {
          var buffer = this.buffer;
          if (buffer.length === 0 && this.isComplete) {
              return { value: null, done: true };
          }
          else {
              return { value: buffer.shift(), done: false };
          }
      };
      ZipBufferIterator.prototype.hasValue = function () {
          return this.buffer.length > 0;
      };
      ZipBufferIterator.prototype.hasCompleted = function () {
          return this.buffer.length === 0 && this.isComplete;
      };
      ZipBufferIterator.prototype.notifyComplete = function () {
          if (this.buffer.length > 0) {
              this.isComplete = true;
              this.parent.notifyInactive();
          }
          else {
              this.destination.complete();
          }
      };
      ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
          this.buffer.push(innerValue);
          this.parent.checkIterators();
      };
      ZipBufferIterator.prototype.subscribe = function (value, index) {
          return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
      };
      return ZipBufferIterator;
  }(OuterSubscriber_1.OuterSubscriber));
  
  },{"../OuterSubscriber":25,"../Subscriber":29,"../observable/ArrayObservable":37,"../symbol/iterator":59,"../util/isArray":65,"../util/subscribeToResult":75}],55:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Subscription_1 = require('../Subscription');
  /**
   * A unit of work to be executed in a {@link Scheduler}. An action is typically
   * created from within a Scheduler and an RxJS user does not need to concern
   * themselves about creating and manipulating an Action.
   *
   * ```ts
   * class Action<T> extends Subscription {
   *   new (scheduler: Scheduler, work: (state?: T) => void);
   *   schedule(state?: T, delay: number = 0): Subscription;
   * }
   * ```
   *
   * @class Action<T>
   */
  var Action = (function (_super) {
      __extends(Action, _super);
      function Action(scheduler, work) {
          _super.call(this);
      }
      /**
       * Schedules this action on its parent Scheduler for execution. May be passed
       * some context object, `state`. May happen at some point in the future,
       * according to the `delay` parameter, if specified.
       * @param {T} [state] Some contextual data that the `work` function uses when
       * called by the Scheduler.
       * @param {number} [delay] Time to wait before executing the work, where the
       * time unit is implicit and defined by the Scheduler.
       * @return {void}
       */
      Action.prototype.schedule = function (state, delay) {
          if (delay === void 0) { delay = 0; }
          return this;
      };
      return Action;
  }(Subscription_1.Subscription));
  exports.Action = Action;
  
  },{"../Subscription":30}],56:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var root_1 = require('../util/root');
  var Action_1 = require('./Action');
  /**
   * We need this JSDoc comment for affecting ESDoc.
   * @ignore
   * @extends {Ignored}
   */
  var AsyncAction = (function (_super) {
      __extends(AsyncAction, _super);
      function AsyncAction(scheduler, work) {
          _super.call(this, scheduler, work);
          this.scheduler = scheduler;
          this.work = work;
          this.pending = false;
      }
      AsyncAction.prototype.schedule = function (state, delay) {
          if (delay === void 0) { delay = 0; }
          if (this.closed) {
              return this;
          }
          // Always replace the current state with the new state.
          this.state = state;
          // Set the pending flag indicating that this action has been scheduled, or
          // has recursively rescheduled itself.
          this.pending = true;
          var id = this.id;
          var scheduler = this.scheduler;
          //
          // Important implementation note:
          //
          // Actions only execute once by default, unless rescheduled from within the
          // scheduled callback. This allows us to implement single and repeat
          // actions via the same code path, without adding API surface area, as well
          // as mimic traditional recursion but across asynchronous boundaries.
          //
          // However, JS runtimes and timers distinguish between intervals achieved by
          // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
          // serial `setTimeout` calls can be individually delayed, which delays
          // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
          // guarantee the interval callback will be invoked more precisely to the
          // interval period, regardless of load.
          //
          // Therefore, we use `setInterval` to schedule single and repeat actions.
          // If the action reschedules itself with the same delay, the interval is not
          // canceled. If the action doesn't reschedule, or reschedules with a
          // different delay, the interval will be canceled after scheduled callback
          // execution.
          //
          if (id != null) {
              this.id = this.recycleAsyncId(scheduler, id, delay);
          }
          this.delay = delay;
          // If this action has already an async Id, don't request a new one.
          this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
          return this;
      };
      AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
          if (delay === void 0) { delay = 0; }
          return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
      };
      AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
          if (delay === void 0) { delay = 0; }
          // If this action is rescheduled with the same delay time, don't clear the interval id.
          if (delay !== null && this.delay === delay && this.pending === false) {
              return id;
          }
          // Otherwise, if the action's delay time is different from the current delay,
          // or the action has been rescheduled before it's executed, clear the interval id
          return root_1.root.clearInterval(id) && undefined || undefined;
      };
      /**
       * Immediately executes this action and the `work` it contains.
       * @return {any}
       */
      AsyncAction.prototype.execute = function (state, delay) {
          if (this.closed) {
              return new Error('executing a cancelled action');
          }
          this.pending = false;
          var error = this._execute(state, delay);
          if (error) {
              return error;
          }
          else if (this.pending === false && this.id != null) {
              // Dequeue if the action didn't reschedule itself. Don't call
              // unsubscribe(), because the action could reschedule later.
              // For example:
              // ```
              // scheduler.schedule(function doWork(counter) {
              //   /* ... I'm a busy worker bee ... */
              //   var originalAction = this;
              //   /* wait 100ms before rescheduling the action */
              //   setTimeout(function () {
              //     originalAction.schedule(counter + 1);
              //   }, 100);
              // }, 1000);
              // ```
              this.id = this.recycleAsyncId(this.scheduler, this.id, null);
          }
      };
      AsyncAction.prototype._execute = function (state, delay) {
          var errored = false;
          var errorValue = undefined;
          try {
              this.work(state);
          }
          catch (e) {
              errored = true;
              errorValue = !!e && e || new Error(e);
          }
          if (errored) {
              this.unsubscribe();
              return errorValue;
          }
      };
      AsyncAction.prototype._unsubscribe = function () {
          var id = this.id;
          var scheduler = this.scheduler;
          var actions = scheduler.actions;
          var index = actions.indexOf(this);
          this.work = null;
          this.state = null;
          this.pending = false;
          this.scheduler = null;
          if (index !== -1) {
              actions.splice(index, 1);
          }
          if (id != null) {
              this.id = this.recycleAsyncId(scheduler, id, null);
          }
          this.delay = null;
      };
      return AsyncAction;
  }(Action_1.Action));
  exports.AsyncAction = AsyncAction;
  
  },{"../util/root":74,"./Action":55}],57:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Scheduler_1 = require('../Scheduler');
  var AsyncScheduler = (function (_super) {
      __extends(AsyncScheduler, _super);
      function AsyncScheduler() {
          _super.apply(this, arguments);
          this.actions = [];
          /**
           * A flag to indicate whether the Scheduler is currently executing a batch of
           * queued actions.
           * @type {boolean}
           */
          this.active = false;
          /**
           * An internal ID used to track the latest asynchronous task such as those
           * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
           * others.
           * @type {any}
           */
          this.scheduled = undefined;
      }
      AsyncScheduler.prototype.flush = function (action) {
          var actions = this.actions;
          if (this.active) {
              actions.push(action);
              return;
          }
          var error;
          this.active = true;
          do {
              if (error = action.execute(action.state, action.delay)) {
                  break;
              }
          } while (action = actions.shift()); // exhaust the scheduler queue
          this.active = false;
          if (error) {
              while (action = actions.shift()) {
                  action.unsubscribe();
              }
              throw error;
          }
      };
      return AsyncScheduler;
  }(Scheduler_1.Scheduler));
  exports.AsyncScheduler = AsyncScheduler;
  
  },{"../Scheduler":26}],58:[function(require,module,exports){
  "use strict";
  var AsyncAction_1 = require('./AsyncAction');
  var AsyncScheduler_1 = require('./AsyncScheduler');
  /**
   *
   * Async Scheduler
   *
   * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
   *
   * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
   * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
   * in intervals.
   *
   * If you just want to "defer" task, that is to perform it right after currently
   * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
   * better choice will be the {@link asap} scheduler.
   *
   * @example <caption>Use async scheduler to delay task</caption>
   * const task = () => console.log('it works!');
   *
   * Rx.Scheduler.async.schedule(task, 2000);
   *
   * // After 2 seconds logs:
   * // "it works!"
   *
   *
   * @example <caption>Use async scheduler to repeat task in intervals</caption>
   * function task(state) {
   *   console.log(state);
   *   this.schedule(state + 1, 1000); // `this` references currently executing Action,
   *                                   // which we reschedule with new state and delay
   * }
   *
   * Rx.Scheduler.async.schedule(task, 3000, 0);
   *
   * // Logs:
   * // 0 after 3s
   * // 1 after 4s
   * // 2 after 5s
   * // 3 after 6s
   *
   * @static true
   * @name async
   * @owner Scheduler
   */
  exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
  
  },{"./AsyncAction":56,"./AsyncScheduler":57}],59:[function(require,module,exports){
  "use strict";
  var root_1 = require('../util/root');
  function symbolIteratorPonyfill(root) {
      var Symbol = root.Symbol;
      if (typeof Symbol === 'function') {
          if (!Symbol.iterator) {
              Symbol.iterator = Symbol('iterator polyfill');
          }
          return Symbol.iterator;
      }
      else {
          // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
          var Set_1 = root.Set;
          if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
              return '@@iterator';
          }
          var Map_1 = root.Map;
          // required for compatability with es6-shim
          if (Map_1) {
              var keys = Object.getOwnPropertyNames(Map_1.prototype);
              for (var i = 0; i < keys.length; ++i) {
                  var key = keys[i];
                  // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
                  if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
                      return key;
                  }
              }
          }
          return '@@iterator';
      }
  }
  exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
  exports.iterator = symbolIteratorPonyfill(root_1.root);
  /**
   * @deprecated use iterator instead
   */
  exports.$$iterator = exports.iterator;
  
  },{"../util/root":74}],60:[function(require,module,exports){
  "use strict";
  var root_1 = require('../util/root');
  function getSymbolObservable(context) {
      var $$observable;
      var Symbol = context.Symbol;
      if (typeof Symbol === 'function') {
          if (Symbol.observable) {
              $$observable = Symbol.observable;
          }
          else {
              $$observable = Symbol('observable');
              Symbol.observable = $$observable;
          }
      }
      else {
          $$observable = '@@observable';
      }
      return $$observable;
  }
  exports.getSymbolObservable = getSymbolObservable;
  exports.observable = getSymbolObservable(root_1.root);
  /**
   * @deprecated use observable instead
   */
  exports.$$observable = exports.observable;
  
  },{"../util/root":74}],61:[function(require,module,exports){
  "use strict";
  var root_1 = require('../util/root');
  var Symbol = root_1.root.Symbol;
  exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
      Symbol.for('rxSubscriber') : '@@rxSubscriber';
  /**
   * @deprecated use rxSubscriber instead
   */
  exports.$$rxSubscriber = exports.rxSubscriber;
  
  },{"../util/root":74}],62:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  /**
   * An error thrown when an action is invalid because the object has been
   * unsubscribed.
   *
   * @see {@link Subject}
   * @see {@link BehaviorSubject}
   *
   * @class ObjectUnsubscribedError
   */
  var ObjectUnsubscribedError = (function (_super) {
      __extends(ObjectUnsubscribedError, _super);
      function ObjectUnsubscribedError() {
          var err = _super.call(this, 'object unsubscribed');
          this.name = err.name = 'ObjectUnsubscribedError';
          this.stack = err.stack;
          this.message = err.message;
      }
      return ObjectUnsubscribedError;
  }(Error));
  exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
  
  },{}],63:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || function (d, b) {
      for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  /**
   * An error thrown when one or more errors have occurred during the
   * `unsubscribe` of a {@link Subscription}.
   */
  var UnsubscriptionError = (function (_super) {
      __extends(UnsubscriptionError, _super);
      function UnsubscriptionError(errors) {
          _super.call(this);
          this.errors = errors;
          var err = Error.call(this, errors ?
              errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
          this.name = err.name = 'UnsubscriptionError';
          this.stack = err.stack;
          this.message = err.message;
      }
      return UnsubscriptionError;
  }(Error));
  exports.UnsubscriptionError = UnsubscriptionError;
  
  },{}],64:[function(require,module,exports){
  "use strict";
  // typeof any so that it we don't have to cast when comparing a result to the error object
  exports.errorObject = { e: {} };
  
  },{}],65:[function(require,module,exports){
  "use strict";
  exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
  
  },{}],66:[function(require,module,exports){
  "use strict";
  exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
  
  },{}],67:[function(require,module,exports){
  "use strict";
  function isDate(value) {
      return value instanceof Date && !isNaN(+value);
  }
  exports.isDate = isDate;
  
  },{}],68:[function(require,module,exports){
  "use strict";
  function isFunction(x) {
      return typeof x === 'function';
  }
  exports.isFunction = isFunction;
  
  },{}],69:[function(require,module,exports){
  "use strict";
  function isObject(x) {
      return x != null && typeof x === 'object';
  }
  exports.isObject = isObject;
  
  },{}],70:[function(require,module,exports){
  "use strict";
  function isPromise(value) {
      return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
  }
  exports.isPromise = isPromise;
  
  },{}],71:[function(require,module,exports){
  "use strict";
  function isScheduler(value) {
      return value && typeof value.schedule === 'function';
  }
  exports.isScheduler = isScheduler;
  
  },{}],72:[function(require,module,exports){
  "use strict";
  /* tslint:disable:no-empty */
  function noop() { }
  exports.noop = noop;
  
  },{}],73:[function(require,module,exports){
  "use strict";
  var noop_1 = require('./noop');
  /* tslint:enable:max-line-length */
  function pipe() {
      var fns = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          fns[_i - 0] = arguments[_i];
      }
      return pipeFromArray(fns);
  }
  exports.pipe = pipe;
  /* @internal */
  function pipeFromArray(fns) {
      if (!fns) {
          return noop_1.noop;
      }
      if (fns.length === 1) {
          return fns[0];
      }
      return function piped(input) {
          return fns.reduce(function (prev, fn) { return fn(prev); }, input);
      };
  }
  exports.pipeFromArray = pipeFromArray;
  
  },{"./noop":72}],74:[function(require,module,exports){
  (function (global){
  "use strict";
  // CommonJS / Node have global context exposed as "global" variable.
  // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
  // the global "global" var for now.
  var __window = typeof window !== 'undefined' && window;
  var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
      self instanceof WorkerGlobalScope && self;
  var __global = typeof global !== 'undefined' && global;
  var _root = __window || __global || __self;
  exports.root = _root;
  // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
  // This is needed when used with angular/tsickle which inserts a goog.module statement.
  // Wrap in IIFE
  (function () {
      if (!_root) {
          throw new Error('RxJS could not find any global context (window, self, global)');
      }
  })();
  
  }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{}],75:[function(require,module,exports){
  "use strict";
  var root_1 = require('./root');
  var isArrayLike_1 = require('./isArrayLike');
  var isPromise_1 = require('./isPromise');
  var isObject_1 = require('./isObject');
  var Observable_1 = require('../Observable');
  var iterator_1 = require('../symbol/iterator');
  var InnerSubscriber_1 = require('../InnerSubscriber');
  var observable_1 = require('../symbol/observable');
  function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
      var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
      if (destination.closed) {
          return null;
      }
      if (result instanceof Observable_1.Observable) {
          if (result._isScalar) {
              destination.next(result.value);
              destination.complete();
              return null;
          }
          else {
              destination.syncErrorThrowable = true;
              return result.subscribe(destination);
          }
      }
      else if (isArrayLike_1.isArrayLike(result)) {
          for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
              destination.next(result[i]);
          }
          if (!destination.closed) {
              destination.complete();
          }
      }
      else if (isPromise_1.isPromise(result)) {
          result.then(function (value) {
              if (!destination.closed) {
                  destination.next(value);
                  destination.complete();
              }
          }, function (err) { return destination.error(err); })
              .then(null, function (err) {
              // Escaping the Promise trap: globally throw unhandled errors
              root_1.root.setTimeout(function () { throw err; });
          });
          return destination;
      }
      else if (result && typeof result[iterator_1.iterator] === 'function') {
          var iterator = result[iterator_1.iterator]();
          do {
              var item = iterator.next();
              if (item.done) {
                  destination.complete();
                  break;
              }
              destination.next(item.value);
              if (destination.closed) {
                  break;
              }
          } while (true);
      }
      else if (result && typeof result[observable_1.observable] === 'function') {
          var obs = result[observable_1.observable]();
          if (typeof obs.subscribe !== 'function') {
              destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
          }
          else {
              return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
          }
      }
      else {
          var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
          var msg = ("You provided " + value + " where a stream was expected.")
              + ' You can provide an Observable, Promise, Array, or Iterable.';
          destination.error(new TypeError(msg));
      }
      return null;
  }
  exports.subscribeToResult = subscribeToResult;
  
  },{"../InnerSubscriber":21,"../Observable":23,"../symbol/iterator":59,"../symbol/observable":60,"./isArrayLike":66,"./isObject":69,"./isPromise":70,"./root":74}],76:[function(require,module,exports){
  "use strict";
  var Subscriber_1 = require('../Subscriber');
  var rxSubscriber_1 = require('../symbol/rxSubscriber');
  var Observer_1 = require('../Observer');
  function toSubscriber(nextOrObserver, error, complete) {
      if (nextOrObserver) {
          if (nextOrObserver instanceof Subscriber_1.Subscriber) {
              return nextOrObserver;
          }
          if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
              return nextOrObserver[rxSubscriber_1.rxSubscriber]();
          }
      }
      if (!nextOrObserver && !error && !complete) {
          return new Subscriber_1.Subscriber(Observer_1.empty);
      }
      return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
  }
  exports.toSubscriber = toSubscriber;
  
  },{"../Observer":24,"../Subscriber":29,"../symbol/rxSubscriber":61}],77:[function(require,module,exports){
  "use strict";
  var errorObject_1 = require('./errorObject');
  var tryCatchTarget;
  function tryCatcher() {
      try {
          return tryCatchTarget.apply(this, arguments);
      }
      catch (e) {
          errorObject_1.errorObject.e = e;
          return errorObject_1.errorObject;
      }
  }
  function tryCatch(fn) {
      tryCatchTarget = fn;
      return tryCatcher;
  }
  exports.tryCatch = tryCatch;
  ;
  
  },{"./errorObject":64}],78:[function(require,module,exports){
  'use strict'
  
  var util = require('util')
  
  var Observable = require('rxjs/Observable').Observable
  var Subscription = require('rxjs/Subscription').Subscription
  
  module.exports = StaticObservable
  
  /**
   * @class StaticObservable
   */
  function StaticObservable () {
    Observable.call(this, subscribe)
    var self = this
    this._observer = null
    this._observerCalls = []
    function subscribe (observer) {
      self._observer = observer
      while (self._observerCalls.length) {
        var call = self._observerCalls.shift()
        observer[call.method].apply(observer, call.args)
      }
      return new Subscription()
    }
  }
  
  // inherit from observable
  util.inherits(StaticObservable, Observable)
  
  /**
   * StaticObservable factories
   */
  
  /**
   * returns an Observable that is immediately "nexted" w/ the given "next" value (all args)
   * @param  {*} next  observable next value
   * @return {Observable} observable
   */
  StaticObservable.next = function () {
    var observable = new StaticObservable()
    return observable.next.apply(observable, arguments)
  }
  
  /**
   * returns an Observable that is immediately "errored" w/ the given error (all args)
   * @param  {Error} error  observable error
   * @return {Observable} observable
   */
  StaticObservable.error = function () {
    var observable = new StaticObservable()
    return observable.error.apply(observable, arguments)
  }
  
  /**
   * returns an Observable that is immediately "completed"
   * @return {Observable} observable
   */
  StaticObservable.complete = function () {
    var observable = new StaticObservable()
    return observable.complete.apply(observable, arguments)
  }
  
  /**
   * Chainable instance methods
   */
  
  StaticObservable.prototype.next = observerCall('next')
  
  StaticObservable.prototype.error = observerCall('error')
  
  StaticObservable.prototype.complete = observerCall('complete')
  
  function observerCall (method) {
    return function () {
      var _observer = this._observer
      if (_observer) {
        _observer[method].apply(_observer, arguments)
      } else {
        this._observerCalls.push({
          method: method,
          args: Array.prototype.slice.call(arguments)
        })
      }
      return this
    }
  }
  },{"rxjs/Observable":23,"rxjs/Subscription":30,"util":81}],79:[function(require,module,exports){
  if (typeof Object.create === 'function') {
    // implementation from standard node.js 'util' module
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
    };
  } else {
    // old school shim for old browsers
    module.exports = function inherits(ctor, superCtor) {
      ctor.super_ = superCtor
      var TempCtor = function () {}
      TempCtor.prototype = superCtor.prototype
      ctor.prototype = new TempCtor()
      ctor.prototype.constructor = ctor
    }
  }
  
  },{}],80:[function(require,module,exports){
  module.exports = function isBuffer(arg) {
    return arg && typeof arg === 'object'
      && typeof arg.copy === 'function'
      && typeof arg.fill === 'function'
      && typeof arg.readUInt8 === 'function';
  }
  },{}],81:[function(require,module,exports){
  (function (process,global){
  // 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.
  
  var formatRegExp = /%[sdj%]/g;
  exports.format = function(f) {
    if (!isString(f)) {
      var objects = [];
      for (var i = 0; i < arguments.length; i++) {
        objects.push(inspect(arguments[i]));
      }
      return objects.join(' ');
    }
  
    var i = 1;
    var args = arguments;
    var len = args.length;
    var str = String(f).replace(formatRegExp, function(x) {
      if (x === '%%') return '%';
      if (i >= len) return x;
      switch (x) {
        case '%s': return String(args[i++]);
        case '%d': return Number(args[i++]);
        case '%j':
          try {
            return JSON.stringify(args[i++]);
          } catch (_) {
            return '[Circular]';
          }
        default:
          return x;
      }
    });
    for (var x = args[i]; i < len; x = args[++i]) {
      if (isNull(x) || !isObject(x)) {
        str += ' ' + x;
      } else {
        str += ' ' + inspect(x);
      }
    }
    return str;
  };
  
  
  // Mark that a method should not be used.
  // Returns a modified function which warns once by default.
  // If --no-deprecation is set, then it is a no-op.
  exports.deprecate = function(fn, msg) {
    // Allow for deprecating things in the process of starting up.
    if (isUndefined(global.process)) {
      return function() {
        return exports.deprecate(fn, msg).apply(this, arguments);
      };
    }
  
    if (process.noDeprecation === true) {
      return fn;
    }
  
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (process.throwDeprecation) {
          throw new Error(msg);
        } else if (process.traceDeprecation) {
          console.trace(msg);
        } else {
          console.error(msg);
        }
        warned = true;
      }
      return fn.apply(this, arguments);
    }
  
    return deprecated;
  };
  
  
  var debugs = {};
  var debugEnviron;
  exports.debuglog = function(set) {
    if (isUndefined(debugEnviron))
      debugEnviron = process.env.NODE_DEBUG || '';
    set = set.toUpperCase();
    if (!debugs[set]) {
      if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
        var pid = process.pid;
        debugs[set] = function() {
          var msg = exports.format.apply(exports, arguments);
          console.error('%s %d: %s', set, pid, msg);
        };
      } else {
        debugs[set] = function() {};
      }
    }
    return debugs[set];
  };
  
  
  /**
   * Echos the value of a value. Trys to print the value out
   * in the best way possible given the different types.
   *
   * @param {Object} obj The object to print out.
   * @param {Object} opts Optional options object that alters the output.
   */
  /* legacy: obj, showHidden, depth, colors*/
  function inspect(obj, opts) {
    // default options
    var ctx = {
      seen: [],
      stylize: stylizeNoColor
    };
    // legacy...
    if (arguments.length >= 3) ctx.depth = arguments[2];
    if (arguments.length >= 4) ctx.colors = arguments[3];
    if (isBoolean(opts)) {
      // legacy...
      ctx.showHidden = opts;
    } else if (opts) {
      // got an "options" object
      exports._extend(ctx, opts);
    }
    // set default options
    if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
    if (isUndefined(ctx.depth)) ctx.depth = 2;
    if (isUndefined(ctx.colors)) ctx.colors = false;
    if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
    if (ctx.colors) ctx.stylize = stylizeWithColor;
    return formatValue(ctx, obj, ctx.depth);
  }
  exports.inspect = inspect;
  
  
  // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  inspect.colors = {
    'bold' : [1, 22],
    'italic' : [3, 23],
    'underline' : [4, 24],
    'inverse' : [7, 27],
    'white' : [37, 39],
    'grey' : [90, 39],
    'black' : [30, 39],
    'blue' : [34, 39],
    'cyan' : [36, 39],
    'green' : [32, 39],
    'magenta' : [35, 39],
    'red' : [31, 39],
    'yellow' : [33, 39]
  };
  
  // Don't use 'blue' not visible on cmd.exe
  inspect.styles = {
    'special': 'cyan',
    'number': 'yellow',
    'boolean': 'yellow',
    'undefined': 'grey',
    'null': 'bold',
    'string': 'green',
    'date': 'magenta',
    // "name": intentionally not styling
    'regexp': 'red'
  };
  
  
  function stylizeWithColor(str, styleType) {
    var style = inspect.styles[styleType];
  
    if (style) {
      return '\u001b[' + inspect.colors[style][0] + 'm' + str +
             '\u001b[' + inspect.colors[style][1] + 'm';
    } else {
      return str;
    }
  }
  
  
  function stylizeNoColor(str, styleType) {
    return str;
  }
  
  
  function arrayToHash(array) {
    var hash = {};
  
    array.forEach(function(val, idx) {
      hash[val] = true;
    });
  
    return hash;
  }
  
  
  function formatValue(ctx, value, recurseTimes) {
    // Provide a hook for user-specified inspect functions.
    // Check that value is an object with an inspect function on it
    if (ctx.customInspect &&
        value &&
        isFunction(value.inspect) &&
        // Filter out the util module, it's inspect function is special
        value.inspect !== exports.inspect &&
        // Also filter out any prototype objects using the circular check.
        !(value.constructor && value.constructor.prototype === value)) {
      var ret = value.inspect(recurseTimes, ctx);
      if (!isString(ret)) {
        ret = formatValue(ctx, ret, recurseTimes);
      }
      return ret;
    }
  
    // Primitive types cannot have properties
    var primitive = formatPrimitive(ctx, value);
    if (primitive) {
      return primitive;
    }
  
    // Look up the keys of the object.
    var keys = Object.keys(value);
    var visibleKeys = arrayToHash(keys);
  
    if (ctx.showHidden) {
      keys = Object.getOwnPropertyNames(value);
    }
  
    // IE doesn't make error fields non-enumerable
    // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
    if (isError(value)
        && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
      return formatError(value);
    }
  
    // Some type of object without properties can be shortcutted.
    if (keys.length === 0) {
      if (isFunction(value)) {
        var name = value.name ? ': ' + value.name : '';
        return ctx.stylize('[Function' + name + ']', 'special');
      }
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      }
      if (isDate(value)) {
        return ctx.stylize(Date.prototype.toString.call(value), 'date');
      }
      if (isError(value)) {
        return formatError(value);
      }
    }
  
    var base = '', array = false, braces = ['{', '}'];
  
    // Make Array say that they are Array
    if (isArray(value)) {
      array = true;
      braces = ['[', ']'];
    }
  
    // Make functions say that they are functions
    if (isFunction(value)) {
      var n = value.name ? ': ' + value.name : '';
      base = ' [Function' + n + ']';
    }
  
    // Make RegExps say that they are RegExps
    if (isRegExp(value)) {
      base = ' ' + RegExp.prototype.toString.call(value);
    }
  
    // Make dates with properties first say the date
    if (isDate(value)) {
      base = ' ' + Date.prototype.toUTCString.call(value);
    }
  
    // Make error with message first say the error
    if (isError(value)) {
      base = ' ' + formatError(value);
    }
  
    if (keys.length === 0 && (!array || value.length == 0)) {
      return braces[0] + base + braces[1];
    }
  
    if (recurseTimes < 0) {
      if (isRegExp(value)) {
        return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
      } else {
        return ctx.stylize('[Object]', 'special');
      }
    }
  
    ctx.seen.push(value);
  
    var output;
    if (array) {
      output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
    } else {
      output = keys.map(function(key) {
        return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
      });
    }
  
    ctx.seen.pop();
  
    return reduceToSingleString(output, base, braces);
  }
  
  
  function formatPrimitive(ctx, value) {
    if (isUndefined(value))
      return ctx.stylize('undefined', 'undefined');
    if (isString(value)) {
      var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                               .replace(/'/g, "\\'")
                                               .replace(/\\"/g, '"') + '\'';
      return ctx.stylize(simple, 'string');
    }
    if (isNumber(value))
      return ctx.stylize('' + value, 'number');
    if (isBoolean(value))
      return ctx.stylize('' + value, 'boolean');
    // For some reason typeof null is "object", so special case here.
    if (isNull(value))
      return ctx.stylize('null', 'null');
  }
  
  
  function formatError(value) {
    return '[' + Error.prototype.toString.call(value) + ']';
  }
  
  
  function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
    var output = [];
    for (var i = 0, l = value.length; i < l; ++i) {
      if (hasOwnProperty(value, String(i))) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            String(i), true));
      } else {
        output.push('');
      }
    }
    keys.forEach(function(key) {
      if (!key.match(/^\d+$/)) {
        output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
            key, true));
      }
    });
    return output;
  }
  
  
  function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
    var name, str, desc;
    desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
    if (desc.get) {
      if (desc.set) {
        str = ctx.stylize('[Getter/Setter]', 'special');
      } else {
        str = ctx.stylize('[Getter]', 'special');
      }
    } else {
      if (desc.set) {
        str = ctx.stylize('[Setter]', 'special');
      }
    }
    if (!hasOwnProperty(visibleKeys, key)) {
      name = '[' + key + ']';
    }
    if (!str) {
      if (ctx.seen.indexOf(desc.value) < 0) {
        if (isNull(recurseTimes)) {
          str = formatValue(ctx, desc.value, null);
        } else {
          str = formatValue(ctx, desc.value, recurseTimes - 1);
        }
        if (str.indexOf('\n') > -1) {
          if (array) {
            str = str.split('\n').map(function(line) {
              return '  ' + line;
            }).join('\n').substr(2);
          } else {
            str = '\n' + str.split('\n').map(function(line) {
              return '   ' + line;
            }).join('\n');
          }
        }
      } else {
        str = ctx.stylize('[Circular]', 'special');
      }
    }
    if (isUndefined(name)) {
      if (array && key.match(/^\d+$/)) {
        return str;
      }
      name = JSON.stringify('' + key);
      if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
        name = name.substr(1, name.length - 2);
        name = ctx.stylize(name, 'name');
      } else {
        name = name.replace(/'/g, "\\'")
                   .replace(/\\"/g, '"')
                   .replace(/(^"|"$)/g, "'");
        name = ctx.stylize(name, 'string');
      }
    }
  
    return name + ': ' + str;
  }
  
  
  function reduceToSingleString(output, base, braces) {
    var numLinesEst = 0;
    var length = output.reduce(function(prev, cur) {
      numLinesEst++;
      if (cur.indexOf('\n') >= 0) numLinesEst++;
      return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
    }, 0);
  
    if (length > 60) {
      return braces[0] +
             (base === '' ? '' : base + '\n ') +
             ' ' +
             output.join(',\n  ') +
             ' ' +
             braces[1];
    }
  
    return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  }
  
  
  // NOTE: These type checking functions intentionally don't use `instanceof`
  // because it is fragile and can be easily faked with `Object.create()`.
  function isArray(ar) {
    return Array.isArray(ar);
  }
  exports.isArray = isArray;
  
  function isBoolean(arg) {
    return typeof arg === 'boolean';
  }
  exports.isBoolean = isBoolean;
  
  function isNull(arg) {
    return arg === null;
  }
  exports.isNull = isNull;
  
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  exports.isNullOrUndefined = isNullOrUndefined;
  
  function isNumber(arg) {
    return typeof arg === 'number';
  }
  exports.isNumber = isNumber;
  
  function isString(arg) {
    return typeof arg === 'string';
  }
  exports.isString = isString;
  
  function isSymbol(arg) {
    return typeof arg === 'symbol';
  }
  exports.isSymbol = isSymbol;
  
  function isUndefined(arg) {
    return arg === void 0;
  }
  exports.isUndefined = isUndefined;
  
  function isRegExp(re) {
    return isObject(re) && objectToString(re) === '[object RegExp]';
  }
  exports.isRegExp = isRegExp;
  
  function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  }
  exports.isObject = isObject;
  
  function isDate(d) {
    return isObject(d) && objectToString(d) === '[object Date]';
  }
  exports.isDate = isDate;
  
  function isError(e) {
    return isObject(e) &&
        (objectToString(e) === '[object Error]' || e instanceof Error);
  }
  exports.isError = isError;
  
  function isFunction(arg) {
    return typeof arg === 'function';
  }
  exports.isFunction = isFunction;
  
  function isPrimitive(arg) {
    return arg === null ||
           typeof arg === 'boolean' ||
           typeof arg === 'number' ||
           typeof arg === 'string' ||
           typeof arg === 'symbol' ||  // ES6 symbol
           typeof arg === 'undefined';
  }
  exports.isPrimitive = isPrimitive;
  
  exports.isBuffer = require('./support/isBuffer');
  
  function objectToString(o) {
    return Object.prototype.toString.call(o);
  }
  
  
  function pad(n) {
    return n < 10 ? '0' + n.toString(10) : n.toString(10);
  }
  
  
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                'Oct', 'Nov', 'Dec'];
  
  // 26 Feb 16:19:34
  function timestamp() {
    var d = new Date();
    var time = [pad(d.getHours()),
                pad(d.getMinutes()),
                pad(d.getSeconds())].join(':');
    return [d.getDate(), months[d.getMonth()], time].join(' ');
  }
  
  
  // log is just a thin wrapper to console.log that prepends a timestamp
  exports.log = function() {
    console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  };
  
  
  /**
   * Inherit the prototype methods from one constructor into another.
   *
   * The Function.prototype.inherits from lang.js rewritten as a standalone
   * function (not on Function.prototype). NOTE: If this file is to be loaded
   * during bootstrapping this function needs to be rewritten using some native
   * functions as prototype setup using normal JavaScript does not work as
   * expected during bootstrapping (see mirror.js in r114903).
   *
   * @param {function} ctor Constructor function which needs to inherit the
   *     prototype.
   * @param {function} superCtor Constructor function to inherit prototype from.
   */
  exports.inherits = require('inherits');
  
  exports._extend = function(origin, add) {
    // Don't do anything if add isn't an object
    if (!add || !isObject(add)) return origin;
  
    var keys = Object.keys(add);
    var i = keys.length;
    while (i--) {
      origin[keys[i]] = add[keys[i]];
    }
    return origin;
  };
  
  function hasOwnProperty(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  }
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"./support/isBuffer":80,"_process":20,"inherits":79}],82:[function(require,module,exports){
  var v1 = require('./v1');
  var v4 = require('./v4');
  
  var uuid = v4;
  uuid.v1 = v1;
  uuid.v4 = v4;
  
  module.exports = uuid;
  
  },{"./v1":85,"./v4":86}],83:[function(require,module,exports){
  /**
   * Convert array of 16 byte values to UUID string format of the form:
   * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
   */
  var byteToHex = [];
  for (var i = 0; i < 256; ++i) {
    byteToHex[i] = (i + 0x100).toString(16).substr(1);
  }
  
  function bytesToUuid(buf, offset) {
    var i = offset || 0;
    var bth = byteToHex;
    // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
    return ([bth[buf[i++]], bth[buf[i++]], 
  	bth[buf[i++]], bth[buf[i++]], '-',
  	bth[buf[i++]], bth[buf[i++]], '-',
  	bth[buf[i++]], bth[buf[i++]], '-',
  	bth[buf[i++]], bth[buf[i++]], '-',
  	bth[buf[i++]], bth[buf[i++]],
  	bth[buf[i++]], bth[buf[i++]],
  	bth[buf[i++]], bth[buf[i++]]]).join('');
  }
  
  module.exports = bytesToUuid;
  
  },{}],84:[function(require,module,exports){
  // Unique ID creation requires a high quality random # generator.  In the
  // browser this is a little complicated due to unknown quality of Math.random()
  // and inconsistent support for the `crypto` API.  We do the best we can via
  // feature-detection
  
  // getRandomValues needs to be invoked in a context where "this" is a Crypto
  // implementation. Also, find the complete implementation of crypto on IE11.
  var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
                        (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
  
  if (getRandomValues) {
    // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
    var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  
    module.exports = function whatwgRNG() {
      getRandomValues(rnds8);
      return rnds8;
    };
  } else {
    // Math.random()-based (RNG)
    //
    // If all else fails, use Math.random().  It's fast, but is of unspecified
    // quality.
    var rnds = new Array(16);
  
    module.exports = function mathRNG() {
      for (var i = 0, r; i < 16; i++) {
        if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
        rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
      }
  
      return rnds;
    };
  }
  
  },{}],85:[function(require,module,exports){
  var rng = require('./lib/rng');
  var bytesToUuid = require('./lib/bytesToUuid');
  
  // **`v1()` - Generate time-based UUID**
  //
  // Inspired by https://github.com/LiosK/UUID.js
  // and http://docs.python.org/library/uuid.html
  
  var _nodeId;
  var _clockseq;
  
  // Previous uuid creation time
  var _lastMSecs = 0;
  var _lastNSecs = 0;
  
  // See https://github.com/broofa/node-uuid for API details
  function v1(options, buf, offset) {
    var i = buf && offset || 0;
    var b = buf || [];
  
    options = options || {};
    var node = options.node || _nodeId;
    var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  
    // node and clockseq need to be initialized to random values if they're not
    // specified.  We do this lazily to minimize issues related to insufficient
    // system entropy.  See #189
    if (node == null || clockseq == null) {
      var seedBytes = rng();
      if (node == null) {
        // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
        node = _nodeId = [
          seedBytes[0] | 0x01,
          seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
        ];
      }
      if (clockseq == null) {
        // Per 4.2.2, randomize (14 bit) clockseq
        clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
      }
    }
  
    // UUID timestamps are 100 nano-second units since the Gregorian epoch,
    // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
    // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
    // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
    var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  
    // Per 4.2.1.2, use count of uuid's generated during the current clock
    // cycle to simulate higher resolution clock
    var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  
    // Time since last uuid creation (in msecs)
    var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  
    // Per 4.2.1.2, Bump clockseq on clock regression
    if (dt < 0 && options.clockseq === undefined) {
      clockseq = clockseq + 1 & 0x3fff;
    }
  
    // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
    // time interval
    if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
      nsecs = 0;
    }
  
    // Per 4.2.1.2 Throw error if too many uuids are requested
    if (nsecs >= 10000) {
      throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
    }
  
    _lastMSecs = msecs;
    _lastNSecs = nsecs;
    _clockseq = clockseq;
  
    // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
    msecs += 12219292800000;
  
    // `time_low`
    var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
    b[i++] = tl >>> 24 & 0xff;
    b[i++] = tl >>> 16 & 0xff;
    b[i++] = tl >>> 8 & 0xff;
    b[i++] = tl & 0xff;
  
    // `time_mid`
    var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
    b[i++] = tmh >>> 8 & 0xff;
    b[i++] = tmh & 0xff;
  
    // `time_high_and_version`
    b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
    b[i++] = tmh >>> 16 & 0xff;
  
    // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
    b[i++] = clockseq >>> 8 | 0x80;
  
    // `clock_seq_low`
    b[i++] = clockseq & 0xff;
  
    // `node`
    for (var n = 0; n < 6; ++n) {
      b[i + n] = node[n];
    }
  
    return buf ? buf : bytesToUuid(b);
  }
  
  module.exports = v1;
  
  },{"./lib/bytesToUuid":83,"./lib/rng":84}],86:[function(require,module,exports){
  var rng = require('./lib/rng');
  var bytesToUuid = require('./lib/bytesToUuid');
  
  function v4(options, buf, offset) {
    var i = buf && offset || 0;
  
    if (typeof(options) == 'string') {
      buf = options === 'binary' ? new Array(16) : null;
      options = null;
    }
    options = options || {};
  
    var rnds = options.random || (options.rng || rng)();
  
    // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
    rnds[6] = (rnds[6] & 0x0f) | 0x40;
    rnds[8] = (rnds[8] & 0x3f) | 0x80;
  
    // Copy bytes to buffer, if provided
    if (buf) {
      for (var ii = 0; ii < 16; ++ii) {
        buf[i + ii] = rnds[ii];
      }
    }
  
    return buf || bytesToUuid(rnds);
  }
  
  module.exports = v4;
  
  },{"./lib/bytesToUuid":83,"./lib/rng":84}],87:[function(require,module,exports){
  var assert = require('assert')
  
  var util = require('util')
  
  var bindAll = require('101/bind-all')
  var debug = require('debug')('primus-graphql:subscription-observable')
  var Observable = require('rxjs/Observable').Observable
  var parseErr = require('error-to-json').parse
  var Subscription = require('rxjs/Subscription').Subscription
  // add subscription.dispose operator
  require('../shared/subscription-dispose.js')
  
  module.exports = SubscriptionObservable
  
  function SubscriptionObservable (primus, resEE, data, primusOpts) {
    debug('SubscriptionObservable', data)
    Observable.call(this, this.__subscribe.bind(this))
    this._primus = primus
    this._resEE = resEE
    this._data = data
    this._key = primusOpts.key
    this._id = data[this._key].id
    // bind handlers
    bindAll(this, [
      '_onData',
      '_onReconnected'
    ])
  }
  
  // inherit from observable
  util.inherits(SubscriptionObservable, Observable)
  
  /**
   * subscribe to this observable
   * @private
   * @param  {SubscriptionObserver} observer
   * @return {DisposableSubscription} supports, both, unsubscribe() and dispose()
   */
  SubscriptionObservable.prototype.__subscribe = function (observer) {
    var self = this
    debug('subscribe')
    this._resEE.on(this._id, this._onData)
    this._primus.on('reconnected', this._onReconnected)
    this._observer = observer
    this._sendSubscription()
    return new Subscription(function () {
      // unsubscribe
      debug('unsubscribe')
      self._resEE.removeListener(self._id, self._onData)
      self._primus.removeListener('reconnected', self._onReconnected)
      self._sendUnsubscribe()
    })
  }
  
  /**
   * send subscription query to server
   * @private
   * @param  {Boolean} reconnect  if subscription is being sent for a reconnect
   */
  SubscriptionObservable.prototype._sendSubscription = function (reconnect) {
    var data = this._data
    debug('write', data)
    var writeSuccess = this._primus.write(data)
    if (!writeSuccess) {
      // Request failed
      var err = new Error('primus-graphql: write failed')
      this._observer.error(err)
    }
  }
  
  /**
   * send unsubscribe (dispose) to server
   * @private
   */
  SubscriptionObservable.prototype._sendUnsubscribe = function () {
    debug('_sendUnsubscribe')
    var data = {}
    data[this._key] = {
      id: this._id,
      event: 'unsubscribe'
    }
    this._primus.write(data)
  }
  
  /**
   * data handler, parse payload and apply to observer
   * @private
   * @param  {Object} payload  from server
   */
  SubscriptionObservable.prototype._onData = function (payload) {
    debug('_onData', payload)
    if (payload.event === 'next') {
      // next
      this._observer.next(payload.data)
    } else if (payload.event === 'error') {
      // error
      var errors = payload.errors.map(parseErr)
      var err = getErr(errors)
      this._observer.error(err)
    } else { // if (payload.event === 'completed') {
      assert(payload.event === 'completed', 'unknown event: ' + payload.event)
      // complete
      this._observer.complete()
    }
    function getErr (errors) {
      var err
      if (errors.length === 1) {
        err = errors[0]
        if (err.errors) {
          return getErr(err.errors.map(parseErr))
        }
      } else {
        err = new Error('multiple errors')
        err.errors = errors
      }
      return err
    }
  }
  
  /**
   * reconnect handler
   * @private
   */
  SubscriptionObservable.prototype._onReconnected = function () {
    this._sendSubscription(true)
  }
  
  },{"../shared/subscription-dispose.js":90,"101/bind-all":2,"assert":12,"debug":15,"error-to-json":17,"rxjs/Observable":23,"rxjs/Subscription":30,"util":81}],88:[function(require,module,exports){
  module.exports = {
    key: 'primus-graphql'
  }
  
  },{}],89:[function(require,module,exports){
  /*
    note: this is a partial script see "make build"
    the build is necessary to keep module.exports functional, but also bundle all dependencies into a single file
  */
  
  var assert = require('assert')
  var EventEmitter = require('events').EventEmitter
  
  var debug = require('debug')('primus-graphql:client')
  var defaults = require('101/defaults')
  var equals = require('101/equals')
  var isFunction = require('101/is-function')
  var maybe = require('call-me-maybe')
  var not = require('101/not')
  var parseErr = require('error-to-json').parse
  var uuid = require('uuid')
  
  var defaultPrimusOpts = require('./default-primus-opts.js')
  var SubscriptionObservable = require('./client/subscription-observable.js')
  // observable operators: used in relay-network-layer, but has to be bundled w/ client
  require('rxjs/add/operator/publish')
  require('observable-backoff')
  
  var notEquals = not(equals)
  var resEE = new EventEmitter()
  
  /* istanbul ignore next */
  primusOpts = primusOpts || {}
  defaults(primusOpts, defaultPrimusOpts)
  var key = primusOpts.key
  
  /**
   * @param  {String} query graphql query
   * @param  {Object} [vars]  graphql query args, optional
   * @param  {Object} [files]  graphql query files, optional
   * @param  {String} [operationName]  graphql operation name for advanced operations like batching
   * @param  {Object} [cb]  callback, optional
   * @return {Promise<Object,Error>|Observable|null}
   */
  primus.graphql = function (query, vars, files, operationName, cb) {
    debug('graphql', query, vars)
    if (isFunction(vars)) {
      cb = vars
      vars = undefined
      files = undefined
    }
    if (isFunction(files)) {
      cb = files
      files = undefined
    }
    if (isFunction(operationName)) {
      cb = operationName
      operationName = undefined
    }
    // parse query operation
    var end = Math.min.apply(Math, [query.indexOf(' '), query.indexOf('{')].filter(notEquals(-1)))
    var queryOperation = query.slice(0, end)
    // create payload
    var payload = {}
    payload.id = uuid.v4()
    payload.query = query
    payload.variables = vars
    payload.operationName = operationName
    if (files) {
      payload.files = files
    }
    // Setup data handler
    if (!~primus.listeners('data').indexOf(handleData)) {
      primus.on('data', handleData)
    }
    // Make request
    var data = {}
    data[key] = payload
    if (queryOperation === 'subscription') {
      // subscription returns an observable
      assert(!cb, 'cannot use callbacks for subscriptions (returns an observable)')
      return this._observeGraphQL(data)
    } else {
      // query, mutation, or malformatted
      var promise
      var err
      debug('write', data)
      var writeSuccess = primus.write(data)
      if (!writeSuccess) {
        // Request failed
        err = new Error('primus-graphql: write failed')
        return maybe(cb, Promise.reject(err))
      }
      // Response promise
      promise = new Promise(function (resolve, reject) {
        resEE.once(payload.id, resolve)
      })
      return maybe(cb, promise)
    }
  }
  
  primus._observeGraphQL = function (data) {
    debug('_observe', data)
    return new SubscriptionObservable(primus, resEE, data, primusOpts)
  }
  
  function handleData (res) {
    debug('handleData', res)
    var payload = res[key]
    if (payload) {
      if (payload.errors) {
        payload.errors = payload.errors.map(parseErr)
      }
      resEE.emit(payload.id, payload)
    }
  }
  
  },{"./client/subscription-observable.js":87,"./default-primus-opts.js":88,"101/defaults":3,"101/equals":4,"101/is-function":7,"101/not":11,"assert":12,"call-me-maybe":13,"debug":15,"error-to-json":17,"events":18,"observable-backoff":19,"rxjs/add/operator/publish":35,"uuid":82}],90:[function(require,module,exports){
  var Subscription = require('rxjs/Subscription').Subscription
  
  /**
   * alias for unsubscribe for disposable signature..
   */
  Subscription.prototype.dispose = function () {
    // added by primus-graphql
    return this.unsubscribe()
  }
  
  },{"rxjs/Subscription":30}]},{},[89]);
  
  };
    return Primus;
  },
  [
  
  ]);