Skip to content
Browse files

Removed connect; included with express/node_modules

  • Loading branch information...
1 parent d354b0b commit 331f4e45ba9572bf087ceb18e49de75aaecfd666 @bbyars committed
Showing with 0 additions and 3,451 deletions.
  1. +0 −5 server/bin/httpmock
  2. +0 −11 server/deps/connect/.npmignore
  3. +0 −24 server/deps/connect/LICENSE
  4. +0 −2 server/deps/connect/index.js
  5. +0 −106 server/deps/connect/lib/connect.js
  6. +0 −218 server/deps/connect/lib/http.js
  7. +0 −47 server/deps/connect/lib/https.js
  8. +0 −41 server/deps/connect/lib/index.js
  9. +0 −93 server/deps/connect/lib/middleware/basicAuth.js
  10. +0 −92 server/deps/connect/lib/middleware/bodyParser.js
  11. +0 −163 server/deps/connect/lib/middleware/compiler.js
  12. +0 −46 server/deps/connect/lib/middleware/cookieParser.js
  13. +0 −100 server/deps/connect/lib/middleware/errorHandler.js
  14. +0 −76 server/deps/connect/lib/middleware/favicon.js
  15. +0 −78 server/deps/connect/lib/middleware/limit.js
  16. +0 −169 server/deps/connect/lib/middleware/logger.js
  17. +0 −38 server/deps/connect/lib/middleware/methodOverride.js
  18. +0 −100 server/deps/connect/lib/middleware/profiler.js
  19. +0 −34 server/deps/connect/lib/middleware/responseTime.js
  20. +0 −379 server/deps/connect/lib/middleware/router.js
  21. +0 −345 server/deps/connect/lib/middleware/session.js
  22. +0 −126 server/deps/connect/lib/middleware/session/cookie.js
  23. +0 −131 server/deps/connect/lib/middleware/session/memory.js
  24. +0 −137 server/deps/connect/lib/middleware/session/session.js
  25. +0 −59 server/deps/connect/lib/middleware/session/store.js
  26. +0 −222 server/deps/connect/lib/middleware/static.js
  27. +0 −44 server/deps/connect/lib/middleware/vhost.js
  28. +0 −51 server/deps/connect/lib/patch.js
  29. +0 −13 server/deps/connect/lib/public/error.html
  30. BIN server/deps/connect/lib/public/favicon.ico
  31. +0 −61 server/deps/connect/lib/public/style.css
  32. +0 −405 server/deps/connect/lib/utils.js
  33. +0 −22 server/deps/connect/package.json
  34. +0 −13 server/deps/connect/test.js
