Merge tag '4.13.1'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parents f90e045, 2ac2509 · Browse files · 21 files·+846 added−353 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+846 added−353 removed
- tests:+154 added−16 removed
- other:+692 added−337 removed
Provenance
- Commit
b309b87- Tree
cce8de7- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent 1
f90e045- Parent 2
2ac2509
21 files changed+846 added−353 removed
modified:lib/router/index.js+33 added-21 removed
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8 9+'use strict';10+11 /**12 * Module dependencies.13+ * @private14 */15 16 var Route = require('./route');17 var Layer = require('./layer');18 var methods = require('methods');19 var mixin = require('utils-merge');20 var debug = require('debug')('express:router');21 var deprecate = require('depd')('express');22+var flatten = require('array-flatten');23 var parseUrl = require('parseurl');13-var utils = require('../utils');24 25 /**26 * Module variables.27+ * @private28 */29 30 var objectRegExp = /^\[object (\S+)\]$/;31 var slice = Array.prototype.slice;3 unmodified lines35 * Initialize a new `Router` with the given `options`.36 *37 * @param {Object} options38 * @return {Router} which is an callable function28- * @api public39+ * @public40 */41 42 var proto = module.exports = function(options) {32- options = options || {};43+ var opts = options || {};44 45 function router(req, res, next) {46 router.handle(req, res, next);47 }2 unmodified lines50 router.__proto__ = proto;51 52 router.params = {};53 router._params = [];43- router.caseSensitive = options.caseSensitive;44- router.mergeParams = options.mergeParams;45- router.strict = options.strict;54+ router.caseSensitive = opts.caseSensitive;55+ router.mergeParams = opts.mergeParams;56+ router.strict = opts.strict;57 router.stack = [];58 59 return router;60 };28 unmodified lines89 *90 * @param {String} name91 * @param {Function} fn92 * @return {app} for chaining82- * @api public93+ * @public94 */95 96 proto.param = function param(name, fn) {97 // param logic30 unmodified lines128 };129 130 /**131 * Dispatch a req, res into the router.121- *122- * @api private132+ * @private133 */134 125-proto.handle = function(req, res, done) {135+proto.handle = function handle(req, res, out) {136 var self = this;137 138 debug('dispatching %s %s', req.method, req.url);139 15 unmodified lines155 156 // manage inter-router variables157 var parentParams = req.params;158 var parentUrl = req.baseUrl || '';149- done = restore(done, req, 'baseUrl', 'next', 'params');159+ var done = restore(out, req, 'baseUrl', 'next', 'params');160 161 // setup next layer162 req.next = next;163 151 unmodified lines315 };316 317 /**318 * Process any parameters for the layer.309- *310- * @api private319+ * @private320 */321 313-proto.process_params = function(layer, called, req, res, done) {322+proto.process_params = function process_params(layer, called, req, res, done) {323 var params = this.params;324 325 // captured parameters from the layer, keys and values326 var keys = layer.keys;38 unmodified lines365 return param();366 }367 368 // param previously called with same value or error occurred360- if (paramCalled && (paramCalled.error || paramCalled.match === paramVal)) {369+ if (paramCalled && (paramCalled.match === paramVal370+ || (paramCalled.error && paramCalled.error !== 'route'))) {371 // restore value372 req.params[name] = paramCalled.value;373 374 // next param46 unmodified lines421 * to the handler function. The main effect of this feature is that mounted422 * handlers can operate without any code changes regardless of the "prefix"423 * pathname.424 *415- * @api public425+ * @public426 */427 428 proto.use = function use(fn) {429 var offset = 0;14 unmodified lines444 path = fn;445 }446 }447 438- var callbacks = utils.flatten(slice.call(arguments, offset));448+ var callbacks = flatten(slice.call(arguments, offset));449 450 if (callbacks.length === 0) {451 throw new TypeError('Router.use() requires middleware functions');452 }453 444- callbacks.forEach(function (fn) {454+ for (var i = 0; i < callbacks.length; i++) {455+ var fn = callbacks[i];456+457 if (typeof fn !== 'function') {458 throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));459 }460 8 unmodified lines469 470 layer.route = undefined;471 472 this.stack.push(layer);461- }, this);473+ }474 475 return this;476 };477 6 unmodified lines484 * and middleware to routes.485 *486 * @param {String} path487 * @return {Route}476- * @api public488+ * @public489 */490 479-proto.route = function(path){491+proto.route = function route(path) {492 var route = new Route(path);493 494 var layer = new Layer(path, {495 sensitive: this.caseSensitive,147 unmodified linesmodified:lib/router/layer.js+30 added-20 removed
1234567891011121314151617181920212223242526152728293031322 unmodified lines353637382639404142434432454634474849505183 unmodified lines1351361371381261271281291391311321331341351361401411421431441451461476 unmodified lines154155156157151158159160154155161162163164165166167161162163168169170171172173174175176/*! * express * Copyright(c) 2009-2013 TJ Holowaychuk * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */
'use strict';
/** * Module dependencies. * @private */
var pathRegexp = require('path-to-regexp');var debug = require('debug')('express:router:layer');
/** * Module variables. * @private */
var hasOwnProperty = Object.prototype.hasOwnProperty;
/** * Expose `Layer`. * Module exports. * @public */
module.exports = Layer;
2 unmodified lines return new Layer(path, options, fn); }
debug('new %s', path); options = options || {}; var opts = options || {};
this.handle = fn; this.name = fn.name || '<anonymous>'; this.params = undefined; this.path = undefined; this.regexp = pathRegexp(path, this.keys = [], options); this.regexp = pathRegexp(path, this.keys = [], opts);
if (path === '/' && options.end === false) { if (path === '/' && opts.end === false) { this.regexp.fast_slash = true; }}
83 unmodified lines this.path = m[0];
var keys = this.keys; var params = this.params; var prop; var n = 0; var key; var val;
for (var i = 1, len = m.length; i < len; ++i) { key = keys[i - 1]; prop = key ? key.name : n++; val = decode_param(m[i]); for (var i = 1; i < m.length; i++) { var key = keys[i - 1]; var prop = key.name; var val = decode_param(m[i]);
if (val !== undefined || !(hasOwnProperty.call(params, prop))) { params[prop] = val; }6 unmodified lines * Decode param value. * * @param {string} val * @return {string} * @api private * @private */
function decode_param(val){ if (typeof val !== 'string') {function decode_param(val) { if (typeof val !== 'string' || val.length === 0) { return val; }
try { return decodeURIComponent(val); } catch (e) { var err = new TypeError("Failed to decode param '" + val + "'"); err.status = 400; } catch (err) { if (err instanceof URIError) { err.message = 'Failed to decode param \'' + val + '\''; err.status = err.statusCode = 400; }
throw err; }}modified:lib/router/route.js+54 added-27 removed
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8+9+'use strict';10+11 /**12 * Module dependencies.13+ * @private14 */15 16 var debug = require('debug')('express:router:route');17+var flatten = require('array-flatten');18 var Layer = require('./layer');19 var methods = require('methods');8-var utils = require('../utils');20 21 /**11- * Expose `Route`.22+ * Module variables.23+ * @private24 */25 26+var slice = Array.prototype.slice;27+var toString = Object.prototype.toString;28+29+/**30+ * Module exports.31+ * @public32+ */33+34 module.exports = Route;35 36 /**37 * Initialize `Route` with the given `path`,38 *39 * @param {String} path20- * @api private40+ * @public41 */42 43 function Route(path) {24- debug('new %s', path);44 this.path = path;45 this.stack = [];46 47+ debug('new %s', path);48+49 // route handlers for various http methods50 this.methods = {};51 }52 53 /**54+ * Determine if the route handles a given method.33- * @api private55+ * @private56 */57 58 Route.prototype._handles_method = function _handles_method(method) {59 if (this.methods._all) {60 return true;61 }62 41- method = method.toLowerCase();63+ var name = method.toLowerCase();64 43- if (method === 'head' && !this.methods['head']) {44- method = 'get';65+ if (name === 'head' && !this.methods['head']) {66+ name = 'get';67 }68 47- return Boolean(this.methods[method]);69+ return Boolean(this.methods[name]);70 };71 72 /**73 * @return {Array} supported HTTP methods52- * @api private74+ * @private75 */76 77 Route.prototype._options = function _options() {78 var methods = Object.keys(this.methods);12 unmodified lines91 };92 93 /**94 * dispatch req, res into this route73- *74- * @api private95+ * @private96 */97 77-Route.prototype.dispatch = function(req, res, done){98+Route.prototype.dispatch = function dispatch(req, res, done) {99 var idx = 0;100 var stack = this.stack;101 if (stack.length === 0) {102 return done();57 unmodified lines160 * @return {Route} for chaining161 * @api public162 */163 143-Route.prototype.all = function(){144- var callbacks = utils.flatten([].slice.call(arguments));145- callbacks.forEach(function(fn) {146- if (typeof fn !== 'function') {147- var type = {}.toString.call(fn);164+Route.prototype.all = function all() {165+ var handles = flatten(slice.call(arguments));166+167+ for (var i = 0; i < handles.length; i++) {168+ var handle = handles[i];169+170+ if (typeof handle !== 'function') {171+ var type = toString.call(handle);172 var msg = 'Route.all() requires callback functions but got a ' + type;149- throw new Error(msg);173+ throw new TypeError(msg);174 }175 152- var layer = Layer('/', {}, fn);176+ var layer = Layer('/', {}, handle);177 layer.method = undefined;178 179 this.methods._all = true;180 this.stack.push(layer);157- }, this);181+ }182 183 return this;184 };185 186 methods.forEach(function(method){187 Route.prototype[method] = function(){164- var callbacks = utils.flatten([].slice.call(arguments));188+ var handles = flatten(slice.call(arguments));189 166- callbacks.forEach(function(fn) {167- if (typeof fn !== 'function') {168- var type = {}.toString.call(fn);190+ for (var i = 0; i < handles.length; i++) {191+ var handle = handles[i];192+193+ if (typeof handle !== 'function') {194+ var type = toString.call(handle);195 var msg = 'Route.' + method + '() requires callback functions but got a ' + type;196 throw new Error(msg);197 }198 199 debug('%s %s', method, this.path);200 175- var layer = Layer('/', {}, fn);201+ var layer = Layer('/', {}, handle);202 layer.method = method;203 204 this.methods[method] = true;205 this.stack.push(layer);180- }, this);206+ }207+208 return this;209 };210 });modified:lib/application.js+110 added-74 removed
4 unmodified lines5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */8 9+'use strict';10+11 /**12 * Module dependencies.11- * @api private13+ * @private14 */15 16 var finalhandler = require('finalhandler');15-var flatten = require('./utils').flatten;17 var Router = require('./router');18 var methods = require('methods');19 var debug = require('debug')('express:application');20 var View = require('./view');21 var http = require('http');22 var compileETag = require('./utils').compileETag;23 var compileQueryParser = require('./utils').compileQueryParser;24 var compileTrust = require('./utils').compileTrust;25+var flatten = require('array-flatten');26 var merge = require('utils-merge');27 var resolve = require('path').resolve;28 var slice = Array.prototype.slice;29 4 unmodified lines34 var app = exports = module.exports = {};35 36 /**37 * Variable for trust proxy inheritance back-compat36- * @api private38+ * @private39 */40 41 var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';42 3 unmodified lines46 * - setup default configuration47 * - setup default middleware48 * - setup route reflection methods49 *48- * @api private50+ * @private51 */52 51-app.init = function(){53+app.init = function init() {54 var router = null;55 56 this.cache = {};55- this.settings = {};57 this.engines = {};58+ this.settings = {};59+60 this.defaultConfiguration();61 62 // Setup getting to lazily add base router63 Object.defineProperty(this, 'router', {13 unmodified lines77 };78 79 /**80 * Initialize application configuration.78- *79- * @api private81+ * @private82 */83 82-app.defaultConfiguration = function(){84+app.defaultConfiguration = function defaultConfiguration() {85+ var env = process.env.NODE_ENV || 'development';86+87 // default settings88 this.enable('x-powered-by');89 this.set('etag', 'weak');86- var env = process.env.NODE_ENV || 'development';90 this.set('env', env);91 this.set('query parser', 'extended');92 this.set('subdomain offset', 2);93 this.set('trust proxy', false);42 unmodified lines136 137 /**138 * Dispatch a req, res pair into the application. Starts pipeline processing.139 *137- * If no _done_ callback is provided, then default error handlers will respond140+ * If no callback is provided, then default error handlers will respond141 * in the event of an error bubbling through the stack.142 *140- * @api private143+ * @private144 */145 143-app.handle = function(req, res, done) {146+app.handle = function handle(req, res, callback) {147 // final handler145- done = done || finalhandler(req, res, {148+ var done = callback || finalhandler(req, res, {149 env: this.get('env'),150 onerror: logerror.bind(this)151 });152 24 unmodified lines177 *178 * If the _fn_ parameter is an express app, then it will be179 * mounted at the _route_ specified.180 *178- * @api public181+ * @public182 */183 184 app.use = function use(fn) {185 var offset = 0;57 unmodified lines243 *244 * Routes are isolated middleware stacks for specific paths.245 * See the Route api docs for details.246 *244- * @api public247+ * @public248 */249 250 app.route = function route(path) {251 return this.router.route(path);29 unmodified lines281 *282 * @param {String} ext283 * @param {Function} fn284 * @return {app} for chaining282- * @api public285+ * @public286 */287 285-app.engine = function(ext, fn){286- if ('function' != typeof fn) throw new Error('callback function required');287- if ('.' != ext[0]) ext = '.' + ext;288- this.engines[ext] = fn;288+app.engine = function engine(ext, fn) {289+ if (typeof fn !== 'function') {290+ throw new Error('callback function required');291+ }292+293+ // get file extension294+ var extension = ext[0] !== '.'295+ ? '.' + ext296+ : ext;297+298+ // store engine299+ this.engines[extension] = fn;300+301 return this;302 };303 304 /**4 unmodified lines309 *310 * @param {String|Array} name311 * @param {Function} fn312 * @return {app} for chaining301- * @api public313+ * @public314 */315 316 app.param = function param(name, fn) {317 if (Array.isArray(name)) {318 for (var i = 0; i < name.length; i++) {319 this.param(name[i], fn);320 }321+322 return this;323 }324 325 this.router.param(name, fn);326+327 return this;328 };329 330 /**7 unmodified lines338 *339 * @param {String} setting340 * @param {*} [val]341 * @return {Server} for chaining328- * @api public342+ * @public343 */344 331-app.set = function(setting, val){345+app.set = function set(setting, val) {346 if (arguments.length === 1) {347 // app.get(setting)348 return this.settings[setting];349 }350 351+ debug('set "%s" to %o', setting, val);352+353 // set value354 this.settings[setting] = val;355 356 // trigger matched settings357 switch (setting) {358 case 'etag':343- debug('compile etag %s', val);359 this.set('etag fn', compileETag(val));360 break;361 case 'query parser':347- debug('compile query parser %s', val);362 this.set('query parser fn', compileQueryParser(val));363 break;364 case 'trust proxy':351- debug('compile trust proxy %s', val);365 this.set('trust proxy fn', compileTrust(val));366 367 // trust proxy inherit back-compat368 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {17 unmodified lines386 * was mounted as "/blog" then the387 * return value would be "/blog/admin".388 *389 * @return {String}377- * @api private390+ * @private391 */392 380-app.path = function(){393+app.path = function path() {394 return this.parent395 ? this.parent.path() + this.mountpath396 : '';397 };9 unmodified lines407 * // => true408 *409 * @param {String} setting410 * @return {Boolean}398- * @api public411+ * @public412 */413 401-app.enabled = function(setting){402- return !!this.set(setting);414+app.enabled = function enabled(setting) {415+ return Boolean(this.set(setting));416 };417 418 /**419 * Check if `setting` is disabled.6 unmodified lines426 * // => false427 *428 * @param {String} setting429 * @return {Boolean}417- * @api public430+ * @public431 */432 420-app.disabled = function(setting){433+app.disabled = function disabled(setting) {434 return !this.set(setting);435 };436 437 /**438 * Enable `setting`.439 *440 * @param {String} setting441 * @return {app} for chaining429- * @api public442+ * @public443 */444 432-app.enable = function(setting){445+app.enable = function enable(setting) {446 return this.set(setting, true);447 };448 449 /**450 * Disable `setting`.451 *452 * @param {String} setting453 * @return {app} for chaining441- * @api public454+ * @public455 */456 444-app.disable = function(setting){457+app.disable = function disable(setting) {458 return this.set(setting, false);459 };460 461 /**1 unmodified line463 */464 465 methods.forEach(function(method){466 app[method] = function(path){454- if ('get' == method && 1 == arguments.length) return this.set(path);467+ if (method === 'get' && arguments.length === 1) {468+ // app.get(setting)469+ return this.set(path);470+ }471 472 var route = this.route(path);473 route[method].apply(route, slice.call(arguments, 1));474 return this;6 unmodified lines481 *482 * @param {String} path483 * @param {Function} ...484 * @return {app} for chaining469- * @api public485+ * @public486 */487 472-app.all = function(path){488+app.all = function all(path) {489 var route = this.route(path);490 var args = slice.call(arguments, 1);475- methods.forEach(function(method){476- route[method].apply(route, args);477- });491 492+ for (var i = 0; i < methods.length; i++) {493+ route[methods[i]].apply(route, args);494+ }495+496 return this;497 };498 499 /**8 unmodified lines508 * })509 *510 * @param {String} name511 * @param {String|Function} options or fn495- * @param {Function} fn496- * @api public512+ * @param {Function} callback513+ * @public514 */515 499-app.render = function(name, options, fn){500- var opts = {};516+app.render = function render(name, options, callback) {517 var cache = this.cache;518+ var done = callback;519 var engines = this.engines;520+ var opts = options;521+ var renderOptions = {};522 var view;523 524 // support callback function as second arg506- if ('function' == typeof options) {507- fn = options, options = {};525+ if (typeof options === 'function') {526+ done = options;527+ opts = {};528 }529 530 // merge app.locals511- merge(opts, this.locals);531+ merge(renderOptions, this.locals);532 533 // merge options._locals514- if (options._locals) {515- merge(opts, options._locals);534+ if (opts._locals) {535+ merge(renderOptions, opts._locals);536 }537 538 // merge options519- merge(opts, options);539+ merge(renderOptions, opts);540 541 // set .cache unless explicitly provided522- opts.cache = null == opts.cache523- ? this.enabled('view cache')524- : opts.cache;542+ if (renderOptions.cache == null) {543+ renderOptions.cache = this.enabled('view cache');544+ }545 546 // primed cache527- if (opts.cache) view = cache[name];547+ if (renderOptions.cache) {548+ view = cache[name];549+ }550 551 // view552 if (!view) {531- view = new (this.get('view'))(name, {553+ var View = this.get('view');554+555+ view = new View(name, {556 defaultEngine: this.get('view engine'),557 root: this.get('views'),558 engines: engines559 });3 unmodified lines563 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'564 : 'directory "' + view.root + '"'565 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);566 err.view = view;543- return fn(err);567+ return done(err);568 }569 570 // prime the cache547- if (opts.cache) cache[name] = view;571+ if (renderOptions.cache) {572+ cache[name] = view;573+ }574 }575 576 // render551- try {552- view.render(opts, fn);553- } catch (err) {554- fn(err);555- }577+ tryRender(view, renderOptions, done);578 };579 580 /**581 * Listen for connections.12 unmodified lines594 * http.createServer(app).listen(80);595 * https.createServer({ ... }, app).listen(443);596 *597 * @return {http.Server}576- * @api public598+ * @public599 */600 579-app.listen = function(){601+app.listen = function listen() {602 var server = http.createServer(this);603 return server.listen.apply(server, arguments);604 };605 606 /**585-* Log error using console.error.586-*587-* @param {Error} err588-* @api private589-*/607+ * Log error using console.error.608+ *609+ * @param {Error} err610+ * @private611+ */612 591-function logerror(err){613+function logerror(err) {614+ /* istanbul ignore next */615 if (this.get('env') !== 'test') console.error(err.stack || err.toString());616 }617+618+/**619+ * Try rendering a view.620+ * @private621+ */622+623+function tryRender(view, options, callback) {624+ try {625+ view.render(options, callback);626+ } catch (err) {627+ callback(err);628+ }629+}modified:lib/express.js+10 added
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8+9+'use strict';10+11 /**12 * Module dependencies.13 */14 89 unmodified linesmodified:lib/request.js+56 added-34 removed
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8+9+'use strict';10+11 /**12 * Module dependencies.13+ * @private14 */15 16 var accepts = require('accepts');17 var deprecate = require('depd')('express');33 unmodified lines51 * Aliased as `req.header()`.52 *53 * @param {String} name54 * @return {String}44- * @api public55+ * @public56 */57 58 req.get =48-req.header = function(name){49- switch (name = name.toLowerCase()) {59+req.header = function header(name) {60+ var lc = name.toLowerCase();61+62+ switch (lc) {63 case 'referer':64 case 'referrer':65 return this.headers.referrer66 || this.headers.referer;67 default:55- return this.headers[name];68+ return this.headers[lc];69 }70 };71 72 /**37 unmodified lines110 * req.accepts('html, json');111 * // => "json"112 *113 * @param {String|Array} type(s)101- * @return {String}102- * @api public114+ * @return {String|Array|Boolean}115+ * @public116 */117 118 req.accepts = function(){119 var accept = accepts(this);3 unmodified lines123 /**124 * Check if the given `encoding`s are accepted.125 *126 * @param {String} ...encoding114- * @return {Boolean}115- * @api public127+ * @return {String|Array}128+ * @public129 */130 131 req.acceptsEncodings = function(){132 var accept = accepts(this);4 unmodified lines137 * Check if the given `charset`s are acceptable,138 * otherwise you should respond with 406 "Not Acceptable".139 *140 * @param {String} ...charset128- * @return {Boolean}129- * @api public141+ * @return {String|Array}142+ * @public143 */144 145 req.acceptsCharsets = function(){146 var accept = accepts(this);4 unmodified lines151 * Check if the given `lang`s are acceptable,152 * otherwise you should respond with 406 "Not Acceptable".153 *154 * @param {String} ...lang142- * @return {Boolean}143- * @api public155+ * @return {String|Array}156+ * @public157 */158 159 req.acceptsLanguages = function(){160 var accept = accepts(this);16 unmodified lines177 * with 4 users when available, not 3.178 *179 * @param {Number} size180 * @return {Array}168- * @api public181+ * @public182 */183 184 req.range = function(size){185 var range = this.get('Range');37 unmodified lines223 *224 * @param {String} name225 * @param {Mixed} [defaultValue]226 * @return {String}214- * @api public227+ * @public228 */229 230 req.param = function param(name, defaultValue) {231 var params = this.params || {};32 unmodified lines264 *265 * req.is('html');266 * // => false267 *255- * @param {String} type256- * @return {Boolean}257- * @api public268+ * @param {String|Array} types...269+ * @return {String|false|null}270+ * @public271 */272 260-req.is = function(types){261- if (!Array.isArray(types)) types = [].slice.call(arguments);262- return typeis(this, types);273+req.is = function is(types) {274+ var arr = types;275+276+ // support flattened arguments277+ if (!Array.isArray(types)) {278+ arr = new Array(arguments.length);279+ for (var i = 0; i < arr.length; i++) {280+ arr[i] = arguments[i];281+ }282+ }283+284+ return typeis(this, arr);285 };286 287 /**288 * Return the protocol string "http" or "https"5 unmodified lines294 * If you're running behind a reverse proxy that295 * supplies https for you this may be enabled.296 *297 * @return {String}276- * @api public298+ * @public299 */300 301 defineGetter(req, 'protocol', function protocol(){302 var proto = this.connection.encrypted16 unmodified lines319 *320 * req.protocol == 'https'321 *322 * @return {Boolean}301- * @api public323+ * @public324 */325 326 defineGetter(req, 'secure', function secure(){305- return 'https' == this.protocol;327+ return this.protocol === 'https';328 });329 330 /**331 * Return the remote address from the trusted proxy.1 unmodified line333 * The is the remote address on the socket unless334 * "trust proxy" is set.335 *336 * @return {String}315- * @api public337+ * @public338 */339 340 defineGetter(req, 'ip', function ip(){341 var trust = this.app.get('trust proxy fn');8 unmodified lines350 * where "proxy2" is the furthest down-stream and "proxy1" and351 * "proxy2" were trusted.352 *353 * @return {Array}332- * @api public354+ * @public355 */356 357 defineGetter(req, 'ips', function ips() {358 var trust = this.app.get('trust proxy fn');12 unmodified lines371 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.372 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.373 *374 * @return {Array}353- * @api public375+ * @public376 */377 378 defineGetter(req, 'subdomains', function subdomains() {379 var hostname = this.hostname;11 unmodified lines391 /**392 * Short-hand for `url.parse(req.url).pathname`.393 *394 * @return {String}373- * @api public395+ * @public396 */397 398 defineGetter(req, 'path', function path() {399 return parse(this).pathname;6 unmodified lines406 * address, the "X-Forwarded-Host" header field will407 * be trusted.408 *409 * @return {String}388- * @api public410+ * @public411 */412 413 defineGetter(req, 'host', function host(){414 var trust = this.app.get('trust proxy fn');27 unmodified lines442 ? host.indexOf(']') + 1443 : 0;444 var index = host.indexOf(':', offset);445 424- return ~index446+ return index !== -1447 ? host.substring(0, index)448 : host;449 });450 2 unmodified lines453 * Last-Modified and/or the ETag454 * still match.455 *456 * @return {Boolean}435- * @api public457+ * @public458 */459 460 defineGetter(req, 'fresh', function(){461 var method = this.method;15 unmodified lines477 * "Last-Modified" and / or the "ETag" for the478 * resource has changed.479 *480 * @return {Boolean}459- * @api public481+ * @public482 */483 484 defineGetter(req, 'stale', function stale(){485 return !this.fresh;2 unmodified lines488 /**489 * Check if the request was an _XMLHttpRequest_.490 *491 * @return {Boolean}470- * @api public492+ * @public493 */494 495 defineGetter(req, 'xhr', function xhr(){496 var val = this.get('X-Requested-With') || '';475- return 'xmlhttprequest' == val.toLowerCase();497+ return val.toLowerCase() === 'xmlhttprequest';498 });499 500 /**501 * Helper function for creating a getter on an object.502 *503 * @param {Object} obj504 * @param {String} name505 * @param {Function} getter484- * @api private506+ * @private507 */508 function defineGetter(obj, name, getter) {509 Object.defineProperty(obj, name, {510 configurable: true,4 unmodified linesmodified:lib/response.js+121 added-98 removed
3 unmodified lines4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7 8+'use strict';9+10 /**11 * Module dependencies.10- * @api private12+ * @private13 */14 15 var contentDisposition = require('content-disposition');16 var deprecate = require('depd')('express');23 unmodified lines40 __proto__: http.ServerResponse.prototype41 };42 43 /**44+ * Module variables.45+ * @private46+ */47+48+var charsetRegExp = /;\s*charset\s*=/;49+50+/**51 * Set status `code`.52 *53 * @param {Number} code54 * @return {ServerResponse}46- * @api public55+ * @public56 */57 49-res.status = function(code){58+res.status = function status(code) {59 this.statusCode = code;60 return this;61 };62 8 unmodified lines71 * });72 *73 * @param {Object} links74 * @return {ServerResponse}66- * @api public75+ * @public76 */77 78 res.links = function(links){79 var link = this.get('Link') || '';12 unmodified lines92 * res.send({ some: 'json' });93 * res.send('<p>some html</p>');94 *95 * @param {string|number|boolean|object|Buffer} body87- * @api public96+ * @public97 */98 99 res.send = function send(body) {100 var chunk = body;96 unmodified lines197 * res.json(null);198 * res.json({ user: 'tj' });199 *200 * @param {string|number|boolean|object} obj192- * @api public201+ * @public202 */203 204 res.json = function json(obj) {205 var val = obj;27 unmodified lines233 * res.jsonp(null);234 * res.jsonp({ user: 'tj' });235 *236 * @param {string|number|boolean|object} obj228- * @api public237+ * @public238 */239 240 res.jsonp = function jsonp(obj) {241 var val = obj;56 unmodified lines298 *299 * res.sendStatus(200);300 *301 * @param {number} statusCode293- * @api public302+ * @public303 */304 305 res.sendStatus = function sendStatus(statusCode) {297- var body = http.STATUS_CODES[statusCode] || String(statusCode);306+ var body = statusCodes[statusCode] || String(statusCode);307 308 this.statusCode = statusCode;309 this.type('txt');310 3 unmodified lines314 /**315 * Transfer the file at the given `path`.316 *317 * Automatically sets the _Content-Type_ response header field.309- * The callback `fn(err)` is invoked when the transfer is complete318+ * The callback `callback(err)` is invoked when the transfer is complete319 * or when an error occurs. Be sure to check `res.sentHeader`320 * if you wish to attempt responding, as the header and some data321 * may have already been transferred.322 *25 unmodified lines348 * }349 * });350 * });351 *343- * @api public352+ * @public353 */354 346-res.sendFile = function sendFile(path, options, fn) {355+res.sendFile = function sendFile(path, options, callback) {356+ var done = callback;357 var req = this.req;358 var res = this;359 var next = req.next;360+ var opts = options || {};361 362 if (!path) {363 throw new TypeError('path argument is required to res.sendFile');364 }365 366 // support function as second arg367 if (typeof options === 'function') {357- fn = options;358- options = {};368+ done = options;369+ opts = {};370 }371 361- options = options || {};362-363- if (!options.root && !isAbsolute(path)) {372+ if (!opts.root && !isAbsolute(path)) {373 throw new TypeError('path must be absolute or specify root to res.sendFile');374 }375 376 // create file stream377 var pathname = encodeURI(path);369- var file = send(req, pathname, options);378+ var file = send(req, pathname, opts);379 380 // transfer372- sendfile(res, file, options, function (err) {373- if (fn) return fn(err);381+ sendfile(res, file, opts, function (err) {382+ if (done) return done(err);383 if (err && err.code === 'EISDIR') return next();384 385 // next() all but write errors386 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {5 unmodified lines392 /**393 * Transfer the file at the given `path` as an attachment.394 *395 * Optionally providing an alternate attachment `filename`,387- * and optional callback `fn(err)`. The callback is invoked396+ * and optional callback `callback(err)`. The callback is invoked397 * when the data transfer is complete, or when an error has398 * ocurred. Be sure to check `res.headersSent` if you plan to respond.399 *400 * This method uses `res.sendFile()`.401 *393- * @api public402+ * @public403 */404 396-res.download = function download(path, filename, fn) {405+res.download = function download(path, filename, callback) {406+ var done = callback;407+ var name = filename;408+409 // support function as second arg410 if (typeof filename === 'function') {399- fn = filename;400- filename = null;411+ done = filename;412+ name = null;413 }414 403- filename = filename || path;404-415 // set Content-Disposition when file is sent416 var headers = {407- 'Content-Disposition': contentDisposition(filename)417+ 'Content-Disposition': contentDisposition(name || path)418 };419 420 // Resolve the full path for sendFile421 var fullPath = resolve(path);422 413- return this.sendFile(fullPath, { headers: headers }, fn);423+ return this.sendFile(fullPath, { headers: headers }, done);424 };425 426 /**427 * Set _Content-Type_ response header with `type` through `mime.lookup()`8 unmodified lines436 * res.type('png');437 *438 * @param {String} type439 * @return {ServerResponse} for chaining430- * @api public440+ * @public441 */442 443 res.contentType =434-res.type = function(type){435- return this.set('Content-Type', ~type.indexOf('/')436- ? type437- : mime.lookup(type));444+res.type = function contentType(type) {445+ var ct = type.indexOf('/') === -1446+ ? mime.lookup(type)447+ : type;448+449+ return this.set('Content-Type', ct);450 };451 452 /**453 * Respond to the Acceptable formats using an `obj`48 unmodified lines502 * instead.503 *504 * @param {Object} obj505 * @return {ServerResponse} for chaining494- * @api public506+ * @public507 */508 509 res.format = function(obj){510 var req = this.req;2 unmodified lines513 var fn = obj.default;514 if (fn) delete obj.default;515 var keys = Object.keys(obj);516 505- var key = req.accepts(keys);517+ var key = keys.length > 0518+ ? req.accepts(keys)519+ : false;520 521 this.vary("Accept");522 523 if (key) {2 unmodified lines526 } else if (fn) {527 fn();528 } else {529 var err = new Error('Not Acceptable');516- err.status = 406;530+ err.status = err.statusCode = 406;531 err.types = normalizeTypes(keys).map(function(o){ return o.value });532 next(err);533 }534 4 unmodified lines539 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.540 *541 * @param {String} filename542 * @return {ServerResponse}529- * @api public543+ * @public544 */545 546 res.attachment = function attachment(filename) {547 if (filename) {16 unmodified lines564 *565 * @param {String} field566 * @param {String|Array} val567 * @return {ServerResponse} for chaining554- * @api public568+ * @public569 */570 571 res.append = function append(field, val) {572 var prev = this.get(field);20 unmodified lines593 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });594 *595 * Aliased as `res.header()`.596 *583- * @param {String|Object|Array} field584- * @param {String} val597+ * @param {String|Object} field598+ * @param {String|Array} val599 * @return {ServerResponse} for chaining586- * @api public600+ * @public601 */602 603 res.set =604 res.header = function header(field, val) {605 if (arguments.length === 2) {592- if (Array.isArray(val)) val = val.map(String);593- else val = String(val);594- if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {595- var charset = mime.charsets.lookup(val.split(';')[0]);596- if (charset) val += '; charset=' + charset.toLowerCase();606+ var value = Array.isArray(val)607+ ? val.map(String)608+ : String(val);609+610+ // add charset to content-type611+ if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {612+ var charset = mime.charsets.lookup(value.split(';')[0]);613+ if (charset) value += '; charset=' + charset.toLowerCase();614 }615+598- this.setHeader(field, val);616+ this.setHeader(field, value);617 } else {618 for (var key in field) {619 this.set(key, field[key]);620 }5 unmodified lines626 * Get value for header `field`.627 *628 * @param {String} field629 * @return {String}612- * @api public630+ * @public631 */632 633 res.get = function(field){634 return this.getHeader(field);4 unmodified lines639 *640 * @param {String} name641 * @param {Object} options642 * @return {ServerResponse} for chaining625- * @api public643+ * @public644 */645 628-res.clearCookie = function(name, options){629- var opts = { expires: new Date(1), path: '/' };630- return this.cookie(name, '', options631- ? merge(opts, options)632- : opts);646+res.clearCookie = function clearCookie(name, options) {647+ var opts = merge({ expires: new Date(1), path: '/' }, options);648+649+ return this.cookie(name, '', opts);650 };651 652 /**636- * Set cookie `name` to `val`, with the given `options`.653+ * Set cookie `name` to `value`, with the given `options`.654 *655 * Options:656 *657 * - `maxAge` max-age in milliseconds, converted to `expires`8 unmodified lines666 * // save as above667 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })668 *669 * @param {String} name653- * @param {String|Object} val670+ * @param {String|Object} value671 * @param {Options} options672 * @return {ServerResponse} for chaining656- * @api public673+ * @public674 */675 659-res.cookie = function(name, val, options){660- options = merge({}, options);676+res.cookie = function (name, value, options) {677+ var opts = merge({}, options);678 var secret = this.req.secret;662- var signed = options.signed;663- if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');664- if ('number' == typeof val) val = val.toString();665- if ('object' == typeof val) val = 'j:' + JSON.stringify(val);666- if (signed) val = 's:' + sign(val, secret);667- if ('maxAge' in options) {668- options.expires = new Date(Date.now() + options.maxAge);669- options.maxAge /= 1000;679+ var signed = opts.signed;680+681+ if (signed && !secret) {682+ throw new Error('cookieParser("secret") required for signed cookies');683 }671- if (null == options.path) options.path = '/';672- var headerVal = cookie.serialize(name, String(val), options);684 674- // supports multiple 'res.cookie' calls by getting previous value675- var prev = this.get('Set-Cookie');676- if (prev) {677- if (Array.isArray(prev)) {678- headerVal = prev.concat(headerVal);679- } else {680- headerVal = [prev, headerVal];681- }685+ var val = typeof value === 'object'686+ ? 'j:' + JSON.stringify(value)687+ : String(value);688+689+ if (signed) {690+ val = 's:' + sign(val, secret);691 }683- this.set('Set-Cookie', headerVal);692+693+ if ('maxAge' in opts) {694+ opts.expires = new Date(Date.now() + opts.maxAge);695+ opts.maxAge /= 1000;696+ }697+698+ if (opts.path == null) {699+ opts.path = '/';700+ }701+702+ this.append('Set-Cookie', cookie.serialize(name, String(val), opts));703+704 return this;705 };706 687-707 /**708 * Set the location header to `url`.709 *710 * The given `url` can also be "back", which redirects6 unmodified lines717 * res.location('../login');718 *719 * @param {String} url720 * @return {ServerResponse} for chaining702- * @api public721+ * @public722 */723 705-res.location = function(url){706- var req = this.req;724+res.location = function location(url) {725+ var loc = url;726 727 // "back" is an alias for the referrer728+ if (url === 'back') {709- if ('back' == url) url = req.get('Referrer') || '/';729+ loc = this.req.get('Referrer') || '/';730+ }731 711- // Respond712- this.set('Location', url);732+ // set location733+ this.set('Location', loc);734 return this;735 };736 737 /**10 unmodified lines748 * res.redirect('http://example.com');749 * res.redirect(301, 'http://example.com');750 * res.redirect('../login'); // /blog/post/1 -> /blog/login751 *731- * @api public752+ * @public753 */754 755 res.redirect = function redirect(url) {756 var address = url;47 unmodified lines804 * this call is simply ignored.805 *806 * @param {Array|String} field807 * @return {ServerResponse} for chaining787- * @api public808+ * @public809 */810 811 res.vary = function(field){812 // checks for back-compat16 unmodified lines829 *830 * - `cache` boolean hinting to the engine it should cache831 * - `filename` filename of the view being rendered832 *812- * @api public833+ * @public834 */835 815-res.render = function(view, options, fn){816- options = options || {};817- var self = this;836+res.render = function render(view, options, callback) {837+ var app = this.req.app;838+ var done = callback;839+ var opts = options || {};840 var req = this.req;819- var app = req.app;841+ var self = this;842 843 // support callback function as second arg822- if ('function' == typeof options) {823- fn = options, options = {};844+ if (typeof options === 'function') {845+ done = options;846+ opts = {};847 }848 849 // merge res.locals827- options._locals = self.locals;850+ opts._locals = self.locals;851 852 // default callback to respond830- fn = fn || function(err, str){853+ done = done || function (err, str) {854 if (err) return req.next(err);855 self.send(str);856 };857 858 // render836- app.render(view, options, fn);859+ app.render(view, opts, done);860 };861 862 // pipe the send file stream863 function sendfile(res, file, options, callback) {88 unmodified linesmodified:lib/utils.js+21 added-13 removed
3 unmodified lines4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7 8+'use strict';9+10 /**11 * Module dependencies.12 * @api private13 */14 15 var mime = require('send').mime;16 var contentType = require('content-type');17+var deprecate = require('depd')('express');18 var etag = require('etag');19+var flatten = require('array-flatten');20 var proxyaddr = require('proxy-addr');21 var qs = require('qs');22 var querystring = require('querystring');23 52 unmodified lines76 * @return {Array}77 * @api private78 */79 76-exports.flatten = function(arr, ret){77- ret = ret || [];78- var len = arr.length;79- for (var i = 0; i < len; ++i) {80- if (Array.isArray(arr[i])) {81- exports.flatten(arr[i], ret);82- } else {83- ret.push(arr[i]);84- }85- }86- return ret;87-};80+exports.flatten = deprecate.function(flatten,81+ 'utils.flatten: use array-flatten npm module instead');82 83 /**84 * Normalize the given `type`, for example "html" becomes "text/html".85 *107 unmodified lines193 break;194 case false:195 break;196 case 'extended':203- fn = qs.parse;197+ fn = parseExtendedQueryString;198 break;199 case 'simple':200 fn = querystring.parse;201 break;55 unmodified lines257 258 // format type259 return contentType.format(parsed);260 };261+262+/**263+ * Parse an extended query string with qs.264+ *265+ * @return {Object}266+ * @private267+ */268+269+function parseExtendedQueryString(str) {270+ return qs.parse(str, {271+ allowDots: false,272+ allowPrototypes: true273+ });274+}modified:lib/view.js+57 added-26 removed
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8+9+'use strict';10+11 /**12 * Module dependencies.13+ * @private14 */15 16 var debug = require('debug')('express:view');17 var path = require('path');11 unmodified lines29 var join = path.join;30 var resolve = path.resolve;31 32 /**22- * Expose `View`.33+ * Module exports.34+ * @public35 */36 37 module.exports = View;38 5 unmodified lines44 * - `defaultEngine` the default template engine name45 * - `engines` template engine require() cache46 * - `root` root path for view lookup47 *36- * @param {String} name37- * @param {Object} options38- * @api private48+ * @param {string} name49+ * @param {object} options50+ * @public51 */52 53 function View(name, options) {42- options = options || {};54+ var opts = options || {};55+56+ this.defaultEngine = opts.defaultEngine;57+ this.ext = extname(name);58 this.name = name;44- this.root = options.root;45- var engines = options.engines;46- this.defaultEngine = options.defaultEngine;47- var ext = this.ext = extname(name);48- if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');49- if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);50- this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);51- this.path = this.lookup(name);59+ this.root = opts.root;60+61+ if (!this.ext && !this.defaultEngine) {62+ throw new Error('No default engine was specified and no extension was provided.');63+ }64+65+ var fileName = name;66+67+ if (!this.ext) {68+ // get extension from default engine name69+ this.ext = this.defaultEngine[0] !== '.'70+ ? '.' + this.defaultEngine71+ : this.defaultEngine;72+73+ fileName += this.ext;74+ }75+76+ if (!opts.engines[this.ext]) {77+ // load engine78+ opts.engines[this.ext] = require(this.ext.substr(1)).__express;79+ }80+81+ // store loaded engine82+ this.engine = opts.engines[this.ext];83+84+ // lookup path85+ this.path = this.lookup(fileName);86 }87 88 /**89 * Lookup view by the given `name`90 *57- * @param {String} name58- * @return {String}59- * @api private91+ * @param {string} name92+ * @private93 */94 95 View.prototype.lookup = function lookup(name) {96 var path;16 unmodified lines113 return path;114 };115 116 /**84- * Render with the given `options` and callback `fn(err, str)`.117+ * Render with the given options.118 *86- * @param {Object} options87- * @param {Function} fn88- * @api private119+ * @param {object} options120+ * @param {function} callback121+ * @private122 */123 91-View.prototype.render = function render(options, fn) {124+View.prototype.render = function render(options, callback) {125 debug('render "%s"', this.path);93- this.engine(this.path, options, fn);126+ this.engine(this.path, options, callback);127 };128 129 /**130 * Resolve the file within the given directory.4 unmodified lines135 */136 137 View.prototype.resolve = function resolve(dir, file) {138 var ext = this.ext;106- var path;107- var stat;139 140 // <path>.<ext>110- path = join(dir, file);111- stat = tryStat(path);141+ var path = join(dir, file);142+ var stat = tryStat(path);143 144 if (stat && stat.isFile()) {145 return path;146 }27 unmodified linesmodified:test/app.param.js+60 added
301 unmodified lines302 request(app)303 .get('/user/new')304 .expect('get.new', done);305 })306+307+ it('should not call when values differ on error', function(done) {308+ var app = express();309+ var called = 0;310+ var count = 0;311+312+ app.param('user', function(req, res, next, user) {313+ called++;314+ if (user === 'foo') throw new Error('err!');315+ req.user = user;316+ next();317+ });318+319+ app.get('/:user/bob', function(req, res, next) {320+ count++;321+ next();322+ });323+ app.get('/foo/:user', function(req, res, next) {324+ count++;325+ next();326+ });327+328+ app.use(function(err, req, res, next) {329+ res.status(500);330+ res.send([count, called, err.message].join(' '));331+ });332+333+ request(app)334+ .get('/foo/bob')335+ .expect(500, '0 1 err!', done)336+ });337+338+ it('should call when values differ when using "next"', function(done) {339+ var app = express();340+ var called = 0;341+ var count = 0;342+343+ app.param('user', function(req, res, next, user) {344+ called++;345+ if (user === 'foo') return next('route');346+ req.user = user;347+ next();348+ });349+350+ app.get('/:user/bob', function(req, res, next) {351+ count++;352+ next();353+ });354+ app.get('/foo/:user', function(req, res, next) {355+ count++;356+ next();357+ });358+ app.use(function(req, res) {359+ res.end([count, called, req.user].join(' '));360+ });361+362+ request(app)363+ .get('/foo/bob')364+ .expect('1 2 bob', done);365+ })366 })367 })modified:test/app.router.js+41 added
639 unmodified lines640 request(app)641 .get('/file')642 .expect(404, done);643 })644+645+ it('should keep correct parameter indexes', function(done){646+ var app = express();647+648+ app.get('/*/user/:id', function (req, res) {649+ res.send(req.params);650+ });651+652+ request(app)653+ .get('/1/user/2')654+ .expect(200, '{"0":"1","id":"2"}', done);655+ })656+657+ it('should work within arrays', function(done){658+ var app = express();659+660+ app.get(['/user/:id', '/foo/*', '/:bar'], function (req, res) {661+ res.send(req.params.bar);662+ });663+664+ request(app)665+ .get('/test')666+ .expect(200, 'test', done);667+ })668 })669 670 describe(':name', function(){671 it('should denote a capture group', function(done){31 unmodified lines703 .get('/user/tj/edit')704 .expect('editing tj', done);705 })706 707+ it('should work following a partial capture group', function(done){708+ var app = express();709+ var cb = after(2, done);710+711+ app.get('/user(s)?/:user/:op', function(req, res){712+ res.end(req.params.op + 'ing ' + req.params.user + (req.params[0] ? ' (old)' : ''));713+ });714+715+ request(app)716+ .get('/user/tj/edit')717+ .expect('editing tj', cb);718+719+ request(app)720+ .get('/users/tj/edit')721+ .expect('editing tj (old)', cb);722+ })723+724 it('should work in array of paths', function(done){725 var app = express();726 var cb = after(2, done);727 259 unmodified linesmodified:test/req.query.js+8 added
26 unmodified lines27 request(app)28 .get('/?user[name]=tj')29 .expect(200, '{"user":{"name":"tj"}}', done);30 });31+32+ it('should parse parameters with dots', function (done) {33+ var app = createApp('extended');34+35+ request(app)36+ .get('/?user.name=tj')37+ .expect(200, '{"user.name":"tj"}', done);38+ });39 });40 41 describe('when "query parser" is simple', function () {42 it('should not parse complex keys', function (done) {61 unmodified linesmodified:test/res.format.js+15 added
65 unmodified lines66 app4.use(function(err, req, res, next){67 res.send(err.status, 'Supports: ' + err.types.join(', '));68 })69 70+var app5 = express();71+72+app5.use(function (req, res, next) {73+ res.format({74+ default: function () { res.send('hey') }75+ });76+});77+78 describe('res', function(){79 describe('.format(obj)', function(){80 describe('with canonicalized mime types', function(){81 test(app1);27 unmodified lines109 .get('/')110 .set('Accept', 'text/html')111 .expect('default', done);112 })113+114+ it('should work when only .default is provided', function (done) {115+ request(app5)116+ .get('/')117+ .set('Accept', '*/*')118+ .expect('hey', done);119+ })120 })121 122 describe('in router', function(){123 test(app4);90 unmodified linesmodified:test/res.render.js+14 added
32 unmodified lines33 .get('/')34 .expect('<p>tobi</p>', done);35 })36 37+ it('should error without "view engine" set and no file extension', function (done) {38+ var app = createApp();39+40+ app.locals.user = { name: 'tobi' };41+42+ app.use(function(req, res){43+ res.render(__dirname + '/fixtures/user');44+ });45+46+ request(app)47+ .get('/')48+ .expect(500, /No default engine was specified/, done);49+ })50+51 it('should expose app.locals', function(done){52 var app = createApp();53 54 app.set('views', __dirname + '/fixtures');289 unmodified linesmodified:test/res.send.js+8 added-8 removed
105 unmodified lines106 });107 108 request(app)109 .get('/')110- .expect('ETag', 'W/"3e7-8084ccd1"')110+ .expect('ETag', 'W/"3e7-VYgCBglFKiDVAcpzPNt4Sg"')111 .expect(200, done);112 })113 114 it('should not override Content-Type', function(done){63 unmodified lines178 });179 180 request(app)181 .get('/')182- .expect('ETag', 'W/"3e7-8084ccd1"')182+ .expect('ETag', 'W/"3e7-VYgCBglFKiDVAcpzPNt4Sg"')183 .expect(200, done);184 })185 186 it('should not override Content-Type', function(done){155 unmodified lines342 app.enable('etag');343 344 request(app)345 .get('/')346- .expect('ETag', 'W/"c-5aee35d8"')346+ .expect('ETag', 'W/"c-ZUfd0NJ26qwjlKF4r8qb2g"')347 .expect(200, done);348 });349 350 methods.forEach(function (method) {7 unmodified lines358 });359 360 request(app)361 [method]('/')362- .expect('ETag', 'W/"c-5aee35d8"')362+ .expect('ETag', 'W/"c-ZUfd0NJ26qwjlKF4r8qb2g"')363 .expect(200, done);364 })365 });366 7 unmodified lines374 app.enable('etag');375 376 request(app)377 .get('/')378- .expect('ETag', 'W/"0-0"')378+ .expect('ETag', 'W/"0-1B2M2Y8AsgTpgAmY7PhCfg"')379 .expect(200, done);380 })381 382 it('should send ETag for long response', function (done) {7 unmodified lines390 app.enable('etag');391 392 request(app)393 .get('/')394- .expect('ETag', 'W/"3e7-8084ccd1"')394+ .expect('ETag', 'W/"3e7-VYgCBglFKiDVAcpzPNt4Sg"')395 .expect(200, done);396 });397 398 it('should not override ETag when manually set', function (done) {73 unmodified lines472 });473 474 request(app)475 .get('/')476- .expect('ETag', '"Otu60XkfuuPskIiUxJY4cA=="')476+ .expect('ETag', '"d-Otu60XkfuuPskIiUxJY4cA"')477 .expect(200, done);478 })479 })480 8 unmodified lines489 });490 491 request(app)492 .get('/')493- .expect('ETag', 'W/"d-58988d13"')493+ .expect('ETag', 'W/"d-Otu60XkfuuPskIiUxJY4cA"')494 .expect(200, done)495 })496 })497 47 unmodified linesmodified:test/utils.js+8 added-8 removed
3 unmodified lines4 5 describe('utils.etag(body, encoding)', function(){6 it('should support strings', function(){7 utils.etag('express!')8- .should.eql('"zZdv4imtWD49AHEviejT6A=="')8+ .should.eql('"8-zZdv4imtWD49AHEviejT6A"')9 })10 11 it('should support utf8 strings', function(){12 utils.etag('express❤', 'utf8')13- .should.eql('"fsFba4IxwQS6h6Umb+FNxw=="')13+ .should.eql('"a-fsFba4IxwQS6h6Umb+FNxw"')14 })15 16 it('should support buffer', function(){17 var buf = new Buffer('express!')18 utils.etag(buf)19- .should.eql('"zZdv4imtWD49AHEviejT6A=="');19+ .should.eql('"8-zZdv4imtWD49AHEviejT6A"');20 })21 22 it('should support empty string', function(){23 utils.etag('')24- .should.eql('"1B2M2Y8AsgTpgAmY7PhCfg=="');24+ .should.eql('"0-1B2M2Y8AsgTpgAmY7PhCfg"');25 })26 })27 28 describe('utils.setCharset(type, charset)', function () {20 unmodified lines49 50 describe('utils.wetag(body, encoding)', function(){51 it('should support strings', function(){52 utils.wetag('express!')53- .should.eql('W/"8-b8aabac7"')53+ .should.eql('W/"8-zZdv4imtWD49AHEviejT6A"')54 })55 56 it('should support utf8 strings', function(){57 utils.wetag('express❤', 'utf8')58- .should.eql('W/"a-686b0af1"')58+ .should.eql('W/"a-fsFba4IxwQS6h6Umb+FNxw"')59 })60 61 it('should support buffer', function(){62 var buf = new Buffer('express!')63 utils.wetag(buf)64- .should.eql('W/"8-b8aabac7"');64+ .should.eql('W/"8-zZdv4imtWD49AHEviejT6A"');65 })66 67 it('should support empty string', function(){68 utils.wetag('')69- .should.eql('W/"0-0"');69+ .should.eql('W/"0-1B2M2Y8AsgTpgAmY7PhCfg"');70 })71 })72 73 describe('utils.isAbsolute()', function(){22 unmodified linesmodified:.travis.yml+2 added
2 unmodified lines3 - "0.10"4 - "0.12"5 - "1.0"6 - "1.8"7+ - "2.0"8+ - "2.3"9 sudo: false10 before_install: "npm rm --save-dev connect-redis"11 script: "npm run-script test-ci"12 after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls"modified:appveyor.yml+2 added
2 unmodified lines3 - nodejs_version: "0.10"4 - nodejs_version: "0.12"5 - nodejs_version: "1.0"6 - nodejs_version: "1.8"7+ - nodejs_version: "2.0"8+ - nodejs_version: "2.3"9 install:10 - ps: Install-Product node $env:nodejs_version11 - npm rm --save-dev connect-redis12 - npm install6 unmodified linesmodified:History.md+166 added-4 removed
1 5.x2 ===3 4-This incorporates all changes after 4.10.1 up to 4.12.4.4+This incorporates all changes after 4.10.1 up to 4.13.1.5 6 5.0.0-alpha.1 / 2014-11-067 ==========================8 15 unmodified lines24 - `req.query` is now a getter instead of a plain property25 * add:26 - `app.router` is a reference to the base router27 28+4.13.1 / 2015-07-0529+===================30+31+ * deps: accepts@~1.2.1032+ - deps: mime-types@~2.1.233+ * deps: qs@4.0.034+ - Fix dropping parameters like `hasOwnProperty`35+ - Fix various parsing edge cases36+ * deps: type-is@~1.6.437+ - deps: mime-types@~2.1.238+ - perf: enable strict mode39+ - perf: remove argument reassignment40+41+4.13.0 / 2015-06-2042+===================43+44+ * Add settings to debug output45+ * Fix `res.format` error when only `default` provided46+ * Fix issue where `next('route')` in `app.param` would incorrectly skip values47+ * Fix hiding platform issues with `decodeURIComponent`48+ - Only `URIError`s are a 40049+ * Fix using `*` before params in routes50+ * Fix using capture groups before params in routes51+ * Simplify `res.cookie` to call `res.append`52+ * Use `array-flatten` module for flattening arrays53+ * deps: accepts@~1.2.954+ - deps: mime-types@~2.1.155+ - perf: avoid argument reassignment & argument slice56+ - perf: avoid negotiator recursive construction57+ - perf: enable strict mode58+ - perf: remove unnecessary bitwise operator59+ * deps: cookie@0.1.360+ - perf: deduce the scope of try-catch deopt61+ - perf: remove argument reassignments62+ * deps: escape-html@1.0.263+ * deps: etag@~1.7.064+ - Always include entity length in ETags for hash length extensions65+ - Generate non-Stats ETags using MD5 only (no longer CRC32)66+ - Improve stat performance by removing hashing67+ - Improve support for JXcore68+ - Remove base64 padding in ETags to shorten69+ - Support "fake" stats objects in environments without fs70+ - Use MD5 instead of MD4 in weak ETags over 1KB71+ * deps: finalhandler@0.4.072+ - Fix a false-positive when unpiping in Node.js 0.873+ - Support `statusCode` property on `Error` objects74+ - Use `unpipe` module for unpiping requests75+ - deps: escape-html@1.0.276+ - deps: on-finished@~2.3.077+ - perf: enable strict mode78+ - perf: remove argument reassignment79+ * deps: fresh@0.3.080+ - Add weak `ETag` matching support81+ * deps: on-finished@~2.3.082+ - Add defined behavior for HTTP `CONNECT` requests83+ - Add defined behavior for HTTP `Upgrade` requests84+ - deps: ee-first@1.1.185+ * deps: path-to-regexp@0.1.686+ * deps: send@0.13.087+ - Allow Node.js HTTP server to set `Date` response header88+ - Fix incorrectly removing `Content-Location` on 304 response89+ - Improve the default redirect response headers90+ - Send appropriate headers on default error response91+ - Use `http-errors` for standard emitted errors92+ - Use `statuses` instead of `http` module for status messages93+ - deps: escape-html@1.0.294+ - deps: etag@~1.7.095+ - deps: fresh@0.3.096+ - deps: on-finished@~2.3.097+ - perf: enable strict mode98+ - perf: remove unnecessary array allocations99+ * deps: serve-static@~1.10.0100+ - Add `fallthrough` option101+ - Fix reading options from options prototype102+ - Improve the default redirect response headers103+ - Malformed URLs now `next()` instead of 400104+ - deps: escape-html@1.0.2105+ - deps: send@0.13.0106+ - perf: enable strict mode107+ - perf: remove argument reassignment108+ * deps: type-is@~1.6.3109+ - deps: mime-types@~2.1.1110+ - perf: reduce try block size111+ - perf: remove bitwise operations112+ * perf: enable strict mode113+ * perf: isolate `app.render` try block114+ * perf: remove argument reassignments in application115+ * perf: remove argument reassignments in request prototype116+ * perf: remove argument reassignments in response prototype117+ * perf: remove argument reassignments in routing118+ * perf: remove argument reassignments in `View`119+ * perf: skip attempting to decode zero length string120+ * perf: use saved reference to `http.STATUS_CODES`121+122 4.12.4 / 2015-05-17123 ===================124 125 * deps: accepts@~1.2.7765 unmodified lines891 - `app.router()` - returns the app Router instance892 - `app.route()` - Proxy to the app's `Router#route()` method to create a new route893 - Router & Route - public API894 895+3.21.1 / 2015-07-05896+===================897+898+ * deps: basic-auth@~1.0.3899+ * deps: connect@2.30.1900+ - deps: body-parser@~1.13.2901+ - deps: compression@~1.5.1902+ - deps: errorhandler@~1.4.1903+ - deps: morgan@~1.6.1904+ - deps: pause@0.1.0905+ - deps: qs@4.0.0906+ - deps: serve-index@~1.7.1907+ - deps: type-is@~1.6.4908+909+3.21.0 / 2015-06-18910+===================911+912+ * deps: basic-auth@1.0.2913+ - perf: enable strict mode914+ - perf: hoist regular expression915+ - perf: parse with regular expressions916+ - perf: remove argument reassignment917+ * deps: connect@2.30.0918+ - deps: body-parser@~1.13.1919+ - deps: bytes@2.1.0920+ - deps: compression@~1.5.0921+ - deps: cookie@0.1.3922+ - deps: cookie-parser@~1.3.5923+ - deps: csurf@~1.8.3924+ - deps: errorhandler@~1.4.0925+ - deps: express-session@~1.11.3926+ - deps: finalhandler@0.4.0927+ - deps: fresh@0.3.0928+ - deps: morgan@~1.6.0929+ - deps: serve-favicon@~2.3.0930+ - deps: serve-index@~1.7.0931+ - deps: serve-static@~1.10.0932+ - deps: type-is@~1.6.3933+ * deps: cookie@0.1.3934+ - perf: deduce the scope of try-catch deopt935+ - perf: remove argument reassignments936+ * deps: escape-html@1.0.2937+ * deps: etag@~1.7.0938+ - Always include entity length in ETags for hash length extensions939+ - Generate non-Stats ETags using MD5 only (no longer CRC32)940+ - Improve stat performance by removing hashing941+ - Improve support for JXcore942+ - Remove base64 padding in ETags to shorten943+ - Support "fake" stats objects in environments without fs944+ - Use MD5 instead of MD4 in weak ETags over 1KB945+ * deps: fresh@0.3.0946+ - Add weak `ETag` matching support947+ * deps: mkdirp@0.5.1948+ - Work in global strict mode949+ * deps: send@0.13.0950+ - Allow Node.js HTTP server to set `Date` response header951+ - Fix incorrectly removing `Content-Location` on 304 response952+ - Improve the default redirect response headers953+ - Send appropriate headers on default error response954+ - Use `http-errors` for standard emitted errors955+ - Use `statuses` instead of `http` module for status messages956+ - deps: escape-html@1.0.2957+ - deps: etag@~1.7.0958+ - deps: fresh@0.3.0959+ - deps: on-finished@~2.3.0960+ - perf: enable strict mode961+ - perf: remove unnecessary array allocations962+963 3.20.3 / 2015-05-17964 ===================965 966 * deps: connect@2.29.2841 unmodified lines1808 * update connect1809 * update commander1810 * jsonp: check if callback is a function1811 * router: wrap encodeURIComponent in a try/catch #1735 (@lxe)1650- * res.format: now includes chraset @1747 (@sorribas)1812+ * res.format: now includes charset @1747 (@sorribas)1813 * res.links: allow multiple calls @1746 (@sorribas)1814 1815 3.4.0 / 2013-09-071816 ==================270 unmodified lines2087 * Added hogan `--hjs` to express(1) [nullfirm]2088 * Added another example to content-negotiation2089 * Added `fresh` dep2090 * Changed: `res.send()` always checks freshness1929- * Fixed: expose connects mime module. Cloases #11652091+ * Fixed: expose connects mime module. Closes #11652092 2093 3.0.0beta2 / 2012-06-062094 ==================2095 73 unmodified lines2169 * Added `req.path`2170 * Added `req.ips`2171 * Added `req.fresh`2172 * Added `req.stale`2011- * Added comma-delmited / array support for `req.accepts()`2173+ * Added comma-delimited / array support for `req.accepts()`2174 * Added debug instrumentation2175 * Added `res.set(obj)`2176 * Added `res.set(field, value)`2177 * Added `res.get(field)`841 unmodified linesmodified:index.js+9 added
1+/*!2+ * express3+ * Copyright(c) 2009-2013 TJ Holowaychuk4+ * Copyright(c) 2013 Roman Shtylman5+ * Copyright(c) 2014-2015 Douglas Christopher Wilson6+ * MIT Licensed7+ */8 9+'use strict';10+11 module.exports = require('./lib/express');modified:package.json+21 added-20 removed
25 unmodified lines26 "app",27 "api"28 ],29 "dependencies": {30- "accepts": "~1.2.7",30+ "accepts": "~1.2.10",31+ "array-flatten": "1.1.0",32 "content-disposition": "0.5.0",33 "content-type": "~1.0.1",33- "cookie": "0.1.2",34+ "cookie": "0.1.3",35 "cookie-signature": "1.0.6",36 "debug": "~2.2.0",37 "depd": "~1.0.1",37- "escape-html": "1.0.1",38- "etag": "~1.6.0",39- "finalhandler": "0.3.6",40- "fresh": "0.2.4",38+ "escape-html": "1.0.2",39+ "etag": "~1.7.0",40+ "finalhandler": "0.4.0",41+ "fresh": "0.3.0",42 "merge-descriptors": "1.0.0",43 "methods": "~1.1.1",43- "on-finished": "~2.2.1",44+ "on-finished": "~2.3.0",45 "parseurl": "~1.3.0",45- "path-to-regexp": "0.1.3",46+ "path-to-regexp": "0.1.6",47 "proxy-addr": "~1.0.8",47- "qs": "2.4.2",48+ "qs": "4.0.0",49 "range-parser": "~1.0.2",49- "send": "0.12.3",50- "serve-static": "~1.9.3",51- "type-is": "~1.6.2",50+ "send": "0.13.0",51+ "serve-static": "~1.10.0",52+ "type-is": "~1.6.4",53 "vary": "~1.0.0",54 "utils-merge": "1.0.0"55 },56 "devDependencies": {57 "after": "0.8.1",57- "ejs": "2.3.1",58+ "ejs": "2.3.2",59 "istanbul": "0.3.9",60 "marked": "0.3.3",61 "mocha": "2.2.5",61- "should": "6.0.1",62+ "should": "7.0.1",63 "supertest": "1.0.1",63- "body-parser": "~1.12.4",64+ "body-parser": "~1.13.2",65 "connect-redis": "~2.3.0",65- "cookie-parser": "~1.3.4",66- "cookie-session": "~1.1.0",67- "express-session": "~1.11.2",68- "jade": "~1.9.2",66+ "cookie-parser": "~1.3.5",67+ "cookie-session": "~1.2.0",68+ "express-session": "~1.11.3",69+ "jade": "~1.11.0",70 "method-override": "~2.3.3",70- "morgan": "~1.5.3",71+ "morgan": "~1.6.1",72 "multiparty": "~4.1.2",73 "vhost": "~3.0.0"74 },75 "engines": {16 unmodified lines