Routes messages parsed with courier to defined handlers by `type`
@constructor
@param {object} socket
@param {object} options
423606
function Router(socket, options) {
  stream.Transform.call(this, { objectMode: true });

  this.options = merge(Object.create(Router.DEFAULTS), options || {});
  this.socket = socket;
}
431390
function Transport(location, callback) {
  if (false === (this instanceof Transport)) throw new Error('new operator required');
  if (typeof location != 'string') throw new Error('argument must a url string');
  if (typeof callback != 'function') throw new Error('argument must a callback');
  var self = this;
  self.connected = false;
  self.initialConnect = true;
  self.location = location;
  if (self.location === '') self.location = 'http host';
  self.socket = io.connect(location, {reconnection: false});
  self.socket.on('connect', function () {
    self.connected = true;
    self.initialConnect = false;
    console.log('socket.io (' + self.location + ') connected');
    callback.call(self, new Message('Connected', ''));
  });
  self.socket.on('connecting', function () {
    console.log('socket.io (' + self.location + ') connecting');
  });
  self.socket.on('error', function (reason) {
    var theError = 'general error with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('connect_error', function (reason) {
    var theError = 'connect error with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('connect_failed', function (reason) {
    var theError = 'connect failed with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('message', function (obj) {
    if (self.rawCallBack) {
      self.rawCallBack(obj);
    } else {
      console.log('socket.io (' + self.location + ') message: ' + obj);
    }
  });
  self.socket.on('disconnect', function (reason) {
    self.connected = false;
    console.log('socket.io (' + self.location + ') disconnect: ' + reason);
  });
}
237071
function defineRoute (server, opts) {

    server.route({
        method: 'GET',
        path: '/' + opts.plural,
        handler: handler,
        config: {
            jsonp: 'callback',
            validate: {
                query: {},
                payload: false
            }
        }
    });

    function handler (req) {
        var res = {};
        res[opts.plural] = opts.things;
        req.reply(res);
    }

}
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
395552
function handleMessage (peer, msg, callback) {
    // update the peer
    dht._add(peer, (err) => {
      if (err) {
        log.error('Failed to update the kbucket store')
        log.error(err)
      }

      // get handler & exectue it
      const handler = getMessageHandler(msg.type)

      if (!handler) {
        log.error(`no handler found for message type: ${msg.type}`)
        return callback()
      }

      handler(peer, msg, callback)
    })
  }
130892
function Message(options, body) {
  Stream.call(this);

  if (options || body)
    this.bind(options, body);

}
947311
function Router(options) {
  if ( !(this instanceof Router) ) {
    return new Router(options);
  }
  options = options || {};
  var self = this;
  this.routes = [];
  this.caseSensitive = options.caseSensitive;
  this.strict = options.strict;
  this.connect = connect();
  this.middleware = function (req, res, next){
    dispatch(self, req, res, next);
  };
  this.eventHandlers = {
    404 : function(req, res){
      res.writeHead(404);
      res.end('Not found');
    },
    405 : function(req, res, resource){
      res.setHeader('Allow', allowHeader(self, resource));
      res.writeHead(405);
      res.end('Not allowed');
    },
    'HEAD' : function(req, res, resource){
      if (!resource.GET){
        return self.eventHandlers[405](req, res, resource);
      }
      // node server suppresses the response output
      // on a HEAD response so we don't need to mute it like this:
      /*

      var origResWrite = res.write;
      var origResEnd = res.end;

      res.write = function(){
        origResWrite.apply(res, ['']);
      };
      res.end = function(){
        console.log("in muted end()");
        origResEnd.apply(res, ['']);
      };
      */
      // re-distpach as a GET
      req.method = "GET";
      return dispatch(self, req, res, function(){});
    },
    'OPTIONS' : function(req, res, resource){
      var header = allowHeader(self, resource);
      res.setHeader('Allow', header);
      res.writeHead(200);
      res.end('Allow: ' + header);
    }
  };
  // we never tackle 501, because the node server just drops requests
  // with invalid methods
}
376128
function Router() {
  var self = this;
  this.arr = [];
  this.caseSensitive = true;
  this.strict = false;

  this.middleware = function router(msg, next) {
    self._dispatch(msg, next);
  };
}
61415
function() {
    // choose from the sub-protocols
    if (typeof self.options.handleProtocols == 'function') {
      var protList = (protocols || '').split(/, */);
      var callbackCalled = false;
      self.options.handleProtocols(protList, function(result, protocol) {
        callbackCalled = true;
        if (!result) abortConnection(socket, 401, 'Unauthorized');
        else completeHybiUpgrade2(protocol);
      });
      if (!callbackCalled) {
        // the handleProtocols handler never called our callback
        abortConnection(socket, 501, 'Could not process protocols');
      }
      return;
    } else {
      if (typeof protocols !== 'undefined') {
        completeHybiUpgrade2(protocols.split(/, */)[0]);
      }
      else {
        completeHybiUpgrade2();
      }
    }
  }
