moved files from lib/express/* to lib/
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 42af4e4 · Browse files · 10 files·+1877 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+1877 added−2 removed
- tests:+2 added−2 removed
- other:+1875 added−0 removed
Provenance
- Commit
3d597a5- Tree
43eba5b- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
42af4e4
10 files changed+1877 added−2 removed
added:lib/view/partial.js+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
/*! * Express - view - Partial * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */
/** * Module dependencies. */
var View = require('./view') , basename = require('path').basename;
/** * Memory cache. */
var cache = {};
/** * Initialize a new `Partial` for the given `view` and `options`. * * @param {String} view * @param {Object} options * @api private */
var Partial = exports = module.exports = function Partial(view, options) { options = options || {}; View.call(this, view, options);};
/** * Inherit from `View.prototype`. */
Partial.prototype.__proto__ = View.prototype;
/** * Resolve partial object name from the view path. * * Examples: * * "user.ejs" becomes "user" * "forum thread.ejs" becomes "forumThread" * "forum/thread/post.ejs" becomes "post" * "blog-post.ejs" becomes "blogPost" * * @return {String} * @api private */
exports.resolveObjectName = function(view){ return cache[view] || (cache[view] = view .split('/') .slice(-1)[0] .split('.')[0] .replace(/^_/, '') .replace(/[^a-zA-Z0-9 ]+/g, ' ') .split(/ +/).map(function(word, i){ return i ? word[0].toUpperCase() + word.substr(1) : word; }).join(''));};No newline at end of fileadded:lib/view/view.js+197 added
1+2+/*!3+ * Express - View4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var utils = require('../utils')13+ , extname = utils.extname14+ , dirname = utils.dirname15+ , basename = utils.basename16+ , fs = require('fs')17+ , stat = fs.statSync;18+19+/**20+ * Memory cache.21+ */22+23+var cache = {};24+25+/**26+ * Existance cache.27+ */28+29+var exists = {};30+31+/**32+ * Initialize a new `View` with the given `view` path and `options`.33+ *34+ * @param {String} view35+ * @param {Object} options36+ * @api private37+ */38+39+var View = exports = module.exports = function View(view, options) {40+ options = options || {};41+ // TODO: more caching42+ this.view = view;43+ this.root = options.root;44+ this.relative = false !== options.relative;45+ this.defaultEngine = options.defaultEngine;46+ this.parent = options.parentView;47+ this.basename = basename(view);48+ this.engine = this.resolveEngine();49+ this.extension = '.' + this.engine;50+ this.path = this.resolvePath();51+ this.dirname = dirname(this.path);52+};53+54+/**55+ * Check if the view path exists.56+ *57+ * @return {Boolean}58+ * @api public59+ */60+61+View.prototype.__defineGetter__('exists', function(){62+ var path = this.path;63+ if (null != exists[path]) {64+ return exists[path];65+ } else {66+ try {67+ stat(path);68+ return exists[path] = true;69+ } catch (err) {70+ return exists[path] = false;71+ }72+ }73+});74+75+/**76+ * Resolve view engine.77+ *78+ * @return {String}79+ * @api private80+ */81+82+View.prototype.resolveEngine = function(){83+ // Explicit84+ if (~this.basename.indexOf('.')) return extname(this.basename).substr(1);85+ // Inherit from parent86+ if (this.parent) return this.parent.engine;87+ // Default88+ return this.defaultEngine;89+};90+91+/**92+ * Resolve view path.93+ *94+ * @return {String}95+ * @api private96+ */97+98+View.prototype.resolvePath = function(){99+ var path = this.view;100+ // Implicit engine101+ if (!~this.basename.indexOf('.')) path += this.extension;102+ // Absolute103+ if ('/' == path[0]) return path;104+ // Relative to parent105+ if (this.relative && this.parent) return this.parent.dirname + '/' + path;106+ // Relative to root107+ return this.root108+ ? this.root + '/' + path109+ : path;110+};111+112+/**113+ * Get view contents. This is a one-time hit, so we114+ * can afford to be sync.115+ *116+ * @return {String}117+ * @api public118+ */119+120+View.prototype.__defineGetter__('contents', function(){121+ return fs.readFileSync(this.path, 'utf8');122+});123+124+/**125+ * Get template engine api, cache exports to reduce126+ * require() calls.127+ *128+ * @return {Object}129+ * @api public130+ */131+132+View.prototype.__defineGetter__('templateEngine', function(){133+ var ext = this.extension;134+ return cache[ext] || (cache[ext] = require(this.engine));135+});136+137+/**138+ * Return index path alternative.139+ *140+ * @return {String}141+ * @api public142+ */143+144+View.prototype.__defineGetter__('indexPath', function(){145+ return this.dirname146+ + '/' + this.basename.replace(this.extension, '')147+ + '/index' + this.extension;148+});149+150+/**151+ * Return _ prefix path alternative152+ *153+ * @return {String}154+ * @api public155+ */156+157+View.prototype.__defineGetter__('prefixPath', function(){158+ return this.dirname + '/_' + this.basename;159+});160+161+/**162+ * Register the given template engine `exports`163+ * as `ext`. For example we may wish to map ".html"164+ * files to jade:165+ *166+ * app.register('.html', require('jade'));167+ *168+ * or169+ *170+ * app.register('html', require('jade'));171+ *172+ * This is also useful for libraries that may not173+ * match extensions correctly. For example my haml.js174+ * library is installed from npm as "hamljs" so instead175+ * of layout.hamljs, we can register the engine as ".haml":176+ *177+ * app.register('.haml', require('haml-js'));178+ *179+ * For engines that do not comply with the Express180+ * specification, we can also wrap their api this way.181+ *182+ * app.register('.foo', {183+ * render: function(str, options) {184+ * // perhaps their api is185+ * // return foo.toHTML(str, options);186+ * }187+ * });188+ *189+ * @param {String} ext190+ * @param {Object} obj191+ * @api public192+ */193+194+exports.register = function(ext, exports) {195+ if ('.' != ext[0]) ext = '.' + ext;196+ cache[ext] = exports;197+};added:lib/express.js+58 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
/*! * Express * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */
/** * Re-export connect auto-loaders. * * This prevents the need to `require('connect')` in order * to access core middleware, so for example `express.logger()` instead * of `require('connect').logger()`. */
var exports = module.exports = require('connect').middleware;
/** * Framework version. */
exports.version = '2.0.0-pre';
/** * Module dependencies. */
var Server = exports.Server = require('./server');
/** * Shortcut for `new Server(...)`. * * @param {Function} ... * @return {Server} * @api public */
exports.createServer = function(){ return new Server(Array.prototype.slice.call(arguments));};
/** * View extensions. */
require('./view');
/** * Response extensions. */
require('./response');
/** * Request extensions. */
require('./request');added:lib/request.js+277 added
1+2+/*!3+ * Express - request4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var http = require('http')13+ , utils = require('./utils')14+ , mime = require('connect').utils.mime;15+16+/**17+ * Default flash formatters.18+ *19+ * @type Object20+ */21+22+var flashFormatters = exports.flashFormatters = {23+ s: function(val){24+ return String(val);25+ }26+};27+28+/**29+ * Return request header or optional default.30+ *31+ * Examples:32+ *33+ * req.header('Content-Type');34+ * // => "text/plain"35+ * 36+ * req.header('content-type');37+ * // => "text/plain"38+ * 39+ * req.header('Accept');40+ * // => undefined41+ * 42+ * req.header('Accept', 'text/html');43+ * // => "text/html"44+ *45+ * @param {String} name46+ * @param {String} defaultValue47+ * @return {String} 48+ * @api public49+ */50+51+http.IncomingMessage.prototype.header = function(name, defaultValue){52+ return this.headers[name.toLowerCase()] || defaultValue;53+};54+55+/**56+ * Check if the _Accept_ header is present, and includes the given `type`.57+ *58+ * When the _Accept_ header is not present `true` is returned. Otherwise59+ * the given `type` is matched by an exact match, and then subtypes. You60+ * may pass the subtype such as "html" which is then converted internally61+ * to "text/html" using the mime lookup table.62+ *63+ * Examples:64+ * 65+ * // Accept: text/html66+ * req.accepts('html');67+ * // => true68+ *69+ * // Accept: text/*; application/json70+ * req.accepts('html');71+ * req.accepts('text/html');72+ * req.accepts('text/plain');73+ * req.accepts('application/json');74+ * // => true75+ *76+ * req.accepts('image/png');77+ * req.accepts('png');78+ * // => false79+ *80+ * @param {String} type81+ * @return {Boolean}82+ * @api public83+ */84+85+http.IncomingMessage.prototype.accepts = function(type){86+ var accept = this.header('Accept');87+88+ // Normalize extensions ".json" -> "json"89+ if (type && '.' == type[0]) type = type.substr(1);90+91+ // When Accept does not exist, or is '*/*' return true 92+ if (!accept || '*/*' == accept) {93+ return true;94+ } else if (type) {95+ // Allow "html" vs "text/html" etc96+ if (type.indexOf('/') < 0) {97+ type = mime.types['.' + type];98+ }99+100+ // Check if we have a direct match101+ if (~accept.indexOf(type)) return true;102+103+ // Check if we have type/*104+ type = type.split('/')[0] + '/*';105+ return accept.indexOf(type) >= 0;106+ } else {107+ return false;108+ }109+};110+111+/**112+ * Return the value of param `name` when present or `defaultValue`.113+ *114+ * - Checks route placeholders, ex: _/user/:id_115+ * - Checks query string params, ex: ?id=12116+ * - Checks urlencoded body params, ex: id=12117+ *118+ * To utilize urlencoded request bodies, `req.body`119+ * should be an object. This can be done by using120+ * the `connect.bodyDecoder` middleware.121+ *122+ * @param {String} name123+ * @param {Mixed} defaultValue124+ * @return {String}125+ * @api public126+ */127+128+http.IncomingMessage.prototype.param = function(name, defaultValue){129+ // Route params like /user/:id130+ if (this.params[name] !== undefined) {131+ return this.params[name]; 132+ }133+ // Query string params134+ if (this.query[name] !== undefined) {135+ return this.query[name]; 136+ }137+ // Request body params via connect.bodyDecoder138+ if (this.body && this.body[name] !== undefined) {139+ return this.body[name];140+ }141+ return defaultValue;142+};143+144+/**145+ * Queue flash `msg` of the given `type`.146+ *147+ * Examples:148+ *149+ * req.flash('info', 'email sent');150+ * req.flash('error', 'email delivery failed');151+ * req.flash('info', 'email re-sent');152+ * // => 2153+ *154+ * req.flash('info');155+ * // => ['email sent', 'email re-sent']156+ *157+ * req.flash('info');158+ * // => []159+ *160+ * req.flash();161+ * // => { error: ['email delivery failed'], info: [] }162+ *163+ * Formatting:164+ *165+ * Flash notifications also support arbitrary formatting support.166+ * For example you may pass variable arguments to `req.flash()`167+ * and use the %s specifier to be replaced by the associated argument:168+ *169+ * req.flash('info', 'email has been sent to %s.', userName);170+ *171+ * To add custom formatters use the `exports.flashFormatters` object.172+ *173+ * @param {String} type174+ * @param {String} msg175+ * @return {Array|Object|Number}176+ * @api public177+ */178+179+http.IncomingMessage.prototype.flash = function(type, msg){180+ var msgs = this.session.flash = this.session.flash || {};181+ if (type && msg) {182+ var i = 2183+ , args = arguments184+ , formatters = this.app.flashFormatters || {};185+ formatters.__proto__ = flashFormatters;186+ msg = utils.miniMarkdown(utils.htmlEscape(msg));187+ msg = msg.replace(/%([a-zA-Z])/g, function(_, format){188+ var formatter = formatters[format];189+ if (formatter) return formatter(args[i++]);190+ });191+ return (msgs[type] = msgs[type] || []).push(msg);192+ } else if (type) {193+ var arr = msgs[type];194+ delete msgs[type];195+ return arr || [];196+ } else {197+ this.session.flash = {};198+ return msgs;199+ }200+};201+202+/**203+ * Check if the incoming request contains the "Content-Type" 204+ * header field, and it contains the give mime `type`.205+ *206+ * Examples:207+ *208+ * // With Content-Type: text/html; charset=utf-8209+ * req.is('html');210+ * req.is('text/html');211+ * // => true212+ * 213+ * // When Content-Type is application/json214+ * req.is('json');215+ * req.is('application/json');216+ * // => true217+ * 218+ * req.is('html');219+ * // => false220+ * 221+ * Ad-hoc callbacks can also be registered with Express, to perform222+ * assertions again the request, for example if we need an expressive223+ * way to check if our incoming request is an image, we can register "an image"224+ * callback:225+ * 226+ * app.is('an image', function(req){227+ * return 0 == req.headers['content-type'].indexOf('image');228+ * });229+ * 230+ * Now within our route callbacks, we can use to to assert content types231+ * such as "image/jpeg", "image/png", etc.232+ * 233+ * app.post('/image/upload', function(req, res, next){234+ * if (req.is('an image')) {235+ * // do something236+ * } else {237+ * next();238+ * }239+ * });240+ * 241+ * @param {String} type242+ * @return {Boolean}243+ * @api public244+ */245+246+http.IncomingMessage.prototype.is = function(type){247+ var fn = this.app.is(type);248+ if (fn) return fn(this);249+ var contentType = this.headers['content-type'];250+ if (!contentType) return;251+ if (!~type.indexOf('/')) type = mime.type('.' + type);252+ // TODO: remove when connect no longer appends charset...253+ if (~type.indexOf(';')) type = type.split(';')[0];254+ if (~type.indexOf('*')) {255+ type = type.split('/')256+ contentType = contentType.split('/');257+ if ('*' == type[0] && type[1] == contentType[1]) return true;258+ if ('*' == type[1] && type[0] == contentType[0]) return true;259+ }260+ return ~contentType.indexOf(type);261+};262+263+// Callback for isXMLHttpRequest / xhr264+265+function isxhr() {266+ return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';267+}268+269+/**270+ * Check if the request was an _XMLHttpRequest_.271+ *272+ * @return {Boolean}273+ * @api public274+ */275+276+http.IncomingMessage.prototype.__defineGetter__('isXMLHttpRequest', isxhr);277+http.IncomingMessage.prototype.__defineGetter__('xhr', isxhr);added:lib/response.js+390 added
1+2+/*!3+ * Express - response4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var fs = require('fs')13+ , http = require('http')14+ , path = require('path')15+ , pump = require('sys').pump16+ , utils = require('connect').utils17+ , parseRange = require('./utils').parseRange18+ , mime = utils.mime;19+20+/**21+ * Header fields supporting multiple values.22+ * 23+ * @type Array24+ */25+26+var multiple = ['Set-Cookie'];27+28+/**29+ * Send a response with the given `body` and optional `headers` and `status` code.30+ *31+ * Examples:32+ *33+ * res.send();34+ * res.send(new Buffer('wahoo'));35+ * res.send({ some: 'json' });36+ * res.send('<p>some html</p>');37+ * res.send('Sorry, cant find that', 404);38+ * res.send('text', { 'Content-Type': 'text/plain' }, 201);39+ * res.send(404);40+ *41+ * @param {String|Object|Number|Buffer} body or status42+ * @param {Object|Number} headers or status43+ * @param {Number} status44+ * @return {ServerResponse}45+ * @api public46+ */47+48+http.ServerResponse.prototype.send = function(body, headers, status){49+ // Allow status as second arg50+ if (typeof headers === 'number') {51+ status = headers,52+ headers = null;53+ }54+55+ // Defaults56+ status = status || 200;57+58+ // Allow 0 args as 20459+ if (!arguments.length) {60+ body = status = 204;61+ }62+63+ // Determine content type64+ switch (typeof body) {65+ case 'number':66+ if (!this.headers['Content-Type']) {67+ this.contentType('.txt');68+ }69+ body = http.STATUS_CODES[status = body];70+ break;71+ case 'string':72+ if (!this.headers['Content-Type']) {73+ this.contentType('.html');74+ }75+ break;76+ case 'object':77+ if (body instanceof Buffer) {78+ if (!this.headers['Content-Type']) {79+ this.contentType('.bin');80+ }81+ } else {82+ if (!this.headers['Content-Type']) {83+ this.contentType('.json');84+ }85+ body = JSON.stringify(body);86+ if (this.req.query.callback && this.app.settings['jsonp callback']) {87+ this.header('Content-Type', 'text/javascript');88+ body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';89+ }90+ }91+ break;92+ }93+94+ // Populate Content-Length95+ if (!this.headers['Content-Length']) {96+ this.header('Content-Length', body instanceof Buffer97+ ? body.length98+ : Buffer.byteLength(body));99+ }100+101+ // Merge headers passed102+ if (headers) {103+ var fields = Object.keys(headers);104+ for (var i = 0, len = fields.length; i < len; ++i) {105+ var field = fields[i];106+ this.header(field, headers[field]);107+ }108+ }109+110+ // Strip irrelevant headers111+ if (204 === status) {112+ delete this.headers['Content-Type'];113+ delete this.headers['Content-Length'];114+ }115+116+ // Respond117+ this.writeHead(status, this.headers);118+ this.end('HEAD' == this.req.method ? undefined : body);119+};120+121+/**122+ * Transfer the file at the given `path`. Automatically sets 123+ * the _Content-Type_ response header via `res.contentType()`. 124+ *125+ * Accepts an optional callback `fn(err, path)`.126+ *127+ * @param {String} path128+ * @param {Function} fn129+ * @api public130+ */131+132+http.ServerResponse.prototype.sendfile = function(path, fn){133+ var self = this134+ , ranges = self.req.headers.range135+ , head = 'HEAD' == self.req.method;136+137+ if (~path.indexOf('..')) return this.send(403);138+139+ function error(err) {140+ delete self.headers['Content-Disposition'];141+ if (fn) {142+ fn(err, path);143+ } else {144+ self.req.next(err);145+ }146+ }147+148+ fs.stat(path, function(err, stat){149+ if (err) return error(err);150+ var status = 200;151+152+ // We have a Range request153+ if (ranges) {154+ ranges = parseRange(stat.size, ranges);155+ // Valid156+ if (ranges) {157+ var stream = fs.createReadStream(path, ranges[0])158+ , start = ranges[0].start159+ , end = ranges[0].end;160+ status = 206;161+ self.header('Content-Range', 'bytes '162+ + start163+ + '-'164+ + end165+ + '/'166+ + stat.size);167+ // Invalid168+ } else {169+ return self.send(416);170+ }171+ // Stream the entire file172+ } else {173+ var stream = fs.createReadStream(path);174+ self.header('Content-Length', stat.size);175+ }176+177+ // Transfer178+ self.contentType(path);179+ self.header('Accept-Ranges', 'bytes');180+ self.writeHead(status, self.headers);181+ if (head) return self.end();182+ pump(stream, self);183+ });184+};185+186+/**187+ * Set _Content-Type_ response header passed through `mime.type()`.188+ *189+ * Examples:190+ *191+ * var filename = 'path/to/image.png';192+ * res.contentType(filename);193+ * // res.headers['Content-Type'] is now "image/png"194+ *195+ * res.contentType('.html');196+ * res.contentType('html');197+ * res.contentType('json');198+ * res.contentType('png');199+ *200+ * @param {String} type201+ * @return {String} the resolved mime type202+ * @api public203+ */204+205+http.ServerResponse.prototype.contentType = function(type){206+ if (!~type.indexOf('.')) type = '.' + type;207+ return this.header('Content-Type', mime.type(type));208+};209+210+/**211+ * Set _Content-Disposition_ header to _attachment_ with optional `filename`.212+ *213+ * @param {String} filename214+ * @return {ServerResponse}215+ * @api public216+ */217+218+http.ServerResponse.prototype.attachment = function(filename){219+ this.header('Content-Disposition', filename220+ ? 'attachment; filename="' + path.basename(filename) + '"'221+ : 'attachment');222+ return this;223+};224+225+/**226+ * Transfer the file at the given `path`, with optional 227+ * `filename` as an attachment. Once transferred, or if an228+ * error occurs `fn` is called with the error and path.229+ *230+ * @param {String} path231+ * @param {String} filename232+ * @param {Function} fn233+ * @return {Type}234+ * @api public235+ */236+237+http.ServerResponse.prototype.download = function(path, filename, fn){238+ this.attachment(filename || path).sendfile(path, fn);239+};240+241+/**242+ * Set or get response header `name` with optional `val`.243+ *244+ * Headers that may be set multiple times (as indicated by the `multiple` array)245+ * can be called with a value several times, for example:246+ *247+ * res.header('Set-Cookie', '...');248+ * res.header('Set-Cookie', '...');249+ *250+ * @param {String} name251+ * @param {String} val252+ * @return {String}253+ * @api public254+ */255+256+http.ServerResponse.prototype.header = function(name, val){257+ if (val === undefined) {258+ return this.headers[name];259+ } else {260+ if (this.headers[name] && ~multiple.indexOf(name)) {261+ return this.headers[name] += '\r\n' + name + ': ' + val;262+ } else {263+ return this.headers[name] = val;264+ }265+ }266+};267+268+/**269+ * Clear cookie `name`.270+ *271+ * @param {String} name272+ * @api public273+ */274+275+http.ServerResponse.prototype.clearCookie = function(name){276+ this.cookie(name, '', { expires: new Date(1) });277+};278+279+/**280+ * Set cookie `name` to `val`.281+ *282+ * Examples:283+ *284+ * // "Remember Me" for 15 minutes285+ * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });286+ *287+ * @param {String} name288+ * @param {String} val289+ * @param {Options} options290+ * @api public291+ */292+293+http.ServerResponse.prototype.cookie = function(name, val, options){294+ var cookie = utils.serializeCookie(name, val, options);295+ this.header('Set-Cookie', cookie);296+};297+298+/**299+ * Redirect to the given `url` with optional response `status`300+ * defauling to 302.301+ *302+ * The given `url` can also be the name of a mapped url, for303+ * example by default express supports "back" which redirects304+ * to the _Referrer_ or _Referer_ headers or the application's305+ * "home" setting. Express also supports "home" out of the box,306+ * which can be set via `app.set('home', '/blog');`, and defaults307+ * to '/'.308+ *309+ * Redirect Mapping:310+ * 311+ * To extend the redirect mapping capabilities that Express provides,312+ * we may use the `app.redirect()` method:313+ * 314+ * app.redirect('google', 'http://google.com');315+ * 316+ * Now in a route we may call:317+ *318+ * res.redirect('google');319+ *320+ * We may also map dynamic redirects:321+ *322+ * app.redirect('comments', function(req, res){323+ * return '/post/' + req.params.id + '/comments';324+ * });325+ *326+ * So now we may do the following, and the redirect will dynamically adjust to327+ * the context of the request. If we called this route with _GET /post/12_ our328+ * redirect _Location_ would be _/post/12/comments_.329+ *330+ * app.get('/post/:id', function(req, res){331+ * res.redirect('comments');332+ * });333+ *334+ * @param {String} url335+ * @param {Number} code336+ * @api public337+ */338+339+http.ServerResponse.prototype.redirect = function(url, status){340+ var basePath = this.app.set('home') || '/'341+ , status = status || 302342+ , body;343+344+ // Setup redirect map345+ var map = {346+ back: this.req.headers.referrer || this.req.headers.referer || basePath,347+ home: basePath348+ };349+350+ // Support custom redirect map351+ map.__proto__ = this.app.redirects;352+353+ // Attempt mapped redirect354+ var mapped = typeof map[url] === 'function'355+ ? map[url](this.req, this)356+ : map[url];357+358+ // Perform redirect359+ url = mapped || url;360+361+ // Support text/{plain,html} by default362+ if (this.req.accepts('html')) {363+ body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';364+ this.header('Content-Type', 'text/html');365+ } else {366+ body = http.STATUS_CODES[status] + '. Redirecting to ' + url;367+ this.header('Content-Type', 'text/plain');368+ }369+370+ // Respond371+ this.send(body, { Location: url }, status);372+};373+374+/**375+ * Assign the view local variable `name` to `val` or return the376+ * local previously assigned to `name`.377+ *378+ * @param {String} name379+ * @param {Mixed} val380+ * @return {Mixed} val381+ * @api public382+ */383+384+http.ServerResponse.prototype.local = function(name, val){385+ this.locals = this.locals || {};386+ return undefined === val387+ ? this.locals[name]388+ : this.locals[name] = val;389+};390+added:lib/server.js+459 added
1+2+/*!3+ * Express - Server4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var url = require('url')13+ , view = require('./view')14+ , connect = require('connect')15+ , utils = connect.utils16+ , queryString = require('querystring')17+ , router = require('connect').router18+ , methods = router.methods.concat(['del', 'all']);19+20+/**21+ * Initialize a new `Server` with optional `middleware`.22+ *23+ * @param {Array} middleware24+ * @api public25+ */26+27+var Server = exports = module.exports = function Server(middleware){28+ var self = this;29+ this.config = {};30+ this.settings = {};31+ this.redirects = {};32+ this.isCallbacks = {};33+ this.viewHelpers = {};34+ this.dynamicViewHelpers = {};35+ this.errorHandlers = [];36+ connect.Server.call(this, []);37+38+ // Default "home" to / 39+ this.set('home', '/');40+41+ // Set "env" to NODE_ENV, defaulting to "development"42+ this.set('env', process.env.NODE_ENV || 'development');43+44+ // Expose objects to each other45+ this.use(function(req, res, next){46+ req.query = {};47+ res.headers = { 'X-Powered-By': 'Express' };48+ req.app = res.app = self;49+ req.res = res;50+ res.req = req;51+ req.next = next;52+ // Assign req.params.get53+ if (req.url.indexOf('?') > 0) {54+ var query = url.parse(req.url).query;55+ req.query = exports.parseQueryString(query);56+ }57+ next();58+ });59+60+ // Apply middleware61+ if (middleware) {62+ middleware.forEach(function(fn){63+ self.use(fn);64+ });65+ }66+67+ // Use router, expose as app.get(), etc68+ var fn = router(function(app){ self.routes = app; });69+ this.__defineGetter__('router', function(){70+ this.__usedRouter = true;71+ return fn;72+ });73+74+ // Default production configuration75+ this.configure('production', function(){76+ this.enable('cache views');77+ });78+};79+80+/**81+ * Inherit from `connect.Server`.82+ */83+84+Server.prototype.__proto__ = connect.Server.prototype;85+86+/**87+ * Support swappable querystring parsers.88+ */89+90+exports.parseQueryString = queryString.parse;91+92+/**93+ * Proxy in order to register error handlers.94+ */95+96+Server.prototype.listen = function(){97+ this.registerErrorHandlers();98+ connect.Server.prototype.listen.apply(this, arguments);99+};100+101+/**102+ * Proxy in order to register error handlers.103+ */104+105+Server.prototype.listenFD = function(){106+ this.registerErrorHandlers();107+ connect.Server.prototype.listenFD.apply(this, arguments);108+};109+110+/**111+ * When using the vhost() middleware register error handlers.112+ */113+114+Server.prototype.onvhost = function(){115+ this.registerErrorHandlers();116+};117+118+/**119+ * Register error handlers. This is automatically120+ * called from within `Server#listen()` and `Server#listenFD()`.121+ *122+ * @return {Server} for chaining123+ * @api public124+ */125+126+Server.prototype.registerErrorHandlers = function(){127+ this.errorHandlers.forEach(function(fn){128+ this.use(function(err, req, res, next){129+ fn.apply(this, arguments);130+ });131+ }, this);132+ return this;133+};134+135+/**136+ * Proxy `connect.Server#use()` to apply settings to137+ * mounted applications.138+ *139+ * @param {String|Function|Server} route140+ * @param {Function|Server} middleware141+ * @return {Server} for chaining142+ * @api public143+ */144+145+Server.prototype.use = function(route, middleware){146+ if (typeof route !== 'string') {147+ middleware = route, route = '/';148+ }149+150+ connect.Server.prototype.use.call(this, route, middleware);151+152+ // Mounted an app153+ if (middleware instanceof Server) {154+ // Home is /:route/:home155+ var app = middleware156+ , home = app.set('home');157+ if (home === '/') home = '';158+ app.set('home', (app.route || '') + home);159+ app.parent = this;160+ // Mounted hook161+ if (app.__mounted) app.__mounted.call(app, this);162+ }163+164+ return this;165+};166+167+/**168+ * Assign a callback `fn` which is called169+ * when this `Server` is passed to `Server#use()`.170+ *171+ * Examples:172+ *173+ * var app = express.createServer(),174+ * blog = express.createServer();175+ *176+ * blog.mounted(function(parent){177+ * // parent is app178+ * // "this" is blog179+ * });180+ *181+ * app.use(blog);182+ *183+ * @param {Function} fn184+ * @return {Server} for chaining185+ * @api public186+ */187+188+Server.prototype.mounted = function(fn){189+ this.__mounted = fn;190+ return this;191+};192+193+/**194+ * See: view.register.195+ *196+ * @return {Server} for chaining197+ * @api public198+ */199+200+Server.prototype.register = function(){201+ view.register.apply(this, arguments);202+ return this;203+};204+205+/**206+ * Register the given view helpers `obj`. This method207+ * can be called several times to apply additional helpers.208+ *209+ * @param {Object} obj210+ * @return {Server} for chaining211+ * @api public212+ */213+214+Server.prototype.helpers = 215+Server.prototype.locals = function(obj){216+ utils.merge(this.viewHelpers, obj);217+ return this;218+};219+220+/**221+ * Register the given dynamic view helpers `obj`. This method222+ * can be called several times to apply additional helpers.223+ *224+ * @param {Object} obj225+ * @return {Server} for chaining226+ * @api public227+ */228+229+Server.prototype.dynamicHelpers = function(obj){230+ utils.merge(this.dynamicViewHelpers, obj);231+ return this;232+};233+234+/**235+ * Map the given param placeholder `name`(s) to the given callback `fn`.236+ *237+ * Param mapping is used to provide pre-conditions to routes238+ * which us normalized placeholders. For example ":user_id" may239+ * attempt to load the user from the database, where as ":num" may 240+ * pass the value through `parseInt(num, 10)`.241+ *242+ * When the callback function accepts only a single argument, the243+ * value of placeholder is passed:244+ *245+ * app.param('page', function(n){ return parseInt(n, 10); });246+ *247+ * After which "/users/:page" would automatically provide us with248+ * an integer for `req.params.page`. If desired we could use the callback 249+ * signature shown below, and immediately `next(new Error('invalid page'))`250+ * when `parseInt` fails.251+ *252+ * Alternatively the callback may accept the request, response, next, and253+ * the value, acting like middlware:254+ *255+ * app.param('userId', function(req, res, next, id){256+ * User.find(id, function(err, user){257+ * if (err) {258+ * next(err);259+ * } else if (user) {260+ * req.user = user;261+ * next();262+ * } else {263+ * next(new Error('failed to load user'));264+ * }265+ * });266+ * });267+ *268+ * Now every time ":userId" is present, the associated user object269+ * will be loaded and assigned before the route handler is invoked.270+ *271+ * @param {String|Array} name272+ * @param {Function} fn273+ * @return {Server} for chaining274+ * @api public275+ */276+277+Server.prototype.param = function(name, fn){278+ if (Array.isArray(name)) {279+ name.forEach(function(name){280+ this.param(name, fn);281+ }, this);282+ } else {283+ if (':' == name[0]) name = name.substr(1);284+ this.routes.param(name, fn);285+ }286+ return this;287+};288+289+/**290+ * Assign a custom exception handler callback `fn`.291+ * These handlers are always _last_ in the middleware stack.292+ *293+ * @param {Function} fn294+ * @return {Server} for chaining295+ * @api public296+ */297+298+Server.prototype.error = function(fn){299+ this.errorHandlers.push(fn);300+ return this;301+};302+303+/**304+ * Register the given callback `fn` for the given `type`.305+ *306+ * @param {String} type307+ * @param {Function} fn308+ * @return {Server} for chaining309+ * @api public310+ */311+312+Server.prototype.is = function(type, fn){313+ if (!fn) return this.isCallbacks[type];314+ this.isCallbacks[type] = fn;315+ return this;316+};317+318+/**319+ * Assign `setting` to `val`, or return `setting`'s value.320+ * Mounted servers inherit their parent server's settings.321+ *322+ * @param {String} setting323+ * @param {String} val324+ * @return {Server|Mixed} for chaining, or the setting value325+ * @api public326+ */327+328+Server.prototype.set = function(setting, val){329+ if (val === undefined) {330+ if (this.settings.hasOwnProperty(setting)) {331+ return this.settings[setting];332+ } else if (this.parent) {333+ return this.parent.set(setting);334+ }335+ } else {336+ this.settings[setting] = val;337+ return this;338+ }339+};340+341+/**342+ * Check if `setting` is enabled.343+ *344+ * @param {String} setting345+ * @return {Boolean}346+ * @api public347+ */348+349+Server.prototype.enabled = function(setting){350+ return !!this.set(setting);351+};352+353+/**354+ * Check if `setting` is disabled.355+ *356+ * @param {String} setting357+ * @return {Boolean}358+ * @api public359+ */360+361+Server.prototype.disabled = function(setting){362+ return !this.set(setting);363+};364+365+/**366+ * Enable `setting`.367+ *368+ * @param {String} setting369+ * @return {Server} for chaining370+ * @api public371+ */372+373+Server.prototype.enable = function(setting){374+ return this.set(setting, true);375+};376+377+/**378+ * Disable `setting`.379+ *380+ * @param {String} setting381+ * @return {Server} for chaining382+ * @api public383+ */384+385+Server.prototype.disable = function(setting){386+ return this.set(setting, false);387+};388+389+/**390+ * Redirect `key` to `url`.391+ *392+ * @param {String} key393+ * @param {String} url394+ * @return {Server} for chaining395+ * @api public396+ */397+398+Server.prototype.redirect = function(key, url){399+ this.redirects[key] = url;400+ return this;401+};402+403+/**404+ * Configure callback for the given `env`.405+ *406+ * @param {String} env407+ * @param {Function} fn408+ * @return {Server} for chaining409+ * @api public410+ */411+412+Server.prototype.configure = function(env, fn){413+ if (typeof env === 'function') {414+ fn = env, env = 'all';415+ }416+ if ('all' == env || env == this.settings.env) {417+ fn.call(this);418+ }419+ return this;420+};421+422+// Generate routing methods423+424+function generateMethod(method){425+ Server.prototype[method] = function(path, fn){426+ var self = this;427+428+ // Ensure router is mounted429+ if (!this.__usedRouter) {430+ this.use(this.router);431+ }432+433+ // Route specific middleware support434+ if (arguments.length > 2) {435+ var args = Array.prototype.slice.call(arguments, 1);436+ fn = args.pop();437+ (function stack(middleware){438+ middleware.forEach(function(fn){439+ if (Array.isArray(fn)) {440+ stack(fn);441+ } else {442+ self[method](path, fn);443+ }444+ });445+ })(args);446+ }447+448+ // Generate the route449+ this.routes[method](path, fn);450+ return this;451+ };452+ return arguments.callee;453+}454+455+methods.forEach(generateMethod);456+457+// Alias delete as "del"458+459+Server.prototype.del = Server.prototype.delete;added:lib/utils.js+150 added
1+2+/*!3+ * Express - Utils4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var path = require('path')13+ , basename = path.basename14+ , dirname = path.dirname15+ , extname = path.extname;16+17+/**18+ * Memory cache.19+ */20+21+var cache = {22+ basename: {}23+ , dirname: {}24+ , extname: {}25+};26+27+/**28+ * Cached basename.29+ *30+ * @param {String} path31+ * @return {String}32+ * @api private33+ */34+35+exports.basename = function(path){36+ return cache.basename[path]37+ || (cache.basename[path] = basename(path));38+};39+40+/**41+ * Cached dirname.42+ *43+ * @param {String} path44+ * @return {String}45+ * @api private46+ */47+48+exports.dirname = function(path){49+ return cache.dirname[path]50+ || (cache.dirname[path] = dirname(path));51+};52+53+/**54+ * Cached extname.55+ *56+ * @param {String} path57+ * @return {String}58+ * @api private59+ */60+61+exports.extname = function(path){62+ return cache.extname[path]63+ || (cache.extname[path] = extname(path));64+};65+66+/**67+ * Parse mini markdown implementation.68+ * The following conversions are supported,69+ * primarily for the "flash" middleware:70+ *71+ * _foo_ or *foo* become <em>foo</em>72+ * __foo__ or **foo** become <strong>foo</strong>73+ * [A](B) becomes <a href="B">A</a>74+ *75+ * @param {String} str76+ * @return {String}77+ * @api private78+ */79+80+exports.miniMarkdown = function(str){81+ return String(str)82+ .replace(/(__|\*\*)(.*?)\1/g, '<strong>$2</strong>')83+ .replace(/(_|\*)(.*?)\1/g, '<em>$2</em>')84+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');85+};86+87+/**88+ * Escape special characters in the given string of html.89+ *90+ * @param {String} html91+ * @return {String}92+ * @api private93+ */94+95+exports.htmlEscape = function(html) {96+ return String(html)97+ .replace(/&/g, '&')98+ .replace(/"/g, '"')99+ .replace(/</g, '<')100+ .replace(/>/g, '>');101+};102+103+/**104+ * Clone `obj`.105+ *106+ * @param {Object} obj107+ * @return {Object}108+ * @api private109+ */110+111+exports.clone = function(obj){112+ var ret = {};113+ for (var key in obj) {114+ ret[key] = obj[key];115+ }116+ return ret;117+};118+119+/**120+ * Parse "Range" header `str` relative to the given file `size`.121+ *122+ * @param {Number} size123+ * @param {String} str124+ * @return {Array}125+ * @api private126+ */127+128+exports.parseRange = function(size, str){129+ var valid = true;130+ var arr = str.substr(6).split(',').map(function(range){131+ var range = range.split('-')132+ , start = parseInt(range[0], 10)133+ , end = parseInt(range[1], 10);134+135+ // -500136+ if (isNaN(start)) {137+ start = size - end;138+ end = size - 1;139+ // 500-140+ } else if (isNaN(end)) {141+ end = size - 1;142+ }143+144+ // Invalid145+ if (isNaN(start) || isNaN(end) || start > end) valid = false;146+147+ return { start: start, end: end };148+ });149+ return valid ? arr : undefined;150+};added:lib/view.js+278 added
1+2+/*!3+ * Express - view4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var path = require('path')13+ , extname = path.extname14+ , dirname = path.dirname15+ , basename = path.basename16+ , utils = require('connect').utils17+ , clone = require('./utils').clone18+ , View = require('./view/view')19+ , Partial = require('./view/partial')20+ , merge = utils.merge21+ , http = require('http')22+ , mime = utils.mime;23+24+/**25+ * Memory cache.26+ *27+ * @type Object28+ */29+30+var cache = {};31+32+/**33+ * Expose constructors.34+ */35+36+exports = module.exports = View;37+exports.Partial = Partial;38+39+/**40+ * Export template engine registrar.41+ */42+43+exports.register = View.register;44+45+/**46+ * Render `view` partial with the given `options`.47+ *48+ * Options:49+ * - `object` Single object with name derived from the view (unless `as` is present) 50+ *51+ * - `as` Variable name for each `collection` value, defaults to the view name.52+ * * as: 'something' will add the `something` local variable53+ * * as: this will use the collection value as the template context54+ * * as: global will merge the collection value's properties with `locals`55+ *56+ * - `collection` Array of objects, the name is derived from the view name itself. 57+ * For example _video.html_ will have a object _video_ available to it.58+ *59+ * @param {String} view60+ * @param {Object|Array} options, collection, or object61+ * @return {String}62+ * @api public63+ */64+65+http.ServerResponse.prototype.partial = function(view, options, locals, parent){66+ var self = this;67+68+ // Inherit parent view extension when not present69+ if (parent && !~view.indexOf('.')) {70+ view += parent.extension;71+ }72+73+ // Allow collection to be passed as second param74+ if (options) {75+ if ('length' in options) {76+ options = { collection: options };77+ } else if (!options.collection && !options.locals && !options.object) {78+ options = { object: options };79+ }80+ } else {81+ options = {};82+ }83+84+ // Inherit locals from parent85+ merge(options, locals);86+ 87+ // Merge locals88+ if (options.locals) {89+ merge(options, options.locals);90+ }91+92+ // Partials dont need layouts93+ options.renderPartial = true;94+ options.layout = false;95+96+ // Deduce name from view path97+ var name = options.as || Partial.resolveObjectName(view);98+99+ // Render partial100+ function render(){101+ if (options.object) {102+ if ('string' == typeof name) {103+ options[name] = options.object;104+ } else if (name === global) {105+ merge(options, options.object);106+ } else {107+ options.scope = options.object;108+ }109+ }110+ return self.render(view, options, null, parent);111+ }112+113+ // Collection support114+ var collection = options.collection;115+ if (collection) {116+ var len = collection.length117+ , buf = '';118+ delete options.collection;119+ options.collectionLength = len;120+ for (var i = 0; i < len; ++i) {121+ var val = collection[i];122+ options.firstInCollection = i === 0;123+ options.indexInCollection = i;124+ options.lastInCollection = i === len - 1;125+ options.object = val;126+ buf += render();127+ }128+ return buf;129+ } else {130+ return render();131+ }132+};133+134+/**135+ * Render `view` with the given `options` and optional callback `fn`.136+ * When a callback function is given a response will _not_ be made137+ * automatically, however otherwise a response of _200_ and _text/html_ is given.138+ *139+ * Options:140+ * 141+ * Most engines accept one or more of the following options,142+ * both _haml_ and _jade_ accept all:143+ *144+ * - `scope` Template evaluation context (the value of `this`)145+ * - `debug` Output debugging information146+ * - `status` Response status code, defaults to 200147+ * - `headers` Response headers object148+ *149+ * @param {String} view150+ * @param {Object|Function} options or callback function151+ * @param {Function} fn152+ * @api public153+ */154+155+http.ServerResponse.prototype.render = function(view, options, fn, parent){156+ // Support callback function as second arg157+ if (typeof options === 'function') {158+ fn = options, options = {};159+ }160+ 161+ var self = this162+ , app = this.app163+ , options = options || {}164+ , helpers = app.viewHelpers165+ , dynamicHelpers = app.dynamicViewHelpers166+ , viewOptions = app.settings['view options']167+ , cacheTemplates = app.settings['cache views'];168+169+ // Merge "view options"170+ if (viewOptions) options = merge(clone(viewOptions), options);171+172+ // Defaults173+ var self = this174+ , root = app.settings.views || process.cwd() + '/views'175+ , partial = options.renderPartial176+ , layout = options.layout;177+178+ // Layout support179+ if (true === layout || undefined === layout) {180+ layout = 'layout';181+ }182+183+ // Default execution scope to the response184+ options.scope = options.scope || this.req;185+186+ // Populate view187+ options.parentView = parent;188+189+ // "views" setting190+ options.root = root;191+192+ // "view engine" setting193+ options.defaultEngine = app.settings['view engine'];194+195+ // Populate view196+ // TODO: cache197+ var orig = view = partial198+ ? new Partial(view, options)199+ : new View(view, options);200+201+ // Ensure view exists, otherwise try _ prefix202+ if (!view.exists) {203+ view = partial204+ ? new Partial(view.prefixPath, options)205+ : new View(view.prefixPath, options);206+ }207+ 208+ // Ensure view _ prefix exists, otherwise try index209+ if (!view.exists) {210+ view = partial211+ ? new Partial(orig.indexPath, options)212+ : new View(orig.indexPath, options);213+ }214+ 215+ // Merge res.locals216+ if (this.locals) {217+ options = merge(this.locals, options);218+ }219+ 220+ // Dynamic helper support221+ if (false !== options.dynamicHelpers) {222+ // cache223+ if (!this.__dynamicHelpers) {224+ this.__dynamicHelpers = {};225+ for (var key in dynamicHelpers) {226+ this.__dynamicHelpers[key] = dynamicHelpers[key].call(227+ this.app228+ , this.req229+ , this);230+ }231+ }232+233+ // apply234+ merge(options, this.__dynamicHelpers);235+ }236+237+ // Merge view helpers238+ options = merge(clone(helpers), options);239+240+ // Always expose partial() as a local241+ options.partial = function(path, opts){242+ return self.partial(path, opts, options, view);243+ };244+245+ function error(err) {246+ if (fn) {247+ fn(err);248+ } else {249+ self.req.next(err);250+ }251+ }252+253+ // Attempt render254+ try {255+ var engine = view.templateEngine256+ , template = cacheTemplates257+ ? cache[view.path] || (cache[view.path] = engine.compile(view.contents, options))258+ : engine.compile(view.contents, options)259+ , str = template.call(options.scope, options);260+ } catch (err) {261+ return error(err);262+ }263+264+ // Layout support265+ if (layout) {266+ options.isLayout = true;267+ options.layout = false;268+ options.body = str;269+ options.relative = false;270+ self.render(layout, options, fn, view);271+ } else if (partial) {272+ return str;273+ } else if (fn) {274+ fn(null, str);275+ } else {276+ this.send(str, options.headers, options.status);277+ }278+};modified:test/utils.test.js+1 added-1 removed
12345667891019 unmodified lines
/** * Module dependencies. */
var utils = require('express/utils')var utils = require('../lib/utils') , should = require('should');
module.exports = { 'test .miniMarkdown()': function(){19 unmodified linesmodified:test/view.test.js+1 added-1 removed
5 unmodified lines6 var express = require('express')7 , connect = require('connect')8 , assert = require('assert')9 , should = require('should')10- , View = require('express/view')10+ , View = require('../lib/view')11 , Partial = View.Partial12 13 /**14 * Create a test server with views set to ./fixtures.876 unmodified lines