Skip to content
Myr

merged from upstream

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by csausdev · committed by csausdev · parents 36fbbeb, 689afd3 · Browse files · 35 files+3466 added−1226 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

35 files+3466 added−1226 removed

  • tests:+2478 added−78 removed
  • other:+988 added−1148 removed

35 files+3466 added−1226 removed

modified:examples/async.js+4 added-4 removed
modified:examples/simple.js+5 added-4 removed
added:lib/express/spec/mocks.js+113 added
12// Express - Mocks - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34/**5 * Mock _request_ object. Optionally pass hash of properties.6 *7 * @param {hash} request8 * @return {hash}9 * @api public10 */1112function mockRequest(request) {13 var mock = {14 listeners: [],15 method: 'GET',16 headers: {},17 uri: {18 path: '/',19 params: {}20 },21 setBodyEncoding : function(type) {22 this.bodyEncoding = type 23 },24 addListener : function(event, callback) {25 this.listeners.push({ event : event, callback : callback })26 if (event == 'body') {27 var body = this.body28 this.body = ''29 callback(body)30 }31 else32 callback()33 }34 }35 JSpec.extend(mock, request)36 mock.uri.params = mock.uri.params || {}37 return mock38}3940/**41 * Mock _response_ object. Optionally pass hash of properties.42 *43 * @param {hash} response44 * @return {hash}45 * @api public46 */47 48function mockResponse(response) {49 var mock = {50 body: null,51 status: 200,52 headers: [],53 sendHeader: function(){},54 sendBody: function(){},55 finish: function(){ this.finished = true }56 }57 JSpec.extend(mock, response)58 return mock59}6061/**62 * Mock server callback.63 *64 * @param {object} request65 * @param {object} response66 * @api private67 */6869orig = Express.server.callback70function mockCallback(request, response) {71 orig(mockRequest(request), mockResponse(response))72}7374/**75 * Mock route function for HTTP _method_.76 *77 * @param {string} method78 * @return {function}79 * @api private80 */8182function mockRouteFunctionFor(method) {83 var orig = Express.routeFunctionFor(method)84 return function(path, options, callback) {85 if ((options && options.constructor == Function) || (callback && callback.constructor == Function)) {86 return orig.apply(Express, arguments)87 }88 var request = mockRequest({ method : method.toUpperCase(), uri : { path : path }})89 if (options)90 JSpec.extend(request, options.request),91 request.uri.path = path92 var response = mockResponse()93 Express.server.callback(request, response)94 return Express.response95 }96}9798// --- Module99100JSpec.include({101 init : function() {102 Express.server.callback = mockCallback103 },104 105 utilities : {106 mockRequest : mockRequest,107 mockResponse : mockResponse,108 get : mockRouteFunctionFor('get'),109 post : mockRouteFunctionFor('post'),110 put : mockRouteFunctionFor('put'),111 del : mockRouteFunctionFor('delete')112 }113})
added:lib/express/cookie.js+48 added
added:lib/express/core.js+678 added
12// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34process.mixin(GLOBAL, require("sys"))5var http = require("http")67Express = { 8 version: '0.0.1',9 utilities: {},10 modules: [],11 routes: [],12 responseCodes : {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 52 // --- Response53 54 response : {55 headers : {},56 cookie : {}57 },58 59 // --- Settings60 61 settings : {62 basepath : '/',63 defaultRoute : {64 callback : function() {65 Express.halt('Page or file cannot be found', 'Not Found')66 }67 }68 },69 70 // --- Modules71 72 RedirectHelpers : {73 init : function() {74 Express.home = Express.settings.basepath75 },76 77 onRequest : {78 'set back to referrer' : function() {79 Express.back = 80 Express.requestHeader('Referer') ||81 Express.requestHeader('Referrer')82 }83 }84 },85 86 ContentLength : {87 onResponse : {88 'set content length' : function() {89 Express.header('Content-Length', (Express.response.body || '').length)90 }91 }92 },93 94 DefaultContentType : {95 onRequest : {96 'set response content type to text/html' : function() {97 Express.header('Content-Type', 'text/html')98 }99 }100 },101 102 BodyDecoder : {103 onRequest : {104 'parse urlencoded bodies' : function() {105 switch (Express.requestHeader('Content-Type')) {106 case 'application/x-www-form-urlencoded':107 Express.request.uri.params = Express.parseParams(decodeURIComponent(Express.request.body))108 break109 110 case 'application/json':111 Express.request.uri.params = Express.jsonDecode(Express.request.body)112 break113 }114 }115 }116 },117 118 MethodOverride : {119 onRequest : {120 'set HTTP method to _method when present' : function() {121 if (method = Express.param('_method'))122 Express.request.method = method.toUpperCase()123 }124 }125 },126 127 Logger : {128 onResponse : {129 'output log data' : function(){130 puts('"' + Express.request.method + ' ' + Express.request.uri.path +131 ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)132 }133 }134 },135 136 /**137 * Invoke hook _name_ with _args_, returning138 * an array of return values.139 *140 * @param {string} name141 * @param {...} args142 * @return {array}143 * @api public144 */145 146 hook : function(name, args) {147 var results = []148 for (var i = 0, len = this.modules.length; i < len; ++i)149 for (var key in this.modules[i][name])150 results.push(this.modules[i][name][key].apply(this.modules[i], this.toArray(arguments, 1))) 151 return results152 },153 154 /**155 * Invoke hook _name_ with _immutable_ and _args_, returning156 * the _immutable_ variable once modified by each hook implementation.157 * When implementing these hooks, the function must return a value.158 *159 * @param {string} name160 * @param {mixed} immutable161 * @param {...} args162 * @return {mixed}163 * @api public164 */165 166 hookImmutable : function(name, immutable, args) {167 for (var i = 0, len = this.modules.length; i < len; ++i)168 for (var key in this.modules[i][name])169 immutable = this.modules[i][name][key].call(this.modules[i], immutable)170 return immutable171 },172 173 /**174 * Add _module_.175 *176 * @param {hash} module177 * @param {...} args178 * @api public179 */180 181 addModule : function(module, args) {182 Express.settings[module.name] = {}183184 if ('init' in module) 185 module.init.apply(module, Express.toArray(arguments, 1))186187 if ('settings' in module) {188 if (!module.name) throw 'module name is required when using .settings'189 for (var name in module.settings)190 Express.settings[module.name][name] = module.settings[name]191 }192 193 if ('utilities' in module)194 for (var name in module.utilities)195 Express.utilities[name] = module.utilities[name]196 197 Express.modules.push(module)198 },199 200 /**201 * Start Express; binding to _host_ / _port_.202 *203 * @param {int} port204 * @param {string} host205 * @api public206 */207 208 start : function(port, host) {209 this.server.listen(port || 3000, host, this.server.callback)210 },211 212 server : {213 214 /**215 * Listen to _host_ / _port_ with _callback_.216 *217 * @param {int} port218 * @param {string} host219 * @param {function} callback220 * @api private221 */222 223 listen : function(port, host, callback) {224 http.createServer(callback).listen(port, host)225 puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')226 },227 228 /**229 * Request callback.230 *231 * @param {object} request232 * @param {object} response233 * @api private234 */235 236 callback : function(request, response){237 request.body = request.body || ''238 request.setBodyEncoding('utf8')239 request.addListener('body', function(chunk) { request.body += chunk })240 request.addListener('complete', function(){241 Express.home = Express.settings.basepath242 Express.response.body = null243 Express.response.status = 200244 Express.request = request245 Express.originalResponse = response246 request.uri.params = Express.parseNestedParams(request.uri.params)247 request.uri.path = Express.normalizePath(request.uri.path)248 Express.hook('onRequest')249 try { Express.response.body = Express.callRouteFor(request) }250 catch (e) { Express.fail(e) }251 if (typeof Express.response.body == 'string')252 Express.server.finished()253 })254 },255 256 finished: function(body) {257 if (body) Express.response.body = body258 Express.hook('onResponse')259 Express.originalResponse.sendHeader(Express.response.status, Express.response.headers)260 Express.originalResponse.sendBody(Express.response.body || '')261 Express.originalResponse.finish()262 }263 },264 265 /**266 * Fail Express with exception _e_.267 *268 * @param {object} e269 * @api private270 */271272 fail : function(e) {273 this.hook('onFailure', e)274 this.header('Content-Type', 'text/plain')275 this.response.body = e.message ? e.name + ': ' + e.message : e.toString()276 this.response.status = 500277 },278 279 /**280 * JSON encode _object_281 *282 * @param {mixed} object283 * @return {string}284 * @api public285 */286 287 jsonEncode : function(object) {288 return JSON.stringify(object)289 },290 291 /**292 * JSON decode _string_.293 *294 * @param {string} string295 * @return {mixed}296 * @api public297 */298 299 jsonDecode : function(string) {300 return JSON.parse(string)301 },302 303 /**304 * Redirect to _uri_.305 *306 * @param {string} uri307 * @api public308 */309 310 redirect : function(uri) {311 this.header('Location', uri)312 this.halt("Page or file has moved to `" + uri + "'", 'Moved Temporarily')313 },314 315 /**316 * Set response status to _value_. Where value may be317 * a case-insensitive string such as 'Not Found', 'forbidden',318 * or a numeric HTTP response status code.319 *320 * @param {int, string} value321 * @return {int}322 * @api public323 */324 325 status : function(value) {326 if (value == undefined) return327 if (typeof value == 'number') return this.response.status = value328 for (var code in this.responseCodes)329 if (this.responseCodes[code].toLowerCase() == value.toLowerCase())330 return this.response.status = parseInt(code)331 },332333 /**334 * Return path segment _n_.335 *336 * @param {int} n337 * @return {string}338 * @api public339 */340 341 arg : function(n) {342 return this.request.uri.path.split('/')[n]343 },344 345 /**346 * Set response _status_ and _body_. Status347 * defaults to 200.348 *349 * @param {string} body350 * @param {string, int} status351 * @api public352 */353 354 halt : function(body, status) {355 this.status(status || 200)356 Express.server.finished(this.response.body = body)357 },358 359 /**360 * Get or set response _name_ header.361 *362 * @param {string} name363 * @param {string} value364 * @return {string}365 * @api public366 */367 368 header : function(name, value) {369 return value ? 370 this.response.headers[name.toLowerCase()] = value :371 this.response.headers[name.toLowerCase()]372 },373 374 /**375 * Get request header _name_ optionally providing _default_376 * when _name_ is not present.377 *378 * @param {string} name379 * @param {string} default380 * @return {string}381 * @api public382 */383 384 requestHeader : function(name, defaultValue) {385 return this.request.headers[name.toLowerCase()] || defaultValue386 },387 388 /**389 * Return param _key_'s value or _defaultValue_ when390 * the param has not been set.391 *392 * @param {string} key393 * @param {mixed} defaultValue394 * @return {mixed}395 * @api public396 */397 398 param : function(key, defaultValue) {399 return this.request.uri.params[key] || defaultValue400 },401 402 /**403 * Parse params _string_ into a nested hash.404 *405 * @param {string} string406 * @return {hash}407 * @api public408 */409 410 parseParams : function(string) {411 var params = {}, pairs = string.split('&'), pair412 for (var i = 0, len = pairs.length; i < len; ++i) {413 pair = pairs[i].split('=')414 params[pair[0]] = pair[1]415 }416 return this.parseNestedParams(params)417 },418 419 /**420 * Parse _params_, splitting { user[info][name] : 'tj' } into421 * { user : { info : { name : 'tj' }}}422 *423 * @param {hash} params424 * @return {hash}425 * @api public426 */427 428 parseNestedParams : function(params) {429 for (var key in params)430 if (parts = key.split('['))431 if (parts.length > 1)432 for (var i = 0, prop = params, len = parts.length; i < len; ++i) {433 var name = parts[i].replace(']', '')434 if (i == len - 1) {435 prop[name] = params[key]436 prop = params, delete params[key]437 }438 else {439 prop = prop[name] = prop[name] || {}440 }441 }442 443 return params444 },445 446 /**447 * Parse _cookie_ string into an object (hash).448 *449 * @param {string} cookie450 * @return {hash}451 * @api public452 */453 454 parseCookie : function(cookie) {455 var hash = {}456 if (!cookie) return hash457 var attrs = cookie.split(/\s*;\s*/)458 for (var i = 0; i < attrs.length; ++i)459 hash[attrs[i].split('=')[0]] = decodeURIComponent(attrs[i].split('=')[1])460 return hash461 },462 463 /**464 * Normalize a path. Strips trailing / leading whitespace465 * and slashes ('/').466 *467 * @param {string} path468 * @return {string}469 * @api public470 */471 472 normalizePath : function(path) {473 if (typeof path != 'string') return path474 return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')475 },476 477 /**478 * Normalize _path_. When a RegExp it is simply returned,479 * otherwise a string is converted to a regular expression480 * surrounded by ^$. So /user/:id/edit would become:481 *482 * \^/user/(.*?)\/edit\$/483 *484 * Each param key (:id) will be captured and placed in the485 * params array, so param('id') would give the string captured.486 *487 * @param {string} path488 * @return {regexp}489 * @api public490 */491 492 pathToRegexp : function(path) {493 Express.regexpKeys = []494 if (path.constructor == RegExp) return path495 path = path.replace(/:(\w+)/g, function(_, key){496 Express.regexpKeys.push(key)497 return '(.*?)'498 })499 return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')500 },501 502 /**503 * Escape RegExp _chars_ in _string_. Where _chars_ 504 * defaults to regular expression special characters.505 *506 * _chars_ should be a space delimited list of characters,507 * for example '[ ] ( )'.508 *509 * @param {string} string510 * @param {string} chars511 * @return {Type}512 * @api public513 */514 515 escapeRegexp : function(string, chars) {516 var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')517 return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')518 },519 520 /**521 * Return the contents of a function body.522 *523 * @param {function} body524 * @return {string}525 * @api public526 */527 528 contentsOf : function(body) {529 if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"530 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]531 },532 533 /**534 * Eval _string_ in context of Express.535 *536 * @param {string} string537 * @return {mixed}538 * @api public539 */540 541 eval : function(string) {542 return eval('with (Express){ with (Express.utilities){ ' + string + '}}')543 },544 545 /**546 * Escape special characters in _html_.547 *548 * @param {string} html549 * @return {string}550 * @api public551 */552 553 escape : function(html) {554 return html.555 replace(/&/g, '&amp;').556 replace(/"/g, '&quot;').557 replace(/</g, '&lt;').558 replace(/>/g, '&gt;')559 },560 561 /**562 * Convert native array-like objects into an563 * array with optional _offset_.564 *565 * @param {object} arr566 * @param {int} offset567 * @return {array}568 * @api public569 */570 571 toArray : function(arr, offset) {572 return Array.prototype.slice.call(arr, offset)573 },574 575 /**576 * Check if _route_ matches provides the proper577 * encoding types listed in _request_'s Accept header.578 *579 * @param {hash} route580 * @param {hash} request581 * @return {bool}582 * @api private583 */584 585 routeProvides : function(route, request) {586 if (!route.options.provides) return true587 if (route.options.provides.constructor != Array) 588 route.options.provides = [route.options.provides]589 for (var i = 0, len = route.options.provides.length; i < len; ++i)590 if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))591 return true592 return false593 },594 595 /**596 * Attept to match and call a route for 597 * the given _request_, returning the data598 * returned by the route callback.599 *600 * @param {object} request601 * @return {mixed}602 * @api private603 */604 605 callRouteFor : function(request) {606 var route = this.findRouteFor(request) || this.settings.defaultRoute607 if (route.keys)608 for (var i = 0, len = route.keys.length; i < len; ++i) 609 this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null610 var body = this.eval(Express.contentsOf(route.callback))611 if (typeof body != 'string') body = null612 return body613 },614 615 /**616 * Attempt to find and return a route matching _request_.617 *618 * @param {object} request619 * @return {object}620 * @api private621 */622 623 findRouteFor : function(request) {624 for (var i = 0, len = this.routes.length; i < len; ++i)625 if (this.routeMatches(this.routes[i], request))626 return this.routes[i]627 },628 629 /**630 * Check if _route_ matches _request_631 *632 * @param {object} route633 * @param {object} request634 * @return {bool}635 * @api private636 */637 638 routeMatches : function(route, request) {639 if (request.method.toLowerCase() != route.method) return false640 switch (route.path.constructor) {641 case String: return route.path == request.uri.path642 case RegExp: return !! (Express.captures = request.uri.path.match(route.path))643 }644 },645 646 /**647 * Return a routing function for _method_.648 *649 * @param {string} method650 * @return {function}651 * @api private652 */653 654 routeFunctionFor : function(method) {655 return function(path, options, callback) {656 if (options.constructor == Function) callback = options, options = {}657 path = Express.pathToRegexp(Express.normalizePath(path))658 var route = {659 keys : Express.regexpKeys,660 path : path,661 method : method,662 options : options,663 callback : callback664 }665 Express.routes.push(route)666 Express.hook('onRouteAdded', route)667 }668 }669}670671// --- Routing API672673get = Express.routeFunctionFor('get')674post = Express.routeFunctionFor('post')675del = Express.routeFunctionFor('delete')676put = Express.routeFunctionFor('put')677use = Express.addModule678
added:lib/express/mime.js+198 added
12// Express - Mime - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34Express.Mime = {5 name : 'mime',6 7 settings : {8 defaultType : 'application/octet-stream'9 },10 11 utilities : {12 13 /**14 * Returns the media type of _ext_, where _ext_ may be an15 * extension ('jpeg') or a file path ('path/to/image.name.jpeg'). 16 * Defaults to Express.settings.mime.defaultType.17 *18 * @param {string} ext19 * @return {string}20 * @api public21 */22 23 mime : function(ext) {24 if (ext.indexOf('.') != -1) 25 ext = ext.substring(ext.lastIndexOf('.') + 1, ext.length)26 return Express.utilities.mimeTypes[ext] || Express.settings.mime.defaultType27 28 },29 30 mimeTypes : {31 "3gp" : "video/3gpp",32 "a" : "application/octet-stream",33 "ai" : "application/postscript",34 "aif" : "audio/x-aiff",35 "aiff" : "audio/x-aiff",36 "asc" : "application/pgp-signature",37 "asf" : "video/x-ms-asf",38 "asm" : "text/x-asm",39 "asx" : "video/x-ms-asf",40 "atom" : "application/atom+xml",41 "au" : "audio/basic",42 "avi" : "video/x-msvideo",43 "bat" : "application/x-msdownload",44 "bin" : "application/octet-stream",45 "bmp" : "image/bmp",46 "bz2" : "application/x-bzip2",47 "c" : "text/x-c",48 "cab" : "application/vnd.ms-cab-compressed",49 "cc" : "text/x-c",50 "chm" : "application/vnd.ms-htmlhelp",51 "class" : "application/octet-stream",52 "com" : "application/x-msdownload",53 "conf" : "text/plain",54 "cpp" : "text/x-c",55 "crt" : "application/x-x509-ca-cert",56 "css" : "text/css",57 "csv" : "text/csv",58 "cxx" : "text/x-c",59 "deb" : "application/x-debian-package",60 "der" : "application/x-x509-ca-cert",61 "diff" : "text/x-diff",62 "djv" : "image/vnd.djvu",63 "djvu" : "image/vnd.djvu",64 "dll" : "application/x-msdownload",65 "dmg" : "application/octet-stream",66 "doc" : "application/msword",67 "dot" : "application/msword",68 "dtd" : "application/xml-dtd",69 "dvi" : "application/x-dvi",70 "ear" : "application/java-archive",71 "eml" : "message/rfc822",72 "eps" : "application/postscript",73 "exe" : "application/x-msdownload",74 "f" : "text/x-fortran",75 "f77" : "text/x-fortran",76 "f90" : "text/x-fortran",77 "flv" : "video/x-flv",78 "for" : "text/x-fortran",79 "gem" : "application/octet-stream",80 "gemspec" : "text/x-script.ruby",81 "gif" : "image/gif",82 "gz" : "application/x-gzip",83 "h" : "text/x-c",84 "hh" : "text/x-c",85 "htm" : "text/html",86 "html" : "text/html",87 "ico" : "image/vnd.microsoft.icon",88 "ics" : "text/calendar",89 "ifb" : "text/calendar",90 "iso" : "application/octet-stream",91 "jar" : "application/java-archive",92 "java" : "text/x-java-source",93 "jnlp" : "application/x-java-jnlp-file",94 "jpeg" : "image/jpeg",95 "jpg" : "image/jpeg",96 "js" : "application/javascript",97 "json" : "application/json",98 "log" : "text/plain",99 "m3u" : "audio/x-mpegurl",100 "m4v" : "video/mp4",101 "man" : "text/troff",102 "mathml" : "application/mathml+xml",103 "mbox" : "application/mbox",104 "mdoc" : "text/troff",105 "me" : "text/troff",106 "mid" : "audio/midi",107 "midi" : "audio/midi",108 "mime" : "message/rfc822",109 "mml" : "application/mathml+xml",110 "mng" : "video/x-mng",111 "mov" : "video/quicktime",112 "mp3" : "audio/mpeg",113 "mp4" : "video/mp4",114 "mp4v" : "video/mp4",115 "mpeg" : "video/mpeg",116 "mpg" : "video/mpeg",117 "ms" : "text/troff",118 "msi" : "application/x-msdownload",119 "odp" : "application/vnd.oasis.opendocument.presentation",120 "ods" : "application/vnd.oasis.opendocument.spreadsheet",121 "odt" : "application/vnd.oasis.opendocument.text",122 "ogg" : "application/ogg",123 "p" : "text/x-pascal",124 "pas" : "text/x-pascal",125 "pbm" : "image/x-portable-bitmap",126 "pdf" : "application/pdf",127 "pem" : "application/x-x509-ca-cert",128 "pgm" : "image/x-portable-graymap",129 "pgp" : "application/pgp-encrypted",130 "pkg" : "application/octet-stream",131 "pl" : "text/x-script.perl",132 "pm" : "text/x-script.perl-module",133 "png" : "image/png",134 "pnm" : "image/x-portable-anymap",135 "ppm" : "image/x-portable-pixmap",136 "pps" : "application/vnd.ms-powerpoint",137 "ppt" : "application/vnd.ms-powerpoint",138 "ps" : "application/postscript",139 "psd" : "image/vnd.adobe.photoshop",140 "py" : "text/x-script.python",141 "qt" : "video/quicktime",142 "ra" : "audio/x-pn-realaudio",143 "rake" : "text/x-script.ruby",144 "ram" : "audio/x-pn-realaudio",145 "rar" : "application/x-rar-compressed",146 "rb" : "text/x-script.ruby",147 "rdf" : "application/rdf+xml",148 "roff" : "text/troff",149 "rpm" : "application/x-redhat-package-manager",150 "rss" : "application/rss+xml",151 "rtf" : "application/rtf",152 "ru" : "text/x-script.ruby",153 "s" : "text/x-asm",154 "sgm" : "text/sgml",155 "sgml" : "text/sgml",156 "sh" : "application/x-sh",157 "sig" : "application/pgp-signature",158 "snd" : "audio/basic",159 "so" : "application/octet-stream",160 "svg" : "image/svg+xml",161 "svgz" : "image/svg+xml",162 "swf" : "application/x-shockwave-flash",163 "t" : "text/troff",164 "tar" : "application/x-tar",165 "tbz" : "application/x-bzip-compressed-tar",166 "tcl" : "application/x-tcl",167 "tex" : "application/x-tex",168 "texi" : "application/x-texinfo",169 "texinfo" : "application/x-texinfo",170 "text" : "text/plain",171 "tif" : "image/tiff",172 "tiff" : "image/tiff",173 "torrent" : "application/x-bittorrent",174 "tr" : "text/troff",175 "txt" : "text/plain",176 "vcf" : "text/x-vcard",177 "vcs" : "text/x-vcalendar",178 "vrml" : "model/vrml",179 "war" : "application/java-archive",180 "wav" : "audio/x-wav",181 "wma" : "audio/x-ms-wma",182 "wmv" : "video/x-ms-wmv",183 "wmx" : "video/x-ms-wmx",184 "wrl" : "model/vrml",185 "wsdl" : "application/wsdl+xml",186 "xbm" : "image/x-xbitmap",187 "xhtml" : "application/xhtml+xml",188 "xls" : "application/vnd.ms-excel",189 "xml" : "application/xml",190 "xpm" : "image/x-xpixmap",191 "xsl" : "application/xml",192 "xslt" : "application/xslt+xml",193 "yaml" : "text/yaml",194 "yml" : "text/yaml",195 "zip" : "application/zip"196 }197 }198}
added:lib/express/session.js+6 added
added:lib/express/view.js+6 added
deleted:lib/express.cookie.js-52 removed
deleted:lib/express.core.js-734 removed
12// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)3process.mixin(GLOBAL, require("sys"));4 5(function(){6 var http = require("http");7 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'58 }59 },60 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 }76 }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 }92 }93 },94 95 ContentLength : {96 onResponse : {97 'set content length' : function() {98 Express.header('Content-Length', (Express.response.body || '').length)99 }100 }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 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 }124 }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 }133 }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] = {}192193 if ('init' in module) 194 module.init.apply(module, Express.argsArray(arguments, 1))195196 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 },208 209 /**210 * Start Express; binding to _host_ / _port_.211 *212 * @param {int} port213 * @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} 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} e282 * @api private283 */284285 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 },292 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 array307 },308 309 /**310 * Return hash generated from an311 * associative array.312 *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 },378379 /**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, '&amp;').602 replace(/"/g, '&quot;').603 replace(/</g, '&lt;').604 replace(/>/g, '&gt;')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 *646 * @param {object} request647 * @return {mixed}648 * @api private649 */650 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 body659 },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 }715 }716 717 // --- Expose718 719 get = Express.routeFunctionFor('get')720 post = Express.routeFunctionFor('post')721 del = Express.routeFunctionFor('delete')722 put = Express.routeFunctionFor('put')723 use = Express.addModule724725 // --- Core Modules726 727 use(Express.BodyDecoder)728 use(Express.MethodOverride)729 use(Express.ContentLength)730 use(Express.DefaultContentType)731 use(Express.RedirectHelpers)732 733})()734
modified:lib/express.js+18 added-5 removed
deleted:lib/express.mime.js-202 removed
12// Express - Mime - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){5 6 Express.Mime = {7 name : 'mime',8 9 settings : {10 defaultType : 'application/octet-stream'11 },12 13 utilities : {14 15 /**16 * Returns the media type of _ext_, where _ext_ may be an17 * extension ('jpeg') or a file path ('path/to/image.name.jpeg'). 18 * Defaults to Express.settings.mime.defaultType.19 *20 * @param {string} ext21 * @return {string}22 * @api public23 */24 25 mime : function(ext) {26 if (ext.indexOf('.') != -1) 27 ext = ext.substring(ext.lastIndexOf('.') + 1, ext.length)28 return Express.utilities.mimeTypes[ext] || Express.settings.mime.defaultType29 30 },31 32 mimeTypes : {33 "3gp" : "video/3gpp",34 "a" : "application/octet-stream",35 "ai" : "application/postscript",36 "aif" : "audio/x-aiff",37 "aiff" : "audio/x-aiff",38 "asc" : "application/pgp-signature",39 "asf" : "video/x-ms-asf",40 "asm" : "text/x-asm",41 "asx" : "video/x-ms-asf",42 "atom" : "application/atom+xml",43 "au" : "audio/basic",44 "avi" : "video/x-msvideo",45 "bat" : "application/x-msdownload",46 "bin" : "application/octet-stream",47 "bmp" : "image/bmp",48 "bz2" : "application/x-bzip2",49 "c" : "text/x-c",50 "cab" : "application/vnd.ms-cab-compressed",51 "cc" : "text/x-c",52 "chm" : "application/vnd.ms-htmlhelp",53 "class" : "application/octet-stream",54 "com" : "application/x-msdownload",55 "conf" : "text/plain",56 "cpp" : "text/x-c",57 "crt" : "application/x-x509-ca-cert",58 "css" : "text/css",59 "csv" : "text/csv",60 "cxx" : "text/x-c",61 "deb" : "application/x-debian-package",62 "der" : "application/x-x509-ca-cert",63 "diff" : "text/x-diff",64 "djv" : "image/vnd.djvu",65 "djvu" : "image/vnd.djvu",66 "dll" : "application/x-msdownload",67 "dmg" : "application/octet-stream",68 "doc" : "application/msword",69 "dot" : "application/msword",70 "dtd" : "application/xml-dtd",71 "dvi" : "application/x-dvi",72 "ear" : "application/java-archive",73 "eml" : "message/rfc822",74 "eps" : "application/postscript",75 "exe" : "application/x-msdownload",76 "f" : "text/x-fortran",77 "f77" : "text/x-fortran",78 "f90" : "text/x-fortran",79 "flv" : "video/x-flv",80 "for" : "text/x-fortran",81 "gem" : "application/octet-stream",82 "gemspec" : "text/x-script.ruby",83 "gif" : "image/gif",84 "gz" : "application/x-gzip",85 "h" : "text/x-c",86 "hh" : "text/x-c",87 "htm" : "text/html",88 "html" : "text/html",89 "ico" : "image/vnd.microsoft.icon",90 "ics" : "text/calendar",91 "ifb" : "text/calendar",92 "iso" : "application/octet-stream",93 "jar" : "application/java-archive",94 "java" : "text/x-java-source",95 "jnlp" : "application/x-java-jnlp-file",96 "jpeg" : "image/jpeg",97 "jpg" : "image/jpeg",98 "js" : "application/javascript",99 "json" : "application/json",100 "log" : "text/plain",101 "m3u" : "audio/x-mpegurl",102 "m4v" : "video/mp4",103 "man" : "text/troff",104 "mathml" : "application/mathml+xml",105 "mbox" : "application/mbox",106 "mdoc" : "text/troff",107 "me" : "text/troff",108 "mid" : "audio/midi",109 "midi" : "audio/midi",110 "mime" : "message/rfc822",111 "mml" : "application/mathml+xml",112 "mng" : "video/x-mng",113 "mov" : "video/quicktime",114 "mp3" : "audio/mpeg",115 "mp4" : "video/mp4",116 "mp4v" : "video/mp4",117 "mpeg" : "video/mpeg",118 "mpg" : "video/mpeg",119 "ms" : "text/troff",120 "msi" : "application/x-msdownload",121 "odp" : "application/vnd.oasis.opendocument.presentation",122 "ods" : "application/vnd.oasis.opendocument.spreadsheet",123 "odt" : "application/vnd.oasis.opendocument.text",124 "ogg" : "application/ogg",125 "p" : "text/x-pascal",126 "pas" : "text/x-pascal",127 "pbm" : "image/x-portable-bitmap",128 "pdf" : "application/pdf",129 "pem" : "application/x-x509-ca-cert",130 "pgm" : "image/x-portable-graymap",131 "pgp" : "application/pgp-encrypted",132 "pkg" : "application/octet-stream",133 "pl" : "text/x-script.perl",134 "pm" : "text/x-script.perl-module",135 "png" : "image/png",136 "pnm" : "image/x-portable-anymap",137 "ppm" : "image/x-portable-pixmap",138 "pps" : "application/vnd.ms-powerpoint",139 "ppt" : "application/vnd.ms-powerpoint",140 "ps" : "application/postscript",141 "psd" : "image/vnd.adobe.photoshop",142 "py" : "text/x-script.python",143 "qt" : "video/quicktime",144 "ra" : "audio/x-pn-realaudio",145 "rake" : "text/x-script.ruby",146 "ram" : "audio/x-pn-realaudio",147 "rar" : "application/x-rar-compressed",148 "rb" : "text/x-script.ruby",149 "rdf" : "application/rdf+xml",150 "roff" : "text/troff",151 "rpm" : "application/x-redhat-package-manager",152 "rss" : "application/rss+xml",153 "rtf" : "application/rtf",154 "ru" : "text/x-script.ruby",155 "s" : "text/x-asm",156 "sgm" : "text/sgml",157 "sgml" : "text/sgml",158 "sh" : "application/x-sh",159 "sig" : "application/pgp-signature",160 "snd" : "audio/basic",161 "so" : "application/octet-stream",162 "svg" : "image/svg+xml",163 "svgz" : "image/svg+xml",164 "swf" : "application/x-shockwave-flash",165 "t" : "text/troff",166 "tar" : "application/x-tar",167 "tbz" : "application/x-bzip-compressed-tar",168 "tcl" : "application/x-tcl",169 "tex" : "application/x-tex",170 "texi" : "application/x-texinfo",171 "texinfo" : "application/x-texinfo",172 "text" : "text/plain",173 "tif" : "image/tiff",174 "tiff" : "image/tiff",175 "torrent" : "application/x-bittorrent",176 "tr" : "text/troff",177 "txt" : "text/plain",178 "vcf" : "text/x-vcard",179 "vcs" : "text/x-vcalendar",180 "vrml" : "model/vrml",181 "war" : "application/java-archive",182 "wav" : "audio/x-wav",183 "wma" : "audio/x-ms-wma",184 "wmv" : "video/x-ms-wmv",185 "wmx" : "video/x-ms-wmx",186 "wrl" : "model/vrml",187 "wsdl" : "application/wsdl+xml",188 "xbm" : "image/x-xbitmap",189 "xhtml" : "application/xhtml+xml",190 "xls" : "application/vnd.ms-excel",191 "xml" : "application/xml",192 "xpm" : "image/x-xpixmap",193 "xsl" : "application/xml",194 "xslt" : "application/xslt+xml",195 "yaml" : "text/yaml",196 "yml" : "text/yaml",197 "zip" : "application/zip"198 }199 }200 }201 202})()
deleted:lib/express.mocks.js-119 removed
12// Express - Mocks - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){5 6 /**7 * Mock _request_ object. Optionally pass hash of properties.8 *9 * @param {hash} request10 * @return {hash}11 * @api public12 */13 14 function mockRequest(request) {15 var mock = {16 listeners : [],17 method : 'GET',18 headers : [],19 uri : {20 path : '/',21 params : {}22 },23 setBodyEncoding : function(type) {24 this.bodyEncoding = type 25 },26 addListener : function(event, callback) {27 this.listeners.push({ event : event, callback : callback })28 if (event == 'body') {29 var body = this.body30 this.body = ''31 callback(body)32 }33 else34 callback()35 }36 }37 JSpec.extend(mock, request)38 mock.uri.params = mock.uri.params || {}39 return mock40 }41 42 /**43 * Mock _response_ object. Optionally pass hash of properties.44 *45 * @param {hash} response46 * @return {hash}47 * @api public48 */49 50 function mockResponse(response) {51 var mock = {52 body : null,53 status : 200,54 headers : [],55 sendHeader : function(){},56 sendBody : function(){},57 finish : function(){ this.finished = true }58 }59 JSpec.extend(mock, response)60 return mock61 }62 63 /**64 * Mock server callback.65 *66 * @param {object} request67 * @param {object} response68 * @api private69 */70 71 var orig = Express.server.callback72 function mockCallback(request, response) {73 orig(mockRequest(request), mockResponse(response))74 }75 76 /**77 * Mock route function for HTTP _method_.78 *79 * @param {string} method80 * @return {function}81 * @api private82 */83 84 function mockRouteFunctionFor(method) {85 var orig = Express.routeFunctionFor(method)86 return function(path, options, callback) {87 if ((options && options.constructor == Function) || (callback && callback.constructor == Function)) {88 return orig.apply(Express, arguments)89 }90 var request = mockRequest({ method : method.toUpperCase(), uri : { path : path }})91 if (options) {92 JSpec.extend(request, options.request)93 //restore the path, since the mockRequest defaults it to "/"94 request.uri.path = path95 }96 var response = mockResponse()97 Express.server.callback(request, response)98 return Express.response99 }100 }101 102 // --- Module103 104 JSpec.include({105 init : function() {106 Express.server.callback = mockCallback107 },108 109 utilities : {110 mockRequest : mockRequest,111 mockResponse : mockResponse,112 get : mockRouteFunctionFor('get'),113 post : mockRouteFunctionFor('post'),114 put : mockRouteFunctionFor('put'),115 del : mockRouteFunctionFor('delete')116 }117 })118 119})()
deleted:lib/express.session.js-10 removed
deleted:lib/express.view.js-10 removed
12// Express - View - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){5 6 Express.View = {7 8 }9 10})()
added:spec/lib/images/bg.pngbinary