765877
function Stream (options) {

  //check options
  if (!options) {

    throw new Error('Initialization error: missing transport options')
  }

  this._initDefaults() //Initialize default params
  this._updateParams(options)
  this._initTransport(options.transport)

  var self = this

  self.on('error', nop)

  this.subscriptions = []

  this.getSubscriptions = function () {

    return this.subscriptions
  }

  this.addSubscription = function (args, callback) {

    var c = new Subscription(args, callback, this)
    this.subscriptions[c.eid] = c
    return c
  }

  this.getSubscription = function (channel, resource) {

    if (this.subscriptions[channel + this.seperator + resource]) {
      return this.subscriptions[channel + this.seperator + resource]
    }
    return null
  }

  this.getAnySubscription = function (channel, resource) {

    if (this.subscriptions[channel + this.seperator + resource]) {
      return this.subscriptions[channel + this.seperator + resource]
    } else if (this.subscriptions[channel + this.seperator + this.wildcard]) {
      return this.subscriptions[channel + this.seperator + this.wildcard]
    } else {
      return null
    }
  }

  this.removeSubscription = function (channel, resource) {

    resource = resource || this.wildcard
    if (this.subscriptions[channel + this.seperator + resource]) {
      var retval = this.subscriptions[channel + this.seperator + resource]
      delete this.subscriptions[channel + this.seperator + resource]
      return retval
    }

    return null
  }

  this.getSubscriptionWithPermission = function (channel, resource, read, write) {

    var Subscription = this.subscriptions[channel + this.seperator + resource]
    var match = false

    if (Subscription) {

      match = true

      if (read) {
        match = Subscription.hasReadPermission()
      }

      if (write) {
        match = Subscription.hasWritePermission()
      }

      if (match) {
        return Subscription
      }
    } else {

      Subscription = this.subscriptions[channel + this.seperator + this.wildcard]

      if (Subscription) {

        match = true

        if (read) {
          match = Subscription.hasReadPermission()
        }

        if (write) {
          match = Subscription.hasWritePermission()
        }

        if (match) {
          return Subscription
        }
      }
    }

    return null
  }

  this.connection = new this.ConnectionFactory(this)
  this.connect()
}
1319873
function GhostRouter(options) {
    const router = express.Router(options);

    function innerRouter(req, res, next) {
        return innerRouter.handle(req, res, next);
    }

    Object.setPrototypeOf(innerRouter, router);

    Object.defineProperty(innerRouter, 'name', {
        value: options.parent.name,
        writable: false
    });

    innerRouter.parent = options.parent;
    return innerRouter;
}
390989
function (options) {
        W.extend(this, W.eventMixin);
        this.socketUrl = options.socketUrl;
        this._connectionDesired = false;
        this.attemptReconnectionAfterMS = (typeof options.attemptReconnectionAfterMS !== 'undefined') ? options.attemptReconnectionAfterMS : 10000;
    }
