Comparar commits

...

376 Commits

Autor SHA1 Mensagem Data
visionmedia db2eb658ca Release 0.13.0 2010-06-01 08:49:04 -07:00
visionmedia 70483484ce Fixed upload example 2010-06-01 08:44:26 -07:00
visionmedia d21afc43a1 Merge branch 'charset' of git://github.com/aheckmann/express 2010-05-31 14:06:29 -07:00
visionmedia 7ad0803f2e Updated package.json 2010-05-31 14:05:15 -07:00
Aaron Heckmann ec4bfd55f9 not-found exceptions using utf-8 2010-05-31 12:58:53 -04:00
Aaron Heckmann f65174a0db show-exceptions uses utf-8 2010-05-31 12:56:30 -04:00
visionmedia 8b1fcd4dd7 mime.type() no longer accepts ".type" 2010-05-30 13:14:08 -07:00
visionmedia 9509237958 Fixed mime.type() due to path.extname() changes 2010-05-30 13:04:35 -07:00
visionmedia f20fd20a06 Fixed view support due to fs.readFile Buffers 2010-05-30 12:46:15 -07:00
visionmedia 8e48120fb7 Updated JSpec 2010-05-30 12:42:31 -07:00
visionmedia 44cc5ac883 Updated haml submodule 2010-05-27 15:32:30 -07:00
visionmedia 9a43cc8c4b Updated haml submodule 2010-05-25 16:08:50 -07:00
visionmedia 8dfc0d54f4 Updated haml submodule 2010-05-25 13:49:30 -07:00
visionmedia 77febd21de Fixed code styling 2010-05-23 09:38:42 -07:00
Aaron Heckmann 84a997c66b Added support for deleting cookies via Request#cookie('key', null) 2010-05-23 09:37:53 -07:00
Aaron Heckmann b900a59fc2 respond(204) should not have a body 2010-05-22 12:13:15 -04:00
visionmedia ca782dbc58 Release 0.12.0 2010-05-22 08:24:22 -07:00
visionmedia 746cda27ec Fixed cookie spec urlencoding 2010-05-22 08:23:28 -07:00
visionmedia 16d1651656 Fixed a cookie spec 2010-05-22 08:22:01 -07:00
visionmedia 4735fb2377 Merge branch 'master' of git://github.com/tritonrc/express 2010-05-22 08:21:08 -07:00
Aaron Heckmann ec6b518fd2 compatible with node v0.1.96 2010-05-22 08:09:09 -07:00
Brian McKinney 580ad1b192 Make sure to URL encode cookie name and value on response if we are going to URL decode on request 2010-05-18 18:53:01 -06:00
visionmedia 23d8810486 Updated haml submodule 2010-05-17 15:43:38 -07:00
visionmedia d579d62eb6 Comment changed to match others 2010-05-14 07:30:14 -07:00
visionmedia 529f785e3c Merge branch 'master' of git://github.com/Guille/express 2010-05-14 07:28:53 -07:00
Guillermo Rauch 0581ae87b4 Renaming Globals to helpers (I'm sold) 2010-05-14 11:16:51 -03:00
visionmedia cda1059336 Updated readme, we are compatible with node --version v0.1.95 2010-05-14 06:51:59 -07:00
Aaron Heckmann 1aed6b5c30 Merge branch 'master' into encoding 2010-05-14 08:05:46 -04:00
Aaron Heckmann 4e68705b24 compatible with node v0.1.95 2010-05-14 08:01:05 -04:00
Guillermo Rauch 216cb1ea12 Added support for globals (eg: helpers) in views
- Added export.Globals in plugins/view.js
 - Added two specs (one for a simple template, one for a template with a layout) with a dummy i18n helper
 - Updated README features list
2010-05-13 20:35:25 -03:00
Guillermo Rauch 8ef6a0b432 Merge branch 'master' of http://github.com/visionmedia/express
* 'master' of http://github.com/visionmedia/express: (168 commits)
  Updated haml submodule
  s/==/===/
  Misc refactoring to make parseCookie() more readable / spec for overriding keys
  s/QueryString/queryString/
  Added spec for malformed cookies
  regexps have no "n" flag
  No need to quote key in spec
  Fixed LF -> CRLF for setting multiple cookies
  Redo cookies parsing to accept quoted values and url escaped cookies
  Remove inode from ETag, modified time only
  Release 0.11.0
  Works fine with node --version v0.1.94
  Refactoring some spec fixtures
  Fixing spec for EJS partial
  Updated ext
  Updated haml
  Added spec / refactored layout of different engine support
  Added spec for layouts with different engines
  Fixing EJS partial support by passing along the context. Issue #307
  Allow layouts to use different engines
  ...

Conflicts:
	lib/express/core.js
2010-05-13 18:53:11 -03:00
visionmedia 5dc152c46e Updated haml submodule 2010-05-11 13:22:32 -07:00
visionmedia c3a21437e4 Merge branch 'integration' 2010-05-11 07:57:50 -07:00
visionmedia 32bc8dcbf9 s/==/===/ 2010-05-11 07:57:24 -07:00
visionmedia 677ca7b4aa Misc refactoring to make parseCookie() more readable / spec for overriding keys 2010-05-11 07:55:15 -07:00
visionmedia dfc2331104 s/QueryString/queryString/ 2010-05-11 07:47:20 -07:00
visionmedia cd06bbfb8d Added spec for malformed cookies 2010-05-11 07:46:44 -07:00
visionmedia 1d596bcbac regexps have no "n" flag 2010-05-11 07:44:31 -07:00
visionmedia 0cb7b9c13d No need to quote key in spec 2010-05-11 07:42:23 -07:00
visionmedia a180efeca7 Merge branch 'master' of git://github.com/tritonrc/express into integration 2010-05-11 07:41:15 -07:00
visionmedia eef24ea29c Fixed LF -> CRLF for setting multiple cookies 2010-05-11 07:25:08 -07:00
Brian McKinney 458bb3d7f7 Redo cookies parsing to accept quoted values and url escaped cookies 2010-05-10 17:18:42 -06:00
visionmedia ffb23d92c0 Remove inode from ETag, modified time only 2010-05-07 13:52:13 -07:00
visionmedia 0ce39a4cf6 Release 0.11.0 2010-05-06 15:41:15 -07:00
visionmedia a24c70e490 Works fine with node --version v0.1.94 2010-05-06 15:36:06 -07:00
visionmedia 8d4ef6e883 Merge branch 'integration' 2010-05-06 15:35:39 -07:00
visionmedia 54865ebdee Refactoring some spec fixtures 2010-05-06 15:24:30 -07:00
visionmedia cb8e704d5c Merged bdotdub/master 2010-05-06 15:21:47 -07:00
Benny Wong 57f4978442 Fixing spec for EJS partial
* Had to use double quote and not single quote for the partial filename
* Couldn't get each to work. Using ugly `for` for now
2010-05-06 13:59:50 -04:00
visionmedia b8833f4c9e Updated ext 2010-05-06 10:29:15 -07:00
visionmedia 5c40cbc675 Merge branch 'update-haml' 2010-05-06 09:17:13 -07:00
visionmedia a455dcc919 Updated haml 2010-05-06 09:17:08 -07:00
visionmedia 289487cc46 Merge branch 'integration' 2010-05-06 07:52:32 -07:00
visionmedia 42b28d5bd6 Added spec / refactored layout of different engine support 2010-05-06 07:52:28 -07:00
visionmedia 46bee05d93 Merge branch 'master' of git://github.com/nick/express into integration 2010-05-06 07:44:43 -07:00
visionmedia 49bed5cd5f Added spec for layouts with different engines 2010-05-06 07:43:54 -07:00
Benny Wong 624cf93e2e Fixing EJS partial support by passing along the context. Issue #307 2010-05-06 01:20:35 -04:00
Nick Poulden 6ab76cda51 Allow layouts to use different engines 2010-05-05 13:19:16 -07:00
Nick Poulden 15beb81368 Allow ejs templates to contain single quotes 2010-05-05 11:42:41 -07:00
visionmedia 6a6cce03b7 Release 0.10.1 2010-05-03 08:42:01 -07:00
Matt Colyer 970ff87ef6 Fix binary uploads. 2010-05-01 11:46:25 -07:00
visionmedia 8b6c4d322f Updated history 2010-04-30 10:46:24 -07:00
visionmedia 4467a00acd Release 0.10.0 2010-04-30 10:34:13 -07:00
visionmedia 63efc61517 Added "dump exceptions" setting, which is enabled by default 2010-04-30 10:09:53 -07:00
visionmedia 7aa18345c8 Added better ejs usage example 2010-04-30 10:05:04 -07:00
visionmedia 34149187a8 Catching ENOENT in view caching, preventing error when "views/partials" is not found 2010-04-30 10:00:00 -07:00
visionmedia 2d132cd0d5 Merge branch 'ejs' 2010-04-30 09:57:23 -07:00
visionmedia 8d741361e0 Added simple ejs support 2010-04-30 09:57:19 -07:00
visionmedia 2bcea3a370 Added more cache key specs 2010-04-30 09:33:10 -07:00
visionmedia ead3cace02 No need to reverse plugins on each request
This was slowing things down quite a bit
2010-04-30 09:24:17 -07:00
visionmedia 7afa5c7b43 Revert "Clone / reverse plugins ONCE"
shit, was causing some bugs, will figure that out first

This reverts commit 115765e1ee.
2010-04-30 09:18:38 -07:00
visionmedia 115765e1ee Clone / reverse plugins ONCE
huuuuge performance boost
2010-04-30 09:12:48 -07:00
visionmedia d712fae2d7 Fixed bug producing messed up response bodies
Express was trying to respond twice to the same request
due to an error caused by having no callback,
which was then caught, and responded to using Request#error()

haha!
2010-04-30 08:53:52 -07:00
visionmedia 0dba9bd87f Removed Logger "request" format 2010-04-30 08:40:59 -07:00
visionmedia 2fbc495088 Merge branch 'update-ext' 2010-04-30 08:00:04 -07:00
visionmedia 37d490cbe4 Fixed bug recently introduced preventing plugin events to trigger 2010-04-30 07:59:57 -07:00
visionmedia 451679c582 Cache reaper destroys null caches as well
so they dont linger until expired
2010-04-29 09:01:17 -07:00
visionmedia 7270a13ef7 Fixed compileCookie() utility due to ext changes 2010-04-29 08:56:55 -07:00
visionmedia 16f3f90ed7 Todo 2010-04-29 08:52:48 -07:00
visionmedia 9ff2f81a10 Fixed cache bugs introduced by 1bc9a1a 2010-04-29 08:52:01 -07:00
visionmedia 1bc9a1af6a Fixed Cache Store.Memory usage of Object#reduce() 2010-04-29 08:42:51 -07:00
visionmedia 760d9e3341 Fixed error page hash iteration 2010-04-29 08:35:20 -07:00
visionmedia 5b28abc5ed Fixed session / cache key iteration due to ext changes 2010-04-29 08:23:24 -07:00
visionmedia defb1596bb Removed Array#at() usage 2010-04-29 08:10:31 -07:00
visionmedia 9c117d5875 Request#accepts() fixed due to ext changes 2010-04-29 08:09:48 -07:00
visionmedia 1b09fce42a Todo 2010-04-29 08:05:51 -07:00
visionmedia 5e328830e7 Replace merge() calls with Object.merge() 2010-04-29 08:04:42 -07:00
visionmedia 606da1c45b Merge branch 'integration' 2010-04-29 06:50:52 -07:00
visionmedia 6232c1a8f3 Several fixes to http client
- Only attempts to "render" data on first request (not redirects)
  - Allows setting of "redirects" via the data variable
  - Fixed Host header predecence issue
  - Only setting Content-Length / Content-Type when not previously set
  - Passing response object on errors
2010-04-29 06:50:46 -07:00
Viktor Kelemen 15a24e68d2 In case of redirect the request function was called with a wrong param list 2010-04-29 19:21:14 +09:00
visionmedia c12ace81db Fixed Logger content-length 2010-04-28 16:57:55 -07:00
visionmedia 531990b516 Merge branch 'rename-halt' 2010-04-26 09:17:06 -07:00
visionmedia b90a3dbffe Renamed Request#halt() to Request#respond(). Closes #289
deprecated Request#halt(), however it will remain until 1.0
2010-04-26 09:17:01 -07:00
visionmedia 0352b97798 Merge branch 'integration' 2010-04-26 07:07:15 -07:00
visionmedia e45abe60bf _ -> val 2010-04-26 07:07:11 -07:00
visionmedia 8077481707 Merge branch 'cache' of git://github.com/aheckmann/express into integration 2010-04-26 07:05:49 -07:00
visionmedia 4651dd33cd Updated haml submodule 2010-04-26 06:56:07 -07:00
visionmedia c93cfa0871 Added "encoding" option to Request#render(). Closes #299
Should work :)
2010-04-26 06:44:29 -07:00
Aaron Heckmann d57cb7d411 utilize each() 2010-04-25 00:02:20 -04:00
visionmedia 81088766ee Updated ext submodule 2010-04-24 14:14:51 -07:00
visionmedia ae59a50c28 Added benchmark link 2010-04-23 15:24:40 -07:00
visionmedia 4a05056393 Removed unused param in Cache.startReaper()
wtf?
2010-04-23 15:15:27 -07:00
visionmedia 71e97c815a Merge branch 'benchmarks' 2010-04-23 14:40:04 -07:00
visionmedia 8b7787aa60 Added sass benchmarks 2010-04-23 14:39:58 -07:00
visionmedia e0f94b052b Added ruby haml :ugly option to make it render faster in benchmarks 2010-04-23 11:56:12 -07:00
visionmedia eb2c9ffd32 Added haml benchmarks 2010-04-23 11:49:22 -07:00
visionmedia 5af315c165 Using sys.inspect() instead of JSON.encode() for error output
produces cleaner output
2010-04-23 10:30:59 -07:00
visionmedia e9fdfc339b Added error reponse support for text/plain, application/json. Closes #297 2010-04-23 10:28:12 -07:00
visionmedia 132730acea Added specs for errors with text/plain and application/json 2010-04-23 09:55:10 -07:00
visionmedia 405097d323 Fixed Request#sendfile() 404 support even when a callback is available 2010-04-23 06:57:02 -07:00
visionmedia c9d79f26c5 Smooth line graph 2010-04-22 14:18:13 -07:00
visionmedia 7ef13eaf0c Merge branch 'benchmarks' 2010-04-22 14:15:41 -07:00
visionmedia 2756aba21f Added COL 2010-04-22 14:15:36 -07:00
visionmedia c01a7f57df Merge branch 'benchmarks' 2010-04-22 13:43:14 -07:00
visionmedia 33a4dd3841 Fixed graph labels 2010-04-22 13:43:11 -07:00
visionmedia 3c150db4a2 Merge branch 'benchmarks' 2010-04-22 13:20:27 -07:00
visionmedia e31f5d2325 Generating bar graphs for requests per sec 2010-04-22 13:20:24 -07:00
visionmedia f8a61c667e My bad, swap express -> node in graphs 2010-04-22 12:09:40 -07:00
visionmedia e2fe60399f Merge branch 'benchmarks' 2010-04-22 12:04:32 -07:00
visionmedia 59c4e35691 Added graphing capabilities (gnuplot must be installed) 2010-04-22 12:04:28 -07:00
visionmedia 2dc5afd018 Docs 2010-04-22 11:04:04 -07:00
visionmedia b5df39bc46 Merge branch 'benchmarks' 2010-04-22 11:02:24 -07:00
visionmedia f87b709923 Added node static / large static benchmarks 2010-04-22 11:02:21 -07:00
visionmedia 671aa1036b Merge branch 'benchmarks' 2010-04-22 10:55:52 -07:00
visionmedia 4580340db3 Added simple node benchmark 2010-04-22 10:55:46 -07:00
visionmedia 31b53eae39 Added larger ~550kb static benchmarks 2010-04-22 10:41:04 -07:00
visionmedia 089423958d run() returns the http.Server instance. Closes #298 2010-04-22 09:48:20 -07:00
visionmedia 0d02ea43e1 Default Server#host to null (INADDR_ANY)
use run(3000, localhost) etc as needed
2010-04-22 09:43:57 -07:00
visionmedia 93239ae3fb Logger "common" format scale of 0.4f 2010-04-22 09:01:08 -07:00
visionmedia 5d21e9364d Match sinatra buffer size for static benchmark 2010-04-21 18:06:57 -07:00
visionmedia b9306c4cca Added sinatra static benchmark 2010-04-21 18:05:03 -07:00
visionmedia c07bd31f61 Outputting rps while benchmarking 2010-04-21 17:07:13 -07:00
visionmedia fee4830669 Added simple sinatra benchmark 2010-04-21 17:05:39 -07:00
visionmedia 9016b6778e Remove pids 2010-04-21 17:04:19 -07:00
visionmedia e05501a1ae Added simple thin benchmark 2010-04-21 17:03:39 -07:00
visionmedia 23d09fcc9e Added express static benchmark 2010-04-21 16:53:11 -07:00
visionmedia 5d11fccbf2 Ignore *.out 2010-04-21 16:42:39 -07:00
visionmedia 3851957dd0 Started benchmark script 2010-04-21 16:41:50 -07:00
visionmedia 135afb0883 Revert "Renamed session Base" - haha :) just kidding
This reverts commit 27b27af7cd.
2010-04-21 15:50:54 -07:00
visionmedia 27b27af7cd Renamed session Base 2010-04-21 15:50:43 -07:00
visionmedia 20fe31b803 Removed ETag work-around for bug in node
commit that fixed this: http://github.com/ry/node/commit/3934cb54853ca23cee7ef3c6206a5b1264f8ba6d
2010-04-21 15:33:06 -07:00
visionmedia ebca9aab8d Fix chat app plugins 2010-04-21 15:13:10 -07:00
visionmedia 49821e0416 Request#stream() fixes
a) on "end" the stream is already destroyed
  b) AFAIK its not destroyed on "error", so now we destroy it
  c) no need to callback(err) unless first