A binary file, added.

added:spec/lib/images/hr.pngbinary

A binary file, added.

added:spec/lib/images/loading.gifbinary

A binary file, added.

added:spec/lib/images/sprites.bg.pngbinary

A binary file, added.

added:spec/lib/images/sprites.pngbinary

A binary file, added.

added:spec/lib/images/vr.pngbinary

A binary file, added.

added:spec/lib/jspec.css+149 added
1body.jspec {2 margin: 45px 0;3 font: 12px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;4 background: #efefef url(images/bg.png) top left repeat-x;5 text-align: center;6}7#jspec {8 margin: 0 auto;9 padding-top: 30px;10 width: 1008px;11 background: url(images/vr.png) top left repeat-y;12 text-align: left;13}14#jspec-top {15 position: relative;16 margin: 0 auto;17 width: 1008px;18 height: 40px;19 background: url(images/sprites.bg.png) top left no-repeat;20}21#jspec-bottom {22 margin: 0 auto;23 width: 1008px;24 height: 15px;25 background: url(images/sprites.bg.png) bottom left no-repeat;26}27#jspec .loading {28 margin-top: -45px;29 width: 1008px;30 height: 80px;31 background: url(images/loading.gif) 50% 50% no-repeat;32}33#jspec-title {34 position: absolute;35 top: 15px;36 left: 20px;37 width: 160px;38 font-size: 22px;39 font-weight: normal;40 background: url(images/sprites.png) 0 -126px no-repeat;41 text-align: center;42}43#jspec-title em {44 font-size: 10px;45 font-style: normal;46 color: #BCC8D1;47}48#jspec-report * {49 margin: 0;50 padding: 0;51 background: none;52 border: none;53}54#jspec-report {55 padding: 15px 40px;56 font: 11px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;57 color: #7B8D9B;58}59#jspec-report.has-failures {60 padding-bottom: 30px;61}62#jspec-report .hidden {63 display: none;64}65#jspec-report .heading {66 margin-bottom: 15px;67}68#jspec-report .heading span {69 padding-right: 10px;70}71#jspec-report .heading .passes em {72 color: #0ea0eb;73}74#jspec-report .heading .failures em {75 color: #FA1616;76}77#jspec-report table {78 font-size: 11px;79 border-collapse: collapse;80}81#jspec-report td {82 padding: 8px;83 text-indent: 30px;84 color: #7B8D9B;85}86#jspec-report tr.body {87 display: none;88}89#jspec-report tr.body pre {90 margin: 0;91 padding: 0 0 5px 25px;92}93#jspec-report tr.even:hover + tr.body, 94#jspec-report tr.odd:hover + tr.body {95 display: block;96}97#jspec-report tr td:first-child em {98 display: block;99 clear: both;100 font-style: normal;101 font-weight: normal;102 color: #7B8D9B;103}104#jspec-report tr.even:hover, 105#jspec-report tr.odd:hover {106 text-shadow: 1px 1px 1px #fff;107 background: #F2F5F7;108}109#jspec-report td + td {110 padding-right: 0;111 width: 15px;112}113#jspec-report td.pass {114 background: url(images/sprites.png) 3px -7px no-repeat;115}116#jspec-report td.fail {117 background: url(images/sprites.png) 3px -47px no-repeat;118 font-weight: bold;119 color: #FC0D0D;120}121#jspec-report td.requires-implementation {122 background: url(images/sprites.png) 3px -87px no-repeat;123}124#jspec-report tr.description td {125 margin-top: 25px;126 padding-top: 25px;127 font-size: 12px;128 font-weight: bold;129 text-indent: 0;130 color: #1a1a1a;131}132#jspec-report tr.description:first-child td {133 border-top: none; 134}135#jspec-report .assertion {136 display: block;137 float: left;138 margin: 0 0 0 1px;139 padding: 0;140 width: 1px;141 height: 5px;142 background: #7B8D9B;143}144#jspec-report .assertion.failed {145 background: red;146}147.jspec-sandbox {148 display: none;149}
added:spec/lib/jspec.jquery.js+71 added
12// JSpec - jQuery - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34JSpec5.requires('jQuery', 'when using jspec.jquery.js')6.include({7 name: 'jQuery',8 9 // --- Initialize10 11 init : function() {12 jQuery.ajaxSetup({ async: false })13 },14 15 // --- Utilities16 17 utilities : {18 element: jQuery,19 elements: jQuery,20 sandbox : function() {21 return jQuery('<div class="sandbox"></div>')22 }23 },24 25 // --- Matchers26 27 matchers : {28 have_tag : "jQuery(expected, actual).length == 1",29 have_one : "alias have_tag",30 have_tags : "jQuery(expected, actual).length > 1",31 have_many : "alias have_tags",32 have_child : "jQuery(actual).children(expected).length == 1",33 have_children : "jQuery(actual).children(expected).length > 1",34 have_text : "jQuery(actual).text() == expected",35 have_value : "jQuery(actual).val() == expected",36 be_enabled : "!jQuery(actual).attr('disabled')",37 have_class : "jQuery(actual).hasClass(expected)",38 39 be_visible : function(actual) {40 return jQuery(actual).css('display') != 'none' &&41 jQuery(actual).css('visibility') != 'hidden' &&42 jQuery(actual).attr('type') != 'hidden'43 },44 45 be_hidden : function(actual) {46 return !JSpec.does(actual, 'be_visible')47 },4849 have_classes : function(actual) {50 return !JSpec.any(JSpec.argumentsToArray(arguments, 1), function(arg){51 return !JSpec.does(actual, 'have_class', arg)52 })53 },5455 have_attr : function(actual, attr, value) {56 return value ? jQuery(actual).attr(attr) == value:57 jQuery(actual).attr(attr)58 },59 60 'be disabled selected checked' : function(attr) {61 return 'jQuery(actual).attr("' + attr + '")'62 },63 64 'have type id title alt href src sel rev name target' : function(attr) {65 return function(actual, value) {66 return JSpec.does(actual, 'have_attr', attr, value)67 }68 }69 }70})71
added:spec/lib/jspec.js+1776 added
12// JSpec - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){56 JSpec = {78 version : '2.11.13',9 cache : {},10 suites : [],11 modules : [],12 allSuites : [],13 matchers : {},14 stubbed : [],15 request : 'XMLHttpRequest' in this ? XMLHttpRequest : null,16 stats : { specs: 0, assertions: 0, failures: 0, passes: 0, specsFinished: 0, suitesFinished: 0 },17 options : { profile: false },1819 /**20 * Default context in which bodies are evaluated.21 *22 * Replace context simply by setting JSpec.context23 * to your own like below:24 *25 * JSpec.context = { foo : 'bar' }26 *27 * Contexts can be changed within any body, this can be useful28 * in order to provide specific helper methods to specific suites.29 *30 * To reset (usually in after hook) simply set to null like below:31 *32 * JSpec.context = null33 *34 */3536 defaultContext : {37 38 /**39 * Return an object used for proxy assertions. 40 * This object is used to indicate that an object41 * should be an instance of _object_, not the constructor42 * itself.43 *44 * @param {function} constructor45 * @return {hash}46 * @api public47 */48 49 an_instance_of : function(constructor) {50 return { an_instance_of : constructor }51 },52 53 /**54 * Load fixture at _path_. This utility function55 * supplies the means to resolve, and cache fixture contents56 * via the DOM or Rhino.57 *58 * Fixtures are resolved as:59 *60 * - <path>61 * - fixtures/<path>62 * - fixtures/<path>.html63 *64 * @param {string} path65 * @return {string}66 * @api public67 */68 69 fixture : function(path) {70 if (JSpec.cache[path]) return JSpec.cache[path]71 return JSpec.cache[path] = 72 JSpec.tryLoading(path) ||73 JSpec.tryLoading('fixtures/' + path) ||74 JSpec.tryLoading('fixtures/' + path + '.html') ||75 JSpec.tryLoading('spec/' + path) ||76 JSpec.tryLoading('spec/fixtures/' + path) ||77 JSpec.tryLoading('spec/fixtures/' + path + '.html')78 }79 },8081 // --- Objects82 83 formatters : {84 85 /**86 * Report to server.87 * 88 * Options:89 * - uri specific uri to report to.90 * - verbose weither or not to output messages91 * - failuresOnly output failure messages only92 *93 * @api public94 */95 96 Server : function(results, options) {97 var uri = options.uri || 'http://' + window.location.host + '/results'98 JSpec.post(uri, {99 stats: JSpec.stats,100 options: options,101 results: map(results.allSuites, function(suite) {102 if (suite.hasSpecs())103 return {104 description: suite.description,105 specs: map(suite.specs, function(spec) {106 return {107 description: spec.description,108 message: !spec.passed() ? spec.failure().message : null,109 status: spec.requiresImplementation() ? 'pending' :110 spec.passed() ? 'pass' :111 'fail',112 assertions: map(spec.assertions, function(assertion){113 return {114 passed: assertion.passed 115 }116 })117 }118 })119 }120 })121 })122 if ('close' in main) main.close()123 },124125 /**126 * Default formatter, outputting to the DOM.127 *128 * Options:129 * - reportToId id of element to output reports to, defaults to 'jspec'130 * - failuresOnly displays only suites with failing specs131 *132 * @api public133 */134135 DOM : function(results, options) {136 var id = option('reportToId') || 'jspec'137 var report = document.getElementById(id)138 var failuresOnly = option('failuresOnly')139 var classes = results.stats.failures ? 'has-failures' : ''140 if (!report) throw 'JSpec requires the element #' + id + ' to output its reports'141 142 function bodyContents(body) {143 return JSpec.144 escape(JSpec.contentsOf(body)).145 replace(/^ */gm, function(a){ return (new Array(Math.round(a.length / 3))).join(' ') }).146 replace(/\r\n|\r|\n/gm, '<br/>')147 }148 149 report.innerHTML = '<div id="jspec-report" class="' + classes + '"><div class="heading"> \150 <span class="passes">Passes: <em>' + results.stats.passes + '</em></span> \151 <span class="failures">Failures: <em>' + results.stats.failures + '</em></span> \152 </div><table class="suites">' + map(results.allSuites, function(suite) {153 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran154 if (displaySuite && suite.hasSpecs())155 return '<tr class="description"><td colspan="2">' + escape(suite.description) + '</td></tr>' +156 map(suite.specs, function(i, spec) {157 return '<tr class="' + (i % 2 ? 'odd' : 'even') + '">' +158 (spec.requiresImplementation() ?159 '<td class="requires-implementation" colspan="2">' + escape(spec.description) + '</td>' :160 (spec.passed() && !failuresOnly) ?161 '<td class="pass">' + escape(spec.description)+ '</td><td>' + spec.assertionsGraph() + '</td>' :162 !spec.passed() ?163 '<td class="fail">' + escape(spec.description) + 164 map(spec.failures(), function(a){ return '<em>' + escape(a.message) + '</em>' }).join('') +165 '</td><td>' + spec.assertionsGraph() + '</td>' :166 '') +167 '<tr class="body"><td colspan="2"><pre>' + bodyContents(spec.body) + '</pre></td></tr>'168 }).join('') + '</tr>'169 }).join('') + '</table></div>'170 },171 172 /**173 * Terminal formatter.174 *175 * @api public176 */177 178 Terminal : function(results, options) {179 failuresOnly = option('failuresOnly')180 print(color("\n Passes: ", 'bold') + color(results.stats.passes, 'green') + 181 color(" Failures: ", 'bold') + color(results.stats.failures, 'red') + "\n")182 183 function indent(string) {184 return string.replace(/^(.)/gm, ' $1')185 }186 187 each(results.allSuites, function(suite) {188 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran189 if (displaySuite && suite.hasSpecs()) {190 print(color(' ' + suite.description, 'bold'))191 each(suite.specs, function(spec){192 var assertionsGraph = inject(spec.assertions, '', function(graph, assertion){193 return graph + color('.', assertion.passed ? 'green' : 'red')194 })195 if (spec.requiresImplementation())196 print(color(' ' + spec.description, 'blue') + assertionsGraph)197 else if (spec.passed() && !failuresOnly)198 print(color(' ' + spec.description, 'green') + assertionsGraph)199 else if (!spec.passed())200 print(color(' ' + spec.description, 'red') + assertionsGraph + 201 "\n" + indent(map(spec.failures(), function(a){ return a.message }).join("\n")) + "\n")202 })203 print("")204 }205 })206 207 quit(results.stats.failures)208 },209210 /**211 * Console formatter.212 *213 * @api public214 */215216 Console : function(results, options) {217 console.log('')218 console.log('Passes: ' + results.stats.passes + ' Failures: ' + results.stats.failures)219 each(results.allSuites, function(suite) {220 if (suite.ran) {221 console.group(suite.description)222 each(suite.specs, function(spec){223 var assertionCount = spec.assertions.length + ':'224 if (spec.requiresImplementation())225 console.warn(spec.description)226 else if (spec.passed())227 console.log(assertionCount + ' ' + spec.description)228 else 229 console.error(assertionCount + ' ' + spec.description + ', ' + spec.failure().message)230 })231 console.groupEnd()232 }233 })234 }235 },236 237 Assertion : function(matcher, actual, expected, negate) {238 extend(this, {239 message: '',240 passed: false,241 actual: actual,242 negate: negate,243 matcher: matcher,244 expected: expected,245 246 // Report assertion results247 248 report : function() {249 this.passed ? JSpec.stats.passes++ : JSpec.stats.failures++250 return this251 },252 253 // Run the assertion254 255 run : function() {256 // TODO: remove unshifting 257 expected.unshift(actual)258 this.result = matcher.match.apply(this, expected)259 this.passed = negate ? !this.result : this.result260 if (!this.passed) this.message = matcher.message.call(this, actual, expected, negate, matcher.name)261 return this262 }263 })264 },265 266 ProxyAssertion : function(object, method, times, negate) {267 var self = this268 var old = object[method]269 270 // Proxy271 272 object[method] = function(){273 args = argumentsToArray(arguments)274 result = old.apply(object, args)275 self.calls.push({ args : args, result : result })276 return result277 }278 279 // Times280 281 this.times = {282 once : 1,283 twice : 2284 }[times] || times || 1285 286 extend(this, {287 calls: [],288 message: '',289 defer: true,290 passed: false,291 negate: negate,292 object: object,293 method: method,294 295 // Proxy return value296 297 and_return : function(result) {298 this.expectedResult = result299 return this300 },301 302 // Proxy arguments passed303 304 with_args : function() {305 this.expectedArgs = argumentsToArray(arguments)306 return this307 },308 309 // Check if any calls have failing results310 311 anyResultsFail : function() {312 return any(this.calls, function(call){313 return self.expectedResult.an_instance_of ?314 call.result.constructor != self.expectedResult.an_instance_of:315 hash(self.expectedResult) != hash(call.result)316 })317 },318 319 // Check if any calls have passing results320 321 anyResultsPass : function() {322 return any(this.calls, function(call){323 return self.expectedResult.an_instance_of ?324 call.result.constructor == self.expectedResult.an_instance_of:325 hash(self.expectedResult) == hash(call.result)326 })327 },328 329 // Return the passing result330 331 passingResult : function() {332 return this.anyResultsPass().result333 },334335 // Return the failing result336 337 failingResult : function() {338 return this.anyResultsFail().result339 },340 341 // Check if any arguments fail342 343 anyArgsFail : function() {344 return any(this.calls, function(call){345 return any(self.expectedArgs, function(i, arg){346 if (arg == null) return call.args[i] == null347 return arg.an_instance_of ?348 call.args[i].constructor != arg.an_instance_of:349 hash(arg) != hash(call.args[i])350 351 })352 })353 },354 355 // Check if any arguments pass356 357 anyArgsPass : function() {358 return any(this.calls, function(call){359 return any(self.expectedArgs, function(i, arg){360 return arg.an_instance_of ?361 call.args[i].constructor == arg.an_instance_of:362 hash(arg) == hash(call.args[i])363 364 })365 })366 },367 368 // Return the passing args369 370 passingArgs : function() {371 return this.anyArgsPass().args372 },373 374 // Return the failing args375 376 failingArgs : function() {377 return this.anyArgsFail().args378 },379 380 // Report assertion results381 382 report : function() {383 this.passed ? ++JSpec.stats.passes : ++JSpec.stats.failures384 return this385 },386 387 // Run the assertion388 389 run : function() {390 var methodString = 'expected ' + object.toString() + '.' + method + '()' + (negate ? ' not' : '' )391 392 function times(n) {393 return n > 2 ? n + ' times' : { 1: 'once', 2: 'twice' }[n]394 }395 396 if (this.expectedResult != null && (negate ? this.anyResultsPass() : this.anyResultsFail()))397 this.message = methodString + ' to return ' + puts(this.expectedResult) + 398 ' but ' + (negate ? 'it did' : 'got ' + puts(this.failingResult())) 399400 if (this.expectedArgs && (negate ? !this.expectedResult && this.anyArgsPass() : this.anyArgsFail()))401 this.message = methodString + ' to be called with ' + puts.apply(this, this.expectedArgs) +402 ' but was' + (negate ? '' : ' called with ' + puts.apply(this, this.failingArgs()))403404 if (negate ? !this.expectedResult && !this.expectedArgs && this.calls.length >= this.times : this.calls.length != this.times)405 this.message = methodString + ' to be called ' + times(this.times) + 406 ', but ' + (this.calls.length == 0 ? ' was not called' : ' was called ' + times(this.calls.length))407 408 if (!this.message.length) 409 this.passed = true410 411 return this412 }413 })414 },415 416 /**417 * Specification Suite block object.418 *419 * @param {string} description420 * @param {function} body421 * @api private422 */423424 Suite : function(description, body) {425 var self = this426 extend(this, {427 body: body,428 description: description,429 suites: [],430 specs: [],431 ran: false,432 hooks: { 'before' : [], 'after' : [], 'before_each' : [], 'after_each' : [] },433 434 // Add a spec to the suite435436 addSpec : function(description, body) {437 var spec = new JSpec.Spec(description, body)438 this.specs.push(spec)439 JSpec.stats.specs++ // TODO: abstract440 spec.suite = this441 },442443 // Add a hook to the suite444445 addHook : function(hook, body) {446 this.hooks[hook].push(body)447 },448449 // Add a nested suite450451 addSuite : function(description, body) {452 var suite = new JSpec.Suite(description, body)453 JSpec.allSuites.push(suite)454 suite.name = suite.description455 suite.description = this.description + ' ' + suite.description456 this.suites.push(suite)457 suite.suite = this458 },459460 // Invoke a hook in context to this suite461462 hook : function(hook) {463 if (this.suite) this.suite.hook(hook)464 each(this.hooks[hook], function(body) {465 JSpec.evalBody(body, "Error in hook '" + hook + "', suite '" + self.description + "': ")466 })467 },468469 // Check if nested suites are present470471 hasSuites : function() {472 return this.suites.length 473 },474475 // Check if this suite has specs476477 hasSpecs : function() {478 return this.specs.length479 },480481 // Check if the entire suite passed482483 passed : function() {484 return !any(this.specs, function(spec){485 return !spec.passed() 486 })487 }488 })489 },490 491 /**492 * Specification block object.493 *494 * @param {string} description495 * @param {function} body496 * @api private497 */498499 Spec : function(description, body) {500 extend(this, {501 body: body,502 description: description,503 assertions: [],504 505 // Add passing assertion506 507 pass : function(message) {508 this.assertions.push({ passed: true, message: message })509 ++JSpec.stats.passes510 },511 512 // Add failing assertion513 514 fail : function(message) {515 this.assertions.push({ passed: false, message: message })516 ++JSpec.stats.failures517 },518 519 // Run deferred assertions520 521 runDeferredAssertions : function() {522 each(this.assertions, function(assertion){523 if (assertion.defer) assertion.run().report(), hook('afterAssertion', assertion)524 })525 },526 527 // Find first failing assertion528529 failure : function() {530 return find(this.assertions, function(assertion){531 return !assertion.passed532 })533 },534535 // Find all failing assertions536537 failures : function() {538 return select(this.assertions, function(assertion){539 return !assertion.passed540 })541 },542543 // Weither or not the spec passed544545 passed : function() {546 return !this.failure()547 },548549 // Weither or not the spec requires implementation (no assertions)550551 requiresImplementation : function() {552 return this.assertions.length == 0553 },554555 // Sprite based assertions graph556557 assertionsGraph : function() {558 return map(this.assertions, function(assertion){559 return '<span class="assertion ' + (assertion.passed ? 'passed' : 'failed') + '"></span>'560 }).join('')561 }562 })563 },564 565 Module : function(methods) {566 extend(this, methods)567 },568 569 JSON : {570 571 /**572 * Generic sequences.573 */574 575 meta : {576 '\b' : '\\b',577 '\t' : '\\t',578 '\n' : '\\n',579 '\f' : '\\f',580 '\r' : '\\r',581 '"' : '\\"',582 '\\' : '\\\\'583 },584 585 /**586 * Escapable sequences.587 */588 589 escapable : /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,590 591 /**592 * JSON encode _object_.593 *594 * @param {mixed} object595 * @return {string}596 * @api private597 */598 599 encode : function(object) {600 var self = this601 if (object == undefined || object == null) return 'null'602 if (object === true) return 'true'603 if (object === false) return 'false'604 switch (typeof object) {605 case 'number': return object606 case 'string': return this.escapable.test(object) ?607 '"' + object.replace(this.escapable, function (a) {608 return typeof self.meta[a] === 'string' ? self.meta[a] :609 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4)610 }) + '"' :611 '"' + object + '"'612 case 'object': 613 if (object.constructor == Array)614 return '[' + map(object, function(val){615 return self.encode(val)616 }).join(', ') + ']'617 else if (object)618 return '{' + map(object, function(key, val){619 return self.encode(key) + ':' + self.encode(val)620 }).join(', ') + '}'621 }622 return 'null'623 }624 },625 626 // --- DSLs627 628 DSLs : {629 snake : {630 expect : function(actual){631 return JSpec.expect(actual)632 },633634 describe : function(description, body) {635 return JSpec.currentSuite.addSuite(description, body)636 },637638 it : function(description, body) {639 return JSpec.currentSuite.addSpec(description, body)640 },641642 before : function(body) {643 return JSpec.currentSuite.addHook('before', body)644 },645646 after : function(body) {647 return JSpec.currentSuite.addHook('after', body)648 },649650 before_each : function(body) {651 return JSpec.currentSuite.addHook('before_each', body)652 },653654 after_each : function(body) {655 return JSpec.currentSuite.addHook('after_each', body)656 },657 658 should_behave_like : function(description) {659 return JSpec.shareBehaviorsOf(description)660 }661 }662 },663664 // --- Methods665 666 /**667 * Check if _value_ is 'stop'. For use as a668 * utility callback function.669 *670 * @param {mixed} value671 * @return {bool}672 * @api public673 */674 675 haveStopped : function(value) {676 return value === 'stop'677 },678 679 /**680 * Include _object_ which may be a hash or Module instance.681 *682 * @param {has, Module} object683 * @return {JSpec}684 * @api public685 */686 687 include : function(object) {688 var module = object.constructor == JSpec.Module ? object : new JSpec.Module(object)689 this.modules.push(module)690 if ('init' in module) module.init()691 if ('utilities' in module) extend(this.defaultContext, module.utilities)692 if ('matchers' in module) this.addMatchers(module.matchers)693 if ('formatters' in module) extend(this.formatters, module.formatters)694 if ('DSLs' in module)695 each(module.DSLs, function(name, methods){696 JSpec.DSLs[name] = JSpec.DSLs[name] || {}697 extend(JSpec.DSLs[name], methods)698 })699 return this700 },701 702 /**703 * Add a module hook _name_, which is immediately704 * called per module with the _args_ given. An array of705 * hook return values is returned.706 *707 * @param {name} string708 * @param {...} args709 * @return {array}710 * @api private711 */712 713 hook : function(name, args) {714 args = argumentsToArray(arguments, 1)715 return inject(JSpec.modules, [], function(results, module){716 if (typeof module[name] == 'function')717 results.push(JSpec.evalHook(module, name, args))718 })719 },720 721 /**722 * Eval _module_ hook _name_ with _args_. Evaluates in context723 * to the module itself, JSpec, and JSpec.context.724 *725 * @param {Module} module726 * @param {string} name727 * @param {array} args728 * @return {mixed}729 * @api private730 */731 732 evalHook : function(module, name, args) {733 hook('evaluatingHookBody', module, name)734 try { return module[name].apply(module, args) }735 catch(e) { error('Error in hook ' + module.name + '.' + name + ': ', e) }736 },737 738 /**739 * Same as hook() however accepts only one _arg_ which is740 * considered immutable. This function passes the arg741 * to the first module, then passes the return value of the last742 * module called, to the following module. 743 *744 * @param {string} name745 * @param {mixed} arg746 * @return {mixed}747 * @api private748 */749 750 hookImmutable : function(name, arg) {751 return inject(JSpec.modules, arg, function(result, module){752 if (typeof module[name] == 'function')753 return JSpec.evalHook(module, name, [result])754 })755 },756 757 /**758 * Find a suite by its description or name.759 *760 * @param {string} description761 * @return {Suite}762 * @api private763 */764 765 findSuite : function(description) {766 return find(this.allSuites, function(suite){767 return suite.name == description || suite.description == description768 })769 },770 771 /**772 * Share behaviors (specs) of the given suite with773 * the current suite.774 *775 * @param {string} description776 * @api public777 */778 779 shareBehaviorsOf : function(description) {780 if (suite = this.findSuite(description)) this.copySpecs(suite, this.currentSuite)781 else throw 'failed to share behaviors. ' + puts(description) + ' is not a valid Suite name'782 },783 784 /**785 * Copy specs from one suite to another. 786 *787 * @param {Suite} fromSuite788 * @param {Suite} toSuite789 * @api public790 */791 792 copySpecs : function(fromSuite, toSuite) {793 each(fromSuite.specs, function(spec){794 spec.assertions = []795 toSuite.specs.push(spec)796 })797 },798 799 /**800 * Convert arguments to an array.801 *802 * @param {object} arguments803 * @param {int} offset804 * @return {array}805 * @api public806 */807 808 argumentsToArray : function(arguments, offset) {809 return Array.prototype.slice.call(arguments, offset || 0)810 },811 812 /**813 * Return ANSI-escaped colored string.814 *815 * @param {string} string816 * @param {string} color817 * @return {string}818 * @api public819 */820 821 color : function(string, color) {822 return "\u001B[" + {823 bold : 1,824 black : 30,825 red : 31,826 green : 32,827 yellow : 33,828 blue : 34,829 magenta : 35,830 cyan : 36,831 white : 37832 }[color] + 'm' + string + "\u001B[0m"833 },834 835 /**836 * Default matcher message callback.837 *838 * @api private839 */840 841 defaultMatcherMessage : function(actual, expected, negate, name) {842 return 'expected ' + puts(actual) + ' to ' + 843 (negate ? 'not ' : '') + 844 name.replace(/_/g, ' ') +845 ' ' + puts.apply(this, expected.slice(1))846 },847 848 /**849 * Normalize a matcher message.850 *851 * When no messge callback is present the defaultMatcherMessage852 * will be assigned, will suffice for most matchers.853 *854 * @param {hash} matcher855 * @return {hash}856 * @api public857 */858 859 normalizeMatcherMessage : function(matcher) {860 if (typeof matcher.message != 'function') 861 matcher.message = this.defaultMatcherMessage862 return matcher863 },864 865 /**866 * Normalize a matcher body867 * 868 * This process allows the following conversions until869 * the matcher is in its final normalized hash state.870 *871 * - '==' becomes 'actual == expected'872 * - 'actual == expected' becomes 'return actual == expected'873 * - function(actual, expected) { return actual == expected } becomes 874 * { match : function(actual, expected) { return actual == expected }}875 *876 * @param {mixed} body877 * @return {hash}878 * @api public879 */880 881 normalizeMatcherBody : function(body) {882 switch (body.constructor) {883 case String:884 if (captures = body.match(/^alias (\w+)/)) return JSpec.matchers[last(captures)]885 if (body.length < 4) body = 'actual ' + body + ' expected'886 return { match: function(actual, expected) { return eval(body) }} 887 888 case Function:889 return { match: body }890 891 default:892 return body893 }894 },895 896 /**897 * Get option value. This method first checks if898 * the option key has been set via the query string,899 * otherwise returning the options hash value.900 *901 * @param {string} key902 * @return {mixed}903 * @api public904 */905 906 option : function(key) {907 return (value = query(key)) !== null ? value :908 JSpec.options[key] || null909 },910911 /**912 * Generates a hash of the object passed.913 *914 * @param {object} object915 * @return {string}916 * @api private917 */918919 hash : function(object) {920 if (object == null) return 'null'921 if (object == undefined) return 'undefined'922 function serialize(prefix) {923 return inject(object, prefix + ':', function(buffer, key, value){924 return buffer += hash(value)925 })926 }927 switch (object.constructor) {928 case Array : return serialize('a')929 case RegExp: return 'r:' + object.toString()930 case Number: return 'n:' + object.toString()931 case String: return 's:' + object.toString()932 case Object: return 'o:' + inject(object, [], function(array, key, value){933 array.push([key, hash(value)])934 }).sort()935 default: return object.toString()936 }937 },938939 /**940 * Return last element of an array.941 *942 * @param {array} array943 * @return {object}944 * @api public945 */946947 last : function(array) {948 return array[array.length - 1]949 },950951 /**952 * Convert object(s) to a print-friend string.953 *954 * @param {...} object955 * @return {string}956 * @api public957 */958959 puts : function(object) {960 if (arguments.length > 1) {961 return map(argumentsToArray(arguments), function(arg){962 return puts(arg)963 }).join(', ')964 }965 if (object === undefined) return ''966 if (object === null) return 'null'967 if (object === true) return 'true'968 if (object === false) return 'false'969 if (object.an_instance_of) return 'an instance of ' + object.an_instance_of.name970 if (object.jquery && object.selector.length > 0) return 'selector ' + puts(object.selector) + ''971 if (object.jquery) return object.get(0).outerHTML972 if (object.nodeName) return object.outerHTML973 switch (object.constructor) {974 case String: return "'" + object + "'"975 case Number: return object976 case Function: return object.name || object 977 case Array: 978 return inject(object, '[', function(b, v){979 return b + ', ' + puts(v)980 }).replace('[,', '[') + ' ]'981 case Object:982 return inject(object, '{', function(b, k, v) {983 return b + ', ' + puts(k) + ' : ' + puts(v)984 }).replace('{,', '{') + ' }'985 default: 986 return object.toString()987 }988 },989990 /**991 * Escape HTML.992 *993 * @param {string} html994 * @return {string}995 * @api public996 */997998 escape : function(html) {999 return html.toString()1000 .replace(/&/gmi, '&amp;')1001 .replace(/"/gmi, '&quot;')1002 .replace(/>/gmi, '&gt;')1003 .replace(/</gmi, '&lt;')1004 },1005 1006 /**1007 * Perform an assertion without reporting.1008 *1009 * This method is primarily used for internal1010 * matchers in order retain DRYness. May be invoked 1011 * like below:1012 *1013 * does('foo', 'eql', 'foo')1014 * does([1,2], 'include', 1, 2)1015 *1016 * External hooks are not run for internal assertions1017 * performed by does().1018 *1019 * @param {mixed} actual1020 * @param {string} matcher1021 * @param {...} expected1022 * @return {mixed}1023 * @api private1024 */1025 1026 does : function(actual, matcher, expected) {1027 var assertion = new JSpec.Assertion(JSpec.matchers[matcher], actual, argumentsToArray(arguments, 2))1028 return assertion.run().result1029 },10301031 /**1032 * Perform an assertion.1033 *1034 * expect(true).to('be', true)1035 * expect('foo').not_to('include', 'bar')1036 * expect([1, [2]]).to('include', 1, [2])1037 *1038 * @param {mixed} actual1039 * @return {hash}1040 * @api public1041 */10421043 expect : function(actual) {1044 assert = function(matcher, args, negate) {1045 var expected = argumentsToArray(args, 1)1046 matcher.negate = negate 1047 assertion = new JSpec.Assertion(matcher, actual, expected, negate)1048 hook('beforeAssertion', assertion)1049 if (matcher.defer) assertion.run()1050 else JSpec.currentSpec.assertions.push(assertion.run().report()), hook('afterAssertion', assertion)1051 return assertion.result1052 }1053 1054 to = function(matcher) {1055 return assert(matcher, arguments, false)1056 }1057 1058 not_to = function(matcher) {1059 return assert(matcher, arguments, true)1060 }1061 1062 return {1063 to : to,1064 should : to,1065 not_to: not_to,1066 should_not : not_to1067 }1068 },10691070 /**1071 * Strim whitespace or chars.1072 *1073 * @param {string} string1074 * @param {string} chars1075 * @return {string}1076 * @api public1077 */10781079 strip : function(string, chars) {1080 return string.1081 replace(new RegExp('[' + (chars || '\\s') + ']*$'), '').1082 replace(new RegExp('^[' + (chars || '\\s') + ']*'), '')1083 },1084 1085 /**1086 * Call an iterator callback with arguments a, or b1087 * depending on the arity of the callback.1088 *1089 * @param {function} callback1090 * @param {mixed} a1091 * @param {mixed} b1092 * @return {mixed}1093 * @api private1094 */1095 1096 callIterator : function(callback, a, b) {1097 return callback.length == 1 ? callback(b) : callback(a, b)1098 },1099 1100 /**1101 * Extend an object with another.1102 *1103 * @param {object} object1104 * @param {object} other1105 * @api public1106 */1107 1108 extend : function(object, other) {1109 each(other, function(property, value){1110 object[property] = value1111 })1112 },1113 1114 /**1115 * Iterate an object, invoking the given callback.1116 *1117 * @param {hash, array, string} object1118 * @param {function} callback1119 * @return {JSpec}1120 * @api public1121 */11221123 each : function(object, callback) {1124 if (typeof object == 'string') object = object.split(' ')1125 for (key in object) 1126 if (object.hasOwnProperty(key))1127 callIterator(callback, key, object[key])1128 },11291130 /**1131 * Iterate with memo.1132 *1133 * @param {hash, array} object1134 * @param {object} memo1135 * @param {function} callback1136 * @return {object}1137 * @api public1138 */11391140 inject : function(object, memo, callback) {1141 each(object, function(key, value){1142 memo = (callback.length == 2 ?1143 callback(memo, value):1144 callback(memo, key, value)) ||1145 memo1146 })1147 return memo1148 },1149 1150 /**1151 * Destub _object_'s _method_. When no _method_ is passed1152 * all stubbed methods are destubbed. When no arguments1153 * are passed every object found in JSpec.stubbed will be1154 * destubbed.1155 *1156 * @param {mixed} object1157 * @param {string} method1158 * @api public1159 */1160 1161 destub : function(object, method) {1162 if (method) {1163 if (object['__prototype__' + method])1164 delete object[method]1165 else1166 object[method] = object['__original__' + method]1167 delete object['__prototype__' + method]1168 delete object['__original____' + method]1169 }1170 else if (object) {1171 for (var key in object)1172 if (captures = key.match(/^(?:__prototype__|__original__)(.*)/))1173 destub(object, captures[1])1174 }1175 else1176 while (JSpec.stubbed.length)1177 destub(JSpec.stubbed.shift())1178 },1179 1180 /**1181 * Stub _object_'s _method_. 1182 *1183 * stub(foo, 'toString').and_return('bar')1184 *1185 * @param {mixed} object1186 * @param {string} method1187 * @return {hash}1188 * @api public1189 */1190 1191 stub : function(object, method) {1192 hook('stubbing', object, method)1193 JSpec.stubbed.push(object)1194 var type = object.hasOwnProperty(method) ? '__original__' : '__prototype__'1195 object[type + method] = object[method]1196 object[method] = function(){}1197 return {1198 and_return : function(value) {1199 if (typeof value == 'function') object[method] = value1200 else object[method] = function(){ return value }1201 }1202 }1203 },1204 1205 /**1206 * Map callback return values.1207 *1208 * @param {hash, array} object1209 * @param {function} callback1210 * @return {array}1211 * @api public1212 */12131214 map : function(object, callback) {1215 return inject(object, [], function(memo, key, value){1216 memo.push(callIterator(callback, key, value))1217 })1218 },1219 1220 /**1221 * Returns the first matching expression or null.1222 *1223 * @param {hash, array} object1224 * @param {function} callback1225 * @return {mixed}1226 * @api public1227 */1228 1229 any : function(object, callback) {1230 return inject(object, null, function(state, key, value){1231 if (state == undefined)1232 return callIterator(callback, key, value) ? value : state1233 })1234 },1235 1236 /**1237 * Returns an array of values collected when the callback1238 * given evaluates to true.1239 *1240 * @param {hash, array} object1241 * @return {function} callback1242 * @return {array}1243 * @api public1244 */1245 1246 select : function(object, callback) {1247 return inject(object, [], function(selected, key, value){1248 if (callIterator(callback, key, value))1249 selected.push(value)1250 })1251 },12521253 /**1254 * Define matchers.1255 *1256 * @param {hash} matchers1257 * @api public1258 */12591260 addMatchers : function(matchers) {1261 each(matchers, function(name, body){1262 JSpec.addMatcher(name, body) 1263 })1264 },1265 1266 /**1267 * Define a matcher.1268 *1269 * @param {string} name1270 * @param {hash, function, string} body1271 * @api public1272 */1273 1274 addMatcher : function(name, body) {1275 hook('addingMatcher', name, body)1276 if (name.indexOf(' ') != -1) {1277 var matchers = name.split(/\s+/)1278 var prefix = matchers.shift()1279 each(matchers, function(name) {1280 JSpec.addMatcher(prefix + '_' + name, body(name))1281 })1282 }1283 this.matchers[name] = this.normalizeMatcherMessage(this.normalizeMatcherBody(body))1284 this.matchers[name].name = name1285 },1286 1287 /**1288 * Add a root suite to JSpec.1289 *1290 * @param {string} description1291 * @param {body} function1292 * @api public1293 */1294 1295 describe : function(description, body) {1296 var suite = new JSpec.Suite(description, body)1297 hook('addingSuite', suite)1298 this.allSuites.push(suite)1299 this.suites.push(suite)1300 },1301 1302 /**1303 * Return the contents of a function body.1304 *1305 * @param {function} body1306 * @return {string}1307 * @api public1308 */1309 1310 contentsOf : function(body) {1311 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]1312 },13131314 /**1315 * Evaluate a JSpec capture body.1316 *1317 * @param {function} body1318 * @param {string} errorMessage (optional)1319 * @return {Type}1320 * @api private1321 */13221323 evalBody : function(body, errorMessage) {1324 var dsl = this.DSL || this.DSLs.snake1325 var matchers = this.matchers1326 var context = this.context || this.defaultContext1327 var contents = this.contentsOf(body)1328 hook('evaluatingBody', dsl, matchers, context, contents)1329 try { eval('with (dsl){ with (context) { with (matchers) { ' + contents + ' }}}') }1330 catch(e) { error(errorMessage, e) }1331 },13321333 /**1334 * Pre-process a string of JSpec.1335 *1336 * @param {string} input1337 * @return {string}1338 * @api private1339 */13401341 preprocess : function(input) {1342 if (typeof input != 'string') return1343 input = hookImmutable('preprocessing', input)1344 return input.1345 replace(/\t/g, ' ').1346 replace(/\r\n|\n|\r/g, '\n').1347 replace(/__END__[^]*/, '').1348 replace(/([\w\.]+)\.(stub|destub)\((.*?)\)$/gm, '$2($1, $3)').1349 replace(/describe\s+(.*?)$/gm, 'describe($1, function(){').1350 replace(/^\s+it\s+(.*?)$/gm, ' it($1, function(){').1351 replace(/^ *(before_each|after_each|before|after)(?= |\n|$)/gm, 'JSpec.currentSuite.addHook("$1", function(){').1352 replace(/^\s*end(?=\s|$)/gm, '});').1353 replace(/-\{/g, 'function(){').1354 replace(/(\d+)\.\.(\d+)/g, function(_, a, b){ return range(a, b) }).1355 replace(/\.should([_\.]not)?[_\.](\w+)(?: |;|$)(.*)$/gm, '.should$1_$2($3)').1356 replace(/([\/\s]*)(.+?)\.(should(?:[_\.]not)?)[_\.](\w+)\((.*)\)\s*;?$/gm, '$1 expect($2).$3($4, $5)').1357 replace(/, \)/g, ')').1358 replace(/should\.not/g, 'should_not')1359 },13601361 /**1362 * Create a range string which can be evaluated to a native array.1363 *1364 * @param {int} start1365 * @param {int} end1366 * @return {string}1367 * @api public1368 */13691370 range : function(start, end) {1371 var current = parseInt(start), end = parseInt(end), values = [current]1372 if (end > current) while (++current <= end) values.push(current)1373 else while (--current >= end) values.push(current)1374 return '[' + values + ']'1375 },13761377 /**1378 * Report on the results. 1379 *1380 * @api public1381 */13821383 report : function() {1384 hook('reporting', JSpec.options)1385 new (JSpec.options.formatter || JSpec.formatters.DOM)(JSpec, JSpec.options)1386 },13871388 /**1389 * Run the spec suites. Options are merged1390 * with JSpec options when present.1391 *1392 * @param {hash} options1393 * @return {JSpec}1394 * @api public1395 */13961397 run : function(options) {1398 if (any(hook('running'), haveStopped)) return this1399 if (options) extend(this.options, options)1400 if (option('profile')) console.group('Profile')1401 each(this.suites, function(suite) { JSpec.runSuite(suite) })1402 if (option('profile')) console.groupEnd()1403 return this1404 },1405 1406 /**1407 * Run a suite.1408 *1409 * @param {Suite} suite1410 * @api public1411 */14121413 runSuite : function(suite) {1414 this.currentSuite = suite1415 this.evalBody(suite.body)1416 suite.ran = true1417 hook('beforeSuite', suite), suite.hook('before')1418 each(suite.specs, function(spec) {1419 hook('beforeSpec', spec)1420 suite.hook('before_each')1421 JSpec.runSpec(spec)1422 hook('afterSpec', spec)1423 suite.hook('after_each')1424 })1425 if (suite.hasSuites()) {1426 each(suite.suites, function(suite) {1427 JSpec.runSuite(suite)1428 })1429 }1430 hook('afterSuite', suite), suite.hook('after')1431 this.stats.suitesFinished++1432 },1433 1434 /**1435 * Report a failure for the current spec.1436 *1437 * @param {string} message1438 * @api public1439 */1440 1441 fail : function(message) {1442 JSpec.currentSpec.fail(message)1443 },1444 1445 /**1446 * Report a passing assertion for the current spec.1447 *1448 * @param {string} message1449 * @api public1450 */1451 1452 pass : function(message) {1453 JSpec.currentSpec.pass(message)1454 },14551456 /**1457 * Run a spec.1458 *1459 * @param {Spec} spec1460 * @api public1461 */14621463 runSpec : function(spec) {1464 this.currentSpec = spec1465 if (option('profile')) console.time(spec.description)1466 try { this.evalBody(spec.body) }1467 catch (e) { fail(e) }1468 if (option('profile')) console.timeEnd(spec.description)1469 spec.runDeferredAssertions()1470 destub()1471 this.stats.specsFinished++1472 this.stats.assertions += spec.assertions.length1473 },14741475 /**1476 * Require a dependency, with optional message.1477 *1478 * @param {string} dependency1479 * @param {string} message (optional)1480 * @return {JSpec}1481 * @api public1482 */14831484 requires : function(dependency, message) {1485 hook('requiring', dependency, message)1486 try { eval(dependency) }1487 catch (e) { throw 'JSpec depends on ' + dependency + ' ' + message }1488 return this1489 },14901491 /**1492 * Query against the current query strings keys1493 * or the queryString specified.1494 *1495 * @param {string} key1496 * @param {string} queryString1497 * @return {string, null}1498 * @api private1499 */15001501 query : function(key, queryString) {1502 var queryString = (queryString || (main.location ? main.location.search : null) || '').substring(1)1503 return inject(queryString.split('&'), null, function(value, pair){1504 parts = pair.split('=')1505 return parts[0] == key ? parts[1].replace(/%20|\+/gmi, ' ') : value1506 })1507 },15081509 /**1510 * Throw a JSpec related error.1511 *1512 * @param {string} message1513 * @param {Exception} e1514 * @api public1515 */15161517 error : function(message, e) {1518 throw (message ? message : '') + e.toString() + 1519 (e.line ? ' near line ' + e.line : '')1520 },1521 1522 /**1523 * Ad-hoc POST request for JSpec server usage.1524 *1525 * @param {string} uri1526 * @param {string} data1527 * @api private1528 */1529 1530 post : function(uri, data) {1531 if (any(hook('posting', uri, data), haveStopped)) return1532 var request = this.xhr()1533 request.open('POST', uri, false)1534 request.setRequestHeader('Content-Type', 'application/json')1535 request.send(JSpec.JSON.encode(data))1536 },15371538 /**1539 * Instantiate an XMLHttpRequest.1540 *1541 * Here we utilize IE's lame ActiveXObjects first which1542 * allow IE access serve files via the file: protocol, otherwise1543 * we then default to XMLHttpRequest.1544 *1545 * @return {XMLHttpRequest, ActiveXObject}1546 * @api private1547 */1548 1549 xhr : function() {1550 return this.ieXhr() || new JSpec.request1551 },1552 1553 /**1554 * Return Microsoft piece of crap ActiveXObject.1555 *1556 * @return {ActiveXObject}1557 * @api public1558 */1559 1560 ieXhr : function() {1561 function object(str) {1562 try { return new ActiveXObject(str) } catch(e) {}1563 }1564 return object('Msxml2.XMLHTTP.6.0') ||1565 object('Msxml2.XMLHTTP.3.0') ||1566 object('Msxml2.XMLHTTP') ||1567 object('Microsoft.XMLHTTP')1568 },1569 1570 /**1571 * Check for HTTP request support.1572 *1573 * @return {bool}1574 * @api private1575 */1576 1577 hasXhr : function() {1578 return JSpec.request || 'ActiveXObject' in main1579 },1580 1581 /**1582 * Try loading _file_ returning the contents1583 * string or null. Chain to locate / read a file.1584 *1585 * @param {string} file1586 * @return {string}1587 * @api public1588 */1589 1590 tryLoading : function(file) {1591 try { return JSpec.load(file) }1592 catch (e) {}1593 },15941595 /**1596 * Load a _file_'s contents.1597 *1598 * @param {string} file1599 * @param {function} callback1600 * @return {string}1601 * @api public1602 */16031604 load : function(file, callback) {1605 if (any(hook('loading', file), haveStopped)) return1606 if ('readFile' in main)1607 return readFile(file)1608 else if (this.hasXhr()) {1609 var request = this.xhr()1610 request.open('GET', file, false)1611 request.send(null)1612 if (request.readyState == 4 && 1613 (request.status == 0 || 1614 request.status.toString().charAt(0) == 2)) 1615 return request.responseText1616 }1617 else1618 error("failed to load `" + file + "'")1619 },16201621 /**1622 * Load, pre-process, and evaluate a file.1623 *1624 * @param {string} file1625 * @param {JSpec}1626 * @api public1627 */16281629 exec : function(file) {1630 if (any(hook('executing', file), haveStopped)) return this1631 eval('with (JSpec){' + this.preprocess(this.load(file)) + '}')1632 return this1633 }1634 }16351636 // --- Utility functions16371638 var main = this1639 var find = JSpec.any1640 var utils = 'haveStopped stub hookImmutable hook destub map any last pass fail range each option inject select \1641 error escape extend puts hash query strip color does addMatchers callIterator argumentsToArray'.split(/\s+/)1642 while (utils.length) util = utils.shift(), eval('var ' + util + ' = JSpec.' + util)1643 if (!main.setTimeout) main.setTimeout = function(callback){ callback() }16441645 // --- Matchers16461647 addMatchers({1648 equal : "===",1649 be : "alias equal",1650 be_greater_than : ">",1651 be_less_than : "<",1652 be_at_least : ">=",1653 be_at_most : "<=",1654 be_a : "actual.constructor == expected",1655 be_an : "alias be_a",1656 be_an_instance_of : "actual instanceof expected",1657 be_null : "actual == null",1658 be_true : "actual == true",1659 be_false : "actual == false",1660 be_undefined : "typeof actual == 'undefined'",1661 be_type : "typeof actual == expected",1662 match : "typeof actual == 'string' ? actual.match(expected) : false",1663 respond_to : "typeof actual[expected] == 'function'",1664 have_length : "actual.length == expected",1665 be_within : "actual >= expected[0] && actual <= last(expected)",1666 have_length_within : "actual.length >= expected[0] && actual.length <= last(expected)",16671668 eql : function(actual, expected) {1669 return actual.constructor == Array ||1670 actual instanceof Object ? 1671 hash(actual) == hash(expected):1672 actual == expected1673 },1674 1675 receive : { defer : true, match : function(actual, method, times) {1676 proxy = new JSpec.ProxyAssertion(actual, method, times, this.negate)1677 JSpec.currentSpec.assertions.push(proxy)1678 return proxy1679 }},1680 1681 be_empty : function(actual) {1682 if (actual.constructor == Object && actual.length == undefined)1683 for (var key in actual)1684 return false;1685 return !actual.length1686 },16871688 include : function(actual) {1689 for (state = true, i = 1; i < arguments.length; i++) {1690 arg = arguments[i]1691 switch (actual.constructor) {1692 case String: 1693 case Number:1694 case RegExp:1695 case Function:1696 state = actual.toString().match(arg.toString())1697 break1698 1699 case Object:1700 state = arg in actual1701 break1702 1703 case Array: 1704 state = any(actual, function(value){ return hash(value) == hash(arg) })1705 break1706 }1707 if (!state) return false1708 }1709 return true1710 },17111712 throw_error : { match : function(actual, expected, message) {1713 try { actual() }1714 catch (e) {1715 this.e = e1716 var assert = function(arg) {1717 switch (arg.constructor) {1718 case RegExp : return arg.test(e)1719 case String : return arg == (e.message || e.toString())1720 case Function : return (e.name || 'Error') == arg.name1721 }1722 }1723 return message ? assert(expected) && assert(message) :1724 expected ? assert(expected) :1725 true1726 }1727 }, message : function(actual, expected, negate) {1728 // TODO: refactor when actual is not in expected [0]1729 var message_for = function(i) {1730 if (expected[i] == undefined) return 'exception'1731 switch (expected[i].constructor) {1732 case RegExp : return 'exception matching ' + puts(expected[i])1733 case String : return 'exception of ' + puts(expected[i])1734 case Function : return expected[i].name || 'Error'1735 }1736 }1737 exception = message_for(1) + (expected[2] ? ' and ' + message_for(2) : '')1738 return 'expected ' + exception + (negate ? ' not ' : '' ) +1739 ' to be thrown, but ' + (this.e ? 'got ' + puts(this.e) : 'nothing was')1740 }},1741 1742 have : function(actual, length, property) {1743 return actual[property].length == length1744 },1745 1746 have_at_least : function(actual, length, property) {1747 return actual[property].length >= length1748 },1749 1750 have_at_most :function(actual, length, property) {1751 return actual[property].length <= length1752 },1753 1754 have_within : function(actual, range, property) {1755 length = actual[property].length1756 return length >= range.shift() && length <= range.pop()1757 },1758 1759 have_prop : function(actual, property, value) {1760 return actual[property] == null || 1761 actual[property] instanceof Function ? false:1762 value == null ? true:1763 does(actual[property], 'eql', value)1764 },1765 1766 have_property : function(actual, property, value) {1767 return actual[property] == null ||1768 actual[property] instanceof Function ? false:1769 value == null ? true:1770 value === actual[property]1771 }1772 })1773 1774 if ('exports' in main) exports.JSpec = JSpec17751776})()
added:spec/lib/jspec.shell.js+36 added
12// JSpec - Shell - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 var _quit = quit7 8 Shell = {9 10 // --- Global11 12 main: this,13 14 // --- Commands15 16 commands: {17 quit: ['Terminate the shell', function(){ _quit() }],18 exit: ['Terminate the shell', function(){ _quit() }]19 },20 21 /**22 * Start the interactive shell.23 *24 * @api public25 */26 27 start : function() {28 for (var name in this.commands)29 if (this.commands.hasOwnProperty(name))30 this.main.__defineGetter__(name, this.commands[name][1])31 }32 }33 34 Shell.start()35 36})()
added:spec/lib/jspec.timers.js+90 added
12// Mock Timers - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 /**7 * Version.8 */9 10 mockTimersVersion = '1.0.2'11 12 /**13 * Localized timer stack.14 */15 16 var timers = []17 18 /**19 * Set mock timeout with _callback_ and timeout of _ms_.20 *21 * @param {function} callback22 * @param {int} ms23 * @return {int}24 * @api public25 */26 27 setTimeout = function(callback, ms) {28 var id29 return id = setInterval(function(){30 callback()31 clearInterval(id)32 }, ms)33 }34 35 /**36 * Set mock interval with _callback_ and interval of _ms_.37 *38 * @param {function} callback39 * @param {int} ms40 * @return {int}41 * @api public42 */4344 setInterval = function(callback, ms) {45 callback.step = ms, callback.current = callback.last = 046 return timers[timers.length] = callback, timers.length47 }48 49 /**50 * Destroy timer with _id_.51 *52 * @param {int} id53 * @return {bool}54 * @api public55 */5657 clearInterval = clearTimeout = function(id) {58 return delete timers[--id]59 }60 61 /**62 * Reset timers.63 *64 * @return {array}65 * @api public66 */67 68 resetTimers = function() {69 return timers = []70 }71 72 /**73 * Increment each timers internal clock by _ms_.74 *75 * @param {int} ms76 * @api public77 */78 79 tick = function(ms) {80 for (var i = 0, len = timers.length; i < len; ++i)81 if (timers[i] && (timers[i].current += ms))82 if (timers[i].current - timers[i].last >= timers[i].step) {83 var times = Math.floor((timers[i].current - timers[i].last) / timers[i].step)84 var remainder = (timers[i].current - timers[i].last) % timers[i].step85 timers[i].last = timers[i].current - remainder86 while (times-- && timers[i]) timers[i]()87 }88 }89 90})()
added:spec/lib/jspec.xhr.js+183 added
12// JSpec - XHR - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){5 6 // --- Original XMLHttpRequest7 8 var OriginalXMLHttpRequest = 'XMLHttpRequest' in this ? 9 XMLHttpRequest :10 function(){}1112 // --- MockXMLHttpRequest1314 var MockXMLHttpRequest = function() {15 this.requestHeaders = {}16 }17 18 MockXMLHttpRequest.prototype = {19 status: 0,20 async: true,21 readyState: 0,22 responseText: '',23 abort: function(){},24 onreadystatechange: function(){},2526 /**27 * Return response headers hash.28 */2930 getAllResponseHeaders : function(){31 return this.responseHeaders32 },33 34 /**35 * Return case-insensitive value for header _name_.36 */3738 getResponseHeader : function(name) {39 return this.responseHeaders[name.toLowerCase()]40 },41 42 /**43 * Set case-insensitive _value_ for header _name_.44 */4546 setRequestHeader : function(name, value) {47 this.requestHeaders[name.toLowerCase()] = value48 },49 50 /**51 * Open mock request.52 */5354 open : function(method, url, async, user, password) {55 this.user = user56 this.password = password57 this.url = url58 this.readyState = 159 this.method = method.toUpperCase()60 if (async != undefined) this.async = async61 if (this.async) this.onreadystatechange()62 },63 64 /**65 * Send request _data_.66 */6768 send : function(data) {69 this.data = data70 this.readyState = 471 if (this.method == 'HEAD') this.responseText = null72 this.responseHeaders['content-length'] = (this.responseText || '').length73 if(this.async) this.onreadystatechange()74 }75 }76 77 // --- Response status codes78 79 JSpec.statusCodes = {80 100: 'Continue',81 101: 'Switching Protocols',82 200: 'OK',83 201: 'Created',84 202: 'Accepted',85 203: 'Non-Authoritative Information',86 204: 'No Content',87 205: 'Reset Content',88 206: 'Partial Content',89 300: 'Multiple Choice',90 301: 'Moved Permanently',91 302: 'Found',92 303: 'See Other',93 304: 'Not Modified',94 305: 'Use Proxy',95 307: 'Temporary Redirect',96 400: 'Bad Request',97 401: 'Unauthorized',98 402: 'Payment Required',99 403: 'Forbidden',100 404: 'Not Found',101 405: 'Method Not Allowed',102 406: 'Not Acceptable',103 407: 'Proxy Authentication Required',104 408: 'Request Timeout',105 409: 'Conflict',106 410: 'Gone',107 411: 'Length Required',108 412: 'Precondition Failed',109 413: 'Request Entity Too Large',110 414: 'Request-URI Too Long',111 415: 'Unsupported Media Type',112 416: 'Requested Range Not Satisfiable',113 417: 'Expectation Failed',114 422: 'Unprocessable Entity',115 500: 'Internal Server Error',116 501: 'Not Implemented',117 502: 'Bad Gateway',118 503: 'Service Unavailable',119 504: 'Gateway Timeout',120 505: 'HTTP Version Not Supported'121 }122 123 /**124 * Mock XMLHttpRequest requests.125 *126 * mockRequest().and_return('some data', 'text/plain', 200, { 'X-SomeHeader' : 'somevalue' })127 *128 * @return {hash}129 * @api public130 */131 132 function mockRequest() {133 return { and_return : function(body, type, status, headers) {134 XMLHttpRequest = MockXMLHttpRequest135 status = status || 200136 headers = headers || {}137 headers['content-type'] = type138 JSpec.extend(XMLHttpRequest.prototype, {139 responseText: body,140 responseHeaders: headers,141 status: status,142 statusText: JSpec.statusCodes[status]143 })144 }}145 }146 147 /**148 * Unmock XMLHttpRequest requests.149 *150 * @api public151 */152 153 function unmockRequest() {154 XMLHttpRequest = OriginalXMLHttpRequest155 }156 157 JSpec.include({158 name: 'Mock XHR',159160 // --- Utilities161162 utilities : {163 mockRequest: mockRequest,164 unmockRequest: unmockRequest165 },166167 // --- Hooks168169 afterSpec : function() {170 unmockRequest()171 },172 173 // --- DSLs174 175 DSLs : {176 snake : {177 mock_request: mockRequest,178 unmock_request: unmockRequest179 }180 }181182 })183})()
modified:spec/spec.async.js+22 added-23 removed
3 unmodified lines
4 before_each5 Express.routes = []6 end78 describe 'callback'9 10 it 'should wait for an asynchronous handler to finish'11 require('jspec.timers')12 get('pants', function() {13 setTimeout(function() {14 Express.server.finished('asynchronous thing done')15 }, 50)16 })17 var response = get('pants')18 response.body.should.be_null1920 tick(50)21 response.body.should.eql 'asynchronous thing done'22 response.status.should.eql 20023 response.headers['content-type'].should.eql 'text/html'24 end25 26 it 'should still accept a synchronous handler that returns a string'27 get('pants', function() { 'no pants' })28 get('pants').body.should.eql 'no pants'29 end30 end8 describe 'callback'9 it 'should wait for an asynchronous handler to finish'10 require('jspec.timers')11 get('pants', function() {12 setTimeout(function() {13 halt('asynchronous thing done')14 }, 50)15 })16 var response = get('pants')17 response.body.should.be_null18 19 tick(50)20 response.body.should.eql 'asynchronous thing done'21 response.status.should.eql 20022 response.headers['content-type'].should.eql 'text/html'23 end24 25 it 'should still accept a synchronous handler that returns a string'26 get('pants', function() { 'no pants' })27 get('pants').body.should.eql 'no pants'28 end29 end30 end31end32
modified:spec/spec.cookie.js+1 added-3 removed
12use(Express.Cookie)32describe 'Express'3 describe 'Cookie'4 before_each5 Express.routes = []
10 unmodified lines
16 get('foo', function() {17 cookie('q')18 })19 request = mockRequest({ 22 headers : [['Cookie', 'path=/; q=something; domain=.example.net']]20 headers : { 'cookie': 'path=/; q=something; domain=.example.net' }21 })22 response = get('foo', { request: request })23 response.body.should.eql 'something'24 end
21 unmodified lines
modified:spec/spec.core.js+12 added-28 removed
11describe 'Express'2 before_each3 Express.routes = []4 end
36 unmodified lines
41 parts.domain.should.eql 'example.net'42 end43 end44 46 describe '.argsArray()'45 describe '.toArray()'46 it 'should return an array of arguments'48 Express.argsArray(-{ return arguments }('foo', 'bar')).should.eql ['foo', 'bar']47 Express.toArray(-{ return arguments }('foo', 'bar')).should.eql ['foo', 'bar']48 end49 50 it 'should allow an offset'52 Express.argsArray(-{ return arguments }('foo', 'bar'), 1).should.eql ['bar']51 Express.toArray(-{ return arguments }('foo', 'bar'), 1).should.eql ['bar']52 end53 end54 55 describe '.escape()'
59 unmodified lines
115 Express.response.status.should.eql 403116 end117 end118 120 describe '.respond()'119 describe '.halt()'120 after_each121 Express.response.status = 200122 end123 124 it 'should set response status and body'126 -{ Express.respond('Page or file cannot be found', 'Not Found') }.should.throw_error125 -{ Express.halt('Page or file cannot be found', 'Not Found') }.should.throw_error126 Express.response.status.should.eql 404127 Express.response.body.should.eql 'Page or file cannot be found'128 end129 130 it 'should allow specific status to be passed'132 -{ Express.respond('File cannot be found', 404) }.should.throw_error131 -{ Express.halt('File cannot be found', 404) }.should.throw_error132 Express.response.status.should.eql 404133 Express.response.body.should.eql 'File cannot be found'134 end135 end137 138 describe '.hashToArray()'139 it 'should map hash key / value pairs to an array'140 headers = { 'Content-Type' : 'text/plain' }141 Express.hashToArray(headers).should.eql [['Content-Type', 'text/plain']]142 end143 end144 145 describe '.arrayToHash()'146 it 'should map an assoc array to an object'147 headers = [['Content-Type', 'text/plain']]148 Express.arrayToHash(headers).should.eql { 'content-type' : 'text/plain' }149 end150 end151 136137 describe '.redirect()'138 it 'should redirect to the url specified'139 get('foo', function(){ redirect('http://google.com') })140 response = get('foo')
22 unmodified lines
163 describe '.back'164 it 'should redirect to the referrer'165 uri = 'http://vision-media.ca'166 get('foo', function(){ redirect(back) })182 request = mockRequest({ headers : [['Referer', uri]] })167 request = mockRequest({ headers : { 'Referer': uri }})168 get('foo', { request: request }).headers.location.should.eql uri169 Express.back.should.eql uri170 end171 end
2 unmodified lines
174 describe 'BodyDecoder'175 it 'should parse urlencoded bodies'176 request = mockRequest({177 method: 'POST',193 headers : [['Content-Type', 'application/x-www-form-urlencoded']],178 headers : { 'content-type': 'application/x-www-form-urlencoded' },179 body : 'user[name]=foo%20bar&status=1'180 })181 post('admin', function(){ param('user').name + ' ' + param('status') })182 post('admin', { request : request }).body.should.eql 'foo bar 1'
1 unmodified line
184185 it 'should parse JSON bodies'186 request = mockRequest({187 method: 'POST',203 headers : [['Content-Type', 'application/json']],188 headers : { 'content-type': 'application/json' },189 body : '{ foo : "bar" }'190 })191 post('foo', function(){ param('foo') })192 post('foo', { request : request }).body.should.eql 'bar'
10 unmodified lines
203 describe 'MethodOverride'204 it 'should override request method when _method param is present'205 request = mockRequest({206 method: 'POST',222 headers : [['Content-Type', 'application/x-www-form-urlencoded']],207 headers : { 'content-type': 'application/x-www-form-urlencoded' },208 body : '_method=delete'209 })210 del('foo', function(){ 'Deleted' })211 post('foo', { request : request}).body.should.eql 'Deleted'
10 unmodified lines
222 get('foo', function(){ header('Content-Type', 'application/json'); 'bar' })223 get('foo').headers['content-type'].should.eql 'application/json'224 end225 end241 242end226end
modified:spec/spec.mime.js-2 removed
12use(Express.Mime)32describe 'Express'3 describe 'Mime'4 describe '.mime()'5 it 'should return media type of extensions passed'
14 unmodified lines
modified:spec/spec.node.js+25 added-20 removed
1require.paths.unshift("../jspec-2.11.2/lib", "./lib");1require.paths.unshift("./spec/lib", "./lib");2process.mixin(GLOBAL, require("sys"))34require("jspec")5require("express")6require("express.mocks")6require("express/spec/mocks")78var posix = require("posix");9readFile = function(path, callback) {8var posix = require('posix')910quit = process.exit11print = puts1213readFile = function(path) {14 var promise = posix.cat(path, "utf8")15 var result = ''16 promise.addErrback(function(){ throw "failed to read file `" + path + "'" })17 promise.addCallback(function(contents){13 callback(contents)18 result = contents19 })20 promise.wait()21 return result22}2318if (process.ARGV[2]) {19 JSpec.exec('spec/spec.'+process.ARGV[2]+'.js') 20} else {21JSpec22 .exec('spec/spec.core.js')23 .exec('spec/spec.routing.js')24 .exec('spec/spec.mocks.js')25 .exec('spec/spec.modules.js')26 .exec('spec/spec.mime.js')27 .exec('spec/spec.cookie.js')28 .exec('spec/spec.session.js')29 .exec('spec/spec.view.js') 30 .exec('spec/spec.async.js')31}32JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })24if (process.ARGV[2])25 JSpec.exec('spec/spec.' + process.ARGV[2] + '.js') 26else27 JSpec28 .exec('spec/spec.core.js')29 .exec('spec/spec.routing.js')30 .exec('spec/spec.mocks.js')31 .exec('spec/spec.modules.js')32 .exec('spec/spec.mime.js')33 .exec('spec/spec.cookie.js')34 .exec('spec/spec.session.js')35 .exec('spec/spec.view.js') 36 .exec('spec/spec.async.js')37JSpec.run({ formatter: JSpec.formatters.Terminal, failuresOnly: true })38JSpec.report()39
modified:spec/spec.session.js-2 removed
12use(Express.Session)32describe 'Express'3 describe 'Session'4 5 end
1 unmodified line
added:Makefile+7 added
12NODE = node34test:5 @$(NODE) spec/spec.node.js6 7.PHONY: test
modified:Readme.md+18 added-8 removed
12# Express32 __ 3 / 4 (___ ___ ___ ___ ___ ___ 5 | (_/_ | )| )|___)|___ |___ 6 |__ / / |__/ | |__ __/ __/ 7 |8 9 Insanely fast (and small) server-side JavaScript web development framework10 built on **node.js** and the **V8 JavaScript engine**.1112 * Stay tuned, coming soon :)
84 unmodified lines
97## Public API9899 * Coming Soon100 96## Testing101## Running Tests10298Install [JSpec](http://jspec.info) - note that this currently requires version jspec-2.11.2 (later versions do not work yet), edit the path to JSpec (in spec/spec.node.js) on your machine, and run:103Express uses the [JSpec](http://jspec.info) BDD JavaScript testing104framework to write and run elegant spec suites. JSpec is froozen 105to spec/lib and does not require seperate installation.106100 $ node spec/spec.node.js107To run all specifications:108109 $ make test110 102Run individual tests files:111Run individual suites:112113 $ node spec/spec.node.js core114 $ node spec/spec.node.js mime115 $ node spec/spec.node.js routing116 ...117 106Will run the tests in spec/spec.core.js only.107 118## More Information119120 * [Mojo](http://github.com/visionmedia/mojo) JavaScript Mustache Templates121
24 unmodified lines