188118
function handleRoute(seneca, options, request, reply, route, next) {
  if (options.parseBody) {
    return ReadBody(request, finish)
  }
  finish(null, request.body || {})

  // Express requires a body parser to work in production
  // This util creates a body obj without neededing a parser
  // but doesn't impact loading one in.
  function finish(err, body) {
    if (err) {
      return next(err)
    }

    // This is what the seneca handler will get
    // Note! request$ and response$ will be stripped
    // if the message is sent over transport.
    const payload = {
      request$: request,
      response$: reply,
      args: {
        body: body,
        route: route,
        params: request.params,
        query: request.query,
        user: request.user || null
      }
    }

    // Call the seneca action specified in the config
    seneca.act(route.pattern, payload, (err, response) => {
      if (err) {
        return next(err)
      }

      // Redirect or reply depending on config.
      if (route.redirect) {
        return reply.redirect(route.redirect)
      }
      if (route.autoreply) {
        return reply.send(response)
      }
    })
  }
}
1040183
function Socket (type, opts) {

    opts = opts || {};
    this.af_domain = opts.raw ? nn.AF_SP_RAW : nn.AF_SP;
    this.type = type;

    switch(type) {
        case 'req':
            this.protocol = nn.NN_REQ;
            this.sender=true;
            this.receiver=true;
            break;

        case 'rep':
            this.protocol = nn.NN_REP;
            this.sender = true;
            this.receiver = true;
            break;

        case 'pair':
            this.protocol = nn.NN_PAIR;
            this.sender = true;
            this.receiver = true;
            break;

        case 'push':
            this.protocol = nn.NN_PUSH;
            this.sender = true;
            this.receiver = false;
            // nndontwait otherwise defaults true, PUSH socket default is false
            opts.dontwait = opts.dontwait || false;
            break;

        case 'pull':
            this.protocol = nn.NN_PULL;
            this.sender = false;
            this.receiver = true;
            break;

        case 'pub':
            this.protocol = nn.NN_PUB;
            this.sender = true;
            this.receiver = false;
            break;

        case 'sub':
            this.protocol = nn.NN_SUB;
            this.sender = false;
            this.receiver = true;
            break;

        case 'bus':
            this.protocol = nn.NN_BUS;
            this.sender = true;
            this.receiver = true;
            break;

        case 'surveyor':
            this.protocol = nn.NN_SURVEYOR;
            this.sender = true;
            this.receiver = false;
            break;

        case 'respondent':
            this.protocol = nn.NN_RESPONDENT;
            this.sender = true;
            this.receiver = true;
            break;

        default:
            throw new Error('unrecognised socket type ' + type);
            break;
    }

  this.binding = nn.Socket(this.af_domain, this.protocol);
  this.bound = {};
  this.connected = {};
  this.queue = [];

  /* async I/O option */
  this.dontwait('dontwait' in opts ? opts.dontwait : true);

  /*  subscription filter control */
  this.channels     = {};

  /*  subscription handling at initialization  */
  if (opts.hasOwnProperty('chan')) {
    if (Array.isArray(opts.chan)) {
      opts.chan.forEach(this._register.bind(this));
    } else {
      throw new TypeError('chan requires an Array');
    }
  } else if (type === 'sub') {
    this._register(''); //default topic is an empty string
  }

  /* sockopt api handling at initialization */
  for(var sokopt in sol){
    if(opts.hasOwnProperty(sokopt)) this[sokopt](opts[sokopt]);
  }

  /* start listening for inbound messages */
  if (this.af_domain === nn.AF_SP && this.receiver) {
    this._startPollReceive();
  }

  if (!opts.hasOwnProperty('objectMode')) {
    // reduce the highwatermark from 16K msgs to 16msgs
    // would be more useful if we have a backpressure mechanism
    opts.objectMode = true;
  }

  Duplex.call(this, opts);

}
589084
function handleConnection(self, options) {
	if (TRACE)	console.log('Connected to ' + options.host + ':' + options.port)
    	//self.socket = socket;
	self.emit("connect");
}
1307741
function Server(server, options)
{
	events.EventEmitter.call(this);
	
	this.listen = function(options, callback) {
		server.listen(options, callback);
	};
	
	server.on('connection', (socket) => {
		options = options || {};
		options.isServer = true;
		this.emit('client', new Client(socket, options));
	});
}
114187
function WebsocketBroker(options) {
  // Superclass Constructor
  EventEmitter.call(this);

  options = options || {};
  this.clientsPath = [];
  this.host = options.host || 'localhost';
  this.port = options.port || 8000;
  this.endpoints = options.endpoints || [];
  this.websocketEndpoints = {};

  this.wsServer = null;
  this.httpServer = null;
}