2010-04-21 14:53:46 -07:00
visionmedia b5d6f1ada5 Merge branch 'etag' 2010-04-21 14:37:17 -07:00
visionmedia b40325cd7b Misc refactoring to Request#trigger() 2010-04-21 13:49:44 -07:00
visionmedia 3b27ec66e1 Removed "data || {}" in Event constructor. Not needed anymore since Object#merge() handles non objects 2010-04-21 13:42:49 -07:00
visionmedia 52b8b36d54 Updated ext submodule which includes higher performance Object#merge() 2010-04-21 13:14:35 -07:00
visionmedia 7e3106dd1b Increase performance by preventing several calls to toLowerCase() in Router#match()
Roughly 10% increase for routing speeds
2010-04-21 12:48:37 -07:00
visionmedia 399e0d94fc Merge branch 'fix-opera' 2010-04-21 11:45:32 -07:00
visionmedia eef1ff9e87 Fixed bug preventing Opera from retaining the generated session id. Closes #292
This might not be the best solution, I am not sure what the cookie spec states.
But it works for now :)
2010-04-21 11:45:27 -07:00
visionmedia 9202c7504b Added "request" logger format for debugging http requests 2010-04-21 10:46:01 -07:00
visionmedia 3fd7e3b93e Added make prof so that we can generate v8.log and analyse the output 2010-04-21 09:58:39 -07:00
visionmedia b6996df86a Added "template created in ..." message in bin/express 2010-04-21 09:24:55 -07:00
visionmedia 4b3efd7bfa Added PREFIX to makefile 2010-04-21 09:24:30 -07:00
visionmedia 12c2682c34 Merge branch 'bin' 2010-04-21 08:57:55 -07:00
visionmedia 2caf67b813 Bash template generator with dummy app 2010-04-21 08:57:50 -07:00
visionmedia fbbe13661a Added view partials to feature list 2010-04-20 20:59:23 -07:00
visionmedia 0fb102edae Normalized another header name 2010-04-20 20:57:12 -07:00
visionmedia b4dd90d074 0.9.0 release details link 2010-04-20 19:53:42 -07:00
visionmedia 2e3f806d07 Normalized header conventions.
For example use Content-Type instead of content-type,
Request#header() lowercases when reading a header,
however does not when writing.
2010-04-20 19:33:54 -07:00
visionmedia f76092e83e Request#error() now accepts a callback function
A common idiom is / will be to accept a callback function in most cases
so this will help to keep things DRY
2010-04-20 19:23:16 -07:00
visionmedia 1e44081583 Added Request#sendHead() 2010-04-20 19:15:30 -07:00
visionmedia 26b3a4259d Added support for Request#halt(status, null) (empty response body) 2010-04-20 19:11:18 -07:00
visionmedia 8a074a7e6d Request#sendfile() Content-Length prevents images from rendering for some reason
commented out for now
2010-04-20 17:27:32 -07:00
visionmedia e99434582f Added ETag support to Request#sendfile() 2010-04-20 16:44:11 -07:00
visionmedia fec57df994 Added options to Request#sendfile(), passed to fs.createReadStream() 2010-04-20 13:09:24 -07:00
visionmedia 033cb2d20a Updated haml submodule 2010-04-20 11:07:58 -07:00
visionmedia a5fa58e3e6 Updated ext submodule 2010-04-20 09:59:35 -07:00
visionmedia fdc9d2714b Removed unused script from sample upload app.
This was preventing the page from loading
2010-04-20 09:46:02 -07:00
visionmedia 824ca9b513 Merge branch 'update-ext' 2010-04-20 09:32:57 -07:00
visionmedia a74a740964 Updated ext submodule 2010-04-20 09:32:52 -07:00
visionmedia 2041d52495 no need for type coercion for testing methods 2010-04-20 08:13:38 -07:00
visionmedia fb5d528eff Merge branch 'stream' 2010-04-19 15:22:24 -07:00
visionmedia a2cedbd9da Request#download() now accepts second filename arg 2010-04-19 15:20:35 -07:00
visionmedia 8574eddfa0 Misc refactoring to Request#stream() 2010-04-19 14:43:42 -07:00
visionmedia 2ccf876929 Started Request#stream() based of Aarons work on Static#streamfile() 2010-04-19 13:58:29 -07:00
visionmedia 28df150784 Revert "Only unshift support libs once"
This reverts commit 0950083da2.
2010-04-16 10:27:33 -07:00
visionmedia 0950083da2 Only unshift support libs once 2010-04-16 10:25:21 -07:00
visionmedia 88c5f910da Changed; sendfile() using notFound()
instead of halt() so that our DSL-level notFound()
route can handle this as needed. Also outputs the pretty
page when visiting directly
2010-04-15 09:43:29 -07:00
visionmedia a9d3e4798e Updated node --version supported 2010-04-15 08:50:25 -07:00
visionmedia d85d834b23 Updated JSpec 2010-04-15 08:49:59 -07:00
visionmedia 5729da5a9f Release 0.9.0 2010-04-14 17:03:57 -07:00
visionmedia 1255331160 Release 0.9.0 2010-04-14 16:56:13 -07:00
visionmedia 0fef51b5f6 Updated git submodules 2010-04-14 16:41:42 -07:00
visionmedia 7cf18c0468 Merge branch 'fix-querystring-0' 2010-04-13 13:25:55 -07:00
visionmedia b994509b9d Fixed bug preventing falsey params. Closes #286
Request#param() would prevously fail with ?page=0 for example
when param("page") is used since it would return undefined and not 0
2010-04-13 13:25:44 -07:00
visionmedia 6571e19e8f Added spec for #286 2010-04-13 13:17:27 -07:00
visionmedia 7441164db9 Merge branch 'integration' 2010-04-12 20:40:03 -07:00
visionmedia 09bb10cd3f Merge branch 'download' of git://github.com/aheckmann/express into integration 2010-04-12 20:39:20 -07:00
Aaron Heckmann bd6f24f4b1 add cookie support to readme 2010-04-12 22:56:59 -04:00
Aaron Heckmann 0a174ad219 move Request#download to Static plugin
#download() was a hangover from before the Static plugin existed and no longer worked. Also added missing specs so this won't happen again.
2010-04-12 22:49:49 -04:00
visionmedia 33d004fb9a Fixed MockResponse to match node API 2010-04-12 11:04:52 -07:00
visionmedia 652bf34c77 Merge branch 'integration' 2010-04-12 10:40:08 -07:00
Aaron Heckmann 3f11bad68e fix FileWriteStream.prototype.close renamed to end() 2010-04-11 23:10:41 -04:00
Aaron Heckmann 5245fbfc6d fix OutgoingMessage.prototype.close has been renamed to end() 2010-04-11 23:06:09 -04:00
visionmedia 68f8ee8a99 Fixed "express" executable due to node 0.1.90 changes 2010-04-11 18:39:14 -07:00
visionmedia 7b83a52dce http client fix from node renaming close to end 2010-04-11 18:10:58 -07:00
visionmedia 5f57c82478 Merge branch 'integration' 2010-04-11 18:08:05 -07:00
visionmedia 3128cbef73 Removed TODO comment
added an issue http://github.com/visionmedia/express/issues/issue/285
2010-04-11 18:08:00 -07:00
visionmedia 694b2bf055 Merge branch 'node_0.1.9_fixes' of git://github.com/ciaranj/express into integration 2010-04-11 18:04:31 -07:00
visionmedia e03a023c5f Merge branch 'integration' 2010-04-11 17:45:19 -07:00
ciaranj 3ff5d3bd09 Temporarily add back in the old multipart support
This will at least get us going again whilst decisions are made :)
2010-04-10 10:06:04 +01:00
ciaranj 04841196e3 Fixed the cookie test so it will work in different timezones.
Tj, I'm not sure what timezone you were in when you wrote the test, but
I've guessed that it was PDT ?   Hopefully this fix allows the test to
run in any timezone :) .. I was surprised that cookies don't use UTC which
could've mate things a lot cleaner, meh, old tech eh.
2010-04-10 09:59:41 +01:00
visionmedia 18dd495d99 Revert "Fixed relative require of Class"
This reverts commit f714945bbb.
2010-04-08 16:09:06 -07:00
visionmedia f714945bbb Fixed relative require of Class 2010-04-08 15:43:33 -07:00
visionmedia a318ef2232 Cookie expires now using Date#toGMTString()
Spec I found wanted hyphens, but this appears to be the norm
for JS cookies
2010-04-06 19:40:59 -07:00
visionmedia 8ed24de9d3 Updated haml submodule 2010-04-06 15:32:36 -07:00
visionmedia e06e50936d Updated sass submodule 2010-04-06 14:38:06 -07:00
visionmedia d710e9cb47 Merge branch 'integration' 2010-04-06 11:01:23 -07:00
Aaron Heckmann 9af3699850 utilize Date.now() 2010-04-04 12:50:11 -04:00
visionmedia 3cc7b4d8c2 Utilizing Date.now() 2010-04-02 14:12:36 -07:00
visionmedia 8b58732a1f Merge branch 'globals' 2010-04-02 13:35:04 -07:00
visionmedia a2a0935343 Request is no longer global 2010-04-02 13:13:26 -07:00
visionmedia 2668156e53 Event is no longer global 2010-04-02 13:07:54 -07:00
visionmedia d67615d239 puts() -> sys.puts() 2010-04-02 13:06:25 -07:00
visionmedia afd70b64ed Removed "sys" global merge 2010-04-02 13:05:18 -07:00
visionmedia 78a6e43667 Request#render() now only sets option.cache to true when set("cache view contents") is true
to allow development editing of the views
2010-03-31 10:36:52 -07:00
visionmedia a65af97e43 Docs 2010-03-31 10:28:40 -07:00
visionmedia 637dfabe69 render() always passing "cache" and "filename" options
if the engine does not use them, then they
will be ignored. However this already bumps
haml.js by about %25 in terms of performance
2010-03-31 10:20:24 -07:00
visionmedia ff8b3c10f3 Updated haml submodule 2010-03-31 10:14:29 -07:00
visionmedia f442555d8f Updated haml submodule 2010-03-31 08:10:28 -07:00
visionmedia bdf9f882ad Merge branch 'better-haml' 2010-03-31 07:51:00 -07:00
visionmedia 1e5c5bfe00 Switching around partial filename 2010-03-31 07:50:11 -07:00
visionmedia 0e78fdfcb4 Templates using haml.js instead of haml-js 2010-03-29 10:23:22 -07:00
visionmedia 4f532f86dc Added haml.js submodule; removed haml-js 2010-03-29 09:21:33 -07:00
visionmedia 92844825cb Always httpOnly session cookie 2010-03-29 08:37:57 -07:00
visionmedia 6b13fc99b0 Merge branch 'flip-views' 2010-03-29 08:25:23 -07:00
visionmedia 0f7aa26757 Added deprecation warning for views 2010-03-29 08:25:18 -07:00
visionmedia a06f963263 Merge branch 'flipViewExt' of git://github.com/aheckmann/express into flip-views 2010-03-29 07:58:13 -07:00
visionmedia d31de1e654 Defaulting httpOnly for Session cookies, however overridable 2010-03-29 07:55:37 -07:00
Aaron Heckmann 46a0301022 session cookie now httpOnly 2010-03-27 00:21:37 -04:00
Aaron Heckmann 73d26036ef updated specs and example apps
all tests passing
2010-03-27 00:00:49 -04:00
Aaron Heckmann b9637c9d7d started flipping view extensions 2010-03-27 00:00:49 -04:00
visionmedia 08497683bf Fixed setting of multiple cookies. Closes #199 2010-03-26 16:08:39 -07:00
visionmedia 44a50f6e58 Moved require("http") out of Server#run() 2010-03-26 07:16:55 -07:00
visionmedia 4c2b4e5c66 Removed unused require 2010-03-26 07:16:12 -07:00
Guillermo Rauch b0884ad7c3 Correction 2010-03-25 19:33:45 -07:00
Guillermo Rauch cf09f86df2 Expose the http.Server instance 2010-03-25 19:17:43 -07:00
visionmedia d33c38f671 Merge branch 'integration' 2010-03-25 15:57:08 -07:00
Aaron Heckmann fbfba21854 multipart parse only when needed 2010-03-25 18:03:32 -04:00
visionmedia b2093d6f10 Merge branch 'partial-index-and-length' 2010-03-25 12:47:22 -07:00
visionmedia 736a0190c1 Passing __index__, __length__, __isFirst__, __isLast__ to collection partials. Closes #254 2010-03-25 12:47:17 -07:00
visionmedia a74c259c38 Request instance created before body parsing. Closes #262
Merge branch 'request'
2010-03-25 11:48:35 -07:00
visionmedia d3dedd6312 Fixed post param issue 2010-03-25 11:44:55 -07:00
visionmedia 920eab0ef9 Fixed mocks to work with new routing api 2010-03-25 11:37:56 -07:00
visionmedia d576085e8d . 2010-03-25 11:09:50 -07:00
visionmedia 62b9a9e287 Docs 2010-03-25 10:49:25 -07:00
visionmedia 56ffe1d62a Merge branch 'upload-limit' 2010-03-25 10:49:00 -07:00
visionmedia 14acbcb5f1 Added "max upload size" setting 2010-03-25 10:48:55 -07:00
visionmedia 9a0011bf49 Updated ext. Closes #256
Should be fixed now :)
2010-03-25 09:29:52 -07:00
visionmedia 7b9f18b097 Added Request#render() callback function. Closes #258 2010-03-25 08:53:47 -07:00
visionmedia f8e4333157 Merge branch 'integration' 2010-03-25 08:40:47 -07:00
visionmedia b5c933aa94 fn -> callback 2010-03-25 08:40:18 -07:00
visionmedia c441af3f2c Typo 2010-03-25 08:39:48 -07:00
visionmedia e885421a67 Merge branch 'master' of git://github.com/aheckmann/express into integration 2010-03-25 08:38:54 -07:00
visionmedia ce4fe24a93 Updated to JSpec 4.0.0 2010-03-25 08:25:38 -07:00
visionmedia 1c0e2ceba5 error() is passed the exception 2010-03-25 08:24:19 -07:00
Aaron Heckmann a435e8ec47 fn -> callback 2010-03-25 11:22:48 -04:00
visionmedia b958393135 Added DSL level error() route support 2010-03-25 08:21:49 -07:00
visionmedia a6dd697a68 Added DSL level notFound() route support 2010-03-25 08:13:22 -07:00
visionmedia a4833e7b35 Added specs for Request#notFound() 2010-03-25 07:58:28 -07:00
visionmedia 54fa643c10 More Request#error() specs 2010-03-25 07:54:07 -07:00
visionmedia 6047cd4542 Added specs for Request#error() 2010-03-25 07:51:19 -07:00
visionmedia 8c5f7df280 Merge branch 'errors' 2010-03-25 07:35:44 -07:00
visionmedia ff1250c33c Added publish Request#notFound() 2010-03-25 07:35:39 -07:00
visionmedia 4297c10fe9 Removed Express.error(), Added public Request#error() 2010-03-25 07:18:55 -07:00
visionmedia ab6ad94ec3 Request#halt() accepts callback function as 3rd/4th arg 2010-03-24 16:05:34 -07:00
visionmedia 759183461f Merge branch 'error-handling' 2010-03-24 15:44:50 -07:00
visionmedia f850fa6bc9 Misc error handling improvements 2010-03-24 15:44:46 -07:00
visionmedia 5a242d35b7 Removed unused variable 2010-03-24 15:15:45 -07:00
visionmedia abf5d66e01 Merge branch 'error-handling' 2010-03-24 15:08:51 -07:00
visionmedia e92360e0d4 Caching notFound / showException modules 2010-03-24 15:08:06 -07:00
visionmedia b5c0fdc013 Express.error() now acts as the core exception handler 2010-03-24 14:54:13 -07:00
visionmedia 906ef02c5e request response event is now fired in reverse.
This does a few things:
  a. Allows plugins such as Logger to properly "wrap" all
     other plugins when it is the first passed to use().

  b. Lessons the chance of a plugin failure effecting another plugin
2010-03-24 14:45:46 -07:00
visionmedia 7550decbc0 Handle when a plugin response fails 2010-03-24 14:32:08 -07:00
visionmedia acd88c3c8a next -> callback 2010-03-24 12:56:26 -07:00
visionmedia a3854a2de1 Styling 2010-03-24 12:54:52 -07:00
visionmedia 880aca5d83 Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) 2010-03-24 12:53:33 -07:00
visionmedia 2d1c98a5a7 Docs for stable / edge 2010-03-24 08:33:43 -07:00
visionmedia fefa06ba21 Merge branch 'route-wildcards' 2010-03-23 10:41:31 -07:00
visionmedia 18faa91c94 Added preprocessing of route param wildcards using param(). Closes #251
Async is yet to come
2010-03-23 10:41:25 -07:00
visionmedia 9f23c7b31a Added specs for param() 2010-03-23 10:31:46 -07:00
visionmedia eee6926bab Added more route wildcard specs 2010-03-23 10:11:52 -07:00
visionmedia 6806f952d6 Merge branch 'pre-cache-views' 2010-03-23 09:53:23 -07:00
visionmedia faaef54b42 Pre-caching views in memory. Closes #253
This mirrors the partial caching functionality. This
causes a slight overhead at boot time, however prevents
the need to perform cache checks per render() call.
2010-03-23 09:53:17 -07:00
visionmedia c29852fae7 Started pre caching of views 2010-03-23 09:42:23 -07:00
visionmedia 7d100dae97 Merge branch 'integration' 2010-03-22 15:34:50 -07:00
visionmedia 206e800963 Added assertion to ensure that partials dir is relative to set("views") 2010-03-22 15:34:46 -07:00
visionmedia 555a334315 Re-using variables 2010-03-22 15:33:08 -07:00
visionmedia d2c5def108 Using set("views") when setting set("partials")
So that /partials is always relative by default
2010-03-22 15:31:39 -07:00
visionmedia 98323c530e partialscache -> partials 2010-03-22 15:30:34 -07:00
Aaron Heckmann b36510dbb9 preload partials
add settings
bug fix, partial now works when cache view contents is true
2010-03-22 18:16:40 -04:00
Aaron Heckmann 50e533c32b add cache view partials 2010-03-22 16:40:35 -04:00
visionmedia 33277c3d37 Removed utils.mixin() use Object#mergeDeep()
jQuery is messy, and this implementation is way to
slow for SSJS, and just gross :)
2010-03-22 11:28:23 -07:00
visionmedia 28f2ad0109 Merge branch 'partials' 2010-03-22 10:21:42 -07:00
visionmedia 5d10ee4e61 Chat sample app using partials as an example 2010-03-22 10:21:37 -07:00
visionmedia b4190ada0c Added partial "as" option 2010-03-22 10:16:12 -07:00
visionmedia 60d314552d Partial collection should not introduce newlines 2010-03-22 10:13:25 -07:00
visionmedia c971d54543 Added partial collection support 2010-03-22 10:12:52 -07:00
visionmedia 346f019fa8 Started view partial support 2010-03-22 10:05:05 -07:00
visionmedia d61c2480b6 Updated ext submodule 2010-03-22 09:12:24 -07:00
visionmedia e30b5b86da Removed Request#_blendInNodeRequest() 2010-03-22 09:12:09 -07:00
visionmedia bd74fe24fd Merge branch 'net2_fixes' of git://github.com/ciaranj/express 2010-03-22 09:05:58 -07:00
visionmedia b30eaa8ee3 Updated support to v0.1.33 2010-03-22 08:34:05 -07:00
ciaranj 75c530516a Various minor fixes required to make express work post the net2 merge branch 2010-03-20 12:26:37 +00:00
visionmedia 3b49821e82 Release 0.8.0 2010-03-19 16:51:43 -07:00
visionmedia febf443960 Fixed session reaper 2010-03-19 15:57:25 -07:00
visionmedia f5da81e782 Removed a comment from chat app 2010-03-19 14:38:26 -07:00
visionmedia 9cb23ac584 Merge branch 'coffee' 2010-03-19 14:14:52 -07:00
visionmedia 6ff3100c1f Added coffeescript example app. Closes #242 2010-03-19 14:14:46 -07:00
visionmedia e3ea3723bf Added dir for coffeescript example 2010-03-19 13:56:31 -07:00
visionmedia 33443d9b41 Merge branch 'integration' 2010-03-19 10:13:26 -07:00
visionmedia e0ef61659f Merge branch 'async-session' into integration 2010-03-19 10:12:56 -07:00
visionmedia 655ad77bce fn -> callback 2010-03-19 09:55:06 -07:00
visionmedia c09e546240 Removed session reaper try/catch
we can revisit this issue later,
and deal with it across Cache as well
2010-03-19 09:53:33 -07:00
visionmedia a08b14a89e Misc Session refactoring 2010-03-19 09:52:18 -07:00
visionmedia 12e90b0eef Merge branch 'session_with_callbacks' of git://github.com/ciaranj/express into async-session 2010-03-19 09:41:30 -07:00
visionmedia 7606f1bcbd Merge branch 'async-cache' 2010-03-19 09:38:47 -07:00
visionmedia cabb43b187 Finished converting async cache api. Closes #240 2010-03-19 09:38:42 -07:00
visionmedia b85cda3f6e Cache api is now async 2010-03-19 09:19:22 -07:00
visionmedia b92f1b7497 Async cache specs 2010-03-19 09:04:31 -07:00
visionmedia 273a51a335 Release 0.7.6 2010-03-19 08:55:52 -07:00
ciaranj 212dc88b89 Squashed commit of the changes I've put in place to support callback
methods on the session object.

This code changes the behaviour of the session handling in a fairly key
way:

If an unknown session id is seen then a *new* session is created with a *new* session
id.  The previous behaviour was to create a new session with the existing id.
2010-03-19 13:55:51 +00:00
visionmedia ce82a91d14 Revert "Fail to test CI"
This reverts commit 52a08401c7.
2010-03-18 16:20:53 -07:00
visionmedia 52a08401c7 Fail to test CI 2010-03-18 16:20:12 -07:00
visionmedia 706c0cb033 View support listed in features already 2010-03-18 16:19:39 -07:00
visionmedia 1567a613a6 Closes #63.
Merge branch 'cli'
2010-03-18 13:02:00 -07:00
visionmedia d767d80d20 Added make install 2010-03-18 13:01:28 -07:00
visionmedia 1103a9d510 Moved a helper function to the helpers section 2010-03-18 13:00:34 -07:00
visionmedia c34af4b97a Started executable 2010-03-18 12:57:44 -07:00
visionmedia 8dcee4d338 Request#render() only calls cache.get() once 2010-03-18 11:40:48 -07:00
visionmedia fc1e69ea73 Namespacing View caches with "view:" 2010-03-18 11:40:04 -07:00
visionmedia db460117c1 Namespacing Static caches with "static:" 2010-03-18 11:39:23 -07:00
visionmedia 1c514df0fd Fixed ternary style 2010-03-18 11:37:34 -07:00
visionmedia 780ec5cbec Docs 2010-03-18 11:27:15 -07:00
visionmedia 3721873b62 Both example apps now use Static 2010-03-18 11:23:07 -07:00
visionmedia 3bdc77ca91 Deprecated Request#sendfile() and express/static 2010-03-18 11:22:40 -07:00
visionmedia b8f54d64a4 Closes #88.
Merge branch 'runtime-routes'
2010-03-18 11:17:16 -07:00
visionmedia 90d48b320a Added "GET /public/*" to Static plugin, defaulting to <root>/public 2010-03-18 11:16:55 -07:00
visionmedia a797342800 Static is now a plugin 2010-03-18 11:09:25 -07:00
visionmedia 31e608e0ae Added Request#sendfile() specs 2010-03-18 10:58:50 -07:00
visionmedia ebcfb0e577 Removed Server#running 2010-03-18 10:31:40 -07:00
visionmedia 161c9f9142 Closes #52
fs.readFile becomes fs.readFileSync when testing