View
5 server/bin/httpmock
@@ -48,11 +48,6 @@ var serverAt = function (options) {
var basedir = __dirname.replace(/\w+$/, '');
-// Needed to require express locally; e.g. it does a require('connect')
-['connect/lib', 'qs', 'mime'].forEach(function (path) {
- require.paths.unshift(basedir + '/deps/' + path);
-});
-
require.paths.push(basedir);
require.paths.push(basedir + '/lib');
require.paths.push(basedir + '/deps');
View
11 server/deps/connect/.npmignore
@@ -1,11 +0,0 @@
-*.markdown
-*.md
-.git*
-Makefile
-benchmarks/
-docs/
-examples/
-install.sh
-support/
-test/
-.DS_Store
View
24 server/deps/connect/LICENSE
@@ -1,24 +0,0 @@
-(The MIT License)
-
-Copyright (c) 2010 Sencha Inc.
-Copyright (c) 2011 LearnBoost
-Copyright (c) 2011 TJ Holowaychuk
-
-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.
View
2 server/deps/connect/index.js
@@ -1,2 +0,0 @@
-
-module.exports = require('./lib/connect');
View
106 server/deps/connect/lib/connect.js
@@ -1,106 +0,0 @@
-
-/*!
- * Connect
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var HTTPServer = require('./http').Server
- , HTTPSServer = require('./https').Server
- , fs = require('fs');
-
-// node patches
-
-require('./patch');
-
-// expose createServer() as the module
-
-exports = module.exports = createServer;
-
-/**
- * Framework version.
- */
-
-exports.version = '1.4.3';
-
-/**
- * Initialize a new `connect.HTTPServer` with the middleware
- * passed to this function. When an object is passed _first_,
- * we assume these are the tls options, and return a `connect.HTTPSServer`.
- *
- * Examples:
- *
- * An example HTTP server, accepting several middleware.
- *
- * var server = connect.createServer(
- * connect.logger()
- * , connect.static(__dirname + '/public')
- * );
- *
- * An HTTPS server, utilizing the same middleware as above.
- *
- * var server = connect.createServer(
- * { key: key, cert: cert }
- * , connect.logger()
- * , connect.static(__dirname + '/public')
- * );
- *
- * Alternatively with connect 1.0 we may omit `createServer()`.
- *
- * connect(
- * connect.logger()
- * , connect.static(__dirname + '/public')
- * ).listen(3000);
- *
- * @param {Object|Function} ...
- * @return {Server}
- * @api public
- */
-
-function createServer() {
- if ('object' == typeof arguments[0]) {
- return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1));
- } else {
- return new HTTPServer(Array.prototype.slice.call(arguments));
- }
-};
-
-// support connect.createServer()
-
-exports.createServer = createServer;
-
-// auto-load getters
-
-exports.middleware = {};
-
-/**
- * Auto-load bundled middleware with getters.
- */
-
-fs.readdirSync(__dirname + '/middleware').forEach(function(filename){
- if (/\.js$/.test(filename)) {
- var name = filename.substr(0, filename.lastIndexOf('.'));
- exports.middleware.__defineGetter__(name, function(){
- return require('./middleware/' + name);
- });
- }
-});
-
-// expose utils
-
-exports.utils = require('./utils');
-
-// expose getters as first-class exports
-
-exports.utils.merge(exports, exports.middleware);
-
-// expose constructors
-
-exports.HTTPServer = HTTPServer;
-exports.HTTPSServer = HTTPSServer;
-
View
218 server/deps/connect/lib/http.js
@@ -1,218 +0,0 @@
-
-/*!
- * Connect - HTTPServer
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var http = require('http')
- , parse = require('url').parse
- , assert = require('assert');
-
-// environment
-
-var env = process.env.NODE_ENV || 'development';
-
-/**
- * Initialize a new `Server` with the given `middleware`.
- *
- * Examples:
- *
- * var server = connect.createServer(
- * connect.favicon()
- * , connect.logger()
- * , connect.static(__dirname + '/public')
- * );
- *
- * @params {Array} middleware
- * @return {Server}
- * @api public
- */
-
-var Server = exports.Server = function HTTPServer(middleware) {
- this.stack = [];
- middleware.forEach(function(fn){
- this.use(fn);
- }, this);
- http.Server.call(this, this.handle);
-};
-
-/**
- * Inherit from `http.Server.prototype`.
- */
-
-Server.prototype.__proto__ = http.Server.prototype;
-
-/**
- * Utilize the given middleware `handle` to the given `route`,
- * defaulting to _/_. This "route" is the mount-point for the
- * middleware, when given a value other than _/_ the middleware
- * is only effective when that segment is present in the request's
- * pathname.
- *
- * For example if we were to mount a function at _/admin_, it would
- * be invoked on _/admin_, and _/admin/settings_, however it would
- * not be invoked for _/_, or _/posts_.
- *
- * This is effectively the same as passing middleware to `connect.createServer()`,
- * however provides a progressive api.
- *
- * Examples:
- *
- * var server = connect.createServer();
- * server.use(connect.favicon());
- * server.use(connect.logger());
- * server.use(connect.static(__dirname + '/public'));
- *
- * If we wanted to prefix static files with _/public_, we could
- * "mount" the `static()` middleware:
- *
- * server.use('/public', connect.static(__dirname + '/public'));
- *
- * This api is chainable, meaning the following is valid:
- *
- * connect.createServer()
- * .use(connect.favicon())
- * .use(connect.logger())
- * .use(connect.static(__dirname + '/public'))
- * .listen(3000);
- *
- * @param {String|Function} route or handle
- * @param {Function} handle
- * @return {Server}
- * @api public
- */
-
-Server.prototype.use = function(route, handle){
- this.route = '/';
-
- // default route to '/'
- if ('string' != typeof route) {
- handle = route;
- route = '/';
- }
-
- // multiples
- if (arguments.length > 2) {
- return Array.prototype.slice.call(arguments, 1).forEach(function(fn){
- this.use(route, fn);
- }, this);
- }
-
- // wrap sub-apps
- if ('function' == typeof handle.handle) {
- var server = handle;
- server.route = route;
- handle = function(req, res, next) {
- server.handle(req, res, next);
- };
- }
-
- // wrap vanilla http.Servers
- if (handle instanceof http.Server) {
- handle = handle.listeners('request')[0];
- }
-
- // normalize route to not trail with slash
- if ('/' == route[route.length - 1]) {
- route = route.substr(0, route.length - 1);
- }
-
- // add the middleware
- this.stack.push({ route: route, handle: handle });
-
- // allow chaining
- return this;
-};
-
-/**
- * Handle server requests, punting them down
- * the middleware stack.
- *
- * @api private
- */
-
-Server.prototype.handle = function(req, res, out) {
- var writeHead = res.writeHead
- , stack = this.stack
- , removed = ''
- , index = 0;
-
- function next(err) {
- req.url = removed + req.url;
- req.originalUrl = req.originalUrl || req.url;
- removed = '';
-
- var layer = stack[index++];
-
- // all done
- if (!layer) {
- // but wait! we have a parent
- if (out) return out(err);
-
- // otherwise send a proper error message to the browser.
- if (err) {
- var msg = 'production' == env
- ? 'Internal Server Error'
- : err.stack || err.toString();
-
- // output to stderr in a non-test env
- if ('test' != env) console.error(err.stack || err.toString());
-
- res.statusCode = 500;
- res.setHeader('Content-Type', 'text/plain');
- res.end(msg);
- } else {
- res.statusCode = 404;
- res.setHeader('Content-Type', 'text/plain');
- res.end('Cannot ' + req.method + ' ' + req.url);
- }
- return;
- }
-
- try {
- var pathname = parse(req.url).pathname;
- if (undefined == pathname) pathname = '/';
-
- // skip this layer if the route doesn't match.
- if (0 != pathname.indexOf(layer.route)) return next(err);
-
- var nextChar = pathname[layer.route.length];
- if (nextChar && '/' != nextChar && '.' != nextChar) return next(err);
-
- // Call the layer handler
- // Trim off the part of the url that matches the route
- removed = layer.route;
- req.url = req.url.substr(removed.length);
-
- // Ensure leading slash
- if ('/' != req.url[0]) req.url = '/' + req.url;
-
- var arity = layer.handle.length;
- if (err) {
- if (arity === 4) {
- layer.handle(err, req, res, next);
- } else {
- next(err);
- }
- } else if (arity < 4) {
- layer.handle(req, res, next);
- } else {
- next();
- }
- } catch (e) {
- if (e instanceof assert.AssertionError) {
- console.error(e.stack + '\n');
- next(e);
- } else {
- next(e);
- }
- }
- }
- next();
-};
View
47 server/deps/connect/lib/https.js
@@ -1,47 +0,0 @@
-
-/*!
- * Connect - HTTPServer
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var HTTPServer = require('./http').Server
- , https = require('https');
-
-/**
- * Initialize a new `Server` with the given
- *`options` and `middleware`. The HTTPS api
- * is identical to the [HTTP](http.html) server,
- * however TLS `options` must be provided before
- * passing in the optional middleware.
- *
- * @params {Object} options
- * @params {Array} middleawre
- * @return {Server}
- * @api public
- */
-
-var Server = exports.Server = function HTTPSServer(options, middleware) {
- this.stack = [];
- middleware.forEach(function(fn){
- this.use(fn);
- }, this);
- https.Server.call(this, options, this.handle);
-};
-
-/**
- * Inherit from `http.Server.prototype`.
- */
-
-Server.prototype.__proto__ = https.Server.prototype;
-
-// mixin HTTPServer methods
-
-Object.keys(HTTPServer.prototype).forEach(function(method){
- Server.prototype[method] = HTTPServer.prototype[method];
-});
View
41 server/deps/connect/lib/index.js
@@ -1,41 +0,0 @@
-
-/**
- * # Connect
- *
- * Connect is a middleware framework for node,
- * shipping with over 11 bundled middleware and a rich choice of
- * [3rd-party middleware](https://github.com/senchalabs/connect/wiki).
- *
- * Installation:
- *
- * $ npm install connect
- *
- * API:
- *
- * - [connect](connect.html) general
- * - [http](http.html) http server
- * - [https](https.html) https server
- *
- * Middleware:
- *
- * - [logger](middleware-logger.html) request logger with custom format support
- * - [basicAuth](middleware-basicAuth.html) basic http authentication
- * - [bodyParser](middleware-bodyParser.html) extensible request body parser
- * - [cookieParser](middleware-cookieParser.html) cookie parser
- * - [session](middleware-session.html) session management support with bundled [MemoryStore](middleware-session-memory.html)
- * - [compiler](middleware-compiler.html) static asset compiler (sass, less, coffee-script, etc)
- * - [methodOverride](middleware-methodOverride.html) faux HTTP method support
- * - [responseTime](middleware-responseTime.html) calculates response-time and exposes via X-Response-Time
- * - [router](middleware-router.html) provides rich Sinatra / Express-like routing
- * - [static](middleware-static.html) streaming static file server supporting `Range` and more
- * - [vhost](middleware-vhost.html) virtual host sub-domain mapping middleware
- * - [favicon](middleware-favicon.html) efficient favicon server (with default icon)
- * - [limit](middleware-limit.html) limit the bytesize of request bodies
- * - [profiler](middleware-profiler.html) request profiler reporting response-time, memory usage, etc
- *
- * Internals:
- *
- * - connect [utilities](utils.html)
- * - node monkey [patches](patch.html)
- *
- */
View
93 server/deps/connect/lib/middleware/basicAuth.js
@@ -1,93 +0,0 @@
-
-/*!
- * Connect - basicAuth
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('../utils')
- , unauthorized = utils.unauthorized
- , badRequest = utils.badRequest;
-
-/**
- * Enfore basic authentication by providing a `callback(user, pass)`,
- * which must return `true` in order to gain access. Alternatively an async
- * method is provided as well, invoking `callback(user, pass, callback)`. Populates
- * `req.remoteUser`. The final alternative is simply passing username / password
- * strings.
- *
- * Examples:
- *
- * connect(connect.basicAuth('username', 'password'));
- *
- * connect(
- * connect.basicAuth(function(user, pass){
- * return 'tj' == user & 'wahoo' == pass;
- * })
- * );
- *
- * connect(
- * connect.basicAuth(function(user, pass, fn){
- * User.authenticate({ user: user, pass: pass }, fn);
- * })
- * );
- *
- * @param {Function|String} callback or username
- * @param {String} realm
- * @api public
- */
-
-module.exports = function basicAuth(callback, realm) {
- var username, password;
-
- // user / pass strings
- if ('string' == typeof callback) {
- username = callback;
- password = realm;
- if ('string' != typeof password) throw new Error('password argument required');
- realm = arguments[2];
- callback = function(user, pass){
- return user == username && pass == password;
- }
- }
-
- realm = realm || 'Authorization Required';
-
- return function(req, res, next) {
- var authorization = req.headers.authorization;
-
- if (req.remoteUser) return next();
- if (!authorization) return unauthorized(res, realm);
-
- var parts = authorization.split(' ')
- , scheme = parts[0]
- , credentials = new Buffer(parts[1], 'base64').toString().split(':');
-
- if ('Basic' != scheme) return badRequest(res);
-
- // async
- if (callback.length >= 3) {
- var pause = utils.pause(req);
- callback(credentials[0], credentials[1], function(err, user){
- if (err || !user) return unauthorized(res, realm);
- req.remoteUser = user;
- next();
- pause.resume();
- });
- // sync
- } else {
- if (callback(credentials[0], credentials[1])) {
- req.remoteUser = credentials[0];
- next();
- } else {
- unauthorized(res, realm);
- }
- }
- }
-};
-
View
92 server/deps/connect/lib/middleware/bodyParser.js
@@ -1,92 +0,0 @@
-
-/*!
- * Connect - bodyParser
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var qs = require('qs');
-
-/**
- * Extract the mime type from the given request's
- * _Content-Type_ header.
- *
- * @param {IncomingMessage} req
- * @return {String}
- * @api private
- */
-
-function mime(req) {
- var str = req.headers['content-type'] || '';
- return str.split(';')[0];
-}
-
-/**
- * Parse request bodies.
- *
- * By default _application/json_ and _application/x-www-form-urlencoded_
- * are supported, however you may map `connect.bodyParser.parse[contentType]`
- * to a function of your choice to replace existing parsers, or implement
- * one for other content-types.
- *
- * Examples:
- *
- * connect.createServer(
- * connect.bodyParser()
- * , function(req, res) {
- * res.end('viewing user ' + req.body.user.name);
- * }
- * );
- *
- * Since both _json_ and _x-www-form-urlencoded_ are supported by
- * default, either of the following requests would result in the response
- * of "viewing user tj".
- *
- * $ curl -d 'user[name]=tj' http://localhost/
- * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://localhost/
- *
- * @return {Function}
- * @api public
- */
-
-exports = module.exports = function bodyParser(){
- return function bodyParser(req, res, next) {
- if ('GET' == req.method || 'HEAD' == req.method) return next();
- var parser = exports.parse[mime(req)];
- if (parser && !req.body) {
- var data = '';
- req.setEncoding('utf8');
- req.on('data', function(chunk) { data += chunk; });
- req.on('end', function(){
- req.rawBody = data;
- try {
- req.body = data
- ? parser(data)
- : {};
- } catch (err) {
- return next(err);
- }
- next();
- });
- } else {
- next();
- }
- }
-};
-
-/**
- * Supported decoders.
- *
- * - application/x-www-form-urlencoded
- * - application/json
- */
-
-exports.parse = {
- 'application/x-www-form-urlencoded': qs.parse
- , 'application/json': JSON.parse
-};
View
163 server/deps/connect/lib/middleware/compiler.js
@@ -1,163 +0,0 @@
-
-/*!
- * Connect - compiler
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var fs = require('fs')
- , path = require('path')
- , parse = require('url').parse;
-
-/**
- * Require cache.
- */
-
-var cache = {};
-
-/**
- * Setup compiler.
- *
- * Options:
- *
- * - `src` Source directory, defaults to **CWD**.
- * - `dest` Destination directory, defaults `src`.
- * - `enable` Array of enabled compilers.
- *
- * Compilers:
- *
- * - `sass` Compiles cass to css
- * - `less` Compiles less to css
- * - `coffeescript` Compiles coffee to js
- *
- * @param {Object} options
- * @api public
- */
-
-exports = module.exports = function compiler(options){
- options = options || {};
-
- var srcDir = options.src || process.cwd()
- , destDir = options.dest || srcDir
- , enable = options.enable;
-
- if (!enable || enable.length === 0) {
- throw new Error('compiler\'s "enable" option is not set, nothing will be compiled.');
- }
-
- return function compiler(req, res, next){
- if ('GET' != req.method) return next();
- var pathname = parse(req.url).pathname;
- for (var i = 0, len = enable.length; i < len; ++i) {
- var name = enable[i]
- , compiler = compilers[name];
- if (compiler.match.test(pathname)) {
- var src = (srcDir + pathname).replace(compiler.match, compiler.ext)
- , dest = destDir + pathname;
-
- // Compare mtimes
- fs.stat(src, function(err, srcStats){
- if (err) {
- if ('ENOENT' == err.code) {
- next();
- } else {
- next(err);
- }
- } else {
- fs.stat(dest, function(err, destStats){
- if (err) {
- // Oh snap! it does not exist, compile it
- if ('ENOENT' == err.code) {
- compile();
- } else {
- next(err);
- }
- } else {
- // Source has changed, compile it
- if (srcStats.mtime > destStats.mtime) {
- compile();
- } else {
- // Defer file serving
- next();
- }
- }
- });
- }
- });
-
- // Compile to the destination
- function compile() {
- fs.readFile(src, 'utf8', function(err, str){
- if (err) {
- next(err);
- } else {
- compiler.compile(str, function(err, str){
- if (err) {
- next(err);
- } else {
- fs.writeFile(dest, str, 'utf8', function(err){
- next(err);
- });
- }
- });
- }
- });
- }
- return;
- }
- }
- next();
- };
-};
-
-/**
- * Bundled compilers:
- *
- * - [sass](http://github.com/visionmedia/sass.js) to _css_
- * - [less](http://github.com/cloudhead/less.js) to _css_
- * - [coffee](http://github.com/jashkenas/coffee-script) to _js_
- */
-
-var compilers = exports.compilers = {
- sass: {
- match: /\.css$/,
- ext: '.sass',
- compile: function(str, fn){
- var sass = cache.sass || (cache.sass = require('sass'));
- try {
- fn(null, sass.render(str));
- } catch (err) {
- fn(err);
- }
- }
- },
- less: {
- match: /\.css$/,
- ext: '.less',
- compile: function(str, fn){
- var less = cache.less || (cache.less = require('less'));
- try {
- less.render(str, fn);
- } catch (err) {
- fn(err);
- }
- }
- },
- coffeescript: {
- match: /\.js$/,
- ext: '.coffee',
- compile: function(str, fn){
- var coffee = cache.coffee || (cache.coffee = require('coffee-script'));
- try {
- fn(null, coffee.compile(str));
- } catch (err) {
- fn(err);
- }
- }
- }
-};
View
46 server/deps/connect/lib/middleware/cookieParser.js
@@ -1,46 +0,0 @@
-
-/*!
- * Connect - cookieParser
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('./../utils');
-
-/**
- * Parse _Cookie_ header and populate `req.cookies`
- * with an object keyed by the cookie names.
- *
- * Examples:
- *
- * connect.createServer(
- * connect.cookieParser()
- * , function(req, res, next){
- * res.end(JSON.stringify(req.cookies));
- * }
- * );
- *
- * @return {Function}
- * @api public
- */
-
-module.exports = function cookieParser(){
- return function cookieParser(req, res, next) {
- var cookie = req.headers.cookie;
- if (req.cookies) return next();
- req.cookies = {};
- if (cookie) {
- try {
- req.cookies = utils.parseCookie(cookie);
- } catch (err) {
- return next(err);
- }
- }
- next();
- };
-};
View
100 server/deps/connect/lib/middleware/errorHandler.js
@@ -1,100 +0,0 @@
-/*!
- * Connect - errorHandler
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('../utils')
- , url = require('url')
- , fs = require('fs');
-
-/**
- * Flexible error handler, providing (_optional_) stack traces
- * and error message responses for requests accepting text, html,
- * or json.
- *
- * Options:
- *
- * - `showStack`, `stack` respond with both the error message and stack trace. Defaults to `false`
- * - `showMessage`, `message`, respond with the exception message only. Defaults to `false`
- * - `dumpExceptions`, `dump`, dump exceptions to stderr (without terminating the process). Defaults to `false`
- *
- * Text:
- *
- * By default, and when _text/plain_ is accepted a simple stack trace
- * or error message will be returned.
- *
- * JSON:
- *
- * When _application/json_ is accepted, connect will respond with
- * an object in the form of `{ "error": error }`.
- *
- * HTML:
- *
- * When accepted connect will output a nice html stack trace.
- *
- * @param {Object} options
- * @return {Function}
- * @api public
- */
-
-exports = module.exports = function errorHandler(options){
- options = options || {};
-
- // defaults
- var showStack = options.showStack || options.stack
- , showMessage = options.showMessage || options.message
- , dumpExceptions = options.dumpExceptions || options.dump
- , formatUrl = options.formatUrl;
-
- return function errorHandler(err, req, res, next){
- res.statusCode = 500;
- if (dumpExceptions) console.error(err.stack);
- if (showStack) {
- var accept = req.headers.accept || '';
- // html
- if (~accept.indexOf('html')) {
- fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){
- fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){
- var stack = (err.stack || '')
- .split('\n').slice(1)
- .map(function(v){ return '<li>' + v + '</li>'; }).join('');
- html = html
- .replace('{style}', style)
- .replace('{stack}', stack)
- .replace('{title}', exports.title)
- .replace(/\{error\}/g, utils.escape(err.toString()));
- res.setHeader('Content-Type', 'text/html');
- res.end(html);
- });
- });
- // json
- } else if (~accept.indexOf('json')) {
- var json = JSON.stringify({ error: err });
- res.setHeader('Content-Type', 'application/json');
- res.end(json);
- // plain text
- } else {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end(err.stack);
- }
- } else {
- var body = showMessage
- ? err.toString()
- : 'Internal Server Error';
- res.setHeader('Content-Type', 'text/plain');
- res.end(body);
- }
- };
-};
-
-/**
- * Template title.
- */
-
-exports.title = 'Connect';
View
76 server/deps/connect/lib/middleware/favicon.js
@@ -1,76 +0,0 @@
-
-/*!
- * Connect - favicon
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var fs = require('fs')
- , utils = require('../utils');
-
-/**
- * Favicon cache.
- */
-
-var icon;
-
-/**
- * By default serves the connect favicon, or the favicon
- * located by the given `path`.
- *
- * Options:
- *
- * - `maxAge` cache-control max-age directive, defaulting to 1 day
- *
- * Examples:
- *
- * connect.createServer(
- * connect.favicon()
- * );
- *
- * connect.createServer(
- * connect.favicon(__dirname + '/public/favicon.ico')
- * );
- *
- * @param {String} path
- * @param {Object} options
- * @return {Function}
- * @api public
- */
-
-module.exports = function favicon(path, options){
- var options = options || {}
- , path = path || __dirname + '/../public/favicon.ico'
- , maxAge = options.maxAge || 86400000;
-
- return function favicon(req, res, next){
- if ('/favicon.ico' == req.url) {
- if (icon) {
- res.writeHead(200, icon.headers);
- res.end(icon.body);
- } else {
- fs.readFile(path, function(err, buf){
- if (err) return next(err);
- icon = {
- headers: {
- 'Content-Type': 'image/x-icon'
- , 'Content-Length': buf.length
- , 'ETag': '"' + utils.md5(buf) + '"'
- , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)
- },
- body: buf
- };
- res.writeHead(200, icon.headers);
- res.end(icon.body);
- });
- }
- } else {
- next();
- }
- };
-};
View
78 server/deps/connect/lib/middleware/limit.js
@@ -1,78 +0,0 @@
-
-/*!
- * Connect - limit
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Limit request bodies to the given size in `bytes`.
- *
- * A string representation of the bytesize may also be passed,
- * for example "5mb", "200kb", "1gb", etc.
- *
- * Examples:
- *
- * var server = connect(
- * connect.limit('5.5mb')
- * ).listen(3000);
- *
- * TODO: pause EV_READ
- *
- * @param {Number|String} bytes
- * @return {Function}
- * @api public
- */
-
-module.exports = function limit(bytes){
- if ('string' == typeof bytes) bytes = parse(bytes);
- if ('number' != typeof bytes) throw new Error('limit() bytes required');
- return function limit(req, res, next){
- var received = 0
- , len = req.headers['content-length']
- ? parseInt(req.headers['content-length'], 10)
- : null;
-
- // deny the request
- function deny() {
- req.destroy();
- }
-
- // self-awareness
- if (req._limit) return next();
- req._limit = true;
-
- // limit by content-length
- if (len && len > bytes) deny();
-
- // limit
- req.on('data', function(chunk){
- received += chunk.length;
- if (received > bytes) deny();
- });
-
- next();
- };
-};
-
-/**
- * Parse byte `size` string.
- *
- * @param {String} size
- * @return {Number}
- * @api private
- */
-
-function parse(size) {
- var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/)
- , n = parseFloat(parts[1])
- , type = parts[2];
-
- var map = {
- kb: 1024
- , mb: 1024 * 1024
- , gb: 1024 * 1024 * 1024
- };
-
- return map[type] * n;
-}
View
169 server/deps/connect/lib/middleware/logger.js
@@ -1,169 +0,0 @@
-
-/*!
- * Connect - logger
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Log buffer.
- */
-
-var buf = [];
-
-/**
- * Default log buffer duration.
- */
-
-var defaultBufferDuration = 1000;
-
-/**
- * Log requests with the given `options` or a `format` string.
- *
- * Options:
- *
- * - `format` Format string, see below for tokens
- * - `stream` Output stream, defaults to _stdout_
- * - `buffer` Buffer duration, defaults to 1000ms when _true_
- *
- * Tokens:
- *
- * - `:req[header]` ex: `:req[Accept]`
- * - `:res[header]` ex: `:res[Content-Length]`
- * - `:http-version`
- * - `:response-time`
- * - `:remote-addr`
- * - `:date`
- * - `:method`
- * - `:url`
- * - `:referrer`
- * - `:user-agent`
- * - `:status`
- *
- * @param {String|Function|Object} format or options
- * @return {Function}
- * @api public
- */
-
-module.exports = function logger(options) {
- if ('object' == typeof options) {
- options = options || {};
- } else if (options) {
- options = { format: options };
- } else {
- options = {};
- }
-
- var fmt = options.format
- , stream = options.stream || process.stdout
- , buffer = options.buffer;
-
- // buffering support
- if (buffer) {
- var realStream = stream
- , interval = 'number' == typeof buffer
- ? buffer
- : defaultBufferDuration;
-
- // flush interval
- setInterval(function(){
- if (buf.length) {
- realStream.write(buf.join(''), 'ascii');
- buf.length = 0;
- }
- }, interval);
-
- // swap the stream
- stream = {
- write: function(str){
- buf.push(str);
- }
- };
- }
-
- return function logger(req, res, next) {
- var start = +new Date
- , statusCode
- , writeHead = res.writeHead
- , end = res.end
- , url = req.originalUrl;
-
- // mount safety
- if (req._logging) return next();
-
- // flag as logging
- req._logging = true;
-
- // proxy for statusCode.
- res.writeHead = function(code, headers){
- res.writeHead = writeHead;
- res.writeHead(code, headers);
- res.__statusCode = statusCode = code;
- res.__headers = headers || {};
- };
-
- // proxy end to output a line to the provided logger.
- if (fmt) {
- res.end = function(chunk, encoding) {
- res.end = end;
- res.end(chunk, encoding);
- res.responseTime = +new Date - start;
- if ('function' == typeof fmt) {
- var line = fmt(req, res, function(str){ return format(str, req, res); });
- if (line) stream.write(line + '\n', 'ascii');
- } else {
- stream.write(format(fmt, req, res) + '\n', 'ascii');
- }
- };
- } else {
- res.end = function(chunk, encoding) {
- var contentLength = (res._headers && res._headers['content-length'])
- || (res.__headers && res.__headers['Content-Length'])
- || '-';
-
- res.end = end;
- res.end(chunk, encoding);
-
- stream.write((req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress)))
- + ' - - [' + (new Date).toUTCString() + ']'
- + ' "' + req.method + ' ' + url
- + ' HTTP/' + req.httpVersionMajor + '.' + req.httpVersionMinor + '" '
- + (statusCode || res.statusCode) + ' ' + contentLength
- + ' "' + (req.headers['referer'] || req.headers['referrer'] || '')
- + '" "' + (req.headers['user-agent'] || '') + '"\n', 'ascii');
- };
- }
-
- next();
- };
-};
-
-/**
- * Return formatted log line.
- *
- * @param {String} str
- * @param {IncomingMessage} req
- * @param {ServerResponse} res
- * @return {String}
- * @api private
- */
-
-function format(str, req, res) {
- return str
- .replace(':url', req.originalUrl)
- .replace(':method', req.method)
- .replace(':status', res.__statusCode || res.statusCode)
- .replace(':response-time', res.responseTime)
- .replace(':date', new Date().toUTCString())
- .replace(':referrer', req.headers['referer'] || req.headers['referrer'] || '')
- .replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor)
- .replace(':remote-addr', req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress)))
- .replace(':user-agent', req.headers['user-agent'] || '')
- .replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; })
- .replace(/:res\[([^\]]+)\]/g, function(_, field){
- return res._headers
- ? (res._headers[field.toLowerCase()] || res.__headers[field])
- : (res.__headers && res.__headers[field]);
- });
-}
View
38 server/deps/connect/lib/middleware/methodOverride.js
@@ -1,38 +0,0 @@
-
-/*!
- * Connect - methodOverride
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Provides faux HTTP method support.
- *
- * Pass an optional `key` to use when checking for
- * a method override, othewise defaults to _\_method_.
- * The original method is available via `req.originalMethod`.
- *
- * @param {String} key
- * @return {Function}
- * @api public
- */
-
-module.exports = function methodOverride(key){
- key = key || "_method";
- return function methodOverride(req, res, next) {
- req.originalMethod = req.originalMethod || req.method;
-
- // req.body
- if (req.body && key in req.body) {
- req.method = req.body[key].toUpperCase();
- delete req.body[key];
- // check X-HTTP-Method-Override
- } else if (req.headers['x-http-method-override']) {
- req.method = req.headers['x-http-method-override'].toUpperCase();
- }
-
- next();
- };
-};
-
View
100 server/deps/connect/lib/middleware/profiler.js
@@ -1,100 +0,0 @@
-
-/*!
- * Connect - profiler
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Profile the duration of a request.
- *
- * Typically this middleware should be utilized
- * _above_ all others, as it proxies the `res.end()`
- * method, being first allows it to encapsulate all
- * other middleware.
- *
- * Example Output:
- *
- * GET /
- * response time 2ms
- * memory rss 52.00kb
- * memory vsize 2.07mb
- * heap before 3.76mb / 8.15mb
- * heap after 3.80mb / 8.15mb
- *
- * @api public
- */
-
-module.exports = function profiler(){
- return function(req, res, next){
- var end = res.end
- , start = snapshot();
-
- // state snapshot
- function snapshot() {
- return {
- mem: process.memoryUsage()
- , time: new Date
- };
- }
-
- // proxy res.end()
- res.end = function(data, encoding){
- res.end = end;
- res.end(data, encoding);
- compare(req, start, snapshot())
- };
-
- next();
- }
-};
-
-/**
- * Compare `start` / `end` snapshots.
- *
- * @param {IncomingRequest} req
- * @param {Object} start
- * @param {Object} end
- * @api private
- */
-
-function compare(req, start, end) {
- console.log();
- row(req.method, req.url);
- row('response time:', (end.time - start.time) + 'ms');
- row('memory rss:', formatBytes(end.mem.rss - start.mem.rss));
- row('memory vsize:', formatBytes(end.mem.vsize - start.mem.vsize));
- row('heap before:', formatBytes(start.mem.heapUsed) + ' / ' + formatBytes(start.mem.heapTotal));
- row('heap after:', formatBytes(end.mem.heapUsed) + ' / ' + formatBytes(end.mem.heapTotal));
- console.log();
-}
-
-/**
- * Row helper
- *
- * @param {String} key
- * @param {String} val
- * @api private
- */
-
-function row(key, val) {
- console.log(' \033[90m%s\033[0m \033[36m%s\033[0m', key, val);
-}
-
-/**
- * Format byte-size.
- *
- * @param {Number} bytes
- * @return {String}
- * @api private
- */
-
-function formatBytes(bytes) {
- var kb = 1024
- , mb = 1024 * kb
- , gb = 1024 * mb;
- if (bytes < kb) return bytes + 'b';
- if (bytes < mb) return (bytes / kb).toFixed(2) + 'kb';
- if (bytes < gb) return (bytes / mb).toFixed(2) + 'mb';
- return (bytes / gb).toFixed(2) + 'gb';
-};
View
34 server/deps/connect/lib/middleware/responseTime.js
@@ -1,34 +0,0 @@
-
-/*!
- * Connect - responseTime
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Adds the `X-Response-Time` header displaying the response
- * duration in milliseconds.
- *
- * @return {Function}
- * @api public
- */
-
-module.exports = function responseTime(){
- return function(req, res, next){
- var writeHead = res.writeHead
- , start = new Date;
-
- if (res._responseTime) return next();
- res._responseTime = true;
-
- // proxy writeHead to calculate duration
- res.writeHead = function(status, headers){
- var duration = new Date - start;
- res.setHeader('X-Response-Time', duration + 'ms');
- res.writeHead = writeHead;
- res.writeHead(status, headers);
- };
-
- next();
- };
-};
View
379 server/deps/connect/lib/middleware/router.js
@@ -1,379 +0,0 @@
-
-/*!
- * Connect - router
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('../utils')
- , parse = require('url').parse;
-
-/**
- * Expose router.
- */
-
-exports = module.exports = router;
-
-/**
- * Supported HTTP / WebDAV methods.
- */
-
-var _methods = exports.methods = [
- 'get'
- , 'post'
- , 'put'
- , 'delete'
- , 'connect'
- , 'options'
- , 'trace'
- , 'copy'
- , 'lock'
- , 'mkcol'
- , 'move'
- , 'propfind'
- , 'proppatch'
- , 'unlock'
- , 'report'
- , 'mkactivity'
- , 'checkout'
- , 'merge'
-];
-
-/**
- * Provides Sinatra and Express-like routing capabilities.
- *
- * Examples:
- *
- * connect.router(function(app){
- * app.get('/user/:id', function(req, res, next){
- * // populates req.params.id
- * });
- * app.put('/user/:id', function(req, res, next){
- * // populates req.params.id
- * });
- * })
- *
- * @param {Function} fn
- * @return {Function}
- * @api public
- */
-
-function router(fn){
- var self = this
- , methods = {}
- , routes = {}
- , params = {};
-
- if (!fn) throw new Error('router provider requires a callback function');
-
- // Generate method functions
- _methods.forEach(function(method){
- methods[method] = generateMethodFunction(method.toUpperCase());
- });
-
- // Alias del -> delete
- methods.del = methods.delete;
-
- // Apply callback to all methods
- methods.all = function(){
- var args = arguments;
- _methods.forEach(function(name){
- methods[name].apply(this, args);
- });
- return self;
- };
-
- // Register param callback
- methods.param = function(name, fn){
- params[name] = fn;
- };
-
- fn.call(this, methods);
-
- function generateMethodFunction(name) {
- var localRoutes = routes[name] = routes[name] || [];
- return function(path, fn){
- var keys = []
- , middleware = [];
-
- // slice middleware
- if (arguments.length > 2) {
- middleware = Array.prototype.slice.call(arguments, 1, arguments.length);
- fn = middleware.pop();
- middleware = utils.flatten(middleware);
- }
-
- fn.middleware = middleware;
-
- if (!path) throw new Error(name + ' route requires a path');
- if (!fn) throw new Error(name + ' route ' + path + ' requires a callback');
- var regexp = path instanceof RegExp
- ? path
- : normalizePath(path, keys);
- localRoutes.push({
- fn: fn
- , path: regexp
- , keys: keys
- , orig: path
- , method: name
- });
- return self;
- };
- }
-
- function router(req, res, next){
- var route
- , self = this;
-
- (function pass(i){
- if (route = match(req, routes, i)) {
- var i = 0
- , keys = route.keys;
-
- req.params = route.params;
-
- // Param preconditions
- (function param(err) {
- try {
- var key = keys[i++]
- , val = req.params[key]
- , fn = params[key];
-
- if ('route' == err) {
- pass(req._route_index + 1);
- // Error
- } else if (err) {
- next(err);
- // Param has callback
- } else if (fn) {
- // Return style
- if (1 == fn.length) {
- req.params[key] = fn(val);
- param();
- // Middleware style
- } else {
- fn(req, res, param, val);
- }
- // Finished processing params
- } else if (!key) {
- // route middleware
- i = 0;
- (function nextMiddleware(err){
- var fn = route.middleware[i++];
- if ('route' == err) {
- pass(req._route_index + 1);
- } else if (err) {
- next(err);
- } else if (fn) {
- fn(req, res, nextMiddleware);
- } else {
- route.call(self, req, res, function(err){
- if (err) {
- next(err);
- } else {
- pass(req._route_index + 1);
- }
- });
- }
- })();
- // More params
- } else {
- param();
- }
- } catch (err) {
- next(err);
- }
- })();
- } else if ('OPTIONS' == req.method) {
- options(req, res, routes);
- } else {
- next();
- }
- })();
- };
-
- router.remove = function(path, method){
- var fns = router.lookup(path, method);
- fns.forEach(function(fn){
- routes[fn.method].splice(fn.index, 1);
- });
- };
-
- router.lookup = function(path, method, ret){
- ret = ret || [];
-
- // method specific lookup
- if (method) {
- method = method.toUpperCase();
- if (routes[method]) {
- routes[method].forEach(function(route, i){
- if (path == route.orig) {
- var fn = route.fn;
- fn.regexp = route.path;
- fn.keys = route.keys;
- fn.path = route.orig;
- fn.method = route.method;
- fn.index = i;
- ret.push(fn);
- }
- });
- }
- // global lookup
- } else {
- _methods.forEach(function(method){
- router.lookup(path, method, ret);
- });
- }
-
- return ret;
- };
-
- router.match = function(url, method, ret){
- var ret = ret || []
- , i = 0
- , fn
- , req;
-
- // method specific matches
- if (method) {
- method = method.toUpperCase();
- req = { url: url, method: method };
- while (fn = match(req, routes, i)) {
- i = req._route_index + 1;
- ret.push(fn);
- }
- // global matches
- } else {
- _methods.forEach(function(method){
- router.match(url, method, ret);
- });
- }
-
- return ret;
- };
-
- return router;
-}
-
-/**
- * Respond to OPTIONS.
- *
- * @param {ServerRequest} req
- * @param {ServerResponse} req
- * @param {Array} routes
- * @api private
- */
-
-function options(req, res, routes) {
- var pathname = parse(req.url).pathname
- , body = optionsFor(pathname, routes).join(',');
- res.writeHead(200, {
- 'Content-Length': body.length
- , 'Allow': body
- });
- res.end(body);
-}
-
-/**
- * Return OPTIONS array for the given `path`, matching `routes`.
- *
- * @param {String} path
- * @param {Array} routes
- * @return {Array}
- * @api private
- */
-
-function optionsFor(path, routes) {
- return _methods.filter(function(method){
- var arr = routes[method.toUpperCase()];
- for (var i = 0, len = arr.length; i < len; ++i) {
- if (arr[i].path.test(path)) return true;
- }
- }).map(function(method){
- return method.toUpperCase();
- });
-}
-
-/**
- * Normalize the given path string,
- * returning a regular expression.
- *
- * An empty array should be passed,
- * which will contain the placeholder
- * key names. For example "/user/:id" will
- * then contain ["id"].
- *
- * @param {String} path
- * @param {Array} keys
- * @return {RegExp}
- * @api private
- */
-
-function normalizePath(path, keys) {
- path = path
- .concat('/?')
- .replace(/\/\(/g, '(?:/')
- .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){
- keys.push(key);
- slash = slash || '';
- return ''
- + (optional ? '' : slash)
- + '(?:'
- + (optional ? slash : '')
- + (format || '') + (capture || '([^/]+?)') + ')'
- + (optional || '');
- })
- .replace(/([\/.])/g, '\\$1')
- .replace(/\*/g, '(.+)');
- return new RegExp('^' + path + '$', 'i');
-}
-
-/**
- * Attempt to match the given request to
- * one of the routes. When successful
- * a route function is returned.
- *
- * @param {ServerRequest} req
- * @param {Object} routes
- * @return {Function}
- * @api private
- */
-
-function match(req, routes, i) {
- var captures
- , method = req.method
- , i = i || 0;
- if ('HEAD' == method) method = 'GET';
- if (routes = routes[method]) {
- var url = parse(req.url)
- , pathname = url.pathname;
- for (var len = routes.length; i < len; ++i) {
- var route = routes[i]
- , fn = route.fn
- , path = route.path
- , keys = fn.keys = route.keys;
- if (captures = path.exec(pathname)) {
- fn.method = method;
- fn.params = [];
- for (var j = 1, len = captures.length; j < len; ++j) {
- var key = keys[j-1],
- val = typeof captures[j] === 'string'
- ? decodeURIComponent(captures[j])
- : captures[j];
- if (key) {
- fn.params[key] = val;
- } else {
- fn.params.push(val);
- }
- }
- req._route_index = i;
- return fn;
- }
- }
- }
-}
View
345 server/deps/connect/lib/middleware/session.js
@@ -1,345 +0,0 @@
-
-/*!
- * Connect - session
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var Session = require('./session/session')
- , MemoryStore = require('./session/memory')
- , Cookie = require('./session/cookie')
- , Store = require('./session/store')
- , utils = require('./../utils')
- , parse = require('url').parse
- , crypto = require('crypto');
-
-// environment
-
-var env = process.env.NODE_ENV;
-
-/**
- * Expose the middleware.
- */
-
-exports = module.exports = session;
-
-/**
- * Expose constructors.
- */
-
-exports.Store = Store;
-exports.Cookie = Cookie;
-exports.Session = Session;
-exports.MemoryStore = MemoryStore;
-
-/**
- * Warning message for `MemoryStore` usage in production.
- */
-
-var warning = 'Warning: connection.session() MemoryStore is not\n'
- + 'designed for a production environment, as it will leak\n'
- + 'memory, and obviously only work within a single process.';
-
-/**
- * Default finger-printing function.
- */
-
-function defaultFingerprint(req) {
- return req.headers['user-agent'] || '';
-};
-
-/**
- * Paths to ignore, defaulting to `/favicon.ico`.
- */
-
-exports.ignore = ['/favicon.ico'];
-
-/**
- * Setup session store with the given `options`.
- *
- * Session data is _not_ saved in the cookie itself, however
- * cookies are used, so we must use the [cookieParser()](middleware-cookieParser.html)
- * middleware _before_ `session()`.
- *
- * Examples:
- *
- * connect.createServer(
- * connect.cookieParser()
- * , connect.session({ secret: 'keyboard cat' })
- * );
- *
- * Options:
- *
- * - `key` cookie name defaulting to `connect.sid`
- * - `store` Session store instance
- * - `fingerprint` Custom fingerprint generating function
- * - `cookie` Session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: 14400000 }`
- * - `secret` Secret string used to compute hash
- *
- * Ignore Paths:
- *
- * By default `/favicon.ico` is the only ignored path, all others
- * will utilize sessions, to manipulate the paths ignored, use
- * `connect.session.ignore.push('/my/path')`. This works for _full_
- * pathnames only, not segments nor substrings.
- *
- * connect.session.ignore.push('/robots.txt');
- *
- * ## req.session
- *
- * To store or access session data, simply use the request property `req.session`,
- * which is (generally) serialized as JSON by the store, so nested objects
- * are typically fine. For example below is a user-specific view counter:
- *
- * connect(
- * connect.cookieParser()
- * , connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})
- * , connect.favicon()
- * , function(req, res, next){
- * var sess = req.session;
- * if (sess.views) {
- * res.setHeader('Content-Type', 'text/html');
- * res.write('<p>views: ' + sess.views + '</p>');
- * res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
- * res.end();
- * sess.views++;
- * } else {
- * sess.views = 1;
- * res.end('welcome to the session demo. refresh!');
- * }
- * }
- * ).listen(3000);
- *
- * ## Session#regenerate()
- *
- * To regenerate the session simply invoke the method, once complete
- * a new SID and `Session` instance will be initialized at `req.session`.
- *
- * req.session.regenerate(function(err){
- * // will have a new session here
- * });
- *
- * ## Session#destroy()
- *
- * Destroys the session, removing `req.session`, will be re-generated next request.
- *
- * req.session.destroy(function(err){
- * // cannot access session here
- * });
- *
- * ## Session#reload()
- *
- * Reloads the session data.
- *
- * req.session.reload(function(err){
- * // session updated
- * });
- *
- * ## Session#save()
- *
- * Save the session.
- *
- * req.session.save(function(err){
- * // session saved
- * });
- *
- * ## Session#touch()
- *
- * Updates the `.maxAge`, and `.lastAccess` properties. Typically this is
- * not necessary to call, as the session middleware does this for you.
- *
- * ## Session#cookie
- *
- * Each session has a unique cookie object accompany it. This allows
- * you to alter the session cookie per visitor. For example we can
- * set `req.session.cookie.expires` to `false` to enable the cookie
- * to remain for only the duration of the user-agent.
- *
- * ## Session#maxAge
- *
- * Alternatively `req.session.cookie.maxAge` will return the time
- * remaining in milliseconds, which we may also re-assign a new value
- * to adjust the `.expires` property appropriately. The following
- * are essentially equivalent
- *
- * var hour = 3600000;
- * req.session.cookie.expires = new Date(Date.now() + hour);
- * req.session.cookie.maxAge = hour;
- *
- * For example when `maxAge` is set to `60000` (one minute), and 30 seconds
- * has elapsed it will return `30000` until the current request has completed,
- * at which time `req.session.touch()` is called to update `req.session.lastAccess`,
- * and reset `req.session.maxAge` to its original value.
- *
- * req.session.cookie.maxAge;
- * // => 30000
- *
- * Session Store Implementation:
- *
- * Every session store _must_ implement the following methods
- *
- * - `.get(sid, callback)`
- * - `.set(sid, session, callback)`
- * - `.destroy(sid, callback)`
- *
- * Recommended methods include, but are not limited to:
- *
- * - `.length(callback)`
- * - `.clear(callback)`
- *
- * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo.
- *
- * @param {Object} options
- * @return {Function}
- * @api public
- */
-
-function session(options){
- var options = options || {}
- , key = options.key || 'connect.sid'
- , secret = options.secret
- , store = options.store || new MemoryStore
- , fingerprint = options.fingerprint || defaultFingerprint
- , cookie = options.cookie;
-
- // notify user that this store is not
- // meant for a production environment
- if ('production' == env && store instanceof MemoryStore) {
- console.warn(warning);
- }
-
- // ensure secret is present
- if (!secret) {
- throw new Error('connect.session({ secret: "string" }) required for security');
- }
-
- // session hashing function
- store.hash = function(req, base) {
- return crypto
- .createHmac('sha256', secret)
- .update(base + fingerprint(req))
- .digest('base64')
- .replace(/=*$/, '');
- };
-
- // generates the new session
- store.generate = function(req){
- var base = utils.uid(24);
- var sessionID = base + '.' + store.hash(req, base);
- req.sessionID = sessionID;
- req.session = new Session(req);
- req.session.cookie = new Cookie(cookie);
- };
-
- return function session(req, res, next) {
- // self-awareness
- if (req.session) return next();
-
- // parse url
- var url = parse(req.url)
- , path = url.pathname;
-
- // ignorable paths
- if (~exports.ignore.indexOf(path)) return next();
-
- // expose store
- req.sessionStore = store;
-
- // proxy writeHead() to Set-Cookie
- var writeHead = res.writeHead;
- res.writeHead = function(status, headers){
- if (req.session) {
- var cookie = req.session.cookie;
- // only send secure session cookies when there is a secure connection.
- // proxySecure is a custom attribute to allow for a reverse proxy
- // to handle SSL connections and to communicate to connect over HTTP that
- // the incoming connection is secure.
- var secured = cookie.secure && (req.connection.encrypted || req.connection.proxySecure);
- if (secured || !cookie.secure) {
- res.setHeader('Set-Cookie', cookie.serialize(key, req.sessionID));
- }
- }
-
- res.writeHead = writeHead;
- return res.writeHead(status, headers);
- };
-
- // proxy end() to commit the session
- var end = res.end;
- res.end = function(data, encoding){
- res.end = end;
- if (req.session) {
- // HACK: ensure Set-Cookie for implicit writeHead()
- if (!res._header) res._implicitHeader();
- req.session.resetMaxAge();
- req.session.save(function(){
- res.end(data, encoding);
- });
- } else {
- res.end(data, encoding);
- }
- };
-
- // session hashing
- function hash(base) {
- return store.hash(req, base);
- }
-
- // generate the session
- function generate() {
- store.generate(req);
- }
-
- // get the sessionID from the cookie
- req.sessionID = req.cookies[key];
-
- // make a new session if the browser doesn't send a sessionID
- if (!req.sessionID) {
- generate();
- next();
- return;
- }
-
- // check the fingerprint
- var parts = req.sessionID.split('.');
- if (parts[1] != hash(parts[0])) {
- generate();
- next();
- return;
- }
-
- // generate the session object
- var pause = utils.pause(req);
- store.get(req.sessionID, function(err, sess){
- // proxy to resume() events
- var _next = next;
- next = function(err){
- _next(err);
- pause.resume();
- }
-
- // error handling
- if (err) {
- if ('ENOENT' == err.code) {
- generate();
- next();
- } else {
- next(err);
- }
- // no session
- } else if (!sess) {
- generate();
- next();
- // populate req.session
- } else {
- store.createSession(req, sess);
- next();
- }
- });
- };
-};
View
126 server/deps/connect/lib/middleware/session/cookie.js
@@ -1,126 +0,0 @@
-
-/*!
- * Connect - session - Cookie
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var utils = require('../../utils');
-
-/**
- * Initialize a new `Cookie` with the given `options`.
- *
- * @param {Object} options
- * @api private
- */
-
-var Cookie = module.exports = function Cookie(options) {
- this.path = '/';
- this.httpOnly = true;
- this.maxAge = 14400000;
- if (options) utils.merge(this, options);
- this.originalMaxAge = undefined == this.originalMaxAge
- ? this.maxAge
- : this.originalMaxAge;
-};
-
-/**
- * Prototype.
- */
-
-Cookie.prototype = {
-
- /**
- * Set expires `date`.
- *
- * @param {Date} date
- * @api public
- */
-
- set expires(date) {
- this._expires = date;
- this.originalMaxAge = this.maxAge;
- },
-
- /**
- * Get expires `date`.
- *
- * @return {Date}
- * @api public
- */
-
- get expires() {
- return this._expires;
- },
-
- /**
- * Set expires via max-age in `ms`.
- *
- * @param {Number} ms
- * @api public
- */
-
- set maxAge(ms) {
- this.expires = 'number' == typeof ms
- ? new Date(Date.now() + ms)
- : ms;
- },
-
- /**
- * Get expires max-age in `ms`.
- *
- * @return {Number}
- * @api public
- */
-
- get maxAge() {
- return this.expires instanceof Date
- ? this.expires.valueOf() - Date.now()
- : this.expires;
- },
-
- /**
- * Return cookie data object.
- *
- * @return {Object}
- * @api private
- */
-
- get data() {
- return {
- originalMaxAge: this.originalMaxAge
- , expires: this._expires
- , secure: this.secure
- , httpOnly: this.httpOnly
- , domain: this.domain
- , path: this.path
- }
- },
-
- /**
- * Return a serialized cookie string.
- *
- * @return {String}
- * @api public
- */
-
- serialize: function(name, val){
- return utils.serializeCookie(name, val, this.data);
- },
-
- /**
- * Return JSON representation of this cookie.
- *
- * @return {Object}
- * @api private
- */
-
- toJSON: function(){
- return this.data;
- }
-};
View
131 server/deps/connect/lib/middleware/session/memory.js
@@ -1,131 +0,0 @@
-
-/*!
- * Connect - session - MemoryStore
- * Copyright(c) 2010 Sencha Inc.
- * Copyright(c) 2011 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var Store = require('./store')
- , utils = require('../../utils')
- , Session = require('./session');
-
-/**
- * Initialize a new `MemoryStore`.
- *
- * @api public
-