Removed anonymous func for scoping
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by visionmedia · committed by visionmedia · parent 9d18efe · Browse files · 1 file·+691 added−694 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+691 added−694 removed
- other:+691 added−694 removed
Provenance
- Commit
e6f71f9- Tree
e70c1e4- Author
visionmedia <tj@vision-media.ca>- Committer
visionmedia <tj@vision-media.ca>- Parent
9d18efe
1 file changed+691 added−694 removed
modified:lib/express.core.js+691 added-694 removed
1 2 // Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)3 process.mixin(GLOBAL, require("sys"));4 5-(function(){6- var http = require("http");5+http = require("http");6+7+Express = { 8+ version : '0.0.1',9+ utilities : {},10+ modules : [],11+ routes : [],12+ STATUS_CODES : {13+ 100 : 'Continue',14+ 101 : 'Switching Protocols',15+ 200 : 'OK',16+ 201 : 'Created',17+ 202 : 'Accepted',18+ 203 : 'Non-Authoritative Information',19+ 204 : 'No Content',20+ 205 : 'Reset Content',21+ 206 : 'Partial Content',22+ 300 : 'Multiple Choices',23+ 301 : 'Moved Permanently',24+ 302 : 'Moved Temporarily',25+ 303 : 'See Other',26+ 304 : 'Not Modified',27+ 305 : 'Use Proxy',28+ 400 : 'Bad Request',29+ 401 : 'Unauthorized',30+ 402 : 'Payment Required',31+ 403 : 'Forbidden',32+ 404 : 'Not Found',33+ 405 : 'Method Not Allowed',34+ 406 : 'Not Acceptable',35+ 407 : 'Proxy Authentication Required',36+ 408 : 'Request Time-out',37+ 409 : 'Conflict',38+ 410 : 'Gone',39+ 411 : 'Length Required',40+ 412 : 'Precondition Failed',41+ 413 : 'Request Entity Too Large',42+ 414 : 'Request-URI Too Large',43+ 415 : 'Unsupported Media Type',44+ 500 : 'Internal Server Error',45+ 501 : 'Not Implemented',46+ 502 : 'Bad Gateway',47+ 503 : 'Service Unavailable',48+ 504 : 'Gateway Time-out',49+ 505 : 'HTTP Version not supported'50+ },51 8- Express = { 9- version : '0.0.1',10- utilities : {},11- modules : [],12- routes : [],13- STATUS_CODES : {14- 100 : 'Continue',15- 101 : 'Switching Protocols',16- 200 : 'OK',17- 201 : 'Created',18- 202 : 'Accepted',19- 203 : 'Non-Authoritative Information',20- 204 : 'No Content',21- 205 : 'Reset Content',22- 206 : 'Partial Content',23- 300 : 'Multiple Choices',24- 301 : 'Moved Permanently',25- 302 : 'Moved Temporarily',26- 303 : 'See Other',27- 304 : 'Not Modified',28- 305 : 'Use Proxy',29- 400 : 'Bad Request',30- 401 : 'Unauthorized',31- 402 : 'Payment Required',32- 403 : 'Forbidden',33- 404 : 'Not Found',34- 405 : 'Method Not Allowed',35- 406 : 'Not Acceptable',36- 407 : 'Proxy Authentication Required',37- 408 : 'Request Time-out',38- 409 : 'Conflict',39- 410 : 'Gone',40- 411 : 'Length Required',41- 412 : 'Precondition Failed',42- 413 : 'Request Entity Too Large',43- 414 : 'Request-URI Too Large',44- 415 : 'Unsupported Media Type',45- 500 : 'Internal Server Error',46- 501 : 'Not Implemented',47- 502 : 'Bad Gateway',48- 503 : 'Service Unavailable',49- 504 : 'Gateway Time-out',50- 505 : 'HTTP Version not supported'51- },52- 53- // --- Halt54- 55- Halt : function(){56- this.toString = function() {57- return 'Express.Halt'52+ // --- Halt53+ 54+ Halt : function(){55+ this.toString = function() {56+ return 'Express.Halt'57+ }58+ },59+ 60+ // --- Response61+ 62+ response : {63+ headers : {},64+ cookie : {}65+ },66+ 67+ // --- Settings68+ 69+ settings : {70+ basepath : '/',71+ defaultRoute : {72+ callback : function() {73+ Express.respond('Page or file cannot be found', 'Not Found')74 }75+ }76+ },77+ 78+ // --- Modules79+ 80+ RedirectHelpers : {81+ init : function() {82+ Express.home = Express.settings.basepath83 },84 61- // --- Response62- 63- response : {64- headers : {},65- cookie : {}66- },67- 68- // --- Settings69- 70- settings : {71- basepath : '/',72- defaultRoute : {73- callback : function() {74- Express.respond('Page or file cannot be found', 'Not Found')75- }85+ onRequest : {86+ 'set back to referrer' : function() {87+ Express.back = 88+ Express.requestHeader('Referer') ||89+ Express.requestHeader('Referrer')90 }77- },78- 79- // --- Modules80- 81- RedirectHelpers : {82- init : function() {83- Express.home = Express.settings.basepath84- },85- 86- onRequest : {87- 'set back to referrer' : function() {88- Express.back = 89- Express.requestHeader('Referer') ||90- Express.requestHeader('Referrer')91- }91+ }92+ },93+ 94+ ContentLength : {95+ onResponse : {96+ 'set content length' : function() {97+ Express.header('Content-Length', (Express.response.body || '').length)98 }93- },94- 95- ContentLength : {96- onResponse : {97- 'set content length' : function() {98- Express.header('Content-Length', (Express.response.body || '').length)99- }99+ }100+ },101+ 102+ DefaultContentType : {103+ onRequest : {104+ 'set response content type to text/html' : function() {105+ Express.header('Content-Type', 'text/html')106 }101- },102- 103- DefaultContentType : {104- onRequest : {105- 'set response content type to text/html' : function() {106- Express.header('Content-Type', 'text/html')107+ }108+ },109+ 110+ BodyDecoder : {111+ onRequest : {112+ 'parse urlencoded bodies' : function() {113+ switch (Express.requestHeader('Content-Type')) {114+ case 'application/x-www-form-urlencoded':115+ Express.request.uri.params = Express.parseParams(unescape(Express.request.body))116+ break117+ 118+ case 'application/json':119+ Express.request.uri.params = Express.jsonDecode(Express.request.body)120+ break121 }122 }109- },110- 111- BodyDecoder : {112- onRequest : {113- 'parse urlencoded bodies' : function() {114- switch (Express.requestHeader('Content-Type')) {115- case 'application/x-www-form-urlencoded':116- Express.request.uri.params = Express.parseParams(unescape(Express.request.body))117- break118- 119- case 'application/json':120- Express.request.uri.params = Express.jsonDecode(Express.request.body)121- break122- }123- }123+ }124+ },125+ 126+ MethodOverride : {127+ onRequest : {128+ 'set HTTP method to _method when present' : function() {129+ if (method = Express.param('_method'))130+ Express.request.method = method.toUpperCase()131 }125- },126- 127- MethodOverride : {128- onRequest : {129- 'set HTTP method to _method when present' : function() {130- if (method = Express.param('_method'))131- Express.request.method = method.toUpperCase()132- }132+ }133+ },134+ 135+ Logger : {136+ onResponse : {137+ 'output log data' : function(){138+ puts('"' + Express.request.method + ' ' + Express.request.uri.path +139+ ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)140 }134- },135- 136- Logger : {137- onResponse : {138- 'output log data' : function(){139- puts('"' + Express.request.method + ' ' + Express.request.uri.path +140- ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)141- }142- }143- },144- 145- /**146- * Invoke hook _name_ with _args_, returning147- * an array of return values.148- *149- * @param {string} name150- * @param {...} args151- * @return {array}152- * @api public153- */154- 155- hook : function(name, args) {156- var results = []157- for (var i = 0, len = this.modules.length; i < len; ++i)158- for (var key in this.modules[i][name])159- results.push(this.modules[i][name][key].apply(this.modules[i], this.argsArray(arguments, 1))) 160- return results161- },162- 163- /**164- * Invoke hook _name_ with _immutable_ and _args_, returning165- * the _immutable_ variable once modified by each hook implementation.166- * When implementing these hooks, the function must return a value.167- *168- * @param {string} name169- * @param {mixed} immutable170- * @param {...} args171- * @return {mixed}172- * @api public173- */174- 175- hookImmutable : function(name, immutable, args) {176- for (var i = 0, len = this.modules.length; i < len; ++i)177- for (var key in this.modules[i][name])178- immutable = this.modules[i][name][key].call(this.modules[i], immutable)179- return immutable180- },181- 182- /**183- * Add _module_.184- *185- * @param {hash} module186- * @param {...} args187- * @api public188- */189- 190- addModule : function(module, args) {191- Express.settings[module.name] = {}141+ }142+ },143+ 144+ /**145+ * Invoke hook _name_ with _args_, returning146+ * an array of return values.147+ *148+ * @param {string} name149+ * @param {...} args150+ * @return {array}151+ * @api public152+ */153+ 154+ hook : function(name, args) {155+ var results = []156+ for (var i = 0, len = this.modules.length; i < len; ++i)157+ for (var key in this.modules[i][name])158+ results.push(this.modules[i][name][key].apply(this.modules[i], this.argsArray(arguments, 1))) 159+ return results160+ },161+ 162+ /**163+ * Invoke hook _name_ with _immutable_ and _args_, returning164+ * the _immutable_ variable once modified by each hook implementation.165+ * When implementing these hooks, the function must return a value.166+ *167+ * @param {string} name168+ * @param {mixed} immutable169+ * @param {...} args170+ * @return {mixed}171+ * @api public172+ */173+ 174+ hookImmutable : function(name, immutable, args) {175+ for (var i = 0, len = this.modules.length; i < len; ++i)176+ for (var key in this.modules[i][name])177+ immutable = this.modules[i][name][key].call(this.modules[i], immutable)178+ return immutable179+ },180+ 181+ /**182+ * Add _module_.183+ *184+ * @param {hash} module185+ * @param {...} args186+ * @api public187+ */188+ 189+ addModule : function(module, args) {190+ Express.settings[module.name] = {}191 193- if ('init' in module) 194- module.init.apply(module, Express.argsArray(arguments, 1))192+ if ('init' in module) 193+ module.init.apply(module, Express.argsArray(arguments, 1))194 196- if ('settings' in module) {197- if (!module.name) throw 'module name is required when using .settings'198- for (var name in module.settings)199- Express.settings[module.name][name] = module.settings[name]200- }201- 202- if ('utilities' in module)203- for (var name in module.utilities)204- Express.utilities[name] = module.utilities[name]205- 206- Express.modules.push(module)207- },195+ if ('settings' in module) {196+ if (!module.name) throw 'module name is required when using .settings'197+ for (var name in module.settings)198+ Express.settings[module.name][name] = module.settings[name]199+ }200+ 201+ if ('utilities' in module)202+ for (var name in module.utilities)203+ Express.utilities[name] = module.utilities[name]204 205+ Express.modules.push(module)206+ },207+ 208+ /**209+ * Start Express; binding to _host_ / _port_.210+ *211+ * @param {int} port212+ * @param {string} host213+ * @api public214+ */215+ 216+ start : function(port, host) {217+ this.server.listen(port || 3000, host, this.server.callback)218+ },219+ 220+ server : {221+ 222 /**210- * Start Express; binding to _host_ / _port_.223+ * Listen to _host_ / _port_ with _callback_.224 *225 * @param {int} port226 * @param {string} host214- * @api public215- */216- 217- start : function(port, host) {218- this.server.listen(port || 3000, host, this.server.callback)219- },220- 221- server : {222- 223- /**224- * Listen to _host_ / _port_ with _callback_.225- *226- * @param {int} port227- * @param {string} host228- * @param {function} callback227+ * @param {function} callback229- * @api private230- */231- 232- listen : function(port, host, callback) {233- http.createServer(callback).listen(port, host)234- puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')235- },236- 237- /**238- * Request callback.239- *240- * @param {object} request241- * @param {object} response242- * @api private243- */244- 245- callback : function(request, response){246- request.body = request.body || ''247- request.setBodyEncoding('utf8')248- request.addListener('body', function(chunk) { request.body += chunk })249- request.addListener('complete', function(){250- Express.home = Express.settings.basepath251- Express.response.body = null252- Express.response.status = 200253- Express.request = request254- Express.originalResponse = response255- request.headers = Express.arrayToHash(request.headers)256- request.uri.params = Express.parseNestedParams(request.uri.params)257- request.uri.path = Express.normalizePath(request.uri.path)258- Express.hook('onRequest')259- try { Express.response.body = Express.callRouteFor(request) }260- catch (e) { Express.fail(e) }261- 262- if (Express.response.body) {263- Express.server.finished()264- }265- })266- },267- 268- finished: function(body) {269- if (body) Express.response.body = body270- Express.hook('onResponse')271- Express.originalResponse.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))272- Express.originalResponse.sendBody(Express.response.body || '')273- Express.originalResponse.finish()274- }275- 276- },277- 278- /**279- * Fail Express with exception _e_.280- *281- * @param {object} e228 * @api private229 */284-285- fail : function(e) {286- this.hook('onFailure', e)287- if (e.constructor == Express.Halt) return288- this.header('Content-Type', 'text/plain')289- this.response.body = e.message ? e.name + ': ' + e.message : e.toString()290- this.response.status = 500291- },230 293- /**294- * Return an associative array generated295- * from the key / value pairs in _hash_.296- *297- * @param {hash} hash298- * @return {array}299- * @api public300- */301- 302- hashToArray : function(hash) {303- var array = []304- for (var key in hash)305- array.push([key, hash[key]])306- return array231+ listen : function(port, host, callback) {232+ http.createServer(callback).listen(port, host)233+ puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')234 },235 236 /**310- * Return hash generated from an311- * associative array.237+ * Request callback.238 *313- * @param {array} array314- * @return {hash}315- * @api public316- */317- 318- arrayToHash : function(array) {319- var hash = {}320- for (var i = 0, len = array.length; i < len; ++i)321- hash[array[i][0].toLowerCase()] = array[i][1]322- return hash323- },324- 325- /**326- * JSON encode _object_327- *328- * @param {mixed} object329- * @return {string}330- * @api public331- */332- 333- jsonEncode : function(object) {334- return JSON.stringify(object)335- },336- 337- /**338- * JSON decode _string_.339- *340- * @param {string} string341- * @return {mixed}342- * @api public343- */344- 345- jsonDecode : function(string) {346- return JSON.parse(string)347- },348- 349- /**350- * Redirect to _uri_.351- *352- * @param {string} uri353- * @api public354- */355- 356- redirect : function(uri) {357- this.header('Location', uri)358- this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')359- },360- 361- /**362- * Set response status to _value_. Where value may be363- * a case-insensitive string such as 'Not Found', 'forbidden',364- * or a numeric HTTP response status code.365- *366- * @param {int, string} value367- * @return {int}368- * @api public369- */370- 371- status : function(value) {372- if (value == undefined) return373- if (typeof value == 'number') return this.response.status = value374- for (var code in this.STATUS_CODES)375- if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())376- return this.response.status = parseInt(code)377- },378-379- /**380- * Return path segment _n_.381- *382- * @param {int} n383- * @return {string}384- * @api public385- */386- 387- arg : function(n) {388- return this.request.uri.path.split('/')[n]389- },390- 391- /**392- * Set response _status_ and _body_.393- *394- * @param {string} body395- * @param {string, int} status396- * @api public397- */398- 399- respond : function(body, status) {400- this.response.body = body401- this.status(status)402- throw new Express.Halt()403- },404- 405- /**406- * Get or set response _name_ header.407- *408- * @param {string} name409- * @param {string} value410- * @return {string}411- * @api public412- */413- 414- header : function(name, value) {415- return value ? 416- this.response.headers[name.toLowerCase()] = value :417- this.response.headers[name.toLowerCase()]418- },419- 420- /**421- * Get request header _name_ optionally providing _default_422- * when _name_ is not present.423- *424- * @param {string} name425- * @param {string} default426- * @return {string}427- * @api public428- */429- 430- requestHeader : function(name, defaultValue) {431- return this.request.headers[name.toLowerCase()] || defaultValue432- },433- 434- /**435- * Return param _key_'s value or _defaultValue_ when436- * the param has not been set.437- *438- * @param {string} key439- * @param {mixed} defaultValue440- * @return {mixed}441- * @api public442- */443- 444- param : function(key, defaultValue) {445- return this.request.uri.params[key] || defaultValue446- },447- 448- /**449- * Parse params _string_ into a nested hash.450- *451- * @param {string} string452- * @return {hash}453- * @api public454- */455- 456- parseParams : function(string) {457- var params = {}, pairs = string.split('&'), pair458- for (var i = 0, len = pairs.length; i < len; ++i) {459- pair = pairs[i].split('=')460- params[pair[0]] = pair[1]461- }462- return this.parseNestedParams(params)463- },464- 465- /**466- * Parse _params_, splitting { user[info][name] : 'tj' } into467- * { user : { info : { name : 'tj' }}}468- *469- * @param {hash} params470- * @return {hash}471- * @api public472- */473- 474- parseNestedParams : function(params) {475- for (var key in params)476- if (parts = key.split('['))477- if (parts.length > 1)478- for (var i = 0, prop = params, len = parts.length; i < len; ++i) {479- var name = parts[i].replace(']', '')480- if (i == len - 1) {481- prop[name] = params[key]482- prop = params, delete params[key]483- }484- else {485- prop = prop[name] = prop[name] || {}486- }487- }488- 489- return params490- },491- 492- /**493- * Parse _cookie_ string into an object (hash).494- *495- * @param {string} cookie496- * @return {hash}497- * @api public498- */499- 500- parseCookie : function(cookie) {501- var hash = {}502- if (!cookie) return hash503- var attrs = cookie.split(/\s*;\s*/)504- for (var i = 0; i < attrs.length; ++i)505- hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])506- return hash507- },508- 509- /**510- * Normalize a path. Strips trailing / leading whitespace511- * and slashes ('/').512- *513- * @param {string} path514- * @return {string}515- * @api public516- */517- 518- normalizePath : function(path) {519- if (typeof path != 'string') return path520- return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')521- },522- 523- /**524- * Normalize _path_. When a RegExp it is simply returned,525- * otherwise a string is converted to a regular expression526- * surrounded by ^$. So /user/:id/edit would become:527- *528- * \^/user/(.*?)\/edit\$/529- *530- * Each param key (:id) will be captured and placed in the531- * params array, so param('id') would give the string captured.532- *533- * @param {string} path534- * @return {regexp}535- * @api public536- */537- 538- pathToRegexp : function(path) {539- Express.regexpKeys = []540- if (path.constructor == RegExp) return path541- path = path.replace(/:(\w+)/g, function(_, key){542- Express.regexpKeys.push(key)543- return '(.*?)'544- })545- return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')546- },547- 548- /**549- * Escape RegExp _chars_ in _string_. Where _chars_ 550- * defaults to regular expression special characters.551- *552- * _chars_ should be a space delimited list of characters,553- * for example '[ ] ( )'.554- *555- * @param {string} string556- * @param {string} chars557- * @return {Type}558- * @api public559- */560- 561- escapeRegexp : function(string, chars) {562- var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')563- return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')564- },565- 566- /**567- * Return the contents of a function body.568- *569- * @param {function} body570- * @return {string}571- * @api public572- */573- 574- contentsOf : function(body) {575- if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"576- return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]577- },578- 579- /**580- * Eval _string_ in context of Express.581- *582- * @param {string} string583- * @return {mixed}584- * @api public585- */586- 587- eval : function(string) {588- return eval('with (Express){ with (Express.utilities){ ' + string + '}}')589- },590- 591- /**592- * Escape special characters in _html_.593- *594- * @param {string} html595- * @return {string}596- * @api public597- */598- 599- escape : function(html) {600- return html.601- replace(/&/g, '&').602- replace(/"/g, '"').603- replace(/</g, '<').604- replace(/>/g, '>')605- },606- 607- /**608- * Convert native arguments object into an609- * array with optional _offset_.610- *611- * @param {arguments} args612- * @param {int} offset613- * @return {array}614- * @api public615- */616- 617- argsArray : function(args, offset) {618- return Array.prototype.slice.call(args, offset)619- },620- 621- /**622- * Check if _route_ matches provides the proper623- * encoding types listed in _request_'s Accept header.624- *625- * @param {hash} route626- * @param {hash} request627- * @return {bool}628- * @api private629- */630- 631- routeProvides : function(route, request) {632- if (!route.options.provides) return true633- if (route.options.provides.constructor != Array) 634- route.options.provides = [route.options.provides]635- for (var i = 0, len = route.options.provides.length; i < len; ++i)636- if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))637- return true638- return false639- },640- 641- /**642- * Attept to match and call a route for 643- * the given _request_, returning the data644- * returned by the route callback.645- *239 * @param {object} request647- * @return {mixed}240+ * @param {object} response241 * @api private242 */243 651- callRouteFor : function(request) {652- var route = this.findRouteFor(request) || this.settings.defaultRoute653- if (route.keys)654- for (var i = 0, len = route.keys.length; i < len; ++i) 655- this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null656- var body = this.eval(Express.contentsOf(route.callback))657- if (typeof body != 'string') body = null658- return body244+ callback : function(request, response){245+ request.body = request.body || ''246+ request.setBodyEncoding('utf8')247+ request.addListener('body', function(chunk) { request.body += chunk })248+ request.addListener('complete', function(){249+ Express.home = Express.settings.basepath250+ Express.response.body = null251+ Express.response.status = 200252+ Express.request = request253+ Express.originalResponse = response254+ request.headers = Express.arrayToHash(request.headers)255+ request.uri.params = Express.parseNestedParams(request.uri.params)256+ request.uri.path = Express.normalizePath(request.uri.path)257+ Express.hook('onRequest')258+ try { Express.response.body = Express.callRouteFor(request) }259+ catch (e) { Express.fail(e) }260+ 261+ if (Express.response.body) {262+ Express.server.finished()263+ }264+ })265 },660- 661- /**662- * Attempt to find and return a route matching _request_.663- *664- * @param {object} request665- * @return {object}666- * @api private667- */668- 669- findRouteFor : function(request) {670- for (var i = 0, len = this.routes.length; i < len; ++i)671- if (this.routeMatches(this.routes[i], request))672- return this.routes[i]673- },674- 675- /**676- * Check if _route_ matches _request_677- *678- * @param {object} route679- * @param {object} request680- * @return {bool}681- * @api private682- */683- 684- routeMatches : function(route, request) {685- if (request.method.toLowerCase() != route.method) return false686- switch (route.path.constructor) {687- case String: return route.path == request.uri.path688- case RegExp: return !! (Express.captures = request.uri.path.match(route.path))689- }690- },691- 692- /**693- * Return a routing function for _method_.694- *695- * @param {string} method696- * @return {function}697- * @api private698- */699- 700- routeFunctionFor : function(method) {701- return function(path, options, callback) {702- if (options.constructor == Function) callback = options, options = {}703- path = Express.pathToRegexp(Express.normalizePath(path))704- var route = {705- keys : Express.regexpKeys,706- path : path,707- method : method,708- options : options,709- callback : callback710- }711- Express.routes.push(route)712- Express.hook('onRouteAdded', route)713- }714- }266+ 267+ finished: function(body) {268+ if (body) Express.response.body = body269+ Express.hook('onResponse')270+ Express.originalResponse.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))271+ Express.originalResponse.sendBody(Express.response.body || '')272+ Express.originalResponse.finish()273 }274 717- // --- Expose275+ },276 719- get = Express.routeFunctionFor('get')720- post = Express.routeFunctionFor('post')721- del = Express.routeFunctionFor('delete')722- put = Express.routeFunctionFor('put')723- use = Express.addModule277+ /**278+ * Fail Express with exception _e_.279+ *280+ * @param {object} e281+ * @api private282+ */283 725- // --- Core Modules284+ fail : function(e) {285+ this.hook('onFailure', e)286+ if (e.constructor == Express.Halt) return287+ this.header('Content-Type', 'text/plain')288+ this.response.body = e.message ? e.name + ': ' + e.message : e.toString()289+ this.response.status = 500290+ },291 727- use(Express.BodyDecoder)728- use(Express.MethodOverride)729- use(Express.ContentLength)730- use(Express.DefaultContentType)731- use(Express.RedirectHelpers)732- 733-})()292+ /**293+ * Return an associative array generated294+ * from the key / value pairs in _hash_.295+ *296+ * @param {hash} hash297+ * @return {array}298+ * @api public299+ */300+ 301+ hashToArray : function(hash) {302+ var array = []303+ for (var key in hash)304+ array.push([key, hash[key]])305+ return array306+ },307+ 308+ /**309+ * Return hash generated from an310+ * associative array.311+ *312+ * @param {array} array313+ * @return {hash}314+ * @api public315+ */316+ 317+ arrayToHash : function(array) {318+ var hash = {}319+ for (var i = 0, len = array.length; i < len; ++i)320+ hash[array[i][0].toLowerCase()] = array[i][1]321+ return hash322+ },323+ 324+ /**325+ * JSON encode _object_326+ *327+ * @param {mixed} object328+ * @return {string}329+ * @api public330+ */331+ 332+ jsonEncode : function(object) {333+ return JSON.stringify(object)334+ },335+ 336+ /**337+ * JSON decode _string_.338+ *339+ * @param {string} string340+ * @return {mixed}341+ * @api public342+ */343+ 344+ jsonDecode : function(string) {345+ return JSON.parse(string)346+ },347+ 348+ /**349+ * Redirect to _uri_.350+ *351+ * @param {string} uri352+ * @api public353+ */354+ 355+ redirect : function(uri) {356+ this.header('Location', uri)357+ this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')358+ },359+ 360+ /**361+ * Set response status to _value_. Where value may be362+ * a case-insensitive string such as 'Not Found', 'forbidden',363+ * or a numeric HTTP response status code.364+ *365+ * @param {int, string} value366+ * @return {int}367+ * @api public368+ */369+ 370+ status : function(value) {371+ if (value == undefined) return372+ if (typeof value == 'number') return this.response.status = value373+ for (var code in this.STATUS_CODES)374+ if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())375+ return this.response.status = parseInt(code)376+ },377 378+ /**379+ * Return path segment _n_.380+ *381+ * @param {int} n382+ * @return {string}383+ * @api public384+ */385+ 386+ arg : function(n) {387+ return this.request.uri.path.split('/')[n]388+ },389+ 390+ /**391+ * Set response _status_ and _body_.392+ *393+ * @param {string} body394+ * @param {string, int} status395+ * @api public396+ */397+ 398+ respond : function(body, status) {399+ this.response.body = body400+ this.status(status)401+ throw new Express.Halt()402+ },403+ 404+ /**405+ * Get or set response _name_ header.406+ *407+ * @param {string} name408+ * @param {string} value409+ * @return {string}410+ * @api public411+ */412+ 413+ header : function(name, value) {414+ return value ? 415+ this.response.headers[name.toLowerCase()] = value :416+ this.response.headers[name.toLowerCase()]417+ },418+ 419+ /**420+ * Get request header _name_ optionally providing _default_421+ * when _name_ is not present.422+ *423+ * @param {string} name424+ * @param {string} default425+ * @return {string}426+ * @api public427+ */428+ 429+ requestHeader : function(name, defaultValue) {430+ return this.request.headers[name.toLowerCase()] || defaultValue431+ },432+ 433+ /**434+ * Return param _key_'s value or _defaultValue_ when435+ * the param has not been set.436+ *437+ * @param {string} key438+ * @param {mixed} defaultValue439+ * @return {mixed}440+ * @api public441+ */442+ 443+ param : function(key, defaultValue) {444+ return this.request.uri.params[key] || defaultValue445+ },446+ 447+ /**448+ * Parse params _string_ into a nested hash.449+ *450+ * @param {string} string451+ * @return {hash}452+ * @api public453+ */454+ 455+ parseParams : function(string) {456+ var params = {}, pairs = string.split('&'), pair457+ for (var i = 0, len = pairs.length; i < len; ++i) {458+ pair = pairs[i].split('=')459+ params[pair[0]] = pair[1]460+ }461+ return this.parseNestedParams(params)462+ },463+ 464+ /**465+ * Parse _params_, splitting { user[info][name] : 'tj' } into466+ * { user : { info : { name : 'tj' }}}467+ *468+ * @param {hash} params469+ * @return {hash}470+ * @api public471+ */472+ 473+ parseNestedParams : function(params) {474+ for (var key in params)475+ if (parts = key.split('['))476+ if (parts.length > 1)477+ for (var i = 0, prop = params, len = parts.length; i < len; ++i) {478+ var name = parts[i].replace(']', '')479+ if (i == len - 1) {480+ prop[name] = params[key]481+ prop = params, delete params[key]482+ }483+ else {484+ prop = prop[name] = prop[name] || {}485+ }486+ }487+ 488+ return params489+ },490+ 491+ /**492+ * Parse _cookie_ string into an object (hash).493+ *494+ * @param {string} cookie495+ * @return {hash}496+ * @api public497+ */498+ 499+ parseCookie : function(cookie) {500+ var hash = {}501+ if (!cookie) return hash502+ var attrs = cookie.split(/\s*;\s*/)503+ for (var i = 0; i < attrs.length; ++i)504+ hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])505+ return hash506+ },507+ 508+ /**509+ * Normalize a path. Strips trailing / leading whitespace510+ * and slashes ('/').511+ *512+ * @param {string} path513+ * @return {string}514+ * @api public515+ */516+ 517+ normalizePath : function(path) {518+ if (typeof path != 'string') return path519+ return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')520+ },521+ 522+ /**523+ * Normalize _path_. When a RegExp it is simply returned,524+ * otherwise a string is converted to a regular expression525+ * surrounded by ^$. So /user/:id/edit would become:526+ *527+ * \^/user/(.*?)\/edit\$/528+ *529+ * Each param key (:id) will be captured and placed in the530+ * params array, so param('id') would give the string captured.531+ *532+ * @param {string} path533+ * @return {regexp}534+ * @api public535+ */536+ 537+ pathToRegexp : function(path) {538+ Express.regexpKeys = []539+ if (path.constructor == RegExp) return path540+ path = path.replace(/:(\w+)/g, function(_, key){541+ Express.regexpKeys.push(key)542+ return '(.*?)'543+ })544+ return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')545+ },546+ 547+ /**548+ * Escape RegExp _chars_ in _string_. Where _chars_ 549+ * defaults to regular expression special characters.550+ *551+ * _chars_ should be a space delimited list of characters,552+ * for example '[ ] ( )'.553+ *554+ * @param {string} string555+ * @param {string} chars556+ * @return {Type}557+ * @api public558+ */559+ 560+ escapeRegexp : function(string, chars) {561+ var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')562+ return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')563+ },564+ 565+ /**566+ * Return the contents of a function body.567+ *568+ * @param {function} body569+ * @return {string}570+ * @api public571+ */572+ 573+ contentsOf : function(body) {574+ if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"575+ return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]576+ },577+ 578+ /**579+ * Eval _string_ in context of Express.580+ *581+ * @param {string} string582+ * @return {mixed}583+ * @api public584+ */585+ 586+ eval : function(string) {587+ return eval('with (Express){ with (Express.utilities){ ' + string + '}}')588+ },589+ 590+ /**591+ * Escape special characters in _html_.592+ *593+ * @param {string} html594+ * @return {string}595+ * @api public596+ */597+ 598+ escape : function(html) {599+ return html.600+ replace(/&/g, '&').601+ replace(/"/g, '"').602+ replace(/</g, '<').603+ replace(/>/g, '>')604+ },605+ 606+ /**607+ * Convert native arguments object into an608+ * array with optional _offset_.609+ *610+ * @param {arguments} args611+ * @param {int} offset612+ * @return {array}613+ * @api public614+ */615+ 616+ argsArray : function(args, offset) {617+ return Array.prototype.slice.call(args, offset)618+ },619+ 620+ /**621+ * Check if _route_ matches provides the proper622+ * encoding types listed in _request_'s Accept header.623+ *624+ * @param {hash} route625+ * @param {hash} request626+ * @return {bool}627+ * @api private628+ */629+ 630+ routeProvides : function(route, request) {631+ if (!route.options.provides) return true632+ if (route.options.provides.constructor != Array) 633+ route.options.provides = [route.options.provides]634+ for (var i = 0, len = route.options.provides.length; i < len; ++i)635+ if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))636+ return true637+ return false638+ },639+ 640+ /**641+ * Attept to match and call a route for 642+ * the given _request_, returning the data643+ * returned by the route callback.644+ *645+ * @param {object} request646+ * @return {mixed}647+ * @api private648+ */649+ 650+ callRouteFor : function(request) {651+ var route = this.findRouteFor(request) || this.settings.defaultRoute652+ if (route.keys)653+ for (var i = 0, len = route.keys.length; i < len; ++i) 654+ this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null655+ var body = this.eval(Express.contentsOf(route.callback))656+ if (typeof body != 'string') body = null657+ return body658+ },659+ 660+ /**661+ * Attempt to find and return a route matching _request_.662+ *663+ * @param {object} request664+ * @return {object}665+ * @api private666+ */667+ 668+ findRouteFor : function(request) {669+ for (var i = 0, len = this.routes.length; i < len; ++i)670+ if (this.routeMatches(this.routes[i], request))671+ return this.routes[i]672+ },673+ 674+ /**675+ * Check if _route_ matches _request_676+ *677+ * @param {object} route678+ * @param {object} request679+ * @return {bool}680+ * @api private681+ */682+ 683+ routeMatches : function(route, request) {684+ if (request.method.toLowerCase() != route.method) return false685+ switch (route.path.constructor) {686+ case String: return route.path == request.uri.path687+ case RegExp: return !! (Express.captures = request.uri.path.match(route.path))688+ }689+ },690+ 691+ /**692+ * Return a routing function for _method_.693+ *694+ * @param {string} method695+ * @return {function}696+ * @api private697+ */698+ 699+ routeFunctionFor : function(method) {700+ return function(path, options, callback) {701+ if (options.constructor == Function) callback = options, options = {}702+ path = Express.pathToRegexp(Express.normalizePath(path))703+ var route = {704+ keys : Express.regexpKeys,705+ path : path,706+ method : method,707+ options : options,708+ callback : callback709+ }710+ Express.routes.push(route)711+ Express.hook('onRouteAdded', route)712+ }713+ }714+}715+716+// --- Expose717+718+get = Express.routeFunctionFor('get')719+post = Express.routeFunctionFor('post')720+del = Express.routeFunctionFor('delete')721+put = Express.routeFunctionFor('put')722+use = Express.addModule723+724+// --- Core Modules725+726+use(Express.BodyDecoder)727+use(Express.MethodOverride)728+use(Express.ContentLength)729+use(Express.DefaultContentType)730+use(Express.RedirectHelpers)731+