Merge branch 'view-specs'
2010-03-18 10:17:03 -07:00
visionmedia 2a099da726 Fixed a few specs 2010-03-18 10:16:14 -07:00
visionmedia 5118397004 Added auto content-type view spec 2010-03-18 10:14:10 -07:00
visionmedia 546c340656 Added view custom context spec 2010-03-18 10:12:20 -07:00
visionmedia 3034cc7c52 View context spec 2010-03-18 10:10:10 -07:00
visionmedia d89381ff78 Added layout local var access spec 2010-03-18 10:04:25 -07:00
visionmedia 86cac58100 Added view locals spec 2010-03-18 09:54:29 -07:00
visionmedia 8fc062007e Added spec for invalid view engine 2010-03-18 09:51:48 -07:00
visionmedia 9fd92e3306 Added view caching specs 2010-03-18 09:50:16 -07:00
visionmedia a4cbbe5dd4 Spec for layout: false 2010-03-18 09:36:57 -07:00
visionmedia da7ea9655f Spec for custom layout 2010-03-18 09:36:12 -07:00
visionmedia 00a8c642dd Started view specs 2010-03-18 09:32:32 -07:00
visionmedia e1152f6e56 Typo 2010-03-18 09:12:46 -07:00
visionmedia 7cf9c6842a Merge branch 'fix-views' 2010-03-18 09:08:06 -07:00
visionmedia d375535cd9 Fixed set("views"). Closes #239
This actually should have never worked (if it even did).
My bad :)
2010-03-18 09:08:02 -07:00
visionmedia c5ea868f47 Merge branch 'bugfix' of git://github.com/aheckmann/express 2010-03-18 08:02:23 -07:00
visionmedia 884d333805 Added Request#isXHR. Closes #229
Merge branch 'integration'
2010-03-18 07:55:30 -07:00
visionmedia 3b9921a15b Added Request#isXHR specs 2010-03-18 07:54:34 -07:00
Aaron Heckmann 17b753d95e add missing space to combined log format 2010-03-17 22:38:45 -04:00
Aaron Heckmann 6a8781b5e2 add request.isXHR 2010-03-17 22:16:13 -04:00
Aaron Heckmann 0dfaf01749 add git clone to git command 2010-03-17 21:40:13 -04:00
visionmedia 088aa83e22 Updated feature list 2010-03-17 16:07:53 -07:00
visionmedia 934adb1e9f Release 0.7.5 2010-03-16 19:38:21 -07:00
visionmedia 50e0593de6 Request#flash() without args now returns all flashes 2010-03-16 19:34:11 -07:00
visionmedia f2637c6421 Fixed Request#flash() specs 2010-03-16 19:22:10 -07:00
visionmedia a52dacea68 Updated ext 2010-03-16 19:12:15 -07:00
visionmedia f56a33d22d Release 0.7.4 2010-03-16 16:14:48 -07:00
visionmedia 2aa858b0fb Merge branch 'class' 2010-03-16 16:12:42 -07:00
visionmedia c3b8ba4b9a NewClass -> Class, removed js-oo dependency 2010-03-16 16:12:14 -07:00
visionmedia ac96b8c0e1 Update class.js submodule with Class#include() 2010-03-16 16:10:39 -07:00
visionmedia a329a9f4d8 Converted more to use class.js 2010-03-16 15:53:32 -07:00
visionmedia 63cc7eb44d Converted more to use class.js 2010-03-16 15:50:17 -07:00
visionmedia 6505f32221 Started conversion of js-oo Class -> class.js 2010-03-16 15:46:22 -07:00
visionmedia 22088260f4 Fixed session reaper 2010-03-16 13:25:39 -07:00
116 arquivos alterados com 3340 adições e 969 exclusões
+5 -1
Ver Arquivo
@@ -1,3 +1,7 @@
.DS_Store
*.seed
*.log
*.log
*.csv
*.dat
*.out
benchmarks/graphs
+7 -4
Ver Arquivo
@@ -1,12 +1,15 @@
[submodule "lib/support/oo"]
path = lib/support/oo
url = git://github.com/visionmedia/js-oo.git
[submodule "lib/support/ext"]
path = lib/support/ext
url = git://github.com/visionmedia/ext.js.git
[submodule "lib/support/sass"]
path = lib/support/sass
url = git://github.com/visionmedia/sass.js.git
[submodule "lib/support/class"]
path = lib/support/class
url = git://github.com/visionmedia/class.js.git
[submodule "lib/support/haml"]
path = lib/support/haml
url = git://github.com/creationix/haml-js.git
url = git://github.com/visionmedia/haml.js.git
[submodule "lib/support/multipart"]
path = lib/support/multipart
url = git://github.com/isaacs/multipart-js.git
+134
Ver Arquivo
@@ -1,4 +1,138 @@
0.13.0 / 2010-06-01
==================
* Added node v0.1.97 compatibility
* Added support for deleting cookies via Request#cookie('key', null)
* Updated haml submodule
* Fixed not-found page, now using using charset utf-8
* Fixed show-exceptions page, now using using charset utf-8
* Fixed view support due to fs.readFile Buffers
* Changed; mime.type() no longer accepts ".type" due to node extname() changes
0.12.0 / 2010-05-22
==================
* Added node v0.1.96 compatibility
* Added view `helpers` export which act as additional local variables
* Updated haml submodule
* Changed ETag; removed inode, modified time only
* Fixed LF to CRLF for setting multiple cookies
* Fixed cookie complation; values are now urlencoded
* Fixed cookies parsing; accepts quoted values and url escaped cookies
0.11.0 / 2010-05-06
==================
* Added support for layouts using different engines
- this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' })
- this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml'
- this.render('page.html.haml', { layout: false }) // no layout
* Updated ext submodule
* Updated haml submodule
* Fixed EJS partial support by passing along the context. Issue #307
0.10.1 / 2010-05-03
==================
* Fixed binary uploads.
0.10.0 / 2010-04-30
==================
* Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s
encoding is set to 'utf8' or 'utf-8'.
* Added "encoding" option to Request#render(). Closes #299
* Added "dump exceptions" setting, which is enabled by default.
* Added simple ejs template engine support
* Added error reponse support for text/plain, application/json. Closes #297
* Added callback function param to Request#error()
* Added Request#sendHead()
* Added Request#stream()
* Added support for Request#respond(304, null) for empty response bodies
* Added ETag support to Request#sendfile()
* Added options to Request#sendfile(), passed to fs.createReadStream()
* Added filename arg to Request#download()
* Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request
* Performance enhanced by preventing several calls to toLowerCase() in Router#match()
* Changed; Request#sendfile() now streams
* Changed; Renamed Request#halt() to Request#respond(). Closes #289
* Changed; Using sys.inspect() instead of JSON.encode() for error output
* Changed; run() returns the http.Server instance. Closes #298
* Changed; Defaulting Server#host to null (INADDR_ANY)
* Changed; Logger "common" format scale of 0.4f
* Removed Logger "request" format
* Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found
* Fixed several issues with http client
* Fixed Logger Content-Length output
* Fixed bug preventing Opera from retaining the generated session id. Closes #292
0.9.0 / 2010-04-14
==================
* Added DSL level error() route support
* Added DSL level notFound() route support
* Added Request#error()
* Added Request#notFound()
* Added Request#render() callback function. Closes #258
* Added "max upload size" setting
* Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254
* Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js
* Added callback function support to Request#halt() as 3rd/4th arg
* Added preprocessing of route param wildcards using param(). Closes #251
* Added view partial support (with collections etc)
* Fixed bug preventing falsey params (such as ?page=0). Closes #286
* Fixed setting of multiple cookies. Closes #199
* Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml)
* Changed; session cookie is now httpOnly
* Changed; Request is no longer global
* Changed; Event is no longer global
* Changed; "sys" module is no longer global
* Changed; moved Request#download to Static plugin where it belongs
* Changed; Request instance created before body parsing. Closes #262
* Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253
* Changed; Pre-caching view partials in memory when "cache view partials" is enabled
* Updated support to node --version 0.1.90
* Updated dependencies
* Removed set("session cookie") in favour of use(Session, { cookie: { ... }})
* Removed utils.mixin(); use Object#mergeDeep()
0.8.0 / 2010-03-19
==================
* Added coffeescript example app. Closes #242
* Changed; cache api now async friendly. Closes #240
* Removed deprecated 'express/static' support. Use 'express/plugins/static'
0.7.6 / 2010-03-19
==================
* Added Request#isXHR. Closes #229
* Added `make install` (for the executable)
* Added `express` executable for setting up simple app templates
* Added "GET /public/*" to Static plugin, defaulting to <root>/public
* Added Static plugin
* Fixed; Request#render() only calls cache.get() once
* Fixed; Namespacing View caches with "view:"
* Fixed; Namespacing Static caches with "static:"
* Fixed; Both example apps now use the Static plugin
* Fixed set("views"). Closes #239
* Fixed missing space for combined log format
* Deprecated Request#sendfile() and 'express/static'
* Removed Server#running
0.7.5 / 2010-03-16
==================
* Added Request#flash() support without args, now returns all flashes
* Updated ext submodule
0.7.4 / 2010-03-16
==================
* Fixed session reaper
* Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft)
0.7.3 / 2010-03-16
==================
+32 -3
Ver Arquivo
@@ -1,17 +1,46 @@
AB = ab
ABFLAGS = -n 3000 -c 50
NODE = node
COFFEE = coffee
PREFIX = /usr/local
all: test
install: bin/express
ln -fs $< $(PREFIX)/bin/express
uninstall:
rm -f $(PREFIX)/bin/express
test:
@$(NODE) spec/node.js all
app: app-chat
prof:
@$(NODE) --prof --prof_auto examples/chat/app.js
app-chat:
@$(NODE) examples/chat/app.js
app-hello-world:
@$(NODE) examples/hello-world/app.js
app-upload:
@$(NODE) examples/upload/app.js
.PHONY: test app
app-coffee-upload: compile-coffee
@$(NODE) examples/coffee-upload/app.js
compile-coffee:
@$(COFFEE) examples/coffee-upload/app.coffee
benchmark: benchmarks/run
@./benchmarks/run
@./benchmarks/graph
graphs:
@./benchmarks/graph
.PHONY: install test app benchmark graphs
+23 -12
Ver Arquivo
@@ -12,15 +12,25 @@
* Sexy DSL with robust sinatra-like routing
* High performance
* Session support
* Cache API
* RESTful HTTP client
* Mime helpers
* ETag support
* Redirection helpers
* Multipart file upload support
* Test helpers (mock requests etc)
* Environment based configuration
* Light-weight JavaScript class implementation via js-oo
* Light-weight JavaScript class implementation via [class.js](http://github.com/visionmedia/class.js/)
* Persistent flash messages
* Route passing
* View support (ejs, haml, sass, etc)
* View partials
* View globals/helpers support
* Full test coverage
* Logger plugin with several formats
* Upload size restrictions
* Extremely readable specs
* Cookie support
## Installation
@@ -33,14 +43,7 @@ or
Install via git clone:
$ git://github.com/visionmedia/express.git && cd express && git submodule update --init
## Performance
Extensive performance enhancements have not yet been made,
since we are focusing on the framework it-self at the moment.
However if you are interested view the premature [benchmarks for Express framework](http://vision-media.ca/resources/nodejs/express-nodejs-web-development-framework-performance).
$ git clone git://github.com/visionmedia/express.git && cd express && git submodule update --init
## Examples
@@ -49,6 +52,10 @@ Below is a tiny Express application. View the [Wiki](http://wiki.github.com/visi
require.paths.unshift('express/lib')
require('express')
configure(function(){
set('root', __dirname)
})
get('/user', function(){
this.redirect('/user/' + this.currentUser.id)
})
@@ -63,7 +70,7 @@ Below is a tiny Express application. View the [Wiki](http://wiki.github.com/visi
})
run()
## Running Tests
Express uses the [JSpec](http://jspec.info) BDD JavaScript testing
@@ -79,14 +86,18 @@ Run individual suites:
$ node spec/node.js routing
...
Express is currently being developed with node --version:
v0.1.32
The latest release of Express is compatible with node --version:
v0.1.97
With _EDGE_ Express we do our best to keep up to date with node's _EDGE_
## More Information
* [JavaScript Extensions &amp; Utilities](http://github.com/visionmedia/ext.js)
* [JavaScript Sass](http://github.com/visionmedia/sass.js)
* Featured in [Advanced JavaScript e-book](http://www.dev-mag.com/2010/02/18/advanced-javascript/) for only $4
* [0.9.0 release details](http://tjholowaychuk.com/post/522036176/express-0-9-0-released)
* [Express vs Sinatra Benchmarks](http://tjholowaychuk.com/post/543953703/express-vs-sinatra-benchmarks)
## Contributors
+16
Ver Arquivo
@@ -0,0 +1,16 @@
require.paths.unshift('lib')
require('express')
require('express/plugins')
configure(function(){
//enable('cache view contents')
set('root', __dirname)
set('views', __dirname + '/../shared')
})
get('/', function(){
this.render('page.html.haml')
})
run()
+16
Ver Arquivo
@@ -0,0 +1,16 @@
require.paths.unshift('lib')
require('express')
require('express/plugins')
configure(function(){
//enable('cache view contents')
set('root', __dirname)
set('views', __dirname + '/../shared')
})
get('/', function(){
this.render('style.css.sass', { layout: false })
})
run()
+9
Ver Arquivo
@@ -0,0 +1,9 @@
require.paths.unshift('lib')
require('express')
get('/', function(){
return 'Hello World'
})
run()
+15
Ver Arquivo
@@ -0,0 +1,15 @@
require.paths.unshift('lib')
require('express')
require('express/plugins')
configure(function(){
use(Static)
set('root', __dirname)
})
get('/', function(){
this.sendfile('benchmarks/shared/jquery.js', { bufferSize: 8 * 1024 })
})
run()
+15
Ver Arquivo
@@ -0,0 +1,15 @@
require.paths.unshift('lib')
require('express')
require('express/plugins')
configure(function(){
use(Static)
set('root', __dirname)
})
get('/', function(){
this.sendfile('benchmarks/shared/huge.js', { bufferSize: 8 * 1024 })
})
run()
Arquivo executável
+84
Ver Arquivo
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
COL=${COL-9}
#
# Log <msg ...>
#
# <msg ...>
#
log(){
echo "... $@"
}
#
# Output gnuplot script for line graph.
#
# <title> <node> <express> <sinatra>
#
function line() {
cat <<-EOF
set terminal png
set output "benchmarks/graphs/$1.png"
set title "$1"
set size 1,0.7
set grid y
set key left top
set xlabel "request"
set ylabel "response time (ms)"
plot "benchmarks/$2" using $COL smooth sbezier with lines title "node", \\
"benchmarks/$3" using $COL smooth sbezier with lines title "express", \\
"benchmarks/$4" using $COL smooth sbezier with lines title "sinatra thin"
EOF
}
#
# Output gnuplot script for bar graph.
#
# <title> <node> <express> <sinatra>
#
function bar() {
cat <<-EOF
set terminal png
set output "benchmarks/graphs/$1.rps.png"
set title "$1"
set size 0.7,0.5
set grid y
set key left top
set ylabel "requests per second"
plot "benchmarks/$1.rps.dat" using 2: xtic(1) with histogram title ""
EOF
}
mkdir -p benchmarks/graphs
for type in simple haml sass static static.large; do
plot=benchmarks/graphs/$type.p
log generating benchmarks/graphs/$type.png
line $type \
node/$type.js.dat \
express/$type.js.dat \
thin/$type.ru.dat \
> $plot
gnuplot $plot
log generating benchmarks/graphs/$type.rps.png
plot=benchmarks/graphs/$type.rps.p
dat=benchmarks/$type.rps.dat
:> $dat
for server in node express thin; do
case $server in
node|express) ext=js ;;
thin) ext=ru ;;
esac
rps=$(cat benchmarks/$server/$type.$ext.out | grep "Requests per second:" | awk '{ print $4 }')
echo $server $rps >> $dat
done
bar $type > $plot
gnuplot $plot
done
rm benchmarks/graphs/*.p
+8
Ver Arquivo
@@ -0,0 +1,8 @@
var fs = require('fs'),
http = require('http')
http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': 11 })
res.end('Hello World', 'ascii')
}).listen(3000, 'localhost')
+14
Ver Arquivo
@@ -0,0 +1,14 @@
var fs = require('fs'),
http = require('http')
http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked' })
fs.createReadStream('benchmarks/shared/jquery.js')
.addListener('data', function(data){
res.write(data, 'binary')
})
.addListener('end', function(){
res.end()
})
}).listen(3000, 'localhost')
+14
Ver Arquivo
@@ -0,0 +1,14 @@
var fs = require('fs'),
http = require('http')
http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked' })
fs.createReadStream('benchmarks/shared/huge.js')
.addListener('data', function(data){
res.write(data, 'binary')
})
.addListener('end', function(){
res.end()
})
}).listen(3000, 'localhost')
Arquivo executável
+61
Ver Arquivo
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
SLEEP=${SLEEP-2}
ABFLAGS=${ABFLAGS-"-n 2000 -c 50"}
ADDR=${ADDR-http://127.0.0.1:3000/}
AB=${AB-ab}
#
# Log <msg ...>
#
# <msg ...>
#
log(){
echo "... $@"
}
#
# Benchmark <type> and <file>
#
# - starts the server
# - allows $SLEEP seconds for startup
# - runs $AB
# - kills the server process
#
# <type> <file>
#
bm(){
local type=$1
local file=$2
log benchmarking $type $file
case $type in
node|express)
node benchmarks/$type/$file &
;;
thin)
thin -R benchmarks/thin/$file -p 3000 start &
;;
esac
pid=$!
sleep $SLEEP
$AB $ABFLAGS -g benchmarks/$type/$file.dat $ADDR > benchmarks/$type/$file.out
log $(cat benchmarks/$type/$file.out | grep Requests)
kill -KILL $pid
}
log ab $ABFLAGS $ADDR
bm node simple.js
bm node static.js
bm node static.large.js
bm express simple.js
bm express static.js
bm express static.large.js
bm express haml.js
bm express sass.js
bm thin simple.ru
bm thin static.ru
bm thin static.large.ru
bm thin haml.ru
bm thin sass.ru
Diff do arquivo suprimido porque uma ou mais linhas são muito longas
+19
Ver Arquivo
Diff do arquivo suprimido porque uma ou mais linhas são muito longas
+6
Ver Arquivo
@@ -0,0 +1,6 @@
!!!
%html
%head
%title Wahoo
%body
#primary= yield
+6
Ver Arquivo
@@ -0,0 +1,6 @@
!!!
%html
%head
%title Wahoo
%body
#primary!= body
+10
Ver Arquivo
@@ -0,0 +1,10 @@
%h1 Some title
%ul
%li a
%li b
%li c
%li
%ol
%li d
%li e
%li f
+10
Ver Arquivo
@@ -0,0 +1,10 @@
%h1 Some title
%ul
%li a
%li b
%li c
%li
%ol
%li d
%li e
%li f
+73
Ver Arquivo
@@ -0,0 +1,73 @@
body
:font-family "Helvetica Neue", "Lucida Grande", "Arial"
:font-size 13px
:text-align center
:color #555
h1, h2
:margin 0
:font-size 22px
:color #343434
h1
:text-shadow 1px 2px 2px #ddd
:font-size 60px
img.bubble
:position absolute
:top -25px
:left 120px
#wrapper
:position relative
:margin 100px auto
:width 500px
:text-align left
ul
:margin 0
:padding 0
:max-height 300px
:overflow-x hidden
li
:margin 5px 0
:padding 3px 8px
:list-style none
:border 1px solid #eee
li:hover
:cursor pointer
:color #2E2E2E
input[type=text]
:padding 5px
:border 1px solid #ddd
:outline none
input[type=text]:focus
:border-color #00C3FF
input[type=submit]
:padding 6px 10px
:border solid 1px #999
:background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ddd))
:color #333
:text-decoration none
:cursor pointer
:display inline-block
:text-align center
:text-shadow 0px 1px 1px #fff
:line-height 1
input[type=submit]:hover
:background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#E6E4E4))
input[type=submit]:active
:background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#c7c7c7))
input[name=name]
:width 80px
a
:color #1ABFF1
a:hover
:padding 0 5px
a:hover:before
:content 'visit: '
#online
:font-size 12px
+14
Ver Arquivo
@@ -0,0 +1,14 @@
require 'rubygems'
require 'sinatra'
require 'haml'
configure do
set 'views', File.dirname(__FILE__) + '/../shared'
end
get '/' do
haml :page, :ugly => true
end
run Sinatra::Application
+14
Ver Arquivo
@@ -0,0 +1,14 @@
require 'rubygems'
require 'sinatra'
require 'sass'
configure do
set 'views', File.dirname(__FILE__) + '/../shared'
end
get '/' do
sass :'style.css'
end
run Sinatra::Application
+9
Ver Arquivo
@@ -0,0 +1,9 @@
require 'rubygems'
require 'sinatra'
get '/' do
'Hello World'
end
run Sinatra::Application
+9
Ver Arquivo
@@ -0,0 +1,9 @@
require 'rubygems'
require 'sinatra'
get '/' do
send_file 'benchmarks/shared/huge.js'
end
run Sinatra::Application
+9
Ver Arquivo
@@ -0,0 +1,9 @@
require 'rubygems'
require 'sinatra'
get '/' do
send_file 'benchmarks/shared/jquery.js'
end
run Sinatra::Application
Arquivo executável
+142
Ver Arquivo
@@ -0,0 +1,142 @@
#!/usr/bin/env bash
#
# Output usage information and exit.
#
function usage() {
echo 'usage: express [options] [dir]'
exit 1
}
#
# Create template in the givin [dir] or cwd.
#
# [dir]
#
function create_template() {
local dir=${1-.}
mkdir -p $dir
[[ $(ls $dir) ]] && confirm "$dir is not empty, continue?"
mkdir -p $dir/public/{javascripts,stylesheets,images}
mkdir -p $dir/views/partials
app_template > $dir/app.js
layout_template > $dir/views/layout.html.haml
front_template > $dir/views/front.html.haml
sass_template > $dir/views/style.css.sass
echo template created in $dir
}
#
# views/style.css.sass
#
function sass_template() {
cat <<-EOF
blue: #03ADF0
light: #4d4d4d
lighter: #eee
body
:margin 80px
:font 14px/1.5 "Helvetica Nueue", "Lucida Grande", "Arial", sans-serif
code
:padding 3px 10px
:border 1px solid !lighter
:color !light
a
:color !blue
:text-decoration none
&:hover
:text-decoration underline
EOF
}
#
# views/front.html.haml
#
function front_template() {
cat <<-EOF
%h1 Express
%p
Generated by the
<code>express</code>
executable.
%p
Visit
%a{ href: 'http://expressjs.com' } ExpressJS.com
for more information.
EOF
}
#
# views/layout.html.haml
#
function layout_template() {
cat <<-EOF
!!! strict
%html
%head
%title Express
%link{ rel: 'stylesheet', href: 'style.css' }
%body!= body
EOF
}
#
# app.js
#
function app_template() {
cat <<-EOF
// If you are using the kiwi package manager
var kiwi = require('kiwi'),
express = kiwi.require('express')
// Otherwise you will need to expose the path to express
// require.paths.unshift('path/to/express/lib')
// require('express')
configure(function(){
set('root', __dirname)
})
get('/', function(){
this.render('front.html.haml')
})
get('/*.css', function(path){
this.render(path + '.css.sass', { layout: false })
})
run()
EOF
}
#
# Confirm <msg> or exit.
#
# <msg>
#
function confirm() {
echo -n "$1 "
read answer
case $answer in
n|N|no) exit 1 ;;
y|Y|yes) ;;
*) confirm "yes or no?" ;;
esac
}
# Process arguments
case $1 in
-h|--help|help) usage ;;
*) create_template $1 ;;
esac
+19 -18
Ver Arquivo
@@ -4,30 +4,35 @@ require('express')
require('express/plugins')
var messages = [],
utils = require('express/utils')
utils = require('express/utils'),
http = require('express/http')
configure(function(){
use(Logger)
use(MethodOverride)
use(ContentLength)
use(Cookie)
use(Cache, { lifetime: (5).minutes, reapInterval: (1).minute })
use(Session, { lifetime: (15).minutes, reapInterval: (1).minute })
use(Logger)
use(Static)
set('root', __dirname)
})
get('/', function(){
get('/', function(){
this.pass('/chat')
})
get('/chat', function(){
this.render('chat.haml.html', {
locals: {
title: 'Chat',
messages: messages,
name: this.session.name,
usersOnline: Session.store.length()
}
var self = this
Session.store.length(function(err, len){
self.render('chat.html.haml', {
locals: {
title: 'Chat',
messages: messages,
name: self.session.name,
usersOnline: len
}
})
})
})
@@ -37,7 +42,7 @@ post('/chat', function(){
.push(utils.escape(this.param('name')) + ': ' + utils.escape(this.param('message'))
.replace(/(http:\/\/[^\s]+)/g, '<a href="$1" target="express-chat">$1</a>')
.replace(/:\)/g, '<img src="http://icons3.iconfinder.netdna-cdn.com/data/icons/ledicons/emoticon_smile.png">'))
this.halt(200)
this.respond(200)
})
get('/chat/messages', function(){
@@ -47,17 +52,13 @@ get('/chat/messages', function(){
if (messages.length > previousLength)
self.contentType('json'),
previousLength = messages.length,
self.halt(200, JSON.encode(messages)),
self.respond(200, JSON.encode(messages)),
clearInterval(timer)
}, 100)
})
get('/public/*', function(file){
this.sendfile(__dirname + '/public/' + file)
})
get('/*.css', function(file){
this.render(file + '.sass.css', { layout: false })
this.render(file + '.css.sass', { layout: false })
})
get('/error/view', function(){
@@ -73,7 +74,7 @@ get('/simple', function(){
})
get('/favicon.ico', function(){
this.halt()
this.notFound()
})
run()
@@ -1,8 +1,7 @@
%h1 Chat
%img.bubble{ src: '/public/images/bubble.png' }
%ul#messages
:each msg in messages
%li= msg
!= this.partial('message.html.haml', { collection: messages })
%form{ method: 'post' }
%input{ type: 'hidden', name: '_method', value: 'put' }
%input{ type: 'text', name: 'name', value: name || 'guest' }
@@ -5,7 +5,8 @@
%script{ src: '/public/javascripts/app.js' }
%link{ rel: 'stylesheet', href: '/style.css' }
%body
#wrapper= body
#online
#wrapper
!= body
#online
Online:
%strong= usersOnline
@@ -0,0 +1 @@
%li= message
+38
Ver Arquivo
@@ -0,0 +1,38 @@
require.paths.unshift 'lib'
require 'express'
require 'express/plugins'
sys: require 'sys'
configure ->
use MethodOverride
use ContentLength
use Cookie
use Session
use Flash
use Logger
use Static
set 'root', __dirname
set 'views', __dirname + '/../upload/views'
get '/', ->
@redirect('/upload')
get '/upload', ->
@render 'upload.html.haml', {
locals: {
flashes: @flash 'info'
}
}
post '/upload', ->
@param('images').each (image) =>
sys.puts image.filename + ' -> ' + image.tempfile
@flash 'info', 'Uploaded ' + image.filename
@redirect '/upload'
get '/*.css', (file) ->
@render file + '.css.sass', { layout: no }
run()
Diff do arquivo suprimido porque uma ou mais linhas são muito longas
+19
Ver Arquivo
@@ -0,0 +1,19 @@
require.paths.unshift('lib')
require('express')
configure(function(){
set('root', __dirname)
})
get('/', function(){
this.render('front.html.ejs', {
locals: {
title: 'Hello World',
name: 'Joe',
items: ['one', 'two', 'three']
}
})
})
run()
+9
Ver Arquivo
@@ -0,0 +1,9 @@
<h1><%= title %></h1>
<%= this.partial("greeting.html.ejs", { locals: { name: name } }) %>
<% if (items && items.length) { %>
<ul>
<% for (var i = 0; i < items.length; ++i) { %>
<li><%= items[i] %></li>
<% } %>
</ul>
<% } %>
+8
Ver Arquivo
@@ -0,0 +1,8 @@
<html>
<head>
<title><%= title %></title>
</head>
<body>
<%= body %>
</body>
</html>
@@ -0,0 +1 @@
Welcome back, <strong><%= name %></strong>!
+7 -7
Ver Arquivo
@@ -3,6 +3,8 @@ require.paths.unshift('lib')
require('express')
require('express/plugins')
var sys = require('sys')
configure(function(){
use(MethodOverride)
use(ContentLength)
@@ -10,7 +12,9 @@ configure(function(){
use(Session)
use(Flash)
use(Logger)
use(Static)
set('root', __dirname)
set('max upload size', (5).megabytes)
})
get('/', function(){
@@ -18,7 +22,7 @@ get('/', function(){
})
get('/upload', function(){
this.render('upload.haml.html', {
this.render('upload.html.haml', {
locals: {
flashes: this.flash('info')
}
@@ -27,18 +31,14 @@ get('/upload', function(){
post('/upload', function(){
this.param('images').each(function(image){
puts(image.filename + ' -> ' + image.tempfile)
sys.puts(image.filename + ' -> ' + image.tempfile)
this.flash('info', 'Uploaded ' + image.filename)
}, this)
this.redirect('/upload')
})
get('/public/*', function(file){
this.sendfile(__dirname + '/public/' + file)
})
get('/*.css', function(file){
this.render(file + '.sass.css', { layout: false })
this.render(file + '.css.sass', { layout: false })
})
run()
@@ -2,13 +2,12 @@
%head
%title Upload
%script{ src: '/public/javascripts/jquery.js' }
%script{ src: '/public/javascripts/app.js' }
%link{ rel: 'stylesheet', href: '/style.css' }
%body
#wrapper
%h1 Upload
:if flashes
- if (flashes)
%ul.messages.info
:each msg in flashes
- each msg in flashes
%li= msg
.body= body
.body!= body
@@ -1,18 +1,17 @@
:if typeof images !== 'undefined'
- if (typeof images !== 'undefined')
.images
:each img in images
- each img in images
%img{ src: img }
%h2 Singles
%form{ method: 'post', enctype: 'multipart/form-data' }
%input{ type: 'file', name: 'images[0]' }
%input{ type: 'file', name: 'images[1]' }
%input{ type: 'file', name: 'images[2]' }
.panel
%div.panel
%input{ type: 'submit', value: 'Upload' }
%h2 Multiple
%form{ method: 'post', enctype: 'multipart/form-data' }
%input{ type: 'file', name: 'images[]', multiple: 'multiple' }
.panel
%div.panel
%input{ type: 'submit', value: 'Upload' }
+3 -1
Ver Arquivo
@@ -1,7 +1,9 @@
require.paths.unshift(__dirname + '/support/ext/lib')
require.paths.unshift(__dirname + '/support/ejs/lib')
require.paths.unshift(__dirname + '/support/haml/lib')
require.paths.unshift(__dirname + '/support/sass/lib')
require.paths.unshift(__dirname + '/support/multipart/lib')
require('ext')
require('support/oo/lib/oo')
Class = require('support/class/lib/class').Class
require('express/core')
+71 -90
Ver Arquivo
@@ -5,24 +5,24 @@
* Module dependencies.
*/
var multipart = require('multipart'),
var Request = require('express/request').Request,
normalizePath = require('express/request').normalizePath,
multipart = require('old'),
utils = require('express/utils'),
events = require('events'),
http = require('http'),
sys = require('sys'),
fs = require('fs')
global.merge(require('sys'))
global.merge(require('express/event'))
global.merge(require('express/request'))
global.merge(require('express/plugin'))
global.merge(require('express/dsl'))
Object.merge(global, require('express/plugin'))
Object.merge(global, require('express/dsl'))
// --- Route
Route = Class({
Route = new Class({
/**
* Initialize a route with the given _method_,
* _path_, and callback _fn_.
* _path_, and _callback_.
*
* The given _path_ becomes #originalPath,
* #path is then a normalized version converted
@@ -30,16 +30,16 @@ Route = Class({
*
* @param {string} method
* @param {string} path
* @param {function} fn
* @param {function} callback
* @param {hash} options
* @api private
*/
init: function(method, path, fn, options){
constructor: function(method, path, callback, options){
this.method = method
this.originalPath = path
this.path = this.normalize(path)
this.fn = fn
this.callback = callback
},
/**
@@ -84,7 +84,7 @@ Route = Class({
// --- Router
Router = Class({
Router = new Class({
/**
* Initialize with _request_ and parse url.
@@ -93,8 +93,9 @@ Router = Class({
* @api private
*/
init: function(request) {
constructor: function(request) {
this.request = request
this.method = request.method.lowercase
},
/**
@@ -108,7 +109,7 @@ Router = Class({
var body,
route = this.matchingRoute()
if (route) {
body = route.fn.apply(this.request, this.request.captures.slice(1));
body = route.callback.apply(this.request, this.request.captures.slice(1));
if (this.request.passed) {
if (typeof this.request.passed === 'string')
this.request.url.pathname = this.request.passed
@@ -117,10 +118,8 @@ Router = Class({
}
return body
}
else if (this.request.accepts('html') && set('helpful 404'))
this.request.halt(404, require('express/pages/not-found').render(this.request))
else
this.request.halt()
this.request.notFound()
},
/**
@@ -149,7 +148,7 @@ Router = Class({
*/
match: function(route) {
if (this.request.method.toLowerCase() == route.method)
if (this.method === route.method)
if (this.request.captures = this.request.url.pathname.match(route.path)) {
this.mapParams(route)
return true
@@ -166,14 +165,18 @@ Router = Class({
mapParams: function(route) {
route.keys.each(function(key, i){
this.request.params.path[key] = this.request.captures[++i]
var val = this.request.captures[++i]
if (key in Express.params)
if ((val = Express.params[key].call(this.request, val)) === false)
this.request.passed = true
this.request.params.path[key] = this.request.captures[i] = val
}, this)
}
})
// --- Server
Server = Class({
Server = new Class({
/**
* Default port number.
@@ -186,67 +189,63 @@ Server = Class({
* all network addresses.
*/
host: 'localhost',
host: null,
/**
* Maximum number of queued connections.
*/
backlog: 128,
/**
* Run Express.
*
* - Buffers request bodies
* - Calls #route() once the request is complete
* Run Express with optional _port_ defaulting to 3000,
* and host defaulting to null (INADDR_ANY).
*
* @param {int} port
* @param {string} host
* @param {int} backlog
* @return {Server}
* @see run()
* @api private
*/
run: function(port, host, backlog){
run: function(port, host){
var self = this
this.running = true
if (host !== undefined) this.host = host
if (port !== undefined) this.port = port
if (backlog !== undefined) this.backlog = backlog
require('http')
.createServer(function(request, response){
var server = http
.createServer(function(req, response){
var request, pendingFiles = 0
req.setEncoding('binary')
request = new Request(req, response)
request.body = ''
request.setBodyEncoding('binary')
function callback(e, result) {
if (e)
self.error(e, request, response)
function callback(err) {
if (err)
request.error(err)
else if (!pendingFiles)
self.route(request, response)
self.route(request)
}
if (request.headers['content-type'] &&
request.headers['content-type'].includes('multipart/form-data')) {
var stream = multipart.parse(request),
pendingFiles = 0
request.params = { post: {}}
if (request.header('Content-Type') &&
request.header('Content-Type').includes('multipart/form-data')) {
var stream,
contentLength = parseInt(request.header('Content-Length')),
maxBodyLength = set('max upload size')
if (maxBodyLength && contentLength > maxBodyLength)
return callback(new Error('upload size limit exceeded'))
stream = multipart.parse(req)
stream
.addListener('partBegin', function(part) {
.addListener('partBegin', function(part) {
if (part.filename)
++pendingFiles,
part.tempfile = '/tmp/express-' + Number(new Date) + utils.uid(),
part.fileStream = fs.createWriteStream(part.tempfile)
part.tempfile = '/tmp/express-' + Date.now() + utils.uid(),
part.fileStream = fs.createWriteStream(part.tempfile),
part.fileStream.addListener('error', callback)
else
part.buf = ''
})
.addListener('body', function(chunk) {
if (stream.part.fileStream)
stream.part.fileStream.write(chunk)
stream.part.fileStream.write(chunk, 'binary')
else
stream.part.buf += chunk
})
.addListener('partEnd', function(part) {
if (!part.name) return
if (part.fileStream)
part.fileStream.close(function(){
part.fileStream.end(function(){
--pendingFiles
callback()
}),
@@ -258,67 +257,46 @@ Server = Class({
.addListener('complete', callback)
}
else
request
req
.addListener('data', function(chunk){ request.body += chunk })
.addListener('end', callback)
})
.listen(this.port, this.host, this.backlog)
puts('Express started at http://' + this.host + ':' + this.port + '/ in ' + Express.environment + ' mode')
server.listen(this.port, this.host)
sys.puts('Express started at http://' + (this.host || '*') + ':' + this.port + '/ in ' + Express.environment + ' mode')
return server
},
/**
* Route the given _request_ and _response_.
* Route the given _request_.
*
* @param {object} request
* @param {object} response
* @param {Request} request
* @api private
*/
route: function(request, response){
var self = this,
request = new Request(request, response)
request.trigger('request', function(e) {
try {
if (e) throw e
route: function(request){
var self = this
request.trigger('request', function(err) {
try {
if (err) throw err
if (request.response.finished) return
if (typeof (body = (new Router(request)).route()) === 'string')
request.halt(200, body)
} catch (e) {
self.error(e, request)
request.respond(200, body)
} catch (err) {
request.error(err)
}
})
},
/**
* Handle errors.
*
* @param {Error} e
* @param {object} request
* @param {object} response
* @api private
*/
error: function (e, request, response) {
if (!(request instanceof Request))
request = new Request(request, response),
request.trigger('request')
if (request.accepts('html') && set('show exceptions'))
request.halt(500, require('express/pages/show-exceptions').render(request, e))
else
request.halt(500)
if (set('throw exceptions'))
throw e
}
})
// --- Express
Express = {
version: '0.7.3',
version: '0.13.0',
config: [],
routes: [],
plugins: [],
settings: {},
params: {},
server: new Server
}
@@ -334,13 +312,16 @@ configure(function(){
configure('development', function(){
enable('helpful 404')
enable('show exceptions')
enable('dump exceptions')
})
configure('test', function(){
enable('throw exceptions')
disable('dump exceptions')
})
configure('production', function(){
enable('cache view contents')
enable('cache view partials')
enable('cache static files')
})
+49 -14
Ver Arquivo
@@ -10,13 +10,10 @@
*/
function route(method) {
return function(path, options, fn){
return function(path, options, callback){
if (options instanceof Function)
fn = options, options = {}
if (!Express.server.running)
Express.routes.push(new Route(method, path, fn, options))
else
throw new Error('cannot create route ' + method.toUpperCase() + " `" + path + "' at runtime")
callback = options, options = {}
Express.routes.push(new Route(method, path, callback, options))
}
}
@@ -76,11 +73,11 @@ exports.run = function() {
if ('init' in plugin.klass)
plugin.klass.init(plugin.options)
})
Express.server.run.apply(Express.server, arguments)
return Express.server.run.apply(Express.server, arguments)
}
/**
* Configure _env_ with _fn_.
* Configure _env_ with _callback_.
*
* Global configuration, disregards which
* environment is active:
@@ -100,17 +97,17 @@ exports.run = function() {
* configure('development')
*
* @param {string, function} env
* @param {function} fn
* @param {function} callback
* @api public
*/
exports.configure = function(env, fn) {
exports.configure = function(env, callback) {
if (env instanceof Function)
fn = env, env = 'all'
if (fn instanceof Function)
return Express.config.push([env, fn])
callback = env, env = 'all'
if (callback instanceof Function)
return Express.config.push([env, callback])
if (typeof env !== 'string')
throw new Error('environment required')
throw new TypeError('environment required')
Express.config.each(function(conf){
if (conf[0] === env ||
conf[0] === 'all')
@@ -118,6 +115,44 @@ exports.configure = function(env, fn) {
})
}
/**
* Pre-process param _key_ with _callback_.
*
* @param {string} key
* @param {function} callback
* @api public
*/
exports.param = function(key, callback) {
if (typeof key !== 'string')
throw new TypeError('param key must be a string')
if (typeof callback !== 'function')
throw new TypeError('param must pass a function to process "' + key + '"')
Express.params[key] = callback
}
/**
* Register a "Not Found" route with the given _callback_.
*
* @param {function} callback
* @api public
*/
exports.notFound = function(callback) {
Express.notFound = callback
}
/**
* Register an "error" route with the given _callback_.
*
* @param {function} callback
* @api public
*/
exports.error = function(callback) {
Express.error = callback
}
// --- Routing API
exports.get = exports.view = route('get')
+3 -3
Ver Arquivo
@@ -1,7 +1,7 @@
// Express - Event - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
exports.Event = Class({
exports.Event = new Class({
/**
* Initialize with event _name_ and optional _data_.
@@ -11,9 +11,9 @@ exports.Event = Class({
* @api private
*/
init: function(name, data) {
constructor: function(name, data) {
this.name = name
this.merge(data || {})
Object.merge(this, data)
},
/**
+46 -25
Ver Arquivo
@@ -6,7 +6,6 @@
*/
var http = require('http'),
utils = require('express/utils'),
parse = require('url').parse,
queryString = require('querystring')
@@ -17,51 +16,54 @@ var http = require('http'),
* @param {string} url
* @param {hash} data
* @param {hash} headers
* @param {function} fn
* @param {function} callback
* @param {number} redirects
* @api private
*/
function request(method, url, data, headers, fn, redirects) {
function request(method, url, data, headers, callback, redirects, first) {
var buf = '',
redirects = redirects || 3,
redirects = typeof redirects !== 'number' ? 3 : redirects,
url = parse(url),
path = url.pathname || '/',
search = url.search || '',
hash = url.hash || '',
port = url.port || 80,
headers = { host: url.hostname }.merge(headers || {}),
headers = Object.merge(headers || {}, { Host: url.hostname }),
client = http.createClient(port, url.hostname)
if (headers.redirect)
redirects = headers.redirect,
delete headers.redirect
if (data) {
data = queryString.stringify(data)
if (typeof data === 'object' && 'redirects' in data)
redirects = data.redirects,
delete data.redirects
if (first && data) {
if (typeof data !== 'string')
data = queryString.stringify(data)
if (method === 'GET')
search += (search ? '&' : '?') + data
else
headers['content-length'] = data.length,
headers['content-type'] = 'application/x-www-form-urlencoded'
else {
if (!headers['Content-Length'])
headers['Content-Length'] = data.length
if (!headers['Content-Type'])
headers['Content-Type'] = 'application/x-www-form-urlencoded'
}
}
var req = client.request(method, path + search + hash, headers)
if (data && method !== 'GET') req.write(data)
req.addListener('response', function(res){
if (req.statusCode < 200 || req.statusCode >= 400)
fn(new Error('request failed with status ' + res.statusCode + ' "' + http.STATUS_CODES[res.statusCode] + '"'))
if (res.statusCode < 200 || res.statusCode >= 400)
callback(new Error('request failed with status ' + res.statusCode + ' "' + http.STATUS_CODES[res.statusCode] + '"'), '', res)
else if (res.statusCode >= 300 && res.statusCode < 400)
if (--redirects)
request(method, res.headers.location, headers, data, fn, redirects)
if (redirects--)
request(method, res.headers.location, data, headers, callback, redirects, false)
else
fn(new Error('maximum number of redirects reached'))
callback(new Error('maximum number of redirects reached'), '', res)
else {
res.setBodyEncoding('utf8')
res
.addListener('data', function(chunk){ buf += chunk })
.addListener('end', function(){ fn(null, buf, res) })
.addListener('end', function(){ callback(null, buf, res) })
}
})
req.close()
req.end()
}
/**
@@ -74,20 +76,39 @@ function request(method, url, data, headers, fn, redirects) {
function client(method) {
return function() {
var headers, data,
var redirects,
args = Array.prototype.slice.call(arguments),
url = args.shift(),
fn = args.pop(),
callback = args.pop(),
data = args.shift(),
headers = args.shift()
if (typeof fn !== 'function')
if (typeof callback !== 'function')
throw new TypeError('http client requires a callback function')
return request(method.toUpperCase(), url, data, headers, fn)
return request(method.toUpperCase(), url, data, headers, callback, redirects, true)
}
}
// --- Public API
/**
* Examples:
*
* var http = require('express/http')
*
* http.get('http://google.com/search', { q: 'foobar' }, function(err, body, response){
* if (!err) sys.puts(body)
* })
*
* http.get('http://google.com/search?lang=en', { q: 'foobar' }, function(){
* // ...
* })
*
* http.post('http://localhost:8000', '<user>tj</user>', { 'Content-Type': 'text/xml' }, function(err, body){
* // ...
* })
*
*/
exports.get = exports.view = client('get')
exports.post = exports.create = client('post')
exports.put = exports.update = client('put')
-1
Ver Arquivo
@@ -352,7 +352,6 @@ exports.types = {
*
* var mime = require('express/mime')
* mime.type('png') // => 'image/png'
* mime.type('.png') // => 'image/png'
* mime.type('image.png') // => 'image/png'
* mime.type('path/to/image.png') // => 'image/png'
*
+1
Ver Arquivo
@@ -4,6 +4,7 @@
var style = require('express/pages/style').style
exports.render = function(request) {
request.charset = 'UTF-8'
request.contentType('html')
var method = request.method.toLowerCase(),
path = request.url.pathname || '/'
+68 -8
Ver Arquivo
@@ -1,12 +1,18 @@
// Express - Pages - Show Exceptions - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
var style = require('express/pages/style').style
/**
* Module dependencies.
*/
var sys = require('sys'),
style = require('express/pages/style').style
/**
* Return list items for exception _e_'s stack.
*
* @param {object} e
* @param {Error} e
* @return {string}
* @api private
*/
@@ -26,19 +32,54 @@ function stack(e) {
/**
* Return table rows for _hash_.
*
* @param {hash} hash
* @param {object} hash
* @return {string}
* @api private
*/
function hash(hash) {
if (!hash || !hash.values.length) return '<tr><td class="empty" colspan="2">Empty</td></tr>'
return hash.map(function(val, key){
return '<tr><td>' + key + ':</td><td>' + JSON.encode(val) + '</td></tr>'
}).join('\n')
var keys = Object.keys(hash),
buf = []
if (!keys.length) return '<tr><td class="empty" colspan="2">Empty</td></tr>'
for (var i = 0, len = keys.length; i < len; ++i)
buf.push('<tr><td>' + keys[i] + ':</td><td>' + sys.inspect(hash[keys[i]]) + '</td></tr>')
return buf.join('\n')
}
/**
* Return plain-text list items for exception _e_'s stack.
*
* @param {Error} e
* @return {string}
* @api private
*/
function stackText(e) {
if (e.stack)
return e.stack.split('\n').slice(1).map(function(val, i){
return '\n ' + val.strip
}).join('')
}
/**
* Return an ascii table for _hash_.
*
* @param {object} hash
* @return {string}
* @api private
*/
function hashText(hash) {
var keys = Object.keys(hash),
buf = ''
if (!keys.length) return '\n Empty'
for (var i = 0, len = keys.length; i < len; ++i)
buf += '\n ' + keys[i] + ': ' + sys.inspect(hash[keys[i]])
return buf
}
exports.render = function(request, e) {
request.charset = 'UTF-8'
request.contentType('html')
return '<html> \n\
<head> \n\
@@ -75,4 +116,23 @@ exports.render = function(request, e) {
</div> \n\
</body> \n\
</html>'
}
}
exports.renderText = function(request, e) {
request.contentType('text')
return '\
\n Express \
\n\n 500 ' + e + ' \
\n' + stackText(e) + ' \
\n\n Request\n ' + hashText(request.headers) + '\
\n\n Response\n ' + hashText(request.response.headers) + '\
\n\n Params\n ' + hashText(request.params.path) + '\
\n\n GET\n ' + hashText(request.params.get) + '\
\n\n POST\n ' + hashText(request.params.post) + '\n'
}
exports.renderJSON = function(request, e) {
request.contentType('json')
delete e.stack
return JSON.encode({ error: e })
}
+1 -19
Ver Arquivo
@@ -1,12 +1,6 @@
// Express - Plugin - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var utils = require('express/utils');
/**
* Push _plugin_ with _options_ to the plugin stack.
* If _plugin_ has already been pushed, then it's options
@@ -32,19 +26,7 @@ exports.use = function(plugin, options) {
// --- Plugin
exports.Plugin = Class({
/**
* Initialize with _options_.
*
* @param {hash} options
* @api private
*/
init: function(options) {
if (options)
utils.mixin(this, options)
},
exports.Plugin = new Class({
/**
* Trigger handler for the given _event_.
+9 -8
Ver Arquivo
@@ -1,11 +1,12 @@
// Express - Plugins - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
global.merge(require('express/plugins/hooks'))
global.merge(require('express/plugins/flash'))
global.merge(require('express/plugins/cache'))
global.merge(require('express/plugins/cookie'))
global.merge(require('express/plugins/session'))
global.merge(require('express/plugins/logger'))
global.merge(require('express/plugins/content-length'))
global.merge(require('express/plugins/method-override'))
Object.merge(global, require('express/plugins/hooks'))
Object.merge(global, require('express/plugins/static'))
Object.merge(global, require('express/plugins/flash'))
Object.merge(global, require('express/plugins/cache'))
Object.merge(global, require('express/plugins/cookie'))
Object.merge(global, require('express/plugins/session'))
Object.merge(global, require('express/plugins/logger'))
Object.merge(global, require('express/plugins/content-length'))
Object.merge(global, require('express/plugins/method-override'))
+2 -2
Ver Arquivo
@@ -20,8 +20,8 @@ exports.BodyDecoder = Plugin.extend({
request: function(event) {
var request = event.request
if (request.header('content-type') &&
request.header('content-type').includes('application/x-www-form-urlencoded'))
if (request.header('Content-Type') &&
request.header('Content-Type').includes('application/x-www-form-urlencoded'))
request.params.post = queryString.parseQuery(request.body)
}
}
+61 -47
Ver Arquivo
@@ -1,24 +1,30 @@
// Express - Cache - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request
// --- Cache
var Cache = Class({
var Cache = new Class({
/**
* Initialize cache with _key_ and _val_.
*/
init: function(key, val) {
constructor: function(key, val) {
this.key = key
this.val = val
this.created = Number(new Date)
this.created = Date.now()
}
})
// --- Store
exports.Store = Class({
exports.Store = new Class({
/**
* Ensure that the given _key_ is a string.
@@ -26,10 +32,11 @@ exports.Store = Class({
*
* @param {string} key
* @param {string} val
* @param {function} callback
* @api public
*/
set: function(key, val) {
set: function(key, val, callback) {
if (typeof key !== 'string')
throw new Error(this.name + ' store #set() key must be a string')
},
@@ -39,10 +46,11 @@ exports.Store = Class({
* Override in subclass to provide data-store specific functionality.
*
* @param {string} key
* @param {function} callback
* @api public
*/
get: function(key) {
get: function(key, callback) {
if (typeof key !== 'string')
throw new Error(this.name + 'store #get() key must be a string')
},
@@ -73,22 +81,24 @@ exports.Store.Memory = exports.Store.extend({
* Initialize data.
*/
init: function() {
constructor: function() {
this.data = {}
},
/**
* Set the given _key_ to _val_, returning _val_.
* Set the given _key_ to _val_.
*
* @param {string} key
* @param {string} val
* @param {function} callback
* @return {string}
* @api public
*/
set: function(key, val) {
this.__super__(key, val)
return this.data[key] = new Cache(key, val), val
set: function(key, val, callback) {
exports.Store.prototype.set.apply(this, arguments)
this.data[key] = new Cache(key, val)
if (callback) callback(val)
},
/**
@@ -96,31 +106,33 @@ exports.Store.Memory = exports.Store.extend({
*
* Examples:
*
* cache.get('page:front')
* cache.get('page:front', function(val){})
* // => '<html>...</html>'
*
* cache.get('page:*')
* cache.get('page:*', function(vals){})
* // => { 'page:front': '<html>...</html>',
* 'page:users': '<html>...</html>',
* ... }
*
* @param {string} key
* @param {function} callback
* @return {mixed}
* @api public
*/
get: function(key) {
this.__super__(key)
get: function(key, callback) {
exports.Store.prototype.get.apply(this, arguments)
if (key.indexOf('*') === -1)
return this.data[key] instanceof Cache ?
this.data[key].val :
null
var regexp = this.normalize(key)
return this.data.reduce(function(vals, cache){
if (regexp.test(cache.key))
vals[cache.key] = cache.val
return vals
}, {})
return callback(this.data[key] instanceof Cache
? this.data[key].val
: null)
var regexp = this.normalize(key),
keys = Object.keys(this.data),
matches = {}
for (var i = 0, len = keys.length; i < len; ++i)
if (regexp.test(keys[i]))
matches[keys[i]] = this.data[keys[i]].val
callback(matches)
},
/**
@@ -128,37 +140,42 @@ exports.Store.Memory = exports.Store.extend({
*
* Examples:
*
* cache.clear('page:front')
* cache.clear('page:*')
* cache.clear('page:front', function(){})
* cache.clear('page:*', function(){})
*
* @param {string} key
* @param {function} callback
* @api public
*/
clear: function(key) {
clear: function(key, callback) {
if (key.indexOf('*') === -1)
return delete this.data[key]
var regexp = this.normalize(key)
for (var key in this.data)
if (this.data.hasOwnProperty(key))
if (regexp.test(key))
delete this.data[key]
delete this.data[key]
else {
var regexp = this.normalize(key),
keys = Object.keys(this.data)
for (var i = 0, len = keys.length; i < len; ++i)
if (regexp.test(keys[i]))
delete this.data[keys[i]]
}
callback()
},
/**
* Reap caches older than _ms_.
* Reap caches older than _ms_ or caches which
* have been "cleared" (null).
*
* @param {int} ms
* @api private
*/
reap: function(ms) {
var self = this,
threshold = Number(new Date(Number(new Date) - ms))
this.data.each(function(cache){
if (cache.created < threshold)
self.clear(cache.key)
})
var threshold = +new Date(Date.now() - ms),
keys = Object.keys(this.data)
for (var i = 0, len = keys.length; i < len; ++i)
if (this.data[keys[i]].created < threshold ||
this.data[keys[i]].val === null)
this.clear(keys[i], function(){})
},
/**
@@ -196,7 +213,7 @@ exports.Cache = Plugin.extend({
*/
init: function(options) {
this.merge(options || {})
Object.merge(this, options)
this.store = new (this.dataStore || exports.Store.Memory)(options)
Request.include({ cache: this.store })
this.startReaper()
@@ -209,12 +226,9 @@ exports.Cache = Plugin.extend({
*/
startReaper: function() {
var self = this,
oneDay = 86400000,
oneHour = 3600000
setInterval(function(){
self.store.reap(self.lifetime || oneDay)
}, self.reapInterval || self.reapEvery || oneHour)
setInterval(function(self){
self.store.reap(self.lifetime || (1).day)
}, this.reapInterval || this.reapEvery || (1).hour, this)
}
}
})
+3 -3
Ver Arquivo
@@ -10,9 +10,9 @@ exports.ContentLength = Plugin.extend({
response: function(event) {
var response = event.request.response
response.headers['content-length'] =
response.headers['content-length'] ||
response.body.length
if (!response.chunkedEncoding)
if (!response.headers['Content-Length'] && response.body)
response.headers['Content-Length'] = response.body.length
}
}
})
+43 -19
Ver Arquivo
@@ -1,6 +1,13 @@
// Express - Cookie - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request,
queryString = require('querystring')
/**
* Parse an HTTP _cookie_ string into a hash.
*
@@ -10,10 +17,18 @@
*/
exports.parseCookie = function(cookie) {
return cookie.replace(/^ *| *$/g, '').split(/ *; */).reduce(function(hash, pair){
var parts = pair.split(/ *= */)
hash[parts[0]] = parts[1]
return hash
return cookie.split(/[;,] */).reduce(function(cookies, pair) {
var eql = pair.indexOf('=')
if (eql === -1) return cookies
var key = queryString.unescape(pair.slice(0, eql).trim(), true)
var val = queryString.unescape(pair.slice(eql + 1).trim(), true)
var captures = val.match(/^("|')([^\1]*)\1$/)
if (captures) val = captures[2].replace('\\' + captures[1], captures[1])
//RFC2109 states the most specific path will be
//listed first
if (cookies[key] === undefined)
cookies[key] = val
return cookies
}, {})
}
@@ -29,14 +44,18 @@ exports.parseCookie = function(cookie) {
exports.compileCookie = function(name, val, options) {
if (!options) return name + '=' + val
return name + '=' + val + '; ' + options.map(function(val, key){
var val,
buf = [queryString.escape(name) + '=' + queryString.escape(val)],
keys = Object.keys(options)
for (var i = 0, len = keys.length; i < len; ++i) {
val = options[keys[i]]
if (val instanceof Date)
val = val.toString()
.replace(/^(\w+)/, '$1,')
.replace(/(\w+) (\d+) (\d+)/, '$2-$1-$3')
.replace(/GMT.*$/, 'GMT')
return val === true ? key : key + '=' + val
}).join('; ')
val = val.toGMTString()
buf.push(val === true
? keys[i]
: keys[i] + '=' + val)
}
return buf.join('; ')
}
// --- Cookie
@@ -52,7 +71,8 @@ exports.Cookie = Plugin.extend({
Request.include({
/**
* Get or set cookie values.
* Get or set cookie values. To delete a cookie
* simply pass a null _val_.
*
* Options:
*
@@ -75,10 +95,13 @@ exports.Cookie = Plugin.extend({
cookie: function(name, val, options) {
options = options || {}
options.path = options.path || '/'
return val ?
this.response.cookies.push(exports.compileCookie(name, val, options)) :
this.cookies[name]
}
if (null === val)
val = "delete",
options.expires = new Date(10000000)
return val
? this.response.cookies.push(exports.compileCookie(name, val, options))
: this.cookies[name]
}
})
}
},
@@ -103,8 +126,9 @@ exports.Cookie = Plugin.extend({
*/
response: function(event) {
if (event.response.cookies.length)
event.request.header('set-cookie', event.response.cookies.join(', '))
if (event.response.cookies &&
event.response.cookies.length)
event.request.header('Set-Cookie', event.response.cookies.join('\r\nSet-Cookie: '))
}
}
})
})
+17 -1
Ver Arquivo
@@ -1,6 +1,14 @@
// Express - Flash - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request
// --- Flash
exports.Flash = Plugin.extend({
extend: {
@@ -18,6 +26,9 @@ exports.Flash = Plugin.extend({
* it will persist in the session until outputted.
* The _val_ pushed is returned.
*
* When no arguments are given, all flashes are
* returned keyed by their type.
*
* Example:
*
* this.flash('info', 'email sent')
@@ -30,12 +41,17 @@ exports.Flash = Plugin.extend({
*
* @param {string} key
* @param {string} val
* @return {string}
* @return {mixed}
* @api public
*/
flash: function(key, val) {
if (!this.session.flash) this.session.flash = {}
if (!key) {
var flashes = this.session.flash
this.session.flash = {}
return flashes
}
if (!(key in this.session.flash)) this.session.flash[key] = []
if (val)
return this.session.flash[key].push(val), val
+13 -13
Ver Arquivo
@@ -8,25 +8,25 @@
exports.callbacks = { before: [], after: [] }
/**
* Add a _fn_ to be excuted before a request.
* Add a _callback_ to be excuted before a request.
*
* @param {function} fn
* @param {function} callback
* @api public
*/
exports.before = function(fn) {
exports.callbacks.before.push(fn)
exports.before = function(callback) {
exports.callbacks.before.push(callback)
}
/**
* Add a _fn_ to be excuted after a request.
* Add a _callback_ to be excuted after a request.
*
* @param {function} fn
* @param {function} callback
* @api public
*/
exports.after = function(fn) {
exports.callbacks.after.push(fn)
exports.after = function(callback) {
exports.callbacks.after.push(callback)
}
// --- Hooks
@@ -39,7 +39,7 @@ exports.Hooks = Plugin.extend({
*/
init: function() {
global.merge({
Object.merge(global, {
before: exports.before,
after: exports.after
})
@@ -55,8 +55,8 @@ exports.Hooks = Plugin.extend({
*/
request: function(event) {
exports.callbacks.before.each(function(fn){
fn.call(event.request, event.request)
exports.callbacks.before.each(function(callback){
callback.call(event.request, event.request)
})
},
@@ -65,8 +65,8 @@ exports.Hooks = Plugin.extend({
*/
response: function(event) {
exports.callbacks.after.each(function(fn){
fn.call(event.request, event.request)
exports.callbacks.after.each(function(callback){
callback.call(event.request, event.request)
})
}
}
+16 -13
Ver Arquivo
@@ -5,7 +5,8 @@
* Module dependencies.
*/
var sys = require('sys')
var sys = require('sys'),
printf = require('ext').printf
/**
* Log formats
@@ -13,24 +14,25 @@ var sys = require('sys')
var formats = {
common: function(event, start) {
printf('%s - - [%s] "%s %s HTTP/%d" %s %d %0.3f',
event.request.connection.remoteAddress,
printf('%s - - [%s] "%s %s HTTP/%d.%d" %s %d %0.4f',
event.request.socket.remoteAddress,
(new Date).format('%d/%b/%Y %H:%M:%S'),
event.request.method.uppercase,
event.request.url.pathname || '/',
event.request.httpVersion,
event.request.httpVersionMajor,
event.request.httpVersionMinor,
event.request.response.status,
event.request.response.headers['content-length'] || 0,
(Number(new Date) - start) / 1000)
event.request.response.headers['Content-Length'] || 0,
(Date.now() - start) / 1000)
},
combined: function(event, start) {
formats.common(event, start)
printf('"%s" "%s"',
printf(' "%s" "%s"',
event.request.headers['referrer'] || event.request.headers['referer'] || '-',
event.request.headers['user-agent'])
},
plot: function(event, start) {
sys.print(Number(new Date) - start)
sys.print(Date.now() - start)
}
}
@@ -45,16 +47,17 @@ exports.Logger = Plugin.extend({
* Options:
*
* - format
* 'common' outputs log in CommonLog format (DEFAULT)
* 'common' outputs log in CommonLog format (DEFAULT)
* 'combined' outputs log in Apache Combined format
* 'plot' outputs request duration in milliseconds only
* 'request' outputs the HTTP request for debugging
* 'plot' outputs request duration in milliseconds only
*
* @param {hash} options
* @api private
*/
init: function(options) {
this.merge(options || {})
Object.merge(this, options)
}
},
@@ -65,7 +68,7 @@ exports.Logger = Plugin.extend({
*/
request: function(event) {
this.start = Number(new Date)
this.start = Date.now()
},
/**
@@ -73,7 +76,7 @@ exports.Logger = Plugin.extend({
*/
response: function(event) {
formats[exports.Logger.format || 'common'](event, this.start)
formats[exports.Logger.format || 'common'](event, this.start || Date.now())
sys.print('\n')
}
}
+11 -3
Ver Arquivo
@@ -1,6 +1,14 @@
// Express - Redirect - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request
// --- Redirect
exports.Redirect = Plugin.extend({
extend: {
@@ -33,8 +41,8 @@ exports.Redirect = Plugin.extend({
redirect: function(url, code) {
if (url === 'back' || url === 'home') url = this[url]
this.header('location', url)
this.halt(code || 303)
this.header('Location', url)
this.respond(code || 303)
}
})
}
@@ -51,7 +59,7 @@ exports.Redirect = Plugin.extend({
request: function(event) {
event.request.home = set('home') || set('basepath') || '/'
event.request.back = event.request.header('referrer') || event.request.header('referer')
event.request.back = event.request.header('Referrer') || event.request.header('Referer')
}
}
})
+67 -35
Ver Arquivo
@@ -5,17 +5,18 @@
* Module dependencies.
*/
var utils = require('express/utils')
var Request = require('express/request').Request,
utils = require('express/utils')
// --- Session
var Session = Class({
exports.Base = new Class({
/**
* Initialize session _sid_.
*/
init: function(sid) {
constructor: function(sid) {
this.id = sid
this.touch()
},
@@ -27,13 +28,13 @@ var Session = Class({
*/
touch: function() {
this.lastAccess = Number(new Date)
this.lastAccess = Date.now()
}
})
// --- Store
exports.Store = Class({
exports.Store = new Class({
/**
* Convert to '[NAME Store]'.
@@ -61,64 +62,73 @@ exports.Store.Memory = exports.Store.extend({
* Initialize in-memory session store.
*/
init: function() {
constructor: function() {
this.store = {}
},
/**
* Fetch session with the given _sid_ or
* a new Session is returned.
* a new Session is created.
*
* @param {int} sid
* @return {Session}
* @param {number} sid
* @param {function} callback
* @api private
*/
fetch: function(sid) {
return this.store[sid] || new Session(sid)
fetch: function(sid, callback) {
if (sid && this.store[sid])
callback(null, this.store[sid])
else
this.generate(callback)
},
/**
* Commit _session_ data.
*
* @param {Session} session
* @param {function} callback
* @api private
*/
commit: function(session) {
return this.store[session.id] = session
commit: function(session, callback) {
this.store[session.id] = session
if (callback) callback(null, session)
},
/**
* Clear all sessions.
*
* @param {function} callback
* @api public
*/
clear: function() {
clear: function(callback) {
this.store = {}
if (callback) callback()
},
/**
* Destroy session using the given _sid_.
*
* @param {int} sid
* @param {function} callback
* @api public
*/
destroy: function(sid) {
destroy: function(sid, callback) {
delete this.store[sid]
if (callback) callback(sid)
},
/**
* Return the number of sessions currently stored.
* Pass the number of sessions currently stored.
*
* @return {int}
* @param {function} callback
* @api public
*/
length: function() {
return this.store.values.length
length: function(callback) {
callback(null, Object.keys(this.store).length)
},
/**
@@ -129,11 +139,22 @@ exports.Store.Memory = exports.Store.extend({
*/
reap: function(ms) {
var threshold = Number(new Date(Number(new Date) - ms))
this.store.each(function(session, sid){
if (session.lastAccess < threshold)
this.destroy(sid)
}, this)
var threshold = +new Date(Date.now() - ms),
sids = Object.keys(this.store)
for (var i = 0, len = sids.length; i < len; ++i)
if (this.store[sids[i]].lastAccess < threshold)
this.destroy(sids[i])
},
/**
* Creates and passes a shiny new session.
*
* @param {function} callback
* @api public
*/
generate: function(callback) {
callback(null, new exports.Base(utils.uid()))
}
})
@@ -150,13 +171,16 @@ exports.Session = Plugin.extend({
* - dataStore   constructor name of session data store, defaults to Store.Memory
* - lifetime lifetime of session in milliseconds, defaults to one day
* - reapInterval, reapEvery interval in milliseconds in which to reap old sessions, defaults to one hour
* - cookie session specific cookie options passed to Request#cookie()
*
* @param {hash} options
* @api private
*/
init: function(options) {
this.merge(options || {})
this.cookie = {}
Object.merge(this, options)
this.cookie.httpOnly = true
this.store = new (this.dataStore || exports.Store.Memory)(options)
this.startReaper()
},
@@ -168,8 +192,8 @@ exports.Session = Plugin.extend({
*/
startReaper: function() {
setInterval(function(){
this.store.reap(this.lifetime || (1).day)
setInterval(function(self) {
self.store.reap(self.lifetime || (1).day)
}, this.reapInterval || this.reapEvery || (1).hour, this)
}
},
@@ -182,20 +206,28 @@ exports.Session = Plugin.extend({
* Create session id when not found; delegate to store.
*/
request: function(event) {
var sid
if (!(sid = event.request.cookie('sid')))
event.request.cookie('sid', sid = utils.uid(), set('session cookie'))
event.request.session = exports.Session.store.fetch(sid)
event.request.session.touch()
request: function(event, callback) {
var sid = event.request.cookie('sid')
if (!sid && event.request.url.pathname === '/favicon.ico') return
exports.Session.store.fetch(sid, function(err, session) {
if (err) return callback(err)
if (session.id != sid)
event.request.cookie('sid', session.id, exports.Session.cookie)
event.request.session = session
event.request.session.touch()
callback()
})
return true
},
/**
* Delegate to store, allowing it to save sessions changes.
*/
response: function(event) {
exports.Session.store.commit(event.request.session)
response: function(event, callback) {
if (event.request.session)
return exports.Session.store.commit(event.request.session, callback),
true
}
}
})
+94
Ver Arquivo
@@ -0,0 +1,94 @@
// Express - Static - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request,
path = require('path'),
fs = require('fs')
// --- Static
exports.Static = Plugin.extend({
extend: {
/**
* Initialize routes and request extensions.
*
* Options:
*
* - path path from which to serve static files. Defaults to <root>/public
*
* @param {hash} options
* @api private
*/
init: function(options) {
options = options || {}
options.path = options.path || set('root') + '/public'
// Routes
get('/public/*', function(file){
this.sendfile(options.path + '/' + file)
})
// Request
Request.include({
/**
* Transfer static file at the given _path_ with optional _callback_.
* _options_ are passed to fs.createReadStream().
*
* @param {string} path
* @param {object} options
* @param {function} callback
* @return {Request}
* @api public
*/
sendfile: function(path, options, callback) {
var self = this
if (options instanceof Function)
callback = options,
options = {}
if (path.indexOf('..') !== -1)
Error.raise('InvalidPathError', "`" + path + "' is not a valid path")
fs.stat(path, function(err, stat){
if (err)
return 'errno' in err && err.errno === 2
? self.notFound()
: self.error(err, callback)
var etag = Number(stat.mtime)
if (self.header('If-None-Match') &&
self.header('If-None-Match') == etag)
return self.respond(304, null)
self.header('Content-Length', stat.size)
self.header('ETag', etag)
self.stream(fs.createReadStream(path, options))
})
return this
},
/**
* Transfer static _file_ as an attachment.
*
* The basename of _file_ is used as the attachment _filename_ when
* not explicitly passed.
*
* @param {string} file
* @param {string} filename
* @return {Request}
* @api public
*/
download: function(file, filename) {
return this.attachment(filename || path.basename(file)).sendfile(file)
}
})
}
}
})
+129 -36
Ver Arquivo
@@ -5,7 +5,7 @@
* Module dependencies.
*/
var utils = require('express/utils'),
var Request = require('express/request').Request,
extname = require('path').extname,
fs = require('fs')
@@ -15,6 +15,40 @@ var utils = require('express/utils'),
var engines = {}
/**
* View cache.
*/
var cache = { views: {}, partials: {} }
/**
* View helpers (merged with locals).
*/
var helpers = exports.helpers = {}
/**
* Cache view files where _type_ is
* "partials" or "views".
*
* @param {string} type
* @api public
*/
function cacheFiles(type) {
var dir = set(type)
try {
fs.readdirSync(dir).each(function(file){
file = dir + '/' + file
if (!fs.statSync(file).isFile()) return
cache[type][file] = fs.readFileSync(file).toString('utf8')
})
} catch (e) {
if (e.errno !== process.ENOENT) throw e
}
}
// --- View
exports.View = Plugin.extend({
@@ -28,70 +62,129 @@ exports.View = Plugin.extend({
// Settings
set('views', function(){ return set('root') + '/views' })
if (!set('views'))
set('views', function(){ return set('root') + '/views' })
if (!set('partials'))
set('partials', function(){ return set('views') + '/partials' })
// Cache views in memory
if (set('cache view contents'))
cacheFiles('views')
if (set('cache view partials'))
cacheFiles('partials')
// Request
Request.include({
/**
* Render _view_ partial with _options_.
* View Request#render() for additional options.
*
* Options:
* - as: String name for the id used to which "collection" assign it's current value.
* - collection: Array of objects, the name is derived from
* the view name itself. For example 'video.haml.html'
* will have an object "video" available to it.
*
* @param {string} view
* @param {hash} options
* @settings 'partials', 'cache view partials'
* @return {string}
* @api public
*/
partial: function(view, options) {
var options = options || {}
options.partial = true
options.layout = false
if (options.collection) {
var name = options.as || view.split('.').first,
len = options.collection.length
options.locals = options.locals || {}
options.locals.__length__ = len
return options.collection.map(function(val, i){
options.locals.__isFirst__ = i === 0
options.locals.__index__ = i
options.locals.__isLast__ = i === len - 1
options.locals[name] = val
return this.render(view, options)
}, this).join('')
} else
return this.render(view, options)
},
/**
* Render _view_ with _options_.
*
* Views are looked up relative to the'views' path setting.
* View filenames should conform to ANY.ENGINE.TYPE so for example
* 'layout.ejs.html', 'ejs' represents the template engine, 'html'
* View filenames should conform to NAME.TYPE.ENGINE so for example
* 'layout.html.ejs', 'ejs' represents the template engine, 'html'
* represents the type of content being rendered, which is then passed
* to contentType().
*
* Engines must export a render() method accepting the template string
* and a hash of options.
* and a hash of options. Engines can respond to the options listed below
* as well as their own arbitrary ones. The "filename" option is always
* passed as the path to the given _view_, allowing engines to perform
* better error reporting.
*
* Options:
*
* - encoding: Passed to Request#respond()
* - layout: The layout to use, none when falsey. Defaults to 'layout'
* - locals: Most engines support a hash of local variable names / values.
* - context: Most engines support an evaluation context (the 'this' keyword).
* Defaults to the current Request instance.
*
* Optionally you may also pass a _callback_ function which
* will be called instead of responding with the 200 status code.
*
* @param {string} view
* @param {hash} options
* @param {object} options
* @param {function} callback
* @settings 'views', 'cache view contents'
* @api public
*/
render: function(view, options) {
var self = this,
options = options || {},
path = set('views') + '/' + view,
type = path.split('.').slice(-2)[0],
ext = extname(path),
layout = options.layout === undefined ? 'layout' : options.layout
render: function(view, options, callback) {
var options = options || {},
type = options.partial ? 'partials' : 'views',
path = set(type) + '/' + view,
parts = view.split('.'),
engine = parts.last,
contentType = parts.slice(-2)[0],
layout = options.layout === undefined
? 'layout'
: options.layout
options.locals = options.locals || {}
Object.merge(options.locals, helpers)
options.filename = path
if (set('cache view contents'))
options.cache = true
var content = cache[type][path] || fs.readFileSync(path).toString(options.encoding || 'utf8')
options.context = options.context || this
self.contentType(ext)
function render(content) {
content = (engines[type] = engines[type] || require(type)).render(content, options)
if (layout)
self.render(layout + '.' + type + ext, utils.mixin(true, options, {
layout: false,
locals: {
body: content
}
}))
else
self.halt(200, content)
}
if (set('cache view contents') && self.cache.get(path))
render(self.cache.get(path))
content = (engines[engine] = engines[engine] || require(engine)).render(content, options)
if (type === 'views') this.contentType(contentType)
if (layout) {
layout = layout.indexOf('.') !== -1
? layout
: [layout, contentType, engine].join('.')
this.render(layout, Object.mergeDeep(options, {
layout: false,
locals: { body: content }
}), callback)
} else if (type === 'partials')
return content
else if (callback)
callback.call(this, null, content)
else
fs.readFile(path, function(e, content){
if (e) throw e
set('cache view contents')
? render(self.cache.set(path, content))
: render(content)
})
this.respond(200, content, options.encoding)
}
})
}
}
})
})
+239 -84
Ver Arquivo
@@ -5,12 +5,15 @@
* Module dependencies.
*/
var StaticFile = require('express/static').File,
var Event = require('express/event').Event,
showExceptions = require('express/pages/show-exceptions'),
notFound = require('express/pages/not-found'),
statusBodies = require('http').STATUS_CODES,
queryString = require('querystring'),
mime = require('express/mime'),
utils = require('express/utils'),
url = require('url')
url = require('url'),
ext = require('ext'),
sys = require('sys')
// --- Helpers
@@ -29,7 +32,7 @@ exports.normalizePath = function(path) {
// --- Request
exports.Request = Class({
exports.Request = new Class({
/**
* Initialize with node's _request_ and _response_ objects.
@@ -44,20 +47,21 @@ exports.Request = Class({
* @param {object} response
* @api private
*/
init: function(request, response) {
utils.mixin(true, this, request)
constructor: function(request, response) {
Object.merge(this, request)
response.headers = {}
this.response = response
this.response = response
this.url = url.parse(this.url)
this.url.pathname = exports.normalizePath(this.url.pathname)
this.params = this.params || {}
this.params.path = {}
this.url.pathname = exports.normalizePath(this.url.pathname)
this.params = {}
this.params.path = {}
this.params.get = this.url.query ? queryString.parseQuery(this.url.query) : {}
this.params.post = this.params.post || {}
this.plugins = Express.plugins.map(function(plugin){
return new plugin.klass(plugin.options)
})
this.reversedPlugins = this.plugins.slice(0).reverse()
},
/**
@@ -72,16 +76,16 @@ exports.Request = Class({
header: function(key, val) {
return val === undefined
? this.headers[key.toLowerCase()]
: this.response.headers[key.toLowerCase()] = val
? this.headers[key.lowercase]
: this.response.headers[key] = val
},
/**
* Return a param _key_ value or null.
* Return the param _key_ value or undefined.
*
* - Checks route populated path parameters
* - Checks POST parameters
* - Checks GET parameters
* - Checks POST parameters
* - Checks route populated path parameters
*
* @param {string} key
* @return {string}
@@ -89,9 +93,12 @@ exports.Request = Class({
*/
param: function(key) {
return this.params.get[key] ||
this.params.post[key] ||
this.params.path[key]
if (key in this.params.get)
return this.params.get[key]
if (key in this.params.post)
return this.params.post[key]
if (key in this.params.path)
return this.params.path[key]
},
/**
@@ -115,20 +122,30 @@ exports.Request = Class({
accepts: function() {
var accept = this.header('accept')
return accept
? arguments.any(function(path){
var type = mime.type(path)
return accept.indexOf(type) !== -1 ||
accept.indexOf(type.split('/')[0]+'/*') !== -1
})
: true
if (!accept || accept === '*/*') return true
return Object.values(arguments).any(function(path){
var type = mime.type(path)
return accept.indexOf(type) !== -1 ||
accept.indexOf(type.split('/')[0] + '/*') !== -1
})
},
/**
* Check if the request was an xmlHttpRequest (ajax).
*
* @return {bool}
* @api public
*/
get isXHR() {
return (this.header('X-Requested-With') || '').lowercase === 'xmlhttprequest'
},
/**
* Set response status to _code_.
*
* @param {int} code
* @return {Request)
* @return {Request}
* @api public
*/
@@ -138,44 +155,124 @@ exports.Request = Class({
},
/**
* Immediately respond with response _code_, _body_ and optional _encoding_.
* Respond with response _code_, and optional _body_.
*
* The status _code_ defaults to to 404, and _body_ will
* default to the default body associated with the response
* _code_.
*
* The _callback_ may be given as the 3rd or 4th argument,
* which is then called when an error occurs OR when the response
* has been completed.
*
* Examples:
*
* request.respond()
* // 404 "Not Found"
*
* request.respond(500)
* // 500 "Internal Server Error"
*
* request.respond(200, "im ok")
* // 200 "im ok"
*
* request.respond(200, "√ woot", "utf8")
* // "utf8" will set Request#charset to 'UTF-8'
*
* @param {int} code
* @param {string} body
* @param {string} encoding
* @param {string|function} encoding
* @param {function} callback
* @see statusBodies
* @api public
*/
halt: function(code, body, encoding, callback) {
respond: function(code, body, encoding, callback) {
var self = this
this.status(code = code || 404)
if (body = body || statusBodies[code])
return this.respond(body, encoding, callback)
if (encoding instanceof Function)
callback = encoding,
encoding = null
if (204 === code)
body = null
else if (body !== null)
body = body || statusBodies[code]
if (encoding === 'utf8' ||
encoding === 'utf-8')
this.charset = 'UTF-8'
this.response.body = body
this.trigger('response', function(err) {
if (err) return self.error(err, callback)
self.sendHead()
if (body) self.response.write(self.response.body, encoding)
self.response.end()
if (callback) callback()
}, true)
},
// >>> DEPRECATED: remove in 1.0
halt: function(){
ext.warn('Request#halt() has been renamed Request#respond()')
this.respond.apply(this, arguments)
},
// <<< DEPRECATED
/**
* Transfer the given _stream_ with optional _callback_.
*
* @param {Stream} stream
* @param {function} callback
* @return {Request}
* @api public
*/
stream: function(stream, callback) {
var self = this,
first = true
stream
.addListener('error', function(err){
if (first)
return self.error(err, callback)
stream.destroy()
self.response.end()
})
.addListener('data', function(data){
if (first) {
first = false
self.header('Transfer-Encoding', 'chunked')
self.status(200)
self.contentType(stream.path)
self.sendHead()
}
self.response.write(data, 'binary')
})
.addListener('end', function(){
self.trigger('response', function(err){
if (err)
return self.error(err, callback)
self.response.end()
}, true)
})
},
/**
* Respond with _body_ and optional _encoding_.
* Send the response header.
*
* @param {string} body
* @param {string} encoding
* @see Request#halt()
* @api private
* If Request#charset is defined, and the
* "Content-Type" header, then "; charset=CHARSET" is
* appended.
*
* @return {Request}
* @api public
*/
respond: function(body, encoding, callback) {
var self = this
this.response.body = body
this.trigger('response', function(e) {
if (e)
if (callback !== undefined) callback(e)
else throw e
self.response.writeHeader(self.response.status, self.response.headers)
self.response.write(self.response.body, encoding)
self.response.close()
});
sendHead: function(){
if (this.charset && this.response.headers['Content-Type'])
this.response.headers['Content-Type'] += '; charset=' + this.charset
this.response.writeHead(this.response.status, this.response.headers)
return this
},
/**
@@ -204,7 +301,7 @@ exports.Request = Class({
*/
contentType: function(path) {
this.header('content-type', mime.type(path))
this.header('Content-Type', mime.type(path))
return this
},
@@ -215,73 +312,131 @@ exports.Request = Class({
* @param {string} name
* @param {object} data
* @param {function} callback
* @param {bool} reverse
* @return {Request}
* @api public
*/
trigger: function(name, data, callback) {
trigger: function(name, data, callback, reverse) {
if (data instanceof Function)
reverse = callback,
callback = data,
data = null
data = data || {}
data.merge({ request: this, response: this.response })
data = Object.merge({ request: this, response: this.response }, data)
var self = this,
complete = 0,
total = this.plugins.length
;(function next(e) {
if (e || complete === total)
callback(e)
total = this.plugins.length,
plugins = reverse
? self.reversedPlugins
: self.plugins
;(function next(err) {
if (err || complete === total)
callback(err)
else {
try {
if (self.plugins.at(complete++).trigger(new Event(name, data), next) !== true)
next()
} catch(e) {
next(e)
}
// TODO: remove when this issue is resolved...
if (plugins[complete] === undefined)
++complete,
next()
else if (plugins[complete++].trigger(new Event(name, data), next) !== true)
next()
}
})()
return this
},
/**
* Transfer static file at the given _path_ as an attachment.
* The basename of _path_ is used as the attachment filename.
*
* @param {string} path
* @return {Request}
* @api public
*/
download: function(path) {
return this.attachment(basename(path)).sendfile(path)
},
/**
* Set Content-Disposition header to 'attachment',
* with optional file _path_.
* with optional file _filename_.
*
* @param {string} path
* @param {string} filename
* @return {Request}
* @api public
*/
attachment: function(path) {
this.header('content-disposition', path
? 'attachment; filename="' + path + '"'
attachment: function(filename) {
this.header('Content-Disposition', filename
? 'attachment; filename="' + filename + '"'
: 'attachment')
return this
},
/**
* Transfer static file at the given _path_.
* Handle exceptions.
*
* When an error route is defined via the DSL it
* will then be called regardless of any setting that
* may be present. ("throw exceptions" will still work)
*
* error(function(err){
* this.respond(500, 'your app sucks!')
* })
*
* When "show exceptions" is enabled the show-exceptions page will be shown for "text/html",
* a plain-text representation of the error for "text/plain" and JSON for "application/json".
* Otherwise the request will halt with default 500 status body.
*
* When "throw exceptions" is enabled the error will be
* re-thrown, terminating the process (unless otherwise caught).
*
* Also a _callback_ function may be supplied, which when defined
* will be called, by-passing the process mentioned above.
*
* @param {Error} err
* @param {function} callback
* @return {Request}
* @settings 'throw exceptions', 'show exceptions'
* @api public
*/
error: function(err, callback) {
if (callback)
return callback(err)
if (Express.error)
Express.error.call(this, err)
else if (set('show exceptions'))
if (this.accepts('html'))
this.respond(500, showExceptions.render(this, err))
else if (this.accepts('json'))
this.respond(500, showExceptions.renderJSON(this, err))
else if (this.accepts('text'))
this.respond(500, showExceptions.renderText(this, err))
else
this.respond(500)
else
this.respond(500)
if (set('dump exceptions'))
sys.puts(err.stack)
if (set('throw exceptions'))
throw err
return this
},
/**
* Halt with 404 Not Found.
*
* When a notFound route is defined via the DSL it
* will then be called regardless of any settings that
* may be present.
*
* notFound(function(){
* this.respond(404, 'Sorry your page cannot be found')
* })
*
* When "html" is accepted, and "helpful 404" is enabled
* the not-found page will be shown, otherwise the
* request will halt with default 404 status body.
*
* @param {string} path
* @return {Request}
* @api public
*/
sendfile: function(path) {
(new StaticFile(path)).send(this)
notFound: function() {
if (Express.notFound)
Express.notFound.call(this)
else if (this.accepts('html') && set('helpful 404'))
this.respond(404, notFound.render(this))
else
this.respond()
return this
}
})
+63 -20
Ver Arquivo
@@ -5,11 +5,53 @@
* Module dependencies.
*/
var utils = require('express/utils')
var Request = require('express/request').Request,
path = require('path'),
fs = require('fs')
/**
* Sync fs.readFile()
*/
fs.readFile = function(path, encoding, callback) {
if (encoding instanceof Function)
callback = encoding,
encoding = null
try {
callback(null, fs.readFileSync(path, encoding))
} catch (e) {
callback(e)
}
}
/**
* Sync path.exists()
*/
path.exists = function(path, callback) {
try {
fs.statSync(path)
callback(true)
} catch (e) {
callback(false)
}
}
/**
* Sync fs.stat()
*/
fs.stat = function(path, callback) {
try {
callback(null, fs.statSync(path))
} catch (e) {
callback(e)
}
}
// --- MockRequest
var MockRequest = Class({
var MockRequest = new Class({
/**
* Default HTTP version.
@@ -26,12 +68,10 @@ var MockRequest = Class({
* @api private
*/
init: function(method, path, options) {
constructor: function(method, path, options) {
this.method = method
this.url = path
this.connection = {
remoteAddress: '127.0.0.1'
}
this.connection = { remoteAddress: '127.0.0.1' }
this.headers = {
'host': 'localhost',
'user-agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/530.19.2 (KHTML, like Gecko) Version/4.0.2 Safari/530.19',
@@ -39,19 +79,19 @@ var MockRequest = Class({
'accept-language': 'en-us',
'connection': 'keep-alive'
}
utils.mixin(true, this, options)
Object.mergeDeep(this, options)
}
})
// --- MockResponse
var MockResponse = Class({
var MockResponse = new Class({
/**
* Store _code_ and _headers_.
*/
writeHeader: function(code, headers) {
writeHead: function(code, headers) {
this.status = code
this.headers = headers
},
@@ -68,7 +108,7 @@ var MockResponse = Class({
* Flag response as finished.
*/
close: function() {
end: function() {
this.finished = true
}
})
@@ -87,11 +127,11 @@ var MockResponse = Class({
* @api private
*/
function request(method, path, options, fn) {
var response = new MockResponse
var request = new MockRequest(method, path, options)
Express.server.route(request, response)
return response
function request(method, path, options, callback) {
var req = new MockRequest(method, path, options),
res = new MockResponse
Express.server.route(new Request(req, res))
return res
}
/**
@@ -105,6 +145,9 @@ reset = function() {
Express.routes = []
Express.plugins = []
Express.settings = {}
Express.params = {}
delete Express.notFound
delete Express.error
configure('test')
}
@@ -117,13 +160,13 @@ reset = function() {
*/
function route(method) {
return function(path, options, fn){
return function(path, options, callback){
if (options instanceof Function)
fn = options, options = {}
if (fn instanceof Function)
Express.routes.push(new Route(method, path, fn, options))
callback = options, options = {}
if (callback instanceof Function)
Express.routes.push(new Route(method, path, callback, options))
else
return request(method, path, options, fn)
return request(method, path, options, callback)
}
}
-61
Ver Arquivo
@@ -1,61 +0,0 @@
// Express - Static - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var path = require('path'),
fs = require('fs')
// --- File
exports.File = Class({
/**
* Initialize with file _path_.
*
* @param {string} path
* @api public
*/
init: function(path) {
this.path = path
if (path.indexOf('..') != -1)
Error.raise('InvalidPathError', "`" + path + "' is not a valid path")
},
/**
* Transfer static file to the given _request_.
*
* - Ensures the file exists
* - Ensures the file is a regular file (not FIFO, Socket, etc)
* - Automatically assigns content type
* - Halts with 404 when failing
*
* @param {Request} request
* @settings 'cache static files'
* @api public
*/
send: function(request) {
var cache, file = this.path
if (set('cache static files') && (cache = request.cache.get(file)))
return request.contentType(cache.type),
request.halt(200, cache.content, 'binary')
path.exists(file, function(exists){
if (!exists) return request.halt()
fs.stat(file, function(e, stats){
if (e) throw e
if (!stats.isFile()) return request.halt()
fs.readFile(file, 'binary', function(e, content){
if (e) throw e
request.contentType(file)
if (set('cache static files'))
request.cache.set(file, { type: file, content: content })
request.halt(200, content, 'binary')
})
})
})
}
})
-75
Ver Arquivo
@@ -74,78 +74,3 @@ exports.mergeParam = function(key, val, params) {
}, queryString.parseQuery(key))
return orig
}
/**
* Return a clone of _obj_.
*
* @param {mixed} obj
* @return {mixed}
* @api public
*/
function Clone() {}
exports.clone = function(obj) {
Clone.prototype = obj
return new Clone
}
// From jQuery.extend in the jQuery JavaScript Library v1.3.2
// Copyright (c) 2009 John Resig
// Dual licensed under the MIT and GPL licenses.
// http://docs.jquery.com/License
// Modified for node.js (formely for copying properties correctly)
exports.mixin = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, source;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !(typeof target === 'function') )
target = {};
// mixin process itself if only one argument is passed
if ( length == i ) {
target = GLOBAL;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (source = arguments[i]) != null ) {
// Extend the base object
Object.getOwnPropertyNames(source).forEach(function(k){
var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]};
if (d.get) {
target.__defineGetter__(k, d.get);
if (d.set) {
target.__defineSetter__(k, d.set);
}
}
else {
// Prevent never-ending loop
if (target !== d.value) {
if (deep && d.value && typeof d.value === "object") {
target[k] = exports.mixin(deep,
// Never move original objects, clone them
target[k] || (d.value.length != null ? [] : {})
, d.value);
}
else {
target[k] = d.value;
}
}
}
});
}
}
// Return the modified object
return target;
};
+1
Submodule lib/support/class added at 5ed0e4aaec
+26
Ver Arquivo
@@ -0,0 +1,26 @@
/**
* Compiled template cache.
*/
var cache = {}
exports.render = function(str, options) {
options = options || {}
var fn = cache[str] = cache[str] ||
new Function("locals",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(locals){p.push('" +
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.split("'").join("\\'")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');")
return fn.call(options.context, options.locals || {})
}
Submodule lib/support/oo deleted from 1f94bd8979
+3 -3
Ver Arquivo
@@ -1,14 +1,14 @@
{
"name": "Express",
"description": "Sinatra inspired web development framework",
"version": "0.7.3",
"version": "0.13.0",
"keywords": ["framework", "sinatra", "web", "rest", "restful"],
"directories": {
"lib": "lib"
"lib": "./lib"
},
"scripts": {
"install": "git submodule update --init",
"test": "make test"
},
"engines": { "node": ">= 0.1.30" }
"engines": { "node": ">= 0.1.97" }
}
+1 -1
Ver Arquivo
@@ -1,4 +1,4 @@
---
name: Express
description: Sinatra inspired web development framework
version: 0.7.3
version: 0.12.0
+1
Ver Arquivo
@@ -0,0 +1 @@
%h2!= this.name
+1
Ver Arquivo
@@ -0,0 +1 @@
%h2 Hello
+1
Ver Arquivo
@@ -0,0 +1 @@
Testing
+1
Ver Arquivo
@@ -0,0 +1 @@
%span= _('Hello world')
+1
Ver Arquivo
@@ -0,0 +1 @@
%span= _(body)
+2
Ver Arquivo
@@ -0,0 +1,2 @@
%title= "Viewing " + name
%body!= body
+1
Ver Arquivo
@@ -0,0 +1 @@
<p><%= body %></p>
+2
Ver Arquivo
@@ -0,0 +1,2 @@
%html
%body!= body
+5
Ver Arquivo
@@ -0,0 +1,5 @@
<ul>
<% for (var i in items) { %>
<%= this.partial("item.html.ejs", { locals: { item: items[i] }}) %>
<% } %>
</ul>
+3
Ver Arquivo
@@ -0,0 +1,3 @@
%ul
- each item in items
!= this.partial('item.html.haml', { locals: { item: item }})
+2
Ver Arquivo
@@ -0,0 +1,2 @@
%title= this.title
%body!= body
+9
Ver Arquivo
@@ -0,0 +1,9 @@
<ul>
<% if (__isFirst__) { %>
<li class="first"><%= article %></li>
<% } else if (__isLast__) { %>
<li class="last"><%= article %></li>
<% } else { %>
<li class="<%= __index__ %>"><%= article %></li>
<% } %>
</ul>
+7
Ver Arquivo
@@ -0,0 +1,7 @@
%ul
- if (__isFirst__)
%li.first= article
- if (__isLast__)
%li.last= article
- if (!__isLast__ && !__isFirst__)
%li{ class: __index__ }= article
+1
Ver Arquivo
@@ -0,0 +1 @@
<li><%= item %></li>
+1
Ver Arquivo
@@ -0,0 +1 @@
%li= item
+1
Ver Arquivo
@@ -0,0 +1 @@
<li><%= vid %></li>
+1
Ver Arquivo
@@ -0,0 +1 @@
%li= vid
+2
Ver Arquivo
@@ -0,0 +1,2 @@
%h1= name
%p= email
Ver Arquivo
+15 -7
Ver Arquivo
@@ -24,18 +24,20 @@ JSpec
// --- Matchers
matchers : {
have_tag : "jQuery(expected, actual).length == 1",
matchers : {
have_tag : "jQuery(expected, actual).length === 1",
have_one : "alias have_tag",
have_tags : "jQuery(expected, actual).length > 1",
have_many : "alias have_tags",
have_child : "jQuery(actual).children(expected).length == 1",
have_any : "alias have_tags",
have_child : "jQuery(actual).children(expected).length === 1",
have_children : "jQuery(actual).children(expected).length > 1",
have_text : "jQuery(actual).text() == expected",
have_value : "jQuery(actual).val() == expected",
have_text : "jQuery(actual).text() === expected",
have_value : "jQuery(actual).val() === expected",
be_enabled : "!jQuery(actual).attr('disabled')",
have_class : "jQuery(actual).hasClass(expected)",
be_animated : "jQuery(actual).queue().length > 0",
be_visible : function(actual) {
return jQuery(actual).css('display') != 'none' &&
jQuery(actual).css('visibility') != 'hidden' &&
@@ -45,7 +47,7 @@ JSpec
be_hidden : function(actual) {
return !JSpec.does(actual, 'be_visible')
},
have_classes : function(actual) {
return !JSpec.any(JSpec.toArray(arguments, 1), function(arg){
return !JSpec.does(actual, 'have_class', arg)
@@ -57,6 +59,12 @@ JSpec
jQuery(actual).attr(attr)
},
have_event_handlers : function(actual, expected) {
return jQuery(actual).data('events') ?
jQuery(actual).data('events').hasOwnProperty(expected) :
false
},
'be disabled selected checked' : function(attr) {
return 'jQuery(actual).attr("' + attr + '")'
},
+268 -148
Ver Arquivo
@@ -4,12 +4,13 @@
;(function(){
JSpec = {
version : '3.2.1',
version : '4.3.2',
assert : true,
cache : {},
suites : [],
modules : [],
allSuites : [],
sharedBehaviors: [],
matchers : {},
stubbed : [],
options : {},
@@ -68,6 +69,31 @@
return JSpec.cache[path] =
JSpec.tryLoading(JSpec.options.fixturePath + '/' + path) ||
JSpec.tryLoading(JSpec.options.fixturePath + '/' + path + '.html')
},
/**
* Load json fixture at _path_.
*
* JSON fixtures are resolved as:
*
* - <path>
* - <path>.json
*
* @param {string} path
* @return {object}
* @api public
*/
json_fixture: function(path) {
if (!JSpec.cache['json:' + path])
JSpec.cache['json:' + path] =
JSpec.tryLoading(JSpec.options.fixturePath + '/' + path) ||
JSpec.tryLoading(JSpec.options.fixturePath + '/' + path + '.json')
try {
return eval('(' + JSpec.cache['json:' + path] + ')')
} catch (e) {
throw 'json_fixture("' + path + '"): ' + e
}
}
},
@@ -92,7 +118,7 @@
stats: JSpec.stats,
options: options,
results: map(results.allSuites, function(suite) {
if (suite.hasSpecs())
if (suite.isExecutable())
return {
description: suite.description,
specs: map(suite.specs, function(spec) {
@@ -126,10 +152,10 @@
*/
DOM : function(results, options) {
var id = option('reportToId') || 'jspec'
var report = document.getElementById(id)
var failuresOnly = option('failuresOnly')
var classes = results.stats.failures ? 'has-failures' : ''
var id = option('reportToId') || 'jspec',
report = document.getElementById(id),
failuresOnly = option('failuresOnly'),
classes = results.stats.failures ? 'has-failures' : ''
if (!report) throw 'JSpec requires the element #' + id + ' to output its reports'
function bodyContents(body) {
@@ -145,7 +171,7 @@
<span class="passes">Duration: <em>' + results.duration + '</em> ms</span> \
</div><table class="suites">' + map(results.allSuites, function(suite) {
var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran
if (displaySuite && suite.hasSpecs())
if (displaySuite && suite.isExecutable())
return '<tr class="description"><td colspan="2">' + escape(suite.description) + '</td></tr>' +
map(suite.specs, function(i, spec) {
return '<tr class="' + (i % 2 ? 'odd' : 'even') + '">' +
@@ -170,7 +196,7 @@
*/
Terminal : function(results, options) {
failuresOnly = option('failuresOnly')
var failuresOnly = option('failuresOnly')
print(color("\n Passes: ", 'bold') + color(results.stats.passes, 'green') +
color(" Failures: ", 'bold') + color(results.stats.failures, 'red') +
color(" Duration: ", 'bold') + color(results.duration, 'green') + " ms \n")
@@ -181,7 +207,7 @@
each(results.allSuites, function(suite) {
var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran
if (displaySuite && suite.hasSpecs()) {
if (displaySuite && suite.isExecutable()) {
print(color(' ' + suite.description, 'bold'))
each(suite.specs, function(spec){
var assertionsGraph = inject(spec.assertions, '', function(graph, assertion){
@@ -200,33 +226,7 @@
})
quit(results.stats.failures)
},
/**
* Console reporter.
*
* @api public
*/
Console : function(results, options) {
console.log('')
console.log('Passes: ' + results.stats.passes + ' Failures: ' + results.stats.failures)
each(results.allSuites, function(suite) {
if (suite.ran) {
console.group(suite.description)
each(suite.specs, function(spec){
var assertionCount = spec.assertions.length + ':'
if (spec.requiresImplementation())
console.warn(spec.description)
else if (spec.passed())
console.log(assertionCount + ' ' + spec.description)
else
console.error(assertionCount + ' ' + spec.description + ', ' + spec.failure().message)
})
console.groupEnd()
}
})
}
}
},
Assertion : function(matcher, actual, expected, negate) {
@@ -260,14 +260,14 @@
},
ProxyAssertion : function(object, method, times, negate) {
var self = this
var old = object[method]
var self = this,
old = object[method]
// Proxy
object[method] = function(){
args = toArray(arguments)
result = old.apply(object, args)
var args = toArray(arguments),
result = old.apply(object, args)
self.calls.push({ args : args, result : result })
return result
}
@@ -418,17 +418,21 @@
* @api private
*/
Suite : function(description, body) {
Suite : function(description, body, isShared) {
var self = this
extend(this, {
body: body,
description: description,
suites: [],
sharedBehaviors: [],
specs: [],
ran: false,
hooks: { 'before' : [], 'after' : [], 'before_each' : [], 'after_each' : [] },
shared: isShared,
hooks: { 'before' : [], 'after' : [],
'before_each' : [], 'after_each' : [],
'before_nested' : [], 'after_nested' : []},
// Add a spec to the suite
// Add a spec to the suite
addSpec : function(description, body) {
var spec = new JSpec.Spec(description, body)
@@ -437,16 +441,30 @@
spec.suite = this
},
// Add a hook to the suite
// Add a before hook to the suite
addBefore : function(options, body) {
body.options = options || {}
this.befores.push(body)
},
// Add an after hook to the suite
addAfter : function(options, body) {
body.options = options || {}
this.afters.unshift(body)
},
// Add a hook to the suite
addHook : function(hook, body) {
this.hooks[hook].push(body)
},
// Add a nested suite
addSuite : function(description, body) {
var suite = new JSpec.Suite(description, body)
addSuite : function(description, body, isShared) {
var suite = new JSpec.Suite(description, body, isShared)
JSpec.allSuites.push(suite)
suite.name = suite.description
suite.description = this.description + ' ' + suite.description
@@ -454,15 +472,17 @@
suite.suite = this
},
// Invoke a hook in context to this suite
// Invoke a hook in context to this suite
hook : function(hook) {
if (this.suite) this.suite.hook(hook)
if (hook != 'before' && hook != 'after')
if (this.suite) this.suite.hook(hook)
each(this.hooks[hook], function(body) {
JSpec.evalBody(body, "Error in hook '" + hook + "', suite '" + self.description + "': ")
})
},
// Check if nested suites are present
hasSuites : function() {
@@ -481,7 +501,15 @@
return !any(this.specs, function(spec){
return !spec.passed()
})
}
},
isShared : function(){
return this.shared
},
isExecutable : function() {
return !this.isShared() && this.hasSpecs()
}
})
},
@@ -629,7 +657,7 @@
},
describe : function(description, body) {
return JSpec.currentSuite.addSuite(description, body)
return JSpec.currentSuite.addSuite(description, body, false)
},
it : function(description, body) {
@@ -639,19 +667,31 @@
before : function(body) {
return JSpec.currentSuite.addHook('before', body)
},
after : function(body) {
return JSpec.currentSuite.addHook('after', body)
},
before_each : function(body) {
return JSpec.currentSuite.addHook('before_each', body)
},
after_each : function(body) {
return JSpec.currentSuite.addHook('after_each', body)
},
before_nested : function(body) {
return JSpec.currentSuite.addHook('before_nested', body)
},
after_nested : function(body){
return JSpec.currentSuite.addhook('after_nested', body)
},
shared_behaviors_for : function(description, body){
return JSpec.currentSuite.addSuite(description, body, true)
},
should_behave_like : function(description) {
return JSpec.shareBehaviorsOf(description)
}
@@ -728,8 +768,7 @@
evalHook : function(module, name, args) {
hook('evaluatingHookBody', module, name)
try { return module[name].apply(module, args) }
catch(e) { error('Error in hook ' + module.name + '.' + name + ': ', e) }
return module[name].apply(module, args)
},
/**
@@ -752,19 +791,69 @@
},
/**
* Find a suite by its description or name.
* Find a shared example suite by its description or name.
* First searches parent tree of suites for shared behavior
* before falling back to global scoped nested behaviors.
*
* @param {string} description
* @return {Suite}
* @api private
*/
findSuite : function(description) {
return find(this.allSuites, function(suite){
return suite.name == description || suite.description == description
})
findSharedBehavior : function(description) {
var behavior
return (behavior = JSpec.findLocalSharedBehavior(description))
? behavior
: JSpec.findGlobalSharedBehavior(description)
},
/**
* Find a shared example suite within the current suite's
* parent tree by its description or name.
*
* @param {string} description
* @return {Suite}
* @api private
*/
findLocalSharedBehavior : function(description) {
var behavior,
currentSuite = JSpec.currentSuite.suite
while (currentSuite)
if (behavior = find(currentSuite.suites, JSpec.suiteDescriptionPredicate(description)))
return behavior
else
currentSuite = currentSuite.suite
},
/**
* Find a shared example suite within the global
* scope by its description or name.
*
* @param {string} description
* @return {Suite}
* @api private
*/
findGlobalSharedBehavior : function(description) {
return find(JSpec.suites, JSpec.suiteDescriptionPredicate(description))
},
/**
* Build a predicate that will match a suite based on name or description
*
* @param {string} description
* @return {function}
* @api private
*/
suiteDescriptionPredicate : function(description) {
return function(suite){
return suite.name === description ||
suite.description === description
}
},
/**
* Share behaviors (specs) of the given suite with
* the current suite.
@@ -774,24 +863,13 @@
*/
shareBehaviorsOf : function(description) {
if (suite = this.findSuite(description)) this.copySpecs(suite, this.currentSuite)
else throw 'failed to share behaviors. ' + puts(description) + ' is not a valid Suite name'
var suite = JSpec.findSharedBehavior(description)
if (suite)
JSpec.evalBody(suite.body)
else
throw new Error("failed to find shared behaviors named `" + description + "'")
},
/**
* Copy specs from one suite to another.
*
* @param {Suite} fromSuite
* @param {Suite} toSuite
* @api public
*/
copySpecs : function(fromSuite, toSuite) {
each(fromSuite.specs, function(spec){
spec.assertions = []
toSuite.specs.push(spec)
})
},
/**
* Convert arguments to an array.
@@ -816,17 +894,21 @@
*/
color : function(string, color) {
return "\u001B[" + {
bold : 1,
black : 30,
red : 31,
green : 32,
yellow : 33,
blue : 34,
magenta : 35,
cyan : 36,
white : 37
}[color] + 'm' + string + "\u001B[0m"
if (option('disableColors')) {
return string
} else {
return "\u001B[" + {
bold : 1,
black : 30,
red : 31,
green : 32,
yellow : 33,
blue : 34,
magenta : 35,
cyan : 36,
white : 37
}[color] + 'm' + string + "\u001B[0m"
}
},
/**
@@ -878,6 +960,7 @@
*/
normalizeMatcherBody : function(body) {
var captures
switch (body.constructor) {
case String:
if (captures = body.match(/^alias (\w+)/)) return JSpec.matchers[last(captures)]
@@ -992,6 +1075,26 @@
}
},
/**
* Parse an XML String and return a 'document'.
*
* @param {string} text
* @return {document}
* @api public
*/
parseXML : function(text) {
var xmlDoc
if (window.DOMParser)
xmlDoc = (new DOMParser()).parseFromString(text, "text/xml")
else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async = "false"
xmlDoc.loadXML(text)
}
return xmlDoc
},
/**
* Escape HTML.
*
@@ -1049,7 +1152,7 @@
function assert(matcher, args, negate) {
var expected = toArray(args, 1)
matcher.negate = negate
assertion = new JSpec.Assertion(matcher, actual, expected, negate)
var assertion = new JSpec.Assertion(matcher, actual, expected, negate)
hook('beforeAssertion', assertion)
if (matcher.defer) assertion.run()
else JSpec.currentSpec.assertions.push(assertion.run().report()), hook('afterAssertion', assertion)
@@ -1167,6 +1270,7 @@
*/
destub : function(object, method) {
var captures
if (method) {
if (object['__prototype__' + method])
delete object[method]
@@ -1301,12 +1405,27 @@
*/
describe : function(description, body) {
var suite = new JSpec.Suite(description, body)
var suite = new JSpec.Suite(description, body, false)
hook('addingSuite', suite)
this.allSuites.push(suite)
this.suites.push(suite)
},
/**
* Add a shared example suite to JSpec.
*
* @param {string} description
* @param {body} function
* @api public
*/
shared_behaviors_for : function(description, body) {
var suite = new JSpec.Suite(description, body, true)
hook('addingSuite', suite)
this.allSuites.push(suite)
this.suites.push(suite)
},
/**
* Return the contents of a function body.
*
@@ -1333,9 +1452,8 @@
var matchers = this.matchers
var context = this.context || this.defaultContext
var contents = this.contentsOf(body)
hook('evaluatingBody', dsl, matchers, context, contents)
try { with (dsl){ with (context) { with (matchers) { eval(contents) }}} }
catch(e) { error(errorMessage, e) }
hook('evaluatingBody', dsl, matchers, context, contents)
with (dsl){ with (context) { with (matchers) { eval(contents) }}}
},
/**
@@ -1355,8 +1473,9 @@
split('__END__')[0].
replace(/([\w\.]+)\.(stub|destub)\((.*?)\)$/gm, '$2($1, $3)').
replace(/describe\s+(.*?)$/gm, 'describe($1, function(){').
replace(/shared_behaviors_for\s+(.*?)$/gm, 'shared_behaviors_for($1, function(){').
replace(/^\s+it\s+(.*?)$/gm, ' it($1, function(){').
replace(/^ *(before_each|after_each|before|after)(?= |\n|$)/gm, 'JSpec.currentSuite.addHook("$1", function(){').
replace(/^ *(before_nested|after_nested|before_each|after_each|before|after)(?= |\n|$)/gm, 'JSpec.currentSuite.addHook("$1", function(){').
replace(/^\s*end(?=\s|$)/gm, '});').
replace(/-\{/g, 'function(){').
replace(/(\d+)\.\.(\d+)/g, function(_, a, b){ return range(a, b) }).
@@ -1419,25 +1538,28 @@
*/
runSuite : function(suite) {
this.currentSuite = suite
this.evalBody(suite.body)
suite.ran = true
hook('beforeSuite', suite), suite.hook('before')
each(suite.specs, function(spec) {
hook('beforeSpec', spec)
suite.hook('before_each')
JSpec.runSpec(spec)
hook('afterSpec', spec)
suite.hook('after_each')
})
if (suite.hasSuites()) {
each(suite.suites, function(suite) {
JSpec.runSuite(suite)
})
}
hook('afterSuite', suite), suite.hook('after')
this.stats.suitesFinished++
},
if (!suite.isShared())
{
this.currentSuite = suite
this.evalBody(suite.body)
suite.ran = true
hook('beforeSuite', suite), suite.hook('before'), suite.hook('before_nested')
each(suite.specs, function(spec) {
hook('beforeSpec', spec)
suite.hook('before_each')
JSpec.runSpec(spec)
hook('afterSpec', spec)
suite.hook('after_each')
})
if (suite.hasSuites()) {
each(suite.suites, function(suite) {
JSpec.runSuite(suite)
})
}
hook('afterSuite', suite), suite.hook('after_nested'), suite.hook('after')
this.stats.suitesFinished++
}
},
/**
* Report a failure for the current spec.
@@ -1512,19 +1634,6 @@
})
},
/**
* Throw a JSpec related error.
*
* @param {string} message
* @param {Exception} e
* @api public
*/
error : function(message, e) {
throw (message ? message : '') + e.toString() +
(e.line ? ' near line ' + e.line : '')
},
/**
* Ad-hoc POST request for JSpec server usage.
*
@@ -1620,7 +1729,7 @@
return request.responseText
}
else
error("failed to load `" + file + "'")
throw new Error("failed to load `" + file + "'")
},
/**
@@ -1637,12 +1746,23 @@
return this
}
}
// --- Node.js support
if (typeof GLOBAL === 'object' && typeof exports === 'object') {
var fs = require('fs')
quit = process.exit
print = require('sys').puts
readFile = function(file){
return fs.readFileSync(file).toString('utf8')
}
}
// --- Utility functions
var main = this
var find = JSpec.any
var utils = 'haveStopped stub hookImmutable hook destub map any last pass fail range each option inject select \
var main = this,
find = JSpec.any,
utils = 'haveStopped stub hookImmutable hook destub map any last pass fail range each option inject select \
error escape extend puts query strip color does addMatchers callIterator toArray equal'.split(/\s+/)
while (utils.length) eval('var ' + utils[0] + ' = JSpec.' + utils.shift())
if (!main.setTimeout) main.setTimeout = function(callback){ callback() }
@@ -1672,7 +1792,7 @@
have_length_within : "actual.length >= expected[0] && actual.length <= last(expected)",
receive : { defer : true, match : function(actual, method, times) {
proxy = new JSpec.ProxyAssertion(actual, method, times, this.negate)
var proxy = new JSpec.ProxyAssertion(actual, method, times, this.negate)
JSpec.currentSpec.assertions.push(proxy)
return proxy
}},
@@ -1685,8 +1805,8 @@
},
include : function(actual) {
for (state = true, i = 1; i < arguments.length; i++) {
arg = arguments[i]
for (var state = true, i = 1; i < arguments.length; i++) {
var arg = arguments[i]
switch (actual.constructor) {
case String:
case Number:
@@ -1733,41 +1853,41 @@
case Function : return expected[i].name || 'Error'
}
}
exception = message_for(1) + (expected[2] ? ' and ' + message_for(2) : '')
var exception = message_for(1) + (expected[2] ? ' and ' + message_for(2) : '')
return 'expected ' + exception + (negate ? ' not ' : '' ) +
' to be thrown, but ' + (this.e ? 'got ' + puts(this.e) : 'nothing was')
}},
have : function(actual, length, property) {
return actual[property].length == length
return actual[property] == null ? false : actual[property].length == length
},
have_at_least : function(actual, length, property) {
return actual[property].length >= length
return actual[property] == null ? (length === 0) : actual[property].length >= length
},
have_at_most :function(actual, length, property) {
return actual[property].length <= length
return actual[property] == null || actual[property].length <= length
},
have_within : function(actual, range, property) {
length = actual[property].length
var length = actual[property] == undefined ? 0 : actual[property].length
return length >= range.shift() && length <= range.pop()
},
have_prop : function(actual, property, value) {
return actual[property] == null ||
actual[property] instanceof Function ? false:
value == null ? true:
does(actual[property], 'eql', value)
var actualVal = actual[property], actualType = typeof actualVal
return (actualType == 'function' || actualType == 'undefined') ? false :
typeof value === 'undefined' ||
does(actual[property],'eql',value)
},
have_property : function(actual, property, value) {
return actual[property] == null ||
actual[property] instanceof Function ? false:
value == null ? true:
value === actual[property]
var actualVal = actual[property], actualType = typeof actualVal
return (actualType == 'function' || actualType == 'undefined') ? false :
typeof value === 'undefined' ||
value === actualVal
}
})
})()
})()
+18
Ver Arquivo
@@ -0,0 +1,18 @@
// JSpec - node - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
JSpec
.include({
name: 'node',
// --- Matchers
matchers : {
have_enumerable_property: 'actual.propertyIsEnumerable(expected)',
have_writable_property: 'Object.getOwnPropertyDescriptor(actual, expected).writable === true',
have_configurable_property: 'Object.getOwnPropertyDescriptor(actual, expected).configurable === true',
have_keys: 'does(Object.keys(actual), "eql", expected)',
have_prototype: 'Object.getPrototypeOf(actual) === expected'
}
})

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais