Primus is a universal wrapper for real-time frameworks that provides a common
interface for server and client interaction.

@constructor
@param {HTTP.Server} server HTTP or HTTPS server instance.
@param {Object} options Configuration
@api public
503360
function Primus(server, options) {
  if (!(this instanceof Primus)) return new Primus(server, options);

  this.fuse();

  if ('object' !== typeof server) {
    var message = 'The first argument of the constructor must be ' +
      'an HTTP or HTTPS server instance';
    throw new PrimusError(message, this);
  }

  options = options || {};
  options.maxLength = options.maxLength || 10485760;  // Maximum allowed packet size.
  options.transport = options.transport || {};        // Transformer specific options.
  options.pingInterval = 'pingInterval' in options    // Heartbeat interval.
    ? options.pingInterval
    : 30000;

  if ('timeout' in options) {
    throw new PrimusError('The `timeout` option has been removed', this);
  }

  var primus = this
    , key;

  this.auth = options.authorization || null;  // Do we have an authorization handler.
  this.connections = Object.create(null);     // Connection storage.
  this.ark = Object.create(null);             // Plugin storage.
  this.layers = [];                           // Middleware layers.
  this.heartbeatInterval = null;              // The heartbeat interval.
  this.transformer = null;                    // Reference to the real-time engine instance.
  this.encoder = null;                        // Shorthand to the parser's encoder.
  this.decoder = null;                        // Shorthand to the parser's decoder.
  this.connected = 0;                         // Connection counter.
  this.whitelist = [];                        // Forwarded-for white listing.
  this.options = options;                     // The configuration.
  this.transformers = {                       // Message transformers.
    outgoing: [],
    incoming: []
  };

  this.server = server;
  this.pathname = 'string' === typeof options.pathname
    ? options.pathname.charAt(0) !== '/'
      ? '/'+ options.pathname
      : options.pathname
    : '/primus';

  //
  // Create a specification file with the information that people might need to
  // connect to the server.
  //
  this.spec = {
    pingInterval: options.pingInterval,
    pathname: this.pathname,
    version: this.version
  };

  //
  // Create a pre-bound Spark constructor. Doing a Spark.bind(Spark, this) doesn't
  // work as we cannot extend the constructor of it anymore. The added benefit of
  // approach listed below is that the prototype extensions are only applied to
  // the Spark of this Primus instance.
  //
  this.Spark = function Sparky(headers, address, query, id, request, socket) {
    Spark.call(this, primus, headers, address, query, id, request, socket);
  };

  this.Spark.prototype = Object.create(Spark.prototype, {
    constructor: {
      configurable: true,
      value: this.Spark,
      writable: true
    },
    __initialise: {
      value: Spark.prototype.__initialise.slice(),
      configurable: true,
      writable: true
    }
  });

  //
  // Copy over the original Spark static properties and methods so readable and
  // writable can also be used.
  //
  for (key in Spark) {
    this.Spark[key] = Spark[key];
  }

  this.parsers(options.parser);
  this.initialise(options.transformer, options);

  //
  // If the plugins are supplied through the options, also initialise them.
  // This also allows us to use plugins when creating a client constructor
  // with the `Primus.createSocket({})` method.
  //
  if ('string' === typeof options.plugin) {
    options.plugin.split(/[, ]+/).forEach(function register(name) {
      primus.plugin(name, name);
    });
  } else if ('object' === typeof options.plugin) {
    for (key in options.plugin) {
      this.plugin(key, options.plugin[key]);
    }
  }

  //
  // - Cluster node 0.10 lets the Operating System decide to which worker a request
  //   goes. This can result in a not even distribution where some workers are
  //   used at 10% while others at 90%. In addition to that the load balancing
  //   isn't sticky.
  //
  // - Cluster node 0.12 implements a custom round robin algorithm. This solves the
  //   not even distribution of work but it does not address our sticky session
  //   requirement.
  //
  // Projects like `sticky-session` attempt to implement sticky sessions but they
  // are using `net` server instead of a HTTP server in combination with the
  // remoteAddress of the connection to load balance. This does not work when you
  // address your servers behind a load balancer as the IP is set to the load
  // balancer, not the connecting clients. All in all, it only causes more
  // scalability problems. So we've opted-in to warn users about the
  // risks of using Primus in a cluster.
  //
  if (!options.iknowclusterwillbreakconnections && require('cluster').isWorker) [
    '',
    'The `cluster` module does not implement sticky sessions. Learn more about',
    'this issue at:',
    '',
    'http://github.com/primus/primus#can-i-use-cluster',
    ''
  ].forEach(function warn(line) {
    console.error('Primus: '+ line);
  });
}
1211609
function initWebServer(settings) {

    let server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };
    adapter.subscribeForeignObjects('system.config');

    settings.ttl = parseInt(settings.ttl, 10) || 3600;
    if (!settings.whiteListEnabled && settings.whiteListSettings) delete settings.whiteListSettings;

    settings.defaultUser = settings.defaultUser || 'system.user.admin';
    if (!settings.defaultUser.match(/^system\.user\./)) settings.defaultUser = 'system.user.' + settings.defaultUser;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) {
                return null;
            }
        }
        server.app = express();

        server.app.disable('x-powered-by');
        // enable use of i-frames together with HTTPS
        server.app.get('/*', (req, res, next) => {
            res.header('X-Frame-Options' , 'SAMEORIGIN');
            next(); // http://expressjs.com/guide.html#passing-route control
        });

        if (settings.auth) {

            initAuth(server, settings);

            let autoLogonOrRedirectToLogin = (req, res, next, redirect) => {
                if (!settings.whiteListSettings) {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else
					if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
                        const parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						// if request for web/lib, ignore it, because no redirect information
						if (parts[0] === 'lib') return res.status(200).send('');
						return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
				adapter.log.silly('whiteListIp ' + whiteListIp);
                if (!whiteListIp || settings.whiteListSettings[whiteListIp].user === 'auth') {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
						let parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						if (parts[0] === 'lib') return res.status(200).send('');
                        return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
					return next(err);
                });
            };

            server.app.post('/login', (req, res, next) => {
                let redirect = '/';
                let parts;
                if (req.body.origin) {
                    parts = req.body.origin.split('=');
                    if (parts[1]) redirect = decodeURIComponent(parts[1]);
                }
                if (req.body && req.body.username && settings.addUserName && redirect.indexOf('?') === -1) {
                    parts = redirect.split('#');
                    parts[0] += '?' + req.body.username;
                    redirect = parts.join('#');
                }
                passport.authenticate('local', {
                    successRedirect: redirect,
                    failureRedirect: '/login/index.html' + req.body.origin + (req.body.origin ? '&error' : '?error'),
                    failureFlash: 'Invalid username or password.'
                })(req, res, next);
            });

            server.app.get('/logout', (req, res) => {
                req.logout();
                res.redirect('/login/index.html');
            });

            // route middleware to make sure a user is logged in
            server.app.use((req, res, next) => {
				// if cache.manifest got back not 200 it makes an error
                if (req.isAuthenticated() ||
                    /web\.\d+\/login-bg\.png(\?.*)?$/.test(req.originalUrl) ||
                    /cache\.manifest(\?.*)?$/.test(req.originalUrl) ||
                    /^\/login\//.test(req.originalUrl) ||
                    /\.ico(\?.*)?$/.test(req.originalUrl)
                ) {
                    return next();
                } else {
                    autoLogonOrRedirectToLogin(req, res, next, '/login/index.html?href=' + encodeURIComponent(req.originalUrl));
                }
            });
        } else {
            server.app.get('/login', (req, res) => {
                res.redirect('/');
            });
            server.app.get('/logout', (req, res) => {
                res.redirect('/');
            });

            if (settings.whiteListEnabled) {
                initAuth(server, settings);
                server.app.use((req, res, next) => {
                    let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                    let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
                    adapter.log.silly('whiteListIp ' + whiteListIp);
                    if (whiteListIp) {
                       req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
                            return next(err);
                        });
                    } else {
                        req.logIn(settings.defaultUser, err => {
                            return next(err);
                        });
                    }
                });
            }
        }

        // Init read from states
        server.app.get('/state/*', (req, res) => {
            try {
                const fileName = req.url.split('/', 3)[2].split('?', 2);
                adapter.getForeignObject(fileName[0], (err, obj) => {
                    let contentType = 'text/plain';
                    if (obj && obj.common.type === 'file')  {
                        contentType = mime.lookup(fileName[0]);
                    }
                    adapter.getBinaryState(fileName[0], {user: req.user ? 'system.user.' + req.user : settings.defaultUser}, (err, obj) => {
                        if (!err && obj !== null && obj !== undefined) {
                            if (obj && typeof obj === 'object' && obj.val !== undefined && obj.ack !== undefined) {
                                res.set('Content-Type', 'application/json');
                            } else {
                                res.set('Content-Type', contentType || 'text/plain');
                            }
                            res.status(200).send(obj);
                        } else {
                            res.status(404).send('404 Not found. File ' + fileName[0] + ' not found');
                        }
                    });
                });
            } catch (e) {
                res.status(500).send('500. Error' + e);
            }
        });

        server.app.get('*/_socket/info.js', (req, res) => {
            res.set('Content-Type', 'application/javascript');
            res.status(200).send(getInfoJs(settings));
        });

        // Enable CORS
        if (settings.socketio) {
            server.app.use((req, res, next) => {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

                // intercept OPTIONS method
                if ('OPTIONS' === req.method) {
                    res.status(200).send(200);
                } else {
                    next();
                }
            });
        }

        let appOptions = {};
        if (settings.cache) appOptions.maxAge = 30758400000;

        server.server = LE.createServer(server.app, settings, settings.certificates, settings.leConfig, adapter.log);
        server.server.__server = server;
    } else {
        adapter.log.error('port missing');
        adapter.terminate ? adapter.terminate(1): process.exit(1);
    }

    if (server.server) {
        settings.port = parseInt(settings.port, 10);
        adapter.getPort(settings.port, port => {
            port = parseInt(port, 10);
            if (port !== settings.port && !settings.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                adapter.terminate ? adapter.terminate(1): process.exit(1);
            }
            server.server.listen(port, (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined);
            adapter.log.info('http' + (settings.secure ? 's' : '') + ' server listening on port ' + port);
        });
    }

    // activate extensions
    for (let e in extensions) {
        if (!extensions.hasOwnProperty(e)) continue;
        try {
            // for debug purposes try to load file in current directory "/lib/file.js" (elsewise node.js cannot debug it)
            let parts = extensions[e].path.split('/');
            parts.shift();
            let extAPI;
            if (fs.existsSync(__dirname + '/' + parts.join('/'))) {
                extAPI = require(__dirname + '/' + parts.join('/'));
            } else {
                extAPI = require(utils.appName + '.' + extensions[e].path);
            }

            extensions[e].obj = new extAPI(server.server, {secure: settings.secure, port: settings.port}, adapter, extensions[e].config, server.app);
            adapter.log.info('Connect extension "' + extensions[e].path + '"');
        } catch (err) {
            adapter.log.error('Cannot start extension "' + e + '": ' + err);
        }
    }

    // Activate integrated simple API
    if (settings.simpleapi) {
        let SimpleAPI = require(utils.appName + '.simple-api/lib/simpleapi.js');

        server.api = new SimpleAPI(server.server, {secure: settings.secure, port: settings.port}, adapter);
    }

    // Activate integrated socket
    if (ownSocket) {
        let IOSocket = require(utils.appName + '.socketio/lib/socket.js');
        let socketSettings = JSON.parse(JSON.stringify(settings));
        // Authentication checked by server itself
        socketSettings.auth             = settings.auth;
        socketSettings.secret           = secret;
        socketSettings.store            = store;
        socketSettings.ttl              = settings.ttl || 3600;
        socketSettings.forceWebSockets  = settings.forceWebSockets || false;
        server.io = new IOSocket(server.server, socketSettings, adapter);
    }

    if (server.app) {
        // deliver web files from objectDB
        server.app.use('/', (req, res) => {

            let url = decodeURI(req.url);
            // remove all ../
            // important: Linux does not normalize "\" but fs.readFile accepts it as '/'
            url = path.normalize(url.replace(/\\/g, '/')).replace(/\\/g, '/');
            // remove '////' at start and let only one
            if (url[0] === '/' && url[1] === '/') {
                let i = 2;
                while (url[i] === '/') i++;
                url = url.substring(i - 1);
            }
            if ((url[0] === '.' && url[1] === '.') || (url[0] === '/' && url[1] === '.' && url[2] === '.')) {
                res.status(404).send('Not found');
                return;
            }

            if (server.api && server.api.checkRequest(url)) {
                server.api.restApi(req, res);
                return;
            }

            if (url === '/' || url === '/index.html') {
                getListOfAllAdapters((err, data) => {
                    if (err) {
                        res.status(500).send('500. Error' + e);
                    } else {
                        res
                            .set('Content-Type', 'text/html')
                            .status(200)
                            .send(data);
                    }
                });
                return;
            }

            // add index.html
            url = url.replace(/\/($|\?|#)/, '/index.html$1');

            if (url.match(/^\/adapter\//)) {
                // add .admin to adapter name
                url = url.replace(/^\/adapter\/([a-zA-Z0-9-_]+)\//, '/$1.admin/');
            }

            if (url.match(/^\/lib\//)) {
                url = '/' + adapter.name + url;
            }
            if (url.match(/^\/admin\//)) {
                url = '/' + adapter.name + url;
            }
            url = url.split('/');
            // Skip first /
            url.shift();
            // Get ID
            let id = url.shift();
            let versionPrefix = url[0];
            url = url.join('/');
            let pos = url.indexOf('?');
            let noFileCache;
            if (pos !== -1) {
                url = url.substring(0, pos);
                // disable file cache if request like /vis/files/picture.png?noCache
                noFileCache = true;
            }

            // get adapter name
            if (webByVersion[id]) {
                if (!versionPrefix || !versionPrefix.match(/^\d+\.\d+.\d+$/)) {
                    // redirect to version
                    res.set('location', '/' + id + '/' + webByVersion[id] + '/' + url);
                    res.status(301).send();
                    return;
                }
            }

            if (settings.cache && cache[id + '/' + url] && !noFileCache) {
                res.contentType(cache[id + '/' + url].mimeType);
                res.status(200).send(cache[id + '/' + url].buffer);
            } else {
                if (id === 'login' && url === 'index.html') {
                    loginPage = loginPage || prepareLoginTemplate();
                    let buffer = loginPage;

                    if (buffer === null || buffer === undefined) {
                        res.contentType('text/html');
                        res.status(200).send('File ' + url + ' not found', 404);
                    } else {
                        // Store file in cache
                        if (settings.cache) {
                            cache[id + '/' + url] = {buffer: buffer.toString(), mimeType: 'text/html'};
                        }
                        res.contentType('text/html');
                        res.status(200).send(buffer.toString());
                    }
                } else {
                    // special solution for socket.io
                    if (socketIoFile !== false && url.match(/\/socket\.io\.js(\?.*)?$/)) {
                        if (socketIoFile) {
                            res.contentType('text/javascript');
                            res.status(200).send(socketIoFile);
                            return
                        } else {
                            try {
                                const dir = require.resolve('socket.io-client');
                                const fileDir = path.join(path.dirname(dir), '../dist/');
                                if (fs.existsSync(fileDir + 'socket.io.min.js')) {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.min.js');
                                } else {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.js');
                                }
                            } catch (e) {
                                socketIoFile = false;
                            }
                            if (socketIoFile) {
                                res.contentType('text/javascript');
                                res.status(200).send(socketIoFile);
                                return
                            }
                        }
                    }
                    
                    adapter.readFile(id, webByVersion[id] ? url.substring(versionPrefix.length + 1) : url , {user: req.user ? 'system.user.' + req.user : settings.defaultUser, noFileCache: noFileCache}, (err, buffer, mimeType) => {
                        if (buffer === null || buffer === undefined || err) {
                            res.contentType('text/html');
                            res.status(404).send('File ' + url + ' not found: ' + err);
                        } else {
                            mimeType = mimeType || mime.lookup(url) || 'text/javascript';

                            // Store file in cache
                            if (settings.cache) {
                                cache[id + '/' + url] = {
                                    buffer: buffer,
                                    mimeType: mimeType
                                };
                            }

                            res.contentType(mimeType);
                            res.status(200).send(buffer);
                        }
                    });
                }
            }
        });
    }

    if (server.server) {
        return server;
    } else {
        return null;
    }
}
1370706
function Application(options) {
  var self = this;

  if (!(self instanceof Application)) {
    return new Application(options);
  }

  stream.Duplex.call(self, { objectMode: true });

  self.id = hat();
  self.server = net.createServer(self._handleInbound.bind(self));
  self.options = merge(Object.create(Application.DEFAULTS), options);
  self.connections = { inbound: [], outbound: [] };

  // setup middlware stack with initial entry a simple passthrough
  self.stack = [function(socket) {
    return through(function(data) {
      this.queue(data);
    });
  }];

  Object.defineProperty(self, 'log', {
    value: this.options.logger || {
      info: NOOP, warn: NOOP, error: NOOP
    }
  });

  // connect to seeds
  self._enterNetwork();
  setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
}
158629
function initServer (args) {
    // get server args
    var server = requireValidOptionalObject(args.server)
    // create module methods
    moduleMethods.forEach(methodName => {
        var method = server[methodName]
        // skip if no method in args
        if (!defined(method)) {
            return
        }
        // require function
        this.assert(typeof method === 'function', 110, `${methodName} method must be function`)
        // create module method
        this.module.method(methodName, method)
    })
}
910030
function createServer(options) {
    var opt = new Options(options || {});

    var app = express();
    // Import configuration
    for (var o in opt) {
	app.set(o, opt[o]);
    }
    // Default middleware
    app.use(express.favicon())
	.use(express.query())
	.use(express.bodyParser())
	.use(express.cookieParser())
	.use(express.session( {secret: opt.secret } ))
	.use(opt.static_mount, express.static(opt.static_dir))
    // Template engines
    app.engine('mustache', cons.hogan)
	.engine('mu', cons.hogan)
	.set('view engine', 'mustache')
	.set('views', opt.template_dir);
    // Custom middleware
    app.use(exports.logger(opt.separator))
	.use(set_cookie)
	.use(exports.multi_render(app))
	.use(exports.fun_router(app));
    
    // Specify default page
    if (opt.default_route)
	app.get('/', function(req, res) { res.redirect(opt.default_route); });

    // Create http server
    app.http_server = http.createServer(app);
    if (app.get('socket_io')) {
	app.io = require('socket.io').listen(app.http_server);
    }

    app.listen = function() {
	app.http_server.listen.apply(app.http_server, arguments);
    };

    app.start = startServer;
    
    return app;
}
497695
function( options ) {
  this.options = options;
  this.wpt = new WPT( this.options.wpt.server );

  this.data  = [];
  this.queue = new Queue();
}
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
548310
function HttpsConfig(options) {
    var httpsOptions = options && options.httpsOptions

    underscore.extend(this, HttpsConfig._DEFAULT)
    CommonConfig.call(this, options)
    this.httpsOptions = applyHttpsOptions.call(this, httpsOptions)
    this.type = serverTypes.HTTPS
}
1284243
function(options, callback) {

     //Validate port
     if(options.port == 80){
       throw "Invalid server port specified. Port 80 is reserved.";
     }

     // fire up the server
     RNHS.init(options, function() {

       // listen for new requests and retrieve appropriate response
       DeviceEventEmitter.addListener('reactNativeHttpServerResponse', function(request) {

         var success = true;

         var promise = new Promise(function(resolve, reject){
           callback(request, resolve);
         })
         .then(function(response){

           //Validate status code
           if(validStatusCodes.indexOf(response.status) === 0){
             success = false;
             throw "Invalid response status code specified in RNHttpServer options.";
           }

           //Set default MIME_TYPE
           if(response.type === null){
             response.type = "text/plain";
           }

           //Set default data field to zero length string
           if(response.data === null){
             response.data = "";
           }

           if(response.headers === null){
             response.headers = {};
           }

           if(success){
             RNHS.setResponse(request.url, response);
           }

         });

       });

     }, function(e){
       throw "Could not initialise server: " + e;
     });

   }
543478
function NetworkServer(server) {
  this.server = server;
  function connection(socket) {
    server.connection(socket, this);
  }
  this.on('connection', connection);
}
907113
function main(args) {
  process.on("uncaughtException", onUncaughtException)

  var opts  = getOpts.parse(args).opts

  var webServer = http.createServer(onRequest)

  utils.log("version: " + utils.VERSION)
  utils.log("server starting")
  webServer.listen(opts.port, function() {
    utils.log("server started on http://localhost:" + opts.port)
  })

  var config = {
    httpServer: webServer
  }

  var rserver = ragentsServer.createServer(config)
  rserver.start()
}
686600
function init(ctx) {
        var server = ctx.server;
        var deferred = Q.defer();

        server.register({register: require('bell')}, function (err) {

            if (err) {
                deferred.reject(err);
                return;
            }

            _.each(config.security.social, function (providerConfig, providerName) {
                var opts = _.extend({}, config.security.cookie, {
                    'cookie': 'bell-' + providerName,
                    'clientId': providerConfig.appId,
                    'clientSecret': providerConfig.appSecret,
                    'isSecure': config.useSSL,
                    'forceHttps': config.useSSL,
                    'provider': getProvider(providerName, providerConfig)
                });

                server.auth.strategy(providerName, 'bell', opts);
            });

            deferred.resolve();
        });

        return deferred.promise.then(function () {
            return Q.when(ctx);
        });
    }
819087
function server(options) {
  status = 'server.started'
  config = _.extend(defaultServerOptions, options)

  open(config.datafile)

  if (config.logToConsole)
    console.log("✔ log to stdout")

  // ws [
  var ServerMessageLog = {}
  var queueMessages = []
  var timer

  function flushMessages(n) {
    queueMessages = _.sortBy(queueMessages, 'time')
    var messages = queueMessages.slice(0, n)
    queueMessages = queueMessages.slice(n)
//    console.log(messages);
    _.each(messages, function (m) {
//      var filename = options.logpath+'/1.log'
//      logString(filename, m.text)
      logMessage(new Date(m.time), m.path, m.data, m.type == 'log' ? '' : m.type)
    })
  }

  console.log("✔ ws server listening on port %d", config.port)

  var wss = new WebSocketServer({port: config.port});

  wss.on('connection', function(ws) {
    ws.on('message', function(m) {
      var message = JSON.parse(m)
      queueMessages.push(message)
      if (queueMessages.length > config.queueMessagesMax)
        flushMessages(config.flushMessagesCount)

      if (timer)
        clearTimeout(timer)
      timer = setTimeout(function () {
        timer = null
        flushMessages(queueMessages.length)
      }, config.serverFlushTimeout)
    })
  })
  // ws ]
}
1248940
function Server(options, requestListener) {
  if (!(this instanceof Server)) {
    return new Server(options, requestListener);
  }
  
    if (typeof options === 'function') {
      requestListener = options;
      options = {};
    } else if (options == null || typeof options === 'object') {
      options = util._extend({}, options);
    }
  
    options = Object.assign({
      server: null,
      token: null,
      id: null,
    }, options);

  if (!isDefinedAndNonNull(options, 'server')) {
    throw new TypeError('\'server\' must be provided');
  }

  if (!isDefinedAndNonNull(options, 'token')) {
    throw new TypeError('A \'token\' string or function must be provided');
  }

  var self = this;

  this.listenUri = options.server;
  if (isDefinedAndNonNull(options, 'id')) {
    this.listenUri = listenUri + '&id=' + options.id;
  }

  this.pendingRequest = null;
  this.closeRequested = false;
  this.options = options;
  this.path = options.path;
  this.clients = [];

  if (requestListener) {
    this.on('request', requestListener);
  }
  this.timeout = 2 * 60 * 1000;
  this.keepAliveTimeout = 5000;
  this.on('requestchannel', function(channel) { requestChannelListener(self, channel) });

}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
1158712
function(server, opts) {
  EventEmitter.call(this);
  this.server = server;
  this.wsprocessor = new WSProcessor();
  this.tcpprocessor = new TCPProcessor(opts.closeMethod);
  this.id = 1;
  this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000;
  this.setNoDelay = opts.setNoDelay;

  if (!opts.ssl) {
    this.server.on('connection', this.newSocket.bind(this));
  } else {
    this.server.on('secureConnection', this.newSocket.bind(this));
    this.server.on('clientError', function(e, tlsSo) {
      logger.warn('an ssl error occured before handshake established: ', e);
      tlsSo.destroy();
    });
  }

  this.wsprocessor.on('connection', this.emit.bind(this, 'connection'));
  this.tcpprocessor.on('connection', this.emit.bind(this, 'connection'));

  this.state = ST_STARTED;
}
743348
function Client(opts) {
    if (!(this instanceof Client)) {
        return new Client(opts);
    }

    var options = {};

    // If single connection provided, array-ify it
    if (typeof opts === 'string') {
        options.hosts = [opts];
        opts = options;
    } else if (typeof opts === 'undefined') {
        opts = {};
    } else if (_.isArray(opts)) {
        options.hosts = opts;
        opts = options;
    }

    _.defaults(opts, {
        autodiscover: false,
        bufferBeforeError: 1000,
        disabled: false,
        hosts: null,
        reconnect: true,
        onNetError: function onNetError(err) { console.error(err); },
        queue: true,
        netTimeout: 500,
        backoffLimit: 10000,
        maxValueSize: 1048576
    });

    // Iterate over options, assign each to this object
    R.keys(opts).forEach(function(key) {
        this[key] = opts[key];
    }, this);

    if (this.queue) {
        this.buffer = new Immutable.List();
    }

    debug('Connect options', opts);
    this.connect();
}