diff --git a/node_modules/.bin/express b/node_modules/.bin/express deleted file mode 120000 index b741d99..0000000 --- a/node_modules/.bin/express +++ /dev/null @@ -1 +0,0 @@ -../express/bin/express \ No newline at end of file diff --git a/node_modules/.bin/jade b/node_modules/.bin/jade deleted file mode 120000 index 571fae7..0000000 --- a/node_modules/.bin/jade +++ /dev/null @@ -1 +0,0 @@ -../jade/bin/jade \ No newline at end of file diff --git a/node_modules/.bin/jshint b/node_modules/.bin/jshint deleted file mode 120000 index fca005f..0000000 --- a/node_modules/.bin/jshint +++ /dev/null @@ -1 +0,0 @@ -../jshint/bin/hint \ No newline at end of file diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha deleted file mode 120000 index 43c668d..0000000 --- a/node_modules/.bin/mocha +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/mocha \ No newline at end of file diff --git a/node_modules/.bin/mocha-debug b/node_modules/.bin/mocha-debug deleted file mode 120000 index 6564fc1..0000000 --- a/node_modules/.bin/mocha-debug +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/mocha-debug \ No newline at end of file diff --git a/node_modules/async/.gitmodules b/node_modules/async/.gitmodules deleted file mode 100644 index a9aae98..0000000 --- a/node_modules/async/.gitmodules +++ /dev/null @@ -1,9 +0,0 @@ -[submodule "deps/nodeunit"] - path = deps/nodeunit - url = git://github.com/caolan/nodeunit.git -[submodule "deps/UglifyJS"] - path = deps/UglifyJS - url = https://github.com/mishoo/UglifyJS.git -[submodule "deps/nodelint"] - path = deps/nodelint - url = https://github.com/tav/nodelint.git diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE deleted file mode 100644 index b7f9d50..0000000 --- a/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Caolan McMahon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/async/Makefile b/node_modules/async/Makefile deleted file mode 100644 index 00f07ea..0000000 --- a/node_modules/async/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -PACKAGE = asyncjs -NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) - -BUILDDIR = dist - -all: build - -build: $(wildcard lib/*.js) - mkdir -p $(BUILDDIR) - uglifyjs lib/async.js > $(BUILDDIR)/async.min.js - -test: - nodeunit test - -clean: - rm -rf $(BUILDDIR) - -lint: - nodelint --config nodelint.cfg lib/async.js - -.PHONY: test build all diff --git a/node_modules/async/README.md b/node_modules/async/README.md deleted file mode 100644 index f3c44ac..0000000 --- a/node_modules/async/README.md +++ /dev/null @@ -1,1009 +0,0 @@ -# Async.js - -Async is a utility module which provides straight-forward, powerful functions -for working with asynchronous JavaScript. Although originally designed for -use with [node.js](http://nodejs.org), it can also be used directly in the -browser. - -Async provides around 20 functions that include the usual 'functional' -suspects (map, reduce, filter, forEach…) as well as some common patterns -for asynchronous control flow (parallel, series, waterfall…). All these -functions assume you follow the node.js convention of providing a single -callback as the last argument of your async function. - - -## Quick Examples - - async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file - }); - - async.filter(['file1','file2','file3'], path.exists, function(results){ - // results now equals an array of the existing files - }); - - async.parallel([ - function(){ ... }, - function(){ ... } - ], callback); - - async.series([ - function(){ ... }, - function(){ ... } - ]); - -There are many more functions available so take a look at the docs below for a -full list. This module aims to be comprehensive, so if you feel anything is -missing please create a GitHub issue for it. - - -## Download - -Releases are available for download from -[GitHub](http://github.com/caolan/async/downloads). -Alternatively, you can install using Node Package Manager (npm): - - npm install async - - -__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 17.5kb Uncompressed - -__Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped - - -## In the Browser - -So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage: - - - - - -## Documentation - -### Collections - -* [forEach](#forEach) -* [map](#map) -* [filter](#filter) -* [reject](#reject) -* [reduce](#reduce) -* [detect](#detect) -* [sortBy](#sortBy) -* [some](#some) -* [every](#every) -* [concat](#concat) - -### Control Flow - -* [series](#series) -* [parallel](#parallel) -* [whilst](#whilst) -* [until](#until) -* [waterfall](#waterfall) -* [queue](#queue) -* [auto](#auto) -* [iterator](#iterator) -* [apply](#apply) -* [nextTick](#nextTick) - -### Utils - -* [memoize](#memoize) -* [unmemoize](#unmemoize) -* [log](#log) -* [dir](#dir) -* [noConflict](#noConflict) - - -## Collections - - -### forEach(arr, iterator, callback) - -Applies an iterator function to each item in an array, in parallel. -The iterator is called with an item from the list and a callback for when it -has finished. If the iterator passes an error to this callback, the main -callback for the forEach function is immediately called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - - // assuming openFiles is an array of file names and saveFile is a function - // to save the modified contents of that file: - - async.forEach(openFiles, saveFile, function(err){ - // if any of the saves produced an error, err would equal that error - }); - ---------------------------------------- - - -### forEachSeries(arr, iterator, callback) - -The same as forEach only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. This means the iterator functions will complete in order. - - ---------------------------------------- - - -### forEachLimit(arr, limit, iterator, callback) - -The same as forEach only the iterator is applied to batches of items in the -array, in series. The next batch of iterators is only called once the current -one has completed processing. - -__Arguments__ - -* arr - An array to iterate over. -* limit - How many items should be in each batch. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - - // Assume documents is an array of JSON objects and requestApi is a - // function that interacts with a rate-limited REST api. - - async.forEachLimit(documents, 20, requestApi, function(err){ - // if any of the saves produced an error, err would equal that error - }); ---------------------------------------- - - -### map(arr, iterator, callback) - -Produces a new array of values by mapping each value in the given array through -the iterator function. The iterator is called with an item from the array and a -callback for when it has finished processing. The callback takes 2 arguments, -an error and the transformed item from the array. If the iterator passes an -error to this callback, the main callback for the map function is immediately -called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order, however -the results array will be in the same order as the original array. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and a transformed item. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array of the - transformed items from the original array. - -__Example__ - - async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file - }); - ---------------------------------------- - - -### mapSeries(arr, iterator, callback) - -The same as map only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - - ---------------------------------------- - - -### filter(arr, iterator, callback) - -__Alias:__ select - -Returns a new array of all the values which pass an async truth test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. This operation is -performed in parallel, but the results array will be in the same order as the -original. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(results) - A callback which is called after all the iterator - functions have finished. - -__Example__ - - async.filter(['file1','file2','file3'], path.exists, function(results){ - // results now equals an array of the existing files - }); - ---------------------------------------- - - -### filterSeries(arr, iterator, callback) - -__alias:__ selectSeries - -The same as filter only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - ---------------------------------------- - - -### reject(arr, iterator, callback) - -The opposite of filter. Removes values that pass an async truth test. - ---------------------------------------- - - -### rejectSeries(arr, iterator, callback) - -The same as filter, only the iterator is applied to each item in the array -in series. - - ---------------------------------------- - - -### reduce(arr, memo, iterator, callback) - -__aliases:__ inject, foldl - -Reduces a list of values into a single value using an async iterator to return -each successive step. Memo is the initial state of the reduction. This -function only operates in series. For performance reasons, it may make sense to -split a call to this function into a parallel map, then use the normal -Array.prototype.reduce on the results. This function is for situations where -each step in the reduction needs to be async, if you can get the data before -reducing it then its probably a good idea to do so. - -__Arguments__ - -* arr - An array to iterate over. -* memo - The initial state of the reduction. -* iterator(memo, item, callback) - A function applied to each item in the - array to produce the next step in the reduction. The iterator is passed a - callback which accepts an optional error as its first argument, and the state - of the reduction as the second. If an error is passed to the callback, the - reduction is stopped and the main callback is immediately called with the - error. -* callback(err, result) - A callback which is called after all the iterator - functions have finished. Result is the reduced value. - -__Example__ - - async.reduce([1,2,3], 0, function(memo, item, callback){ - // pointless async: - process.nextTick(function(){ - callback(null, memo + item) - }); - }, function(err, result){ - // result is now equal to the last value of memo, which is 6 - }); - ---------------------------------------- - - -### reduceRight(arr, memo, iterator, callback) - -__Alias:__ foldr - -Same as reduce, only operates on the items in the array in reverse order. - - ---------------------------------------- - - -### detect(arr, iterator, callback) - -Returns the first value in a list that passes an async truth test. The -iterator is applied in parallel, meaning the first iterator to return true will -fire the detect callback with that result. That means the result might not be -the first item in the original array (in terms of order) that passes the test. - -If order within the original array is important then look at detectSeries. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - the first item in the array that passes the truth test (iterator) or the - value undefined if none passed. - -__Example__ - - async.detect(['file1','file2','file3'], path.exists, function(result){ - // result now equals the first file in the list that exists - }); - ---------------------------------------- - - -### detectSeries(arr, iterator, callback) - -The same as detect, only the iterator is applied to each item in the array -in series. This means the result is always the first in the original array (in -terms of array order) that passes the truth test. - - ---------------------------------------- - - -### sortBy(arr, iterator, callback) - -Sorts a list by the results of running each value through an async iterator. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and a value to use as the sort criteria. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is the items from - the original array sorted by the values returned by the iterator calls. - -__Example__ - - async.sortBy(['file1','file2','file3'], function(file, callback){ - fs.stat(file, function(err, stats){ - callback(err, stats.mtime); - }); - }, function(err, results){ - // results is now the original array of files sorted by - // modified date - }); - - ---------------------------------------- - - -### some(arr, iterator, callback) - -__Alias:__ any - -Returns true if at least one element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. Once any iterator -call returns true, the main callback is immediately called. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - either true or false depending on the values of the async tests. - -__Example__ - - async.some(['file1','file2','file3'], path.exists, function(result){ - // if result is true then at least one of the files exists - }); - ---------------------------------------- - - -### every(arr, iterator, callback) - -__Alias:__ all - -Returns true if every element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called after all the iterator - functions have finished. Result will be either true or false depending on - the values of the async tests. - -__Example__ - - async.every(['file1','file2','file3'], path.exists, function(result){ - // if result is true then every file exists - }); - ---------------------------------------- - - -### concat(arr, iterator, callback) - -Applies an iterator to each item in a list, concatenating the results. Returns the -concatenated list. The iterators are called in parallel, and the results are -concatenated as they return. There is no guarantee that the results array will -be returned in the original order of the arguments passed to the iterator function. - -__Arguments__ - -* arr - An array to iterate over -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and an array of results. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array containing - the concatenated results of the iterator function. - -__Example__ - - async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ - // files is now a list of filenames that exist in the 3 directories - }); - ---------------------------------------- - - -### concatSeries(arr, iterator, callback) - -Same as async.concat, but executes in series instead of parallel. - - -## Control Flow - - -### series(tasks, [callback]) - -Run an array of functions in series, each one running once the previous -function has completed. If any functions in the series pass an error to its -callback, no more functions are run and the callback for the series is -immediately called with the value of the error. Once the tasks have completed, -the results are passed to the final callback as an array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.series. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed - a callback it must call on completion. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets an array of all the arguments passed to - the callbacks used in the array. - -__Example__ - - async.series([ - function(callback){ - // do some stuff ... - callback(null, 'one'); - }, - function(callback){ - // do some more stuff ... - callback(null, 'two'); - }, - ], - // optional callback - function(err, results){ - // results is now equal to ['one', 'two'] - }); - - - // an example using an object instead of an array - async.series({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - }, - }, - function(err, results) { - // results is now equal to: {one: 1, two: 2} - }); - - ---------------------------------------- - - -### parallel(tasks, [callback]) - -Run an array of functions in parallel, without waiting until the previous -function has completed. If any of the functions pass an error to its -callback, the main callback is immediately called with the value of the error. -Once the tasks have completed, the results are passed to the final callback as an -array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.parallel. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed a - callback it must call on completion. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets an array of all the arguments passed to - the callbacks used in the array. - -__Example__ - - async.parallel([ - function(callback){ - setTimeout(function(){ - callback(null, 'one'); - }, 200); - }, - function(callback){ - setTimeout(function(){ - callback(null, 'two'); - }, 100); - }, - ], - // optional callback - function(err, results){ - // in this case, the results array will equal ['two','one'] - // because the functions were run in parallel and the second - // function had a shorter timeout before calling the callback. - }); - - - // an example using an object instead of an array - async.parallel({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - }, - }, - function(err, results) { - // results is now equals to: {one: 1, two: 2} - }); - - ---------------------------------------- - - -### whilst(test, fn, callback) - -Repeatedly call fn, while test returns true. Calls the callback when stopped, -or an error occurs. - -__Arguments__ - -* test() - synchronous truth test to perform before each execution of fn. -* fn(callback) - A function to call each time the test passes. The function is - passed a callback which must be called once it has completed with an optional - error as the first argument. -* callback(err) - A callback which is called after the test fails and repeated - execution of fn has stopped. - -__Example__ - - var count = 0; - - async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); - }, - function (err) { - // 5 seconds have passed - } - }); - - ---------------------------------------- - - -### until(test, fn, callback) - -Repeatedly call fn, until test returns true. Calls the callback when stopped, -or an error occurs. - -The inverse of async.whilst. - - ---------------------------------------- - - -### waterfall(tasks, [callback]) - -Runs an array of functions in series, each passing their results to the next in -the array. However, if any of the functions pass an error to the callback, the -next function is not executed and the main callback is immediately called with -the error. - -__Arguments__ - -* tasks - An array of functions to run, each function is passed a callback it - must call on completion. -* callback(err) - An optional callback to run once all the functions have - completed. This function gets passed any error that may have occurred. - -__Example__ - - async.waterfall([ - function(callback){ - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - callback(null, 'three'); - }, - function(arg1, callback){ - // arg1 now equals 'three' - callback(null, 'done'); - } - ]); - - ---------------------------------------- - - -### queue(worker, concurrency) - -Creates a queue object with the specified concurrency. Tasks added to the -queue will be processed in parallel (up to the concurrency limit). If all -workers are in progress, the task is queued until one is available. Once -a worker has completed a task, the task's callback is called. - -__Arguments__ - -* worker(task, callback) - An asynchronous function for processing a queued - task. -* concurrency - An integer for determining how many worker functions should be - run in parallel. - -__Queue objects__ - -The queue object returned by this function has the following properties and -methods: - -* length() - a function returning the number of items waiting to be processed. -* concurrency - an integer for determining how many worker functions should be - run in parallel. This property can be changed after a queue is created to - alter the concurrency on-the-fly. -* push(task, [callback]) - add a new task to the queue, the callback is called - once the worker has finished processing the task. -* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued -* empty - a callback that is called when the last item from the queue is given to a worker -* drain - a callback that is called when the last item from the queue has returned from the worker - -__Example__ - - // create a queue object with concurrency 2 - - var q = async.queue(function (task, callback) { - console.log('hello ' + task.name); - callback(); - }, 2); - - - // assign a callback - q.drain = function() { - console.log('all items have been processed'); - } - - // add some items to the queue - - q.push({name: 'foo'}, function (err) { - console.log('finished processing foo'); - }); - q.push({name: 'bar'}, function (err) { - console.log('finished processing bar'); - }); - - ---------------------------------------- - - -### auto(tasks, [callback]) - -Determines the best order for running functions based on their requirements. -Each function can optionally depend on other functions being completed first, -and each function is run as soon as its requirements are satisfied. If any of -the functions pass an error to their callback, that function will not complete -(so any other functions depending on it will not run) and the main callback -will be called immediately with the error. Functions also receive an object -containing the results of functions on which they depend. - -__Arguments__ - -* tasks - An object literal containing named functions or an array of - requirements, with the function itself the last item in the array. The key - used for each function or array is used when specifying requirements. The - syntax is easier to understand by looking at the example. -* callback(err) - An optional callback which is called when all the tasks have - been completed. The callback may receive an error as an argument. - -__Example__ - - async.auto({ - get_data: function(callback){ - // async code to get some data - }, - make_folder: function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - }, - write_file: ['get_data', 'make_folder', function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - callback(null, filename); - }], - email_link: ['write_file', function(callback, results){ - // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. - }] - }); - -This is a fairly trivial example, but to do this using the basic parallel and -series functions would look like this: - - async.parallel([ - function(callback){ - // async code to get some data - }, - function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - } - ], - function(results){ - async.series([ - function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - }, - email_link: ['write_file', function(callback){ - // once the file is written let's email a link to it... - } - ]); - }); - -For a complicated series of async tasks using the auto function makes adding -new tasks much easier and makes the code more readable. - - ---------------------------------------- - - -### iterator(tasks) - -Creates an iterator function which calls the next function in the array, -returning a continuation to call the next one after that. Its also possible to -'peek' the next iterator by doing iterator.next(). - -This function is used internally by the async module but can be useful when -you want to manually control the flow of functions in series. - -__Arguments__ - -* tasks - An array of functions to run, each function is passed a callback it - must call on completion. - -__Example__ - - var iterator = async.iterator([ - function(){ sys.p('one'); }, - function(){ sys.p('two'); }, - function(){ sys.p('three'); } - ]); - - node> var iterator2 = iterator(); - 'one' - node> var iterator3 = iterator2(); - 'two' - node> iterator3(); - 'three' - node> var nextfn = iterator2.next(); - node> nextfn(); - 'three' - - ---------------------------------------- - - -### apply(function, arguments..) - -Creates a continuation function with some arguments already applied, a useful -shorthand when combined with other control flow functions. Any arguments -passed to the returned function are added to the arguments originally passed -to apply. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to automatically apply when the - continuation is called. - -__Example__ - - // using apply - - async.parallel([ - async.apply(fs.writeFile, 'testfile1', 'test1'), - async.apply(fs.writeFile, 'testfile2', 'test2'), - ]); - - - // the same process without using apply - - async.parallel([ - function(callback){ - fs.writeFile('testfile1', 'test1', callback); - }, - function(callback){ - fs.writeFile('testfile2', 'test2', callback); - }, - ]); - -It's possible to pass any number of additional arguments when calling the -continuation: - - node> var fn = async.apply(sys.puts, 'one'); - node> fn('two', 'three'); - one - two - three - ---------------------------------------- - - -### nextTick(callback) - -Calls the callback on a later loop around the event loop. In node.js this just -calls process.nextTick, in the browser it falls back to setTimeout(callback, 0), -which means other higher priority events may precede the execution of the callback. - -This is used internally for browser-compatibility purposes. - -__Arguments__ - -* callback - The function to call on a later loop around the event loop. - -__Example__ - - var call_order = []; - async.nextTick(function(){ - call_order.push('two'); - // call_order now equals ['one','two] - }); - call_order.push('one') - - -## Utils - - -### memoize(fn, [hasher]) - -Caches the results of an async function. When creating a hash to store function -results against, the callback is omitted from the hash and an optional hash -function can be used. - -__Arguments__ - -* fn - the function you to proxy and cache results from. -* hasher - an optional function for generating a custom hash for storing - results, it has all the arguments applied to it apart from the callback, and - must be synchronous. - -__Example__ - - var slow_fn = function (name, callback) { - // do something - callback(null, result); - }; - var fn = async.memoize(slow_fn); - - // fn can now be used as if it were slow_fn - fn('some name', function () { - // callback - }); - - -### unmemoize(fn) - -Undoes a memoized function, reverting it to the original, unmemoized -form. Comes handy in tests. - -__Arguments__ - -* fn - the memoized function - - -### log(function, arguments) - -Logs the result of an async function to the console. Only works in node.js or -in browsers that support console.log and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.log is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - - var hello = function(name, callback){ - setTimeout(function(){ - callback(null, 'hello ' + name); - }, 1000); - }; - - node> async.log(hello, 'world'); - 'hello world' - - ---------------------------------------- - - -### dir(function, arguments) - -Logs the result of an async function to the console using console.dir to -display the properties of the resulting object. Only works in node.js or -in browsers that support console.dir and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.dir is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - - var hello = function(name, callback){ - setTimeout(function(){ - callback(null, {hello: name}); - }, 1000); - }; - - node> async.dir(hello, 'world'); - {hello: 'world'} - - ---------------------------------------- - - -### noConflict() - -Changes the value of async back to its original value, returning a reference to the -async object. diff --git a/node_modules/async/deps/nodeunit.css b/node_modules/async/deps/nodeunit.css deleted file mode 100644 index 274434a..0000000 --- a/node_modules/async/deps/nodeunit.css +++ /dev/null @@ -1,70 +0,0 @@ -/*! - * Styles taken from qunit.css - */ - -h1#nodeunit-header, h1.nodeunit-header { - padding: 15px; - font-size: large; - background-color: #06b; - color: white; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; -} - -h1#nodeunit-header a { - color: white; -} - -h2#nodeunit-banner { - height: 2em; - border-bottom: 1px solid white; - background-color: #eee; - margin: 0; - font-family: 'trebuchet ms', verdana, arial; -} -h2#nodeunit-banner.pass { - background-color: green; -} -h2#nodeunit-banner.fail { - background-color: red; -} - -h2#nodeunit-userAgent, h2.nodeunit-userAgent { - padding: 10px; - background-color: #eee; - color: black; - margin: 0; - font-size: small; - font-weight: normal; - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} - -div#nodeunit-testrunner-toolbar { - background: #eee; - border-top: 1px solid black; - padding: 10px; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; - font-size: 10pt; -} - -ol#nodeunit-tests { - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} -ol#nodeunit-tests li strong { - cursor:pointer; -} -ol#nodeunit-tests .pass { - color: green; -} -ol#nodeunit-tests .fail { - color: red; -} - -p#nodeunit-testresult { - margin-left: 1em; - font-size: 10pt; - font-family: 'trebuchet ms', verdana, arial; -} diff --git a/node_modules/async/deps/nodeunit.js b/node_modules/async/deps/nodeunit.js deleted file mode 100644 index 5957184..0000000 --- a/node_modules/async/deps/nodeunit.js +++ /dev/null @@ -1,1966 +0,0 @@ -/*! - * Nodeunit - * https://github.com/caolan/nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * json2.js - * http://www.JSON.org/json2.js - * Public Domain. - * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - */ -nodeunit = (function(){ -/* - http://www.JSON.org/json2.js - 2010-11-17 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, strict: false, regexp: false */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (!this.JSON) { - this.JSON = {}; -} - -(function () { - "use strict"; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) ? - this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? - '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : - '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 ? '[]' : - gap ? '[\n' + gap + - partial.join(',\n' + gap) + '\n' + - mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - k = rep[i]; - if (typeof k === 'string') { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 ? '{}' : - gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + - mind + '}' : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ -.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') -.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') -.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); -var assert = this.assert = {}; -var types = {}; -var core = {}; -var nodeunit = {}; -var reporter = {}; -/*global setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root = this, - previous_async = root.async; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - else { - root.async = async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - //// cross-browser compatiblity functions //// - - var _forEach = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _forEach(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _forEach(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - var _indexOf = function (arr, item) { - if (arr.indexOf) { - return arr.indexOf(item); - } - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === item) { - return i; - } - } - return -1; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - async.nextTick = function (fn) { - if (typeof process === 'undefined' || !(process.nextTick)) { - setTimeout(fn, 0); - } - else { - process.nextTick(fn); - } - }; - - async.forEach = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - _forEach(arr, function (x) { - iterator(x, function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - } - }); - }); - }; - - async.forEachSeries = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEach].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.forEachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var completed = []; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (completed.length === keys.length) { - callback(null); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - completed.push(k); - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && _indexOf(completed, x) !== -1); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var tasks = []; - var q = { - concurrency: concurrency, - push: function (data, callback) { - tasks.push({data: data, callback: callback}); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && tasks.length) { - var task = tasks.splice(0, 1)[0]; - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - q.process(); - }); - } - }, - length: function () { - return tasks.length; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - -}()); -(function(exports){ -/** - * This file is based on the node.js assert module, but with some small - * changes for browser-compatibility - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - */ - - -/** - * Added for browser compatibility - */ - -var _keys = function(obj){ - if(Object.keys) return Object.keys(obj); - var keys = []; - for(var k in obj){ - if(obj.hasOwnProperty(k)) keys.push(k); - } - return keys; -}; - - - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = exports; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({message: message, actual: actual, expected: expected}) - -assert.AssertionError = function AssertionError (options) { - this.name = "AssertionError"; - this.message = options.message; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } -}; -// code from util.inherits in node -assert.AssertionError.super_ = Error; - - -// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call -// TODO: test what effect this may have -var ctor = function () { this.constructor = assert.AssertionError; }; -ctor.prototype = Error.prototype; -assert.AssertionError.prototype = new ctor(); - - -assert.AssertionError.prototype.toString = function() { - if (this.message) { - return [this.name+":", this.message].join(' '); - } else { - return [ this.name+":" - , JSON.stringify(this.expected ) - , this.operator - , JSON.stringify(this.actual) - ].join(" "); - } -}; - -// assert.AssertionError instanceof Error - -assert.AssertionError.__proto__ = Error.prototype; - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -assert.ok = function ok(value, message) { - if (!!!value) fail(value, true, message, "==", assert.ok); -}; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, "==", assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, "!=", assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, "deepEqual", assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = _keys(a), - kb = _keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key] )) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, "===", assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as determined by !==. -// assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, "!==", assert.notStrictEqual); - } -}; - -function _throws (shouldThrow, block, err, message) { - var exception = null, - threw = false, - typematters = true; - - message = message || ""; - - //handle optional arguments - if (arguments.length == 3) { - if (typeof(err) == "string") { - message = err; - typematters = false; - } - } else if (arguments.length == 2) { - typematters = false; - } - - try { - block(); - } catch (e) { - threw = true; - exception = e; - } - - if (shouldThrow && !threw) { - fail( "Missing expected exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if (!shouldThrow && threw && typematters && exception instanceof err) { - fail( "Got unwanted exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if ((shouldThrow && threw && typematters && !(exception instanceof err)) || - (!shouldThrow && threw)) { - throw exception; - } -}; - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function (err) { if (err) {throw err;}}; -})(assert); -(function(exports){ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - - - -/** - * Creates assertion objects representing the result of an assert call. - * Accepts an object or AssertionError as its argument. - * - * @param {object} obj - * @api public - */ - -exports.assertion = function (obj) { - return { - method: obj.method || '', - message: obj.message || (obj.error && obj.error.message) || '', - error: obj.error, - passed: function () { - return !this.error; - }, - failed: function () { - return Boolean(this.error); - } - }; -}; - -/** - * Creates an assertion list object representing a group of assertions. - * Accepts an array of assertion objects. - * - * @param {Array} arr - * @param {Number} duration - * @api public - */ - -exports.assertionList = function (arr, duration) { - var that = arr || []; - that.failures = function () { - var failures = 0; - for (var i=0; i(' + - '' + assertions.failures() + ', ' + - '' + assertions.passes() + ', ' + - assertions.length + - ')'; - test.className = assertions.failures() ? 'fail': 'pass'; - test.appendChild(strong); - - var aList = document.createElement('ol'); - aList.style.display = 'none'; - test.onclick = function () { - var d = aList.style.display; - aList.style.display = (d == 'none') ? 'block': 'none'; - }; - for (var i=0; i' + (a.error.stack || a.error) + ''; - li.className = 'fail'; - } - else { - li.innerHTML = a.message || a.method || 'no message'; - li.className = 'pass'; - } - aList.appendChild(li); - } - test.appendChild(aList); - tests.appendChild(test); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - - var failures = assertions.failures(); - banner.className = failures ? 'fail': 'pass'; - - result.innerHTML = 'Tests completed in ' + duration + - ' milliseconds.
' + - assertions.passes() + ' assertions of ' + - '' + assertions.length + ' passed, ' + - assertions.failures() + ' failed.'; - } - }); -}; -})(reporter); -nodeunit = core; -nodeunit.assert = assert; -nodeunit.reporter = reporter; -nodeunit.run = reporter.run; -return nodeunit; })(); diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js deleted file mode 100644 index e4c898b..0000000 --- a/node_modules/async/dist/async.min.js +++ /dev/null @@ -1 +0,0 @@ -/*global setTimeout: false, console: false */(function(){var a={},b=this,c=b.async;typeof module!="undefined"&&module.exports?module.exports=a:b.async=a,a.noConflict=function(){return b.async=c,a};var d=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;cd?1:0};d(null,e(b.sort(c),function(a){return a.value}))})},a.auto=function(a,b){b=b||function(){};var c=g(a);if(!c.length)return b(null);var e={},h=[],i=function(a){h.unshift(a)},j=function(a){for(var b=0;b b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - q.tasks.push({data: data, callback: callback}); - if(q.saturated && q.tasks.length == concurrency) q.saturated(); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if(q.empty && q.tasks.length == 0) q.empty(); - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if(q.drain && q.tasks.length + workers == 0) q.drain(); - q.process(); - }); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - } - }; - -}()); diff --git a/node_modules/async/nodelint.cfg b/node_modules/async/nodelint.cfg deleted file mode 100644 index 457a967..0000000 --- a/node_modules/async/nodelint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -var options = { - indent: 4, - onevar: false -}; diff --git a/node_modules/async/package.json b/node_modules/async/package.json deleted file mode 100644 index 6198943..0000000 --- a/node_modules/async/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ "name": "async" -, "description": "Higher-order functions and common patterns for asynchronous code" -, "main": "./index" -, "author": "Caolan McMahon" -, "version": "0.1.15" -, "repository" : - { "type" : "git" - , "url" : "http://github.com/caolan/async.git" - } -, "bugs" : { "url" : "http://github.com/caolan/async/issues" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/caolan/async/raw/master/LICENSE" - } - ] -} diff --git a/node_modules/async/test/test-async.js b/node_modules/async/test/test-async.js deleted file mode 100644 index d3eeddc..0000000 --- a/node_modules/async/test/test-async.js +++ /dev/null @@ -1,1577 +0,0 @@ -var async = require('../lib/async'); - - -exports['auto'] = function(test){ - var callOrder = []; - var testdata = [{test: 'test'}]; - async.auto({ - task1: ['task2', function(callback){ - setTimeout(function(){ - callOrder.push('task1'); - callback(); - }, 25); - }], - task2: function(callback){ - setTimeout(function(){ - callOrder.push('task2'); - callback(); - }, 50); - }, - task3: ['task2', function(callback){ - callOrder.push('task3'); - callback(); - }], - task4: ['task1', 'task2', function(callback){ - callOrder.push('task4'); - callback(); - }] - }, - function(err){ - test.same(callOrder, ['task2','task3','task1','task4']); - test.done(); - }); -}; - -exports['auto results'] = function(test){ - var callOrder = []; - async.auto({ - task1: ['task2', function(callback, results){ - test.same(results.task2, 'task2'); - setTimeout(function(){ - callOrder.push('task1'); - callback(null, 'task1a', 'task1b'); - }, 25); - }], - task2: function(callback){ - setTimeout(function(){ - callOrder.push('task2'); - callback(null, 'task2'); - }, 50); - }, - task3: ['task2', function(callback, results){ - test.same(results.task2, 'task2'); - callOrder.push('task3'); - callback(null); - }], - task4: ['task1', 'task2', function(callback, results){ - test.same(results.task1, ['task1a','task1b']); - test.same(results.task2, 'task2'); - callOrder.push('task4'); - callback(null, 'task4'); - }] - }, - function(err, results){ - test.same(callOrder, ['task2','task3','task1','task4']); - test.same(results, {task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'}); - test.done(); - }); -}; - - -exports['auto empty object'] = function(test){ - async.auto({}, function(err){ - test.done(); - }); -}; - -exports['auto error'] = function(test){ - test.expect(1); - async.auto({ - task1: function(callback){ - callback('testerror'); - }, - task2: ['task1', function(callback){ - test.ok(false, 'task2 should not be called'); - callback(); - }], - task3: function(callback){ - callback('testerror2'); - } - }, - function(err){ - test.equals(err, 'testerror'); - }); - setTimeout(test.done, 100); -}; - -exports['auto no callback'] = function(test){ - async.auto({ - task1: function(callback){callback();}, - task2: ['task1', function(callback){callback(); test.done();}] - }); -}; - -exports['waterfall'] = function(test){ - test.expect(6); - var call_order = []; - async.waterfall([ - function(callback){ - call_order.push('fn1'); - setTimeout(function(){callback(null, 'one', 'two');}, 0); - }, - function(arg1, arg2, callback){ - call_order.push('fn2'); - test.equals(arg1, 'one'); - test.equals(arg2, 'two'); - setTimeout(function(){callback(null, arg1, arg2, 'three');}, 25); - }, - function(arg1, arg2, arg3, callback){ - call_order.push('fn3'); - test.equals(arg1, 'one'); - test.equals(arg2, 'two'); - test.equals(arg3, 'three'); - callback(null, 'four'); - }, - function(arg4, callback){ - call_order.push('fn4'); - test.same(call_order, ['fn1','fn2','fn3','fn4']); - callback(null, 'test'); - } - ], function(err){ - test.done(); - }); -}; - -exports['waterfall empty array'] = function(test){ - async.waterfall([], function(err){ - test.done(); - }); -}; - -exports['waterfall no callback'] = function(test){ - async.waterfall([ - function(callback){callback();}, - function(callback){callback(); test.done();} - ]); -}; - -exports['waterfall async'] = function(test){ - var call_order = []; - async.waterfall([ - function(callback){ - call_order.push(1); - callback(); - call_order.push(2); - }, - function(callback){ - call_order.push(3); - callback(); - }, - function(){ - test.same(call_order, [1,2,3]); - test.done(); - } - ]); -}; - -exports['waterfall error'] = function(test){ - test.expect(1); - async.waterfall([ - function(callback){ - callback('error'); - }, - function(callback){ - test.ok(false, 'next function should not be called'); - callback(); - } - ], function(err){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['waterfall multiple callback calls'] = function(test){ - var call_order = []; - var arr = [ - function(callback){ - call_order.push(1); - // call the callback twice. this should call function 2 twice - callback(null, 'one', 'two'); - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - call_order.push(2); - callback(null, arg1, arg2, 'three'); - }, - function(arg1, arg2, arg3, callback){ - call_order.push(3); - callback(null, 'four'); - }, - function(arg4){ - call_order.push(4); - arr[3] = function(){ - call_order.push(4); - test.same(call_order, [1,2,2,3,3,4,4]); - test.done(); - }; - } - ]; - async.waterfall(arr); -}; - - -exports['parallel'] = function(test){ - var call_order = []; - async.parallel([ - function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 50); - }, - function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 100); - }, - function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 25); - } - ], - function(err, results){ - test.equals(err, null); - test.same(call_order, [3,1,2]); - test.same(results, [1,2,[3,3]]); - test.done(); - }); -}; - -exports['parallel empty array'] = function(test){ - async.parallel([], function(err, results){ - test.equals(err, null); - test.same(results, []); - test.done(); - }); -}; - -exports['parallel error'] = function(test){ - async.parallel([ - function(callback){ - callback('error', 1); - }, - function(callback){ - callback('error2', 2); - } - ], - function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 100); -}; - -exports['parallel no callback'] = function(test){ - async.parallel([ - function(callback){callback();}, - function(callback){callback(); test.done();}, - ]); -}; - -exports['parallel object'] = function(test){ - var call_order = []; - async.parallel({ - one: function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - two: function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - three: function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - }, - function(err, results){ - test.equals(err, null); - test.same(call_order, [3,1,2]); - test.same(results, { - one: 1, - two: 2, - three: [3,3] - }); - test.done(); - }); -}; - -exports['series'] = function(test){ - var call_order = []; - async.series([ - function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - ], - function(err, results){ - test.equals(err, null); - test.same(results, [1,2,[3,3]]); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['series empty array'] = function(test){ - async.series([], function(err, results){ - test.equals(err, null); - test.same(results, []); - test.done(); - }); -}; - -exports['series error'] = function(test){ - test.expect(1); - async.series([ - function(callback){ - callback('error', 1); - }, - function(callback){ - test.ok(false, 'should not be called'); - callback('error2', 2); - } - ], - function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 100); -}; - -exports['series no callback'] = function(test){ - async.series([ - function(callback){callback();}, - function(callback){callback(); test.done();}, - ]); -}; - -exports['series object'] = function(test){ - var call_order = []; - async.series({ - one: function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - two: function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - three: function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - }, - function(err, results){ - test.equals(err, null); - test.same(results, { - one: 1, - two: 2, - three: [3,3] - }); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['iterator'] = function(test){ - var call_order = []; - var iterator = async.iterator([ - function(){call_order.push(1);}, - function(arg1){ - test.equals(arg1, 'arg1'); - call_order.push(2); - }, - function(arg1, arg2){ - test.equals(arg1, 'arg1'); - test.equals(arg2, 'arg2'); - call_order.push(3); - } - ]); - iterator(); - test.same(call_order, [1]); - var iterator2 = iterator(); - test.same(call_order, [1,1]); - var iterator3 = iterator2('arg1'); - test.same(call_order, [1,1,2]); - var iterator4 = iterator3('arg1', 'arg2'); - test.same(call_order, [1,1,2,3]); - test.equals(iterator4, undefined); - test.done(); -}; - -exports['iterator empty array'] = function(test){ - var iterator = async.iterator([]); - test.equals(iterator(), undefined); - test.equals(iterator.next(), undefined); - test.done(); -}; - -exports['iterator.next'] = function(test){ - var call_order = []; - var iterator = async.iterator([ - function(){call_order.push(1);}, - function(arg1){ - test.equals(arg1, 'arg1'); - call_order.push(2); - }, - function(arg1, arg2){ - test.equals(arg1, 'arg1'); - test.equals(arg2, 'arg2'); - call_order.push(3); - } - ]); - var fn = iterator.next(); - var iterator2 = fn('arg1'); - test.same(call_order, [2]); - iterator2('arg1','arg2'); - test.same(call_order, [2,3]); - test.equals(iterator2.next(), undefined); - test.done(); -}; - -exports['forEach'] = function(test){ - var args = []; - async.forEach([1,3,2], function(x, callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, [1,2,3]); - test.done(); - }); -}; - -exports['forEach empty array'] = function(test){ - test.expect(1); - async.forEach([], function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEach error'] = function(test){ - test.expect(1); - async.forEach([1,2,3], function(x, callback){ - callback('error'); - }, function(err){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['forEachSeries'] = function(test){ - var args = []; - async.forEachSeries([1,3,2], function(x, callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, [1,3,2]); - test.done(); - }); -}; - -exports['forEachSeries empty array'] = function(test){ - test.expect(1); - async.forEachSeries([], function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachSeries error'] = function(test){ - test.expect(2); - var call_order = []; - async.forEachSeries([1,2,3], function(x, callback){ - call_order.push(x); - callback('error'); - }, function(err){ - test.same(call_order, [1]); - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['forEachLimit'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 2, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*5); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit empty array'] = function(test){ - test.expect(1); - async.forEachLimit([], 2, function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachLimit limit exceeds size'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 20, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*5); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit limit equal size'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 10, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*5); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit zero limit'] = function(test){ - test.expect(1); - async.forEachLimit([0,1,2,3,4,5], 0, function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachLimit error'] = function(test){ - test.expect(2); - var arr = [0,1,2,3,4,5,6,7,8,9]; - var call_order = []; - - async.forEachLimit(arr, 3, function(x, callback){ - call_order.push(x); - if (x === 2) { - callback('error'); - } - }, function(err){ - test.same(call_order, [0,1,2]); - test.equals(err, 'error'); - }); - setTimeout(test.done, 25); -}; - -exports['map'] = function(test){ - var call_order = []; - async.map([1,3,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(null, x*2); - }, x*25); - }, function(err, results){ - test.same(call_order, [1,2,3]); - test.same(results, [2,6,4]); - test.done(); - }); -}; - -exports['map original untouched'] = function(test){ - var a = [1,2,3]; - async.map(a, function(x, callback){ - callback(null, x*2); - }, function(err, results){ - test.same(results, [2,4,6]); - test.same(a, [1,2,3]); - test.done(); - }); -}; - -exports['map error'] = function(test){ - test.expect(1); - async.map([1,2,3], function(x, callback){ - callback('error'); - }, function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['mapSeries'] = function(test){ - var call_order = []; - async.mapSeries([1,3,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(null, x*2); - }, x*25); - }, function(err, results){ - test.same(call_order, [1,3,2]); - test.same(results, [2,6,4]); - test.done(); - }); -}; - -exports['mapSeries error'] = function(test){ - test.expect(1); - async.mapSeries([1,2,3], function(x, callback){ - callback('error'); - }, function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['reduce'] = function(test){ - var call_order = []; - async.reduce([1,2,3], 0, function(a, x, callback){ - call_order.push(x); - callback(null, a + x); - }, function(err, result){ - test.equals(result, 6); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['reduce async with non-reference memo'] = function(test){ - async.reduce([1,3,2], 0, function(a, x, callback){ - setTimeout(function(){callback(null, a + x)}, Math.random()*100); - }, function(err, result){ - test.equals(result, 6); - test.done(); - }); -}; - -exports['reduce error'] = function(test){ - test.expect(1); - async.reduce([1,2,3], 0, function(a, x, callback){ - callback('error'); - }, function(err, result){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['inject alias'] = function(test){ - test.equals(async.inject, async.reduce); - test.done(); -}; - -exports['foldl alias'] = function(test){ - test.equals(async.foldl, async.reduce); - test.done(); -}; - -exports['reduceRight'] = function(test){ - var call_order = []; - var a = [1,2,3]; - async.reduceRight(a, 0, function(a, x, callback){ - call_order.push(x); - callback(null, a + x); - }, function(err, result){ - test.equals(result, 6); - test.same(call_order, [3,2,1]); - test.same(a, [1,2,3]); - test.done(); - }); -}; - -exports['foldr alias'] = function(test){ - test.equals(async.foldr, async.reduceRight); - test.done(); -}; - -exports['filter'] = function(test){ - async.filter([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [3,1]); - test.done(); - }); -}; - -exports['filter original untouched'] = function(test){ - var a = [3,1,2]; - async.filter(a, function(x, callback){ - callback(x % 2); - }, function(results){ - test.same(results, [3,1]); - test.same(a, [3,1,2]); - test.done(); - }); -}; - -exports['filterSeries'] = function(test){ - async.filterSeries([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [3,1]); - test.done(); - }); -}; - -exports['select alias'] = function(test){ - test.equals(async.select, async.filter); - test.done(); -}; - -exports['selectSeries alias'] = function(test){ - test.equals(async.selectSeries, async.filterSeries); - test.done(); -}; - -exports['reject'] = function(test){ - async.reject([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [2]); - test.done(); - }); -}; - -exports['reject original untouched'] = function(test){ - var a = [3,1,2]; - async.reject(a, function(x, callback){ - callback(x % 2); - }, function(results){ - test.same(results, [2]); - test.same(a, [3,1,2]); - test.done(); - }); -}; - -exports['rejectSeries'] = function(test){ - async.rejectSeries([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [2]); - test.done(); - }); -}; - -exports['some true'] = function(test){ - async.some([3,1,2], function(x, callback){ - setTimeout(function(){callback(x === 1);}, 0); - }, function(result){ - test.equals(result, true); - test.done(); - }); -}; - -exports['some false'] = function(test){ - async.some([3,1,2], function(x, callback){ - setTimeout(function(){callback(x === 10);}, 0); - }, function(result){ - test.equals(result, false); - test.done(); - }); -}; - -exports['some early return'] = function(test){ - var call_order = []; - async.some([1,2,3], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x === 1); - }, x*25); - }, function(result){ - call_order.push('callback'); - }); - setTimeout(function(){ - test.same(call_order, [1,'callback',2,3]); - test.done(); - }, 100); -}; - -exports['any alias'] = function(test){ - test.equals(async.any, async.some); - test.done(); -}; - -exports['every true'] = function(test){ - async.every([1,2,3], function(x, callback){ - setTimeout(function(){callback(true);}, 0); - }, function(result){ - test.equals(result, true); - test.done(); - }); -}; - -exports['every false'] = function(test){ - async.every([1,2,3], function(x, callback){ - setTimeout(function(){callback(x % 2);}, 0); - }, function(result){ - test.equals(result, false); - test.done(); - }); -}; - -exports['every early return'] = function(test){ - var call_order = []; - async.every([1,2,3], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x === 1); - }, x*25); - }, function(result){ - call_order.push('callback'); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',3]); - test.done(); - }, 100); -}; - -exports['all alias'] = function(test){ - test.equals(async.all, async.every); - test.done(); -}; - -exports['detect'] = function(test){ - var call_order = []; - async.detect([3,2,1], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',3]); - test.done(); - }, 100); -}; - -exports['detect - mulitple matches'] = function(test){ - var call_order = []; - async.detect([3,2,2,1,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',2,2,3]); - test.done(); - }, 100); -}; - -exports['detectSeries'] = function(test){ - var call_order = []; - async.detectSeries([3,2,1], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [3,2,'callback']); - test.done(); - }, 200); -}; - -exports['detectSeries - multiple matches'] = function(test){ - var call_order = []; - async.detectSeries([3,2,2,1,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [3,2,'callback']); - test.done(); - }, 200); -}; - -exports['sortBy'] = function(test){ - async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){ - setTimeout(function(){callback(null, x.a);}, 0); - }, function(err, result){ - test.same(result, [{a:1},{a:6},{a:15}]); - test.done(); - }); -}; - -exports['apply'] = function(test){ - test.expect(6); - var fn = function(){ - test.same(Array.prototype.slice.call(arguments), [1,2,3,4]) - }; - async.apply(fn, 1, 2, 3, 4)(); - async.apply(fn, 1, 2, 3)(4); - async.apply(fn, 1, 2)(3, 4); - async.apply(fn, 1)(2, 3, 4); - async.apply(fn)(1, 2, 3, 4); - test.equals( - async.apply(function(name){return 'hello ' + name}, 'world')(), - 'hello world' - ); - test.done(); -}; - - -// generates tests for console functions such as async.log -var console_fn_tests = function(name){ - - if (typeof console !== 'undefined') { - exports[name] = function(test){ - test.expect(5); - var fn = function(arg1, callback){ - test.equals(arg1, 'one'); - setTimeout(function(){callback(null, 'test');}, 0); - }; - var fn_err = function(arg1, callback){ - test.equals(arg1, 'one'); - setTimeout(function(){callback('error');}, 0); - }; - var _console_fn = console[name]; - var _error = console.error; - console[name] = function(val){ - test.equals(val, 'test'); - test.equals(arguments.length, 1); - console.error = function(val){ - test.equals(val, 'error'); - console[name] = _console_fn; - console.error = _error; - test.done(); - }; - async[name](fn_err, 'one'); - }; - async[name](fn, 'one'); - }; - - exports[name + ' with multiple result params'] = function(test){ - var fn = function(callback){callback(null,'one','two','three');}; - var _console_fn = console[name]; - var called_with = []; - console[name] = function(x){ - called_with.push(x); - }; - async[name](fn); - test.same(called_with, ['one','two','three']); - console[name] = _console_fn; - test.done(); - }; - } - - // browser-only test - exports[name + ' without console.' + name] = function(test){ - if (typeof window !== 'undefined') { - var _console = window.console; - window.console = undefined; - var fn = function(callback){callback(null, 'val');}; - var fn_err = function(callback){callback('error');}; - async[name](fn); - async[name](fn_err); - window.console = _console; - } - test.done(); - }; - -}; - -console_fn_tests('log'); -console_fn_tests('dir'); -/*console_fn_tests('info'); -console_fn_tests('warn'); -console_fn_tests('error');*/ - -exports['nextTick'] = function(test){ - var call_order = []; - async.nextTick(function(){call_order.push('two');}); - call_order.push('one'); - setTimeout(function(){ - test.same(call_order, ['one','two']); - test.done(); - }, 50); -}; - -exports['nextTick in the browser'] = function(test){ - if (typeof process !== 'undefined') { - // skip this test in node - return test.done(); - } - test.expect(1); - - var call_order = []; - async.nextTick(function(){call_order.push('two');}); - - call_order.push('one'); - setTimeout(function(){ - if (typeof process !== 'undefined') { - process.nextTick = _nextTick; - } - test.same(call_order, ['one','two']); - }, 50); - setTimeout(test.done, 100); -}; - -exports['noConflict - node only'] = function(test){ - if (typeof process !== 'undefined') { - // node only test - test.expect(3); - var fs = require('fs'); - var filename = __dirname + '/../lib/async.js'; - fs.readFile(filename, function(err, content){ - if(err) return test.done(); - var Script = process.binding('evals').Script; - - var s = new Script(content, filename); - var s2 = new Script( - content + 'this.async2 = this.async.noConflict();', - filename - ); - - var sandbox1 = {async: 'oldvalue'}; - s.runInNewContext(sandbox1); - test.ok(sandbox1.async); - - var sandbox2 = {async: 'oldvalue'}; - s2.runInNewContext(sandbox2); - test.equals(sandbox2.async, 'oldvalue'); - test.ok(sandbox2.async2); - - test.done(); - }); - } - else test.done(); -}; - -exports['concat'] = function(test){ - var call_order = []; - var iterator = function (x, cb) { - setTimeout(function(){ - call_order.push(x); - var r = []; - while (x > 0) { - r.push(x); - x--; - } - cb(null, r); - }, x*25); - }; - async.concat([1,3,2], iterator, function(err, results){ - test.same(results, [1,2,1,3,2,1]); - test.same(call_order, [1,2,3]); - test.ok(!err); - test.done(); - }); -}; - -exports['concat error'] = function(test){ - var iterator = function (x, cb) { - cb(new Error('test error')); - }; - async.concat([1,2,3], iterator, function(err, results){ - test.ok(err); - test.done(); - }); -}; - -exports['concatSeries'] = function(test){ - var call_order = []; - var iterator = function (x, cb) { - setTimeout(function(){ - call_order.push(x); - var r = []; - while (x > 0) { - r.push(x); - x--; - } - cb(null, r); - }, x*25); - }; - async.concatSeries([1,3,2], iterator, function(err, results){ - test.same(results, [1,3,2,1,2,1]); - test.same(call_order, [1,3,2]); - test.ok(!err); - test.done(); - }); -}; - -exports['until'] = function (test) { - var call_order = []; - - var count = 0; - async.until( - function () { - call_order.push(['test', count]); - return (count == 5); - }, - function (cb) { - call_order.push(['iterator', count]); - count++; - cb(); - }, - function (err) { - test.same(call_order, [ - ['test', 0], - ['iterator', 0], ['test', 1], - ['iterator', 1], ['test', 2], - ['iterator', 2], ['test', 3], - ['iterator', 3], ['test', 4], - ['iterator', 4], ['test', 5], - ]); - test.equals(count, 5); - test.done(); - } - ); -}; - -exports['whilst'] = function (test) { - var call_order = []; - - var count = 0; - async.whilst( - function () { - call_order.push(['test', count]); - return (count < 5); - }, - function (cb) { - call_order.push(['iterator', count]); - count++; - cb(); - }, - function (err) { - test.same(call_order, [ - ['test', 0], - ['iterator', 0], ['test', 1], - ['iterator', 1], ['test', 2], - ['iterator', 2], ['test', 3], - ['iterator', 3], ['test', 4], - ['iterator', 4], ['test', 5], - ]); - test.equals(count, 5); - test.done(); - } - ); -}; - -exports['queue'] = function (test) { - var call_order = [], - delays = [40,20,60,20]; - - // worker1: --1-4 - // worker2: -2---3 - // order of completion: 2,1,4,3 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 1); - call_order.push('callback ' + 1); - }); - q.push(2, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 2); - call_order.push('callback ' + 2); - }); - q.push(3, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 3); - }); - q.push(4, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 4); - }); - test.equal(q.length(), 4); - test.equal(q.concurrency, 2); - - setTimeout(function () { - test.same(call_order, [ - 'process 2', 'callback 2', - 'process 1', 'callback 1', - 'process 4', 'callback 4', - 'process 3', 'callback 3' - ]); - test.equal(q.concurrency, 2); - test.equal(q.length(), 0); - test.done(); - }, 200); -}; - -exports['queue changing concurrency'] = function (test) { - var call_order = [], - delays = [40,20,60,20]; - - // worker1: --1-2---3-4 - // order of completion: 1,2,3,4 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 3); - call_order.push('callback ' + 1); - }); - q.push(2, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 2); - call_order.push('callback ' + 2); - }); - q.push(3, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 1); - call_order.push('callback ' + 3); - }); - q.push(4, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 4); - }); - test.equal(q.length(), 4); - test.equal(q.concurrency, 2); - q.concurrency = 1; - - setTimeout(function () { - test.same(call_order, [ - 'process 1', 'callback 1', - 'process 2', 'callback 2', - 'process 3', 'callback 3', - 'process 4', 'callback 4' - ]); - test.equal(q.concurrency, 1); - test.equal(q.length(), 0); - test.done(); - }, 250); -}; - -exports['queue push without callback'] = function (test) { - var call_order = [], - delays = [40,20,60,20]; - - // worker1: --1-4 - // worker2: -2---3 - // order of completion: 2,1,4,3 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1); - q.push(2); - q.push(3); - q.push(4); - - setTimeout(function () { - test.same(call_order, [ - 'process 2', - 'process 1', - 'process 4', - 'process 3' - ]); - test.done(); - }, 200); -}; - -exports['memoize'] = function (test) { - test.expect(4); - var call_order = []; - - var fn = function (arg1, arg2, callback) { - call_order.push(['fn', arg1, arg2]); - callback(null, arg1 + arg2); - }; - - var fn2 = async.memoize(fn); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(2, 2, function (err, result) { - test.equal(result, 4); - }); - - test.same(call_order, [['fn',1,2], ['fn',2,2]]); - test.done(); -}; - -exports['unmemoize'] = function(test) { - test.expect(4); - var call_order = []; - - var fn = function (arg1, arg2, callback) { - call_order.push(['fn', arg1, arg2]); - callback(null, arg1 + arg2); - }; - - var fn2 = async.memoize(fn); - var fn3 = async.unmemoize(fn2); - fn3(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn3(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn3(2, 2, function (err, result) { - test.equal(result, 4); - }); - - test.same(call_order, [['fn',1,2], ['fn',1,2], ['fn',2,2]]); - - test.done(); -} - -exports['unmemoize a not memoized function'] = function(test) { - test.expect(1); - - var fn = function (arg1, arg2, callback) { - callback(null, arg1 + arg2); - }; - - var fn2 = async.unmemoize(fn); - fn2(1, 2, function(err, result) { - test.equal(result, 3); - }); - - test.done(); -} - -exports['memoize error'] = function (test) { - test.expect(1); - var testerr = new Error('test'); - var fn = function (arg1, arg2, callback) { - callback(testerr, arg1 + arg2); - }; - async.memoize(fn)(1, 2, function (err, result) { - test.equal(err, testerr); - }); - test.done(); -}; - -exports['memoize multiple calls'] = function (test) { - test.expect(3); - var fn = function (arg1, arg2, callback) { - test.ok(true); - setTimeout(function(){ - callback(null, arg1, arg2); - }, 10); - }; - var fn2 = async.memoize(fn); - fn2(1, 2, function(err, result) { - test.equal(result, 1, 2); - }); - fn2(1, 2, function(err, result) { - test.equal(result, 1, 2); - test.done(); - }); -}; - -exports['memoize custom hash function'] = function (test) { - test.expect(2); - var testerr = new Error('test'); - - var fn = function (arg1, arg2, callback) { - callback(testerr, arg1 + arg2); - }; - var fn2 = async.memoize(fn, function () { - return 'custom hash'; - }); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(2, 2, function (err, result) { - test.equal(result, 3); - }); - test.done(); -}; - -// Issue 10 on github: https://github.com/caolan/async/issues#issue/10 -exports['falsy return values in series'] = function (test) { - function taskFalse(callback) { - async.nextTick(function() { - callback(null, false); - }); - }; - function taskUndefined(callback) { - async.nextTick(function() { - callback(null, undefined); - }); - }; - function taskEmpty(callback) { - async.nextTick(function() { - callback(null); - }); - }; - function taskNull(callback) { - async.nextTick(function() { - callback(null, null); - }); - }; - async.series( - [taskFalse, taskUndefined, taskEmpty, taskNull], - function(err, results) { - test.equal(results.length, 4); - test.strictEqual(results[0], false); - test.strictEqual(results[1], undefined); - test.strictEqual(results[2], undefined); - test.strictEqual(results[3], null); - test.done(); - } - ); -}; - -// Issue 10 on github: https://github.com/caolan/async/issues#issue/10 -exports['falsy return values in parallel'] = function (test) { - function taskFalse(callback) { - async.nextTick(function() { - callback(null, false); - }); - }; - function taskUndefined(callback) { - async.nextTick(function() { - callback(null, undefined); - }); - }; - function taskEmpty(callback) { - async.nextTick(function() { - callback(null); - }); - }; - function taskNull(callback) { - async.nextTick(function() { - callback(null, null); - }); - }; - async.parallel( - [taskFalse, taskUndefined, taskEmpty, taskNull], - function(err, results) { - test.equal(results.length, 4); - test.strictEqual(results[0], false); - test.strictEqual(results[1], undefined); - test.strictEqual(results[2], undefined); - test.strictEqual(results[3], null); - test.done(); - } - ); -}; - -exports['queue events'] = function(test) { - var calls = []; - var q = async.queue(function(task, cb) { - // nop - calls.push('process ' + task); - cb(); - }, 3); - - q.saturated = function() { - test.ok(q.length() == 3, 'queue should be saturated now'); - calls.push('saturated'); - }; - q.empty = function() { - test.ok(q.length() == 0, 'queue should be empty now'); - calls.push('empty'); - }; - q.drain = function() { - test.ok( - q.length() == 0 && q.running() == 0, - 'queue should be empty now and no more workers should be running' - ); - calls.push('drain'); - test.same(calls, [ - 'saturated', - 'process foo', - 'foo cb', - 'process bar', - 'bar cb', - 'process zoo', - 'zoo cb', - 'process poo', - 'poo cb', - 'empty', - 'process moo', - 'moo cb', - 'drain', - ]); - test.done(); - }; - q.push('foo', function () {calls.push('foo cb');}); - q.push('bar', function () {calls.push('bar cb');}); - q.push('zoo', function () {calls.push('zoo cb');}); - q.push('poo', function () {calls.push('poo cb');}); - q.push('moo', function () {calls.push('moo cb');}); -}; diff --git a/node_modules/async/test/test.html b/node_modules/async/test/test.html deleted file mode 100644 index 2450e2d..0000000 --- a/node_modules/async/test/test.html +++ /dev/null @@ -1,24 +0,0 @@ - - - Async.js Test Suite - - - - - - - - -

Async.js Test Suite

- - - diff --git a/node_modules/connection_pool/.npmignore b/node_modules/connection_pool/.npmignore deleted file mode 100644 index a4df376..0000000 --- a/node_modules/connection_pool/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -npm-debug.log -*.log -node_modules/** \ No newline at end of file diff --git a/node_modules/connection_pool/Readme.md b/node_modules/connection_pool/Readme.md deleted file mode 100644 index 565d0f1..0000000 --- a/node_modules/connection_pool/Readme.md +++ /dev/null @@ -1,69 +0,0 @@ -Connection Pool -================ - -This provides a simple connection pool for node.js applications to use for managing connections to servers. - -It is used in [redis-proxy](https://github.com/sreeix/redis-proxy) for pooling redis connections. - - -It does not LRU or release stale connections. - -That may be something we can build in, but right now the API expects connections to be taken and released correctly, otherwise we will end up with unused connections - -The API is very simple currently and is used as following - - -Creation ---------- - -`var Pool = require('connection_pool')` - -` var p = new Pool({maxSize: 100, delayCreation:false, growBy: 2})` - -Following options are available: - -`create` : takes a function that invokes a callback (err, conn) . This is _Mandatory_ - -maxSize`` : Maximum connections on the pool : default 20 - -startSize : stars with these many connections: default 1/3 of max connections(6 if not maxSize is not specified) - -growBy : how to grow the pool default to 1/3 of max connections - -delayCreation: Create only on use rather than preemptively. This may mean a slight initial pool creation expense. - -close : optional close function to be called after release for doing cleanups - - -Taking Connections ------------------- - -`p.take('some_identifier', function(err, connection){ - doSomething(); -})` - - -Releasing Connections ---------------------- - -`p.close(identifier)` - -or - -`p.closeAll()` - -or - -`p.release(connection)` - - -Stats --------- - -It exposes the following basic information - -`totalConnections` : The current total connections in the pool. Note that this may not be the maxSize, because the pool size may be grown later - -`totalFreeConnections` : show how many more connections are available in the pool - -`totalInUseConnections` Show the total connections currently being used. \ No newline at end of file diff --git a/node_modules/connection_pool/lib/connection_pool.js b/node_modules/connection_pool/lib/connection_pool.js deleted file mode 100644 index 3297a87..0000000 --- a/node_modules/connection_pool/lib/connection_pool.js +++ /dev/null @@ -1,156 +0,0 @@ -var _ = require('underscore'); -var async = require('async'); -var logger = require('winston'); -var util = require('util'); - -// maxSize : Maximum connections on the pool : default 20 -// startSize : stars with these many connections: default 1/3 of max connections(6 if not maxSize is not specified) -// Mandatory create function -> takes a function that invokes a callback (err, conn) -// growBy : how to grwo the pool default to 1/3 of max connections -// delayCreation: Create only on use rather than preemptively. This may mean a slight initial poool creation expense. -// close : - -var ConnectionPool = module.exports = function(o){ - var self = this; - this.options = {maxSize: 20, close: function(cnnx){}}; - this.freepool = []; - this.inUsePool = {}; - - _.extend(this.options, o); - if(!this.options.startSize){ - this.options.startSize = parseInt(this.options.maxSize/3, 10); - if(this.options.startSize === 0) { - this.options.startSize = this.options.maxSize; - } - } - if(!this.options.growBy){ - this.options.growBy = parseInt(this.options.maxSize/3, 10); - if(this.options.growBy === 0) { - this.options.growBy = this.options.maxSize; - } - } - if(!this.options.delayCreation){ - this._addConnectionsToPool(); - } -}; - -ConnectionPool.prototype.take = function take(id, cb){ - var self = this; - if(this.inUsePool[id]){ - return cb(null, this.inUsePool[id]); - } - if(this.freepool.length === 0){ - this._addConnectionsToPool(function(err, done){ - if(err){ - logger.error(err); - return cb(err); - } - logger.debug('Adding more to free pool and allocating.'); - - self.inUsePool[id] = self.freepool.shift(); - return cb(null, self.inUsePool[id]); - }); - } else { - logger.debug('Free pool exists... reserving one from there..'); - this.inUsePool[id] = this.freepool.shift(); - return cb(null, this.inUsePool[id]); - } -}; - -ConnectionPool.prototype.release = function release(conn){ - logger.debug('releaseing' + conn); - var matchingId = null; - - _.each(this.inUsePool, function(x, y){ - if(_.isEqual(x, conn)){ - matchingId = y; - } - }); - - if(matchingId){ - this.close(matchingId); - } -}; - -ConnectionPool.prototype.close = function close(id){ - logger.debug("Releaseing "+ id); - logger.debug(util.inspect(this.inUsePool)); - if(!_.isNull(this.inUsePool[id])){ - logger.debug('connection for id '+ id +' closed') - this.freepool.push(this.inUsePool[id]); - delete this.inUsePool[id]; - } else { - logger.debug('No connection found in the pool.'); - - } -}; - -ConnectionPool.prototype.closeAll = function(){ - var self = this; - _.each(_.keys(this.inUsePool), function(id){ - self.close(id); - }); -}; - -Object.defineProperty(ConnectionPool.prototype, 'totalConnections', { - get: function() { - return this.freepool.length + _.size(this.inUsePool); - } -}); - -Object.defineProperty(ConnectionPool.prototype, 'totalFreeConnections', { - get: function() { - return this.freepool.length; - } -}); - -Object.defineProperty(ConnectionPool.prototype, 'totalInUseConnections', { - get: function() { - return _.size(this.inUsePool); - } -}); - - -ConnectionPool.prototype._addToFreePool = function(cb){ - var self = this, remaining; - var howManyConnections = this.options.growBy; - howManyConnections = (this.totalConnections === 0) ? this.options.startSize : this.options.growBy ; - - if(!_.isFunction(self.options.create)){ - cb('Need a create method for creating the pool connection'); - } - - remaining = this.options.maxSize - this.totalConnections; - if( howManyConnections > remaining){ - howManyConnections = remaining; - } - - if(remaining === 0){ - cb('Out of connections'); - } - - _.times(howManyConnections, function(i) { - self.options.create(function(err, conn){ - if(err) { - return cb(err); - } - self.freepool.push(conn); - if(i+1 === howManyConnections){ - return cb(null, true); - } - }); - }); -}; - -ConnectionPool.prototype._addConnectionsToPool = function(cb){ - var self = this; - if(!cb){ - cb = function(err, conn){} - } - this._addToFreePool(function(err, res){ - if(err){ - return cb(err); - } - return cb(null, true); - }); -}; \ No newline at end of file diff --git a/node_modules/connection_pool/package.json b/node_modules/connection_pool/package.json deleted file mode 100644 index 3d82f13..0000000 --- a/node_modules/connection_pool/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "author": "Sreekanth " - , "name": "connection_pool" - , "description": "Connection Pool for managing connections" - , "version": "0.0.1" - , "repository": { - "type": "git" - , "url": "git@github.com:sreeix/node-connection-pool.git" - } - , "main": "lib/connection_pool.js" - , "engines": { "node": ">= 0.4.7" } - , "node-version": ">0.4.7" - , "dependencies": { - "underscore": "1.2.4" - , "async": "0.1.15" - , "winston": "0.5.10" - } - , "devDependencies": { - "mocha": "0.0.8" - , "should": "0.3.2" - , "jshint":"0.5.5" - } - , "scripts": { - "test": "mocha --reporter dot --require should --ui bdd test/lib/*.js" - , "lint": " find . -not -path '*node_modules*' -and -name '*.js' -print0 | xargs -0 node_modules/.bin/jshint" - } -} diff --git a/node_modules/connection_pool/test/lib/connection_pool_spec.js b/node_modules/connection_pool/test/lib/connection_pool_spec.js deleted file mode 100644 index 09f8fc9..0000000 --- a/node_modules/connection_pool/test/lib/connection_pool_spec.js +++ /dev/null @@ -1,298 +0,0 @@ -var _ = require('underscore'); -var Pool = require('../../lib/connection_pool'); - -describe('ConnectionPool', function() { - it('raises exception when no rediss available', function() { - (function(){ - new Pool({}); - }).should.throw(); - }); - - it('should default startsize', function(done) { - var pool = new Pool({maxSize: 10 - , delayCreation: true - , create: function(){ - done(false); - } - }); - pool.options.startSize.should.equal(3); - setTimeout(done, 1000); - }); - it('should not set a 0 startsize', function(done) { - var pool = new Pool({maxSize: 2 - , delayCreation: true - , create: function(){ - done(false); - } - }); - pool.options.startSize.should.equal(2); - setTimeout(done, 1000); - }); - - it('should default growby', function(done) { - var pool = new Pool({maxSize: 20 - , delayCreation: true - , create: function(){ - done(false); - } - }); - pool.options.growBy.should.equal(6); - setTimeout(done, 1000); - }); - - it('should default growby to more than 0', function(done) { - var pool = new Pool({maxSize: 2 - , delayCreation: true - , create: function(){ - done(false); - } - }); - pool.options.growBy.should.equal(2); - setTimeout(done, 1000); - }); - - - describe("delayCreation", function() { - it('should not open connections immediately when delayCreation', function(done) { - new Pool({maxSize: 3 - , delayCreation: true - , create: function(){ - done(false); - } - }); - setTimeout(done, 1000); - }); - - it('should create when used on delayCreation', function(done) { - var pool = new Pool({maxSize: 3 - , delayCreation: true - , create: function(cb){ - cb(null, 'xx'); - } - }); - pool.freepool.length.should.equal(0); - - pool.take('1', function(err, val){ - val.should.equal('xx'); - pool.inUsePool['1'].should.equal('xx'); - done(); - }); - }); - - it('should use same item that was created for the id', function(done) { - var whatToReturn = ['xx', 'yyy', 'zzzz']; - var pool = new Pool({maxSize: 10 - , delayCreation: true - , create: function(cb){ - cb(null, whatToReturn.shift()); - } - }); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.freepool.length.should.equal(2); - done(); - }); - - }); - }); - - it('should create new connection for another id', function(done) { - var whatToReturn = ['xx', 'yyy', 'zzzz']; - var pool = new Pool({maxSize: 3 - , delayCreation: true - , create: function(cb){ - cb(null, whatToReturn.shift()); - } - }); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.take('2', function(err, conn){ - conn.should.equal('yyy'); - pool.freepool.length.should.equal(0); - done(); - }); - }); - }); - - it('should release on close', function(done) { - var whatToReturn = ['xx', 'yyy', 'zzzz']; - var pool = new Pool({maxSize: 10 - , delayCreation: true - , create: function(cb){ - cb(null, whatToReturn.shift()); - } - }); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.take('2', function(err, conn){ - conn.should.equal('yyy'); - pool.close('2'); - pool.freepool.length.should.equal(2); - done(); - }); - }); - }); - - it('should assign released for next request', function(done) { - var whatToReturn = ['xx', 'yyy']; - var pool = new Pool({maxSize: 2 - , delayCreation: true - , create: function(cb){ - cb(null, whatToReturn.shift()); - } - }); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.take('2', function(err, conn){ - conn.should.equal('yyy'); - pool.close('2'); - pool.freepool.length.should.equal(1); - pool.take('3', function(err, co){ - co.should.equal('yyy'); - done(); - }); - }); - }); - }); - - it('should release on close', function(done) { - var whatToReturn = ['xx', 'yyy', 'zzzz']; - var pool = new Pool({maxSize: 10 - , delayCreation: true - , create: function(cb){ - cb(null, whatToReturn.shift()); - } - }); - pool.take('1', function(err, conn){ - conn.should.equal('xx'); - pool.take('2', function(err, conn){ - conn.should.equal('yyy'); - pool.close('2'); - pool.freepool.length.should.equal(2); - done(); - }); - }); - }); - - }); - - describe('no delaycreation', function(){ - it('should open startSize connection immediately', function(done) { - var count = 0; - var pool = new Pool({maxSize: 3 - , delayCreation: false - , create: function(cb){ - cb(null, count++); - if(count == 1){ - done(); - } - } - }); - }); - - it('should open more connections when needed', function(done) { - var count = 0; - var pool = new Pool({maxSize: 5 - , startSize: 1 - , delayCreation: false - , create: function(cb){ - cb(null, count++); - if(count === 5){ - pool.totalConnections.should.equal(5); - done(); - } - } - }); - _.times(5, function(i){ - pool.take(i, function(err, conn){ - pool.totalConnections.should.equal(i+1); - pool.freepool.length.should.equal(0); - _.size(pool.inUsePool).should.equal(i + 1); - }); - }); - }); - - it('should open required connections only', function(done) { - var count = 0; - var pool = new Pool({maxSize: 5 - , startSize: 1 - , delayCreation: false - , create: function(cb){ - return cb(null, count++); - } - }); - _.times(5, function(i){ - console.log(i); - pool.take(i, function(err, conn){ - pool.totalConnections.should.equal(1); - pool.freepool.length.should.equal(0); - _.size(pool.inUsePool).should.equal(1); - pool.close(i); - pool.freepool.length.should.equal(1); - _.size(pool.inUsePool).should.equal(0); - if(i === 4){done();} - }); - }); - }); - - it('should not exeeed maxSize', function(done) { - var count = 0; - var pool = new Pool({maxSize: 5 - , startSize: 1 - , delayCreation: false - , create: function(cb){ - cb(null, count++); - if(count === 5){ - pool.totalConnections.should.equal(5); - } - } - }); - _.times(6, function(i){ - pool.take(i, function(err, conn){ - if(i === 5){ - err.should.not.equal(null); - return done(); - } - pool.totalConnections.should.equal(i+1); - pool.freepool.length.should.equal(0); - _.size(pool.inUsePool).should.equal(i + 1); - }); - }); - }); - }); - - describe('release', function(){ - it('should close the connection correctly', function(done){ - var whatToReturn = [1,3,6,8]; - var pool = new Pool({maxSize: 3 - , delayCreation: false - , create: function(cb){ - return cb(null, whatToReturn.shift()); - } - }); - pool.take('x', function(err, conn){ - pool.totalInUseConnections.should.equal(1); - pool.release(conn); - pool.totalInUseConnections.should.equal(0); - done(); - }); - }); - it('should do nothing if no match', function(done){ - var whatToReturn = [1,3,6,8]; - var pool = new Pool({maxSize: 3 - , delayCreation: false - , create: function(cb){ - return cb(null, whatToReturn.shift()); - } - }); - pool.take('x', function(err, conn){ - pool.totalInUseConnections.should.equal(1); - pool.release('unk'); - pool.totalInUseConnections.should.equal(1); - done(); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/connection_pool/test/mocha.opts b/node_modules/connection_pool/test/mocha.opts deleted file mode 100644 index 3fb7f79..0000000 --- a/node_modules/connection_pool/test/mocha.opts +++ /dev/null @@ -1,4 +0,0 @@ ---require should ---reporter dot ---ui bdd ---growl \ No newline at end of file diff --git a/node_modules/express/.npmignore b/node_modules/express/.npmignore deleted file mode 100644 index 74bd365..0000000 --- a/node_modules/express/.npmignore +++ /dev/null @@ -1,7 +0,0 @@ -.git* -docs/ -examples/ -support/ -test/ -testing.js -.DS_Store diff --git a/node_modules/express/History.md b/node_modules/express/History.md deleted file mode 100644 index 0527ec2..0000000 --- a/node_modules/express/History.md +++ /dev/null @@ -1,770 +0,0 @@ - -2.5.1 / 2011-11-17 -================== - - * Changed: updated connect to 1.8.x - * Removed sass.js support from express(1) - -2.5.0 / 2011-10-24 -================== - - * Added ./routes dir for generated app by default - * Added npm install reminder to express(1) app gen - * Added 0.5.x support - * Removed `make test-cov` since it wont work with node 0.5.x - * Fixed express(1) public dir for windows. Closes #866 - -2.4.7 / 2011-10-05 -================== - - * Added mkdirp to express(1). Closes #795 - * Added simple _json-config_ example - * Added shorthand for the parsed request's pathname via `req.path` - * Changed connect dep to 1.7.x to fix npm issue... - * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] - * Fixed `req.flash()`, only escape args - * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] - -2.4.6 / 2011-08-22 -================== - - * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] - -2.4.5 / 2011-08-19 -================== - - * Added support for routes to handle errors. Closes #809 - * Added `app.routes.all()`. Closes #803 - * Added "basepath" setting to work in conjunction with reverse proxies etc. - * Refactored `Route` to use a single array of callbacks - * Added support for multiple callbacks for `app.param()`. Closes #801 -Closes #805 - * Changed: removed .call(self) for route callbacks - * Dependency: `qs >= 0.3.1` - * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 - -2.4.4 / 2011-08-05 -================== - - * Fixed `res.header()` intention of a set, even when `undefined` - * Fixed `*`, value no longer required - * Fixed `res.send(204)` support. Closes #771 - -2.4.3 / 2011-07-14 -================== - - * Added docs for `status` option special-case. Closes #739 - * Fixed `options.filename`, exposing the view path to template engines - -2.4.2. / 2011-07-06 -================== - - * Revert "removed jsonp stripping" for XSS - -2.4.1 / 2011-07-06 -================== - - * Added `res.json()` JSONP support. Closes #737 - * Added _extending-templates_ example. Closes #730 - * Added "strict routing" setting for trailing slashes - * Added support for multiple envs in `app.configure()` calls. Closes #735 - * Changed: `res.send()` using `res.json()` - * Changed: when cookie `path === null` don't default it - * Changed; default cookie path to "home" setting. Closes #731 - * Removed _pids/logs_ creation from express(1) - -2.4.0 / 2011-06-28 -================== - - * Added chainable `res.status(code)` - * Added `res.json()`, an explicit version of `res.send(obj)` - * Added simple web-service example - -2.3.12 / 2011-06-22 -================== - - * \#express is now on freenode! come join! - * Added `req.get(field, param)` - * Added links to Japanese documentation, thanks @hideyukisaito! - * Added; the `express(1)` generated app outputs the env - * Added `content-negotiation` example - * Dependency: connect >= 1.5.1 < 2.0.0 - * Fixed view layout bug. Closes #720 - * Fixed; ignore body on 304. Closes #701 - -2.3.11 / 2011-06-04 -================== - - * Added `npm test` - * Removed generation of dummy test file from `express(1)` - * Fixed; `express(1)` adds express as a dep - * Fixed; prune on `prepublish` - -2.3.10 / 2011-05-27 -================== - - * Added `req.route`, exposing the current route - * Added _package.json_ generation support to `express(1)` - * Fixed call to `app.param()` function for optional params. Closes #682 - -2.3.9 / 2011-05-25 -================== - - * Fixed bug-ish with `../' in `res.partial()` calls - -2.3.8 / 2011-05-24 -================== - - * Fixed `app.options()` - -2.3.7 / 2011-05-23 -================== - - * Added route `Collection`, ex: `app.get('/user/:id').remove();` - * Added support for `app.param(fn)` to define param logic - * Removed `app.param()` support for callback with return value - * Removed module.parent check from express(1) generated app. Closes #670 - * Refactored router. Closes #639 - -2.3.6 / 2011-05-20 -================== - - * Changed; using devDependencies instead of git submodules - * Fixed redis session example - * Fixed markdown example - * Fixed view caching, should not be enabled in development - -2.3.5 / 2011-05-20 -================== - - * Added export `.view` as alias for `.View` - -2.3.4 / 2011-05-08 -================== - - * Added `./examples/say` - * Fixed `res.sendfile()` bug preventing the transfer of files with spaces - -2.3.3 / 2011-05-03 -================== - - * Added "case sensitive routes" option. - * Changed; split methods supported per rfc [slaskis] - * Fixed route-specific middleware when using the same callback function several times - -2.3.2 / 2011-04-27 -================== - - * Fixed view hints - -2.3.1 / 2011-04-26 -================== - - * Added `app.match()` as `app.match.all()` - * Added `app.lookup()` as `app.lookup.all()` - * Added `app.remove()` for `app.remove.all()` - * Added `app.remove.VERB()` - * Fixed template caching collision issue. Closes #644 - * Moved router over from connect and started refactor - -2.3.0 / 2011-04-25 -================== - - * Added options support to `res.clearCookie()` - * Added `res.helpers()` as alias of `res.locals()` - * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` - * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] - * Renamed "cache views" to "view cache". Closes #628 - * Fixed caching of views when using several apps. Closes #637 - * Fixed gotcha invoking `app.param()` callbacks once per route middleware. -Closes #638 - * Fixed partial lookup precedence. Closes #631 -Shaw] - -2.2.2 / 2011-04-12 -================== - - * Added second callback support for `res.download()` connection errors - * Fixed `filename` option passing to template engine - -2.2.1 / 2011-04-04 -================== - - * Added `layout(path)` helper to change the layout within a view. Closes #610 - * Fixed `partial()` collection object support. - Previously only anything with `.length` would work. - When `.length` is present one must still be aware of holes, - however now `{ collection: {foo: 'bar'}}` is valid, exposes - `keyInCollection` and `keysInCollection`. - - * Performance improved with better view caching - * Removed `request` and `response` locals - * Changed; errorHandler page title is now `Express` instead of `Connect` - -2.2.0 / 2011-03-30 -================== - - * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 - * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 - * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. - * Dependency `connect >= 1.2.0` - -2.1.1 / 2011-03-29 -================== - - * Added; expose `err.view` object when failing to locate a view - * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] - * Fixed; `res.send(undefined)` responds with 204 [aheckmann] - -2.1.0 / 2011-03-24 -================== - - * Added `/_?` partial lookup support. Closes #447 - * Added `request`, `response`, and `app` local variables - * Added `settings` local variable, containing the app's settings - * Added `req.flash()` exception if `req.session` is not available - * Added `res.send(bool)` support (json response) - * Fixed stylus example for latest version - * Fixed; wrap try/catch around `res.render()` - -2.0.0 / 2011-03-17 -================== - - * Fixed up index view path alternative. - * Changed; `res.locals()` without object returns the locals - -2.0.0rc3 / 2011-03-17 -================== - - * Added `res.locals(obj)` to compliment `res.local(key, val)` - * Added `res.partial()` callback support - * Fixed recursive error reporting issue in `res.render()` - -2.0.0rc2 / 2011-03-17 -================== - - * Changed; `partial()` "locals" are now optional - * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] - * Fixed .filename view engine option [reported by drudge] - * Fixed blog example - * Fixed `{req,res}.app` reference when mounting [Ben Weaver] - -2.0.0rc / 2011-03-14 -================== - - * Fixed; expose `HTTPSServer` constructor - * Fixed express(1) default test charset. Closes #579 [reported by secoif] - * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] - -2.0.0beta3 / 2011-03-09 -================== - - * Added support for `res.contentType()` literal - The original `res.contentType('.json')`, - `res.contentType('application/json')`, and `res.contentType('json')` - will work now. - * Added `res.render()` status option support back - * Added charset option for `res.render()` - * Added `.charset` support (via connect 1.0.4) - * Added view resolution hints when in development and a lookup fails - * Added layout lookup support relative to the page view. - For example while rendering `./views/user/index.jade` if you create - `./views/user/layout.jade` it will be used in favour of the root layout. - * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] - * Fixed; default `res.send()` string charset to utf8 - * Removed `Partial` constructor (not currently used) - -2.0.0beta2 / 2011-03-07 -================== - - * Added res.render() `.locals` support back to aid in migration process - * Fixed flash example - -2.0.0beta / 2011-03-03 -================== - - * Added HTTPS support - * Added `res.cookie()` maxAge support - * Added `req.header()` _Referrer_ / _Referer_ special-case, either works - * Added mount support for `res.redirect()`, now respects the mount-point - * Added `union()` util, taking place of `merge(clone())` combo - * Added stylus support to express(1) generated app - * Added secret to session middleware used in examples and generated app - * Added `res.local(name, val)` for progressive view locals - * Added default param support to `req.param(name, default)` - * Added `app.disabled()` and `app.enabled()` - * Added `app.register()` support for omitting leading ".", either works - * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 - * Added `app.param()` to map route params to async/sync logic - * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 - * Added extname with no leading "." support to `res.contentType()` - * Added `cache views` setting, defaulting to enabled in "production" env - * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. - * Added `req.accepts()` support for extensions - * Changed; `res.download()` and `res.sendfile()` now utilize Connect's - static file server `connect.static.send()`. - * Changed; replaced `connect.utils.mime()` with npm _mime_ module - * Changed; allow `req.query` to be pre-defined (via middleware or other parent - * Changed view partial resolution, now relative to parent view - * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. - * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 - * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` - * Fixed; using _qs_ module instead of _querystring_ - * Fixed; strip unsafe chars from jsonp callbacks - * Removed "stream threshold" setting - -1.0.8 / 2011-03-01 -================== - - * Allow `req.query` to be pre-defined (via middleware or other parent app) - * "connect": ">= 0.5.0 < 1.0.0". Closes #547 - * Removed the long deprecated __EXPRESS_ENV__ support - -1.0.7 / 2011-02-07 -================== - - * Fixed `render()` setting inheritance. - Mounted apps would not inherit "view engine" - -1.0.6 / 2011-02-07 -================== - - * Fixed `view engine` setting bug when period is in dirname - -1.0.5 / 2011-02-05 -================== - - * Added secret to generated app `session()` call - -1.0.4 / 2011-02-05 -================== - - * Added `qs` dependency to _package.json_ - * Fixed namespaced `require()`s for latest connect support - -1.0.3 / 2011-01-13 -================== - - * Remove unsafe characters from JSONP callback names [Ryan Grove] - -1.0.2 / 2011-01-10 -================== - - * Removed nested require, using `connect.router` - -1.0.1 / 2010-12-29 -================== - - * Fixed for middleware stacked via `createServer()` - previously the `foo` middleware passed to `createServer(foo)` - would not have access to Express methods such as `res.send()` - or props like `req.query` etc. - -1.0.0 / 2010-11-16 -================== - - * Added; deduce partial object names from the last segment. - For example by default `partial('forum/post', postObject)` will - give you the _post_ object, providing a meaningful default. - * Added http status code string representation to `res.redirect()` body - * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. - * Added `req.is()` to aid in content negotiation - * Added partial local inheritance [suggested by masylum]. Closes #102 - providing access to parent template locals. - * Added _-s, --session[s]_ flag to express(1) to add session related middleware - * Added _--template_ flag to express(1) to specify the - template engine to use. - * Added _--css_ flag to express(1) to specify the - stylesheet engine to use (or just plain css by default). - * Added `app.all()` support [thanks aheckmann] - * Added partial direct object support. - You may now `partial('user', user)` providing the "user" local, - vs previously `partial('user', { object: user })`. - * Added _route-separation_ example since many people question ways - to do this with CommonJS modules. Also view the _blog_ example for - an alternative. - * Performance; caching view path derived partial object names - * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 - * Fixed jsonp support; _text/javascript_ as per mailinglist discussion - -1.0.0rc4 / 2010-10-14 -================== - - * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 - * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) - * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] - * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] - * Added `partial()` support for array-like collections. Closes #434 - * Added support for swappable querystring parsers - * Added session usage docs. Closes #443 - * Added dynamic helper caching. Closes #439 [suggested by maritz] - * Added authentication example - * Added basic Range support to `res.sendfile()` (and `res.download()` etc) - * Changed; `express(1)` generated app using 2 spaces instead of 4 - * Default env to "development" again [aheckmann] - * Removed _context_ option is no more, use "scope" - * Fixed; exposing _./support_ libs to examples so they can run without installs - * Fixed mvc example - -1.0.0rc3 / 2010-09-20 -================== - - * Added confirmation for `express(1)` app generation. Closes #391 - * Added extending of flash formatters via `app.flashFormatters` - * Added flash formatter support. Closes #411 - * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" - * Added _stream threshold_ setting for `res.sendfile()` - * Added `res.send()` __HEAD__ support - * Added `res.clearCookie()` - * Added `res.cookie()` - * Added `res.render()` headers option - * Added `res.redirect()` response bodies - * Added `res.render()` status option support. Closes #425 [thanks aheckmann] - * Fixed `res.sendfile()` responding with 403 on malicious path - * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ - * Fixed; mounted apps settings now inherit from parent app [aheckmann] - * Fixed; stripping Content-Length / Content-Type when 204 - * Fixed `res.send()` 204. Closes #419 - * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 - * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] - - -1.0.0rc2 / 2010-08-17 -================== - - * Added `app.register()` for template engine mapping. Closes #390 - * Added `res.render()` callback support as second argument (no options) - * Added callback support to `res.download()` - * Added callback support for `res.sendfile()` - * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` - * Added "partials" setting to docs - * Added default expresso tests to `express(1)` generated app. Closes #384 - * Fixed `res.sendfile()` error handling, defer via `next()` - * Fixed `res.render()` callback when a layout is used [thanks guillermo] - * Fixed; `make install` creating ~/.node_libraries when not present - * Fixed issue preventing error handlers from being defined anywhere. Closes #387 - -1.0.0rc / 2010-07-28 -================== - - * Added mounted hook. Closes #369 - * Added connect dependency to _package.json_ - - * Removed "reload views" setting and support code - development env never caches, production always caches. - - * Removed _param_ in route callbacks, signature is now - simply (req, res, next), previously (req, res, params, next). - Use _req.params_ for path captures, _req.query_ for GET params. - - * Fixed "home" setting - * Fixed middleware/router precedence issue. Closes #366 - * Fixed; _configure()_ callbacks called immediately. Closes #368 - -1.0.0beta2 / 2010-07-23 -================== - - * Added more examples - * Added; exporting `Server` constructor - * Added `Server#helpers()` for view locals - * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 - * Added support for absolute view paths - * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 - * Added Guillermo Rauch to the contributor list - * Added support for "as" for non-collection partials. Closes #341 - * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] - * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] - * Fixed instanceof `Array` checks, now `Array.isArray()` - * Fixed express(1) expansion of public dirs. Closes #348 - * Fixed middleware precedence. Closes #345 - * Fixed view watcher, now async [thanks aheckmann] - -1.0.0beta / 2010-07-15 -================== - - * Re-write - - much faster - - much lighter - - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs - -0.14.0 / 2010-06-15 -================== - - * Utilize relative requires - * Added Static bufferSize option [aheckmann] - * Fixed caching of view and partial subdirectories [aheckmann] - * Fixed mime.type() comments now that ".ext" is not supported - * Updated haml submodule - * Updated class submodule - * Removed bin/express - -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 /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 -================== - - * Added package.json - * Fixed requiring of haml / sass due to kiwi removal - -0.7.2 / 2010-03-16 -================== - - * Fixed GIT submodules (HAH!) - -0.7.1 / 2010-03-16 -================== - - * Changed; Express now using submodules again until a PM is adopted - * Changed; chat example using millisecond conversions from ext - -0.7.0 / 2010-03-15 -================== - - * Added Request#pass() support (finds the next matching route, or the given path) - * Added Logger plugin (default "common" format replaces CommonLogger) - * Removed Profiler plugin - * Removed CommonLogger plugin - -0.6.0 / 2010-03-11 -================== - - * Added seed.yml for kiwi package management support - * Added HTTP client query string support when method is GET. Closes #205 - - * Added support for arbitrary view engines. - For example "foo.engine.html" will now require('engine'), - the exports from this module are cached after the first require(). - - * Added async plugin support - - * Removed usage of RESTful route funcs as http client - get() etc, use http.get() and friends - - * Removed custom exceptions - -0.5.0 / 2010-03-10 -================== - - * Added ext dependency (library of js extensions) - * Removed extname() / basename() utils. Use path module - * Removed toArray() util. Use arguments.values - * Removed escapeRegexp() util. Use RegExp.escape() - * Removed process.mixin() dependency. Use utils.mixin() - * Removed Collection - * Removed ElementCollection - * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) - -0.4.0 / 2010-02-11 -================== - - * Added flash() example to sample upload app - * Added high level restful http client module (express/http) - * Changed; RESTful route functions double as HTTP clients. Closes #69 - * Changed; throwing error when routes are added at runtime - * Changed; defaulting render() context to the current Request. Closes #197 - * Updated haml submodule - -0.3.0 / 2010-02-11 -================== - - * Updated haml / sass submodules. Closes #200 - * Added flash message support. Closes #64 - * Added accepts() now allows multiple args. fixes #117 - * Added support for plugins to halt. Closes #189 - * Added alternate layout support. Closes #119 - * Removed Route#run(). Closes #188 - * Fixed broken specs due to use(Cookie) missing - -0.2.1 / 2010-02-05 -================== - - * Added "plot" format option for Profiler (for gnuplot processing) - * Added request number to Profiler plugin - * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 - * Fixed issue with routes not firing when not files are present. Closes #184 - * Fixed process.Promise -> events.Promise - -0.2.0 / 2010-02-03 -================== - - * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 - * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 - * Added expiration support to cache api with reaper. Closes #133 - * Added cache Store.Memory#reap() - * Added Cache; cache api now uses first class Cache instances - * Added abstract session Store. Closes #172 - * Changed; cache Memory.Store#get() utilizing Collection - * Renamed MemoryStore -> Store.Memory - * Fixed use() of the same plugin several time will always use latest options. Closes #176 - -0.1.0 / 2010-02-03 -================== - - * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context - * Updated node support to 0.1.27 Closes #169 - * Updated dirname(__filename) -> __dirname - * Updated libxmljs support to v0.2.0 - * Added session support with memory store / reaping - * Added quick uid() helper - * Added multi-part upload support - * Added Sass.js support / submodule - * Added production env caching view contents and static files - * Added static file caching. Closes #136 - * Added cache plugin with memory stores - * Added support to StaticFile so that it works with non-textual files. - * Removed dirname() helper - * Removed several globals (now their modules must be required) - -0.0.2 / 2010-01-10 -================== - - * Added view benchmarks; currently haml vs ejs - * Added Request#attachment() specs. Closes #116 - * Added use of node's parseQuery() util. Closes #123 - * Added `make init` for submodules - * Updated Haml - * Updated sample chat app to show messages on load - * Updated libxmljs parseString -> parseHtmlString - * Fixed `make init` to work with older versions of git - * Fixed specs can now run independant specs for those who cant build deps. Closes #127 - * Fixed issues introduced by the node url module changes. Closes 126. - * Fixed two assertions failing due to Collection#keys() returning strings - * Fixed faulty Collection#toArray() spec due to keys() returning strings - * Fixed `make test` now builds libxmljs.node before testing - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE deleted file mode 100644 index 36075a3..0000000 --- a/node_modules/express/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2009-2011 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/Makefile b/node_modules/express/Makefile deleted file mode 100644 index dfbfd67..0000000 --- a/node_modules/express/Makefile +++ /dev/null @@ -1,29 +0,0 @@ - -DOCS = $(shell find docs/*.md) -HTMLDOCS = $(DOCS:.md=.html) -TESTS = $(shell find test/*.test.js) - -test: - @NODE_ENV=test ./node_modules/.bin/expresso $(TESTS) - -docs: $(HTMLDOCS) - @ echo "... generating TOC" - @./support/toc.js docs/guide.html - -%.html: %.md - @echo "... $< -> $@" - @markdown $< \ - | cat docs/layout/head.html - docs/layout/foot.html \ - > $@ - -site: - rm -fr /tmp/docs \ - && cp -fr docs /tmp/docs \ - && git checkout gh-pages \ - && cp -fr /tmp/docs/* . \ - && echo "done" - -docclean: - rm -f docs/*.{1,html} - -.PHONY: site test docs docclean \ No newline at end of file diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md deleted file mode 100644 index d2c64c7..0000000 --- a/node_modules/express/Readme.md +++ /dev/null @@ -1,145 +0,0 @@ - -# Express - - Insanely fast (and small) server-side JavaScript web development framework - built on [node](http://nodejs.org) and [Connect](http://github.com/senchalabs/connect). - - var app = express.createServer(); - - app.get('/', function(req, res){ - res.send('Hello World'); - }); - - app.listen(3000); - -## Installation - - $ npm install express - -or to access the `express(1)` executable install globally: - - $ npm install -g express - -## Quick Start - - The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below: - - Create the app: - - $ npm install -g express - $ express /tmp/foo && cd /tmp/foo - - Install dependencies: - - $ npm install -d - - Start the server: - - $ node app.js - -## Features - - * Robust routing - * Redirection helpers - * Dynamic view helpers - * Content negotiation - * Focus on high performance - * View rendering and partials support - * Environment based configuration - * Session based flash notifications - * Built on [Connect](http://github.com/senchalabs/connect) - * High test coverage - * Executable for generating applications quickly - * Application level view options - -Via Connect: - - * Session support - * Cache API - * Mime helpers - * ETag support - * Persistent flash notifications - * Cookie support - * JSON-RPC - * Logging - * and _much_ more! - -## Contributors - -The following are the major contributors of Express (in no specific order). - - * TJ Holowaychuk ([visionmedia](http://github.com/visionmedia)) - * Ciaran Jessup ([ciaranj](http://github.com/ciaranj)) - * Aaron Heckmann ([aheckmann](http://github.com/aheckmann)) - * Guillermo Rauch ([guille](http://github.com/guille)) - -## More Information - - * #express on freenode - * [express-expose](http://github.com/visionmedia/express-expose) expose objects, functions, modules and more to client-side js with ease - * [express-configure](http://github.com/visionmedia/express-configuration) async configuration support - * [express-messages](http://github.com/visionmedia/express-messages) flash notification rendering helper - * [express-namespace](http://github.com/visionmedia/express-namespace) namespaced route support - * [express-params](https://github.com/visionmedia/express-params) param pre-condition functions - * [express-mongoose](https://github.com/LearnBoost/express-mongoose) plugin for easy rendering of Mongoose async Query results - * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates - * [Google Group](http://groups.google.com/group/express-js) for discussion - * Visit the [Wiki](http://github.com/visionmedia/express/wiki) - * [日本語ドキュメンテーション](http://hideyukisaito.com/doc/expressjs/) by [hideyukisaito](https://github.com/hideyukisaito) - * Screencast - [Introduction](http://bit.ly/eRYu0O) - * Screencast - [View Partials](http://bit.ly/dU13Fx) - * Screencast - [Route Specific Middleware](http://bit.ly/hX4IaH) - * Screencast - [Route Path Placeholder Preconditions](http://bit.ly/eNqmVs) - -## Node Compatibility - -Express 1.x is compatible with node 0.2.x and connect < 1.0. - -Express 2.x is compatible with node 0.4.x or 0.6.x, and connect 1.x - -Express 3.x (master) will be compatible with node 0.6.x and connect 2.x - -## Viewing Examples - -First install the dev dependencies to install all the example / test suite deps: - - $ npm install - -then run whichever tests you want: - - $ node examples/jade/app.js - -## Running Tests - -To run the test suite first invoke the following command within the repo, installing the development dependencies: - - $ npm install - -then run the tests: - - $ make test - -## License - -(The MIT License) - -Copyright (c) 2009-2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/bin/express b/node_modules/express/bin/express deleted file mode 100755 index eebb724..0000000 --- a/node_modules/express/bin/express +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var fs = require('fs') - , exec = require('child_process').exec - , mkdirp = require('mkdirp'); - -/** - * Framework version. - */ - -var version = '2.5.1'; - -/** - * Add session support. - */ - -var sessions = false; - -/** - * CSS engine to utilize. - */ - -var cssEngine; - -/** - * Template engine to utilize. - */ - -var templateEngine = 'jade'; - -/** - * Usage documentation. - */ - -var usage = '' - + '\n' - + ' Usage: express [options] [path]\n' - + '\n' - + ' Options:\n' - + ' -s, --sessions add session support\n' - + ' -t, --template add template support (jade|ejs). default=jade\n' - + ' -c, --css add stylesheet support (less|stylus). default=plain css\n' - + ' -v, --version output framework version\n' - + ' -h, --help output help information\n' - ; - -/** - * Routes index template. - */ - -var index = [ - '' - , '/*' - , ' * GET home page.' - , ' */' - , '' - , 'exports.index = function(req, res){' - , ' res.render(\'index\', { title: \'Express\' })' - , '};' -].join('\n'); - -/** - * Jade layout template. - */ - -var jadeLayout = [ - '!!!' - , 'html' - , ' head' - , ' title= title' - , ' link(rel=\'stylesheet\', href=\'/stylesheets/style.css\')' - , ' body!= body' -].join('\n'); - -/** - * Jade index template. - */ - -var jadeIndex = [ - 'h1= title' - , 'p Welcome to #{title}' -].join('\n'); - -/** - * EJS layout template. - */ - -var ejsLayout = [ - '' - , '' - , ' ' - , ' <%= title %>' - , ' ' - , ' ' - , ' ' - , ' <%- body %>' - , ' ' - , '' -].join('\n'); - -/** - * EJS index template. - */ - -var ejsIndex = [ - '

<%= title %>

' - , '

Welcome to <%= title %>

' - ].join('\n'); - -/** - * Default css template. - */ - -var css = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join('\n'); - -/** - * Default less template. - */ - -var less = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join('\n'); - -/** - * Default stylus template. - */ - -var stylus = [ - 'body' - , ' padding: 50px' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif' - , 'a' - , ' color: #00B7FF' -].join('\n'); - -/** - * App template. - */ - -var app = [ - '' - , '/**' - , ' * Module dependencies.' - , ' */' - , '' - , 'var express = require(\'express\')' - , ' , routes = require(\'./routes\')' - , '' - , 'var app = module.exports = express.createServer();' - , '' - , '// Configuration' - , '' - , 'app.configure(function(){' - , ' app.set(\'views\', __dirname + \'/views\');' - , ' app.set(\'view engine\', \':TEMPLATE\');' - , ' app.use(express.bodyParser());' - , ' app.use(express.methodOverride());{sess}{css}' - , ' app.use(app.router);' - , ' app.use(express.static(__dirname + \'/public\'));' - , '});' - , '' - , 'app.configure(\'development\', function(){' - , ' app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); ' - , '});' - , '' - , 'app.configure(\'production\', function(){' - , ' app.use(express.errorHandler()); ' - , '});' - , '' - , '// Routes' - , '' - , 'app.get(\'/\', routes.index);' - , '' - , 'app.listen(3000);' - , 'console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);' - , '' -].join('\n'); - -// Parse arguments - -var args = process.argv.slice(2) - , path = '.'; - -while (args.length) { - var arg = args.shift(); - switch (arg) { - case '-h': - case '--help': - abort(usage); - break; - case '-v': - case '--version': - abort(version); - break; - case '-s': - case '--session': - case '--sessions': - sessions = true; - break; - case '-c': - case '--css': - args.length - ? (cssEngine = args.shift()) - : abort('--css requires an argument'); - break; - case '-t': - case '--template': - args.length - ? (templateEngine = args.shift()) - : abort('--template requires an argument'); - break; - default: - path = arg; - } -} - -// Generate application - -(function createApplication(path) { - emptyDirectory(path, function(empty){ - if (empty) { - createApplicationAt(path); - } else { - confirm('destination is not empty, continue? ', function(ok){ - if (ok) { - process.stdin.destroy(); - createApplicationAt(path); - } else { - abort('aborting'); - } - }); - } - }); -})(path); - -/** - * Create application at the given directory `path`. - * - * @param {String} path - */ - -function createApplicationAt(path) { - console.log(); - process.on('exit', function(){ - console.log(); - console.log(' dont forget to install dependencies:'); - console.log(' $ cd %s && npm install', path); - console.log(); - }); - - mkdir(path, function(){ - mkdir(path + '/public'); - mkdir(path + '/public/javascripts'); - mkdir(path + '/public/images'); - mkdir(path + '/public/stylesheets', function(){ - switch (cssEngine) { - case 'stylus': - write(path + '/public/stylesheets/style.styl', stylus); - break; - case 'less': - write(path + '/public/stylesheets/style.less', less); - break; - default: - write(path + '/public/stylesheets/style.css', css); - } - }); - - mkdir(path + '/routes', function(){ - write(path + '/routes/index.js', index); - }); - - mkdir(path + '/views', function(){ - switch (templateEngine) { - case 'ejs': - write(path + '/views/layout.ejs', ejsLayout); - write(path + '/views/index.ejs', ejsIndex); - break; - case 'jade': - write(path + '/views/layout.jade', jadeLayout); - write(path + '/views/index.jade', jadeIndex); - break; - } - }); - - // CSS Engine support - switch (cssEngine) { - case 'less': - app = app.replace('{css}', '\n app.use(express.compiler({ src: __dirname + \'/public\', enable: [\'' + cssEngine + '\'] }));'); - break; - case 'stylus': - app = app.replace('{css}', '\n app.use(require(\'stylus\').middleware({ src: __dirname + \'/public\' }));'); - break; - default: - app = app.replace('{css}', ''); - } - - // Session support - app = app.replace('{sess}', sessions - ? '\n app.use(express.cookieParser());\n app.use(express.session({ secret: \'your secret here\' }));' - : ''); - - // Template support - app = app.replace(':TEMPLATE', templateEngine); - - // package.json - var json = '{\n'; - json += ' "name": "application-name"\n'; - json += ' , "version": "0.0.1"\n'; - json += ' , "private": true\n'; - json += ' , "dependencies": {\n'; - json += ' "express": "' + version + '"\n'; - if (cssEngine) json += ' , "' + cssEngine + '": ">= 0.0.1"\n'; - if (templateEngine) json += ' , "' + templateEngine + '": ">= 0.0.1"\n'; - json += ' }\n'; - json += '}'; - - - write(path + '/package.json', json); - write(path + '/app.js', app); - }); -} - -/** - * Check if the given directory `path` is empty. - * - * @param {String} path - * @param {Function} fn - */ - -function emptyDirectory(path, fn) { - fs.readdir(path, function(err, files){ - if (err && 'ENOENT' != err.code) throw err; - fn(!files || !files.length); - }); -} - -/** - * echo str > path. - * - * @param {String} path - * @param {String} str - */ - -function write(path, str) { - fs.writeFile(path, str); - console.log(' \x1b[36mcreate\x1b[0m : ' + path); -} - -/** - * Prompt confirmation with the given `msg`. - * - * @param {String} msg - * @param {Function} fn - */ - -function confirm(msg, fn) { - prompt(msg, function(val){ - fn(/^ *y(es)?/i.test(val)); - }); -} - -/** - * Prompt input with the given `msg` and callback `fn`. - * - * @param {String} msg - * @param {Function} fn - */ - -function prompt(msg, fn) { - // prompt - if (' ' == msg[msg.length - 1]) { - process.stdout.write(msg); - } else { - console.log(msg); - } - - // stdin - process.stdin.setEncoding('ascii'); - process.stdin.once('data', function(data){ - fn(data); - }).resume(); -} - -/** - * Mkdir -p. - * - * @param {String} path - * @param {Function} fn - */ - -function mkdir(path, fn) { - mkdirp(path, 0755, function(err){ - if (err) throw err; - console.log(' \033[36mcreate\033[0m : ' + path); - fn && fn(); - }); -} - -/** - * Exit with the given `str`. - * - * @param {String} str - */ - -function abort(str) { - console.error(str); - process.exit(1); -} diff --git a/node_modules/express/index.js b/node_modules/express/index.js deleted file mode 100644 index 8d81ea7..0000000 --- a/node_modules/express/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/express'); \ No newline at end of file diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js deleted file mode 100644 index 072a010..0000000 --- a/node_modules/express/lib/express.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Express - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var connect = require('connect') - , HTTPSServer = require('./https') - , HTTPServer = require('./http') - , Route = require('./router/route') - -/** - * Re-export connect auto-loaders. - * - * This prevents the need to `require('connect')` in order - * to access core middleware, so for example `express.logger()` instead - * of `require('connect').logger()`. - */ - -var exports = module.exports = connect.middleware; - -/** - * Framework version. - */ - -exports.version = '2.5.1'; - -/** - * Shortcut for `new Server(...)`. - * - * @param {Function} ... - * @return {Server} - * @api public - */ - -exports.createServer = function(options){ - if ('object' == typeof options) { - return new HTTPSServer(options, Array.prototype.slice.call(arguments, 1)); - } else { - return new HTTPServer(Array.prototype.slice.call(arguments)); - } -}; - -/** - * Expose constructors. - */ - -exports.HTTPServer = HTTPServer; -exports.HTTPSServer = HTTPSServer; -exports.Route = Route; - -/** - * View extensions. - */ - -exports.View = -exports.view = require('./view'); - -/** - * Response extensions. - */ - -require('./response'); - -/** - * Request extensions. - */ - -require('./request'); - -// Error handler title - -exports.errorHandler.title = 'Express'; - diff --git a/node_modules/express/lib/http.js b/node_modules/express/lib/http.js deleted file mode 100644 index 4256dc4..0000000 --- a/node_modules/express/lib/http.js +++ /dev/null @@ -1,583 +0,0 @@ - -/*! - * Express - HTTPServer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , connect = require('connect') - , router = require('./router') - , Router = require('./router') - , view = require('./view') - , toArray = require('./utils').toArray - , methods = router.methods.concat('del', 'all') - , url = require('url') - , utils = connect.utils; - -/** - * Expose `HTTPServer`. - */ - -exports = module.exports = HTTPServer; - -/** - * Server proto. - */ - -var app = HTTPServer.prototype; - -/** - * Initialize a new `HTTPServer` with optional `middleware`. - * - * @param {Array} middleware - * @api public - */ - -function HTTPServer(middleware){ - connect.HTTPServer.call(this, []); - this.init(middleware); -}; - -/** - * Inherit from `connect.HTTPServer`. - */ - -app.__proto__ = connect.HTTPServer.prototype; - -/** - * Initialize the server. - * - * @param {Array} middleware - * @api private - */ - -app.init = function(middleware){ - var self = this; - this.cache = {}; - this.settings = {}; - this.redirects = {}; - this.isCallbacks = {}; - this._locals = {}; - this.dynamicViewHelpers = {}; - this.errorHandlers = []; - - this.set('env', process.env.NODE_ENV || 'development'); - - // expose objects to each other - this.use(function(req, res, next){ - req.query = req.query || {}; - res.setHeader('X-Powered-By', 'Express'); - req.app = res.app = self; - req.res = res; - res.req = req; - req.next = next; - // assign req.query - if (req.url.indexOf('?') > 0) { - var query = url.parse(req.url).query; - req.query = qs.parse(query); - } - next(); - }); - - // apply middleware - if (middleware) middleware.forEach(self.use.bind(self)); - - // router - this.routes = new Router(this); - this.__defineGetter__('router', function(){ - this.__usedRouter = true; - return self.routes.middleware; - }); - - // default locals - this.locals({ - settings: this.settings - , app: this - }); - - // default development configuration - this.configure('development', function(){ - this.enable('hints'); - }); - - // default production configuration - this.configure('production', function(){ - this.enable('view cache'); - }); - - // register error handlers on "listening" - // so that they disregard definition position. - this.on('listening', this.registerErrorHandlers.bind(this)); - - // route manipulation methods - methods.forEach(function(method){ - self.lookup[method] = function(path){ - return self.routes.lookup(method, path); - }; - - self.match[method] = function(path){ - return self.routes.match(method, path); - }; - - self.remove[method] = function(path){ - return self.routes.lookup(method, path).remove(); - }; - }); - - // del -> delete - self.lookup.del = self.lookup.delete; - self.match.del = self.match.delete; - self.remove.del = self.remove.delete; -}; - -/** - * Remove routes matching the given `path`. - * - * @param {Route} path - * @return {Boolean} - * @api public - */ - -app.remove = function(path){ - return this.routes.lookup('all', path).remove(); -}; - -/** - * Lookup routes defined with a path - * equivalent to `path`. - * - * @param {Stirng} path - * @return {Array} - * @api public - */ - -app.lookup = function(path){ - return this.routes.lookup('all', path); -}; - -/** - * Lookup routes matching the given `url`. - * - * @param {Stirng} url - * @return {Array} - * @api public - */ - -app.match = function(url){ - return this.routes.match('all', url); -}; - -/** - * When using the vhost() middleware register error handlers. - */ - -app.onvhost = function(){ - this.registerErrorHandlers(); -}; - -/** - * Register error handlers. - * - * @return {Server} for chaining - * @api public - */ - -app.registerErrorHandlers = function(){ - this.errorHandlers.forEach(function(fn){ - this.use(function(err, req, res, next){ - fn.apply(this, arguments); - }); - }, this); - return this; -}; - -/** - * Proxy `connect.HTTPServer#use()` to apply settings to - * mounted applications. - * - * @param {String|Function|Server} route - * @param {Function|Server} middleware - * @return {Server} for chaining - * @api public - */ - -app.use = function(route, middleware){ - var app, base, handle; - - if ('string' != typeof route) { - middleware = route, route = '/'; - } - - // express app - if (middleware.handle && middleware.set) app = middleware; - - // restore .app property on req and res - if (app) { - app.route = route; - middleware = function(req, res, next) { - var orig = req.app; - app.handle(req, res, function(err){ - req.app = res.app = orig; - next(err); - }); - }; - } - - connect.HTTPServer.prototype.use.call(this, route, middleware); - - // mounted an app, invoke the hook - // and adjust some settings - if (app) { - base = this.set('basepath') || this.route; - if ('/' == base) base = ''; - base = base + (app.set('basepath') || app.route); - app.set('basepath', base); - app.parent = this; - if (app.__mounted) app.__mounted.call(app, this); - } - - return this; -}; - -/** - * Assign a callback `fn` which is called - * when this `Server` is passed to `Server#use()`. - * - * Examples: - * - * var app = express.createServer() - * , blog = express.createServer(); - * - * blog.mounted(function(parent){ - * // parent is app - * // "this" is blog - * }); - * - * app.use(blog); - * - * @param {Function} fn - * @return {Server} for chaining - * @api public - */ - -app.mounted = function(fn){ - this.__mounted = fn; - return this; -}; - -/** - * See: view.register. - * - * @return {Server} for chaining - * @api public - */ - -app.register = function(){ - view.register.apply(this, arguments); - return this; -}; - -/** - * Register the given view helpers `obj`. This method - * can be called several times to apply additional helpers. - * - * @param {Object} obj - * @return {Server} for chaining - * @api public - */ - -app.helpers = -app.locals = function(obj){ - utils.merge(this._locals, obj); - return this; -}; - -/** - * Register the given dynamic view helpers `obj`. This method - * can be called several times to apply additional helpers. - * - * @param {Object} obj - * @return {Server} for chaining - * @api public - */ - -app.dynamicHelpers = function(obj){ - utils.merge(this.dynamicViewHelpers, obj); - return this; -}; - -/** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Param mapping is used to provide pre-conditions to routes - * which us normalized placeholders. This callback has the same - * signature as regular middleware, for example below when ":userId" - * is used this function will be invoked in an attempt to load the user. - * - * app.param('userId', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * Passing a single function allows you to map logic - * to the values passed to `app.param()`, for example - * this is useful to provide coercion support in a concise manner. - * - * The following example maps regular expressions to param values - * ensuring that they match, otherwise passing control to the next - * route: - * - * app.param(function(name, regexp){ - * if (regexp instanceof RegExp) { - * return function(req, res, next, val){ - * var captures; - * if (captures = regexp.exec(String(val))) { - * req.params[name] = captures; - * next(); - * } else { - * next('route'); - * } - * } - * } - * }); - * - * We can now use it as shown below, where "/commit/:commit" expects - * that the value for ":commit" is at 5 or more digits. The capture - * groups are then available as `req.params.commit` as we defined - * in the function above. - * - * app.param('commit', /^\d{5,}$/); - * - * For more of this useful functionality take a look - * at [express-params](http://github.com/visionmedia/express-params). - * - * @param {String|Array|Function} name - * @param {Function} fn - * @return {Server} for chaining - * @api public - */ - -app.param = function(name, fn){ - var self = this - , fns = [].slice.call(arguments, 1); - - // array - if (Array.isArray(name)) { - name.forEach(function(name){ - fns.forEach(function(fn){ - self.param(name, fn); - }); - }); - // param logic - } else if ('function' == typeof name) { - this.routes.param(name); - // single - } else { - if (':' == name[0]) name = name.substr(1); - fns.forEach(function(fn){ - self.routes.param(name, fn); - }); - } - - return this; -}; - -/** - * Assign a custom exception handler callback `fn`. - * These handlers are always _last_ in the middleware stack. - * - * @param {Function} fn - * @return {Server} for chaining - * @api public - */ - -app.error = function(fn){ - this.errorHandlers.push(fn); - return this; -}; - -/** - * Register the given callback `fn` for the given `type`. - * - * @param {String} type - * @param {Function} fn - * @return {Server} for chaining - * @api public - */ - -app.is = function(type, fn){ - if (!fn) return this.isCallbacks[type]; - this.isCallbacks[type] = fn; - return this; -}; - -/** - * Assign `setting` to `val`, or return `setting`'s value. - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {String} val - * @return {Server|Mixed} for chaining, or the setting value - * @api public - */ - -app.set = function(setting, val){ - if (val === undefined) { - if (this.settings.hasOwnProperty(setting)) { - return this.settings[setting]; - } else if (this.parent) { - return this.parent.set(setting); - } - } else { - this.settings[setting] = val; - return this; - } -}; - -/** - * Check if `setting` is enabled. - * - * @param {String} setting - * @return {Boolean} - * @api public - */ - -app.enabled = function(setting){ - return !!this.set(setting); -}; - -/** - * Check if `setting` is disabled. - * - * @param {String} setting - * @return {Boolean} - * @api public - */ - -app.disabled = function(setting){ - return !this.set(setting); -}; - -/** - * Enable `setting`. - * - * @param {String} setting - * @return {Server} for chaining - * @api public - */ - -app.enable = function(setting){ - return this.set(setting, true); -}; - -/** - * Disable `setting`. - * - * @param {String} setting - * @return {Server} for chaining - * @api public - */ - -app.disable = function(setting){ - return this.set(setting, false); -}; - -/** - * Redirect `key` to `url`. - * - * @param {String} key - * @param {String} url - * @return {Server} for chaining - * @api public - */ - -app.redirect = function(key, url){ - this.redirects[key] = url; - return this; -}; - -/** - * Configure callback for zero or more envs, - * when no env is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * @param {String} env... - * @param {Function} fn - * @return {Server} for chaining - * @api public - */ - -app.configure = function(env, fn){ - var envs = 'all' - , args = toArray(arguments); - fn = args.pop(); - if (args.length) envs = args; - if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this); - return this; -}; - -/** - * Delegate `.VERB(...)` calls to `.route(VERB, ...)`. - */ - -methods.forEach(function(method){ - app[method] = function(path){ - if (1 == arguments.length) return this.routes.lookup(method, path); - var args = [method].concat(toArray(arguments)); - if (!this.__usedRouter) this.use(this.router); - return this.routes._route.apply(this.routes, args); - } -}); - -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {Server} for chaining - * @api public - */ - -app.all = function(path){ - var args = arguments; - if (1 == args.length) return this.routes.lookup('all', path); - methods.forEach(function(method){ - if ('all' == method) return; - app[method].apply(this, args); - }, this); - return this; -}; - -// del -> delete alias - -app.del = app.delete; - diff --git a/node_modules/express/lib/https.js b/node_modules/express/lib/https.js deleted file mode 100644 index 8a8c008..0000000 --- a/node_modules/express/lib/https.js +++ /dev/null @@ -1,52 +0,0 @@ - -/*! - * Express - HTTPSServer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var connect = require('connect') - , HTTPServer = require('./http') - , https = require('https'); - -/** - * Expose `HTTPSServer`. - */ - -exports = module.exports = HTTPSServer; - -/** - * Server proto. - */ - -var app = HTTPSServer.prototype; - -/** - * Initialize a new `HTTPSServer` with the - * given `options`, and optional `middleware`. - * - * @param {Object} options - * @param {Array} middleware - * @api public - */ - -function HTTPSServer(options, middleware){ - connect.HTTPSServer.call(this, options, []); - this.init(middleware); -}; - -/** - * Inherit from `connect.HTTPSServer`. - */ - -app.__proto__ = connect.HTTPSServer.prototype; - -// mixin HTTPServer methods - -Object.keys(HTTPServer.prototype).forEach(function(method){ - app[method] = HTTPServer.prototype[method]; -}); diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js deleted file mode 100644 index bc95eae..0000000 --- a/node_modules/express/lib/request.js +++ /dev/null @@ -1,321 +0,0 @@ - -/*! - * Express - request - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , req = http.IncomingMessage.prototype - , utils = require('./utils') - , parse = require('url').parse - , mime = require('mime'); - -/** - * Default flash formatters. - * - * @type Object - */ - -var flashFormatters = exports.flashFormatters = { - s: function(val){ - return String(val); - } -}; - -/** - * Return request header or optional default. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` will yield are - * interchangeable. - * - * Examples: - * - * req.header('Content-Type'); - * // => "text/plain" - * - * req.header('content-type'); - * // => "text/plain" - * - * req.header('Accept'); - * // => undefined - * - * req.header('Accept', 'text/html'); - * // => "text/html" - * - * @param {String} name - * @param {String} defaultValue - * @return {String} - * @api public - */ - -req.header = function(name, defaultValue){ - switch (name = name.toLowerCase()) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer - || defaultValue; - default: - return this.headers[name] || defaultValue; - } -}; - -/** - * Get `field`'s `param` value, defaulting to ''. - * - * Examples: - * - * req.get('content-disposition', 'filename'); - * // => "something.png" - * - * @param {String} field - * @param {String} param - * @return {String} - * @api public - */ - -req.get = function(field, param){ - var val = this.header(field); - if (!val) return ''; - var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i'); - if (!regexp.exec(val)) return ''; - return RegExp.$1 || RegExp.$2; -}; - -/** - * Short-hand for `require('url').parse(req.url).pathname`. - * - * @return {String} - * @api public - */ - -req.__defineGetter__('path', function(){ - return parse(this.url).pathname; -}); - -/** - * Check if the _Accept_ header is present, and includes the given `type`. - * - * When the _Accept_ header is not present `true` is returned. Otherwise - * the given `type` is matched by an exact match, and then subtypes. You - * may pass the subtype such as "html" which is then converted internally - * to "text/html" using the mime lookup table. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => true - * - * // Accept: text/*; application/json - * req.accepts('html'); - * req.accepts('text/html'); - * req.accepts('text/plain'); - * req.accepts('application/json'); - * // => true - * - * req.accepts('image/png'); - * req.accepts('png'); - * // => false - * - * @param {String} type - * @return {Boolean} - * @api public - */ - -req.accepts = function(type){ - var accept = this.header('Accept'); - - // normalize extensions ".json" -> "json" - if (type && '.' == type[0]) type = type.substr(1); - - // when Accept does not exist, or is '*/*' return true - if (!accept || '*/*' == accept) { - return true; - } else if (type) { - // allow "html" vs "text/html" etc - if (!~type.indexOf('/')) type = mime.lookup(type); - - // check if we have a direct match - if (~accept.indexOf(type)) return true; - - // check if we have type/* - type = type.split('/')[0] + '/*'; - return !!~accept.indexOf(type); - } else { - return false; - } -}; - -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks query string params, ex: ?id=12 - * - Checks urlencoded body params, ex: id=12 - * - * To utilize urlencoded request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser` middleware. - * - * @param {String} name - * @param {Mixed} defaultValue - * @return {String} - * @api public - */ - -req.param = function(name, defaultValue){ - // route params like /user/:id - if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) { - return this.params[name]; - } - // query string params - if (undefined !== this.query[name]) { - return this.query[name]; - } - // request body params via connect.bodyParser - if (this.body && undefined !== this.body[name]) { - return this.body[name]; - } - return defaultValue; -}; - -/** - * Queue flash `msg` of the given `type`. - * - * Examples: - * - * req.flash('info', 'email sent'); - * req.flash('error', 'email delivery failed'); - * req.flash('info', 'email re-sent'); - * // => 2 - * - * req.flash('info'); - * // => ['email sent', 'email re-sent'] - * - * req.flash('info'); - * // => [] - * - * req.flash(); - * // => { error: ['email delivery failed'], info: [] } - * - * Formatting: - * - * Flash notifications also support arbitrary formatting support. - * For example you may pass variable arguments to `req.flash()` - * and use the %s specifier to be replaced by the associated argument: - * - * req.flash('info', 'email has been sent to %s.', userName); - * - * To add custom formatters use the `exports.flashFormatters` object. - * - * @param {String} type - * @param {String} msg - * @return {Array|Object|Number} - * @api public - */ - -req.flash = function(type, msg){ - if (this.session === undefined) throw Error('req.flash() requires sessions'); - var msgs = this.session.flash = this.session.flash || {}; - if (type && msg) { - var i = 2 - , args = arguments - , formatters = this.app.flashFormatters || {}; - formatters.__proto__ = flashFormatters; - msg = utils.miniMarkdown(msg); - msg = msg.replace(/%([a-zA-Z])/g, function(_, format){ - var formatter = formatters[format]; - if (formatter) return formatter(utils.escape(args[i++])); - }); - return (msgs[type] = msgs[type] || []).push(msg); - } else if (type) { - var arr = msgs[type]; - delete msgs[type]; - return arr || []; - } else { - this.session.flash = {}; - return msgs; - } -}; - -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * // => true - * - * req.is('html'); - * // => false - * - * Ad-hoc callbacks can also be registered with Express, to perform - * assertions again the request, for example if we need an expressive - * way to check if our incoming request is an image, we can register "an image" - * callback: - * - * app.is('an image', function(req){ - * return 0 == req.headers['content-type'].indexOf('image'); - * }); - * - * Now within our route callbacks, we can use to to assert content types - * such as "image/jpeg", "image/png", etc. - * - * app.post('/image/upload', function(req, res, next){ - * if (req.is('an image')) { - * // do something - * } else { - * next(); - * } - * }); - * - * @param {String} type - * @return {Boolean} - * @api public - */ - -req.is = function(type){ - var fn = this.app.is(type); - if (fn) return fn(this); - var contentType = this.headers['content-type']; - if (!contentType) return; - if (!~type.indexOf('/')) type = mime.lookup(type); - if (~type.indexOf('*')) { - type = type.split('/') - contentType = contentType.split('/'); - if ('*' == type[0] && type[1] == contentType[1]) return true; - if ('*' == type[1] && type[0] == contentType[0]) return true; - } - return !! ~contentType.indexOf(type); -}; - -// Callback for isXMLHttpRequest / xhr - -function isxhr() { - return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest'; -} - -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @api public - */ - -req.__defineGetter__('isXMLHttpRequest', isxhr); -req.__defineGetter__('xhr', isxhr); diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js deleted file mode 100644 index a671771..0000000 --- a/node_modules/express/lib/response.js +++ /dev/null @@ -1,460 +0,0 @@ - -/*! - * Express - response - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , http = require('http') - , path = require('path') - , connect = require('connect') - , utils = connect.utils - , parseRange = require('./utils').parseRange - , res = http.ServerResponse.prototype - , send = connect.static.send - , mime = require('mime') - , basename = path.basename - , join = path.join; - -/** - * Send a response with the given `body` and optional `headers` and `status` code. - * - * Examples: - * - * res.send(); - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send('Sorry, cant find that', 404); - * res.send('text', { 'Content-Type': 'text/plain' }, 201); - * res.send(404); - * - * @param {String|Object|Number|Buffer} body or status - * @param {Object|Number} headers or status - * @param {Number} status - * @return {ServerResponse} - * @api public - */ - -res.send = function(body, headers, status){ - // allow status as second arg - if ('number' == typeof headers) { - status = headers, - headers = null; - } - - // default status - status = status || this.statusCode; - - // allow 0 args as 204 - if (!arguments.length || undefined === body) status = 204; - - // determine content type - switch (typeof body) { - case 'number': - if (!this.header('Content-Type')) { - this.contentType('.txt'); - } - body = http.STATUS_CODES[status = body]; - break; - case 'string': - if (!this.header('Content-Type')) { - this.charset = this.charset || 'utf-8'; - this.contentType('.html'); - } - break; - case 'boolean': - case 'object': - if (Buffer.isBuffer(body)) { - if (!this.header('Content-Type')) { - this.contentType('.bin'); - } - } else { - return this.json(body, headers, status); - } - break; - } - - // populate Content-Length - if (undefined !== body && !this.header('Content-Length')) { - this.header('Content-Length', Buffer.isBuffer(body) - ? body.length - : Buffer.byteLength(body)); - } - - // merge headers passed - if (headers) { - var fields = Object.keys(headers); - for (var i = 0, len = fields.length; i < len; ++i) { - var field = fields[i]; - this.header(field, headers[field]); - } - } - - // strip irrelevant headers - if (204 == status || 304 == status) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - body = ''; - } - - // respond - this.statusCode = status; - this.end('HEAD' == this.req.method ? null : body); - return this; -}; - -/** - * Send JSON response with `obj`, optional `headers`, and optional `status`. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json('oh noes!', 500); - * res.json('I dont have that', 404); - * - * @param {Mixed} obj - * @param {Object|Number} headers or status - * @param {Number} status - * @return {ServerResponse} - * @api public - */ - -res.json = function(obj, headers, status){ - var body = JSON.stringify(obj) - , callback = this.req.query.callback - , jsonp = this.app.enabled('jsonp callback'); - - this.charset = this.charset || 'utf-8'; - this.header('Content-Type', 'application/json'); - - if (callback && jsonp) { - this.header('Content-Type', 'text/javascript'); - body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');'; - } - - return this.send(body, headers, status); -}; - -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @api public - */ - -res.status = function(code){ - this.statusCode = code; - return this; -}; - -/** - * Transfer the file at the given `path`. Automatically sets - * the _Content-Type_ response header field. `next()` is called - * when `path` is a directory, or when an error occurs. - * - * Options: - * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames - * - * @param {String} path - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -res.sendfile = function(path, options, fn){ - var next = this.req.next; - options = options || {}; - - // support function as second arg - if ('function' == typeof options) { - fn = options; - options = {}; - } - - options.path = encodeURIComponent(path); - options.callback = fn; - send(this.req, this, next, options); -}; - -/** - * Set _Content-Type_ response header passed through `mime.lookup()`. - * - * Examples: - * - * var filename = 'path/to/image.png'; - * res.contentType(filename); - * // res.headers['Content-Type'] is now "image/png" - * - * res.contentType('.html'); - * res.contentType('html'); - * res.contentType('json'); - * res.contentType('png'); - * - * @param {String} type - * @return {String} the resolved mime type - * @api public - */ - -res.contentType = function(type){ - return this.header('Content-Type', mime.lookup(type)); -}; - -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @api public - */ - -res.attachment = function(filename){ - if (filename) this.contentType(filename); - this.header('Content-Disposition', filename - ? 'attachment; filename="' + basename(filename) + '"' - : 'attachment'); - return this; -}; - -/** - * Transfer the file at the given `path`, with optional - * `filename` as an attachment and optional callback `fn(err)`, - * and optional `fn2(err)` which is invoked when an error has - * occurred after header has been sent. - * - * @param {String} path - * @param {String|Function} filename or fn - * @param {Function} fn - * @param {Function} fn2 - * @api public - */ - -res.download = function(path, filename, fn, fn2){ - var self = this; - - // support callback as second arg - if ('function' == typeof filename) { - fn2 = fn; - fn = filename; - filename = null; - } - - // transfer the file - this.attachment(filename || path).sendfile(path, function(err){ - var sentHeader = self._header; - if (err) { - if (!sentHeader) self.removeHeader('Content-Disposition'); - if (sentHeader) { - fn2 && fn2(err); - } else if (fn) { - fn(err); - } else { - self.req.next(err); - } - } else if (fn) { - fn(); - } - }); -}; - -/** - * Set or get response header `name` with optional `val`. - * - * @param {String} name - * @param {String} val - * @return {ServerResponse} for chaining - * @api public - */ - -res.header = function(name, val){ - if (1 == arguments.length) return this.getHeader(name); - this.setHeader(name, val); - return this; -}; - -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} options - * @api public - */ - -res.clearCookie = function(name, options){ - var opts = { expires: new Date(1) }; - this.cookie(name, '', options - ? utils.merge(options, opts) - : opts); -}; - -/** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `path` defaults to the "basepath" setting which is typically "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String} val - * @param {Options} options - * @api public - */ - -res.cookie = function(name, val, options){ - options = options || {}; - if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge); - if (undefined === options.path) options.path = this.app.set('basepath'); - var cookie = utils.serializeCookie(name, val, options); - this.header('Set-Cookie', cookie); -}; - -/** - * Redirect to the given `url` with optional response `status` - * defauling to 302. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or the application's - * "basepath" setting. Express also supports "basepath" out of the box, - * which can be set via `app.set('basepath', '/blog');`, and defaults - * to '/'. - * - * Redirect Mapping: - * - * To extend the redirect mapping capabilities that Express provides, - * we may use the `app.redirect()` method: - * - * app.redirect('google', 'http://google.com'); - * - * Now in a route we may call: - * - * res.redirect('google'); - * - * We may also map dynamic redirects: - * - * app.redirect('comments', function(req, res){ - * return '/post/' + req.params.id + '/comments'; - * }); - * - * So now we may do the following, and the redirect will dynamically adjust to - * the context of the request. If we called this route with _GET /post/12_ our - * redirect _Location_ would be _/post/12/comments_. - * - * app.get('/post/:id', function(req, res){ - * res.redirect('comments'); - * }); - * - * Unless an absolute `url` is given, the app's mount-point - * will be respected. For example if we redirect to `/posts`, - * and our app is mounted at `/blog` we will redirect to `/blog/posts`. - * - * @param {String} url - * @param {Number} code - * @api public - */ - -res.redirect = function(url, status){ - var app = this.app - , req = this.req - , base = app.set('basepath') || app.route - , status = status || 302 - , head = 'HEAD' == req.method - , body; - - // Setup redirect map - var map = { - back: req.header('Referrer', base) - , home: base - }; - - // Support custom redirect map - map.__proto__ = app.redirects; - - // Attempt mapped redirect - var mapped = 'function' == typeof map[url] - ? map[url](req, this) - : map[url]; - - // Perform redirect - url = mapped || url; - - // Relative - if (!~url.indexOf('://')) { - // Respect mount-point - if ('/' != base && 0 != url.indexOf(base)) url = base + url; - - // Absolute - var host = req.headers.host - , tls = req.connection.encrypted; - url = 'http' + (tls ? 's' : '') + '://' + host + url; - } - - // Support text/{plain,html} by default - if (req.accepts('html')) { - body = '

' + http.STATUS_CODES[status] + '. Redirecting to ' + url + '

'; - this.header('Content-Type', 'text/html'); - } else { - body = http.STATUS_CODES[status] + '. Redirecting to ' + url; - this.header('Content-Type', 'text/plain'); - } - - // Respond - this.statusCode = status; - this.header('Location', url); - this.end(head ? null : body); -}; - -/** - * Assign the view local variable `name` to `val` or return the - * local previously assigned to `name`. - * - * @param {String} name - * @param {Mixed} val - * @return {Mixed} val - * @api public - */ - -res.local = function(name, val){ - this._locals = this._locals || {}; - return undefined === val - ? this._locals[name] - : this._locals[name] = val; -}; - -/** - * Assign several locals with the given `obj`, - * or return the locals. - * - * @param {Object} obj - * @return {Object|Undefined} - * @api public - */ - -res.locals = -res.helpers = function(obj){ - if (obj) { - for (var key in obj) { - this.local(key, obj[key]); - } - } else { - return this._locals; - } -}; diff --git a/node_modules/express/lib/router/collection.js b/node_modules/express/lib/router/collection.js deleted file mode 100644 index 991a9a2..0000000 --- a/node_modules/express/lib/router/collection.js +++ /dev/null @@ -1,53 +0,0 @@ - -/*! - * Express - router - Collection - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Expose `Collection`. - */ - -module.exports = Collection; - -/** - * Initialize a new route `Collection` - * with the given `router`. - * - * @param {Router} router - * @api private - */ - -function Collection(router) { - Array.apply(this, arguments); - this.router = router; -} - -/** - * Inherit from `Array.prototype`. - */ - -Collection.prototype.__proto__ = Array.prototype; - -/** - * Remove the routes in this collection. - * - * @return {Collection} of routes removed - * @api public - */ - -Collection.prototype.remove = function(){ - var router = this.router - , len = this.length - , ret = new Collection(this.router); - - for (var i = 0; i < len; ++i) { - if (router.remove(this[i])) { - ret.push(this[i]); - } - } - - return ret; -}; - diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js deleted file mode 100644 index ff1498b..0000000 --- a/node_modules/express/lib/router/index.js +++ /dev/null @@ -1,398 +0,0 @@ - -/*! - * Express - Router - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Route = require('./route') - , Collection = require('./collection') - , utils = require('../utils') - , parse = require('url').parse - , toArray = utils.toArray; - -/** - * Expose `Router` constructor. - */ - -exports = module.exports = Router; - -/** - * Expose HTTP methods. - */ - -var methods = exports.methods = require('./methods'); - -/** - * Initialize a new `Router` with the given `app`. - * - * @param {express.HTTPServer} app - * @api private - */ - -function Router(app) { - var self = this; - this.app = app; - this.routes = {}; - this.params = {}; - this._params = []; - - this.middleware = function(req, res, next){ - self._dispatch(req, res, next); - }; -} - -/** - * Register a param callback `fn` for the given `name`. - * - * @param {String|Function} name - * @param {Function} fn - * @return {Router} for chaining - * @api public - */ - -Router.prototype.param = function(name, fn){ - // param logic - if ('function' == typeof name) { - this._params.push(name); - return; - } - - // apply param functions - var params = this._params - , len = params.length - , ret; - - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } - - // ensure we end up with a - // middleware function - if ('function' != typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } - - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Return a `Collection` of all routes defined. - * - * @return {Collection} - * @api public - */ - -Router.prototype.all = function(){ - return this.find(function(){ - return true; - }); -}; - -/** - * Remove the given `route`, returns - * a bool indicating if the route was present - * or not. - * - * @param {Route} route - * @return {Boolean} - * @api public - */ - -Router.prototype.remove = function(route){ - var routes = this.routes[route.method] - , len = routes.length; - - for (var i = 0; i < len; ++i) { - if (route == routes[i]) { - routes.splice(i, 1); - return true; - } - } -}; - -/** - * Return routes with route paths matching `path`. - * - * @param {String} method - * @param {String} path - * @return {Collection} - * @api public - */ - -Router.prototype.lookup = function(method, path){ - return this.find(function(route){ - return path == route.path - && (route.method == method - || method == 'all'); - }); -}; - -/** - * Return routes with regexps that match the given `url`. - * - * @param {String} method - * @param {String} url - * @return {Collection} - * @api public - */ - -Router.prototype.match = function(method, url){ - return this.find(function(route){ - return route.match(url) - && (route.method == method - || method == 'all'); - }); -}; - -/** - * Find routes based on the return value of `fn` - * which is invoked once per route. - * - * @param {Function} fn - * @return {Collection} - * @api public - */ - -Router.prototype.find = function(fn){ - var len = methods.length - , ret = new Collection(this) - , method - , routes - , route; - - for (var i = 0; i < len; ++i) { - method = methods[i]; - routes = this.routes[method]; - if (!routes) continue; - for (var j = 0, jlen = routes.length; j < jlen; ++j) { - route = routes[j]; - if (fn(route)) ret.push(route); - } - } - - return ret; -}; - -/** - * Route dispatcher aka the route "middleware". - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @param {Function} next - * @api private - */ - -Router.prototype._dispatch = function(req, res, next){ - var params = this.params - , self = this; - - // route dispatch - (function pass(i, err){ - var paramCallbacks - , paramIndex = 0 - , paramVal - , route - , keys - , key - , ret; - - // match next route - function nextRoute(err) { - pass(req._route_index + 1, err); - } - - // match route - req.route = route = self._match(req, i); - - // implied OPTIONS - if (!route && 'OPTIONS' == req.method) return self._options(req, res); - - // no route - if (!route) return next(err); - - // we have a route - // start at param 0 - req.params = route.params; - keys = route.keys; - i = 0; - - // param callbacks - function param(err) { - paramIndex = 0; - key = keys[i++]; - paramVal = key && req.params[key.name]; - paramCallbacks = key && params[key.name]; - - try { - if ('route' == err) { - nextRoute(); - } else if (err) { - i = 0; - callbacks(err); - } else if (paramCallbacks && undefined !== paramVal) { - paramCallback(); - } else if (key) { - param(); - } else { - i = 0; - callbacks(); - } - } catch (err) { - param(err); - } - }; - - param(err); - - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - if (err || !fn) return param(err); - fn(req, res, paramCallback, paramVal, key.name); - } - - // invoke route callbacks - function callbacks(err) { - var fn = route.callbacks[i++]; - try { - if ('route' == err) { - nextRoute(); - } else if (err && fn) { - if (fn.length < 4) return callbacks(err); - fn(err, req, res, callbacks); - } else if (fn) { - fn(req, res, callbacks); - } else { - nextRoute(err); - } - } catch (err) { - callbacks(err); - } - } - })(0); -}; - -/** - * Respond to __OPTIONS__ method. - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @api private - */ - -Router.prototype._options = function(req, res){ - var path = parse(req.url).pathname - , body = this._optionsFor(path).join(','); - res.send(body, { Allow: body }); -}; - -/** - * Return an array of HTTP verbs or "options" for `path`. - * - * @param {String} path - * @return {Array} - * @api private - */ - -Router.prototype._optionsFor = function(path){ - var self = this; - return methods.filter(function(method){ - var routes = self.routes[method]; - if (!routes || 'options' == method) return; - for (var i = 0, len = routes.length; i < len; ++i) { - if (routes[i].match(path)) return true; - } - }).map(function(method){ - return method.toUpperCase(); - }); -}; - -/** - * Attempt to match a route for `req` - * starting from offset `i`. - * - * @param {IncomingMessage} req - * @param {Number} i - * @return {Route} - * @api private - */ - -Router.prototype._match = function(req, i){ - var method = req.method.toLowerCase() - , url = parse(req.url) - , path = url.pathname - , routes = this.routes - , captures - , route - , keys; - - // pass HEAD to GET routes - if ('head' == method) method = 'get'; - - // routes for this method - if (routes = routes[method]) { - - // matching routes - for (var len = routes.length; i < len; ++i) { - route = routes[i]; - if (captures = route.match(path)) { - keys = route.keys; - route.params = []; - - // params from capture groups - for (var j = 1, jlen = captures.length; j < jlen; ++j) { - var key = keys[j-1] - , val = 'string' == typeof captures[j] - ? decodeURIComponent(captures[j]) - : captures[j]; - if (key) { - route.params[key.name] = val; - } else { - route.params.push(val); - } - } - - // all done - req._route_index = i; - return route; - } - } - } -}; - -/** - * Route `method`, `path`, and one or more callbacks. - * - * @param {String} method - * @param {String} path - * @param {Function} callback... - * @return {Router} for chaining - * @api private - */ - -Router.prototype._route = function(method, path, callbacks){ - var app = this.app - , callbacks = utils.flatten(toArray(arguments, 2)); - - // ensure path was given - if (!path) throw new Error('app.' + method + '() requires a path'); - - // create the route - var route = new Route(method, path, callbacks, { - sensitive: app.enabled('case sensitive routes') - , strict: app.enabled('strict routing') - }); - - // add it - (this.routes[method] = this.routes[method] || []) - .push(route); - return this; -}; diff --git a/node_modules/express/lib/router/methods.js b/node_modules/express/lib/router/methods.js deleted file mode 100644 index e19787b..0000000 --- a/node_modules/express/lib/router/methods.js +++ /dev/null @@ -1,70 +0,0 @@ - -/*! - * Express - router - methods - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Hypertext Transfer Protocol -- HTTP/1.1 - * http://www.ietf.org/rfc/rfc2616.txt - */ - -var RFC2616 = ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']; - -/** - * HTTP Extensions for Distributed Authoring -- WEBDAV - * http://www.ietf.org/rfc/rfc2518.txt - */ - -var RFC2518 = ['PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK']; - -/** - * Versioning Extensions to WebDAV - * http://www.ietf.org/rfc/rfc3253.txt - */ - -var RFC3253 = ['VERSION-CONTROL', 'REPORT', 'CHECKOUT', 'CHECKIN', 'UNCHECKOUT', 'MKWORKSPACE', 'UPDATE', 'LABEL', 'MERGE', 'BASELINE-CONTROL', 'MKACTIVITY']; - -/** - * Ordered Collections Protocol (WebDAV) - * http://www.ietf.org/rfc/rfc3648.txt - */ - -var RFC3648 = ['ORDERPATCH']; - -/** - * Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol - * http://www.ietf.org/rfc/rfc3744.txt - */ - -var RFC3744 = ['ACL']; - -/** - * Web Distributed Authoring and Versioning (WebDAV) SEARCH - * http://www.ietf.org/rfc/rfc5323.txt - */ - -var RFC5323 = ['SEARCH']; - -/** - * PATCH Method for HTTP - * http://www.ietf.org/rfc/rfc5789.txt - */ - -var RFC5789 = ['PATCH']; - -/** - * Expose the methods. - */ - -module.exports = [].concat( - RFC2616 - , RFC2518 - , RFC3253 - , RFC3648 - , RFC3744 - , RFC5323 - , RFC5789).map(function(method){ - return method.toLowerCase(); - }); diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js deleted file mode 100644 index 7f2965c..0000000 --- a/node_modules/express/lib/router/route.js +++ /dev/null @@ -1,88 +0,0 @@ - -/*! - * Express - router - Route - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Expose `Route`. - */ - -module.exports = Route; - -/** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param {String} method - * @param {String} path - * @param {Array} callbacks - * @param {Object} options. - * @api private - */ - -function Route(method, path, callbacks, options) { - options = options || {}; - this.path = path; - this.method = method; - this.callbacks = callbacks; - this.regexp = normalize(path - , this.keys = [] - , options.sensitive - , options.strict); -} - -/** - * Check if this route matches `path` and return captures made. - * - * @param {String} path - * @return {Array} - * @api private - */ - -Route.prototype.match = function(path){ - return this.regexp.exec(path); -}; - -/** - * Normalize the given path string, - * returning a regular expression. - * - * An empty array should be passed, - * which will contain the placeholder - * key names. For example "/user/:id" will - * then contain ["id"]. - * - * @param {String|RegExp} path - * @param {Array} keys - * @param {Boolean} sensitive - * @param {Boolean} strict - * @return {RegExp} - * @api private - */ - -function normalize(path, keys, sensitive, strict) { - if (path instanceof RegExp) return path; - path = path - .concat(strict ? '' : '/?') - .replace(/\/\(/g, '(?:/') - .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){ - keys.push({ name: key, optional: !! optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' - + (optional || ''); - }) - .replace(/([\/.])/g, '\\$1') - .replace(/\*/g, '(.*)'); - return new RegExp('^' + path + '$', sensitive ? '' : 'i'); -} diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js deleted file mode 100644 index d579f7c..0000000 --- a/node_modules/express/lib/utils.js +++ /dev/null @@ -1,152 +0,0 @@ - -/*! - * Express - Utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -exports.isAbsolute = function(path){ - if ('/' == path[0]) return true; - if (':' == path[1] && '\\' == path[2]) return true; -}; - -/** - * Merge object `b` with `a` giving precedence to - * values in object `a`. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.union = function(a, b){ - if (a && b) { - var keys = Object.keys(b) - , len = keys.length - , key; - for (var i = 0; i < len; ++i) { - key = keys[i]; - if (!a.hasOwnProperty(key)) { - a[key] = b[key]; - } - } - } - return a; -}; - -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = function(arr, ret){ - var ret = ret || [] - , len = arr.length; - for (var i = 0; i < len; ++i) { - if (Array.isArray(arr[i])) { - exports.flatten(arr[i], ret); - } else { - ret.push(arr[i]); - } - } - return ret; -}; - -/** - * Parse mini markdown implementation. - * The following conversions are supported, - * primarily for the "flash" middleware: - * - * _foo_ or *foo* become foo - * __foo__ or **foo** become foo - * [A](B) becomes A - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.miniMarkdown = function(str){ - return String(str) - .replace(/(__|\*\*)(.*?)\1/g, '$2') - .replace(/(_|\*)(.*?)\1/g, '$2') - .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); -}; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Parse "Range" header `str` relative to the given file `size`. - * - * @param {Number} size - * @param {String} str - * @return {Array} - * @api private - */ - -exports.parseRange = function(size, str){ - var valid = true; - var arr = str.substr(6).split(',').map(function(range){ - var range = range.split('-') - , start = parseInt(range[0], 10) - , end = parseInt(range[1], 10); - - // -500 - if (isNaN(start)) { - start = size - end; - end = size - 1; - // 500- - } else if (isNaN(end)) { - end = size - 1; - } - - // Invalid - if (isNaN(start) || isNaN(end) || start > end) valid = false; - - return { start: start, end: end }; - }); - return valid ? arr : undefined; -}; - -/** - * Fast alternative to `Array.prototype.slice.call()`. - * - * @param {Arguments} args - * @param {Number} n - * @return {Array} - * @api public - */ - -exports.toArray = function(args, i){ - var arr = [] - , len = args.length - , i = i || 0; - for (; i < len; ++i) arr.push(args[i]); - return arr; -}; diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js deleted file mode 100644 index 876d795..0000000 --- a/node_modules/express/lib/view.js +++ /dev/null @@ -1,457 +0,0 @@ - -/*! - * Express - view - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('path') - , extname = path.extname - , dirname = path.dirname - , basename = path.basename - , utils = require('connect').utils - , View = require('./view/view') - , partial = require('./view/partial') - , union = require('./utils').union - , merge = utils.merge - , http = require('http') - , res = http.ServerResponse.prototype; - -/** - * Expose constructors. - */ - -exports = module.exports = View; - -/** - * Export template engine registrar. - */ - -exports.register = View.register; - -/** - * Lookup and compile `view` with cache support by supplying - * both the `cache` object and `cid` string, - * followed by `options` passed to `exports.lookup()`. - * - * @param {String} view - * @param {Object} cache - * @param {Object} cid - * @param {Object} options - * @return {View} - * @api private - */ - -exports.compile = function(view, cache, cid, options){ - if (cache && cid && cache[cid]) return cache[cid]; - - // lookup - view = exports.lookup(view, options); - - // hints - if (!view.exists) { - if (options.hint) hintAtViewPaths(view.original, options); - var err = new Error('failed to locate view "' + view.original.view + '"'); - err.view = view.original; - throw err; - } - - // compile - options.filename = view.path; - view.fn = view.templateEngine.compile(view.contents, options); - cache[cid] = view; - - return view; -}; - -/** - * Lookup `view`, returning an instanceof `View`. - * - * Options: - * - * - `root` root directory path - * - `defaultEngine` default template engine - * - `parentView` parent `View` object - * - `cache` cache object - * - `cacheid` optional cache id - * - * Lookup: - * - * - partial `_` - * - any `/index` - * - non-layout `..//index` - * - any `/` - * - partial `/_` - * - * @param {String} view - * @param {Object} options - * @return {View} - * @api private - */ - -exports.lookup = function(view, options){ - var orig = view = new View(view, options) - , partial = options.isPartial - , layout = options.isLayout; - - // Try _ prefix ex: ./views/_.jade - // taking precedence over the direct path - if (partial) { - view = new View(orig.prefixPath, options); - if (!view.exists) view = orig; - } - - // Try index ex: ./views/user/index.jade - if (!layout && !view.exists) view = new View(orig.indexPath, options); - - // Try ..//index ex: ../user/index.jade - // when calling partial('user') within the same dir - if (!layout && !view.exists) view = new View(orig.upIndexPath, options); - - // Try root ex: /user.jade - if (!view.exists) view = new View(orig.rootPath, options); - - // Try root _ prefix ex: /_user.jade - if (!view.exists && partial) view = new View(view.prefixPath, options); - - view.original = orig; - return view; -}; - -/** - * Partial render helper. - * - * @api private - */ - -function renderPartial(res, view, options, parentLocals, parent){ - var collection, object, locals; - - if (options) { - // collection - if (options.collection) { - collection = options.collection; - delete options.collection; - } else if ('length' in options) { - collection = options; - options = {}; - } - - // locals - if (options.locals) { - locals = options.locals; - delete options.locals; - } - - // object - if ('Object' != options.constructor.name) { - object = options; - options = {}; - } else if (undefined != options.object) { - object = options.object; - delete options.object; - } - } else { - options = {}; - } - - // Inherit locals from parent - union(options, parentLocals); - - // Merge locals - if (locals) merge(options, locals); - - // Partials dont need layouts - options.isPartial = true; - options.layout = false; - - // Deduce name from view path - var name = options.as || partial.resolveObjectName(view); - - // Render partial - function render(){ - if (object) { - if ('string' == typeof name) { - options[name] = object; - } else if (name === global) { - merge(options, object); - } - } - return res.render(view, options, null, parent, true); - } - - // Collection support - if (collection) { - var len = collection.length - , buf = '' - , keys - , key - , val; - - options.collectionLength = len; - - if ('number' == typeof len || Array.isArray(collection)) { - for (var i = 0; i < len; ++i) { - val = collection[i]; - options.firstInCollection = i == 0; - options.indexInCollection = i; - options.lastInCollection = i == len - 1; - object = val; - buf += render(); - } - } else { - keys = Object.keys(collection); - len = keys.length; - options.collectionLength = len; - options.collectionKeys = keys; - for (var i = 0; i < len; ++i) { - key = keys[i]; - val = collection[key]; - options.keyInCollection = key; - options.firstInCollection = i == 0; - options.indexInCollection = i; - options.lastInCollection = i == len - 1; - object = val; - buf += render(); - } - } - - return buf; - } else { - return render(); - } -}; - -/** - * Render `view` partial with the given `options`. Optionally a - * callback `fn(err, str)` may be passed instead of writing to - * the socket. - * - * Options: - * - * - `object` Single object with name derived from the view (unless `as` is present) - * - * - `as` Variable name for each `collection` value, defaults to the view name. - * * as: 'something' will add the `something` local variable - * * as: this will use the collection value as the template context - * * as: global will merge the collection value's properties with `locals` - * - * - `collection` Array of objects, the name is derived from the view name itself. - * For example _video.html_ will have a object _video_ available to it. - * - * @param {String} view - * @param {Object|Array|Function} options, collection, callback, or object - * @param {Function} fn - * @return {String} - * @api public - */ - -res.partial = function(view, options, fn){ - var app = this.app - , options = options || {} - , viewEngine = app.set('view engine') - , parent = {}; - - // accept callback as second argument - if ('function' == typeof options) { - fn = options; - options = {}; - } - - // root "views" option - parent.dirname = app.set('views') || process.cwd() + '/views'; - - // utilize "view engine" option - if (viewEngine) parent.engine = viewEngine; - - // render the partial - try { - var str = renderPartial(this, view, options, null, parent); - } catch (err) { - if (fn) { - fn(err); - } else { - this.req.next(err); - } - return; - } - - // callback or transfer - if (fn) { - fn(null, str); - } else { - this.send(str); - } -}; - -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, however otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `scope` Template evaluation context (the value of `this`) - * - `debug` Output debugging information - * - `status` Response status code - * - * @param {String} view - * @param {Object|Function} options or callback function - * @param {Function} fn - * @api public - */ - -res.render = function(view, opts, fn, parent, sub){ - // support callback function as second arg - if ('function' == typeof opts) { - fn = opts, opts = null; - } - - try { - return this._render(view, opts, fn, parent, sub); - } catch (err) { - // callback given - if (fn) { - fn(err); - // unwind to root call to prevent multiple callbacks - } else if (sub) { - throw err; - // root template, next(err) - } else { - this.req.next(err); - } - } -}; - -// private render() - -res._render = function(view, opts, fn, parent, sub){ - var options = {} - , self = this - , app = this.app - , helpers = app._locals - , dynamicHelpers = app.dynamicViewHelpers - , viewOptions = app.set('view options') - , root = app.set('views') || process.cwd() + '/views'; - - // cache id - var cid = app.enabled('view cache') - ? view + (parent ? ':' + parent.path : '') - : false; - - // merge "view options" - if (viewOptions) merge(options, viewOptions); - - // merge res._locals - if (this._locals) merge(options, this._locals); - - // merge render() options - if (opts) merge(options, opts); - - // merge render() .locals - if (opts && opts.locals) merge(options, opts.locals); - - // status support - if (options.status) this.statusCode = options.status; - - // capture attempts - options.attempts = []; - - var partial = options.isPartial - , layout = options.layout; - - // Layout support - if (true === layout || undefined === layout) { - layout = 'layout'; - } - - // Default execution scope to a plain object - options.scope = options.scope || {}; - - // Populate view - options.parentView = parent; - - // "views" setting - options.root = root; - - // "view engine" setting - options.defaultEngine = app.set('view engine'); - - // charset option - if (options.charset) this.charset = options.charset; - - // Dynamic helper support - if (false !== options.dynamicHelpers) { - // cache - if (!this.__dynamicHelpers) { - this.__dynamicHelpers = {}; - for (var key in dynamicHelpers) { - this.__dynamicHelpers[key] = dynamicHelpers[key].call( - this.app - , this.req - , this); - } - } - - // apply - merge(options, this.__dynamicHelpers); - } - - // Merge view helpers - union(options, helpers); - - // Always expose partial() as a local - options.partial = function(path, opts){ - return renderPartial(self, path, opts, options, view); - }; - - // View lookup - options.hint = app.enabled('hints'); - view = exports.compile(view, app.cache, cid, options); - - // layout helper - options.layout = function(path){ - layout = path; - }; - - // render - var str = view.fn.call(options.scope, options); - - // layout expected - if (layout) { - options.isLayout = true; - options.layout = false; - options.body = str; - this.render(layout, options, fn, view, true); - // partial return - } else if (partial) { - return str; - // render complete, and - // callback given - } else if (fn) { - fn(null, str); - // respond - } else { - this.send(str); - } -} - -/** - * Hint at view path resolution, outputting the - * paths that Express has tried. - * - * @api private - */ - -function hintAtViewPaths(view, options) { - console.error(); - console.error('failed to locate view "' + view.view + '", tried:'); - options.attempts.forEach(function(path){ - console.error(' - %s', path); - }); - console.error(); -} \ No newline at end of file diff --git a/node_modules/express/lib/view/partial.js b/node_modules/express/lib/view/partial.js deleted file mode 100644 index 7d2f69b..0000000 --- a/node_modules/express/lib/view/partial.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Express - view - Partial - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Memory cache. - */ - -var cache = {}; - -/** - * Resolve partial object name from the view path. - * - * Examples: - * - * "user.ejs" becomes "user" - * "forum thread.ejs" becomes "forumThread" - * "forum/thread/post.ejs" becomes "post" - * "blog-post.ejs" becomes "blogPost" - * - * @return {String} - * @api private - */ - -exports.resolveObjectName = function(view){ - return cache[view] || (cache[view] = view - .split('/') - .slice(-1)[0] - .split('.')[0] - .replace(/^_/, '') - .replace(/[^a-zA-Z0-9 ]+/g, ' ') - .split(/ +/).map(function(word, i){ - return i - ? word[0].toUpperCase() + word.substr(1) - : word; - }).join('')); -}; \ No newline at end of file diff --git a/node_modules/express/lib/view/view.js b/node_modules/express/lib/view/view.js deleted file mode 100644 index 7d9392c..0000000 --- a/node_modules/express/lib/view/view.js +++ /dev/null @@ -1,210 +0,0 @@ - -/*! - * Express - View - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('path') - , utils = require('../utils') - , extname = path.extname - , dirname = path.dirname - , basename = path.basename - , fs = require('fs') - , stat = fs.statSync; - -/** - * Expose `View`. - */ - -exports = module.exports = View; - -/** - * Require cache. - */ - -var cache = {}; - -/** - * Initialize a new `View` with the given `view` path and `options`. - * - * @param {String} view - * @param {Object} options - * @api private - */ - -function View(view, options) { - options = options || {}; - this.view = view; - this.root = options.root; - this.relative = false !== options.relative; - this.defaultEngine = options.defaultEngine; - this.parent = options.parentView; - this.basename = basename(view); - this.engine = this.resolveEngine(); - this.extension = '.' + this.engine; - this.name = this.basename.replace(this.extension, ''); - this.path = this.resolvePath(); - this.dirname = dirname(this.path); - if (options.attempts) { - if (!~options.attempts.indexOf(this.path)) - options.attempts.push(this.path); - } -}; - -/** - * Check if the view path exists. - * - * @return {Boolean} - * @api public - */ - -View.prototype.__defineGetter__('exists', function(){ - try { - stat(this.path); - return true; - } catch (err) { - return false; - } -}); - -/** - * Resolve view engine. - * - * @return {String} - * @api private - */ - -View.prototype.resolveEngine = function(){ - // Explicit - if (~this.basename.indexOf('.')) return extname(this.basename).substr(1); - // Inherit from parent - if (this.parent) return this.parent.engine; - // Default - return this.defaultEngine; -}; - -/** - * Resolve view path. - * - * @return {String} - * @api private - */ - -View.prototype.resolvePath = function(){ - var path = this.view; - // Implicit engine - if (!~this.basename.indexOf('.')) path += this.extension; - // Absolute - if (utils.isAbsolute(path)) return path; - // Relative to parent - if (this.relative && this.parent) return this.parent.dirname + '/' + path; - // Relative to root - return this.root - ? this.root + '/' + path - : path; -}; - -/** - * Get view contents. This is a one-time hit, so we - * can afford to be sync. - * - * @return {String} - * @api public - */ - -View.prototype.__defineGetter__('contents', function(){ - return fs.readFileSync(this.path, 'utf8'); -}); - -/** - * Get template engine api, cache exports to reduce - * require() calls. - * - * @return {Object} - * @api public - */ - -View.prototype.__defineGetter__('templateEngine', function(){ - var ext = this.extension; - return cache[ext] || (cache[ext] = require(this.engine)); -}); - -/** - * Return root path alternative. - * - * @return {String} - * @api public - */ - -View.prototype.__defineGetter__('rootPath', function(){ - this.relative = false; - return this.resolvePath(); -}); - -/** - * Return index path alternative. - * - * @return {String} - * @api public - */ - -View.prototype.__defineGetter__('indexPath', function(){ - return this.dirname - + '/' + this.basename.replace(this.extension, '') - + '/index' + this.extension; -}); - -/** - * Return ..//index path alternative. - * - * @return {String} - * @api public - */ - -View.prototype.__defineGetter__('upIndexPath', function(){ - return this.dirname + '/../' + this.name + '/index' + this.extension; -}); - -/** - * Return _ prefix path alternative - * - * @return {String} - * @api public - */ - -View.prototype.__defineGetter__('prefixPath', function(){ - return this.dirname + '/_' + this.basename; -}); - -/** - * Register the given template engine `exports` - * as `ext`. For example we may wish to map ".html" - * files to jade: - * - * app.register('.html', require('jade')); - * - * or - * - * app.register('html', require('jade')); - * - * This is also useful for libraries that may not - * match extensions correctly. For example my haml.js - * library is installed from npm as "hamljs" so instead - * of layout.hamljs, we can register the engine as ".haml": - * - * app.register('.haml', require('haml-js')); - * - * @param {String} ext - * @param {Object} obj - * @api public - */ - -exports.register = function(ext, exports) { - if ('.' != ext[0]) ext = '.' + ext; - cache[ext] = exports; -}; diff --git a/node_modules/express/node_modules/connect/.npmignore b/node_modules/express/node_modules/connect/.npmignore deleted file mode 100644 index b04a224..0000000 --- a/node_modules/express/node_modules/connect/.npmignore +++ /dev/null @@ -1,11 +0,0 @@ -*.markdown -*.md -.git* -Makefile -benchmarks/ -docs/ -examples/ -install.sh -support/ -test/ -.DS_Store diff --git a/node_modules/express/node_modules/connect/LICENSE b/node_modules/express/node_modules/connect/LICENSE deleted file mode 100644 index 0c5d22d..0000000 --- a/node_modules/express/node_modules/connect/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2010 Sencha Inc. -Copyright (c) 2011 LearnBoost -Copyright (c) 2011 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/index.js b/node_modules/express/node_modules/connect/index.js deleted file mode 100644 index 7477048..0000000 --- a/node_modules/express/node_modules/connect/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/connect'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/cache.js b/node_modules/express/node_modules/connect/lib/cache.js deleted file mode 100644 index 4aa026e..0000000 --- a/node_modules/express/node_modules/connect/lib/cache.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - Cache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Expose `Cache`. - */ - -module.exports = Cache; - -/** - * LRU cache store. - * - * @param {Number} limit - * @api private - */ - -function Cache(limit) { - this.store = {}; - this.keys = []; - this.limit = limit; -} - -/** - * Touch `key`, promoting the object. - * - * @param {String} key - * @param {Number} i - * @api private - */ - -Cache.prototype.touch = function(key, i){ - this.keys.splice(i,1); - this.keys.push(key); -}; - -/** - * Remove `key`. - * - * @param {String} key - * @api private - */ - -Cache.prototype.remove = function(key){ - delete this.store[key]; -}; - -/** - * Get the object stored for `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.get = function(key){ - return this.store[key]; -}; - -/** - * Add a cache `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.add = function(key){ - // initialize store - var len = this.keys.push(key); - - // limit reached, invalid LRU - if (len > this.limit) this.remove(this.keys.shift()); - - var arr = this.store[key] = []; - arr.createdAt = new Date; - return arr; -}; diff --git a/node_modules/express/node_modules/connect/lib/connect.js b/node_modules/express/node_modules/connect/lib/connect.js deleted file mode 100644 index 7857023..0000000 --- a/node_modules/express/node_modules/connect/lib/connect.js +++ /dev/null @@ -1,106 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var HTTPServer = require('./http').Server - , HTTPSServer = require('./https').Server - , fs = require('fs'); - -// node patches - -require('./patch'); - -// expose createServer() as the module - -exports = module.exports = createServer; - -/** - * Framework version. - */ - -exports.version = '1.8.5'; - -/** - * Initialize a new `connect.HTTPServer` with the middleware - * passed to this function. When an object is passed _first_, - * we assume these are the tls options, and return a `connect.HTTPSServer`. - * - * Examples: - * - * An example HTTP server, accepting several middleware. - * - * var server = connect.createServer( - * connect.logger() - * , connect.static(__dirname + '/public') - * ); - * - * An HTTPS server, utilizing the same middleware as above. - * - * var server = connect.createServer( - * { key: key, cert: cert } - * , connect.logger() - * , connect.static(__dirname + '/public') - * ); - * - * Alternatively with connect 1.0 we may omit `createServer()`. - * - * connect( - * connect.logger() - * , connect.static(__dirname + '/public') - * ).listen(3000); - * - * @param {Object|Function} ... - * @return {Server} - * @api public - */ - -function createServer() { - if ('object' == typeof arguments[0]) { - return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1)); - } else { - return new HTTPServer(Array.prototype.slice.call(arguments)); - } -}; - -// support connect.createServer() - -exports.createServer = createServer; - -// auto-load getters - -exports.middleware = {}; - -/** - * Auto-load bundled middleware with getters. - */ - -fs.readdirSync(__dirname + '/middleware').forEach(function(filename){ - if (/\.js$/.test(filename)) { - var name = filename.substr(0, filename.lastIndexOf('.')); - exports.middleware.__defineGetter__(name, function(){ - return require('./middleware/' + name); - }); - } -}); - -// expose utils - -exports.utils = require('./utils'); - -// expose getters as first-class exports - -exports.utils.merge(exports, exports.middleware); - -// expose constructors - -exports.HTTPServer = HTTPServer; -exports.HTTPSServer = HTTPSServer; - diff --git a/node_modules/express/node_modules/connect/lib/http.js b/node_modules/express/node_modules/connect/lib/http.js deleted file mode 100644 index 09898e2..0000000 --- a/node_modules/express/node_modules/connect/lib/http.js +++ /dev/null @@ -1,217 +0,0 @@ - -/*! - * Connect - HTTPServer - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , parse = require('url').parse - , assert = require('assert'); - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Initialize a new `Server` with the given `middleware`. - * - * Examples: - * - * var server = connect.createServer( - * connect.favicon() - * , connect.logger() - * , connect.static(__dirname + '/public') - * ); - * - * @params {Array} middleware - * @return {Server} - * @api public - */ - -var Server = exports.Server = function HTTPServer(middleware) { - this.stack = []; - middleware.forEach(function(fn){ - this.use(fn); - }, this); - http.Server.call(this, this.handle); -}; - -/** - * Inherit from `http.Server.prototype`. - */ - -Server.prototype.__proto__ = http.Server.prototype; - -/** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - * - * This is effectively the same as passing middleware to `connect.createServer()`, - * however provides a progressive api. - * - * Examples: - * - * var server = connect.createServer(); - * server.use(connect.favicon()); - * server.use(connect.logger()); - * server.use(connect.static(__dirname + '/public')); - * - * If we wanted to prefix static files with _/public_, we could - * "mount" the `static()` middleware: - * - * server.use('/public', connect.static(__dirname + '/public')); - * - * This api is chainable, meaning the following is valid: - * - * connect.createServer() - * .use(connect.favicon()) - * .use(connect.logger()) - * .use(connect.static(__dirname + '/public')) - * .listen(3000); - * - * @param {String|Function} route or handle - * @param {Function} handle - * @return {Server} - * @api public - */ - -Server.prototype.use = function(route, handle){ - this.route = '/'; - - // default route to '/' - if ('string' != typeof route) { - handle = route; - route = '/'; - } - - // wrap sub-apps - if ('function' == typeof handle.handle) { - var server = handle; - server.route = route; - handle = function(req, res, next) { - server.handle(req, res, next); - }; - } - - // wrap vanilla http.Servers - if (handle instanceof http.Server) { - handle = handle.listeners('request')[0]; - } - - // normalize route to not trail with slash - if ('/' == route[route.length - 1]) { - route = route.substr(0, route.length - 1); - } - - // add the middleware - this.stack.push({ route: route, handle: handle }); - - // allow chaining - return this; -}; - -/** - * Handle server requests, punting them down - * the middleware stack. - * - * @api private - */ - -Server.prototype.handle = function(req, res, out) { - var writeHead = res.writeHead - , stack = this.stack - , removed = '' - , index = 0; - - function next(err) { - var layer, path, c; - req.url = removed + req.url; - req.originalUrl = req.originalUrl || req.url; - removed = ''; - - layer = stack[index++]; - - // all done - if (!layer || res.headerSent) { - // but wait! we have a parent - if (out) return out(err); - - // error - if (err) { - var msg = 'production' == env - ? 'Internal Server Error' - : err.stack || err.toString(); - - // output to stderr in a non-test env - if ('test' != env) console.error(err.stack || err.toString()); - - // unable to respond - if (res.headerSent) return req.socket.destroy(); - - res.statusCode = 500; - res.setHeader('Content-Type', 'text/plain'); - if ('HEAD' == req.method) return res.end(); - res.end(msg); - } else { - res.statusCode = 404; - res.setHeader('Content-Type', 'text/plain'); - if ('HEAD' == req.method) return res.end(); - res.end('Cannot ' + req.method + ' ' + req.url); - } - return; - } - - try { - path = parse(req.url).pathname; - if (undefined == path) path = '/'; - - // skip this layer if the route doesn't match. - if (0 != path.indexOf(layer.route)) return next(err); - - c = path[layer.route.length]; - if (c && '/' != c && '.' != c) return next(err); - - // Call the layer handler - // Trim off the part of the url that matches the route - removed = layer.route; - req.url = req.url.substr(removed.length); - - // Ensure leading slash - if ('/' != req.url[0]) req.url = '/' + req.url; - - var arity = layer.handle.length; - if (err) { - if (arity === 4) { - layer.handle(err, req, res, next); - } else { - next(err); - } - } else if (arity < 4) { - layer.handle(req, res, next); - } else { - next(); - } - } catch (e) { - if (e instanceof assert.AssertionError) { - console.error(e.stack + '\n'); - next(e); - } else { - next(e); - } - } - } - next(); -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/https.js b/node_modules/express/node_modules/connect/lib/https.js deleted file mode 100644 index 9b09fa4..0000000 --- a/node_modules/express/node_modules/connect/lib/https.js +++ /dev/null @@ -1,47 +0,0 @@ - -/*! - * Connect - HTTPServer - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var HTTPServer = require('./http').Server - , https = require('https'); - -/** - * Initialize a new `Server` with the given - *`options` and `middleware`. The HTTPS api - * is identical to the [HTTP](http.html) server, - * however TLS `options` must be provided before - * passing in the optional middleware. - * - * @params {Object} options - * @params {Array} middleawre - * @return {Server} - * @api public - */ - -var Server = exports.Server = function HTTPSServer(options, middleware) { - this.stack = []; - middleware.forEach(function(fn){ - this.use(fn); - }, this); - https.Server.call(this, options, this.handle); -}; - -/** - * Inherit from `http.Server.prototype`. - */ - -Server.prototype.__proto__ = https.Server.prototype; - -// mixin HTTPServer methods - -Object.keys(HTTPServer.prototype).forEach(function(method){ - Server.prototype[method] = HTTPServer.prototype[method]; -}); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/index.js b/node_modules/express/node_modules/connect/lib/index.js deleted file mode 100644 index 77b14c3..0000000 --- a/node_modules/express/node_modules/connect/lib/index.js +++ /dev/null @@ -1,46 +0,0 @@ - -/** - * # Connect - * - * Connect is a middleware framework for node, - * shipping with over 11 bundled middleware and a rich choice of - * [3rd-party middleware](https://github.com/senchalabs/connect/wiki). - * - * Installation: - * - * $ npm install connect - * - * API: - * - * - [connect](connect.html) general - * - [http](http.html) http server - * - [https](https.html) https server - * - * Middleware: - * - * - [logger](middleware-logger.html) request logger with custom format support - * - [csrf](middleware-csrf.html) Cross-site request forgery protection - * - [basicAuth](middleware-basicAuth.html) basic http authentication - * - [bodyParser](middleware-bodyParser.html) extensible request body parser - * - [cookieParser](middleware-cookieParser.html) cookie parser - * - [session](middleware-session.html) session management support with bundled [MemoryStore](middleware-session-memory.html) - * - [compiler](middleware-compiler.html) static asset compiler (sass, less, coffee-script, etc) - * - [methodOverride](middleware-methodOverride.html) faux HTTP method support - * - [responseTime](middleware-responseTime.html) calculates response-time and exposes via X-Response-Time - * - [router](middleware-router.html) provides rich Sinatra / Express-like routing - * - [staticCache](middleware-staticCache.html) memory cache layer for the static() middleware - * - [static](middleware-static.html) streaming static file server supporting `Range` and more - * - [directory](middleware-directory.html) directory listing middleware - * - [vhost](middleware-vhost.html) virtual host sub-domain mapping middleware - * - [favicon](middleware-favicon.html) efficient favicon server (with default icon) - * - [limit](middleware-limit.html) limit the bytesize of request bodies - * - [profiler](middleware-profiler.html) request profiler reporting response-time, memory usage, etc - * - [query](middleware-query.html) automatic querystring parser, populating `req.query` - * - [errorHandler](middleware-errorHandler.html) flexible error handler - * - * Internals: - * - * - connect [utilities](utils.html) - * - node monkey [patches](patch.html) - * - */ \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js b/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js deleted file mode 100644 index 3ff472b..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js +++ /dev/null @@ -1,93 +0,0 @@ - -/*! - * Connect - basicAuth - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , unauthorized = utils.unauthorized - , badRequest = utils.badRequest; - -/** - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.remoteUser`. The final alternative is simply passing username / password - * strings. - * - * Examples: - * - * connect(connect.basicAuth('username', 'password')); - * - * connect( - * connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * }) - * ); - * - * connect( - * connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * }) - * ); - * - * @param {Function|String} callback or username - * @param {String} realm - * @api public - */ - -module.exports = function basicAuth(callback, realm) { - var username, password; - - // user / pass strings - if ('string' == typeof callback) { - username = callback; - password = realm; - if ('string' != typeof password) throw new Error('password argument required'); - realm = arguments[2]; - callback = function(user, pass){ - return user == username && pass == password; - } - } - - realm = realm || 'Authorization Required'; - - return function(req, res, next) { - var authorization = req.headers.authorization; - - if (req.remoteUser) return next(); - if (!authorization) return unauthorized(res, realm); - - var parts = authorization.split(' ') - , scheme = parts[0] - , credentials = new Buffer(parts[1], 'base64').toString().split(':'); - - if ('Basic' != scheme) return badRequest(res); - - // async - if (callback.length >= 3) { - var pause = utils.pause(req); - callback(credentials[0], credentials[1], function(err, user){ - if (err || !user) return unauthorized(res, realm); - req.remoteUser = user; - next(); - pause.resume(); - }); - // sync - } else { - if (callback(credentials[0], credentials[1])) { - req.remoteUser = credentials[0]; - next(); - } else { - unauthorized(res, realm); - } - } - } -}; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js b/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js deleted file mode 100644 index a52568c..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js +++ /dev/null @@ -1,196 +0,0 @@ - -/*! - * Connect - bodyParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , formidable = require('formidable'); - -/** - * Extract the mime type from the given request's - * _Content-Type_ header. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -function mime(req) { - var str = req.headers['content-type'] || ''; - return str.split(';')[0]; -} - -/** - * Parse request bodies. - * - * By default _application/json_, _application/x-www-form-urlencoded_, - * and _multipart/form-data_ are supported, however you may map `connect.bodyParser.parse[contentType]` - * to a function receiving `(req, options, callback)`. - * - * Examples: - * - * connect.createServer( - * connect.bodyParser() - * , function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * } - * ); - * - * $ curl -d 'user[name]=tj' http://localhost/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://localhost/ - * - * Multipart req.files: - * - * As a security measure files are stored in a separate object, stored - * as `req.files`. This prevents attacks that may potentially alter - * filenames, and depending on the application gain access to restricted files. - * - * Multipart configuration: - * - * The `options` passed are provided to each parser function. - * The _multipart/form-data_ parser merges these with formidable's - * IncomingForm object, allowing you to tweak the upload directory, - * size limits, etc. For example you may wish to retain the file extension - * and change the upload directory: - * - * server.use(bodyParser({ uploadDir: '/www/mysite.com/uploads' })); - * - * View [node-formidable](https://github.com/felixge/node-formidable) for more information. - * - * If you wish to use formidable directly within your app, and do not - * desire this behaviour for multipart requests simply remove the - * parser: - * - * delete connect.bodyParser.parse['multipart/form-data']; - * - * Or - * - * delete express.bodyParser.parse['multipart/form-data']; - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function bodyParser(options){ - options = options || {}; - return function bodyParser(req, res, next) { - if (req.body) return next(); - req.body = {}; - - if ('GET' == req.method || 'HEAD' == req.method) return next(); - var parser = exports.parse[mime(req)]; - if (parser) { - parser(req, options, next); - } else { - next(); - } - } -}; - -/** - * Parsers. - */ - -exports.parse = {}; - -/** - * Parse application/x-www-form-urlencoded. - */ - -exports.parse['application/x-www-form-urlencoded'] = function(req, options, fn){ - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - try { - req.body = buf.length - ? qs.parse(buf) - : {}; - fn(); - } catch (err){ - fn(err); - } - }); -}; - -/** - * Parse application/json. - */ - -exports.parse['application/json'] = function(req, options, fn){ - var buf = ''; - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - try { - req.body = buf.length - ? JSON.parse(buf) - : {}; - fn(); - } catch (err){ - fn(err); - } - }); -}; - -/** - * Parse multipart/form-data. - * - * TODO: make multiple support optional - * TODO: revisit "error" flag if it's a formidable bug - */ - -exports.parse['multipart/form-data'] = function(req, options, fn){ - var form = new formidable.IncomingForm - , data = {} - , files = {} - , done; - - Object.keys(options).forEach(function(key){ - form[key] = options[key]; - }); - - function ondata(name, val, data){ - if (Array.isArray(data[name])) { - data[name].push(val); - } else if (data[name]) { - data[name] = [data[name], val]; - } else { - data[name] = val; - } - } - - form.on('field', function(name, val){ - ondata(name, val, data); - }); - - form.on('file', function(name, val){ - ondata(name, val, files); - }); - - form.on('error', function(err){ - fn(err); - done = true; - }); - - form.on('end', function(){ - if (done) return; - try { - req.body = qs.parse(data); - req.files = qs.parse(files); - fn(); - } catch (err) { - fn(err); - } - }); - - form.parse(req); -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/compiler.js b/node_modules/express/node_modules/connect/lib/middleware/compiler.js deleted file mode 100644 index dc4dd66..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/compiler.js +++ /dev/null @@ -1,163 +0,0 @@ - -/*! - * Connect - compiler - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , path = require('path') - , parse = require('url').parse; - -/** - * Require cache. - */ - -var cache = {}; - -/** - * Setup compiler. - * - * Options: - * - * - `src` Source directory, defaults to **CWD**. - * - `dest` Destination directory, defaults `src`. - * - `enable` Array of enabled compilers. - * - * Compilers: - * - * - `sass` Compiles sass to css - * - `less` Compiles less to css - * - `coffeescript` Compiles coffee to js - * - * @param {Object} options - * @api public - */ - -exports = module.exports = function compiler(options){ - options = options || {}; - - var srcDir = options.src || process.cwd() - , destDir = options.dest || srcDir - , enable = options.enable; - - if (!enable || enable.length === 0) { - throw new Error('compiler\'s "enable" option is not set, nothing will be compiled.'); - } - - return function compiler(req, res, next){ - if ('GET' != req.method) return next(); - var pathname = parse(req.url).pathname; - for (var i = 0, len = enable.length; i < len; ++i) { - var name = enable[i] - , compiler = compilers[name]; - if (compiler.match.test(pathname)) { - var src = (srcDir + pathname).replace(compiler.match, compiler.ext) - , dest = destDir + pathname; - - // Compare mtimes - fs.stat(src, function(err, srcStats){ - if (err) { - if ('ENOENT' == err.code) { - next(); - } else { - next(err); - } - } else { - fs.stat(dest, function(err, destStats){ - if (err) { - // Oh snap! it does not exist, compile it - if ('ENOENT' == err.code) { - compile(); - } else { - next(err); - } - } else { - // Source has changed, compile it - if (srcStats.mtime > destStats.mtime) { - compile(); - } else { - // Defer file serving - next(); - } - } - }); - } - }); - - // Compile to the destination - function compile() { - fs.readFile(src, 'utf8', function(err, str){ - if (err) { - next(err); - } else { - compiler.compile(str, function(err, str){ - if (err) { - next(err); - } else { - fs.writeFile(dest, str, 'utf8', function(err){ - next(err); - }); - } - }); - } - }); - } - return; - } - } - next(); - }; -}; - -/** - * Bundled compilers: - * - * - [sass](http://github.com/visionmedia/sass.js) to _css_ - * - [less](http://github.com/cloudhead/less.js) to _css_ - * - [coffee](http://github.com/jashkenas/coffee-script) to _js_ - */ - -var compilers = exports.compilers = { - sass: { - match: /\.css$/, - ext: '.sass', - compile: function(str, fn){ - var sass = cache.sass || (cache.sass = require('sass')); - try { - fn(null, sass.render(str)); - } catch (err) { - fn(err); - } - } - }, - less: { - match: /\.css$/, - ext: '.less', - compile: function(str, fn){ - var less = cache.less || (cache.less = require('less')); - try { - less.render(str, fn); - } catch (err) { - fn(err); - } - } - }, - coffeescript: { - match: /\.js$/, - ext: '.coffee', - compile: function(str, fn){ - var coffee = cache.coffee || (cache.coffee = require('coffee-script')); - try { - fn(null, coffee.compile(str)); - } catch (err) { - fn(err); - } - } - } -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js b/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js deleted file mode 100644 index d6b69de..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js +++ /dev/null @@ -1,46 +0,0 @@ - -/*! - * Connect - cookieParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils'); - -/** - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. - * - * Examples: - * - * connect.createServer( - * connect.cookieParser() - * , function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * } - * ); - * - * @return {Function} - * @api public - */ - -module.exports = function cookieParser(){ - return function cookieParser(req, res, next) { - var cookie = req.headers.cookie; - if (req.cookies) return next(); - req.cookies = {}; - if (cookie) { - try { - req.cookies = utils.parseCookie(cookie); - } catch (err) { - return next(err); - } - } - next(); - }; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/csrf.js b/node_modules/express/node_modules/connect/lib/middleware/csrf.js deleted file mode 100644 index 1dcf0d1..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/csrf.js +++ /dev/null @@ -1,105 +0,0 @@ - -/*! - * Connect - csrf - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , crypto = require('crypto'); - -/** - * CRSF protection middleware. - * - * By default this middleware generates a token named "_csrf" - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's `req.session._csrf` - * property which is re-generated per request. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Examples: - * - * var form = '\n\ - *
\n\ - * \n\ - * \n\ - * \n\ - * \n\ - *
\n\ - * '; - * - * connect( - * connect.cookieParser() - * , connect.session({ secret: 'keyboard cat' }) - * , connect.bodyParser() - * , connect.csrf() - * - * , function(req, res, next){ - * if ('POST' != req.method) return next(); - * req.session.user = req.body.user; - * next(); - * } - * - * , function(req, res){ - * res.setHeader('Content-Type', 'text/html'); - * var body = form - * .replace('{token}', req.session._csrf) - * .replace('{user}', req.session.user && req.session.user.name || ''); - * res.end(body); - * } - * ).listen(3000); - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param {Object} options - * @api public - */ - -module.exports = function csrf(options) { - var options = options || {} - , value = options.value || defaultValue; - - return function(req, res, next){ - // generate CSRF token - var token = req.session._csrf || (req.session._csrf = utils.uid(24)); - - // ignore GET (for now) - if ('GET' == req.method) return next(); - - // determine value - var val = value(req); - - // check - if (val != token) return utils.forbidden(res); - - next(); - } -}; - -/** - * Default value function, checking the `req.body` - * and `req.query` for the CSRF token. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -function defaultValue(req) { - return (req.body && req.body._csrf) - || (req.query && req.query._csrf) - || (req.headers['x-csrf-token']); -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/directory.js b/node_modules/express/node_modules/connect/lib/middleware/directory.js deleted file mode 100644 index df5b5e6..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/directory.js +++ /dev/null @@ -1,222 +0,0 @@ - -/*! - * Connect - directory - * Copyright(c) 2011 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -// TODO: icon / style for directories -// TODO: arrow key navigation -// TODO: make icons extensible - -/** - * Module dependencies. - */ - -var fs = require('fs') - , parse = require('url').parse - , utils = require('../utils') - , path = require('path') - , normalize = path.normalize - , extname = path.extname - , join = path.join; - -/** - * Icon cache. - */ - -var cache = {}; - -/** - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function directory(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('directory() root path required'); - var hidden = options.hidden - , icons = options.icons - , filter = options.filter - , root = normalize(root); - - return function directory(req, res, next) { - var accept = req.headers.accept || 'text/plain' - , url = parse(req.url) - , dir = decodeURIComponent(url.pathname) - , path = normalize(join(root, dir)) - , originalUrl = parse(req.originalUrl) - , originalDir = decodeURIComponent(originalUrl.pathname) - , showUp = path != root && path != root + '/'; - - // null byte(s) - if (~path.indexOf('\0')) return utils.badRequest(res); - - // malicious path - if (0 != path.indexOf(root)) return utils.forbidden(res); - - // check if we have a directory - fs.stat(path, function(err, stat){ - if (err) return 'ENOENT' == err.code - ? next() - : next(err); - - if (!stat.isDirectory()) return next(); - - // fetch files - fs.readdir(path, function(err, files){ - if (err) return next(err); - if (!hidden) files = removeHidden(files); - if (filter) files = files.filter(filter); - files.sort(); - // content-negotiation - for (var key in exports) { - if (~accept.indexOf(key) || ~accept.indexOf('*/*')) { - exports[key](req, res, files, next, originalDir, showUp, icons); - return; - } - } - utils.notAcceptable(res); - }); - }); - }; -}; - -/** - * Respond with text/html. - */ - -exports.html = function(req, res, files, next, dir, showUp, icons){ - fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){ - if (err) return next(err); - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){ - if (err) return next(err); - if (showUp) files.unshift('..'); - str = str - .replace('{style}', style) - .replace('{files}', html(files, dir, icons)) - .replace('{directory}', dir) - .replace('{linked-path}', htmlPath(dir)); - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Length', str.length); - res.end(str); - }); - }); -}; - -/** - * Respond with application/json. - */ - -exports.json = function(req, res, files){ - files = JSON.stringify(files); - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Respond with text/plain. - */ - -exports.plain = function(req, res, files){ - files = files.join('\n') + '\n'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Map html `dir`, returning a linked path. - */ - -function htmlPath(dir) { - var curr = []; - return dir.split('/').map(function(part){ - curr.push(part); - return '' + part + ''; - }).join(' / '); -} - -/** - * Map html `files`, returning an html unordered list. - */ - -function html(files, dir, useIcons) { - return '
    ' + files.map(function(file){ - var icon = '' - , classes = []; - - if (useIcons && '..' != file) { - icon = icons[extname(file)] || icons.default; - icon = ''; - classes.push('icon'); - } - - return '
  • ' - + icon + file + '
  • '; - - }).join('\n') + '
'; -} - -/** - * Load and cache the given `icon`. - * - * @param {String} icon - * @return {String} - * @api private - */ - -function load(icon) { - if (cache[icon]) return cache[icon]; - return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64'); -} - -/** - * Filter "hidden" `files`, aka files - * beginning with a `.`. - * - * @param {Array} files - * @return {Array} - * @api private - */ - -function removeHidden(files) { - return files.filter(function(file){ - return '.' != file[0]; - }); -} - -/** - * Icon map. - */ - -var icons = { - '.js': 'page_white_code_red.png' - , '.c': 'page_white_c.png' - , '.h': 'page_white_h.png' - , '.cc': 'page_white_cplusplus.png' - , '.php': 'page_white_php.png' - , '.rb': 'page_white_ruby.png' - , '.cpp': 'page_white_cplusplus.png' - , '.swf': 'page_white_flash.png' - , '.pdf': 'page_white_acrobat.png' - , 'default': 'page_white.png' -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js b/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js deleted file mode 100644 index f2fc44f..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js +++ /dev/null @@ -1,100 +0,0 @@ -/*! - * Connect - errorHandler - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , url = require('url') - , fs = require('fs'); - -/** - * Flexible error handler, providing (_optional_) stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Options: - * - * - `showStack`, `stack` respond with both the error message and stack trace. Defaults to `false` - * - `showMessage`, `message`, respond with the exception message only. Defaults to `false` - * - `dumpExceptions`, `dump`, dump exceptions to stderr (without terminating the process). Defaults to `false` - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function errorHandler(options){ - options = options || {}; - - // defaults - var showStack = options.showStack || options.stack - , showMessage = options.showMessage || options.message - , dumpExceptions = options.dumpExceptions || options.dump - , formatUrl = options.formatUrl; - - return function errorHandler(err, req, res, next){ - res.statusCode = 500; - if (dumpExceptions) console.error(err.stack); - if (showStack) { - var accept = req.headers.accept || ''; - // html - if (~accept.indexOf('html')) { - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){ - fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){ - var stack = (err.stack || '') - .split('\n').slice(1) - .map(function(v){ return '
  • ' + v + '
  • '; }).join(''); - html = html - .replace('{style}', style) - .replace('{stack}', stack) - .replace('{title}', exports.title) - .replace(/\{error\}/g, utils.escape(err.toString())); - res.setHeader('Content-Type', 'text/html'); - res.end(html); - }); - }); - // json - } else if (~accept.indexOf('json')) { - var json = JSON.stringify({ error: err }); - res.setHeader('Content-Type', 'application/json'); - res.end(json); - // plain text - } else { - res.writeHead(500, { 'Content-Type': 'text/plain' }); - res.end(err.stack); - } - } else { - var body = showMessage - ? err.toString() - : 'Internal Server Error'; - res.setHeader('Content-Type', 'text/plain'); - res.end(body); - } - }; -}; - -/** - * Template title. - */ - -exports.title = 'Connect'; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/favicon.js b/node_modules/express/node_modules/connect/lib/middleware/favicon.js deleted file mode 100644 index 8eeafba..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/favicon.js +++ /dev/null @@ -1,76 +0,0 @@ - -/*! - * Connect - favicon - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , utils = require('../utils'); - -/** - * Favicon cache. - */ - -var icon; - -/** - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * connect.createServer( - * connect.favicon() - * ); - * - * connect.createServer( - * connect.favicon(__dirname + '/public/favicon.ico') - * ); - * - * @param {String} path - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function favicon(path, options){ - var options = options || {} - , path = path || __dirname + '/../public/favicon.ico' - , maxAge = options.maxAge || 86400000; - - return function favicon(req, res, next){ - if ('/favicon.ico' == req.url) { - if (icon) { - res.writeHead(200, icon.headers); - res.end(icon.body); - } else { - fs.readFile(path, function(err, buf){ - if (err) return next(err); - icon = { - headers: { - 'Content-Type': 'image/x-icon' - , 'Content-Length': buf.length - , 'ETag': '"' + utils.md5(buf) + '"' - , 'Cache-Control': 'public, max-age=' + (maxAge / 1000) - }, - body: buf - }; - res.writeHead(200, icon.headers); - res.end(icon.body); - }); - } - } else { - next(); - } - }; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/limit.js b/node_modules/express/node_modules/connect/lib/middleware/limit.js deleted file mode 100644 index 4dafdd3..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/limit.js +++ /dev/null @@ -1,82 +0,0 @@ - -/*! - * Connect - limit - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * Examples: - * - * var server = connect( - * connect.limit('5.5mb') - * ).listen(3000); - * - * TODO: pause EV_READ - * - * @param {Number|String} bytes - * @return {Function} - * @api public - */ - -module.exports = function limit(bytes){ - if ('string' == typeof bytes) bytes = parse(bytes); - if ('number' != typeof bytes) throw new Error('limit() bytes required'); - return function limit(req, res, next){ - var received = 0 - , len = req.headers['content-length'] - ? parseInt(req.headers['content-length'], 10) - : null; - - // deny the request - function deny() { - req.destroy(); - } - - // self-awareness - if (req._limit) return next(); - req._limit = true; - - // limit by content-length - if (len && len > bytes) { - res.statusCode = 413; - res.end('Request Entity Too Large'); - return; - } - - // limit - req.on('data', function(chunk){ - received += chunk.length; - if (received > bytes) deny(); - }); - - next(); - }; -}; - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api private - */ - -function parse(size) { - var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/) - , n = parseFloat(parts[1]) - , type = parts[2]; - - var map = { - kb: 1024 - , mb: 1024 * 1024 - , gb: 1024 * 1024 * 1024 - }; - - return map[type] * n; -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/logger.js b/node_modules/express/node_modules/connect/lib/middleware/logger.js deleted file mode 100644 index 75cc5aa..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/logger.js +++ /dev/null @@ -1,299 +0,0 @@ - -/*! - * Connect - logger - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Log buffer. - */ - -var buf = []; - -/** - * Default log buffer duration. - */ - -var defaultBufferDuration = 1000; - -/** - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger('dev') - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - * - * @param {String|Function|Object} format or options - * @return {Function} - * @api public - */ - -exports = module.exports = function logger(options) { - if ('object' == typeof options) { - options = options || {}; - } else if (options) { - options = { format: options }; - } else { - options = {}; - } - - // output on request instead of response - var immediate = options.immediate; - - // format name - var fmt = exports[options.format] || options.format || exports.default; - - // compile format - if ('function' != typeof fmt) fmt = compile(fmt); - - // options - var stream = options.stream || process.stdout - , buffer = options.buffer; - - // buffering support - if (buffer) { - var realStream = stream - , interval = 'number' == typeof buffer - ? buffer - : defaultBufferDuration; - - // flush interval - setInterval(function(){ - if (buf.length) { - realStream.write(buf.join(''), 'ascii'); - buf.length = 0; - } - }, interval); - - // swap the stream - stream = { - write: function(str){ - buf.push(str); - } - }; - } - - return function logger(req, res, next) { - req._startTime = new Date; - - // mount safety - if (req._logging) return next(); - - // flag as logging - req._logging = true; - - // immediate - if (immediate) { - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n', 'ascii'); - } else { - // proxy end to output loggging - var end = res.end; - res.end = function(chunk, encoding){ - res.end = end; - res.end(chunk, encoding); - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n', 'ascii'); - }; - } - - - next(); - }; -}; - -/** - * Compile `fmt` into a function. - * - * @param {String} fmt - * @return {Function} - * @api private - */ - -function compile(fmt) { - fmt = fmt.replace(/"/g, '\\"'); - var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ - return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "'; - }) + '";' - return new Function('tokens, req, res', js); -}; - -/** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param {String} name - * @param {Function} fn - * @return {Object} exports for chaining - * @api public - */ - -exports.token = function(name, fn) { - exports[name] = fn; - return this; -}; - -/** - * Define a `fmt` with the given `name`. - * - * @param {String} name - * @param {String|Function} fmt - * @return {Object} exports for chaining - * @api public - */ - -exports.format = function(name, str){ - exports[name] = str; - return this; -}; - -// default format - -exports.format('default', ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); - -// short format - -exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); - -// tiny format - -exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); - -// dev (colored) - -exports.format('dev', function(tokens, req, res){ - var status = res.statusCode - , color = 32; - - if (status >= 500) color = 31 - else if (status >= 400) color = 33 - else if (status >= 300) color = 36; - - return '\033[90m' + req.method - + ' ' + req.originalUrl + ' ' - + '\033[' + color + 'm' + res.statusCode - + ' \033[90m' - + (new Date - req._startTime) - + 'ms\033[0m'; -}); - -// request url - -exports.token('url', function(req){ - return req.originalUrl; -}); - -// request method - -exports.token('method', function(req){ - return req.method; -}); - -// response time in milliseconds - -exports.token('response-time', function(req){ - return new Date - req._startTime; -}); - -// UTC date - -exports.token('date', function(){ - return new Date().toUTCString(); -}); - -// response status code - -exports.token('status', function(req, res){ - return res.statusCode; -}); - -// normalized referrer - -exports.token('referrer', function(req){ - return req.headers['referer'] || req.headers['referrer']; -}); - -// remote address - -exports.token('remote-addr', function(req){ - return req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress)); -}); - -// HTTP version - -exports.token('http-version', function(req){ - return req.httpVersionMajor + '.' + req.httpVersionMinor; -}); - -// UA string - -exports.token('user-agent', function(req){ - return req.headers['user-agent']; -}); - -// request header - -exports.token('req', function(req, res, field){ - return req.headers[field.toLowerCase()]; -}); - -// response header - -exports.token('res', function(req, res, field){ - return (res._headers || {})[field.toLowerCase()]; -}); - diff --git a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js b/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js deleted file mode 100644 index db4e9f3..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js +++ /dev/null @@ -1,38 +0,0 @@ - -/*! - * Connect - methodOverride - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param {String} key - * @return {Function} - * @api public - */ - -module.exports = function methodOverride(key){ - key = key || "_method"; - return function methodOverride(req, res, next) { - req.originalMethod = req.originalMethod || req.method; - - // req.body - if (req.body && key in req.body) { - req.method = req.body[key].toUpperCase(); - delete req.body[key]; - // check X-HTTP-Method-Override - } else if (req.headers['x-http-method-override']) { - req.method = req.headers['x-http-method-override'].toUpperCase(); - } - - next(); - }; -}; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/profiler.js b/node_modules/express/node_modules/connect/lib/middleware/profiler.js deleted file mode 100644 index b0b5bac..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/profiler.js +++ /dev/null @@ -1,100 +0,0 @@ - -/*! - * Connect - profiler - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Profile the duration of a request. - * - * Typically this middleware should be utilized - * _above_ all others, as it proxies the `res.end()` - * method, being first allows it to encapsulate all - * other middleware. - * - * Example Output: - * - * GET / - * response time 2ms - * memory rss 52.00kb - * memory vsize 2.07mb - * heap before 3.76mb / 8.15mb - * heap after 3.80mb / 8.15mb - * - * @api public - */ - -module.exports = function profiler(){ - return function(req, res, next){ - var end = res.end - , start = snapshot(); - - // state snapshot - function snapshot() { - return { - mem: process.memoryUsage() - , time: new Date - }; - } - - // proxy res.end() - res.end = function(data, encoding){ - res.end = end; - res.end(data, encoding); - compare(req, start, snapshot()) - }; - - next(); - } -}; - -/** - * Compare `start` / `end` snapshots. - * - * @param {IncomingRequest} req - * @param {Object} start - * @param {Object} end - * @api private - */ - -function compare(req, start, end) { - console.log(); - row(req.method, req.url); - row('response time:', (end.time - start.time) + 'ms'); - row('memory rss:', formatBytes(end.mem.rss - start.mem.rss)); - row('memory vsize:', formatBytes(end.mem.vsize - start.mem.vsize)); - row('heap before:', formatBytes(start.mem.heapUsed) + ' / ' + formatBytes(start.mem.heapTotal)); - row('heap after:', formatBytes(end.mem.heapUsed) + ' / ' + formatBytes(end.mem.heapTotal)); - console.log(); -} - -/** - * Row helper - * - * @param {String} key - * @param {String} val - * @api private - */ - -function row(key, val) { - console.log(' \033[90m%s\033[0m \033[36m%s\033[0m', key, val); -} - -/** - * Format byte-size. - * - * @param {Number} bytes - * @return {String} - * @api private - */ - -function formatBytes(bytes) { - var kb = 1024 - , mb = 1024 * kb - , gb = 1024 * mb; - if (bytes < kb) return bytes + 'b'; - if (bytes < mb) return (bytes / kb).toFixed(2) + 'kb'; - if (bytes < gb) return (bytes / mb).toFixed(2) + 'mb'; - return (bytes / gb).toFixed(2) + 'gb'; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/query.js b/node_modules/express/node_modules/connect/lib/middleware/query.js deleted file mode 100644 index d3b1acd..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/query.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - query - * Copyright(c) 2011 TJ Holowaychuk - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , parse = require('url').parse; - -/** - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect( - * connect.query() - * , function(req, res){ - * res.end(JSON.stringify(req.query)); - * } - * ).listen(3000); - * - * @return {Function} - * @api public - */ - -module.exports = function query(){ - return function query(req, res, next){ - req.query = ~req.url.indexOf('?') - ? qs.parse(parse(req.url).query) - : {}; - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js b/node_modules/express/node_modules/connect/lib/middleware/responseTime.js deleted file mode 100644 index 2b2133a..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js +++ /dev/null @@ -1,34 +0,0 @@ - -/*! - * Connect - responseTime - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - * - * @return {Function} - * @api public - */ - -module.exports = function responseTime(){ - return function(req, res, next){ - var writeHead = res.writeHead - , start = new Date; - - if (res._responseTime) return next(); - res._responseTime = true; - - // proxy writeHead to calculate duration - res.writeHead = function(status, headers){ - var duration = new Date - start; - res.setHeader('X-Response-Time', duration + 'ms'); - res.writeHead = writeHead; - res.writeHead(status, headers); - }; - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/router.js b/node_modules/express/node_modules/connect/lib/middleware/router.js deleted file mode 100644 index a07452e..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/router.js +++ /dev/null @@ -1,379 +0,0 @@ - -/*! - * Connect - router - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , parse = require('url').parse; - -/** - * Expose router. - */ - -exports = module.exports = router; - -/** - * Supported HTTP / WebDAV methods. - */ - -var _methods = exports.methods = [ - 'get' - , 'post' - , 'put' - , 'delete' - , 'connect' - , 'options' - , 'trace' - , 'copy' - , 'lock' - , 'mkcol' - , 'move' - , 'propfind' - , 'proppatch' - , 'unlock' - , 'report' - , 'mkactivity' - , 'checkout' - , 'merge' -]; - -/** - * Provides Sinatra and Express-like routing capabilities. - * - * Examples: - * - * connect.router(function(app){ - * app.get('/user/:id', function(req, res, next){ - * // populates req.params.id - * }); - * app.put('/user/:id', function(req, res, next){ - * // populates req.params.id - * }); - * }) - * - * @param {Function} fn - * @return {Function} - * @api public - */ - -function router(fn){ - var self = this - , methods = {} - , routes = {} - , params = {}; - - if (!fn) throw new Error('router provider requires a callback function'); - - // Generate method functions - _methods.forEach(function(method){ - methods[method] = generateMethodFunction(method.toUpperCase()); - }); - - // Alias del -> delete - methods.del = methods.delete; - - // Apply callback to all methods - methods.all = function(){ - var args = arguments; - _methods.forEach(function(name){ - methods[name].apply(this, args); - }); - return self; - }; - - // Register param callback - methods.param = function(name, fn){ - params[name] = fn; - }; - - fn.call(this, methods); - - function generateMethodFunction(name) { - var localRoutes = routes[name] = routes[name] || []; - return function(path, fn){ - var keys = [] - , middleware = []; - - // slice middleware - if (arguments.length > 2) { - middleware = Array.prototype.slice.call(arguments, 1, arguments.length); - fn = middleware.pop(); - middleware = utils.flatten(middleware); - } - - fn.middleware = middleware; - - if (!path) throw new Error(name + ' route requires a path'); - if (!fn) throw new Error(name + ' route ' + path + ' requires a callback'); - var regexp = path instanceof RegExp - ? path - : normalizePath(path, keys); - localRoutes.push({ - fn: fn - , path: regexp - , keys: keys - , orig: path - , method: name - }); - return self; - }; - } - - function router(req, res, next){ - var route - , self = this; - - (function pass(i){ - if (route = match(req, routes, i)) { - var i = 0 - , keys = route.keys; - - req.params = route.params; - - // Param preconditions - (function param(err) { - try { - var key = keys[i++] - , val = req.params[key] - , fn = params[key]; - - if ('route' == err) { - pass(req._route_index + 1); - // Error - } else if (err) { - next(err); - // Param has callback - } else if (fn) { - // Return style - if (1 == fn.length) { - req.params[key] = fn(val); - param(); - // Middleware style - } else { - fn(req, res, param, val); - } - // Finished processing params - } else if (!key) { - // route middleware - i = 0; - (function nextMiddleware(err){ - var fn = route.middleware[i++]; - if ('route' == err) { - pass(req._route_index + 1); - } else if (err) { - next(err); - } else if (fn) { - fn(req, res, nextMiddleware); - } else { - route.call(self, req, res, function(err){ - if (err) { - next(err); - } else { - pass(req._route_index + 1); - } - }); - } - })(); - // More params - } else { - param(); - } - } catch (err) { - next(err); - } - })(); - } else if ('OPTIONS' == req.method) { - options(req, res, routes); - } else { - next(); - } - })(); - }; - - router.remove = function(path, method){ - var fns = router.lookup(path, method); - fns.forEach(function(fn){ - routes[fn.method].splice(fn.index, 1); - }); - }; - - router.lookup = function(path, method, ret){ - ret = ret || []; - - // method specific lookup - if (method) { - method = method.toUpperCase(); - if (routes[method]) { - routes[method].forEach(function(route, i){ - if (path == route.orig) { - var fn = route.fn; - fn.regexp = route.path; - fn.keys = route.keys; - fn.path = route.orig; - fn.method = route.method; - fn.index = i; - ret.push(fn); - } - }); - } - // global lookup - } else { - _methods.forEach(function(method){ - router.lookup(path, method, ret); - }); - } - - return ret; - }; - - router.match = function(url, method, ret){ - var ret = ret || [] - , i = 0 - , fn - , req; - - // method specific matches - if (method) { - method = method.toUpperCase(); - req = { url: url, method: method }; - while (fn = match(req, routes, i)) { - i = req._route_index + 1; - ret.push(fn); - } - // global matches - } else { - _methods.forEach(function(method){ - router.match(url, method, ret); - }); - } - - return ret; - }; - - return router; -} - -/** - * Respond to OPTIONS. - * - * @param {ServerRequest} req - * @param {ServerResponse} req - * @param {Array} routes - * @api private - */ - -function options(req, res, routes) { - var pathname = parse(req.url).pathname - , body = optionsFor(pathname, routes).join(','); - res.writeHead(200, { - 'Content-Length': body.length - , 'Allow': body - }); - res.end(body); -} - -/** - * Return OPTIONS array for the given `path`, matching `routes`. - * - * @param {String} path - * @param {Array} routes - * @return {Array} - * @api private - */ - -function optionsFor(path, routes) { - return _methods.filter(function(method){ - var arr = routes[method.toUpperCase()]; - for (var i = 0, len = arr.length; i < len; ++i) { - if (arr[i].path.test(path)) return true; - } - }).map(function(method){ - return method.toUpperCase(); - }); -} - -/** - * Normalize the given path string, - * returning a regular expression. - * - * An empty array should be passed, - * which will contain the placeholder - * key names. For example "/user/:id" will - * then contain ["id"]. - * - * @param {String} path - * @param {Array} keys - * @return {RegExp} - * @api private - */ - -function normalizePath(path, keys) { - path = path - .concat('/?') - .replace(/\/\(/g, '(?:/') - .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){ - keys.push(key); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (format || '') + (capture || '([^/]+?)') + ')' - + (optional || ''); - }) - .replace(/([\/.])/g, '\\$1') - .replace(/\*/g, '(.+)'); - return new RegExp('^' + path + '$', 'i'); -} - -/** - * Attempt to match the given request to - * one of the routes. When successful - * a route function is returned. - * - * @param {ServerRequest} req - * @param {Object} routes - * @return {Function} - * @api private - */ - -function match(req, routes, i) { - var captures - , method = req.method - , i = i || 0; - if ('HEAD' == method) method = 'GET'; - if (routes = routes[method]) { - var url = parse(req.url) - , pathname = url.pathname; - for (var len = routes.length; i < len; ++i) { - var route = routes[i] - , fn = route.fn - , path = route.path - , keys = fn.keys = route.keys; - if (captures = path.exec(pathname)) { - fn.method = method; - fn.params = []; - for (var j = 1, len = captures.length; j < len; ++j) { - var key = keys[j-1], - val = typeof captures[j] === 'string' - ? decodeURIComponent(captures[j]) - : captures[j]; - if (key) { - fn.params[key] = val; - } else { - fn.params.push(val); - } - } - req._route_index = i; - return fn; - } - } - } -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/session.js b/node_modules/express/node_modules/connect/lib/middleware/session.js deleted file mode 100644 index 7fbeb18..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session.js +++ /dev/null @@ -1,346 +0,0 @@ - -/*! - * Connect - session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Session = require('./session/session') - , MemoryStore = require('./session/memory') - , Cookie = require('./session/cookie') - , Store = require('./session/store') - , utils = require('./../utils') - , parse = require('url').parse - , crypto = require('crypto'); - -// environment - -var env = process.env.NODE_ENV; - -/** - * Expose the middleware. - */ - -exports = module.exports = session; - -/** - * Expose constructors. - */ - -exports.Store = Store; -exports.Cookie = Cookie; -exports.Session = Session; -exports.MemoryStore = MemoryStore; - -/** - * Warning message for `MemoryStore` usage in production. - */ - -var warning = 'Warning: connection.session() MemoryStore is not\n' - + 'designed for a production environment, as it will leak\n' - + 'memory, and obviously only work within a single process.'; - -/** - * Default finger-printing function. - */ - -function defaultFingerprint(req) { - var ua = req.headers['user-agent'] || ''; - return ua.replace(/;?\schromeframe\/[\d\.]+/, ''); -}; - -/** - * Paths to ignore. - */ - -exports.ignore = []; - -/** - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](middleware-cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect.createServer( - * connect.cookieParser() - * , connect.session({ secret: 'keyboard cat' }) - * ); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` Session store instance - * - `fingerprint` Custom fingerprint generating function - * - `cookie` Session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: 14400000 }` - * - `secret` Secret string used to compute hash - * - * Ignore Paths: - * - * By default `/favicon.ico` is the only ignored path, all others - * will utilize sessions, to manipulate the paths ignored, use - * `connect.session.ignore.push('/my/path')`. This works for _full_ - * pathnames only, not segments nor substrings. - * - * connect.session.ignore.push('/robots.txt'); - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect( - * connect.cookieParser() - * , connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}) - * , connect.favicon() - * , function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

    views: ' + sess.views + '

    '); - * res.write('

    expires in: ' + (sess.cookie.maxAge / 1000) + 's

    '); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * ).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge`, and `.lastAccess` properties. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to update `req.session.lastAccess`, - * and reset `req.session.maxAge` to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -function session(options){ - var options = options || {} - , key = options.key || 'connect.sid' - , secret = options.secret - , store = options.store || new MemoryStore - , fingerprint = options.fingerprint || defaultFingerprint - , cookie = options.cookie; - - // notify user that this store is not - // meant for a production environment - if ('production' == env && store instanceof MemoryStore) { - console.warn(warning); - } - - // ensure secret is present - if (!secret) { - throw new Error('connect.session({ secret: "string" }) required for security'); - } - - // session hashing function - store.hash = function(req, base) { - return crypto - .createHmac('sha256', secret) - .update(base + fingerprint(req)) - .digest('base64') - .replace(/=*$/, ''); - }; - - // generates the new session - store.generate = function(req){ - var base = utils.uid(24); - var sessionID = base + '.' + store.hash(req, base); - req.sessionID = sessionID; - req.session = new Session(req); - req.session.cookie = new Cookie(cookie); - }; - - return function session(req, res, next) { - // self-awareness - if (req.session) return next(); - - // parse url - var url = parse(req.url) - , path = url.pathname; - - // ignorable paths - if (~exports.ignore.indexOf(path)) return next(); - - // expose store - req.sessionStore = store; - - // proxy writeHead() to Set-Cookie - var writeHead = res.writeHead; - res.writeHead = function(status, headers){ - if (req.session) { - var cookie = req.session.cookie; - // only send secure session cookies when there is a secure connection. - // proxySecure is a custom attribute to allow for a reverse proxy - // to handle SSL connections and to communicate to connect over HTTP that - // the incoming connection is secure. - var secured = cookie.secure && (req.connection.encrypted || req.connection.proxySecure); - if (secured || !cookie.secure) { - res.setHeader('Set-Cookie', cookie.serialize(key, req.sessionID)); - } - } - - res.writeHead = writeHead; - return res.writeHead(status, headers); - }; - - // proxy end() to commit the session - var end = res.end; - res.end = function(data, encoding){ - res.end = end; - if (req.session) { - // HACK: ensure Set-Cookie for implicit writeHead() - if (!res._header) res._implicitHeader(); - req.session.resetMaxAge(); - req.session.save(function(){ - res.end(data, encoding); - }); - } else { - res.end(data, encoding); - } - }; - - // session hashing - function hash(base) { - return store.hash(req, base); - } - - // generate the session - function generate() { - store.generate(req); - } - - // get the sessionID from the cookie - req.sessionID = req.cookies[key]; - - // make a new session if the browser doesn't send a sessionID - if (!req.sessionID) { - generate(); - next(); - return; - } - - // check the fingerprint - var parts = req.sessionID.split('.'); - if (parts[1] != hash(parts[0])) { - generate(); - next(); - return; - } - - // generate the session object - var pause = utils.pause(req); - store.get(req.sessionID, function(err, sess){ - // proxy to resume() events - var _next = next; - next = function(err){ - _next(err); - pause.resume(); - } - - // error handling - if (err) { - if ('ENOENT' == err.code) { - generate(); - next(); - } else { - next(err); - } - // no session - } else if (!sess) { - generate(); - next(); - // populate req.session - } else { - store.createSession(req, sess); - next(); - } - }); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js b/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js deleted file mode 100644 index 793c2e9..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js +++ /dev/null @@ -1,126 +0,0 @@ - -/*! - * Connect - session - Cookie - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils'); - -/** - * Initialize a new `Cookie` with the given `options`. - * - * @param {Object} options - * @api private - */ - -var Cookie = module.exports = function Cookie(options) { - this.path = '/'; - this.httpOnly = true; - this.maxAge = 14400000; - if (options) utils.merge(this, options); - this.originalMaxAge = undefined == this.originalMaxAge - ? this.maxAge - : this.originalMaxAge; -}; - -/** - * Prototype. - */ - -Cookie.prototype = { - - /** - * Set expires `date`. - * - * @param {Date} date - * @api public - */ - - set expires(date) { - this._expires = date; - this.originalMaxAge = this.maxAge; - }, - - /** - * Get expires `date`. - * - * @return {Date} - * @api public - */ - - get expires() { - return this._expires; - }, - - /** - * Set expires via max-age in `ms`. - * - * @param {Number} ms - * @api public - */ - - set maxAge(ms) { - this.expires = 'number' == typeof ms - ? new Date(Date.now() + ms) - : ms; - }, - - /** - * Get expires max-age in `ms`. - * - * @return {Number} - * @api public - */ - - get maxAge() { - return this.expires instanceof Date - ? this.expires.valueOf() - Date.now() - : this.expires; - }, - - /** - * Return cookie data object. - * - * @return {Object} - * @api private - */ - - get data() { - return { - originalMaxAge: this.originalMaxAge - , expires: this._expires - , secure: this.secure - , httpOnly: this.httpOnly - , domain: this.domain - , path: this.path - } - }, - - /** - * Return a serialized cookie string. - * - * @return {String} - * @api public - */ - - serialize: function(name, val){ - return utils.serializeCookie(name, val, this.data); - }, - - /** - * Return JSON representation of this cookie. - * - * @return {Object} - * @api private - */ - - toJSON: function(){ - return this.data; - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js b/node_modules/express/node_modules/connect/lib/middleware/session/memory.js deleted file mode 100644 index ec569f5..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js +++ /dev/null @@ -1,131 +0,0 @@ - -/*! - * Connect - session - MemoryStore - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Store = require('./store') - , utils = require('../../utils') - , Session = require('./session'); - -/** - * Initialize a new `MemoryStore`. - * - * @api public - */ - -var MemoryStore = module.exports = function MemoryStore() { - this.sessions = {}; -}; - -/** - * Inherit from `Store.prototype`. - */ - -MemoryStore.prototype.__proto__ = Store.prototype; - -/** - * Attempt to fetch session by the given `sid`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.get = function(sid, fn){ - var self = this; - process.nextTick(function(){ - var expires - , sess = self.sessions[sid]; - if (sess) { - sess = JSON.parse(sess); - expires = 'string' == typeof sess.cookie.expires - ? new Date(sess.cookie.expires) - : sess.cookie.expires; - if (!expires || new Date < expires) { - fn(null, sess); - } else { - self.destroy(sid, fn); - } - } else { - fn(); - } - }); -}; - -/** - * Commit the given `sess` object associated with the given `sid`. - * - * @param {String} sid - * @param {Session} sess - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.set = function(sid, sess, fn){ - var self = this; - process.nextTick(function(){ - self.sessions[sid] = JSON.stringify(sess); - fn && fn(); - }); -}; - -/** - * Destroy the session associated with the given `sid`. - * - * @param {String} sid - * @api public - */ - -MemoryStore.prototype.destroy = function(sid, fn){ - var self = this; - process.nextTick(function(){ - delete self.sessions[sid]; - fn && fn(); - }); -}; - -/** - * Invoke the given callback `fn` with all active sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.all = function(fn){ - var arr = [] - , keys = Object.keys(this.sessions); - for (var i = 0, len = keys.length; i < len; ++i) { - arr.push(this.sessions[keys[i]]); - } - fn(null, arr); -}; - -/** - * Clear all sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.clear = function(fn){ - this.sessions = {}; - fn && fn(); -}; - -/** - * Fetch number of sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.length = function(fn){ - fn(null, Object.keys(this.sessions).length); -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/session.js b/node_modules/express/node_modules/connect/lib/middleware/session/session.js deleted file mode 100644 index 4e7e1a6..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/session.js +++ /dev/null @@ -1,137 +0,0 @@ - -/*! - * Connect - session - Session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils') - , Cookie = require('./cookie'); - -/** - * Create a new `Session` with the given request and `data`. - * - * @param {IncomingRequest} req - * @param {Object} data - * @api private - */ - -var Session = module.exports = function Session(req, data) { - Object.defineProperty(this, 'req', { value: req }); - Object.defineProperty(this, 'id', { value: req.sessionID }); - if ('object' == typeof data) { - utils.merge(this, data); - } else { - this.lastAccess = Date.now(); - } -}; - -/** - * Update `.lastAccess` timestamp, - * and reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.touch = function(){ - return this - .resetLastAccess() - .resetMaxAge(); -}; - -/** - * Update `.lastAccess` timestamp. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.resetLastAccess = function(){ - this.lastAccess = Date.now(); - return this; -}; - -/** - * Reset `.maxAge` to `.originalMaxAge`. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.resetMaxAge = function(){ - this.cookie.maxAge = this.cookie.originalMaxAge; - return this; -}; - -/** - * Save the session data with optional callback `fn(err)`. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.save = function(fn){ - this.req.sessionStore.set(this.id, this, fn || function(){}); - return this; -}; - -/** - * Re-loads the session data _without_ altering - * the maxAge or lastAccess properties. Invokes the - * callback `fn(err)`, after which time if no exception - * has occurred the `req.session` property will be - * a new `Session` object, although representing the - * same session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.reload = function(fn){ - var req = this.req - , store = this.req.sessionStore; - store.get(this.id, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(new Error('failed to load session')); - store.createSession(req, sess); - fn(); - }); - return this; -}; - -/** - * Destroy `this` session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.destroy = function(fn){ - delete this.req.session; - this.req.sessionStore.destroy(this.id, fn); - return this; -}; - -/** - * Regenerate this request's session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.regenerate = function(fn){ - this.req.sessionStore.regenerate(this.req, fn); - return this; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/store.js b/node_modules/express/node_modules/connect/lib/middleware/session/store.js deleted file mode 100644 index 6a3d47d..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/store.js +++ /dev/null @@ -1,87 +0,0 @@ - -/*! - * Connect - session - Store - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Session = require('./session') - , Cookie = require('./cookie') - , utils = require('../../utils'); - -/** - * Initialize abstract `Store`. - * - * @api private - */ - -var Store = module.exports = function Store(options){}; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Store.prototype.__proto__ = EventEmitter.prototype; - -/** - * Re-generate the given requests's session. - * - * @param {IncomingRequest} req - * @return {Function} fn - * @api public - */ - -Store.prototype.regenerate = function(req, fn){ - var self = this; - this.destroy(req.sessionID, function(err){ - self.generate(req); - fn(err); - }); -}; - -/** - * Load a `Session` instance via the given `sid` - * and invoke the callback `fn(err, sess)`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -Store.prototype.load = function(sid, fn){ - var self = this; - this.get(sid, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(); - var req = { sessionID: sid, sessionStore: self }; - sess = self.createSession(req, sess, false); - fn(null, sess); - }); -}; - -/** - * Create session from JSON `sess` data. - * - * @param {IncomingRequest} req - * @param {Object} sess - * @return {Session} - * @api private - */ - -Store.prototype.createSession = function(req, sess, update){ - var expires = sess.cookie.expires - , orig = sess.cookie.originalMaxAge - , update = null == update ? true : false; - sess.cookie = new Cookie(sess.cookie); - if ('string' == typeof expires) sess.cookie.expires = new Date(expires); - sess.cookie.originalMaxAge = orig; - req.session = new Session(req, sess); - if (update) req.session.resetLastAccess(); - return req.session; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/static.js b/node_modules/express/node_modules/connect/lib/middleware/static.js deleted file mode 100644 index b9c2c86..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/static.js +++ /dev/null @@ -1,225 +0,0 @@ - -/*! - * Connect - staticProvider - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , path = require('path') - , join = path.join - , basename = path.basename - , normalize = path.normalize - , utils = require('../utils') - , Buffer = require('buffer').Buffer - , parse = require('url').parse - , mime = require('mime'); - -/** - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect( - * connect.static(__dirname + '/public') - * ).listen(3000); - * - * connect( - * connect.static(__dirname + '/public', { maxAge: oneDay }) - * ).listen(3000); - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function static(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('static() root path required'); - options.root = root; - - return function static(req, res, next) { - options.path = req.url; - options.getOnly = true; - send(req, res, next, options); - }; -}; - -/** - * Expose mime module. - */ - -exports.mime = mime; - -/** - * Respond with 416 "Requested Range Not Satisfiable" - * - * @param {ServerResponse} res - * @api private - */ - -function invalidRange(res) { - var body = 'Requested Range Not Satisfiable'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', body.length); - res.statusCode = 416; - res.end(body); -} - -/** - * Attempt to tranfer the requseted file to `res`. - * - * @param {ServerRequest} - * @param {ServerResponse} - * @param {Function} next - * @param {Object} options - * @api private - */ - -var send = exports.send = function(req, res, next, options){ - options = options || {}; - if (!options.path) throw new Error('path required'); - - // setup - var maxAge = options.maxAge || 0 - , ranges = req.headers.range - , head = 'HEAD' == req.method - , get = 'GET' == req.method - , root = options.root ? normalize(options.root) : null - , redirect = false === options.redirect ? false : true - , getOnly = options.getOnly - , fn = options.callback - , hidden = options.hidden - , done; - - // replace next() with callback when available - if (fn) next = fn; - - // ignore non-GET requests - if (getOnly && !get && !head) return next(); - - // parse url - var url = parse(options.path) - , path = decodeURIComponent(url.pathname) - , type; - - // null byte(s) - if (~path.indexOf('\0')) return utils.badRequest(res); - - // when root is not given, consider .. malicious - if (!root && ~path.indexOf('..')) return utils.forbidden(res); - - // join / normalize from optional root dir - path = normalize(join(root, path)); - - // malicious path - if (root && 0 != path.indexOf(root)) return fn - ? fn(new Error('Forbidden')) - : utils.forbidden(res); - - // index.html support - if (normalize('/') == path[path.length - 1]) path += 'index.html'; - - // "hidden" file - if (!hidden && '.' == basename(path)[0]) return next(); - - fs.stat(path, function(err, stat){ - // mime type - type = mime.lookup(path); - - // ignore ENOENT - if (err) { - if (fn) return fn(err); - return 'ENOENT' == err.code - ? next() - : next(err); - // redirect directory in case index.html is present - } else if (stat.isDirectory()) { - if (!redirect) return next(); - res.statusCode = 301; - res.setHeader('Location', url.pathname + '/'); - res.end('Redirecting to ' + url.pathname + '/'); - return; - } - - // header fields - if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString()); - if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000)); - if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString()); - if (!res.getHeader('ETag')) res.setHeader('ETag', utils.etag(stat)); - if (!res.getHeader('content-type')) { - var charset = mime.charsets.lookup(type); - res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); - } - res.setHeader('Accept-Ranges', 'bytes'); - - // conditional GET support - if (utils.conditionalGET(req)) { - if (!utils.modified(req, res)) { - req.emit('static'); - return utils.notModified(res); - } - } - - var opts = {}; - var chunkSize = stat.size; - - // we have a Range request - if (ranges) { - ranges = utils.parseRange(stat.size, ranges); - // valid - if (ranges) { - // TODO: stream options - // TODO: multiple support - opts.start = ranges[0].start; - opts.end = ranges[0].end; - chunkSize = opts.end - opts.start + 1; - res.statusCode = 206; - res.setHeader('Content-Range', 'bytes ' - + opts.start - + '-' - + opts.end - + '/' - + stat.size); - // invalid - } else { - return fn - ? fn(new Error('Requested Range Not Satisfiable')) - : invalidRange(res); - } - } - - res.setHeader('Content-Length', chunkSize); - - // transfer - if (head) return res.end(); - - // stream - var stream = fs.createReadStream(path, opts); - req.emit('static', stream); - stream.pipe(res); - - // callback - if (fn) { - function callback(err) { done || fn(err); done = true } - req.on('close', callback); - stream.on('end', callback); - } - }); -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js b/node_modules/express/node_modules/connect/lib/middleware/staticCache.js deleted file mode 100644 index 9ea8eb7..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js +++ /dev/null @@ -1,175 +0,0 @@ - -/*! - * Connect - staticCache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , utils = require('../utils') - , Cache = require('../cache') - , url = require('url') - , fs = require('fs'); - -/** - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - * - * @param {Type} name - * @return {Type} - * @api public - */ - -module.exports = function staticCache(options){ - var options = options || {} - , cache = new Cache(options.maxObjects || 128) - , maxlen = options.maxLength || 1024 * 256; - - return function staticCache(req, res, next){ - var path = url.parse(req.url).pathname - , ranges = req.headers.range - , hit = cache.get(path) - , hitCC - , uaCC - , header - , age; - - // cache static - req.on('static', function(stream){ - var headers = res._headers - , cc = utils.parseCacheControl(headers['cache-control'] || '') - , contentLength = headers['content-length'] - , hit; - - // ignore larger files - if (!contentLength || contentLength > maxlen) return; - - // dont cache items we shouldn't be - if ( cc['no-cache'] - || cc['no-store'] - || cc['private'] - || cc['must-revalidate']) return; - - // if already in cache then validate - if (hit = cache.get(path)){ - if (headers.etag == hit[0].etag) { - hit[0].date = new Date; - return; - } else { - cache.remove(path); - } - } - - // validation notifiactions don't contain a steam - if (null == stream) return; - - // add the cache object - var arr = cache.add(path); - arr.push(headers); - - // store the chunks - stream.on('data', function(chunk){ - arr.push(chunk); - }); - - // flag it as complete - stream.on('end', function(){ - arr.complete = true; - }); - }); - - // cache hit, doesnt support range requests - if (hit && hit.complete && !ranges) { - header = utils.merge({}, hit[0]); - header.Age = age = (new Date - new Date(header.date)) / 1000 | 0; - header.date = new Date().toUTCString(); - - // parse cache-controls - hitCC = utils.parseCacheControl(header['cache-control'] || ''); - uaCC = utils.parseCacheControl(req.headers['cache-control'] || ''); - - // check if we must revalidate(bypass) - if (hitCC['no-cache'] || uaCC['no-cache']) return next(); - - // check freshness of entity - if (isStale(hitCC, age) || isStale(uaCC, age)) return next(); - - // conditional GET support - if (utils.conditionalGET(req)) { - if (!utils.modified(req, res, header)) { - header['content-length'] = 0; - res.writeHead(304, header); - return res.end(); - } - } - - // HEAD support - if ('HEAD' == req.method) { - header['content-length'] = 0; - res.writeHead(200, header); - return res.end(); - } - - // respond with cache - res.writeHead(200, header); - - // backpressure - function write(i) { - var buf = hit[i]; - if (!buf) return res.end(); - if (false === res.write(buf)) { - res.once('drain', function(){ - write(++i); - }); - } else { - write(++i); - } - } - - return write(1); - } - - next(); - } -}; - -/** - * Check if cache item is stale - * - * @param {Object} cc - * @param {Number} age - * @return {Boolean} - * @api private - */ - -function isStale(cc, age) { - return cc['max-age'] && cc['max-age'] <= age; -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/vhost.js b/node_modules/express/node_modules/connect/lib/middleware/vhost.js deleted file mode 100644 index 913d756..0000000 --- a/node_modules/express/node_modules/connect/lib/middleware/vhost.js +++ /dev/null @@ -1,44 +0,0 @@ - -/*! - * Connect - vhost - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Setup vhost for the given `hostname` and `server`. - * - * Examples: - * - * connect( - * connect.vhost('foo.com', - * connect.createServer(...middleware...) - * ), - * connect.vhost('bar.com', - * connect.createServer(...middleware...) - * ) - * ); - * - * @param {String} hostname - * @param {Server} server - * @return {Function} - * @api public - */ - -module.exports = function vhost(hostname, server){ - if (!hostname) throw new Error('vhost hostname required'); - if (!server) throw new Error('vhost server required'); - var regexp = new RegExp('^' + hostname.replace(/[*]/g, '(.*?)') + '$'); - if (server.onvhost) server.onvhost(hostname); - return function vhost(req, res, next){ - if (!req.headers.host) return next(); - var host = req.headers.host.split(':')[0]; - if (req.subdomains = regexp.exec(host)) { - req.subdomains = req.subdomains[0].split('.').slice(0, -1); - server.emit("request", req, res); - } else { - next(); - } - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/patch.js b/node_modules/express/node_modules/connect/lib/patch.js deleted file mode 100644 index a6ff297..0000000 --- a/node_modules/express/node_modules/connect/lib/patch.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , res = http.OutgoingMessage.prototype; - -// original setHeader() - -var setHeader = res.setHeader; - -// original _renderHeaders() - -var _renderHeaders = res._renderHeaders; - -if (res._hasConnectPatch) return; - -/** - * Provide a public "header sent" flag - * until node does. - * - * @return {Boolean} - * @api public - */ - -res.__defineGetter__('headerSent', function(){ - return this._headerSent; -}); - -/** - * Set header `field` to `val`, special-casing - * the `Set-Cookie` field for multiple support. - * - * @param {String} field - * @param {String} val - * @api public - */ - -res.setHeader = function(field, val){ - var key = field.toLowerCase() - , prev; - - // special-case Set-Cookie - if (this._headers && 'set-cookie' == key) { - if (prev = this.getHeader(field)) { - val = Array.isArray(prev) - ? prev.concat(val) - : [prev, val]; - } - // charset - } else if ('content-type' == key && this.charset) { - val += '; charset=' + this.charset; - } - - return setHeader.call(this, field, val); -}; - -/** - * Proxy `res.end()` to expose a 'header' event, - * allowing arbitrary augmentation before the header - * fields are written to the socket. - * - * NOTE: this _only_ supports node's progressive header - * field API aka `res.setHeader()`. - */ - -res._renderHeaders = function(){ - this.emit('header'); - return _renderHeaders.call(this); -}; - -res._hasConnectPatch = true; diff --git a/node_modules/express/node_modules/connect/lib/public/directory.html b/node_modules/express/node_modules/connect/lib/public/directory.html deleted file mode 100644 index 15164bb..0000000 --- a/node_modules/express/node_modules/connect/lib/public/directory.html +++ /dev/null @@ -1,75 +0,0 @@ - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/public/error.html b/node_modules/express/node_modules/connect/lib/public/error.html deleted file mode 100644 index 34e0df5..0000000 --- a/node_modules/express/node_modules/connect/lib/public/error.html +++ /dev/null @@ -1,13 +0,0 @@ - - - {error} - - - -
    -

    {title}

    -

    500 {error}

    -
      {stack}
    -
    - - \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/public/favicon.ico b/node_modules/express/node_modules/connect/lib/public/favicon.ico deleted file mode 100644 index 895fc96..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/favicon.ico and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page.png b/node_modules/express/node_modules/connect/lib/public/icons/page.png deleted file mode 100755 index 03ddd79..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_add.png deleted file mode 100755 index d5bfa07..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png b/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png deleted file mode 100755 index 89ee2da..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_code.png deleted file mode 100755 index f7ea904..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png deleted file mode 100755 index 195dc6d..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png deleted file mode 100755 index 3141467..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png deleted file mode 100755 index 046811e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_error.png deleted file mode 100755 index f07f449..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png deleted file mode 100755 index eb6158e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_find.png deleted file mode 100755 index 2f19388..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png deleted file mode 100755 index 8e83281..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_go.png deleted file mode 100755 index 80fe1ed..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png b/node_modules/express/node_modules/connect/lib/public/icons/page_green.png deleted file mode 100755 index de8e003..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_key.png deleted file mode 100755 index d6626cb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png deleted file mode 100755 index 7e56870..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_link.png deleted file mode 100755 index 312eab0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png deleted file mode 100755 index 246a2f0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png deleted file mode 100755 index 968f073..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_red.png deleted file mode 100755 index 0b18247..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png deleted file mode 100755 index cf347c7..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png b/node_modules/express/node_modules/connect/lib/public/icons/page_save.png deleted file mode 100755 index caea546..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white.png deleted file mode 100755 index 8b8b1ca..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png deleted file mode 100755 index 8f8095e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png deleted file mode 100755 index 159b240..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png deleted file mode 100755 index aa23dde..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png deleted file mode 100755 index 34a05cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png deleted file mode 100755 index f501a59..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png deleted file mode 100755 index 848bdaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png deleted file mode 100755 index 0c76bd1..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png deleted file mode 100755 index 87a6914..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png deleted file mode 100755 index c66011f..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png deleted file mode 100755 index 2b6b100..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png deleted file mode 100755 index a9f31a2..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png deleted file mode 100755 index a87cf84..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png deleted file mode 100755 index ffb8fc9..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png deleted file mode 100755 index 0a7d6f4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png deleted file mode 100755 index bddba1f..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png deleted file mode 100755 index af1ecaf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png deleted file mode 100755 index 4cc537a..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png deleted file mode 100755 index b93e776..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png deleted file mode 100755 index 9fc5a0a..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png deleted file mode 100755 index b977d7e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png deleted file mode 100755 index 5818436..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png deleted file mode 100755 index 5769120..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png deleted file mode 100755 index 8d719df..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png deleted file mode 100755 index 106f5aa..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png deleted file mode 100755 index e4a1ecb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png deleted file mode 100755 index 7e62a92..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png deleted file mode 100755 index e902abb..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png deleted file mode 100755 index 1d2d0a4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png deleted file mode 100755 index d616484..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png deleted file mode 100755 index 7215d1e..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png deleted file mode 100755 index bf7bd1c..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png deleted file mode 100755 index f6b74cc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png deleted file mode 100755 index d3fffb6..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png deleted file mode 100755 index a65bcb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png deleted file mode 100755 index 23a37b8..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png deleted file mode 100755 index f907e44..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png deleted file mode 100755 index 5b2cbb3..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png deleted file mode 100755 index 7868a25..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png deleted file mode 100755 index 134b669..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png deleted file mode 100755 index c4eff03..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png deleted file mode 100755 index 884ffd6..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png deleted file mode 100755 index f59b7c4..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png deleted file mode 100755 index 44084ad..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png deleted file mode 100755 index 3a1441c..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png deleted file mode 100755 index e770829..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png deleted file mode 100755 index 813f712..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png deleted file mode 100755 index d9cf132..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png deleted file mode 100755 index 52699bf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png deleted file mode 100755 index 4a05955..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png deleted file mode 100755 index a0a433d..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png deleted file mode 100755 index 1eb8809..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png deleted file mode 100755 index ae8ecbf..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png deleted file mode 100755 index 6ed2490..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png deleted file mode 100755 index fecadd0..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png deleted file mode 100755 index fd4bbcc..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_word.png deleted file mode 100755 index 834cdfa..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_world.png deleted file mode 100755 index b8895dd..0000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/style.css b/node_modules/express/node_modules/connect/lib/public/style.css deleted file mode 100644 index 32b6507..0000000 --- a/node_modules/express/node_modules/connect/lib/public/style.css +++ /dev/null @@ -1,141 +0,0 @@ -body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul { - margin: 0; - padding: 0; -} -ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 500px; -} -ul#files li { - padding: 0; -} -ul#files li img { - position: absolute; - top: 5px; - left: 5px; -} -ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; -} -ul#files li a.icon { - text-indent: 25px; -} -ul#files li a:focus, -ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} diff --git a/node_modules/express/node_modules/connect/lib/utils.js b/node_modules/express/node_modules/connect/lib/utils.js deleted file mode 100644 index d0bc172..0000000 --- a/node_modules/express/node_modules/connect/lib/utils.js +++ /dev/null @@ -1,451 +0,0 @@ - -/*! - * Connect - utils - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var crypto = require('crypto') - , Path = require('path') - , fs = require('fs'); - -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = function(arr, ret){ - var ret = ret || [] - , len = arr.length; - for (var i = 0; i < len; ++i) { - if (Array.isArray(arr[i])) { - exports.flatten(arr[i], ret); - } else { - ret.push(arr[i]); - } - } - return ret; -}; - -/** - * Return md5 hash of the given string and optional encoding, - * defaulting to hex. - * - * utils.md5('wahoo'); - * // => "e493298061761236c96b02ea6aa8a2ad" - * - * @param {String} str - * @param {String} encoding - * @return {String} - * @api public - */ - -exports.md5 = function(str, encoding){ - return crypto - .createHash('md5') - .update(str) - .digest(encoding || 'hex'); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api public - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api public - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - - -/** - * Return a unique identifier with the given `len`. - * - * utils.uid(10); - * // => "FDaS435D2z" - * - * @param {Number} len - * @return {String} - * @api public - */ - -exports.uid = function(len) { - var buf = [] - , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' - , charlen = chars.length; - - for (var i = 0; i < len; ++i) { - buf.push(chars[getRandomInt(0, charlen - 1)]); - } - - return buf.join(''); -}; - -/** - * Parse the given cookie string into an object. - * - * @param {String} str - * @return {Object} - * @api public - */ - -exports.parseCookie = function(str){ - var obj = {} - , pairs = str.split(/[;,] */); - for (var i = 0, len = pairs.length; i < len; ++i) { - var pair = pairs[i] - , eqlIndex = pair.indexOf('=') - , key = pair.substr(0, eqlIndex).trim().toLowerCase() - , val = pair.substr(++eqlIndex, pair.length).trim(); - - // quoted values - if ('"' == val[0]) val = val.slice(1, -1); - - // only assign once - if (undefined == obj[key]) { - val = val.replace(/\+/g, ' '); - try { - obj[key] = decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - obj[key] = val; - } else { - throw err; - } - } - } - } - return obj; -}; - -/** - * Serialize the given object into a cookie string. - * - * utils.serializeCookie('name', 'tj', { httpOnly: true }) - * // => "name=tj; httpOnly" - * - * @param {String} name - * @param {String} val - * @param {Object} obj - * @return {String} - * @api public - */ - -exports.serializeCookie = function(name, val, obj){ - var pairs = [name + '=' + encodeURIComponent(val)] - , obj = obj || {}; - - if (obj.domain) pairs.push('domain=' + obj.domain); - if (obj.path) pairs.push('path=' + obj.path); - if (obj.expires) pairs.push('expires=' + obj.expires.toUTCString()); - if (obj.httpOnly) pairs.push('httpOnly'); - if (obj.secure) pairs.push('secure'); - - return pairs.join('; '); -}; - -/** - * Pause `data` and `end` events on the given `obj`. - * Middleware performing async tasks _should_ utilize - * this utility (or similar), to re-emit data once - * the async operation has completed, otherwise these - * events may be lost. - * - * var pause = utils.pause(req); - * fs.readFile(path, function(){ - * next(); - * pause.resume(); - * }); - * - * @param {Object} obj - * @return {Object} - * @api public - */ - -exports.pause = function(obj){ - var onData - , onEnd - , events = []; - - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); - - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); - - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; -}; - -/** - * Check `req` and `res` to see if it has been modified. - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @return {Boolean} - * @api public - */ - -exports.modified = function(req, res, headers) { - var headers = headers || res._headers || {} - , modifiedSince = req.headers['if-modified-since'] - , lastModified = headers['last-modified'] - , noneMatch = req.headers['if-none-match'] - , etag = headers['etag']; - - if (noneMatch) noneMatch = noneMatch.split(/ *, */); - - // check If-None-Match - if (noneMatch && etag && ~noneMatch.indexOf(etag)) { - return false; - } - - // check If-Modified-Since - if (modifiedSince && lastModified) { - modifiedSince = new Date(modifiedSince); - lastModified = new Date(lastModified); - // Ignore invalid dates - if (!isNaN(modifiedSince.getTime())) { - if (lastModified <= modifiedSince) return false; - } - } - - return true; -}; - -/** - * Strip `Content-*` headers from `res`. - * - * @param {ServerResponse} res - * @api public - */ - -exports.removeContentHeaders = function(res){ - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Check if `req` is a conditional GET request. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api public - */ - -exports.conditionalGET = function(req) { - return req.headers['if-modified-since'] - || req.headers['if-none-match']; -}; - -/** - * Respond with 403 "Forbidden". - * - * @param {ServerResponse} res - * @api public - */ - -exports.forbidden = function(res) { - var body = 'Forbidden'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', body.length); - res.statusCode = 403; - res.end(body); -}; - -/** - * Respond with 401 "Unauthorized". - * - * @param {ServerResponse} res - * @param {String} realm - * @api public - */ - -exports.unauthorized = function(res, realm) { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); - res.end('Unauthorized'); -}; - -/** - * Respond with 400 "Bad Request". - * - * @param {ServerResponse} res - * @api public - */ - -exports.badRequest = function(res) { - res.statusCode = 400; - res.end('Bad Request'); -}; - -/** - * Respond with 304 "Not Modified". - * - * @param {ServerResponse} res - * @param {Object} headers - * @api public - */ - -exports.notModified = function(res) { - exports.removeContentHeaders(res); - res.statusCode = 304; - res.end(); -}; - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api public - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * Parse "Range" header `str` relative to the given file `size`. - * - * @param {Number} size - * @param {String} str - * @return {Array} - * @api public - */ - -exports.parseRange = function(size, str){ - var valid = true; - var arr = str.substr(6).split(',').map(function(range){ - var range = range.split('-') - , start = parseInt(range[0], 10) - , end = parseInt(range[1], 10); - - // -500 - if (isNaN(start)) { - start = size - end; - end = size - 1; - // 500- - } else if (isNaN(end)) { - end = size - 1; - } - - // Invalid - if (isNaN(start) || isNaN(end) || start > end) valid = false; - - return { start: start, end: end }; - }); - return valid ? arr : undefined; -}; - -/** - * Parse the given Cache-Control `str`. - * - * @param {String} str - * @return {Object} - * @api public - */ - -exports.parseCacheControl = function(str){ - var directives = str.split(',') - , obj = {}; - - for(var i = 0, len = directives.length; i < len; i++) { - var parts = directives[i].split('=') - , key = parts.shift().trim() - , val = parseInt(parts.shift(), 10); - - obj[key] = isNaN(val) ? true : val; - } - - return obj; -}; - - -/** - * Convert array-like object to an `Array`. - * - * node-bench measured "16.5 times faster than Array.prototype.slice.call()" - * - * @param {Object} obj - * @return {Array} - * @api public - */ - -var toArray = exports.toArray = function(obj){ - var len = obj.length - , arr = new Array(len); - for (var i = 0; i < len; ++i) { - arr[i] = obj[i]; - } - return arr; -}; - -/** - * Retrun a random int, used by `utils.uid()` - * - * @param {Number} min - * @param {Number} max - * @return {Number} - * @api private - */ - -function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/..travis.yml.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/..travis.yml.un~ deleted file mode 100644 index 5dc982f..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/..travis.yml.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.Readme.md.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/.Readme.md.un~ deleted file mode 100644 index 1898fa0..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/.Readme.md.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore b/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore deleted file mode 100644 index 4fbabb3..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -/test/tmp/ -*.upload -*.un~ -*.http diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.package.json.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/.package.json.un~ deleted file mode 100644 index 26c5b26..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/.package.json.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml b/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/Makefile b/node_modules/express/node_modules/connect/node_modules/formidable/Makefile deleted file mode 100644 index 8945872..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -SHELL := /bin/bash - -test: - @./test/run.js - -build: npm test - -npm: - npm install . - -clean: - rm test/tmp/* - -.PHONY: test clean build diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md b/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md deleted file mode 100644 index 3427514..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/Readme.md +++ /dev/null @@ -1,303 +0,0 @@ -# Formidable - -[![Build Status](https://secure.travis-ci.org/felixge/node-formidable.png)](http://travis-ci.org/felixge/node-formidable) - -## Purpose - -A node.js module for parsing form data, especially file uploads. - -## Current status - -This module was developed for [Transloadit](http://transloadit.com/), a service focused on uploading -and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from -a large variety of clients and is considered production-ready. - -## Features - -* Fast (~500mb/sec), non-buffering multipart parser -* Automatically writing file uploads to disk -* Low memory footprint -* Graceful error handling -* Very high test coverage - -## Changelog - -### v1.0.9 - -* Emit progress when content length header parsed (Tim Koschützki) -* Fix Readme syntax due to GitHub changes (goob) -* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara) - -### v1.0.8 - -* Strip potentially unsafe characters when using `keepExtensions: true`. -* Switch to utest / urun for testing -* Add travis build - -### v1.0.7 - -* Remove file from package that was causing problems when installing on windows. (#102) -* Fix typos in Readme (Jason Davies). - -### v1.0.6 - -* Do not default to the default to the field name for file uploads where - filename="". - -### v1.0.5 - -* Support filename="" in multipart parts -* Explain unexpected end() errors in parser better - -**Note:** Starting with this version, formidable emits 'file' events for empty -file input fields. Previously those were incorrectly emitted as regular file -input fields with value = "". - -### v1.0.4 - -* Detect a good default tmp directory regardless of platform. (#88) - -### v1.0.3 - -* Fix problems with utf8 characters (#84) / semicolons in filenames (#58) -* Small performance improvements -* New test suite and fixture system - -### v1.0.2 - -* Exclude node\_modules folder from git -* Implement new `'aborted'` event -* Fix files in example folder to work with recent node versions -* Make gently a devDependency - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2) - -### v1.0.1 - -* Fix package.json to refer to proper main directory. (#68, Dean Landolt) - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1) - -### v1.0.0 - -* Add support for multipart boundaries that are quoted strings. (Jeff Craig) - -This marks the beginning of development on version 2.0 which will include -several architectural improvements. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0) - -### v0.9.11 - -* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki) -* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class - -**Important:** The old property names of the File class will be removed in a -future release. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11) - -### Older releases - -These releases were done before starting to maintain the above Changelog: - -* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10) -* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9) -* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8) -* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7) -* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6) -* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5) -* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4) -* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3) -* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2) -* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0) - -## Installation - -Via [npm](http://github.com/isaacs/npm): - - npm install formidable@latest - -Manually: - - git clone git://github.com/felixge/node-formidable.git formidable - vim my.js - # var formidable = require('./formidable'); - -Note: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library. - -## Example - -Parse an incoming file upload. - - var formidable = require('formidable'), - http = require('http'), - - util = require('util'); - - http.createServer(function(req, res) { - if (req.url == '/upload' && req.method.toLowerCase() == 'post') { - // parse a file upload - var form = new formidable.IncomingForm(); - form.parse(req, function(err, fields, files) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received upload:\n\n'); - res.end(util.inspect({fields: fields, files: files})); - }); - return; - } - - // show a file upload form - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }).listen(80); - -## API - -### formidable.IncomingForm - -__new formidable.IncomingForm()__ - -Creates a new incoming form. - -__incomingForm.encoding = 'utf-8'__ - -The encoding to use for incoming form fields. - -__incomingForm.uploadDir = process.env.TMP || '/tmp' || process.cwd()__ - -The directory for placing file uploads in. You can move them later on using -`fs.rename()`. The default directory is picked at module load time depending on -the first existing directory from those listed above. - -__incomingForm.keepExtensions = false__ - -If you want the files written to `incomingForm.uploadDir` to include the extensions of the original files, set this property to `true`. - -__incomingForm.type__ - -Either 'multipart' or 'urlencoded' depending on the incoming request. - -__incomingForm.maxFieldsSize = 2 * 1024 * 1024__ - -Limits the amount of memory a field (not file) can allocate in bytes. -If this value is exceeded, an `'error'` event is emitted. The default -size is 2MB. - -__incomingForm.bytesReceived__ - -The amount of bytes received for this form so far. - -__incomingForm.bytesExpected__ - -The expected number of bytes in this form. - -__incomingForm.parse(request, [cb])__ - -Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields an files are collected and passed to the callback: - - incomingForm.parse(req, function(err, fields, files) { - // ... - }); - -__incomingForm.onPart(part)__ - -You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing. - - incomingForm.onPart = function(part) { - part.addListener('data', function() { - // ... - }); - } - -If you want to use formidable to only handle certain parts for you, you can do so: - - incomingForm.onPart = function(part) { - if (!part.filename) { - // let formidable handle all non-file parts - incomingForm.handlePart(part); - } - } - -Check the code in this method for further inspiration. - -__Event: 'progress' (bytesReceived, bytesExpected)__ - -Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar. - -__Event: 'field' (name, value)__ - -Emitted whenever a field / value pair has been received. - -__Event: 'fileBegin' (name, file)__ - -Emitted whenever a new file is detected in the upload stream. Use this even if -you want to stream the file to somewhere else while buffering the upload on -the file system. - -__Event: 'file' (name, file)__ - -Emitted whenever a field / file pair has been received. `file` is an instance of `File`. - -__Event: 'error' (err)__ - -Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events. - -__Event: 'aborted'__ - -Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. In the future there will be a separate 'timeout' event (needs a change in the node core). - -__Event: 'end' ()__ - -Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response. - -### formidable.File - -__file.size = 0__ - -The size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet. - -__file.path = null__ - -The path this file is being written to. You can modify this in the `'fileBegin'` event in -case you are unhappy with the way formidable generates a temporary path for your files. - -__file.name = null__ - -The name this file had according to the uploading client. - -__file.type = null__ - -The mime type of this file, according to the uploading client. - -__file.lastModifiedDate = null__ - -A date object (or `null`) containing the time this file was last written to. Mostly -here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). - -## License - -Formidable is licensed under the MIT license. - -## Ports - -* [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ parser based on formidable - -## Credits - -* [Ryan Dahl](http://twitter.com/ryah) for his work on [http-parser](http://github.com/ry/http-parser) which heavily inspired multipart_parser.js diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/TODO b/node_modules/express/node_modules/connect/node_modules/formidable/TODO deleted file mode 100644 index e1107f2..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/TODO +++ /dev/null @@ -1,3 +0,0 @@ -- Better bufferMaxSize handling approach -- Add tests for JSON parser pull request and merge it -- Implement QuerystringParser the same way as MultipartParser diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js deleted file mode 100644 index bff41f1..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js +++ /dev/null @@ -1,70 +0,0 @@ -require('../test/common'); -var multipartParser = require('../lib/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - Buffer = require('buffer').Buffer, - boundary = '-----------------------------168072824752491622650073', - mb = 100, - buffer = createMultipartBuffer(boundary, mb * 1024 * 1024), - callbacks = - { partBegin: -1, - partEnd: -1, - headerField: -1, - headerValue: -1, - partData: -1, - end: -1, - }; - - -parser.initWithBoundary(boundary); -parser.onHeaderField = function() { - callbacks.headerField++; -}; - -parser.onHeaderValue = function() { - callbacks.headerValue++; -}; - -parser.onPartBegin = function() { - callbacks.partBegin++; -}; - -parser.onPartData = function() { - callbacks.partData++; -}; - -parser.onPartEnd = function() { - callbacks.partEnd++; -}; - -parser.onEnd = function() { - callbacks.end++; -}; - -var start = +new Date(), - nparsed = parser.write(buffer), - duration = +new Date - start, - mbPerSec = (mb / (duration / 1000)).toFixed(2); - -console.log(mbPerSec+' mb/sec'); - -assert.equal(nparsed, buffer.length); - -function createMultipartBuffer(boundary, size) { - var head = - '--'+boundary+'\r\n' - + 'content-disposition: form-data; name="field1"\r\n' - + '\r\n' - , tail = '\r\n--'+boundary+'--\r\n' - , buffer = new Buffer(size); - - buffer.write(head, 'ascii', 0); - buffer.write(tail, 'ascii', buffer.length - tail.length); - return buffer; -} - -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]); - } -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js b/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js deleted file mode 100644 index f6c15a6..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js +++ /dev/null @@ -1,43 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/post') { - var form = new formidable.IncomingForm(), - fields = []; - - form - .on('error', function(err) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('error:\n\n'+util.inspect(err)); - }) - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('end', function() { - console.log('-> post done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('received fields:\n\n '+util.inspect(fields)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js b/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js deleted file mode 100644 index 050cdd9..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js +++ /dev/null @@ -1,48 +0,0 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; - -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/upload') { - var form = new formidable.IncomingForm(), - files = [], - fields = []; - - form.uploadDir = TEST_TMP; - - form - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('file', function(field, file) { - console.log(field, file); - files.push([field, file]); - }) - .on('end', function() { - console.log('-> upload done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received fields:\n\n '+util.inspect(fields)); - res.write('\n\n'); - res.end('received files:\n\n '+util.inspect(files)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); - -console.log('listening on http://localhost:'+TEST_PORT+'/'); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/index.js deleted file mode 100644 index be41032..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/formidable'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/.incoming_form.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/lib/.incoming_form.js.un~ deleted file mode 100644 index 2e32201..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/lib/.incoming_form.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js deleted file mode 100644 index 6dc8720..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js +++ /dev/null @@ -1,61 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var util = require('./util'), - WriteStream = require('fs').WriteStream, - EventEmitter = require('events').EventEmitter; - -function File(properties) { - EventEmitter.call(this); - - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.lastModifiedDate = null; - - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; - } - - this._backwardsCompatibility(); -} -module.exports = File; -util.inherits(File, EventEmitter); - -// @todo Next release: Show error messages when accessing these -File.prototype._backwardsCompatibility = function() { - var self = this; - this.__defineGetter__('length', function() { - return self.size; - }); - this.__defineGetter__('filename', function() { - return self.name; - }); - this.__defineGetter__('mime', function() { - return self.type; - }); -}; - -File.prototype.open = function() { - this._writeStream = new WriteStream(this.path); -}; - -File.prototype.write = function(buffer, cb) { - var self = this; - this._writeStream.write(buffer, function() { - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; - -File.prototype.end = function(cb) { - var self = this; - this._writeStream.end(function() { - self.emit('end'); - cb(); - }); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js deleted file mode 100644 index b1e2bfb..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js +++ /dev/null @@ -1,378 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -var fs = require('fs'); -var util = require('./util'), - path = require('path'), - File = require('./file'), - MultipartParser = require('./multipart_parser').MultipartParser, - QuerystringParser = require('./querystring_parser').QuerystringParser, - StringDecoder = require('string_decoder').StringDecoder, - EventEmitter = require('events').EventEmitter; - -function IncomingForm() { - if (!(this instanceof IncomingForm)) return new IncomingForm; - EventEmitter.call(this); - - this.error = null; - this.ended = false; - - this.maxFieldsSize = 2 * 1024 * 1024; - this.keepExtensions = false; - this.uploadDir = IncomingForm.UPLOAD_DIR; - this.encoding = 'utf-8'; - this.headers = null; - this.type = null; - - this.bytesReceived = null; - this.bytesExpected = null; - - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; -}; -util.inherits(IncomingForm, EventEmitter); -exports.IncomingForm = IncomingForm; - -IncomingForm.UPLOAD_DIR = (function() { - var dirs = [process.env.TMP, '/tmp', process.cwd()]; - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var isDirectory = false; - - try { - isDirectory = fs.statSync(dir).isDirectory(); - } catch (e) {} - - if (isDirectory) return dir; - } -})(); - -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - return true; - }; - - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - - return true; - }; - - this.writeHeaders(req.headers); - - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } - - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); - - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - files[name] = file; - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); - } - - return this; -}; - -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); -}; - -IncomingForm.prototype.write = function(buffer) { - if (!this._parser) { - this._error(new Error('unintialized parser')); - return; - } - - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); - - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } - - return bytesParsed; -}; - -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; - -IncomingForm.prototype.handlePart = function(part) { - var self = this; - - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); - - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); - - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } - - this._flushing++; - - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - }); - - this.emit('fileBegin', part.name, file); - - file.open(); - - part.on('data', function(buffer) { - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); - - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; - -IncomingForm.prototype._parseContentType = function() { - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } - - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } - - if (this.headers['content-type'].match(/multipart/i)) { - var m; - if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); - } - return; - } - - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; - -IncomingForm.prototype._error = function(err) { - if (this.error) { - return; - } - - this.error = err; - this.pause(); - this.emit('error', err); -}; - -IncomingForm.prototype._parseContentLength = function() { - if (this.headers['content-length']) { - this.bytesReceived = 0; - this.bytesExpected = parseInt(this.headers['content-length'], 10); - this.emit('progress', this.bytesReceived, this.bytesExpected); - } -}; - -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); -}; - -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; - - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; - - parser.initWithBoundary(boundary); - - parser.onPartBegin = function() { - part = new EventEmitter(); - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; - - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; - - var m; - if (headerField == 'content-disposition') { - if (m = headerValue.match(/name="([^"]+)"/i)) { - part.name = m[1]; - } - - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } - - headerField = ''; - headerValue = ''; - }; - - parser.onHeadersEnd = function() { - self.onPart(part); - }; - - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; - - parser.onPartEnd = function() { - part.emit('end'); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._fileName = function(headerValue) { - var m = headerValue.match(/filename="(.*?)"($|; )/i) - if (!m) return; - - var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -}; - -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; - - var parser = new QuerystringParser() - , self = this; - - parser.onField = function(key, val) { - self.emit('field', key, val); - }; - - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - - this._parser = parser; -}; - -IncomingForm.prototype._uploadPath = function(filename) { - var name = ''; - for (var i = 0; i < 32; i++) { - name += Math.floor(Math.random() * 16).toString(16); - } - - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/, '$1') - - name += ext; - } - - return path.join(this.uploadDir, name); -}; - -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing) { - return; - } - - this.emit('end'); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js deleted file mode 100644 index 7a6e3e1..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js +++ /dev/null @@ -1,3 +0,0 @@ -var IncomingForm = require('./incoming_form').IncomingForm; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js deleted file mode 100644 index 9ca567c..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js +++ /dev/null @@ -1,312 +0,0 @@ -var Buffer = require('buffer').Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++, - }, - - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2, - }, - - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, - - lower = function(c) { - return c | 0x20; - }; - -for (var s in S) { - exports[s] = S[s]; -} - -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; - - this.index = null; - this.flags = 0; -}; -exports.MultipartParser = MultipartParser; - -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } -}; - -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 'ascii', 0); - this.boundary.write(str, 'ascii', 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; - - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; - -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, - - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } - - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } - - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; - - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (c != LF) { - return i; - } - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - - if (c != boundary[index+2]) { - return i; - } - index++; - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } - - index++; - if (c == HYPHEN) { - break; - } - - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } - - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } - - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } - - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA - mark('partData'); - case S.PART_DATA: - prevIndex = index; - - if (index == 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } - - if (index < boundary.length) { - if (boundary[index] == c) { - if (index == 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - } else { - index = 0; - } - } else { - index = 0; - } - } - - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); - - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } - - break; - case S.END: - break; - default: - return i; - } - } - - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); - - this.index = index; - this.state = state; - this.flags = flags; - - return len; -}; - -MultipartParser.prototype.end = function() { - if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); - } -}; - -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js deleted file mode 100644 index 63f109e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js +++ /dev/null @@ -1,25 +0,0 @@ -if (global.GENTLY) require = GENTLY.hijack(require); - -// This is a buffering parser, not quite as nice as the multipart one. -// If I find time I'll rewrite this to be fully streaming as well -var querystring = require('querystring'); - -function QuerystringParser() { - this.buffer = ''; -}; -exports.QuerystringParser = QuerystringParser; - -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; -}; - -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer); - for (var field in fields) { - this.onField(field, fields[field]); - } - this.buffer = ''; - - this.onEnd(); -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js b/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js deleted file mode 100644 index e9493e9..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js +++ /dev/null @@ -1,6 +0,0 @@ -// Backwards compatibility ... -try { - module.exports = require('util'); -} catch (e) { - module.exports = require('sys'); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/package.json b/node_modules/express/node_modules/connect/node_modules/formidable/package.json deleted file mode 100644 index 4cf5f2d..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "formidable", - "version": "1.0.9", - "dependencies": {}, - "devDependencies": { - "gently": "0.8.0", - "findit": "0.1.1", - "hashish": "0.0.4", - "urun": "0.0.4", - "utest": "0.0.3" - }, - "directories": { - "lib": "./lib" - }, - "main": "./lib/index", - "scripts": { - "test": "make test" - }, - "engines": { - "node": "*" - } -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/.common.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/.common.js.un~ deleted file mode 100644 index 0042076..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/.common.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/.run.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/.run.js.un~ deleted file mode 100755 index f74cb51..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/.run.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js deleted file mode 100644 index eb432ad..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js +++ /dev/null @@ -1,19 +0,0 @@ -var mysql = require('..'); -var path = require('path'); - -var root = path.join(__dirname, '../'); -exports.dir = { - root : root, - lib : root + '/lib', - fixture : root + '/test/fixture', - tmp : root + '/test/tmp', -}; - -exports.port = 13532; - -exports.formidable = require('..'); -exports.assert = require('assert'); - -exports.require = function(lib) { - return require(exports.dir.lib + '/' + lib); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt deleted file mode 100644 index e7a4785..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/funkyfilename.txt +++ /dev/null @@ -1 +0,0 @@ -I am a text file with a funky name! diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt deleted file mode 100644 index 9b6903e..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/file/plain.txt +++ /dev/null @@ -1 +0,0 @@ -I am a plain text file diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/no-filename/.generic.http.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/no-filename/.generic.http.un~ deleted file mode 100644 index a863c08..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/no-filename/.generic.http.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md deleted file mode 100644 index 3c9dbe3..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md +++ /dev/null @@ -1,3 +0,0 @@ -* Opera does not allow submitting this file, it shows a warning to the - user that the file could not be found instead. Tested in 9.8, 11.51 on OSX. - Reported to Opera on 08.09.2011 (tracking email DSK-346009@bugs.opera.com). diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.no-filename.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.no-filename.js.un~ deleted file mode 100644 index ea9828b..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.no-filename.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.special-chars-in-filename.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.special-chars-in-filename.js.un~ deleted file mode 100644 index 4c13bdb..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/.special-chars-in-filename.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js deleted file mode 100644 index 0bae449..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports['generic.http'] = [ - {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt'}, -]; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js deleted file mode 100644 index eb76fdc..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js +++ /dev/null @@ -1,21 +0,0 @@ -var properFilename = 'funkyfilename.txt'; - -function expect(filename) { - return [ - {type: 'field', name: 'title', value: 'Weird filename'}, - {type: 'file', name: 'upload', filename: filename, fixture: properFilename}, - ]; -}; - -var webkit = " ? % * | \" < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; -var ffOrIe = " ? % * | \" < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; - -module.exports = { - 'osx-chrome-13.http' : expect(webkit), - 'osx-firefox-3.6.http' : expect(ffOrIe), - 'osx-safari-5.http' : expect(webkit), - 'xp-chrome-12.http' : expect(webkit), - 'xp-ie-7.http' : expect(ffOrIe), - 'xp-ie-8.http' : expect(ffOrIe), - 'xp-safari-5.http' : expect(webkit), -}; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js deleted file mode 100644 index a476169..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js +++ /dev/null @@ -1,72 +0,0 @@ -exports['rfc1867'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['noTrailing\r\n'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['emptyHeader'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - ': foo\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - expectError: true, - }; diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/.test-fixtures.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/.test-fixtures.js.un~ deleted file mode 100644 index a4d8a0e..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/.test-fixtures.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js deleted file mode 100644 index 66ad259..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js +++ /dev/null @@ -1,89 +0,0 @@ -var hashish = require('hashish'); -var fs = require('fs'); -var findit = require('findit'); -var path = require('path'); -var http = require('http'); -var net = require('net'); -var assert = require('assert'); - -var common = require('../common'); -var formidable = common.formidable; - -var server = http.createServer(); -server.listen(common.port, findFixtures); - -function findFixtures() { - var fixtures = []; - findit - .sync(common.dir.fixture + '/js') - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; - - var group = path.basename(jsPath, '.js'); - hashish.forEach(require(jsPath), function(fixture, name) { - fixtures.push({ - name : group + '/' + name, - fixture : fixture, - }); - }); - }); - - testNext(fixtures); -} - -function testNext(fixtures) { - var fixture = fixtures.shift(); - if (!fixture) return server.close(); - - var name = fixture.name; - var fixture = fixture.fixture; - - uploadFixture(name, function(err, parts) { - if (err) throw err; - - fixture.forEach(function(expectedPart, i) { - var parsedPart = parts[i]; - assert.equal(parsedPart.type, expectedPart.type); - assert.equal(parsedPart.name, expectedPart.name); - - if (parsedPart.type === 'file') { - var filename = parsedPart.value.name; - assert.equal(filename, expectedPart.filename); - } - }); - - testNext(fixtures); - }); -}; - -function uploadFixture(name, cb) { - server.once('request', function(req, res) { - var form = new formidable.IncomingForm(); - form.uploadDir = common.dir.tmp; - form.parse(req); - - function callback() { - var realCallback = cb; - cb = function() {}; - realCallback.apply(null, arguments); - } - - var parts = []; - form - .on('error', callback) - .on('fileBegin', function(name, value) { - parts.push({type: 'file', name: name, value: value}); - }) - .on('field', function(name, value) { - parts.push({type: 'field', name: name, value: value}); - }) - .on('end', function() { - callback(null, parts); - }); - }); - - var socket = net.createConnection(common.port); - var file = fs.createReadStream(common.dir.fixture + '/http/' + name); - - file.pipe(socket); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js deleted file mode 100644 index 2b98598..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js +++ /dev/null @@ -1,24 +0,0 @@ -var path = require('path'), - fs = require('fs'); - -try { - global.Gently = require('gently'); -} catch (e) { - throw new Error('this test suite requires node-gently'); -} - -exports.lib = path.join(__dirname, '../../lib'); - -global.GENTLY = new Gently(); - -global.assert = require('assert'); -global.TEST_PORT = 13532; -global.TEST_FIXTURES = path.join(__dirname, '../fixture'); -global.TEST_TMP = path.join(__dirname, '../tmp'); - -// Stupid new feature in node that complains about gently attaching too many -// listeners to process 'exit'. This is a workaround until I can think of a -// better way to deal with this. -if (process.setMaxListeners) { - process.setMaxListeners(10000); -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js deleted file mode 100644 index 75232aa..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js +++ /dev/null @@ -1,80 +0,0 @@ -var common = require('../common'); -var CHUNK_LENGTH = 10, - multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - fixtures = require(TEST_FIXTURES + '/multipart'), - Buffer = require('buffer').Buffer; - -Object.keys(fixtures).forEach(function(name) { - var fixture = fixtures[name], - buffer = new Buffer(Buffer.byteLength(fixture.raw, 'binary')), - offset = 0, - chunk, - nparsed, - - parts = [], - part = null, - headerField, - headerValue, - endCalled = ''; - - parser.initWithBoundary(fixture.boundary); - parser.onPartBegin = function() { - part = {headers: {}, data: ''}; - parts.push(part); - headerField = ''; - headerValue = ''; - }; - - parser.onHeaderField = function(b, start, end) { - headerField += b.toString('ascii', start, end); - }; - - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString('ascii', start, end); - } - - parser.onHeaderEnd = function() { - part.headers[headerField] = headerValue; - headerField = ''; - headerValue = ''; - }; - - parser.onPartData = function(b, start, end) { - var str = b.toString('ascii', start, end); - part.data += b.slice(start, end); - } - - parser.onEnd = function() { - endCalled = true; - } - - buffer.write(fixture.raw, 'binary', 0); - - while (offset < buffer.length) { - if (offset + CHUNK_LENGTH < buffer.length) { - chunk = buffer.slice(offset, offset+CHUNK_LENGTH); - } else { - chunk = buffer.slice(offset, buffer.length); - } - offset = offset + CHUNK_LENGTH; - - nparsed = parser.write(chunk); - if (nparsed != chunk.length) { - if (fixture.expectError) { - return; - } - puts('-- ERROR --'); - p(chunk.toString('ascii')); - throw new Error(chunk.length+' bytes written, but only '+nparsed+' bytes parsed!'); - } - } - - if (fixture.expectError) { - throw new Error('expected parse error did not happen'); - } - - assert.ok(endCalled); - assert.deepEqual(parts, fixture.parts); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js deleted file mode 100644 index 52ceedb..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js +++ /dev/null @@ -1,104 +0,0 @@ -var common = require('../common'); -var WriteStreamStub = GENTLY.stub('fs', 'WriteStream'); - -var File = require(common.lib + '/file'), - EventEmitter = require('events').EventEmitter, - file, - gently; - -function test(test) { - gently = new Gently(); - file = new File(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.ok(file instanceof EventEmitter); - assert.strictEqual(file.size, 0); - assert.strictEqual(file.path, null); - assert.strictEqual(file.name, null); - assert.strictEqual(file.type, null); - assert.strictEqual(file.lastModifiedDate, null); - - assert.strictEqual(file._writeStream, null); - - (function testSetProperties() { - var file2 = new File({foo: 'bar'}); - assert.equal(file2.foo, 'bar'); - })(); -}); - -test(function open() { - var WRITE_STREAM; - file.path = '/foo'; - - gently.expect(WriteStreamStub, 'new', function (path) { - WRITE_STREAM = this; - assert.strictEqual(path, file.path); - }); - - file.open(); - assert.strictEqual(file._writeStream, WRITE_STREAM); -}); - -test(function write() { - var BUFFER = {length: 10}, - CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'write', function (buffer, cb) { - assert.strictEqual(buffer, BUFFER); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.ok(file.lastModifiedDate instanceof Date); - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 10); - }); - - cb(); - - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); - - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 20); - }); - - cb(); - }); - - file.write(BUFFER, CB); -}); - -test(function end() { - var CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; - - file._writeStream = {}; - - gently.expect(file._writeStream, 'end', function (cb) { - gently.expect(file, 'emit', function (event) { - assert.equal(event, 'end'); - }); - - CB_STUB = gently.expect(function endCb() { - }); - - cb(); - }); - - file.end(CB); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js deleted file mode 100644 index b64df8b..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js +++ /dev/null @@ -1,726 +0,0 @@ -var common = require('../common'); -var MultipartParserStub = GENTLY.stub('./multipart_parser', 'MultipartParser'), - QuerystringParserStub = GENTLY.stub('./querystring_parser', 'QuerystringParser'), - EventEmitterStub = GENTLY.stub('events', 'EventEmitter'), - FileStub = GENTLY.stub('./file'); - -var formidable = require(common.lib + '/index'), - IncomingForm = formidable.IncomingForm, - events = require('events'), - fs = require('fs'), - path = require('path'), - Buffer = require('buffer').Buffer, - fixtures = require(TEST_FIXTURES + '/multipart'), - form, - gently; - -function test(test) { - gently = new Gently(); - gently.expect(EventEmitterStub, 'call'); - form = new IncomingForm(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.strictEqual(form.error, null); - assert.strictEqual(form.ended, false); - assert.strictEqual(form.type, null); - assert.strictEqual(form.headers, null); - assert.strictEqual(form.keepExtensions, false); - assert.strictEqual(form.uploadDir, '/tmp'); - assert.strictEqual(form.encoding, 'utf-8'); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - assert.strictEqual(form.maxFieldsSize, 2 * 1024 * 1024); - assert.strictEqual(form._parser, null); - assert.strictEqual(form._flushing, 0); - assert.strictEqual(form._fieldsSize, 0); - assert.ok(form instanceof EventEmitterStub); - assert.equal(form.constructor.name, 'IncomingForm'); - - (function testSimpleConstructor() { - gently.expect(EventEmitterStub, 'call'); - var form = IncomingForm(); - assert.ok(form instanceof IncomingForm); - })(); - - (function testSimpleConstructorShortcut() { - gently.expect(EventEmitterStub, 'call'); - var form = formidable(); - assert.ok(form instanceof IncomingForm); - })(); -}); - -test(function parse() { - var REQ = {headers: {}} - , emit = {}; - - gently.expect(form, 'writeHeaders', function(headers) { - assert.strictEqual(headers, REQ.headers); - }); - - var events = ['error', 'aborted', 'data', 'end']; - gently.expect(REQ, 'on', events.length, function(event, fn) { - assert.equal(event, events.shift()); - emit[event] = fn; - return this; - }); - - form.parse(REQ); - - (function testPause() { - gently.expect(REQ, 'pause'); - assert.strictEqual(form.pause(), true); - })(); - - (function testPauseCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testPauseHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testResume() { - gently.expect(REQ, 'resume'); - assert.strictEqual(form.resume(), true); - })(); - - (function testResumeCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testResumeHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testEmitError() { - var ERR = new Error('something bad happened'); - gently.expect(form, '_error',function(err) { - assert.strictEqual(err, ERR); - }); - emit.error(ERR); - })(); - - (function testEmitAborted() { - gently.expect(form, 'emit',function(event) { - assert.equal(event, 'aborted'); - }); - - emit.aborted(); - })(); - - - (function testEmitData() { - var BUFFER = [1, 2, 3]; - gently.expect(form, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - }); - emit.data(BUFFER); - })(); - - (function testEmitEnd() { - form._parser = {}; - - (function testWithError() { - var ERR = new Error('haha'); - gently.expect(form._parser, 'end', function() { - return ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - emit.end(); - })(); - - (function testWithoutError() { - gently.expect(form._parser, 'end'); - emit.end(); - })(); - - (function testAfterError() { - form.error = true; - emit.end(); - })(); - })(); - - (function testWithCallback() { - gently.expect(EventEmitterStub, 'call'); - var form = new IncomingForm(), - REQ = {headers: {}}, - parseCalled = 0; - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - gently.expect(form, 'on', 4, function(event, fn) { - if (event == 'field') { - fn('field1', 'foo'); - fn('field1', 'bar'); - fn('field2', 'nice'); - } - - if (event == 'file') { - fn('file1', '1'); - fn('file1', '2'); - fn('file2', '3'); - } - - if (event == 'end') { - fn(); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbOk(err, fields, files) { - assert.deepEqual(fields, {field1: 'bar', field2: 'nice'}); - assert.deepEqual(files, {file1: '2', file2: '3'}); - })); - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - var ERR = new Error('test'); - gently.expect(form, 'on', 3, function(event, fn) { - if (event == 'field') { - fn('foo', 'bar'); - } - - if (event == 'error') { - fn(ERR); - gently.expect(form, 'on'); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbErr(err, fields, files) { - assert.strictEqual(err, ERR); - assert.deepEqual(fields, {foo: 'bar'}); - })); - })(); -}); - -test(function pause() { - assert.strictEqual(form.pause(), false); -}); - -test(function resume() { - assert.strictEqual(form.resume(), false); -}); - - -test(function writeHeaders() { - var HEADERS = {}; - gently.expect(form, '_parseContentLength'); - gently.expect(form, '_parseContentType'); - - form.writeHeaders(HEADERS); - assert.strictEqual(form.headers, HEADERS); -}); - -test(function write() { - var parser = {}, - BUFFER = [1, 2, 3]; - - form._parser = parser; - form.bytesExpected = 523423; - - (function testBasic() { - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, BUFFER.length); - assert.equal(bytesExpected, form.bytesExpected); - }); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length; - }); - - assert.equal(form.write(BUFFER), BUFFER.length); - assert.equal(form.bytesReceived, BUFFER.length); - })(); - - (function testParserError() { - gently.expect(form, 'emit'); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length - 1; - }); - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/parser error/i)); - }); - - assert.equal(form.write(BUFFER), BUFFER.length - 1); - assert.equal(form.bytesReceived, BUFFER.length + BUFFER.length); - })(); - - (function testUninitialized() { - delete form._parser; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unintialized parser/i)); - }); - form.write(BUFFER); - })(); -}); - -test(function parseContentType() { - var HEADERS = {}; - - form.headers = {'content-type': 'application/x-www-form-urlencoded'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - // accept anything that has 'urlencoded' in it - form.headers = {'content-type': 'broken-client/urlencoded-stupid'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - var BOUNDARY = '---------------------------57814261102167618332366269'; - form.headers = {'content-type': 'multipart/form-data; boundary='+BOUNDARY}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - - (function testQuotedBoundary() { - form.headers = {'content-type': 'multipart/form-data; boundary="' + BOUNDARY + '"'}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - })(); - - (function testNoBoundary() { - form.headers = {'content-type': 'multipart/form-data'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no multipart boundary/i)); - }); - form._parseContentType(); - })(); - - (function testNoContentType() { - form.headers = {}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no content-type/i)); - }); - form._parseContentType(); - })(); - - (function testUnknownContentType() { - form.headers = {'content-type': 'invalid'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unknown content-type/i)); - }); - form._parseContentType(); - })(); -}); - -test(function parseContentLength() { - var HEADERS = {}; - - form.headers = {}; - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - - form.headers['content-length'] = '8'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, 0); - assert.strictEqual(form.bytesExpected, 8); - - // JS can be evil, lets make sure we are not - form.headers['content-length'] = '08'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesExpected, 8); -}); - -test(function _initMultipart() { - var BOUNDARY = '123', - PARSER; - - gently.expect(MultipartParserStub, 'new', function() { - PARSER = this; - }); - - gently.expect(MultipartParserStub.prototype, 'initWithBoundary', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - - form._initMultipart(BOUNDARY); - assert.equal(form.type, 'multipart'); - assert.strictEqual(form._parser, PARSER); - - (function testRegularField() { - var PART; - gently.expect(EventEmitterStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.strictEqual(part, PART); - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field1"' - , 'foo': 'bar' - } - ); - assert.equal(part.name, 'field1'); - - var strings = ['hello', ' world']; - gently.expect(part, 'emit', 2, function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), strings.shift()); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 10); - PARSER.onHeaderField(new Buffer('content-disposition'), 10, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 0, 14); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 14, 24); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('foo'), 0, 3); - PARSER.onHeaderValue(new Buffer('bar'), 0, 3); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('hello world'), 0, 5); - PARSER.onPartData(new Buffer('hello world'), 5, 11); - PARSER.onPartEnd(); - })(); - - (function testFileField() { - var PART; - gently.expect(EventEmitterStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"' - , 'content-type': 'text/plain' - } - ); - assert.equal(part.name, 'field2'); - assert.equal(part.filename, 'Sun"et.jpg'); - assert.equal(part.mime, 'text/plain'); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), '... contents of file1.txt ...'); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"'), 0, 85); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('Content-Type'), 0, 12); - PARSER.onHeaderValue(new Buffer('text/plain'), 0, 10); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('... contents of file1.txt ...'), 0, 29); - PARSER.onPartEnd(); - })(); - - (function testEnd() { - gently.expect(form, '_maybeEnd'); - PARSER.onEnd(); - assert.ok(form.ended); - })(); -}); - -test(function _fileName() { - // TODO - return; -}); - -test(function _initUrlencoded() { - var PARSER; - - gently.expect(QuerystringParserStub, 'new', function() { - PARSER = this; - }); - - form._initUrlencoded(); - assert.equal(form.type, 'urlencoded'); - assert.strictEqual(form._parser, PARSER); - - (function testOnField() { - var KEY = 'KEY', VAL = 'VAL'; - gently.expect(form, 'emit', function(field, key, val) { - assert.equal(field, 'field'); - assert.equal(key, KEY); - assert.equal(val, VAL); - }); - - PARSER.onField(KEY, VAL); - })(); - - (function testOnEnd() { - gently.expect(form, '_maybeEnd'); - - PARSER.onEnd(); - assert.equal(form.ended, true); - })(); -}); - -test(function _error() { - var ERR = new Error('bla'); - - gently.expect(form, 'pause'); - gently.expect(form, 'emit', function(event, err) { - assert.equal(event, 'error'); - assert.strictEqual(err, ERR); - }); - - form._error(ERR); - assert.strictEqual(form.error, ERR); - - // make sure _error only does its thing once - form._error(ERR); -}); - -test(function onPart() { - var PART = {}; - gently.expect(form, 'handlePart', function(part) { - assert.strictEqual(part, PART); - }); - - form.onPart(PART); -}); - -test(function handlePart() { - (function testUtf8Field() { - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field'); - assert.equal(value, 'hello world: €'); - }); - - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testBinaryField() { - var PART = new events.EventEmitter(); - PART.name = 'my_field2'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field2'); - assert.equal(value, 'hello world: '+new Buffer([0xE2, 0x82, 0xAC]).toString('binary')); - }); - - form.encoding = 'binary'; - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testFieldSize() { - form.maxFieldsSize = 8; - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, '_error', function(err) { - assert.equal(err.message, 'maxFieldsSize exceeded, received 9 bytes of field data'); - }); - - form.handlePart(PART); - form._fieldsSize = 1; - PART.emit('data', new Buffer(7)); - PART.emit('data', new Buffer(1)); - })(); - - (function testFilePart() { - var PART = new events.EventEmitter(), - FILE = new events.EventEmitter(), - PATH = '/foo/bar'; - - PART.name = 'my_file'; - PART.filename = 'sweet.txt'; - PART.mime = 'sweet.txt'; - - gently.expect(form, '_uploadPath', function(filename) { - assert.equal(filename, PART.filename); - return PATH; - }); - - gently.expect(FileStub, 'new', function(properties) { - assert.equal(properties.path, PATH); - assert.equal(properties.name, PART.filename); - assert.equal(properties.type, PART.mime); - FILE = this; - - gently.expect(form, 'emit', function (event, field, file) { - assert.equal(event, 'fileBegin'); - assert.strictEqual(field, PART.name); - assert.strictEqual(file, FILE); - }); - - gently.expect(FILE, 'open'); - }); - - form.handlePart(PART); - assert.equal(form._flushing, 1); - - var BUFFER; - gently.expect(form, 'pause'); - gently.expect(FILE, 'write', function(buffer, cb) { - assert.strictEqual(buffer, BUFFER); - gently.expect(form, 'resume'); - // @todo handle cb(new Err) - cb(); - }); - - PART.emit('data', BUFFER = new Buffer('test')); - - gently.expect(FILE, 'end', function(cb) { - gently.expect(form, 'emit', function(event, field, file) { - assert.equal(event, 'file'); - assert.strictEqual(file, FILE); - }); - - gently.expect(form, '_maybeEnd'); - - cb(); - assert.equal(form._flushing, 0); - }); - - PART.emit('end'); - })(); -}); - -test(function _uploadPath() { - (function testUniqueId() { - var UUID_A, UUID_B; - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - assert.equal(uploadDir, form.uploadDir); - UUID_A = uuid; - }); - form._uploadPath(); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - UUID_B = uuid; - }); - form._uploadPath(); - - assert.notEqual(UUID_A, UUID_B); - })(); - - (function testFileExtension() { - form.keepExtensions = true; - var FILENAME = 'foo.jpg', - EXT = '.bar'; - - gently.expect(GENTLY.hijacked.path, 'extname', function(filename) { - assert.equal(filename, FILENAME); - gently.restore(path, 'extname'); - - return EXT; - }); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, name) { - assert.equal(path.extname(name), EXT); - }); - form._uploadPath(FILENAME); - })(); -}); - -test(function _maybeEnd() { - gently.expect(form, 'emit', 0); - form._maybeEnd(); - - form.ended = true; - form._flushing = 1; - form._maybeEnd(); - - gently.expect(form, 'emit', function(event) { - assert.equal(event, 'end'); - }); - - form.ended = true; - form._flushing = 0; - form._maybeEnd(); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js deleted file mode 100644 index d8dc968..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js +++ /dev/null @@ -1,50 +0,0 @@ -var common = require('../common'); -var multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - events = require('events'), - Buffer = require('buffer').Buffer, - parser; - -function test(test) { - parser = new MultipartParser(); - test(); -} - -test(function constructor() { - assert.equal(parser.boundary, null); - assert.equal(parser.state, 0); - assert.equal(parser.flags, 0); - assert.equal(parser.boundaryChars, null); - assert.equal(parser.index, null); - assert.equal(parser.lookbehind, null); - assert.equal(parser.constructor.name, 'MultipartParser'); -}); - -test(function initWithBoundary() { - var boundary = 'abc'; - parser.initWithBoundary(boundary); - assert.deepEqual(Array.prototype.slice.call(parser.boundary), [13, 10, 45, 45, 97, 98, 99]); - assert.equal(parser.state, multipartParser.START); - - assert.deepEqual(parser.boundaryChars, {10: true, 13: true, 45: true, 97: true, 98: true, 99: true}); -}); - -test(function parserError() { - var boundary = 'abc', - buffer = new Buffer(5); - - parser.initWithBoundary(boundary); - buffer.write('--ad', 'ascii', 0); - assert.equal(parser.write(buffer), 3); -}); - -test(function end() { - (function testError() { - assert.equal(parser.end().message, 'MultipartParser.end(): stream ended unexpectedly: ' + parser.explain()); - })(); - - (function testRegular() { - parser.state = multipartParser.END; - assert.strictEqual(parser.end(), undefined); - })(); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js deleted file mode 100644 index 54d3e2d..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js +++ /dev/null @@ -1,45 +0,0 @@ -var common = require('../common'); -var QuerystringParser = require(common.lib + '/querystring_parser').QuerystringParser, - Buffer = require('buffer').Buffer, - gently, - parser; - -function test(test) { - gently = new Gently(); - parser = new QuerystringParser(); - test(); - gently.verify(test.name); -} - -test(function constructor() { - assert.equal(parser.buffer, ''); - assert.equal(parser.constructor.name, 'QuerystringParser'); -}); - -test(function write() { - var a = new Buffer('a=1'); - assert.equal(parser.write(a), a.length); - - var b = new Buffer('&b=2'); - parser.write(b); - assert.equal(parser.buffer, a + b); -}); - -test(function end() { - var FIELDS = {a: ['b', {c: 'd'}], e: 'f'}; - - gently.expect(GENTLY.hijacked.querystring, 'parse', function(str) { - assert.equal(str, parser.buffer); - return FIELDS; - }); - - gently.expect(parser, 'onField', Object.keys(FIELDS).length, function(key, val) { - assert.deepEqual(FIELDS[key], val); - }); - - gently.expect(parser, 'onEnd'); - - parser.buffer = 'my buffer'; - parser.end(); - assert.equal(parser.buffer, ''); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js deleted file mode 100644 index fcfdb94..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js +++ /dev/null @@ -1,72 +0,0 @@ -var common = require('../common'); -var BOUNDARY = '---------------------------10102754414578508781458777923', - FIXTURE = TEST_FIXTURES+'/multi_video.upload', - fs = require('fs'), - util = require(common.lib + '/util'), - http = require('http'), - formidable = require(common.lib + '/index'), - server = http.createServer(); - -server.on('request', function(req, res) { - var form = new formidable.IncomingForm(), - uploads = {}; - - form.uploadDir = TEST_TMP; - form.parse(req); - - form - .on('fileBegin', function(field, file) { - assert.equal(field, 'upload'); - - var tracker = {file: file, progress: [], ended: false}; - uploads[file.filename] = tracker; - file - .on('progress', function(bytesReceived) { - tracker.progress.push(bytesReceived); - assert.equal(bytesReceived, file.length); - }) - .on('end', function() { - tracker.ended = true; - }); - }) - .on('field', function(field, value) { - assert.equal(field, 'title'); - assert.equal(value, ''); - }) - .on('file', function(field, file) { - assert.equal(field, 'upload'); - assert.strictEqual(uploads[file.filename].file, file); - }) - .on('end', function() { - assert.ok(uploads['shortest_video.flv']); - assert.ok(uploads['shortest_video.flv'].ended); - assert.ok(uploads['shortest_video.flv'].progress.length > 3); - assert.equal(uploads['shortest_video.flv'].progress.slice(-1), uploads['shortest_video.flv'].file.length); - assert.ok(uploads['shortest_video.mp4']); - assert.ok(uploads['shortest_video.mp4'].ended); - assert.ok(uploads['shortest_video.mp4'].progress.length > 3); - - server.close(); - res.writeHead(200); - res.end('good'); - }); -}); - -server.listen(TEST_PORT, function() { - var client = http.createClient(TEST_PORT), - stat = fs.statSync(FIXTURE), - headers = { - 'content-type': 'multipart/form-data; boundary='+BOUNDARY, - 'content-length': stat.size, - } - request = client.request('POST', '/', headers), - fixture = new fs.ReadStream(FIXTURE); - - fixture - .on('data', function(b) { - request.write(b); - }) - .on('end', function() { - request.end(); - }); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js deleted file mode 100755 index 50b2361..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('urun')(__dirname) diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/tmp/.empty b/node_modules/express/node_modules/connect/node_modules/formidable/test/tmp/.empty deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/.test-incoming-form.js.un~ b/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/.test-incoming-form.js.un~ deleted file mode 100644 index 4002e6d..0000000 Binary files a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/.test-incoming-form.js.un~ and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js b/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js deleted file mode 100644 index bcf61d7..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js +++ /dev/null @@ -1,63 +0,0 @@ -var common = require('../common'); -var test = require('utest'); -var assert = common.assert; -var IncomingForm = common.require('incoming_form').IncomingForm; -var path = require('path'); - -var from; -test('IncomingForm', { - before: function() { - form = new IncomingForm(); - }, - - '#_fileName with regular characters': function() { - var filename = 'foo.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'foo.txt'); - }, - - '#_fileName with unescaped quote': function() { - var filename = 'my".txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with escaped quote': function() { - var filename = 'my%22.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, - - '#_fileName with bad quote and additional sub-header': function() { - var filename = 'my".txt'; - var header = makeHeader(filename) + '; foo="bar"'; - assert.equal(form._fileName(header), filename); - }, - - '#_fileName with semicolon': function() { - var filename = 'my;.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my;.txt'); - }, - - '#_fileName with utf8 character': function() { - var filename = 'my☃.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my☃.txt'); - }, - - '#_uploadPath strips harmful characters from extension when keepExtensions': function() { - form.keepExtensions = true; - - var ext = path.extname(form._uploadPath('fine.jpg?foo=bar')); - assert.equal(ext, '.jpg'); - - var ext = path.extname(form._uploadPath('fine?foo=bar')); - assert.equal(ext, ''); - - var ext = path.extname(form._uploadPath('super.cr2+dsad')); - assert.equal(ext, '.cr2'); - - var ext = path.extname(form._uploadPath('super.bar')); - assert.equal(ext, '.bar'); - }, -}); - -function makeHeader(filename) { - return 'Content-Disposition: form-data; name="upload"; filename="' + filename + '"'; -} diff --git a/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js b/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js deleted file mode 100644 index 9f1cef8..0000000 --- a/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js +++ /dev/null @@ -1,47 +0,0 @@ -var http = require('http'); -var fs = require('fs'); -var connections = 0; - -var server = http.createServer(function(req, res) { - var socket = req.socket; - console.log('Request: %s %s -> %s', req.method, req.url, socket.filename); - - req.on('end', function() { - if (req.url !== '/') { - res.end(JSON.stringify({ - method: req.method, - url: req.url, - filename: socket.filename, - })); - return; - } - - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }); -}); - -server.on('connection', function(socket) { - connections++; - - socket.id = connections; - socket.filename = 'connection-' + socket.id + '.http'; - socket.file = fs.createWriteStream(socket.filename); - socket.pipe(socket.file); - - console.log('--> %s', socket.filename); - socket.on('close', function() { - console.log('<-- %s', socket.filename); - }); -}); - -var port = process.env.PORT || 8080; -server.listen(port, function() { - console.log('Recording connections on port %s', port); -}); diff --git a/node_modules/express/node_modules/connect/package.json b/node_modules/express/node_modules/connect/package.json deleted file mode 100644 index f9c43d5..0000000 --- a/node_modules/express/node_modules/connect/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "connect", - "version": "1.8.5", - "description": "High performance middleware framework", - "keywords": ["framework", "web", "middleware", "connect", "rack"], - "repository": "git://github.com/senchalabs/connect.git", - "author": "TJ Holowaychuk (http://tjholowaychuk.com)", - "repository": "git://github.com/senchalabs/connect", - "dependencies": { - "qs": ">= 0.4.0", - "mime": ">= 0.0.1", - "formidable": "1.0.x" - }, - "devDependencies": { - "expresso": "0.9.2", - "koala": "0.1.2", - "less": "1.1.1", - "sass": "0.5.0", - "markdown": "0.2.1", - "ejs": "0.4.3", - "should": "0.3.2" - }, - "main": "index", - "engines": { "node": ">= 0.4.1 < 0.7.0" } -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/test.js b/node_modules/express/node_modules/connect/test.js deleted file mode 100644 index a1e1d55..0000000 --- a/node_modules/express/node_modules/connect/test.js +++ /dev/null @@ -1,52 +0,0 @@ - -var connect = require('./') - , http = require('http') - , RedisStore = require('connect-redis')(connect); - -var app = connect(); -app.use(connect.cookieParser('fucj')); -app.use(connect.session({store:new RedisStore})); -app.use(function(req, res, next){ - req.session.views = (req.session.views || 0) + 1; - res.writeHead(200, {"Content-Type": "text/plain"}); - res.end("You've viewed this page "+req.session.views+" times."); -}) - -http.createServer(app).listen(3000); - - -// var set = RedisStore.prototype.set; -// -// function slow(sid){ -// console.log('%s saving', sid); -// var args = arguments; -// setTimeout(function(self){ -// console.log('%s saved', sid); -// set.apply(self, args); -// }, 2000, this); -// }; -// -// http.createServer(connect() -// .use(connect.logger('dev')) -// .use(connect.cookieParser('keyboard cat')) -// .use(connect.session({ store: new RedisStore })) -// .use(function(req, res, next){ -// var sess = req.session; -// switch (req.url) { -// case '/foo.js': -// console.log('%s foo.js sid', sess.id); -// RedisStore.prototype.set = set; -// res.end('data'); -// break; -// default: -// console.log('%s html sid', sess.id); -// RedisStore.prototype.set = slow; -// res.setHeader('Content-Type', 'html'); -// res.write(''); -// setTimeout(function(){ -// res.end(''); -// }, 1000); -// } -// })).listen(3000); -// -// console.log('port 3000'); \ No newline at end of file diff --git a/node_modules/express/node_modules/mime/LICENSE b/node_modules/express/node_modules/mime/LICENSE deleted file mode 100644 index 451fc45..0000000 --- a/node_modules/express/node_modules/mime/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Benjamin Thomas, Robert Kieffer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express/node_modules/mime/README.md b/node_modules/express/node_modules/mime/README.md deleted file mode 100644 index d8b66a8..0000000 --- a/node_modules/express/node_modules/mime/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# mime - -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - - var mime = require('mime'); - - mime.lookup('/path/to/file.txt'); // => 'text/plain' - mime.lookup('file.txt'); // => 'text/plain' - mime.lookup('.TXT'); // => 'text/plain' - mime.lookup('htm'); // => 'text/html' - -### mime.extension(type) -Get the default extension for `type` - - mime.extension('text/html'); // => 'html' - mime.extension('application/octet-stream'); // => 'bin' - -### mime.charsets.lookup() - -Map mime-type to charset - - mime.charsets.lookup('text/plain'); // => 'UTF-8' - -(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) - -## API - Defining Custom Types - -The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/bentomas/node-mime/wiki/Requesting-New-Types). - -### mime.define() - -Add custom mime/extension mappings - - mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... - }); - - mime.lookup('x-sft'); // => 'text/x-some-format' - -The first entry in the extensions array is returned by `mime.extension()`. E.g. - - mime.extension('text/x-some-format'); // => 'x-sf' - -### mime.load(filepath) - -Load mappings from an Apache ".types" format file - - mime.load('./my_project.types'); - -The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/mime/mime.js b/node_modules/express/node_modules/mime/mime.js deleted file mode 100644 index 64dbeec..0000000 --- a/node_modules/express/node_modules/mime/mime.js +++ /dev/null @@ -1,93 +0,0 @@ -var path = require('path'), - fs = require('fs'); - -var mime = module.exports = { - // Map of extension to mime type - types: Object.create(null), - - // Map of mime type to extension - extensions :Object.create(null), - - /** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ - define: function(map) { - for (var type in map) { - var exts = map[type]; - - for (var i = 0; i < exts.length; i++) { - mime.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!mime.extensions[type]) { - mime.extensions[type] = exts[0]; - } - } - }, - - /** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ - load: function(file) { - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line, lineno) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - mime.define(map); - }, - - /** - * Lookup a mime type based on extension - */ - lookup: function(path, fallback) { - var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); - - return mime.types[ext] || fallback || mime.default_type - }, - - /** - * Return file extension associated with a mime type - */ - extension: function(mimeType) { - return mime.extensions[mimeType]; - }, - - /** - * Lookup a charset based on mime type. - */ - charsets: { - lookup: function (mimeType, fallback) { - // Assume text types are utf8. Modify mime logic as needed. - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } - } -}; - -// Load our local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Overlay enhancements submitted by the node.js community -mime.load(path.join(__dirname, 'types/node.types')); - -// Set the default type -mime.default_type = mime.types.bin; diff --git a/node_modules/express/node_modules/mime/package.json b/node_modules/express/node_modules/mime/package.json deleted file mode 100644 index 31d4e20..0000000 --- a/node_modules/express/node_modules/mime/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "author": { - "name": "Robert Kieffer", - "url": "http://github.com/broofa", - "email": "robert@broofa.com" - }, - "contributors": [ - { - "name": "Benjamin Thomas", - "url": "http://github.com/bentomas", - "email": "benjamin@benjaminthomas.org" - } - ], - "dependencies": {}, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": {}, - "keywords": ["util", "mime"], - "main": "mime.js", - "name": "mime", - "repository": {"url": "http://github.com/bentomas/node-mime", "type": "git"}, - "version": "1.2.5" -} diff --git a/node_modules/express/node_modules/mime/test.js b/node_modules/express/node_modules/mime/test.js deleted file mode 100644 index 8a8a5b1..0000000 --- a/node_modules/express/node_modules/mime/test.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('./mime'); -var assert = require('assert'); - -function eq(a, b) { - console.log('Test: ' + a + ' === ' + b); - assert.strictEqual.apply(null, arguments); -} - -console.log(Object.keys(mime.extensions).length + ' types'); -console.log(Object.keys(mime.types).length + ' extensions\n'); - -// -// Test mime lookups -// - -eq('text/plain', mime.lookup('text.txt')); -eq('text/plain', mime.lookup('.text.txt')); -eq('text/plain', mime.lookup('.txt')); -eq('text/plain', mime.lookup('txt')); -eq('application/octet-stream', mime.lookup('text.nope')); -eq('fallback', mime.lookup('text.fallback', 'fallback')); -eq('application/octet-stream', mime.lookup('constructor')); -eq('text/plain', mime.lookup('TEXT.TXT')); - -// -// Test extensions -// - -eq('txt', mime.extension(mime.types.text)); -eq('html', mime.extension(mime.types.htm)); -eq('bin', mime.extension('application/octet-stream')); -eq(undefined, mime.extension('constructor')); - -// -// Test node types -// - -eq('application/octet-stream', mime.lookup('file.buffer')); -eq('audio/mp4', mime.lookup('file.m4a')); - -// -// Test charsets -// - -eq('UTF-8', mime.charsets.lookup('text/plain')); -eq(undefined, mime.charsets.lookup(mime.types.js)); -eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -console.log('\nOK'); diff --git a/node_modules/express/node_modules/mime/types/mime.types b/node_modules/express/node_modules/mime/types/mime.types deleted file mode 100644 index b3cae2e..0000000 --- a/node_modules/express/node_modules/mime/types/mime.types +++ /dev/null @@ -1,1510 +0,0 @@ -# This file maps Internet media types to unique file extension(s). -# Although created for httpd, this file is used by many software systems -# and has been placed in the public domain for unlimited redisribution. -# -# The table below contains both registered and (common) unregistered types. -# A type that has no unique extension can be ignored -- they are listed -# here to guide configurations toward known types and to make it easier to -# identify "new" types. File extensions are also commonly used to indicate -# content languages and encodings, so choose them carefully. -# -# Internet media types should be registered as described in RFC 4288. -# The registry is at . -# -# MIME type (lowercased) Extensions -# ============================================ ========== -# application/1d-interleaved-parityfec -# application/3gpp-ims+xml -# application/activemessage -application/andrew-inset ez -# application/applefile -application/applixware aw -application/atom+xml atom -application/atomcat+xml atomcat -# application/atomicmail -application/atomsvc+xml atomsvc -# application/auth-policy+xml -# application/batch-smtp -# application/beep+xml -# application/calendar+xml -# application/cals-1840 -# application/ccmp+xml -application/ccxml+xml ccxml -application/cdmi-capability cdmia -application/cdmi-container cdmic -application/cdmi-domain cdmid -application/cdmi-object cdmio -application/cdmi-queue cdmiq -# application/cea-2018+xml -# application/cellml+xml -# application/cfw -# application/cnrp+xml -# application/commonground -# application/conference-info+xml -# application/cpl+xml -# application/csta+xml -# application/cstadata+xml -application/cu-seeme cu -# application/cybercash -application/davmount+xml davmount -# application/dca-rft -# application/dec-dx -# application/dialog-info+xml -# application/dicom -# application/dns -# application/dskpp+xml -application/dssc+der dssc -application/dssc+xml xdssc -# application/dvcs -application/ecmascript ecma -# application/edi-consent -# application/edi-x12 -# application/edifact -application/emma+xml emma -# application/epp+xml -application/epub+zip epub -# application/eshop -# application/example -application/exi exi -# application/fastinfoset -# application/fastsoap -# application/fits -application/font-tdpfr pfr -# application/framework-attributes+xml -# application/h224 -# application/held+xml -# application/http -application/hyperstudio stk -# application/ibe-key-request+xml -# application/ibe-pkg-reply+xml -# application/ibe-pp-data -# application/iges -# application/im-iscomposing+xml -# application/index -# application/index.cmd -# application/index.obj -# application/index.response -# application/index.vnd -application/inkml+xml ink inkml -# application/iotp -application/ipfix ipfix -# application/ipp -# application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/javascript js -application/json json -# application/kpml-request+xml -# application/kpml-response+xml -application/lost+xml lostxml -application/mac-binhex40 hqx -application/mac-compactpro cpt -# application/macwriteii -application/mads+xml mads -application/marc mrc -application/marcxml+xml mrcx -application/mathematica ma nb mb -# application/mathml-content+xml -# application/mathml-presentation+xml -application/mathml+xml mathml -# application/mbms-associated-procedure-description+xml -# application/mbms-deregister+xml -# application/mbms-envelope+xml -# application/mbms-msk+xml -# application/mbms-msk-response+xml -# application/mbms-protection-description+xml -# application/mbms-reception-report+xml -# application/mbms-register+xml -# application/mbms-register-response+xml -# application/mbms-user-service-description+xml -application/mbox mbox -# application/media_control+xml -application/mediaservercontrol+xml mscml -application/metalink4+xml meta4 -application/mets+xml mets -# application/mikey -application/mods+xml mods -# application/moss-keys -# application/moss-signature -# application/mosskey-data -# application/mosskey-request -application/mp21 m21 mp21 -application/mp4 mp4s -# application/mpeg4-generic -# application/mpeg4-iod -# application/mpeg4-iod-xmt -# application/msc-ivr+xml -# application/msc-mixer+xml -application/msword doc dot -application/mxf mxf -# application/nasdata -# application/news-checkgroups -# application/news-groupinfo -# application/news-transmission -# application/nss -# application/ocsp-request -# application/ocsp-response -application/octet-stream bin dms lha lrf lzh so iso dmg dist distz pkg bpk dump elc deploy -application/oda oda -application/oebps-package+xml opf -application/ogg ogx -application/onenote onetoc onetoc2 onetmp onepkg -application/oxps oxps -# application/parityfec -application/patch-ops-error+xml xer -application/pdf pdf -application/pgp-encrypted pgp -# application/pgp-keys -application/pgp-signature asc sig -application/pics-rules prf -# application/pidf+xml -# application/pidf-diff+xml -application/pkcs10 p10 -application/pkcs7-mime p7m p7c -application/pkcs7-signature p7s -application/pkcs8 p8 -application/pkix-attr-cert ac -application/pkix-cert cer -application/pkix-crl crl -application/pkix-pkipath pkipath -application/pkixcmp pki -application/pls+xml pls -# application/poc-settings+xml -application/postscript ai eps ps -# application/prs.alvestrand.titrax-sheet -application/prs.cww cww -# application/prs.nprend -# application/prs.plucker -# application/prs.rdf-xml-crypt -# application/prs.xsf+xml -application/pskc+xml pskcxml -# application/qsig -application/rdf+xml rdf -application/reginfo+xml rif -application/relax-ng-compact-syntax rnc -# application/remote-printing -application/resource-lists+xml rl -application/resource-lists-diff+xml rld -# application/riscos -# application/rlmi+xml -application/rls-services+xml rs -application/rpki-ghostbusters gbr -application/rpki-manifest mft -application/rpki-roa roa -# application/rpki-updown -application/rsd+xml rsd -application/rss+xml rss -application/rtf rtf -# application/rtx -# application/samlassertion+xml -# application/samlmetadata+xml -application/sbml+xml sbml -application/scvp-cv-request scq -application/scvp-cv-response scs -application/scvp-vp-request spq -application/scvp-vp-response spp -application/sdp sdp -# application/set-payment -application/set-payment-initiation setpay -# application/set-registration -application/set-registration-initiation setreg -# application/sgml -# application/sgml-open-catalog -application/shf+xml shf -# application/sieve -# application/simple-filter+xml -# application/simple-message-summary -# application/simplesymbolcontainer -# application/slate -# application/smil -application/smil+xml smi smil -# application/soap+fastinfoset -# application/soap+xml -application/sparql-query rq -application/sparql-results+xml srx -# application/spirits-event+xml -application/srgs gram -application/srgs+xml grxml -application/sru+xml sru -application/ssml+xml ssml -# application/tamp-apex-update -# application/tamp-apex-update-confirm -# application/tamp-community-update -# application/tamp-community-update-confirm -# application/tamp-error -# application/tamp-sequence-adjust -# application/tamp-sequence-adjust-confirm -# application/tamp-status-query -# application/tamp-status-response -# application/tamp-update -# application/tamp-update-confirm -application/tei+xml tei teicorpus -application/thraud+xml tfi -# application/timestamp-query -# application/timestamp-reply -application/timestamped-data tsd -# application/tve-trigger -# application/ulpfec -# application/vcard+xml -# application/vemmi -# application/vividence.scriptfile -# application/vnd.3gpp.bsf+xml -application/vnd.3gpp.pic-bw-large plb -application/vnd.3gpp.pic-bw-small psb -application/vnd.3gpp.pic-bw-var pvb -# application/vnd.3gpp.sms -# application/vnd.3gpp2.bcmcsinfo+xml -# application/vnd.3gpp2.sms -application/vnd.3gpp2.tcap tcap -application/vnd.3m.post-it-notes pwn -application/vnd.accpac.simply.aso aso -application/vnd.accpac.simply.imp imp -application/vnd.acucobol acu -application/vnd.acucorp atc acutc -application/vnd.adobe.air-application-installer-package+zip air -application/vnd.adobe.fxp fxp fxpl -# application/vnd.adobe.partial-upload -application/vnd.adobe.xdp+xml xdp -application/vnd.adobe.xfdf xfdf -# application/vnd.aether.imp -# application/vnd.ah-barcode -application/vnd.ahead.space ahead -application/vnd.airzip.filesecure.azf azf -application/vnd.airzip.filesecure.azs azs -application/vnd.amazon.ebook azw -application/vnd.americandynamics.acc acc -application/vnd.amiga.ami ami -# application/vnd.amundsen.maze+xml -application/vnd.android.package-archive apk -application/vnd.anser-web-certificate-issue-initiation cii -application/vnd.anser-web-funds-transfer-initiation fti -application/vnd.antix.game-component atx -application/vnd.apple.installer+xml mpkg -application/vnd.apple.mpegurl m3u8 -# application/vnd.arastra.swi -application/vnd.aristanetworks.swi swi -application/vnd.astraea-software.iota iota -application/vnd.audiograph aep -# application/vnd.autopackage -# application/vnd.avistar+xml -application/vnd.blueice.multipass mpm -# application/vnd.bluetooth.ep.oob -application/vnd.bmi bmi -application/vnd.businessobjects rep -# application/vnd.cab-jscript -# application/vnd.canon-cpdl -# application/vnd.canon-lips -# application/vnd.cendio.thinlinc.clientconf -application/vnd.chemdraw+xml cdxml -application/vnd.chipnuts.karaoke-mmd mmd -application/vnd.cinderella cdy -# application/vnd.cirpack.isdn-ext -application/vnd.claymore cla -application/vnd.cloanto.rp9 rp9 -application/vnd.clonk.c4group c4g c4d c4f c4p c4u -application/vnd.cluetrust.cartomobile-config c11amc -application/vnd.cluetrust.cartomobile-config-pkg c11amz -# application/vnd.collection+json -# application/vnd.commerce-battelle -application/vnd.commonspace csp -application/vnd.contact.cmsg cdbcmsg -application/vnd.cosmocaller cmc -application/vnd.crick.clicker clkx -application/vnd.crick.clicker.keyboard clkk -application/vnd.crick.clicker.palette clkp -application/vnd.crick.clicker.template clkt -application/vnd.crick.clicker.wordbank clkw -application/vnd.criticaltools.wbs+xml wbs -application/vnd.ctc-posml pml -# application/vnd.ctct.ws+xml -# application/vnd.cups-pdf -# application/vnd.cups-postscript -application/vnd.cups-ppd ppd -# application/vnd.cups-raster -# application/vnd.cups-raw -# application/vnd.curl -application/vnd.curl.car car -application/vnd.curl.pcurl pcurl -# application/vnd.cybank -application/vnd.data-vision.rdz rdz -application/vnd.dece.data uvf uvvf uvd uvvd -application/vnd.dece.ttml+xml uvt uvvt -application/vnd.dece.unspecified uvx uvvx -application/vnd.dece.zip uvz uvvz -application/vnd.denovo.fcselayout-link fe_launch -# application/vnd.dir-bi.plate-dl-nosuffix -application/vnd.dna dna -application/vnd.dolby.mlp mlp -# application/vnd.dolby.mobile.1 -# application/vnd.dolby.mobile.2 -application/vnd.dpgraph dpg -application/vnd.dreamfactory dfac -application/vnd.dvb.ait ait -# application/vnd.dvb.dvbj -# application/vnd.dvb.esgcontainer -# application/vnd.dvb.ipdcdftnotifaccess -# application/vnd.dvb.ipdcesgaccess -# application/vnd.dvb.ipdcesgaccess2 -# application/vnd.dvb.ipdcesgpdd -# application/vnd.dvb.ipdcroaming -# application/vnd.dvb.iptv.alfec-base -# application/vnd.dvb.iptv.alfec-enhancement -# application/vnd.dvb.notif-aggregate-root+xml -# application/vnd.dvb.notif-container+xml -# application/vnd.dvb.notif-generic+xml -# application/vnd.dvb.notif-ia-msglist+xml -# application/vnd.dvb.notif-ia-registration-request+xml -# application/vnd.dvb.notif-ia-registration-response+xml -# application/vnd.dvb.notif-init+xml -# application/vnd.dvb.pfr -application/vnd.dvb.service svc -# application/vnd.dxr -application/vnd.dynageo geo -# application/vnd.easykaraoke.cdgdownload -# application/vnd.ecdis-update -application/vnd.ecowin.chart mag -# application/vnd.ecowin.filerequest -# application/vnd.ecowin.fileupdate -# application/vnd.ecowin.series -# application/vnd.ecowin.seriesrequest -# application/vnd.ecowin.seriesupdate -# application/vnd.emclient.accessrequest+xml -application/vnd.enliven nml -# application/vnd.eprints.data+xml -application/vnd.epson.esf esf -application/vnd.epson.msf msf -application/vnd.epson.quickanime qam -application/vnd.epson.salt slt -application/vnd.epson.ssf ssf -# application/vnd.ericsson.quickcall -application/vnd.eszigno3+xml es3 et3 -# application/vnd.etsi.aoc+xml -# application/vnd.etsi.cug+xml -# application/vnd.etsi.iptvcommand+xml -# application/vnd.etsi.iptvdiscovery+xml -# application/vnd.etsi.iptvprofile+xml -# application/vnd.etsi.iptvsad-bc+xml -# application/vnd.etsi.iptvsad-cod+xml -# application/vnd.etsi.iptvsad-npvr+xml -# application/vnd.etsi.iptvservice+xml -# application/vnd.etsi.iptvsync+xml -# application/vnd.etsi.iptvueprofile+xml -# application/vnd.etsi.mcid+xml -# application/vnd.etsi.overload-control-policy-dataset+xml -# application/vnd.etsi.sci+xml -# application/vnd.etsi.simservs+xml -# application/vnd.etsi.tsl+xml -# application/vnd.etsi.tsl.der -# application/vnd.eudora.data -application/vnd.ezpix-album ez2 -application/vnd.ezpix-package ez3 -# application/vnd.f-secure.mobile -application/vnd.fdf fdf -application/vnd.fdsn.mseed mseed -application/vnd.fdsn.seed seed dataless -# application/vnd.ffsns -# application/vnd.fints -application/vnd.flographit gph -application/vnd.fluxtime.clip ftc -# application/vnd.font-fontforge-sfd -application/vnd.framemaker fm frame maker book -application/vnd.frogans.fnc fnc -application/vnd.frogans.ltf ltf -application/vnd.fsc.weblaunch fsc -application/vnd.fujitsu.oasys oas -application/vnd.fujitsu.oasys2 oa2 -application/vnd.fujitsu.oasys3 oa3 -application/vnd.fujitsu.oasysgp fg5 -application/vnd.fujitsu.oasysprs bh2 -# application/vnd.fujixerox.art-ex -# application/vnd.fujixerox.art4 -# application/vnd.fujixerox.hbpl -application/vnd.fujixerox.ddd ddd -application/vnd.fujixerox.docuworks xdw -application/vnd.fujixerox.docuworks.binder xbd -# application/vnd.fut-misnet -application/vnd.fuzzysheet fzs -application/vnd.genomatix.tuxedo txd -# application/vnd.geocube+xml -application/vnd.geogebra.file ggb -application/vnd.geogebra.tool ggt -application/vnd.geometry-explorer gex gre -application/vnd.geonext gxt -application/vnd.geoplan g2w -application/vnd.geospace g3w -# application/vnd.globalplatform.card-content-mgt -# application/vnd.globalplatform.card-content-mgt-response -application/vnd.gmx gmx -application/vnd.google-earth.kml+xml kml -application/vnd.google-earth.kmz kmz -application/vnd.grafeq gqf gqs -# application/vnd.gridmp -application/vnd.groove-account gac -application/vnd.groove-help ghf -application/vnd.groove-identity-message gim -application/vnd.groove-injector grv -application/vnd.groove-tool-message gtm -application/vnd.groove-tool-template tpl -application/vnd.groove-vcard vcg -# application/vnd.hal+json -application/vnd.hal+xml hal -application/vnd.handheld-entertainment+xml zmm -application/vnd.hbci hbci -# application/vnd.hcl-bireports -application/vnd.hhe.lesson-player les -application/vnd.hp-hpgl hpgl -application/vnd.hp-hpid hpid -application/vnd.hp-hps hps -application/vnd.hp-jlyt jlt -application/vnd.hp-pcl pcl -application/vnd.hp-pclxl pclxl -# application/vnd.httphone -application/vnd.hydrostatix.sof-data sfd-hdstx -application/vnd.hzn-3d-crossword x3d -# application/vnd.ibm.afplinedata -# application/vnd.ibm.electronic-media -application/vnd.ibm.minipay mpy -application/vnd.ibm.modcap afp listafp list3820 -application/vnd.ibm.rights-management irm -application/vnd.ibm.secure-container sc -application/vnd.iccprofile icc icm -application/vnd.igloader igl -application/vnd.immervision-ivp ivp -application/vnd.immervision-ivu ivu -# application/vnd.informedcontrol.rms+xml -# application/vnd.informix-visionary -# application/vnd.infotech.project -# application/vnd.infotech.project+xml -application/vnd.insors.igm igm -application/vnd.intercon.formnet xpw xpx -application/vnd.intergeo i2g -# application/vnd.intertrust.digibox -# application/vnd.intertrust.nncp -application/vnd.intu.qbo qbo -application/vnd.intu.qfx qfx -# application/vnd.iptc.g2.conceptitem+xml -# application/vnd.iptc.g2.knowledgeitem+xml -# application/vnd.iptc.g2.newsitem+xml -# application/vnd.iptc.g2.packageitem+xml -application/vnd.ipunplugged.rcprofile rcprofile -application/vnd.irepository.package+xml irp -application/vnd.is-xpr xpr -application/vnd.isac.fcs fcs -application/vnd.jam jam -# application/vnd.japannet-directory-service -# application/vnd.japannet-jpnstore-wakeup -# application/vnd.japannet-payment-wakeup -# application/vnd.japannet-registration -# application/vnd.japannet-registration-wakeup -# application/vnd.japannet-setstore-wakeup -# application/vnd.japannet-verification -# application/vnd.japannet-verification-wakeup -application/vnd.jcp.javame.midlet-rms rms -application/vnd.jisp jisp -application/vnd.joost.joda-archive joda -application/vnd.kahootz ktz ktr -application/vnd.kde.karbon karbon -application/vnd.kde.kchart chrt -application/vnd.kde.kformula kfo -application/vnd.kde.kivio flw -application/vnd.kde.kontour kon -application/vnd.kde.kpresenter kpr kpt -application/vnd.kde.kspread ksp -application/vnd.kde.kword kwd kwt -application/vnd.kenameaapp htke -application/vnd.kidspiration kia -application/vnd.kinar kne knp -application/vnd.koan skp skd skt skm -application/vnd.kodak-descriptor sse -application/vnd.las.las+xml lasxml -# application/vnd.liberty-request+xml -application/vnd.llamagraphics.life-balance.desktop lbd -application/vnd.llamagraphics.life-balance.exchange+xml lbe -application/vnd.lotus-1-2-3 123 -application/vnd.lotus-approach apr -application/vnd.lotus-freelance pre -application/vnd.lotus-notes nsf -application/vnd.lotus-organizer org -application/vnd.lotus-screencam scm -application/vnd.lotus-wordpro lwp -application/vnd.macports.portpkg portpkg -# application/vnd.marlin.drm.actiontoken+xml -# application/vnd.marlin.drm.conftoken+xml -# application/vnd.marlin.drm.license+xml -# application/vnd.marlin.drm.mdcf -application/vnd.mcd mcd -application/vnd.medcalcdata mc1 -application/vnd.mediastation.cdkey cdkey -# application/vnd.meridian-slingshot -application/vnd.mfer mwf -application/vnd.mfmp mfm -application/vnd.micrografx.flo flo -application/vnd.micrografx.igx igx -application/vnd.mif mif -# application/vnd.minisoft-hp3000-save -# application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf daf -application/vnd.mobius.dis dis -application/vnd.mobius.mbk mbk -application/vnd.mobius.mqy mqy -application/vnd.mobius.msl msl -application/vnd.mobius.plc plc -application/vnd.mobius.txf txf -application/vnd.mophun.application mpn -application/vnd.mophun.certificate mpc -# application/vnd.motorola.flexsuite -# application/vnd.motorola.flexsuite.adsi -# application/vnd.motorola.flexsuite.fis -# application/vnd.motorola.flexsuite.gotap -# application/vnd.motorola.flexsuite.kmr -# application/vnd.motorola.flexsuite.ttc -# application/vnd.motorola.flexsuite.wem -# application/vnd.motorola.iprm -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry cil -# application/vnd.ms-asf -application/vnd.ms-cab-compressed cab -application/vnd.ms-excel xls xlm xla xlc xlt xlw -application/vnd.ms-excel.addin.macroenabled.12 xlam -application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb -application/vnd.ms-excel.sheet.macroenabled.12 xlsm -application/vnd.ms-excel.template.macroenabled.12 xltm -application/vnd.ms-fontobject eot -application/vnd.ms-htmlhelp chm -application/vnd.ms-ims ims -application/vnd.ms-lrm lrm -# application/vnd.ms-office.activex+xml -application/vnd.ms-officetheme thmx -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -# application/vnd.ms-playready.initiator+xml -application/vnd.ms-powerpoint ppt pps pot -application/vnd.ms-powerpoint.addin.macroenabled.12 ppam -application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm -application/vnd.ms-powerpoint.slide.macroenabled.12 sldm -application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm -application/vnd.ms-powerpoint.template.macroenabled.12 potm -application/vnd.ms-project mpp mpt -# application/vnd.ms-tnef -# application/vnd.ms-wmdrm.lic-chlg-req -# application/vnd.ms-wmdrm.lic-resp -# application/vnd.ms-wmdrm.meter-chlg-req -# application/vnd.ms-wmdrm.meter-resp -application/vnd.ms-word.document.macroenabled.12 docm -application/vnd.ms-word.template.macroenabled.12 dotm -application/vnd.ms-works wps wks wcm wdb -application/vnd.ms-wpl wpl -application/vnd.ms-xpsdocument xps -application/vnd.mseq mseq -# application/vnd.msign -# application/vnd.multiad.creator -# application/vnd.multiad.creator.cif -# application/vnd.music-niff -application/vnd.musician mus -application/vnd.muvee.style msty -application/vnd.mynfc taglet -# application/vnd.ncd.control -# application/vnd.ncd.reference -# application/vnd.nervana -# application/vnd.netfpx -application/vnd.neurolanguage.nlu nlu -application/vnd.noblenet-directory nnd -application/vnd.noblenet-sealer nns -application/vnd.noblenet-web nnw -# application/vnd.nokia.catalogs -# application/vnd.nokia.conml+wbxml -# application/vnd.nokia.conml+xml -# application/vnd.nokia.isds-radio-presets -# application/vnd.nokia.iptv.config+xml -# application/vnd.nokia.landmark+wbxml -# application/vnd.nokia.landmark+xml -# application/vnd.nokia.landmarkcollection+xml -# application/vnd.nokia.n-gage.ac+xml -application/vnd.nokia.n-gage.data ngdat -application/vnd.nokia.n-gage.symbian.install n-gage -# application/vnd.nokia.ncd -# application/vnd.nokia.pcd+wbxml -# application/vnd.nokia.pcd+xml -application/vnd.nokia.radio-preset rpst -application/vnd.nokia.radio-presets rpss -application/vnd.novadigm.edm edm -application/vnd.novadigm.edx edx -application/vnd.novadigm.ext ext -# application/vnd.ntt-local.file-transfer -# application/vnd.ntt-local.sip-ta_remote -# application/vnd.ntt-local.sip-ta_tcp_stream -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.chart-template otc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.formula-template odft -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.image-template oti -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -# application/vnd.obn -# application/vnd.oftn.l10n+json -# application/vnd.oipf.contentaccessdownload+xml -# application/vnd.oipf.contentaccessstreaming+xml -# application/vnd.oipf.cspg-hexbinary -# application/vnd.oipf.dae.svg+xml -# application/vnd.oipf.dae.xhtml+xml -# application/vnd.oipf.mippvcontrolmessage+xml -# application/vnd.oipf.pae.gem -# application/vnd.oipf.spdiscovery+xml -# application/vnd.oipf.spdlist+xml -# application/vnd.oipf.ueprofile+xml -# application/vnd.oipf.userprofile+xml -application/vnd.olpc-sugar xo -# application/vnd.oma-scws-config -# application/vnd.oma-scws-http-request -# application/vnd.oma-scws-http-response -# application/vnd.oma.bcast.associated-procedure-parameter+xml -# application/vnd.oma.bcast.drm-trigger+xml -# application/vnd.oma.bcast.imd+xml -# application/vnd.oma.bcast.ltkm -# application/vnd.oma.bcast.notification+xml -# application/vnd.oma.bcast.provisioningtrigger -# application/vnd.oma.bcast.sgboot -# application/vnd.oma.bcast.sgdd+xml -# application/vnd.oma.bcast.sgdu -# application/vnd.oma.bcast.simple-symbol-container -# application/vnd.oma.bcast.smartcard-trigger+xml -# application/vnd.oma.bcast.sprov+xml -# application/vnd.oma.bcast.stkm -# application/vnd.oma.cab-address-book+xml -# application/vnd.oma.cab-feature-handler+xml -# application/vnd.oma.cab-pcc+xml -# application/vnd.oma.cab-user-prefs+xml -# application/vnd.oma.dcd -# application/vnd.oma.dcdc -application/vnd.oma.dd2+xml dd2 -# application/vnd.oma.drm.risd+xml -# application/vnd.oma.group-usage-list+xml -# application/vnd.oma.pal+xml -# application/vnd.oma.poc.detailed-progress-report+xml -# application/vnd.oma.poc.final-report+xml -# application/vnd.oma.poc.groups+xml -# application/vnd.oma.poc.invocation-descriptor+xml -# application/vnd.oma.poc.optimized-progress-report+xml -# application/vnd.oma.push -# application/vnd.oma.scidm.messages+xml -# application/vnd.oma.xcap-directory+xml -# application/vnd.omads-email+xml -# application/vnd.omads-file+xml -# application/vnd.omads-folder+xml -# application/vnd.omaloc-supl-init -application/vnd.openofficeorg.extension oxt -# application/vnd.openxmlformats-officedocument.custom-properties+xml -# application/vnd.openxmlformats-officedocument.customxmlproperties+xml -# application/vnd.openxmlformats-officedocument.drawing+xml -# application/vnd.openxmlformats-officedocument.drawingml.chart+xml -# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml -# application/vnd.openxmlformats-officedocument.extended-properties+xml -# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml -# application/vnd.openxmlformats-officedocument.presentationml.comments+xml -# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml -application/vnd.openxmlformats-officedocument.presentationml.presentation pptx -# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml -application/vnd.openxmlformats-officedocument.presentationml.slide sldx -# application/vnd.openxmlformats-officedocument.presentationml.slide+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml -application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx -# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml -# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml -# application/vnd.openxmlformats-officedocument.presentationml.tags+xml -application/vnd.openxmlformats-officedocument.presentationml.template potx -# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx -# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml -# application/vnd.openxmlformats-officedocument.theme+xml -# application/vnd.openxmlformats-officedocument.themeoverride+xml -# application/vnd.openxmlformats-officedocument.vmldrawing -# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.document docx -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx -# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml -# application/vnd.openxmlformats-package.core-properties+xml -# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml -# application/vnd.openxmlformats-package.relationships+xml -# application/vnd.quobject-quoxdocument -# application/vnd.osa.netdeploy -application/vnd.osgeo.mapguide.package mgp -# application/vnd.osgi.bundle -application/vnd.osgi.dp dp -# application/vnd.otps.ct-kip+xml -application/vnd.palm pdb pqa oprc -# application/vnd.paos.xml -application/vnd.pawaafile paw -application/vnd.pg.format str -application/vnd.pg.osasli ei6 -# application/vnd.piaccess.application-licence -application/vnd.picsel efif -application/vnd.pmi.widget wg -# application/vnd.poc.group-advertisement+xml -application/vnd.pocketlearn plf -application/vnd.powerbuilder6 pbd -# application/vnd.powerbuilder6-s -# application/vnd.powerbuilder7 -# application/vnd.powerbuilder7-s -# application/vnd.powerbuilder75 -# application/vnd.powerbuilder75-s -# application/vnd.preminet -application/vnd.previewsystems.box box -application/vnd.proteus.magazine mgz -application/vnd.publishare-delta-tree qps -application/vnd.pvi.ptid1 ptid -# application/vnd.pwg-multiplexed -# application/vnd.pwg-xhtml-print+xml -# application/vnd.qualcomm.brew-app-res -application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb -# application/vnd.radisys.moml+xml -# application/vnd.radisys.msml+xml -# application/vnd.radisys.msml-audit+xml -# application/vnd.radisys.msml-audit-conf+xml -# application/vnd.radisys.msml-audit-conn+xml -# application/vnd.radisys.msml-audit-dialog+xml -# application/vnd.radisys.msml-audit-stream+xml -# application/vnd.radisys.msml-conf+xml -# application/vnd.radisys.msml-dialog+xml -# application/vnd.radisys.msml-dialog-base+xml -# application/vnd.radisys.msml-dialog-fax-detect+xml -# application/vnd.radisys.msml-dialog-fax-sendrecv+xml -# application/vnd.radisys.msml-dialog-group+xml -# application/vnd.radisys.msml-dialog-speech+xml -# application/vnd.radisys.msml-dialog-transform+xml -# application/vnd.rainstor.data -# application/vnd.rapid -application/vnd.realvnc.bed bed -application/vnd.recordare.musicxml mxl -application/vnd.recordare.musicxml+xml musicxml -# application/vnd.renlearn.rlprint -application/vnd.rig.cryptonote cryptonote -application/vnd.rim.cod cod -application/vnd.rn-realmedia rm -application/vnd.route66.link66+xml link66 -# application/vnd.ruckus.download -# application/vnd.s3sms -application/vnd.sailingtracker.track st -# application/vnd.sbm.cid -# application/vnd.sbm.mid2 -# application/vnd.scribus -# application/vnd.sealed.3df -# application/vnd.sealed.csf -# application/vnd.sealed.doc -# application/vnd.sealed.eml -# application/vnd.sealed.mht -# application/vnd.sealed.net -# application/vnd.sealed.ppt -# application/vnd.sealed.tiff -# application/vnd.sealed.xls -# application/vnd.sealedmedia.softseal.html -# application/vnd.sealedmedia.softseal.pdf -application/vnd.seemail see -application/vnd.sema sema -application/vnd.semd semd -application/vnd.semf semf -application/vnd.shana.informed.formdata ifm -application/vnd.shana.informed.formtemplate itp -application/vnd.shana.informed.interchange iif -application/vnd.shana.informed.package ipk -application/vnd.simtech-mindmapper twd twds -application/vnd.smaf mmf -# application/vnd.smart.notebook -application/vnd.smart.teacher teacher -# application/vnd.software602.filler.form+xml -# application/vnd.software602.filler.form-xml-zip -application/vnd.solent.sdkm+xml sdkm sdkd -application/vnd.spotfire.dxp dxp -application/vnd.spotfire.sfs sfs -# application/vnd.sss-cod -# application/vnd.sss-dtf -# application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.stepmania.package smzip -application/vnd.stepmania.stepchart sm -# application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -# application/vnd.sun.wadl+xml -application/vnd.sus-calendar sus susp -application/vnd.svd svd -# application/vnd.swiftview-ics -application/vnd.symbian.install sis sisx -application/vnd.syncml+xml xsm -application/vnd.syncml.dm+wbxml bdm -application/vnd.syncml.dm+xml xdm -# application/vnd.syncml.dm.notification -# application/vnd.syncml.ds.notification -application/vnd.tao.intent-module-archive tao -application/vnd.tcpdump.pcap pcap cap dmp -application/vnd.tmobile-livetv tmo -application/vnd.trid.tpt tpt -application/vnd.triscape.mxs mxs -application/vnd.trueapp tra -# application/vnd.truedoc -# application/vnd.ubisoft.webplayer -application/vnd.ufdl ufd ufdl -application/vnd.uiq.theme utz -application/vnd.umajin umj -application/vnd.unity unityweb -application/vnd.uoml+xml uoml -# application/vnd.uplanet.alert -# application/vnd.uplanet.alert-wbxml -# application/vnd.uplanet.bearer-choice -# application/vnd.uplanet.bearer-choice-wbxml -# application/vnd.uplanet.cacheop -# application/vnd.uplanet.cacheop-wbxml -# application/vnd.uplanet.channel -# application/vnd.uplanet.channel-wbxml -# application/vnd.uplanet.list -# application/vnd.uplanet.list-wbxml -# application/vnd.uplanet.listcmd -# application/vnd.uplanet.listcmd-wbxml -# application/vnd.uplanet.signal -application/vnd.vcx vcx -# application/vnd.vd-study -# application/vnd.vectorworks -# application/vnd.verimatrix.vcas -# application/vnd.vidsoft.vidconference -application/vnd.visio vsd vst vss vsw -application/vnd.visionary vis -# application/vnd.vividence.scriptfile -application/vnd.vsf vsf -# application/vnd.wap.sic -# application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo wtb -# application/vnd.wfa.wsc -# application/vnd.wmc -# application/vnd.wmf.bootstrap -# application/vnd.wolfram.mathematica -# application/vnd.wolfram.mathematica.package -application/vnd.wolfram.player nbp -application/vnd.wordperfect wpd -application/vnd.wqd wqd -# application/vnd.wrq-hp3000-labelled -application/vnd.wt.stf stf -# application/vnd.wv.csp+wbxml -# application/vnd.wv.csp+xml -# application/vnd.wv.ssp+xml -application/vnd.xara xar -application/vnd.xfdl xfdl -# application/vnd.xfdl.webform -# application/vnd.xmi+xml -# application/vnd.xmpie.cpkg -# application/vnd.xmpie.dpkg -# application/vnd.xmpie.plan -# application/vnd.xmpie.ppkg -# application/vnd.xmpie.xlim -application/vnd.yamaha.hv-dic hvd -application/vnd.yamaha.hv-script hvs -application/vnd.yamaha.hv-voice hvp -application/vnd.yamaha.openscoreformat osf -application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg -# application/vnd.yamaha.remote-setup -application/vnd.yamaha.smaf-audio saf -application/vnd.yamaha.smaf-phrase spf -# application/vnd.yamaha.through-ngn -# application/vnd.yamaha.tunnel-udpencap -application/vnd.yellowriver-custom-menu cmp -application/vnd.zul zir zirz -application/vnd.zzazz.deck+xml zaz -application/voicexml+xml vxml -# application/vq-rtcpxr -# application/watcherinfo+xml -# application/whoispp-query -# application/whoispp-response -application/widget wgt -application/winhlp hlp -# application/wita -# application/wordperfect5.1 -application/wsdl+xml wsdl -application/wspolicy+xml wspolicy -application/x-7z-compressed 7z -application/x-abiword abw -application/x-ace-compressed ace -application/x-authorware-bin aab x32 u32 vox -application/x-authorware-map aam -application/x-authorware-seg aas -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-bzip bz -application/x-bzip2 bz2 boz -application/x-cdlink vcd -application/x-chat chat -application/x-chess-pgn pgn -# application/x-compress -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-director dir dcr dxr cst cct cxt w3d fgd swa -application/x-doom wad -application/x-dtbncx+xml ncx -application/x-dtbook+xml dtb -application/x-dtbresource+xml res -application/x-dvi dvi -application/x-font-bdf bdf -# application/x-font-dos -# application/x-font-framemaker -application/x-font-ghostscript gsf -# application/x-font-libgrx -application/x-font-linux-psf psf -application/x-font-otf otf -application/x-font-pcf pcf -application/x-font-snf snf -# application/x-font-speedo -# application/x-font-sunos-news -application/x-font-ttf ttf ttc -application/x-font-type1 pfa pfb pfm afm -application/x-font-woff woff -# application/x-font-vfont -application/x-futuresplash spl -application/x-gnumeric gnumeric -application/x-gtar gtar -# application/x-gzip -application/x-hdf hdf -application/x-java-jnlp-file jnlp -application/x-latex latex -application/x-mobipocket-ebook prc mobi -application/x-ms-application application -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-ms-xbap xbap -application/x-msaccess mdb -application/x-msbinder obd -application/x-mscardfile crd -application/x-msclip clp -application/x-msdownload exe dll com bat msi -application/x-msmediaview mvb m13 m14 -application/x-msmetafile wmf -application/x-msmoney mny -application/x-mspublisher pub -application/x-msschedule scd -application/x-msterminal trm -application/x-mswrite wri -application/x-netcdf nc cdf -application/x-pkcs12 p12 pfx -application/x-pkcs7-certificates p7b spc -application/x-pkcs7-certreqresp p7r -application/x-rar-compressed rar -application/x-sh sh -application/x-shar shar -application/x-shockwave-flash swf -application/x-silverlight-app xap -application/x-stuffit sit -application/x-stuffitx sitx -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-tar tar -application/x-tcl tcl -application/x-tex tex -application/x-tex-tfm tfm -application/x-texinfo texinfo texi -application/x-ustar ustar -application/x-wais-source src -application/x-x509-ca-cert der crt -application/x-xfig fig -application/x-xpinstall xpi -# application/x400-bp -# application/xcap-att+xml -# application/xcap-caps+xml -application/xcap-diff+xml xdf -# application/xcap-el+xml -# application/xcap-error+xml -# application/xcap-ns+xml -# application/xcon-conference-info-diff+xml -# application/xcon-conference-info+xml -application/xenc+xml xenc -application/xhtml+xml xhtml xht -# application/xhtml-voice+xml -application/xml xml xsl -application/xml-dtd dtd -# application/xml-external-parsed-entity -# application/xmpp+xml -application/xop+xml xop -application/xslt+xml xslt -application/xspf+xml xspf -application/xv+xml mxml xhvml xvml xvm -application/yang yang -application/yin+xml yin -application/zip zip -# audio/1d-interleaved-parityfec -# audio/32kadpcm -# audio/3gpp -# audio/3gpp2 -# audio/ac3 -audio/adpcm adp -# audio/amr -# audio/amr-wb -# audio/amr-wb+ -# audio/asc -# audio/atrac-advanced-lossless -# audio/atrac-x -# audio/atrac3 -audio/basic au snd -# audio/bv16 -# audio/bv32 -# audio/clearmode -# audio/cn -# audio/dat12 -# audio/dls -# audio/dsr-es201108 -# audio/dsr-es202050 -# audio/dsr-es202211 -# audio/dsr-es202212 -# audio/dv -# audio/dvi4 -# audio/eac3 -# audio/evrc -# audio/evrc-qcp -# audio/evrc0 -# audio/evrc1 -# audio/evrcb -# audio/evrcb0 -# audio/evrcb1 -# audio/evrcwb -# audio/evrcwb0 -# audio/evrcwb1 -# audio/example -# audio/fwdred -# audio/g719 -# audio/g722 -# audio/g7221 -# audio/g723 -# audio/g726-16 -# audio/g726-24 -# audio/g726-32 -# audio/g726-40 -# audio/g728 -# audio/g729 -# audio/g7291 -# audio/g729d -# audio/g729e -# audio/gsm -# audio/gsm-efr -# audio/gsm-hr-08 -# audio/ilbc -# audio/ip-mr_v2.5 -# audio/l16 -# audio/l20 -# audio/l24 -# audio/l8 -# audio/lpc -audio/midi mid midi kar rmi -# audio/mobile-xmf -audio/mp4 mp4a -# audio/mp4a-latm -# audio/mpa -# audio/mpa-robust -audio/mpeg mpga mp2 mp2a mp3 m2a m3a -# audio/mpeg4-generic -audio/ogg oga ogg spx -# audio/parityfec -# audio/pcma -# audio/pcma-wb -# audio/pcmu-wb -# audio/pcmu -# audio/prs.sid -# audio/qcelp -# audio/red -# audio/rtp-enc-aescm128 -# audio/rtp-midi -# audio/rtx -# audio/smv -# audio/smv0 -# audio/smv-qcp -# audio/sp-midi -# audio/speex -# audio/t140c -# audio/t38 -# audio/telephone-event -# audio/tone -# audio/uemclip -# audio/ulpfec -# audio/vdvi -# audio/vmr-wb -# audio/vnd.3gpp.iufp -# audio/vnd.4sb -# audio/vnd.audiokoz -# audio/vnd.celp -# audio/vnd.cisco.nse -# audio/vnd.cmles.radio-events -# audio/vnd.cns.anp1 -# audio/vnd.cns.inf1 -audio/vnd.dece.audio uva uvva -audio/vnd.digital-winds eol -# audio/vnd.dlna.adts -# audio/vnd.dolby.heaac.1 -# audio/vnd.dolby.heaac.2 -# audio/vnd.dolby.mlp -# audio/vnd.dolby.mps -# audio/vnd.dolby.pl2 -# audio/vnd.dolby.pl2x -# audio/vnd.dolby.pl2z -# audio/vnd.dolby.pulse.1 -audio/vnd.dra dra -audio/vnd.dts dts -audio/vnd.dts.hd dtshd -# audio/vnd.dvb.file dvb -# audio/vnd.everad.plj -# audio/vnd.hns.audio -audio/vnd.lucent.voice lvp -audio/vnd.ms-playready.media.pya pya -# audio/vnd.nokia.mobile-xmf -# audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 ecelp4800 -audio/vnd.nuera.ecelp7470 ecelp7470 -audio/vnd.nuera.ecelp9600 ecelp9600 -# audio/vnd.octel.sbc -# audio/vnd.qcelp -# audio/vnd.rhetorex.32kadpcm -audio/vnd.rip rip -# audio/vnd.sealedmedia.softseal.mpeg -# audio/vnd.vmx.cvsd -# audio/vorbis -# audio/vorbis-config -audio/webm weba -audio/x-aac aac -audio/x-aiff aif aiff aifc -audio/x-mpegurl m3u -audio/x-ms-wax wax -audio/x-ms-wma wma -audio/x-pn-realaudio ram ra -audio/x-pn-realaudio-plugin rmp -audio/x-wav wav -chemical/x-cdx cdx -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-csml csml -# chemical/x-pdb -chemical/x-xyz xyz -image/bmp bmp -image/cgm cgm -# image/example -# image/fits -image/g3fax g3 -image/gif gif -image/ief ief -# image/jp2 -image/jpeg jpeg jpg jpe -# image/jpm -# image/jpx -image/ktx ktx -# image/naplps -image/png png -image/prs.btif btif -# image/prs.pti -image/svg+xml svg svgz -# image/t38 -image/tiff tiff tif -# image/tiff-fx -image/vnd.adobe.photoshop psd -# image/vnd.cns.inf2 -image/vnd.dece.graphic uvi uvvi uvg uvvg -image/vnd.dvb.subtitle sub -image/vnd.djvu djvu djv -image/vnd.dwg dwg -image/vnd.dxf dxf -image/vnd.fastbidsheet fbs -image/vnd.fpx fpx -image/vnd.fst fst -image/vnd.fujixerox.edmics-mmr mmr -image/vnd.fujixerox.edmics-rlc rlc -# image/vnd.globalgraphics.pgb -# image/vnd.microsoft.icon -# image/vnd.mix -image/vnd.ms-modi mdi -image/vnd.net-fpx npx -# image/vnd.radiance -# image/vnd.sealed.png -# image/vnd.sealedmedia.softseal.gif -# image/vnd.sealedmedia.softseal.jpg -# image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff xif -image/webp webp -image/x-cmu-raster ras -image/x-cmx cmx -image/x-freehand fh fhc fh4 fh5 fh7 -image/x-icon ico -image/x-pcx pcx -image/x-pict pic pct -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd -# message/cpim -# message/delivery-status -# message/disposition-notification -# message/example -# message/external-body -# message/feedback-report -# message/global -# message/global-delivery-status -# message/global-disposition-notification -# message/global-headers -# message/http -# message/imdn+xml -# message/news -# message/partial -message/rfc822 eml mime -# message/s-http -# message/sip -# message/sipfrag -# message/tracking-status -# message/vnd.si.simp -# model/example -model/iges igs iges -model/mesh msh mesh silo -model/vnd.collada+xml dae -model/vnd.dwf dwf -# model/vnd.flatland.3dml -model/vnd.gdl gdl -# model/vnd.gs-gdl -# model/vnd.gs.gdl -model/vnd.gtw gtw -# model/vnd.moml+xml -model/vnd.mts mts -# model/vnd.parasolid.transmit.binary -# model/vnd.parasolid.transmit.text -model/vnd.vtu vtu -model/vrml wrl vrml -# multipart/alternative -# multipart/appledouble -# multipart/byteranges -# multipart/digest -# multipart/encrypted -# multipart/example -# multipart/form-data -# multipart/header-set -# multipart/mixed -# multipart/parallel -# multipart/related -# multipart/report -# multipart/signed -# multipart/voice-message -# text/1d-interleaved-parityfec -text/calendar ics ifb -text/css css -text/csv csv -# text/directory -# text/dns -# text/ecmascript -# text/enriched -# text/example -# text/fwdred -text/html html htm -# text/javascript -text/n3 n3 -# text/parityfec -text/plain txt text conf def list log in -# text/prs.fallenstein.rst -text/prs.lines.tag dsc -# text/vnd.radisys.msml-basic-layout -# text/red -# text/rfc822-headers -text/richtext rtx -# text/rtf -# text/rtp-enc-aescm128 -# text/rtx -text/sgml sgml sgm -# text/t140 -text/tab-separated-values tsv -text/troff t tr roff man me ms -text/turtle ttl -# text/ulpfec -text/uri-list uri uris urls -text/vcard vcard -# text/vnd.abc -text/vnd.curl curl -text/vnd.curl.dcurl dcurl -text/vnd.curl.scurl scurl -text/vnd.curl.mcurl mcurl -# text/vnd.dmclientscript -text/vnd.dvb.subtitle sub -# text/vnd.esmertec.theme-descriptor -text/vnd.fly fly -text/vnd.fmi.flexstor flx -text/vnd.graphviz gv -text/vnd.in3d.3dml 3dml -text/vnd.in3d.spot spot -# text/vnd.iptc.newsml -# text/vnd.iptc.nitf -# text/vnd.latex-z -# text/vnd.motorola.reflex -# text/vnd.ms-mediapackage -# text/vnd.net2phone.commcenter.command -# text/vnd.si.uricatalogue -text/vnd.sun.j2me.app-descriptor jad -# text/vnd.trolltech.linguist -# text/vnd.wap.si -# text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-asm s asm -text/x-c c cc cxx cpp h hh dic -text/x-fortran f for f77 f90 -text/x-pascal p pas -text/x-java-source java -text/x-setext etx -text/x-uuencode uu -text/x-vcalendar vcs -text/x-vcard vcf -# text/xml -# text/xml-external-parsed-entity -# video/1d-interleaved-parityfec -video/3gpp 3gp -# video/3gpp-tt -video/3gpp2 3g2 -# video/bmpeg -# video/bt656 -# video/celb -# video/dv -# video/example -video/h261 h261 -video/h263 h263 -# video/h263-1998 -# video/h263-2000 -video/h264 h264 -# video/h264-rcdo -# video/h264-svc -video/jpeg jpgv -# video/jpeg2000 -video/jpm jpm jpgm -video/mj2 mj2 mjp2 -# video/mp1s -# video/mp2p -# video/mp2t -video/mp4 mp4 mp4v mpg4 -# video/mp4v-es -video/mpeg mpeg mpg mpe m1v m2v -# video/mpeg4-generic -# video/mpv -# video/nv -video/ogg ogv -# video/parityfec -# video/pointer -video/quicktime qt mov -# video/raw -# video/rtp-enc-aescm128 -# video/rtx -# video/smpte292m -# video/ulpfec -# video/vc1 -# video/vnd.cctv -video/vnd.dece.hd uvh uvvh -video/vnd.dece.mobile uvm uvvm -# video/vnd.dece.mp4 -video/vnd.dece.pd uvp uvvp -video/vnd.dece.sd uvs uvvs -video/vnd.dece.video uvv uvvv -# video/vnd.directv.mpeg -# video/vnd.directv.mpeg-tts -# video/vnd.dlna.mpeg-tts -video/vnd.dvb.file dvb -video/vnd.fvt fvt -# video/vnd.hns.video -# video/vnd.iptvforum.1dparityfec-1010 -# video/vnd.iptvforum.1dparityfec-2005 -# video/vnd.iptvforum.2dparityfec-1010 -# video/vnd.iptvforum.2dparityfec-2005 -# video/vnd.iptvforum.ttsavc -# video/vnd.iptvforum.ttsmpeg2 -# video/vnd.motorola.video -# video/vnd.motorola.videop -video/vnd.mpegurl mxu m4u -video/vnd.ms-playready.media.pyv pyv -# video/vnd.nokia.interleaved-multimedia -# video/vnd.nokia.videovoip -# video/vnd.objectvideo -# video/vnd.sealed.mpeg1 -# video/vnd.sealed.mpeg4 -# video/vnd.sealed.swf -# video/vnd.sealedmedia.softseal.mov -video/vnd.uvvu.mp4 uvu uvvu -video/vnd.vivo viv -video/webm webm -video/x-f4v f4v -video/x-fli fli -video/x-flv flv -video/x-m4v m4v -video/x-ms-asf asf asx -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie -x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/mime/types/node.types b/node_modules/express/node_modules/mime/types/node.types deleted file mode 100644 index f7da49f..0000000 --- a/node_modules/express/node_modules/mime/types/node.types +++ /dev/null @@ -1,48 +0,0 @@ -# What: Google Chrome Extension -# Why: To allow apps to (work) be served with the right content type header. -# http://codereview.chromium.org/2830017 -# Added by: niftylettuce -application/x-chrome-extension crx - -# What: OTF Message Silencer -# Why: To silence the "Resource interpreted as font but transferred with MIME -# type font/otf" message that occurs in Google Chrome -# Added by: niftylettuce -font/opentype otf - -# What: HTC support -# Why: To properly render .htc files such as CSS3PIE -# Added by: niftylettuce -text/x-component htc - -# What: HTML5 application cache manifest -# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps -# per https://developer.mozilla.org/en/offline_resources_in_firefox -# Added by: louisremi -text/cache-manifest appcache manifest - -# What: node binary buffer format -# Why: semi-standard extension w/in the node community -# Added by: tootallnate -application/octet-stream buffer - -# What: The "protected" MP-4 formats used by iTunes. -# Why: Required for streaming music to browsers (?) -# Added by: broofa -application/mp4 m4p -audio/mp4 m4a - -# What: Music playlist format (http://en.wikipedia.org/wiki/M3U) -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -application/x-mpegURL m3u8 - -# What: Video format, Part of RFC1890 -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -video/MP2T ts - -# What: The FLAC lossless codec format -# Why: Streaming and serving FLAC audio -# Added by: jacobrask -audio/flac flac \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/.gitignore.orig b/node_modules/express/node_modules/mkdirp/.gitignore.orig deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/express/node_modules/mkdirp/.gitignore.orig +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/.gitignore.rej b/node_modules/express/node_modules/mkdirp/.gitignore.rej deleted file mode 100644 index 69244ff..0000000 --- a/node_modules/express/node_modules/mkdirp/.gitignore.rej +++ /dev/null @@ -1,5 +0,0 @@ ---- /dev/null -+++ .gitignore -@@ -0,0 +1,2 @@ -+node_modules/ -+npm-debug.log \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/.npmignore b/node_modules/express/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/express/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/LICENSE b/node_modules/express/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/express/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express/node_modules/mkdirp/README.markdown b/node_modules/express/node_modules/mkdirp/README.markdown deleted file mode 100644 index 0393c4e..0000000 --- a/node_modules/express/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,21 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -Example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! diff --git a/node_modules/express/node_modules/mkdirp/examples/pow.js b/node_modules/express/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index 7741462..0000000 --- a/node_modules/express/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/express/node_modules/mkdirp/examples/pow.js.orig b/node_modules/express/node_modules/mkdirp/examples/pow.js.orig deleted file mode 100644 index 7741462..0000000 --- a/node_modules/express/node_modules/mkdirp/examples/pow.js.orig +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/express/node_modules/mkdirp/examples/pow.js.rej b/node_modules/express/node_modules/mkdirp/examples/pow.js.rej deleted file mode 100644 index 81e7f43..0000000 --- a/node_modules/express/node_modules/mkdirp/examples/pow.js.rej +++ /dev/null @@ -1,19 +0,0 @@ ---- examples/pow.js -+++ examples/pow.js -@@ -1,6 +1,15 @@ --var mkdirp = require('mkdirp').mkdirp; -+var mkdirp = require('../').mkdirp, -+ mkdirpSync = require('../').mkdirpSync; - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); -+ -+try { -+ mkdirpSync('/tmp/bar/foo/baz', 0755); -+ console.log('double pow!'); -+} -+catch (ex) { -+ console.log(ex); -+} \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/index.js b/node_modules/express/node_modules/mkdirp/index.js deleted file mode 100644 index 30e9600..0000000 --- a/node_modules/express/node_modules/mkdirp/index.js +++ /dev/null @@ -1,20 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -var exports = module.exports = function mkdirP (p, mode, f) { - var cb = f || function () {}; - p = path.resolve(p); - - var ps = path.normalize(p).split('/'); - path.exists(p, function (exists) { - if (exists) cb(null); - else mkdirP(ps.slice(0,-1).join('/'), mode, function (err) { - if (err && err.code !== 'EEXIST') cb(err) - else fs.mkdir(p, mode, function (err) { - if (err && err.code !== 'EEXIST') cb(err) - else cb() - }); - }); - }); -}; -exports.mkdirp = exports.mkdirP = module.exports; diff --git a/node_modules/express/node_modules/mkdirp/package.json b/node_modules/express/node_modules/mkdirp/package.json deleted file mode 100644 index f5ceb00..0000000 --- a/node_modules/express/node_modules/mkdirp/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name" : "mkdirp", - "description" : "Recursively mkdir, like `mkdir -p`", - "version" : "0.0.7", - "author" : "James Halliday (http://substack.net)", - "main" : "./index", - "keywords" : [ - "mkdir", - "directory" - ], - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-mkdirp.git" - }, - "scripts" : { - "test" : "node node_modules/tap/bin/tap.js test/*.js" - }, - "devDependencies" : { - "tap" : "0.0.x" - }, - "license" : "MIT/X11", - "engines": { "node": "*" } -} diff --git a/node_modules/express/node_modules/mkdirp/test/mkdirp.js b/node_modules/express/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/express/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/race.js b/node_modules/express/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/express/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/express/node_modules/mkdirp/test/rel.js b/node_modules/express/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/express/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/express/node_modules/qs/.gitmodules b/node_modules/express/node_modules/qs/.gitmodules deleted file mode 100644 index 49e31da..0000000 --- a/node_modules/express/node_modules/qs/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git -[submodule "support/should"] - path = support/should - url = git://github.com/visionmedia/should.js.git diff --git a/node_modules/express/node_modules/qs/.npmignore b/node_modules/express/node_modules/qs/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/express/node_modules/qs/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/express/node_modules/qs/.travis.yml b/node_modules/express/node_modules/qs/.travis.yml deleted file mode 100644 index 2c0a8f6..0000000 --- a/node_modules/express/node_modules/qs/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.4 \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/History.md b/node_modules/express/node_modules/qs/History.md deleted file mode 100644 index 3eaf7df..0000000 --- a/node_modules/express/node_modules/qs/History.md +++ /dev/null @@ -1,73 +0,0 @@ - -0.4.2 / 2012-02-08 -================== - - * Fixed: ensure objects are created when appropriate not arrays [aheckmann] - -0.4.1 / 2012-01-26 -================== - - * Fixed stringify()ing numbers. Closes #23 - -0.4.0 / 2011-11-21 -================== - - * Allow parsing of an existing object (for `bodyParser()`) [jackyz] - * Replaced expresso with mocha - -0.3.2 / 2011-11-08 -================== - - * Fixed global variable leak - -0.3.1 / 2011-08-17 -================== - - * Added `try/catch` around malformed uri components - * Add test coverage for Array native method bleed-though - -0.3.0 / 2011-07-19 -================== - - * Allow `array[index]` and `object[property]` syntaxes [Aria Stewart] - -0.2.0 / 2011-06-29 -================== - - * Added `qs.stringify()` [Cory Forsyth] - -0.1.0 / 2011-04-13 -================== - - * Added jQuery-ish array support - -0.0.7 / 2011-03-13 -================== - - * Fixed; handle empty string and `== null` in `qs.parse()` [dmit] - allows for convenient `qs.parse(url.parse(str).query)` - -0.0.6 / 2011-02-14 -================== - - * Fixed; support for implicit arrays - -0.0.4 / 2011-02-09 -================== - - * Fixed `+` as a space - -0.0.3 / 2011-02-08 -================== - - * Fixed case when right-hand value contains "]" - -0.0.2 / 2011-02-07 -================== - - * Fixed "=" presence in key - -0.0.1 / 2011-02-07 -================== - - * Initial release \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/Makefile b/node_modules/express/node_modules/qs/Makefile deleted file mode 100644 index e4df837..0000000 --- a/node_modules/express/node_modules/qs/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @./node_modules/.bin/mocha - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/Readme.md b/node_modules/express/node_modules/qs/Readme.md deleted file mode 100644 index db0d145..0000000 --- a/node_modules/express/node_modules/qs/Readme.md +++ /dev/null @@ -1,54 +0,0 @@ -# node-querystring - - query string parser for node supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others. - -## Installation - - $ npm install qs - -## Examples - -```js -var qs = require('qs'); - -qs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com'); -// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } } - -qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}) -// => user[name]=Tobi&user[email]=tobi%40learnboost.com -``` - -## Testing - -Install dev dependencies: - - $ npm install -d - -and execute: - - $ make test - -## License - -(The MIT License) - -Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/benchmark.js b/node_modules/express/node_modules/qs/benchmark.js deleted file mode 100644 index 97e2c93..0000000 --- a/node_modules/express/node_modules/qs/benchmark.js +++ /dev/null @@ -1,17 +0,0 @@ - -var qs = require('./'); - -var times = 100000 - , start = new Date - , n = times; - -console.log('times: %d', times); - -while (n--) qs.parse('foo=bar'); -console.log('simple: %dms', new Date - start); - -var start = new Date - , n = times; - -while (n--) qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log('nested: %dms', new Date - start); \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/examples.js b/node_modules/express/node_modules/qs/examples.js deleted file mode 100644 index 27617b7..0000000 --- a/node_modules/express/node_modules/qs/examples.js +++ /dev/null @@ -1,51 +0,0 @@ - -/** - * Module dependencies. - */ - -var qs = require('./'); - -var obj = qs.parse('foo'); -console.log(obj) - -var obj = qs.parse('foo=bar=baz'); -console.log(obj) - -var obj = qs.parse('users[]'); -console.log(obj) - -var obj = qs.parse('name=tj&email=tj@vision-media.ca'); -console.log(obj) - -var obj = qs.parse('users[]=tj&users[]=tobi&users[]=jane'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('users[][name][first]=tj&users[][name][last]=holowaychuk'); -console.log(obj) - -var obj = qs.parse('a=a&a=b&a=c'); -console.log(obj) - -var obj = qs.parse('user[tj]=tj&user[tj]=TJ'); -console.log(obj) - -var obj = qs.parse('user[names]=tj&user[names]=TJ&user[names]=Tyler'); -console.log(obj) - -var obj = qs.parse('user[name][first]=tj&user[name][first]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[1]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[]=TJ'); -console.log(obj) - -var obj = qs.parse('user[0]=tj&user[foo]=TJ'); -console.log(obj) - -var str = qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}); -console.log(str); \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/index.js b/node_modules/express/node_modules/qs/index.js deleted file mode 100644 index d177d20..0000000 --- a/node_modules/express/node_modules/qs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/querystring'); \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/lib/querystring.js b/node_modules/express/node_modules/qs/lib/querystring.js deleted file mode 100644 index 6c72712..0000000 --- a/node_modules/express/node_modules/qs/lib/querystring.js +++ /dev/null @@ -1,264 +0,0 @@ - -/*! - * querystring - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Library version. - */ - -exports.version = '0.4.2'; - -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; -} - -/** - * Parse the given str. - */ - -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - try{ - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch(e) { - // ignore - } - - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - - return merge(ret, key, val); - }, { base: {} }).base; -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '[]')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} diff --git a/node_modules/express/node_modules/qs/package.json b/node_modules/express/node_modules/qs/package.json deleted file mode 100644 index 68dd5a6..0000000 --- a/node_modules/express/node_modules/qs/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "qs", - "description": "querystring parser", - "version": "0.4.2", - "repository": { - "type" : "git", - "url" : "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*" - , "should": "*" - }, - "author": "TJ Holowaychuk (http://tjholowaychuk.com)", - "main": "index", - "engines": { "node": "*" } -} \ No newline at end of file diff --git a/node_modules/express/node_modules/qs/test/mocha.opts b/node_modules/express/node_modules/qs/test/mocha.opts deleted file mode 100644 index 521cbb2..0000000 --- a/node_modules/express/node_modules/qs/test/mocha.opts +++ /dev/null @@ -1,2 +0,0 @@ ---require should ---ui exports diff --git a/node_modules/express/node_modules/qs/test/parse.js b/node_modules/express/node_modules/qs/test/parse.js deleted file mode 100644 index f219e27..0000000 --- a/node_modules/express/node_modules/qs/test/parse.js +++ /dev/null @@ -1,167 +0,0 @@ - -/** - * Module dependencies. - */ - -var qs = require('../'); - -module.exports = { - 'test basics': function(){ - qs.parse('0=foo').should.eql({ '0': 'foo' }); - - qs.parse('foo=c++') - .should.eql({ foo: 'c ' }); - - qs.parse('a[>=]=23') - .should.eql({ a: { '>=': '23' }}); - - qs.parse('a[<=>]==23') - .should.eql({ a: { '<=>': '=23' }}); - - qs.parse('a[==]=23') - .should.eql({ a: { '==': '23' }}); - - qs.parse('foo') - .should.eql({ foo: '' }); - - qs.parse('foo=bar') - .should.eql({ foo: 'bar' }); - - qs.parse('foo%3Dbar=baz') - .should.eql({ foo: 'bar=baz' }); - - qs.parse(' foo = bar = baz ') - .should.eql({ ' foo ': ' bar = baz ' }); - - qs.parse('foo=bar=baz') - .should.eql({ foo: 'bar=baz' }); - - qs.parse('foo=bar&bar=baz') - .should.eql({ foo: 'bar', bar: 'baz' }); - - qs.parse('foo=bar&baz') - .should.eql({ foo: 'bar', baz: '' }); - - qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World') - .should.eql({ - cht: 'p3' - , chd: 't:60,40' - , chs: '250x100' - , chl: 'Hello|World' - }); - }, - - 'test nesting': function(){ - qs.parse('ops[>=]=25') - .should.eql({ ops: { '>=': '25' }}); - - qs.parse('user[name]=tj') - .should.eql({ user: { name: 'tj' }}); - - qs.parse('user[name][first]=tj&user[name][last]=holowaychuk') - .should.eql({ user: { name: { first: 'tj', last: 'holowaychuk' }}}); - }, - - 'test escaping': function(){ - qs.parse('foo=foo%20bar') - .should.eql({ foo: 'foo bar' }); - }, - - 'test arrays': function(){ - qs.parse('images[]') - .should.eql({ images: [] }); - - qs.parse('user[]=tj') - .should.eql({ user: ['tj'] }); - - qs.parse('user[]=tj&user[]=tobi&user[]=jane') - .should.eql({ user: ['tj', 'tobi', 'jane'] }); - - qs.parse('user[names][]=tj&user[names][]=tyler') - .should.eql({ user: { names: ['tj', 'tyler'] }}); - - qs.parse('user[names][]=tj&user[names][]=tyler&user[email]=tj@vision-media.ca') - .should.eql({ user: { names: ['tj', 'tyler'], email: 'tj@vision-media.ca' }}); - - qs.parse('items=a&items=b') - .should.eql({ items: ['a', 'b'] }); - - qs.parse('user[names]=tj&user[names]=holowaychuk&user[names]=TJ') - .should.eql({ user: { names: ['tj', 'holowaychuk', 'TJ'] }}); - - qs.parse('user[name][first]=tj&user[name][first]=TJ') - .should.eql({ user: { name: { first: ['tj', 'TJ'] }}}); - - var o = qs.parse('existing[fcbaebfecc][name][last]=tj') - o.should.eql({ existing: { 'fcbaebfecc': { name: { last: 'tj' }}}}) - Array.isArray(o.existing).should.be.false; - }, - - 'test right-hand brackets': function(){ - qs.parse('pets=["tobi"]') - .should.eql({ pets: '["tobi"]' }); - - qs.parse('operators=[">=", "<="]') - .should.eql({ operators: '[">=", "<="]' }); - - qs.parse('op[>=]=[1,2,3]') - .should.eql({ op: { '>=': '[1,2,3]' }}); - - qs.parse('op[>=]=[1,2,3]&op[=]=[[[[1]]]]') - .should.eql({ op: { '>=': '[1,2,3]', '=': '[[[[1]]]]' }}); - }, - - 'test duplicates': function(){ - qs.parse('items=bar&items=baz&items=raz') - .should.eql({ items: ['bar', 'baz', 'raz'] }); - }, - - 'test empty': function(){ - qs.parse('').should.eql({}); - qs.parse(undefined).should.eql({}); - qs.parse(null).should.eql({}); - }, - - 'test arrays with indexes': function(){ - qs.parse('foo[0]=bar&foo[1]=baz').should.eql({ foo: ['bar', 'baz'] }); - qs.parse('foo[1]=bar&foo[0]=baz').should.eql({ foo: ['baz', 'bar'] }); - qs.parse('foo[base64]=RAWR').should.eql({ foo: { base64: 'RAWR' }}); - qs.parse('foo[64base]=RAWR').should.eql({ foo: { '64base': 'RAWR' }}); - }, - - 'test arrays becoming objects': function(){ - qs.parse('foo[0]=bar&foo[bad]=baz').should.eql({ foo: { 0: "bar", bad: "baz" }}); - qs.parse('foo[bad]=baz&foo[0]=bar').should.eql({ foo: { 0: "bar", bad: "baz" }}); - }, - - 'test bleed-through of Array native properties/methods': function(){ - Array.prototype.protoProperty = true; - Array.prototype.protoFunction = function () {}; - qs.parse('foo=bar').should.eql({ foo: 'bar' }); - }, - - 'test malformed uri': function(){ - qs.parse('{%:%}').should.eql({ '{%:%}': '' }); - qs.parse('foo=%:%}').should.eql({ 'foo': '%:%}' }); - }, - - 'test semi-parsed': function(){ - qs.parse({ 'user[name]': 'tobi' }) - .should.eql({ user: { name: 'tobi' }}); - - qs.parse({ 'user[name]': 'tobi', 'user[email][main]': 'tobi@lb.com' }) - .should.eql({ user: { name: 'tobi', email: { main: 'tobi@lb.com' } }}); - } - - // 'test complex': function(){ - // qs.parse('users[][name][first]=tj&users[foo]=bar') - // .should.eql({ - // users: [ { name: 'tj' }, { name: 'tobi' }, { foo: 'bar' }] - // }); - // - // qs.parse('users[][name][first]=tj&users[][name][first]=tobi') - // .should.eql({ - // users: [ { name: 'tj' }, { name: 'tobi' }] - // }); - // } -}; diff --git a/node_modules/express/node_modules/qs/test/stringify.js b/node_modules/express/node_modules/qs/test/stringify.js deleted file mode 100644 index c2195cb..0000000 --- a/node_modules/express/node_modules/qs/test/stringify.js +++ /dev/null @@ -1,103 +0,0 @@ - -/** - * Module dependencies. - */ - -var qs = require('../') - , should = require('should') - , str_identities = { - 'basics': [ - { str: 'foo=bar', obj: {'foo' : 'bar'}}, - { str: 'foo=%22bar%22', obj: {'foo' : '\"bar\"'}}, - { str: 'foo=', obj: {'foo': ''}}, - { str: 'foo=1&bar=2', obj: {'foo' : '1', 'bar' : '2'}}, - { str: 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj: {'my weird field': "q1!2\"'w$5&7/z8)?"}}, - { str: 'foo%3Dbaz=bar', obj: {'foo=baz': 'bar'}}, - { str: 'foo=bar&bar=baz', obj: {foo: 'bar', bar: 'baz'}} - ], - 'escaping': [ - { str: 'foo=foo%20bar', obj: {foo: 'foo bar'}}, - { str: 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj: { - cht: 'p3' - , chd: 't:60,40' - , chs: '250x100' - , chl: 'Hello|World' - }} - ], - 'nested': [ - { str: 'foo[]=bar&foo[]=quux', obj: {'foo' : ['bar', 'quux']}}, - { str: 'foo[]=bar', obj: {foo: ['bar']}}, - { str: 'foo[]=1&foo[]=2', obj: {'foo' : ['1', '2']}}, - { str: 'foo=bar&baz[]=1&baz[]=2&baz[]=3', obj: {'foo' : 'bar', 'baz' : ['1', '2', '3']}}, - { str: 'foo[]=bar&baz[]=1&baz[]=2&baz[]=3', obj: {'foo' : ['bar'], 'baz' : ['1', '2', '3']}}, - { str: 'x[y][z]=1', obj: {'x' : {'y' : {'z' : '1'}}}}, - { str: 'x[y][z][]=1', obj: {'x' : {'y' : {'z' : ['1']}}}}, - { str: 'x[y][z]=2', obj: {'x' : {'y' : {'z' : '2'}}}}, - { str: 'x[y][z][]=1&x[y][z][]=2', obj: {'x' : {'y' : {'z' : ['1', '2']}}}}, - { str: 'x[y][][z]=1', obj: {'x' : {'y' : [{'z' : '1'}]}}}, - { str: 'x[y][][z][]=1', obj: {'x' : {'y' : [{'z' : ['1']}]}}}, - { str: 'x[y][][z]=1&x[y][][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'w' : '2'}]}}}, - { str: 'x[y][][v][w]=1', obj: {'x' : {'y' : [{'v' : {'w' : '1'}}]}}}, - { str: 'x[y][][z]=1&x[y][][v][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'v' : {'w' : '2'}}]}}}, - { str: 'x[y][][z]=1&x[y][][z]=2', obj: {'x' : {'y' : [{'z' : '1'}, {'z' : '2'}]}}}, - { str: 'x[y][][z]=1&x[y][][w]=a&x[y][][z]=2&x[y][][w]=3', obj: {'x' : {'y' : [{'z' : '1', 'w' : 'a'}, {'z' : '2', 'w' : '3'}]}}}, - { str: 'user[name][first]=tj&user[name][last]=holowaychuk', obj: { user: { name: { first: 'tj', last: 'holowaychuk' }}}} - ], - 'errors': [ - { obj: 'foo=bar', message: 'stringify expects an object' }, - { obj: ['foo', 'bar'], message: 'stringify expects an object' } - ], - 'numbers': [ - { str: 'limit[]=1&limit[]=2&limit[]=3', obj: { limit: [1, 2, '3'] }}, - { str: 'limit=1', obj: { limit: 1 }} - ] - }; - - -// Assert error -function err(fn, msg){ - var err; - try { - fn(); - } catch (e) { - should.equal(e.message, msg); - return; - } - throw new Error('no exception thrown, expected "' + msg + '"'); -} - -function test(type) { - var str, obj; - for (var i = 0; i < str_identities[type].length; i++) { - str = str_identities[type][i].str; - obj = str_identities[type][i].obj; - qs.stringify(obj).should.eql(str); - } -} - -module.exports = { - 'test basics': function() { - test('basics'); - }, - - 'test escaping': function() { - test('escaping'); - }, - - 'test nested': function() { - test('nested'); - }, - - 'test numbers': function(){ - test('numbers'); - }, - - 'test errors': function() { - var obj, message; - for (var i = 0; i < str_identities['errors'].length; i++) { - message = str_identities['errors'][i].message; - obj = str_identities['errors'][i].obj; - err(function(){ qs.stringify(obj) }, message); - } - } -}; \ No newline at end of file diff --git a/node_modules/express/package.json b/node_modules/express/package.json deleted file mode 100644 index b36433c..0000000 --- a/node_modules/express/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "express", - "description": "Sinatra inspired web development framework", - "version": "2.5.1", - "author": "TJ Holowaychuk ", - "contributors": [ - { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, - { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - { "name": "Ciaran Jessup", "email": "ciaranj@gmail.com" }, - { "name": "Guillermo Rauch", "email": "rauchg@gmail.com" } - ], - "dependencies": { - "connect": "1.8.x", - "mime": ">= 0.0.1", - "qs": ">= 0.3.1", - "mkdirp": "0.0.7" - }, - "devDependencies": { - "connect-form": "0.2.1", - "ejs": "0.4.2", - "expresso": "0.9.2", - "hamljs": "0.5.1", - "jade": "0.16.2", - "stylus": "0.13.0", - "should": "0.3.2", - "express-messages": "0.0.2", - "node-markdown": ">= 0.0.1", - "connect-redis": ">= 0.0.1" - }, - "keywords": ["framework", "sinatra", "web", "rest", "restful"], - "repository": "git://github.com/visionmedia/express", - "main": "index", - "bin": { "express": "./bin/express" }, - "scripts": { - "test": "make test", - "prepublish" : "npm prune" - }, - "engines": { "node": ">= 0.4.1 < 0.7.0" } -} \ No newline at end of file diff --git a/node_modules/express/testing/foo/app.js b/node_modules/express/testing/foo/app.js deleted file mode 100644 index 7574676..0000000 --- a/node_modules/express/testing/foo/app.js +++ /dev/null @@ -1,35 +0,0 @@ - -/** - * Module dependencies. - */ - -var express = require('express') - , routes = require('./routes') - -var app = module.exports = express.createServer(); - -// Configuration - -app.configure(function(){ - app.set('views', __dirname + '/views'); - app.set('view engine', 'jade'); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(express.static(__dirname + '/public')); -}); - -app.configure('development', function(){ - app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); -}); - -app.configure('production', function(){ - app.use(express.errorHandler()); -}); - -// Routes - -app.get('/', routes.index); - -app.listen(3000); -console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); diff --git a/node_modules/express/testing/foo/package.json b/node_modules/express/testing/foo/package.json deleted file mode 100644 index dd54123..0000000 --- a/node_modules/express/testing/foo/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "application-name" - , "version": "0.0.1" - , "private": true - , "dependencies": { - "express": "2.5.0" - , "jade": ">= 0.0.1" - } -} \ No newline at end of file diff --git a/node_modules/express/testing/foo/public/stylesheets/style.css b/node_modules/express/testing/foo/public/stylesheets/style.css deleted file mode 100644 index 30e047d..0000000 --- a/node_modules/express/testing/foo/public/stylesheets/style.css +++ /dev/null @@ -1,8 +0,0 @@ -body { - padding: 50px; - font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; -} - -a { - color: #00B7FF; -} \ No newline at end of file diff --git a/node_modules/express/testing/foo/routes/index.js b/node_modules/express/testing/foo/routes/index.js deleted file mode 100644 index 0b2205c..0000000 --- a/node_modules/express/testing/foo/routes/index.js +++ /dev/null @@ -1,10 +0,0 @@ - -/* - * GET home page. - */ - -exports.index = function(req, res){ - res.writeHead(200); - req.doesnotexist(); - // res.render('index', { title: 'Express' }) -}; \ No newline at end of file diff --git a/node_modules/express/testing/foo/views/index.jade b/node_modules/express/testing/foo/views/index.jade deleted file mode 100644 index c9c35fa..0000000 --- a/node_modules/express/testing/foo/views/index.jade +++ /dev/null @@ -1,2 +0,0 @@ -h1= title -p Welcome to #{title} \ No newline at end of file diff --git a/node_modules/express/testing/foo/views/layout.jade b/node_modules/express/testing/foo/views/layout.jade deleted file mode 100644 index 1a36941..0000000 --- a/node_modules/express/testing/foo/views/layout.jade +++ /dev/null @@ -1,6 +0,0 @@ -!!! -html - head - title= title - link(rel='stylesheet', href='/stylesheets/style.css') - body!= body \ No newline at end of file diff --git a/node_modules/express/testing/index.js b/node_modules/express/testing/index.js deleted file mode 100644 index 3c5185d..0000000 --- a/node_modules/express/testing/index.js +++ /dev/null @@ -1,43 +0,0 @@ - -/** - * Module dependencies. - */ - -var express = require('../') - , http = require('http') - , connect = require('connect'); - -var app = express.createServer(); - -app.get('/', function(req, res){ - req.foo(); - res.send('test'); -}); - -// app.set('views', __dirname + '/views'); -// app.set('view engine', 'jade'); -// -// app.configure(function(){ -// app.use(function(req, res, next){ -// debugger -// res.write('first'); -// console.error('first'); -// next(); -// }); -// -// app.use(app.router); -// -// app.use(function(req, res, next){ -// console.error('last'); -// res.end('last'); -// }); -// }); -// -// app.get('/', function(req, res, next){ -// console.error('middle'); -// res.write(' route '); -// next(); -// }); - -app.listen(3000); -console.log('listening on port 3000'); \ No newline at end of file diff --git a/node_modules/express/testing/public/test.txt b/node_modules/express/testing/public/test.txt deleted file mode 100644 index cb9a165..0000000 --- a/node_modules/express/testing/public/test.txt +++ /dev/null @@ -1,2971 +0,0 @@ -foo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -bazfoo -bar -baz \ No newline at end of file diff --git a/node_modules/express/testing/views/page.html b/node_modules/express/testing/views/page.html deleted file mode 100644 index 4ff9827..0000000 --- a/node_modules/express/testing/views/page.html +++ /dev/null @@ -1 +0,0 @@ -p register test \ No newline at end of file diff --git a/node_modules/express/testing/views/page.jade b/node_modules/express/testing/views/page.jade deleted file mode 100644 index 9c3f888..0000000 --- a/node_modules/express/testing/views/page.jade +++ /dev/null @@ -1,3 +0,0 @@ -html - body - h1 test \ No newline at end of file diff --git a/node_modules/express/testing/views/test.md b/node_modules/express/testing/views/test.md deleted file mode 100644 index 9139ff4..0000000 --- a/node_modules/express/testing/views/test.md +++ /dev/null @@ -1 +0,0 @@ -testing _some_ markdown \ No newline at end of file diff --git a/node_modules/express/testing/views/user/index.jade b/node_modules/express/testing/views/user/index.jade deleted file mode 100644 index 1b66a4f..0000000 --- a/node_modules/express/testing/views/user/index.jade +++ /dev/null @@ -1 +0,0 @@ -p user page \ No newline at end of file diff --git a/node_modules/express/testing/views/user/list.jade b/node_modules/express/testing/views/user/list.jade deleted file mode 100644 index ed2b471..0000000 --- a/node_modules/express/testing/views/user/list.jade +++ /dev/null @@ -1 +0,0 @@ -p user list page \ No newline at end of file diff --git a/node_modules/hiredis/.lock-wscript b/node_modules/hiredis/.lock-wscript deleted file mode 100644 index 92339b2..0000000 --- a/node_modules/hiredis/.lock-wscript +++ /dev/null @@ -1,9 +0,0 @@ -argv = ['/usr/local/bin/node-waf', 'configure', 'build'] -blddir = '/Users/v/code/redis-proxy/node_modules/hiredis/build' -commands = {'dist': 0, 'configure': True, 'distcheck': 0, 'install': 0, 'build': True, 'clean': 0, 'distclean': 0, 'check': 0, 'uninstall': 0} -cwd = '/Users/v/code/redis-proxy/node_modules/hiredis' -environ = {'npm_config_color': 'true', 'rvm_hook': '', 'rvm_niceness': '', 'rvm_version': '1.10.2', 'npm_config_searchopts': '', 'LC_CTYPE': '', 'npm_config_group': '20', 'npm_package_homepage': 'http://github.com/pietern/hiredis-node', 'npm_config_browser': 'open', 'npm_config_global': '', 'npm_package_dist_shasum': '22d7a98e1215de3771c2cb65ee84a69535f44da3', 'SHELL': '/bin/zsh', '_first': '1', 'SECURITYSESSIONID': '186a5', 'npm_config_pre': '', 'MFLAGS': '', 'npm_config_logfd': '2', 'npm_config_tmp': '/var/folders/yj/c5zd0xk958n03b8nn1czpy_m0000gn/T', 'npm_package_engines_node': '*', 'npm_config_argv': '{"remain":[],"cooked":["install"],"original":["install"]}', 'npm_package_scripts_preinstall': 'make || gmake', 'npm_config_init_version': '0.0.0', 'npm_lifecycle_event': 'preinstall', 'rvm_ruby_mode': '', 'npm_config_init_author_name': '', 'npm_config_yes': '', 'rvm_install_on_use_flag': '', 'npm_config_usage': '', 'npm_package_description': 'Wrapper for reply processing code in hiredis', 'npm_config_shell': '/bin/zsh', 'npm_config_ignore': '', 'rvm_proxy': '', 'npm_config_ca': '"-----BEGIN CERTIFICATE-----\\nMIIChzCCAfACCQDauvz/KHp8ejANBgkqhkiG9w0BAQUFADCBhzELMAkGA1UEBhMC\\nVVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMQwwCgYDVQQKEwNucG0x\\nIjAgBgNVBAsTGW5wbSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxDjAMBgNVBAMTBW5w\\nbUNBMRcwFQYJKoZIhvcNAQkBFghpQGl6cy5tZTAeFw0xMTA5MDUwMTQ3MTdaFw0y\\nMTA5MDIwMTQ3MTdaMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEDAOBgNV\\nBAcTB09ha2xhbmQxDDAKBgNVBAoTA25wbTEiMCAGA1UECxMZbnBtIENlcnRpZmlj\\nYXRlIEF1dGhvcml0eTEOMAwGA1UEAxMFbnBtQ0ExFzAVBgkqhkiG9w0BCQEWCGlA\\naXpzLm1lMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLI4tIqPpRW+ACw9GE\\nOgBlJZwK5f8nnKCLK629Pv5yJpQKs3DENExAyOgDcyaF0HD0zk8zTp+ZsLaNdKOz\\nGn2U181KGprGKAXP6DU6ByOJDWmTlY6+Ad1laYT0m64fERSpHw/hjD3D+iX4aMOl\\ny0HdbT5m1ZGh6SJz3ZqxavhHLQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAC4ySDbC\\nl7W1WpLmtLGEQ/yuMLUf6Jy/vr+CRp4h+UzL+IQpCv8FfxsYE7dhf/bmWTEupBkv\\nyNL18lipt2jSvR3v6oAHAReotvdjqhxddpe5Holns6EQd1/xEZ7sB1YhQKJtvUrl\\nZNufy1Jf1r0ldEGeA+0ISck7s+xSh9rQD2Op\\n-----END CERTIFICATE-----"', 'npm_config_globalconfig': '/usr/local/etc/npmrc', 'rvm_gemstone_package_file': '', 'npm_config_parseable': '', 'rvm_path': '/Users/v/.rvm', 'escape_flag': '1', 'npm_config_userignorefile': '/Users/v/.npmignore', 'USER': 'v', 'npm_package_author_name': 'Pieter Noordhuis', 'npm_config_proxy': '', 'SHLVL': '2', 'npm_config_init_author_url': '', 'npm_config_prefix': '/usr/local', 'npm_config_cache': '/Users/v/.npm', 'EDITOR': '/Users/v/bin/mate -w', 'rvm_uname': 'Darwin', 'rvm_script_name': '', 'npm_package_directories_lib': '.', 'rvm_ruby_make_install': '', 'npm_config_depth': 'null', 'npm_config_logprefix': 'true', 'npm_config_umask': '022', 'npm_config_long': '', 'npm_config_editor': '/Users/v/bin/mate -w', 'rvm_nightly_flag': '', 'TMPDIR': '/var/folders/yj/c5zd0xk958n03b8nn1czpy_m0000gn/T/', 'npm_config_npat': '', 'GREP_OPTIONS': '--color=auto', 'rvm_alias_expanded': '', 'npm_config_searchsort': 'name', 'npm_package_author_email': 'pcnoordhuis@gmail.com', 'npm_lifecycle_script': 'make || gmake', '__array_start': '1', 'PAGER': 'less', 'COMMAND_MODE': 'unix2003', 'npm_config_git': 'git', 'TERM_PROGRAM_VERSION': '303', 'npm_config_rollback': 'true', 'rvm_gemstone_url': '', 'HOME': '/Users/v', 'DISPLAY': '/tmp/launch-Mj5chS/org.x:0', 'TERM_PROGRAM': 'Apple_Terminal', 'Apple_PubSub_Socket_Render': '/tmp/launch-qDK7Rc/Render', 'npm_config_save': '', 'npm_config_registry': 'https://registry.npmjs.org/', 'npm_config_unicode': 'true', 'npm_config_production': '', 'npm_config_message': '%s', 'rvm_sdk': '', '_': '/usr/bin/make', 'rvm_quiet_flag': '', 'npm_config_searchexclude': '', 'npm_config_loglevel': 'http', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'rvm_prefix': '/Users/v', 'npm_config_strict_ssl': 'true', 'TERM_SESSION_ID': 'C45BAAF7-83D9-4524-8375-9422342EBC93', 'npm_package_main': 'hiredis', 'npm_config_tag': 'latest', '_second': '2', 'npm_config_globalignorefile': '/usr/local/etc/npmignore', '__CF_USER_TEXT_ENCODING': '0x1F5:0:0', 'MAKELEVEL': '1', 'npm_config_npaturl': 'http://npat.npmjs.org/', 'rvm_docs_type': '', 'npm_config_force': '', 'LOGNAME': 'v', 'npm_config_user': '', 'npm_config_link': '', 'npm_package_name': 'hiredis', 'npm_config_userconfig': '/Users/v/.npmrc', 'rvm_ruby_sha': '', 'npm_config_dev': '', 'npm_config_rebuild_bundle': 'true', 'npm_config_version': '', 'npm_config_username': '', 'PATH': '/Users/v/code/redis-proxy/node_modules/hiredis/node_modules/.bin:/Users/v/code/redis-proxy/node_modules/.bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin::/opt/node/bin:/Users/v/.rvm/bin', 'npm_config_coverage': '', 'SSH_AGENT_PID': '381', 'npm_config_proprietary_attribs': 'true', 'npm_package_scripts_test': 'node test/reader.js', 'npm_config_onload_script': '', 'VERSIONER_PYTHON_VERSION': '2.7', 'npm_config_always_auth': '', 'npm_config_bindist': '0.6-ares1.7.5-DEV-evundefined-openssl1.0.0g-v83.6.6.20-darwin-x64-11.3.0', 'MAKEFLAGS': '', 'GREP_COLOR': '1;32', 'rvm_bin_path': '/Users/v/.rvm/bin', 'npm_config_viewer': 'man', 'rvm_ruby_file': '', 'npm_config_showlevel': '2', 'npm_config_unsafe_perm': 'true', 'SSH_AUTH_SOCK': '/tmp/ssh-bpRLATv0XD/agent.379', 'TERM': 'xterm-256color', 'rvm_ruby_make': '', 'npm_package_version': '0.1.14', 'npm_config_https_proxy': '', 'npm_config_node_version': '0.6.10', 'npm_config_init_author_email': '', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', 'rvm_wrapper_name': '', 'rvm_tar': 'tar', 'npm_config_outfd': '1', 'npm_config_bin_publish': '', 'Apple_Ubiquity_Message': '/tmp/launch-fhsgbV/Apple_Ubiquity_Message', 'PWD': '/Users/v/code/redis-proxy/node_modules/hiredis', 'rvm_silent_flag': '', 'npm_config_description': 'true'} -files = [] -hash = 0 -options = {'compile_targets': None, 'force': False, 'verbose': 0, 'nocache': False, 'progress_bar': 0, 'destdir': '', 'keep': False, 'zones': '', 'blddir': '', 'prefix': '/usr/local/', 'jobs': 4, 'srcdir': '', 'check_cxx_compiler': 'g++'} -srcdir = '/Users/v/code/redis-proxy/node_modules/hiredis' diff --git a/node_modules/hiredis/Makefile b/node_modules/hiredis/Makefile deleted file mode 100644 index 422d93b..0000000 --- a/node_modules/hiredis/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -all: - cd deps/hiredis && $(MAKE) static - node-waf configure build - -clean: - cd deps/hiredis && $(MAKE) clean - rm -rf build - -temp: - rm -rf tmp/hiredis - mkdir -p tmp/hiredis - cp -r README *.{cc,h,js*} wscript Makefile deps test tmp/hiredis - cd tmp/hiredis && rm -rf deps/*/.git* deps/*/*.o deps/hiredis/libhiredis.* - -package: temp - cd tmp && tar -czvf hiredis.tgz hiredis diff --git a/node_modules/hiredis/README b/node_modules/hiredis/README deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/hiredis/bench.js b/node_modules/hiredis/bench.js deleted file mode 100644 index 01433ca..0000000 --- a/node_modules/hiredis/bench.js +++ /dev/null @@ -1,121 +0,0 @@ -var hiredis = require("./hiredis"), - num_clients = 10, - active_clients = 0, - pipeline = 0, - num_requests = parseInt(process.argv[2]) || 20000, - issued_requests = 0, - test_start; - -var tests = []; -tests.push({ - descr: "PING", - command: ["PING"] -}); -tests.push({ - descr: "SET", - command: ["SET", "foo", "bar"] -}); -tests.push({ - descr: "GET", - command: ["GET", "foo"] -}); -tests.push({ - descr: "LPUSH 8 bytes", - command: ["LPUSH", "mylist-8", new Buffer(Array(8).join("-"))] -}); -tests.push({ - descr: "LPUSH 64 bytes", - command: ["LPUSH", "mylist-64", new Buffer(Array(64).join("-"))] -}); -tests.push({ - descr: "LPUSH 512 bytes", - command: ["LPUSH", "mylist-512", new Buffer(Array(512).join("-"))] -}); -tests.push({ - descr: "LRANGE 10 elements, 8 bytes", - command: ["LRANGE", "mylist-8", "0", "9"] -}); -tests.push({ - descr: "LRANGE 100 elements, 8 bytes", - command: ["LRANGE", "mylist-8", "0", "99"] -}); -tests.push({ - descr: "LRANGE 100 elements, 64 bytes", - command: ["LRANGE", "mylist-64", "0", "99"] -}); -tests.push({ - descr: "LRANGE 100 elements, 512 bytes", - command: ["LRANGE", "mylist-512", "0", "99"] -}); - -function call(client, test) { - client.on("reply", function() { - if (issued_requests < num_requests) { - request(); - } else { - client.end(); - if (--active_clients == 0) - done(test); - } - }); - - function request() { - issued_requests++; - client.write.apply(client,test.command); - }; - - request(); -} - -function done(test) { - var time = (new Date - test_start); - var op_rate = (num_requests/(time/1000.0)).toFixed(2); - console.log(test.descr + ": " + op_rate + " ops/sec"); - next(); -} - -function concurrent_test(test) { - var i = num_clients; - var client; - - issued_requests = 0; - test_start = new Date; - while(i-- && issued_requests < num_requests) { - active_clients++; - client = hiredis.createConnection(); - call(client, test); - } -} - -function pipelined_test(test) { - var client = hiredis.createConnection(); - var received_replies = 0; - - issued_requests = 0; - while (issued_requests < num_requests) { - issued_requests++; - client.write.apply(client,test.command); - } - - test_start = new Date; - client.on("reply", function() { - if (++received_replies == num_requests) { - client.end(); - done(test); - } - }); -} - -function next() { - var test = tests.shift(); - if (test) { - if (pipeline) { - pipelined_test(test); - } else { - concurrent_test(test); - } - } -} - -next(); - diff --git a/node_modules/hiredis/build/.wafpickle-7 b/node_modules/hiredis/build/.wafpickle-7 deleted file mode 100644 index 0bd5c60..0000000 Binary files a/node_modules/hiredis/build/.wafpickle-7 and /dev/null differ diff --git a/node_modules/hiredis/build/Release/hiredis.node b/node_modules/hiredis/build/Release/hiredis.node deleted file mode 100755 index 7318f50..0000000 Binary files a/node_modules/hiredis/build/Release/hiredis.node and /dev/null differ diff --git a/node_modules/hiredis/build/Release/hiredis_1.o b/node_modules/hiredis/build/Release/hiredis_1.o deleted file mode 100644 index 78c3b5e..0000000 Binary files a/node_modules/hiredis/build/Release/hiredis_1.o and /dev/null differ diff --git a/node_modules/hiredis/build/Release/reader_1.o b/node_modules/hiredis/build/Release/reader_1.o deleted file mode 100644 index 725ba58..0000000 Binary files a/node_modules/hiredis/build/Release/reader_1.o and /dev/null differ diff --git a/node_modules/hiredis/build/c4che/Release.cache.py b/node_modules/hiredis/build/c4che/Release.cache.py deleted file mode 100644 index 9ec1ac6..0000000 --- a/node_modules/hiredis/build/c4che/Release.cache.py +++ /dev/null @@ -1,50 +0,0 @@ -AR = '/usr/bin/ar' -ARFLAGS = 'rcs' -CCFLAGS = ['-g'] -CCFLAGS_MACBUNDLE = ['-fPIC'] -CCFLAGS_NODE = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64'] -CC_VERSION = ('4', '2', '1') -COMPILER_CXX = 'g++' -CPP = '/usr/bin/cpp' -CPPFLAGS_NODE = ['-D_GNU_SOURCE'] -CPPPATH_NODE = '/usr/local/include/node' -CPPPATH_ST = '-I%s' -CXX = ['/usr/bin/g++'] -CXXDEFINES_ST = '-D%s' -CXXFLAGS = ['-g', '-Wall', '-O3'] -CXXFLAGS_DEBUG = ['-g'] -CXXFLAGS_NODE = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64'] -CXXFLAGS_RELEASE = ['-O2'] -CXXLNK_SRC_F = '' -CXXLNK_TGT_F = ['-o', ''] -CXX_NAME = 'gcc' -CXX_SRC_F = '' -CXX_TGT_F = ['-c', '-o', ''] -DEST_CPU = 'x86_64' -DEST_OS = 'darwin' -FULLSTATIC_MARKER = '-static' -LIBDIR = '/Users/v/.node_libraries' -LIBPATH_HIREDIS = '../deps/hiredis' -LIBPATH_NODE = '/usr/local/lib' -LIBPATH_ST = '-L%s' -LIB_HIREDIS = 'hiredis' -LIB_ST = '-l%s' -LINKFLAGS_MACBUNDLE = ['-bundle', '-undefined', 'dynamic_lookup'] -LINK_CXX = ['/usr/bin/g++'] -NODE_PATH = '/Users/v/.node_libraries' -PREFIX = '/usr/local' -PREFIX_NODE = '/usr/local' -RANLIB = '/usr/bin/ranlib' -RPATH_ST = '-Wl,-rpath,%s' -SHLIB_MARKER = '' -SONAME_ST = '' -STATICLIBPATH_ST = '-L%s' -STATICLIB_MARKER = '' -STATICLIB_ST = '-l%s' -macbundle_PATTERN = '%s.bundle' -program_PATTERN = '%s' -shlib_CXXFLAGS = ['-fPIC', '-compatibility_version', '1', '-current_version', '1'] -shlib_LINKFLAGS = ['-dynamiclib'] -shlib_PATTERN = 'lib%s.dylib' -staticlib_LINKFLAGS = [] -staticlib_PATTERN = 'lib%s.a' diff --git a/node_modules/hiredis/build/c4che/build.config.py b/node_modules/hiredis/build/c4che/build.config.py deleted file mode 100644 index 55cf008..0000000 --- a/node_modules/hiredis/build/c4che/build.config.py +++ /dev/null @@ -1,2 +0,0 @@ -version = 0x105016 -tools = [{'tool': 'ar', 'tooldir': None, 'funs': None}, {'tool': 'cxx', 'tooldir': None, 'funs': None}, {'tool': 'gxx', 'tooldir': None, 'funs': None}, {'tool': 'compiler_cxx', 'tooldir': None, 'funs': None}, {'tool': 'osx', 'tooldir': None, 'funs': None}, {'tool': 'node_addon', 'tooldir': None, 'funs': None}] diff --git a/node_modules/hiredis/build/config.log b/node_modules/hiredis/build/config.log deleted file mode 100644 index 8a4da49..0000000 --- a/node_modules/hiredis/build/config.log +++ /dev/null @@ -1,44 +0,0 @@ -# project noname (1.0) configured on Thu Feb 23 00:07:12 2012 by -# waf 1.5.16 (abi 7, python 20701f0 on darwin) -# using /usr/local/bin/node-waf configure build -# - ----------------------------------------- -Setting srcdir to -/Users/v/code/redis-proxy/node_modules/hiredis - ----------------------------------------- -Setting blddir to -/Users/v/code/redis-proxy/node_modules/hiredis/build - ----------------------------------------- -Checking for program g++ or c++ - find program=['g++', 'c++'] paths=[] var='CXX' - -> '/usr/bin/g++' - ----------------------------------------- -Checking for program cpp - find program=['cpp'] paths=[] var='CPP' - -> '/usr/bin/cpp' - ----------------------------------------- -Checking for program ar - find program=['ar'] paths=[] var='AR' - -> '/usr/bin/ar' - ----------------------------------------- -Checking for program ranlib - find program=['ranlib'] paths=[] var='RANLIB' - -> '/usr/bin/ranlib' - ----------------------------------------- -Checking for g++ -ok - ----------------------------------------- -Checking for node path -not found - ----------------------------------------- -Checking for node prefix -ok /usr/local diff --git a/node_modules/hiredis/deps/hiredis/CHANGELOG.md b/node_modules/hiredis/deps/hiredis/CHANGELOG.md deleted file mode 100644 index d41db8a..0000000 --- a/node_modules/hiredis/deps/hiredis/CHANGELOG.md +++ /dev/null @@ -1,16 +0,0 @@ -### 0.10.1 - -* Makefile overhaul. Important to check out if you override one or more - variables using environment variables or via arguments to the "make" tool. - -* Issue #45: Fix potential memory leak for a multi bulk reply with 0 elements - being created by the default reply object functions. - -* Issue #43: Don't crash in an asynchronous context when Redis returns an error - reply after the connection has been made (this happens when the maximum - number of connections is reached). - -### 0.10.0 - -* See commit log. - diff --git a/node_modules/hiredis/deps/hiredis/COPYING b/node_modules/hiredis/deps/hiredis/COPYING deleted file mode 100644 index a5fc973..0000000 --- a/node_modules/hiredis/deps/hiredis/COPYING +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2009-2011, Salvatore Sanfilippo -Copyright (c) 2010-2011, Pieter Noordhuis - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of Redis nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/hiredis/deps/hiredis/Makefile b/node_modules/hiredis/deps/hiredis/Makefile deleted file mode 100644 index 57f057e..0000000 --- a/node_modules/hiredis/deps/hiredis/Makefile +++ /dev/null @@ -1,148 +0,0 @@ -# Hiredis Makefile -# Copyright (C) 2010-2011 Salvatore Sanfilippo -# Copyright (C) 2010-2011 Pieter Noordhuis -# This file is released under the BSD license, see the COPYING file - -OBJ=net.o hiredis.o sds.o async.o -BINS=hiredis-example hiredis-test -LIBNAME=libhiredis - -HIREDIS_MAJOR=0 -HIREDIS_MINOR=10 - -# Fallback to gcc when $CC is not in $PATH. -CC:=$(shell sh -c 'type $(CC) >/dev/null 2>/dev/null && echo $(CC) || echo gcc') -OPTIMIZATION?=-O3 -WARNINGS=-Wall -W -Wstrict-prototypes -Wwrite-strings -DEBUG?= -g -ggdb -REAL_CFLAGS=$(OPTIMIZATION) -fPIC $(CFLAGS) $(WARNINGS) $(DEBUG) -REAL_LDFLAGS=$(LDFLAGS) - -DYLIBSUFFIX=so -STLIBSUFFIX=a -DYLIB_MINOR_NAME=$(LIBNAME).$(DYLIBSUFFIX).$(HIREDIS_MAJOR).$(HIREDIS_MINOR) -DYLIB_MAJOR_NAME=$(LIBNAME).$(DYLIBSUFFIX).$(HIREDIS_MAJOR) -DYLIBNAME=$(LIBNAME).$(DYLIBSUFFIX) -DYLIB_MAKE_CMD=$(CC) -shared -Wl,-soname,$(DYLIB_MINOR_NAME) -o $(DYLIBNAME) $(LDFLAGS) -STLIBNAME=$(LIBNAME).$(STLIBSUFFIX) -STLIB_MAKE_CMD=ar rcs $(STLIBNAME) - -# Platform-specific overrides -uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') -ifeq ($(uname_S),SunOS) - REAL_LDFLAGS+= -ldl -lnsl -lsocket - DYLIB_MAKE_CMD=$(CC) -G -o $(DYLIBNAME) -h $(DYLIB_MINOR_NAME) $(LDFLAGS) - INSTALL= cp -r -endif -ifeq ($(uname_S),Darwin) - DYLIBSUFFIX=dylib - DYLIB_MINOR_NAME=$(LIBNAME).$(HIREDIS_MAJOR).$(HIREDIS_MINOR).$(DYLIBSUFFIX) - DYLIB_MAJOR_NAME=$(LIBNAME).$(HIREDIS_MAJOR).$(DYLIBSUFFIX) - DYLIB_MAKE_CMD=$(CC) -shared -Wl,-install_name,$(DYLIB_MINOR_NAME) -o $(DYLIBNAME) $(LDFLAGS) -endif - -all: $(DYLIBNAME) $(BINS) - -# Deps (use make dep to generate this) -net.o: net.c fmacros.h net.h hiredis.h -async.o: async.c async.h hiredis.h sds.h dict.c dict.h -example.o: example.c hiredis.h -hiredis.o: hiredis.c fmacros.h hiredis.h net.h sds.h -sds.o: sds.c sds.h -test.o: test.c hiredis.h - -$(DYLIBNAME): $(OBJ) - $(DYLIB_MAKE_CMD) $(OBJ) - -$(STLIBNAME): $(OBJ) - $(STLIB_MAKE_CMD) $(OBJ) - -dynamic: $(DYLIBNAME) -static: $(STLIBNAME) - -# Binaries: -hiredis-example-libevent: example-libevent.c adapters/libevent.h $(STLIBNAME) - $(CC) -o $@ $(REAL_CFLAGS) $(REAL_LDFLAGS) -levent example-libevent.c $(STLIBNAME) - -hiredis-example-libev: example-libev.c adapters/libev.h $(STLIBNAME) - $(CC) -o $@ $(REAL_CFLAGS) $(REAL_LDFLAGS) -lev example-libev.c $(STLIBNAME) - -ifndef AE_DIR -hiredis-example-ae: - @echo "Please specify AE_DIR (e.g. /src)" - @false -else -hiredis-example-ae: example-ae.c adapters/ae.h $(STLIBNAME) - $(CC) -o $@ $(REAL_CFLAGS) $(REAL_LDFLAGS) -I$(AE_DIR) $(AE_DIR)/ae.o $(AE_DIR)/zmalloc.o example-ae.c $(STLIBNAME) -endif - -hiredis-%: %.o $(STLIBNAME) - $(CC) -o $@ $(REAL_LDFLAGS) $< $(STLIBNAME) - -test: hiredis-test - ./hiredis-test - -check: hiredis-test - echo \ - "daemonize yes\n" \ - "pidfile /tmp/hiredis-test-redis.pid\n" \ - "port 56379\n" \ - "bind 127.0.0.1\n" \ - "unixsocket /tmp/hiredis-test-redis.sock" \ - | redis-server - - ./hiredis-test -h 127.0.0.1 -p 56379 -s /tmp/hiredis-test-redis.sock || \ - ( kill `cat /tmp/hiredis-test-redis.pid` && false ) - kill `cat /tmp/hiredis-test-redis.pid` - -.c.o: - $(CC) -std=c99 -pedantic -c $(REAL_CFLAGS) $< - -clean: - rm -rf $(DYLIBNAME) $(STLIBNAME) $(BINS) hiredis-example* *.o *.gcda *.gcno *.gcov - -dep: - $(CC) -MM *.c - -# Installation related variables and target -PREFIX?=/usr/local -INCLUDE_PATH?=include/hiredis -LIBRARY_PATH?=lib -INSTALL_INCLUDE_PATH= $(PREFIX)/$(INCLUDE_PATH) -INSTALL_LIBRARY_PATH= $(PREFIX)/$(LIBRARY_PATH) - -ifeq ($(uname_S),SunOS) - INSTALL?= cp -r -endif - -INSTALL?= cp -a - -install: $(DYLIBNAME) $(STLIBNAME) - mkdir -p $(INSTALL_INCLUDE_PATH) $(INSTALL_LIBRARY_PATH) - $(INSTALL) hiredis.h async.h adapters $(INSTALL_INCLUDE_PATH) - $(INSTALL) $(DYLIBNAME) $(INSTALL_LIBRARY_PATH)/$(DYLIB_MINOR_NAME) - cd $(INSTALL_LIBRARY_PATH) && ln -sf $(DYLIB_MINOR_NAME) $(DYLIB_MAJOR_NAME) - cd $(INSTALL_LIBRARY_PATH) && ln -sf $(DYLIB_MAJOR_NAME) $(DYLIBNAME) - $(INSTALL) $(STLIBNAME) $(INSTALL_LIBRARY_PATH) - -32bit: - @echo "" - @echo "WARNING: if this fails under Linux you probably need to install libc6-dev-i386" - @echo "" - $(MAKE) CFLAGS="-m32" LDFLAGS="-m32" - -gprof: - $(MAKE) CFLAGS="-pg" LDFLAGS="-pg" - -gcov: - $(MAKE) CFLAGS="-fprofile-arcs -ftest-coverage" LDFLAGS="-fprofile-arcs" - -coverage: gcov - make check - mkdir -p tmp/lcov - lcov -d . -c -o tmp/lcov/hiredis.info - genhtml --legend -o tmp/lcov/report tmp/lcov/hiredis.info - -noopt: - $(MAKE) OPTIMIZATION="" - -.PHONY: all test check clean dep install 32bit gprof gcov noopt diff --git a/node_modules/hiredis/deps/hiredis/README.md b/node_modules/hiredis/deps/hiredis/README.md deleted file mode 100644 index a58101c..0000000 --- a/node_modules/hiredis/deps/hiredis/README.md +++ /dev/null @@ -1,352 +0,0 @@ -# HIREDIS - -Hiredis is a minimalistic C client library for the [Redis](http://redis.io/) database. - -It is minimalistic because it just adds minimal support for the protocol, but -at the same time it uses an high level printf-alike API in order to make it -much higher level than otherwise suggested by its minimal code base and the -lack of explicit bindings for every Redis command. - -Apart from supporting sending commands and receiving replies, it comes with -a reply parser that is decoupled from the I/O layer. It -is a stream parser designed for easy reusability, which can for instance be used -in higher level language bindings for efficient reply parsing. - -Hiredis only supports the binary-safe Redis protocol, so you can use it with any -Redis version >= 1.2.0. - -The library comes with multiple APIs. There is the -*synchronous API*, the *asynchronous API* and the *reply parsing API*. - -## UPGRADING - -Version 0.9.0 is a major overhaul of hiredis in every aspect. However, upgrading existing -code using hiredis should not be a big pain. The key thing to keep in mind when -upgrading is that hiredis >= 0.9.0 uses a `redisContext*` to keep state, in contrast to -the stateless 0.0.1 that only has a file descriptor to work with. - -## Synchronous API - -To consume the synchronous API, there are only a few function calls that need to be introduced: - - redisContext *redisConnect(const char *ip, int port); - void *redisCommand(redisContext *c, const char *format, ...); - void freeReplyObject(void *reply); - -### Connecting - -The function `redisConnect` is used to create a so-called `redisContext`. The -context is where Hiredis holds state for a connection. The `redisContext` -struct has an integer `err` field that is non-zero when an the connection is in -an error state. The field `errstr` will contain a string with a description of -the error. More information on errors can be found in the **Errors** section. -After trying to connect to Redis using `redisConnect` you should -check the `err` field to see if establishing the connection was successful: - - redisContext *c = redisConnect("127.0.0.1", 6379); - if (c->err) { - printf("Error: %s\n", c->errstr); - // handle error - } - -### Sending commands - -There are several ways to issue commands to Redis. The first that will be introduced is -`redisCommand`. This function takes a format similar to printf. In the simplest form, -it is used like this: - - reply = redisCommand(context, "SET foo bar"); - -The specifier `%s` interpolates a string in the command, and uses `strlen` to -determine the length of the string: - - reply = redisCommand(context, "SET foo %s", value); - -When you need to pass binary safe strings in a command, the `%b` specifier can be -used. Together with a pointer to the string, it requires a `size_t` length argument -of the string: - - reply = redisCommand(context, "SET foo %b", value, valuelen); - -Internally, Hiredis splits the command in different arguments and will -convert it to the protocol used to communicate with Redis. -One or more spaces separates arguments, so you can use the specifiers -anywhere in an argument: - - reply = redisCommand("SET key:%s %s", myid, value); - -### Using replies - -The return value of `redisCommand` holds a reply when the command was -successfully executed. When an error occurs, the return value is `NULL` and -the `err` field in the context will be set (see section on **Errors**). -Once an error is returned the context cannot be reused and you should set up -a new connection. - -The standard replies that `redisCommand` are of the type `redisReply`. The -`type` field in the `redisReply` should be used to test what kind of reply -was received: - -* **`REDIS_REPLY_STATUS`**: - * The command replied with a status reply. The status string can be accessed using `reply->str`. - The length of this string can be accessed using `reply->len`. - -* **`REDIS_REPLY_ERROR`**: - * The command replied with an error. The error string can be accessed identical to `REDIS_REPLY_STATUS`. - -* **`REDIS_REPLY_INTEGER`**: - * The command replied with an integer. The integer value can be accessed using the - `reply->integer` field of type `long long`. - -* **`REDIS_REPLY_NIL`**: - * The command replied with a **nil** object. There is no data to access. - -* **`REDIS_REPLY_STRING`**: - * A bulk (string) reply. The value of the reply can be accessed using `reply->str`. - The length of this string can be accessed using `reply->len`. - -* **`REDIS_REPLY_ARRAY`**: - * A multi bulk reply. The number of elements in the multi bulk reply is stored in - `reply->elements`. Every element in the multi bulk reply is a `redisReply` object as well - and can be accessed via `reply->element[..index..]`. - Redis may reply with nested arrays but this is fully supported. - -Replies should be freed using the `freeReplyObject()` function. -Note that this function will take care of freeing sub-replies objects -contained in arrays and nested arrays, so there is no need for the user to -free the sub replies (it is actually harmful and will corrupt the memory). - -**Important:** the current version of hiredis (0.10.0) free's replies when the -asynchronous API is used. This means you should not call `freeReplyObject` when -you use this API. The reply is cleaned up by hiredis _after_ the callback -returns. This behavior will probably change in future releases, so make sure to -keep an eye on the changelog when upgrading (see issue #39). - -### Cleaning up - -To disconnect and free the context the following function can be used: - - void redisFree(redisContext *c); - -This function immediately closes the socket and then free's the allocations done in -creating the context. - -### Sending commands (cont'd) - -Together with `redisCommand`, the function `redisCommandArgv` can be used to issue commands. -It has the following prototype: - - void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -It takes the number of arguments `argc`, an array of strings `argv` and the lengths of the -arguments `argvlen`. For convenience, `argvlen` may be set to `NULL` and the function will -use `strlen(3)` on every argument to determine its length. Obviously, when any of the arguments -need to be binary safe, the entire array of lengths `argvlen` should be provided. - -The return value has the same semantic as `redisCommand`. - -### Pipelining - -To explain how Hiredis supports pipelining in a blocking connection, there needs to be -understanding of the internal execution flow. - -When any of the functions in the `redisCommand` family is called, Hiredis first formats the -command according to the Redis protocol. The formatted command is then put in the output buffer -of the context. This output buffer is dynamic, so it can hold any number of commands. -After the command is put in the output buffer, `redisGetReply` is called. This function has the -following two execution paths: - -1. The input buffer is non-empty: - * Try to parse a single reply from the input buffer and return it - * If no reply could be parsed, continue at *2* -2. The input buffer is empty: - * Write the **entire** output buffer to the socket - * Read from the socket until a single reply could be parsed - -The function `redisGetReply` is exported as part of the Hiredis API and can be used when a reply -is expected on the socket. To pipeline commands, the only things that needs to be done is -filling up the output buffer. For this cause, two commands can be used that are identical -to the `redisCommand` family, apart from not returning a reply: - - void redisAppendCommand(redisContext *c, const char *format, ...); - void redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -After calling either function one or more times, `redisGetReply` can be used to receive the -subsequent replies. The return value for this function is either `REDIS_OK` or `REDIS_ERR`, where -the latter means an error occurred while reading a reply. Just as with the other commands, -the `err` field in the context can be used to find out what the cause of this error is. - -The following examples shows a simple pipeline (resulting in only a single call to `write(2)` and -a single call to `read(2)`): - - redisReply *reply; - redisAppendCommand(context,"SET foo bar"); - redisAppendCommand(context,"GET foo"); - redisGetReply(context,&reply); // reply for SET - freeReplyObject(reply); - redisGetReply(context,&reply); // reply for GET - freeReplyObject(reply); - -This API can also be used to implement a blocking subscriber: - - reply = redisCommand(context,"SUBSCRIBE foo"); - freeReplyObject(reply); - while(redisGetReply(context,&reply) == REDIS_OK) { - // consume message - freeReplyObject(reply); - } - -### Errors - -When a function call is not successful, depending on the function either `NULL` or `REDIS_ERR` is -returned. The `err` field inside the context will be non-zero and set to one of the -following constants: - -* **`REDIS_ERR_IO`**: - There was an I/O error while creating the connection, trying to write - to the socket or read from the socket. If you included `errno.h` in your - application, you can use the global `errno` variable to find out what is - wrong. - -* **`REDIS_ERR_EOF`**: - The server closed the connection which resulted in an empty read. - -* **`REDIS_ERR_PROTOCOL`**: - There was an error while parsing the protocol. - -* **`REDIS_ERR_OTHER`**: - Any other error. Currently, it is only used when a specified hostname to connect - to cannot be resolved. - -In every case, the `errstr` field in the context will be set to hold a string representation -of the error. - -## Asynchronous API - -Hiredis comes with an asynchronous API that works easily with any event library. -Examples are bundled that show using Hiredis with [libev](http://software.schmorp.de/pkg/libev.html) -and [libevent](http://monkey.org/~provos/libevent/). - -### Connecting - -The function `redisAsyncConnect` can be used to establish a non-blocking connection to -Redis. It returns a pointer to the newly created `redisAsyncContext` struct. The `err` field -should be checked after creation to see if there were errors creating the connection. -Because the connection that will be created is non-blocking, the kernel is not able to -instantly return if the specified host and port is able to accept a connection. - - redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); - if (c->err) { - printf("Error: %s\n", c->errstr); - // handle error - } - -The asynchronous context can hold a disconnect callback function that is called when the -connection is disconnected (either because of an error or per user request). This function should -have the following prototype: - - void(const redisAsyncContext *c, int status); - -On a disconnect, the `status` argument is set to `REDIS_OK` when disconnection was initiated by the -user, or `REDIS_ERR` when the disconnection was caused by an error. When it is `REDIS_ERR`, the `err` -field in the context can be accessed to find out the cause of the error. - -The context object is always free'd after the disconnect callback fired. When a reconnect is needed, -the disconnect callback is a good point to do so. - -Setting the disconnect callback can only be done once per context. For subsequent calls it will -return `REDIS_ERR`. The function to set the disconnect callback has the following prototype: - - int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn); - -### Sending commands and their callbacks - -In an asynchronous context, commands are automatically pipelined due to the nature of an event loop. -Therefore, unlike the synchronous API, there is only a single way to send commands. -Because commands are sent to Redis asynchronously, issuing a command requires a callback function -that is called when the reply is received. Reply callbacks should have the following prototype: - - void(redisAsyncContext *c, void *reply, void *privdata); - -The `privdata` argument can be used to curry arbitrary data to the callback from the point where -the command is initially queued for execution. - -The functions that can be used to issue commands in an asynchronous context are: - - int redisAsyncCommand( - redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, - const char *format, ...); - int redisAsyncCommandArgv( - redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, - int argc, const char **argv, const size_t *argvlen); - -Both functions work like their blocking counterparts. The return value is `REDIS_OK` when the command -was successfully added to the output buffer and `REDIS_ERR` otherwise. Example: when the connection -is being disconnected per user-request, no new commands may be added to the output buffer and `REDIS_ERR` is -returned on calls to the `redisAsyncCommand` family. - -If the reply for a command with a `NULL` callback is read, it is immediately free'd. When the callback -for a command is non-`NULL`, the memory is free'd immediately following the callback: the reply is only -valid for the duration of the callback. - -All pending callbacks are called with a `NULL` reply when the context encountered an error. - -### Disconnecting - -An asynchronous connection can be terminated using: - - void redisAsyncDisconnect(redisAsyncContext *ac); - -When this function is called, the connection is **not** immediately terminated. Instead, new -commands are no longer accepted and the connection is only terminated when all pending commands -have been written to the socket, their respective replies have been read and their respective -callbacks have been executed. After this, the disconnection callback is executed with the -`REDIS_OK` status and the context object is free'd. - -### Hooking it up to event library *X* - -There are a few hooks that need to be set on the context object after it is created. -See the `adapters/` directory for bindings to *libev* and *libevent*. - -## Reply parsing API - -Hiredis comes with a reply parsing API that makes it easy for writing higher -level language bindings. - -The reply parsing API consists of the following functions: - - redisReader *redisReaderCreate(void); - void redisReaderFree(redisReader *reader); - int redisReaderFeed(redisReader *reader, const char *buf, size_t len); - int redisReaderGetReply(redisReader *reader, void **reply); - -### Usage - -The function `redisReaderCreate` creates a `redisReader` structure that holds a -buffer with unparsed data and state for the protocol parser. - -Incoming data -- most likely from a socket -- can be placed in the internal -buffer of the `redisReader` using `redisReaderFeed`. This function will make a -copy of the buffer pointed to by `buf` for `len` bytes. This data is parsed -when `redisReaderGetReply` is called. This function returns an integer status -and a reply object (as described above) via `void **reply`. The returned status -can be either `REDIS_OK` or `REDIS_ERR`, where the latter means something went -wrong (either a protocol error, or an out of memory error). - -### Customizing replies - -The function `redisReaderGetReply` creates `redisReply` and makes the function -argument `reply` point to the created `redisReply` variable. For instance, if -the response of type `REDIS_REPLY_STATUS` then the `str` field of `redisReply` -will hold the status as a vanilla C string. However, the functions that are -responsible for creating instances of the `redisReply` can be customized by -setting the `fn` field on the `redisReader` struct. This should be done -immediately after creating the `redisReader`. - -For example, [hiredis-rb](https://github.com/pietern/hiredis-rb/blob/master/ext/hiredis_ext/reader.c) -uses customized reply object functions to create Ruby objects. - -## AUTHORS - -Hiredis was written by Salvatore Sanfilippo (antirez at gmail) and -Pieter Noordhuis (pcnoordhuis at gmail) and is released under the BSD license. diff --git a/node_modules/hiredis/deps/hiredis/adapters/ae.h b/node_modules/hiredis/deps/hiredis/adapters/ae.h deleted file mode 100644 index 65235f8..0000000 --- a/node_modules/hiredis/deps/hiredis/adapters/ae.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef __HIREDIS_AE_H__ -#define __HIREDIS_AE_H__ -#include -#include -#include "../hiredis.h" -#include "../async.h" - -typedef struct redisAeEvents { - redisAsyncContext *context; - aeEventLoop *loop; - int fd; - int reading, writing; -} redisAeEvents; - -static void redisAeReadEvent(aeEventLoop *el, int fd, void *privdata, int mask) { - ((void)el); ((void)fd); ((void)mask); - - redisAeEvents *e = (redisAeEvents*)privdata; - redisAsyncHandleRead(e->context); -} - -static void redisAeWriteEvent(aeEventLoop *el, int fd, void *privdata, int mask) { - ((void)el); ((void)fd); ((void)mask); - - redisAeEvents *e = (redisAeEvents*)privdata; - redisAsyncHandleWrite(e->context); -} - -static void redisAeAddRead(void *privdata) { - redisAeEvents *e = (redisAeEvents*)privdata; - aeEventLoop *loop = e->loop; - if (!e->reading) { - e->reading = 1; - aeCreateFileEvent(loop,e->fd,AE_READABLE,redisAeReadEvent,e); - } -} - -static void redisAeDelRead(void *privdata) { - redisAeEvents *e = (redisAeEvents*)privdata; - aeEventLoop *loop = e->loop; - if (e->reading) { - e->reading = 0; - aeDeleteFileEvent(loop,e->fd,AE_READABLE); - } -} - -static void redisAeAddWrite(void *privdata) { - redisAeEvents *e = (redisAeEvents*)privdata; - aeEventLoop *loop = e->loop; - if (!e->writing) { - e->writing = 1; - aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e); - } -} - -static void redisAeDelWrite(void *privdata) { - redisAeEvents *e = (redisAeEvents*)privdata; - aeEventLoop *loop = e->loop; - if (e->writing) { - e->writing = 0; - aeDeleteFileEvent(loop,e->fd,AE_WRITABLE); - } -} - -static void redisAeCleanup(void *privdata) { - redisAeEvents *e = (redisAeEvents*)privdata; - redisAeDelRead(privdata); - redisAeDelWrite(privdata); - free(e); -} - -static int redisAeAttach(aeEventLoop *loop, redisAsyncContext *ac) { - redisContext *c = &(ac->c); - redisAeEvents *e; - - /* Nothing should be attached when something is already attached */ - if (ac->ev.data != NULL) - return REDIS_ERR; - - /* Create container for context and r/w events */ - e = (redisAeEvents*)malloc(sizeof(*e)); - e->context = ac; - e->loop = loop; - e->fd = c->fd; - e->reading = e->writing = 0; - - /* Register functions to start/stop listening for events */ - ac->ev.addRead = redisAeAddRead; - ac->ev.delRead = redisAeDelRead; - ac->ev.addWrite = redisAeAddWrite; - ac->ev.delWrite = redisAeDelWrite; - ac->ev.cleanup = redisAeCleanup; - ac->ev.data = e; - - return REDIS_OK; -} -#endif diff --git a/node_modules/hiredis/deps/hiredis/adapters/libev.h b/node_modules/hiredis/deps/hiredis/adapters/libev.h deleted file mode 100644 index 534d743..0000000 --- a/node_modules/hiredis/deps/hiredis/adapters/libev.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __HIREDIS_LIBEV_H__ -#define __HIREDIS_LIBEV_H__ -#include -#include -#include -#include "../hiredis.h" -#include "../async.h" - -typedef struct redisLibevEvents { - redisAsyncContext *context; - struct ev_loop *loop; - int reading, writing; - ev_io rev, wev; -} redisLibevEvents; - -static void redisLibevReadEvent(EV_P_ ev_io *watcher, int revents) { -#if EV_MULTIPLICITY - ((void)loop); -#endif - ((void)revents); - - redisLibevEvents *e = (redisLibevEvents*)watcher->data; - redisAsyncHandleRead(e->context); -} - -static void redisLibevWriteEvent(EV_P_ ev_io *watcher, int revents) { -#if EV_MULTIPLICITY - ((void)loop); -#endif - ((void)revents); - - redisLibevEvents *e = (redisLibevEvents*)watcher->data; - redisAsyncHandleWrite(e->context); -} - -static void redisLibevAddRead(void *privdata) { - redisLibevEvents *e = (redisLibevEvents*)privdata; - struct ev_loop *loop = e->loop; - ((void)loop); - if (!e->reading) { - e->reading = 1; - ev_io_start(EV_A_ &e->rev); - } -} - -static void redisLibevDelRead(void *privdata) { - redisLibevEvents *e = (redisLibevEvents*)privdata; - struct ev_loop *loop = e->loop; - ((void)loop); - if (e->reading) { - e->reading = 0; - ev_io_stop(EV_A_ &e->rev); - } -} - -static void redisLibevAddWrite(void *privdata) { - redisLibevEvents *e = (redisLibevEvents*)privdata; - struct ev_loop *loop = e->loop; - ((void)loop); - if (!e->writing) { - e->writing = 1; - ev_io_start(EV_A_ &e->wev); - } -} - -static void redisLibevDelWrite(void *privdata) { - redisLibevEvents *e = (redisLibevEvents*)privdata; - struct ev_loop *loop = e->loop; - ((void)loop); - if (e->writing) { - e->writing = 0; - ev_io_stop(EV_A_ &e->wev); - } -} - -static void redisLibevCleanup(void *privdata) { - redisLibevEvents *e = (redisLibevEvents*)privdata; - redisLibevDelRead(privdata); - redisLibevDelWrite(privdata); - free(e); -} - -static int redisLibevAttach(EV_P_ redisAsyncContext *ac) { - redisContext *c = &(ac->c); - redisLibevEvents *e; - - /* Nothing should be attached when something is already attached */ - if (ac->ev.data != NULL) - return REDIS_ERR; - - /* Create container for context and r/w events */ - e = (redisLibevEvents*)malloc(sizeof(*e)); - e->context = ac; -#if EV_MULTIPLICITY - e->loop = loop; -#else - e->loop = NULL; -#endif - e->reading = e->writing = 0; - e->rev.data = e; - e->wev.data = e; - - /* Register functions to start/stop listening for events */ - ac->ev.addRead = redisLibevAddRead; - ac->ev.delRead = redisLibevDelRead; - ac->ev.addWrite = redisLibevAddWrite; - ac->ev.delWrite = redisLibevDelWrite; - ac->ev.cleanup = redisLibevCleanup; - ac->ev.data = e; - - /* Initialize read/write events */ - ev_io_init(&e->rev,redisLibevReadEvent,c->fd,EV_READ); - ev_io_init(&e->wev,redisLibevWriteEvent,c->fd,EV_WRITE); - return REDIS_OK; -} - -#endif diff --git a/node_modules/hiredis/deps/hiredis/adapters/libevent.h b/node_modules/hiredis/deps/hiredis/adapters/libevent.h deleted file mode 100644 index 4055ec0..0000000 --- a/node_modules/hiredis/deps/hiredis/adapters/libevent.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef __HIREDIS_LIBEVENT_H__ -#define __HIREDIS_LIBEVENT_H__ -#include -#include "../hiredis.h" -#include "../async.h" - -typedef struct redisLibeventEvents { - redisAsyncContext *context; - struct event rev, wev; -} redisLibeventEvents; - -static void redisLibeventReadEvent(int fd, short event, void *arg) { - ((void)fd); ((void)event); - redisLibeventEvents *e = (redisLibeventEvents*)arg; - redisAsyncHandleRead(e->context); -} - -static void redisLibeventWriteEvent(int fd, short event, void *arg) { - ((void)fd); ((void)event); - redisLibeventEvents *e = (redisLibeventEvents*)arg; - redisAsyncHandleWrite(e->context); -} - -static void redisLibeventAddRead(void *privdata) { - redisLibeventEvents *e = (redisLibeventEvents*)privdata; - event_add(&e->rev,NULL); -} - -static void redisLibeventDelRead(void *privdata) { - redisLibeventEvents *e = (redisLibeventEvents*)privdata; - event_del(&e->rev); -} - -static void redisLibeventAddWrite(void *privdata) { - redisLibeventEvents *e = (redisLibeventEvents*)privdata; - event_add(&e->wev,NULL); -} - -static void redisLibeventDelWrite(void *privdata) { - redisLibeventEvents *e = (redisLibeventEvents*)privdata; - event_del(&e->wev); -} - -static void redisLibeventCleanup(void *privdata) { - redisLibeventEvents *e = (redisLibeventEvents*)privdata; - event_del(&e->rev); - event_del(&e->wev); - free(e); -} - -static int redisLibeventAttach(redisAsyncContext *ac, struct event_base *base) { - redisContext *c = &(ac->c); - redisLibeventEvents *e; - - /* Nothing should be attached when something is already attached */ - if (ac->ev.data != NULL) - return REDIS_ERR; - - /* Create container for context and r/w events */ - e = (redisLibeventEvents*)malloc(sizeof(*e)); - e->context = ac; - - /* Register functions to start/stop listening for events */ - ac->ev.addRead = redisLibeventAddRead; - ac->ev.delRead = redisLibeventDelRead; - ac->ev.addWrite = redisLibeventAddWrite; - ac->ev.delWrite = redisLibeventDelWrite; - ac->ev.cleanup = redisLibeventCleanup; - ac->ev.data = e; - - /* Initialize and install read/write events */ - event_set(&e->rev,c->fd,EV_READ,redisLibeventReadEvent,e); - event_set(&e->wev,c->fd,EV_WRITE,redisLibeventWriteEvent,e); - event_base_set(base,&e->rev); - event_base_set(base,&e->wev); - return REDIS_OK; -} -#endif diff --git a/node_modules/hiredis/deps/hiredis/async.c b/node_modules/hiredis/deps/hiredis/async.c deleted file mode 100644 index f83e2f5..0000000 --- a/node_modules/hiredis/deps/hiredis/async.c +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (c) 2009-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fmacros.h" -#include -#include -#include -#include -#include -#include -#include "async.h" -#include "net.h" -#include "dict.c" -#include "sds.h" - -#define _EL_ADD_READ(ctx) do { \ - if ((ctx)->ev.addRead) (ctx)->ev.addRead((ctx)->ev.data); \ - } while(0) -#define _EL_DEL_READ(ctx) do { \ - if ((ctx)->ev.delRead) (ctx)->ev.delRead((ctx)->ev.data); \ - } while(0) -#define _EL_ADD_WRITE(ctx) do { \ - if ((ctx)->ev.addWrite) (ctx)->ev.addWrite((ctx)->ev.data); \ - } while(0) -#define _EL_DEL_WRITE(ctx) do { \ - if ((ctx)->ev.delWrite) (ctx)->ev.delWrite((ctx)->ev.data); \ - } while(0) -#define _EL_CLEANUP(ctx) do { \ - if ((ctx)->ev.cleanup) (ctx)->ev.cleanup((ctx)->ev.data); \ - } while(0); - -/* Forward declaration of function in hiredis.c */ -void __redisAppendCommand(redisContext *c, char *cmd, size_t len); - -/* Functions managing dictionary of callbacks for pub/sub. */ -static unsigned int callbackHash(const void *key) { - return dictGenHashFunction((unsigned char*)key,sdslen((char*)key)); -} - -static void *callbackValDup(void *privdata, const void *src) { - ((void) privdata); - redisCallback *dup = malloc(sizeof(*dup)); - memcpy(dup,src,sizeof(*dup)); - return dup; -} - -static int callbackKeyCompare(void *privdata, const void *key1, const void *key2) { - int l1, l2; - ((void) privdata); - - l1 = sdslen((sds)key1); - l2 = sdslen((sds)key2); - if (l1 != l2) return 0; - return memcmp(key1,key2,l1) == 0; -} - -static void callbackKeyDestructor(void *privdata, void *key) { - ((void) privdata); - sdsfree((sds)key); -} - -static void callbackValDestructor(void *privdata, void *val) { - ((void) privdata); - free(val); -} - -static dictType callbackDict = { - callbackHash, - NULL, - callbackValDup, - callbackKeyCompare, - callbackKeyDestructor, - callbackValDestructor -}; - -static redisAsyncContext *redisAsyncInitialize(redisContext *c) { - redisAsyncContext *ac = realloc(c,sizeof(redisAsyncContext)); - c = &(ac->c); - - /* The regular connect functions will always set the flag REDIS_CONNECTED. - * For the async API, we want to wait until the first write event is - * received up before setting this flag, so reset it here. */ - c->flags &= ~REDIS_CONNECTED; - - ac->err = 0; - ac->errstr = NULL; - ac->data = NULL; - - ac->ev.data = NULL; - ac->ev.addRead = NULL; - ac->ev.delRead = NULL; - ac->ev.addWrite = NULL; - ac->ev.delWrite = NULL; - ac->ev.cleanup = NULL; - - ac->onConnect = NULL; - ac->onDisconnect = NULL; - - ac->replies.head = NULL; - ac->replies.tail = NULL; - ac->sub.invalid.head = NULL; - ac->sub.invalid.tail = NULL; - ac->sub.channels = dictCreate(&callbackDict,NULL); - ac->sub.patterns = dictCreate(&callbackDict,NULL); - return ac; -} - -/* We want the error field to be accessible directly instead of requiring - * an indirection to the redisContext struct. */ -static void __redisAsyncCopyError(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - ac->err = c->err; - ac->errstr = c->errstr; -} - -redisAsyncContext *redisAsyncConnect(const char *ip, int port) { - redisContext *c = redisConnectNonBlock(ip,port); - redisAsyncContext *ac = redisAsyncInitialize(c); - __redisAsyncCopyError(ac); - return ac; -} - -redisAsyncContext *redisAsyncConnectUnix(const char *path) { - redisContext *c = redisConnectUnixNonBlock(path); - redisAsyncContext *ac = redisAsyncInitialize(c); - __redisAsyncCopyError(ac); - return ac; -} - -int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn) { - if (ac->onConnect == NULL) { - ac->onConnect = fn; - - /* The common way to detect an established connection is to wait for - * the first write event to be fired. This assumes the related event - * library functions are already set. */ - _EL_ADD_WRITE(ac); - return REDIS_OK; - } - return REDIS_ERR; -} - -int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn) { - if (ac->onDisconnect == NULL) { - ac->onDisconnect = fn; - return REDIS_OK; - } - return REDIS_ERR; -} - -/* Helper functions to push/shift callbacks */ -static int __redisPushCallback(redisCallbackList *list, redisCallback *source) { - redisCallback *cb; - - /* Copy callback from stack to heap */ - cb = malloc(sizeof(*cb)); - if (source != NULL) { - memcpy(cb,source,sizeof(*cb)); - cb->next = NULL; - } - - /* Store callback in list */ - if (list->head == NULL) - list->head = cb; - if (list->tail != NULL) - list->tail->next = cb; - list->tail = cb; - return REDIS_OK; -} - -static int __redisShiftCallback(redisCallbackList *list, redisCallback *target) { - redisCallback *cb = list->head; - if (cb != NULL) { - list->head = cb->next; - if (cb == list->tail) - list->tail = NULL; - - /* Copy callback from heap to stack */ - if (target != NULL) - memcpy(target,cb,sizeof(*cb)); - free(cb); - return REDIS_OK; - } - return REDIS_ERR; -} - -static void __redisRunCallback(redisAsyncContext *ac, redisCallback *cb, redisReply *reply) { - redisContext *c = &(ac->c); - if (cb->fn != NULL) { - c->flags |= REDIS_IN_CALLBACK; - cb->fn(ac,reply,cb->privdata); - c->flags &= ~REDIS_IN_CALLBACK; - } -} - -/* Helper function to free the context. */ -static void __redisAsyncFree(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - redisCallback cb; - dictIterator *it; - dictEntry *de; - - /* Execute pending callbacks with NULL reply. */ - while (__redisShiftCallback(&ac->replies,&cb) == REDIS_OK) - __redisRunCallback(ac,&cb,NULL); - - /* Execute callbacks for invalid commands */ - while (__redisShiftCallback(&ac->sub.invalid,&cb) == REDIS_OK) - __redisRunCallback(ac,&cb,NULL); - - /* Run subscription callbacks callbacks with NULL reply */ - it = dictGetIterator(ac->sub.channels); - while ((de = dictNext(it)) != NULL) - __redisRunCallback(ac,dictGetEntryVal(de),NULL); - dictReleaseIterator(it); - dictRelease(ac->sub.channels); - - it = dictGetIterator(ac->sub.patterns); - while ((de = dictNext(it)) != NULL) - __redisRunCallback(ac,dictGetEntryVal(de),NULL); - dictReleaseIterator(it); - dictRelease(ac->sub.patterns); - - /* Signal event lib to clean up */ - _EL_CLEANUP(ac); - - /* Execute disconnect callback. When redisAsyncFree() initiated destroying - * this context, the status will always be REDIS_OK. */ - if (ac->onDisconnect && (c->flags & REDIS_CONNECTED)) { - if (c->flags & REDIS_FREEING) { - ac->onDisconnect(ac,REDIS_OK); - } else { - ac->onDisconnect(ac,(ac->err == 0) ? REDIS_OK : REDIS_ERR); - } - } - - /* Cleanup self */ - redisFree(c); -} - -/* Free the async context. When this function is called from a callback, - * control needs to be returned to redisProcessCallbacks() before actual - * free'ing. To do so, a flag is set on the context which is picked up by - * redisProcessCallbacks(). Otherwise, the context is immediately free'd. */ -void redisAsyncFree(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - c->flags |= REDIS_FREEING; - if (!(c->flags & REDIS_IN_CALLBACK)) - __redisAsyncFree(ac); -} - -/* Helper function to make the disconnect happen and clean up. */ -static void __redisAsyncDisconnect(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - - /* Make sure error is accessible if there is any */ - __redisAsyncCopyError(ac); - - if (ac->err == 0) { - /* For clean disconnects, there should be no pending callbacks. */ - assert(__redisShiftCallback(&ac->replies,NULL) == REDIS_ERR); - } else { - /* Disconnection is caused by an error, make sure that pending - * callbacks cannot call new commands. */ - c->flags |= REDIS_DISCONNECTING; - } - - /* For non-clean disconnects, __redisAsyncFree() will execute pending - * callbacks with a NULL-reply. */ - __redisAsyncFree(ac); -} - -/* Tries to do a clean disconnect from Redis, meaning it stops new commands - * from being issued, but tries to flush the output buffer and execute - * callbacks for all remaining replies. When this function is called from a - * callback, there might be more replies and we can safely defer disconnecting - * to redisProcessCallbacks(). Otherwise, we can only disconnect immediately - * when there are no pending callbacks. */ -void redisAsyncDisconnect(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - c->flags |= REDIS_DISCONNECTING; - if (!(c->flags & REDIS_IN_CALLBACK) && ac->replies.head == NULL) - __redisAsyncDisconnect(ac); -} - -static int __redisGetSubscribeCallback(redisAsyncContext *ac, redisReply *reply, redisCallback *dstcb) { - redisContext *c = &(ac->c); - dict *callbacks; - dictEntry *de; - int pvariant; - char *stype; - sds sname; - - /* Custom reply functions are not supported for pub/sub. This will fail - * very hard when they are used... */ - if (reply->type == REDIS_REPLY_ARRAY) { - assert(reply->elements >= 2); - assert(reply->element[0]->type == REDIS_REPLY_STRING); - stype = reply->element[0]->str; - pvariant = (tolower(stype[0]) == 'p') ? 1 : 0; - - if (pvariant) - callbacks = ac->sub.patterns; - else - callbacks = ac->sub.channels; - - /* Locate the right callback */ - assert(reply->element[1]->type == REDIS_REPLY_STRING); - sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len); - de = dictFind(callbacks,sname); - if (de != NULL) { - memcpy(dstcb,dictGetEntryVal(de),sizeof(*dstcb)); - - /* If this is an unsubscribe message, remove it. */ - if (strcasecmp(stype+pvariant,"unsubscribe") == 0) { - dictDelete(callbacks,sname); - - /* If this was the last unsubscribe message, revert to - * non-subscribe mode. */ - assert(reply->element[2]->type == REDIS_REPLY_INTEGER); - if (reply->element[2]->integer == 0) - c->flags &= ~REDIS_SUBSCRIBED; - } - } - sdsfree(sname); - } else { - /* Shift callback for invalid commands. */ - __redisShiftCallback(&ac->sub.invalid,dstcb); - } - return REDIS_OK; -} - -void redisProcessCallbacks(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - redisCallback cb; - void *reply = NULL; - int status; - - while((status = redisGetReply(c,&reply)) == REDIS_OK) { - if (reply == NULL) { - /* When the connection is being disconnected and there are - * no more replies, this is the cue to really disconnect. */ - if (c->flags & REDIS_DISCONNECTING && sdslen(c->obuf) == 0) { - __redisAsyncDisconnect(ac); - return; - } - - /* When the connection is not being disconnected, simply stop - * trying to get replies and wait for the next loop tick. */ - break; - } - - /* Even if the context is subscribed, pending regular callbacks will - * get a reply before pub/sub messages arrive. */ - if (__redisShiftCallback(&ac->replies,&cb) != REDIS_OK) { - /* A spontaneous reply in a not-subscribed context can only be the - * error reply that is sent when a new connection exceeds the - * maximum number of allowed connections on the server side. This - * is seen as an error instead of a regular reply because the - * server closes the connection after sending it. To prevent the - * error from being overwritten by an EOF error the connection is - * closed here. See issue #43. */ - if ( !(c->flags & REDIS_SUBSCRIBED) && ((redisReply*)reply)->type == REDIS_REPLY_ERROR ) { - c->err = REDIS_ERR_OTHER; - snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str); - __redisAsyncDisconnect(ac); - return; - } - /* No more regular callbacks and no errors, the context *must* be subscribed. */ - assert(c->flags & REDIS_SUBSCRIBED); - __redisGetSubscribeCallback(ac,reply,&cb); - } - - if (cb.fn != NULL) { - __redisRunCallback(ac,&cb,reply); - c->reader->fn->freeObject(reply); - - /* Proceed with free'ing when redisAsyncFree() was called. */ - if (c->flags & REDIS_FREEING) { - __redisAsyncFree(ac); - return; - } - } else { - /* No callback for this reply. This can either be a NULL callback, - * or there were no callbacks to begin with. Either way, don't - * abort with an error, but simply ignore it because the client - * doesn't know what the server will spit out over the wire. */ - c->reader->fn->freeObject(reply); - } - } - - /* Disconnect when there was an error reading the reply */ - if (status != REDIS_OK) - __redisAsyncDisconnect(ac); -} - -/* Internal helper function to detect socket status the first time a read or - * write event fires. When connecting was not succesful, the connect callback - * is called with a REDIS_ERR status and the context is free'd. */ -static int __redisAsyncHandleConnect(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - - if (redisCheckSocketError(c,c->fd) == REDIS_ERR) { - /* Try again later when connect(2) is still in progress. */ - if (errno == EINPROGRESS) - return REDIS_OK; - - if (ac->onConnect) ac->onConnect(ac,REDIS_ERR); - __redisAsyncDisconnect(ac); - return REDIS_ERR; - } - - /* Mark context as connected. */ - c->flags |= REDIS_CONNECTED; - if (ac->onConnect) ac->onConnect(ac,REDIS_OK); - return REDIS_OK; -} - -/* This function should be called when the socket is readable. - * It processes all replies that can be read and executes their callbacks. - */ -void redisAsyncHandleRead(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - - if (!(c->flags & REDIS_CONNECTED)) { - /* Abort connect was not successful. */ - if (__redisAsyncHandleConnect(ac) != REDIS_OK) - return; - /* Try again later when the context is still not connected. */ - if (!(c->flags & REDIS_CONNECTED)) - return; - } - - if (redisBufferRead(c) == REDIS_ERR) { - __redisAsyncDisconnect(ac); - } else { - /* Always re-schedule reads */ - _EL_ADD_READ(ac); - redisProcessCallbacks(ac); - } -} - -void redisAsyncHandleWrite(redisAsyncContext *ac) { - redisContext *c = &(ac->c); - int done = 0; - - if (!(c->flags & REDIS_CONNECTED)) { - /* Abort connect was not successful. */ - if (__redisAsyncHandleConnect(ac) != REDIS_OK) - return; - /* Try again later when the context is still not connected. */ - if (!(c->flags & REDIS_CONNECTED)) - return; - } - - if (redisBufferWrite(c,&done) == REDIS_ERR) { - __redisAsyncDisconnect(ac); - } else { - /* Continue writing when not done, stop writing otherwise */ - if (!done) - _EL_ADD_WRITE(ac); - else - _EL_DEL_WRITE(ac); - - /* Always schedule reads after writes */ - _EL_ADD_READ(ac); - } -} - -/* Sets a pointer to the first argument and its length starting at p. Returns - * the number of bytes to skip to get to the following argument. */ -static char *nextArgument(char *start, char **str, size_t *len) { - char *p = start; - if (p[0] != '$') { - p = strchr(p,'$'); - if (p == NULL) return NULL; - } - - *len = (int)strtol(p+1,NULL,10); - p = strchr(p,'\r'); - assert(p); - *str = p+2; - return p+2+(*len)+2; -} - -/* Helper function for the redisAsyncCommand* family of functions. Writes a - * formatted command to the output buffer and registers the provided callback - * function with the context. */ -static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, char *cmd, size_t len) { - redisContext *c = &(ac->c); - redisCallback cb; - int pvariant, hasnext; - char *cstr, *astr; - size_t clen, alen; - char *p; - sds sname; - - /* Don't accept new commands when the connection is about to be closed. */ - if (c->flags & (REDIS_DISCONNECTING | REDIS_FREEING)) return REDIS_ERR; - - /* Setup callback */ - cb.fn = fn; - cb.privdata = privdata; - - /* Find out which command will be appended. */ - p = nextArgument(cmd,&cstr,&clen); - assert(p != NULL); - hasnext = (p[0] == '$'); - pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0; - cstr += pvariant; - clen -= pvariant; - - if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) { - c->flags |= REDIS_SUBSCRIBED; - - /* Add every channel/pattern to the list of subscription callbacks. */ - while ((p = nextArgument(p,&astr,&alen)) != NULL) { - sname = sdsnewlen(astr,alen); - if (pvariant) - dictReplace(ac->sub.patterns,sname,&cb); - else - dictReplace(ac->sub.channels,sname,&cb); - } - } else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) { - /* It is only useful to call (P)UNSUBSCRIBE when the context is - * subscribed to one or more channels or patterns. */ - if (!(c->flags & REDIS_SUBSCRIBED)) return REDIS_ERR; - - /* (P)UNSUBSCRIBE does not have its own response: every channel or - * pattern that is unsubscribed will receive a message. This means we - * should not append a callback function for this command. */ - } else { - if (c->flags & REDIS_SUBSCRIBED) - /* This will likely result in an error reply, but it needs to be - * received and passed to the callback. */ - __redisPushCallback(&ac->sub.invalid,&cb); - else - __redisPushCallback(&ac->replies,&cb); - } - - __redisAppendCommand(c,cmd,len); - - /* Always schedule a write when the write buffer is non-empty */ - _EL_ADD_WRITE(ac); - - return REDIS_OK; -} - -int redisvAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, va_list ap) { - char *cmd; - int len; - int status; - len = redisvFormatCommand(&cmd,format,ap); - status = __redisAsyncCommand(ac,fn,privdata,cmd,len); - free(cmd); - return status; -} - -int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, ...) { - va_list ap; - int status; - va_start(ap,format); - status = redisvAsyncCommand(ac,fn,privdata,format,ap); - va_end(ap); - return status; -} - -int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen) { - char *cmd; - int len; - int status; - len = redisFormatCommandArgv(&cmd,argc,argv,argvlen); - status = __redisAsyncCommand(ac,fn,privdata,cmd,len); - free(cmd); - return status; -} diff --git a/node_modules/hiredis/deps/hiredis/async.h b/node_modules/hiredis/deps/hiredis/async.h deleted file mode 100644 index 268274e..0000000 --- a/node_modules/hiredis/deps/hiredis/async.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2009-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __HIREDIS_ASYNC_H -#define __HIREDIS_ASYNC_H -#include "hiredis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct redisAsyncContext; /* need forward declaration of redisAsyncContext */ -struct dict; /* dictionary header is included in async.c */ - -/* Reply callback prototype and container */ -typedef void (redisCallbackFn)(struct redisAsyncContext*, void*, void*); -typedef struct redisCallback { - struct redisCallback *next; /* simple singly linked list */ - redisCallbackFn *fn; - void *privdata; -} redisCallback; - -/* List of callbacks for either regular replies or pub/sub */ -typedef struct redisCallbackList { - redisCallback *head, *tail; -} redisCallbackList; - -/* Connection callback prototypes */ -typedef void (redisDisconnectCallback)(const struct redisAsyncContext*, int status); -typedef void (redisConnectCallback)(const struct redisAsyncContext*, int status); - -/* Context for an async connection to Redis */ -typedef struct redisAsyncContext { - /* Hold the regular context, so it can be realloc'ed. */ - redisContext c; - - /* Setup error flags so they can be used directly. */ - int err; - char *errstr; - - /* Not used by hiredis */ - void *data; - - /* Event library data and hooks */ - struct { - void *data; - - /* Hooks that are called when the library expects to start - * reading/writing. These functions should be idempotent. */ - void (*addRead)(void *privdata); - void (*delRead)(void *privdata); - void (*addWrite)(void *privdata); - void (*delWrite)(void *privdata); - void (*cleanup)(void *privdata); - } ev; - - /* Called when either the connection is terminated due to an error or per - * user request. The status is set accordingly (REDIS_OK, REDIS_ERR). */ - redisDisconnectCallback *onDisconnect; - - /* Called when the first write event was received. */ - redisConnectCallback *onConnect; - - /* Regular command callbacks */ - redisCallbackList replies; - - /* Subscription callbacks */ - struct { - redisCallbackList invalid; - struct dict *channels; - struct dict *patterns; - } sub; -} redisAsyncContext; - -/* Functions that proxy to hiredis */ -redisAsyncContext *redisAsyncConnect(const char *ip, int port); -redisAsyncContext *redisAsyncConnectUnix(const char *path); -int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn); -int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn); -void redisAsyncDisconnect(redisAsyncContext *ac); -void redisAsyncFree(redisAsyncContext *ac); - -/* Handle read/write events */ -void redisAsyncHandleRead(redisAsyncContext *ac); -void redisAsyncHandleWrite(redisAsyncContext *ac); - -/* Command functions for an async context. Write the command to the - * output buffer and register the provided callback. */ -int redisvAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, va_list ap); -int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, ...); -int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/node_modules/hiredis/deps/hiredis/async.o b/node_modules/hiredis/deps/hiredis/async.o deleted file mode 100644 index d2ddee7..0000000 Binary files a/node_modules/hiredis/deps/hiredis/async.o and /dev/null differ diff --git a/node_modules/hiredis/deps/hiredis/dict.c b/node_modules/hiredis/deps/hiredis/dict.c deleted file mode 100644 index 79b1041..0000000 --- a/node_modules/hiredis/deps/hiredis/dict.c +++ /dev/null @@ -1,338 +0,0 @@ -/* Hash table implementation. - * - * This file implements in memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) - * - * Copyright (c) 2006-2010, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fmacros.h" -#include -#include -#include -#include "dict.h" - -/* -------------------------- private prototypes ---------------------------- */ - -static int _dictExpandIfNeeded(dict *ht); -static unsigned long _dictNextPower(unsigned long size); -static int _dictKeyIndex(dict *ht, const void *key); -static int _dictInit(dict *ht, dictType *type, void *privDataPtr); - -/* -------------------------- hash functions -------------------------------- */ - -/* Generic hash function (a popular one from Bernstein). - * I tested a few and this was the best. */ -static unsigned int dictGenHashFunction(const unsigned char *buf, int len) { - unsigned int hash = 5381; - - while (len--) - hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */ - return hash; -} - -/* ----------------------------- API implementation ------------------------- */ - -/* Reset an hashtable already initialized with ht_init(). - * NOTE: This function should only called by ht_destroy(). */ -static void _dictReset(dict *ht) { - ht->table = NULL; - ht->size = 0; - ht->sizemask = 0; - ht->used = 0; -} - -/* Create a new hash table */ -static dict *dictCreate(dictType *type, void *privDataPtr) { - dict *ht = malloc(sizeof(*ht)); - _dictInit(ht,type,privDataPtr); - return ht; -} - -/* Initialize the hash table */ -static int _dictInit(dict *ht, dictType *type, void *privDataPtr) { - _dictReset(ht); - ht->type = type; - ht->privdata = privDataPtr; - return DICT_OK; -} - -/* Expand or create the hashtable */ -static int dictExpand(dict *ht, unsigned long size) { - dict n; /* the new hashtable */ - unsigned long realsize = _dictNextPower(size), i; - - /* the size is invalid if it is smaller than the number of - * elements already inside the hashtable */ - if (ht->used > size) - return DICT_ERR; - - _dictInit(&n, ht->type, ht->privdata); - n.size = realsize; - n.sizemask = realsize-1; - n.table = calloc(realsize,sizeof(dictEntry*)); - - /* Copy all the elements from the old to the new table: - * note that if the old hash table is empty ht->size is zero, - * so dictExpand just creates an hash table. */ - n.used = ht->used; - for (i = 0; i < ht->size && ht->used > 0; i++) { - dictEntry *he, *nextHe; - - if (ht->table[i] == NULL) continue; - - /* For each hash entry on this slot... */ - he = ht->table[i]; - while(he) { - unsigned int h; - - nextHe = he->next; - /* Get the new element index */ - h = dictHashKey(ht, he->key) & n.sizemask; - he->next = n.table[h]; - n.table[h] = he; - ht->used--; - /* Pass to the next element */ - he = nextHe; - } - } - assert(ht->used == 0); - free(ht->table); - - /* Remap the new hashtable in the old */ - *ht = n; - return DICT_OK; -} - -/* Add an element to the target hash table */ -static int dictAdd(dict *ht, void *key, void *val) { - int index; - dictEntry *entry; - - /* Get the index of the new element, or -1 if - * the element already exists. */ - if ((index = _dictKeyIndex(ht, key)) == -1) - return DICT_ERR; - - /* Allocates the memory and stores key */ - entry = malloc(sizeof(*entry)); - entry->next = ht->table[index]; - ht->table[index] = entry; - - /* Set the hash entry fields. */ - dictSetHashKey(ht, entry, key); - dictSetHashVal(ht, entry, val); - ht->used++; - return DICT_OK; -} - -/* Add an element, discarding the old if the key already exists. - * Return 1 if the key was added from scratch, 0 if there was already an - * element with such key and dictReplace() just performed a value update - * operation. */ -static int dictReplace(dict *ht, void *key, void *val) { - dictEntry *entry, auxentry; - - /* Try to add the element. If the key - * does not exists dictAdd will suceed. */ - if (dictAdd(ht, key, val) == DICT_OK) - return 1; - /* It already exists, get the entry */ - entry = dictFind(ht, key); - /* Free the old value and set the new one */ - /* Set the new value and free the old one. Note that it is important - * to do that in this order, as the value may just be exactly the same - * as the previous one. In this context, think to reference counting, - * you want to increment (set), and then decrement (free), and not the - * reverse. */ - auxentry = *entry; - dictSetHashVal(ht, entry, val); - dictFreeEntryVal(ht, &auxentry); - return 0; -} - -/* Search and remove an element */ -static int dictDelete(dict *ht, const void *key) { - unsigned int h; - dictEntry *de, *prevde; - - if (ht->size == 0) - return DICT_ERR; - h = dictHashKey(ht, key) & ht->sizemask; - de = ht->table[h]; - - prevde = NULL; - while(de) { - if (dictCompareHashKeys(ht,key,de->key)) { - /* Unlink the element from the list */ - if (prevde) - prevde->next = de->next; - else - ht->table[h] = de->next; - - dictFreeEntryKey(ht,de); - dictFreeEntryVal(ht,de); - free(de); - ht->used--; - return DICT_OK; - } - prevde = de; - de = de->next; - } - return DICT_ERR; /* not found */ -} - -/* Destroy an entire hash table */ -static int _dictClear(dict *ht) { - unsigned long i; - - /* Free all the elements */ - for (i = 0; i < ht->size && ht->used > 0; i++) { - dictEntry *he, *nextHe; - - if ((he = ht->table[i]) == NULL) continue; - while(he) { - nextHe = he->next; - dictFreeEntryKey(ht, he); - dictFreeEntryVal(ht, he); - free(he); - ht->used--; - he = nextHe; - } - } - /* Free the table and the allocated cache structure */ - free(ht->table); - /* Re-initialize the table */ - _dictReset(ht); - return DICT_OK; /* never fails */ -} - -/* Clear & Release the hash table */ -static void dictRelease(dict *ht) { - _dictClear(ht); - free(ht); -} - -static dictEntry *dictFind(dict *ht, const void *key) { - dictEntry *he; - unsigned int h; - - if (ht->size == 0) return NULL; - h = dictHashKey(ht, key) & ht->sizemask; - he = ht->table[h]; - while(he) { - if (dictCompareHashKeys(ht, key, he->key)) - return he; - he = he->next; - } - return NULL; -} - -static dictIterator *dictGetIterator(dict *ht) { - dictIterator *iter = malloc(sizeof(*iter)); - - iter->ht = ht; - iter->index = -1; - iter->entry = NULL; - iter->nextEntry = NULL; - return iter; -} - -static dictEntry *dictNext(dictIterator *iter) { - while (1) { - if (iter->entry == NULL) { - iter->index++; - if (iter->index >= - (signed)iter->ht->size) break; - iter->entry = iter->ht->table[iter->index]; - } else { - iter->entry = iter->nextEntry; - } - if (iter->entry) { - /* We need to save the 'next' here, the iterator user - * may delete the entry we are returning. */ - iter->nextEntry = iter->entry->next; - return iter->entry; - } - } - return NULL; -} - -static void dictReleaseIterator(dictIterator *iter) { - free(iter); -} - -/* ------------------------- private functions ------------------------------ */ - -/* Expand the hash table if needed */ -static int _dictExpandIfNeeded(dict *ht) { - /* If the hash table is empty expand it to the intial size, - * if the table is "full" dobule its size. */ - if (ht->size == 0) - return dictExpand(ht, DICT_HT_INITIAL_SIZE); - if (ht->used == ht->size) - return dictExpand(ht, ht->size*2); - return DICT_OK; -} - -/* Our hash table capability is a power of two */ -static unsigned long _dictNextPower(unsigned long size) { - unsigned long i = DICT_HT_INITIAL_SIZE; - - if (size >= LONG_MAX) return LONG_MAX; - while(1) { - if (i >= size) - return i; - i *= 2; - } -} - -/* Returns the index of a free slot that can be populated with - * an hash entry for the given 'key'. - * If the key already exists, -1 is returned. */ -static int _dictKeyIndex(dict *ht, const void *key) { - unsigned int h; - dictEntry *he; - - /* Expand the hashtable if needed */ - if (_dictExpandIfNeeded(ht) == DICT_ERR) - return -1; - /* Compute the key hash value */ - h = dictHashKey(ht, key) & ht->sizemask; - /* Search if this slot does not already contain the given key */ - he = ht->table[h]; - while(he) { - if (dictCompareHashKeys(ht, key, he->key)) - return -1; - he = he->next; - } - return h; -} - diff --git a/node_modules/hiredis/deps/hiredis/dict.h b/node_modules/hiredis/deps/hiredis/dict.h deleted file mode 100644 index 95fcd28..0000000 --- a/node_modules/hiredis/deps/hiredis/dict.h +++ /dev/null @@ -1,126 +0,0 @@ -/* Hash table implementation. - * - * This file implements in memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) - * - * Copyright (c) 2006-2010, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __DICT_H -#define __DICT_H - -#define DICT_OK 0 -#define DICT_ERR 1 - -/* Unused arguments generate annoying warnings... */ -#define DICT_NOTUSED(V) ((void) V) - -typedef struct dictEntry { - void *key; - void *val; - struct dictEntry *next; -} dictEntry; - -typedef struct dictType { - unsigned int (*hashFunction)(const void *key); - void *(*keyDup)(void *privdata, const void *key); - void *(*valDup)(void *privdata, const void *obj); - int (*keyCompare)(void *privdata, const void *key1, const void *key2); - void (*keyDestructor)(void *privdata, void *key); - void (*valDestructor)(void *privdata, void *obj); -} dictType; - -typedef struct dict { - dictEntry **table; - dictType *type; - unsigned long size; - unsigned long sizemask; - unsigned long used; - void *privdata; -} dict; - -typedef struct dictIterator { - dict *ht; - int index; - dictEntry *entry, *nextEntry; -} dictIterator; - -/* This is the initial size of every hash table */ -#define DICT_HT_INITIAL_SIZE 4 - -/* ------------------------------- Macros ------------------------------------*/ -#define dictFreeEntryVal(ht, entry) \ - if ((ht)->type->valDestructor) \ - (ht)->type->valDestructor((ht)->privdata, (entry)->val) - -#define dictSetHashVal(ht, entry, _val_) do { \ - if ((ht)->type->valDup) \ - entry->val = (ht)->type->valDup((ht)->privdata, _val_); \ - else \ - entry->val = (_val_); \ -} while(0) - -#define dictFreeEntryKey(ht, entry) \ - if ((ht)->type->keyDestructor) \ - (ht)->type->keyDestructor((ht)->privdata, (entry)->key) - -#define dictSetHashKey(ht, entry, _key_) do { \ - if ((ht)->type->keyDup) \ - entry->key = (ht)->type->keyDup((ht)->privdata, _key_); \ - else \ - entry->key = (_key_); \ -} while(0) - -#define dictCompareHashKeys(ht, key1, key2) \ - (((ht)->type->keyCompare) ? \ - (ht)->type->keyCompare((ht)->privdata, key1, key2) : \ - (key1) == (key2)) - -#define dictHashKey(ht, key) (ht)->type->hashFunction(key) - -#define dictGetEntryKey(he) ((he)->key) -#define dictGetEntryVal(he) ((he)->val) -#define dictSlots(ht) ((ht)->size) -#define dictSize(ht) ((ht)->used) - -/* API */ -static unsigned int dictGenHashFunction(const unsigned char *buf, int len); -static dict *dictCreate(dictType *type, void *privDataPtr); -static int dictExpand(dict *ht, unsigned long size); -static int dictAdd(dict *ht, void *key, void *val); -static int dictReplace(dict *ht, void *key, void *val); -static int dictDelete(dict *ht, const void *key); -static void dictRelease(dict *ht); -static dictEntry * dictFind(dict *ht, const void *key); -static dictIterator *dictGetIterator(dict *ht); -static dictEntry *dictNext(dictIterator *iter); -static void dictReleaseIterator(dictIterator *iter); - -#endif /* __DICT_H */ diff --git a/node_modules/hiredis/deps/hiredis/example-ae.c b/node_modules/hiredis/deps/hiredis/example-ae.c deleted file mode 100644 index 5ed34a3..0000000 --- a/node_modules/hiredis/deps/hiredis/example-ae.c +++ /dev/null @@ -1,56 +0,0 @@ -#include -#include -#include -#include -#include "hiredis.h" -#include "async.h" -#include "adapters/ae.h" - -/* Put event loop in the global scope, so it can be explicitly stopped */ -static aeEventLoop *loop; - -void getCallback(redisAsyncContext *c, void *r, void *privdata) { - redisReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); - - /* Disconnect after receiving the reply to GET */ - redisAsyncDisconnect(c); -} - -void connectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Connected...\n"); -} - -void disconnectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Disconnected...\n"); -} - -int main (int argc, char **argv) { - signal(SIGPIPE, SIG_IGN); - - redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); - if (c->err) { - /* Let *c leak for now... */ - printf("Error: %s\n", c->errstr); - return 1; - } - - loop = aeCreateEventLoop(); - redisAeAttach(loop, c); - redisAsyncSetConnectCallback(c,connectCallback); - redisAsyncSetDisconnectCallback(c,disconnectCallback); - redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); - aeMain(loop); - return 0; -} - diff --git a/node_modules/hiredis/deps/hiredis/example-libev.c b/node_modules/hiredis/deps/hiredis/example-libev.c deleted file mode 100644 index 7894f1f..0000000 --- a/node_modules/hiredis/deps/hiredis/example-libev.c +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include -#include -#include -#include "hiredis.h" -#include "async.h" -#include "adapters/libev.h" - -void getCallback(redisAsyncContext *c, void *r, void *privdata) { - redisReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); - - /* Disconnect after receiving the reply to GET */ - redisAsyncDisconnect(c); -} - -void connectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Connected...\n"); -} - -void disconnectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Disconnected...\n"); -} - -int main (int argc, char **argv) { - signal(SIGPIPE, SIG_IGN); - - redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); - if (c->err) { - /* Let *c leak for now... */ - printf("Error: %s\n", c->errstr); - return 1; - } - - redisLibevAttach(EV_DEFAULT_ c); - redisAsyncSetConnectCallback(c,connectCallback); - redisAsyncSetDisconnectCallback(c,disconnectCallback); - redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); - ev_loop(EV_DEFAULT_ 0); - return 0; -} diff --git a/node_modules/hiredis/deps/hiredis/example-libevent.c b/node_modules/hiredis/deps/hiredis/example-libevent.c deleted file mode 100644 index 9da8e02..0000000 --- a/node_modules/hiredis/deps/hiredis/example-libevent.c +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -#include -#include "hiredis.h" -#include "async.h" -#include "adapters/libevent.h" - -void getCallback(redisAsyncContext *c, void *r, void *privdata) { - redisReply *reply = r; - if (reply == NULL) return; - printf("argv[%s]: %s\n", (char*)privdata, reply->str); - - /* Disconnect after receiving the reply to GET */ - redisAsyncDisconnect(c); -} - -void connectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Connected...\n"); -} - -void disconnectCallback(const redisAsyncContext *c, int status) { - if (status != REDIS_OK) { - printf("Error: %s\n", c->errstr); - return; - } - printf("Disconnected...\n"); -} - -int main (int argc, char **argv) { - signal(SIGPIPE, SIG_IGN); - struct event_base *base = event_base_new(); - - redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); - if (c->err) { - /* Let *c leak for now... */ - printf("Error: %s\n", c->errstr); - return 1; - } - - redisLibeventAttach(c,base); - redisAsyncSetConnectCallback(c,connectCallback); - redisAsyncSetDisconnectCallback(c,disconnectCallback); - redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); - redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); - event_base_dispatch(base); - return 0; -} diff --git a/node_modules/hiredis/deps/hiredis/example.c b/node_modules/hiredis/deps/hiredis/example.c deleted file mode 100644 index 90ff9ed..0000000 --- a/node_modules/hiredis/deps/hiredis/example.c +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include - -#include "hiredis.h" - -int main(void) { - unsigned int j; - redisContext *c; - redisReply *reply; - - struct timeval timeout = { 1, 500000 }; // 1.5 seconds - c = redisConnectWithTimeout((char*)"127.0.0.2", 6379, timeout); - if (c->err) { - printf("Connection error: %s\n", c->errstr); - exit(1); - } - - /* PING server */ - reply = redisCommand(c,"PING"); - printf("PING: %s\n", reply->str); - freeReplyObject(reply); - - /* Set a key */ - reply = redisCommand(c,"SET %s %s", "foo", "hello world"); - printf("SET: %s\n", reply->str); - freeReplyObject(reply); - - /* Set a key using binary safe API */ - reply = redisCommand(c,"SET %b %b", "bar", 3, "hello", 5); - printf("SET (binary API): %s\n", reply->str); - freeReplyObject(reply); - - /* Try a GET and two INCR */ - reply = redisCommand(c,"GET foo"); - printf("GET foo: %s\n", reply->str); - freeReplyObject(reply); - - reply = redisCommand(c,"INCR counter"); - printf("INCR counter: %lld\n", reply->integer); - freeReplyObject(reply); - /* again ... */ - reply = redisCommand(c,"INCR counter"); - printf("INCR counter: %lld\n", reply->integer); - freeReplyObject(reply); - - /* Create a list of numbers, from 0 to 9 */ - reply = redisCommand(c,"DEL mylist"); - freeReplyObject(reply); - for (j = 0; j < 10; j++) { - char buf[64]; - - snprintf(buf,64,"%d",j); - reply = redisCommand(c,"LPUSH mylist element-%s", buf); - freeReplyObject(reply); - } - - /* Let's check what we have inside the list */ - reply = redisCommand(c,"LRANGE mylist 0 -1"); - if (reply->type == REDIS_REPLY_ARRAY) { - for (j = 0; j < reply->elements; j++) { - printf("%u) %s\n", j, reply->element[j]->str); - } - } - freeReplyObject(reply); - - return 0; -} diff --git a/node_modules/hiredis/deps/hiredis/fmacros.h b/node_modules/hiredis/deps/hiredis/fmacros.h deleted file mode 100644 index 21cd9cf..0000000 --- a/node_modules/hiredis/deps/hiredis/fmacros.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef __HIREDIS_FMACRO_H -#define __HIREDIS_FMACRO_H - -#if !defined(_BSD_SOURCE) -#define _BSD_SOURCE -#endif - -#if defined(__sun__) -#define _POSIX_C_SOURCE 200112L -#elif defined(__linux__) -#define _XOPEN_SOURCE 600 -#else -#define _XOPEN_SOURCE -#endif - -#endif diff --git a/node_modules/hiredis/deps/hiredis/hiredis.c b/node_modules/hiredis/deps/hiredis/hiredis.c deleted file mode 100644 index 1a57adb..0000000 --- a/node_modules/hiredis/deps/hiredis/hiredis.c +++ /dev/null @@ -1,1284 +0,0 @@ -/* - * Copyright (c) 2009-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fmacros.h" -#include -#include -#include -#include -#include -#include - -#include "hiredis.h" -#include "net.h" -#include "sds.h" - -static redisReply *createReplyObject(int type); -static void *createStringObject(const redisReadTask *task, char *str, size_t len); -static void *createArrayObject(const redisReadTask *task, int elements); -static void *createIntegerObject(const redisReadTask *task, long long value); -static void *createNilObject(const redisReadTask *task); - -/* Default set of functions to build the reply. Keep in mind that such a - * function returning NULL is interpreted as OOM. */ -static redisReplyObjectFunctions defaultFunctions = { - createStringObject, - createArrayObject, - createIntegerObject, - createNilObject, - freeReplyObject -}; - -/* Create a reply object */ -static redisReply *createReplyObject(int type) { - redisReply *r = calloc(1,sizeof(*r)); - - if (r == NULL) - return NULL; - - r->type = type; - return r; -} - -/* Free a reply object */ -void freeReplyObject(void *reply) { - redisReply *r = reply; - size_t j; - - switch(r->type) { - case REDIS_REPLY_INTEGER: - break; /* Nothing to free */ - case REDIS_REPLY_ARRAY: - if (r->element != NULL) { - for (j = 0; j < r->elements; j++) - if (r->element[j] != NULL) - freeReplyObject(r->element[j]); - free(r->element); - } - break; - case REDIS_REPLY_ERROR: - case REDIS_REPLY_STATUS: - case REDIS_REPLY_STRING: - if (r->str != NULL) - free(r->str); - break; - } - free(r); -} - -static void *createStringObject(const redisReadTask *task, char *str, size_t len) { - redisReply *r, *parent; - char *buf; - - r = createReplyObject(task->type); - if (r == NULL) - return NULL; - - buf = malloc(len+1); - if (buf == NULL) { - freeReplyObject(r); - return NULL; - } - - assert(task->type == REDIS_REPLY_ERROR || - task->type == REDIS_REPLY_STATUS || - task->type == REDIS_REPLY_STRING); - - /* Copy string value */ - memcpy(buf,str,len); - buf[len] = '\0'; - r->str = buf; - r->len = len; - - if (task->parent) { - parent = task->parent->obj; - assert(parent->type == REDIS_REPLY_ARRAY); - parent->element[task->idx] = r; - } - return r; -} - -static void *createArrayObject(const redisReadTask *task, int elements) { - redisReply *r, *parent; - - r = createReplyObject(REDIS_REPLY_ARRAY); - if (r == NULL) - return NULL; - - if (elements > 0) { - r->element = calloc(elements,sizeof(redisReply*)); - if (r->element == NULL) { - freeReplyObject(r); - return NULL; - } - } - - r->elements = elements; - - if (task->parent) { - parent = task->parent->obj; - assert(parent->type == REDIS_REPLY_ARRAY); - parent->element[task->idx] = r; - } - return r; -} - -static void *createIntegerObject(const redisReadTask *task, long long value) { - redisReply *r, *parent; - - r = createReplyObject(REDIS_REPLY_INTEGER); - if (r == NULL) - return NULL; - - r->integer = value; - - if (task->parent) { - parent = task->parent->obj; - assert(parent->type == REDIS_REPLY_ARRAY); - parent->element[task->idx] = r; - } - return r; -} - -static void *createNilObject(const redisReadTask *task) { - redisReply *r, *parent; - - r = createReplyObject(REDIS_REPLY_NIL); - if (r == NULL) - return NULL; - - if (task->parent) { - parent = task->parent->obj; - assert(parent->type == REDIS_REPLY_ARRAY); - parent->element[task->idx] = r; - } - return r; -} - -static void __redisReaderSetError(redisReader *r, int type, const char *str) { - size_t len; - - if (r->reply != NULL && r->fn && r->fn->freeObject) { - r->fn->freeObject(r->reply); - r->reply = NULL; - } - - /* Clear input buffer on errors. */ - if (r->buf != NULL) { - sdsfree(r->buf); - r->buf = NULL; - r->pos = r->len = 0; - } - - /* Reset task stack. */ - r->ridx = -1; - - /* Set error. */ - r->err = type; - len = strlen(str); - len = len < (sizeof(r->errstr)-1) ? len : (sizeof(r->errstr)-1); - memcpy(r->errstr,str,len); - r->errstr[len] = '\0'; -} - -static size_t chrtos(char *buf, size_t size, char byte) { - size_t len = 0; - - switch(byte) { - case '\\': - case '"': - len = snprintf(buf,size,"\"\\%c\"",byte); - break; - case '\n': len = snprintf(buf,size,"\"\\n\""); break; - case '\r': len = snprintf(buf,size,"\"\\r\""); break; - case '\t': len = snprintf(buf,size,"\"\\t\""); break; - case '\a': len = snprintf(buf,size,"\"\\a\""); break; - case '\b': len = snprintf(buf,size,"\"\\b\""); break; - default: - if (isprint(byte)) - len = snprintf(buf,size,"\"%c\"",byte); - else - len = snprintf(buf,size,"\"\\x%02x\"",(unsigned char)byte); - break; - } - - return len; -} - -static void __redisReaderSetErrorProtocolByte(redisReader *r, char byte) { - char cbuf[8], sbuf[128]; - - chrtos(cbuf,sizeof(cbuf),byte); - snprintf(sbuf,sizeof(sbuf), - "Protocol error, got %s as reply type byte", cbuf); - __redisReaderSetError(r,REDIS_ERR_PROTOCOL,sbuf); -} - -static void __redisReaderSetErrorOOM(redisReader *r) { - __redisReaderSetError(r,REDIS_ERR_OOM,"Out of memory"); -} - -static char *readBytes(redisReader *r, unsigned int bytes) { - char *p; - if (r->len-r->pos >= bytes) { - p = r->buf+r->pos; - r->pos += bytes; - return p; - } - return NULL; -} - -/* Find pointer to \r\n. */ -static char *seekNewline(char *s, size_t len) { - int pos = 0; - int _len = len-1; - - /* Position should be < len-1 because the character at "pos" should be - * followed by a \n. Note that strchr cannot be used because it doesn't - * allow to search a limited length and the buffer that is being searched - * might not have a trailing NULL character. */ - while (pos < _len) { - while(pos < _len && s[pos] != '\r') pos++; - if (s[pos] != '\r') { - /* Not found. */ - return NULL; - } else { - if (s[pos+1] == '\n') { - /* Found. */ - return s+pos; - } else { - /* Continue searching. */ - pos++; - } - } - } - return NULL; -} - -/* Read a long long value starting at *s, under the assumption that it will be - * terminated by \r\n. Ambiguously returns -1 for unexpected input. */ -static long long readLongLong(char *s) { - long long v = 0; - int dec, mult = 1; - char c; - - if (*s == '-') { - mult = -1; - s++; - } else if (*s == '+') { - mult = 1; - s++; - } - - while ((c = *(s++)) != '\r') { - dec = c - '0'; - if (dec >= 0 && dec < 10) { - v *= 10; - v += dec; - } else { - /* Should not happen... */ - return -1; - } - } - - return mult*v; -} - -static char *readLine(redisReader *r, int *_len) { - char *p, *s; - int len; - - p = r->buf+r->pos; - s = seekNewline(p,(r->len-r->pos)); - if (s != NULL) { - len = s-(r->buf+r->pos); - r->pos += len+2; /* skip \r\n */ - if (_len) *_len = len; - return p; - } - return NULL; -} - -static void moveToNextTask(redisReader *r) { - redisReadTask *cur, *prv; - while (r->ridx >= 0) { - /* Return a.s.a.p. when the stack is now empty. */ - if (r->ridx == 0) { - r->ridx--; - return; - } - - cur = &(r->rstack[r->ridx]); - prv = &(r->rstack[r->ridx-1]); - assert(prv->type == REDIS_REPLY_ARRAY); - if (cur->idx == prv->elements-1) { - r->ridx--; - } else { - /* Reset the type because the next item can be anything */ - assert(cur->idx < prv->elements); - cur->type = -1; - cur->elements = -1; - cur->idx++; - return; - } - } -} - -static int processLineItem(redisReader *r) { - redisReadTask *cur = &(r->rstack[r->ridx]); - void *obj; - char *p; - int len; - - if ((p = readLine(r,&len)) != NULL) { - if (cur->type == REDIS_REPLY_INTEGER) { - if (r->fn && r->fn->createInteger) - obj = r->fn->createInteger(cur,readLongLong(p)); - else - obj = (void*)REDIS_REPLY_INTEGER; - } else { - /* Type will be error or status. */ - if (r->fn && r->fn->createString) - obj = r->fn->createString(cur,p,len); - else - obj = (void*)(size_t)(cur->type); - } - - if (obj == NULL) { - __redisReaderSetErrorOOM(r); - return REDIS_ERR; - } - - /* Set reply if this is the root object. */ - if (r->ridx == 0) r->reply = obj; - moveToNextTask(r); - return REDIS_OK; - } - - return REDIS_ERR; -} - -static int processBulkItem(redisReader *r) { - redisReadTask *cur = &(r->rstack[r->ridx]); - void *obj = NULL; - char *p, *s; - long len; - unsigned long bytelen; - int success = 0; - - p = r->buf+r->pos; - s = seekNewline(p,r->len-r->pos); - if (s != NULL) { - p = r->buf+r->pos; - bytelen = s-(r->buf+r->pos)+2; /* include \r\n */ - len = readLongLong(p); - - if (len < 0) { - /* The nil object can always be created. */ - if (r->fn && r->fn->createNil) - obj = r->fn->createNil(cur); - else - obj = (void*)REDIS_REPLY_NIL; - success = 1; - } else { - /* Only continue when the buffer contains the entire bulk item. */ - bytelen += len+2; /* include \r\n */ - if (r->pos+bytelen <= r->len) { - if (r->fn && r->fn->createString) - obj = r->fn->createString(cur,s+2,len); - else - obj = (void*)REDIS_REPLY_STRING; - success = 1; - } - } - - /* Proceed when obj was created. */ - if (success) { - if (obj == NULL) { - __redisReaderSetErrorOOM(r); - return REDIS_ERR; - } - - r->pos += bytelen; - - /* Set reply if this is the root object. */ - if (r->ridx == 0) r->reply = obj; - moveToNextTask(r); - return REDIS_OK; - } - } - - return REDIS_ERR; -} - -static int processMultiBulkItem(redisReader *r) { - redisReadTask *cur = &(r->rstack[r->ridx]); - void *obj; - char *p; - long elements; - int root = 0; - - /* Set error for nested multi bulks with depth > 2 */ - if (r->ridx == 3) { - __redisReaderSetError(r,REDIS_ERR_PROTOCOL, - "No support for nested multi bulk replies with depth > 2"); - return REDIS_ERR; - } - - if ((p = readLine(r,NULL)) != NULL) { - elements = readLongLong(p); - root = (r->ridx == 0); - - if (elements == -1) { - if (r->fn && r->fn->createNil) - obj = r->fn->createNil(cur); - else - obj = (void*)REDIS_REPLY_NIL; - - if (obj == NULL) { - __redisReaderSetErrorOOM(r); - return REDIS_ERR; - } - - moveToNextTask(r); - } else { - if (r->fn && r->fn->createArray) - obj = r->fn->createArray(cur,elements); - else - obj = (void*)REDIS_REPLY_ARRAY; - - if (obj == NULL) { - __redisReaderSetErrorOOM(r); - return REDIS_ERR; - } - - /* Modify task stack when there are more than 0 elements. */ - if (elements > 0) { - cur->elements = elements; - cur->obj = obj; - r->ridx++; - r->rstack[r->ridx].type = -1; - r->rstack[r->ridx].elements = -1; - r->rstack[r->ridx].idx = 0; - r->rstack[r->ridx].obj = NULL; - r->rstack[r->ridx].parent = cur; - r->rstack[r->ridx].privdata = r->privdata; - } else { - moveToNextTask(r); - } - } - - /* Set reply if this is the root object. */ - if (root) r->reply = obj; - return REDIS_OK; - } - - return REDIS_ERR; -} - -static int processItem(redisReader *r) { - redisReadTask *cur = &(r->rstack[r->ridx]); - char *p; - - /* check if we need to read type */ - if (cur->type < 0) { - if ((p = readBytes(r,1)) != NULL) { - switch (p[0]) { - case '-': - cur->type = REDIS_REPLY_ERROR; - break; - case '+': - cur->type = REDIS_REPLY_STATUS; - break; - case ':': - cur->type = REDIS_REPLY_INTEGER; - break; - case '$': - cur->type = REDIS_REPLY_STRING; - break; - case '*': - cur->type = REDIS_REPLY_ARRAY; - break; - default: - __redisReaderSetErrorProtocolByte(r,*p); - return REDIS_ERR; - } - } else { - /* could not consume 1 byte */ - return REDIS_ERR; - } - } - - /* process typed item */ - switch(cur->type) { - case REDIS_REPLY_ERROR: - case REDIS_REPLY_STATUS: - case REDIS_REPLY_INTEGER: - return processLineItem(r); - case REDIS_REPLY_STRING: - return processBulkItem(r); - case REDIS_REPLY_ARRAY: - return processMultiBulkItem(r); - default: - assert(NULL); - return REDIS_ERR; /* Avoid warning. */ - } -} - -redisReader *redisReaderCreate(void) { - redisReader *r; - - r = calloc(sizeof(redisReader),1); - if (r == NULL) - return NULL; - - r->err = 0; - r->errstr[0] = '\0'; - r->fn = &defaultFunctions; - r->buf = sdsempty(); - if (r->buf == NULL) { - free(r); - return NULL; - } - - r->ridx = -1; - return r; -} - -void redisReaderFree(redisReader *r) { - if (r->reply != NULL && r->fn && r->fn->freeObject) - r->fn->freeObject(r->reply); - if (r->buf != NULL) - sdsfree(r->buf); - free(r); -} - -int redisReaderFeed(redisReader *r, const char *buf, size_t len) { - sds newbuf; - - /* Return early when this reader is in an erroneous state. */ - if (r->err) - return REDIS_ERR; - - /* Copy the provided buffer. */ - if (buf != NULL && len >= 1) { - /* Destroy internal buffer when it is empty and is quite large. */ - if (r->len == 0 && sdsavail(r->buf) > 16*1024) { - sdsfree(r->buf); - r->buf = sdsempty(); - r->pos = 0; - - /* r->buf should not be NULL since we just free'd a larger one. */ - assert(r->buf != NULL); - } - - newbuf = sdscatlen(r->buf,buf,len); - if (newbuf == NULL) { - __redisReaderSetErrorOOM(r); - return REDIS_ERR; - } - - r->buf = newbuf; - r->len = sdslen(r->buf); - } - - return REDIS_OK; -} - -int redisReaderGetReply(redisReader *r, void **reply) { - /* Default target pointer to NULL. */ - if (reply != NULL) - *reply = NULL; - - /* Return early when this reader is in an erroneous state. */ - if (r->err) - return REDIS_ERR; - - /* When the buffer is empty, there will never be a reply. */ - if (r->len == 0) - return REDIS_OK; - - /* Set first item to process when the stack is empty. */ - if (r->ridx == -1) { - r->rstack[0].type = -1; - r->rstack[0].elements = -1; - r->rstack[0].idx = -1; - r->rstack[0].obj = NULL; - r->rstack[0].parent = NULL; - r->rstack[0].privdata = r->privdata; - r->ridx = 0; - } - - /* Process items in reply. */ - while (r->ridx >= 0) - if (processItem(r) != REDIS_OK) - break; - - /* Return ASAP when an error occurred. */ - if (r->err) - return REDIS_ERR; - - /* Discard part of the buffer when we've consumed at least 1k, to avoid - * doing unnecessary calls to memmove() in sds.c. */ - if (r->pos >= 1024) { - r->buf = sdsrange(r->buf,r->pos,-1); - r->pos = 0; - r->len = sdslen(r->buf); - } - - /* Emit a reply when there is one. */ - if (r->ridx == -1) { - if (reply != NULL) - *reply = r->reply; - r->reply = NULL; - } - return REDIS_OK; -} - -/* Calculate the number of bytes needed to represent an integer as string. */ -static int intlen(int i) { - int len = 0; - if (i < 0) { - len++; - i = -i; - } - do { - len++; - i /= 10; - } while(i); - return len; -} - -/* Helper that calculates the bulk length given a certain string length. */ -static size_t bulklen(size_t len) { - return 1+intlen(len)+2+len+2; -} - -int redisvFormatCommand(char **target, const char *format, va_list ap) { - const char *c = format; - char *cmd = NULL; /* final command */ - int pos; /* position in final command */ - sds curarg, newarg; /* current argument */ - int touched = 0; /* was the current argument touched? */ - char **curargv = NULL, **newargv = NULL; - int argc = 0; - int totlen = 0; - int j; - - /* Abort if there is not target to set */ - if (target == NULL) - return -1; - - /* Build the command string accordingly to protocol */ - curarg = sdsempty(); - if (curarg == NULL) - return -1; - - while(*c != '\0') { - if (*c != '%' || c[1] == '\0') { - if (*c == ' ') { - if (touched) { - newargv = realloc(curargv,sizeof(char*)*(argc+1)); - if (newargv == NULL) goto err; - curargv = newargv; - curargv[argc++] = curarg; - totlen += bulklen(sdslen(curarg)); - - /* curarg is put in argv so it can be overwritten. */ - curarg = sdsempty(); - if (curarg == NULL) goto err; - touched = 0; - } - } else { - newarg = sdscatlen(curarg,c,1); - if (newarg == NULL) goto err; - curarg = newarg; - touched = 1; - } - } else { - char *arg; - size_t size; - - /* Set newarg so it can be checked even if it is not touched. */ - newarg = curarg; - - switch(c[1]) { - case 's': - arg = va_arg(ap,char*); - size = strlen(arg); - if (size > 0) - newarg = sdscatlen(curarg,arg,size); - break; - case 'b': - arg = va_arg(ap,char*); - size = va_arg(ap,size_t); - if (size > 0) - newarg = sdscatlen(curarg,arg,size); - break; - case '%': - newarg = sdscat(curarg,"%"); - break; - default: - /* Try to detect printf format */ - { - static const char intfmts[] = "diouxX"; - char _format[16]; - const char *_p = c+1; - size_t _l = 0; - va_list _cpy; - - /* Flags */ - if (*_p != '\0' && *_p == '#') _p++; - if (*_p != '\0' && *_p == '0') _p++; - if (*_p != '\0' && *_p == '-') _p++; - if (*_p != '\0' && *_p == ' ') _p++; - if (*_p != '\0' && *_p == '+') _p++; - - /* Field width */ - while (*_p != '\0' && isdigit(*_p)) _p++; - - /* Precision */ - if (*_p == '.') { - _p++; - while (*_p != '\0' && isdigit(*_p)) _p++; - } - - /* Copy va_list before consuming with va_arg */ - va_copy(_cpy,ap); - - /* Integer conversion (without modifiers) */ - if (strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); - goto fmt_valid; - } - - /* Double conversion (without modifiers) */ - if (strchr("eEfFgGaA",*_p) != NULL) { - va_arg(ap,double); - goto fmt_valid; - } - - /* Size: char */ - if (_p[0] == 'h' && _p[1] == 'h') { - _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); /* char gets promoted to int */ - goto fmt_valid; - } - goto fmt_invalid; - } - - /* Size: short */ - if (_p[0] == 'h') { - _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,int); /* short gets promoted to int */ - goto fmt_valid; - } - goto fmt_invalid; - } - - /* Size: long long */ - if (_p[0] == 'l' && _p[1] == 'l') { - _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,long long); - goto fmt_valid; - } - goto fmt_invalid; - } - - /* Size: long */ - if (_p[0] == 'l') { - _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { - va_arg(ap,long); - goto fmt_valid; - } - goto fmt_invalid; - } - - fmt_invalid: - va_end(_cpy); - goto err; - - fmt_valid: - _l = (_p+1)-c; - if (_l < sizeof(_format)-2) { - memcpy(_format,c,_l); - _format[_l] = '\0'; - newarg = sdscatvprintf(curarg,_format,_cpy); - - /* Update current position (note: outer blocks - * increment c twice so compensate here) */ - c = _p-1; - } - - va_end(_cpy); - break; - } - } - - if (newarg == NULL) goto err; - curarg = newarg; - - touched = 1; - c++; - } - c++; - } - - /* Add the last argument if needed */ - if (touched) { - newargv = realloc(curargv,sizeof(char*)*(argc+1)); - if (newargv == NULL) goto err; - curargv = newargv; - curargv[argc++] = curarg; - totlen += bulklen(sdslen(curarg)); - } else { - sdsfree(curarg); - } - - /* Clear curarg because it was put in curargv or was free'd. */ - curarg = NULL; - - /* Add bytes needed to hold multi bulk count */ - totlen += 1+intlen(argc)+2; - - /* Build the command at protocol level */ - cmd = malloc(totlen+1); - if (cmd == NULL) goto err; - - pos = sprintf(cmd,"*%d\r\n",argc); - for (j = 0; j < argc; j++) { - pos += sprintf(cmd+pos,"$%zu\r\n",sdslen(curargv[j])); - memcpy(cmd+pos,curargv[j],sdslen(curargv[j])); - pos += sdslen(curargv[j]); - sdsfree(curargv[j]); - cmd[pos++] = '\r'; - cmd[pos++] = '\n'; - } - assert(pos == totlen); - cmd[pos] = '\0'; - - free(curargv); - *target = cmd; - return totlen; - -err: - while(argc--) - sdsfree(curargv[argc]); - free(curargv); - - if (curarg != NULL) - sdsfree(curarg); - - /* No need to check cmd since it is the last statement that can fail, - * but do it anyway to be as defensive as possible. */ - if (cmd != NULL) - free(cmd); - - return -1; -} - -/* Format a command according to the Redis protocol. This function - * takes a format similar to printf: - * - * %s represents a C null terminated string you want to interpolate - * %b represents a binary safe string - * - * When using %b you need to provide both the pointer to the string - * and the length in bytes. Examples: - * - * len = redisFormatCommand(target, "GET %s", mykey); - * len = redisFormatCommand(target, "SET %s %b", mykey, myval, myvallen); - */ -int redisFormatCommand(char **target, const char *format, ...) { - va_list ap; - int len; - va_start(ap,format); - len = redisvFormatCommand(target,format,ap); - va_end(ap); - return len; -} - -/* Format a command according to the Redis protocol. This function takes the - * number of arguments, an array with arguments and an array with their - * lengths. If the latter is set to NULL, strlen will be used to compute the - * argument lengths. - */ -int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen) { - char *cmd = NULL; /* final command */ - int pos; /* position in final command */ - size_t len; - int totlen, j; - - /* Calculate number of bytes needed for the command */ - totlen = 1+intlen(argc)+2; - for (j = 0; j < argc; j++) { - len = argvlen ? argvlen[j] : strlen(argv[j]); - totlen += bulklen(len); - } - - /* Build the command at protocol level */ - cmd = malloc(totlen+1); - if (cmd == NULL) - return -1; - - pos = sprintf(cmd,"*%d\r\n",argc); - for (j = 0; j < argc; j++) { - len = argvlen ? argvlen[j] : strlen(argv[j]); - pos += sprintf(cmd+pos,"$%zu\r\n",len); - memcpy(cmd+pos,argv[j],len); - pos += len; - cmd[pos++] = '\r'; - cmd[pos++] = '\n'; - } - assert(pos == totlen); - cmd[pos] = '\0'; - - *target = cmd; - return totlen; -} - -void __redisSetError(redisContext *c, int type, const char *str) { - size_t len; - - c->err = type; - if (str != NULL) { - len = strlen(str); - len = len < (sizeof(c->errstr)-1) ? len : (sizeof(c->errstr)-1); - memcpy(c->errstr,str,len); - c->errstr[len] = '\0'; - } else { - /* Only REDIS_ERR_IO may lack a description! */ - assert(type == REDIS_ERR_IO); - strerror_r(errno,c->errstr,sizeof(c->errstr)); - } -} - -static redisContext *redisContextInit(void) { - redisContext *c; - - c = calloc(1,sizeof(redisContext)); - if (c == NULL) - return NULL; - - c->err = 0; - c->errstr[0] = '\0'; - c->obuf = sdsempty(); - c->reader = redisReaderCreate(); - return c; -} - -void redisFree(redisContext *c) { - if (c->fd > 0) - close(c->fd); - if (c->obuf != NULL) - sdsfree(c->obuf); - if (c->reader != NULL) - redisReaderFree(c->reader); - free(c); -} - -/* Connect to a Redis instance. On error the field error in the returned - * context will be set to the return value of the error function. - * When no set of reply functions is given, the default set will be used. */ -redisContext *redisConnect(const char *ip, int port) { - redisContext *c = redisContextInit(); - c->flags |= REDIS_BLOCK; - redisContextConnectTcp(c,ip,port,NULL); - return c; -} - -redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv) { - redisContext *c = redisContextInit(); - c->flags |= REDIS_BLOCK; - redisContextConnectTcp(c,ip,port,&tv); - return c; -} - -redisContext *redisConnectNonBlock(const char *ip, int port) { - redisContext *c = redisContextInit(); - c->flags &= ~REDIS_BLOCK; - redisContextConnectTcp(c,ip,port,NULL); - return c; -} - -redisContext *redisConnectUnix(const char *path) { - redisContext *c = redisContextInit(); - c->flags |= REDIS_BLOCK; - redisContextConnectUnix(c,path,NULL); - return c; -} - -redisContext *redisConnectUnixWithTimeout(const char *path, struct timeval tv) { - redisContext *c = redisContextInit(); - c->flags |= REDIS_BLOCK; - redisContextConnectUnix(c,path,&tv); - return c; -} - -redisContext *redisConnectUnixNonBlock(const char *path) { - redisContext *c = redisContextInit(); - c->flags &= ~REDIS_BLOCK; - redisContextConnectUnix(c,path,NULL); - return c; -} - -/* Set read/write timeout on a blocking socket. */ -int redisSetTimeout(redisContext *c, struct timeval tv) { - if (c->flags & REDIS_BLOCK) - return redisContextSetTimeout(c,tv); - return REDIS_ERR; -} - -/* Use this function to handle a read event on the descriptor. It will try - * and read some bytes from the socket and feed them to the reply parser. - * - * After this function is called, you may use redisContextReadReply to - * see if there is a reply available. */ -int redisBufferRead(redisContext *c) { - char buf[2048]; - int nread; - - /* Return early when the context has seen an error. */ - if (c->err) - return REDIS_ERR; - - nread = read(c->fd,buf,sizeof(buf)); - if (nread == -1) { - if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) { - /* Try again later */ - } else { - __redisSetError(c,REDIS_ERR_IO,NULL); - return REDIS_ERR; - } - } else if (nread == 0) { - __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection"); - return REDIS_ERR; - } else { - if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) { - __redisSetError(c,c->reader->err,c->reader->errstr); - return REDIS_ERR; - } - } - return REDIS_OK; -} - -/* Write the output buffer to the socket. - * - * Returns REDIS_OK when the buffer is empty, or (a part of) the buffer was - * succesfully written to the socket. When the buffer is empty after the - * write operation, "done" is set to 1 (if given). - * - * Returns REDIS_ERR if an error occured trying to write and sets - * c->errstr to hold the appropriate error string. - */ -int redisBufferWrite(redisContext *c, int *done) { - int nwritten; - - /* Return early when the context has seen an error. */ - if (c->err) - return REDIS_ERR; - - if (sdslen(c->obuf) > 0) { - nwritten = write(c->fd,c->obuf,sdslen(c->obuf)); - if (nwritten == -1) { - if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) { - /* Try again later */ - } else { - __redisSetError(c,REDIS_ERR_IO,NULL); - return REDIS_ERR; - } - } else if (nwritten > 0) { - if (nwritten == (signed)sdslen(c->obuf)) { - sdsfree(c->obuf); - c->obuf = sdsempty(); - } else { - c->obuf = sdsrange(c->obuf,nwritten,-1); - } - } - } - if (done != NULL) *done = (sdslen(c->obuf) == 0); - return REDIS_OK; -} - -/* Internal helper function to try and get a reply from the reader, - * or set an error in the context otherwise. */ -int redisGetReplyFromReader(redisContext *c, void **reply) { - if (redisReaderGetReply(c->reader,reply) == REDIS_ERR) { - __redisSetError(c,c->reader->err,c->reader->errstr); - return REDIS_ERR; - } - return REDIS_OK; -} - -int redisGetReply(redisContext *c, void **reply) { - int wdone = 0; - void *aux = NULL; - - /* Try to read pending replies */ - if (redisGetReplyFromReader(c,&aux) == REDIS_ERR) - return REDIS_ERR; - - /* For the blocking context, flush output buffer and read reply */ - if (aux == NULL && c->flags & REDIS_BLOCK) { - /* Write until done */ - do { - if (redisBufferWrite(c,&wdone) == REDIS_ERR) - return REDIS_ERR; - } while (!wdone); - - /* Read until there is a reply */ - do { - if (redisBufferRead(c) == REDIS_ERR) - return REDIS_ERR; - if (redisGetReplyFromReader(c,&aux) == REDIS_ERR) - return REDIS_ERR; - } while (aux == NULL); - } - - /* Set reply object */ - if (reply != NULL) *reply = aux; - return REDIS_OK; -} - - -/* Helper function for the redisAppendCommand* family of functions. - * - * Write a formatted command to the output buffer. When this family - * is used, you need to call redisGetReply yourself to retrieve - * the reply (or replies in pub/sub). - */ -int __redisAppendCommand(redisContext *c, char *cmd, size_t len) { - sds newbuf; - - newbuf = sdscatlen(c->obuf,cmd,len); - if (newbuf == NULL) { - __redisSetError(c,REDIS_ERR_OOM,"Out of memory"); - return REDIS_ERR; - } - - c->obuf = newbuf; - return REDIS_OK; -} - -int redisvAppendCommand(redisContext *c, const char *format, va_list ap) { - char *cmd; - int len; - - len = redisvFormatCommand(&cmd,format,ap); - if (len == -1) { - __redisSetError(c,REDIS_ERR_OOM,"Out of memory"); - return REDIS_ERR; - } - - if (__redisAppendCommand(c,cmd,len) != REDIS_OK) { - free(cmd); - return REDIS_ERR; - } - - free(cmd); - return REDIS_OK; -} - -int redisAppendCommand(redisContext *c, const char *format, ...) { - va_list ap; - int ret; - - va_start(ap,format); - ret = redisvAppendCommand(c,format,ap); - va_end(ap); - return ret; -} - -int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) { - char *cmd; - int len; - - len = redisFormatCommandArgv(&cmd,argc,argv,argvlen); - if (len == -1) { - __redisSetError(c,REDIS_ERR_OOM,"Out of memory"); - return REDIS_ERR; - } - - if (__redisAppendCommand(c,cmd,len) != REDIS_OK) { - free(cmd); - return REDIS_ERR; - } - - free(cmd); - return REDIS_OK; -} - -/* Helper function for the redisCommand* family of functions. - * - * Write a formatted command to the output buffer. If the given context is - * blocking, immediately read the reply into the "reply" pointer. When the - * context is non-blocking, the "reply" pointer will not be used and the - * command is simply appended to the write buffer. - * - * Returns the reply when a reply was succesfully retrieved. Returns NULL - * otherwise. When NULL is returned in a blocking context, the error field - * in the context will be set. - */ -static void *__redisBlockForReply(redisContext *c) { - void *reply; - - if (c->flags & REDIS_BLOCK) { - if (redisGetReply(c,&reply) != REDIS_OK) - return NULL; - return reply; - } - return NULL; -} - -void *redisvCommand(redisContext *c, const char *format, va_list ap) { - if (redisvAppendCommand(c,format,ap) != REDIS_OK) - return NULL; - return __redisBlockForReply(c); -} - -void *redisCommand(redisContext *c, const char *format, ...) { - va_list ap; - void *reply = NULL; - va_start(ap,format); - reply = redisvCommand(c,format,ap); - va_end(ap); - return reply; -} - -void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) { - if (redisAppendCommandArgv(c,argc,argv,argvlen) != REDIS_OK) - return NULL; - return __redisBlockForReply(c); -} diff --git a/node_modules/hiredis/deps/hiredis/hiredis.h b/node_modules/hiredis/deps/hiredis/hiredis.h deleted file mode 100644 index 8358375..0000000 --- a/node_modules/hiredis/deps/hiredis/hiredis.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2009-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __HIREDIS_H -#define __HIREDIS_H -#include /* for size_t */ -#include /* for va_list */ -#include /* for struct timeval */ - -#define HIREDIS_MAJOR 0 -#define HIREDIS_MINOR 10 -#define HIREDIS_PATCH 1 - -#define REDIS_ERR -1 -#define REDIS_OK 0 - -/* When an error occurs, the err flag in a context is set to hold the type of - * error that occured. REDIS_ERR_IO means there was an I/O error and you - * should use the "errno" variable to find out what is wrong. - * For other values, the "errstr" field will hold a description. */ -#define REDIS_ERR_IO 1 /* Error in read or write */ -#define REDIS_ERR_EOF 3 /* End of file */ -#define REDIS_ERR_PROTOCOL 4 /* Protocol error */ -#define REDIS_ERR_OOM 5 /* Out of memory */ -#define REDIS_ERR_OTHER 2 /* Everything else... */ - -/* Connection type can be blocking or non-blocking and is set in the - * least significant bit of the flags field in redisContext. */ -#define REDIS_BLOCK 0x1 - -/* Connection may be disconnected before being free'd. The second bit - * in the flags field is set when the context is connected. */ -#define REDIS_CONNECTED 0x2 - -/* The async API might try to disconnect cleanly and flush the output - * buffer and read all subsequent replies before disconnecting. - * This flag means no new commands can come in and the connection - * should be terminated once all replies have been read. */ -#define REDIS_DISCONNECTING 0x4 - -/* Flag specific to the async API which means that the context should be clean - * up as soon as possible. */ -#define REDIS_FREEING 0x8 - -/* Flag that is set when an async callback is executed. */ -#define REDIS_IN_CALLBACK 0x10 - -/* Flag that is set when the async context has one or more subscriptions. */ -#define REDIS_SUBSCRIBED 0x20 - -#define REDIS_REPLY_STRING 1 -#define REDIS_REPLY_ARRAY 2 -#define REDIS_REPLY_INTEGER 3 -#define REDIS_REPLY_NIL 4 -#define REDIS_REPLY_STATUS 5 -#define REDIS_REPLY_ERROR 6 - -#ifdef __cplusplus -extern "C" { -#endif - -/* This is the reply object returned by redisCommand() */ -typedef struct redisReply { - int type; /* REDIS_REPLY_* */ - long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ - int len; /* Length of string */ - char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ - size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ - struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */ -} redisReply; - -typedef struct redisReadTask { - int type; - int elements; /* number of elements in multibulk container */ - int idx; /* index in parent (array) object */ - void *obj; /* holds user-generated value for a read task */ - struct redisReadTask *parent; /* parent task */ - void *privdata; /* user-settable arbitrary field */ -} redisReadTask; - -typedef struct redisReplyObjectFunctions { - void *(*createString)(const redisReadTask*, char*, size_t); - void *(*createArray)(const redisReadTask*, int); - void *(*createInteger)(const redisReadTask*, long long); - void *(*createNil)(const redisReadTask*); - void (*freeObject)(void*); -} redisReplyObjectFunctions; - -/* State for the protocol parser */ -typedef struct redisReader { - int err; /* Error flags, 0 when there is no error */ - char errstr[128]; /* String representation of error when applicable */ - - char *buf; /* Read buffer */ - size_t pos; /* Buffer cursor */ - size_t len; /* Buffer length */ - - redisReadTask rstack[4]; - int ridx; /* Index of current read task */ - void *reply; /* Temporary reply pointer */ - - redisReplyObjectFunctions *fn; - void *privdata; -} redisReader; - -/* Public API for the protocol parser. */ -redisReader *redisReaderCreate(void); -void redisReaderFree(redisReader *r); -int redisReaderFeed(redisReader *r, const char *buf, size_t len); -int redisReaderGetReply(redisReader *r, void **reply); - -/* Backwards compatibility, can be removed on big version bump. */ -#define redisReplyReaderCreate redisReaderCreate -#define redisReplyReaderFree redisReaderFree -#define redisReplyReaderFeed redisReaderFeed -#define redisReplyReaderGetReply redisReaderGetReply -#define redisReplyReaderSetPrivdata(_r, _p) (int)(((redisReader*)(_r))->privdata = (_p)) -#define redisReplyReaderGetObject(_r) (((redisReader*)(_r))->reply) -#define redisReplyReaderGetError(_r) (((redisReader*)(_r))->errstr) - -/* Function to free the reply objects hiredis returns by default. */ -void freeReplyObject(void *reply); - -/* Functions to format a command according to the protocol. */ -int redisvFormatCommand(char **target, const char *format, va_list ap); -int redisFormatCommand(char **target, const char *format, ...); -int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen); - -/* Context for a connection to Redis */ -typedef struct redisContext { - int err; /* Error flags, 0 when there is no error */ - char errstr[128]; /* String representation of error when applicable */ - int fd; - int flags; - char *obuf; /* Write buffer */ - redisReader *reader; /* Protocol reader */ -} redisContext; - -redisContext *redisConnect(const char *ip, int port); -redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv); -redisContext *redisConnectNonBlock(const char *ip, int port); -redisContext *redisConnectUnix(const char *path); -redisContext *redisConnectUnixWithTimeout(const char *path, struct timeval tv); -redisContext *redisConnectUnixNonBlock(const char *path); -int redisSetTimeout(redisContext *c, struct timeval tv); -void redisFree(redisContext *c); -int redisBufferRead(redisContext *c); -int redisBufferWrite(redisContext *c, int *done); - -/* In a blocking context, this function first checks if there are unconsumed - * replies to return and returns one if so. Otherwise, it flushes the output - * buffer to the socket and reads until it has a reply. In a non-blocking - * context, it will return unconsumed replies until there are no more. */ -int redisGetReply(redisContext *c, void **reply); -int redisGetReplyFromReader(redisContext *c, void **reply); - -/* Write a command to the output buffer. Use these functions in blocking mode - * to get a pipeline of commands. */ -int redisvAppendCommand(redisContext *c, const char *format, va_list ap); -int redisAppendCommand(redisContext *c, const char *format, ...); -int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -/* Issue a command to Redis. In a blocking context, it is identical to calling - * redisAppendCommand, followed by redisGetReply. The function will return - * NULL if there was an error in performing the request, otherwise it will - * return the reply. In a non-blocking context, it is identical to calling - * only redisAppendCommand and will always return NULL. */ -void *redisvCommand(redisContext *c, const char *format, va_list ap); -void *redisCommand(redisContext *c, const char *format, ...); -void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/node_modules/hiredis/deps/hiredis/hiredis.o b/node_modules/hiredis/deps/hiredis/hiredis.o deleted file mode 100644 index 7c4ac71..0000000 Binary files a/node_modules/hiredis/deps/hiredis/hiredis.o and /dev/null differ diff --git a/node_modules/hiredis/deps/hiredis/libhiredis.a b/node_modules/hiredis/deps/hiredis/libhiredis.a deleted file mode 100644 index 2f43829..0000000 Binary files a/node_modules/hiredis/deps/hiredis/libhiredis.a and /dev/null differ diff --git a/node_modules/hiredis/deps/hiredis/net.c b/node_modules/hiredis/deps/hiredis/net.c deleted file mode 100644 index 158e1dd..0000000 --- a/node_modules/hiredis/deps/hiredis/net.c +++ /dev/null @@ -1,279 +0,0 @@ -/* Extracted from anet.c to work properly with Hiredis error reporting. - * - * Copyright (c) 2006-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fmacros.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "net.h" -#include "sds.h" - -/* Defined in hiredis.c */ -void __redisSetError(redisContext *c, int type, const char *str); - -static void __redisSetErrorFromErrno(redisContext *c, int type, const char *prefix) { - char buf[128]; - size_t len = 0; - - if (prefix != NULL) - len = snprintf(buf,sizeof(buf),"%s: ",prefix); - strerror_r(errno,buf+len,sizeof(buf)-len); - __redisSetError(c,type,buf); -} - -static int redisSetReuseAddr(redisContext *c, int fd) { - int on = 1; - if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL); - close(fd); - return REDIS_ERR; - } - return REDIS_OK; -} - -static int redisCreateSocket(redisContext *c, int type) { - int s; - if ((s = socket(type, SOCK_STREAM, 0)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL); - return REDIS_ERR; - } - if (type == AF_INET) { - if (redisSetReuseAddr(c,s) == REDIS_ERR) { - return REDIS_ERR; - } - } - return s; -} - -static int redisSetBlocking(redisContext *c, int fd, int blocking) { - int flags; - - /* Set the socket nonblocking. - * Note that fcntl(2) for F_GETFL and F_SETFL can't be - * interrupted by a signal. */ - if ((flags = fcntl(fd, F_GETFL)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_GETFL)"); - close(fd); - return REDIS_ERR; - } - - if (blocking) - flags &= ~O_NONBLOCK; - else - flags |= O_NONBLOCK; - - if (fcntl(fd, F_SETFL, flags) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_SETFL)"); - close(fd); - return REDIS_ERR; - } - return REDIS_OK; -} - -static int redisSetTcpNoDelay(redisContext *c, int fd) { - int yes = 1; - if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(TCP_NODELAY)"); - close(fd); - return REDIS_ERR; - } - return REDIS_OK; -} - -static int redisContextWaitReady(redisContext *c, int fd, const struct timeval *timeout) { - struct timeval to; - struct timeval *toptr = NULL; - fd_set wfd; - - /* Only use timeout when not NULL. */ - if (timeout != NULL) { - to = *timeout; - toptr = &to; - } - - if (errno == EINPROGRESS) { - FD_ZERO(&wfd); - FD_SET(fd, &wfd); - - if (select(FD_SETSIZE, NULL, &wfd, NULL, toptr) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"select(2)"); - close(fd); - return REDIS_ERR; - } - - if (!FD_ISSET(fd, &wfd)) { - errno = ETIMEDOUT; - __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL); - close(fd); - return REDIS_ERR; - } - - if (redisCheckSocketError(c, fd) != REDIS_OK) - return REDIS_ERR; - - return REDIS_OK; - } - - __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL); - close(fd); - return REDIS_ERR; -} - -int redisCheckSocketError(redisContext *c, int fd) { - int err = 0; - socklen_t errlen = sizeof(err); - - if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"getsockopt(SO_ERROR)"); - close(fd); - return REDIS_ERR; - } - - if (err) { - errno = err; - __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL); - close(fd); - return REDIS_ERR; - } - - return REDIS_OK; -} - -int redisContextSetTimeout(redisContext *c, struct timeval tv) { - if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_RCVTIMEO)"); - return REDIS_ERR; - } - if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1) { - __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_SNDTIMEO)"); - return REDIS_ERR; - } - return REDIS_OK; -} - -int redisContextConnectTcp(redisContext *c, const char *addr, int port, struct timeval *timeout) { - int s, rv; - char _port[6]; /* strlen("65535"); */ - struct addrinfo hints, *servinfo, *p; - int blocking = (c->flags & REDIS_BLOCK); - - snprintf(_port, 6, "%d", port); - memset(&hints,0,sizeof(hints)); - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - - if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) { - __redisSetError(c,REDIS_ERR_OTHER,gai_strerror(rv)); - return REDIS_ERR; - } - for (p = servinfo; p != NULL; p = p->ai_next) { - if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) - continue; - - if (redisSetBlocking(c,s,0) != REDIS_OK) - goto error; - if (connect(s,p->ai_addr,p->ai_addrlen) == -1) { - if (errno == EHOSTUNREACH) { - close(s); - continue; - } else if (errno == EINPROGRESS && !blocking) { - /* This is ok. */ - } else { - if (redisContextWaitReady(c,s,timeout) != REDIS_OK) - goto error; - } - } - if (blocking && redisSetBlocking(c,s,1) != REDIS_OK) - goto error; - if (redisSetTcpNoDelay(c,s) != REDIS_OK) - goto error; - - c->fd = s; - c->flags |= REDIS_CONNECTED; - rv = REDIS_OK; - goto end; - } - if (p == NULL) { - char buf[128]; - snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno)); - __redisSetError(c,REDIS_ERR_OTHER,buf); - goto error; - } - -error: - rv = REDIS_ERR; -end: - freeaddrinfo(servinfo); - return rv; // Need to return REDIS_OK if alright -} - -int redisContextConnectUnix(redisContext *c, const char *path, struct timeval *timeout) { - int s; - int blocking = (c->flags & REDIS_BLOCK); - struct sockaddr_un sa; - - if ((s = redisCreateSocket(c,AF_LOCAL)) < 0) - return REDIS_ERR; - if (redisSetBlocking(c,s,0) != REDIS_OK) - return REDIS_ERR; - - sa.sun_family = AF_LOCAL; - strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1); - if (connect(s, (struct sockaddr*)&sa, sizeof(sa)) == -1) { - if (errno == EINPROGRESS && !blocking) { - /* This is ok. */ - } else { - if (redisContextWaitReady(c,s,timeout) != REDIS_OK) - return REDIS_ERR; - } - } - - /* Reset socket to be blocking after connect(2). */ - if (blocking && redisSetBlocking(c,s,1) != REDIS_OK) - return REDIS_ERR; - - c->fd = s; - c->flags |= REDIS_CONNECTED; - return REDIS_OK; -} diff --git a/node_modules/hiredis/deps/hiredis/net.h b/node_modules/hiredis/deps/hiredis/net.h deleted file mode 100644 index eb8a0a1..0000000 --- a/node_modules/hiredis/deps/hiredis/net.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Extracted from anet.c to work properly with Hiredis error reporting. - * - * Copyright (c) 2006-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __NET_H -#define __NET_H - -#include "hiredis.h" - -#if defined(__sun) -#define AF_LOCAL AF_UNIX -#endif - -int redisCheckSocketError(redisContext *c, int fd); -int redisContextSetTimeout(redisContext *c, struct timeval tv); -int redisContextConnectTcp(redisContext *c, const char *addr, int port, struct timeval *timeout); -int redisContextConnectUnix(redisContext *c, const char *path, struct timeval *timeout); - -#endif diff --git a/node_modules/hiredis/deps/hiredis/net.o b/node_modules/hiredis/deps/hiredis/net.o deleted file mode 100644 index d3b8c2f..0000000 Binary files a/node_modules/hiredis/deps/hiredis/net.o and /dev/null differ diff --git a/node_modules/hiredis/deps/hiredis/sds.c b/node_modules/hiredis/deps/hiredis/sds.c deleted file mode 100644 index 0af9c67..0000000 --- a/node_modules/hiredis/deps/hiredis/sds.c +++ /dev/null @@ -1,605 +0,0 @@ -/* SDSLib, A C dynamic strings library - * - * Copyright (c) 2006-2010, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include "sds.h" - -#ifdef SDS_ABORT_ON_OOM -static void sdsOomAbort(void) { - fprintf(stderr,"SDS: Out Of Memory (SDS_ABORT_ON_OOM defined)\n"); - abort(); -} -#endif - -sds sdsnewlen(const void *init, size_t initlen) { - struct sdshdr *sh; - - sh = malloc(sizeof(struct sdshdr)+initlen+1); -#ifdef SDS_ABORT_ON_OOM - if (sh == NULL) sdsOomAbort(); -#else - if (sh == NULL) return NULL; -#endif - sh->len = initlen; - sh->free = 0; - if (initlen) { - if (init) memcpy(sh->buf, init, initlen); - else memset(sh->buf,0,initlen); - } - sh->buf[initlen] = '\0'; - return (char*)sh->buf; -} - -sds sdsempty(void) { - return sdsnewlen("",0); -} - -sds sdsnew(const char *init) { - size_t initlen = (init == NULL) ? 0 : strlen(init); - return sdsnewlen(init, initlen); -} - -sds sdsdup(const sds s) { - return sdsnewlen(s, sdslen(s)); -} - -void sdsfree(sds s) { - if (s == NULL) return; - free(s-sizeof(struct sdshdr)); -} - -void sdsupdatelen(sds s) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - int reallen = strlen(s); - sh->free += (sh->len-reallen); - sh->len = reallen; -} - -static sds sdsMakeRoomFor(sds s, size_t addlen) { - struct sdshdr *sh, *newsh; - size_t free = sdsavail(s); - size_t len, newlen; - - if (free >= addlen) return s; - len = sdslen(s); - sh = (void*) (s-(sizeof(struct sdshdr))); - newlen = (len+addlen)*2; - newsh = realloc(sh, sizeof(struct sdshdr)+newlen+1); -#ifdef SDS_ABORT_ON_OOM - if (newsh == NULL) sdsOomAbort(); -#else - if (newsh == NULL) return NULL; -#endif - - newsh->free = newlen - len; - return newsh->buf; -} - -/* Grow the sds to have the specified length. Bytes that were not part of - * the original length of the sds will be set to zero. */ -sds sdsgrowzero(sds s, size_t len) { - struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); - size_t totlen, curlen = sh->len; - - if (len <= curlen) return s; - s = sdsMakeRoomFor(s,len-curlen); - if (s == NULL) return NULL; - - /* Make sure added region doesn't contain garbage */ - sh = (void*)(s-(sizeof(struct sdshdr))); - memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ - totlen = sh->len+sh->free; - sh->len = len; - sh->free = totlen-sh->len; - return s; -} - -sds sdscatlen(sds s, const void *t, size_t len) { - struct sdshdr *sh; - size_t curlen = sdslen(s); - - s = sdsMakeRoomFor(s,len); - if (s == NULL) return NULL; - sh = (void*) (s-(sizeof(struct sdshdr))); - memcpy(s+curlen, t, len); - sh->len = curlen+len; - sh->free = sh->free-len; - s[curlen+len] = '\0'; - return s; -} - -sds sdscat(sds s, const char *t) { - return sdscatlen(s, t, strlen(t)); -} - -sds sdscpylen(sds s, char *t, size_t len) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - size_t totlen = sh->free+sh->len; - - if (totlen < len) { - s = sdsMakeRoomFor(s,len-sh->len); - if (s == NULL) return NULL; - sh = (void*) (s-(sizeof(struct sdshdr))); - totlen = sh->free+sh->len; - } - memcpy(s, t, len); - s[len] = '\0'; - sh->len = len; - sh->free = totlen-len; - return s; -} - -sds sdscpy(sds s, char *t) { - return sdscpylen(s, t, strlen(t)); -} - -sds sdscatvprintf(sds s, const char *fmt, va_list ap) { - va_list cpy; - char *buf, *t; - size_t buflen = 16; - - while(1) { - buf = malloc(buflen); -#ifdef SDS_ABORT_ON_OOM - if (buf == NULL) sdsOomAbort(); -#else - if (buf == NULL) return NULL; -#endif - buf[buflen-2] = '\0'; - va_copy(cpy,ap); - vsnprintf(buf, buflen, fmt, cpy); - if (buf[buflen-2] != '\0') { - free(buf); - buflen *= 2; - continue; - } - break; - } - t = sdscat(s, buf); - free(buf); - return t; -} - -sds sdscatprintf(sds s, const char *fmt, ...) { - va_list ap; - char *t; - va_start(ap, fmt); - t = sdscatvprintf(s,fmt,ap); - va_end(ap); - return t; -} - -sds sdstrim(sds s, const char *cset) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - char *start, *end, *sp, *ep; - size_t len; - - sp = start = s; - ep = end = s+sdslen(s)-1; - while(sp <= end && strchr(cset, *sp)) sp++; - while(ep > start && strchr(cset, *ep)) ep--; - len = (sp > ep) ? 0 : ((ep-sp)+1); - if (sh->buf != sp) memmove(sh->buf, sp, len); - sh->buf[len] = '\0'; - sh->free = sh->free+(sh->len-len); - sh->len = len; - return s; -} - -sds sdsrange(sds s, int start, int end) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - size_t newlen, len = sdslen(s); - - if (len == 0) return s; - if (start < 0) { - start = len+start; - if (start < 0) start = 0; - } - if (end < 0) { - end = len+end; - if (end < 0) end = 0; - } - newlen = (start > end) ? 0 : (end-start)+1; - if (newlen != 0) { - if (start >= (signed)len) { - newlen = 0; - } else if (end >= (signed)len) { - end = len-1; - newlen = (start > end) ? 0 : (end-start)+1; - } - } else { - start = 0; - } - if (start && newlen) memmove(sh->buf, sh->buf+start, newlen); - sh->buf[newlen] = 0; - sh->free = sh->free+(sh->len-newlen); - sh->len = newlen; - return s; -} - -void sdstolower(sds s) { - int len = sdslen(s), j; - - for (j = 0; j < len; j++) s[j] = tolower(s[j]); -} - -void sdstoupper(sds s) { - int len = sdslen(s), j; - - for (j = 0; j < len; j++) s[j] = toupper(s[j]); -} - -int sdscmp(sds s1, sds s2) { - size_t l1, l2, minlen; - int cmp; - - l1 = sdslen(s1); - l2 = sdslen(s2); - minlen = (l1 < l2) ? l1 : l2; - cmp = memcmp(s1,s2,minlen); - if (cmp == 0) return l1-l2; - return cmp; -} - -/* Split 's' with separator in 'sep'. An array - * of sds strings is returned. *count will be set - * by reference to the number of tokens returned. - * - * On out of memory, zero length string, zero length - * separator, NULL is returned. - * - * Note that 'sep' is able to split a string using - * a multi-character separator. For example - * sdssplit("foo_-_bar","_-_"); will return two - * elements "foo" and "bar". - * - * This version of the function is binary-safe but - * requires length arguments. sdssplit() is just the - * same function but for zero-terminated strings. - */ -sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) { - int elements = 0, slots = 5, start = 0, j; - - sds *tokens = malloc(sizeof(sds)*slots); -#ifdef SDS_ABORT_ON_OOM - if (tokens == NULL) sdsOomAbort(); -#endif - if (seplen < 1 || len < 0 || tokens == NULL) return NULL; - if (len == 0) { - *count = 0; - return tokens; - } - for (j = 0; j < (len-(seplen-1)); j++) { - /* make sure there is room for the next element and the final one */ - if (slots < elements+2) { - sds *newtokens; - - slots *= 2; - newtokens = realloc(tokens,sizeof(sds)*slots); - if (newtokens == NULL) { -#ifdef SDS_ABORT_ON_OOM - sdsOomAbort(); -#else - goto cleanup; -#endif - } - tokens = newtokens; - } - /* search the separator */ - if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { - tokens[elements] = sdsnewlen(s+start,j-start); - if (tokens[elements] == NULL) { -#ifdef SDS_ABORT_ON_OOM - sdsOomAbort(); -#else - goto cleanup; -#endif - } - elements++; - start = j+seplen; - j = j+seplen-1; /* skip the separator */ - } - } - /* Add the final element. We are sure there is room in the tokens array. */ - tokens[elements] = sdsnewlen(s+start,len-start); - if (tokens[elements] == NULL) { -#ifdef SDS_ABORT_ON_OOM - sdsOomAbort(); -#else - goto cleanup; -#endif - } - elements++; - *count = elements; - return tokens; - -#ifndef SDS_ABORT_ON_OOM -cleanup: - { - int i; - for (i = 0; i < elements; i++) sdsfree(tokens[i]); - free(tokens); - return NULL; - } -#endif -} - -void sdsfreesplitres(sds *tokens, int count) { - if (!tokens) return; - while(count--) - sdsfree(tokens[count]); - free(tokens); -} - -sds sdsfromlonglong(long long value) { - char buf[32], *p; - unsigned long long v; - - v = (value < 0) ? -value : value; - p = buf+31; /* point to the last character */ - do { - *p-- = '0'+(v%10); - v /= 10; - } while(v); - if (value < 0) *p-- = '-'; - p++; - return sdsnewlen(p,32-(p-buf)); -} - -sds sdscatrepr(sds s, char *p, size_t len) { - s = sdscatlen(s,"\"",1); - if (s == NULL) return NULL; - - while(len--) { - switch(*p) { - case '\\': - case '"': - s = sdscatprintf(s,"\\%c",*p); - break; - case '\n': s = sdscatlen(s,"\\n",2); break; - case '\r': s = sdscatlen(s,"\\r",2); break; - case '\t': s = sdscatlen(s,"\\t",2); break; - case '\a': s = sdscatlen(s,"\\a",2); break; - case '\b': s = sdscatlen(s,"\\b",2); break; - default: - if (isprint(*p)) - s = sdscatprintf(s,"%c",*p); - else - s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); - break; - } - p++; - if (s == NULL) return NULL; - } - return sdscatlen(s,"\"",1); -} - -/* Split a line into arguments, where every argument can be in the - * following programming-language REPL-alike form: - * - * foo bar "newline are supported\n" and "\xff\x00otherstuff" - * - * The number of arguments is stored into *argc, and an array - * of sds is returned. The caller should sdsfree() all the returned - * strings and finally free() the array itself. - * - * Note that sdscatrepr() is able to convert back a string into - * a quoted string in the same format sdssplitargs() is able to parse. - */ -sds *sdssplitargs(char *line, int *argc) { - char *p = line; - char *current = NULL; - char **vector = NULL, **_vector = NULL; - - *argc = 0; - while(1) { - /* skip blanks */ - while(*p && isspace(*p)) p++; - if (*p) { - /* get a token */ - int inq=0; /* set to 1 if we are in "quotes" */ - int done=0; - - if (current == NULL) { - current = sdsempty(); - if (current == NULL) goto err; - } - - while(!done) { - if (inq) { - if (*p == '\\' && *(p+1)) { - char c; - - p++; - switch(*p) { - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'b': c = '\b'; break; - case 'a': c = '\a'; break; - default: c = *p; break; - } - current = sdscatlen(current,&c,1); - } else if (*p == '"') { - /* closing quote must be followed by a space */ - if (*(p+1) && !isspace(*(p+1))) goto err; - done=1; - } else if (!*p) { - /* unterminated quotes */ - goto err; - } else { - current = sdscatlen(current,p,1); - } - } else { - switch(*p) { - case ' ': - case '\n': - case '\r': - case '\t': - case '\0': - done=1; - break; - case '"': - inq=1; - break; - default: - current = sdscatlen(current,p,1); - break; - } - } - if (*p) p++; - if (current == NULL) goto err; - } - /* add the token to the vector */ - _vector = realloc(vector,((*argc)+1)*sizeof(char*)); - if (_vector == NULL) goto err; - - vector = _vector; - vector[*argc] = current; - (*argc)++; - current = NULL; - } else { - return vector; - } - } - -err: - while((*argc)--) - sdsfree(vector[*argc]); - if (vector != NULL) free(vector); - if (current != NULL) sdsfree(current); - return NULL; -} - -#ifdef SDS_TEST_MAIN -#include - -int __failed_tests = 0; -int __test_num = 0; -#define test_cond(descr,_c) do { \ - __test_num++; printf("%d - %s: ", __test_num, descr); \ - if(_c) printf("PASSED\n"); else {printf("FAILED\n"); __failed_tests++;} \ -} while(0); -#define test_report() do { \ - printf("%d tests, %d passed, %d failed\n", __test_num, \ - __test_num-__failed_tests, __failed_tests); \ - if (__failed_tests) { \ - printf("=== WARNING === We have failed tests here...\n"); \ - } \ -} while(0); - -int main(void) { - { - sds x = sdsnew("foo"), y; - - test_cond("Create a string and obtain the length", - sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) - - sdsfree(x); - x = sdsnewlen("foo",2); - test_cond("Create a string with specified length", - sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) - - x = sdscat(x,"bar"); - test_cond("Strings concatenation", - sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); - - x = sdscpy(x,"a"); - test_cond("sdscpy() against an originally longer string", - sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) - - x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); - test_cond("sdscpy() against an originally shorter string", - sdslen(x) == 33 && - memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) - - sdsfree(x); - x = sdscatprintf(sdsempty(),"%d",123); - test_cond("sdscatprintf() seems working in the base case", - sdslen(x) == 3 && memcmp(x,"123\0",4) ==0) - - sdsfree(x); - x = sdstrim(sdsnew("xxciaoyyy"),"xy"); - test_cond("sdstrim() correctly trims characters", - sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) - - y = sdsrange(sdsdup(x),1,1); - test_cond("sdsrange(...,1,1)", - sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) - - sdsfree(y); - y = sdsrange(sdsdup(x),1,-1); - test_cond("sdsrange(...,1,-1)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) - - sdsfree(y); - y = sdsrange(sdsdup(x),-2,-1); - test_cond("sdsrange(...,-2,-1)", - sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) - - sdsfree(y); - y = sdsrange(sdsdup(x),2,1); - test_cond("sdsrange(...,2,1)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) - - sdsfree(y); - y = sdsrange(sdsdup(x),1,100); - test_cond("sdsrange(...,1,100)", - sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) - - sdsfree(y); - y = sdsrange(sdsdup(x),100,100); - test_cond("sdsrange(...,100,100)", - sdslen(y) == 0 && memcmp(y,"\0",1) == 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("foo"); - y = sdsnew("foa"); - test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("bar"); - y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) - - sdsfree(y); - sdsfree(x); - x = sdsnew("aar"); - y = sdsnew("bar"); - test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) - } - test_report() -} -#endif diff --git a/node_modules/hiredis/deps/hiredis/sds.h b/node_modules/hiredis/deps/hiredis/sds.h deleted file mode 100644 index 94f5871..0000000 --- a/node_modules/hiredis/deps/hiredis/sds.h +++ /dev/null @@ -1,88 +0,0 @@ -/* SDSLib, A C dynamic strings library - * - * Copyright (c) 2006-2010, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __SDS_H -#define __SDS_H - -#include -#include - -typedef char *sds; - -struct sdshdr { - int len; - int free; - char buf[]; -}; - -static inline size_t sdslen(const sds s) { - struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); - return sh->len; -} - -static inline size_t sdsavail(const sds s) { - struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); - return sh->free; -} - -sds sdsnewlen(const void *init, size_t initlen); -sds sdsnew(const char *init); -sds sdsempty(void); -size_t sdslen(const sds s); -sds sdsdup(const sds s); -void sdsfree(sds s); -size_t sdsavail(sds s); -sds sdsgrowzero(sds s, size_t len); -sds sdscatlen(sds s, const void *t, size_t len); -sds sdscat(sds s, const char *t); -sds sdscpylen(sds s, char *t, size_t len); -sds sdscpy(sds s, char *t); - -sds sdscatvprintf(sds s, const char *fmt, va_list ap); -#ifdef __GNUC__ -sds sdscatprintf(sds s, const char *fmt, ...) - __attribute__((format(printf, 2, 3))); -#else -sds sdscatprintf(sds s, const char *fmt, ...); -#endif - -sds sdstrim(sds s, const char *cset); -sds sdsrange(sds s, int start, int end); -void sdsupdatelen(sds s); -int sdscmp(sds s1, sds s2); -sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count); -void sdsfreesplitres(sds *tokens, int count); -void sdstolower(sds s); -void sdstoupper(sds s); -sds sdsfromlonglong(long long value); -sds sdscatrepr(sds s, char *p, size_t len); -sds *sdssplitargs(char *line, int *argc); - -#endif diff --git a/node_modules/hiredis/deps/hiredis/sds.o b/node_modules/hiredis/deps/hiredis/sds.o deleted file mode 100644 index c521edc..0000000 Binary files a/node_modules/hiredis/deps/hiredis/sds.o and /dev/null differ diff --git a/node_modules/hiredis/deps/hiredis/test.c b/node_modules/hiredis/deps/hiredis/test.c deleted file mode 100644 index 5945b65..0000000 --- a/node_modules/hiredis/deps/hiredis/test.c +++ /dev/null @@ -1,654 +0,0 @@ -#include "fmacros.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "hiredis.h" - -enum connection_type { - CONN_TCP, - CONN_UNIX -}; - -struct config { - enum connection_type type; - - struct { - const char *host; - int port; - } tcp; - - struct { - const char *path; - } unix; -}; - -/* The following lines make up our testing "framework" :) */ -static int tests = 0, fails = 0; -#define test(_s) { printf("#%02d ", ++tests); printf(_s); } -#define test_cond(_c) if(_c) printf("\033[0;32mPASSED\033[0;0m\n"); else {printf("\033[0;31mFAILED\033[0;0m\n"); fails++;} - -static long long usec(void) { - struct timeval tv; - gettimeofday(&tv,NULL); - return (((long long)tv.tv_sec)*1000000)+tv.tv_usec; -} - -static redisContext *select_database(redisContext *c) { - redisReply *reply; - - /* Switch to DB 9 for testing, now that we know we can chat. */ - reply = redisCommand(c,"SELECT 9"); - assert(reply != NULL); - freeReplyObject(reply); - - /* Make sure the DB is emtpy */ - reply = redisCommand(c,"DBSIZE"); - assert(reply != NULL); - if (reply->type == REDIS_REPLY_INTEGER && reply->integer == 0) { - /* Awesome, DB 9 is empty and we can continue. */ - freeReplyObject(reply); - } else { - printf("Database #9 is not empty, test can not continue\n"); - exit(1); - } - - return c; -} - -static void disconnect(redisContext *c) { - redisReply *reply; - - /* Make sure we're on DB 9. */ - reply = redisCommand(c,"SELECT 9"); - assert(reply != NULL); - freeReplyObject(reply); - reply = redisCommand(c,"FLUSHDB"); - assert(reply != NULL); - freeReplyObject(reply); - - /* Free the context as well. */ - redisFree(c); -} - -static redisContext *connect(struct config config) { - redisContext *c = NULL; - - if (config.type == CONN_TCP) { - c = redisConnect(config.tcp.host, config.tcp.port); - } else if (config.type == CONN_UNIX) { - c = redisConnectUnix(config.unix.path); - } else { - assert(NULL); - } - - if (c->err) { - printf("Connection error: %s\n", c->errstr); - exit(1); - } - - return select_database(c); -} - -static void test_format_commands(void) { - char *cmd; - int len; - - test("Format command without interpolation: "); - len = redisFormatCommand(&cmd,"SET foo bar"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); - free(cmd); - - test("Format command with %%s string interpolation: "); - len = redisFormatCommand(&cmd,"SET %s %s","foo","bar"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); - free(cmd); - - test("Format command with %%s and an empty string: "); - len = redisFormatCommand(&cmd,"SET %s %s","foo",""); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(0+2)); - free(cmd); - - test("Format command with an empty string in between proper interpolations: "); - len = redisFormatCommand(&cmd,"SET %s %s","","foo"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$0\r\n\r\n$3\r\nfoo\r\n",len) == 0 && - len == 4+4+(3+2)+4+(0+2)+4+(3+2)); - free(cmd); - - test("Format command with %%b string interpolation: "); - len = redisFormatCommand(&cmd,"SET %b %b","foo",3,"b\0r",3); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nb\0r\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); - free(cmd); - - test("Format command with %%b and an empty string: "); - len = redisFormatCommand(&cmd,"SET %b %b","foo",3,"",0); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(0+2)); - free(cmd); - - test("Format command with literal %%: "); - len = redisFormatCommand(&cmd,"SET %% %%"); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$1\r\n%\r\n$1\r\n%\r\n",len) == 0 && - len == 4+4+(3+2)+4+(1+2)+4+(1+2)); - free(cmd); - - /* Vararg width depends on the type. These tests make sure that the - * width is correctly determined using the format and subsequent varargs - * can correctly be interpolated. */ -#define INTEGER_WIDTH_TEST(fmt, type) do { \ - type value = 123; \ - test("Format command with printf-delegation (" #type "): "); \ - len = redisFormatCommand(&cmd,"key:%08" fmt " str:%s", value, "hello"); \ - test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:00000123\r\n$9\r\nstr:hello\r\n",len) == 0 && \ - len == 4+5+(12+2)+4+(9+2)); \ - free(cmd); \ -} while(0) - -#define FLOAT_WIDTH_TEST(type) do { \ - type value = 123.0; \ - test("Format command with printf-delegation (" #type "): "); \ - len = redisFormatCommand(&cmd,"key:%08.3f str:%s", value, "hello"); \ - test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:0123.000\r\n$9\r\nstr:hello\r\n",len) == 0 && \ - len == 4+5+(12+2)+4+(9+2)); \ - free(cmd); \ -} while(0) - - INTEGER_WIDTH_TEST("d", int); - INTEGER_WIDTH_TEST("hhd", char); - INTEGER_WIDTH_TEST("hd", short); - INTEGER_WIDTH_TEST("ld", long); - INTEGER_WIDTH_TEST("lld", long long); - INTEGER_WIDTH_TEST("u", unsigned int); - INTEGER_WIDTH_TEST("hhu", unsigned char); - INTEGER_WIDTH_TEST("hu", unsigned short); - INTEGER_WIDTH_TEST("lu", unsigned long); - INTEGER_WIDTH_TEST("llu", unsigned long long); - FLOAT_WIDTH_TEST(float); - FLOAT_WIDTH_TEST(double); - - test("Format command with invalid printf format: "); - len = redisFormatCommand(&cmd,"key:%08p %b",(void*)1234,"foo",3); - test_cond(len == -1); - - const char *argv[3]; - argv[0] = "SET"; - argv[1] = "foo\0xxx"; - argv[2] = "bar"; - size_t lens[3] = { 3, 7, 3 }; - int argc = 3; - - test("Format command by passing argc/argv without lengths: "); - len = redisFormatCommandArgv(&cmd,argc,argv,NULL); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(3+2)+4+(3+2)); - free(cmd); - - test("Format command by passing argc/argv with lengths: "); - len = redisFormatCommandArgv(&cmd,argc,argv,lens); - test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 && - len == 4+4+(3+2)+4+(7+2)+4+(3+2)); - free(cmd); -} - -static void test_reply_reader(void) { - redisReader *reader; - void *reply; - int ret; - - test("Error handling in reply parser: "); - reader = redisReaderCreate(); - redisReaderFeed(reader,(char*)"@foo\r\n",6); - ret = redisReaderGetReply(reader,NULL); - test_cond(ret == REDIS_ERR && - strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0); - redisReaderFree(reader); - - /* when the reply already contains multiple items, they must be free'd - * on an error. valgrind will bark when this doesn't happen. */ - test("Memory cleanup in reply parser: "); - reader = redisReaderCreate(); - redisReaderFeed(reader,(char*)"*2\r\n",4); - redisReaderFeed(reader,(char*)"$5\r\nhello\r\n",11); - redisReaderFeed(reader,(char*)"@foo\r\n",6); - ret = redisReaderGetReply(reader,NULL); - test_cond(ret == REDIS_ERR && - strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0); - redisReaderFree(reader); - - test("Set error on nested multi bulks with depth > 2: "); - reader = redisReaderCreate(); - redisReaderFeed(reader,(char*)"*1\r\n",4); - redisReaderFeed(reader,(char*)"*1\r\n",4); - redisReaderFeed(reader,(char*)"*1\r\n",4); - redisReaderFeed(reader,(char*)"*1\r\n",4); - ret = redisReaderGetReply(reader,NULL); - test_cond(ret == REDIS_ERR && - strncasecmp(reader->errstr,"No support for",14) == 0); - redisReaderFree(reader); - - test("Works with NULL functions for reply: "); - reader = redisReaderCreate(); - reader->fn = NULL; - redisReaderFeed(reader,(char*)"+OK\r\n",5); - ret = redisReaderGetReply(reader,&reply); - test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS); - redisReaderFree(reader); - - test("Works when a single newline (\\r\\n) covers two calls to feed: "); - reader = redisReaderCreate(); - reader->fn = NULL; - redisReaderFeed(reader,(char*)"+OK\r",4); - ret = redisReaderGetReply(reader,&reply); - assert(ret == REDIS_OK && reply == NULL); - redisReaderFeed(reader,(char*)"\n",1); - ret = redisReaderGetReply(reader,&reply); - test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS); - redisReaderFree(reader); - - test("Don't reset state after protocol error: "); - reader = redisReaderCreate(); - reader->fn = NULL; - redisReaderFeed(reader,(char*)"x",1); - ret = redisReaderGetReply(reader,&reply); - assert(ret == REDIS_ERR); - ret = redisReaderGetReply(reader,&reply); - test_cond(ret == REDIS_ERR && reply == NULL); - redisReaderFree(reader); - - /* Regression test for issue #45 on GitHub. */ - test("Don't do empty allocation for empty multi bulk: "); - reader = redisReaderCreate(); - redisReaderFeed(reader,(char*)"*0\r\n",4); - ret = redisReaderGetReply(reader,&reply); - test_cond(ret == REDIS_OK && - ((redisReply*)reply)->type == REDIS_REPLY_ARRAY && - ((redisReply*)reply)->elements == 0); - freeReplyObject(reply); - redisReaderFree(reader); -} - -static void test_blocking_connection_errors(void) { - redisContext *c; - - test("Returns error when host cannot be resolved: "); - c = redisConnect((char*)"idontexist.local", 6379); - test_cond(c->err == REDIS_ERR_OTHER && - (strcmp(c->errstr,"Name or service not known") == 0 || - strcmp(c->errstr,"Can't resolve: idontexist.local") == 0)); - redisFree(c); - - test("Returns error when the port is not open: "); - c = redisConnect((char*)"localhost", 1); - test_cond(c->err == REDIS_ERR_IO && - strcmp(c->errstr,"Connection refused") == 0); - redisFree(c); - - test("Returns error when the unix socket path doesn't accept connections: "); - c = redisConnectUnix((char*)"/tmp/idontexist.sock"); - test_cond(c->err == REDIS_ERR_IO); /* Don't care about the message... */ - redisFree(c); -} - -static void test_blocking_connection(struct config config) { - redisContext *c; - redisReply *reply; - - c = connect(config); - - test("Is able to deliver commands: "); - reply = redisCommand(c,"PING"); - test_cond(reply->type == REDIS_REPLY_STATUS && - strcasecmp(reply->str,"pong") == 0) - freeReplyObject(reply); - - test("Is a able to send commands verbatim: "); - reply = redisCommand(c,"SET foo bar"); - test_cond (reply->type == REDIS_REPLY_STATUS && - strcasecmp(reply->str,"ok") == 0) - freeReplyObject(reply); - - test("%%s String interpolation works: "); - reply = redisCommand(c,"SET %s %s","foo","hello world"); - freeReplyObject(reply); - reply = redisCommand(c,"GET foo"); - test_cond(reply->type == REDIS_REPLY_STRING && - strcmp(reply->str,"hello world") == 0); - freeReplyObject(reply); - - test("%%b String interpolation works: "); - reply = redisCommand(c,"SET %b %b","foo",3,"hello\x00world",11); - freeReplyObject(reply); - reply = redisCommand(c,"GET foo"); - test_cond(reply->type == REDIS_REPLY_STRING && - memcmp(reply->str,"hello\x00world",11) == 0) - - test("Binary reply length is correct: "); - test_cond(reply->len == 11) - freeReplyObject(reply); - - test("Can parse nil replies: "); - reply = redisCommand(c,"GET nokey"); - test_cond(reply->type == REDIS_REPLY_NIL) - freeReplyObject(reply); - - /* test 7 */ - test("Can parse integer replies: "); - reply = redisCommand(c,"INCR mycounter"); - test_cond(reply->type == REDIS_REPLY_INTEGER && reply->integer == 1) - freeReplyObject(reply); - - test("Can parse multi bulk replies: "); - freeReplyObject(redisCommand(c,"LPUSH mylist foo")); - freeReplyObject(redisCommand(c,"LPUSH mylist bar")); - reply = redisCommand(c,"LRANGE mylist 0 -1"); - test_cond(reply->type == REDIS_REPLY_ARRAY && - reply->elements == 2 && - !memcmp(reply->element[0]->str,"bar",3) && - !memcmp(reply->element[1]->str,"foo",3)) - freeReplyObject(reply); - - /* m/e with multi bulk reply *before* other reply. - * specifically test ordering of reply items to parse. */ - test("Can handle nested multi bulk replies: "); - freeReplyObject(redisCommand(c,"MULTI")); - freeReplyObject(redisCommand(c,"LRANGE mylist 0 -1")); - freeReplyObject(redisCommand(c,"PING")); - reply = (redisCommand(c,"EXEC")); - test_cond(reply->type == REDIS_REPLY_ARRAY && - reply->elements == 2 && - reply->element[0]->type == REDIS_REPLY_ARRAY && - reply->element[0]->elements == 2 && - !memcmp(reply->element[0]->element[0]->str,"bar",3) && - !memcmp(reply->element[0]->element[1]->str,"foo",3) && - reply->element[1]->type == REDIS_REPLY_STATUS && - strcasecmp(reply->element[1]->str,"pong") == 0); - freeReplyObject(reply); - - disconnect(c); -} - -static void test_blocking_io_errors(struct config config) { - redisContext *c; - redisReply *reply; - void *_reply; - int major, minor; - - /* Connect to target given by config. */ - c = connect(config); - { - /* Find out Redis version to determine the path for the next test */ - const char *field = "redis_version:"; - char *p, *eptr; - - reply = redisCommand(c,"INFO"); - p = strstr(reply->str,field); - major = strtol(p+strlen(field),&eptr,10); - p = eptr+1; /* char next to the first "." */ - minor = strtol(p,&eptr,10); - freeReplyObject(reply); - } - - test("Returns I/O error when the connection is lost: "); - reply = redisCommand(c,"QUIT"); - if (major >= 2 && minor > 0) { - /* > 2.0 returns OK on QUIT and read() should be issued once more - * to know the descriptor is at EOF. */ - test_cond(strcasecmp(reply->str,"OK") == 0 && - redisGetReply(c,&_reply) == REDIS_ERR); - freeReplyObject(reply); - } else { - test_cond(reply == NULL); - } - - /* On 2.0, QUIT will cause the connection to be closed immediately and - * the read(2) for the reply on QUIT will set the error to EOF. - * On >2.0, QUIT will return with OK and another read(2) needed to be - * issued to find out the socket was closed by the server. In both - * conditions, the error will be set to EOF. */ - assert(c->err == REDIS_ERR_EOF && - strcmp(c->errstr,"Server closed the connection") == 0); - redisFree(c); - - c = connect(config); - test("Returns I/O error on socket timeout: "); - struct timeval tv = { 0, 1000 }; - assert(redisSetTimeout(c,tv) == REDIS_OK); - test_cond(redisGetReply(c,&_reply) == REDIS_ERR && - c->err == REDIS_ERR_IO && errno == EAGAIN); - redisFree(c); -} - -static void test_throughput(struct config config) { - redisContext *c = connect(config); - redisReply **replies; - int i, num; - long long t1, t2; - - test("Throughput:\n"); - for (i = 0; i < 500; i++) - freeReplyObject(redisCommand(c,"LPUSH mylist foo")); - - num = 1000; - replies = malloc(sizeof(redisReply*)*num); - t1 = usec(); - for (i = 0; i < num; i++) { - replies[i] = redisCommand(c,"PING"); - assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS); - } - t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); - free(replies); - printf("\t(%dx PING: %.3fs)\n", num, (t2-t1)/1000000.0); - - replies = malloc(sizeof(redisReply*)*num); - t1 = usec(); - for (i = 0; i < num; i++) { - replies[i] = redisCommand(c,"LRANGE mylist 0 499"); - assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY); - assert(replies[i] != NULL && replies[i]->elements == 500); - } - t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); - free(replies); - printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2-t1)/1000000.0); - - num = 10000; - replies = malloc(sizeof(redisReply*)*num); - for (i = 0; i < num; i++) - redisAppendCommand(c,"PING"); - t1 = usec(); - for (i = 0; i < num; i++) { - assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK); - assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS); - } - t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); - free(replies); - printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0); - - replies = malloc(sizeof(redisReply*)*num); - for (i = 0; i < num; i++) - redisAppendCommand(c,"LRANGE mylist 0 499"); - t1 = usec(); - for (i = 0; i < num; i++) { - assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK); - assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY); - assert(replies[i] != NULL && replies[i]->elements == 500); - } - t2 = usec(); - for (i = 0; i < num; i++) freeReplyObject(replies[i]); - free(replies); - printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0); - - disconnect(c); -} - -// static long __test_callback_flags = 0; -// static void __test_callback(redisContext *c, void *privdata) { -// ((void)c); -// /* Shift to detect execution order */ -// __test_callback_flags <<= 8; -// __test_callback_flags |= (long)privdata; -// } -// -// static void __test_reply_callback(redisContext *c, redisReply *reply, void *privdata) { -// ((void)c); -// /* Shift to detect execution order */ -// __test_callback_flags <<= 8; -// __test_callback_flags |= (long)privdata; -// if (reply) freeReplyObject(reply); -// } -// -// static redisContext *__connect_nonblock() { -// /* Reset callback flags */ -// __test_callback_flags = 0; -// return redisConnectNonBlock("127.0.0.1", port, NULL); -// } -// -// static void test_nonblocking_connection() { -// redisContext *c; -// int wdone = 0; -// -// test("Calls command callback when command is issued: "); -// c = __connect_nonblock(); -// redisSetCommandCallback(c,__test_callback,(void*)1); -// redisCommand(c,"PING"); -// test_cond(__test_callback_flags == 1); -// redisFree(c); -// -// test("Calls disconnect callback on redisDisconnect: "); -// c = __connect_nonblock(); -// redisSetDisconnectCallback(c,__test_callback,(void*)2); -// redisDisconnect(c); -// test_cond(__test_callback_flags == 2); -// redisFree(c); -// -// test("Calls disconnect callback and free callback on redisFree: "); -// c = __connect_nonblock(); -// redisSetDisconnectCallback(c,__test_callback,(void*)2); -// redisSetFreeCallback(c,__test_callback,(void*)4); -// redisFree(c); -// test_cond(__test_callback_flags == ((2 << 8) | 4)); -// -// test("redisBufferWrite against empty write buffer: "); -// c = __connect_nonblock(); -// test_cond(redisBufferWrite(c,&wdone) == REDIS_OK && wdone == 1); -// redisFree(c); -// -// test("redisBufferWrite against not yet connected fd: "); -// c = __connect_nonblock(); -// redisCommand(c,"PING"); -// test_cond(redisBufferWrite(c,NULL) == REDIS_ERR && -// strncmp(c->error,"write:",6) == 0); -// redisFree(c); -// -// test("redisBufferWrite against closed fd: "); -// c = __connect_nonblock(); -// redisCommand(c,"PING"); -// redisDisconnect(c); -// test_cond(redisBufferWrite(c,NULL) == REDIS_ERR && -// strncmp(c->error,"write:",6) == 0); -// redisFree(c); -// -// test("Process callbacks in the right sequence: "); -// c = __connect_nonblock(); -// redisCommandWithCallback(c,__test_reply_callback,(void*)1,"PING"); -// redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING"); -// redisCommandWithCallback(c,__test_reply_callback,(void*)3,"PING"); -// -// /* Write output buffer */ -// wdone = 0; -// while(!wdone) { -// usleep(500); -// redisBufferWrite(c,&wdone); -// } -// -// /* Read until at least one callback is executed (the 3 replies will -// * arrive in a single packet, causing all callbacks to be executed in -// * a single pass). */ -// while(__test_callback_flags == 0) { -// assert(redisBufferRead(c) == REDIS_OK); -// redisProcessCallbacks(c); -// } -// test_cond(__test_callback_flags == 0x010203); -// redisFree(c); -// -// test("redisDisconnect executes pending callbacks with NULL reply: "); -// c = __connect_nonblock(); -// redisSetDisconnectCallback(c,__test_callback,(void*)1); -// redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING"); -// redisDisconnect(c); -// test_cond(__test_callback_flags == 0x0201); -// redisFree(c); -// } - -int main(int argc, char **argv) { - struct config cfg = { - .tcp = { - .host = "127.0.0.1", - .port = 6379 - }, - .unix = { - .path = "/tmp/redis.sock" - } - }; - int throughput = 1; - - /* Ignore broken pipe signal (for I/O error tests). */ - signal(SIGPIPE, SIG_IGN); - - /* Parse command line options. */ - argv++; argc--; - while (argc) { - if (argc >= 2 && !strcmp(argv[0],"-h")) { - argv++; argc--; - cfg.tcp.host = argv[0]; - } else if (argc >= 2 && !strcmp(argv[0],"-p")) { - argv++; argc--; - cfg.tcp.port = atoi(argv[0]); - } else if (argc >= 2 && !strcmp(argv[0],"-s")) { - argv++; argc--; - cfg.unix.path = argv[0]; - } else if (argc >= 1 && !strcmp(argv[0],"--skip-throughput")) { - throughput = 0; - } else { - fprintf(stderr, "Invalid argument: %s\n", argv[0]); - exit(1); - } - argv++; argc--; - } - - test_format_commands(); - test_reply_reader(); - test_blocking_connection_errors(); - - printf("\nTesting against TCP connection (%s:%d):\n", cfg.tcp.host, cfg.tcp.port); - cfg.type = CONN_TCP; - test_blocking_connection(cfg); - test_blocking_io_errors(cfg); - if (throughput) test_throughput(cfg); - - printf("\nTesting against Unix socket connection (%s):\n", cfg.unix.path); - cfg.type = CONN_UNIX; - test_blocking_connection(cfg); - test_blocking_io_errors(cfg); - if (throughput) test_throughput(cfg); - - if (fails) { - printf("*** %d TESTS FAILED ***\n", fails); - return 1; - } - - printf("ALL TESTS PASSED\n"); - return 0; -} diff --git a/node_modules/hiredis/hiredis.cc b/node_modules/hiredis/hiredis.cc deleted file mode 100644 index 2751fdd..0000000 --- a/node_modules/hiredis/hiredis.cc +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include -#include "reader.h" - -using namespace v8; - -extern "C" { - static void init (Handle target) { - HandleScope scope; - hiredis::Reader::Initialize(target); - } - NODE_MODULE(hiredis,init); -} - diff --git a/node_modules/hiredis/hiredis.js b/node_modules/hiredis/hiredis.js deleted file mode 100644 index 952f522..0000000 --- a/node_modules/hiredis/hiredis.js +++ /dev/null @@ -1,39 +0,0 @@ -var hiredis, net = require("net"); - -try { - hiredis = require('./build/Release/hiredis'); -} catch (e) { - hiredis = require('./build/default/hiredis'); -} - -exports.Reader = hiredis.Reader; -exports.createConnection = function(port, host) { - var s = net.createConnection(port || 6379, host); - var r = new hiredis.Reader(); - var _write = s.write; - - s.write = function() { - var i, args = arguments; - _write.call(s, "*" + args.length + "\r\n"); - for (i = 0; i < args.length; i++) { - var arg = args[i]; - _write.call(s, "$" + arg.length + "\r\n" + arg + "\r\n"); - } - } - - s.on("data", function(data) { - var reply; - r.feed(data); - try { - while((reply = r.get()) !== undefined) - s.emit("reply", reply); - } catch(err) { - r = null; - s.emit("error", err); - s.destroy(); - } - }); - - return s; -} - diff --git a/node_modules/hiredis/package.json b/node_modules/hiredis/package.json deleted file mode 100644 index b8755ad..0000000 --- a/node_modules/hiredis/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "hiredis", - "description": "Wrapper for reply processing code in hiredis", - "version": "0.1.14", - "homepage": "http://github.com/pietern/hiredis-node", - "author": "Pieter Noordhuis ", - "main": "hiredis", - "directories": { - "lib": "." - }, - "scripts": { - "preinstall": "make || gmake", - "test": "node test/reader.js" - }, - "engines": { - "node": "*" - } -} diff --git a/node_modules/hiredis/parser_bench.js b/node_modules/hiredis/parser_bench.js deleted file mode 100644 index 95ecb09..0000000 --- a/node_modules/hiredis/parser_bench.js +++ /dev/null @@ -1,37 +0,0 @@ -var hiredis = require("./hiredis"); - - -function go(num) { - var parser = new hiredis.Reader(); - - var i, j; - var n = 10, m = 0; - - var feed = "*" + n + "\r\n"; - for (i = 0; i < n; i++) { - if (m > 1) { - feed += "*" + m + "\r\n"; - for (j = 0; j < m; j++) { - feed += "$10\r\nxxxxxxxxxx\r\n"; - } - } else { - feed += "$10\r\nxxxxxxxxxx\r\n"; - } - } - - var t1 = new Date, t2; - for (i = 0; i < num; i++) { - parser.feed(feed); - parser.get(); - } - - t2 = new Date; - console.log("" + num + " took: " + (t2-t1) + "ms"); -} - - -var stdin = process.openStdin(); -stdin.on('data', function(chunk) { - go(parseInt(chunk)); -}); - diff --git a/node_modules/hiredis/reader.cc b/node_modules/hiredis/reader.cc deleted file mode 100644 index f400be3..0000000 --- a/node_modules/hiredis/reader.cc +++ /dev/null @@ -1,238 +0,0 @@ -#include -#include -#include -#include -#include -#include "reader.h" - -using namespace hiredis; - -static void *tryParentize(const redisReadTask *task, const Local &v) { - Reader *r = reinterpret_cast(task->privdata); - size_t pidx, vidx; - - if (task->parent != NULL) { - pidx = (size_t)task->parent->obj; - assert(pidx > 0 && pidx < 3); - - /* When there is a parent, it should be an array. */ - assert(r->handle[pidx]->IsArray()); - Local parent = Local::Cast(r->handle[pidx]->ToObject()); - parent->Set(task->idx,v); - - /* Store the handle when this is an inner array. Otherwise, hiredis - * doesn't care about the return value as long as the value is set in - * its parent array. */ - vidx = pidx+1; - if (v->IsArray()) { - r->handle[vidx].Dispose(); - r->handle[vidx].Clear(); - r->handle[vidx] = Persistent::New(v); - return (void*)vidx; - } else { - /* Return value doesn't matter for inner value, as long as it is - * not NULL (which means OOM for hiredis). */ - return (void*)0xcafef00d; - } - } else { - /* There is no parent, so this value is the root object. */ - r->handle[1] = Persistent::New(v); - return (void*)1; - } -} - -static void *createArray(const redisReadTask *task, int size) { - Local v(Array::New(size)); - return tryParentize(task,v); -} - -static void *createString(const redisReadTask *task, char *str, size_t len) { - Reader *r = reinterpret_cast(task->privdata); - Local v(r->createString(str,len)); - - if (task->type == REDIS_REPLY_ERROR) - v = Exception::Error(v->ToString()); - return tryParentize(task,v); -} - -static void *createInteger(const redisReadTask *task, long long value) { - Local v(Number::New(value)); - return tryParentize(task,v); -} - -static void *createNil(const redisReadTask *task) { - Local v(Local::New(Null())); - return tryParentize(task,v); -} - -static redisReplyObjectFunctions v8ReplyFunctions = { - createString, - createArray, - createInteger, - createNil, - NULL /* No free function: cleanup is done in Reader::Get. */ -}; - -Reader::Reader(bool return_buffers) : - return_buffers(return_buffers) -{ - reader = redisReaderCreate(); - reader->fn = &v8ReplyFunctions; - reader->privdata = this; - -#if NODE_VERSION_AT_LEAST(0,3,0) - if (return_buffers) { - Local global = Context::GetCurrent()->Global(); - Local bv = global->Get(String::NewSymbol("Buffer")); - assert(bv->IsFunction()); - Local bf = Local::Cast(bv); - buffer_fn = Persistent::New(bf); - - buffer_pool_length = 8*1024; /* Same as node */ - buffer_pool_offset = 0; - - Buffer *b = Buffer::New(buffer_pool_length); - buffer_pool = Persistent::New(b->handle_); - } -#endif -} - -Reader::~Reader() { - redisReaderFree(reader); -} - -/* Don't use a HandleScope here, so the objects are created within the scope of - * the caller (Reader::Get) and we don't have to the pay the overhead. */ -Local Reader::createString(char *str, size_t len) { - if (return_buffers) { -#if NODE_VERSION_AT_LEAST(0,3,0) - if (len > buffer_pool_length) { - Buffer *b = Buffer::New(str,len); - return Local::New(b->handle_); - } else { - return createBufferFromPool(str,len); - } -#else - Buffer *b = Buffer::New(len); - memcpy(b->data(),str,len); - return Local::New(b->handle_); -#endif - } else { - return String::New(str,len); - } -} - -#if NODE_VERSION_AT_LEAST(0,3,0) -Local Reader::createBufferFromPool(char *str, size_t len) { - HandleScope scope; - Local argv[3]; - Local instance; - - assert(len <= buffer_pool_length); - if (buffer_pool_length - buffer_pool_offset < len) { - Buffer *b = Buffer::New(buffer_pool_length); - buffer_pool.Dispose(); - buffer_pool = Persistent::New(b->handle_); - buffer_pool_offset = 0; - } - - memcpy(Buffer::Data(buffer_pool)+buffer_pool_offset,str,len); - - argv[0] = Local::New(buffer_pool); - argv[1] = Integer::New(len); - argv[2] = Integer::New(buffer_pool_offset); - instance = buffer_fn->NewInstance(3,argv); - buffer_pool_offset += len; - return scope.Close(instance); -} -#endif - -Handle Reader::New(const Arguments& args) { - HandleScope scope; - bool return_buffers = false; - - if (args.Length() > 0 && args[0]->IsObject()) { - Local bv = args[0]->ToObject()->Get(String::New("return_buffers")); - if (bv->IsBoolean()) - return_buffers = bv->ToBoolean()->Value(); - } - - Reader *r = new Reader(return_buffers); - r->Wrap(args.This()); - return scope.Close(args.This()); -} - -void Reader::Initialize(Handle target) { - HandleScope scope; - - Local t = FunctionTemplate::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - NODE_SET_PROTOTYPE_METHOD(t, "feed", Feed); - NODE_SET_PROTOTYPE_METHOD(t, "get", Get); - target->Set(String::NewSymbol("Reader"), t->GetFunction()); -} - -Handle Reader::Feed(const Arguments &args) { - HandleScope scope; - Reader *r = ObjectWrap::Unwrap(args.This()); - - if (args.Length() == 0) { - return ThrowException(Exception::Error( - String::New("First argument must be a string or buffer"))); - } else { - if (Buffer::HasInstance(args[0])) { - Local buffer_object = args[0]->ToObject(); - char *data; - size_t length; - -#if NODE_VERSION_AT_LEAST(0,3,0) - data = Buffer::Data(buffer_object); - length = Buffer::Length(buffer_object); -#else - Buffer *buffer = ObjectWrap::Unwrap(buffer_object); - data = buffer->data(); - length = buffer->length(); -#endif - - /* Can't handle OOM for now. */ - assert(redisReaderFeed(r->reader, data, length) == REDIS_OK); - } else if (args[0]->IsString()) { - String::Utf8Value str(args[0]->ToString()); - redisReplyReaderFeed(r->reader, *str, str.length()); - } else { - return ThrowException(Exception::Error( - String::New("Invalid argument"))); - } - } - - return args.This(); -} - -Handle Reader::Get(const Arguments &args) { - HandleScope scope; - Reader *r = ObjectWrap::Unwrap(args.This()); - void *index = NULL; - Local reply; - int i; - - if (redisReaderGetReply(r->reader,&index) == REDIS_OK) { - if (index == 0) { - return Undefined(); - } else { - /* Complete replies should always have a root object at index 1. */ - assert((unsigned size_t)index == 1); - reply = Local::New(r->handle[1]); - - /* Dispose and clear used handles. */ - for (i = 1; i < 3; i++) { - r->handle[i].Dispose(); - r->handle[i].Clear(); - } - } - } else { - return ThrowException(Exception::Error(String::New(r->reader->errstr))); - } - - return scope.Close(reply); -} - diff --git a/node_modules/hiredis/reader.h b/node_modules/hiredis/reader.h deleted file mode 100644 index 4716646..0000000 --- a/node_modules/hiredis/reader.h +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include -#include - -namespace hiredis { - -using namespace v8; -using namespace node; - -class Reader : ObjectWrap { -public: - Reader(bool); - ~Reader(); - - static void Initialize(Handle target); - static Handle New(const Arguments& args); - static Handle Feed(const Arguments &args); - static Handle Get(const Arguments &args); - - /* Objects created by the reply object functions need to get back to the - * reader when the reply is requested via Reader::Get(). Keep temporary - * objects in this handle. Use an array of handles because replies may - * include nested multi bulks and child-elements need to be added to the - * right respective parent. handle[0] will be unused, so the real index of - * an object in this array can be returned from the reply object functions. - * The returned value needs to be non-zero to distinguish complete replies - * from incomplete replies. These are persistent handles because - * Reader::Get might not return a full reply and the objects need to be - * kept around for subsequent calls. */ - Persistent handle[3]; - - /* Helper function to create string/buffer objects. */ - Local createString(char *str, size_t len); - -private: - redisReader *reader; - - /* Determines whether to return strings or buffers for single line and bulk - * replies. This defaults to false, so strings are returned by default. */ - bool return_buffers; - -#if NODE_VERSION_AT_LEAST(0,3,0) - /* Use a buffer pool like the fast buffers. */ - Local createBufferFromPool(char *str, size_t len); - Persistent buffer_fn; - Persistent buffer_pool; - size_t buffer_pool_length; - size_t buffer_pool_offset; -#endif - -}; - -}; - diff --git a/node_modules/hiredis/test/reader.js b/node_modules/hiredis/test/reader.js deleted file mode 100644 index 21671a4..0000000 --- a/node_modules/hiredis/test/reader.js +++ /dev/null @@ -1,172 +0,0 @@ -var assert = require("assert"), - hiredis = require("../hiredis"); - -/* Monkey-patch Buffer.isBuffer on 0.3.1 */ -if (process.versions.node == "0.3.1") { - var SlowBuffer = process.binding('buffer').SlowBuffer; - Buffer.isBuffer = function isBuffer(b) { - return b instanceof Buffer || b instanceof SlowBuffer; - }; -} - -var passed = 0; -var failed = 0; - -function test(str, fn) { - try { - fn(); - passed++; - } catch (err) { - console.log("\x1B[1;31m" + str + " failed!\x1B[0m"); - console.log(err.stack + "\n"); - failed++; - } -} - -test("CreateReader", function() { - var reader = new hiredis.Reader(); - assert.notEqual(reader, null); -}); - -test("StatusReply", function() { - var reader = new hiredis.Reader(); - reader.feed("+OK\r\n"); - assert.equal("OK", reader.get()); -}); - -test("StatusReplyAsBuffer", function() { - var reader = new hiredis.Reader({ return_buffers: true }); - reader.feed("+OK\r\n"); - var reply = reader.get(); - assert.ok(Buffer.isBuffer(reply)); - assert.equal("OK", reply.toString()); -}); - -test("IntegerReply", function() { - var reader = new hiredis.Reader(); - reader.feed(":1\r\n"); - assert.equal(1, reader.get()); -}); - -// This test fails since v8 doesn't to 64-bit integers... -test("LargeIntegerReply", function() { - var reader = new hiredis.Reader(); - reader.feed(":9223372036854775807\r\n"); - assert.equal("9223372036854775807", String(reader.get())); -}); - -test("ErrorReply", function() { - var reader = new hiredis.Reader(); - reader.feed("-ERR foo\r\n"); - var reply = reader.get(); - assert.equal(Error, reply.constructor); - assert.equal("ERR foo", reply.message); -}); - -test("ErrorReplyWithReturnBuffers", function() { - var reader = new hiredis.Reader({ return_buffers: true }); - reader.feed("-ERR foo\r\n"); - var reply = reader.get(); - assert.equal(Error, reply.constructor); - assert.equal("ERR foo", reply.message); -}); - -test("NullBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("$-1\r\n"); - assert.equal(null, reader.get()); -}); - -test("EmptyBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("$0\r\n\r\n"); - assert.equal("", reader.get()); -}); - -test("BulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("$3\r\nfoo\r\n"); - assert.equal("foo", reader.get()); -}); - -test("BulkReplyAsBuffer", function() { - var reader = new hiredis.Reader({ return_buffers: true }); - reader.feed("$3\r\nfoo\r\n"); - var reply = reader.get(); - assert.ok(Buffer.isBuffer(reply)); - assert.equal("foo", reply.toString()); -}); - -test("BulkReplyWithEncoding", function() { - var reader = new hiredis.Reader(); - reader.feed("$" + Buffer.byteLength("☃") + "\r\n☃\r\n"); - assert.equal("☃", reader.get()); -}); - -test("NullMultiBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("*-1\r\n"); - assert.equal(null, reader.get()); -}); - -test("EmptyMultiBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("*0\r\n"); - assert.deepEqual([], reader.get()); -}); - -test("MultiBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n"); - assert.deepEqual(["foo", "bar"], reader.get()); -}); - -test("NestedMultiBulkReply", function() { - var reader = new hiredis.Reader(); - reader.feed("*2\r\n*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$3\r\nqux\r\n"); - assert.deepEqual([["foo", "bar"], "qux"], reader.get()); -}); - -test("MultiBulkReplyWithNonStringValues", function() { - var reader = new hiredis.Reader(); - reader.feed("*3\r\n:1\r\n+OK\r\n$-1\r\n"); - assert.deepEqual([1, "OK", null], reader.get()); -}); - -test("FeedWithBuffer", function() { - var reader = new hiredis.Reader(); - reader.feed(new Buffer("$3\r\nfoo\r\n")); - assert.deepEqual("foo", reader.get()); -}); - -test("UndefinedReplyOnIncompleteFeed", function() { - var reader = new hiredis.Reader(); - reader.feed("$3\r\nfoo"); - assert.deepEqual(undefined, reader.get()); - reader.feed("\r\n"); - assert.deepEqual("foo", reader.get()); -}); - -test("Leaks", function(beforeExit) { - /* The "leaks" utility is only available on OSX. */ - if (process.platform != "darwin") return; - - var done = 0; - var leaks = require('child_process').spawn("leaks", [process.pid]); - leaks.stdout.on("data", function(data) { - var str = data.toString(); - var notice = "Node 0.2.5 always leaks 16 bytes (this is " + process.versions.node + ")"; - var matches; - if ((matches = /(\d+) leaks?/i.exec(str)) != null) { - if (parseInt(matches[1]) > 0) { - console.log(str); - console.log('\x1B[31mNotice: ' + notice + '\x1B[0m'); - } - } - done = 1; - }); - - process.on('exit', function() { - assert.ok(done, "Leaks test should have completed"); - }); -}); diff --git a/node_modules/hiredis/wscript b/node_modules/hiredis/wscript deleted file mode 100644 index 3c6aa2f..0000000 --- a/node_modules/hiredis/wscript +++ /dev/null @@ -1,15 +0,0 @@ -def set_options(opt): - opt.tool_options("compiler_cxx") - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_unique('CXXFLAGS', ['-Wall', '-O3']) - conf.env['LIBPATH_HIREDIS'] = '../deps/hiredis' - conf.env['LIB_HIREDIS'] = 'hiredis' - -def build(bld): - ext = bld.new_task_gen("cxx", "shlib", "node_addon", uselib="HIREDIS") - ext.cxxflags = ["-I../deps", "-g", "-Wall"] - ext.source = "hiredis.cc reader.cc" - ext.target = "hiredis" diff --git a/node_modules/jade/.gitmodules b/node_modules/jade/.gitmodules deleted file mode 100644 index b5b4321..0000000 --- a/node_modules/jade/.gitmodules +++ /dev/null @@ -1,21 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git -[submodule "support/sass"] - path = support/sass - url = git://github.com/visionmedia/sass.js.git -[submodule "benchmarks/haml-js"] - path = benchmarks/haml-js - url = git://github.com/creationix/haml-js.git -[submodule "benchmarks/ejs"] - path = benchmarks/ejs - url = git://github.com/visionmedia/ejs.git -[submodule "benchmarks/haml"] - path = benchmarks/haml - url = git://github.com/visionmedia/haml.js.git -[submodule "support/coffee-script"] - path = support/coffee-script - url = http://github.com/jashkenas/coffee-script.git -[submodule "support/stylus"] - path = support/stylus - url = git://github.com/LearnBoost/stylus.git diff --git a/node_modules/jade/.npmignore b/node_modules/jade/.npmignore deleted file mode 100644 index 10fd0d4..0000000 --- a/node_modules/jade/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -test -support -benchmarks -examples diff --git a/node_modules/jade/.travis.yml b/node_modules/jade/.travis.yml deleted file mode 100644 index 381c985..0000000 --- a/node_modules/jade/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 \ No newline at end of file diff --git a/node_modules/jade/History.md b/node_modules/jade/History.md deleted file mode 100644 index 34976e6..0000000 --- a/node_modules/jade/History.md +++ /dev/null @@ -1,506 +0,0 @@ - -0.20.0 / 2011-12-28 -================== - - * Added a browser example - * Added `yield` for block `include`s - * Changed: replaced internal `__` var with `__jade` [chrisleishman] - * Fixed two globals. Closes #433 - -0.19.0 / 2011-12-02 -================== - - * Added block `append` / `prepend` support. Closes #355 - * Added link in readme to jade-mode for Emacs - * Added link to python implementation - -0.18.0 / 2011-11-21 -================== - - * Changed: only ['script', 'style'] are text-only. Closes #398' - -0.17.0 / 2011-11-10 -================== - - * jade.renderFile() is back! (for express 3.x) - * Fixed `Object.keys()` failover bug - -0.16.4 / 2011-10-24 -================== - - * Fixed a test due to reserved keyword - * Fixed: commander 0.1.x dep for 0.5.x - -0.16.3 / 2011-10-24 -================== - - * Added: allow leading space for conditional comments - * Added quick implementation of a switch statement - * Fixed parens in mixin args. Closes #380 - * Fixed: include files with a .jade extension as jade files - -0.16.2 / 2011-09-30 -================== - - * Fixed include regression. Closes #354 - -0.16.1 / 2011-09-29 -================== - - * Fixed unexpected `else` bug when compileDebug: false - * Fixed attr state issue for balancing pairs. Closes #353 - -0.16.0 / 2011-09-26 -================== - - * Added `include` block support. Closes #303 - * Added template inheritance via `block` and `extends`. Closes #242 - * Added 'type="text/css"' to the style tags generated by filters. - * Added 'uglifyjs' as an explicit devDependency. - * Added -p, --path flag to jade(1) - * Added support for any arbitrary doctype - * Added `jade.render(str[,options], fn)` back - * Added first-class `while` support - * Added first-class assignment support - * Fixed runtime.js `Array.isArray()` polyfill. Closes #345 - * Fixed: set .filename option in jade(1) when passing filenames - * Fixed `Object.keys()` polyfill typo. Closes #331 - * Fixed `include` error context - * Renamed magic "index" to "$index". Closes #350 - -0.15.4 / 2011-09-05 -================== - - * Fixed script template html. Closes #316 - * Revert "Fixed script() tag with trailing ".". Closes #314" - -0.15.3 / 2011-08-30 -================== - - * Added Makefile example. Closes #312 - * Fixed script() tag with trailing ".". Closes #314 - -0.15.2 / 2011-08-26 -================== - - * Fixed new conditional boundaries. Closes #307 - -0.15.1 / 2011-08-26 -================== - - * Fixed jade(1) support due to `res.render()` removal - * Removed --watch support (use a makefile + watch...) - -0.15.0 / 2011-08-26 -================== - - * Added `client` option to reference runtime helpers - * Added `Array.isArray()` for runtime.js as well - * Added `Object.keys()` for the client-side runtime - * Added first-class `if`, `unless`, `else` and `else if` support - * Added first-class `each` / `for` support - * Added `make benchmark` for continuous-bench - * Removed `inline` option, SS helpers are no longer inlined either - * Removed `Parser#debug()` - * Removed `jade.render()` and `jade.renderFile()` - * Fixed runtime.js `escape()` bug causing window.escape to be used - * Fixed a bunch of tests - -0.14.2 / 2011-08-16 -================== - - * Added `include` support for non-jade files - * Fixed code indentation when followed by newline(s). Closes #295 [reported by masylum] - -0.14.1 / 2011-08-14 -================== - - * Added `colons` option for everyone stuck with ":". Closes #231 - * Optimization: consecutive lines are merged in compiled js - -0.14.0 / 2011-08-08 -================== - - * Added array iteration with index example. Closes #276 - * Added _runtime.js_ - * Added `compileDebug` option to enable lineno instrumentation - * Added `inline` option to disable inlining of helpers (for client-side) - -0.13.0 / 2011-07-13 -================== - - * Added `mixin` support - * Added `include` support - * Added array support for the class attribute - -0.12.4 / 2011-06-23 -================== - - * Fixed filter indentation bug. Closes #243 - -0.12.3 / 2011-06-21 -================== - - * Fixed empty strings support. Closes #223 - * Fixed conditional comments documentation. Closes #245 - -0.12.2 / 2011-06-16 -================== - - * Fixed `make test` - * Fixed block comments - -0.12.1 / 2011-06-04 -================== - - * Fixed attribute interpolation with double quotes. Fixes #232 [topaxi] - -0.12.0 / 2011-06-03 -================== - - * Added `doctype` as alias of `!!!` - * Added; doctype value is now case-insensitive - * Added attribute interpolation support - * Fixed; retain original indentation spaces in text blocks - -0.11.1 / 2011-06-01 -================== - - * Fixed text block indentation [Laszlo Bacsi] - * Changed; utilizing devDependencies - * Fixed try/catch issue with renderFile(). Closes #227 - * Removed attribute ":" support, use "=" (option for ':' coming soon) - -0.11.0 / 2011-05-14 -================== - - * Added `self` object to avoid poor `with(){}` performance [masylum] - * Added `doctype` option [Jeremy Larkin] - -0.10.7 / 2011-05-04 -================== - - * expose Parser - -0.10.6 / 2011-04-29 -================== - - * Fixed CS `Object.keys()` [reported by robholland] - -0.10.5 / 2011-04-26 -================== - - * Added error context after the lineno - * Added; indicate failing lineno with ">" - * Added `Object.keys()` for the client-side - * Fixed attr strings when containing the opposite quote. Closes 207 - * Fixed attr issue with js expressions within strings - * Fixed single-quote filter escape bug. Closes #196 - - -0.10.4 / 2011-04-05 -================== - - * Added `html` doctype, same as "5" - * Fixed `pre`, no longer text-only - -0.10.3 / 2011-03-30 -================== - - * Fixed support for quoted attribute keys ex `rss("xmlns:atom"="atom")` - -0.10.2 / 2011-03-30 -================== - - * Fixed pipeless text bug with missing outdent - -0.10.1 / 2011-03-28 -================== - - * Fixed `support/compile.js` to exclude browser js in node - * Fixes for IE [Patrick Pfeiffer] - -0.10.0 / 2011-03-25 -================== - - * Added AST-filter support back in the form of `[attrs]<:>` - -0.9.3 / 2011-03-24 -================== - - * Added `Block#unshift(node)` - * Added `jade.js` for the client-side to the repo - * Added `jade.min.js` for the client-side to the repo - * Removed need for pipes in filters. Closes #185 - Note that this _will_ break filters used to - manipulate the AST, until we have a different - syntax for doing so. - -0.9.2 / 2011-03-23 -================== - - * Added jade `--version` - * Removed `${}` interpolation support, use `#{}` - -0.9.1 / 2011-03-16 -================== - - * Fixed invalid `.map()` call due to recent changes - -0.9.0 / 2011-03-16 -================== - - * Added client-side browser support via `make jade.js` and `make jade.min.js`. - -0.8.9 / 2011-03-15 -================== - - * Fixed preservation of newlines in text blocks - -0.8.8 / 2011-03-14 -================== - - * Fixed jade(1) stdio - -0.8.7 / 2011-03-14 -================== - - * Added `mkdirs()` to jade(1) - * Added jade(1) stdio support - * Added new features to jade(1), `--watch`, recursive compilation etc [khingebjerg] - * Fixed pipe-less text newlines - * Removed jade(1) `--pipe` flag - -0.8.6 / 2011-03-11 -================== - - * Fixed parenthesized expressions in attrs. Closes #170 - * Changed; default interpolation values `== null` to ''. Closes #167 - -0.8.5 / 2011-03-09 -================== - - * Added pipe-less text support with immediate ".". Closes #157 - * Fixed object support in attrs - * Fixed array support for attrs - -0.8.4 / 2011-03-08 -================== - - * Fixed issue with expressions being evaluated several times. closes #162 - -0.8.2 / 2011-03-07 -================== - - * Added markdown, discount, and markdown-js support to `:markdown`. Closes #160 - * Removed `:discount` - -0.8.1 / 2011-03-04 -================== - - * Added `pre` pipe-less text support (and auto-escaping) - -0.8.0 / 2011-03-04 -================== - - * Added block-expansion support. Closes #74 - * Added support for multi-line attrs without commas. Closes #65 - -0.7.1 / 2011-03-04 -================== - - * Fixed `script()` etc pipe-less text with attrs - -0.7.0 / 2011-03-04 -================== - - * Removed `:javascript` filter (it doesn't really do anything special, use `script` tags) - * Added pipe-less text support. Tags that only accept text nodes (`script`, `textarea`, etc) do not require `|`. - * Added `:text` filter for ad-hoc pipe-less - * Added flexible indentation. Tabs, arbitrary number of spaces etc - * Added conditional-comment support. Closes #146 - * Added block comment support - * Added rss example - * Added `:stylus` filter - * Added `:discount` filter - * Fixed; auto-detect xml and do not self-close tags. Closes #147 - * Fixed whitespace issue. Closes #118 - * Fixed attrs. `,`, `=`, and `:` within attr value strings are valid Closes #133 - * Fixed; only output "" when code == null. Ex: `span.name= user.name` when undefined or null will not output "undefined". Closes #130 - * Fixed; throw on unexpected token instead of hanging - -0.6.3 / 2011-02-02 -================== - - * Added `each` support for Array-like objects [guillermo] - -0.6.2 / 2011-02-02 -================== - - * Added CSRF example, showing how you can transparently add inputs to a form - * Added link to vim-jade - * Fixed self-closing col support [guillermo] - * Fixed exception when getAttribute or removeAttribute run into removed attributes [Naitik Shah] - -0.6.0 / 2010-12-19 -================== - - * Added unescaped interpolation variant `!{code}`. Closes #124 - * Changed; escape interpolated code by default `#{code}` - -0.5.7 / 2010-12-08 -================== - - * Fixed; hyphen in get `tag()` - -0.5.6 / 2010-11-24 -================== - - * Added `exports.compile(str, options)` - * Renamed internal `_` to `__`, since `_()` is commonly used for translation - -0.5.5 / 2010-10-30 -================== - - * Add _coffeescript_ filter [Michael Hampton] - * Added link to _slim_; a ruby implementation - * Fixed quoted attributes issue. - - * Fixed attribute issue with over greedy regexp. - Previously "p(foo=(((('bar')))))= ((('baz')))" - would __fail__ for example since the regexp - would lookahead to far. Now we simply pair - the delimiters. - -0.5.4 / 2010-10-18 -================== - - * Adding newline when using tag code when preceding text - * Assume newline in tag text when preceding text - * Changed; retain leading text whitespace - * Fixed code block support to prevent multiple buffer openings [Jake Luer] - * Fixed nested filter support - -0.5.3 / 2010-10-06 -================== - - * Fixed bug when tags with code also have a block [reported by chrisirhc] - -0.5.2 / 2010-10-05 -================== - - * Added; Text introduces newlines to mimic the grammar. - Whitespace handling is a little tricky with this sort of grammar. - Jade will now mimic the written grammar, meaning that text blocks - using the "|" margin character will introduce a literal newline, - where as immediate tag text (ex "a(href='#') Link") will not. - - This may not be ideal, but it makes more sense than what Jade was - previously doing. - - * Added `Tag#text` to disambiguate between immediate / block text - * Removed _pretty_ option (was kinda useless in the state it was in) - * Reverted ignoring of newlines. Closes #92. - * Fixed; `Parser#parse()` ignoring newlines - -0.5.1 / 2010-10-04 -================== - - * Added many examples - * Added; compiler api is now public - * Added; filters can accept / manipulate the parse tree - * Added filter attribute support. Closes #79 - * Added LL(*) capabilities - * Performance; wrapping code blocks in {} instead of `(function(){}).call(this)` - * Performance; Optimized attribute buffering - * Fixed trailing newlines in blocks - -0.5.0 / 2010-09-11 -================== - - * __Major__ refactor. Logic now separated into lexer/parser/compiler for future extensibility. - * Added _pretty_ option - * Added parse tree output for _debug_ option - * Added new examples - * Removed _context_ option, use _scope_ - -0.4.1 / 2010-09-09 -================== - - * Added support for arbitrary indentation for single-line comments. Closes #71 - * Only strip first space in text (ex '| foo' will buffer ' foo') - -0.4.0 / 2010-08-30 -================== - - * Added tab naive support (tabs are converted to a single indent, aka two spaces). Closes #24 - * Added unbuffered comment support. Closes #62 - * Added hyphen support for tag names, ex: "fb:foo-bar" - * Fixed bug with single quotes in comments. Closes #61 - * Fixed comment whitespace issue, previously padding. Closes #55 - -0.3.0 / 2010-08-04 -================== - - * Added single line comment support. Closes #25 - * Removed CDATA from _:javascript_ filter. Closes #47 - * Removed _sys_ local - * Fixed code following tag - -0.2.4 / 2010-08-02 -================== - - * Added Buffer support to `render()` - * Fixed filter text block exception reporting - * Fixed tag exception reporting - -0.2.3 / 2010-07-27 -================== - - * Fixed newlines before block - * Fixed; tag text allowing arbitrary trailing whitespace - -0.2.2 / 2010-07-16 -================== - - * Added support for `jade.renderFile()` to utilize primed cache - * Added link to [textmate bundle](http://github.com/miksago/jade-tmbundle) - * Fixed filter issue with single quotes - * Fixed hyphenated attr bug - * Fixed interpolation single quotes. Closes #28 - * Fixed issue with comma in attrs - -0.2.1 / 2010-07-09 -================== - - * Added support for node-discount and markdown-js - depending on which is available. - - * Added support for tags to have blocks _and_ text. - this kinda fucks with arbitrary whitespace unfortunately, - but also fixes trailing spaces after tags _with_ blocks. - - * Caching generated functions. Closes #46 - -0.2.0 / 2010-07-08 -================== - - * Added `- each` support for readable iteration - * Added [markdown-js](http://github.com/evilstreak/markdown-js) support (no compilation required) - * Removed node-discount support - -0.1.0 / 2010-07-05 -================== - - * Added `${}` support for interpolation. Closes #45 - * Added support for quoted attr keys: `label("for": 'something')` is allowed (_although not required_) [Guillermo] - * Added `:less` filter [jakeluer] - -0.0.2 / 2010-07-03 -================== - - * Added `context` as synonym for `scope` option [Guillermo] - * Fixed attr splitting: `div(style:"color: red")` is now allowed - * Fixed issue with `(` and `)` within attrs: `a(class: (a ? 'a' : 'b'))` is now allowed - * Fixed issue with leading / trailing spaces in attrs: `a( href="#" )` is now allowed [Guillermo] - diff --git a/node_modules/jade/LICENSE b/node_modules/jade/LICENSE deleted file mode 100644 index 8ad0e0d..0000000 --- a/node_modules/jade/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/jade/Makefile b/node_modules/jade/Makefile deleted file mode 100644 index 6ef5edb..0000000 --- a/node_modules/jade/Makefile +++ /dev/null @@ -1,40 +0,0 @@ - -TESTS = test/*.js -SRC = $(shell find lib -name "*.js" -type f) -UGLIFY = $(shell find node_modules -name "uglifyjs" -type f) -UGLIFY_FLAGS = --no-mangle - -all: jade.min.js runtime.min.js - -test: - @./node_modules/.bin/mocha \ - --ui exports \ - --globals name \ - $(TESTS) - -benchmark: - @node support/benchmark - -jade.js: $(SRC) - @node support/compile.js $^ - -jade.min.js: jade.js - @$(UGLIFY) $(UGLIFY_FLAGS) $< > $@ \ - && du jade.min.js \ - && du jade.js - -runtime.js: lib/runtime.js - @cat support/head.js $< support/foot.js > $@ - -runtime.min.js: runtime.js - @$(UGLIFY) $(UGLIFY_FLAGS) $< > $@ \ - && du runtime.min.js \ - && du runtime.js - -clean: - rm -f jade.js - rm -f jade.min.js - rm -f runtime.js - rm -f runtime.min.js - -.PHONY: test benchmark clean diff --git a/node_modules/jade/Readme.md b/node_modules/jade/Readme.md deleted file mode 100644 index c9dc782..0000000 --- a/node_modules/jade/Readme.md +++ /dev/null @@ -1,1072 +0,0 @@ - [![Build Status](https://secure.travis-ci.org/visionmedia/jade.png)](http://travis-ci.org/visionmedia/jade) - -# Jade - template engine - - Jade is a high performance template engine heavily influenced by [Haml](http://haml-lang.com) - and implemented with JavaScript for [node](http://nodejs.org). - -## Features - - - client-side support - - great readability - - flexible indentation - - block-expansion - - mixins - - static includes - - attribute interpolation - - code is escaped by default for security - - contextual error reporting at compile & run time - - executable for compiling jade templates via the command line - - html 5 mode (using the _!!! 5_ doctype) - - optional memory caching - - combine dynamic and static tag classes - - parse tree manipulation via _filters_ - - template inheritance - - block append / prepend - - supports [Express JS](http://expressjs.com) out of the box - - transparent iteration over objects, arrays, and even non-enumerables via `each` - - block comments - - no tag prefix - - AST filters - - filters - - :stylus must have [stylus](http://github.com/LearnBoost/stylus) installed - - :sass must have [sass.js](http://github.com/visionmedia/sass.js) installed - - :less must have [less.js](http://github.com/cloudhead/less.js) installed - - :markdown must have [markdown-js](http://github.com/evilstreak/markdown-js) installed or [node-discount](http://github.com/visionmedia/node-discount) - - :cdata - - :coffeescript must have [coffee-script](http://jashkenas.github.com/coffee-script/) installed - - [Emacs Mode](https://github.com/brianc/jade-mode) - - [Vim Syntax](https://github.com/digitaltoad/vim-jade) - - [TextMate Bundle](http://github.com/miksago/jade-tmbundle) - - [Screencasts](http://tjholowaychuk.com/post/1004255394/jade-screencast-template-engine-for-nodejs) - - [html2jade](https://github.com/donpark/html2jade) converter - -## Implementations - - - [php](http://github.com/everzet/jade.php) - - [scala](http://scalate.fusesource.org/versions/snapshot/documentation/scaml-reference.html) - - [ruby](http://github.com/stonean/slim) - - [python](https://github.com/SyrusAkbary/pyjade) - -## Installation - -via npm: - - npm install jade - -## Browser Support - - To compile jade to a single file compatible for client-side use simply execute: - - $ make jade.js - - Alternatively, if uglifyjs is installed via npm (`npm install uglify-js`) you may execute the following which will create both files. However each release builds these for you. - - $ make jade.min.js - - By default Jade instruments templates with line number statements such as `__.lineno = 3` for debugging purposes. When used in a browser it's useful to minimize this boiler plate, you can do so by passing the option `{ compileDebug: false }`. The following template - - p Hello #{name} - - Can then be as small as the following generated function: - -```js -function anonymous(locals, attrs, escape, rethrow) { - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - - Through the use of Jade's `./runtime.js` you may utilize these pre-compiled templates on the client-side _without_ Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as `jade.attrs`, `jade.escape` etc. To enable this you should pass `{ client: true }` to `jade.compile()` to tell Jade to reference the helper functions - via `jade.attrs`, `jade.escape` etc. - -```js -function anonymous(locals, attrs, escape, rethrow) { - var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; - var buf = []; - with (locals || {}) { - var interp; - buf.push('\n

    Hello ' + escape((interp = name) == null ? '' : interp) + '\n

    '); - } - return buf.join(""); -} -``` - -## Public API - -```javascript - var jade = require('jade'); - - // Compile a function - var fn = jade.compile('string of jade', options); - fn(locals); -``` - -### Options - - - `self` Use a `self` namespace to hold the locals. _false by default_ - - `locals` Local variable object - - `filename` Used in exceptions, and required when using includes - - `debug` Outputs tokens and function body generated - - `compiler` Compiler to replace jade's default - - `compileDebug` When `false` no debug instrumentation is compiled - -## Syntax - -### Line Endings - -**CRLF** and **CR** are converted to **LF** before parsing. - -### Tags - -A tag is simply a leading word: - - html - -for example is converted to `` - -tags can also have ids: - - div#container - -which would render `
    ` - -how about some classes? - - div.user-details - -renders `
    ` - -multiple classes? _and_ an id? sure: - - div#foo.bar.baz - -renders `
    ` - -div div div sure is annoying, how about: - - #foo - .bar - -which is syntactic sugar for what we have already been doing, and outputs: - - `
    ` - -### Tag Text - -Simply place some content after the tag: - - p wahoo! - -renders `

    wahoo!

    `. - -well cool, but how about large bodies of text: - - p - | foo bar baz - | rawr rawr - | super cool - | go jade go - -renders `

    foo bar baz rawr.....

    ` - -interpolation? yup! both types of text can utilize interpolation, -if we passed `{ name: 'tj', email: 'tj@vision-media.ca' }` to the compiled function we can do the following: - - #user #{name} <#{email}> - -outputs `
    tj <tj@vision-media.ca>
    ` - -Actually want `#{}` for some reason? escape it! - - p \#{something} - -now we have `

    #{something}

    ` - -We can also utilize the unescaped variant `!{html}`, so the following -will result in a literal script tag: - - - var html = "" - | !{html} - -Nested tags that also contain text can optionally use a text block: - - label - | Username: - input(name='user[name]') - -or immediate tag text: - - label Username: - input(name='user[name]') - -Tags that accept _only_ text such as `script` and `style` do not -need the leading `|` character, for example: - - html - head - title Example - script - if (foo) { - bar(); - } else { - baz(); - } - -Once again as an alternative, we may use a trailing '.' to indicate a text block, for example: - - p. - foo asdf - asdf - asdfasdfaf - asdf - asd. - -outputs: - -

    foo asdf - asdf - asdfasdfaf - asdf - asd. -

    - -This however differs from a trailing '.' followed by a space, which although is ignored by the Jade parser, tells Jade that this period is a literal: - - p . - -outputs: - -

    .

    - - -It should be noted that text blocks should be doubled escaped. For example if you desire the following output. - -

    foo\bar

    - -use: - - p. - foo\\bar - -### Comments - -Single line comments currently look the same as JavaScript comments, -aka "//" and must be placed on their own line: - - // just some paragraphs - p foo - p bar - -would output - - -

    foo

    -

    bar

    - -Jade also supports unbuffered comments, by simply adding a hyphen: - - //- will not output within markup - p foo - p bar - -outputting - -

    foo

    -

    bar

    - -### Block Comments - - A block comment is legal as well: - - body - // - #content - h1 Example - -outputting - - - - - -Jade supports conditional-comments as well, for example: - - head - //if lt IE 8 - script(src='/ie-sucks.js') - -outputs: - - - - - - -### Nesting - - Jade supports nesting to define the tags in a natural way: - - ul - li.first - a(href='#') foo - li - a(href='#') bar - li.last - a(href='#') baz - -### Block Expansion - - Block expansion allows you to create terse single-line nested tags, - the following example is equivalent to the nesting example above. - - ul - li.first: a(href='#') foo - li: a(href='#') bar - li.last: a(href='#') baz - -### Case - - The case statement takes the following form: - - html - body - friends = 10 - case friends - when 0 - p you have no friends - when 1 - p you have a friend - default - p you have #{friends} friends - - Block expansion may also be used: - - friends = 5 - - html - body - case friends - when 0: p you have no friends - when 1: p you have a friend - default: p you have #{friends} friends - -### Attributes - -Jade currently supports '(' and ')' as attribute delimiters. - - a(href='/login', title='View login page') Login - -When a value is `undefined` or `null` the attribute is _not_ added, -so this is fine, it will not compile 'something="null"'. - - div(something=null) - -Boolean attributes are also supported: - - input(type="checkbox", checked) - -Boolean attributes with code will only output the attribute when `true`: - - input(type="checkbox", checked=someValue) - -Multiple lines work too: - - input(type='checkbox', - name='agreement', - checked) - -Multiple lines without the comma work fine: - - input(type='checkbox' - name='agreement' - checked) - -Funky whitespace? fine: - - - input( - type='checkbox' - name='agreement' - checked) - -Colons work: - - rss(xmlns:atom="atom") - -Suppose we have the `user` local `{ id: 12, name: 'tobi' }` -and we wish to create an anchor tag with `href` pointing to "/user/12" -we could use regular javascript concatenation: - - a(href='/user/' + user.id)= user.name - -or we could use jade's interpolation, which I added because everyone -using Ruby or CoffeeScript seems to think this is legal js..: - - a(href='/user/#{user.id}')= user.name - -The `class` attribute is special-cased when an array is given, -allowing you to pass an array such as `bodyClasses = ['user', 'authenticated']` directly: - - body(class=bodyClasses) - -### HTML - - Inline html is fine, we can use the pipe syntax to - write arbitrary text, in this case some html: - -``` -html - body - |

    Title

    - |

    foo bar baz

    -``` - - Or we can use the trailing `.` to indicate to Jade that we - only want text in this block, allowing us to omit the pipes: - -``` -html - body. -

    Title

    -

    foo bar baz

    -``` - - Both of these examples yield the same result: - -``` -

    Title

    -

    foo bar baz

    - -``` - - The same rule applies for anywhere you can have text - in jade, raw html is fine: - -``` -html - body - h1 User #{name} -``` - -### Doctypes - -To add a doctype simply use `!!!`, or `doctype` followed by an optional value: - - !!! - -Will output the _transitional_ doctype, however: - - !!! 5 - -or - - !!! html - -or - - doctype html - -doctypes are case-insensitive, so the following are equivalent: - - doctype Basic - doctype basic - -it's also possible to simply pass a doctype literal: - - doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN - -yielding: - - - -Will output the _html 5_ doctype. Below are the doctypes -defined by default, which can easily be extended: - -```javascript - var doctypes = exports.doctypes = { - '5': '', - 'xml': '', - 'default': '', - 'transitional': '', - 'strict': '', - 'frameset': '', - '1.1': '', - 'basic': '', - 'mobile': '' - }; -``` - -To alter the default simply change: - -```javascript - jade.doctypes.default = 'whatever you want'; -``` - -## Filters - -Filters are prefixed with `:`, for example `:markdown` and -pass the following block of text to an arbitrary function for processing. View the _features_ -at the top of this document for available filters. - - body - :markdown - Woah! jade _and_ markdown, very **cool** - we can even link to [stuff](http://google.com) - -Renders: - -

    Woah! jade and markdown, very cool we can even link to stuff

    - -## Code - -Jade currently supports three classifications of executable code. The first -is prefixed by `-`, and is not buffered: - - - var foo = 'bar'; - -This can be used for conditionals, or iteration: - - - for (var key in obj) - p= obj[key] - -Due to Jade's buffering techniques the following is valid as well: - - - if (foo) - ul - li yay - li foo - li worked - - else - p oh no! didnt work - -Hell, even verbose iteration: - - - if (items.length) - ul - - items.forEach(function(item){ - li= item - - }) - -Anything you want! - -Next up we have _escaped_ buffered code, which is used to -buffer a return value, which is prefixed by `=`: - - - var foo = 'bar' - = foo - h1= foo - -Which outputs `bar

    bar

    `. Code buffered by `=` is escaped -by default for security, however to output unescaped return values -you may use `!=`: - - p!= aVarContainingMoreHTML - - Jade also has designer-friendly variants, making the literal JavaScript - more expressive and declarative. For example the following assignments - are equivalent, and the expression is still regular javascript: - - - var foo = 'foo ' + 'bar' - foo = 'foo ' + 'bar' - - Likewise Jade has first-class `if`, `else if`, `else`, `until`, `while`, `unless` among others, however you must remember that the expressions are still regular javascript: - - if foo == 'bar' - ul - li yay - li foo - li worked - else - p oh no! didnt work - -## Iteration - - Along with vanilla JavaScript Jade also supports a subset of - constructs that allow you to create more designer-friendly templates, - one of these constructs is `each`, taking the form: - - each VAL[, KEY] in OBJ - -An example iterating over an array: - - - var items = ["one", "two", "three"] - each item in items - li= item - -outputs: - -
  • one
  • -
  • two
  • -
  • three
  • - -iterating an array with index: - - items = ["one", "two", "three"] - each item, i in items - li #{item}: #{i} - -outputs: - -
  • one: 0
  • -
  • two: 1
  • -
  • three: 2
  • - -iterating an object's keys and values: - - obj = { foo: 'bar' } - each val, key in obj - li #{key}: #{val} - -would output `
  • foo: bar
  • ` - -Internally Jade converts these statements to regular -JavaScript loops such as `users.forEach(function(user){`, -so lexical scope and nesting applies as it would with regular -JavaScript: - - each user in users - each role in user.roles - li= role - - You may also use `for` if you prefer: - - for user in users - for role in user.roles - li= role - -## Conditionals - - Jade conditionals are equivalent to those using the code (`-`) prefix, - however allow you to ditch parenthesis to become more designer friendly, - however keep in mind the expression given is _regular_ JavaScript: - - for user in users - if user.role == 'admin' - p #{user.name} is an admin - else - p= user.name - - is equivalent to the following using vanilla JavaScript literals: - - for user in users - - if (user.role == 'admin') - p #{user.name} is an admin - - else - p= user.name - - Jade also provides have `unless` which is equivalent to `if (!(expr))`: - - for user in users - unless user.isAnonymous - p - | Click to view - a(href='/users/' + user.id)= user.name - -## Template inheritance - - Jade supports template inheritance via the `block` and `extends` keywords. A block is simply a "block" of Jade that may be replaced within a child template, this process is recursive. To activate template inheritance in Express 2.x you must add: `app.set('view options', { layout: false });`. - - Jade blocks can provide default content if desired, however optional as shown below by `block scripts`, `block content`, and `block foot`. - -``` -html - head - h1 My Site - #{title} - block scripts - script(src='/jquery.js') - body - block content - block foot - #footer - p some footer content -``` - - Now to extend the layout, simply create a new file and use the `extends` directive as shown below, giving the path (with or without the .jade extension). You may now define one or more blocks that will override the parent block content, note that here the `foot` block is _not_ redefined and will output "some footer content". - -``` -extends layout - -block scripts - script(src='/jquery.js') - script(src='/pets.js') - -block content - h1= title - each pet in pets - include pet -``` - - It's also possible to override a block to provide additional blocks, as shown in the following example where `content` now exposes a `sidebar` and `primary` block for overriding, or the child template could override `content` all together. - -``` -extends regular-layout - -block content - .sidebar - block sidebar - p nothing - .primary - block primary - p nothing -``` - -## Block append / prepend - - Jade allows you to _replace_ (default), _prepend_, or _append_ blocks. Suppose for example you have default scripts in a "head" block that you wish to utilize on _every_ page, you might do this: - -``` -html - head - block head - script(src='/vendor/jquery.js') - script(src='/vendor/caustic.js') - body - block content -``` - - Now suppose you have a page of your application for a JavaScript game, you want some game related scripts as well as these defaults, you can simply `append` the block: - -``` -include layout - -block append head - script(src='/vendor/three.js') - script(src='/game.js') -``` - - When using `block append` or `block prepend` the `block` is optional: - -``` -include layout - -append head - script(src='/vendor/three.js') - script(src='/game.js') -``` - -## Includes - - Includes allow you to statically include chunks of Jade, - or other content like css, or html which lives in separate files. The classical example is including a header and footer. Suppose we have the following directory structure: - - ./layout.jade - ./includes/ - ./head.jade - ./tail.jade - -and the following _layout.jade_: - - html - include includes/head - body - h1 My Site - p Welcome to my super amazing site. - include includes/foot - -both includes _includes/head_ and _includes/foot_ are -read relative to the `filename` option given to _layout.jade_, -which should be an absolute path to this file, however Express does this for you. Include then parses these files, and injects the AST produced to render what you would expect: - -```html - - - My Site - - - -

    My Site

    -

    Welcome to my super lame site.

    - - - -``` - - As mentioned `include` can be used to include other content - such as html or css. By providing an extension Jade will not - assume that the file is Jade source and will include it as - a literal: - -``` -html - body - include content.html -``` - - Include directives may also accept a block, in which case the - the given block will be appended to the _last_ block defined - in the file. For example if `head.jade` contains: - -``` -head - script(src='/jquery.js') -``` - - We may append values by providing a block to `include head` - as shown below, adding the two scripts. - -``` -html - include head - script(src='/foo.js') - script(src='/bar.js') - body - h1 test -``` - - You may also `yield` within an included template, allowing you to explicitly mark where the block given to `include` will be placed. Suppose for example you wish to prepend scripts rather than append, you might do the following: - -``` -head - yield - script(src='/jquery.js') - script(src='/jquery.ui.js') -``` - - Since included Jade is parsed and literally merges the AST, lexically scoped variables function as if the included Jade was written right in the same file. This means `include` may be used as sort of partial, for example support we have `user.jade` which utilizes a `user` variable. - -``` -h1= user.name -p= user.occupation -``` - -We could then simply `include user` while iterating users, and since the `user` variable is already defined within the loop the included template will have access to it. - -``` -users = [{ name: 'Tobi', occupation: 'Ferret' }] - -each user in users - .user - include user -``` - -yielding: - -```html -
    -

    Tobi

    -

    Ferret

    -
    -``` - -If we wanted to expose a different variable name as `user` since `user.jade` references that name, we could simply define a new variable as shown here with `user = person`: - -``` -each person in users - .user - user = person - include user -``` - -## Mixins - - Mixins are converted to regular JavaScript functions in - the compiled template that Jade constructs. Mixins may - take arguments, though not required: - - mixin list - ul - li foo - li bar - li baz - - Utilizing a mixin without args looks similar, just without a block: - - h2 Groceries - mixin list - - Mixins may take one or more arguments as well, the arguments - are regular javascripts expressions, so for example the following: - - mixin pets(pets) - ul.pets - - each pet in pets - li= pet - - mixin profile(user) - .user - h2= user.name - mixin pets(user.pets) - - Would yield something similar to the following html: - -```html -
    -

    tj

    -
      -
    • tobi
    • -
    • loki
    • -
    • jane
    • -
    • manny
    • -
    -
    -``` - -## Generated Output - - Suppose we have the following Jade: - -``` -- var title = 'yay' -h1.title #{title} -p Just an example -``` - - When the `compileDebug` option is not explicitly `false`, Jade - will compile the function instrumented with `__.lineno = n;`, which - in the event of an exception is passed to `rethrow()` which constructs - a useful message relative to the initial Jade input. - -```js -function anonymous(locals) { - var __ = { lineno: 1, input: "- var title = 'yay'\nh1.title #{title}\np Just an example", filename: "testing/test.js" }; - var rethrow = jade.rethrow; - try { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - __.lineno = 1; - var title = 'yay' - __.lineno = 2; - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - __.lineno = 3; - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); - } catch (err) { - rethrow(err, __.input, __.filename, __.lineno); - } -} -``` - -When the `compileDebug` option _is_ explicitly `false`, this instrumentation -is stripped, which is very helpful for light-weight client-side templates. Combining Jade's options with the `./runtime.js` file in this repo allows you -to toString() compiled templates and avoid running the entire Jade library on -the client, increasing performance, and decreasing the amount of JavaScript -required. - -```js -function anonymous(locals) { - var attrs = jade.attrs, escape = jade.escape; - var buf = []; - with (locals || {}) { - var interp; - var title = 'yay' - buf.push(''); - buf.push('' + escape((interp = title) == null ? '' : interp) + ''); - buf.push(''); - buf.push('

    '); - buf.push('Just an example'); - buf.push('

    '); - } - return buf.join(""); -} -``` - -## Example Makefile - - Below is an example Makefile used to compile _pages/*.jade_ - into _pages/*.html_ files by simply executing `make`. - -```make -JADE = $(shell find pages/*.jade) -HTML = $(JADE:.jade=.html) - -all: $(HTML) - -%.html: %.jade - jade < $< --path $< > $@ - -clean: - rm -f $(HTML) - -.PHONY: clean -``` - -this can be combined with the `watch(1)` command to produce -a watcher-like behaviour: - - $ watch make - -## jade(1) - -``` - -Usage: jade [options] [dir|file ...] - -Options: - - -h, --help output usage information - -v, --version output the version number - -o, --obj javascript options object - -O, --out output the compiled html to - -p, --path filename used to resolve includes over stdio - -Examples: - - # translate jade the templates dir - $ jade templates - - # create {foo,bar}.html - $ jade {foo,bar}.jade - - # jade over stdio - $ jade < my.jade > my.html - - # jade over stdio specifying filename to resolve include directives - $ jade < my.jade -p my.jade > my.html - - # jade over stdio - $ echo "h1 Jade!" | jade - - # foo, bar dirs rendering to /tmp - $ jade foo bar --out /tmp - -``` - -## License - -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jade/bin/jade b/node_modules/jade/bin/jade deleted file mode 100755 index fd4122c..0000000 --- a/node_modules/jade/bin/jade +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var fs = require('fs') - , program = require('commander') - , path = require('path') - , basename = path.basename - , dirname = path.dirname - , resolve = path.resolve - , join = path.join - , mkdirp = require('mkdirp') - , jade = require('../'); - -// jade options - -var options = {}; - -// options - -program - .version(jade.version) - .usage('[options] [dir|file ...]') - .option('-o, --obj ', 'javascript options object') - .option('-O, --out ', 'output the compiled html to ') - .option('-p, --path ', 'filename used to resolve includes') - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' # translate jade the templates dir'); - console.log(' $ jade templates'); - console.log(''); - console.log(' # create {foo,bar}.html'); - console.log(' $ jade {foo,bar}.jade'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ jade < my.jade > my.html'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ echo "h1 Jade!" | jade'); - console.log(''); - console.log(' # foo, bar dirs rendering to /tmp'); - console.log(' $ jade foo bar --out /tmp '); - console.log(''); -}); - -program.parse(process.argv); - -// options given, parse them - -if (program.obj) options = eval('(' + program.obj + ')'); - -// filename - -if (program.path) options.filename = program.path; - -// left-over args are file paths - -var files = program.args; - -// compile files - -if (files.length) { - console.log(); - files.forEach(renderFile); - process.on('exit', console.log); -// stdio -} else { - stdin(); -} - -/** - * Compile from stdin. - */ - -function stdin() { - var buf = ''; - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(chunk){ buf += chunk; }); - process.stdin.on('end', function(){ - var fn = jade.compile(buf, options); - process.stdout.write(fn(options)); - }).resume(); -} - -/** - * Process the given path, compiling the jade files found. - * Always walk the subdirectories. - */ - -function renderFile(path) { - var re = /\.jade$/; - fs.lstat(path, function(err, stat) { - if (err) throw err; - // Found jade file - if (stat.isFile() && re.test(path)) { - fs.readFile(path, 'utf8', function(err, str){ - if (err) throw err; - options.filename = path; - var fn = jade.compile(str, options); - path = path.replace(re, '.html'); - if (program.out) path = join(program.out, basename(path)); - var dir = resolve(dirname(path)); - mkdirp(dir, 0755, function(err){ - if (err) throw err; - fs.writeFile(path, fn(options), function(err){ - if (err) throw err; - console.log(' \033[90mrendered \033[36m%s\033[0m', path); - }); - }); - }); - // Found directory - } else if (stat.isDirectory()) { - fs.readdir(path, function(err, files) { - if (err) throw err; - files.map(function(filename) { - return path + '/' + filename; - }).forEach(renderFile); - }); - } - }); -} diff --git a/node_modules/jade/index.js b/node_modules/jade/index.js deleted file mode 100644 index 857e431..0000000 --- a/node_modules/jade/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/jade'); \ No newline at end of file diff --git a/node_modules/jade/jade.js b/node_modules/jade/jade.js deleted file mode 100644 index a8bf6cb..0000000 --- a/node_modules/jade/jade.js +++ /dev/null @@ -1,3135 +0,0 @@ -(function() { - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p[0]) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("compiler.js", function(module, exports, require){ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , inlineTags = require('./inline-tags') - , utils = require('./utils'); - - - if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } - } - - if (!String.prototype.trimLeft) { - String.prototype.trimLeft = function(){ - return this.replace(/^\s+/, ''); - } - } - - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - this.lastBufferedIdx = -1 - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - var doctype = doctypes[(name || 'default').toLowerCase()]; - doctype = doctype || ''; - this.doctype = doctype; - this.terse = '5' == name || 'html' == name; - this.xml = 0 == this.doctype.indexOf('" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || ''; - - if (mixin.block) { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.visit(mixin.block); - this.buf.push('}'); - } else { - this.buf.push(name + '(' + args + ');'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (this.pp && inlineTags.indexOf(name) == -1) { - this.buffer('\\n' + Array(this.indents).join(' ')); - } - - if (~selfClosing.indexOf(name) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - if (tag.text) this.buffer(utils.text(tag.text.nodes[0].trimLeft())); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (this.pp && !~inlineTags.indexOf(name) && !tag.textOnly) { - this.buffer('\\n' + Array(this.indents).join(' ')); - } - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) { - if (filter.isASTFilter) { - throw new Error('unknown ast filter "' + filter.name + ':"'); - } else { - throw new Error('unknown filter ":' + filter.name + '"'); - } - } - if (filter.isASTFilter) { - this.buf.push(fn(filter.block, this, filter.attrs)); - } else { - var text = filter.block.nodes.join(''); - this.buffer(utils.text(fn(text, filter.attrs))); - } - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.nodes.join('')); - if (this.escape) text = escape(text); - this.buffer(text); - this.buffer('\\n'); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.buffer('\\n' + Array(this.indents + 1).join(' ')); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + '(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push('' - + ' }\n' - + ' } else {\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push(' }\n'); - - this.buf.push(' }\n }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var buf = [] - , classes = []; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push("class: " + classes); - } - - buf = buf.join(', ').replace('class:', '"class":'); - - this.buf.push("buf.push(attrs({ " + buf + " }));"); - } -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} - -}); // module: compiler.js - -require.register("doctypes.js", function(module, exports, require){ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'xml': '' - , 'default': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; -}); // module: doctypes.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - - /** - * Wrap text with CDATA block. - */ - - cdata: function(str){ - return ''; - }, - - /** - * Transform sass to css, wrapped in style tags. - */ - - sass: function(str){ - str = str.replace(/\\n/g, '\n'); - var sass = require('sass').render(str).replace(/\n/g, '\\n'); - return ''; - }, - - /** - * Transform stylus to css, wrapped in style tags. - */ - - stylus: function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; - }, - - /** - * Transform less to css, wrapped in style tags. - */ - - less: function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; - }, - - /** - * Transform markdown to html. - */ - - markdown: function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - throw new Error('Cannot find markdown library, install markdown or discount'); - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); - }, - - /** - * Transform coffeescript to javascript. - */ - - coffeescript: function(str){ - str = str.replace(/\\n/g, '\n'); - var js = require('coffee-script').compile(str).replace(/\n/g, '\\n'); - return ''; - } -}; - -}); // module: filters.js - -require.register("inline-tags.js", function(module, exports, require){ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; -}); // module: inline-tags.js - -require.register("jade.js", function(module, exports, require){ - -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') - -/** - * Library version. - */ - -exports.version = '0.19.0'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(String(str), options || {}) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(String(str), options || {}); - } - - if (client) { - fn = 'var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; - -}); // module: jade.js - -require.register("lexer.js", function(module, exports, require){ - -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str[i]) { - ++nstart; - } else if (end == str[i]) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - extends: function() { - return this.scan(/^extends +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - case: function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - default: function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - while: function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags[0] === '='; - tok.buffer = flags[0] === '=' || flags[1] === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input[0]) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , key = '' - , val = '' - , quote - , c; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/#\{([^}]+)\}/g, function(_, expr){ - return quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - } - - for (var i = 0; i < len; ++i) { - parse(str[i]); - } - - parse(','); - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.case() - || this.when() - || this.default() - || this.extends() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.conditional() - || this.each() - || this.while() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; - -}); // module: lexer.js - -require.register("nodes/block-comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype = new Node; -BlockComment.prototype.constructor = BlockComment; - -}); // module: nodes/block-comment.js - -require.register("nodes/block.js", function(module, exports, require){ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype = new Node; -Block.prototype.constructor = Block; - - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - } - - return ret; -}; - - -}); // module: nodes/block.js - -require.register("nodes/case.js", function(module, exports, require){ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype = new Node; -Case.prototype.constructor = Case; - - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype = new Node; -When.prototype.constructor = When; - - - -}); // module: nodes/case.js - -require.register("nodes/code.js", function(module, exports, require){ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype = new Node; -Code.prototype.constructor = Code; - -}); // module: nodes/code.js - -require.register("nodes/comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype = new Node; -Comment.prototype.constructor = Comment; - -}); // module: nodes/comment.js - -require.register("nodes/doctype.js", function(module, exports, require){ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype = new Node; -Doctype.prototype.constructor = Doctype; - -}); // module: nodes/doctype.js - -require.register("nodes/each.js", function(module, exports, require){ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype = new Node; -Each.prototype.constructor = Each; - -}); // module: nodes/each.js - -require.register("nodes/filter.js", function(module, exports, require){ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; - this.isASTFilter = block instanceof Block; -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype = new Node; -Filter.prototype.constructor = Filter; - -}); // module: nodes/filter.js - -require.register("nodes/index.js", function(module, exports, require){ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); - -}); // module: nodes/index.js - -require.register("nodes/literal.js", function(module, exports, require){ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype = new Node; -Literal.prototype.constructor = Literal; - - -}); // module: nodes/literal.js - -require.register("nodes/mixin.js", function(module, exports, require){ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block){ - this.name = name; - this.args = args; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Mixin.prototype = new Node; -Mixin.prototype.constructor = Mixin; - - - -}); // module: nodes/mixin.js - -require.register("nodes/node.js", function(module, exports, require){ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; -}); // module: nodes/node.js - -require.register("nodes/tag.js", function(module, exports, require){ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Node`. - */ - -Tag.prototype = new Node; -Tag.prototype.constructor = Tag; - - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @return {Tag} for chaining - * @api public - */ - -Tag.prototype.setAttribute = function(name, val){ - this.attrs.push({ name: name, val: val }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Tag.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Tag.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; - -}); // module: nodes/tag.js - -require.register("nodes/text.js", function(module, exports, require){ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.nodes = []; - if ('string' == typeof line) this.push(line); -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype = new Node; -Text.prototype.constructor = Text; - - -/** - * Push the given `node.` - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Text.prototype.push = function(node){ - return this.nodes.push(node); -}; - -}); // module: nodes/text.js - -require.register("parser.js", function(module, exports, require){ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes'); - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text') - , node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val - , node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code') - , node = new nodes.Code(tok.val, tok.buffer, tok.escape) - , block - , i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment') - , node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype') - , node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var block - , tok = this.expect('filter') - , attrs = this.accept('attrs'); - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * tag ':' attrs? block - */ - - parseASTFilter: function(){ - var block - , tok = this.expect('tag') - , attrs = this.accept('attrs'); - - this.expect(':'); - block = this.block(); - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each') - , node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim() - , dir = dirname(this.filename); - - var path = join(dir, path + '.jade') - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block') - , mode = block.mode - , name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - var path = this.expect('include').val.trim() - , dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8'); - return new nodes.Literal(str); - } - - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin') - , name = tok.val - , args = tok.args; - var block = 'indent' == this.peek().type - ? this.block() - : null; - return new nodes.Mixin(name, args, block); - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var text = new nodes.Text; - text.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - text.push('\\n'); - this.advance(); - break; - case 'indent': - text.push('\\n'); - this.parseTextBlock().nodes.forEach(function(node){ - text.push(node); - }); - text.push('\\n'); - break; - default: - text.push(indent + this.advance().val); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return text; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - if (':' == this.lookahead(i).type) { - if ('indent' == this.lookahead(++i).type) { - return this.parseASTFilter(); - } - } - - var name = this.advance().val - , tag = new nodes.Tag(name) - , dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var obj = this.advance().attrs - , names = Object.keys(obj); - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.text = this.parseText(); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseTag()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; - -}); // module: parser.js - -require.register("runtime.js", function(module, exports, require){ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj){ - var buf = [] - , terse = obj.terse; - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else { - buf.push(key + '="' + exports.escape(val) + '"'); - } - } - } - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - -}); // module: runtime.js - -require.register("self-closing.js", function(module, exports, require){ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; -}); // module: self-closing.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - return escape - ? str - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code.replace(/\\'/g, "'") - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; -}); // module: utils.js - -window.jade = require("jade"); -})(); diff --git a/node_modules/jade/jade.min.js b/node_modules/jade/jade.min.js deleted file mode 100644 index 067b8b5..0000000 --- a/node_modules/jade/jade.min.js +++ /dev/null @@ -1,2 +0,0 @@ -(function(){function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');return mod.exports||(mod.exports={},mod.call(mod.exports,mod,mod.exports,require.relative(path))),mod.exports}require.modules={},require.resolve=function(path){var orig=path,reg=path+".js",index=path+"/index.js";return require.modules[reg]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p[0])return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i",this.doctype=doctype,this.terse="5"==name||"html"==name,this.xml=0==this.doctype.indexOf(""):this.buffer("/>")):(tag.attrs.length?(this.buffer("<"+name),tag.attrs.length&&this.visitAttributes(tag.attrs),this.buffer(">")):this.buffer("<"+name+">"),tag.code&&this.visitCode(tag.code),tag.text&&this.buffer(utils.text(tag.text.nodes[0].trimLeft())),this.escape="pre"==tag.name,this.visit(tag.block),this.pp&&!~inlineTags.indexOf(name)&&!tag.textOnly&&this.buffer("\\n"+Array(this.indents).join(" ")),this.buffer("")),this.indents--},visitFilter:function(filter){var fn=filters[filter.name];if(!fn)throw filter.isASTFilter?new Error('unknown ast filter "'+filter.name+':"'):new Error('unknown filter ":'+filter.name+'"');if(filter.isASTFilter)this.buf.push(fn(filter.block,this,filter.attrs));else{var text=filter.block.nodes.join("");this.buffer(utils.text(fn(text,filter.attrs)))}},visitText:function(text){text=utils.text(text.nodes.join("")),this.escape&&(text=escape(text)),this.buffer(text),this.buffer("\\n")},visitComment:function(comment){if(!comment.buffer)return;this.pp&&this.buffer("\\n"+Array(this.indents+1).join(" ")),this.buffer("")},visitBlockComment:function(comment){if(!comment.buffer)return;0==comment.val.trim().indexOf("if")?(this.buffer("")):(this.buffer(""))},visitCode:function(code){if(code.buffer){var val=code.val.trimLeft();this.buf.push("var __val__ = "+val),val='null == __val__ ? "" : __val__',code.escape&&(val="escape("+val+")"),this.buf.push("buf.push("+val+");")}else this.buf.push(code.val);code.block&&(code.buffer||this.buf.push("{"),this.visit(code.block),code.buffer||this.buf.push("}"))},visitEach:function(each){this.buf.push("// iterate "+each.obj+"\n"+"(function(){\n"+" if ('number' == typeof "+each.obj+".length) {\n"+" for (var "+each.key+" = 0, $$l = "+each.obj+".length; "+each.key+" < $$l; "+each.key+"++) {\n"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n } else {\n for (var "+each.key+" in "+each.obj+") {\n"+" if ("+each.obj+".hasOwnProperty("+each.key+")){"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n"),this.buf.push(" }\n }\n}).call(this);\n")},visitAttributes:function(attrs){var buf=[],classes=[];this.terse&&buf.push("terse: true"),attrs.forEach(function(attr){if(attr.name=="class")classes.push("("+attr.val+")");else{var pair="'"+attr.name+"':("+attr.val+")";buf.push(pair)}}),classes.length&&(classes=classes.join(" + ' ' + "),buf.push("class: "+classes)),buf=buf.join(", ").replace("class:",'"class":'),this.buf.push("buf.push(attrs({ "+buf+" }));")}};function escape(html){return String(html).replace(/&(?!\w+;)/g,"&").replace(//g,">").replace(/"/g,""")}}),require.register("doctypes.js",function(module,exports,require){module.exports={5:"",xml:'',"default":'',transitional:'',strict:'',frameset:'',1.1:'',basic:'',mobile:''}}),require.register("filters.js",function(module,exports,require){module.exports={cdata:function(str){return""},sass:function(str){str=str.replace(/\\n/g,"\n");var sass=require("sass").render(str).replace(/\n/g,"\\n");return'"},stylus:function(str,options){var ret;str=str.replace(/\\n/g,"\n");var stylus=require("stylus");return stylus(str,options).render(function(err,css){if(err)throw err;ret=css.replace(/\n/g,"\\n")}),'"},less:function(str){var ret;return str=str.replace(/\\n/g,"\n"),require("less").render(str,function(err,css){if(err)throw err;ret='"}),ret},markdown:function(str){var md;try{md=require("markdown")}catch(err){try{md=require("discount")}catch(err){try{md=require("markdown-js")}catch(err){throw new Error("Cannot find markdown library, install markdown or discount")}}}return str=str.replace(/\\n/g,"\n"),md.parse(str).replace(/\n/g,"\\n").replace(/'/g,"'")},coffeescript:function(str){str=str.replace(/\\n/g,"\n");var js=require("coffee-script").compile(str).replace(/\n/g,"\\n");return'"}}}),require.register("inline-tags.js",function(module,exports,require){module.exports=["a","abbr","acronym","b","br","code","em","font","i","img","ins","kbd","map","samp","small","span","strong","sub","sup"]}),require.register("jade.js",function(module,exports,require){var Parser=require("./parser"),Lexer=require("./lexer"),Compiler=require("./compiler"),runtime=require("./runtime");exports.version="0.19.0",exports.selfClosing=require("./self-closing"),exports.doctypes=require("./doctypes"),exports.filters=require("./filters"),exports.utils=require("./utils"),exports.Compiler=Compiler,exports.Parser=Parser,exports.Lexer=Lexer,exports.nodes=require("./nodes"),exports.runtime=runtime,exports.cache={};function parse(str,options){try{var parser=new Parser(str,options.filename,options),compiler=new(options.compiler||Compiler)(parser.parse(),options),js=compiler.compile();return options.debug&&console.error("\nCompiled Function:\n\n%s",js.replace(/^/gm," ")),"var buf = [];\n"+(options.self?"var self = locals || {};\n"+js:"with (locals || {}) {\n"+js+"\n}\n")+'return buf.join("");'}catch(err){parser=parser.context(),runtime.rethrow(err,parser.filename,parser.lexer.lineno)}}exports.compile=function(str,options){var options=options||{},client=options.client,filename=options.filename?JSON.stringify(options.filename):"undefined",fn;return options.compileDebug!==!1?fn=["var __jade = [{ lineno: 1, filename: "+filename+" }];","try {",parse(String(str),options||{}),"} catch (err) {"," rethrow(err, __jade[0].filename, __jade[0].lineno);","}"].join("\n"):fn=parse(String(str),options||{}),client&&(fn="var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\n"+fn),fn=new Function("locals, attrs, escape, rethrow",fn),client?fn:function(locals){return fn(locals,runtime.attrs,runtime.escape,runtime.rethrow)}},exports.render=function(str,options,fn){"function"==typeof options&&(fn=options,options={});if(options.cache&&!options.filename)return fn(new Error('the "filename" option is required for caching'));try{var path=options.filename,tmpl=options.cache?exports.cache[path]||(exports.cache[path]=exports.compile(str,options)):exports.compile(str,options);fn(null,tmpl(options))}catch(err){fn(err)}},exports.renderFile=function(path,options,fn){var key=path+":string";"function"==typeof options&&(fn=options,options={});try{options.filename=path;var str=options.cache?exports.cache[key]||(exports.cache[key]=fs.readFileSync(path,"utf8")):fs.readFileSync(path,"utf8");exports.render(str,options,fn)}catch(err){fn(err)}},exports.__express=exports.renderFile}),require.register("lexer.js",function(module,exports,require){var Lexer=module.exports=function(str,options){options=options||{},this.input=str.replace(/\r\n|\r/g,"\n"),this.colons=options.colons,this.deferredTokens=[],this.lastIndents=0,this.lineno=1,this.stash=[],this.indentStack=[],this.indentRe=null,this.pipeless=!1};Lexer.prototype={tok:function(type,val){return{type:type,line:this.lineno,val:val}},consume:function(len){this.input=this.input.substr(len)},scan:function(regexp,type){var captures;if(captures=regexp.exec(this.input))return this.consume(captures[0].length),this.tok(type,captures[1])},defer:function(tok){this.deferredTokens.push(tok)},lookahead:function(n){var fetch=n-this.stash.length;while(fetch-->0)this.stash.push(this.next());return this.stash[--n]},indexOfDelimiters:function(start,end){var str=this.input,nstart=0,nend=0,pos=0;for(var i=0,len=str.length;iindents)this.stash.push(this.tok("outdent")),this.indentStack.shift();tok=this.stash.pop()}else indents&&indents!=this.indentStack[0]?(this.indentStack.unshift(indents),tok=this.tok("indent",indents)):tok=this.tok("newline");return tok}},pipelessText:function(){if(this.pipeless){if("\n"==this.input[0])return;var i=this.input.indexOf("\n");-1==i&&(i=this.input.length);var str=this.input.substr(0,i);return this.consume(str.length),this.tok("text",str)}},colon:function(){return this.scan(/^: */,":")},advance:function(){return this.stashed()||this.next()},next:function(){return this.deferred()||this.eos()||this.pipelessText()||this.yield()||this.doctype()||this.case()||this.when()||this.default()||this.extends()||this.append()||this.prepend()||this.block()||this.include()||this.mixin()||this.conditional()||this.each()||this.while()||this.assignment()||this.tag()||this.filter()||this.code()||this.id()||this.className()||this.attrs()||this.indent()||this.comment()||this.colon()||this.text()}}}),require.register("nodes/block-comment.js",function(module,exports,require){var Node=require("./node"),BlockComment=module.exports=function(val,block,buffer){this.block=block,this.val=val,this.buffer=buffer};BlockComment.prototype=new Node,BlockComment.prototype.constructor=BlockComment}),require.register("nodes/block.js",function(module,exports,require){var Node=require("./node"),Block=module.exports=function(node){this.nodes=[],node&&this.push(node)};Block.prototype=new Node,Block.prototype.constructor=Block,Block.prototype.replace=function(other){other.nodes=this.nodes},Block.prototype.push=function(node){return this.nodes.push(node)},Block.prototype.isEmpty=function(){return 0==this.nodes.length},Block.prototype.unshift=function(node){return this.nodes.unshift(node)},Block.prototype.includeBlock=function(){var ret=this,node;for(var i=0,len=this.nodes.length;i/g,">").replace(/"/g,""")},exports.rethrow=function(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err}}),require.register("self-closing.js",function(module,exports,require){module.exports=["meta","img","link","input","area","base","col","br","hr"]}),require.register("utils.js",function(module,exports,require){var interpolate=exports.interpolate=function(str){return str.replace(/(\\)?([#!]){(.*?)}/g,function(str,escape,flag,code){return escape?str:"' + "+("!"==flag?"":"escape")+"((interp = "+code.replace(/\\'/g,"'")+") == null ? '' : interp) + '"})},escape=exports.escape=function(str){return str.replace(/'/g,"\\'")};exports.text=function(str){return interpolate(escape(str))}}),window.jade=require("jade")})(); \ No newline at end of file diff --git a/node_modules/jade/lib/compiler.js b/node_modules/jade/lib/compiler.js deleted file mode 100644 index 7ca543c..0000000 --- a/node_modules/jade/lib/compiler.js +++ /dev/null @@ -1,501 +0,0 @@ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , inlineTags = require('./inline-tags') - , utils = require('./utils'); - -// if browser -// -// if (!Object.keys) { -// Object.keys = function(obj){ -// var arr = []; -// for (var key in obj) { -// if (obj.hasOwnProperty(key)) { -// arr.push(key); -// } -// } -// return arr; -// } -// } -// -// if (!String.prototype.trimLeft) { -// String.prototype.trimLeft = function(){ -// return this.replace(/^\s+/, ''); -// } -// } -// -// end - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - this.lastBufferedIdx = -1 - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - var doctype = doctypes[(name || 'default').toLowerCase()]; - doctype = doctype || ''; - this.doctype = doctype; - this.terse = '5' == name || 'html' == name; - this.xml = 0 == this.doctype.indexOf('" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || ''; - - if (mixin.block) { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.visit(mixin.block); - this.buf.push('}'); - } else { - this.buf.push(name + '(' + args + ');'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (this.pp && inlineTags.indexOf(name) == -1) { - this.buffer('\\n' + Array(this.indents).join(' ')); - } - - if (~selfClosing.indexOf(name) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - if (tag.text) this.buffer(utils.text(tag.text.nodes[0].trimLeft())); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (this.pp && !~inlineTags.indexOf(name) && !tag.textOnly) { - this.buffer('\\n' + Array(this.indents).join(' ')); - } - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) { - if (filter.isASTFilter) { - throw new Error('unknown ast filter "' + filter.name + ':"'); - } else { - throw new Error('unknown filter ":' + filter.name + '"'); - } - } - if (filter.isASTFilter) { - this.buf.push(fn(filter.block, this, filter.attrs)); - } else { - var text = filter.block.nodes.join(''); - this.buffer(utils.text(fn(text, filter.attrs))); - } - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.nodes.join('')); - if (this.escape) text = escape(text); - this.buffer(text); - this.buffer('\\n'); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.buffer('\\n' + Array(this.indents + 1).join(' ')); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + '(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push('' - + ' }\n' - + ' } else {\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - // if browser - // + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - // end - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - // if browser - // this.buf.push(' }\n'); - // end - - this.buf.push(' }\n }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var buf = [] - , classes = []; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push("class: " + classes); - } - - buf = buf.join(', ').replace('class:', '"class":'); - - this.buf.push("buf.push(attrs({ " + buf + " }));"); - } -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} diff --git a/node_modules/jade/lib/doctypes.js b/node_modules/jade/lib/doctypes.js deleted file mode 100644 index feeb560..0000000 --- a/node_modules/jade/lib/doctypes.js +++ /dev/null @@ -1,18 +0,0 @@ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'xml': '' - , 'default': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; \ No newline at end of file diff --git a/node_modules/jade/lib/filters.js b/node_modules/jade/lib/filters.js deleted file mode 100644 index dd1b99d..0000000 --- a/node_modules/jade/lib/filters.js +++ /dev/null @@ -1,92 +0,0 @@ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - - /** - * Wrap text with CDATA block. - */ - - cdata: function(str){ - return ''; - }, - - /** - * Transform sass to css, wrapped in style tags. - */ - - sass: function(str){ - str = str.replace(/\\n/g, '\n'); - var sass = require('sass').render(str).replace(/\n/g, '\\n'); - return ''; - }, - - /** - * Transform stylus to css, wrapped in style tags. - */ - - stylus: function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; - }, - - /** - * Transform less to css, wrapped in style tags. - */ - - less: function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; - }, - - /** - * Transform markdown to html. - */ - - markdown: function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - throw new Error('Cannot find markdown library, install markdown or discount'); - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); - }, - - /** - * Transform coffeescript to javascript. - */ - - coffeescript: function(str){ - str = str.replace(/\\n/g, '\n'); - var js = require('coffee-script').compile(str).replace(/\n/g, '\\n'); - return ''; - } -}; diff --git a/node_modules/jade/lib/index.js b/node_modules/jade/lib/index.js deleted file mode 120000 index 6a783c2..0000000 --- a/node_modules/jade/lib/index.js +++ /dev/null @@ -1 +0,0 @@ -jade.js \ No newline at end of file diff --git a/node_modules/jade/lib/inline-tags.js b/node_modules/jade/lib/inline-tags.js deleted file mode 100644 index 491de0b..0000000 --- a/node_modules/jade/lib/inline-tags.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; \ No newline at end of file diff --git a/node_modules/jade/lib/jade.js b/node_modules/jade/lib/jade.js deleted file mode 100644 index 45a568a..0000000 --- a/node_modules/jade/lib/jade.js +++ /dev/null @@ -1,238 +0,0 @@ - -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') -// if node - , fs = require('fs'); -// end - -/** - * Library version. - */ - -exports.version = '0.20.0'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(String(str), options || {}) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(String(str), options || {}); - } - - if (client) { - fn = 'var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; diff --git a/node_modules/jade/lib/lexer.js b/node_modules/jade/lib/lexer.js deleted file mode 100644 index aac94f5..0000000 --- a/node_modules/jade/lib/lexer.js +++ /dev/null @@ -1,707 +0,0 @@ - -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str[i]) { - ++nstart; - } else if (end == str[i]) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - extends: function() { - return this.scan(/^extends +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - case: function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - default: function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - while: function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags[0] === '='; - tok.buffer = flags[0] === '=' || flags[1] === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input[0]) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , key = '' - , val = '' - , quote - , c; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/#\{([^}]+)\}/g, function(_, expr){ - return quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - } - - for (var i = 0; i < len; ++i) { - parse(str[i]); - } - - parse(','); - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.case() - || this.when() - || this.default() - || this.extends() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.conditional() - || this.each() - || this.while() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; diff --git a/node_modules/jade/lib/nodes/block-comment.js b/node_modules/jade/lib/nodes/block-comment.js deleted file mode 100644 index 4f41e4a..0000000 --- a/node_modules/jade/lib/nodes/block-comment.js +++ /dev/null @@ -1,33 +0,0 @@ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/block.js b/node_modules/jade/lib/nodes/block.js deleted file mode 100644 index d3f2343..0000000 --- a/node_modules/jade/lib/nodes/block.js +++ /dev/null @@ -1,99 +0,0 @@ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype.__proto__ = Node.prototype; - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - } - - return ret; -}; - diff --git a/node_modules/jade/lib/nodes/case.js b/node_modules/jade/lib/nodes/case.js deleted file mode 100644 index 08ff033..0000000 --- a/node_modules/jade/lib/nodes/case.js +++ /dev/null @@ -1,43 +0,0 @@ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype.__proto__ = Node.prototype; - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype.__proto__ = Node.prototype; - diff --git a/node_modules/jade/lib/nodes/code.js b/node_modules/jade/lib/nodes/code.js deleted file mode 100644 index babc675..0000000 --- a/node_modules/jade/lib/nodes/code.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/comment.js b/node_modules/jade/lib/nodes/comment.js deleted file mode 100644 index 2e1469e..0000000 --- a/node_modules/jade/lib/nodes/comment.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/doctype.js b/node_modules/jade/lib/nodes/doctype.js deleted file mode 100644 index b8f33e5..0000000 --- a/node_modules/jade/lib/nodes/doctype.js +++ /dev/null @@ -1,29 +0,0 @@ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/each.js b/node_modules/jade/lib/nodes/each.js deleted file mode 100644 index f54101f..0000000 --- a/node_modules/jade/lib/nodes/each.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/filter.js b/node_modules/jade/lib/nodes/filter.js deleted file mode 100644 index 5a0a237..0000000 --- a/node_modules/jade/lib/nodes/filter.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; - this.isASTFilter = block instanceof Block; -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/index.js b/node_modules/jade/lib/nodes/index.js deleted file mode 100644 index 386ad2f..0000000 --- a/node_modules/jade/lib/nodes/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); diff --git a/node_modules/jade/lib/nodes/literal.js b/node_modules/jade/lib/nodes/literal.js deleted file mode 100644 index 3ddab65..0000000 --- a/node_modules/jade/lib/nodes/literal.js +++ /dev/null @@ -1,31 +0,0 @@ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype.__proto__ = Node.prototype; diff --git a/node_modules/jade/lib/nodes/mixin.js b/node_modules/jade/lib/nodes/mixin.js deleted file mode 100644 index f007c84..0000000 --- a/node_modules/jade/lib/nodes/mixin.js +++ /dev/null @@ -1,34 +0,0 @@ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block){ - this.name = name; - this.args = args; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Mixin.prototype.__proto__ = Node.prototype; - diff --git a/node_modules/jade/lib/nodes/node.js b/node_modules/jade/lib/nodes/node.js deleted file mode 100644 index 0669e67..0000000 --- a/node_modules/jade/lib/nodes/node.js +++ /dev/null @@ -1,14 +0,0 @@ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; \ No newline at end of file diff --git a/node_modules/jade/lib/nodes/tag.js b/node_modules/jade/lib/nodes/tag.js deleted file mode 100644 index 35993c9..0000000 --- a/node_modules/jade/lib/nodes/tag.js +++ /dev/null @@ -1,80 +0,0 @@ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Node`. - */ - -Tag.prototype.__proto__ = Node.prototype; - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @return {Tag} for chaining - * @api public - */ - -Tag.prototype.setAttribute = function(name, val){ - this.attrs.push({ name: name, val: val }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Tag.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Tag.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; diff --git a/node_modules/jade/lib/nodes/text.js b/node_modules/jade/lib/nodes/text.js deleted file mode 100644 index 3baff4b..0000000 --- a/node_modules/jade/lib/nodes/text.js +++ /dev/null @@ -1,42 +0,0 @@ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.nodes = []; - if ('string' == typeof line) this.push(line); -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype.__proto__ = Node.prototype; - -/** - * Push the given `node.` - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Text.prototype.push = function(node){ - return this.nodes.push(node); -}; diff --git a/node_modules/jade/lib/parser.js b/node_modules/jade/lib/parser.js deleted file mode 100644 index 3dcfb57..0000000 --- a/node_modules/jade/lib/parser.js +++ /dev/null @@ -1,651 +0,0 @@ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes'); - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text') - , node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val - , node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code') - , node = new nodes.Code(tok.val, tok.buffer, tok.escape) - , block - , i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment') - , node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype') - , node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var block - , tok = this.expect('filter') - , attrs = this.accept('attrs'); - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * tag ':' attrs? block - */ - - parseASTFilter: function(){ - var block - , tok = this.expect('tag') - , attrs = this.accept('attrs'); - - this.expect(':'); - block = this.block(); - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each') - , node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim() - , dir = dirname(this.filename); - - var path = join(dir, path + '.jade') - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block') - , mode = block.mode - , name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - var path = this.expect('include').val.trim() - , dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8'); - return new nodes.Literal(str); - } - - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin') - , name = tok.val - , args = tok.args; - var block = 'indent' == this.peek().type - ? this.block() - : null; - return new nodes.Mixin(name, args, block); - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var text = new nodes.Text; - text.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - text.push('\\n'); - this.advance(); - break; - case 'indent': - text.push('\\n'); - this.parseTextBlock().nodes.forEach(function(node){ - text.push(node); - }); - text.push('\\n'); - break; - default: - text.push(indent + this.advance().val); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return text; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - if (':' == this.lookahead(i).type) { - if ('indent' == this.lookahead(++i).type) { - return this.parseASTFilter(); - } - } - - var name = this.advance().val - , tag = new nodes.Tag(name) - , dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var obj = this.advance().attrs - , names = Object.keys(obj); - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.text = this.parseText(); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseTag()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; diff --git a/node_modules/jade/lib/runtime.js b/node_modules/jade/lib/runtime.js deleted file mode 100644 index 7b357ca..0000000 --- a/node_modules/jade/lib/runtime.js +++ /dev/null @@ -1,118 +0,0 @@ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj){ - var buf = [] - , terse = obj.terse; - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else { - buf.push(key + '="' + exports.escape(val) + '"'); - } - } - } - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; diff --git a/node_modules/jade/lib/self-closing.js b/node_modules/jade/lib/self-closing.js deleted file mode 100644 index 293e7f8..0000000 --- a/node_modules/jade/lib/self-closing.js +++ /dev/null @@ -1,18 +0,0 @@ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; \ No newline at end of file diff --git a/node_modules/jade/lib/utils.js b/node_modules/jade/lib/utils.js deleted file mode 100644 index ff46d02..0000000 --- a/node_modules/jade/lib/utils.js +++ /dev/null @@ -1,49 +0,0 @@ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - return escape - ? str - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code.replace(/\\'/g, "'") - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/.npmignore b/node_modules/jade/node_modules/commander/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/jade/node_modules/commander/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/jade/node_modules/commander/History.md b/node_modules/jade/node_modules/commander/History.md deleted file mode 100644 index 9d80834..0000000 --- a/node_modules/jade/node_modules/commander/History.md +++ /dev/null @@ -1,42 +0,0 @@ - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/jade/node_modules/commander/Makefile b/node_modules/jade/node_modules/commander/Makefile deleted file mode 100644 index 0074625..0000000 --- a/node_modules/jade/node_modules/commander/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -TESTS = $(shell find test/test.*.js) - -test: - @./test/run $(TESTS) - -.PHONY: test \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/Readme.md b/node_modules/jade/node_modules/commander/Readme.md deleted file mode 100644 index 22909fa..0000000 --- a/node_modules/jade/node_modules/commander/Readme.md +++ /dev/null @@ -1,260 +0,0 @@ - -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineappe'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -v, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineappe - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -v, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/index.js b/node_modules/jade/node_modules/commander/index.js deleted file mode 100644 index 06ec1e4..0000000 --- a/node_modules/jade/node_modules/commander/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/commander'); \ No newline at end of file diff --git a/node_modules/jade/node_modules/commander/lib/commander.js b/node_modules/jade/node_modules/commander/lib/commander.js deleted file mode 100644 index 2d40479..0000000 --- a/node_modules/jade/node_modules/commander/lib/commander.js +++ /dev/null @@ -1,906 +0,0 @@ -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , path = require('path') - , tty = require('tty') - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/) - this.short = flags.shift(); - this.long = flags.shift(); - this.description = description; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this.args = []; - this.name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - return cmd; -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self.args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self.args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this.name, function(args){ - self.args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // store raw args - this.rawArgs = argv; - - // guess name - if (!this.name) this.name = basename(argv[1]); - - // process argv - this.args = this.parseOptions(this.normalize(argv)); - return this.parseArgs(this.args); -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args); - } else { - this.emit('*', args); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , argv = argv.slice(2) - , len = argv.length - , option - , arg; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0]) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || '-' == arg[0]) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - this.unknownOption(arg); - } - - // arg - args.push(arg); - } - - return args; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-v, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str){ - if (0 == arguments.length) return this._version; - this._version = str; - this.option('-v, --version', 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']'; - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - return this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - }).join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - return cmd.name + ' ' + args - + (cmd.description() - ? '\n' + cmd.description() - : ''); - }).join('\n\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this.name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - this.promptSingleLine(str, function(val){ - val = Number(val); - if (isNaN(val)) return program.promptForNumber(str + '(must be a number) ', fn); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - this.promptSingleLine(str, function(val){ - val = new Date(val); - if (isNaN(val.getTime())) return program.promptForDate(str + '(must be a date) ', fn); - fn(val); - }); -}; - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = ''; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf); - } else { - buf += val; - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - tty.setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.removeAllListeners('keypress'); - tty.setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - return self.confirm(str, fn); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, fn){ - var self = this; - - list.forEach(function(item, i){ - console.log(' %d) %s', i + 1, item); - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Default -h, --help option. - */ - -exports.option('-h, --help', 'output usage information'); -exports.on('help', function(){ - process.stdout.write(this.helpInformation()); - exports.emit('--help'); - process.exit(0); -}); diff --git a/node_modules/jade/node_modules/commander/package.json b/node_modules/jade/node_modules/commander/package.json deleted file mode 100644 index cc72d7b..0000000 --- a/node_modules/jade/node_modules/commander/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "commander" - , "version": "0.2.1" - , "description": "the complete solution for node.js command-line programs" - , "keywords": ["command", "option", "parser", "prompt", "stdin"] - , "author": "TJ Holowaychuk " - , "repository": { "type": "git", "url": "https://github.com/visionmedia/commander.js.git" } - , "dependencies": {} - , "devDependencies": { "should": ">= 0.0.1" } - , "main": "index" - , "engines": { "node": ">= 0.4.x < 0.7.0" } -} \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/.gitignore.orig b/node_modules/jade/node_modules/mkdirp/.gitignore.orig deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/jade/node_modules/mkdirp/.gitignore.orig +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/.gitignore.rej b/node_modules/jade/node_modules/mkdirp/.gitignore.rej deleted file mode 100644 index 69244ff..0000000 --- a/node_modules/jade/node_modules/mkdirp/.gitignore.rej +++ /dev/null @@ -1,5 +0,0 @@ ---- /dev/null -+++ .gitignore -@@ -0,0 +1,2 @@ -+node_modules/ -+npm-debug.log \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/.npmignore b/node_modules/jade/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/jade/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/LICENSE b/node_modules/jade/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/jade/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/jade/node_modules/mkdirp/README.markdown b/node_modules/jade/node_modules/mkdirp/README.markdown deleted file mode 100644 index b4dd75f..0000000 --- a/node_modules/jade/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,54 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! - -methods -======= - -var mkdirp = require('mkdirp'); - -mkdirp(dir, mode, cb) ---------------------- - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -mkdirp.sync(dir, mode) ----------------------- - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install mkdirp - -license -======= - -MIT/X11 diff --git a/node_modules/jade/node_modules/mkdirp/examples/pow.js b/node_modules/jade/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e692421..0000000 --- a/node_modules/jade/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig b/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig deleted file mode 100644 index 7741462..0000000 --- a/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej b/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej deleted file mode 100644 index 81e7f43..0000000 --- a/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej +++ /dev/null @@ -1,19 +0,0 @@ ---- examples/pow.js -+++ examples/pow.js -@@ -1,6 +1,15 @@ --var mkdirp = require('mkdirp').mkdirp; -+var mkdirp = require('../').mkdirp, -+ mkdirpSync = require('../').mkdirpSync; - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); -+ -+try { -+ mkdirpSync('/tmp/bar/foo/baz', 0755); -+ console.log('double pow!'); -+} -+catch (ex) { -+ console.log(ex); -+} \ No newline at end of file diff --git a/node_modules/jade/node_modules/mkdirp/index.js b/node_modules/jade/node_modules/mkdirp/index.js deleted file mode 100644 index 25f43ad..0000000 --- a/node_modules/jade/node_modules/mkdirp/index.js +++ /dev/null @@ -1,79 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) return cb(); - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er) { - if (er) cb(er); - else mkdirP(p, mode, cb); - }); - break; - - case 'EEXIST': - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original EEXIST be the failure reason. - if (er2 || !stat.isDirectory()) cb(er) - else cb(); - }); - break; - - default: - cb(er); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode) - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - var err1 = sync(path.dirname(p), mode) - if (err1) throw err1; - else return sync(p, mode); - break; - - case 'EEXIST' : - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0 - } - if (!stat.isDirectory()) throw err0; - else return null; - break; - default : - throw err0 - break; - } - } - - return null; -}; diff --git a/node_modules/jade/node_modules/mkdirp/package.json b/node_modules/jade/node_modules/mkdirp/package.json deleted file mode 100644 index 1bf9ac7..0000000 --- a/node_modules/jade/node_modules/mkdirp/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name" : "mkdirp", - "description" : "Recursively mkdir, like `mkdir -p`", - "version" : "0.3.0", - "author" : "James Halliday (http://substack.net)", - "main" : "./index", - "keywords" : [ - "mkdir", - "directory" - ], - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-mkdirp.git" - }, - "scripts" : { - "test" : "tap test/*.js" - }, - "devDependencies" : { - "tap" : "0.0.x" - }, - "license" : "MIT/X11", - "engines": { "node": "*" } -} diff --git a/node_modules/jade/node_modules/mkdirp/test/chmod.js b/node_modules/jade/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/clobber.js b/node_modules/jade/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/mkdirp.js b/node_modules/jade/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/perm.js b/node_modules/jade/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abb..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/perm_sync.js b/node_modules/jade/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f60..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/race.js b/node_modules/jade/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/rel.js b/node_modules/jade/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/sync.js b/node_modules/jade/node_modules/mkdirp/test/sync.js deleted file mode 100644 index e0e389d..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file, 0755); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/umask.js b/node_modules/jade/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 64ccafe..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/jade/node_modules/mkdirp/test/umask_sync.js b/node_modules/jade/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 83cba56..0000000 --- a/node_modules/jade/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); diff --git a/node_modules/jade/package.json b/node_modules/jade/package.json deleted file mode 100644 index 2fce87a..0000000 --- a/node_modules/jade/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "jade", - "description": "Jade template engine", - "version": "0.20.0", - "author": "TJ Holowaychuk ", - "repository": "git://github.com/visionmedia/jade", - "main": "./index.js", - "bin": { "jade": "./bin/jade" }, - "dependencies": { - "commander": "0.2.x", - "mkdirp": ">= 0.0.7" - }, - "devDependencies": { - "mocha": "*", - "coffee-script": ">= 0.0.1", - "markdown": ">= 0.0.1", - "stylus": ">= 0.0.1", - "uubench": "0.0.1", - "uglify-js": ">= 1.0.7" - }, - "scripts" : { "prepublish" : "npm prune" }, - "engines": { "node": ">= 0.1.98" } -} diff --git a/node_modules/jade/runtime.js b/node_modules/jade/runtime.js deleted file mode 100644 index 39f8a28..0000000 --- a/node_modules/jade/runtime.js +++ /dev/null @@ -1,123 +0,0 @@ - -var jade = (function(exports){ -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj){ - var buf = [] - , terse = obj.terse; - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else { - buf.push(key + '="' + exports.escape(val) + '"'); - } - } - } - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - - return exports; - -})({}); \ No newline at end of file diff --git a/node_modules/jade/runtime.min.js b/node_modules/jade/runtime.min.js deleted file mode 100644 index 8c19a98..0000000 --- a/node_modules/jade/runtime.min.js +++ /dev/null @@ -1 +0,0 @@ -var jade=function(exports){return Array.isArray||(Array.isArray=function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}),Object.keys||(Object.keys=function(obj){var arr=[];for(var key in obj)obj.hasOwnProperty(key)&&arr.push(key);return arr}),exports.attrs=function(obj){var buf=[],terse=obj.terse;delete obj.terse;var keys=Object.keys(obj),len=keys.length;if(len){buf.push("");for(var i=0;i/g,">").replace(/"/g,""")},exports.rethrow=function(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err},exports}({}) \ No newline at end of file diff --git a/node_modules/jade/testing/head.jade b/node_modules/jade/testing/head.jade deleted file mode 100644 index 8515406..0000000 --- a/node_modules/jade/testing/head.jade +++ /dev/null @@ -1,5 +0,0 @@ -head - script(src='/jquery.js') - yield - if false - script(src='/jquery.ui.js') diff --git a/node_modules/jade/testing/index.jade b/node_modules/jade/testing/index.jade deleted file mode 100644 index 0f7f511..0000000 --- a/node_modules/jade/testing/index.jade +++ /dev/null @@ -1,5 +0,0 @@ -html - body - include head - script(src='/caustic.js') - script(src='/app.js') diff --git a/node_modules/jade/testing/index.js b/node_modules/jade/testing/index.js deleted file mode 100644 index 776fa0f..0000000 --- a/node_modules/jade/testing/index.js +++ /dev/null @@ -1,11 +0,0 @@ - -/** - * Module dependencies. - */ - -var jade = require('../'); - -jade.renderFile('testing/index.jade', { pretty: true }, function(err, str){ - if (err) throw err; - console.log(str); -}); \ No newline at end of file diff --git a/node_modules/jade/testing/layout.jade b/node_modules/jade/testing/layout.jade deleted file mode 100644 index 6923cf1..0000000 --- a/node_modules/jade/testing/layout.jade +++ /dev/null @@ -1,6 +0,0 @@ -html - include head - script(src='/caustic.js') - script(src='/app.js') - body - block content \ No newline at end of file diff --git a/node_modules/jade/testing/user.jade b/node_modules/jade/testing/user.jade deleted file mode 100644 index 7907ea1..0000000 --- a/node_modules/jade/testing/user.jade +++ /dev/null @@ -1,3 +0,0 @@ - -h1= user.name -p= user.occupation \ No newline at end of file diff --git a/node_modules/jshint/.gitmodules b/node_modules/jshint/.gitmodules deleted file mode 100644 index e88ce8c..0000000 --- a/node_modules/jshint/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "packages/jshint"] - path = packages/jshint - url = git://github.com/jshint/jshint.git diff --git a/node_modules/jshint/.jshintignore b/node_modules/jshint/.jshintignore deleted file mode 100644 index 96cb28b..0000000 --- a/node_modules/jshint/.jshintignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -packages -.git diff --git a/node_modules/jshint/.jshintrc b/node_modules/jshint/.jshintrc deleted file mode 100644 index 6246b8b..0000000 --- a/node_modules/jshint/.jshintrc +++ /dev/null @@ -1,40 +0,0 @@ -{ - "predef": [ - "jasmine", - "spyOn", - "it", - "console", - "describe", - "expect", - "beforeEach", - "waits", - "waitsFor", - "runs" - ], - - "node" : true, - "es5" : true, - "browser" : true, - - "boss" : false, - "curly": false, - "debug": false, - "devel": false, - "eqeqeq": true, - "evil": true, - "forin": false, - "immed": true, - "laxbreak": false, - "newcap": true, - "noarg": true, - "noempty": false, - "nonew": false, - "nomen": false, - "onevar": true, - "plusplus": false, - "regexp": false, - "undef": true, - "sub": true, - "strict": false, - "white": true -} diff --git a/node_modules/jshint/.npmignore b/node_modules/jshint/.npmignore deleted file mode 100644 index 779f45c..0000000 --- a/node_modules/jshint/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -tags -node_modules -test/system/.files diff --git a/node_modules/jshint/HELP b/node_modules/jshint/HELP deleted file mode 100644 index e5738de..0000000 --- a/node_modules/jshint/HELP +++ /dev/null @@ -1,9 +0,0 @@ -Usage: jshint path path2 [options] - -Options: - - --version display package version - --config custom config file - --reporter custom reporter - --jslint-reporter use a jslint compatible xml reporter - --show-non-errors show additional data generated by jshint diff --git a/node_modules/jshint/LICENSE b/node_modules/jshint/LICENSE deleted file mode 100644 index 0b310fe..0000000 --- a/node_modules/jshint/LICENSE +++ /dev/null @@ -1,4 +0,0 @@ -** Licensed Under ** - - The MIT License - http://www.opensource.org/licenses/mit-license.php diff --git a/node_modules/jshint/README.md b/node_modules/jshint/README.md deleted file mode 100644 index 4f52a77..0000000 --- a/node_modules/jshint/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# node-jshint - -A command line interface and npm package for jshint. - -## Install - -To use jshint from any location (for npm v1.x) you need to install using the global (-g) flag. - - npm install -g jshint - -## Usage - -The command line interface looks like this. - - jshint path path2 [options] - -You can also require JSHint itself as a module. - - var jshint = require('jshint'); - -Note: If you are using npm v1.x be sure to install jshint locally (without the -g flag) or link it globally. - -## Text Editor Plugins - -* [gedit-node-jshint](https://github.com/niftylettuce/gedit-node-jshint) - Simply use CTRL+J in gedit to run JSHint using `node-jshint`. -* [vim syntastic](https://github.com/scrooloose/syntastic) - Run node-jshint at each file save. - -## Custom Reporters - -Specify a custom reporter module (see example/reporter.js). - - --reporter path/to/reporter.js - -Use a jslint compatible xml reporter. - - --jslint-reporter - -Show additional non-error data generated by jshint (unused globals etc). - - --show-non-errors - -## Custom Options - -Specify custom lint options (see [example/config.json](https://github.com/jshint/node-jshint/blob/master/example/config.json)). - - --config path/to/config.json - -Note: This bypasses any .jshintrc files. - -## Default Options - -The CLI uses the default options that come with JSHint. However, if it locates a .jshintrc file in your home directory (~/) it will use those options first. - -## Per Directory Options - -If there is a .jshintrc file in the current working directory, any of those options will take precedence over (or be merged with) any options found in the ~/.jshintrc file (if it exists). - -## Ignoring Files and Directories - -If there is a .jshintignore file in the current working directory, then any directories or files will be skipped over. - -Note: Pattern matching uses minimatch, with the nocase [option](https://github.com/isaacs/minimatch). When there is no match, it performs a left side match (when no forward slashes present and path is a directory). - -## Installing dependencies for development - - ./configure - -## Build Commands - - jake -T diff --git a/node_modules/jshint/bin/hint b/node_modules/jshint/bin/hint deleted file mode 100755 index 2b11eec..0000000 --- a/node_modules/jshint/bin/hint +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('./../lib/cli').interpret(process.argv); diff --git a/node_modules/jshint/lib/cli.js b/node_modules/jshint/lib/cli.js deleted file mode 100644 index 80a2f23..0000000 --- a/node_modules/jshint/lib/cli.js +++ /dev/null @@ -1,135 +0,0 @@ -var fs = require('fs'), - path = require('path'), - argsparser = require('argsparser'), - hint = require('./hint'); - -function _help() { - process.stdout.write(fs.readFileSync(__dirname + "/../HELP", "utf-8")); -} - -function _version() { - process.stdout.write(JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf-8")).version + "\n"); -} - -function _removeJsComments(str) { - str = str || ''; - str = str.replace(/\/\*[\s\S]*(?:\*\/)/g, ''); //everything between "/* */" - str = str.replace(/\/\/[^\n\r]*/g, ''); //everything after "//" - return str; -} - -function _loadAndParseConfig(filePath) { - return path.existsSync(filePath) ? - JSON.parse(_removeJsComments(fs.readFileSync(filePath, "utf-8"))) : {}; -} - -function _mergeConfigs(homerc, cwdrc) { - var homeConfig = _loadAndParseConfig(homerc), - cwdConfig = _loadAndParseConfig(cwdrc), - prop; - - for (prop in cwdConfig) { - if (typeof prop === 'string') { - if (prop === 'predef') { - homeConfig.predef = (homeConfig.predef || []).concat(cwdConfig.predef); - } else { - homeConfig[prop] = cwdConfig[prop]; - } - } - } - - return homeConfig; -} - -function _print(results) { - function exit() { - process.exit(results.length > 0 ? 1 : 0); - } - - // avoid stdout cutoff in node 0.4.x, also supports 0.5.x - // see https://github.com/joyent/node/issues/1669 - try { - if (!process.stdout.flush()) { - process.stdout.once("drain", exit); - } else { - exit(); - } - } catch (e) { - exit(); - } -} - -module.exports = { - interpret: function (args) { - var config, reporter, ignore, - options = argsparser.parse(args), - pathsToIgnore = path.join(process.cwd(), '.jshintignore'), - defaultConfig = path.join(process.env.HOME, '.jshintrc'), - projectConfig = path.join(process.cwd(), '.jshintrc'), - customConfig = options["--config"], - customReporter = options["--reporter"] ? path.resolve(process.cwd(), options["--reporter"]) : null, - targets = options.node; - - //could be on Windows which we are looking for an attribute ending in 'node.exe' - if (targets === undefined) { - (function () { - var arg; - - for (arg in options) { - if (path.basename(arg) === 'node.exe') { - targets = options[arg]; - break; - } - } - }()); - } - - targets = typeof targets === "string" ? null : targets.slice(1); - - - if (options["--version"]) { - _version(); - return; - } - - if (!targets || options["--help"]) { - _help(); - return; - } - - if (options["--jslint-reporter"]) { - customReporter = "./reporters/jslint_xml.js"; - } - - if (options["--show-non-errors"]) { - customReporter = "./reporters/non_error.js"; - } - - if (customConfig) { - config = _loadAndParseConfig(customConfig); - } else { - config = _mergeConfigs(defaultConfig, projectConfig); - } - - if (customReporter) { - try { - reporter = require(customReporter).reporter; - } catch (r) { - process.stdout.write("Error opening reporter file: " + customReporter); - process.stdout.write(r + "\n"); - process.exit(1); - } - } - - if (path.existsSync(pathsToIgnore)) { - ignore = fs.readFileSync(pathsToIgnore, "utf-8").split("\n").map(function (line) { - return line.trim(); - }).filter(function (line) { - return !!line; - }); - } - - _print(hint.hint(targets, config, reporter, ignore)); - } -}; - diff --git a/node_modules/jshint/lib/hint.js b/node_modules/jshint/lib/hint.js deleted file mode 100644 index 5e4861b..0000000 --- a/node_modules/jshint/lib/hint.js +++ /dev/null @@ -1,108 +0,0 @@ -var fs = require('fs'), - minimatch = require('minimatch'), - path = require('path'), - jshint = require('./../packages/jshint/jshint.js'), - _reporter = require('./reporters/default').reporter, - _cache = { - directories: {} - }; - -function _lint(file, results, config, data) { - var buffer, - lintdata; - - try { - buffer = fs.readFileSync(file, 'utf-8'); - } catch (e) { - process.stdout.write("Error: Cant open: " + file); - process.stdout.write(e + '\n'); - } - - // Remove potential Unicode Byte Order Mark. - buffer = buffer.replace(/^\uFEFF/, ''); - - if (!jshint.JSHINT(buffer, config)) { - jshint.JSHINT.errors.forEach(function (error) { - if (error) { - results.push({file: file, error: error}); - } - }); - } - - lintdata = jshint.JSHINT.data(); - - if (lintdata) { - lintdata.file = file; - data.push(lintdata); - } -} - -function isDirectory(aPath) { - var isDir; - - try { - if (_cache.directories.hasOwnProperty(aPath)) { - isDir = _cache.directories[aPath]; - } else { - isDir = fs.statSync(aPath).isDirectory(); - _cache.directories[aPath] = isDir; - } - } catch (e) { - isDir = false; - } - - return isDir; -} - - -function _shouldIgnore(somePath, ignore) { - function isIgnored(p) { - var fnmatch = minimatch(somePath, p, {nocase: true}), - lsmatch = isDirectory(p) && p.match(/^[^\/]*\/?$/) && - somePath.match(new RegExp("^" + p + ".*")); - - return !!(fnmatch || lsmatch); - } - - return ignore.some(function (ignorePath) { - return isIgnored(ignorePath); - }); -} - -function _collect(filePath, files, ignore) { - if (ignore && _shouldIgnore(filePath, ignore)) { - return; - } - - if (fs.statSync(filePath).isDirectory()) { - fs.readdirSync(filePath).forEach(function (item) { - _collect(path.join(filePath, item), files, ignore); - }); - } else if (filePath.match(/\.js$/)) { - files.push(filePath); - } -} - -module.exports = { - hint: function (targets, config, reporter, ignore) { - var files = [], - results = [], - data = []; - - targets.forEach(function (target) { - _collect(target, files, ignore); - }); - - files.forEach(function (file) { - _lint(file, results, config, data); - }); - - _cache = { - directories: {} - }; - - (reporter || _reporter)(results, data); - - return results; - } -}; diff --git a/node_modules/jshint/lib/reporters/default.js b/node_modules/jshint/lib/reporters/default.js deleted file mode 100644 index 92f9902..0000000 --- a/node_modules/jshint/lib/reporters/default.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - reporter: function (results, data) { - var len = results.length, - str = '', - file, error; - - results.forEach(function (result) { - file = result.file; - error = result.error; - str += file + ': line ' + error.line + ', col ' + - error.character + ', ' + error.reason + '\n'; - }); - - if (str) { - process.stdout.write(str + "\n" + len + ' error' + ((len === 1) ? '' : 's') + "\n"); - } - } -}; diff --git a/node_modules/jshint/lib/reporters/jslint_xml.js b/node_modules/jshint/lib/reporters/jslint_xml.js deleted file mode 100644 index eca2327..0000000 --- a/node_modules/jshint/lib/reporters/jslint_xml.js +++ /dev/null @@ -1,54 +0,0 @@ -// Author: Vasili Sviridov -// http://github.com/vsviridov -module.exports = -{ - reporter: function (results) - { - "use strict"; - - var files = {}, - out = [], - pairs = { - "&": "&", - '"': """, - "'": "'", - "<": "<", - ">": ">" - }, - file, i, issue; - - function encode(s) { - for (var r in pairs) { - if (typeof(s) !== "undefined") { - s = s.replace(new RegExp(r, "g"), pairs[r]); - } - } - return s || ""; - } - - - results.forEach(function (result) { - result.file = result.file.replace(/^\.\//, ''); - if (!files[result.file]) { - files[result.file] = []; - } - files[result.file].push(result.error); - }); - - out.push(""); - out.push(""); - - for (file in files) { - out.push("\t"); - for (i = 0; i < files[file].length; i++) { - issue = files[file][i]; - out.push("\t\t"); - } - out.push("\t"); - } - - out.push(""); - - process.stdout.write(out.join("\n") + "\n"); - } -}; diff --git a/node_modules/jshint/lib/reporters/non_error.js b/node_modules/jshint/lib/reporters/non_error.js deleted file mode 100644 index d8c3243..0000000 --- a/node_modules/jshint/lib/reporters/non_error.js +++ /dev/null @@ -1,45 +0,0 @@ -/*jshint node: true */ -module.exports = -{ - reporter: function (results, data, done) { - var len = results.length, - str = '', - file, error, globals, unuseds; - - results.forEach(function (result) { - file = result.file; - error = result.error; - str += file + ': line ' + error.line + ', col ' + - error.character + ', ' + error.reason + '\n'; - }); - - str += len > 0 ? ("\n" + len + ' error' + ((len === 1) ? '' : 's')) : ""; - - data.forEach(function (data) { - file = data.file; - globals = data.implieds; - unuseds = data.unused; - - if (globals || unuseds) { - str += '\n\n' + file + ' :\n'; - } - - if (globals) { - str += '\tImplied globals:\n'; - globals.forEach(function (global) { - str += '\t\t' + global.name + ': ' + global.line + '\n'; - }); - } - if (unuseds) { - str += '\tUnused Variables:\n\t\t'; - unuseds.forEach(function (unused) { - str += unused.name + '(' + unused.line + '), '; - }); - } - }); - - if (str) { - process.stdout.write(str + "\n"); - } - } -}; diff --git a/node_modules/jshint/node_modules/argsparser/.npmignore b/node_modules/jshint/node_modules/argsparser/.npmignore deleted file mode 100644 index 496ee2c..0000000 --- a/node_modules/jshint/node_modules/argsparser/.npmignore +++ /dev/null @@ -1 +0,0 @@ -.DS_Store \ No newline at end of file diff --git a/node_modules/jshint/node_modules/argsparser/Makefile b/node_modules/jshint/node_modules/argsparser/Makefile deleted file mode 100644 index 5e9c4b0..0000000 --- a/node_modules/jshint/node_modules/argsparser/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - node test/test.js - -.PHONY: test \ No newline at end of file diff --git a/node_modules/jshint/node_modules/argsparser/index.js b/node_modules/jshint/node_modules/argsparser/index.js deleted file mode 100644 index dd1cb00..0000000 --- a/node_modules/jshint/node_modules/argsparser/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/argsparser'); diff --git a/node_modules/jshint/node_modules/argsparser/lib/argsparser.js b/node_modules/jshint/node_modules/argsparser/lib/argsparser.js deleted file mode 100644 index d3a8092..0000000 --- a/node_modules/jshint/node_modules/argsparser/lib/argsparser.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Parser arguments array - * @param {Array} args optional arguments arrray. - * @return {Object} opts key value hash. - * @export - */ -exports.parse = function(args) { - // args is optional, default is process.argv - args = args || process.argv; - - var opts = {}, curSwitch; - - args.forEach(function(arg) { - // its a switch - if (/^(-|--)/.test(arg) || !curSwitch) { - opts[arg] = true; - curSwitch = arg; - // this arg is a data - } else { - if (arg === 'false') { - arg = false; - } else if (arg === 'true') { - arg = true; - } else if (!isNaN(arg)) { - arg = Number(arg); - } - - // it was a boolean switch per default, - // now it has got a val - if (typeof opts[curSwitch] === 'boolean') { - opts[curSwitch] = arg; - } else if (Array.isArray(opts[curSwitch])) { - opts[curSwitch].push(arg); - } else { - opts[curSwitch] = [opts[curSwitch], arg]; - } - } - }); - - return opts; -}; diff --git a/node_modules/jshint/node_modules/argsparser/package.json b/node_modules/jshint/node_modules/argsparser/package.json deleted file mode 100644 index 4b09eec..0000000 --- a/node_modules/jshint/node_modules/argsparser/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "argsparser", - "description": "A tiny command line arguments parser", - "version": "0.0.6", - "author": "Oleg Slobodskoi ", - "repository": { - "type": "git", - "url": "http://github.com/kof/node-argsparser.git" - }, - "keywords": [ "arguments", "options", "command line", "parser" ], - "engines": { "node": ">= 0.2.0" }, - "scripts": { "test": "node ./test/test.js" }, - "licenses": [ - { - "type": "MIT", - "url" : "http://www.opensource.org/licenses/mit-license.php" - } - ] -} diff --git a/node_modules/jshint/node_modules/argsparser/readme.md b/node_modules/jshint/node_modules/argsparser/readme.md deleted file mode 100644 index 9cde9ae..0000000 --- a/node_modules/jshint/node_modules/argsparser/readme.md +++ /dev/null @@ -1,34 +0,0 @@ -## Yet another tiny arguments parser for node - -## Features - * extremely tiny - * instead to parse all possible spellings, it uses just some simple rules - -## How this parser works -The target is to get a key-value object from an array. A key can be the first element or element prefixed by "-" and "--" (switch). -So the parser loops through the array and looks for keys. After he could detect an a key all next elements will be added as a value of this key until he find another key. -If there is no value, then the key is true (boolean). If there are a lot of values, then the key is an array. - -## Examples - -node script.js -> {"node": "script.js"} - -node script.js -o -> {"node": "script.js", "-o": true} - -node script.js -o test -> {"node": "script.js", "-o": "test"} - -node script.js -a testa --b testb -> {node: "script.js", "-a": "testa", "--b": "testb"} - -node script.js -paths /test.js /test1.js -> {node: "script.js", "-paths": ["/test.js", "/test1.js"]} - -## Usage - - // per default it parses process.argv - var args = require( "argsparser" ).parse(); // {"node": "/path/to/your/script.js"} - - // optional you can pass your own arguments array - var args = require( "argsparser" ).parse(["-a", "test"]); // {"-a": "test"} - - -## Installation - npm install argsparser \ No newline at end of file diff --git a/node_modules/jshint/node_modules/argsparser/test/test.js b/node_modules/jshint/node_modules/argsparser/test/test.js deleted file mode 100644 index 811de42..0000000 --- a/node_modules/jshint/node_modules/argsparser/test/test.js +++ /dev/null @@ -1,39 +0,0 @@ -var a = require('assert'), - util = require('util'), - parse = require('../lib/argsparser').parse; - -util.print('Run tests...\n'); - -a.deepEqual(parse(), {node: __filename}, 'node script.js'); - -a.deepEqual(parse(['-o']), {'-o': true}, 'node script.js -o'); - -a.deepEqual(parse(['-o', 'true']), {'-o': true}, 'node script.js -o true'); - -a.deepEqual(parse(['-o', 'false']), {'-o': false}, 'node script.js -o false'); - -a.deepEqual(parse(['-o', '123']), {'-o': 123}, 'node script.js -o 123'); - -a.deepEqual(parse(['--token', 'bla--bla']), {'--token': 'bla--bla'}, 'node script.js --token bla--bla'); - -a.deepEqual(parse(['-o', '123.456']), {'-o': 123.456}, 'node script.js -o 123.456'); - -a.deepEqual(parse(['-o', 'test']), {'-o': 'test'}, 'node script.js -o test'); - -a.deepEqual(parse(['-a', 'testa', '-b', 'testb']), {'-a': 'testa', '-b': 'testb'}, 'node script.js -a testa -b testb'); - -a.deepEqual(parse(['--a', 'testa', '--b', 'testb']), {'--a': 'testa', '--b': 'testb'}, 'node script.js --a testa --b testb '); - -a.deepEqual(parse(['-a', 'testa', '--b', 'testb']), {'-a': 'testa', '--b': 'testb'}, 'node script.js -a testa --b testb'); - -a.deepEqual(parse(['--a', 'testa', '-b', 'testb']), {'--a': 'testa', '-b': 'testb'}, 'node script.js --a testa -b testb'); - -a.deepEqual(parse(['-paths', '/test.js', '/test1.js']), {'-paths': ['/test.js', '/test1.js']}, 'node script.js -paths /test.js /test1.js'); - -a.deepEqual(parse(['--paths', '/test.js', '/test1.js']), {'--paths': ['/test.js', '/test1.js']}, 'node script.js --paths /test.js /test1.js'); - -a.deepEqual(parse(['--paths', '/test.js', '/test1.js', '-a', 'testa']), {'--paths': ['/test.js', '/test1.js'], '-a': 'testa'}, 'node script.js --paths /test.js /test1.js -a testa'); - -a.deepEqual(parse(['--port', '80', '8080']), {'--port': [80, 8080]}, 'node server.js --port 80 8080'); - -util.print('All tests ok\n'); diff --git a/node_modules/jshint/node_modules/minimatch/.travis.yml b/node_modules/jshint/node_modules/minimatch/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/jshint/node_modules/minimatch/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/jshint/node_modules/minimatch/LICENSE b/node_modules/jshint/node_modules/minimatch/LICENSE deleted file mode 100644 index 05a4010..0000000 --- a/node_modules/jshint/node_modules/minimatch/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright 2009, 2010, 2011 Isaac Z. Schlueter. -All rights reserved. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jshint/node_modules/minimatch/README.md b/node_modules/jshint/node_modules/minimatch/README.md deleted file mode 100644 index d5f9723..0000000 --- a/node_modules/jshint/node_modules/minimatch/README.md +++ /dev/null @@ -1,212 +0,0 @@ -# minimatch - -A minimal matching utility. - -[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) - - -This is the matching library used internally by npm. - -Eventually, it will replace the C binding in node-glob. - -It works by converting glob expressions into JavaScript `RegExp` -objects. - -## Usage - -```javascript -var minimatch = require("minimatch") - -minimatch("bar.foo", "*.foo") // true! -minimatch("bar.foo", "*.bar") // false! -``` - -## Features - -Supports these glob features: - -* Brace Expansion -* Extended glob matching -* "Globstar" `**` matching - -See: - -* `man sh` -* `man bash` -* `man 3 fnmatch` -* `man 5 gitignore` - -### Comparisons to other fnmatch/glob implementations - -While strict compliance with the existing standards is a worthwhile -goal, some discrepancies exist between minimatch and other -implementations, and are intentional. - -If the pattern starts with a `!` character, then it is negated. Set the -`nonegate` flag to suppress this behavior, and treat leading `!` -characters normally. This is perhaps relevant if you wish to start the -pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` -characters at the start of a pattern will negate the pattern multiple -times. - -If a pattern starts with `#`, then it is treated as a comment, and -will not match anything. Use `\#` to match a literal `#` at the -start of a line, or set the `nocomment` flag to suppress this behavior. - -The double-star character `**` is supported by default, unless the -`noglobstar` flag is set. This is supported in the manner of bsdglob -and bash 4.1, where `**` only has special significance if it is the only -thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but -`a/**b` will not. **Note that this is different from the way that `**` is -handled by ruby's `Dir` class.** - -If an escaped pattern has no matches, and the `null` flag is not set, -then minimatch.match returns the pattern as-provided, rather than -interpreting the character escapes. For example, -`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than -`"*a?"`. - -If brace expansion is not disabled, then it is performed before any -other interpretation of the glob pattern. Thus, a pattern like -`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded -**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are -checked for validity. Since those two are valid, matching proceeds. - - -## Minimatch Class - -Create a minimatch object by instanting the `minimatch.Minimatch` class. - -```javascript -var Minimatch = require("minimatch").Minimatch -var mm = new Minimatch(pattern, options) -``` - -### Properties - -* `pattern` The original pattern the minimatch object represents. -* `options` The options supplied to the constructor. -* `set` A 2-dimensional array of regexp or string expressions. - Each row in the - array corresponds to a brace-expanded pattern. Each item in the row - corresponds to a single path-part. For example, the pattern - `{a,b/c}/d` would expand to a set of patterns like: - - [ [ a, d ] - , [ b, c, d ] ] - - If a portion of the pattern doesn't have any "magic" in it - (that is, it's something like `"foo"` rather than `fo*o?`), then it - will be left as a string rather than converted to a regular - expression. - -* `regexp` Created by the `makeRe` method. A single regular expression - expressing the entire pattern. This is useful in cases where you wish - to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. -* `negate` True if the pattern is negated. -* `comment` True if the pattern is a comment. -* `empty` True if the pattern is `""`. - -### Methods - -* `makeRe` Generate the `regexp` member if necessary, and return it. - Will return `false` if the pattern is invalid. -* `match(fname)` Return true if the filename matches the pattern, or - false otherwise. -* `matchOne(fileArray, patternArray, partial)` Take a `/`-split - filename, and match it against a single row in the `regExpSet`. This - method is mainly for internal use, but is exposed so that it can be - used by a glob-walker that needs to avoid excessive filesystem calls. - -All other methods are internal, and will be called as necessary. - -## Functions - -The top-level exported function has a `cache` property, which is an LRU -cache set to store 100 items. So, calling these methods repeatedly -with the same pattern and options will use the same Minimatch object, -saving the cost of parsing it multiple times. - -### minimatch(path, pattern, options) - -Main export. Tests a path against the pattern using the options. - -```javascript -var isJS = minimatch(file, "*.js", { matchBase: true }) -``` - -### minimatch.filter(pattern, options) - -Returns a function that tests its -supplied argument, suitable for use with `Array.filter`. Example: - -```javascript -var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) -``` - -### minimatch.match(list, pattern, options) - -Match against the list of -files, in the style of fnmatch or glob. If nothing is matched, then -return the pattern (unless `{ null: true }` in the options.) - -```javascript -var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) -``` - -### minimatch.makeRe(pattern, options) - -Make a regular expression object from the pattern. - -## Options - -All options are `false` by default. - -### debug - -Dump a ton of stuff to stderr. - -### nobrace - -Do not expand `{a,b}` and `{1..3}` brace sets. - -### noglobstar - -Disable `**` matching against multiple folder names. - -### dot - -Allow patterns to match filenames starting with a period, even if -the pattern does not explicitly have a period in that spot. - -Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` -is set. - -### noext - -Disable "extglob" style patterns like `+(a|b)`. - -### nocase - -Perform a case-insensitive match. - -### nonull - -When a match is not found by `minimatch.match`, return a list containing -the pattern itself. When set, an empty list is returned if there are -no matches. - -### matchBase - -If set, then patterns without slashes will be matched -against the basename of the path if it contains slashes. For example, -`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. - -### nocomment - -Suppress the behavior of treating `#` at the start of a pattern as a -comment. - -### nonegate - -Suppress the behavior of treating a leading `!` character as negation. diff --git a/node_modules/jshint/node_modules/minimatch/minimatch.js b/node_modules/jshint/node_modules/minimatch/minimatch.js deleted file mode 100644 index 737c82e..0000000 --- a/node_modules/jshint/node_modules/minimatch/minimatch.js +++ /dev/null @@ -1,980 +0,0 @@ -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var LRU = require("lru-cache") - , cache = minimatch.cache = new LRU(100) - , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} - , pathSplit = process.platform === "win32" ? /\\|\// : "/" - -var path = require("path") - // any single thing other than / - // don't need to escape / when using new RegExp() - , qmark = "[^/]" - - // * => any number of characters - , star = qmark + "*?" - - // ** when dots are allowed. Anything goes, except .. and . - // not (^ or / followed by one or two dots followed by $ or /), - // followed by anything, any number of times. - , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" - - // not a ^ or / followed by a dot, - // followed by anything, any number of times. - , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" - - // characters that need to be escaped in RegExp. - , reSpecials = charSet("().*{}+?[]^$\\!") - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split("").reduce(function (set, c) { - set[c] = true - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/ - -minimatch.monkeyPatch = monkeyPatch -function monkeyPatch () { - var desc = Object.getOwnPropertyDescriptor(String.prototype, "match") - var orig = desc.value - desc.value = function (p) { - if (p instanceof Minimatch) return p.match(this) - return orig.call(this, p) - } - Object.defineProperty(String.prototype, desc) -} - -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -function minimatch (p, pattern, options) { - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required") - } - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === "#") { - return false - } - - // "" only matches "" - if (pattern.trim() === "") return p === "" - - return new Minimatch(pattern, options).match(p) -} - -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options, cache) - } - - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required") - } - - if (!options) options = {} - pattern = pattern.trim() - - // lru storage. - // these things aren't particularly big, but walking down the string - // and turning it into a regexp can get pretty costly. - var cacheKey = pattern + "\n" + Object.keys(options).filter(function (k) { - return options[k] - }).join(":") - var cached = minimatch.cache.get(cacheKey) - if (cached) return cached - minimatch.cache.set(cacheKey, this) - - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - - // make the set of regexps etc. - this.make() -} - -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === "#") { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) console.error(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) - - if (options.debug) console.error(this.pattern, set) - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - if (options.debug) console.error(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return -1 === s.indexOf(false) - }) - - if (options.debug) console.error(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - , negate = false - , options = this.options - , negateOffset = 0 - - if (options.nonegate) return - - for ( var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === "!" - ; i ++) { - negate = !negate - negateOffset ++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return new Minimatch(pattern, options).braceExpand() -} - -Minimatch.prototype.braceExpand = braceExpand -function braceExpand (pattern, options) { - options = options || this.options - pattern = typeof pattern === "undefined" - ? this.pattern : pattern - - if (typeof pattern === "undefined") { - throw new Error("undefined pattern") - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - var escaping = false - - // examples and comments refer to this crazy pattern: - // a{b,c{d,e},{f,g}h}x{y,z} - // expected: - // abxy - // abxz - // acdxy - // acdxz - // acexy - // acexz - // afhxy - // afhxz - // aghxy - // aghxz - - // everything before the first \{ is just a prefix. - // So, we pluck that off, and work with the rest, - // and then prepend it to everything we find. - if (pattern.charAt(0) !== "{") { - // console.error(pattern) - var prefix = null - for (var i = 0, l = pattern.length; i < l; i ++) { - var c = pattern.charAt(i) - // console.error(i, c) - if (c === "\\") { - escaping = !escaping - } else if (c === "{" && !escaping) { - prefix = pattern.substr(0, i) - break - } - } - - // actually no sets, all { were escaped. - if (prefix === null) { - // console.error("no sets") - return [pattern] - } - - var tail = braceExpand(pattern.substr(i), options) - return tail.map(function (t) { - return prefix + t - }) - } - - // now we have something like: - // {b,c{d,e},{f,g}h}x{y,z} - // walk through the set, expanding each part, until - // the set ends. then, we'll expand the suffix. - // If the set only has a single member, then'll put the {} back - - // first, handle numeric sets, since they're easier - var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/) - if (numset) { - // console.error("numset", numset[1], numset[2]) - var suf = braceExpand(pattern.substr(numset[0].length), options) - , start = +numset[1] - , end = +numset[2] - , inc = start > end ? -1 : 1 - , set = [] - for (var i = start; i != (end + inc); i += inc) { - // append all the suffixes - for (var ii = 0, ll = suf.length; ii < ll; ii ++) { - set.push(i + suf[ii]) - } - } - return set - } - - // ok, walk through the set - // We hope, somewhat optimistically, that there - // will be a } at the end. - // If the closing brace isn't found, then the pattern is - // interpreted as braceExpand("\\" + pattern) so that - // the leading \{ will be interpreted literally. - var i = 1 // skip the \{ - , depth = 1 - , set = [] - , member = "" - , sawEnd = false - , escaping = false - - function addMember () { - set.push(member) - member = "" - } - - // console.error("Entering for") - FOR: for (i = 1, l = pattern.length; i < l; i ++) { - var c = pattern.charAt(i) - // console.error("", i, c) - - if (escaping) { - escaping = false - member += "\\" + c - } else { - switch (c) { - case "\\": - escaping = true - continue - - case "{": - depth ++ - member += "{" - continue - - case "}": - depth -- - // if this closes the actual set, then we're done - if (depth === 0) { - addMember() - // pluck off the close-brace - i ++ - break FOR - } else { - member += c - continue - } - - case ",": - if (depth === 1) { - addMember() - } else { - member += c - } - continue - - default: - member += c - continue - } // switch - } // else - } // for - - // now we've either finished the set, and the suffix is - // pattern.substr(i), or we have *not* closed the set, - // and need to escape the leading brace - if (depth !== 0) { - // console.error("didn't close", pattern) - return braceExpand("\\" + pattern, options) - } - - // x{y,z} -> ["xy", "xz"] - // console.error("set", set) - // console.error("suffix", pattern.substr(i)) - var suf = braceExpand(pattern.substr(i), options) - // ["b", "c{d,e}","{f,g}h"] -> - // [["b"], ["cd", "ce"], ["fh", "gh"]] - var addBraces = set.length === 1 - // console.error("set pre-expanded", set) - set = set.map(function (p) { - return braceExpand(p, options) - }) - // console.error("set expanded", set) - - - // [["b"], ["cd", "ce"], ["fh", "gh"]] -> - // ["b", "cd", "ce", "fh", "gh"] - set = set.reduce(function (l, r) { - return l.concat(r) - }) - - if (addBraces) { - set = set.map(function (s) { - return "{" + s + "}" - }) - } - - // now attach the suffixes. - var ret = [] - for (var i = 0, l = set.length; i < l; i ++) { - for (var ii = 0, ll = suf.length; ii < ll; ii ++) { - ret.push(set[i] + suf[ii]) - } - } - return ret -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === "**") return GLOBSTAR - if (pattern === "") return "" - - var re = "" - , hasMagic = false - , escaping = false - // ? => one single character - , patternListStack = [] - , plType - , stateChar - , inClass = false - , reClassStart = -1 - , classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - , patternStart = pattern.charAt(0) === "." ? "" // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" - : "(?!\\.)" - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case "*": - re += star - hasMagic = true - break - case "?": - re += qmark - hasMagic = true - break - default: - re += "\\"+stateChar - break - } - stateChar = false - } - } - - for ( var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i ++ ) { - - if (options.debug) { - console.error("%s\t%s %s %j", pattern, i, re, c) - } - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += "\\" + c - escaping = false - continue - } - - SWITCH: switch (c) { - case "/": - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case "\\": - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case "?": - case "*": - case "+": - case "@": - case "!": - if (options.debug) { - console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c) - } - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - if (c === "!" && i === classStart + 1) c = "^" - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case "(": - if (inClass) { - re += "(" - continue - } - - if (!stateChar) { - re += "\\(" - continue - } - - plType = stateChar - patternListStack.push({ type: plType - , start: i - 1 - , reStart: re.length }) - re += stateChar === "!" ? "(?!" : "(?:" - stateChar = false - continue - - case ")": - if (inClass || !patternListStack.length) { - re += "\\)" - continue - } - - hasMagic = true - re += ")" - plType = patternListStack.pop().type - switch (plType) { - case "?": - case "+": - case "*": re += plType - case "!": // already handled by the start - case "@": break // the default anyway - } - continue - - case "|": - if (inClass || !patternListStack.length || escaping) { - re += "\\|" - escaping = false - continue - } - - re += "|" - continue - - // these are mostly the same in regexp and glob - case "[": - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += "\\" + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case "]": - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += "\\" + c - escaping = false - continue - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === "^" && inClass)) { - re += "\\" - } - - re += c - - } // switch - } // for - - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - var cs = pattern.substr(classStart + 1) - , sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + "\\[" + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - var pl - while (pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + 3) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = "\\" - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + "|" - }) - - // console.error("tail=%j\n %s", tail, tail) - var t = pl.type === "*" ? star - : pl.type === "?" ? qmark - : "\\" + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) - + t + "\\(" - + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += "\\\\" - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case ".": - case "[": - case "(": addPatternStart = true - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== "" && hasMagic) re = "(?=.)" + re - - if (addPatternStart) re = patternStart + re - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [ re, hasMagic ] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? "i" : "" - , regExp = new RegExp("^" + re + "$", flags) - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) return this.regexp = false - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - , flags = options.nocase ? "i" : "" - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === "string") ? regExpEscape(p) - : p._src - }).join("\\\/") - }).join("|") - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = "^" + re + "$" - - // can match anything, as long as it's not this. - if (this.negate) re = "^(?!" + re + ").*$" - - try { - return this.regexp = new RegExp(re, flags) - } catch (ex) { - return this.regexp = false - } -} - -minimatch.match = function (list, pattern, options) { - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - // console.error("match", f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === "" - - if (f === "/" && partial) return true - - var options = this.options - - // first, normalize any slash-separated path parts. - // f = path.normalize(f) - - // windows: need to use /, not \ - // On other platforms, \ is a valid (albeit bad) filename char. - if (process.platform === "win32") { - f = f.split("\\").join("/") - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - if (options.debug) { - console.error(this.pattern, "split", f) - } - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - // console.error(this.pattern, "set", set) - - for (var i = 0, l = set.length; i < l; i ++) { - var pattern = set[i] - var hit = this.matchOne(f, pattern, partial) - if (hit) { - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - if (options.debug) { - console.error("matchOne", - { "this": this - , file: file - , pattern: pattern }) - } - - if (options.matchBase && pattern.length === 1) { - file = path.basename(file.join("/")).split("/") - } - - if (options.debug) { - console.error("matchOne", file.length, pattern.length) - } - - for ( var fi = 0 - , pi = 0 - , fl = file.length - , pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi ++, pi ++ ) { - - if (options.debug) { - console.error("matchOne loop") - } - var p = pattern[pi] - , f = file[fi] - - if (options.debug) { - console.error(pattern, p, f) - } - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - , pr = pi + 1 - if (pr === pl) { - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for ( ; fi < fl; fi ++) { - if (file[fi] === "." || file[fi] === ".." || - (!options.dot && file[fi].charAt(0) === ".")) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - WHILE: while (fr < fl) { - var swallowee = file[fr] - if (swallowee === "." || swallowee === ".." || - (!options.dot && swallowee.charAt(0) === ".")) { - // console.error("dot detected!") - break WHILE - } - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - // found a match. - return true - } else { - // ** swallows a segment, and continue. - fr ++ - } - } - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - // console.error("\n>>> no match, partial?", file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === "string") { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - if (options.debug) { - console.error("string match", p, f, hit) - } - } else { - hit = f.match(p) - if (options.debug) { - console.error("pattern match", p, f, hit) - } - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === "") - return emptyFileEnd - } - - // should be unreachable. - throw new Error("wtf?") -} - - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, "$1") -} - - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") -} diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/.npmignore deleted file mode 100644 index 07e6e47..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/LICENSE deleted file mode 100644 index 05a4010..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright 2009, 2010, 2011 Isaac Z. Schlueter. -All rights reserved. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md deleted file mode 100644 index 1f5f155..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# lru cache - -A cache object that deletes the least-recently-used items. - -Usage: - - var LRU = require("lru-cache") - , cache = LRU(10) // max 10 items. default = Infinity - cache.set("key", "value") - cache.get("key") // "value" - -RTFS for more info. diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js deleted file mode 100644 index ca7a2b3..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js +++ /dev/null @@ -1,100 +0,0 @@ -;(function () { // closure for web browsers - -if (module) { - module.exports = LRUCache -} else { - // just set the global for non-node platforms. - ;(function () { return this })().LRUCache = LRUCache -} - -function hOP (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key) -} - -function LRUCache (maxLength) { - if (!(this instanceof LRUCache)) { - return new LRUCache(maxLength) - } - var cache = {} // hash of items by key - , lruList = {} // list of items in order of use recency - , lru = 0 // least recently used - , mru = 0 // most recently used - , length = 0 // number of items in the list - - // resize the cache when the maxLength changes. - Object.defineProperty(this, "maxLength", - { set : function (mL) { - if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity - maxLength = mL - // if it gets above double maxLength, trim right away. - // otherwise, do it whenever it's convenient. - if (length > maxLength) trim() - } - , get : function () { return maxLength } - , enumerable : true - }) - - this.maxLength = maxLength - - Object.defineProperty(this, "length", - { get : function () { return length } - , enumerable : true - }) - - this.reset = function () { - cache = {} - lruList = {} - lru = 0 - mru = 0 - length = 0 - } - - this.set = function (key, value) { - if (hOP(cache, key)) { - this.get(key) - cache[key].value = value - return undefined - } - var hit = {key:key, value:value, lu:mru++} - lruList[hit.lu] = cache[key] = hit - length ++ - if (length > maxLength) trim() - } - - this.get = function (key) { - if (!hOP(cache, key)) return undefined - var hit = cache[key] - delete lruList[hit.lu] - if (hit.lu === lru) lruWalk() - hit.lu = mru ++ - lruList[hit.lu] = hit - return hit.value - } - - this.del = function (key) { - if (!hOP(cache, key)) return undefined - var hit = cache[key] - delete cache[key] - delete lruList[hit.lu] - if (hit.lu === lru) lruWalk() - length -- - } - - function lruWalk () { - // lru has been deleted, hop up to the next hit. - lru = Object.keys(lruList).shift() - } - - function trim () { - if (length <= maxLength) return undefined - var prune = Object.keys(lruList).slice(0, length - maxLength) - for (var i = 0, l = (length - maxLength); i < l; i ++) { - delete cache[ lruList[prune[i]].key ] - delete lruList[prune[i]] - } - length = maxLength - lruWalk() - } -} - -})() diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json deleted file mode 100644 index 676ec3a..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ "name": "lru-cache" -, "description": "A cache object that deletes the least-recently-used items." -, "version": "1.0.5" -, "author": "Isaac Z. Schlueter " -, "scripts": { "test": "tap test" } -, "main": "lib/lru-cache.js" -, "repository": "git://github.com/isaacs/node-lru-cache.git" -, "devDependencies": { "tap": "0.1" } -, "license": - { "type": "MIT" - , "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" - } -} diff --git a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js deleted file mode 100644 index d726cbf..0000000 --- a/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js +++ /dev/null @@ -1,93 +0,0 @@ -var test = require('tap').test - , LRU = require('../') - -test('basic', function (t) { - var cache = new LRU(10) - cache.set("key", "value") - t.equal(cache.get("key"), "value") - t.equal(cache.get("nada"), undefined) - t.equal(cache.length, 1) - t.equal(cache.maxLength, 10) - t.end() -}) - -test('least recently set', function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.set("b", "B") - cache.set("c", "C") - t.equal(cache.get("c"), "C") - t.equal(cache.get("b"), "B") - t.equal(cache.get("a"), undefined) - t.end() -}) - -test('lru recently gotten', function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.set("b", "B") - cache.get("a") - cache.set("c", "C") - t.equal(cache.get("c"), "C") - t.equal(cache.get("b"), undefined) - t.equal(cache.get("a"), "A") - t.end() -}) - -test('del', function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.del("a") - t.equal(cache.get("a"), undefined) - t.end() -}) - -test('maxLength', function (t) { - var cache = new LRU(3) - - // test changing the maxLength, verify that the LRU items get dropped. - cache.maxLength = 100 - for (var i = 0; i < 100; i ++) cache.set(i, i) - t.equal(cache.length, 100) - for (var i = 0; i < 100; i ++) { - t.equal(cache.get(i), i) - } - cache.maxLength = 3 - t.equal(cache.length, 3) - for (var i = 0; i < 97; i ++) { - t.equal(cache.get(i), undefined) - } - for (var i = 98; i < 100; i ++) { - t.equal(cache.get(i), i) - } - - // now remove the maxLength restriction, and try again. - cache.maxLength = "hello" - for (var i = 0; i < 100; i ++) cache.set(i, i) - t.equal(cache.length, 100) - for (var i = 0; i < 100; i ++) { - t.equal(cache.get(i), i) - } - // should trigger an immediate resize - cache.maxLength = 3 - t.equal(cache.length, 3) - for (var i = 0; i < 97; i ++) { - t.equal(cache.get(i), undefined) - } - for (var i = 98; i < 100; i ++) { - t.equal(cache.get(i), i) - } - t.end() -}) - -test('reset', function (t) { - var cache = new LRU(10) - cache.set("a", "A") - cache.set("b", "B") - cache.reset() - t.equal(cache.length, 0) - t.equal(cache.maxLength, 10) - t.equal(cache.get("a"), undefined) - t.equal(cache.get("b"), undefined) - t.end() -}) diff --git a/node_modules/jshint/node_modules/minimatch/package.json b/node_modules/jshint/node_modules/minimatch/package.json deleted file mode 100644 index ee66c3b..0000000 --- a/node_modules/jshint/node_modules/minimatch/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "author": "Isaac Z. Schlueter (http://blog.izs.me)", - "name": "minimatch", - "description": "a glob matcher in javascript", - "version": "0.2.0", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "main": "minimatch.js", - "scripts": { - "test": "tap test" - }, - "engines": { - "node": "*" - }, - "dependencies": { - "lru-cache": "~1.0.5" - }, - "devDependencies": { - "tap": "~0.1.3" - }, - "licenses" : [ - { - "type" : "MIT", - "url" : "http://github.com/isaacs/minimatch/raw/master/LICENSE" - } - ] -} diff --git a/node_modules/jshint/node_modules/minimatch/test/basic.js b/node_modules/jshint/node_modules/minimatch/test/basic.js deleted file mode 100644 index 06d9428..0000000 --- a/node_modules/jshint/node_modules/minimatch/test/basic.js +++ /dev/null @@ -1,261 +0,0 @@ -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test -// -// TODO: Some of these tests do very bad things with backslashes, and will -// most likely fail badly on windows. They should probably be skipped. - -var tap = require("tap") - , globalBefore = Object.keys(global) - , mm = require("../") - , files = [ "a", "b", "c", "d", "abc" - , "abd", "abe", "bb", "bcd" - , "ca", "cb", "dd", "de" - , "bdir/", "bdir/cfile"] - , next = files.concat([ "a-b", "aXb" - , ".x", ".y" ]) - -tap.test("basic tests", function (t) { - var start = Date.now() - - // [ pattern, [matches], MM opts, files, TAP opts] - ; [ "http://www.bashcookbook.com/bashinfo" + - "/source/bash-1.14.7/tests/glob-test" - , ["a*", ["a", "abc", "abd", "abe"]] - , ["X*", ["X*"], {nonull: true}] - - // allow null glob expansion - , ["X*", []] - - // isaacs: Slightly different than bash/sh/ksh - // \\* is not un-escaped to literal "*" in a failed match, - // but it does make it get treated as a literal star - , ["\\*", ["\\*"], {nonull: true}] - , ["\\**", ["\\**"], {nonull: true}] - , ["\\*\\*", ["\\*\\*"], {nonull: true}] - - , ["b*/", ["bdir/"]] - , ["c*", ["c", "ca", "cb"]] - , ["**", files] - - , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] - , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] - - , "legendary larry crashes bashes" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] - - , "character classes" - , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] - , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", - "bdir/", "ca", "cb", "dd", "de"]] - , ["a*[^c]", ["abd", "abe"]] - , function () { files.push("a-b", "aXb") } - , ["a[X-]b", ["a-b", "aXb"]] - , function () { files.push(".x", ".y") } - , ["[^a-c]*", ["d", "dd", "de"]] - , function () { files.push("a*b/", "a*b/ooo") } - , ["a\\*b/*", ["a*b/ooo"]] - , ["a\\*?/*", ["a*b/ooo"]] - , ["*\\\\!*", [], {null: true}, ["echo !7"]] - , ["*\\!*", ["echo !7"], null, ["echo !7"]] - , ["*.\\*", ["r.*"], null, ["r.*"]] - , ["a[b]c", ["abc"]] - , ["a[\\b]c", ["abc"]] - , ["a?c", ["abc"]] - , ["a\\*c", [], {null: true}, ["abc"]] - , ["", [""], { null: true }, [""]] - - , "http://www.opensource.apple.com/source/bash/bash-23/" + - "bash/tests/glob-test" - , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } - , ["*/man*/bash.*", ["man/man1/bash.1"]] - , ["man/man1/bash.1", ["man/man1/bash.1"]] - , ["a***c", ["abc"], null, ["abc"]] - , ["a*****?c", ["abc"], null, ["abc"]] - , ["?*****??", ["abc"], null, ["abc"]] - , ["*****??", ["abc"], null, ["abc"]] - , ["?*****?c", ["abc"], null, ["abc"]] - , ["?***?****c", ["abc"], null, ["abc"]] - , ["?***?****?", ["abc"], null, ["abc"]] - , ["?***?****", ["abc"], null, ["abc"]] - , ["*******c", ["abc"], null, ["abc"]] - , ["*******?", ["abc"], null, ["abc"]] - , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["[-abc]", ["-"], null, ["-"]] - , ["[abc-]", ["-"], null, ["-"]] - , ["\\", ["\\"], null, ["\\"]] - , ["[\\\\]", ["\\"], null, ["\\"]] - , ["[[]", ["["], null, ["["]] - , ["[", ["["], null, ["["]] - , ["[*", ["[abc"], null, ["[abc"]] - , "a right bracket shall lose its special meaning and\n" + - "represent itself in a bracket expression if it occurs\n" + - "first in the list. -- POSIX.2 2.8.3.2" - , ["[]]", ["]"], null, ["]"]] - , ["[]-]", ["]"], null, ["]"]] - , ["[a-\z]", ["p"], null, ["p"]] - , ["??**********?****?", [], { null: true }, ["abc"]] - , ["??**********?****c", [], { null: true }, ["abc"]] - , ["?************c****?****", [], { null: true }, ["abc"]] - , ["*c*?**", [], { null: true }, ["abc"]] - , ["a*****c*?**", [], { null: true }, ["abc"]] - , ["a********???*******", [], { null: true }, ["abc"]] - , ["[]", [], { null: true }, ["a"]] - , ["[abc", [], { null: true }, ["["]] - - , "nocase tests" - , ["XYZ", ["xYz"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["ab*", ["ABC"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - - // [ pattern, [matches], MM opts, files, TAP opts] - , "onestar/twostar" - , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] - , ["{/?,*}", ["/a", "bb"], {null: true} - , ["/a", "/b/b", "/a/b/c", "bb"]] - - , "dots should not match unless requested" - , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] - - // .. and . can only match patterns starting with ., - // even when options.dot is set. - , function () { - files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] - } - , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] - , ["a/*/b", ["a/c/b"], {dot:false}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] - - - // this also tests that changing the options needs - // to change the cache key, even if the pattern is - // the same! - , ["**", ["a/b","a/.d",".a/.d"], { dot: true } - , [ ".a/.d", "a/.d", "a/b"]] - - , "paren sets cannot contain slashes" - , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] - - // brace sets trump all else. - // - // invalid glob pattern. fails on bash4 and bsdglob. - // however, in this implementation, it's easier just - // to do the intuitive thing, and let brace-expansion - // actually come before parsing any extglob patterns, - // like the documentation seems to say. - // - // XXX: if anyone complains about this, either fix it - // or tell them to grow up and stop complaining. - // - // bash/bsdglob says this: - // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] - // but we do this instead: - , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] - - // test partial parsing in the presence of comment/negation chars - , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] - , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] - - // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. - , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] - , {} - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] - - - // crazy nested {,,} and *(||) tests. - , function () { - files = [ "a", "b", "c", "d" - , "ab", "ac", "ad" - , "bc", "cb" - , "bc,d", "c,db", "c,d" - , "d)", "(b|c", "*(b|c" - , "b|c", "b|cc", "cb|c" - , "x(a|b|c)", "x(a|c)" - , "(a|b|c)", "(a|c)"] - } - , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] - , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] - // a - // *(b|c) - // *(b|d) - , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] - , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] - - - // test various flag settings. - , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] - , { noext: true } ] - , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} - , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] - , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] - - - // begin channelling Boole and deMorgan... - , "negation tests" - , function () { - files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] - } - - // anything that is NOT a* matches. - , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] - - // anything that IS !a* matches. - , ["!a*", ["!ab", "!abc"], {nonegate: true}] - - // anything that IS a* matches - , ["!!a*", ["a!b"]] - - // anything that is NOT !a* matches - , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] - - ].forEach(function (c) { - if (typeof c === "function") return c() - if (typeof c === "string") return t.comment(c) - - var pattern = c[0] - , expect = c[1].sort(alpha) - , options = c[2] || {} - , f = c[3] || files - , tapOpts = c[4] || {} - - // options.debug = true - var m = new mm.Minimatch(pattern, options) - var r = m.makeRe() - tapOpts.re = String(r) || JSON.stringify(r) - tapOpts.files = JSON.stringify(f) - tapOpts.pattern = pattern - tapOpts.set = m.set - tapOpts.negated = m.negate - - var actual = mm.match(f, pattern, options) - actual.sort(alpha) - - t.equivalent( actual, expect - , JSON.stringify(pattern) + " " + JSON.stringify(expect) - , tapOpts ) - }) - - t.comment("time=" + (Date.now() - start) + "ms") - t.end() -}) - -tap.test("global leak test", function (t) { - var globalAfter = Object.keys(global) - t.equivalent(globalAfter, globalBefore, "no new globals, please") - t.end() -}) - -function alpha (a, b) { - return a > b ? 1 : -1 -} diff --git a/node_modules/jshint/node_modules/minimatch/test/brace-expand.js b/node_modules/jshint/node_modules/minimatch/test/brace-expand.js deleted file mode 100644 index 7ee278a..0000000 --- a/node_modules/jshint/node_modules/minimatch/test/brace-expand.js +++ /dev/null @@ -1,33 +0,0 @@ -var tap = require("tap") - , minimatch = require("../") - -tap.test("brace expansion", function (t) { - // [ pattern, [expanded] ] - ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" - , [ "abxy" - , "abxz" - , "acdxy" - , "acdxz" - , "acexy" - , "acexz" - , "afhxy" - , "afhxz" - , "aghxy" - , "aghxz" ] ] - , [ "a{1..5}b" - , [ "a1b" - , "a2b" - , "a3b" - , "a4b" - , "a5b" ] ] - , [ "a{b}c", ["a{b}c"] ] - ].forEach(function (tc) { - var p = tc[0] - , expect = tc[1] - t.equivalent(minimatch.braceExpand(p), expect, p) - }) - console.error("ending") - t.end() -}) - - diff --git a/node_modules/jshint/node_modules/minimatch/test/caching.js b/node_modules/jshint/node_modules/minimatch/test/caching.js deleted file mode 100644 index 0fec4b0..0000000 --- a/node_modules/jshint/node_modules/minimatch/test/caching.js +++ /dev/null @@ -1,14 +0,0 @@ -var Minimatch = require("../minimatch.js").Minimatch -var tap = require("tap") -tap.test("cache test", function (t) { - var mm1 = new Minimatch("a?b") - var mm2 = new Minimatch("a?b") - t.equal(mm1, mm2, "should get the same object") - // the lru should drop it after 100 entries - for (var i = 0; i < 100; i ++) { - new Minimatch("a"+i) - } - mm2 = new Minimatch("a?b") - t.notEqual(mm1, mm2, "cache should have dropped") - t.end() -}) diff --git a/node_modules/jshint/package.json b/node_modules/jshint/package.json deleted file mode 100644 index be075d6..0000000 --- a/node_modules/jshint/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "jshint", - "version": "0.5.5", - "description": "A CLI for JSHint", - "homepage": "http://github.com/jshint/node-jshint", - "author": { - "name": "Brent Lintner", - "email": "brent.lintner@gmail.com", - "url": "http://github.com/brentlintner" - }, - "licenses": [{ - "type": "MIT", - "url": "http://www.opensource.org/licenses/mit-license.php" - }], - "bin": { "jshint": "./bin/hint" }, - "main": "packages/jshint/jshint", - "files": [ - "packages/jshint/README.markdown", - "packages/jshint/jshint.js", - "README.md", - "LICENSE", - "HELP", - "bin/hint", - "lib" - ], - "dependencies": { - "argsparser": ">=0.0.3", - "minimatch": ">=0.0.4" - }, - "devDependencies": { - "jasmine-node": "1.0.7" - }, - "preferGlobal" : true -} diff --git a/node_modules/jshint/packages/jshint/.npmignore b/node_modules/jshint/packages/jshint/.npmignore deleted file mode 100644 index 4199381..0000000 --- a/node_modules/jshint/packages/jshint/.npmignore +++ /dev/null @@ -1 +0,0 @@ -build/*.js diff --git a/node_modules/jshint/packages/jshint/README.markdown b/node_modules/jshint/packages/jshint/README.markdown deleted file mode 100755 index d8e6713..0000000 --- a/node_modules/jshint/packages/jshint/README.markdown +++ /dev/null @@ -1,71 +0,0 @@ -JSHint, A Static Code Analysis Tool for JavaScript -================================================== - -JSHint is a community-driven tool to detect errors and potential problems in -JavaScript code and to enforce your team's coding conventions. - -**IMPORTANT**: - - * This README is for people who are thinking about contributing to JSHint. For general usage - please refer to [our website](http://jshint.com/). - * If you want to report a bug about the website, please go to the - [jshint/site](https://github.com/jshint/site/) repository. - * If you want to report a bug or contribute to our NPM package, please go to the - [jshint/node-jshint](https://github.com/jshint/node-jshint/) repository. - -Reporting a bug ---------------- - -To report a bug simply create a [new GitHub Issue](https://github.com/jshint/jshint/issues/new) and -describe your problem or suggestion. We welcome all kind of feedback regarding JSHint including but -not limited to: - - * When JSHint doesn't work as expected - * When JSHint complains about valid JavaScript code that works in all browsers - * When you simply want a new option or feature - -Please, before reporting a bug look around to see if there are any open or closed tickets that -cover your issue. And remember the wisdom: pull request > bug report > tweet. - -Submitting patches ------------------- - -The best way to make sure your issue is addressed is to submit a patch. GitHub provides a very -nice interface--pull requests--for that but we accept patches through all mediums: email, issue -comment, tweet with a link to a snippet, etc. - -Before submitting a patch make sure that you comply to our style. We don't have specific style -guide so just look around the code you are changing. - -Also, make sure that you write tests for new features and make sure that all tests pass before -submitting a patch. Patches that break the build will be rejected. - -**FEATURE FREEZE**: Please note that we currently have a feature freeze on new environments and -styling options. The only patches we accept at this time are for bug fixes. - -Tests ------ - -To run tests you will need to install [node.js](http://nodejs.org/) and -expresso. You can install the latter with npm: - - npm install expresso - -After that, running tests is as easy as: - - expresso tests/*.js - -Attribution ------------ - -Maintainer: [Anton Kovalyov](http://anton.kovalyov.net/) ([@valueof](http://twitter.com/valueof)) - -Distinguished Contributors: - - * [Wolfgang Kluge](http://klugesoftware.de/) ([blog](http://gehirnwindung.de/)) - * [Josh Perez](http://www.goatslacker.com/) - -Thank you! ----------- - -We really appreciate all kind of feedback and contributions. Thanks for using and supporing JSHint! \ No newline at end of file diff --git a/node_modules/jshint/packages/jshint/jshint.js b/node_modules/jshint/packages/jshint/jshint.js deleted file mode 100644 index 27aba28..0000000 --- a/node_modules/jshint/packages/jshint/jshint.js +++ /dev/null @@ -1,4311 +0,0 @@ -/*! - * JSHint, by JSHint Community. - * - * Licensed under the same slightly modified MIT license that JSLint is. - * It stops evil-doers everywhere. - * - * JSHint is a derivative work of JSLint: - * - * Copyright (c) 2002 Douglas Crockford (www.JSLint.com) - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom - * the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * The Software shall be used for Good, not Evil. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - * JSHint was forked from 2010-12-16 edition of JSLint. - * - */ - -/* - JSHINT is a global function. It takes two parameters. - - var myResult = JSHINT(source, option); - - The first parameter is either a string or an array of strings. If it is a - string, it will be split on '\n' or '\r'. If it is an array of strings, it - is assumed that each string represents one line. The source can be a - JavaScript text or a JSON text. - - The second parameter is an optional object of options which control the - operation of JSHINT. Most of the options are booleans: They are all - optional and have a default value of false. One of the options, predef, - can be an array of names, which will be used to declare global variables, - or an object whose keys are used as global names, with a boolean value - that determines if they are assignable. - - If it checks out, JSHINT returns true. Otherwise, it returns false. - - If false, you can inspect JSHINT.errors to find out the problems. - JSHINT.errors is an array of objects containing these members: - - { - line : The line (relative to 0) at which the lint was found - character : The character (relative to 0) at which the lint was found - reason : The problem - evidence : The text line in which the problem occurred - raw : The raw message before the details were inserted - a : The first detail - b : The second detail - c : The third detail - d : The fourth detail - } - - If a fatal error was found, a null will be the last element of the - JSHINT.errors array. - - You can request a Function Report, which shows all of the functions - and the parameters and vars that they use. This can be used to find - implied global variables and other problems. The report is in HTML and - can be inserted in an HTML . - - var myReport = JSHINT.report(limited); - - If limited is true, then the report will be limited to only errors. - - You can request a data structure which contains JSHint's results. - - var myData = JSHINT.data(); - - It returns a structure with this form: - - { - errors: [ - { - line: NUMBER, - character: NUMBER, - reason: STRING, - evidence: STRING - } - ], - functions: [ - name: STRING, - line: NUMBER, - last: NUMBER, - param: [ - STRING - ], - closure: [ - STRING - ], - var: [ - STRING - ], - exception: [ - STRING - ], - outer: [ - STRING - ], - unused: [ - STRING - ], - global: [ - STRING - ], - label: [ - STRING - ] - ], - globals: [ - STRING - ], - member: { - STRING: NUMBER - }, - unuseds: [ - { - name: STRING, - line: NUMBER - } - ], - implieds: [ - { - name: STRING, - line: NUMBER - } - ], - urls: [ - STRING - ], - json: BOOLEAN - } - - Empty arrays will not be included. - -*/ - -/*jshint - evil: true, nomen: false, onevar: false, regexp: false, strict: true, boss: true, - undef: true, maxlen: 100, indent:4 -*/ - -/*members "\b", "\t", "\n", "\f", "\r", "!=", "!==", "\"", "%", "(begin)", - "(breakage)", "(context)", "(error)", "(global)", "(identifier)", "(last)", - "(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)", - "(statement)", "(verb)", "*", "+", "++", "-", "--", "\/", "<", "<=", "==", - "===", ">", ">=", $, $$, $A, $F, $H, $R, $break, $continue, $w, Abstract, Ajax, - __filename, __dirname, ActiveXObject, Array, ArrayBuffer, ArrayBufferView, Audio, - Autocompleter, Assets, Boolean, Builder, Buffer, Browser, COM, CScript, Canvas, - CustomAnimation, Class, Control, Chain, Color, Cookie, Core, DataView, Date, - Debug, Draggable, Draggables, Droppables, Document, DomReady, DOMReady, Drag, - E, Enumerator, Enumerable, Element, Elements, Error, Effect, EvalError, Event, - Events, FadeAnimation, Field, Flash, Float32Array, Float64Array, Form, - FormField, Frame, FormData, Function, Fx, GetObject, Group, Hash, HotKey, - HTMLElement, HTMLAnchorElement, HTMLBaseElement, HTMLBlockquoteElement, - HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLCanvasElement, HTMLDirectoryElement, - HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, - HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, - HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, - HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, - HTMLLabelElement, HTMLLayerElement, HTMLLegendElement, HTMLLIElement, - HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, - HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, - HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, - HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, - HtmlTable, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, - HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, - HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, HTMLVideoElement, - Iframe, IframeShim, Image, Int16Array, Int32Array, Int8Array, - Insertion, InputValidator, JSON, Keyboard, Locale, LN10, LN2, LOG10E, LOG2E, - MAX_VALUE, MIN_VALUE, Mask, Math, MenuItem, MoveAnimation, MooTools, Native, - NEGATIVE_INFINITY, Number, Object, ObjectRange, Option, Options, OverText, PI, - POSITIVE_INFINITY, PeriodicalExecuter, Point, Position, Prototype, RangeError, - Rectangle, ReferenceError, RegExp, ResizeAnimation, Request, RotateAnimation, - SQRT1_2, SQRT2, ScrollBar, ScriptEngine, ScriptEngineBuildVersion, - ScriptEngineMajorVersion, ScriptEngineMinorVersion, Scriptaculous, Scroller, - Slick, Slider, Selector, SharedWorker, String, Style, SyntaxError, Sortable, Sortables, - SortableObserver, Sound, Spinner, System, Swiff, Text, TextArea, Template, - Timer, Tips, Type, TypeError, Toggle, Try, "use strict", unescape, URI, URIError, URL, - VBArray, WSH, WScript, XDomainRequest, Web, Window, XMLDOM, XMLHttpRequest, XPathEvaluator, - XPathException, XPathExpression, XPathNamespace, XPathNSResolver, XPathResult, "\\", a, - addEventListener, address, alert, apply, applicationCache, arguments, arity, - asi, b, bitwise, block, blur, boolOptions, boss, browser, c, call, callee, - caller, cases, charAt, charCodeAt, character, clearInterval, clearTimeout, - close, closed, closure, comment, condition, confirm, console, constructor, - content, couch, create, css, curly, d, data, datalist, dd, debug, decodeURI, - decodeURIComponent, defaultStatus, defineClass, deserialize, devel, document, - dojo, dijit, dojox, define, edition, else, emit, encodeURI, encodeURIComponent, - entityify, eqeqeq, eqnull, errors, es5, escape, esnext, eval, event, evidence, evil, - ex, exception, exec, exps, expr, exports, FileReader, first, floor, focus, - forin, fragment, frames, from, fromCharCode, fud, funcscope, funct, function, functions, - g, gc, getComputedStyle, getRow, getter, GLOBAL, global, globals, globalstrict, - hasOwnProperty, help, history, i, id, identifier, immed, implieds, importPackage, include, - indent, indexOf, init, ins, instanceOf, isAlpha, isApplicationRunning, isArray, - isDigit, isFinite, isNaN, iterator, java, join, jshint, - JSHINT, json, jquery, jQuery, keys, label, labelled, last, lastsemic, laxbreak, - latedef, lbp, led, left, length, line, load, loadClass, localStorage, location, - log, loopfunc, m, match, maxerr, maxlen, member,message, meta, module, moveBy, - moveTo, mootools, multistr, name, navigator, new, newcap, noarg, node, noempty, nomen, - nonew, nonstandard, nud, onbeforeunload, onblur, onerror, onevar, onecase, onfocus, - onload, onresize, onunload, open, openDatabase, openURL, opener, opera, options, outer, param, - parent, parseFloat, parseInt, passfail, plusplus, predef, print, process, prompt, - proto, prototype, prototypejs, provides, push, quit, range, raw, reach, reason, regexp, - readFile, readUrl, regexdash, removeEventListener, replace, report, require, - reserved, resizeBy, resizeTo, resolvePath, resumeUpdates, respond, rhino, right, - runCommand, scroll, screen, scripturl, scrollBy, scrollTo, scrollbar, search, seal, - send, serialize, sessionStorage, setInterval, setTimeout, setter, setterToken, shift, slice, - smarttabs, sort, spawn, split, stack, status, start, strict, sub, substr, supernew, shadow, - supplant, sum, sync, test, toLowerCase, toString, toUpperCase, toint32, token, top, trailing, - type, typeOf, Uint16Array, Uint32Array, Uint8Array, undef, undefs, unused, urls, validthis, - value, valueOf, var, version, WebSocket, white, window, Worker, wsh*/ - -/*global exports: false */ - -// We build the application inside a function so that we produce only a single -// global variable. That function will be invoked immediately, and its return -// value is the JSHINT function itself. - -var JSHINT = (function () { - "use strict"; - - var anonname, // The guessed name for anonymous functions. - -// These are operators that should not be used with the ! operator. - - bang = { - '<' : true, - '<=' : true, - '==' : true, - '===': true, - '!==': true, - '!=' : true, - '>' : true, - '>=' : true, - '+' : true, - '-' : true, - '*' : true, - '/' : true, - '%' : true - }, - - // These are the JSHint boolean options. - boolOptions = { - asi : true, // if automatic semicolon insertion should be tolerated - bitwise : true, // if bitwise operators should not be allowed - boss : true, // if advanced usage of assignments should be allowed - browser : true, // if the standard browser globals should be predefined - couch : true, // if CouchDB globals should be predefined - curly : true, // if curly braces around all blocks should be required - debug : true, // if debugger statements should be allowed - devel : true, // if logging globals should be predefined (console, - // alert, etc.) - dojo : true, // if Dojo Toolkit globals should be predefined - eqeqeq : true, // if === should be required - eqnull : true, // if == null comparisons should be tolerated - es5 : true, // if ES5 syntax should be allowed - esnext : true, // if es.next specific syntax should be allowed - evil : true, // if eval should be allowed - expr : true, // if ExpressionStatement should be allowed as Programs - forin : true, // if for in statements must filter - funcscope : true, // if only function scope should be used for scope tests - globalstrict: true, // if global "use strict"; should be allowed (also - // enables 'strict') - immed : true, // if immediate invocations must be wrapped in parens - iterator : true, // if the `__iterator__` property should be allowed - jquery : true, // if jQuery globals should be predefined - lastsemic : true, // if semicolons may be ommitted for the trailing - // statements inside of a one-line blocks. - latedef : true, // if the use before definition should not be tolerated - laxbreak : true, // if line breaks should not be checked - loopfunc : true, // if functions should be allowed to be defined within - // loops - mootools : true, // if MooTools globals should be predefined - multistr : true, // allow multiline strings - newcap : true, // if constructor names must be capitalized - noarg : true, // if arguments.caller and arguments.callee should be - // disallowed - node : true, // if the Node.js environment globals should be - // predefined - noempty : true, // if empty blocks should be disallowed - nonew : true, // if using `new` for side-effects should be disallowed - nonstandard : true, // if non-standard (but widely adopted) globals should - // be predefined - nomen : true, // if names should be checked - onevar : true, // if only one var statement per function should be - // allowed - onecase : true, // if one case switch statements should be allowed - passfail : true, // if the scan should stop on first error - plusplus : true, // if increment/decrement should not be allowed - proto : true, // if the `__proto__` property should be allowed - prototypejs : true, // if Prototype and Scriptaculous globals should be - // predefined - regexdash : true, // if unescaped first/last dash (-) inside brackets - // should be tolerated - regexp : true, // if the . should not be allowed in regexp literals - rhino : true, // if the Rhino environment globals should be predefined - undef : true, // if variables should be declared before used - scripturl : true, // if script-targeted URLs should be tolerated - shadow : true, // if variable shadowing should be tolerated - smarttabs : true, // if smarttabs should be tolerated - // (http://www.emacswiki.org/emacs/SmartTabs) - strict : true, // require the "use strict"; pragma - sub : true, // if all forms of subscript notation are tolerated - supernew : true, // if `new function () { ... };` and `new Object;` - // should be tolerated - trailing : true, // if trailing whitespace rules apply - validthis : true, // if 'this' inside a non-constructor function is valid. - // This is a function scoped option only. - white : true, // if strict whitespace rules apply - wsh : true // if the Windows Scripting Host environment globals - // should be predefined - }, - - // browser contains a set of global names which are commonly provided by a - // web browser environment. - browser = { - ArrayBuffer : false, - ArrayBufferView : false, - Audio : false, - addEventListener : false, - applicationCache : false, - blur : false, - clearInterval : false, - clearTimeout : false, - close : false, - closed : false, - DataView : false, - defaultStatus : false, - document : false, - event : false, - FileReader : false, - Float32Array : false, - Float64Array : false, - FormData : false, - focus : false, - frames : false, - getComputedStyle : false, - HTMLElement : false, - HTMLAnchorElement : false, - HTMLBaseElement : false, - HTMLBlockquoteElement : false, - HTMLBodyElement : false, - HTMLBRElement : false, - HTMLButtonElement : false, - HTMLCanvasElement : false, - HTMLDirectoryElement : false, - HTMLDivElement : false, - HTMLDListElement : false, - HTMLFieldSetElement : false, - HTMLFontElement : false, - HTMLFormElement : false, - HTMLFrameElement : false, - HTMLFrameSetElement : false, - HTMLHeadElement : false, - HTMLHeadingElement : false, - HTMLHRElement : false, - HTMLHtmlElement : false, - HTMLIFrameElement : false, - HTMLImageElement : false, - HTMLInputElement : false, - HTMLIsIndexElement : false, - HTMLLabelElement : false, - HTMLLayerElement : false, - HTMLLegendElement : false, - HTMLLIElement : false, - HTMLLinkElement : false, - HTMLMapElement : false, - HTMLMenuElement : false, - HTMLMetaElement : false, - HTMLModElement : false, - HTMLObjectElement : false, - HTMLOListElement : false, - HTMLOptGroupElement : false, - HTMLOptionElement : false, - HTMLParagraphElement : false, - HTMLParamElement : false, - HTMLPreElement : false, - HTMLQuoteElement : false, - HTMLScriptElement : false, - HTMLSelectElement : false, - HTMLStyleElement : false, - HTMLTableCaptionElement : false, - HTMLTableCellElement : false, - HTMLTableColElement : false, - HTMLTableElement : false, - HTMLTableRowElement : false, - HTMLTableSectionElement : false, - HTMLTextAreaElement : false, - HTMLTitleElement : false, - HTMLUListElement : false, - HTMLVideoElement : false, - history : false, - Int16Array : false, - Int32Array : false, - Int8Array : false, - Image : false, - length : false, - localStorage : false, - location : false, - moveBy : false, - moveTo : false, - name : false, - navigator : false, - onbeforeunload : true, - onblur : true, - onerror : true, - onfocus : true, - onload : true, - onresize : true, - onunload : true, - open : false, - openDatabase : false, - opener : false, - Option : false, - parent : false, - print : false, - removeEventListener : false, - resizeBy : false, - resizeTo : false, - screen : false, - scroll : false, - scrollBy : false, - scrollTo : false, - sessionStorage : false, - setInterval : false, - setTimeout : false, - SharedWorker : false, - status : false, - top : false, - Uint16Array : false, - Uint32Array : false, - Uint8Array : false, - WebSocket : false, - window : false, - Worker : false, - XMLHttpRequest : false, - XPathEvaluator : false, - XPathException : false, - XPathExpression : false, - XPathNamespace : false, - XPathNSResolver : false, - XPathResult : false - }, - - couch = { - "require" : false, - respond : false, - getRow : false, - emit : false, - send : false, - start : false, - sum : false, - log : false, - exports : false, - module : false, - provides : false - }, - - devel = { - alert : false, - confirm : false, - console : false, - Debug : false, - opera : false, - prompt : false - }, - - dojo = { - dojo : false, - dijit : false, - dojox : false, - define : false, - "require" : false - }, - - escapes = { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '/' : '\\/', - '\\': '\\\\' - }, - - funct, // The current function - - functionicity = [ - 'closure', 'exception', 'global', 'label', - 'outer', 'unused', 'var' - ], - - functions, // All of the functions - - global, // The global scope - implied, // Implied globals - inblock, - indent, - jsonmode, - - jquery = { - '$' : false, - jQuery : false - }, - - lines, - lookahead, - member, - membersOnly, - - mootools = { - '$' : false, - '$$' : false, - Assets : false, - Browser : false, - Chain : false, - Class : false, - Color : false, - Cookie : false, - Core : false, - Document : false, - DomReady : false, - DOMReady : false, - Drag : false, - Element : false, - Elements : false, - Event : false, - Events : false, - Fx : false, - Group : false, - Hash : false, - HtmlTable : false, - Iframe : false, - IframeShim : false, - InputValidator : false, - instanceOf : false, - Keyboard : false, - Locale : false, - Mask : false, - MooTools : false, - Native : false, - Options : false, - OverText : false, - Request : false, - Scroller : false, - Slick : false, - Slider : false, - Sortables : false, - Spinner : false, - Swiff : false, - Tips : false, - Type : false, - typeOf : false, - URI : false, - Window : false - }, - - nexttoken, - - node = { - __filename : false, - __dirname : false, - Buffer : false, - console : false, - exports : false, - GLOBAL : false, - global : false, - module : false, - process : false, - require : false, - setTimeout : false, - clearTimeout : false, - setInterval : false, - clearInterval : false - }, - - noreach, - option, - predefined, // Global variables defined by option - prereg, - prevtoken, - - prototypejs = { - '$' : false, - '$$' : false, - '$A' : false, - '$F' : false, - '$H' : false, - '$R' : false, - '$break' : false, - '$continue' : false, - '$w' : false, - Abstract : false, - Ajax : false, - Class : false, - Enumerable : false, - Element : false, - Event : false, - Field : false, - Form : false, - Hash : false, - Insertion : false, - ObjectRange : false, - PeriodicalExecuter: false, - Position : false, - Prototype : false, - Selector : false, - Template : false, - Toggle : false, - Try : false, - Autocompleter : false, - Builder : false, - Control : false, - Draggable : false, - Draggables : false, - Droppables : false, - Effect : false, - Sortable : false, - SortableObserver : false, - Sound : false, - Scriptaculous : false - }, - - rhino = { - defineClass : false, - deserialize : false, - gc : false, - help : false, - importPackage: false, - "java" : false, - load : false, - loadClass : false, - print : false, - quit : false, - readFile : false, - readUrl : false, - runCommand : false, - seal : false, - serialize : false, - spawn : false, - sync : false, - toint32 : false, - version : false - }, - - scope, // The current scope - stack, - - // standard contains the global names that are provided by the - // ECMAScript standard. - standard = { - Array : false, - Boolean : false, - Date : false, - decodeURI : false, - decodeURIComponent : false, - encodeURI : false, - encodeURIComponent : false, - Error : false, - 'eval' : false, - EvalError : false, - Function : false, - hasOwnProperty : false, - isFinite : false, - isNaN : false, - JSON : false, - Math : false, - Number : false, - Object : false, - parseInt : false, - parseFloat : false, - RangeError : false, - ReferenceError : false, - RegExp : false, - String : false, - SyntaxError : false, - TypeError : false, - URIError : false - }, - - // widely adopted global names that are not part of ECMAScript standard - nonstandard = { - escape : false, - unescape : false - }, - - standard_member = { - E : true, - LN2 : true, - LN10 : true, - LOG2E : true, - LOG10E : true, - MAX_VALUE : true, - MIN_VALUE : true, - NEGATIVE_INFINITY : true, - PI : true, - POSITIVE_INFINITY : true, - SQRT1_2 : true, - SQRT2 : true - }, - - directive, - syntax = {}, - tab, - token, - urls, - useESNextSyntax, - warnings, - - wsh = { - ActiveXObject : true, - Enumerator : true, - GetObject : true, - ScriptEngine : true, - ScriptEngineBuildVersion : true, - ScriptEngineMajorVersion : true, - ScriptEngineMinorVersion : true, - VBArray : true, - WSH : true, - WScript : true, - XDomainRequest : true - }; - - // Regular expressions. Some of these are stupidly long. - var ax, cx, tx, nx, nxg, lx, ix, jx, ft; - (function () { - /*jshint maxlen:300 */ - - // unsafe comment or string - ax = /@cc|<\/?|script|\]\s*\]|<\s*!|</i; - - // unsafe characters that are silently deleted by one or more browsers - cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; - - // token - tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(jshint|jslint|members?|global)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/; - - // characters in strings that need escapement - nx = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; - nxg = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - - // star slash - lx = /\*\/|\/\*/; - - // identifier - ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; - - // javascript url - jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i; - - // catches /* falls through */ comments - ft = /^\s*\/\*\s*falls\sthrough\s*\*\/\s*$/; - }()); - - function F() {} // Used by Object.create - - function is_own(object, name) { - -// The object.hasOwnProperty method fails when the property under consideration -// is named 'hasOwnProperty'. So we have to use this more convoluted form. - - return Object.prototype.hasOwnProperty.call(object, name); - } - -// Provide critical ES5 functions to ES3. - - if (typeof Array.isArray !== 'function') { - Array.isArray = function (o) { - return Object.prototype.toString.apply(o) === '[object Array]'; - }; - } - - if (typeof Object.create !== 'function') { - Object.create = function (o) { - F.prototype = o; - return new F(); - }; - } - - if (typeof Object.keys !== 'function') { - Object.keys = function (o) { - var a = [], k; - for (k in o) { - if (is_own(o, k)) { - a.push(k); - } - } - return a; - }; - } - -// Non standard methods - - if (typeof String.prototype.entityify !== 'function') { - String.prototype.entityify = function () { - return this - .replace(/&/g, '&') - .replace(//g, '>'); - }; - } - - if (typeof String.prototype.isAlpha !== 'function') { - String.prototype.isAlpha = function () { - return (this >= 'a' && this <= 'z\uffff') || - (this >= 'A' && this <= 'Z\uffff'); - }; - } - - if (typeof String.prototype.isDigit !== 'function') { - String.prototype.isDigit = function () { - return (this >= '0' && this <= '9'); - }; - } - - if (typeof String.prototype.supplant !== 'function') { - String.prototype.supplant = function (o) { - return this.replace(/\{([^{}]*)\}/g, function (a, b) { - var r = o[b]; - return typeof r === 'string' || typeof r === 'number' ? r : a; - }); - }; - } - - if (typeof String.prototype.name !== 'function') { - String.prototype.name = function () { - -// If the string looks like an identifier, then we can return it as is. -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can simply slap some quotes around it. -// Otherwise we must also replace the offending characters with safe -// sequences. - - if (ix.test(this)) { - return this; - } - if (nx.test(this)) { - return '"' + this.replace(nxg, function (a) { - var c = escapes[a]; - if (c) { - return c; - } - return '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); - }) + '"'; - } - return '"' + this + '"'; - }; - } - - - function combine(t, o) { - var n; - for (n in o) { - if (is_own(o, n)) { - t[n] = o[n]; - } - } - } - - function assume() { - if (option.couch) { - combine(predefined, couch); - } - - if (option.rhino) { - combine(predefined, rhino); - } - - if (option.prototypejs) { - combine(predefined, prototypejs); - } - - if (option.node) { - combine(predefined, node); - } - - if (option.devel) { - combine(predefined, devel); - } - - if (option.dojo) { - combine(predefined, dojo); - } - - if (option.browser) { - combine(predefined, browser); - } - - if (option.nonstandard) { - combine(predefined, nonstandard); - } - - if (option.jquery) { - combine(predefined, jquery); - } - - if (option.mootools) { - combine(predefined, mootools); - } - - if (option.wsh) { - combine(predefined, wsh); - } - - if (option.esnext) { - useESNextSyntax(); - } - - if (option.globalstrict && option.strict !== false) { - option.strict = true; - } - } - - - // Produce an error warning. - function quit(message, line, chr) { - var percentage = Math.floor((line / lines.length) * 100); - - throw { - name: 'JSHintError', - line: line, - character: chr, - message: message + " (" + percentage + "% scanned).", - raw: message - }; - } - - function isundef(scope, m, t, a) { - return JSHINT.undefs.push([scope, m, t, a]); - } - - function warning(m, t, a, b, c, d) { - var ch, l, w; - t = t || nexttoken; - if (t.id === '(end)') { // `~ - t = token; - } - l = t.line || 0; - ch = t.from || 0; - w = { - id: '(error)', - raw: m, - evidence: lines[l - 1] || '', - line: l, - character: ch, - a: a, - b: b, - c: c, - d: d - }; - w.reason = m.supplant(w); - JSHINT.errors.push(w); - if (option.passfail) { - quit('Stopping. ', l, ch); - } - warnings += 1; - if (warnings >= option.maxerr) { - quit("Too many errors.", l, ch); - } - return w; - } - - function warningAt(m, l, ch, a, b, c, d) { - return warning(m, { - line: l, - from: ch - }, a, b, c, d); - } - - function error(m, t, a, b, c, d) { - var w = warning(m, t, a, b, c, d); - } - - function errorAt(m, l, ch, a, b, c, d) { - return error(m, { - line: l, - from: ch - }, a, b, c, d); - } - - - -// lexical analysis and token construction - - var lex = (function lex() { - var character, from, line, s; - -// Private lex methods - - function nextLine() { - var at, - tw; // trailing whitespace check - - if (line >= lines.length) - return false; - - character = 1; - s = lines[line]; - line += 1; - - // If smarttabs option is used check for spaces followed by tabs only. - // Otherwise check for any occurence of mixed tabs and spaces. - if (option.smarttabs) - at = s.search(/ \t/); - else - at = s.search(/ \t|\t /); - - if (at >= 0) - warningAt("Mixed spaces and tabs.", line, at + 1); - - s = s.replace(/\t/g, tab); - at = s.search(cx); - - if (at >= 0) - warningAt("Unsafe character.", line, at); - - if (option.maxlen && option.maxlen < s.length) - warningAt("Line too long.", line, s.length); - - // Check for trailing whitespaces - tw = /\s+$/.test(s); - if (option.trailing && tw && !/^\s+$/.test(s)) { - warningAt("Trailing whitespace.", line, tw); - } - return true; - } - -// Produce a token object. The token inherits from a syntax symbol. - - function it(type, value) { - var i, t; - if (type === '(color)' || type === '(range)') { - t = {type: type}; - } else if (type === '(punctuator)' || - (type === '(identifier)' && is_own(syntax, value))) { - t = syntax[value] || syntax['(error)']; - } else { - t = syntax[type]; - } - t = Object.create(t); - if (type === '(string)' || type === '(range)') { - if (!option.scripturl && jx.test(value)) { - warningAt("Script URL.", line, from); - } - } - if (type === '(identifier)') { - t.identifier = true; - if (value === '__proto__' && !option.proto) { - warningAt("The '{a}' property is deprecated.", - line, from, value); - } else if (value === '__iterator__' && !option.iterator) { - warningAt("'{a}' is only available in JavaScript 1.7.", - line, from, value); - } else if (option.nomen && (value.charAt(0) === '_' || - value.charAt(value.length - 1) === '_')) { - if (!option.node || token.id === '.' || - (value !== '__dirname' && value !== '__filename')) { - warningAt("Unexpected {a} in '{b}'.", line, from, "dangling '_'", value); - } - } - } - t.value = value; - t.line = line; - t.character = character; - t.from = from; - i = t.id; - if (i !== '(endline)') { - prereg = i && - (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || - i === 'return' || - i === 'case'); - } - return t; - } - - // Public lex methods - return { - init: function (source) { - if (typeof source === 'string') { - lines = source - .replace(/\r\n/g, '\n') - .replace(/\r/g, '\n') - .split('\n'); - } else { - lines = source; - } - - // If the first line is a shebang (#!), make it a blank and move on. - // Shebangs are used by Node scripts. - if (lines[0] && lines[0].substr(0, 2) === '#!') - lines[0] = ''; - - line = 0; - nextLine(); - from = 1; - }, - - range: function (begin, end) { - var c, value = ''; - from = character; - if (s.charAt(0) !== begin) { - errorAt("Expected '{a}' and instead saw '{b}'.", - line, character, begin, s.charAt(0)); - } - for (;;) { - s = s.slice(1); - character += 1; - c = s.charAt(0); - switch (c) { - case '': - errorAt("Missing '{a}'.", line, character, c); - break; - case end: - s = s.slice(1); - character += 1; - return it('(range)', value); - case '\\': - warningAt("Unexpected '{a}'.", line, character, c); - } - value += c; - } - - }, - - - // token -- this is called by advance to get the next token - token: function () { - var b, c, captures, d, depth, high, i, l, low, q, t, isLiteral, isInRange; - - function match(x) { - var r = x.exec(s), r1; - if (r) { - l = r[0].length; - r1 = r[1]; - c = r1.charAt(0); - s = s.substr(l); - from = character + l - r1.length; - character += l; - return r1; - } - } - - function string(x) { - var c, j, r = '', allowNewLine = false; - - if (jsonmode && x !== '"') { - warningAt("Strings must use doublequote.", - line, character); - } - - function esc(n) { - var i = parseInt(s.substr(j + 1, n), 16); - j += n; - if (i >= 32 && i <= 126 && - i !== 34 && i !== 92 && i !== 39) { - warningAt("Unnecessary escapement.", line, character); - } - character += n; - c = String.fromCharCode(i); - } - j = 0; -unclosedString: for (;;) { - while (j >= s.length) { - j = 0; - - var cl = line, cf = from; - if (!nextLine()) { - errorAt("Unclosed string.", cl, cf); - break unclosedString; - } - - if (allowNewLine) { - allowNewLine = false; - } else { - warningAt("Unclosed string.", cl, cf); - } - } - c = s.charAt(j); - if (c === x) { - character += 1; - s = s.substr(j + 1); - return it('(string)', r, x); - } - if (c < ' ') { - if (c === '\n' || c === '\r') { - break; - } - warningAt("Control character in string: {a}.", - line, character + j, s.slice(0, j)); - } else if (c === '\\') { - j += 1; - character += 1; - c = s.charAt(j); - switch (c) { - case '\\': - case '"': - case '/': - break; - case '\'': - if (jsonmode) { - warningAt("Avoid \\'.", line, character); - } - break; - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'n': - c = '\n'; - break; - case 'r': - c = '\r'; - break; - case 't': - c = '\t'; - break; - case 'u': - esc(4); - break; - case 'v': - if (jsonmode) { - warningAt("Avoid \\v.", line, character); - } - c = '\v'; - break; - case 'x': - if (jsonmode) { - warningAt("Avoid \\x-.", line, character); - } - esc(2); - break; - case '': - // last character is escape character - // always allow new line if escaped, but show - // warning if option is not set - allowNewLine = true; - if (option.multistr) { - if (jsonmode) { - warningAt("Avoid EOL escapement.", line, character); - } - c = ''; - character -= 1; - break; - } - warningAt("Bad escapement of EOL. Use option multistr if needed.", - line, character); - break; - default: - warningAt("Bad escapement.", line, character); - } - } - r += c; - character += 1; - j += 1; - } - } - - for (;;) { - if (!s) { - return it(nextLine() ? '(endline)' : '(end)', ''); - } - t = match(tx); - if (!t) { - t = ''; - c = ''; - while (s && s < '!') { - s = s.substr(1); - } - if (s) { - errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); - s = ''; - } - } else { - - // identifier - - if (c.isAlpha() || c === '_' || c === '$') { - return it('(identifier)', t); - } - - // number - - if (c.isDigit()) { - if (!isFinite(Number(t))) { - warningAt("Bad number '{a}'.", - line, character, t); - } - if (s.substr(0, 1).isAlpha()) { - warningAt("Missing space after '{a}'.", - line, character, t); - } - if (c === '0') { - d = t.substr(1, 1); - if (d.isDigit()) { - if (token.id !== '.') { - warningAt("Don't use extra leading zeros '{a}'.", - line, character, t); - } - } else if (jsonmode && (d === 'x' || d === 'X')) { - warningAt("Avoid 0x-. '{a}'.", - line, character, t); - } - } - if (t.substr(t.length - 1) === '.') { - warningAt( -"A trailing decimal point can be confused with a dot '{a}'.", line, character, t); - } - return it('(number)', t); - } - switch (t) { - - // string - - case '"': - case "'": - return string(t); - - // // comment - - case '//': - s = ''; - token.comment = true; - break; - - // /* comment - - case '/*': - for (;;) { - i = s.search(lx); - if (i >= 0) { - break; - } - if (!nextLine()) { - errorAt("Unclosed comment.", line, character); - } - } - character += i + 2; - if (s.substr(i, 1) === '/') { - errorAt("Nested comment.", line, character); - } - s = s.substr(i + 2); - token.comment = true; - break; - - // /*members /*jshint /*global - - case '/*members': - case '/*member': - case '/*jshint': - case '/*jslint': - case '/*global': - case '*/': - return { - value: t, - type: 'special', - line: line, - character: character, - from: from - }; - - case '': - break; - // / - case '/': - if (token.id === '/=') { - errorAt("A regular expression literal can be confused with '/='.", - line, from); - } - if (prereg) { - depth = 0; - captures = 0; - l = 0; - for (;;) { - b = true; - c = s.charAt(l); - l += 1; - switch (c) { - case '': - errorAt("Unclosed regular expression.", line, from); - return quit('Stopping.', line, from); - case '/': - if (depth > 0) { - warningAt("{a} unterminated regular expression " + - "group(s).", line, from + l, depth); - } - c = s.substr(0, l - 1); - q = { - g: true, - i: true, - m: true - }; - while (q[s.charAt(l)] === true) { - q[s.charAt(l)] = false; - l += 1; - } - character += l; - s = s.substr(l); - q = s.charAt(0); - if (q === '/' || q === '*') { - errorAt("Confusing regular expression.", - line, from); - } - return it('(regexp)', c); - case '\\': - c = s.charAt(l); - if (c < ' ') { - warningAt( -"Unexpected control character in regular expression.", line, from + l); - } else if (c === '<') { - warningAt( -"Unexpected escaped character '{a}' in regular expression.", line, from + l, c); - } - l += 1; - break; - case '(': - depth += 1; - b = false; - if (s.charAt(l) === '?') { - l += 1; - switch (s.charAt(l)) { - case ':': - case '=': - case '!': - l += 1; - break; - default: - warningAt( -"Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); - } - } else { - captures += 1; - } - break; - case '|': - b = false; - break; - case ')': - if (depth === 0) { - warningAt("Unescaped '{a}'.", - line, from + l, ')'); - } else { - depth -= 1; - } - break; - case ' ': - q = 1; - while (s.charAt(l) === ' ') { - l += 1; - q += 1; - } - if (q > 1) { - warningAt( -"Spaces are hard to count. Use {{a}}.", line, from + l, q); - } - break; - case '[': - c = s.charAt(l); - if (c === '^') { - l += 1; - if (option.regexp) { - warningAt("Insecure '{a}'.", - line, from + l, c); - } else if (s.charAt(l) === ']') { - errorAt("Unescaped '{a}'.", - line, from + l, '^'); - } - } - if (c === ']') { - warningAt("Empty class.", line, - from + l - 1); - } - isLiteral = false; - isInRange = false; -klass: do { - c = s.charAt(l); - l += 1; - switch (c) { - case '[': - case '^': - warningAt("Unescaped '{a}'.", - line, from + l, c); - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case '-': - if (isLiteral && !isInRange) { - isLiteral = false; - isInRange = true; - } else if (isInRange) { - isInRange = false; - } else if (s.charAt(l) === ']') { - isInRange = true; - } else { - if (option.regexdash !== (l === 2 || (l === 3 && - s.charAt(2) === '^'))) { - warningAt("Unescaped '{a}'.", - line, from + l - 1, '-'); - } - isLiteral = true; - } - break; - case ']': - if (isInRange && !option.regexdash) { - warningAt("Unescaped '{a}'.", - line, from + l - 1, '-'); - } - break klass; - case '\\': - c = s.charAt(l); - if (c < ' ') { - warningAt( -"Unexpected control character in regular expression.", line, from + l); - } else if (c === '<') { - warningAt( -"Unexpected escaped character '{a}' in regular expression.", line, from + l, c); - } - l += 1; - - // \w, \s and \d are never part of a character range - if (/[wsd]/i.test(c)) { - if (isInRange) { - warningAt("Unescaped '{a}'.", - line, from + l, '-'); - isInRange = false; - } - isLiteral = false; - } else if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case '/': - warningAt("Unescaped '{a}'.", - line, from + l - 1, '/'); - - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case '<': - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - default: - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - } - } while (c); - break; - case '.': - if (option.regexp) { - warningAt("Insecure '{a}'.", line, - from + l, c); - } - break; - case ']': - case '?': - case '{': - case '}': - case '+': - case '*': - warningAt("Unescaped '{a}'.", line, - from + l, c); - } - if (b) { - switch (s.charAt(l)) { - case '?': - case '+': - case '*': - l += 1; - if (s.charAt(l) === '?') { - l += 1; - } - break; - case '{': - l += 1; - c = s.charAt(l); - if (c < '0' || c > '9') { - warningAt( -"Expected a number and instead saw '{a}'.", line, from + l, c); - } - l += 1; - low = +c; - for (;;) { - c = s.charAt(l); - if (c < '0' || c > '9') { - break; - } - l += 1; - low = +c + (low * 10); - } - high = low; - if (c === ',') { - l += 1; - high = Infinity; - c = s.charAt(l); - if (c >= '0' && c <= '9') { - l += 1; - high = +c; - for (;;) { - c = s.charAt(l); - if (c < '0' || c > '9') { - break; - } - l += 1; - high = +c + (high * 10); - } - } - } - if (s.charAt(l) !== '}') { - warningAt( -"Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); - } else { - l += 1; - } - if (s.charAt(l) === '?') { - l += 1; - } - if (low > high) { - warningAt( -"'{a}' should not be greater than '{b}'.", line, from + l, low, high); - } - } - } - } - c = s.substr(0, l - 1); - character += l; - s = s.substr(l); - return it('(regexp)', c); - } - return it('(punctuator)', t); - - // punctuator - - case '#': - return it('(punctuator)', t); - default: - return it('(punctuator)', t); - } - } - } - } - }; - }()); - - - function addlabel(t, type) { - - if (t === 'hasOwnProperty') { - warning("'hasOwnProperty' is a really bad name."); - } - -// Define t in the current function in the current scope. - if (is_own(funct, t) && !funct['(global)']) { - if (funct[t] === true) { - if (option.latedef) - warning("'{a}' was used before it was defined.", nexttoken, t); - } else { - if (!option.shadow && type !== "exception") - warning("'{a}' is already defined.", nexttoken, t); - } - } - - funct[t] = type; - if (funct['(global)']) { - global[t] = funct; - if (is_own(implied, t)) { - if (option.latedef) - warning("'{a}' was used before it was defined.", nexttoken, t); - delete implied[t]; - } - } else { - scope[t] = funct; - } - } - - - function doOption() { - var b, obj, filter, o = nexttoken.value, t, v; - switch (o) { - case '*/': - error("Unbegun comment."); - break; - case '/*members': - case '/*member': - o = '/*members'; - if (!membersOnly) { - membersOnly = {}; - } - obj = membersOnly; - break; - case '/*jshint': - case '/*jslint': - obj = option; - filter = boolOptions; - break; - case '/*global': - obj = predefined; - break; - default: - error("What?"); - } - t = lex.token(); -loop: for (;;) { - for (;;) { - if (t.type === 'special' && t.value === '*/') { - break loop; - } - if (t.id !== '(endline)' && t.id !== ',') { - break; - } - t = lex.token(); - } - if (t.type !== '(string)' && t.type !== '(identifier)' && - o !== '/*members') { - error("Bad option.", t); - } - v = lex.token(); - if (v.id === ':') { - v = lex.token(); - if (obj === membersOnly) { - error("Expected '{a}' and instead saw '{b}'.", - t, '*/', ':'); - } - if (t.value === 'indent' && (o === '/*jshint' || o === '/*jslint')) { - b = +v.value; - if (typeof b !== 'number' || !isFinite(b) || b <= 0 || - Math.floor(b) !== b) { - error("Expected a small integer and instead saw '{a}'.", - v, v.value); - } - obj.white = true; - obj.indent = b; - } else if (t.value === 'maxerr' && (o === '/*jshint' || o === '/*jslint')) { - b = +v.value; - if (typeof b !== 'number' || !isFinite(b) || b <= 0 || - Math.floor(b) !== b) { - error("Expected a small integer and instead saw '{a}'.", - v, v.value); - } - obj.maxerr = b; - } else if (t.value === 'maxlen' && (o === '/*jshint' || o === '/*jslint')) { - b = +v.value; - if (typeof b !== 'number' || !isFinite(b) || b <= 0 || - Math.floor(b) !== b) { - error("Expected a small integer and instead saw '{a}'.", - v, v.value); - } - obj.maxlen = b; - } else if (t.value === 'validthis') { - if (funct['(global)']) { - error("Option 'validthis' can't be used in a global scope."); - } else { - if (v.value === 'true' || v.value === 'false') - obj[t.value] = v.value === 'true'; - else - error("Bad option value.", v); - } - } else if (v.value === 'true') { - obj[t.value] = true; - } else if (v.value === 'false') { - obj[t.value] = false; - } else { - error("Bad option value.", v); - } - t = lex.token(); - } else { - if (o === '/*jshint' || o === '/*jslint') { - error("Missing option value.", t); - } - obj[t.value] = false; - t = v; - } - } - if (filter) { - assume(); - } - } - - -// We need a peek function. If it has an argument, it peeks that much farther -// ahead. It is used to distinguish -// for ( var i in ... -// from -// for ( var i = ... - - function peek(p) { - var i = p || 0, j = 0, t; - - while (j <= i) { - t = lookahead[j]; - if (!t) { - t = lookahead[j] = lex.token(); - } - j += 1; - } - return t; - } - - - -// Produce the next token. It looks for programming errors. - - function advance(id, t) { - switch (token.id) { - case '(number)': - if (nexttoken.id === '.') { - warning("A dot following a number can be confused with a decimal point.", token); - } - break; - case '-': - if (nexttoken.id === '-' || nexttoken.id === '--') { - warning("Confusing minusses."); - } - break; - case '+': - if (nexttoken.id === '+' || nexttoken.id === '++') { - warning("Confusing plusses."); - } - break; - } - - if (token.type === '(string)' || token.identifier) { - anonname = token.value; - } - - if (id && nexttoken.id !== id) { - if (t) { - if (nexttoken.id === '(end)') { - warning("Unmatched '{a}'.", t, t.id); - } else { - warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", - nexttoken, id, t.id, t.line, nexttoken.value); - } - } else if (nexttoken.type !== '(identifier)' || - nexttoken.value !== id) { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, id, nexttoken.value); - } - } - - prevtoken = token; - token = nexttoken; - for (;;) { - nexttoken = lookahead.shift() || lex.token(); - if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { - return; - } - if (nexttoken.type === 'special') { - doOption(); - } else { - if (nexttoken.id !== '(endline)') { - break; - } - } - } - } - - -// This is the heart of JSHINT, the Pratt parser. In addition to parsing, it -// is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is -// like .nud except that it is only used on the first token of a statement. -// Having .fud makes it much easier to define statement-oriented languages like -// JavaScript. I retained Pratt's nomenclature. - -// .nud Null denotation -// .fud First null denotation -// .led Left denotation -// lbp Left binding power -// rbp Right binding power - -// They are elements of the parsing method called Top Down Operator Precedence. - - function expression(rbp, initial) { - var left, isArray = false; - - if (nexttoken.id === '(end)') - error("Unexpected early end of program.", token); - - advance(); - if (initial) { - anonname = 'anonymous'; - funct['(verb)'] = token.value; - } - if (initial === true && token.fud) { - left = token.fud(); - } else { - if (token.nud) { - left = token.nud(); - } else { - if (nexttoken.type === '(number)' && token.id === '.') { - warning("A leading decimal point can be confused with a dot: '.{a}'.", - token, nexttoken.value); - advance(); - return token; - } else { - error("Expected an identifier and instead saw '{a}'.", - token, token.id); - } - } - while (rbp < nexttoken.lbp) { - isArray = token.value === 'Array'; - advance(); - if (isArray && token.id === '(' && nexttoken.id === ')') - warning("Use the array literal notation [].", token); - if (token.led) { - left = token.led(left); - } else { - error("Expected an operator and instead saw '{a}'.", - token, token.id); - } - } - } - return left; - } - - -// Functions for conformance of style. - - function adjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white) { - if (left.character !== right.from && left.line === right.line) { - left.from += (left.character - left.from); - warning("Unexpected space after '{a}'.", left, left.value); - } - } - } - - function nobreak(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white && (left.character !== right.from || left.line !== right.line)) { - warning("Unexpected space before '{a}'.", right, right.value); - } - } - - function nospace(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white && !left.comment) { - if (left.line === right.line) { - adjacent(left, right); - } - } - } - - function nonadjacent(left, right) { - if (option.white) { - left = left || token; - right = right || nexttoken; - if (left.line === right.line && left.character === right.from) { - left.from += (left.character - left.from); - warning("Missing space after '{a}'.", - left, left.value); - } - } - } - - function nobreaknonadjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (!option.laxbreak && left.line !== right.line) { - warning("Bad line breaking before '{a}'.", right, right.id); - } else if (option.white) { - left = left || token; - right = right || nexttoken; - if (left.character === right.from) { - left.from += (left.character - left.from); - warning("Missing space after '{a}'.", - left, left.value); - } - } - } - - function indentation(bias) { - var i; - if (option.white && nexttoken.id !== '(end)') { - i = indent + (bias || 0); - if (nexttoken.from !== i) { - warning( -"Expected '{a}' to have an indentation at {b} instead at {c}.", - nexttoken, nexttoken.value, i, nexttoken.from); - } - } - } - - function nolinebreak(t) { - t = t || token; - if (t.line !== nexttoken.line) { - warning("Line breaking error '{a}'.", t, t.value); - } - } - - - function comma() { - if (token.line !== nexttoken.line) { - if (!option.laxbreak) { - warning("Bad line breaking before '{a}'.", token, nexttoken.id); - } - } else if (!token.comment && token.character !== nexttoken.from && option.white) { - token.from += (token.character - token.from); - warning("Unexpected space after '{a}'.", token, token.value); - } - advance(','); - nonadjacent(token, nexttoken); - } - - -// Functional constructors for making the symbols that will be inherited by -// tokens. - - function symbol(s, p) { - var x = syntax[s]; - if (!x || typeof x !== 'object') { - syntax[s] = x = { - id: s, - lbp: p, - value: s - }; - } - return x; - } - - - function delim(s) { - return symbol(s, 0); - } - - - function stmt(s, f) { - var x = delim(s); - x.identifier = x.reserved = true; - x.fud = f; - return x; - } - - - function blockstmt(s, f) { - var x = stmt(s, f); - x.block = true; - return x; - } - - - function reserveName(x) { - var c = x.id.charAt(0); - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { - x.identifier = x.reserved = true; - } - return x; - } - - - function prefix(s, f) { - var x = symbol(s, 150); - reserveName(x); - x.nud = (typeof f === 'function') ? f : function () { - this.right = expression(150); - this.arity = 'unary'; - if (this.id === '++' || this.id === '--') { - if (option.plusplus) { - warning("Unexpected use of '{a}'.", this, this.id); - } else if ((!this.right.identifier || this.right.reserved) && - this.right.id !== '.' && this.right.id !== '[') { - warning("Bad operand.", this); - } - } - return this; - }; - return x; - } - - - function type(s, f) { - var x = delim(s); - x.type = s; - x.nud = f; - return x; - } - - - function reserve(s, f) { - var x = type(s, f); - x.identifier = x.reserved = true; - return x; - } - - - function reservevar(s, v) { - return reserve(s, function () { - if (typeof v === 'function') { - v(this); - } - return this; - }); - } - - - function infix(s, f, p, w) { - var x = symbol(s, p); - reserveName(x); - x.led = function (left) { - if (!w) { - nobreaknonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - } - if (s === "in" && left.id === "!") { - warning("Confusing use of '{a}'.", left, '!'); - } - if (typeof f === 'function') { - return f(left, this); - } else { - this.left = left; - this.right = expression(p); - return this; - } - }; - return x; - } - - - function relation(s, f) { - var x = symbol(s, 100); - x.led = function (left) { - nobreaknonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - var right = expression(100); - if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { - warning("Use the isNaN function to compare with NaN.", this); - } else if (f) { - f.apply(this, [left, right]); - } - if (left.id === '!') { - warning("Confusing use of '{a}'.", left, '!'); - } - if (right.id === '!') { - warning("Confusing use of '{a}'.", right, '!'); - } - this.left = left; - this.right = right; - return this; - }; - return x; - } - - - function isPoorRelation(node) { - return node && - ((node.type === '(number)' && +node.value === 0) || - (node.type === '(string)' && node.value === '') || - (node.type === 'null' && !option.eqnull) || - node.type === 'true' || - node.type === 'false' || - node.type === 'undefined'); - } - - - function assignop(s, f) { - symbol(s, 20).exps = true; - return infix(s, function (left, that) { - var l; - that.left = left; - if (predefined[left.value] === false && - scope[left.value]['(global)'] === true) { - warning("Read only.", left); - } else if (left['function']) { - warning("'{a}' is a function.", left, left.value); - } - if (left) { - if (option.esnext && funct[left.value] === 'const') { - warning("Attempting to override '{a}' which is a constant", left, left.value); - } - if (left.id === '.' || left.id === '[') { - if (!left.left || left.left.value === 'arguments') { - warning('Bad assignment.', that); - } - that.right = expression(19); - return that; - } else if (left.identifier && !left.reserved) { - if (funct[left.value] === 'exception') { - warning("Do not assign to the exception parameter.", left); - } - that.right = expression(19); - return that; - } - if (left === syntax['function']) { - warning( -"Expected an identifier in an assignment and instead saw a function invocation.", - token); - } - } - error("Bad assignment.", that); - }, 20); - } - - - function bitwise(s, f, p) { - var x = symbol(s, p); - reserveName(x); - x.led = (typeof f === 'function') ? f : function (left) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", this, this.id); - } - this.left = left; - this.right = expression(p); - return this; - }; - return x; - } - - - function bitwiseassignop(s) { - symbol(s, 20).exps = true; - return infix(s, function (left, that) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", that, that.id); - } - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - if (left) { - if (left.id === '.' || left.id === '[' || - (left.identifier && !left.reserved)) { - expression(19); - return that; - } - if (left === syntax['function']) { - warning( -"Expected an identifier in an assignment, and instead saw a function invocation.", - token); - } - return that; - } - error("Bad assignment.", that); - }, 20); - } - - - function suffix(s, f) { - var x = symbol(s, 150); - x.led = function (left) { - if (option.plusplus) { - warning("Unexpected use of '{a}'.", this, this.id); - } else if ((!left.identifier || left.reserved) && - left.id !== '.' && left.id !== '[') { - warning("Bad operand.", this); - } - this.left = left; - return this; - }; - return x; - } - - - // fnparam means that this identifier is being defined as a function - // argument (see identifier()) - function optionalidentifier(fnparam) { - if (nexttoken.identifier) { - advance(); - if (token.reserved && !option.es5) { - // `undefined` as a function param is a common pattern to protect - // against the case when somebody does `undefined = true` and - // help with minification. More info: https://gist.github.com/315916 - if (!fnparam || token.value !== 'undefined') { - warning("Expected an identifier and instead saw '{a}' (a reserved word).", - token, token.id); - } - } - return token.value; - } - } - - // fnparam means that this identifier is being defined as a function - // argument - function identifier(fnparam) { - var i = optionalidentifier(fnparam); - if (i) { - return i; - } - if (token.id === 'function' && nexttoken.id === '(') { - warning("Missing name in function declaration."); - } else { - error("Expected an identifier and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - } - - - function reachable(s) { - var i = 0, t; - if (nexttoken.id !== ';' || noreach) { - return; - } - for (;;) { - t = peek(i); - if (t.reach) { - return; - } - if (t.id !== '(endline)') { - if (t.id === 'function') { - warning( -"Inner functions should be listed at the top of the outer function.", t); - break; - } - warning("Unreachable '{a}' after '{b}'.", t, t.value, s); - break; - } - i += 1; - } - } - - - function statement(noindent) { - var i = indent, r, s = scope, t = nexttoken; - - if (t.id === ";") { - advance(";"); - return; - } - -// Is this a labelled statement? - - if (t.identifier && !t.reserved && peek().id === ':') { - advance(); - advance(':'); - scope = Object.create(s); - addlabel(t.value, 'label'); - if (!nexttoken.labelled) { - warning("Label '{a}' on {b} statement.", - nexttoken, t.value, nexttoken.value); - } - if (jx.test(t.value + ':')) { - warning("Label '{a}' looks like a javascript url.", - t, t.value); - } - nexttoken.label = t.value; - t = nexttoken; - } - -// Parse the statement. - - if (!noindent) { - indentation(); - } - r = expression(0, true); - - // Look for the final semicolon. - if (!t.block) { - if (!option.expr && (!r || !r.exps)) { - warning("Expected an assignment or function call and instead saw an expression.", - token); - } else if (option.nonew && r.id === '(' && r.left.id === 'new') { - warning("Do not use 'new' for side effects."); - } - - if (nexttoken.id !== ';') { - if (!option.asi) { - // If this is the last statement in a block that ends on - // the same line *and* option lastsemic is on, ignore the warning. - // Otherwise, complain about missing semicolon. - if (!option.lastsemic || nexttoken.id !== '}' || - nexttoken.line !== token.line) { - warningAt("Missing semicolon.", token.line, token.character); - } - } - } else { - adjacent(token, nexttoken); - advance(';'); - nonadjacent(token, nexttoken); - } - } - -// Restore the indentation. - - indent = i; - scope = s; - return r; - } - - - function statements(startLine) { - var a = [], f, p; - - while (!nexttoken.reach && nexttoken.id !== '(end)') { - if (nexttoken.id === ';') { - warning("Unnecessary semicolon."); - advance(';'); - } else { - a.push(statement(startLine === nexttoken.line)); - } - } - return a; - } - - - /* - * read all directives - * recognizes a simple form of asi, but always - * warns, if it is used - */ - function directives() { - var i, p, pn; - - for (;;) { - if (nexttoken.id === "(string)") { - p = peek(0); - if (p.id === "(endline)") { - i = 1; - do { - pn = peek(i); - i = i + 1; - } while (pn.id === "(endline)"); - - if (pn.id !== ";") { - if (pn.id !== "(string)" && pn.id !== "(number)" && - pn.id !== "(regexp)" && pn.identifier !== true && - pn.id !== "}") { - break; - } - warning("Missing semicolon.", nexttoken); - } else { - p = pn; - } - } else if (p.id === "}") { - // directive with no other statements, warn about missing semicolon - warning("Missing semicolon.", p); - } else if (p.id !== ";") { - break; - } - - indentation(); - advance(); - if (directive[token.value]) { - warning("Unnecessary directive \"{a}\".", token, token.value); - } - - if (token.value === "use strict") { - option.newcap = true; - option.undef = true; - } - - // there's no directive negation, so always set to true - directive[token.value] = true; - - if (p.id === ";") { - advance(";"); - } - continue; - } - break; - } - } - - - /* - * Parses a single block. A block is a sequence of statements wrapped in - * braces. - * - * ordinary - true for everything but function bodies and try blocks. - * stmt - true if block can be a single statement (e.g. in if/for/while). - * isfunc - true if block is a function body - */ - function block(ordinary, stmt, isfunc) { - var a, - b = inblock, - old_indent = indent, - m, - s = scope, - t, - line, - d; - - inblock = ordinary; - if (!ordinary || !option.funcscope) scope = Object.create(scope); - nonadjacent(token, nexttoken); - t = nexttoken; - - if (nexttoken.id === '{') { - advance('{'); - line = token.line; - if (nexttoken.id !== '}') { - indent += option.indent; - while (!ordinary && nexttoken.from > indent) { - indent += option.indent; - } - - if (isfunc) { - m = {}; - for (d in directive) { - if (is_own(directive, d)) { - m[d] = directive[d]; - } - } - directives(); - - if (option.strict && funct['(context)']['(global)']) { - if (!m["use strict"] && !directive["use strict"]) { - warning("Missing \"use strict\" statement."); - } - } - } - - a = statements(line); - - if (isfunc) { - directive = m; - } - - indent -= option.indent; - if (line !== nexttoken.line) { - indentation(); - } - } else if (line !== nexttoken.line) { - indentation(); - } - advance('}', t); - indent = old_indent; - } else if (!ordinary) { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, '{', nexttoken.value); - } else { - if (!stmt || option.curly) - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, '{', nexttoken.value); - - noreach = true; - indent += option.indent; - // test indentation only if statement is in new line - a = [statement(nexttoken.line === token.line)]; - indent -= option.indent; - noreach = false; - } - funct['(verb)'] = null; - if (!ordinary || !option.funcscope) scope = s; - inblock = b; - if (ordinary && option.noempty && (!a || a.length === 0)) { - warning("Empty block."); - } - return a; - } - - - function countMember(m) { - if (membersOnly && typeof membersOnly[m] !== 'boolean') { - warning("Unexpected /*member '{a}'.", token, m); - } - if (typeof member[m] === 'number') { - member[m] += 1; - } else { - member[m] = 1; - } - } - - - function note_implied(token) { - var name = token.value, line = token.line, a = implied[name]; - if (typeof a === 'function') { - a = false; - } - if (!a) { - a = [line]; - implied[name] = a; - } else if (a[a.length - 1] !== line) { - a.push(line); - } - } - - - // Build the syntax table by declaring the syntactic elements of the language. - - type('(number)', function () { - return this; - }); - - type('(string)', function () { - return this; - }); - - syntax['(identifier)'] = { - type: '(identifier)', - lbp: 0, - identifier: true, - nud: function () { - var v = this.value, - s = scope[v], - f; - - if (typeof s === 'function') { - // Protection against accidental inheritance. - s = undefined; - } else if (typeof s === 'boolean') { - f = funct; - funct = functions[0]; - addlabel(v, 'var'); - s = funct; - funct = f; - } - - // The name is in scope and defined in the current function. - if (funct === s) { - // Change 'unused' to 'var', and reject labels. - switch (funct[v]) { - case 'unused': - funct[v] = 'var'; - break; - case 'unction': - funct[v] = 'function'; - this['function'] = true; - break; - case 'function': - this['function'] = true; - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - break; - } - } else if (funct['(global)']) { - // The name is not defined in the function. If we are in the global - // scope, then we have an undefined variable. - // - // Operators typeof and delete do not raise runtime errors even if - // the base object of a reference is null so no need to display warning - // if we're inside of typeof or delete. - if (anonname !== 'typeof' && anonname !== 'delete' && - option.undef && typeof predefined[v] !== 'boolean') { - isundef(funct, "'{a}' is not defined.", token, v); - } - note_implied(token); - } else { - // If the name is already defined in the current - // function, but not as outer, then there is a scope error. - - switch (funct[v]) { - case 'closure': - case 'function': - case 'var': - case 'unused': - warning("'{a}' used out of scope.", token, v); - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - break; - case 'outer': - case 'global': - break; - default: - // If the name is defined in an outer function, make an outer entry, - // and if it was unused, make it var. - if (s === true) { - funct[v] = true; - } else if (s === null) { - warning("'{a}' is not allowed.", token, v); - note_implied(token); - } else if (typeof s !== 'object') { - // Operators typeof and delete do not raise runtime errors even - // if the base object of a reference is null so no need to - // display warning if we're inside of typeof or delete. - if (anonname !== 'typeof' && anonname !== 'delete' && option.undef) { - isundef(funct, "'{a}' is not defined.", token, v); - } - funct[v] = true; - note_implied(token); - } else { - switch (s[v]) { - case 'function': - case 'unction': - this['function'] = true; - s[v] = 'closure'; - funct[v] = s['(global)'] ? 'global' : 'outer'; - break; - case 'var': - case 'unused': - s[v] = 'closure'; - funct[v] = s['(global)'] ? 'global' : 'outer'; - break; - case 'closure': - case 'parameter': - funct[v] = s['(global)'] ? 'global' : 'outer'; - break; - case 'label': - warning("'{a}' is a statement label.", token, v); - } - } - } - } - return this; - }, - led: function () { - error("Expected an operator and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - }; - - type('(regexp)', function () { - return this; - }); - - -// ECMAScript parser - - delim('(endline)'); - delim('(begin)'); - delim('(end)').reach = true; - delim(''); - delim('(error)').reach = true; - delim('}').reach = true; - delim(')'); - delim(']'); - delim('"').reach = true; - delim("'").reach = true; - delim(';'); - delim(':').reach = true; - delim(','); - delim('#'); - delim('@'); - reserve('else'); - reserve('case').reach = true; - reserve('catch'); - reserve('default').reach = true; - reserve('finally'); - reservevar('arguments', function (x) { - if (directive['use strict'] && funct['(global)']) { - warning("Strict violation.", x); - } - }); - reservevar('eval'); - reservevar('false'); - reservevar('Infinity'); - reservevar('NaN'); - reservevar('null'); - reservevar('this', function (x) { - if (directive['use strict'] && !option.validthis && ((funct['(statement)'] && - funct['(name)'].charAt(0) > 'Z') || funct['(global)'])) { - warning("Possible strict violation.", x); - } - }); - reservevar('true'); - reservevar('undefined'); - assignop('=', 'assign', 20); - assignop('+=', 'assignadd', 20); - assignop('-=', 'assignsub', 20); - assignop('*=', 'assignmult', 20); - assignop('/=', 'assigndiv', 20).nud = function () { - error("A regular expression literal can be confused with '/='."); - }; - assignop('%=', 'assignmod', 20); - bitwiseassignop('&=', 'assignbitand', 20); - bitwiseassignop('|=', 'assignbitor', 20); - bitwiseassignop('^=', 'assignbitxor', 20); - bitwiseassignop('<<=', 'assignshiftleft', 20); - bitwiseassignop('>>=', 'assignshiftright', 20); - bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); - infix('?', function (left, that) { - that.left = left; - that.right = expression(10); - advance(':'); - that['else'] = expression(10); - return that; - }, 30); - - infix('||', 'or', 40); - infix('&&', 'and', 50); - bitwise('|', 'bitor', 70); - bitwise('^', 'bitxor', 80); - bitwise('&', 'bitand', 90); - relation('==', function (left, right) { - var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); - - if (!eqnull && option.eqeqeq) - warning("Expected '{a}' and instead saw '{b}'.", this, '===', '=='); - else if (isPoorRelation(left)) - warning("Use '{a}' to compare with '{b}'.", this, '===', left.value); - else if (isPoorRelation(right)) - warning("Use '{a}' to compare with '{b}'.", this, '===', right.value); - - return this; - }); - relation('==='); - relation('!=', function (left, right) { - var eqnull = option.eqnull && - (left.value === 'null' || right.value === 'null'); - - if (!eqnull && option.eqeqeq) { - warning("Expected '{a}' and instead saw '{b}'.", - this, '!==', '!='); - } else if (isPoorRelation(left)) { - warning("Use '{a}' to compare with '{b}'.", - this, '!==', left.value); - } else if (isPoorRelation(right)) { - warning("Use '{a}' to compare with '{b}'.", - this, '!==', right.value); - } - return this; - }); - relation('!=='); - relation('<'); - relation('>'); - relation('<='); - relation('>='); - bitwise('<<', 'shiftleft', 120); - bitwise('>>', 'shiftright', 120); - bitwise('>>>', 'shiftrightunsigned', 120); - infix('in', 'in', 120); - infix('instanceof', 'instanceof', 120); - infix('+', function (left, that) { - var right = expression(130); - if (left && right && left.id === '(string)' && right.id === '(string)') { - left.value += right.value; - left.character = right.character; - if (!option.scripturl && jx.test(left.value)) { - warning("JavaScript URL.", left); - } - return left; - } - that.left = left; - that.right = right; - return that; - }, 130); - prefix('+', 'num'); - prefix('+++', function () { - warning("Confusing pluses."); - this.right = expression(150); - this.arity = 'unary'; - return this; - }); - infix('+++', function (left) { - warning("Confusing pluses."); - this.left = left; - this.right = expression(130); - return this; - }, 130); - infix('-', 'sub', 130); - prefix('-', 'neg'); - prefix('---', function () { - warning("Confusing minuses."); - this.right = expression(150); - this.arity = 'unary'; - return this; - }); - infix('---', function (left) { - warning("Confusing minuses."); - this.left = left; - this.right = expression(130); - return this; - }, 130); - infix('*', 'mult', 140); - infix('/', 'div', 140); - infix('%', 'mod', 140); - - suffix('++', 'postinc'); - prefix('++', 'preinc'); - syntax['++'].exps = true; - - suffix('--', 'postdec'); - prefix('--', 'predec'); - syntax['--'].exps = true; - prefix('delete', function () { - var p = expression(0); - if (!p || (p.id !== '.' && p.id !== '[')) { - warning("Variables should not be deleted."); - } - this.first = p; - return this; - }).exps = true; - - prefix('~', function () { - if (option.bitwise) { - warning("Unexpected '{a}'.", this, '~'); - } - expression(150); - return this; - }); - - prefix('!', function () { - this.right = expression(150); - this.arity = 'unary'; - if (bang[this.right.id] === true) { - warning("Confusing use of '{a}'.", this, '!'); - } - return this; - }); - prefix('typeof', 'typeof'); - prefix('new', function () { - var c = expression(155), i; - if (c && c.id !== 'function') { - if (c.identifier) { - c['new'] = true; - switch (c.value) { - case 'Object': - warning("Use the object literal notation {}.", token); - break; - case 'Number': - case 'String': - case 'Boolean': - case 'Math': - case 'JSON': - warning("Do not use {a} as a constructor.", token, c.value); - break; - case 'Function': - if (!option.evil) { - warning("The Function constructor is eval."); - } - break; - case 'Date': - case 'RegExp': - break; - default: - if (c.id !== 'function') { - i = c.value.substr(0, 1); - if (option.newcap && (i < 'A' || i > 'Z')) { - warning("A constructor name should start with an uppercase letter.", - token); - } - } - } - } else { - if (c.id !== '.' && c.id !== '[' && c.id !== '(') { - warning("Bad constructor.", token); - } - } - } else { - if (!option.supernew) - warning("Weird construction. Delete 'new'.", this); - } - adjacent(token, nexttoken); - if (nexttoken.id !== '(' && !option.supernew) { - warning("Missing '()' invoking a constructor."); - } - this.first = c; - return this; - }); - syntax['new'].exps = true; - - prefix('void').exps = true; - - infix('.', function (left, that) { - adjacent(prevtoken, token); - nobreak(); - var m = identifier(); - if (typeof m === 'string') { - countMember(m); - } - that.left = left; - that.right = m; - if (left && left.value === 'arguments' && (m === 'callee' || m === 'caller')) { - if (option.noarg) - warning("Avoid arguments.{a}.", left, m); - else if (directive['use strict']) - error('Strict violation.'); - } else if (!option.evil && left && left.value === 'document' && - (m === 'write' || m === 'writeln')) { - warning("document.write can be a form of eval.", left); - } - if (!option.evil && (m === 'eval' || m === 'execScript')) { - warning('eval is evil.'); - } - return that; - }, 160, true); - - infix('(', function (left, that) { - if (prevtoken.id !== '}' && prevtoken.id !== ')') { - nobreak(prevtoken, token); - } - nospace(); - if (option.immed && !left.immed && left.id === 'function') { - warning("Wrap an immediate function invocation in parentheses " + - "to assist the reader in understanding that the expression " + - "is the result of a function, and not the function itself."); - } - var n = 0, - p = []; - if (left) { - if (left.type === '(identifier)') { - if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { - if (left.value !== 'Number' && left.value !== 'String' && - left.value !== 'Boolean' && - left.value !== 'Date') { - if (left.value === 'Math') { - warning("Math is not a function.", left); - } else if (option.newcap) { - warning( -"Missing 'new' prefix when invoking a constructor.", left); - } - } - } - } - } - if (nexttoken.id !== ')') { - for (;;) { - p[p.length] = expression(10); - n += 1; - if (nexttoken.id !== ',') { - break; - } - comma(); - } - } - advance(')'); - nospace(prevtoken, token); - if (typeof left === 'object') { - if (left.value === 'parseInt' && n === 1) { - warning("Missing radix parameter.", left); - } - if (!option.evil) { - if (left.value === 'eval' || left.value === 'Function' || - left.value === 'execScript') { - warning("eval is evil.", left); - } else if (p[0] && p[0].id === '(string)' && - (left.value === 'setTimeout' || - left.value === 'setInterval')) { - warning( - "Implied eval is evil. Pass a function instead of a string.", left); - } - } - if (!left.identifier && left.id !== '.' && left.id !== '[' && - left.id !== '(' && left.id !== '&&' && left.id !== '||' && - left.id !== '?') { - warning("Bad invocation.", left); - } - } - that.left = left; - return that; - }, 155, true).exps = true; - - prefix('(', function () { - nospace(); - if (nexttoken.id === 'function') { - nexttoken.immed = true; - } - var v = expression(0); - advance(')', this); - nospace(prevtoken, token); - if (option.immed && v.id === 'function') { - if (nexttoken.id === '(') { - warning( -"Move the invocation into the parens that contain the function.", nexttoken); - } else { - warning( -"Do not wrap function literals in parens unless they are to be immediately invoked.", - this); - } - } - return v; - }); - - infix('[', function (left, that) { - nobreak(prevtoken, token); - nospace(); - var e = expression(0), s; - if (e && e.type === '(string)') { - if (!option.evil && (e.value === 'eval' || e.value === 'execScript')) { - warning("eval is evil.", that); - } - countMember(e.value); - if (!option.sub && ix.test(e.value)) { - s = syntax[e.value]; - if (!s || !s.reserved) { - warning("['{a}'] is better written in dot notation.", - e, e.value); - } - } - } - advance(']', that); - nospace(prevtoken, token); - that.left = left; - that.right = e; - return that; - }, 160, true); - - prefix('[', function () { - var b = token.line !== nexttoken.line; - this.first = []; - if (b) { - indent += option.indent; - if (nexttoken.from === indent + option.indent) { - indent += option.indent; - } - } - while (nexttoken.id !== '(end)') { - while (nexttoken.id === ',') { - warning("Extra comma."); - advance(','); - } - if (nexttoken.id === ']') { - break; - } - if (b && token.line !== nexttoken.line) { - indentation(); - } - this.first.push(expression(10)); - if (nexttoken.id === ',') { - comma(); - if (nexttoken.id === ']' && !option.es5) { - warning("Extra comma.", token); - break; - } - } else { - break; - } - } - if (b) { - indent -= option.indent; - indentation(); - } - advance(']', this); - return this; - }, 160); - - - function property_name() { - var id = optionalidentifier(true); - if (!id) { - if (nexttoken.id === '(string)') { - id = nexttoken.value; - advance(); - } else if (nexttoken.id === '(number)') { - id = nexttoken.value.toString(); - advance(); - } - } - return id; - } - - - function functionparams() { - var i, t = nexttoken, p = []; - advance('('); - nospace(); - if (nexttoken.id === ')') { - advance(')'); - return; - } - for (;;) { - i = identifier(true); - p.push(i); - addlabel(i, 'parameter'); - if (nexttoken.id === ',') { - comma(); - } else { - advance(')', t); - nospace(prevtoken, token); - return p; - } - } - } - - - function doFunction(i, statement) { - var f, - oldOption = option, - oldScope = scope; - - option = Object.create(option); - scope = Object.create(scope); - - funct = { - '(name)' : i || '"' + anonname + '"', - '(line)' : nexttoken.line, - '(context)' : funct, - '(breakage)' : 0, - '(loopage)' : 0, - '(scope)' : scope, - '(statement)': statement - }; - f = funct; - token.funct = funct; - functions.push(funct); - if (i) { - addlabel(i, 'function'); - } - funct['(params)'] = functionparams(); - - block(false, false, true); - scope = oldScope; - option = oldOption; - funct['(last)'] = token.line; - funct = funct['(context)']; - return f; - } - - - (function (x) { - x.nud = function () { - var b, f, i, j, p, seen = {}, t; - var prop, acc = {}; // Accessor methods - - function saveSetter(name, token) { - if (!acc[name]) { - acc[name] = {}; - } - acc[name].setter = true; - acc[name].setterToken = token; - } - - function saveGetter(name) { - if (!acc[name]) { - acc[name] = {}; - } - acc[name].getter = true; - } - - b = token.line !== nexttoken.line; - if (b) { - indent += option.indent; - if (nexttoken.from === indent + option.indent) { - indent += option.indent; - } - } - for (;;) { - if (nexttoken.id === '}') { - break; - } - if (b) { - indentation(); - } - if (nexttoken.value === 'get' && peek().id !== ':') { - advance('get'); - if (!option.es5) { - error("get/set are ES5 features."); - } - i = property_name(); - if (!i) { - error("Missing property name."); - } - saveGetter(i); - t = nexttoken; - adjacent(token, nexttoken); - f = doFunction(); - if (!option.loopfunc && funct['(loopage)']) { - warning("Don't make functions within a loop.", t); - } - p = f['(params)']; - if (p) { - warning("Unexpected parameter '{a}' in get {b} function.", t, p[0], i); - } - adjacent(token, nexttoken); - } else if (nexttoken.value === 'set' && peek().id !== ':') { - advance('set'); - if (!option.es5) { - error("get/set are ES5 features."); - } - i = property_name(); - if (!i) { - error("Missing property name."); - } - saveSetter(i, nexttoken); - seen[i] = false; - t = nexttoken; - adjacent(token, nexttoken); - f = doFunction(); - p = f['(params)']; - if (!p || p.length !== 1 || p[0] !== 'value') { - warning("Expected (value) in set {a} function.", t, i); - } - } else { - i = property_name(); - if (typeof i !== 'string') { - break; - } - advance(':'); - nonadjacent(token, nexttoken); - expression(10); - } - if (seen[i] === true) { - warning("Duplicate member '{a}'.", nexttoken, i); - } - seen[i] = true; - countMember(i); - if (nexttoken.id === ',') { - comma(); - if (nexttoken.id === ',') { - warning("Extra comma.", token); - } else if (nexttoken.id === '}' && !option.es5) { - warning("Extra comma.", token); - } - } else { - break; - } - } - if (b) { - indent -= option.indent; - indentation(); - } - advance('}', this); - - // Check for lonely setters if in the ES5 mode. - if (option.es5) { - for (prop in acc) { - if (acc.hasOwnProperty(prop) && acc[prop].setter && !acc[prop].getter) { - warning("Setter is defined without getter.", acc[prop].setterToken); - } - } - } - return this; - }; - x.fud = function () { - error("Expected to see a statement and instead saw a block.", token); - }; - }(delim('{'))); - -// This Function is called when esnext option is set to true -// it adds the `const` statement to JSHINT - - useESNextSyntax = function () { - var conststatement = stmt('const', function (prefix) { - var id, name, value; - - this.first = []; - for (;;) { - nonadjacent(token, nexttoken); - id = identifier(); - if (funct[id] === "const") { - warning("const '" + id + "' has already been declared"); - } - if (funct['(global)'] && predefined[id] === false) { - warning("Redefinition of '{a}'.", token, id); - } - addlabel(id, 'const'); - if (prefix) { - break; - } - name = token; - this.first.push(token); - - if (nexttoken.id !== "=") { - warning("const " + - "'{a}' is initialized to 'undefined'.", token, id); - } - - if (nexttoken.id === '=') { - nonadjacent(token, nexttoken); - advance('='); - nonadjacent(token, nexttoken); - if (nexttoken.id === 'undefined') { - warning("It is not necessary to initialize " + - "'{a}' to 'undefined'.", token, id); - } - if (peek(0).id === '=' && nexttoken.identifier) { - error("Constant {a} was not declared correctly.", - nexttoken, nexttoken.value); - } - value = expression(0); - name.first = value; - } - - if (nexttoken.id !== ',') { - break; - } - comma(); - } - return this; - }); - conststatement.exps = true; - }; - - var varstatement = stmt('var', function (prefix) { - // JavaScript does not have block scope. It only has function scope. So, - // declaring a variable in a block can have unexpected consequences. - var id, name, value; - - if (funct['(onevar)'] && option.onevar) { - warning("Too many var statements."); - } else if (!funct['(global)']) { - funct['(onevar)'] = true; - } - this.first = []; - for (;;) { - nonadjacent(token, nexttoken); - id = identifier(); - if (option.esnext && funct[id] === "const") { - warning("const '" + id + "' has already been declared"); - } - if (funct['(global)'] && predefined[id] === false) { - warning("Redefinition of '{a}'.", token, id); - } - addlabel(id, 'unused'); - if (prefix) { - break; - } - name = token; - this.first.push(token); - if (nexttoken.id === '=') { - nonadjacent(token, nexttoken); - advance('='); - nonadjacent(token, nexttoken); - if (nexttoken.id === 'undefined') { - warning("It is not necessary to initialize '{a}' to 'undefined'.", token, id); - } - if (peek(0).id === '=' && nexttoken.identifier) { - error("Variable {a} was not declared correctly.", - nexttoken, nexttoken.value); - } - value = expression(0); - name.first = value; - } - if (nexttoken.id !== ',') { - break; - } - comma(); - } - return this; - }); - varstatement.exps = true; - - blockstmt('function', function () { - if (inblock) { - warning("Function declarations should not be placed in blocks. " + - "Use a function expression or move the statement to the top of " + - "the outer function.", token); - - } - var i = identifier(); - if (option.esnext && funct[i] === "const") { - warning("const '" + i + "' has already been declared"); - } - adjacent(token, nexttoken); - addlabel(i, 'unction'); - doFunction(i, true); - if (nexttoken.id === '(' && nexttoken.line === token.line) { - error( -"Function declarations are not invocable. Wrap the whole function invocation in parens."); - } - return this; - }); - - prefix('function', function () { - var i = optionalidentifier(); - if (i) { - adjacent(token, nexttoken); - } else { - nonadjacent(token, nexttoken); - } - doFunction(i); - if (!option.loopfunc && funct['(loopage)']) { - warning("Don't make functions within a loop."); - } - return this; - }); - - blockstmt('if', function () { - var t = nexttoken; - advance('('); - nonadjacent(this, t); - nospace(); - expression(20); - if (nexttoken.id === '=') { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance('='); - expression(20); - } - advance(')', t); - nospace(prevtoken, token); - block(true, true); - if (nexttoken.id === 'else') { - nonadjacent(token, nexttoken); - advance('else'); - if (nexttoken.id === 'if' || nexttoken.id === 'switch') { - statement(true); - } else { - block(true, true); - } - } - return this; - }); - - blockstmt('try', function () { - var b, e, s; - - block(false); - if (nexttoken.id === 'catch') { - advance('catch'); - nonadjacent(token, nexttoken); - advance('('); - s = scope; - scope = Object.create(s); - e = nexttoken.value; - if (nexttoken.type !== '(identifier)') { - warning("Expected an identifier and instead saw '{a}'.", - nexttoken, e); - } else { - addlabel(e, 'exception'); - } - advance(); - advance(')'); - block(false); - b = true; - scope = s; - } - if (nexttoken.id === 'finally') { - advance('finally'); - block(false); - return; - } else if (!b) { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, 'catch', nexttoken.value); - } - return this; - }); - - blockstmt('while', function () { - var t = nexttoken; - funct['(breakage)'] += 1; - funct['(loopage)'] += 1; - advance('('); - nonadjacent(this, t); - nospace(); - expression(20); - if (nexttoken.id === '=') { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance('='); - expression(20); - } - advance(')', t); - nospace(prevtoken, token); - block(true, true); - funct['(breakage)'] -= 1; - funct['(loopage)'] -= 1; - return this; - }).labelled = true; - - reserve('with'); - - blockstmt('switch', function () { - var t = nexttoken, - g = false; - funct['(breakage)'] += 1; - advance('('); - nonadjacent(this, t); - nospace(); - this.condition = expression(20); - advance(')', t); - nospace(prevtoken, token); - nonadjacent(token, nexttoken); - t = nexttoken; - advance('{'); - nonadjacent(token, nexttoken); - indent += option.indent; - this.cases = []; - for (;;) { - switch (nexttoken.id) { - case 'case': - switch (funct['(verb)']) { - case 'break': - case 'case': - case 'continue': - case 'return': - case 'switch': - case 'throw': - break; - default: - // You can tell JSHint that you don't use break intentionally by - // adding a comment /* falls through */ on a line just before - // the next `case`. - if (!ft.test(lines[nexttoken.line - 2])) { - warning( - "Expected a 'break' statement before 'case'.", - token); - } - } - indentation(-option.indent); - advance('case'); - this.cases.push(expression(20)); - g = true; - advance(':'); - funct['(verb)'] = 'case'; - break; - case 'default': - switch (funct['(verb)']) { - case 'break': - case 'continue': - case 'return': - case 'throw': - break; - default: - if (!ft.test(lines[nexttoken.line - 2])) { - warning( - "Expected a 'break' statement before 'default'.", - token); - } - } - indentation(-option.indent); - advance('default'); - g = true; - advance(':'); - break; - case '}': - indent -= option.indent; - indentation(); - advance('}', t); - if (this.cases.length === 1 || this.condition.id === 'true' || - this.condition.id === 'false') { - if (!option.onecase) - warning("This 'switch' should be an 'if'.", this); - } - funct['(breakage)'] -= 1; - funct['(verb)'] = undefined; - return; - case '(end)': - error("Missing '{a}'.", nexttoken, '}'); - return; - default: - if (g) { - switch (token.id) { - case ',': - error("Each value should have its own case label."); - return; - case ':': - g = false; - statements(); - break; - default: - error("Missing ':' on a case clause.", token); - return; - } - } else { - if (token.id === ':') { - advance(':'); - error("Unexpected '{a}'.", token, ':'); - statements(); - } else { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, 'case', nexttoken.value); - return; - } - } - } - } - }).labelled = true; - - stmt('debugger', function () { - if (!option.debug) { - warning("All 'debugger' statements should be removed."); - } - return this; - }).exps = true; - - (function () { - var x = stmt('do', function () { - funct['(breakage)'] += 1; - funct['(loopage)'] += 1; - this.first = block(true); - advance('while'); - var t = nexttoken; - nonadjacent(token, t); - advance('('); - nospace(); - expression(20); - if (nexttoken.id === '=') { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance('='); - expression(20); - } - advance(')', t); - nospace(prevtoken, token); - funct['(breakage)'] -= 1; - funct['(loopage)'] -= 1; - return this; - }); - x.labelled = true; - x.exps = true; - }()); - - blockstmt('for', function () { - var s, t = nexttoken; - funct['(breakage)'] += 1; - funct['(loopage)'] += 1; - advance('('); - nonadjacent(this, t); - nospace(); - if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { - if (nexttoken.id === 'var') { - advance('var'); - varstatement.fud.call(varstatement, true); - } else { - switch (funct[nexttoken.value]) { - case 'unused': - funct[nexttoken.value] = 'var'; - break; - case 'var': - break; - default: - warning("Bad for in variable '{a}'.", - nexttoken, nexttoken.value); - } - advance(); - } - advance('in'); - expression(20); - advance(')', t); - s = block(true, true); - if (option.forin && s && (s.length > 1 || typeof s[0] !== 'object' || - s[0].value !== 'if')) { - warning("The body of a for in should be wrapped in an if statement to filter " + - "unwanted properties from the prototype.", this); - } - funct['(breakage)'] -= 1; - funct['(loopage)'] -= 1; - return this; - } else { - if (nexttoken.id !== ';') { - if (nexttoken.id === 'var') { - advance('var'); - varstatement.fud.call(varstatement); - } else { - for (;;) { - expression(0, 'for'); - if (nexttoken.id !== ',') { - break; - } - comma(); - } - } - } - nolinebreak(token); - advance(';'); - if (nexttoken.id !== ';') { - expression(20); - if (nexttoken.id === '=') { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance('='); - expression(20); - } - } - nolinebreak(token); - advance(';'); - if (nexttoken.id === ';') { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, ')', ';'); - } - if (nexttoken.id !== ')') { - for (;;) { - expression(0, 'for'); - if (nexttoken.id !== ',') { - break; - } - comma(); - } - } - advance(')', t); - nospace(prevtoken, token); - block(true, true); - funct['(breakage)'] -= 1; - funct['(loopage)'] -= 1; - return this; - } - }).labelled = true; - - - stmt('break', function () { - var v = nexttoken.value; - - if (funct['(breakage)'] === 0) - warning("Unexpected '{a}'.", nexttoken, this.value); - - if (!option.asi) - nolinebreak(this); - - if (nexttoken.id !== ';') { - if (token.line === nexttoken.line) { - if (funct[v] !== 'label') { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - this.first = nexttoken; - advance(); - } - } - reachable('break'); - return this; - }).exps = true; - - - stmt('continue', function () { - var v = nexttoken.value; - - if (funct['(breakage)'] === 0) - warning("Unexpected '{a}'.", nexttoken, this.value); - - if (!option.asi) - nolinebreak(this); - - if (nexttoken.id !== ';') { - if (token.line === nexttoken.line) { - if (funct[v] !== 'label') { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - this.first = nexttoken; - advance(); - } - } else if (!funct['(loopage)']) { - warning("Unexpected '{a}'.", nexttoken, this.value); - } - reachable('continue'); - return this; - }).exps = true; - - - stmt('return', function () { - if (this.line === nexttoken.line) { - if (nexttoken.id === '(regexp)') - warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); - - if (nexttoken.id !== ';' && !nexttoken.reach) { - nonadjacent(token, nexttoken); - if (peek().value === "=" && !option.boss) { - warningAt("Did you mean to return a conditional instead of an assignment?", - token.line, token.character + 1); - } - this.first = expression(0); - } - } else if (!option.asi) { - nolinebreak(this); // always warn (Line breaking error) - } - reachable('return'); - return this; - }).exps = true; - - - stmt('throw', function () { - nolinebreak(this); - nonadjacent(token, nexttoken); - this.first = expression(20); - reachable('throw'); - return this; - }).exps = true; - -// Superfluous reserved words - - reserve('class'); - reserve('const'); - reserve('enum'); - reserve('export'); - reserve('extends'); - reserve('import'); - reserve('super'); - - reserve('let'); - reserve('yield'); - reserve('implements'); - reserve('interface'); - reserve('package'); - reserve('private'); - reserve('protected'); - reserve('public'); - reserve('static'); - - -// Parse JSON - - function jsonValue() { - - function jsonObject() { - var o = {}, t = nexttoken; - advance('{'); - if (nexttoken.id !== '}') { - for (;;) { - if (nexttoken.id === '(end)') { - error("Missing '}' to match '{' from line {a}.", - nexttoken, t.line); - } else if (nexttoken.id === '}') { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ',') { - error("Unexpected comma.", nexttoken); - } else if (nexttoken.id !== '(string)') { - warning("Expected a string and instead saw {a}.", - nexttoken, nexttoken.value); - } - if (o[nexttoken.value] === true) { - warning("Duplicate key '{a}'.", - nexttoken, nexttoken.value); - } else if ((nexttoken.value === '__proto__' && - !option.proto) || (nexttoken.value === '__iterator__' && - !option.iterator)) { - warning("The '{a}' key may produce unexpected results.", - nexttoken, nexttoken.value); - } else { - o[nexttoken.value] = true; - } - advance(); - advance(':'); - jsonValue(); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance('}'); - } - - function jsonArray() { - var t = nexttoken; - advance('['); - if (nexttoken.id !== ']') { - for (;;) { - if (nexttoken.id === '(end)') { - error("Missing ']' to match '[' from line {a}.", - nexttoken, t.line); - } else if (nexttoken.id === ']') { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ',') { - error("Unexpected comma.", nexttoken); - } - jsonValue(); - if (nexttoken.id !== ',') { - break; - } - advance(','); - } - } - advance(']'); - } - - switch (nexttoken.id) { - case '{': - jsonObject(); - break; - case '[': - jsonArray(); - break; - case 'true': - case 'false': - case 'null': - case '(number)': - case '(string)': - advance(); - break; - case '-': - advance('-'); - if (token.character !== nexttoken.from) { - warning("Unexpected space after '-'.", token); - } - adjacent(token, nexttoken); - advance('(number)'); - break; - default: - error("Expected a JSON value.", nexttoken); - } - } - - -// The actual JSHINT function itself. - - var itself = function (s, o, g) { - var a, i, k; - JSHINT.errors = []; - JSHINT.undefs = []; - predefined = Object.create(standard); - combine(predefined, g || {}); - if (o) { - a = o.predef; - if (a) { - if (Array.isArray(a)) { - for (i = 0; i < a.length; i += 1) { - predefined[a[i]] = true; - } - } else if (typeof a === 'object') { - k = Object.keys(a); - for (i = 0; i < k.length; i += 1) { - predefined[k[i]] = !!a[k[i]]; - } - } - } - option = o; - } else { - option = {}; - } - option.indent = option.indent || 4; - option.maxerr = option.maxerr || 50; - - tab = ''; - for (i = 0; i < option.indent; i += 1) { - tab += ' '; - } - indent = 1; - global = Object.create(predefined); - scope = global; - funct = { - '(global)': true, - '(name)': '(global)', - '(scope)': scope, - '(breakage)': 0, - '(loopage)': 0 - }; - functions = [funct]; - urls = []; - stack = null; - member = {}; - membersOnly = null; - implied = {}; - inblock = false; - lookahead = []; - jsonmode = false; - warnings = 0; - lex.init(s); - prereg = true; - directive = {}; - - prevtoken = token = nexttoken = syntax['(begin)']; - assume(); - - // combine the passed globals after we've assumed all our options - combine(predefined, g || {}); - - try { - advance(); - switch (nexttoken.id) { - case '{': - case '[': - option.laxbreak = true; - jsonmode = true; - jsonValue(); - break; - default: - directives(); - if (directive["use strict"] && !option.globalstrict) { - warning("Use the function form of \"use strict\".", prevtoken); - } - - statements(); - } - advance('(end)'); - } catch (e) { - if (e) { - var nt = nexttoken || {}; - JSHINT.errors.push({ - raw : e.raw, - reason : e.message, - line : e.line || nt.line, - character : e.character || nt.from - }, null); - } - } - - for (i = 0; i < JSHINT.undefs.length; i += 1) { - k = JSHINT.undefs[i].slice(0); - scope = k.shift(); - a = k[2]; - - if (typeof scope[a] !== 'string' && typeof funct[a] !== 'string') { - warning.apply(warning, k); - } - } - - return JSHINT.errors.length === 0; - }; - - // Data summary. - itself.data = function () { - - var data = { functions: [], options: option }, fu, globals, implieds = [], f, i, j, - members = [], n, unused = [], v; - if (itself.errors.length) { - data.errors = itself.errors; - } - - if (jsonmode) { - data.json = true; - } - - for (n in implied) { - if (is_own(implied, n)) { - implieds.push({ - name: n, - line: implied[n] - }); - } - } - if (implieds.length > 0) { - data.implieds = implieds; - } - - if (urls.length > 0) { - data.urls = urls; - } - - globals = Object.keys(scope); - if (globals.length > 0) { - data.globals = globals; - } - - for (i = 1; i < functions.length; i += 1) { - f = functions[i]; - fu = {}; - for (j = 0; j < functionicity.length; j += 1) { - fu[functionicity[j]] = []; - } - for (n in f) { - if (is_own(f, n) && n.charAt(0) !== '(') { - v = f[n]; - if (v === 'unction') { - v = 'unused'; - } - if (Array.isArray(fu[v])) { - fu[v].push(n); - if (v === 'unused') { - unused.push({ - name: n, - line: f['(line)'], - 'function': f['(name)'] - }); - } - } - } - } - for (j = 0; j < functionicity.length; j += 1) { - if (fu[functionicity[j]].length === 0) { - delete fu[functionicity[j]]; - } - } - fu.name = f['(name)']; - fu.param = f['(params)']; - fu.line = f['(line)']; - fu.last = f['(last)']; - data.functions.push(fu); - } - - if (unused.length > 0) { - data.unused = unused; - } - - members = []; - for (n in member) { - if (typeof member[n] === 'number') { - data.member = member; - break; - } - } - - return data; - }; - - itself.report = function (option) { - var data = itself.data(); - - var a = [], c, e, err, f, i, k, l, m = '', n, o = [], s; - - function detail(h, array) { - var b, i, singularity; - if (array) { - o.push('
    ' + h + ' '); - array = array.sort(); - for (i = 0; i < array.length; i += 1) { - if (array[i] !== singularity) { - singularity = array[i]; - o.push((b ? ', ' : '') + singularity); - b = true; - } - } - o.push('
    '); - } - } - - - if (data.errors || data.implieds || data.unused) { - err = true; - o.push('
    Error:'); - if (data.errors) { - for (i = 0; i < data.errors.length; i += 1) { - c = data.errors[i]; - if (c) { - e = c.evidence || ''; - o.push('

    Problem' + (isFinite(c.line) ? ' at line ' + - c.line + ' character ' + c.character : '') + - ': ' + c.reason.entityify() + - '

    ' + - (e && (e.length > 80 ? e.slice(0, 77) + '...' : - e).entityify()) + '

    '); - } - } - } - - if (data.implieds) { - s = []; - for (i = 0; i < data.implieds.length; i += 1) { - s[i] = '' + data.implieds[i].name + ' ' + - data.implieds[i].line + ''; - } - o.push('

    Implied global: ' + s.join(', ') + '

    '); - } - - if (data.unused) { - s = []; - for (i = 0; i < data.unused.length; i += 1) { - s[i] = '' + data.unused[i].name + ' ' + - data.unused[i].line + ' ' + - data.unused[i]['function'] + ''; - } - o.push('

    Unused variable: ' + s.join(', ') + '

    '); - } - if (data.json) { - o.push('

    JSON: bad.

    '); - } - o.push('
    '); - } - - if (!option) { - - o.push('
    '); - - if (data.urls) { - detail("URLs
    ", data.urls, '
    '); - } - - if (data.json && !err) { - o.push('

    JSON: good.

    '); - } else if (data.globals) { - o.push('
    Global ' + - data.globals.sort().join(', ') + '
    '); - } else { - o.push('
    No new global variables introduced.
    '); - } - - for (i = 0; i < data.functions.length; i += 1) { - f = data.functions[i]; - - o.push('
    ' + f.line + '-' + - f.last + ' ' + (f.name || '') + '(' + - (f.param ? f.param.join(', ') : '') + ')
    '); - detail('Unused', f.unused); - detail('Closure', f.closure); - detail('Variable', f['var']); - detail('Exception', f.exception); - detail('Outer', f.outer); - detail('Global', f.global); - detail('Label', f.label); - } - - if (data.member) { - a = Object.keys(data.member); - if (a.length) { - a = a.sort(); - m = '
    /*members ';
    -                    l = 10;
    -                    for (i = 0; i < a.length; i += 1) {
    -                        k = a[i];
    -                        n = k.name();
    -                        if (l + n.length > 72) {
    -                            o.push(m + '
    '); - m = ' '; - l = 1; - } - l += n.length + 2; - if (data.member[k] === 1) { - n = '' + n + ''; - } - if (i < a.length - 1) { - n += ', '; - } - m += n; - } - o.push(m + '
    */
    '); - } - o.push('
    '); - } - } - return o.join(''); - }; - - itself.jshint = itself; - itself.edition = '2011-04-16'; - - return itself; -}()); - -// Make JSHINT a Node module, if possible. -if (typeof exports === 'object' && exports) - exports.JSHINT = JSHINT; diff --git a/node_modules/metrics/README.md b/node_modules/metrics/README.md deleted file mode 100644 index 1724581..0000000 --- a/node_modules/metrics/README.md +++ /dev/null @@ -1,109 +0,0 @@ -Metrics -======= - -* A node.js port of codahale's metrics library: https://github.com/codahale/metrics - -How to Use ----------- - -**Import Metrics** - -```javascript -metrics = require('./../deps/metrics') -``` - -**Start a metrics Server** - -```javascript -metricsServer = new metrics.Server(config.metricsPort || 9091); -``` - -**Create some metrics** - -```javascript - // Counters count things. They implement inc, dec, clear -var counterForThingA = new metrics.Counter - // Histograms collect a sample's distribution. They're highly configurable, - // so check out the actual implementation if the defaults don't fit your needs - // (but they probably will). This is useful for tracking how long things take - // for instance. Exponential decay histograms favor more recent data, which - // is typically what you want - , histForThingB = new metrics.createExponentialDecayHistogram() - , histForThingC = new metrics.createUniformHistogram() - // A meter tracks how often things happen. It exposes a 1 minute rate, a 5 minute rate, and a 15 minute rate - // using exponentially weighted moving averages (the same strategy that unix load average takes) - , meterForThingD = new metrics.Meter - // A Timer is a combination of a meter and a histogram. Everything you could possibly want! - , timerForThingE = new metrics.Timer; -``` - -**Add the metrics to the server** - -```javascript -metricsServer.addMetric('com.co.thingA', counterForThingA); -metricsServer.addMetric('com.co.thingB', counterForThingB); -metricsServer.addMetric('com.co.thingC', counterForThingC); -metricsServer.addMetric('com.co.thingD', counterForThingD); -``` - - -Advanced Usage --------------- -Typical production deployments have multiple node processes per server. Rather than each process exposing metrics on different ports, it makes more sense to expose the metrics from the "master" process. Writing a thin wrapper around this api to perform the process communication is trivial, with a message passing setup, the client processes could look something like this: - -```javascript -var Metric = exports = module.exports = function Metrics(messagePasser, eventType) { - this.messagePasser = messagePasser; - this.eventType = eventType; -} - -Metric.prototype.newMetric = function(type, eventType) { - this.messagePasser.sendMessage({ - method: 'createMetric' - , type: type - , eventType: eventType - }); -} -Metric.prototype.forwardMessage = function(method, args) { - this.messagePasser.sendMessage({ - method: 'updateMetric' - , metricMethod: method - , metricArgs: args - , eventType: this.eventType - }); -} - -Metric.prototype.update = function(val) { return this.forwardMessage('update', [val]); } -Metric.prototype.mark = function(n) { return this.forwardMessage('mark', [n]); } -Metric.prototype.inc = function(n) { return this.forwardMessage('inc', [n]); } -Metric.prototype.dec = function(n) { return this.forwardMessage('dec', [n]); } -Metric.prototype.clear = function() { return this.forwardMessage('clear'); } -``` - -And the server side that receives the createMetric and updateMetric rpcs could look something like this: - -```javascript -{ - createMetric: function(msg) { - if (metricsServer) { - msg.type = msg.type[0].toUpperCase() + msg.type.substring(1) - metricsServer.addMetric(msg.eventType, new metrics[msg.type]); - } - } - updateMetric: function(msg) { - if (metricsServer) { - var namespaces = msg.eventType.split('.') - , event = namespaces.pop() - , namespace = namespaces.join('.'); - var metric = metricsServer.trackedMetrics[namespace][event]; - metric[msg.metricMethod].apply(metric, msg.metricArgs); - } -} -``` - -For multiple server deployments, you have more options, but the best approach will be highly application dependent. Best of luck, and always be tracking! - -How to Collect --------------- - -Hit the server on your configured port and you'll get a json representation of your metrics. You should collect these periodically to generate timeseries to monitor the health of your application. diff --git a/node_modules/metrics/index.js b/node_modules/metrics/index.js deleted file mode 100644 index 319c9a2..0000000 --- a/node_modules/metrics/index.js +++ /dev/null @@ -1,13 +0,0 @@ -var Metrics = require('./metrics') - , Reporting = require('./reporting'); - -exports.Histogram = Metrics.Histogram; -exports.Meter = Metrics.Meter; -exports.Counter = Metrics.Counter; -exports.Timer = Metrics.Timer; - -exports.Server = Reporting.Server; -exports.Report = Reporting.Report; - -exports.version = '0.1.5'; - diff --git a/node_modules/metrics/lib/binary_heap.js b/node_modules/metrics/lib/binary_heap.js deleted file mode 100644 index 68ed13c..0000000 --- a/node_modules/metrics/lib/binary_heap.js +++ /dev/null @@ -1,136 +0,0 @@ -// From http://eloquentjavascript.net/appendix2.html, -// licensed under CCv3.0: http://creativecommons.org/licenses/by/3.0/ - -var utils = require('./utils') - -/* This acts as a ordered binary heap for any serializeable JS object or collection of such objects */ -var BinaryHeap = module.exports = function BinaryHeap(scoreFunction){ - this.content = []; - this.scoreFunction = scoreFunction; -} - -BinaryHeap.prototype = { - - clone: function() { - var heap = new BinaryHeap(this.scoreFunction); - // A little hacky, but effective. - heap.content = JSON.parse(JSON.stringify(this.content)); - return heap; - }, - - push: function(element) { - // Add the new element to the end of the array. - this.content.push(element); - // Allow it to bubble up. - this.bubbleUp(this.content.length - 1); - }, - - peek: function() { - return this.content[0]; - }, - - pop: function() { - // Store the first element so we can return it later. - var result = this.content[0]; - // Get the element at the end of the array. - var end = this.content.pop(); - // If there are any elements left, put the end element at the - // start, and let it sink down. - if (this.content.length > 0) { - this.content[0] = end; - this.sinkDown(0); - } - return result; - }, - - remove: function(node) { - var len = this.content.length; - // To remove a value, we must search through the array to find - // it. - for (var i = 0; i < len; i++) { - if (this.content[i] == node) { - // When it is found, the process seen in 'pop' is repeated - // to fill up the hole. - var end = this.content.pop(); - if (i != len - 1) { - this.content[i] = end; - if (this.scoreFunction(end) < this.scoreFunction(node)) - this.bubbleUp(i); - else - this.sinkDown(i); - } - return true; - } - } - throw new Error("Node not found."); - }, - - size: function() { - return this.content.length; - }, - - bubbleUp: function(n) { - // Fetch the element that has to be moved. - var element = this.content[n]; - // When at 0, an element can not go up any further. - while (n > 0) { - // Compute the parent element's index, and fetch it. - var parentN = Math.floor((n + 1) / 2) - 1, - parent = this.content[parentN]; - // Swap the elements if the parent is greater. - if (this.scoreFunction(element) < this.scoreFunction(parent)) { - this.content[parentN] = element; - this.content[n] = parent; - // Update 'n' to continue at the new position. - n = parentN; - } - // Found a parent that is less, no need to move it further. - else { - break; - } - } - }, - - sinkDown: function(n) { - // Look up the target element and its score. - var length = this.content.length, - element = this.content[n], - elemScore = this.scoreFunction(element); - - while(true) { - // Compute the indices of the child elements. - var child2N = (n + 1) * 2, child1N = child2N - 1; - // This is used to store the new position of the element, - // if any. - var swap = null; - // If the first child exists (is inside the array)... - if (child1N < length) { - // Look it up and compute its score. - var child1 = this.content[child1N], - child1Score = this.scoreFunction(child1); - // If the score is less than our element's, we need to swap. - if (child1Score < elemScore) - swap = child1N; - } - // Do the same checks for the other child. - if (child2N < length) { - var child2 = this.content[child2N], - child2Score = this.scoreFunction(child2); - if (child2Score < (swap == null ? elemScore : child1Score)) - swap = child2N; - } - - // If the element needs to be moved, swap it, and continue. - if (swap != null) { - this.content[n] = this.content[swap]; - this.content[swap] = element; - n = swap; - } - // Otherwise, we are done. - else { - break; - } - } - } -}; - diff --git a/node_modules/metrics/lib/utils.js b/node_modules/metrics/lib/utils.js deleted file mode 100644 index ba720f9..0000000 --- a/node_modules/metrics/lib/utils.js +++ /dev/null @@ -1,51 +0,0 @@ -/* -/* - * Mix in the properties on an object to another object - * utils.mixin(target, source, [source,] [source, etc.] [merge-flag]); - * 'merge' recurses, to merge object sub-properties together instead - * of just overwriting with the source object. - */ -exports.mixin = (function () { - var _mix = function (targ, src, merge) { - for (var p in src) { - // Don't copy stuff from the prototype - if (src.hasOwnProperty(p)) { - if (merge && - // Assumes the source property is an Object you can - // actually recurse down into - (typeof src[p] == 'object') && - (src[p] !== null) && - !(src[p] instanceof Array)) { - // Create the source property if it doesn't exist - // TODO: What if it's something weird like a String or Number? - if (typeof targ[p] == 'undefined') { - targ[p] = {}; - } - _mix(targ[p], src[p], merge); // Recurse - } - // If it's not a merge-copy, just set and forget - else { - targ[p] = src[p]; - } - } - } - }; - - return function () { - var args = Array.prototype.slice.apply(arguments), - merge = false, - targ, sources; - if (args.length > 2) { - if (typeof args[args.length - 1] == 'boolean') { - merge = args.pop(); - } - } - targ = args.shift(); - sources = args; - for (var i = 0, ii = sources.length; i < ii; i++) { - _mix(targ, sources[i], merge); - } - return targ; - }; -})(); - diff --git a/node_modules/metrics/metrics/counter.js b/node_modules/metrics/metrics/counter.js deleted file mode 100644 index ef1ffeb..0000000 --- a/node_modules/metrics/metrics/counter.js +++ /dev/null @@ -1,39 +0,0 @@ -/* -* A simple counter object -*/ - -/* JavaScript uses double-precision FP for all numeric types. - * Perhaps someday we'll have native 64-bit integers that can safely be - * transported via JSON without additional code, but not today. */ -var MAX_COUNTER_VALUE = Math.pow(2, 32); // 4294967296 - -var Counter = module.exports = function Counter() { - this.count = 0; - this.type = 'counter'; -} - -Counter.prototype.inc = function(val) { - if (!val) { val = 1; } - this.count += val; - // Wrap counter if necessary. - if (this.count > MAX_COUNTER_VALUE) { - this.count -= (MAX_COUNTER_VALUE + 1); - } -} - -Counter.prototype.dec = function(val) { - if (!val) { val = 1; } - this.count -= val; - // Prevent counter from being decremented below zero. - if (this.count < 0) { - this.count = 0; - } -} - -Counter.prototype.clear = function() { - this.count = 0; -} - -Counter.prototype.printObj = function() { - return {type: 'counter', count: this.count}; -} diff --git a/node_modules/metrics/metrics/histogram.js b/node_modules/metrics/metrics/histogram.js deleted file mode 100644 index 2f9b007..0000000 --- a/node_modules/metrics/metrics/histogram.js +++ /dev/null @@ -1,122 +0,0 @@ -var EDS = require('../stats/exponentially_decaying_sample') - , UniformSample = require('../stats/uniform_sample'); - -var DEFAULT_PERCENTILES = [0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.98, 0.99, 0.999]; - -/* -* A histogram tracks the distribution of items, given a sample type -*/ -var Histogram = module.exports = function Histogram(sample) { - this.sample = sample || new EDS(1028, 0.015); - this.min = null; - this.max = null; - this.sum = null; - // These are for the Welford algorithm for calculating running variance - // without floating-point doom. - this.varianceM = null; - this.varianceS = null; - this.count = 0; - this.type = 'histogram'; -} - -Histogram.prototype.clear = function() { - this.sample.clear(); - this.min = null; - this.max = null; - this.sum = null; - this.varianceM = null; - this.varianceS = null; - this.count = 0; -} - -// timestamp param primarily used for testing -Histogram.prototype.update = function(val, timestamp) { - this.count++; - this.sample.update(val, timestamp); - if (this.max === null) { - this.max = val; - } else { - this.max = val > this.max ? val : this.max; - } - if (this.min === null) { - this.min = val; - } else { - this.min = val < this.min ? val : this.min; - } - this.sum = (this.sum === null) ? val : this.sum + val; - this.updateVariance(val); -} - -Histogram.prototype.updateVariance = function(val) { - var oldVM = this.varianceM - , oldVS = this.varianceS; - if (this.count == 1) { - this.varianceM = val; - } else { - this.varianceM = oldVM + (val - oldVM) / this.count; - this.varianceS = oldVS + (val - oldVM) * (val - this.varianceM); - } -} - -// Pass an array of percentiles, e.g. [0.5, 0.75, 0.9, 0.99] -Histogram.prototype.percentiles = function(percentiles) { - if (!percentiles) { - percentiles = DEFAULT_PERCENTILES; - } - var values = this.sample.getValues().map(function(v){ return parseFloat(v);}).sort(function(a,b){ return a-b;}) - , scores = {} - , percentile - , pos - , lower - , upper; - for (var i = 0; i < percentiles.length; i++) { - pos = percentiles[i] * (values.length + 1); - percentile = percentiles[i]; - if (pos < 1) { scores[percentile] = values[0]; } - else if (pos >= values.length) { scores[percentile] = values[values.length - 1]; } - else { - lower = values[Math.floor(pos) - 1]; - upper = values[Math.ceil(pos) - 1]; - scores[percentile] = lower + (pos - Math.floor(pos)) * (upper - lower); - } - } - return scores; -} - -Histogram.prototype.variance = function() { - return this.count < 1 ? null : this.varianceS / (this.count - 1); -} - -Histogram.prototype.mean = function() { - return this.count == 0 ? null : this.varianceM; -} - -Histogram.prototype.stdDev = function() { - return this.count < 1 ? null : Math.sqrt(this.variance()); -} - -Histogram.prototype.values = function() { - return this.sample.getValues(); -} - -Histogram.prototype.printObj = function() { - var percentiles = this.percentiles(); - return { - type: 'histogram' - , min: this.min - , max: this.max - , sum: this.sum - , variance: this.variance() - , mean: this.mean() - , std_dev: this.stdDev() - , count: this.count - , median: percentiles[0.5] - , p75: percentiles[0.75] - , p95: percentiles[0.95] - , p99: percentiles[0.99] - , p999: percentiles[0.999]}; -} - -module.exports.createExponentialDecayHistogram = function(size, alpha) { return new Histogram(new EDS((size || 1028), (alpha || 0.015))); }; -module.exports.createUniformHistogram = function(size) { return new Histogram(new UniformSample((size || 1028))); }; -module.exports.DEFAULT_PERCENTILES = DEFAULT_PERCENTILES; diff --git a/node_modules/metrics/metrics/index.js b/node_modules/metrics/metrics/index.js deleted file mode 100644 index 189e718..0000000 --- a/node_modules/metrics/metrics/index.js +++ /dev/null @@ -1,6 +0,0 @@ - -exports.Counter = require('./counter'); -exports.Histogram = require('./histogram'); -exports.Meter = require('./meter'); -exports.Timer = require('./timer'); - diff --git a/node_modules/metrics/metrics/meter.js b/node_modules/metrics/metrics/meter.js deleted file mode 100644 index f6320eb..0000000 --- a/node_modules/metrics/metrics/meter.js +++ /dev/null @@ -1,61 +0,0 @@ -var EWMA = require('../stats/exponentially_weighted_moving_average.js'); -/* -* -*/ -var Meter = module.exports = function Meter() { - this.m1Rate = EWMA.createM1EWMA(); - this.m5Rate = EWMA.createM5EWMA(); - this.m15Rate = EWMA.createM15EWMA(); - this.count = 0; - this.startTime = (new Date).getTime(); - this.type = 'meter'; -} - -// Mark the occurence of n events -Meter.prototype.mark = function(n) { - if (!n) { n = 1; } - this.count += n; - this.m1Rate.update(n); - this.m5Rate.update(n); - this.m15Rate.update(n); -} - -Meter.prototype.rates = function() { - return {1: this.oneMinuteRate() - , 5: this.fiveMinuteRate() - , 15: this.fifteenMinuteRate() - , mean: this.meanRate()}; -} - -// Rates are per second -Meter.prototype.fifteenMinuteRate = function() { - return this.m15Rate.rate(); -} - -Meter.prototype.fiveMinuteRate = function() { - return this.m5Rate.rate(); -} - -Meter.prototype.oneMinuteRate = function() { - return this.m1Rate.rate(); -} - -Meter.prototype.meanRate = function() { - return this.count / ((new Date).getTime() - this.startTime) * 1000; -} - -Meter.prototype.printObj = function() { - return {type: 'meter' - , count: this.count - , m1: this.oneMinuteRate() - , m5: this.fiveMinuteRate() - , m15: this.fifteenMinuteRate() - , mean: this.meanRate() - , unit: 'seconds'}; -} - -Meter.prototype.tick = function(){ - this.m1Rate.tick(); - this.m5Rate.tick(); - this.m15Rate.tick(); -} diff --git a/node_modules/metrics/metrics/timer.js b/node_modules/metrics/metrics/timer.js deleted file mode 100644 index 897da6b..0000000 --- a/node_modules/metrics/metrics/timer.js +++ /dev/null @@ -1,41 +0,0 @@ -var Meter = require('./meter'); -Histogram = require('./histogram') -ExponentiallyDecayingSample = require('../stats/exponentially_decaying_sample'); -/* -* Basically a timer tracks the rate of events and histograms the durations -*/ -var Timer = module.exports = function Timer() { - this.meter = new Meter(); - this.histogram = new Histogram(new ExponentiallyDecayingSample(1028, 0.015)); - this.clear(); - this.type = 'timer'; -} - -Timer.prototype.update = function(duration) { - this.histogram.update(duration); - this.meter.mark(); -} - -// delegate these to histogram -Timer.prototype.clear = function() { return this.histogram.clear(); } -Timer.prototype.count = function() { return this.histogram.count; } -Timer.prototype.min = function() { return this.histogram.min; } -Timer.prototype.max = function() { return this.histogram.max; } -Timer.prototype.mean = function() { return this.histogram.mean(); } -Timer.prototype.stdDev = function() { return this.histogram.stdDev(); } -Timer.prototype.percentiles = function(percentiles) { return this.histogram.percentiles(percentiles); } -Timer.prototype.values = function() { return this.histogram.values(); } - -// delegate these to meter -Timer.prototype.oneMinuteRate = function() { return this.meter.oneMinuteRate(); } -Timer.prototype.fiveMinuteRate = function() { return this.meter.fiveMinuteRate(); } -Timer.prototype.fifteenMinuteRate = function() { return this.meter.fifteenMinuteRate(); } -Timer.prototype.meanRate = function() { return this.meter.meanRate(); } -Timer.prototype.tick = function() { this.meter.tick(); } // primarily for testing - -Timer.prototype.printObj = function() { - return {type: 'timer' - , duration: this.histogram.printObj() - , rate: this.meter.printObj()}; -} - diff --git a/node_modules/metrics/package.json b/node_modules/metrics/package.json deleted file mode 100644 index 529e9ca..0000000 --- a/node_modules/metrics/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "metrics", - "description": "A node.js port of Coda Hale's metrics library. In use at Yammer.", - "version": "0.1.6", - "repository": { - "type": "git", - "url": "git://github.com/mikejihbe/metrics.git" - }, - "author": "Mike Ihbe (mikeihbe.com)", - "directories": { - "lib": "." - }, - "engines": { - "node": ">=0.4.x" - }, - "dependencies": {}, - "devDependencies": {} -} diff --git a/node_modules/metrics/reporting/index.js b/node_modules/metrics/reporting/index.js deleted file mode 100644 index c38f4c0..0000000 --- a/node_modules/metrics/reporting/index.js +++ /dev/null @@ -1,2 +0,0 @@ -exports.Report = require('./report'); -exports.Server = require('./server'); diff --git a/node_modules/metrics/reporting/report.js b/node_modules/metrics/reporting/report.js deleted file mode 100644 index 8356dcf..0000000 --- a/node_modules/metrics/reporting/report.js +++ /dev/null @@ -1,29 +0,0 @@ -/** -* trackedMetrics is an object with eventTypes as keys and metrics object as values. -*/ -var Report = module.exports = function (trackedMetrics){ - this.trackedMetrics = trackedMetrics || {}; -} - -Report.prototype.addMetric = function(eventName, metric) { - var namespaces = eventName.split('.') - , event = namespaces.pop() - , namespace = namespaces.join('.'); - if (!this.trackedMetrics[namespace]) { - this.trackedMetrics[namespace] = {}; - } - if(!this.trackedMetrics[namespace][event]) { - this.trackedMetrics[namespace][event] = metric; - } -} - -Report.prototype.summary = function (){ - var metricsObj = {}; - for (namespace in this.trackedMetrics) { - metricsObj[namespace] = {}; - for (event in this.trackedMetrics[namespace]) { - metricsObj[namespace][event] = this.trackedMetrics[namespace][event].printObj(); - } - } - return metricsObj; -} diff --git a/node_modules/metrics/reporting/server.js b/node_modules/metrics/reporting/server.js deleted file mode 100644 index 26e85fc..0000000 --- a/node_modules/metrics/reporting/server.js +++ /dev/null @@ -1,29 +0,0 @@ -var http = require('http') - , Report = require('./report'); - - -/** - * This server will print the object upon request. The user should update the metrics - * as normal within their application. - */ -var Server = module.exports = function Server(port, trackedMetrics) { - var self = this; - this.report = new Report(trackedMetrics); - - this.server = http.createServer(function (req, res) { - if (req.url.match(/^\/metrics/)) { - res.writeHead(200, {'Content-Type': 'application/json'}); - res.end(JSON.stringify(self.report.summary())); - } else { - res.writeHead(404, {'Content-Type': 'text/plain'}); - res.end('Try hitting /metrics instead'); - } - }).listen(port, "127.0.0.1"); -} - -/** - * Adds a metric to be tracked by this server - */ -Server.prototype.addMetric = function (){ - this.report.addMetric.apply(this.report, arguments); -} diff --git a/node_modules/metrics/stats/exponentially_decaying_sample.js b/node_modules/metrics/stats/exponentially_decaying_sample.js deleted file mode 100644 index 7c1c970..0000000 --- a/node_modules/metrics/stats/exponentially_decaying_sample.js +++ /dev/null @@ -1,97 +0,0 @@ -var Sample = require('./sample') - , BinaryHeap = require('../lib/binary_heap') - , util = require('util') - , utils = require('../lib/utils'); - -/* - * Take an exponentially decaying sample of size size of all values - */ -var RESCALE_THRESHOLD = 60 * 60 * 1000; // 1 hour in milliseconds - -var ExponentiallyDecayingSample = module.exports = function ExponentiallyDecayingSample(size, alpha) { - this.limit = size; - this.alpha = alpha; - this.clear(); -} - -ExponentiallyDecayingSample.prototype = new Sample(); - -// This is a relatively expensive operation -ExponentiallyDecayingSample.prototype.getValues = function() { - var values = [] - , heap = this.values.clone(); - while(elt = heap.pop()) { - values.push(elt.val); - } - return values; -} - -ExponentiallyDecayingSample.prototype.size = function() { - return this.values.size(); -} - -ExponentiallyDecayingSample.prototype.newHeap = function() { - return new BinaryHeap(function(obj){return obj.priority;}); -} - -ExponentiallyDecayingSample.prototype.now = function() { - return (new Date()).getTime(); -} - -ExponentiallyDecayingSample.prototype.tick = function() { - return this.now() / 1000; -} - -ExponentiallyDecayingSample.prototype.clear = function() { - this.values = this.newHeap(); - this.count = 0; - this.startTime = this.tick(); - this.nextScaleTime = this.now() + RESCALE_THRESHOLD; -} - -/* -* timestamp in milliseconds -*/ -ExponentiallyDecayingSample.prototype.update = function(val, timestamp) { - // Convert timestamp to seconds - if (timestamp == undefined) { - timestamp = this.tick(); - } else { - timestamp = timestamp / 1000; - } - var priority = this.weight(timestamp - this.startTime) / Math.random() - , value = {val: val, priority: priority}; - if (this.count < this.limit) { - this.count += 1; - this.values.push(value); - } else { - var first = this.values.peek(); - if (first.priority < priority) { - this.values.push(value); - this.values.pop(); - } - } - - if (this.now() > this.nextScaleTime) { - this.rescale(this.now(), this.nextScaleTime); - } -} - -ExponentiallyDecayingSample.prototype.weight = function(time) { - return Math.exp(this.alpha * time); -} - -// now: parameter primarily used for testing rescales -ExponentiallyDecayingSample.prototype.rescale = function(now) { - this.nextScaleTime = this.now() + RESCALE_THRESHOLD; - var oldContent = this.values.content - , newContent = [] - , elt - , oldStartTime = this.startTime; - this.startTime = (now && now / 1000) || this.tick(); - // Downscale every priority by the same factor. Order is unaffected, which is why we're avoiding the cost of popping. - for(var i = 0; i < oldContent.length; i++) { - newContent.push({val: oldContent[i].val, priority: oldContent[i].priority * Math.exp(-this.alpha * (this.startTime - oldStartTime))}); - } - this.values.content = newContent; -} diff --git a/node_modules/metrics/stats/exponentially_weighted_moving_average.js b/node_modules/metrics/stats/exponentially_weighted_moving_average.js deleted file mode 100644 index 2bde219..0000000 --- a/node_modules/metrics/stats/exponentially_weighted_moving_average.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Exponentially weighted moving average. - * Args: - * - alpha: - * - interval: time in milliseconds - */ - -var M1_ALPHA = 1 - Math.exp(-5/60); -var M5_ALPHA = 1 - Math.exp(-5/60/5); -var M15_ALPHA = 1 - Math.exp(-5/60/15); - -var ExponentiallyWeightedMovingAverage = EWMA = module.exports = function ExponentiallyWeightedMovingAverage(alpha, interval) { - var self = this; - this.alpha = alpha; - this.interval = interval || 5000; - this.initialized = false; - this.currentRate = 0.0; - this.uncounted = 0; - if (interval) { - this.tickInterval = setInterval(function(){ self.tick(); }, interval); - } -} - -ExponentiallyWeightedMovingAverage.prototype.update = function(n) { - this.uncounted += (n || 1); -} - -/* - * Update our rate measurements every interval - */ -ExponentiallyWeightedMovingAverage.prototype.tick = function() { - var instantRate = this.uncounted / this.interval; - this.uncounted = 0; - - if(this.initialized) { - this.currentRate += this.alpha * (instantRate - this.currentRate); - } else { - this.currentRate = instantRate; - this.initialized = true; - } -} - -/* - * Return the rate per second - */ -ExponentiallyWeightedMovingAverage.prototype.rate = function() { - return this.currentRate * 1000; -} - -module.exports.createM1EWMA = function(){ return new EWMA(M1_ALPHA, 5000); } -module.exports.createM5EWMA = function(){ return new EWMA(M5_ALPHA, 5000); } -module.exports.createM15EWMA = function(){ return new EWMA(M15_ALPHA, 5000); } diff --git a/node_modules/metrics/stats/sample.js b/node_modules/metrics/stats/sample.js deleted file mode 100644 index 1de18b8..0000000 --- a/node_modules/metrics/stats/sample.js +++ /dev/null @@ -1,12 +0,0 @@ -var Sample = module.exports = function Sample() { - this.values = []; - this.count = 0; -} -var Sample = module.exports = function Sample() {} -Sample.prototype.init = function(){ this.clear(); } -Sample.prototype.update = function(val){ this.values.push(val); }; -Sample.prototype.clear = function(){ this.values = []; this.count = 0; }; -Sample.prototype.size = function(){ return this.values.length;}; -Sample.prototype.print = function(){console.log(this.values);} -Sample.prototype.getValues = function(){ return this.values; } - diff --git a/node_modules/metrics/stats/uniform_sample.js b/node_modules/metrics/stats/uniform_sample.js deleted file mode 100644 index a45d29c..0000000 --- a/node_modules/metrics/stats/uniform_sample.js +++ /dev/null @@ -1,26 +0,0 @@ -var utils = require('../lib/utils'); -var Sample = require('./sample'); - -/* - * Take a uniform sample of size size for all values - */ -var UniformSample = module.exports = function UniformSample(size) { - this.limit = size; - this.count = 0; - this.init(); -} - -UniformSample.prototype = new Sample(); - -UniformSample.prototype.update = function(val) { - this.count++; - if (this.size() < this.limit) { - //console.log("Adding "+val+" to values."); - this.values.push(val); - } else { - var rand = parseInt(Math.random() * this.count); - if (rand < this.limit) { - this.values[rand] = val; - } - } -} diff --git a/node_modules/metrics/tests/histogram.js b/node_modules/metrics/tests/histogram.js deleted file mode 100644 index 56e6455..0000000 --- a/node_modules/metrics/tests/histogram.js +++ /dev/null @@ -1,39 +0,0 @@ -var Histogram = require('../metrics/histogram'); - -var test = function(callback){ - console.log("\nCreating a new histogram"); - var edsHist = Histogram.createExponentialDecayHistogram(5000) - , unifHist = Histogram.createUniformHistogram(5000) - , time = (new Date()).getTime(); - - console.log("Seeding histograms with values 1-10000, evenly distributed"); - - for(var i = 0; i < 10000; i++) { - edsHist.update(i, time + ((2+i) * 60*60*1000 / 10000)); - unifHist.update(i); - } - - console.log("Uniform Expected Percentiles: " + JSON.stringify(Histogram.DEFAULT_PERCENTILES.map(function(v){return v * 10000;}))); - console.log(unifHist.percentiles()); - console.log("Uniform Expected Mean: 5000.5"); - console.log("Uniform mean: " + unifHist.mean()); - console.log("Uniform Expected Variance: 8333333.25"); - console.log("Uniform variance: " + unifHist.variance()); - console.log("Uniform Expected stdDev: 2886.75133151437"); - console.log("Uniform stdDev: " + unifHist.stdDev()); - - console.log("Exponential decay: "); - console.log(edsHist.percentiles()); - - if (typeof callback == 'function') { - callback(); - } -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} - - diff --git a/node_modules/metrics/tests/meter.js b/node_modules/metrics/tests/meter.js deleted file mode 100644 index 590317a..0000000 --- a/node_modules/metrics/tests/meter.js +++ /dev/null @@ -1,31 +0,0 @@ -var Meter = require('../metrics/meter'); - -var test = function(callback){ - console.log("\nCreating a new meter, updating 10 times / sec for 30 secs"); - var meter = new Meter(600) - , n = 0; - var updateInterval = setInterval(function(){ - meter.mark(1); - n += 1; - if (n % 10 == 0) { - process.stdout.write(".") - } - }, 100); - setTimeout(function(){ - clearInterval(updateInterval); - console.log('Expected rate: 10/sec'); - console.log(meter.rates()); - }, 30000); - - - if (typeof callback == 'function') { - callback(); - } -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} - diff --git a/node_modules/metrics/tests/test_all.js b/node_modules/metrics/tests/test_all.js deleted file mode 100644 index 5b8ab7b..0000000 --- a/node_modules/metrics/tests/test_all.js +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Returns a function that is the composition of a list of functions, - * each consuming the return value of the function that follows. - */ -var slice = Array.prototype.slice; -var compose = function() { - var funcs = slice.call(arguments); - return function() { - var args = slice.call(arguments); - for (var i=funcs.length-1; i >= 0; i--) { - args = [funcs[i].apply(this, args)]; - } - return args[0]; - }; -}; - -compose( - require('./test_exponentially_weighted_moving_average') -, require('./test_exponentially_decaying_sample') -, require('./test_uniform_sample') -, require('./meter') -, require('./histogram') -, require('./timer') -)(); diff --git a/node_modules/metrics/tests/test_exponentially_decaying_sample.js b/node_modules/metrics/tests/test_exponentially_decaying_sample.js deleted file mode 100644 index 77a3e38..0000000 --- a/node_modules/metrics/tests/test_exponentially_decaying_sample.js +++ /dev/null @@ -1,45 +0,0 @@ -var ExponentiallyDecayingSample = require('../stats/exponentially_decaying_sample.js') - , eds = new ExponentiallyDecayingSample(1000, 0.015); - -var test = function(callback) { - eds.clear(); - - var time = (new Date()).getTime() - , interval = 60 * 60 * 1000 / 100; - for(var i = 0; i < 100; i++) { - for(var j = 0; j < 100; j++) { - eds.update(i, time + i * interval); - } - } - - function printSample(eds) { - var valueCounts = {} - , values = eds.getValues(); - - for(var i = 0; i < eds.size(); i++) { - if (valueCounts[values[i].val]) { - valueCounts[values[i].val]++; - } else { - valueCounts[values[i].val] = 1; - } - } - return valueCounts; - } - - console.log("This is an exponential distribution:"); - console.log(printSample(eds)); - - eds.rescale(time + 100*interval); - - console.log("This is after rescaling"); - console.log(eds.getValues()); - if (typeof callback == 'function') { - callback(); - } -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} \ No newline at end of file diff --git a/node_modules/metrics/tests/test_exponentially_weighted_moving_average.js b/node_modules/metrics/tests/test_exponentially_weighted_moving_average.js deleted file mode 100644 index f89fc5e..0000000 --- a/node_modules/metrics/tests/test_exponentially_weighted_moving_average.js +++ /dev/null @@ -1,25 +0,0 @@ -var ExponentiallyWeightedMovingAverage = require('../stats/exponentially_weighted_moving_average'); -var exponentially_weighted_moving_average = new ExponentiallyWeightedMovingAverage.createM1EWMA(); - -var test = function (callback) { - console.log("\nTesting ExponentiallyWeightedMovingAverage\n"); - console.log("Sending updates every 100 milliseconds for 30 seconds."); - - var updateInterval = setInterval(function(){ - exponentially_weighted_moving_average.update(); - }, 100); - setTimeout(function(){ - clearInterval(updateInterval); - console.log("\n\nExpected Average: 10"); - console.log("Exponentially Weighted Moving Average: "+exponentially_weighted_moving_average.rate()+"\n"); - if (typeof callback == 'function') { - callback(); - } - }, 30000); -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} diff --git a/node_modules/metrics/tests/test_uniform_sample.js b/node_modules/metrics/tests/test_uniform_sample.js deleted file mode 100644 index 8d5a871..0000000 --- a/node_modules/metrics/tests/test_uniform_sample.js +++ /dev/null @@ -1,26 +0,0 @@ -var UniformSample = require('../stats/uniform_sample'); - -var test = function(callback){ - console.log("\nCreating a new UniformSample with a limit of 600."); - var uniform_sample = new UniformSample(600); - console.log("Sending 10000 updates to the UniformSample.") - for (var i = 0; i<10000; i++) { - uniform_sample.update(i); - } - var sum = 0; - for (var k in uniform_sample.values) { - sum += uniform_sample.values[k]; - } - var mean = sum / uniform_sample.values.length; - console.log("\nAverage of Sample: "+mean); - console.log("Average of 'real data': 5000\n"); - if (typeof callback == 'function') { - callback(); - } -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} \ No newline at end of file diff --git a/node_modules/metrics/tests/timer.js b/node_modules/metrics/tests/timer.js deleted file mode 100644 index db26768..0000000 --- a/node_modules/metrics/tests/timer.js +++ /dev/null @@ -1,31 +0,0 @@ -var Timer = require('../metrics/timer'); - -var test = function(callback){ - console.log("\nCreating a new timer, updating 10 times / sec for 30 secs"); - var timer = new Timer(); - - for(var i = 0; i < 10000; i++) { - timer.update(i); - } - timer.tick(); - console.log(timer.count()); - console.log(timer.min()); - console.log(timer.max()); - console.log(timer.mean()); - console.log(timer.stdDev()); - console.log(timer.percentiles()); - console.log(timer.oneMinuteRate()); - console.log(timer.fiveMinuteRate()); - console.log(timer.fifteenMinuteRate()); - console.log(timer.meanRate()); - if (typeof callback == 'function') { - callback(); - } -} - -if (module.parent) { - module.exports = test; -} else { - test(); -} - diff --git a/node_modules/mocha/.npmignore b/node_modules/mocha/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/mocha/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/mocha/.travis.yml b/node_modules/mocha/.travis.yml deleted file mode 100644 index 381c985..0000000 --- a/node_modules/mocha/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 \ No newline at end of file diff --git a/node_modules/mocha/History.md b/node_modules/mocha/History.md deleted file mode 100644 index 6711efe..0000000 --- a/node_modules/mocha/History.md +++ /dev/null @@ -1,98 +0,0 @@ - -0.0.8 / 2011-11-25 -================== - - * Fixed: use `Runner#total` for accurate reporting - -0.0.7 / 2011-11-25 -================== - - * Added `Hook` - * Added `Runnable` - * Changed: `Test` is `Runnable` - * Fixed global leak reporting in hooks - * Fixed: > 2 calls to done() only report the error once - * Fixed: clear timer on failure. Closes #80 - -0.0.6 / 2011-11-25 -================== - - * Fixed return on immediate async error. Closes #80 - -0.0.5 / 2011-11-24 -================== - - * Fixed: make mocha.opts whitespace less picky [kkaefer] - -0.0.4 / 2011-11-24 -================== - - * Added `--interfaces` - * Added `--reporters` - * Added `-c, --colors`. Closes #69 - * Fixed hook timeouts - -0.0.3 / 2011-11-23 -================== - - * Added `-C, --no-colors` to explicitly disable - * Added coffee-script support - -0.0.2 / 2011-11-22 -================== - - * Fixed global leak detection due to Safari bind() change - * Fixed: escape html entities in Doc reporter - * Fixed: escape html entities in HTML reporter - * Fixed pending test support for HTML reporter. Closes #66 - -0.0.1 / 2011-11-22 -================== - - * Added `--timeout` second shorthand support, ex `--timeout 3s`. - * Fixed "test end" event for uncaughtExceptions. Closes #61 - -0.0.1-alpha6 / 2011-11-19 -================== - - * Added travis CI support (needs enabling when public) - * Added preliminary browser support - * Added `make mocha.css` target. Closes #45 - * Added stack trace to TAP errors. Closes #52 - * Renamed tearDown to teardown. Closes #49 - * Fixed: cascading hooksc. Closes #30 - * Fixed some colors for non-tty - * Fixed errors thrown in sync test-cases due to nextTick - * Fixed Base.window.width... again give precedence to 0.6.x - -0.0.1-alpha5 / 2011-11-17 -================== - - * Added `doc` reporter. Closes #33 - * Added suite merging. Closes #28 - * Added TextMate bundle and `make tm`. Closes #20 - -0.0.1-alpha4 / 2011-11-15 -================== - - * Fixed getWindowSize() for 0.4.x - -0.0.1-alpha3 / 2011-11-15 -================== - - * Added `-s, --slow ` to specify "slow" test threshold - * Added `mocha-debug(1)` - * Added `mocha.opts` support. Closes #31 - * Added: default [files] to _test/*.js_ - * Added protection against multiple calls to `done()`. Closes #35 - * Changed: bright yellow for slow Dot reporter tests - -0.0.1-alpha1 / 2011-11-08 -================== - - * Missed this one :) - -0.0.1-alpha1 / 2011-11-08 -================== - - * Initial release diff --git a/node_modules/mocha/Makefile b/node_modules/mocha/Makefile deleted file mode 100644 index 8c08136..0000000 --- a/node_modules/mocha/Makefile +++ /dev/null @@ -1,79 +0,0 @@ - -REPORTER = dot -TM_DEST = ~/Library/Application\ Support/TextMate/Bundles -TM_BUNDLE = JavaScript\ mocha.tmbundle -SRC = $(shell find lib -name "*.js" -type f) - -all: mocha.js mocha.css - -mocha.css: test/browser/style.css - cp -f $< $@ - -mocha.js: $(SRC) - @node support/compile $^ - @cat support/tail.js >> mocha.js - -clean: - rm -f mocha.js - -test: test-unit - -test-all: test-bdd test-tdd test-exports test-unit test-grep - -test-unit: - @./bin/mocha \ - --reporter $(REPORTER) - -test-bdd: - @./bin/mocha \ - --reporter $(REPORTER) \ - --ui bdd \ - test/interfaces/bdd - -test-tdd: - @./bin/mocha \ - --reporter $(REPORTER) \ - --ui tdd \ - test/interfaces/tdd - -test-exports: - @./bin/mocha \ - --reporter $(REPORTER) \ - --ui exports \ - test/interfaces/exports - -test-grep: - @./bin/mocha \ - --reporter $(REPORTER) \ - --grep fast \ - test/misc/grep - -non-tty: - @./bin/mocha \ - --reporter dot \ - test/interfaces/bdd 2>&1 > /tmp/dot.out - - @echo dot: - @cat /tmp/dot.out - - @./bin/mocha \ - --reporter list \ - test/interfaces/bdd 2>&1 > /tmp/list.out - - @echo list: - @cat /tmp/list.out - - @./bin/mocha \ - --reporter spec \ - test/interfaces/bdd 2>&1 > /tmp/spec.out - - @echo spec: - @cat /tmp/spec.out - -watch: - watch --interval=1 $(MAKE) mocha.js - -tm: - cp -fr editors/$(TM_BUNDLE) $(TM_DEST)/$(TM_BUNDLE) - -.PHONY: watch test test-all test-bdd test-tdd test-exports test-unit non-tty test-grep tm clean \ No newline at end of file diff --git a/node_modules/mocha/Readme.md b/node_modules/mocha/Readme.md deleted file mode 100644 index 026e495..0000000 --- a/node_modules/mocha/Readme.md +++ /dev/null @@ -1,31 +0,0 @@ - - [![Build Status](https://secure.travis-ci.org/visionmedia/mocha.png)](http://travis-ci.org/visionmedia/mocha) - - [![Mocha test framework](http://f.cl.ly/items/3H1W3W3i3W163X0U3127/Screenshot.png)](http://visionmedia.github.com/mocha) - - Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser. For more information view the [documentation](http://visionmedia.github.com/mocha). - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/mocha/bin/mocha b/node_modules/mocha/bin/mocha deleted file mode 100755 index c8b09c6..0000000 --- a/node_modules/mocha/bin/mocha +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander') - , exec = require('child_process').exec - , path = require('path') - , mocha = require('../') - , reporters = mocha.reporters - , interfaces = mocha.interfaces - , Runner = mocha.Runner - , Suite = mocha.Suite - , vm = require('vm') - , fs = require('fs') - , join = path.join - , cwd = process.cwd(); - -/** - * Files. - */ - -var files = []; - -// options - -program - .version(mocha.version) - .usage('[options] [files]') - .option('-r, --require ', 'require the given module') - .option('-R, --reporter ', 'specify the reporter to use', 'dot') - .option('-u, --ui ', 'specify user-interface (bdd|tdd|exports)', 'bdd') - .option('-g, --grep ', 'only run tests matching ') - .option('-t, --timeout ', 'set test-case timeout in milliseconds [2000]') - .option('-s, --slow ', '"slow" test threshold in milliseconds [75]', parseInt) - .option('-C, --no-colors', 'force disabling of colors') - .option('-c, --colors', 'force enabling of colors') - .option('-G, --growl', 'enable growl support') - .option('--interfaces', 'display available interfaces') - .option('--reporters', 'display available reporters') - -// --reporters - -program.on('reporters', function(){ - console.log(); - console.log(' dot - dot matrix'); - console.log(' doc - html documentation'); - console.log(' spec - hierarchical spec list'); - console.log(' json - single json object'); - console.log(' progress - progress bar'); - console.log(' list - spec-style listing'); - console.log(' tap - test-anything-protocol'); - console.log(' landing - unicode landing strip'); - console.log(' json-stream - newline delimited json events'); - console.log(); - process.exit(); -}); - -// --interfaces - -program.on('interfaces', function(){ - console.log(''); - console.log(' bdd'); - console.log(' tdd'); - console.log(' exports'); - console.log(''); - process.exit(); -}); - -// -r, --require - -program.on('require', function(mod){ - require(mod); -}); - -// mocha.opts support - -try { - var opts = fs.readFileSync('test/mocha.opts', 'utf8').trim(); - opts = opts.split(/\s+/); - process.argv = process.argv - .slice(0, 2) - .concat(opts.concat(process.argv.slice(2))); -} catch (err) { - // ignore -} - -// parse args - -program.parse(process.argv); - -// infinite stack traces - -Error.stackTraceLimit = Infinity; // TODO: config - -// reporter - -var suite = new Suite('') - , Base = require('../lib/reporters/base') - , Reporter = require('../lib/reporters/' + program.reporter) - , ui = interfaces[program.ui](suite); - -// --no-colors - -if (!program.colors) Base.useColors = false; - -// --colors - -if (~process.argv.indexOf('--colors') || - ~process.argv.indexOf('-c')) { - Base.useColors = true; -} - -// --slow - -if (program.slow) Base.slow = program.slow; - -// --timeout - -if (program.timeout) suite.timeout(program.timeout); - -// files - -var files = program.args; - -// default files to test/*.js -// with optional coffee-script support - -if (!files.length) { - files = fs.readdirSync('test').filter(function(path){ - try { - require('coffee-script'); - return path.match(/\.(js|coffee)$/); - } catch (err) { - return path.match(/\.js$/); - } - }).map(function(path){ - return join('test', path); - }); -} - -// require test files before running -// the root suite - -var pending = files.length; -files.forEach(function(file){ - file = join(cwd, file); - suite.emit('pre-require', global, file); - suite.emit('require', require(file), file); - suite.emit('post-require', global, file); - --pending || run(suite); -}); - -// run the given suite - -function run(suite) { - suite.emit('run'); - var runner = new Runner(suite); - var reporter = new Reporter(runner); - if (program.grep) runner.grep(new RegExp(program.grep)); - if (program.growl) growl(runner, reporter) - runner.run(); -} - -// enable growl notifications - -function growl(runner, reporter) { - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + stats.tests + ' tests failed'; - notify(msg, { title: 'Failed' }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - title: 'Passed' - }); - } - }); -} - -// growl notification - -function notify(msg, options) { - var image - , args = ['growlnotify', '-m', '"' + msg + '"'] - , options = options || {} - , fn = fn || function(){}; - - if (image = options.image) { - var flag, ext = path.extname(image).substr(1) - flag = flag || ext == 'icns' && 'iconpath' - flag = flag || /^[A-Z]/.test(image) && 'appIcon' - flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image' - flag = flag || ext && (image = ext) && 'icon' - flag = flag || 'icon' - args.push('--' + flag, image) - } - - if (options.sticky) args.push('--sticky'); - if (options.priority) args.push('--priority', options.priority); - if (options.name) args.push('--name', options.name); - if (options.title) args.push(options.title); - exec(args.join(' '), fn); -} diff --git a/node_modules/mocha/bin/mocha-debug b/node_modules/mocha/bin/mocha-debug deleted file mode 100755 index 0968bcf..0000000 --- a/node_modules/mocha/bin/mocha-debug +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node debug - -require('./mocha'); \ No newline at end of file diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after each.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after each.tmSnippet deleted file mode 100644 index e76cae1..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after each.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - afterEach(function(){ - $0 -}) - name - bdd - after each - tabTrigger - ae - uuid - 7B4DA8F4-2064-468B-B252-054148419B4B - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after.tmSnippet deleted file mode 100644 index f1a67aa..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - after.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - after(function(){ - $0 -}) - name - bdd - after - tabTrigger - a - uuid - A49A87F9-399E-4D74-A489-C535BB06D487 - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before each.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before each.tmSnippet deleted file mode 100644 index f8442fa..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before each.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - beforeEach(function(){ - $0 -}) - name - bdd - before each - tabTrigger - be - uuid - 7AB064E3-EFBB-4FA7-98CA-9E87C10CC04E - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before.tmSnippet deleted file mode 100644 index 5c7e40f..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - before.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - before(function(){ - $0 -}) - name - bdd - before - tabTrigger - b - uuid - DF6F1F42-F80A-4A24-AF78-376F19070C4C - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - it.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - it.tmSnippet deleted file mode 100644 index 8cd3fb1..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/bdd - it.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - it('should $1', function(){ - $0 -}) - name - bdd - it - tabTrigger - it - uuid - 591AE071-95E4-4E1E-B0F3-A7DAF41595EE - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/untitled.tmSnippet b/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/untitled.tmSnippet deleted file mode 100644 index 46fd720..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/Snippets/untitled.tmSnippet +++ /dev/null @@ -1,16 +0,0 @@ - - - - - content - describe('$1', function(){ - $0 -}) - name - bdd - describe - tabTrigger - des - uuid - 4AA1FB50-9BB9-400E-A140-D61C39BDFDF5 - - diff --git a/node_modules/mocha/editors/JavaScript mocha.tmbundle/info.plist b/node_modules/mocha/editors/JavaScript mocha.tmbundle/info.plist deleted file mode 100644 index 16f6587..0000000 --- a/node_modules/mocha/editors/JavaScript mocha.tmbundle/info.plist +++ /dev/null @@ -1,19 +0,0 @@ - - - - - name - JavaScript mocha - ordering - - 4AA1FB50-9BB9-400E-A140-D61C39BDFDF5 - 591AE071-95E4-4E1E-B0F3-A7DAF41595EE - DF6F1F42-F80A-4A24-AF78-376F19070C4C - A49A87F9-399E-4D74-A489-C535BB06D487 - 7AB064E3-EFBB-4FA7-98CA-9E87C10CC04E - 7B4DA8F4-2064-468B-B252-054148419B4B - - uuid - 094ACE33-0C0E-422A-B3F7-5B919F5B1239 - - diff --git a/node_modules/mocha/index.js b/node_modules/mocha/index.js deleted file mode 100644 index 238f0f1..0000000 --- a/node_modules/mocha/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/mocha'); \ No newline at end of file diff --git a/node_modules/mocha/lib/browser/events.js b/node_modules/mocha/lib/browser/events.js deleted file mode 100644 index dfcd4ee..0000000 --- a/node_modules/mocha/lib/browser/events.js +++ /dev/null @@ -1,53 +0,0 @@ - -/** - * Expose `EventEmitter`. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Slice reference. - */ - -var slice = [].slice; - -/** - * EventEmitter. - */ - -function EventEmitter() { - this.callbacks = {}; -}; - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - */ - -EventEmitter.prototype.on = function(event, fn){ - (this.callbacks[event] = this.callbacks[event] || []) - .push(fn); - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - */ - -EventEmitter.prototype.emit = function(event){ - var args = slice.call(arguments, 1) - , callbacks = this.callbacks[event]; - - if (callbacks) { - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args) - } - } - - return this; -}; diff --git a/node_modules/mocha/lib/browser/tty.js b/node_modules/mocha/lib/browser/tty.js deleted file mode 100644 index 2d84374..0000000 --- a/node_modules/mocha/lib/browser/tty.js +++ /dev/null @@ -1,8 +0,0 @@ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; -}; \ No newline at end of file diff --git a/node_modules/mocha/lib/hook.js b/node_modules/mocha/lib/hook.js deleted file mode 100644 index 0dba20c..0000000 --- a/node_modules/mocha/lib/hook.js +++ /dev/null @@ -1,30 +0,0 @@ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Hook.prototype.__proto__ = Runnable.prototype; diff --git a/node_modules/mocha/lib/interfaces/bdd.js b/node_modules/mocha/lib/interfaces/bdd.js deleted file mode 100644 index 1a06567..0000000 --- a/node_modules/mocha/lib/interfaces/bdd.js +++ /dev/null @@ -1,86 +0,0 @@ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn(); - suites.shift(); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; diff --git a/node_modules/mocha/lib/interfaces/exports.js b/node_modules/mocha/lib/interfaces/exports.js deleted file mode 100644 index b22607e..0000000 --- a/node_modules/mocha/lib/interfaces/exports.js +++ /dev/null @@ -1,60 +0,0 @@ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); - } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; \ No newline at end of file diff --git a/node_modules/mocha/lib/interfaces/index.js b/node_modules/mocha/lib/interfaces/index.js deleted file mode 100644 index 0dc7667..0000000 --- a/node_modules/mocha/lib/interfaces/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.exports = require('./exports'); \ No newline at end of file diff --git a/node_modules/mocha/lib/interfaces/tdd.js b/node_modules/mocha/lib/interfaces/tdd.js deleted file mode 100644 index a3f35c4..0000000 --- a/node_modules/mocha/lib/interfaces/tdd.js +++ /dev/null @@ -1,70 +0,0 @@ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute before each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn(); - suites.shift(); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; diff --git a/node_modules/mocha/lib/mocha.js b/node_modules/mocha/lib/mocha.js deleted file mode 100644 index 26a836d..0000000 --- a/node_modules/mocha/lib/mocha.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Library version. - */ - -exports.version = '0.0.8'; - -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/base.js b/node_modules/mocha/lib/reporters/base.js deleted file mode 100644 index 6b0b28a..0000000 --- a/node_modules/mocha/lib/reporters/base.js +++ /dev/null @@ -1,227 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': '40' - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 -}; - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\033[' + exports.colors[type] + 'm' + str + '\033[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - process.stdout.write('\033[?25l'); - }, - - show: function(){ - process.stdout.write('\033[?25h'); - } -}; - -/** - * A test is considered slow if it - * exceeds the following value in milliseconds. - */ - -exports.slow = 75; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var stack = test.err.stack - , index = stack.indexOf('at') - , msg = stack.slice(0, index); - - // indent stack trace without msg - stack = stack.slice(index) - .replace(/^/gm, ' '); - - console.error(fmt, i, test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = exports.slow / 2; - test.speed = test.duration > exports.slow - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt; - - console.log(); - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ✖') - + color('fail', ' %d of %d tests failed') - + color('light', ':') - - console.error(fmt, stats.failures, this.runner.total); - Base.list(this.failures); - console.error(); - process.nextTick(function(){ - process.exit(stats.failures); - }); - return; - } - - // pass - fmt = color('bright pass', ' ✔') - + color('green', ' %d tests complete') - + color('light', ' (%dms)'); - - console.log(fmt, stats.tests || 0, stats.duration); - console.log(); - process.nextTick(function(){ - process.exit(0); - }); -}; diff --git a/node_modules/mocha/lib/reporters/doc.js b/node_modules/mocha/lib/reporters/doc.js deleted file mode 100644 index 8175e43..0000000 --- a/node_modules/mocha/lib/reporters/doc.js +++ /dev/null @@ -1,78 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
    ', indent()); - ++indents; - console.log('%s

    %s

    ', indent(), suite.title); - console.log('%s
    ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
    ', indent()); - --indents; - console.log('%s
    ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
    %s
    ', indent(), test.title); - var code = utils.escape(clean(test.fn.toString())); - console.log('%s
    %s
    ', indent(), code); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -function clean(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str.replace(re, ''); - - return str; -} \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/dot.js b/node_modules/mocha/lib/reporters/dot.js deleted file mode 100644 index 20158db..0000000 --- a/node_modules/mocha/lib/reporters/dot.js +++ /dev/null @@ -1,62 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = 0; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - process.stdout.write(color('pending', '.')); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', '.')); - } else { - process.stdout.write(color(test.speed, '.')); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', '.')); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Dot.prototype.__proto__ = Base.prototype; \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/html.js b/node_modules/mocha/lib/reporters/html.js deleted file mode 100644 index 3297d4e..0000000 --- a/node_modules/mocha/lib/reporters/html.js +++ /dev/null @@ -1,126 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = '
      ' - + '
    • passes: 0
    • ' - + '
    • failures: 0
    • ' - + '
    • duration: 0s
    • ' - + '
    '; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - // TODO: clean up - - var self = this - , stats = this.stats - , total = runner.total - , root = $('#mocha') - , stack = [root] - , stat = $(statsTemplate).appendTo(root); - - if (!root.length) return error('#mocha div missing, add it to your document'); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var el = $('

    ' + suite.title + '

    '); - - // container - stack[0].append(el); - stack.unshift($('
    ')); - el.append(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('test end', function(test){ - // update stats - var ms = new Date - stats.start; - stat.find('.passes em').text(stats.passes); - stat.find('.failures em').text(stats.failures); - stat.find('.duration em').text((ms / 1000).toFixed(2)); - - // test - if (test.passed) { - var el = $('

    ' + test.title + '

    ') - } else if (test.pending) { - var el = $('

    ' + test.title + '

    ') - } else { - var el = $('

    ' + test.title + '

    '); - var str = test.err.stack || test.err; - var err = $('
    ' + str + '
    '); - el.append(err); - } - - // toggle code - el.find('h2').toggle(function(){ - pre.slideDown('fast'); - }, function(){ - pre.slideUp('fast'); - }); - - // code - // TODO: defer - if (!test.pending) { - var code = utils.escape(clean(test.fn.toString())); - var pre = $('
    ' + code + '
    '); - pre.appendTo(el).hide(); - } - stack[0].append(el); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} - -function error(msg) { - $('
    ' + msg + '
    ').appendTo('body'); -} - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -function clean(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str - .replace(re, '') - .replace(/^\s+/, ''); - - return str; -} \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/index.js b/node_modules/mocha/lib/reporters/index.js deleted file mode 100644 index 2120c28..0000000 --- a/node_modules/mocha/lib/reporters/index.js +++ /dev/null @@ -1,11 +0,0 @@ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONStream = require('./json-stream'); diff --git a/node_modules/mocha/lib/reporters/json-stream.js b/node_modules/mocha/lib/reporters/json-stream.js deleted file mode 100644 index f695679..0000000 --- a/node_modules/mocha/lib/reporters/json-stream.js +++ /dev/null @@ -1,63 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats]), function(){ - process.exit(0); - }); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/json.js b/node_modules/mocha/lib/reporters/json.js deleted file mode 100644 index d6edce9..0000000 --- a/node_modules/mocha/lib/reporters/json.js +++ /dev/null @@ -1,72 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; - - process.stdout.write(JSON.stringify(obj), function(){ - process.exit(0); - }); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/landing.js b/node_modules/mocha/lib/reporters/landing.js deleted file mode 100644 index ceab6d8..0000000 --- a/node_modules/mocha/lib/reporters/landing.js +++ /dev/null @@ -1,97 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if (test.failed) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\033[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\033[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Landing.prototype.__proto__ = Base.prototype; \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/list.js b/node_modules/mocha/lib/reporters/list.js deleted file mode 100644 index 60acc4f..0000000 --- a/node_modules/mocha/lib/reporters/list.js +++ /dev/null @@ -1,61 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' ✓') - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - console.log('\r' + fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - console.log('\r' + color('fail', ' %d) %s'), n++, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -List.prototype.__proto__ = Base.prototype; \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/progress.js b/node_modules/mocha/lib/reporters/progress.js deleted file mode 100644 index 423c982..0000000 --- a/node_modules/mocha/lib/reporters/progress.js +++ /dev/null @@ -1,84 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || '⋅'; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - var incomplete = total - complete - , percent = complete++ / total - , n = width * percent | 0 - , i = width - n; - - process.stdout.write('\r\033[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Progress.prototype.__proto__ = Base.prototype; \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/spec.js b/node_modules/mocha/lib/reporters/spec.js deleted file mode 100644 index 5af9642..0000000 --- a/node_modules/mocha/lib/reporters/spec.js +++ /dev/null @@ -1,83 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s '); - console.log('\r' + fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - console.log('\r' + fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - console.log('\r' + indent() + color('fail', ' %d) %s'), n++, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -Spec.prototype.__proto__ = Base.prototype; \ No newline at end of file diff --git a/node_modules/mocha/lib/reporters/tap.js b/node_modules/mocha/lib/reporters/tap.js deleted file mode 100644 index 15e9021..0000000 --- a/node_modules/mocha/lib/reporters/tap.js +++ /dev/null @@ -1,51 +0,0 @@ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , n = 1; - - runner.on('start', function(){ - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pass', function(test){ - console.log('ok %d %s', n, test.fullTitle()); - }); - - runner.on('fail', function(test, err){ - console.log('not ok %d %s', n, test.fullTitle()); - console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} \ No newline at end of file diff --git a/node_modules/mocha/lib/runnable.js b/node_modules/mocha/lib/runnable.js deleted file mode 100644 index feaf965..0000000 --- a/node_modules/mocha/lib/runnable.js +++ /dev/null @@ -1,118 +0,0 @@ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this.timeout(2000); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runnable.prototype.__proto__ = EventEmitter.prototype; - -/** - * Set & get timeout `ms`. - * - * @param {Number} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - this._timeout = ms; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , finished - , emitted - , timer; - - // timeout - if (this.async) { - timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - }, ms); - } - - // called multiple times - function multiple() { - if (emitted) return; - emitted = true; - self.emit('error', new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (finished) return multiple(); - clearTimeout(timer); - self.duration = new Date - start; - finished = true; - fn(err); - } - - // async - if (this.async) { - try { - this.fn(done); - } catch (err) { - done(err); - } - return; - } - - // sync - try { - if (!this.pending) this.fn(); - this.duration = new Date - start; - fn(); - } catch (err) { - fn(err); - } -}; diff --git a/node_modules/mocha/lib/runner.js b/node_modules/mocha/lib/runner.js deleted file mode 100644 index 362c269..0000000 --- a/node_modules/mocha/lib/runner.js +++ /dev/null @@ -1,360 +0,0 @@ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Test = require('./test') - , noop = function(){}; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - * @api public - */ - -function Runner(suite) { - var self = this; - this.suite = suite; - this.total = suite.total(); - this.globals = Object.keys(global).concat(['errno']); - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runner.prototype.__proto__ = EventEmitter.prototype; - -/** - * Run tests with full titles matching `re`. - * - * @param {RegExp} re - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re){ - this._grep = re; - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - var leaks = Object.keys(global).filter(function(key){ - return !~this.globals.indexOf(key); - }, this); - - this.globals = this.globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - test.failed = true; - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures (currently) hard-exit due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - this.emit('end'); - process.exit(0); -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , ms = suite._timeout - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - if (err) return self.failHook(hook, err); - self.emit('hook end', hook); - next(++i); - }); - } - - process.nextTick(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - self.suite = orig; - return fn(err); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests - , test; - - function next(err) { - // error handling - if (err) { - self.fail(test, err); - self.emit('test end', test); - } - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - if (!self._grep.test(test.fullTitle())) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ - self.runTest(function(err){ - if (err) return next(err); - self.emit('pass', test); - test.passed = true; - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var self = this - , i = 0; - - this.emit('suite', this.suite = suite); - - function next() { - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done() { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); - } - - this.hook('beforeAll', function(){ - self.runTests(suite, next); - }); -}; - -/** - * Run the root suite. - * - * @api public - */ - -Runner.prototype.run = function(){ - var self = this; - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', function(err){ - self.fail(self.test, err); - self.emit('test end', self.test); - self.emit('end'); - }); - - return this; -}; diff --git a/node_modules/mocha/lib/suite.js b/node_modules/mocha/lib/suite.js deleted file mode 100644 index 3783aec..0000000 --- a/node_modules/mocha/lib/suite.js +++ /dev/null @@ -1,205 +0,0 @@ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Suite map. - */ - -var map = {}; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title); - suite.parent = parent; - title = suite.fullTitle(); - if (map[title]) return map[title]; - parent.addSuite(suite); - return map[title] = suite; -}; - -/** - * Initialize a new `Suite` with the given `title`. - * - * @param {String} title - * @api private - */ - -function Suite(title) { - this.title = title; - this.suites = []; - this.tests = []; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this.timeout(2000); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Suite.prototype.__proto__ = EventEmitter.prototype; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (String(ms).match(/s$/)) ms = parseFloat(ms) * 1000; - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(fn){ - var hook = new Hook('"before all" hook', fn); - hook.parent = this; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(fn){ - var hook = new Hook('"after all" hook', fn); - hook.parent = this; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(fn){ - var hook = new Hook('"before each" hook', fn); - hook.parent = this; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(fn){ - var hook = new Hook('"after each" hook', fn); - hook.parent = this; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - if (this._timeout) suite.timeout(this._timeout); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - if (this._timeout) test.timeout(this._timeout); - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return this.suites.reduce(function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; diff --git a/node_modules/mocha/lib/test.js b/node_modules/mocha/lib/test.js deleted file mode 100644 index c910cc5..0000000 --- a/node_modules/mocha/lib/test.js +++ /dev/null @@ -1,31 +0,0 @@ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Test.prototype.__proto__ = Runnable.prototype; diff --git a/node_modules/mocha/lib/utils.js b/node_modules/mocha/lib/utils.js deleted file mode 100644 index 35570bc..0000000 --- a/node_modules/mocha/lib/utils.js +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; \ No newline at end of file diff --git a/node_modules/mocha/mocha.css b/node_modules/mocha/mocha.css deleted file mode 100644 index 756d668..0000000 --- a/node_modules/mocha/mocha.css +++ /dev/null @@ -1,91 +0,0 @@ - -body { - font: 20px/1.5 "Helvetica Neue", Helvetica, Aria;, sans-serif; - padding: 60px 50px; -} - -h1, h2 { - margin: 0; -} - -h1 { - font-size: 1em; - font-weight: 200; -} - -.suite .suite h1 { - font-size: .8em; -} - -h2 { - font-size: 12px; - font-weight: normal; - cursor: pointer; -} - -.suite { - margin-left: 15px; -} - -.test { - margin-left: 15px; -} - -.test.pass::before { - content: '◦'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; -} - -.test.fail { - color: #c00; -} - -.test.fail pre { - color: black; -} - -.test.fail::before { - content: '✖'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #c00; -} - -.test pre.error { - color: #c00; -} - -.test pre { - display: inline-block; - font: 12px/1.5 monaco, monospace; - margin: 5px; - padding: 15px; - border: 1px solid #eee; - border-bottom-color: #ddd; - -webkit-border-radius: 3px; - -webkit-box-shadow: 0 1px 3px #eee; -} - -#error { - color: #c00; - font-size: 1.5 em; - font-weight: 100; - letter-spacing: 1px; -} - -#stats { - position: fixed; - top: 15px; - right: 30px; - font-size: 12px; - margin: 0; -} - -#stats li { - list-style: none; -} \ No newline at end of file diff --git a/node_modules/mocha/mocha.js b/node_modules/mocha/mocha.js deleted file mode 100644 index f9e04e4..0000000 --- a/node_modules/mocha/mocha.js +++ /dev/null @@ -1,2266 +0,0 @@ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p[0]) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Expose `EventEmitter`. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Slice reference. - */ - -var slice = [].slice; - -/** - * EventEmitter. - */ - -function EventEmitter() { - this.callbacks = {}; -}; - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - */ - -EventEmitter.prototype.on = function(event, fn){ - (this.callbacks[event] = this.callbacks[event] || []) - .push(fn); - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - */ - -EventEmitter.prototype.emit = function(event){ - var args = slice.call(arguments, 1) - , callbacks = this.callbacks[event]; - - if (callbacks) { - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args) - } - } - - return this; -}; - -}); // module: browser/events.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; -}; -}); // module: browser/tty.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Hook.prototype = new Runnable; -Hook.prototype.constructor = Hook; - - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn(); - suites.shift(); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); - } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.exports = require('./exports'); -}); // module: interfaces/index.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute before each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn(); - suites.shift(); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ - -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Library version. - */ - -exports.version = '0.0.6'; - -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); -}); // module: mocha.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty'); - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': '40' - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 -}; - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\033[' + exports.colors[type] + 'm' + str + '\033[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - process.stdout.write('\033[?25l'); - }, - - show: function(){ - process.stdout.write('\033[?25h'); - } -}; - -/** - * A test is considered slow if it - * exceeds the following value in milliseconds. - */ - -exports.slow = 75; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var stack = test.err.stack - , index = stack.indexOf('at') - , msg = stack.slice(0, index); - - // indent stack trace without msg - stack = stack.slice(index) - .replace(/^/gm, ' '); - - console.error(fmt, i, test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = exports.slow / 2; - test.speed = test.duration > exports.slow - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt; - - console.log(); - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ✖') - + color('fail', ' %d of %d tests failed') - + color('light', ':') - - console.error(fmt, stats.failures, stats.tests); - Base.list(this.failures); - console.error(); - process.nextTick(function(){ - process.exit(stats.failures); - }); - return; - } - - // pass - fmt = color('bright pass', ' ✔') - + color('green', ' %d tests complete') - + color('light', ' (%dms)'); - - console.log(fmt, stats.tests || 0, stats.duration); - console.log(); - process.nextTick(function(){ - process.exit(0); - }); -}; - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
    ', indent()); - ++indents; - console.log('%s

    %s

    ', indent(), suite.title); - console.log('%s
    ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
    ', indent()); - --indents; - console.log('%s
    ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
    %s
    ', indent(), test.title); - var code = utils.escape(clean(test.fn.toString())); - console.log('%s
    %s
    ', indent(), code); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -function clean(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str.replace(re, ''); - - return str; -} -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = 0; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - process.stdout.write(color('pending', '.')); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', '.')); - } else { - process.stdout.write(color(test.speed, '.')); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', '.')); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Dot.prototype = new Base; -Dot.prototype.constructor = Dot; - -}); // module: reporters/dot.js - -require.register("reporters/html.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = '
      ' - + '
    • passes: 0
    • ' - + '
    • failures: 0
    • ' - + '
    • duration: 0s
    • ' - + '
    '; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - // TODO: clean up - - var self = this - , stats = this.stats - , total = runner.total - , root = $('#mocha') - , stack = [root] - , stat = $(statsTemplate).appendTo(root); - - if (!root.length) return error('#mocha div missing, add it to your document'); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var el = $('

    ' + suite.title + '

    '); - - // container - stack[0].append(el); - stack.unshift($('
    ')); - el.append(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('test end', function(test){ - // update stats - var ms = new Date - stats.start; - stat.find('.passes em').text(stats.passes); - stat.find('.failures em').text(stats.failures); - stat.find('.duration em').text((ms / 1000).toFixed(2)); - - // test - if (test.passed) { - var el = $('

    ' + test.title + '

    ') - } else if (test.pending) { - var el = $('

    ' + test.title + '

    ') - } else { - var el = $('

    ' + test.title + '

    '); - var str = test.err.stack || test.err; - var err = $('
    ' + str + '
    '); - el.append(err); - } - - // toggle code - el.find('h2').toggle(function(){ - pre.slideDown('fast'); - }, function(){ - pre.slideUp('fast'); - }); - - // code - // TODO: defer - if (!test.pending) { - var code = utils.escape(clean(test.fn.toString())); - var pre = $('
    ' + code + '
    '); - pre.appendTo(el).hide(); - } - stack[0].append(el); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} - -function error(msg) { - $('
    ' + msg + '
    ').appendTo('body'); -} - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -function clean(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str - .replace(re, '') - .replace(/^\s+/, ''); - - return str; -} -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONStream = require('./json-stream'); - -}); // module: reporters/index.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats]), function(){ - process.exit(0); - }); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; - - process.stdout.write(JSON.stringify(obj), function(){ - process.exit(0); - }); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if (test.failed) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\033[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\033[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Landing.prototype = new Base; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' ✓') - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - console.log('\r' + fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - console.log('\r' + color('fail', ' %d) %s'), n++, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -List.prototype = new Base; -List.prototype.constructor = List; - -}); // module: reporters/list.js - -require.register("reporters/progress.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || '⋅'; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - var incomplete = total - complete - , percent = complete++ / total - , n = width * percent | 0 - , i = width - n; - - process.stdout.write('\r\033[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Progress.prototype = new Base; -Progress.prototype.constructor = Progress; - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', test.title + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s '); - console.log('\r' + fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - console.log('\r' + fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - console.log('\r' + indent() + color('fail', ' %d) %s'), n++, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -Spec.prototype = new Base; -Spec.prototype.constructor = Spec; - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , n = 1; - - runner.on('start', function(){ - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pass', function(test){ - console.log('ok %d %s', n, test.fullTitle()); - }); - - runner.on('fail', function(test, err){ - console.log('not ok %d %s', n, test.fullTitle()); - console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - process.exit(stats.failures); - }); -} -}); // module: reporters/tap.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this.timeout(2000); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runnable.prototype = new EventEmitter; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - this._timeout = ms; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this._timeout - , start = new Date - , finished - , emitted - , timer; - - // timeout - if (this.async) { - timer = setTimeout(function(){ - fn(new Error('timeout of ' + ms + 'ms exceeded')); - }, ms); - } - - // called multiple times - function multiple() { - if (emitted) return; - emitted = true; - self.emit('error', new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (finished) return multiple(); - clearTimeout(timer); - self.duration = new Date - start; - finished = true; - fn(err); - } - - // async - if (this.async) { - try { - this.fn(done); - } catch (err) { - done(err); - } - return; - } - - // sync - try { - if (!this.pending) this.fn(); - this.duration = new Date - start; - fn(); - } catch (err) { - fn(err); - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , Test = require('./test') - , noop = function(){}; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - * @api public - */ - -function Runner(suite) { - var self = this; - this.suite = suite; - this.total = suite.total(); - this.globals = Object.keys(global).concat(['errno']); - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runner.prototype = new EventEmitter; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. - * - * @param {RegExp} re - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re){ - this._grep = re; - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - var leaks = Object.keys(global).filter(function(key){ - return !~this.globals.indexOf(key); - }, this); - - this.globals = this.globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - test.failed = true; - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures (currently) hard-exit due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - this.emit('end'); - process.exit(0); -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , ms = suite._timeout - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - if (err) return self.failHook(hook, err); - self.emit('hook end', hook); - next(++i); - }); - } - - process.nextTick(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - self.suite = orig; - return fn(err); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests - , test; - - function next(err) { - // error handling - if (err) { - self.fail(test, err); - self.emit('test end', test); - } - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - if (!self._grep.test(test.fullTitle())) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ - self.runTest(function(err){ - if (err) return next(err); - self.emit('pass', test); - test.passed = true; - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var self = this - , i = 0; - - this.emit('suite', this.suite = suite); - - function next() { - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done() { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); - } - - this.hook('beforeAll', function(){ - self.runTests(suite, next); - }); -}; - -/** - * Run the root suite. - * - * @api public - */ - -Runner.prototype.run = function(){ - var self = this; - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', function(err){ - self.fail(self.test, err); - self.emit('test end', self.test); - self.emit('end'); - }); - - return this; -}; - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Suite map. - */ - -var map = {}; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title); - suite.parent = parent; - title = suite.fullTitle(); - if (map[title]) return map[title]; - parent.addSuite(suite); - return map[title] = suite; -}; - -/** - * Initialize a new `Suite` with the given `title`. - * - * @param {String} title - * @api private - */ - -function Suite(title) { - this.title = title; - this.suites = []; - this.tests = []; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this.timeout(2000); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Suite.prototype = new EventEmitter; -Suite.prototype.constructor = Suite; - - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (String(ms).match(/s$/)) ms = parseFloat(ms) * 1000; - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(fn){ - var hook = new Hook('"before all" hook', fn); - hook.parent = this; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(fn){ - var hook = new Hook('"after all" hook', fn); - hook.parent = this; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(fn){ - var hook = new Hook('"before each" hook', fn); - hook.parent = this; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(fn){ - var hook = new Hook('"after each" hook', fn); - hook.parent = this; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - if (this._timeout) suite.timeout(this._timeout); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - if (this._timeout) test.timeout(this._timeout); - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return this.suites.reduce(function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Test.prototype = new Runnable; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; -}); // module: utils.js - -/** - * Node shims. - * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -process = {}; -process.nextTick = function(fn){ setTimeout(fn, 0); }; -process.on = function(){}; -process.exit = function(status){}; -process.stdout = {}; -global = this; - -mocha = require('mocha'); - -// boot - -;(function(){ - var suite = new mocha.Suite; - var Reporter = mocha.reporters.HTML; - - mocha.setup = function(ui){ - ui = mocha.interfaces[ui]; - if (!ui) throw new Error('invalid mocha interface "' + ui + '"'); - ui(suite); - suite.emit('pre-require', global); - }; - - mocha.run = function(){ - suite.emit('run'); - var runner = new mocha.Runner(suite); - var reporter = new Reporter(runner); - runner.run(); - }; -})(); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/commander/.npmignore b/node_modules/mocha/node_modules/commander/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/mocha/node_modules/commander/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/mocha/node_modules/commander/History.md b/node_modules/mocha/node_modules/commander/History.md deleted file mode 100644 index 44de373..0000000 --- a/node_modules/mocha/node_modules/commander/History.md +++ /dev/null @@ -1,58 +0,0 @@ - -0.3.2 / 2011-11-01 -================== - - * Fixed long flag definitions with values [felixge] - -0.3.1 / 2011-10-31 -================== - - * Changed `--version` short flag to `-V` from `-v` - * Changed `.version()` so it's configurable [felixge] - -0.3.0 / 2011-10-31 -================== - - * Added support for long flags only. Closes #18 - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mocha/node_modules/commander/Makefile b/node_modules/mocha/node_modules/commander/Makefile deleted file mode 100644 index 0074625..0000000 --- a/node_modules/mocha/node_modules/commander/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -TESTS = $(shell find test/test.*.js) - -test: - @./test/run $(TESTS) - -.PHONY: test \ No newline at end of file diff --git a/node_modules/mocha/node_modules/commander/Readme.md b/node_modules/mocha/node_modules/commander/Readme.md deleted file mode 100644 index 22909fa..0000000 --- a/node_modules/mocha/node_modules/commander/Readme.md +++ /dev/null @@ -1,260 +0,0 @@ - -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineappe'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -v, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineappe - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range
    ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -v, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/mocha/node_modules/commander/index.js b/node_modules/mocha/node_modules/commander/index.js deleted file mode 100644 index 06ec1e4..0000000 --- a/node_modules/mocha/node_modules/commander/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/commander'); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/commander/lib/commander.js b/node_modules/mocha/node_modules/commander/lib/commander.js deleted file mode 100644 index ef84078..0000000 --- a/node_modules/mocha/node_modules/commander/lib/commander.js +++ /dev/null @@ -1,908 +0,0 @@ -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , path = require('path') - , tty = require('tty') - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this.args = []; - this.name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - return cmd; -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self.args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self.args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this.name, function(args){ - self.args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // store raw args - this.rawArgs = argv; - - // guess name - if (!this.name) this.name = basename(argv[1]); - - // process argv - this.args = this.parseOptions(this.normalize(argv)); - return this.parseArgs(this.args); -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args); - } else { - this.emit('*', args); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , argv = argv.slice(2) - , len = argv.length - , option - , arg; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0]) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || '-' == arg[0]) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - this.unknownOption(arg); - } - - // arg - args.push(arg); - } - - return args; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']'; - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - return this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - }).join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - return cmd.name + ' ' + args - + (cmd.description() - ? '\n' + cmd.description() - : ''); - }).join('\n\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this.name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - this.promptSingleLine(str, function(val){ - val = Number(val); - if (isNaN(val)) return program.promptForNumber(str + '(must be a number) ', fn); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - this.promptSingleLine(str, function(val){ - val = new Date(val); - if (isNaN(val.getTime())) return program.promptForDate(str + '(must be a date) ', fn); - fn(val); - }); -}; - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = ''; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf); - } else { - buf += val; - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - tty.setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.removeAllListeners('keypress'); - tty.setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - return self.confirm(str, fn); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, fn){ - var self = this; - - list.forEach(function(item, i){ - console.log(' %d) %s', i + 1, item); - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Default -h, --help option. - */ - -exports.option('-h, --help', 'output usage information'); -exports.on('help', function(){ - process.stdout.write(this.helpInformation()); - exports.emit('--help'); - process.exit(0); -}); diff --git a/node_modules/mocha/node_modules/commander/package.json b/node_modules/mocha/node_modules/commander/package.json deleted file mode 100644 index 2ef6efa..0000000 --- a/node_modules/mocha/node_modules/commander/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "commander" - , "version": "0.3.2" - , "description": "the complete solution for node.js command-line programs" - , "keywords": ["command", "option", "parser", "prompt", "stdin"] - , "author": "TJ Holowaychuk " - , "repository": { "type": "git", "url": "https://github.com/visionmedia/commander.js.git" } - , "dependencies": {} - , "devDependencies": { "should": ">= 0.0.1" } - , "main": "index" - , "engines": { "node": ">= 0.4.x < 0.7.0" } -} \ No newline at end of file diff --git a/node_modules/mocha/package.json b/node_modules/mocha/package.json deleted file mode 100644 index e17971c..0000000 --- a/node_modules/mocha/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "mocha" - , "version": "0.0.8" - , "description": "Test framework inspired by JSpec, Expresso, & Qunit" - , "keywords": ["test", "bdd", "tdd", "tap"] - , "bin": { "mocha": "./bin/mocha" } - , "author": "TJ Holowaychuk " - , "main": "index" - , "bin": { - "mocha": "./bin/mocha" - , "mocha-debug": "./bin/mocha-debug" - } - , "engines": { "node": ">= 0.4.x < 0.7.0" } - , "scripts": { - "test": "make test" - } - , "dependencies":{ - "commander": "0.3.2" - } - , "devDependencies": { - "should": "0.3.x" - } -} diff --git a/node_modules/mocha/test.js b/node_modules/mocha/test.js deleted file mode 100644 index b1247a1..0000000 --- a/node_modules/mocha/test.js +++ /dev/null @@ -1,15 +0,0 @@ - -describe('something', function(){ - before(function(done){ - foo = 'bar' - done(); - }) - - it('should foo', function(){ - - }) - - it('should bar', function(){ - - }) -}) \ No newline at end of file diff --git a/node_modules/node-redis-raw/.npmignore b/node_modules/node-redis-raw/.npmignore deleted file mode 100644 index b512c09..0000000 --- a/node_modules/node-redis-raw/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/node_modules/node-redis-raw/Readme.md b/node_modules/node-redis-raw/Readme.md deleted file mode 100644 index 5f10063..0000000 --- a/node_modules/node-redis-raw/Readme.md +++ /dev/null @@ -1,23 +0,0 @@ -Redis Raw Mode -=============== - -This package monkey patches [node-redis](https://github.com/mranney/node_redis) to support writing raw commands to Redis. This is extremely useful in cases when you want to work with the native [redis command protocol](http://redis.io/topics/protocol), without invoking the penalties for parsing the commands. - -Useful for low level applications like proxies. It is use in the [Redis-Proxy](https://github.com/sreeix/redis-proxy). - -Usage -====== - -`require('raw-redis')` - -The only public API it adds to the redis client API is `sendRaw` - -It is used as following - -`var r = require('redis')` - -`var cl = r.createClient()` - -`cl.sendRaw("*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$7\r\nmyvalue\r\n", function(err, res) {console.log(res);});` - - diff --git a/node_modules/node-redis-raw/lib/raw.js b/node_modules/node-redis-raw/lib/raw.js deleted file mode 100644 index 9969675..0000000 --- a/node_modules/node-redis-raw/lib/raw.js +++ /dev/null @@ -1,58 +0,0 @@ -var redis = require('redis'); - -redis.RedisClient.prototype.sendRaw = function(command_str, callback){ - var stream = this.stream, buffer_args, buffered_writes = 0, command_obj; - if(!this.command_queue.peek){ - this.command_queue.peek = function () { - if (this.offset === this.head.length) { - var tmp = this.head; - tmp.length = 0; - this.head = this.tail; - this.tail = tmp; - this.offset = 0; - if (this.head.length === 0) { - return; - } - } - return this.head[this.offset]; // sorry, JSLint - }; - } - command_obj = new Command(command_str,[], false, true, callback); - this.command_queue.push(command_obj); - this.commands_sent += 1; - - buffered_writes += !stream.write(command_str); - if (buffered_writes || this.command_queue.getLength() >= this.command_queue_high_water) { - this.should_buffer = true; - } - return !this.should_buffer; -}; - -var originalOnData = redis.RedisClient.prototype.on_data; - -redis.RedisClient.prototype.on_data = function (data) { - if(this.command_queue.peek && this.command_queue.peek().raw){ - var command_obj = this.command_queue.shift(); - return try_callback(command_obj.callback, data); - } - originalOnData.call(this, data); -}; - -// Cargo culted from node-redis. -function try_callback(callback, reply) { - try { - callback(null, reply); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } -}; - -function Command(command, args, sub_command, raw, callback) { - this.command = command; - this.args = args; - this.sub_command = sub_command; - this.raw = raw; - this.callback = callback; -}; diff --git a/node_modules/node-redis-raw/package.json b/node_modules/node-redis-raw/package.json deleted file mode 100644 index 2fcae45..0000000 --- a/node_modules/node-redis-raw/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "author": "Sreekanth " - , "name": "node-redis-raw" - , "description": "Raw mode for node redis" - , "version": "0.0.2" - , "repository": { - "type": "git" - , "url": "git@github.com:sreeix/node-redis-raw.git" - } - , "main": "lib/raw.js" - , "engines": { "node": ">= 0.4.7" } - , "node-version": ">0.4.7" - , "dependencies": { - "redis": "0.7.1" - } -} diff --git a/node_modules/redis/README.md b/node_modules/redis/README.md deleted file mode 100644 index 02a873b..0000000 --- a/node_modules/redis/README.md +++ /dev/null @@ -1,567 +0,0 @@ -redis - a node.js redis client -=========================== - -This is a complete Redis client for node.js. It supports all Redis commands, including many recently added commands like EVAL from -experimental Redis server branches. - - -Install with: - - npm install redis - -Pieter Noordhuis has provided a binding to the official `hiredis` C library, which is non-blocking and fast. To use `hiredis`, do: - - npm install hiredis redis - -If `hiredis` is installed, `node_redis` will use it by default. Otherwise, a pure JavaScript parser will be used. - -If you use `hiredis`, be sure to rebuild it whenever you upgrade your version of node. There are mysterious failures that can -happen between node and native code modules after a node upgrade. - - -## Usage - -Simple example, included as `examples/simple.js`: - - var redis = require("redis"), - client = redis.createClient(); - - client.on("error", function (err) { - console.log("Error " + err); - }); - - client.set("string key", "string val", redis.print); - client.hset("hash key", "hashtest 1", "some value", redis.print); - client.hset(["hash key", "hashtest 2", "some other value"], redis.print); - client.hkeys("hash key", function (err, replies) { - console.log(replies.length + " replies:"); - replies.forEach(function (reply, i) { - console.log(" " + i + ": " + reply); - }); - client.quit(); - }); - -This will display: - - mjr:~/work/node_redis (master)$ node example.js - Reply: OK - Reply: 0 - Reply: 0 - 2 replies: - 0: hashtest 1 - 1: hashtest 2 - mjr:~/work/node_redis (master)$ - - -## Performance - -Here are typical results of `multi_bench.js` which is similar to `redis-benchmark` from the Redis distribution. -It uses 50 concurrent connections with no pipelining. - -JavaScript parser: - - PING: 20000 ops 42283.30 ops/sec 0/5/1.182 - SET: 20000 ops 32948.93 ops/sec 1/7/1.515 - GET: 20000 ops 28694.40 ops/sec 0/9/1.740 - INCR: 20000 ops 39370.08 ops/sec 0/8/1.269 - LPUSH: 20000 ops 36429.87 ops/sec 0/8/1.370 - LRANGE (10 elements): 20000 ops 9891.20 ops/sec 1/9/5.048 - LRANGE (100 elements): 20000 ops 1384.56 ops/sec 10/91/36.072 - -hiredis parser: - - PING: 20000 ops 46189.38 ops/sec 1/4/1.082 - SET: 20000 ops 41237.11 ops/sec 0/6/1.210 - GET: 20000 ops 39682.54 ops/sec 1/7/1.257 - INCR: 20000 ops 40080.16 ops/sec 0/8/1.242 - LPUSH: 20000 ops 41152.26 ops/sec 0/3/1.212 - LRANGE (10 elements): 20000 ops 36563.07 ops/sec 1/8/1.363 - LRANGE (100 elements): 20000 ops 21834.06 ops/sec 0/9/2.287 - -The performance of `node_redis` improves dramatically with pipelining, which happens automatically in most normal programs. - - -### Sending Commands - -Each Redis command is exposed as a function on the `client` object. -All functions take either take either an `args` Array plus optional `callback` Function or -a variable number of individual arguments followed by an optional callback. -Here is an example of passing an array of arguments and a callback: - - client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {}); - -Here is that same call in the second style: - - client.mset("test keys 1", "test val 1", "test keys 2", "test val 2", function (err, res) {}); - -Note that in either form the `callback` is optional: - - client.set("some key", "some val"); - client.set(["some other key", "some val"]); - -For a list of Redis commands, see [Redis Command Reference](http://redis.io/commands) - -The commands can be specified in uppercase or lowercase for convenience. `client.get()` is the same as `client.GET()`. - -Minimal parsing is done on the replies. Commands that return a single line reply return JavaScript Strings, -integer replies return JavaScript Numbers, "bulk" replies return node Buffers, and "multi bulk" replies return a -JavaScript Array of node Buffers. `HGETALL` returns an Object with Buffers keyed by the hash keys. - -# API - -## Connection Events - -`client` will emit some events about the state of the connection to the Redis server. - -### "ready" - -`client` will emit `ready` a connection is established to the Redis server and the server reports -that it is ready to receive commands. Commands issued before the `ready` event are queued, -then replayed just before this event is emitted. - -### "connect" - -`client` will emit `connect` at the same time as it emits `ready` unless `client.options.no_ready_check` -is set. If this options is set, `connect` will be emitted when the stream is connected, and then -you are free to try to send commands. - -### "error" - -`client` will emit `error` when encountering an error connecting to the Redis server. - -Note that "error" is a special event type in node. If there are no listeners for an -"error" event, node will exit. This is usually what you want, but it can lead to some -cryptic error messages like this: - - mjr:~/work/node_redis (master)$ node example.js - - node.js:50 - throw e; - ^ - Error: ECONNREFUSED, Connection refused - at IOWatcher.callback (net:870:22) - at node.js:607:9 - -Not very useful in diagnosing the problem, but if your program isn't ready to handle this, -it is probably the right thing to just exit. - -`client` will also emit `error` if an exception is thrown inside of `node_redis` for whatever reason. -It would be nice to distinguish these two cases. - -### "end" - -`client` will emit `end` when an established Redis server connection has closed. - -### "drain" - -`client` will emit `drain` when the TCP connection to the Redis server has been buffering, but is now -writable. This event can be used to stream commands in to Redis and adapt to backpressure. Right now, -you need to check `client.command_queue.length` to decide when to reduce your send rate. Then you can -resume sending when you get `drain`. - -### "idle" - -`client` will emit `idle` when there are no outstanding commands that are awaiting a response. - -## redis.createClient(port, host, options) - -Create a new client connection. `port` defaults to `6379` and `host` defaults -to `127.0.0.1`. If you have `redis-server` running on the same computer as node, then the defaults for -port and host are probably fine. `options` in an object with the following possible properties: - -* `parser`: which Redis protocol reply parser to use. Defaults to `hiredis` if that module is installed. -This may also be set to `javascript`. -* `return_buffers`: defaults to false. If set to `true`, then bulk data replies will be returned as node Buffer -objects instead of JavaScript Strings. - -`createClient()` returns a `RedisClient` object that is named `client` in all of the examples here. - -## client.auth(password, callback) - -When connecting to Redis servers that require authentication, the `AUTH` command must be sent as the -first command after connecting. This can be tricky to coordinate with reconnections, the ready check, -etc. To make this easier, `client.auth()` stashes `password` and will send it after each connection, -including reconnections. `callback` is invoked only once, after the response to the very first -`AUTH` command sent. - -## client.end() - -Forcibly close the connection to the Redis server. Note that this does not wait until all replies have been parsed. -If you want to exit cleanly, call `client.quit()` to send the `QUIT` command after you have handled all replies. - -This example closes the connection to the Redis server before the replies have been read. You probably don't -want to do this: - - var redis = require("redis"), - client = redis.createClient(); - - client.set("foo_rand000000000000", "some fantastic value"); - client.get("foo_rand000000000000", function (err, reply) { - console.log(reply.toString()); - }); - client.end(); - -`client.end()` is useful for timeout cases where something is stuck or taking too long and you want -to start over. - -## Friendlier hash commands - -Most Redis commands take a single String or an Array of Strings as arguments, and replies are sent back as a single String or an Array of Strings. When dealing with hash values, there are a couple of useful exceptions to this. - -### client.hgetall(hash) - -The reply from an HGETALL command will be converted into a JavaScript Object by `node_redis`. That way you can interact -with the responses using JavaScript syntax. - -Example: - - client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234"); - client.hgetall("hosts", function (err, obj) { - console.dir(obj); - }); - -Output: - - { mjr: '1', another: '23', home: '1234' } - -### client.hmset(hash, obj, [callback]) - -Multiple values in a hash can be set by supplying an object: - - client.HMSET(key2, { - "0123456789": "abcdefghij", - "some manner of key": "a type of value" - }); - -The properties and values of this Object will be set as keys and values in the Redis hash. - -### client.hmset(hash, key1, val1, ... keyn, valn, [callback]) - -Multiple values may also be set by supplying a list: - - client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value"); - - -## Publish / Subscribe - -Here is a simple example of the API for publish / subscribe. This program opens two -client connections, subscribes to a channel on one of them, and publishes to that -channel on the other: - - var redis = require("redis"), - client1 = redis.createClient(), client2 = redis.createClient(), - msg_count = 0; - - client1.on("subscribe", function (channel, count) { - client2.publish("a nice channel", "I am sending a message."); - client2.publish("a nice channel", "I am sending a second message."); - client2.publish("a nice channel", "I am sending my last message."); - }); - - client1.on("message", function (channel, message) { - console.log("client1 channel " + channel + ": " + message); - msg_count += 1; - if (msg_count === 3) { - client1.unsubscribe(); - client1.end(); - client2.end(); - } - }); - - client1.incr("did a thing"); - client1.subscribe("a nice channel"); - -When a client issues a `SUBSCRIBE` or `PSUBSCRIBE`, that connection is put into "pub/sub" mode. -At that point, only commands that modify the subscription set are valid. When the subscription -set is empty, the connection is put back into regular mode. - -If you need to send regular commands to Redis while in pub/sub mode, just open another connection. - -## Pub / Sub Events - -If a client has subscriptions active, it may emit these events: - -### "message" (channel, message) - -Client will emit `message` for every message received that matches an active subscription. -Listeners are passed the channel name as `channel` and the message Buffer as `message`. - -### "pmessage" (pattern, channel, message) - -Client will emit `pmessage` for every message received that matches an active subscription pattern. -Listeners are passed the original pattern used with `PSUBSCRIBE` as `pattern`, the sending channel -name as `channel`, and the message Buffer as `message`. - -### "subscribe" (channel, count) - -Client will emit `subscribe` in response to a `SUBSCRIBE` command. Listeners are passed the -channel name as `channel` and the new count of subscriptions for this client as `count`. - -### "psubscribe" (pattern, count) - -Client will emit `psubscribe` in response to a `PSUBSCRIBE` command. Listeners are passed the -original pattern as `pattern`, and the new count of subscriptions for this client as `count`. - -### "unsubscribe" (channel, count) - -Client will emit `unsubscribe` in response to a `UNSUBSCRIBE` command. Listeners are passed the -channel name as `channel` and the new count of subscriptions for this client as `count`. When -`count` is 0, this client has left pub/sub mode and no more pub/sub events will be emitted. - -### "punsubscribe" (pattern, count) - -Client will emit `punsubscribe` in response to a `PUNSUBSCRIBE` command. Listeners are passed the -channel name as `channel` and the new count of subscriptions for this client as `count`. When -`count` is 0, this client has left pub/sub mode and no more pub/sub events will be emitted. - -## client.multi([commands]) - -`MULTI` commands are queued up until an `EXEC` is issued, and then all commands are run atomically by -Redis. The interface in `node_redis` is to return an individual `Multi` object by calling `client.multi()`. - - var redis = require("./index"), - client = redis.createClient(), set_size = 20; - - client.sadd("bigset", "a member"); - client.sadd("bigset", "another member"); - - while (set_size > 0) { - client.sadd("bigset", "member " + set_size); - set_size -= 1; - } - - // multi chain with an individual callback - client.multi() - .scard("bigset") - .smembers("bigset") - .keys("*", function (err, replies) { - client.mget(replies, redis.print); - }) - .dbsize() - .exec(function (err, replies) { - console.log("MULTI got " + replies.length + " replies"); - replies.forEach(function (reply, index) { - console.log("Reply " + index + ": " + reply.toString()); - }); - }); - -`client.multi()` is a constructor that returns a `Multi` object. `Multi` objects share all of the -same command methods as `client` objects do. Commands are queued up inside the `Multi` object -until `Multi.exec()` is invoked. - -You can either chain together `MULTI` commands as in the above example, or you can queue individual -commands while still sending regular client command as in this example: - - var redis = require("redis"), - client = redis.createClient(), multi; - - // start a separate multi command queue - multi = client.multi(); - multi.incr("incr thing", redis.print); - multi.incr("incr other thing", redis.print); - - // runs immediately - client.mset("incr thing", 100, "incr other thing", 1, redis.print); - - // drains multi queue and runs atomically - multi.exec(function (err, replies) { - console.log(replies); // 101, 2 - }); - - // you can re-run the same transaction if you like - multi.exec(function (err, replies) { - console.log(replies); // 102, 3 - client.quit(); - }); - -In addition to adding commands to the `MULTI` queue individually, you can also pass an array -of commands and arguments to the constructor: - - var redis = require("redis"), - client = redis.createClient(), multi; - - client.multi([ - ["mget", "multifoo", "multibar", redis.print], - ["incr", "multifoo"], - ["incr", "multibar"] - ]).exec(function (err, replies) { - console.log(replies); - }); - - -## Monitor mode - -Redis supports the `MONITOR` command, which lets you see all commands received by the Redis server -across all client connections, including from other client libraries and other computers. - -After you send the `MONITOR` command, no other commands are valid on that connection. `node_redis` -will emit a `monitor` event for every new monitor message that comes across. The callback for the -`monitor` event takes a timestamp from the Redis server and an array of command arguments. - -Here is a simple example: - - var client = require("redis").createClient(), - util = require("util"); - - client.monitor(function (err, res) { - console.log("Entering monitoring mode."); - }); - - client.on("monitor", function (time, args) { - console.log(time + ": " + util.inspect(args)); - }); - - -# Extras - -Some other things you might like to know about. - -## client.server_info - -After the ready probe completes, the results from the INFO command are saved in the `client.server_info` -object. - -The `versions` key contains an array of the elements of the version string for easy comparison. - - > client.server_info.redis_version - '2.3.0' - > client.server_info.versions - [ 2, 3, 0 ] - -## redis.print() - -A handy callback function for displaying return values when testing. Example: - - var redis = require("redis"), - client = redis.createClient(); - - client.on("connect", function () { - client.set("foo_rand000000000000", "some fantastic value", redis.print); - client.get("foo_rand000000000000", redis.print); - }); - -This will print: - - Reply: OK - Reply: some fantastic value - -Note that this program will not exit cleanly because the client is still connected. - -## redis.debug_mode - -Boolean to enable debug mode and protocol tracing. - - var redis = require("redis"), - client = redis.createClient(); - - redis.debug_mode = true; - - client.on("connect", function () { - client.set("foo_rand000000000000", "some fantastic value"); - }); - -This will display: - - mjr:~/work/node_redis (master)$ node ~/example.js - send command: *3 - $3 - SET - $20 - foo_rand000000000000 - $20 - some fantastic value - - on_data: +OK - -`send command` is data sent into Redis and `on_data` is data received from Redis. - -## client.send_command(command_name, args, callback) - -Used internally to send commands to Redis. For convenience, nearly all commands that are published on the Redis -Wiki have been added to the `client` object. However, if I missed any, or if new commands are introduced before -this library is updated, you can use `send_command()` to send arbitrary commands to Redis. - -All commands are sent as multi-bulk commands. `args` can either be an Array of arguments, or individual arguments, -or omitted completely. - -## client.connected - -Boolean tracking the state of the connection to the Redis server. - -## client.command_queue.length - -The number of commands that have been sent to the Redis server but not yet replied to. You can use this to -enforce some kind of maximum queue depth for commands while connected. - -Don't mess with `client.command_queue` though unless you really know what you are doing. - -## client.offline_queue.length - -The number of commands that have been queued up for a future connection. You can use this to enforce -some kind of maximum queue depth for pre-connection commands. - -## client.retry_delay - -Current delay in milliseconds before a connection retry will be attempted. This starts at `250`. - -## client.retry_backoff - -Multiplier for future retry timeouts. This should be larger than 1 to add more time between retries. -Defaults to 1.7. The default initial connection retry is 250, so the second retry will be 425, followed by 723.5, etc. - - -## TODO - -Better tests for monitor mode, auth, disconnect/reconnect, and all combinations thereof. - -Stream large set/get values into and out of Redis. Otherwise the entire value must be in node's memory. - -Performance can be better for very large values. - -I think there are more performance improvements left in there for smaller values, especially for large lists of small values. - -## Contributors - -Some people have have added features and fixed bugs in `node_redis` other than me. - -In order of first contribution, they are: - -* [Tim Smart](https://github.com/Tim-Smart) -* [TJ Holowaychuk](https://github.com/visionmedia) -* [Rick Olson](https://github.com/technoweenie) -* [Orion Henry](https://github.com/orionz) -* [Hank Sims](https://github.com/hanksims) -* [Aivo Paas](https://github.com/aivopaas) -* [Paul Carey](https://github.com/paulcarey) -* [Pieter Noordhuis](https://github.com/pietern) -* [Vladimir Dronnikov](https://github.com/dvv) -* [Dave Hoover](https://github.com/redsquirrel) - -Thanks. - -## LICENSE - "MIT License" - -Copyright (c) 2010 Matthew Ranney, http://ranney.com/ - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -![spacer](http://ranney.com/1px.gif) diff --git a/node_modules/redis/changelog.md b/node_modules/redis/changelog.md deleted file mode 100644 index 63a29bc..0000000 --- a/node_modules/redis/changelog.md +++ /dev/null @@ -1,210 +0,0 @@ -Changelog -========= - -## v0.7.1 - November 15, 2011 - -Fix regression in reconnect logic. - -Very much need automated tests for reconnection and queue logic. - -## v0.7.0 - November 14, 2011 - -Many contributed fixes. Thanks everybody. - -* [GH-127] - properly re-initialize parser on reconnect -* [GH-136] - handle passing undefined as callback (Ian Babrou) -* [GH-139] - properly handle exceptions thrown in pub/sub event handlers (Felix Geisendörfer) -* [GH-141] - detect closing state on stream error (Felix Geisendörfer) -* [GH-142] - re-select database on reconnection (Jean-Hugues Pinson) -* [GH-146] - add sort example (Maksim Lin) - -Some more goodies: - -* Fix bugs with node 0.6 -* Performance improvements -* New version of `multi_bench.js` that tests more realistic scenarios -* [GH-140] - support optional callback for subscribe commands -* Properly flush and error out command queue when connection fails -* Initial work on reconnection thresholds - -## v0.6.7 - July 30, 2011 - -(accidentally skipped v0.6.6) - -Fix and test for [GH-123] - -Passing an Array as as the last argument should expand as users -expect. The old behavior was to coerce the arguments into Strings, -which did surprising things with Arrays. - -## v0.6.5 - July 6, 2011 - -Contributed changes: - -* Support SlowBuffers (Umair Siddique) -* Add Multi to exports (Louis-Philippe Perron) -* Fix for drain event calculation (Vladimir Dronnikov) - -Thanks! - -## v0.6.4 - June 30, 2011 - -Fix bug with optional callbacks for hmset. - -## v0.6.2 - June 30, 2011 - -Bugs fixed: - -* authentication retry while server is loading db (danmaz74) [GH-101] -* command arguments processing issue with arrays - -New features: - -* Auto update of new commands from redis.io (Dave Hoover) -* Performance improvements and backpressure controls. -* Commands now return the true/false value from the underlying socket write(s). -* Implement command_queue high water and low water for more better control of queueing. - -See `examples/backpressure_drain.js` for more information. - -## v0.6.1 - June 29, 2011 - -Add support and tests for Redis scripting through EXEC command. - -Bug fix for monitor mode. (forddg) - -Auto update of new commands from redis.io (Dave Hoover) - -## v0.6.0 - April 21, 2011 - -Lots of bugs fixed. - -* connection error did not properly trigger reconnection logic [GH-85] -* client.hmget(key, [val1, val2]) was not expanding properly [GH-66] -* client.quit() while in pub/sub mode would throw an error [GH-87] -* client.multi(['hmset', 'key', {foo: 'bar'}]) fails [GH-92] -* unsubscribe before subscribe would make things very confused [GH-88] -* Add BRPOPLPUSH [GH-79] - -## v0.5.11 - April 7, 2011 - -Added DISCARD - -I originally didn't think DISCARD would do anything here because of the clever MULTI interface, but somebody -pointed out to me that DISCARD can be used to flush the WATCH set. - -## v0.5.10 - April 6, 2011 - -Added HVALS - -## v0.5.9 - March 14, 2011 - -Fix bug with empty Array arguments - Andy Ray - -## v0.5.8 - March 14, 2011 - -Add `MONITOR` command and special monitor command reply parsing. - -## v0.5.7 - February 27, 2011 - -Add magical auth command. - -Authentication is now remembered by the client and will be automatically sent to the server -on every connection, including any reconnections. - -## v0.5.6 - February 22, 2011 - -Fix bug in ready check with `return_buffers` set to `true`. - -Thanks to Dean Mao and Austin Chau. - -## v0.5.5 - February 16, 2011 - -Add probe for server readiness. - -When a Redis server starts up, it might take a while to load the dataset into memory. -During this time, the server will accept connections, but will return errors for all non-INFO -commands. Now node_redis will send an INFO command whenever it connects to a server. -If the info command indicates that the server is not ready, the client will keep trying until -the server is ready. Once it is ready, the client will emit a "ready" event as well as the -"connect" event. The client will queue up all commands sent before the server is ready, just -like it did before. When the server is ready, all offline/non-ready commands will be replayed. -This should be backward compatible with previous versions. - -To disable this ready check behavior, set `options.no_ready_check` when creating the client. - -As a side effect of this change, the key/val params from the info command are available as -`client.server_options`. Further, the version string is decomposed into individual elements -in `client.server_options.versions`. - -## v0.5.4 - February 11, 2011 - -Fix excess memory consumption from Queue backing store. - -Thanks to Gustaf Sjöberg. - -## v0.5.3 - February 5, 2011 - -Fix multi/exec error reply callback logic. - -Thanks to Stella Laurenzo. - -## v0.5.2 - January 18, 2011 - -Fix bug where unhandled error replies confuse the parser. - -## v0.5.1 - January 18, 2011 - -Fix bug where subscribe commands would not handle redis-server startup error properly. - -## v0.5.0 - December 29, 2010 - -Some bug fixes: - -* An important bug fix in reconnection logic. Previously, reply callbacks would be invoked twice after - a reconnect. -* Changed error callback argument to be an actual Error object. - -New feature: - -* Add friendly syntax for HMSET using an object. - -## v0.4.1 - December 8, 2010 - -Remove warning about missing hiredis. You probably do want it though. - -## v0.4.0 - December 5, 2010 - -Support for multiple response parsers and hiredis C library from Pieter Noordhuis. -Return Strings instead of Buffers by default. -Empty nested mb reply bug fix. - -## v0.3.9 - November 30, 2010 - -Fix parser bug on failed EXECs. - -## v0.3.8 - November 10, 2010 - -Fix for null MULTI response when WATCH condition fails. - -## v0.3.7 - November 9, 2010 - -Add "drain" and "idle" events. - -## v0.3.6 - November 3, 2010 - -Add all known Redis commands from Redis master, even ones that are coming in 2.2 and beyond. - -Send a friendlier "error" event message on stream errors like connection refused / reset. - -## v0.3.5 - October 21, 2010 - -A few bug fixes. - -* Fixed bug with `nil` multi-bulk reply lengths that showed up with `BLPOP` timeouts. -* Only emit `end` once when connection goes away. -* Fixed bug in `test.js` where driver finished before all tests completed. - -## unversioned wasteland - -See the git history for what happened before. diff --git a/node_modules/redis/examples/auth.js b/node_modules/redis/examples/auth.js deleted file mode 100644 index 6c0a563..0000000 --- a/node_modules/redis/examples/auth.js +++ /dev/null @@ -1,5 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(); - -// This command is magical. Client stashes the password and will issue on every connect. -client.auth("somepass"); diff --git a/node_modules/redis/examples/backpressure_drain.js b/node_modules/redis/examples/backpressure_drain.js deleted file mode 100644 index 3488ef4..0000000 --- a/node_modules/redis/examples/backpressure_drain.js +++ /dev/null @@ -1,33 +0,0 @@ -var redis = require("../index"), - client = redis.createClient(null, null, { - command_queue_high_water: 5, - command_queue_low_water: 1 - }), - remaining_ops = 100000, paused = false; - -function op() { - if (remaining_ops <= 0) { - console.error("Finished."); - process.exit(0); - } - - remaining_ops--; - if (client.hset("test hash", "val " + remaining_ops, remaining_ops) === false) { - console.log("Pausing at " + remaining_ops); - paused = true; - } else { - process.nextTick(op); - } -} - -client.on("drain", function () { - if (paused) { - console.log("Resuming at " + remaining_ops); - paused = false; - process.nextTick(op); - } else { - console.log("Got drain while not paused at " + remaining_ops); - } -}); - -op(); diff --git a/node_modules/redis/examples/eval.js b/node_modules/redis/examples/eval.js deleted file mode 100644 index c1fbf8a..0000000 --- a/node_modules/redis/examples/eval.js +++ /dev/null @@ -1,9 +0,0 @@ -var redis = require("./index"), - client = redis.createClient(); - -redis.debug_mode = true; - -client.eval("return 100.5", 0, function (err, res) { - console.dir(err); - console.dir(res); -}); diff --git a/node_modules/redis/examples/extend.js b/node_modules/redis/examples/extend.js deleted file mode 100644 index 488b8c2..0000000 --- a/node_modules/redis/examples/extend.js +++ /dev/null @@ -1,24 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(); - -// Extend the RedisClient prototype to add a custom method -// This one converts the results from "INFO" into a JavaScript Object - -redis.RedisClient.prototype.parse_info = function (callback) { - this.info(function (err, res) { - var lines = res.toString().split("\r\n").sort(); - var obj = {}; - lines.forEach(function (line) { - var parts = line.split(':'); - if (parts[1]) { - obj[parts[0]] = parts[1]; - } - }); - callback(obj) - }); -}; - -client.parse_info(function (info) { - console.dir(info); - client.quit(); -}); diff --git a/node_modules/redis/examples/file.js b/node_modules/redis/examples/file.js deleted file mode 100644 index 4d2b5d1..0000000 --- a/node_modules/redis/examples/file.js +++ /dev/null @@ -1,32 +0,0 @@ -// Read a file from disk, store it in Redis, then read it back from Redis. - -var redis = require("redis"), - client = redis.createClient(), - fs = require("fs"), - filename = "kids_in_cart.jpg"; - -// Get the file I use for testing like this: -// curl http://ranney.com/kids_in_cart.jpg -o kids_in_cart.jpg -// or just use your own file. - -// Read a file from fs, store it in Redis, get it back from Redis, write it back to fs. -fs.readFile(filename, function (err, data) { - if (err) throw err - console.log("Read " + data.length + " bytes from filesystem."); - - client.set(filename, data, redis.print); // set entire file - client.get(filename, function (err, reply) { // get entire file - if (err) { - console.log("Get error: " + err); - } else { - fs.writeFile("duplicate_" + filename, reply, function (err) { - if (err) { - console.log("Error on write: " + err) - } else { - console.log("File written."); - } - client.end(); - }); - } - }); -}); diff --git a/node_modules/redis/examples/mget.js b/node_modules/redis/examples/mget.js deleted file mode 100644 index 936740d..0000000 --- a/node_modules/redis/examples/mget.js +++ /dev/null @@ -1,5 +0,0 @@ -var client = require("redis").createClient(); - -client.mget(["sessions started", "sessions started", "foo"], function (err, res) { - console.dir(res); -}); \ No newline at end of file diff --git a/node_modules/redis/examples/monitor.js b/node_modules/redis/examples/monitor.js deleted file mode 100644 index 2cb6a4e..0000000 --- a/node_modules/redis/examples/monitor.js +++ /dev/null @@ -1,10 +0,0 @@ -var client = require("../index").createClient(), - util = require("util"); - -client.monitor(function (err, res) { - console.log("Entering monitoring mode."); -}); - -client.on("monitor", function (time, args) { - console.log(time + ": " + util.inspect(args)); -}); diff --git a/node_modules/redis/examples/multi.js b/node_modules/redis/examples/multi.js deleted file mode 100644 index 35c08e1..0000000 --- a/node_modules/redis/examples/multi.js +++ /dev/null @@ -1,46 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(), set_size = 20; - -client.sadd("bigset", "a member"); -client.sadd("bigset", "another member"); - -while (set_size > 0) { - client.sadd("bigset", "member " + set_size); - set_size -= 1; -} - -// multi chain with an individual callback -client.multi() - .scard("bigset") - .smembers("bigset") - .keys("*", function (err, replies) { - client.mget(replies, redis.print); - }) - .dbsize() - .exec(function (err, replies) { - console.log("MULTI got " + replies.length + " replies"); - replies.forEach(function (reply, index) { - console.log("Reply " + index + ": " + reply.toString()); - }); - }); - -client.mset("incr thing", 100, "incr other thing", 1, redis.print); - -// start a separate multi command queue -var multi = client.multi(); -multi.incr("incr thing", redis.print); -multi.incr("incr other thing", redis.print); - -// runs immediately -client.get("incr thing", redis.print); // 100 - -// drains multi queue and runs atomically -multi.exec(function (err, replies) { - console.log(replies); // 101, 2 -}); - -// you can re-run the same transaction if you like -multi.exec(function (err, replies) { - console.log(replies); // 102, 3 - client.quit(); -}); diff --git a/node_modules/redis/examples/multi2.js b/node_modules/redis/examples/multi2.js deleted file mode 100644 index 8be4d73..0000000 --- a/node_modules/redis/examples/multi2.js +++ /dev/null @@ -1,29 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(), multi; - -// start a separate command queue for multi -multi = client.multi(); -multi.incr("incr thing", redis.print); -multi.incr("incr other thing", redis.print); - -// runs immediately -client.mset("incr thing", 100, "incr other thing", 1, redis.print); - -// drains multi queue and runs atomically -multi.exec(function (err, replies) { - console.log(replies); // 101, 2 -}); - -// you can re-run the same transaction if you like -multi.exec(function (err, replies) { - console.log(replies); // 102, 3 - client.quit(); -}); - -client.multi([ - ["mget", "multifoo", "multibar", redis.print], - ["incr", "multifoo"], - ["incr", "multibar"] -]).exec(function (err, replies) { - console.log(replies.toString()); -}); diff --git a/node_modules/redis/examples/psubscribe.js b/node_modules/redis/examples/psubscribe.js deleted file mode 100644 index c57117b..0000000 --- a/node_modules/redis/examples/psubscribe.js +++ /dev/null @@ -1,33 +0,0 @@ -var redis = require("redis"), - client1 = redis.createClient(), - client2 = redis.createClient(), - client3 = redis.createClient(), - client4 = redis.createClient(), - msg_count = 0; - -redis.debug_mode = false; - -client1.on("psubscribe", function (pattern, count) { - console.log("client1 psubscribed to " + pattern + ", " + count + " total subscriptions"); - client2.publish("channeltwo", "Me!"); - client3.publish("channelthree", "Me too!"); - client4.publish("channelfour", "And me too!"); -}); - -client1.on("punsubscribe", function (pattern, count) { - console.log("client1 punsubscribed from " + pattern + ", " + count + " total subscriptions"); - client4.end(); - client3.end(); - client2.end(); - client1.end(); -}); - -client1.on("pmessage", function (pattern, channel, message) { - console.log("("+ pattern +")" + " client1 received message on " + channel + ": " + message); - msg_count += 1; - if (msg_count === 3) { - client1.punsubscribe(); - } -}); - -client1.psubscribe("channel*"); diff --git a/node_modules/redis/examples/pub_sub.js b/node_modules/redis/examples/pub_sub.js deleted file mode 100644 index aa508d6..0000000 --- a/node_modules/redis/examples/pub_sub.js +++ /dev/null @@ -1,41 +0,0 @@ -var redis = require("redis"), - client1 = redis.createClient(), msg_count = 0, - client2 = redis.createClient(); - -redis.debug_mode = false; - -// Most clients probably don't do much on "subscribe". This example uses it to coordinate things within one program. -client1.on("subscribe", function (channel, count) { - console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions"); - if (count === 2) { - client2.publish("a nice channel", "I am sending a message."); - client2.publish("another one", "I am sending a second message."); - client2.publish("a nice channel", "I am sending my last message."); - } -}); - -client1.on("unsubscribe", function (channel, count) { - console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions"); - if (count === 0) { - client2.end(); - client1.end(); - } -}); - -client1.on("message", function (channel, message) { - console.log("client1 channel " + channel + ": " + message); - msg_count += 1; - if (msg_count === 3) { - client1.unsubscribe(); - } -}); - -client1.on("ready", function () { - // if you need auth, do it here - client1.incr("did a thing"); - client1.subscribe("a nice channel", "another one"); -}); - -client2.on("ready", function () { - // if you need auth, do it here -}); diff --git a/node_modules/redis/examples/simple.js b/node_modules/redis/examples/simple.js deleted file mode 100644 index f1f2e32..0000000 --- a/node_modules/redis/examples/simple.js +++ /dev/null @@ -1,24 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(); - -client.on("error", function (err) { - console.log("error event - " + client.host + ":" + client.port + " - " + err); -}); - -client.set("string key", "string val", redis.print); -client.hset("hash key", "hashtest 1", "some value", redis.print); -client.hset(["hash key", "hashtest 2", "some other value"], redis.print); -client.hkeys("hash key", function (err, replies) { - if (err) { - return console.error("error response - " + err); - } - - console.log(replies.length + " replies:"); - replies.forEach(function (reply, i) { - console.log(" " + i + ": " + reply); - }); -}); - -client.quit(function (err, res) { - console.log("Exiting from quit command."); -}); diff --git a/node_modules/redis/examples/sort.js b/node_modules/redis/examples/sort.js deleted file mode 100644 index e7c6249..0000000 --- a/node_modules/redis/examples/sort.js +++ /dev/null @@ -1,17 +0,0 @@ -var redis = require("redis"), - client = redis.createClient(); - -client.sadd("mylist", 1); -client.sadd("mylist", 2); -client.sadd("mylist", 3); - -client.set("weight_1", 5); -client.set("weight_2", 500); -client.set("weight_3", 1); - -client.set("object_1", "foo"); -client.set("object_2", "bar"); -client.set("object_3", "qux"); - -client.sort("mylist", "by", "weight_*", "get", "object_*", redis.print); -// Prints Reply: qux,foo,bar \ No newline at end of file diff --git a/node_modules/redis/examples/subqueries.js b/node_modules/redis/examples/subqueries.js deleted file mode 100644 index 560db24..0000000 --- a/node_modules/redis/examples/subqueries.js +++ /dev/null @@ -1,15 +0,0 @@ -// Sending commands in response to other commands. -// This example runs "type" against every key in the database -// -var client = require("redis").createClient(); - -client.keys("*", function (err, keys) { - keys.forEach(function (key, pos) { - client.type(key, function (err, keytype) { - console.log(key + " is " + keytype); - if (pos === (keys.length - 1)) { - client.quit(); - } - }); - }); -}); diff --git a/node_modules/redis/examples/subquery.js b/node_modules/redis/examples/subquery.js deleted file mode 100644 index 861657e..0000000 --- a/node_modules/redis/examples/subquery.js +++ /dev/null @@ -1,19 +0,0 @@ -var client = require("redis").createClient(); - -function print_results(obj) { - console.dir(obj); -} - -// build a map of all keys and their types -client.keys("*", function (err, all_keys) { - var key_types = {}; - - all_keys.forEach(function (key, pos) { // use second arg of forEach to get pos - client.type(key, function (err, type) { - key_types[key] = type; - if (pos === all_keys.length - 1) { // callbacks all run in order - print_results(key_types); - } - }); - }); -}); diff --git a/node_modules/redis/examples/unix_socket.js b/node_modules/redis/examples/unix_socket.js deleted file mode 100644 index 4a5e0bb..0000000 --- a/node_modules/redis/examples/unix_socket.js +++ /dev/null @@ -1,29 +0,0 @@ -var redis = require("redis"), - client = redis.createClient("/tmp/redis.sock"), - profiler = require("v8-profiler"); - -client.on("connect", function () { - console.log("Got Unix socket connection.") -}); - -client.on("error", function (err) { - console.log(err.message); -}); - -client.set("space chars", "space value"); - -setInterval(function () { - client.get("space chars"); -}, 100); - -function done() { - client.info(function (err, reply) { - console.log(reply.toString()); - client.quit(); - }); -} - -setTimeout(function () { - console.log("Taking snapshot."); - var snap = profiler.takeSnapshot(); -}, 5000); diff --git a/node_modules/redis/examples/web_server.js b/node_modules/redis/examples/web_server.js deleted file mode 100644 index 9fd8592..0000000 --- a/node_modules/redis/examples/web_server.js +++ /dev/null @@ -1,31 +0,0 @@ -// A simple web server that generates dyanmic content based on responses from Redis - -var http = require("http"), server, - redis_client = require("redis").createClient(); - -server = http.createServer(function (request, response) { - response.writeHead(200, { - "Content-Type": "text/plain" - }); - - var redis_info, total_requests; - - redis_client.info(function (err, reply) { - redis_info = reply; // stash response in outer scope - }); - redis_client.incr("requests", function (err, reply) { - total_requests = reply; // stash response in outer scope - }); - redis_client.hincrby("ip", request.connection.remoteAddress, 1); - redis_client.hgetall("ip", function (err, reply) { - // This is the last reply, so all of the previous replies must have completed already - response.write("This page was generated after talking to redis.\n\n" + - "Redis info:\n" + redis_info + "\n" + - "Total requests: " + total_requests + "\n\n" + - "IP count: \n"); - Object.keys(reply).forEach(function (ip) { - response.write(" " + ip + ": " + reply[ip] + "\n"); - }); - response.end(); - }); -}).listen(80); diff --git a/node_modules/redis/generate_commands.js b/node_modules/redis/generate_commands.js deleted file mode 100644 index e6949d3..0000000 --- a/node_modules/redis/generate_commands.js +++ /dev/null @@ -1,39 +0,0 @@ -var http = require("http"), - fs = require("fs"); - -function prettyCurrentTime() { - var date = new Date(); - return date.toLocaleString(); -} - -function write_file(commands, path) { - var file_contents, out_commands; - - console.log("Writing " + Object.keys(commands).length + " commands to " + path); - - file_contents = "// This file was generated by ./generate_commands.js on " + prettyCurrentTime() + "\n"; - - out_commands = Object.keys(commands).map(function (key) { - return key.toLowerCase(); - }); - - file_contents += "module.exports = " + JSON.stringify(out_commands, null, " ") + ";\n"; - - fs.writeFile(path, file_contents); -} - -http.get({host: "redis.io", path: "/commands.json"}, function (res) { - var body = ""; - - console.log("Response from redis.io/commands.json: " + res.statusCode); - - res.on('data', function (chunk) { - body += chunk; - }); - - res.on('end', function () { - write_file(JSON.parse(body), "lib/commands.js"); - }); -}).on('error', function (e) { - console.log("Error fetching command list from redis.io: " + e.message); -}); diff --git a/node_modules/redis/index.js b/node_modules/redis/index.js deleted file mode 100644 index 5edd3bf..0000000 --- a/node_modules/redis/index.js +++ /dev/null @@ -1,955 +0,0 @@ -/*global Buffer require exports console setTimeout */ - -var net = require("net"), - util = require("./lib/util").util, - Queue = require("./lib/queue").Queue, - to_array = require("./lib/to_array"), - events = require("events"), - parsers = [], commands, - connection_id = 0, - default_port = 6379, - default_host = "127.0.0.1"; - -// can set this to true to enable for all connections -exports.debug_mode = false; - -// hiredis might not be installed -try { - require("./lib/parser/hiredis"); - parsers.push(require("./lib/parser/hiredis")); -} catch (err) { - if (exports.debug_mode) { - console.warn("hiredis parser not installed."); - } -} - -parsers.push(require("./lib/parser/javascript")); - -function RedisClient(stream, options) { - this.stream = stream; - this.options = options = options || {}; - - this.connection_id = ++connection_id; - this.connected = false; - this.ready = false; - this.connections = 0; - this.should_buffer = false; - this.command_queue_high_water = this.options.command_queue_high_water || 1000; - this.command_queue_low_water = this.options.command_queue_low_water || 0; - this.max_attempts = null; - if (options.max_attempts && !isNaN(options.max_attempts) && options.max_attempts > 0) { - this.max_attempts = +options.max_attempts; - } - this.command_queue = new Queue(); // holds sent commands to de-pipeline them - this.offline_queue = new Queue(); // holds commands issued but not able to be sent - this.commands_sent = 0; - this.connect_timeout = false; - if (options.connect_timeout && !isNaN(options.connect_timeout) && options.connect_timeout > 0) { - this.connect_timeout = +options.connect_timeout; - } - this.initialize_retry_vars(); - this.subscriptions = false; - this.monitoring = false; - this.closing = false; - this.server_info = {}; - this.auth_pass = null; - this.parser_module = null; - this.selected_db = null; // save the selected db here, used when reconnecting - - var self = this; - - this.stream.on("connect", function () { - self.on_connect(); - }); - - this.stream.on("data", function (buffer_from_socket) { - self.on_data(buffer_from_socket); - }); - - this.stream.on("error", function (msg) { - self.on_error(msg.message); - }); - - this.stream.on("close", function () { - self.connection_gone("close"); - }); - - this.stream.on("end", function () { - self.connection_gone("end"); - }); - - this.stream.on("drain", function () { - self.should_buffer = false; - self.emit("drain"); - }); - - events.EventEmitter.call(this); -} -util.inherits(RedisClient, events.EventEmitter); -exports.RedisClient = RedisClient; - -RedisClient.prototype.initialize_retry_vars = function () { - this.retry_timer = null; - this.retry_totaltime = 0; - this.retry_delay = 250; - this.retry_backoff = 1.7; - this.attempts = 1; -}; - -// flush offline_queue and command_queue, erroring any items with a callback first -RedisClient.prototype.flush_and_error = function (message) { - var command_obj; - while (this.offline_queue.length > 0) { - command_obj = this.offline_queue.shift(); - if (typeof command_obj.callback === "function") { - command_obj.callback(message); - } - } - this.offline_queue = new Queue(); - - while (this.command_queue.length > 0) { - command_obj = this.command_queue.shift(); - if (typeof command_obj.callback === "function") { - command_obj.callback(message); - } - } - this.command_queue = new Queue(); -}; - -RedisClient.prototype.on_error = function (msg) { - var message = "Redis connection to " + this.host + ":" + this.port + " failed - " + msg, - self = this, command_obj; - - if (this.closing) { - return; - } - - if (exports.debug_mode) { - console.warn(message); - } - - this.flush_and_error(message); - - this.connected = false; - this.ready = false; - - this.emit("error", new Error(message)); - // "error" events get turned into exceptions if they aren't listened for. If the user handled this error - // then we should try to reconnect. - this.connection_gone("error"); -}; - -RedisClient.prototype.do_auth = function () { - var self = this; - - if (exports.debug_mode) { - console.log("Sending auth to " + self.host + ":" + self.port + " id " + self.connection_id); - } - self.send_anyway = true; - self.send_command("auth", [this.auth_pass], function (err, res) { - if (err) { - if (err.toString().match("LOADING")) { - // if redis is still loading the db, it will not authenticate and everything else will fail - console.log("Redis still loading, trying to authenticate later"); - setTimeout(function () { - self.do_auth(); - }, 2000); // TODO - magic number alert - return; - } else { - return self.emit("error", "Auth error: " + err); - } - } - if (res.toString() !== "OK") { - return self.emit("error", "Auth failed: " + res.toString()); - } - if (exports.debug_mode) { - console.log("Auth succeeded " + self.host + ":" + self.port + " id " + self.connection_id); - } - if (self.auth_callback) { - self.auth_callback(err, res); - self.auth_callback = null; - } - - // restore the selected db if needed - if (self.selected_db !== null) { - self.send_command('select', [self.selected_db]); - } - - // now we are really connected - self.emit("connect"); - if (self.options.no_ready_check) { - self.ready = true; - self.send_offline_queue(); - } else { - self.ready_check(); - } - }); - self.send_anyway = false; -}; - -RedisClient.prototype.on_connect = function () { - if (exports.debug_mode) { - console.log("Stream connected " + this.host + ":" + this.port + " id " + this.connection_id); - } - var self = this; - - this.connected = true; - this.ready = false; - this.attempts = 0; - this.connections += 1; - this.command_queue = new Queue(); - this.emitted_end = false; - this.initialize_retry_vars(); - this.stream.setNoDelay(); - this.stream.setTimeout(0); - - this.init_parser(); - - if (this.auth_pass) { - this.do_auth(); - } else { - // restore the selected db if needed - if (this.selected_db !== null) { - this.send_command('select', [this.selected_db]); - } - - this.emit("connect"); - - if (this.options.no_ready_check) { - this.ready = true; - this.send_offline_queue(); - } else { - this.ready_check(); - } - } -}; - -RedisClient.prototype.init_parser = function () { - var self = this; - - if (this.options.parser) { - if (! parsers.some(function (parser) { - if (parser.name === self.options.parser) { - this.parser_module = parser; - if (exports.debug_mode) { - console.log("Using parser module: " + self.parser_module.name); - } - return true; - } - })) { - throw new Error("Couldn't find named parser " + self.options.parser + " on this system"); - } - } else { - if (exports.debug_mode) { - console.log("Using default parser module: " + parsers[0].name); - } - this.parser_module = parsers[0]; - } - - this.parser_module.debug_mode = exports.debug_mode; - - this.reply_parser = new this.parser_module.Parser({ - return_buffers: self.options.return_buffers || false - }); - // "reply error" is an error sent back by Redis - this.reply_parser.on("reply error", function (reply) { - self.return_error(new Error(reply)); - }); - this.reply_parser.on("reply", function (reply) { - self.return_reply(reply); - }); - // "error" is bad. Somehow the parser got confused. It'll try to reset and continue. - this.reply_parser.on("error", function (err) { - self.emit("error", new Error("Redis reply parser error: " + err.stack)); - }); -}; - -RedisClient.prototype.on_info_cmd = function (err, res) { - var self = this, obj = {}, lines, retry_time; - - if (err) { - return self.emit("error", "Ready check failed: " + err); - } - - lines = res.toString().split("\r\n"); - - lines.forEach(function (line) { - var parts = line.split(':'); - if (parts[1]) { - obj[parts[0]] = parts[1]; - } - }); - - obj.versions = []; - obj.redis_version.split('.').forEach(function (num) { - obj.versions.push(+num); - }); - - // expose info key/vals to users - this.server_info = obj; - - if (!obj.loading || (obj.loading && obj.loading === "0")) { - if (exports.debug_mode) { - console.log("Redis server ready."); - } - this.ready = true; - - this.send_offline_queue(); - this.emit("ready"); - } else { - retry_time = obj.loading_eta_seconds * 1000; - if (retry_time > 1000) { - retry_time = 1000; - } - if (exports.debug_mode) { - console.log("Redis server still loading, trying again in " + retry_time); - } - setTimeout(function () { - self.ready_check(); - }, retry_time); - } -}; - -RedisClient.prototype.ready_check = function () { - var self = this; - - if (exports.debug_mode) { - console.log("checking server ready state..."); - } - - this.send_anyway = true; // secret flag to send_command to send something even if not "ready" - this.info(function (err, res) { - self.on_info_cmd(err, res); - }); - this.send_anyway = false; -}; - -RedisClient.prototype.send_offline_queue = function () { - var command_obj, buffered_writes = 0; - while (this.offline_queue.length > 0) { - command_obj = this.offline_queue.shift(); - if (exports.debug_mode) { - console.log("Sending offline command: " + command_obj.command); - } - buffered_writes += !this.send_command(command_obj.command, command_obj.args, command_obj.callback); - } - this.offline_queue = new Queue(); - // Even though items were shifted off, Queue backing store still uses memory until next add, so just get a new Queue - - if (!buffered_writes) { - this.should_buffer = false; - this.emit("drain"); - } -}; - -RedisClient.prototype.connection_gone = function (why) { - var self = this, message; - - // If a retry is already in progress, just let that happen - if (this.retry_timer) { - return; - } - - if (exports.debug_mode) { - console.warn("Redis connection is gone from " + why + " event."); - } - this.connected = false; - this.ready = false; - this.subscriptions = false; - this.monitoring = false; - - // since we are collapsing end and close, users don't expect to be called twice - if (! this.emitted_end) { - this.emit("end"); - this.emitted_end = true; - } - - this.flush_and_error("Redis connection gone from " + why + " event."); - - // If this is a requested shutdown, then don't retry - if (this.closing) { - this.retry_timer = null; - if (exports.debug_mode) { - console.warn("connection ended from quit command, not retrying."); - } - return; - } - - this.retry_delay = Math.floor(this.retry_delay * this.retry_backoff); - - if (exports.debug_mode) { - console.log("Retry connection in " + this.current_retry_delay + " ms"); - } - - if (this.max_attempts && this.attempts >= this.max_attempts) { - this.retry_timer = null; - // TODO - some people need a "Redis is Broken mode" for future commands that errors immediately, and others - // want the program to exit. Right now, we just log, which doesn't really help in either case. - console.error("node_redis: Couldn't get Redis connection after " + this.max_attempts + " attempts."); - return; - } - - this.attempts += 1; - this.emit("reconnecting", { - delay: self.retry_delay, - attempt: self.attempts - }); - this.retry_timer = setTimeout(function () { - if (exports.debug_mode) { - console.log("Retrying connection..."); - } - - self.retry_totaltime += self.current_retry_delay; - - if (self.connect_timeout && self.retry_totaltime >= self.connect_timeout) { - self.retry_timer = null; - // TODO - engage Redis is Broken mode for future commands, or whatever - console.error("node_redis: Couldn't get Redis connection after " + self.retry_totaltime + "ms."); - return; - } - - self.stream.connect(self.port, self.host); - self.retry_timer = null; - }, this.retry_delay); -}; - -RedisClient.prototype.on_data = function (data) { - if (exports.debug_mode) { - console.log("net read " + this.host + ":" + this.port + " id " + this.connection_id + ": " + data.toString()); - } - - try { - this.reply_parser.execute(data); - } catch (err) { - // This is an unexpected parser problem, an exception that came from the parser code itself. - // Parser should emit "error" events if it notices things are out of whack. - // Callbacks that throw exceptions will land in return_reply(), below. - // TODO - it might be nice to have a different "error" event for different types of errors - this.emit("error", err); - } -}; - -RedisClient.prototype.return_error = function (err) { - var command_obj = this.command_queue.shift(), queue_len = this.command_queue.getLength(); - - if (this.subscriptions === false && queue_len === 0) { - this.emit("idle"); - this.command_queue = new Queue(); - } - if (this.should_buffer && queue_len <= this.command_queue_low_water) { - this.emit("drain"); - this.should_buffer = false; - } - - if (command_obj && typeof command_obj.callback === "function") { - try { - command_obj.callback(err); - } catch (callback_err) { - // if a callback throws an exception, re-throw it on a new stack so the parser can keep going - process.nextTick(function () { - throw callback_err; - }); - } - } else { - console.log("node_redis: no callback to send error: " + err.message); - // this will probably not make it anywhere useful, but we might as well throw - process.nextTick(function () { - throw err; - }); - } -}; - -// if a callback throws an exception, re-throw it on a new stack so the parser can keep going. -// put this try/catch in its own function because V8 doesn't optimize this well yet. -function try_callback(callback, reply) { - try { - callback(null, reply); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } -} - -RedisClient.prototype.return_reply = function (reply) { - var command_obj, obj, i, len, key, val, type, timestamp, argindex, args, queue_len; - - queue_len = this.command_queue.getLength(); - - if (this.subscriptions === false && queue_len === 0) { - this.emit("idle"); - this.command_queue = new Queue(); // explicitly reclaim storage from old Queue - } - if (this.should_buffer && queue_len <= this.command_queue_low_water) { - this.emit("drain"); - this.should_buffer = false; - } - - command_obj = this.command_queue.shift(); - - if (command_obj && !command_obj.sub_command) { - if (typeof command_obj.callback === "function") { - // HGETALL special case replies with keyed Buffers - if (reply && 'hgetall' === command_obj.command.toLowerCase()) { - obj = {}; - for (i = 0, len = reply.length; i < len; i += 2) { - key = reply[i].toString(); - val = reply[i + 1]; - obj[key] = val; - } - reply = obj; - } - - try_callback(command_obj.callback, reply); - } else if (exports.debug_mode) { - console.log("no callback for reply: " + (reply && reply.toString && reply.toString())); - } - } else if (this.subscriptions || (command_obj && command_obj.sub_command)) { - if (Array.isArray(reply)) { - type = reply[0].toString(); - - if (type === "message") { - this.emit("message", reply[1].toString(), reply[2]); // channel, message - } else if (type === "pmessage") { - this.emit("pmessage", reply[1].toString(), reply[2].toString(), reply[3]); // pattern, channel, message - } else if (type === "subscribe" || type === "unsubscribe" || type === "psubscribe" || type === "punsubscribe") { - if (reply[2] === 0) { - this.subscriptions = false; - if (this.debug_mode) { - console.log("All subscriptions removed, exiting pub/sub mode"); - } - } - // subscribe commands take an optional callback and also emit an event, but only the first response is included in the callback - // TODO - document this - if (command_obj && typeof command_obj.callback === "function") { - try_callback(command_obj.callback, reply[1].toString()); - } - this.emit(type, reply[1].toString(), reply[2]); // channel, count - } else { - throw new Error("subscriptions are active but got unknown reply type " + type); - } - } else if (! this.closing) { - throw new Error("subscriptions are active but got an invalid reply: " + reply); - } - } else if (this.monitoring) { - len = reply.indexOf(" "); - timestamp = reply.slice(0, len); - argindex = reply.indexOf('"'); - args = reply.slice(argindex + 1, -1).split('" "').map(function (elem) { - return elem.replace(/\\"/g, '"'); - }); - this.emit("monitor", timestamp, args); - } else { - throw new Error("node_redis command queue state error. If you can reproduce this, please report it."); - } -}; - -// This Command constructor is ever so slightly faster than using an object literal, but more importantly, using -// a named constructor helps it show up meaningfully in the V8 CPU profiler and in heap snapshots. -function Command(command, args, sub_command, callback) { - this.command = command; - this.args = args; - this.sub_command = sub_command; - this.callback = callback; -} - -RedisClient.prototype.send_command = function (command, args, callback) { - var arg, this_args, command_obj, i, il, elem_count, stream = this.stream, buffer_args, command_str = "", buffered_writes = 0, last_arg_type; - - if (typeof command !== "string") { - throw new Error("First argument to send_command must be the command name string, not " + typeof command); - } - - if (Array.isArray(args)) { - if (typeof callback === "function") { - // probably the fastest way: - // client.command([arg1, arg2], cb); (straight passthrough) - // send_command(command, [arg1, arg2], cb); - } else if (! callback) { - // most people find this variable argument length form more convenient, but it uses arguments, which is slower - // client.command(arg1, arg2, cb); (wraps up arguments into an array) - // send_command(command, [arg1, arg2, cb]); - // client.command(arg1, arg2); (callback is optional) - // send_command(command, [arg1, arg2]); - // client.command(arg1, arg2, undefined); (callback is undefined) - // send_command(command, [arg1, arg2, undefined]); - last_arg_type = typeof args[args.length - 1]; - if (last_arg_type === "function" || last_arg_type === "undefined") { - callback = args.pop(); - } - } else { - throw new Error("send_command: last argument must be a callback or undefined"); - } - } else { - throw new Error("send_command: second argument must be an array"); - } - - // if the last argument is an array, expand it out. This allows commands like this: - // client.command(arg1, [arg2, arg3, arg4], cb); - // and converts to: - // client.command(arg1, arg2, arg3, arg4, cb); - // which is convenient for some things like sadd - if (Array.isArray(args[args.length - 1])) { - args = args.slice(0, -1).concat(args[args.length - 1]); - } - - command_obj = new Command(command, args, false, callback); - - if ((!this.ready && !this.send_anyway) || !stream.writable) { - if (exports.debug_mode) { - if (!stream.writable) { - console.log("send command: stream is not writeable."); - } - - console.log("Queueing " + command + " for next server connection."); - } - this.offline_queue.push(command_obj); - this.should_buffer = true; - return false; - } - - if (command === "subscribe" || command === "psubscribe" || command === "unsubscribe" || command === "punsubscribe") { - if (this.subscriptions === false && exports.debug_mode) { - console.log("Entering pub/sub mode from " + command); - } - command_obj.sub_command = true; - this.subscriptions = true; - } else if (command === "monitor") { - this.monitoring = true; - } else if (command === "quit") { - this.closing = true; - } else if (this.subscriptions === true) { - throw new Error("Connection in pub/sub mode, only pub/sub commands may be used"); - } - this.command_queue.push(command_obj); - this.commands_sent += 1; - - elem_count = 1; - buffer_args = false; - - elem_count += args.length; - - // Always use "Multi bulk commands", but if passed any Buffer args, then do multiple writes, one for each arg - // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer. - // Also, why am I putting user documentation in the library source code? - - command_str = "*" + elem_count + "\r\n$" + command.length + "\r\n" + command + "\r\n"; - - for (i = 0, il = args.length, arg; i < il; i += 1) { - if (Buffer.isBuffer(args[i])) { - buffer_args = true; - } - } - - if (! buffer_args) { // Build up a string and send entire command in one write - for (i = 0, il = args.length, arg; i < il; i += 1) { - arg = args[i]; - if (typeof arg !== "string") { - arg = String(arg); - } - command_str += "$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"; - } - if (exports.debug_mode) { - console.log("send " + this.host + ":" + this.port + " id " + this.connection_id + ": " + command_str); - } - buffered_writes += !stream.write(command_str); - } else { - if (exports.debug_mode) { - console.log("send command (" + command_str + ") has Buffer arguments"); - } - buffered_writes += !stream.write(command_str); - - for (i = 0, il = args.length, arg; i < il; i += 1) { - arg = args[i]; - if (!(Buffer.isBuffer(arg) || arg instanceof String)) { - arg = String(arg); - } - - if (Buffer.isBuffer(arg)) { - if (arg.length === 0) { - if (exports.debug_mode) { - console.log("send_command: using empty string for 0 length buffer"); - } - buffered_writes += !stream.write("$0\r\n\r\n"); - } else { - buffered_writes += !stream.write("$" + arg.length + "\r\n"); - buffered_writes += !stream.write(arg); - buffered_writes += !stream.write("\r\n"); - if (exports.debug_mode) { - console.log("send_command: buffer send " + arg.length + " bytes"); - } - } - } else { - if (exports.debug_mode) { - console.log("send_command: string send " + Buffer.byteLength(arg) + " bytes: " + arg); - } - buffered_writes += !stream.write("$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"); - } - } - } - if (exports.debug_mode) { - console.log("send_command buffered_writes: " + buffered_writes, " should_buffer: " + this.should_buffer); - } - if (buffered_writes || this.command_queue.getLength() >= this.command_queue_high_water) { - this.should_buffer = true; - } - return !this.should_buffer; -}; - -RedisClient.prototype.end = function () { - this.stream._events = {}; - this.connected = false; - this.ready = false; - return this.stream.end(); -}; - -function Multi(client, args) { - this.client = client; - this.queue = [["MULTI"]]; - if (Array.isArray(args)) { - this.queue = this.queue.concat(args); - } -} - -exports.Multi = Multi; - -// take 2 arrays and return the union of their elements -function set_union(seta, setb) { - var obj = {}; - - seta.forEach(function (val) { - obj[val] = true; - }); - setb.forEach(function (val) { - obj[val] = true; - }); - return Object.keys(obj); -} - -// This static list of commands is updated from time to time. ./lib/commands.js can be updated with generate_commands.js -commands = set_union(["get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", - "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", - "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", - "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", - "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", - "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", - "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", - "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", - "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", - "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); - -commands.forEach(function (command) { - RedisClient.prototype[command] = function (args, callback) { - if (Array.isArray(args) && typeof callback === "function") { - return this.send_command(command, args, callback); - } else { - return this.send_command(command, to_array(arguments)); - } - }; - RedisClient.prototype[command.toUpperCase()] = RedisClient.prototype[command]; - - Multi.prototype[command] = function () { - this.queue.push([command].concat(to_array(arguments))); - return this; - }; - Multi.prototype[command.toUpperCase()] = Multi.prototype[command]; -}); - -// store db in this.select_db to restore it on reconnect -RedisClient.prototype.select = function (db, callback) { - var self = this; - - this.send_command('select', [db], function (err, res) { - if (err === null) { - self.selected_db = db; - } - if (typeof(callback) === 'function') { - callback(err, res); - } - }); -}; -RedisClient.prototype.SELECT = RedisClient.prototype.select; - -// Stash auth for connect and reconnect. Send immediately if already connected. -RedisClient.prototype.auth = function () { - var args = to_array(arguments); - this.auth_pass = args[0]; - this.auth_callback = args[1]; - if (exports.debug_mode) { - console.log("Saving auth as " + this.auth_pass); - } - - if (this.connected) { - this.send_command("auth", args); - } -}; -RedisClient.prototype.AUTH = RedisClient.prototype.auth; - -RedisClient.prototype.hmget = function (arg1, arg2, arg3) { - if (Array.isArray(arg2) && typeof arg3 === "function") { - return this.send_command("hmget", [arg1].concat(arg2), arg3); - } else if (Array.isArray(arg1) && typeof arg2 === "function") { - return this.send_command("hmget", arg1, arg2); - } else { - return this.send_command("hmget", to_array(arguments)); - } -}; -RedisClient.prototype.HMGET = RedisClient.prototype.hmget; - -RedisClient.prototype.hmset = function (args, callback) { - var tmp_args, tmp_keys, i, il, key; - - if (Array.isArray(args) && typeof callback === "function") { - return this.send_command("hmset", args, callback); - } - - args = to_array(arguments); - if (typeof args[args.length - 1] === "function") { - callback = args[args.length - 1]; - args.length -= 1; - } else { - callback = null; - } - - if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object") { - // User does: client.hmset(key, {key1: val1, key2: val2}) - tmp_args = [ args[0] ]; - tmp_keys = Object.keys(args[1]); - for (i = 0, il = tmp_keys.length; i < il ; i++) { - key = tmp_keys[i]; - tmp_args.push(key); - tmp_args.push(args[1][key]); - } - args = tmp_args; - } - - return this.send_command("hmset", args, callback); -}; -RedisClient.prototype.HMSET = RedisClient.prototype.hmset; - -Multi.prototype.hmset = function () { - var args = to_array(arguments), tmp_args; - if (args.length >= 2 && typeof args[0] === "string" && typeof args[1] === "object") { - tmp_args = [ "hmset", args[0] ]; - Object.keys(args[1]).map(function (key) { - tmp_args.push(key); - tmp_args.push(args[1][key]); - }); - if (args[2]) { - tmp_args.push(args[2]); - } - args = tmp_args; - } else { - args.unshift("hmset"); - } - - this.queue.push(args); - return this; -}; -Multi.prototype.HMSET = Multi.prototype.hmset; - -Multi.prototype.exec = function (callback) { - var self = this; - - // drain queue, callback will catch "QUEUED" or error - // TODO - get rid of all of these anonymous functions which are elegant but slow - this.queue.forEach(function (args, index) { - var command = args[0], obj; - if (typeof args[args.length - 1] === "function") { - args = args.slice(1, -1); - } else { - args = args.slice(1); - } - if (args.length === 1 && Array.isArray(args[0])) { - args = args[0]; - } - if (command === 'hmset' && typeof args[1] === 'object') { - obj = args.pop(); - Object.keys(obj).forEach(function (key) { - args.push(key); - args.push(obj[key]); - }); - } - this.client.send_command(command, args, function (err, reply) { - if (err) { - var cur = self.queue[index]; - if (typeof cur[cur.length - 1] === "function") { - cur[cur.length - 1](err); - } else { - throw new Error(err); - } - self.queue.splice(index, 1); - } - }); - }, this); - - // TODO - make this callback part of Multi.prototype instead of creating it each time - return this.client.send_command("EXEC", [], function (err, replies) { - if (err) { - if (callback) { - callback(new Error(err)); - return; - } else { - throw new Error(err); - } - } - - var i, il, j, jl, reply, args, obj, key, val; - - if (replies) { - for (i = 1, il = self.queue.length; i < il; i += 1) { - reply = replies[i - 1]; - args = self.queue[i]; - - // Convert HGETALL reply to object - if (reply && args[0].toLowerCase() === "hgetall") { - obj = {}; - for (j = 0, jl = reply.length; j < jl; j += 2) { - key = reply[j].toString(); - val = reply[j + 1]; - obj[key] = val; - } - replies[i - 1] = reply = obj; - } - - if (typeof args[args.length - 1] === "function") { - args[args.length - 1](null, reply); - } - } - } - - if (callback) { - callback(null, replies); - } - }); -}; - -RedisClient.prototype.multi = function (args) { - return new Multi(this, args); -}; -RedisClient.prototype.MULTI = function (args) { - return new Multi(this, args); -}; - -exports.createClient = function (port_arg, host_arg, options) { - var port = port_arg || default_port, - host = host_arg || default_host, - redis_client, net_client; - - net_client = net.createConnection(port, host); - - redis_client = new RedisClient(net_client, options); - - redis_client.port = port; - redis_client.host = host; - - return redis_client; -}; - -exports.print = function (err, reply) { - if (err) { - console.log("Error: " + err); - } else { - console.log("Reply: " + reply); - } -}; diff --git a/node_modules/redis/lib/commands.js b/node_modules/redis/lib/commands.js deleted file mode 100644 index 0293ae8..0000000 --- a/node_modules/redis/lib/commands.js +++ /dev/null @@ -1,126 +0,0 @@ -// This file was generated by ./generate_commands.js on Tue Jun 28 2011 22:37:02 GMT-0700 (PDT) -module.exports = [ - "append", - "auth", - "bgrewriteaof", - "bgsave", - "blpop", - "brpop", - "brpoplpush", - "config get", - "config set", - "config resetstat", - "dbsize", - "debug object", - "debug segfault", - "decr", - "decrby", - "del", - "discard", - "echo", - "exec", - "exists", - "expire", - "expireat", - "flushall", - "flushdb", - "get", - "getbit", - "getrange", - "getset", - "hdel", - "hexists", - "hget", - "hgetall", - "hincrby", - "hkeys", - "hlen", - "hmget", - "hmset", - "hset", - "hsetnx", - "hvals", - "incr", - "incrby", - "info", - "keys", - "lastsave", - "lindex", - "linsert", - "llen", - "lpop", - "lpush", - "lpushx", - "lrange", - "lrem", - "lset", - "ltrim", - "mget", - "monitor", - "move", - "mset", - "msetnx", - "multi", - "object", - "persist", - "ping", - "psubscribe", - "publish", - "punsubscribe", - "quit", - "randomkey", - "rename", - "renamenx", - "rpop", - "rpoplpush", - "rpush", - "rpushx", - "sadd", - "save", - "scard", - "sdiff", - "sdiffstore", - "select", - "set", - "setbit", - "setex", - "setnx", - "setrange", - "shutdown", - "sinter", - "sinterstore", - "sismember", - "slaveof", - "smembers", - "smove", - "sort", - "spop", - "srandmember", - "srem", - "strlen", - "subscribe", - "sunion", - "sunionstore", - "sync", - "ttl", - "type", - "unsubscribe", - "unwatch", - "watch", - "zadd", - "zcard", - "zcount", - "zincrby", - "zinterstore", - "zrange", - "zrangebyscore", - "zrank", - "zrem", - "zremrangebyrank", - "zremrangebyscore", - "zrevrange", - "zrevrangebyscore", - "zrevrank", - "zscore", - "zunionstore" -]; diff --git a/node_modules/redis/lib/parser/hiredis.js b/node_modules/redis/lib/parser/hiredis.js deleted file mode 100644 index e7db743..0000000 --- a/node_modules/redis/lib/parser/hiredis.js +++ /dev/null @@ -1,46 +0,0 @@ -/*global Buffer require exports console setTimeout */ - -var events = require("events"), - util = require("../util").util, - hiredis = require("hiredis"); - -exports.debug_mode = false; -exports.name = "hiredis"; - -function HiredisReplyParser(options) { - this.name = exports.name; - this.options = options || {}; - this.reset(); - events.EventEmitter.call(this); -} - -util.inherits(HiredisReplyParser, events.EventEmitter); - -exports.Parser = HiredisReplyParser; - -HiredisReplyParser.prototype.reset = function () { - this.reader = new hiredis.Reader({ - return_buffers: this.options.return_buffers || false - }); -}; - -HiredisReplyParser.prototype.execute = function (data) { - var reply; - this.reader.feed(data); - while (true) { - try { - reply = this.reader.get(); - } catch (err) { - this.emit("error", err); - break; - } - - if (reply === undefined) break; - - if (reply && reply.constructor === Error) { - this.emit("reply error", reply); - } else { - this.emit("reply", reply); - } - } -}; diff --git a/node_modules/redis/lib/parser/javascript.js b/node_modules/redis/lib/parser/javascript.js deleted file mode 100644 index f90bcc6..0000000 --- a/node_modules/redis/lib/parser/javascript.js +++ /dev/null @@ -1,317 +0,0 @@ -/*global Buffer require exports console setTimeout */ - -// TODO - incorporate these V8 pro tips: -// pre-allocate Arrays if length is known in advance -// do not use delete -// use numbers for parser state - -var events = require("events"), - util = require("../util").util; - -exports.debug_mode = false; -exports.name = "javascript"; - -function RedisReplyParser(options) { - this.name = exports.name; - this.options = options || {}; - this.reset(); - events.EventEmitter.call(this); -} - -util.inherits(RedisReplyParser, events.EventEmitter); - -exports.Parser = RedisReplyParser; - -// Buffer.toString() is quite slow for small strings -function small_toString(buf, len) { - var tmp = "", i; - - for (i = 0; i < len; i += 1) { - tmp += String.fromCharCode(buf[i]); - } - - return tmp; -} - -// Reset parser to it's original state. -RedisReplyParser.prototype.reset = function () { - this.return_buffer = new Buffer(16384); // for holding replies, might grow - this.return_string = ""; - this.tmp_string = ""; // for holding size fields - - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; - this.multi_bulk_nested_length = 0; - this.multi_bulk_nested_replies = null; - - this.states = { - TYPE: 1, - SINGLE_LINE: 2, - MULTI_BULK_COUNT: 3, - INTEGER_LINE: 4, - BULK_LENGTH: 5, - ERROR_LINE: 6, - BULK_DATA: 7, - UNKNOWN_TYPE: 8, - FINAL_CR: 9, - FINAL_LF: 10, - MULTI_BULK_COUNT_LF: 11, - BULK_LF: 12 - }; - - this.state = this.states.TYPE; -}; - -RedisReplyParser.prototype.parser_error = function (message) { - this.emit("error", message); - this.reset(); -}; - -RedisReplyParser.prototype.execute = function (incoming_buf) { - var pos = 0, bd_tmp, bd_str, i, il, states = this.states; - //, state_times = {}, start_execute = new Date(), start_switch, end_switch, old_state; - //start_switch = new Date(); - - while (pos < incoming_buf.length) { - // old_state = this.state; - // console.log("execute: " + this.state + ", " + pos + "/" + incoming_buf.length + ", " + String.fromCharCode(incoming_buf[pos])); - - switch (this.state) { - case 1: // states.TYPE - this.type = incoming_buf[pos]; - pos += 1; - - switch (this.type) { - case 43: // + - this.state = states.SINGLE_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - case 42: // * - this.state = states.MULTI_BULK_COUNT; - this.tmp_string = ""; - break; - case 58: // : - this.state = states.INTEGER_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - case 36: // $ - this.state = states.BULK_LENGTH; - this.tmp_string = ""; - break; - case 45: // - - this.state = states.ERROR_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - default: - this.state = states.UNKNOWN_TYPE; - } - break; - case 4: // states.INTEGER_LINE - if (incoming_buf[pos] === 13) { - this.send_reply(+small_toString(this.return_buffer, this.return_buffer.end)); - this.state = states.FINAL_LF; - } else { - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - } - pos += 1; - break; - case 6: // states.ERROR_LINE - if (incoming_buf[pos] === 13) { - this.send_error(this.return_buffer.toString("ascii", 0, this.return_buffer.end)); - this.state = states.FINAL_LF; - } else { - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - } - pos += 1; - break; - case 2: // states.SINGLE_LINE - if (incoming_buf[pos] === 13) { - this.send_reply(this.return_string); - this.state = states.FINAL_LF; - } else { - this.return_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case 3: // states.MULTI_BULK_COUNT - if (incoming_buf[pos] === 13) { // \r - this.state = states.MULTI_BULK_COUNT_LF; - } else { - this.tmp_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case 11: // states.MULTI_BULK_COUNT_LF - if (incoming_buf[pos] === 10) { // \n - if (this.multi_bulk_length) { // nested multi-bulk - this.multi_bulk_nested_length = this.multi_bulk_length; - this.multi_bulk_nested_replies = this.multi_bulk_replies; - this.multi_bulk_nested_pos = this.multi_bulk_pos; - } - this.multi_bulk_length = +this.tmp_string; - this.multi_bulk_pos = 0; - this.state = states.TYPE; - if (this.multi_bulk_length < 0) { - this.send_reply(null); - this.multi_bulk_length = 0; - } else if (this.multi_bulk_length === 0) { - this.multi_bulk_pos = 0; - this.multi_bulk_replies = null; - this.send_reply([]); - } else { - this.multi_bulk_replies = new Array(this.multi_bulk_length); - } - } else { - this.parser_error(new Error("didn't see LF after NL reading multi bulk count")); - return; - } - pos += 1; - break; - case 5: // states.BULK_LENGTH - if (incoming_buf[pos] === 13) { // \r - this.state = states.BULK_LF; - } else { - this.tmp_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case 12: // states.BULK_LF - if (incoming_buf[pos] === 10) { // \n - this.bulk_length = +this.tmp_string; - if (this.bulk_length === -1) { - this.send_reply(null); - this.state = states.TYPE; - } else if (this.bulk_length === 0) { - this.send_reply(new Buffer("")); - this.state = states.FINAL_CR; - } else { - this.state = states.BULK_DATA; - if (this.bulk_length > this.return_buffer.length) { - if (exports.debug_mode) { - console.log("Growing return_buffer from " + this.return_buffer.length + " to " + this.bulk_length); - } - this.return_buffer = new Buffer(this.bulk_length); - } - this.return_buffer.end = 0; - } - } else { - this.parser_error(new Error("didn't see LF after NL while reading bulk length")); - return; - } - pos += 1; - break; - case 7: // states.BULK_DATA - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - pos += 1; - if (this.return_buffer.end === this.bulk_length) { - bd_tmp = new Buffer(this.bulk_length); - // When the response is small, Buffer.copy() is a lot slower. - if (this.bulk_length > 10) { - this.return_buffer.copy(bd_tmp, 0, 0, this.bulk_length); - } else { - for (i = 0, il = this.bulk_length; i < il; i += 1) { - bd_tmp[i] = this.return_buffer[i]; - } - } - this.send_reply(bd_tmp); - this.state = states.FINAL_CR; - } - break; - case 9: // states.FINAL_CR - if (incoming_buf[pos] === 13) { // \r - this.state = states.FINAL_LF; - pos += 1; - } else { - this.parser_error(new Error("saw " + incoming_buf[pos] + " when expecting final CR")); - return; - } - break; - case 10: // states.FINAL_LF - if (incoming_buf[pos] === 10) { // \n - this.state = states.TYPE; - pos += 1; - } else { - this.parser_error(new Error("saw " + incoming_buf[pos] + " when expecting final LF")); - return; - } - break; - default: - this.parser_error(new Error("invalid state " + this.state)); - } - // end_switch = new Date(); - // if (state_times[old_state] === undefined) { - // state_times[old_state] = 0; - // } - // state_times[old_state] += (end_switch - start_switch); - // start_switch = end_switch; - } - // console.log("execute ran for " + (Date.now() - start_execute) + " ms, on " + incoming_buf.length + " Bytes. "); - // Object.keys(state_times).forEach(function (state) { - // console.log(" " + state + ": " + state_times[state]); - // }); -}; - -RedisReplyParser.prototype.send_error = function (reply) { - if (this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0) { - // TODO - can this happen? Seems like maybe not. - this.add_multi_bulk_reply(reply); - } else { - this.emit("reply error", reply); - } -}; - -RedisReplyParser.prototype.send_reply = function (reply) { - if (this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0) { - if (!this.options.return_buffers && Buffer.isBuffer(reply)) { - this.add_multi_bulk_reply(reply.toString("utf8")); - } else { - this.add_multi_bulk_reply(reply); - } - } else { - if (!this.options.return_buffers && Buffer.isBuffer(reply)) { - this.emit("reply", reply.toString("utf8")); - } else { - this.emit("reply", reply); - } - } -}; - -RedisReplyParser.prototype.add_multi_bulk_reply = function (reply) { - if (this.multi_bulk_replies) { - this.multi_bulk_replies[this.multi_bulk_pos] = reply; - this.multi_bulk_pos += 1; - if (this.multi_bulk_pos < this.multi_bulk_length) { - return; - } - } else { - this.multi_bulk_replies = reply; - } - - if (this.multi_bulk_nested_length > 0) { - this.multi_bulk_nested_replies[this.multi_bulk_nested_pos] = this.multi_bulk_replies; - this.multi_bulk_nested_pos += 1; - - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; - - if (this.multi_bulk_nested_length === this.multi_bulk_nested_pos) { - this.emit("reply", this.multi_bulk_nested_replies); - this.multi_bulk_nested_length = 0; - this.multi_bulk_nested_pos = 0; - this.multi_bulk_nested_replies = null; - } - } else { - this.emit("reply", this.multi_bulk_replies); - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; - } -}; diff --git a/node_modules/redis/lib/queue.js b/node_modules/redis/lib/queue.js deleted file mode 100644 index 61587b4..0000000 --- a/node_modules/redis/lib/queue.js +++ /dev/null @@ -1,58 +0,0 @@ -var to_array = require("./to_array"); - -// Queue class adapted from Tim Caswell's pattern library -// http://github.com/creationix/pattern/blob/master/lib/pattern/queue.js - -function Queue() { - this.tail = []; - this.head = []; - this.offset = 0; -} - -Queue.prototype.shift = function () { - if (this.offset === this.head.length) { - var tmp = this.head; - tmp.length = 0; - this.head = this.tail; - this.tail = tmp; - this.offset = 0; - if (this.head.length === 0) { - return; - } - } - return this.head[this.offset++]; // sorry, JSLint -}; - -Queue.prototype.push = function (item) { - return this.tail.push(item); -}; - -Queue.prototype.forEach = function (fn, thisv) { - var array = this.head.slice(this.offset), i, il; - - array.push.apply(array, this.tail); - - if (thisv) { - for (i = 0, il = array.length; i < il; i += 1) { - fn.call(thisv, array[i], i, array); - } - } else { - for (i = 0, il = array.length; i < il; i += 1) { - fn(array[i], i, array); - } - } - - return array; -}; - -Queue.prototype.getLength = function () { - return this.head.length - this.offset + this.tail.length; -}; - -Object.defineProperty(Queue.prototype, 'length', { - get: function () { - return this.getLength(); - } -}); - -exports.Queue = Queue; diff --git a/node_modules/redis/lib/to_array.js b/node_modules/redis/lib/to_array.js deleted file mode 100644 index 88a57e1..0000000 --- a/node_modules/redis/lib/to_array.js +++ /dev/null @@ -1,12 +0,0 @@ -function to_array(args) { - var len = args.length, - arr = new Array(len), i; - - for (i = 0; i < len; i += 1) { - arr[i] = args[i]; - } - - return arr; -} - -module.exports = to_array; diff --git a/node_modules/redis/lib/util.js b/node_modules/redis/lib/util.js deleted file mode 100644 index 632631c..0000000 --- a/node_modules/redis/lib/util.js +++ /dev/null @@ -1,7 +0,0 @@ -// Support for very old versions of node. At some point, we should abandon this. -var minor = process.versions.node.split('.')[1]; -if (minor > 2) { - exports.util = require("util"); -} else { - exports.util = require("sys"); -} diff --git a/node_modules/redis/multi_bench.js b/node_modules/redis/multi_bench.js deleted file mode 100644 index 5be2e56..0000000 --- a/node_modules/redis/multi_bench.js +++ /dev/null @@ -1,225 +0,0 @@ -var redis = require("./index"), - metrics = require("metrics"), - num_clients = parseInt(process.argv[2], 10) || 5, - num_requests = 20000, - tests = [], - versions_logged = false, - client_options = { - return_buffers: false - }, - small_str, large_str, small_buf, large_buf; - -redis.debug_mode = false; - -function lpad(input, len, chr) { - var str = input.toString(); - chr = chr || " "; - - while (str.length < len) { - str = chr + str; - } - return str; -} - -metrics.Histogram.prototype.print_line = function () { - var obj = this.printObj(); - - return lpad(obj.min, 4) + "/" + lpad(obj.max, 4) + "/" + lpad(obj.mean.toFixed(2), 7) + "/" + lpad(obj.p95.toFixed(2), 7); -}; - -function Test(args) { - var self = this; - - this.args = args; - - this.callback = null; - this.clients = []; - this.clients_ready = 0; - this.commands_sent = 0; - this.commands_completed = 0; - this.max_pipeline = this.args.pipeline || num_requests; - this.client_options = args.client_options || client_options; - - this.connect_latency = new metrics.Histogram(); - this.ready_latency = new metrics.Histogram(); - this.command_latency = new metrics.Histogram(); -} - -Test.prototype.run = function (callback) { - var self = this, i; - - this.callback = callback; - - for (i = 0; i < num_clients ; i++) { - this.new_client(i); - } -}; - -Test.prototype.new_client = function (id) { - var self = this, new_client; - - new_client = redis.createClient(6379, "127.0.0.1", this.client_options); - new_client.create_time = Date.now(); - - new_client.on("connect", function () { - self.connect_latency.update(Date.now() - new_client.create_time); - }); - - new_client.on("ready", function () { - if (! versions_logged) { - console.log("Client count: " + num_clients + ", node version: " + process.versions.node + ", server version: " + - new_client.server_info.redis_version + ", parser: " + new_client.reply_parser.name); - versions_logged = true; - } - self.ready_latency.update(Date.now() - new_client.create_time); - self.clients_ready++; - if (self.clients_ready === self.clients.length) { - self.on_clients_ready(); - } - }); - - self.clients[id] = new_client; -}; - -Test.prototype.on_clients_ready = function () { - process.stdout.write(lpad(this.args.descr, 13) + ", " + lpad(this.args.pipeline, 5) + "/" + this.clients_ready + " "); - this.test_start = Date.now(); - - this.fill_pipeline(); -}; - -Test.prototype.fill_pipeline = function () { - var pipeline = this.commands_sent - this.commands_completed; - - while (this.commands_sent < num_requests && pipeline < this.max_pipeline) { - this.commands_sent++; - pipeline++; - this.send_next(); - } - - if (this.commands_completed === num_requests) { - this.print_stats(); - this.stop_clients(); - } -}; - -Test.prototype.stop_clients = function () { - var self = this; - - this.clients.forEach(function (client, pos) { - if (pos === self.clients.length - 1) { - client.quit(function (err, res) { - self.callback(); - }); - } else { - client.quit(); - } - }); -}; - -Test.prototype.send_next = function () { - var self = this, - cur_client = this.commands_sent % this.clients.length, - command_num = this.commands_sent, - start = Date.now(); - - this.clients[cur_client][this.args.command](this.args.args, function (err, res) { - if (err) { - throw err; - } - self.commands_completed++; - self.command_latency.update(Date.now() - start); - self.fill_pipeline(); - }); -}; - -Test.prototype.print_stats = function () { - var duration = Date.now() - this.test_start; - - console.log("min/max/avg/p95: " + this.command_latency.print_line() + " " + lpad(duration, 6) + "ms total, " + - lpad((num_requests / (duration / 1000)).toFixed(2), 8) + " ops/sec"); -}; - -small_str = "1234"; -small_buf = new Buffer(small_str); -large_str = (new Array(4097).join("-")); -large_buf = new Buffer(large_str); - -tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 1})); -tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 50})); -tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 200})); -tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 20000})); - -tests.push(new Test({descr: "SET small str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 1})); -tests.push(new Test({descr: "SET small str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 50})); -tests.push(new Test({descr: "SET small str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 200})); -tests.push(new Test({descr: "SET small str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 20000})); - -tests.push(new Test({descr: "SET small buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 1})); -tests.push(new Test({descr: "SET small buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 50})); -tests.push(new Test({descr: "SET small buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 200})); -tests.push(new Test({descr: "SET small buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 20000})); - -tests.push(new Test({descr: "GET small str", command: "get", args: ["foo_rand000000000000"], pipeline: 1})); -tests.push(new Test({descr: "GET small str", command: "get", args: ["foo_rand000000000000"], pipeline: 50})); -tests.push(new Test({descr: "GET small str", command: "get", args: ["foo_rand000000000000"], pipeline: 200})); -tests.push(new Test({descr: "GET small str", command: "get", args: ["foo_rand000000000000"], pipeline: 20000})); - -tests.push(new Test({descr: "GET small buf", command: "get", args: ["foo_rand000000000000"], pipeline: 1, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET small buf", command: "get", args: ["foo_rand000000000000"], pipeline: 50, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET small buf", command: "get", args: ["foo_rand000000000000"], pipeline: 200, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET small buf", command: "get", args: ["foo_rand000000000000"], pipeline: 20000, client_opts: { return_buffers: true} })); - -tests.push(new Test({descr: "SET large str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 1})); -tests.push(new Test({descr: "SET large str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 50})); -tests.push(new Test({descr: "SET large str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 200})); -tests.push(new Test({descr: "SET large str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 20000})); - -tests.push(new Test({descr: "SET large buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 1})); -tests.push(new Test({descr: "SET large buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 50})); -tests.push(new Test({descr: "SET large buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 200})); -tests.push(new Test({descr: "SET large buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 20000})); - -tests.push(new Test({descr: "GET large str", command: "get", args: ["foo_rand000000000001"], pipeline: 1})); -tests.push(new Test({descr: "GET large str", command: "get", args: ["foo_rand000000000001"], pipeline: 50})); -tests.push(new Test({descr: "GET large str", command: "get", args: ["foo_rand000000000001"], pipeline: 200})); -tests.push(new Test({descr: "GET large str", command: "get", args: ["foo_rand000000000001"], pipeline: 20000})); - -tests.push(new Test({descr: "GET large buf", command: "get", args: ["foo_rand000000000001"], pipeline: 1, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET large buf", command: "get", args: ["foo_rand000000000001"], pipeline: 50, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET large buf", command: "get", args: ["foo_rand000000000001"], pipeline: 200, client_opts: { return_buffers: true} })); -tests.push(new Test({descr: "GET large buf", command: "get", args: ["foo_rand000000000001"], pipeline: 20000, client_opts: { return_buffers: true} })); - -tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 1})); -tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 50})); -tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 200})); -tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 20000})); - -tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 1})); -tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 50})); -tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 200})); -tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 20000})); - -tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 1})); -tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 50})); -tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 200})); -tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 20000})); - -tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 1})); -tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 50})); -tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 200})); -tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 20000})); - -function next() { - var test = tests.shift(); - if (test) { - test.run(function () { - next(); - }); - } else { - console.log("End of tests."); - process.exit(0); - } -} - -next(); diff --git a/node_modules/redis/package.json b/node_modules/redis/package.json deleted file mode 100644 index cf1248c..0000000 --- a/node_modules/redis/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ "name" : "redis", - "version" : "0.7.1", - "description" : "Redis client library", - "author": "Matt Ranney ", - "contributors": [ - "Rick Olson", - "Tim-Smart", - "TJ Holowaychuk", - "Orion Henry", - "Hank Sims", - "Aivo Paas", - "Paul Carey", - "Pieter Noordhuis", - "Andy Ray", - "Vladimir Dronnikov", - "Dave Hoover" - ], - "main": "./index.js", - "scripts": { - "test": "node ./test.js" - }, - "devDependencies": { - "metrics": ">=0.1.5" - }, - "repository": { - "type": "git", - "url": "git://github.com/mranney/node_redis.git" - } -} diff --git a/node_modules/redis/test.js b/node_modules/redis/test.js deleted file mode 100644 index 3c68d40..0000000 --- a/node_modules/redis/test.js +++ /dev/null @@ -1,1301 +0,0 @@ -/*global require console setTimeout process Buffer */ -var redis = require("./index"), - client = redis.createClient(), - client2 = redis.createClient(), - client3 = redis.createClient(), - client4 = redis.createClient(9006, "filefish.redistogo.com"), - client5 = redis.createClient(), - assert = require("assert"), - util = require("./lib/util").util, - test_db_num = 15, // this DB will be flushed and used for testing - tests = {}, - connected = false, - ended = false, - next, cur_start, run_next_test, all_tests, all_start, test_count; - -// Set this to truthy to see the wire protocol and other debugging info -redis.debug_mode = process.argv[2]; - -function buffers_to_strings(arr) { - return arr.map(function (val) { - return val.toString(); - }); -} - -function require_number(expected, label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(expected, results, label + " " + expected + " !== " + results); - assert.strictEqual(typeof results, "number", label); - return true; - }; -} - -function require_number_any(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(typeof results, "number", label + " " + results + " is not a number"); - return true; - }; -} - -function require_number_pos(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(true, (results > 0), label + " " + results + " is not a positive number"); - return true; - }; -} - -function require_string(str, label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.equal(str, results, label + " " + str + " does not match " + results); - return true; - }; -} - -function require_null(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(null, results, label + ": " + results + " is not null"); - return true; - }; -} - -function require_error(label) { - return function (err, results) { - assert.notEqual(err, null, label + " err is null, but an error is expected here."); - return true; - }; -} - -function is_empty_array(obj) { - return Array.isArray(obj) && obj.length === 0; -} - -function last(name, fn) { - return function (err, results) { - fn(err, results); - next(name); - }; -} - -next = function next(name) { - console.log(" \x1b[33m" + (Date.now() - cur_start) + "\x1b[0m ms"); - run_next_test(); -}; - -// Tests are run in the order they are defined. So FLUSHDB should be stay first. - -tests.FLUSHDB = function () { - var name = "FLUSHDB"; - client.select(test_db_num, require_string("OK", name)); - client2.select(test_db_num, require_string("OK", name)); - client3.select(test_db_num, require_string("OK", name)); - client.mset("flush keys 1", "flush val 1", "flush keys 2", "flush val 2", require_string("OK", name)); - client.FLUSHDB(require_string("OK", name)); - client.dbsize(last(name, require_number(0, name))); -}; - -tests.MULTI_1 = function () { - var name = "MULTI_1", multi1, multi2; - - // Provoke an error at queue time - multi1 = client.multi(); - multi1.mset("multifoo", "10", "multibar", "20", require_string("OK", name)); - multi1.set("foo2", require_error(name)); - multi1.incr("multifoo", require_number(11, name)); - multi1.incr("multibar", require_number(21, name)); - multi1.exec(); - - // Confirm that the previous command, while containing an error, still worked. - multi2 = client.multi(); - multi2.incr("multibar", require_number(22, name)); - multi2.incr("multifoo", require_number(12, name)); - multi2.exec(function (err, replies) { - assert.strictEqual(22, replies[0]); - assert.strictEqual(12, replies[1]); - next(name); - }); -}; - -tests.MULTI_2 = function () { - var name = "MULTI_2"; - - // test nested multi-bulk replies - client.multi([ - ["mget", "multifoo", "multibar", function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("12", res[0].toString(), name); - assert.strictEqual("22", res[1].toString(), name); - }], - ["set", "foo2", require_error(name)], - ["incr", "multifoo", require_number(13, name)], - ["incr", "multibar", require_number(23, name)] - ]).exec(function (err, replies) { - assert.strictEqual(2, replies[0].length, name); - assert.strictEqual("12", replies[0][0].toString(), name); - assert.strictEqual("22", replies[0][1].toString(), name); - - assert.strictEqual("13", replies[1].toString()); - assert.strictEqual("23", replies[2].toString()); - next(name); - }); -}; - -tests.MULTI_3 = function () { - var name = "MULTI_3"; - - client.sadd("some set", "mem 1"); - client.sadd("some set", "mem 2"); - client.sadd("some set", "mem 3"); - client.sadd("some set", "mem 4"); - - // make sure empty mb reply works - client.del("some missing set"); - client.smembers("some missing set", function (err, reply) { - // make sure empty mb reply works - assert.strictEqual(true, is_empty_array(reply), name); - }); - - // test nested multi-bulk replies with empty mb elements. - client.multi([ - ["smembers", "some set"], - ["del", "some set"], - ["smembers", "some set"] - ]) - .scard("some set") - .exec(function (err, replies) { - assert.strictEqual(true, is_empty_array(replies[2]), name); - next(name); - }); -}; - -tests.MULTI_4 = function () { - var name = "MULTI_4"; - - client.multi() - .mset('some', '10', 'keys', '20') - .incr('some') - .incr('keys') - .mget('some', 'keys') - .exec(function (err, replies) { - assert.strictEqual(null, err); - assert.equal('OK', replies[0]); - assert.equal(11, replies[1]); - assert.equal(21, replies[2]); - assert.equal(11, replies[3][0].toString()); - assert.equal(21, replies[3][1].toString()); - next(name); - }); -}; - -tests.MULTI_5 = function () { - var name = "MULTI_5"; - - // test nested multi-bulk replies with nulls. - client.multi([ - ["mget", ["multifoo", "some", "random value", "keys"]], - ["incr", "multifoo"] - ]) - .exec(function (err, replies) { - assert.strictEqual(replies.length, 2, name); - assert.strictEqual(replies[0].length, 4, name); - next(name); - }); -}; - -tests.MULTI_6 = function () { - var name = "MULTI_6"; - - client.multi() - .hmset("multihash", "a", "foo", "b", 1) - .hmset("multihash", { - extra: "fancy", - things: "here" - }) - .hgetall("multihash") - .exec(function (err, replies) { - assert.strictEqual(null, err); - assert.equal("OK", replies[0]); - assert.equal(Object.keys(replies[2]).length, 4); - assert.equal("foo", replies[2].a); - assert.equal("1", replies[2].b); - assert.equal("fancy", replies[2].extra); - assert.equal("here", replies[2].things); - next(name); - }); -}; - -tests.EVAL_1 = function () { - var name = "EVAL_1"; - - if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 9) { - // test {EVAL - Lua integer -> Redis protocol type conversion} - client.eval("return 100.5", 0, require_number(100, name)); - // test {EVAL - Lua string -> Redis protocol type conversion} - client.eval("return 'hello world'", 0, require_string("hello world", name)); - // test {EVAL - Lua true boolean -> Redis protocol type conversion} - client.eval("return true", 0, require_number(1, name)); - // test {EVAL - Lua false boolean -> Redis protocol type conversion} - client.eval("return false", 0, require_null(name)); - // test {EVAL - Lua status code reply -> Redis protocol type conversion} - client.eval("return {ok='fine'}", 0, require_string("fine", name)); - // test {EVAL - Lua error reply -> Redis protocol type conversion} - client.eval("return {err='this is an error'}", 0, require_error(name)); - // test {EVAL - Lua table -> Redis protocol type conversion} - client.eval("return {1,2,3,'ciao',{1,2}}", 0, function (err, res) { - assert.strictEqual(5, res.length, name); - assert.strictEqual(1, res[0], name); - assert.strictEqual(2, res[1], name); - assert.strictEqual(3, res[2], name); - assert.strictEqual("ciao", res[3], name); - assert.strictEqual(2, res[4].length, name); - assert.strictEqual(1, res[4][0], name); - assert.strictEqual(2, res[4][1], name); - }); - // test {EVAL - Are the KEYS and ARGS arrays populated correctly?} - client.eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", 2, "a", "b", "c", "d", function (err, res) { - assert.strictEqual(4, res.length, name); - assert.strictEqual("a", res[0], name); - assert.strictEqual("b", res[1], name); - assert.strictEqual("c", res[2], name); - assert.strictEqual("d", res[3], name); - }); - // test {EVAL - is Lua able to call Redis API?} - client.set("mykey", "myval"); - client.eval("return redis.call('get','mykey')", 0, require_string("myval", name)); - // test {EVALSHA - Can we call a SHA1 if already defined?} - client.evalsha("9bd632c7d33e571e9f24556ebed26c3479a87129", 0, require_string("myval", name)); - // test {EVALSHA - Do we get an error on non defined SHA1?} - client.evalsha("ffffffffffffffffffffffffffffffffffffffff", 0, require_error(name)); - // test {EVAL - Redis integer -> Lua type conversion} - client.set("x", 0); - client.eval("local foo = redis.call('incr','x')\n" + "return {type(foo),foo}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("number", res[0], name); - assert.strictEqual(1, res[1], name); - }); - // test {EVAL - Redis bulk -> Lua type conversion} - client.eval("local foo = redis.call('get','mykey'); return {type(foo),foo}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("string", res[0], name); - assert.strictEqual("myval", res[1], name); - }); - // test {EVAL - Redis multi bulk -> Lua type conversion} - client.del("mylist"); - client.rpush("mylist", "a"); - client.rpush("mylist", "b"); - client.rpush("mylist", "c"); - client.eval("local foo = redis.call('lrange','mylist',0,-1)\n" + "return {type(foo),foo[1],foo[2],foo[3],# foo}", 0, function (err, res) { - assert.strictEqual(5, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("a", res[1], name); - assert.strictEqual("b", res[2], name); - assert.strictEqual("c", res[3], name); - assert.strictEqual(3, res[4], name); - }); - // test {EVAL - Redis status reply -> Lua type conversion} - client.eval("local foo = redis.call('set','mykey','myval'); return {type(foo),foo['ok']}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("OK", res[1], name); - }); - // test {EVAL - Redis error reply -> Lua type conversion} - client.set("mykey", "myval"); - client.eval("local foo = redis.call('incr','mykey'); return {type(foo),foo['err']}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("ERR value is not an integer or out of range", res[1], name); - }); - // test {EVAL - Redis nil bulk reply -> Lua type conversion} - client.del("mykey"); - client.eval("local foo = redis.call('get','mykey'); return {type(foo),foo == false}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("boolean", res[0], name); - assert.strictEqual(1, res[1], name); - }); - // test {EVAL - Script can't run more than configured time limit} { - client.config("set", "lua-time-limit", 1); - client.eval("local i = 0; while true do i=i+1 end", 0, last("name", require_error(name))); - } else { - console.log("Skipping " + name + " because server version isn't new enough."); - next(name); - } -}; - -tests.WATCH_MULTI = function () { - var name = 'WATCH_MULTI', multi; - - if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 1) { - client.watch(name); - client.incr(name); - multi = client.multi(); - multi.incr(name); - multi.exec(last(name, require_null(name))); - } else { - console.log("Skipping " + name + " because server version isn't new enough."); - next(name); - } -}; - -tests.reconnect = function () { - var name = "reconnect"; - - client.set("recon 1", "one"); - client.set("recon 2", "two", function (err, res) { - // Do not do this in normal programs. This is to simulate the server closing on us. - // For orderly shutdown in normal programs, do client.quit() - client.stream.destroy(); - }); - - client.on("reconnecting", function on_recon(params) { - client.on("connect", function on_connect() { - client.select(test_db_num, require_string("OK", name)); - client.get("recon 1", require_string("one", name)); - client.get("recon 1", require_string("one", name)); - client.get("recon 2", require_string("two", name)); - client.get("recon 2", require_string("two", name)); - client.removeListener("connect", on_connect); - client.removeListener("reconnecting", on_recon); - next(name); - }); - }); -}; - -tests.HSET = function () { - var key = "test hash", - field1 = new Buffer("0123456789"), - value1 = new Buffer("abcdefghij"), - field2 = new Buffer(0), - value2 = new Buffer(0), - name = "HSET"; - - client.HSET(key, field1, value1, require_number(1, name)); - client.HGET(key, field1, require_string(value1.toString(), name)); - - // Empty value - client.HSET(key, field1, value2, require_number(0, name)); - client.HGET([key, field1], require_string("", name)); - - // Empty key, empty value - client.HSET([key, field2, value1], require_number(1, name)); - client.HSET(key, field2, value2, last(name, require_number(0, name))); -}; - -tests.HMSET_BUFFER_AND_ARRAY = function () { - // Saving a buffer and an array to the same key should not error - var key = "test hash", - field1 = "buffer", - value1 = new Buffer("abcdefghij"), - field2 = "array", - value2 = ["array contents"], - name = "HSET"; - - client.HMSET(key, field1, value1, field2, value2, last(name, require_string("OK", name))); -}; - -// TODO - add test for HMSET with optional callbacks - -tests.HMGET = function () { - var key1 = "test hash 1", key2 = "test hash 2", name = "HMGET"; - - // redis-like hmset syntax - client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value", require_string("OK", name)); - - // fancy hmset syntax - client.HMSET(key2, { - "0123456789": "abcdefghij", - "some manner of key": "a type of value" - }, require_string("OK", name)); - - client.HMGET(key1, "0123456789", "some manner of key", function (err, reply) { - assert.strictEqual("abcdefghij", reply[0].toString(), name); - assert.strictEqual("a type of value", reply[1].toString(), name); - }); - - client.HMGET(key2, "0123456789", "some manner of key", function (err, reply) { - assert.strictEqual("abcdefghij", reply[0].toString(), name); - assert.strictEqual("a type of value", reply[1].toString(), name); - }); - - client.HMGET(key1, ["0123456789"], function (err, reply) { - assert.strictEqual("abcdefghij", reply[0], name); - }); - - client.HMGET(key1, ["0123456789", "some manner of key"], function (err, reply) { - assert.strictEqual("abcdefghij", reply[0], name); - assert.strictEqual("a type of value", reply[1], name); - }); - - client.HMGET(key1, "missing thing", "another missing thing", function (err, reply) { - assert.strictEqual(null, reply[0], name); - assert.strictEqual(null, reply[1], name); - next(name); - }); -}; - -tests.HINCRBY = function () { - var name = "HINCRBY"; - client.hset("hash incr", "value", 10, require_number(1, name)); - client.HINCRBY("hash incr", "value", 1, require_number(11, name)); - client.HINCRBY("hash incr", "value 2", 1, last(name, require_number(1, name))); -}; - -tests.SUBSCRIBE = function () { - var client1 = client, msg_count = 0, name = "SUBSCRIBE"; - - client1.on("subscribe", function (channel, count) { - if (channel === "chan1") { - client2.publish("chan1", "message 1", require_number(1, name)); - client2.publish("chan2", "message 2", require_number(1, name)); - client2.publish("chan1", "message 3", require_number(1, name)); - } - }); - - client1.on("unsubscribe", function (channel, count) { - if (count === 0) { - // make sure this connection can go into and out of pub/sub mode - client1.incr("did a thing", last(name, require_number(2, name))); - } - }); - - client1.on("message", function (channel, message) { - msg_count += 1; - assert.strictEqual("message " + msg_count, message.toString()); - if (msg_count === 3) { - client1.unsubscribe("chan1", "chan2"); - } - }); - - client1.set("did a thing", 1, require_string("OK", name)); - client1.subscribe("chan1", "chan2", function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual("chan1", results.toString(), name); - }); -}; - -tests.SUBSCRIBE_QUIT = function () { - var name = "SUBSCRIBE_QUIT"; - client3.on("end", function () { - next(name); - }); - client3.on("subscribe", function (channel, count) { - client3.quit(); - }); - client3.subscribe("chan3"); -}; - -tests.EXISTS = function () { - var name = "EXISTS"; - client.del("foo", "foo2", require_number_any(name)); - client.set("foo", "bar", require_string("OK", name)); - client.EXISTS("foo", require_number(1, name)); - client.EXISTS("foo2", last(name, require_number(0, name))); -}; - -tests.DEL = function () { - var name = "DEL"; - client.DEL("delkey", require_number_any(name)); - client.set("delkey", "delvalue", require_string("OK", name)); - client.DEL("delkey", require_number(1, name)); - client.exists("delkey", require_number(0, name)); - client.DEL("delkey", require_number(0, name)); - client.mset("delkey", "delvalue", "delkey2", "delvalue2", require_string("OK", name)); - client.DEL("delkey", "delkey2", last(name, require_number(2, name))); -}; - -tests.TYPE = function () { - var name = "TYPE"; - client.set(["string key", "should be a string"], require_string("OK", name)); - client.rpush(["list key", "should be a list"], require_number_pos(name)); - client.sadd(["set key", "should be a set"], require_number_any(name)); - client.zadd(["zset key", "10.0", "should be a zset"], require_number_any(name)); - client.hset(["hash key", "hashtest", "should be a hash"], require_number_any(0, name)); - - client.TYPE(["string key"], require_string("string", name)); - client.TYPE(["list key"], require_string("list", name)); - client.TYPE(["set key"], require_string("set", name)); - client.TYPE(["zset key"], require_string("zset", name)); - client.TYPE("not here yet", require_string("none", name)); - client.TYPE(["hash key"], last(name, require_string("hash", name))); -}; - -tests.KEYS = function () { - var name = "KEYS"; - client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); - client.KEYS(["test keys*"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(2, results.length, name); - assert.strictEqual("test keys 1", results[0].toString(), name); - assert.strictEqual("test keys 2", results[1].toString(), name); - next(name); - }); -}; - -tests.MULTIBULK_ZERO_LENGTH = function () { - var name = "MULTIBULK_ZERO_LENGTH"; - client.KEYS(['users:*'], function (err, results) { - assert.strictEqual(null, err, 'error on empty multibulk reply'); - assert.strictEqual(true, is_empty_array(results), "not an empty array"); - next(name); - }); -}; - -tests.RANDOMKEY = function () { - var name = "RANDOMKEY"; - client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); - client.RANDOMKEY([], function (err, results) { - assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); - assert.strictEqual(true, /\w+/.test(results), name); - next(name); - }); -}; - -tests.RENAME = function () { - var name = "RENAME"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.RENAME(["foo", "new foo"], require_string("OK", name)); - client.exists(["foo"], require_number(0, name)); - client.exists(["new foo"], last(name, require_number(1, name))); -}; - -tests.RENAMENX = function () { - var name = "RENAMENX"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.set(['foo2', 'bar2'], require_string("OK", name)); - client.RENAMENX(["foo", "foo2"], require_number(0, name)); - client.exists(["foo"], require_number(1, name)); - client.exists(["foo2"], require_number(1, name)); - client.del(["foo2"], require_number(1, name)); - client.RENAMENX(["foo", "foo2"], require_number(1, name)); - client.exists(["foo"], require_number(0, name)); - client.exists(["foo2"], last(name, require_number(1, name))); -}; - -tests.DBSIZE = function () { - var name = "DBSIZE"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.DBSIZE([], last(name, require_number_pos("DBSIZE"))); -}; - -tests.GET = function () { - var name = "GET"; - client.set(["get key", "get val"], require_string("OK", name)); - client.GET(["get key"], last(name, require_string("get val", name))); -}; - -tests.SET = function () { - var name = "SET"; - client.SET(["set key", "set val"], require_string("OK", name)); - client.get(["set key"], last(name, require_string("set val", name))); -}; - -tests.GETSET = function () { - var name = "GETSET"; - client.set(["getset key", "getset val"], require_string("OK", name)); - client.GETSET(["getset key", "new getset val"], require_string("getset val", name)); - client.get(["getset key"], last(name, require_string("new getset val", name))); -}; - -tests.MGET = function () { - var name = "MGET"; - client.mset(["mget keys 1", "mget val 1", "mget keys 2", "mget val 2", "mget keys 3", "mget val 3"], require_string("OK", name)); - client.MGET("mget keys 1", "mget keys 2", "mget keys 3", function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(3, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual("mget val 2", results[1].toString(), name); - assert.strictEqual("mget val 3", results[2].toString(), name); - }); - client.MGET(["mget keys 1", "mget keys 2", "mget keys 3"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(3, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual("mget val 2", results[1].toString(), name); - assert.strictEqual("mget val 3", results[2].toString(), name); - }); - client.MGET(["mget keys 1", "some random shit", "mget keys 2", "mget keys 3"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(4, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual(null, results[1], name); - assert.strictEqual("mget val 2", results[2].toString(), name); - assert.strictEqual("mget val 3", results[3].toString(), name); - next(name); - }); -}; - -tests.SETNX = function () { - var name = "SETNX"; - client.set(["setnx key", "setnx value"], require_string("OK", name)); - client.SETNX(["setnx key", "new setnx value"], require_number(0, name)); - client.del(["setnx key"], require_number(1, name)); - client.exists(["setnx key"], require_number(0, name)); - client.SETNX(["setnx key", "new setnx value"], require_number(1, name)); - client.exists(["setnx key"], last(name, require_number(1, name))); -}; - -tests.SETEX = function () { - var name = "SETEX"; - client.SETEX(["setex key", "100", "setex val"], require_string("OK", name)); - client.exists(["setex key"], require_number(1, name)); - client.ttl(["setex key"], last(name, require_number_pos(name))); -}; - -tests.MSETNX = function () { - var name = "MSETNX"; - client.mset(["mset1", "val1", "mset2", "val2", "mset3", "val3"], require_string("OK", name)); - client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(0, name)); - client.del(["mset3"], require_number(1, name)); - client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(1, name)); - client.exists(["mset3"], require_number(1, name)); - client.exists(["mset4"], last(name, require_number(1, name))); -}; - -tests.HGETALL = function () { - var name = "HGETALL"; - client.hmset(["hosts", "mjr", "1", "another", "23", "home", "1234"], require_string("OK", name)); - client.HGETALL(["hosts"], function (err, obj) { - assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); - assert.strictEqual(3, Object.keys(obj).length, name); - assert.strictEqual("1", obj.mjr.toString(), name); - assert.strictEqual("23", obj.another.toString(), name); - assert.strictEqual("1234", obj.home.toString(), name); - next(name); - }); -}; - -tests.HGETALL_NULL = function () { - var name = "HGETALL_NULL"; - - client.hgetall('missing', function (err, obj) { - assert.strictEqual(null, err); - assert.deepEqual([], obj); - next(name); - }); -}; - -tests.UTF8 = function () { - var name = "UTF8", - utf8_sample = "ಠ_ಠ"; - - client.set(["utf8test", utf8_sample], require_string("OK", name)); - client.get(["utf8test"], function (err, obj) { - assert.strictEqual(null, err); - assert.strictEqual(utf8_sample, obj); - next(name); - }); -}; - -// Set tests were adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite - -tests.SADD = function () { - var name = "SADD"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.sadd('set0', 'member0', last(name, require_number(0, name))); -}; - -tests.SADD2 = function () { - var name = "SADD2"; - - client.del("set0"); - client.sadd("set0", ["member0", "member1", "member2"], require_number(3, name)); - client.smembers("set0", function (err, res) { - assert.strictEqual(res.length, 3); - assert.strictEqual(res[0], "member0"); - assert.strictEqual(res[1], "member1"); - assert.strictEqual(res[2], "member2"); - next(name); - }); -}; - -tests.SISMEMBER = function () { - var name = "SISMEMBER"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.sismember('set0', 'member0', require_number(1, name)); - client.sismember('set0', 'member1', last(name, require_number(0, name))); -}; - -tests.SCARD = function () { - var name = "SCARD"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.scard('set0', require_number(1, name)); - client.sadd('set0', 'member1', require_number(1, name)); - client.scard('set0', last(name, require_number(2, name))); -}; - -tests.SREM = function () { - var name = "SREM"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.srem('set0', 'foobar', require_number(0, name)); - client.srem('set0', 'member0', require_number(1, name)); - client.scard('set0', last(name, require_number(0, name))); -}; - -tests.SPOP = function () { - var name = "SPOP"; - - client.del('zzz'); - client.sadd('zzz', 'member0', require_number(1, name)); - client.scard('zzz', require_number(1, name)); - - client.spop('zzz', function (err, value) { - if (err) { - assert.fail(err); - } - assert.equal(value, 'member0', name); - }); - - client.scard('zzz', last(name, require_number(0, name))); -}; - -tests.SDIFF = function () { - var name = "SDIFF"; - - client.del('foo'); - client.sadd('foo', 'x', require_number(1, name)); - client.sadd('foo', 'a', require_number(1, name)); - client.sadd('foo', 'b', require_number(1, name)); - client.sadd('foo', 'c', require_number(1, name)); - - client.sadd('bar', 'c', require_number(1, name)); - - client.sadd('baz', 'a', require_number(1, name)); - client.sadd('baz', 'd', require_number(1, name)); - - client.sdiff('foo', 'bar', 'baz', function (err, values) { - if (err) { - assert.fail(err, name); - } - values.sort(); - assert.equal(values.length, 2, name); - assert.equal(values[0], 'b', name); - assert.equal(values[1], 'x', name); - next(name); - }); -}; - -tests.SDIFFSTORE = function () { - var name = "SDIFFSTORE"; - - client.del('foo'); - client.del('bar'); - client.del('baz'); - client.del('quux'); - - client.sadd('foo', 'x', require_number(1, name)); - client.sadd('foo', 'a', require_number(1, name)); - client.sadd('foo', 'b', require_number(1, name)); - client.sadd('foo', 'c', require_number(1, name)); - - client.sadd('bar', 'c', require_number(1, name)); - - client.sadd('baz', 'a', require_number(1, name)); - client.sadd('baz', 'd', require_number(1, name)); - - // NB: SDIFFSTORE returns the number of elements in the dstkey - - client.sdiffstore('quux', 'foo', 'bar', 'baz', require_number(2, name)); - - client.smembers('quux', function (err, values) { - if (err) { - assert.fail(err, name); - } - var members = buffers_to_strings(values).sort(); - - assert.deepEqual(members, [ 'b', 'x' ], name); - next(name); - }); -}; - -tests.SMEMBERS = function () { - var name = "SMEMBERS"; - - client.del('foo'); - client.sadd('foo', 'x', require_number(1, name)); - - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(members), [ 'x' ], name); - }); - - client.sadd('foo', 'y', require_number(1, name)); - - client.smembers('foo', function (err, values) { - if (err) { - assert.fail(err, name); - } - assert.equal(values.length, 2, name); - var members = buffers_to_strings(values).sort(); - - assert.deepEqual(members, [ 'x', 'y' ], name); - next(name); - }); -}; - -tests.SMOVE = function () { - var name = "SMOVE"; - - client.del('foo'); - client.del('bar'); - - client.sadd('foo', 'x', require_number(1, name)); - client.smove('foo', 'bar', 'x', require_number(1, name)); - client.sismember('foo', 'x', require_number(0, name)); - client.sismember('bar', 'x', require_number(1, name)); - client.smove('foo', 'bar', 'x', last(name, require_number(0, name))); -}; - -tests.SINTER = function () { - var name = "SINTER"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); - - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); - - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); - - client.sinter('sa', 'sb', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 2, name); - assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'b', 'c' ], name); - }); - - client.sinter('sb', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 2, name); - assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'c', 'd' ], name); - }); - - client.sinter('sa', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 1, name); - assert.equal(intersection[0], 'c', name); - }); - - // 3-way - - client.sinter('sa', 'sb', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 1, name); - assert.equal(intersection[0], 'c', name); - next(name); - }); -}; - -tests.SINTERSTORE = function () { - var name = "SINTERSTORE"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - client.del('foo'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); - - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); - - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); - - client.sinterstore('foo', 'sa', 'sb', 'sc', require_number(1, name)); - - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(members), [ 'c' ], name); - next(name); - }); -}; - -tests.SUNION = function () { - var name = "SUNION"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); - - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); - - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); - - client.sunion('sa', 'sb', 'sc', function (err, union) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(union).sort(), ['a', 'b', 'c', 'd', 'e'], name); - next(name); - }); -}; - -tests.SUNIONSTORE = function () { - var name = "SUNIONSTORE"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - client.del('foo'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); - - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); - - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); - - client.sunionstore('foo', 'sa', 'sb', 'sc', function (err, cardinality) { - if (err) { - assert.fail(err, name); - } - assert.equal(cardinality, 5, name); - }); - - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.equal(members.length, 5, name); - assert.deepEqual(buffers_to_strings(members).sort(), ['a', 'b', 'c', 'd', 'e'], name); - next(name); - }); -}; - -// SORT test adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite - -tests.SORT = function () { - var name = "SORT"; - - client.del('y'); - client.del('x'); - - client.rpush('y', 'd', require_number(1, name)); - client.rpush('y', 'b', require_number(2, name)); - client.rpush('y', 'a', require_number(3, name)); - client.rpush('y', 'c', require_number(4, name)); - - client.rpush('x', '3', require_number(1, name)); - client.rpush('x', '9', require_number(2, name)); - client.rpush('x', '2', require_number(3, name)); - client.rpush('x', '4', require_number(4, name)); - - client.set('w3', '4', require_string("OK", name)); - client.set('w9', '5', require_string("OK", name)); - client.set('w2', '12', require_string("OK", name)); - client.set('w4', '6', require_string("OK", name)); - - client.set('o2', 'buz', require_string("OK", name)); - client.set('o3', 'foo', require_string("OK", name)); - client.set('o4', 'baz', require_string("OK", name)); - client.set('o9', 'bar', require_string("OK", name)); - - client.set('p2', 'qux', require_string("OK", name)); - client.set('p3', 'bux', require_string("OK", name)); - client.set('p4', 'lux', require_string("OK", name)); - client.set('p9', 'tux', require_string("OK", name)); - - // Now the data has been setup, we can test. - - // But first, test basic sorting. - - // y = [ d b a c ] - // sort y ascending = [ a b c d ] - // sort y descending = [ d c b a ] - - client.sort('y', 'asc', 'alpha', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['a', 'b', 'c', 'd'], name); - }); - - client.sort('y', 'desc', 'alpha', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['d', 'c', 'b', 'a'], name); - }); - - // Now try sorting numbers in a list. - // x = [ 3, 9, 2, 4 ] - - client.sort('x', 'asc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [2, 3, 4, 9], name); - }); - - client.sort('x', 'desc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [9, 4, 3, 2], name); - }); - - // Try sorting with a 'by' pattern. - - client.sort('x', 'by', 'w*', 'asc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [3, 9, 4, 2], name); - }); - - // Try sorting with a 'by' pattern and 1 'get' pattern. - - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bar', 'baz', 'buz'], name); - }); - - // Try sorting with a 'by' pattern and 2 'get' patterns. - - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); - }); - - // Try sorting with a 'by' pattern and 2 'get' patterns. - // Instead of getting back the sorted set/list, store the values to a list. - // Then check that the values are there in the expected order. - - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', function (err) { - if (err) { - assert.fail(err, name); - } - }); - - client.lrange('bacon', 0, -1, function (err, values) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(values), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); - next(name); - }); - - // TODO - sort by hash value -}; - -tests.MONITOR = function () { - var name = "MONITOR", responses = []; - - client5.monitor(function (err, res) { - client.mget("some", "keys", "foo", "bar"); - client.set("json", JSON.stringify({ - foo: "123", - bar: "sdflkdfsjk", - another: false - })); - }); - client5.on("monitor", function (time, args) { - responses.push(args); - if (responses.length === 3) { - assert.strictEqual(1, responses[0].length); - assert.strictEqual("monitor", responses[0][0]); - assert.strictEqual(5, responses[1].length); - assert.strictEqual("mget", responses[1][0]); - assert.strictEqual("some", responses[1][1]); - assert.strictEqual("keys", responses[1][2]); - assert.strictEqual("foo", responses[1][3]); - assert.strictEqual("bar", responses[1][4]); - assert.strictEqual(3, responses[2].length); - assert.strictEqual("set", responses[2][0]); - assert.strictEqual("json", responses[2][1]); - assert.strictEqual('{"foo":"123","bar":"sdflkdfsjk","another":false}', responses[2][2]); - next(name); - } - }); -}; - -tests.BLPOP = function () { - var name = "BLPOP"; - - client.rpush("blocking list", "initial value", function (err, res) { - client2.BLPOP("blocking list", 0, function (err, res) { - assert.strictEqual("blocking list", res[0].toString()); - assert.strictEqual("initial value", res[1].toString()); - - client.rpush("blocking list", "wait for this value"); - }); - client2.BLPOP("blocking list", 0, function (err, res) { - assert.strictEqual("blocking list", res[0].toString()); - assert.strictEqual("wait for this value", res[1].toString()); - next(name); - }); - }); -}; - -tests.BLPOP_TIMEOUT = function () { - var name = "BLPOP_TIMEOUT"; - - // try to BLPOP the list again, which should be empty. This should timeout and return null. - client2.BLPOP("blocking list", 1, function (err, res) { - if (err) { - throw err; - } - - assert.strictEqual(res, null); - next(name); - }); -}; - -tests.EXPIRE = function () { - var name = "EXPIRE"; - client.set(['expiry key', 'bar'], require_string("OK", name)); - client.EXPIRE(["expiry key", "1"], require_number_pos(name)); - setTimeout(function () { - client.exists(["expiry key"], last(name, require_number(0, name))); - }, 2000); -}; - -tests.TTL = function () { - var name = "TTL"; - client.set(["ttl key", "ttl val"], require_string("OK", name)); - client.expire(["ttl key", "100"], require_number_pos(name)); - setTimeout(function () { - client.TTL(["ttl key"], last(name, require_number_pos(0, name))); - }, 500); -}; - -tests.OPTIONAL_CALLBACK = function() { - var name = "OPTIONAL_CALLBACK"; - client.del("op_cb1"); - client.set("op_cb1", "x"); - client.get("op_cb1", last(name, require_string("x", name))); -}; - -tests.OPTIONAL_CALLBACK_UNDEFINED = function() { - var name = "OPTIONAL_CALLBACK_UNDEFINED"; - client.del("op_cb2"); - client.set("op_cb2", "y", undefined); - client.get("op_cb2", last(name, require_string("y", name))); -} - -all_tests = Object.keys(tests); -all_start = new Date(); -test_count = 0; - -run_next_test = function run_next_test() { - var test_name = all_tests.shift(); - if (typeof tests[test_name] === "function") { - util.print('- \x1b[1m' + test_name.toLowerCase() + '\x1b[0m:'); - cur_start = new Date(); - test_count += 1; - tests[test_name](); - } else { - console.log('\n completed \x1b[32m%d\x1b[0m tests in \x1b[33m%d\x1b[0m ms\n', test_count, new Date() - all_start); - client.quit(); - client2.quit(); - client4.quit(); - client5.quit(); - } -}; - -client.once("ready", function start_tests() { - console.log("Connected to " + client.host + ":" + client.port + ", Redis server version " + client.server_info.redis_version + "\n"); - console.log("Using reply parser " + client.reply_parser.name); - - run_next_test(); - - connected = true; -}); - -client.on('end', function () { - ended = true; -}); - -// TODO - need a better way to test auth, maybe auto-config a local Redis server? Sounds hard. -// Yes, this is the real password. Please be nice, thanks. -client4.auth("664b1b6aaf134e1ec281945a8de702a9", function (err, res) { - var name = "AUTH_4"; - - if (err) { - assert.fail(err, name); - } - assert.strictEqual("OK", res.toString(), "auth"); -}); - -// Exit immediately on connection failure, which triggers "exit", below, which fails the test -client.on("error", function (err) { - console.error("client: " + err.stack); - process.exit(); -}); -client2.on("error", function (err) { - console.error("client2: " + err.stack); - process.exit(); -}); -client3.on("error", function (err) { - console.error("client3: " + err.stack); - process.exit(); -}); -client5.on("error", function (err) { - console.error("client5: " + err.stack); - process.exit(); -}); - -client.on("reconnecting", function (params) { - console.log("reconnecting: " + util.inspect(params)); -}); - -process.on('uncaughtException', function (err) { - console.error("Uncaught exception: " + err.stack); - process.exit(1); -}); - -process.on('exit', function (code) { - assert.equal(true, connected); - assert.equal(true, ended); -}); diff --git a/node_modules/redis/tests/buffer_bench.js b/node_modules/redis/tests/buffer_bench.js deleted file mode 100644 index a504fbc..0000000 --- a/node_modules/redis/tests/buffer_bench.js +++ /dev/null @@ -1,89 +0,0 @@ -var source = new Buffer(100), - dest = new Buffer(100), i, j, k, tmp, count = 1000000, bytes = 100; - -for (i = 99 ; i >= 0 ; i--) { - source[i] = 120; -} - -var str = "This is a nice String.", - buf = new Buffer("This is a lovely Buffer."); - -var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (Buffer.isBuffer(str)) {} -} -var end = new Date(); -console.log("Buffer.isBuffer(str) " + (end - start) + " ms"); - -var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (Buffer.isBuffer(buf)) {} -} -var end = new Date(); -console.log("Buffer.isBuffer(buf) " + (end - start) + " ms"); - -var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (str instanceof Buffer) {} -} -var end = new Date(); -console.log("str instanceof Buffer " + (end - start) + " ms"); - -var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (buf instanceof Buffer) {} -} -var end = new Date(); -console.log("buf instanceof Buffer " + (end - start) + " ms"); - -for (i = bytes ; i > 0 ; i --) { - var start = new Date(); - for (j = count ; j > 0; j--) { - tmp = source.toString("ascii", 0, bytes); - } - var end = new Date(); - console.log("toString() " + i + " bytes " + (end - start) + " ms"); -} - -for (i = bytes ; i > 0 ; i --) { - var start = new Date(); - for (j = count ; j > 0; j--) { - tmp = ""; - for (k = 0; k <= i ; k++) { - tmp += String.fromCharCode(source[k]); - } - } - var end = new Date(); - console.log("manual string " + i + " bytes " + (end - start) + " ms"); -} - -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - for (k = i ; k > 0 ; k--) { - dest[k] = source[k]; - } - } - var end = new Date(); - console.log("Manual copy " + i + " bytes " + (end - start) + " ms"); -} - -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - for (k = i ; k > 0 ; k--) { - dest[k] = 120; - } - } - var end = new Date(); - console.log("Direct assignment " + i + " bytes " + (end - start) + " ms"); -} - -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - source.copy(dest, 0, 0, i); - } - var end = new Date(); - console.log("Buffer.copy() " + i + " bytes " + (end - start) + " ms"); -} diff --git a/node_modules/redis/tests/hiredis_parser.js b/node_modules/redis/tests/hiredis_parser.js deleted file mode 100644 index f1515b1..0000000 --- a/node_modules/redis/tests/hiredis_parser.js +++ /dev/null @@ -1,38 +0,0 @@ -var Parser = require('../lib/parser/hiredis').Parser; -var assert = require('assert'); - -/* -This test makes sure that exceptions thrown inside of "reply" event handlers -are not trapped and mistakenly emitted as parse errors. -*/ -(function testExecuteDoesNotCatchReplyCallbackExceptions() { - var parser = new Parser(); - var replies = [{}]; - - parser.reader = { - feed: function() {}, - get: function() { - return replies.shift(); - } - }; - - var emittedError = false; - var caughtException = false; - - parser - .on('error', function() { - emittedError = true; - }) - .on('reply', function() { - throw new Error('bad'); - }); - - try { - parser.execute(); - } catch (err) { - caughtException = true; - } - - assert.equal(caughtException, true); - assert.equal(emittedError, false); -})(); diff --git a/node_modules/redis/tests/reconnect_test.js b/node_modules/redis/tests/reconnect_test.js deleted file mode 100644 index 7abdd51..0000000 --- a/node_modules/redis/tests/reconnect_test.js +++ /dev/null @@ -1,29 +0,0 @@ -var redis = require("../index").createClient(null, null, { -// max_attempts: 4 -}); - -redis.on("error", function (err) { - console.log("Redis says: " + err); -}); - -redis.on("ready", function () { - console.log("Redis ready."); -}); - -redis.on("reconnecting", function (arg) { - console.log("Redis reconnecting: " + JSON.stringify(arg)); -}); -redis.on("connect", function () { - console.log("Redis connected."); -}); - -setInterval(function () { - var now = Date.now(); - redis.set("now", now, function (err, res) { - if (err) { - console.log(now + " Redis reply error: " + err); - } else { - console.log(now + " Redis reply: " + res); - } - }); -}, 100); diff --git a/node_modules/redis/tests/stress/codec.js b/node_modules/redis/tests/stress/codec.js deleted file mode 100644 index 7d764f6..0000000 --- a/node_modules/redis/tests/stress/codec.js +++ /dev/null @@ -1,16 +0,0 @@ -var json = { - encode: JSON.stringify, - decode: JSON.parse -}; - -var MsgPack = require('node-msgpack'); -msgpack = { - encode: MsgPack.pack, - decode: function(str) { return MsgPack.unpack(new Buffer(str)); } -}; - -bison = require('bison'); - -module.exports = json; -//module.exports = msgpack; -//module.exports = bison; diff --git a/node_modules/redis/tests/stress/pubsub/pub.js b/node_modules/redis/tests/stress/pubsub/pub.js deleted file mode 100644 index 0acde7a..0000000 --- a/node_modules/redis/tests/stress/pubsub/pub.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -var freemem = require('os').freemem; -var profiler = require('v8-profiler'); -var codec = require('../codec'); - -var sent = 0; - -var pub = require('redis').createClient(null, null, { - //command_queue_high_water: 5, - //command_queue_low_water: 1 -}) -.on('ready', function() { - this.emit('drain'); -}) -.on('drain', function() { - process.nextTick(exec); -}); - -var payload = '1'; for (var i = 0; i < 12; ++i) payload += payload; -console.log('Message payload length', payload.length); - -function exec() { - pub.publish('timeline', codec.encode({ foo: payload })); - ++sent; - if (!pub.should_buffer) { - process.nextTick(exec); - } -} - -profiler.takeSnapshot('s_0'); - -exec(); - -setInterval(function() { - profiler.takeSnapshot('s_' + sent); - console.error('sent', sent, 'free', freemem(), 'cmdqlen', pub.command_queue.length, 'offqlen', pub.offline_queue.length); -}, 2000); diff --git a/node_modules/redis/tests/stress/pubsub/run b/node_modules/redis/tests/stress/pubsub/run deleted file mode 100755 index bd9ac39..0000000 --- a/node_modules/redis/tests/stress/pubsub/run +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -node server.js & -node server.js & -node server.js & -node server.js & -node server.js & -node server.js & -node server.js & -node server.js & -node --debug pub.js diff --git a/node_modules/redis/tests/stress/pubsub/server.js b/node_modules/redis/tests/stress/pubsub/server.js deleted file mode 100644 index 035e6b7..0000000 --- a/node_modules/redis/tests/stress/pubsub/server.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var freemem = require('os').freemem; -var codec = require('../codec'); - -var id = Math.random(); -var recv = 0; - -var sub = require('redis').createClient() - .on('ready', function() { - this.subscribe('timeline'); - }) - .on('message', function(channel, message) { - var self = this; - if (message) { - message = codec.decode(message); - ++recv; - } - }); - -setInterval(function() { - console.error('id', id, 'received', recv, 'free', freemem()); -}, 2000); diff --git a/node_modules/redis/tests/stress/rpushblpop/pub.js b/node_modules/redis/tests/stress/rpushblpop/pub.js deleted file mode 100644 index 9caf1d0..0000000 --- a/node_modules/redis/tests/stress/rpushblpop/pub.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -var freemem = require('os').freemem; -//var profiler = require('v8-profiler'); -var codec = require('../codec'); - -var sent = 0; - -var pub = require('redis').createClient(null, null, { - //command_queue_high_water: 5, - //command_queue_low_water: 1 -}) -.on('ready', function() { - this.del('timeline'); - this.emit('drain'); -}) -.on('drain', function() { - process.nextTick(exec); -}); - -var payload = '1'; for (var i = 0; i < 12; ++i) payload += payload; -console.log('Message payload length', payload.length); - -function exec() { - pub.rpush('timeline', codec.encode({ foo: payload })); - ++sent; - if (!pub.should_buffer) { - process.nextTick(exec); - } -} - -//profiler.takeSnapshot('s_0'); - -exec(); - -setInterval(function() { - //var ss = profiler.takeSnapshot('s_' + sent); - //console.error(ss.stringify()); - pub.llen('timeline', function(err, result) { - console.error('sent', sent, 'free', freemem(), - 'cmdqlen', pub.command_queue.length, 'offqlen', pub.offline_queue.length, - 'llen', result - ); - }); -}, 2000); - -/*setTimeout(function() { - process.exit(); -}, 30000);*/ diff --git a/node_modules/redis/tests/stress/rpushblpop/run b/node_modules/redis/tests/stress/rpushblpop/run deleted file mode 100755 index 8045ae8..0000000 --- a/node_modules/redis/tests/stress/rpushblpop/run +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh -node server.js & -#node server.js & -#node server.js & -#node server.js & -node --debug pub.js diff --git a/node_modules/redis/tests/stress/rpushblpop/server.js b/node_modules/redis/tests/stress/rpushblpop/server.js deleted file mode 100644 index 9cbcdd9..0000000 --- a/node_modules/redis/tests/stress/rpushblpop/server.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var freemem = require('os').freemem; -var codec = require('../codec'); - -var id = Math.random(); -var recv = 0; - -var cmd = require('redis').createClient(); -var sub = require('redis').createClient() - .on('ready', function() { - this.emit('timeline'); - }) - .on('timeline', function() { - var self = this; - this.blpop('timeline', 0, function(err, result) { - var message = result[1]; - if (message) { - message = codec.decode(message); - ++recv; - } - self.emit('timeline'); - }); - }); - -setInterval(function() { - cmd.llen('timeline', function(err, result) { - console.error('id', id, 'received', recv, 'free', freemem(), 'llen', result); - }); -}, 2000); diff --git a/node_modules/redis/tests/stress/speed/00 b/node_modules/redis/tests/stress/speed/00 deleted file mode 100644 index 29d7bf7..0000000 --- a/node_modules/redis/tests/stress/speed/00 +++ /dev/null @@ -1,13 +0,0 @@ -# size JSON msgpack bison -26602 2151.0170848180414 -25542 ? 2842.589272665782 -24835 ? ? 7280.4538397469805 -6104 6985.234528557929 -5045 ? 7217.461392841478 -4341 ? ? 14261.406335354604 -4180 15864.633685636572 -4143 ? 12954.806235781925 -4141 ? ? 44650.70733912719 -75 114227.07313350472 -40 ? 30162.440062810834 -39 ? ? 119815.66013519121 diff --git a/node_modules/redis/tests/stress/speed/plot b/node_modules/redis/tests/stress/speed/plot deleted file mode 100755 index 2563797..0000000 --- a/node_modules/redis/tests/stress/speed/plot +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh - -gnuplot >size-rate.jpg << _EOF_ - -set terminal png nocrop enhanced font verdana 12 size 640,480 -set logscale x -set logscale y -set grid -set xlabel 'Serialized object size, octets' -set ylabel 'decode(encode(obj)) rate, 1/sec' -plot '00' using 1:2 title 'json' smooth bezier, '00' using 1:3 title 'msgpack' smooth bezier, '00' using 1:4 title 'bison' smooth bezier - -_EOF_ diff --git a/node_modules/redis/tests/stress/speed/size-rate.png b/node_modules/redis/tests/stress/speed/size-rate.png deleted file mode 100644 index c9c2bee..0000000 Binary files a/node_modules/redis/tests/stress/speed/size-rate.png and /dev/null differ diff --git a/node_modules/redis/tests/stress/speed/speed.js b/node_modules/redis/tests/stress/speed/speed.js deleted file mode 100644 index 8e43cbc..0000000 --- a/node_modules/redis/tests/stress/speed/speed.js +++ /dev/null @@ -1,84 +0,0 @@ -var msgpack = require('node-msgpack'); -var bison = require('bison'); -var codec = { - JSON: { - encode: JSON.stringify, - decode: JSON.parse - }, - msgpack: { - encode: msgpack.pack, - decode: msgpack.unpack - }, - bison: bison -}; - -var obj, l; - -var s = '0'; -for (var i = 0; i < 12; ++i) s += s; - -obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [], - a: s, - ccc: s, - b: s + s + s -}; -for (i = 0; i < 100; ++i) obj.rand.push(Math.random()); -forObj(obj); - -obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] -}; -for (i = 0; i < 100; ++i) obj.rand.push(Math.random()); -forObj(obj); - -obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] -}; -forObj(obj); - -obj = { - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] -}; -forObj(obj); - -function run(obj, codec) { - var t1 = Date.now(); - var n = 10000; - for (var i = 0; i < n; ++i) { - codec.decode(l = codec.encode(obj)); - } - var t2 = Date.now(); - //console.log('DONE', n*1000/(t2-t1), 'codecs/sec, length=', l.length); - return [n*1000/(t2-t1), l.length]; -} - -function series(obj, cname, n) { - var rate = 0; - var len = 0; - for (var i = 0; i < n; ++i) { - var r = run(obj, codec[cname]); - rate += r[0]; - len += r[1]; - } - rate /= n; - len /= n; - console.log(cname + ' ' + rate + ' ' + len); - return [rate, len]; -} - -function forObj(obj) { - var r = { - JSON: series(obj, 'JSON', 20), - msgpack: series(obj, 'msgpack', 20), - bison: series(obj, 'bison', 20) - }; - return r; -} diff --git a/node_modules/redis/tests/sub_quit_test.js b/node_modules/redis/tests/sub_quit_test.js deleted file mode 100644 index ad1f413..0000000 --- a/node_modules/redis/tests/sub_quit_test.js +++ /dev/null @@ -1,18 +0,0 @@ -var client = require("redis").createClient(), - client2 = require("redis").createClient(); - -client.subscribe("something"); -client.on("subscribe", function (channel, count) { - console.log("Got sub: " + channel); - client.unsubscribe("something"); -}); - -client.on("unsubscribe", function (channel, count) { - console.log("Got unsub: " + channel + ", quitting"); - client.quit(); -}); - -// exercise unsub before sub -client2.unsubscribe("something"); -client2.subscribe("another thing"); -client2.quit(); diff --git a/node_modules/should/.gitmodules b/node_modules/should/.gitmodules deleted file mode 100644 index ffe0dcb..0000000 --- a/node_modules/should/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git diff --git a/node_modules/should/.npmignore b/node_modules/should/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/should/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/should/History.md b/node_modules/should/History.md deleted file mode 100644 index 3ae7510..0000000 --- a/node_modules/should/History.md +++ /dev/null @@ -1,55 +0,0 @@ - -0.3.2 / 2011-10-24 -================== - - * Fixed tests for 0.5.x - * Fixed sys warning - -0.3.1 / 2011-08-22 -================== - - * configurable - -0.3.0 / 2011-08-20 -================== - - * Added assertion for inclusion of an object: `foo.should.include.object({ foo: 'bar' })` - -0.2.1 / 2011-05-13 -================== - - * Fixed .status(code). Closes #18 - -0.2.0 / 2011-04-17 -================== - - * Added `res.should.have.status(code)` method - * Added `res.should.have.header(field, val)` method - -0.1.0 / 2011-04-06 -================== - - * Added `should.exist(obj)` [aseemk] - * Added `should.not.exist(obj)` [aseemk] - -0.0.4 / 2010-11-24 -================== - - * Added `.ok` to assert truthfulness - * Added `.arguments` - * Fixed double required bug. [thanks dominictarr] - -0.0.3 / 2010-11-19 -================== - - * Added `true` / `false` assertions - -0.0.2 / 2010-11-19 -================== - - * Added chaining support - -0.0.1 / 2010-11-19 -================== - - * Initial release diff --git a/node_modules/should/Makefile b/node_modules/should/Makefile deleted file mode 100644 index 5565ce7..0000000 --- a/node_modules/should/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @./node_modules/.bin/expresso - -.PHONY: test \ No newline at end of file diff --git a/node_modules/should/Readme.md b/node_modules/should/Readme.md deleted file mode 100644 index 8b63bfd..0000000 --- a/node_modules/should/Readme.md +++ /dev/null @@ -1,315 +0,0 @@ -_should_ is an expressive, readable, test framework agnostic, assertion library for [node](http://nodejs.org). - -It extends the Object prototype with a single non-enumerable getter that allows you to express how that object should behave. - -_should_ literally extends node's _assert_ module, in fact, it is node's assert module, for example `should.equal(str, 'foo')` will work, just as `assert.equal(str, 'foo')` would, and `should.AssertionError` **is** `asset.AssertionError`, meaning any test framework supporting this constructor will function properly with _should_. - -## Example - - var user = { - name: 'tj' - , pets: ['tobi', 'loki', 'jane', 'bandit'] - }; - - user.should.have.property('name', 'tj'); - user.should.have.property('pets').with.lengthOf(4) - - someAsyncTask(foo, function (err, result) { - should.not.exist(err); - should.exist(result); - result.bar.should.equal(foo); - }); - -## Installation - - $ npm install should - -## assert extras - -As mentioned above, _should_ extends node's _assert_. The returned object from `require('should')` is thus similar to the returned object from `require('assert')`, but it has one extra convenience method: - - should.exist('hello') - should.exist([]) - should.exist(null) // will throw - -This is equivalent to `should.ok`, which is equivalent to `assert.ok`, but reads a bit better. It gets better, though: - - should.not.exist(false) - should.not.exist('') - should.not.exist({}) // will throw - -We may add more _assert_ extras in the future... ;) - -## modifiers - - _should_'s assertion chaining provides an expressive way to build up an assertion, along with dummy getters such as _an_, _have_, and _be_, provided are what I am simply calling **modifiers**, which have a meaning effect on the assertion. An example of this is the _not_ getter, which negates the meaning, aka `user.should.not.have.property('name')`. In the previous example note the use of _have_, as we could omit it and still construct a valid assertion. - -Some modifiers such as _include_ only have an effect with specific assertion methods, for example when asserting a substring like so: `str.should.include.string('test')`, we could omit _include_, but it helps express the meaning, however _keys_ has a strict effect, unless the _include_ modifier is used. - -## chaining assertions - -Some assertions can be chained, for example if a property is volatile we can first assert property existence: - - user.should.have.property('pets').with.lengthOf(4) - -which is essentially equivalent to below, however the property may not exist: - - user.pets.should.have.lengthOf(4) - -our dummy getters such as _and_ also help express chaining: - - user.should.be.a('object').and.have.property('name', 'tj') - -## exist (static) - -The returned object from `require('should')` is the same object as `require('assert')`. So you can use `should` just like `assert`: - - should.fail('expected an error!') - should.strictEqual(foo, bar) - -In general, using the Object prototype's _should_ is nicer than using these `assert` equivalents, because _should_ gives you access to the expressive and readable language described above: - - foo.should.equal(bar) // same as should.strictEqual(foo, bar) above - -The only exception, though, is when you can't be sure that a particular object exists. In that case, attempting to access the _should_ property may throw a TypeError: - - foo.should.equal(bar) // throws if foo is null or undefined! - -For this case, `require('should')` extends `require('assert')` with an extra convenience method to check whether an object exists: - - should.exist({}) - should.exist([]) - should.exist('') - should.exist(0) - should.exist(null) // will throw - should.exist(undefined) // will throw - -You can also check the negation: - - should.not.exist(undefined) - should.not.exist(null) - should.not.exist('') // will throw - should.not.exist({}) // will throw - -Once you know an object exists, you can safely use the _should_ property on it. - -## ok - -Assert truthfulness: - - true.should.be.ok - 'yay'.should.be.ok - (1).should.be.ok - -or negated: - - false.should.not.be.ok - ''.should.not.be.ok - (0).should.not.be.ok - -## true - -Assert === true: - - true.should.be.true - '1'.should.not.be.true - -## false - -Assert === false: - - false.should.be.false - (0).should.not.be.false - -## arguments - -Assert `Arguments`: - - var args = (function(){ return arguments; })(1,2,3); - args.should.be.arguments; - [].should.not.be.arguments; - -## empty - -Asserts that length is 0: - - [].should.be.empty - ''.should.be.empty - ({ length: 0 }).should.be.empty - -## eql - -equality: - - ({ foo: 'bar' }).should.eql({ foo: 'bar' }) - [1,2,3].should.eql([1,2,3]) - -## equal - -strict equality: - - should.strictEqual(undefined, value) - should.strictEqual(false, value) - (4).should.equal(4) - 'test'.should.equal('test') - [1,2,3].should.not.equal([1,2,3]) - -## within - -Assert inclusive numeric range: - - user.age.should.be.within(5, 50) - -## a - -Assert __typeof__: - - user.should.be.a('object') - 'test'.should.be.a('string') - -## instanceof - -Assert __instanceof__: - - user.should.be.an.instanceof(User) - [].should.be.an.instanceof(Array) - -## above - -Assert numeric value above the given value: - - user.age.should.be.above(5) - user.age.should.not.be.above(100) - -## below - -Assert numeric value below the given value: - - user.age.should.be.below(100) - user.age.should.not.be.below(5) - -## match - -Assert regexp match: - - username.should.match(/^\w+$/) - -## length - -Assert _length_ property exists and has a value of the given number: - - user.pets.should.have.length(5) - user.pets.should.have.a.lengthOf(5) - -Aliases: _lengthOf_ - -## string - -Substring assertion: - - 'foobar'.should.include.string('foo') - 'foobar'.should.include.string('bar') - 'foobar'.should.not.include.string('baz') - -## object - -Assert inclusion of object: - - var obj = {foo: 'bar', baz: {baaz: 42}}; - obj.should.include.object({foo: 'bar'}); - obj.should.include.object({baz: {baaz: 42}}); - obj.should.not.include.object({foo: 'baz'}); - -## property - -Assert property exists and has optional value: - - user.should.have.property('name') - user.should.have.property('age', 15) - user.should.not.have.property('rawr') - user.should.not.have.property('age', 0) - -## ownProperty - -Assert own property (on the immediate object): - - ({ foo: 'bar' }).should.have.ownProperty('foo') - -## contain - -Assert array value: - - [1,2,3].should.contain(3) - [1,2,3].should.contain(2) - [1,2,3].should.not.contain(4) - -## keys - -Assert own object keys, which must match _exactly_, -and will fail if you omit a key or two: - - var obj = { foo: 'bar', baz: 'raz' }; - obj.should.have.keys('foo', 'bar'); - obj.should.have.keys(['foo', 'bar']); - -using the _include_ modifier, we can check inclusion of a key, -but not fail when we omit a few: - - obj.should.include.keys('foo') - obj.should.include.keys('bar') - obj.should.not.include.keys('baz') - -## respondTo - -Assert that the given property is a function: - - user.should.respondTo('email') - -## Express example - -For example you can use should with the [Expresso TDD Framework](http://github.com/visionmedia/expresso) by simply including it: - - var lib = require('mylib') - , should = require('should'); - - module.exports = { - 'test .version': function(){ - lib.version.should.match(/^\d+\.\d+\.\d+$/); - } - }; - -## Running tests - -To run the tests for _should_ simple update your git submodules and run: - - $ make test - -## OMG IT EXTENDS OBJECT???!?!@ - -Yes, yes it does, with a single getter _should_, and no it wont break your code, because it does this **properly** with a non-enumerable property. - -## License - -(The MIT License) - -Copyright (c) 2010-2011 TJ Holowaychuk <tj@vision-media.ca> -Copyright (c) 2011 Aseem Kishore <aseem.kishore@gmail.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/should/examples/runner.js b/node_modules/should/examples/runner.js deleted file mode 100644 index 9355955..0000000 --- a/node_modules/should/examples/runner.js +++ /dev/null @@ -1,53 +0,0 @@ - -/** - * Module dependencies. - */ - -var should = require('../'); - -function test(name, fn){ - try { - fn(); - } catch (err) { - console.log(' \x1b[31m%s', name); - console.log(' %s\x1b[0m', err.stack); - return; - } - console.log(' √ \x1b[32m%s\x1b[0m', name); -} - -function Point(x, y) { - this.x = x; - this.y = y; - this.sub = function(other){ - return new Point( - this.x - other.x - , this.y - other.y); - } -} - -console.log(); - -test('new Point(x, y)', function(){ - var point = new Point(50, 100); - point.should.be.an.instanceof(Point); - point.should.have.property('x', 50); - point.should.have.property('y', 100); -}); - -test('Point#sub()', function(){ - var a = new Point(50, 100) - , b = new Point(20, 50); - a.sub(b).should.be.an.instanceof(Point); - a.sub(b).should.not.equal(a); - a.sub(b).should.not.equal(b); - a.sub(b).should.have.property('x', 30); - a.sub(b).should.have.property('y', 50); -}); - -test('Point#add()', function(){ - var point = new Point(50, 100); - point.should.respondTo('add'); -}); - -console.log(); \ No newline at end of file diff --git a/node_modules/should/index.js b/node_modules/should/index.js deleted file mode 100644 index 6dbdbde..0000000 --- a/node_modules/should/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/should'); \ No newline at end of file diff --git a/node_modules/should/lib/eql.js b/node_modules/should/lib/eql.js deleted file mode 100644 index ef21923..0000000 --- a/node_modules/should/lib/eql.js +++ /dev/null @@ -1,91 +0,0 @@ - -// Taken from node's assert module, because it sucks -// and exposes next to nothing useful. - -module.exports = _deepEqual; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual === expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key] )) - return false; - } - return true; -} diff --git a/node_modules/should/lib/should.js b/node_modules/should/lib/should.js deleted file mode 100644 index e2599b5..0000000 --- a/node_modules/should/lib/should.js +++ /dev/null @@ -1,645 +0,0 @@ -/*! - * Should - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var util = require('util') - , http = require('http') - , assert = require('assert') - , AssertionError = assert.AssertionError - , statusCodes = http.STATUS_CODES - , eql = require('./eql') - , i = util.inspect; - -/** - * Expose assert as should. - * - * This allows you to do things like below - * without require()ing the assert module. - * - * should.equal(foo.bar, undefined); - * - */ - -exports = module.exports = assert; - -/** - * Library version. - */ - -exports.version = '0.3.2'; - -/** - * Assert _obj_ exists, with optional message. - * - * @param {Mixed} obj - * @param {String} msg - * @api public - */ - -exports.exist = function(obj, msg){ - if (null == obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to exist') - , stackStartFunction: should.exist - }); - } -}; - -/** - * Asserts _obj_ does not exist, with optional message. - * - * @param {Mixed} obj - * @param {String} msg - * @api public - */ - -exports.not = {}; -exports.not.exist = function(obj, msg){ - if (null != obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to not exist') - , stackStartFunction: should.not.exist - }); - } -}; - -/** - * Expose api via `Object#should`. - * - * @api public - */ - -Object.defineProperty(Object.prototype, 'should', { - set: function(){}, - get: function(){ - return new Assertion(this); - }, - configurable: true -}); - -/** - * Initialize a new `Assertion` with the given _obj_. - * - * @param {Mixed} obj - * @api private - */ - -var Assertion = exports.Assertion = function Assertion(obj) { - this.obj = obj; -}; - -/** - * Prototype. - */ - -Assertion.prototype = { - - /** - * HACK: prevents double require() from failing. - */ - - exports: exports, - - /** - * Assert _expr_ with the given _msg_ and _negatedMsg_. - * - * @param {Boolean} expr - * @param {String} msg - * @param {String} negatedMsg - * @api private - */ - - assert: function(expr, msg, negatedMsg){ - var msg = this.negate ? negatedMsg : msg - , ok = this.negate ? !expr : expr; - if (!ok) { - throw new AssertionError({ - message: msg - , stackStartFunction: this.assert - }); - } - }, - - /** - * Dummy getter. - * - * @api public - */ - - get an() { - return this; - }, - - /** - * Dummy getter. - * - * @api public - */ - - get and() { - return this; - }, - - /** - * Dummy getter. - * - * @api public - */ - - get be() { - return this; - }, - - /** - * Dummy getter. - * - * @api public - */ - - get have() { - return this; - }, - - /** - * Dummy getter. - * - * @api public - */ - - get with() { - return this; - }, - - /** - * Inclusion modifier. - * - * @api public - */ - - get include() { - this.includes = true; - return this; - }, - - /** - * Negation modifier. - * - * @api public - */ - - get not() { - this.negate = true; - return this; - }, - - /** - * Get object inspection string. - * - * @return {String} - * @api private - */ - - get inspect() { - return i(this.obj); - }, - - /** - * Assert instanceof `Arguments`. - * - * @api public - */ - - get arguments() { - this.assert( - '[object Arguments]' == Object.prototype.toString.call(this.obj) - , 'expected ' + this.inspect + ' to be arguments' - , 'expected ' + this.inspect + ' to not be arguments'); - return this; - }, - - /** - * Assert that an object is empty aka length of 0. - * - * @api public - */ - - get empty() { - this.obj.should.have.property('length'); - this.assert( - 0 === this.obj.length - , 'expected ' + this.inspect + ' to be empty' - , 'expected ' + this.inspect + ' not to be empty'); - return this; - }, - - /** - * Assert ok. - * - * @api public - */ - - get ok() { - this.assert( - this.obj - , 'expected ' + this.inspect + ' to be truthy' - , 'expected ' + this.inspect + ' to be falsey'); - return this; - }, - - /** - * Assert true. - * - * @api public - */ - - get true() { - this.assert( - true === this.obj - , 'expected ' + this.inspect + ' to be true' - , 'expected ' + this.inspect + ' not to be true'); - return this; - }, - - /** - * Assert false. - * - * @api public - */ - - get false() { - this.assert( - false === this.obj - , 'expected ' + this.inspect + ' to be false' - , 'expected ' + this.inspect + ' not to be false'); - return this; - }, - - /** - * Assert equal. - * - * @param {Mixed} val - * @api public - */ - - eql: function(val){ - this.assert( - eql(val, this.obj) - , 'expected ' + this.inspect + ' to equal ' + i(val) - , 'expected ' + this.inspect + ' to not equal ' + i(val)); - return this; - }, - - /** - * Assert strict equal. - * - * @param {Mixed} val - * @api public - */ - - equal: function(val){ - this.assert( - val === this.obj - , 'expected ' + this.inspect + ' to equal ' + i(val) - , 'expected ' + this.inspect + ' to not equal ' + i(val)); - return this; - }, - - /** - * Assert within start to finish (inclusive). - * - * @param {Number} start - * @param {Number} finish - * @api public - */ - - within: function(start, finish){ - var range = start + '..' + finish; - this.assert( - this.obj >= start && this.obj <= finish - , 'expected ' + this.inspect + ' to be within ' + range - , 'expected ' + this.inspect + ' to not be within ' + range); - return this; - }, - - /** - * Assert typeof. - * - * @api public - */ - - a: function(type){ - this.assert( - type == typeof this.obj - , 'expected ' + this.inspect + ' to be a ' + type - , 'expected ' + this.inspect + ' not to be a ' + type); - return this; - }, - - /** - * Assert instanceof. - * - * @api public - */ - - instanceof: function(constructor){ - var name = constructor.name; - this.assert( - this.obj instanceof constructor - , 'expected ' + this.inspect + ' to be an instance of ' + name - , 'expected ' + this.inspect + ' not to be an instance of ' + name); - return this; - }, - - /** - * Assert numeric value above _n_. - * - * @param {Number} n - * @api public - */ - - above: function(n){ - this.assert( - this.obj > n - , 'expected ' + this.inspect + ' to be above ' + n - , 'expected ' + this.inspect + ' to be below ' + n); - return this; - }, - - /** - * Assert numeric value below _n_. - * - * @param {Number} n - * @api public - */ - - below: function(n){ - this.assert( - this.obj < n - , 'expected ' + this.inspect + ' to be below ' + n - , 'expected ' + this.inspect + ' to be above ' + n); - return this; - }, - - /** - * Assert string value matches _regexp_. - * - * @param {RegExp} regexp - * @api public - */ - - match: function(regexp){ - this.assert( - regexp.exec(this.obj) - , 'expected ' + this.inspect + ' to match ' + regexp - , 'expected ' + this.inspect + ' not to match ' + regexp); - return this; - }, - - /** - * Assert property "length" exists and has value of _n_. - * - * @param {Number} n - * @api public - */ - - length: function(n){ - this.obj.should.have.property('length'); - var len = this.obj.length; - this.assert( - n == len - , 'expected ' + this.inspect + ' to have a length of ' + n + ' but got ' + len - , 'expected ' + this.inspect + ' to not have a length of ' + len); - return this; - }, - - /** - * Assert substring. - * - * @param {String} str - * @api public - */ - - string: function(str){ - this.obj.should.be.a('string'); - this.assert( - ~this.obj.indexOf(str) - , 'expected ' + this.inspect + ' to include ' + i(str) - , 'expected ' + this.inspect + ' to not include ' + i(str)); - return this; - }, - - /** - * Assert inclusion of object. - * - * @param {Object} obj - * @api public - */ - - object: function(obj){ - this.obj.should.be.a('object'); - var included = true; - for (var key in obj) { - if (obj.hasOwnProperty(key) && !eql(obj[key], this.obj[key])) { - included = false; - break; - } - } - this.assert( - included - , 'expected ' + this.inspect + ' to include ' + i(obj) - , 'expected ' + this.inspect + ' to not include ' + i(obj)); - return this; - }, - - /** - * Assert property _name_ exists, with optional _val_. - * - * @param {String} name - * @param {Mixed} val - * @api public - */ - - property: function(name, val){ - if (this.negate && undefined !== val) { - if (undefined === this.obj[name]) { - throw new Error(this.inspect + ' has no property ' + i(name)); - } - } else { - this.assert( - undefined !== this.obj[name] - , 'expected ' + this.inspect + ' to have a property ' + i(name) - , 'expected ' + this.inspect + ' to not have a property ' + i(name)); - } - - if (undefined !== val) { - this.assert( - val === this.obj[name] - , 'expected ' + this.inspect + ' to have a property ' + i(name) - + ' of ' + i(val) + ', but got ' + i(this.obj[name]) - , 'expected ' + this.inspect + ' to not have a property ' + i(name) + ' of ' + i(val)); - } - - this.obj = this.obj[name]; - return this; - }, - - /** - * Assert own property _name_ exists. - * - * @param {String} name - * @api public - */ - - ownProperty: function(name){ - this.assert( - this.obj.hasOwnProperty(name) - , 'expected ' + this.inspect + ' to have own property ' + i(name) - , 'expected ' + this.inspect + ' to not have own property ' + i(name)); - return this; - }, - - /** - * Assert that the array contains _obj_. - * - * @param {Mixed} obj - * @api public - */ - - contain: function(obj){ - this.obj.should.be.an.instanceof(Array); - this.assert( - ~this.obj.indexOf(obj) - , 'expected ' + this.inspect + ' to contain ' + i(obj) - , 'expected ' + this.inspect + ' to not contain ' + i(obj)); - return this; - }, - - /** - * Assert exact keys or inclusion of keys by using - * the `.include` modifier. - * - * @param {Array|String ...} keys - * @api public - */ - - keys: function(keys){ - var str - , ok = true; - - keys = keys instanceof Array - ? keys - : Array.prototype.slice.call(arguments); - - if (!keys.length) throw new Error('keys required'); - - var actual = Object.keys(this.obj) - , len = keys.length; - - // Inclusion - ok = keys.every(function(key){ - return ~actual.indexOf(key); - }); - - // Strict - if (!this.negate && !this.includes) { - ok = ok && keys.length == actual.length; - } - - // Key string - if (len > 1) { - keys = keys.map(function(key){ - return i(key); - }); - var last = keys.pop(); - str = keys.join(', ') + ', and ' + last; - } else { - str = i(keys[0]); - } - - // Form - str = (len > 1 ? 'keys ' : 'key ') + str; - - // Have / include - str = (this.includes ? 'include ' : 'have ') + str; - - // Assertion - this.assert( - ok - , 'expected ' + this.inspect + ' to ' + str - , 'expected ' + this.inspect + ' to not ' + str); - - return this; - }, - - /** - * Assert that _method_ is a function. - * - * @param {String} method - * @api public - */ - - respondTo: function(method){ - this.assert( - 'function' == typeof this.obj[method] - , 'expected ' + this.inspect + ' to respond to ' + method + '()' - , 'expected ' + this.inspect + ' to not respond to ' + method + '()'); - return this; - }, - - /** - * Assert that header `field` has the given `val`. - * - * @param {String} field - * @param {String} val - * @return {Assertion} for chaining - * @api public - */ - - header: function(field, val){ - this.obj.should.have.property('headers'); - this.obj.headers.should.have.property(field.toLowerCase(), val); - return this; - }, - - /** - * Assert `.statusCode` of `code`. - * - * @param {Number} code - * @return {Assertion} for chaining - * @api public - */ - - status: function(code){ - this.obj.should.have.property('statusCode'); - var status = this.obj.statusCode; - - this.assert( - code == status - , 'expected response code of ' + code + ' ' + i(statusCodes[code]) - + ', but got ' + status + ' ' + i(statusCodes[status]) - , 'expected to not respond with ' + code + ' ' + i(statusCodes[code])); - - return this; - } -}; - -/** - * Aliases. - */ - -(function alias(name, as){ - Assertion.prototype[as] = Assertion.prototype[name]; - return alias; -}) -('length', 'lengthOf') -('keys', 'key') -('ownProperty', 'haveOwnProperty') -('above', 'greaterThan') -('below', 'lessThan'); - diff --git a/node_modules/should/package.json b/node_modules/should/package.json deleted file mode 100644 index e10e875..0000000 --- a/node_modules/should/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ "name": "should" - , "description": "test framework agnostic BDD-style assertions" - , "version": "0.3.2" - , "author": "TJ Holowaychuk " - , "contributors": [ "Aseem Kishore " ] - , "devDependencies": { - "expresso": "0.9.2" - , "should": "*" - } - , "keywords": ["test", "bdd", "assert"] - , "main": "./lib/should.js" - , "engines": { "node": ">= 0.2.0" } -} \ No newline at end of file diff --git a/node_modules/should/test/exist.test.js b/node_modules/should/test/exist.test.js deleted file mode 100644 index 7aa1082..0000000 --- a/node_modules/should/test/exist.test.js +++ /dev/null @@ -1,96 +0,0 @@ - -/** - * Module dependencies. - */ - -var should = require('../'); -var util = require('util'); - -function err(fn, msg) { - try { - fn(); - should.fail('expected an error'); - } catch (err) { - should.equal(msg, err.message); - } -} - -function err_should_exist(obj) { - err(function () { - should.exist(obj); - }, 'expected ' + util.inspect(obj) + ' to exist'); -} - -function err_should_not_exist(obj) { - err(function () { - should.not.exist(obj); - }, 'expected ' + util.inspect(obj) + ' to not exist'); -} - -module.exports = { - - // static should.exist() pass: - - 'test static should.exist() pass w/ bool': function () { - should.exist(false); - }, - - 'test static should.exist() pass w/ number': function () { - should.exist(0); - }, - - 'test static should.exist() pass w/ string': function () { - should.exist(''); - }, - - 'test static should.exist() pass w/ object': function () { - should.exist({}); - }, - - 'test static should.exist() pass w/ array': function () { - should.exist([]); - }, - - // static should.exist() fail: - - 'test static should.exist() fail w/ null': function () { - err_should_exist(null); - }, - - 'test static should.exist() fail w/ undefined': function () { - err_should_exist(undefined); - }, - - // static should.not.exist() pass: - - 'test static should.not.exist() pass w/ null': function () { - should.not.exist(null); - }, - - 'test static should.not.exist() pass w/ undefined': function () { - should.not.exist(undefined); - }, - - // static should.not.exist() fail: - - 'test static should.not.exist() fail w/ bool': function () { - err_should_not_exist(false); - }, - - 'test static should.not.exist() fail w/ number': function () { - err_should_not_exist(0); - }, - - 'test static should.not.exist() fail w/ string': function () { - err_should_not_exist(''); - }, - - 'test static should.not.exist() fail w/ object': function () { - err_should_not_exist({}); - }, - - 'test static should.not.exist() fail w/ array': function () { - err_should_not_exist([]); - }, - -}; diff --git a/node_modules/should/test/should.test.js b/node_modules/should/test/should.test.js deleted file mode 100644 index 21e738b..0000000 --- a/node_modules/should/test/should.test.js +++ /dev/null @@ -1,380 +0,0 @@ - -/** - * Module dependencies. - */ - -var should = require('../'); - -function err(fn, msg) { - try { - fn(); - should.fail('expected an error'); - } catch (err) { - should.equal(msg, err.message); - } -} - -module.exports = { - 'test .version': function(){ - should.version.should.match(/^\d+\.\d+\.\d+$/); - }, - - 'test double require': function(){ - require('should').should.equal(should); - }, - - 'test assertion': function(){ - 'test'.should.be.a.string; - should.equal('foo', 'foo'); - }, - - 'test true': function(){ - true.should.be.true; - false.should.not.be.true; - (1).should.not.be.true; - - err(function(){ - 'test'.should.be.true; - }, "expected 'test' to be true") - }, - - 'test ok': function(){ - true.should.be.ok; - false.should.not.be.ok; - (1).should.be.ok; - (0).should.not.be.ok; - - err(function(){ - ''.should.be.ok; - }, "expected '' to be truthy"); - - err(function(){ - 'test'.should.not.be.ok; - }, "expected 'test' to be falsey"); - }, - - 'test false': function(){ - false.should.be.false; - true.should.not.be.false; - (0).should.not.be.false; - - err(function(){ - ''.should.be.false; - }, "expected '' to be false") - }, - - 'test arguments': function(){ - var args = (function(){ return arguments; })(1,2,3); - args.should.be.arguments; - [].should.not.be.arguments; - }, - - 'test .equal()': function(){ - var foo; - should.equal(undefined, foo); - }, - - 'test typeof': function(){ - 'test'.should.be.a('string'); - - err(function(){ - 'test'.should.not.be.a('string'); - }, "expected 'test' not to be a string"); - - (5).should.be.a('number'); - - err(function(){ - (5).should.not.be.a('number'); - }, "expected 5 not to be a number"); - }, - - 'test instanceof': function(){ - function Foo(){} - new Foo().should.be.an.instanceof(Foo); - - err(function(){ - (3).should.an.instanceof(Foo); - }, "expected 3 to be an instance of Foo"); - }, - - 'test within(start, finish)': function(){ - (5).should.be.within(5, 10); - (5).should.be.within(3,6); - (5).should.be.within(3,5); - (5).should.not.be.within(1,3); - - err(function(){ - (5).should.not.be.within(4,6); - }, "expected 5 to not be within 4..6"); - - err(function(){ - (10).should.be.within(50,100); - }, "expected 10 to be within 50..100"); - }, - - 'test above(n)': function(){ - (5).should.be.above(2); - (5).should.be.greaterThan(2); - (5).should.not.be.above(5); - (5).should.not.be.above(6); - - err(function(){ - (5).should.be.above(6); - }, "expected 5 to be above 6"); - - err(function(){ - (10).should.not.be.above(6); - }, "expected 10 to be below 6"); - }, - - 'test match(regexp)': function(){ - 'foobar'.should.match(/^foo/) - 'foobar'.should.not.match(/^bar/) - - err(function(){ - 'foobar'.should.match(/^bar/i) - }, "expected 'foobar' to match /^bar/i"); - - err(function(){ - 'foobar'.should.not.match(/^foo/i) - }, "expected 'foobar' not to match /^foo/i"); - }, - - 'test length(n)': function(){ - 'test'.should.have.length(4); - 'test'.should.not.have.length(3); - [1,2,3].should.have.length(3); - - err(function(){ - (4).should.have.length(3); - }, 'expected 4 to have a property \'length\''); - - err(function(){ - 'asd'.should.not.have.length(3); - }, "expected 'asd' to not have a length of 3"); - }, - - 'test eql(val)': function(){ - 'test'.should.eql('test'); - ({ foo: 'bar' }).should.eql({ foo: 'bar' }); - (1).should.eql(1); - '4'.should.not.eql(4); - - err(function(){ - (4).should.eql(3); - }, 'expected 4 to equal 3'); - }, - - 'test equal(val)': function(){ - 'test'.should.equal('test'); - (1).should.equal(1); - - err(function(){ - (4).should.equal(3); - }, 'expected 4 to equal 3'); - - err(function(){ - '4'.should.equal(4); - }, "expected '4' to equal 4"); - }, - - 'test empty': function(){ - ''.should.be.empty; - [].should.be.empty; - ({ length: 0 }).should.be.empty; - - err(function(){ - ({}).should.be.empty; - }, 'expected {} to have a property \'length\''); - - err(function(){ - 'asd'.should.be.empty; - }, "expected 'asd' to be empty"); - - err(function(){ - ''.should.not.be.empty; - }, "expected '' not to be empty"); - }, - - 'test property(name)': function(){ - 'test'.should.have.property('length'); - (4).should.not.have.property('length'); - - err(function(){ - 'asd'.should.have.property('foo'); - }, "expected 'asd' to have a property 'foo'"); - }, - - 'test property(name, val)': function(){ - 'test'.should.have.property('length', 4); - 'asd'.should.have.property('constructor', String); - - err(function(){ - 'asd'.should.have.property('length', 4); - }, "expected 'asd' to have a property 'length' of 4, but got 3"); - - err(function(){ - 'asd'.should.not.have.property('length', 3); - }, "expected 'asd' to not have a property 'length' of 3"); - - err(function(){ - 'asd'.should.not.have.property('foo', 3); - }, "'asd' has no property 'foo'"); - - err(function(){ - 'asd'.should.have.property('constructor', Number); - }, "expected 'asd' to have a property 'constructor' of [Function: Number], but got [Function: String]"); - }, - - 'test ownProperty(name)': function(){ - 'test'.should.have.ownProperty('length'); - 'test'.should.haveOwnProperty('length'); - ({ length: 12 }).should.have.ownProperty('length'); - - err(function(){ - ({ length: 12 }).should.not.have.ownProperty('length'); - }, "expected { length: 12 } to not have own property 'length'"); - }, - - 'test string()': function(){ - 'foobar'.should.include.string('bar'); - 'foobar'.should.include.string('foo'); - 'foobar'.should.not.include.string('baz'); - - err(function(){ - (3).should.include.string('baz'); - }, "expected 3 to be a string"); - - err(function(){ - 'foobar'.should.include.string('baz'); - }, "expected 'foobar' to include 'baz'"); - - err(function(){ - 'foobar'.should.not.include.string('bar'); - }, "expected 'foobar' to not include 'bar'"); - }, - - 'test object()': function(){ - var obj = {foo: 'bar', baz: {baaz: 42}, qux: 13}; - obj.should.include.object({foo: 'bar'}); - obj.should.include.object({baz: {baaz: 42}}); - obj.should.include.object({foo: 'bar', qux: 13}); - obj.should.not.include.object({foo: 'baz'}); - obj.should.not.include.object({foo: 'bar', baz: {baaz: -42}}); - - err(function(){ - (3).should.include.object({foo: 'bar'}); - }, "expected 3 to be a object"); - - err(function(){ - var obj = {foo: 'bar'}; - obj.should.include.object({foo: 'baz'}); - }, "expected { foo: 'bar' } to include { foo: 'baz' }"); - - err(function(){ - var obj = {foo: 'bar'}; - obj.should.not.include.object({foo: 'bar'}); - }, "expected { foo: 'bar' } to not include { foo: 'bar' }"); - }, - 'test contain()': function(){ - ['foo', 'bar'].should.contain('foo'); - ['foo', 'bar'].should.contain('foo'); - ['foo', 'bar'].should.contain('bar'); - [1,2].should.contain(1); - ['foo', 'bar'].should.not.contain('baz'); - ['foo', 'bar'].should.not.contain(1); - - err(function(){ - ['foo'].should.contain('bar'); - }, "expected [ 'foo' ] to contain 'bar'"); - - err(function(){ - ['bar', 'foo'].should.not.contain('foo'); - }, "expected [ 'bar', 'foo' ] to not contain 'foo'"); - }, - - 'test keys(array)': function(){ - ({ foo: 1 }).should.have.keys(['foo']); - ({ foo: 1, bar: 2 }).should.have.keys(['foo', 'bar']); - ({ foo: 1, bar: 2 }).should.have.keys('foo', 'bar'); - ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('foo', 'bar'); - ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('bar', 'foo'); - ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('baz'); - - ({ foo: 1, bar: 2 }).should.include.keys('foo'); - ({ foo: 1, bar: 2 }).should.include.keys('bar', 'foo'); - ({ foo: 1, bar: 2 }).should.include.keys(['foo']); - ({ foo: 1, bar: 2 }).should.include.keys(['bar']); - ({ foo: 1, bar: 2 }).should.include.keys(['bar', 'foo']); - - ({ foo: 1, bar: 2 }).should.not.have.keys('baz'); - ({ foo: 1, bar: 2 }).should.not.have.keys('foo', 'baz'); - ({ foo: 1, bar: 2 }).should.not.include.keys('baz'); - ({ foo: 1, bar: 2 }).should.not.include.keys('foo', 'baz'); - ({ foo: 1, bar: 2 }).should.not.include.keys('baz', 'foo'); - - err(function(){ - ({ foo: 1 }).should.have.keys(); - }, "keys required"); - - err(function(){ - ({ foo: 1 }).should.have.keys([]); - }, "keys required"); - - err(function(){ - ({ foo: 1 }).should.not.have.keys([]); - }, "keys required"); - - err(function(){ - ({ foo: 1 }).should.include.keys([]); - }, "keys required"); - - err(function(){ - ({ foo: 1 }).should.have.keys(['bar']); - }, "expected { foo: 1 } to have key 'bar'"); - - err(function(){ - ({ foo: 1 }).should.have.keys(['bar', 'baz']); - }, "expected { foo: 1 } to have keys 'bar', and 'baz'"); - - err(function(){ - ({ foo: 1 }).should.have.keys(['foo', 'bar', 'baz']); - }, "expected { foo: 1 } to have keys 'foo', 'bar', and 'baz'"); - - err(function(){ - ({ foo: 1 }).should.not.have.keys(['foo']); - }, "expected { foo: 1 } to not have key 'foo'"); - - err(function(){ - ({ foo: 1 }).should.not.have.keys(['foo']); - }, "expected { foo: 1 } to not have key 'foo'"); - - err(function(){ - ({ foo: 1, bar: 2 }).should.not.have.keys(['foo', 'bar']); - }, "expected { foo: 1, bar: 2 } to not have keys 'foo', and 'bar'"); - - err(function(){ - ({ foo: 1 }).should.not.include.keys(['foo']); - }, "expected { foo: 1 } to not include key 'foo'"); - - err(function(){ - ({ foo: 1 }).should.include.keys('foo', 'bar'); - }, "expected { foo: 1 } to include keys 'foo', and 'bar'"); - }, - - 'test respondTo(method)': function(){ - 'test'.should.respondTo('toString'); - 'test'.should.not.respondTo('toBuffer'); - }, - - 'test chaining': function(){ - var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] }; - user.should.have.property('pets').with.lengthOf(4); - - err(function(){ - user.should.have.property('pets').with.lengthOf(5); - }, "expected [ 'tobi', 'loki', 'jane', 'bandit' ] to have a length of 5 but got 4"); - - user.should.be.a('object').and.have.property('name', 'tj'); - } -}; diff --git a/node_modules/underscore/.npmignore b/node_modules/underscore/.npmignore deleted file mode 100644 index 2ce2684..0000000 --- a/node_modules/underscore/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -test/ -Rakefile -docs/ \ No newline at end of file diff --git a/node_modules/underscore/LICENSE b/node_modules/underscore/LICENSE deleted file mode 100644 index 61d28c0..0000000 --- a/node_modules/underscore/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2009-2012 Jeremy Ashkenas, DocumentCloud - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/underscore/README b/node_modules/underscore/README deleted file mode 100644 index ba19f1d..0000000 --- a/node_modules/underscore/README +++ /dev/null @@ -1,19 +0,0 @@ - __ - /\ \ - __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ -/\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ -\ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ - \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\ - \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/ - - - -Underscore.js is a utility-belt library for JavaScript that provides -support for the usual functional suspects (each, map, reduce, filter...) -without extending any core JavaScript objects. - -For Docs, License, Tests, and pre-packed downloads, see: -http://documentcloud.github.com/underscore/ - -Many thanks to our contributors: -https://github.com/documentcloud/underscore/contributors diff --git a/node_modules/underscore/index.html b/node_modules/underscore/index.html deleted file mode 100644 index ebcb466..0000000 --- a/node_modules/underscore/index.html +++ /dev/null @@ -1,1919 +0,0 @@ - - - - - - Underscore.js - - - - - - -
    - -

    - Underscore.js -

    - -

    - Underscore is a - utility-belt library for JavaScript that provides a lot of the - functional programming support that you would expect in - Prototype.js - (or Ruby), - but without extending any of the built-in JavaScript objects. It's the - tie to go along with jQuery's tux, - and Backbone.js's suspenders. -

    - -

    - Underscore provides 60-odd functions that support both the usual - functional suspects: map, select, invoke — - as well as more specialized helpers: function binding, javascript - templating, deep equality testing, and so on. It delegates to built-in - functions, if present, so modern browsers will use the - native implementations of forEach, map, reduce, - filter, every, some and indexOf. -

    - -

    - A complete Test & Benchmark Suite - is included for your perusal. -

    - -

    - You may also read through the annotated source code. -

    - -

    - The project is - hosted on GitHub. - You can report bugs and discuss features on the - issues page, - on Freenode in the #documentcloud channel, - or send tweets to @documentcloud. -

    - -

    - Underscore is an open-source component of DocumentCloud. -

    - -

    Downloads (Right-click, and use "Save As")

    - - - - - - - - - - -
    Development Version (1.2.4)34kb, Uncompressed with Comments
    Production Version (1.2.4)< 4kb, Minified and Gzipped
    - -
    - -

    Collection Functions (Arrays or Objects)

    - -

    - each_.each(list, iterator, [context]) - Alias: forEach -
    - Iterates over a list of elements, yielding each in turn to an iterator - function. The iterator is bound to the context object, if one is - passed. Each invocation of iterator is called with three arguments: - (element, index, list). If list is a JavaScript object, iterator's - arguments will be (value, key, list). Delegates to the native - forEach function if it exists. -

    -
    -_.each([1, 2, 3], function(num){ alert(num); });
    -=> alerts each number in turn...
    -_.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
    -=> alerts each number in turn...
    - -

    - map_.map(list, iterator, [context]) -
    - Produces a new array of values by mapping each value in list - through a transformation function (iterator). If the native map method - exists, it will be used instead. If list is a JavaScript object, - iterator's arguments will be (value, key, list). -

    -
    -_.map([1, 2, 3], function(num){ return num * 3; });
    -=> [3, 6, 9]
    -_.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
    -=> [3, 6, 9]
    - -

    - reduce_.reduce(list, iterator, memo, [context]) - Aliases: inject, foldl -
    - Also known as inject and foldl, reduce boils down a - list of values into a single value. Memo is the initial state - of the reduction, and each successive step of it should be returned by - iterator. -

    -
    -var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
    -=> 6
    -
    - -

    - reduceRight_.reduceRight(list, iterator, memo, [context]) - Alias: foldr -
    - The right-associative version of reduce. Delegates to the - JavaScript 1.8 version of reduceRight, if it exists. Foldr - is not as useful in JavaScript as it would be in a language with lazy - evaluation. -

    -
    -var list = [[0, 1], [2, 3], [4, 5]];
    -var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
    -=> [4, 5, 2, 3, 0, 1]
    -
    - -

    - find_.find(list, iterator, [context]) - Alias: detect -
    - Looks through each value in the list, returning the first one that - passes a truth test (iterator). The function returns as - soon as it finds an acceptable element, and doesn't traverse the - entire list. -

    -
    -var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
    -=> 2
    -
    - -

    - filter_.filter(list, iterator, [context]) - Alias: select -
    - Looks through each value in the list, returning an array of all - the values that pass a truth test (iterator). Delegates to the - native filter method, if it exists. -

    -
    -var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
    -=> [2, 4, 6]
    -
    - -

    - reject_.reject(list, iterator, [context]) -
    - Returns the values in list without the elements that the truth - test (iterator) passes. The opposite of filter. -

    -
    -var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
    -=> [1, 3, 5]
    -
    - -

    - all_.all(list, iterator, [context]) - Alias: every -
    - Returns true if all of the values in the list pass the iterator - truth test. Delegates to the native method every, if present. -

    -
    -_.all([true, 1, null, 'yes'], _.identity);
    -=> false
    -
    - -

    - any_.any(list, [iterator], [context]) - Alias: some -
    - Returns true if any of the values in the list pass the - iterator truth test. Short-circuits and stops traversing the list - if a true element is found. Delegates to the native method some, - if present. -

    -
    -_.any([null, 0, 'yes', false]);
    -=> true
    -
    - -

    - include_.include(list, value) - Alias: contains -
    - Returns true if the value is present in the list, using - === to test equality. Uses indexOf internally, if list - is an Array. -

    -
    -_.include([1, 2, 3], 3);
    -=> true
    -
    - -

    - invoke_.invoke(list, methodName, [*arguments]) -
    - Calls the method named by methodName on each value in the list. - Any extra arguments passed to invoke will be forwarded on to the - method invocation. -

    -
    -_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
    -=> [[1, 5, 7], [1, 2, 3]]
    -
    - -

    - pluck_.pluck(list, propertyName) -
    - A convenient version of what is perhaps the most common use-case for - map: extracting a list of property values. -

    -
    -var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
    -_.pluck(stooges, 'name');
    -=> ["moe", "larry", "curly"]
    -
    - -

    - max_.max(list, [iterator], [context]) -
    - Returns the maximum value in list. If iterator is passed, - it will be used on each value to generate the criterion by which the - value is ranked. -

    -
    -var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
    -_.max(stooges, function(stooge){ return stooge.age; });
    -=> {name : 'curly', age : 60};
    -
    - -

    - min_.min(list, [iterator], [context]) -
    - Returns the minimum value in list. If iterator is passed, - it will be used on each value to generate the criterion by which the - value is ranked. -

    -
    -var numbers = [10, 5, 100, 2, 1000];
    -_.min(numbers);
    -=> 2
    -
    - -

    - sortBy_.sortBy(list, iterator, [context]) -
    - Returns a sorted copy of list, ranked by the results of running - each value through iterator. -

    -
    -_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
    -=> [5, 4, 6, 3, 1, 2]
    -
    - -

    - groupBy_.groupBy(list, iterator) -
    - Splits a collection into sets, grouped by the result of running each - value through iterator. If iterator is a string instead of - a function, groups by the property named by iterator on each of - the values. -

    -
    -_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
    -=> {1: [1.3], 2: [2.1, 2.4]}
    -
    -_.groupBy(['one', 'two', 'three'], 'length');
    -=> {3: ["one", "two"], 5: ["three"]}
    -
    - -

    - sortedIndex_.sortedIndex(list, value, [iterator]) -
    - Uses a binary search to determine the index at which the value - should be inserted into the list in order to maintain the list's - sorted order. If an iterator is passed, it will be used to compute - the sort ranking of each value. -

    -
    -_.sortedIndex([10, 20, 30, 40, 50], 35);
    -=> 3
    -
    - -

    - shuffle_.shuffle(list) -
    - Returns a shuffled copy of the list, using a version of the - Fisher-Yates shuffle. -

    -
    -_.shuffle([1, 2, 3, 4, 5, 6]);
    -=> [4, 1, 6, 3, 5, 2]
    -
    - -

    - toArray_.toArray(list) -
    - Converts the list (anything that can be iterated over), into a - real Array. Useful for transmuting the arguments object. -

    -
    -(function(){ return _.toArray(arguments).slice(0); })(1, 2, 3);
    -=> [1, 2, 3]
    -
    - -

    - size_.size(list) -
    - Return the number of values in the list. -

    -
    -_.size({one : 1, two : 2, three : 3});
    -=> 3
    -
    - -

    Array Functions

    - -

    - Note: All array functions will also work on the arguments object. -

    - -

    - first_.first(array, [n]) - Alias: head -
    - Returns the first element of an array. Passing n will - return the first n elements of the array. -

    -
    -_.first([5, 4, 3, 2, 1]);
    -=> 5
    -
    - -

    - initial_.initial(array, [n]) -
    - Returns everything but the last entry of the array. Especially useful on - the arguments object. Pass n to exclude the last n elements - from the result. -

    -
    -_.initial([5, 4, 3, 2, 1]);
    -=> [5, 4, 3, 2]
    -
    - -

    - last_.last(array, [n]) -
    - Returns the last element of an array. Passing n will return - the last n elements of the array. -

    -
    -_.last([5, 4, 3, 2, 1]);
    -=> 1
    -
    - -

    - rest_.rest(array, [index]) - Alias: tail -
    - Returns the rest of the elements in an array. Pass an index - to return the values of the array from that index onward. -

    -
    -_.rest([5, 4, 3, 2, 1]);
    -=> [4, 3, 2, 1]
    -
    - -

    - compact_.compact(array) -
    - Returns a copy of the array with all falsy values removed. - In JavaScript, false, null, 0, "", - undefined and NaN are all falsy. -

    -
    -_.compact([0, 1, false, 2, '', 3]);
    -=> [1, 2, 3]
    -
    - -

    - flatten_.flatten(array) -
    - Flattens a nested array (the nesting can be to any depth). -

    -
    -_.flatten([1, [2], [3, [[[4]]]]]);
    -=> [1, 2, 3, 4];
    -
    - -

    - without_.without(array, [*values]) -
    - Returns a copy of the array with all instances of the values - removed. === is used for the equality test. -

    -
    -_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    -=> [2, 3, 4]
    -
    - -

    - union_.union(*arrays) -
    - Computes the union of the passed-in arrays: the list of unique items, - in order, that are present in one or more of the arrays. -

    -
    -_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
    -=> [1, 2, 3, 101, 10]
    -
    - -

    - intersection_.intersection(*arrays) -
    - Computes the list of values that are the intersection of all the arrays. - Each value in the result is present in each of the arrays. -

    -
    -_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
    -=> [1, 2]
    -
    - -

    - difference_.difference(array, *others) -
    - Similar to without, but returns the values from array that - are not present in the other arrays. -

    -
    -_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
    -=> [1, 3, 4]
    -
    - -

    - uniq_.uniq(array, [isSorted], [iterator]) - Alias: unique -
    - Produces a duplicate-free version of the array, using === to test - object equality. If you know in advance that the array is sorted, - passing true for isSorted will run a much faster algorithm. - If you want to compute unique items based on a transformation, pass an - iterator function. -

    -
    -_.uniq([1, 2, 1, 3, 1, 4]);
    -=> [1, 2, 3, 4]
    -
    - -

    - zip_.zip(*arrays) -
    - Merges together the values of each of the arrays with the - values at the corresponding position. Useful when you have separate - data sources that are coordinated through matching array indexes. - If you're working with a matrix of nested arrays, zip.apply - can transpose the matrix in a similar fashion. -

    -
    -_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
    -=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
    -
    - -

    - indexOf_.indexOf(array, value, [isSorted]) -
    - Returns the index at which value can be found in the array, - or -1 if value is not present in the array. Uses the native - indexOf function unless it's missing. If you're working with a - large array, and you know that the array is already sorted, pass true - for isSorted to use a faster binary search. -

    -
    -_.indexOf([1, 2, 3], 2);
    -=> 1
    -
    - -

    - lastIndexOf_.lastIndexOf(array, value) -
    - Returns the index of the last occurrence of value in the array, - or -1 if value is not present. Uses the native lastIndexOf - function if possible. -

    -
    -_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
    -=> 4
    -
    - -

    - range_.range([start], stop, [step]) -
    - A function to create flexibly-numbered lists of integers, handy for - each and map loops. start, if omitted, defaults - to 0; step defaults to 1. Returns a list of integers - from start to stop, incremented (or decremented) by step, - exclusive. -

    -
    -_.range(10);
    -=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    -_.range(1, 11);
    -=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    -_.range(0, 30, 5);
    -=> [0, 5, 10, 15, 20, 25]
    -_.range(0, -10, -1);
    -=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    -_.range(0);
    -=> []
    -
    - -

    Function (uh, ahem) Functions

    - -

    - bind_.bind(function, object, [*arguments]) -
    - Bind a function to an object, meaning that whenever - the function is called, the value of this will be the object. - Optionally, bind arguments to the function to pre-fill them, - also known as partial application. -

    -
    -var func = function(greeting){ return greeting + ': ' + this.name };
    -func = _.bind(func, {name : 'moe'}, 'hi');
    -func();
    -=> 'hi: moe'
    -
    - -

    - bindAll_.bindAll(object, [*methodNames]) -
    - Binds a number of methods on the object, specified by - methodNames, to be run in the context of that object whenever they - are invoked. Very handy for binding functions that are going to be used - as event handlers, which would otherwise be invoked with a fairly useless - this. If no methodNames are provided, all of the object's - function properties will be bound to it. -

    -
    -var buttonView = {
    -  label   : 'underscore',
    -  onClick : function(){ alert('clicked: ' + this.label); },
    -  onHover : function(){ console.log('hovering: ' + this.label); }
    -};
    -_.bindAll(buttonView);
    -jQuery('#underscore_button').bind('click', buttonView.onClick);
    -=> When the button is clicked, this.label will have the correct value...
    -
    - -

    - memoize_.memoize(function, [hashFunction]) -
    - Memoizes a given function by caching the computed result. Useful - for speeding up slow-running computations. If passed an optional - hashFunction, it will be used to compute the hash key for storing - the result, based on the arguments to the original function. The default - hashFunction just uses the first argument to the memoized function - as the key. -

    -
    -var fibonacci = _.memoize(function(n) {
    -  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    -});
    -
    - -

    - delay_.delay(function, wait, [*arguments]) -
    - Much like setTimeout, invokes function after wait - milliseconds. If you pass the optional arguments, they will be - forwarded on to the function when it is invoked. -

    -
    -var log = _.bind(console.log, console);
    -_.delay(log, 1000, 'logged later');
    -=> 'logged later' // Appears after one second.
    -
    - -

    - defer_.defer(function) -
    - Defers invoking the function until the current call stack has cleared, - similar to using setTimeout with a delay of 0. Useful for performing - expensive computations or HTML rendering in chunks without blocking the UI thread - from updating. -

    -
    -_.defer(function(){ alert('deferred'); });
    -// Returns from the function before the alert runs.
    -
    - -

    - throttle_.throttle(function, wait) -
    - Creates and returns a new, throttled version of the passed function, - that, when invoked repeatedly, will only actually call the original function - at most once per every wait - milliseconds. Useful for rate-limiting events that occur faster than you - can keep up with. -

    -
    -var throttled = _.throttle(updatePosition, 100);
    -$(window).scroll(throttled);
    -
    - -

    - debounce_.debounce(function, wait) -
    - Creates and returns a new debounced version of the passed function that - will postpone its execution until after - wait milliseconds have elapsed since the last time it - was invoked. Useful for implementing behavior that should only happen - after the input has stopped arriving. For example: rendering a - preview of a Markdown comment, recalculating a layout after the window - has stopped being resized, and so on. -

    -
    -var lazyLayout = _.debounce(calculateLayout, 300);
    -$(window).resize(lazyLayout);
    -
    - -

    - once_.once(function) -
    - Creates a version of the function that can only be called one time. - Repeated calls to the modified function will have no effect, returning - the value from the original call. Useful for initialization functions, - instead of having to set a boolean flag and then check it later. -

    -
    -var initialize = _.once(createApplication);
    -initialize();
    -initialize();
    -// Application is only created once.
    -
    - -

    - after_.after(count, function) -
    - Creates a version of the function that will only be run after first - being called count times. Useful for grouping asynchronous responses, - where you want to be sure that all the async calls have finished, before - proceeding. -

    -
    -var renderNotes = _.after(notes.length, render);
    -_.each(notes, function(note) {
    -  note.asyncSave({success: renderNotes}); 
    -});
    -// renderNotes is run once, after all notes have saved.
    -
    - -

    - wrap_.wrap(function, wrapper) -
    - Wraps the first function inside of the wrapper function, - passing it as the first argument. This allows the wrapper to - execute code before and after the function runs, adjust the arguments, - and execute it conditionally. -

    -
    -var hello = function(name) { return "hello: " + name; };
    -hello = _.wrap(hello, function(func) {
    -  return "before, " + func("moe") + ", after";
    -});
    -hello();
    -=> 'before, hello: moe, after'
    -
    - -

    - compose_.compose(*functions) -
    - Returns the composition of a list of functions, where each function - consumes the return value of the function that follows. In math terms, - composing the functions f(), g(), and h() produces - f(g(h())). -

    -
    -var greet    = function(name){ return "hi: " + name; };
    -var exclaim  = function(statement){ return statement + "!"; };
    -var welcome = _.compose(exclaim, greet);
    -welcome('moe');
    -=> 'hi: moe!'
    -
    - -

    Object Functions

    - -

    - keys_.keys(object) -
    - Retrieve all the names of the object's properties. -

    -
    -_.keys({one : 1, two : 2, three : 3});
    -=> ["one", "two", "three"]
    -
    - -

    - values_.values(object) -
    - Return all of the values of the object's properties. -

    -
    -_.values({one : 1, two : 2, three : 3});
    -=> [1, 2, 3]
    -
    - -

    - functions_.functions(object) - Alias: methods -
    - Returns a sorted list of the names of every method in an object — - that is to say, the name of every function property of the object. -

    -
    -_.functions(_);
    -=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
    -
    - -

    - extend_.extend(destination, *sources) -
    - Copy all of the properties in the source objects over to the - destination object. It's in-order, so the last source will override - properties of the same name in previous arguments. -

    -
    -_.extend({name : 'moe'}, {age : 50});
    -=> {name : 'moe', age : 50}
    -
    - -

    - defaults_.defaults(object, *defaults) -
    - Fill in missing properties in object with default values from the - defaults objects. As soon as the property is filled, further defaults - will have no effect. -

    -
    -var iceCream = {flavor : "chocolate"};
    -_.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
    -=> {flavor : "chocolate", sprinkles : "lots"}
    -
    - -

    - clone_.clone(object) -
    - Create a shallow-copied clone of the object. Any nested objects - or arrays will be copied by reference, not duplicated. -

    -
    -_.clone({name : 'moe'});
    -=> {name : 'moe'};
    -
    - -

    - tap_.tap(object, interceptor) -
    - Invokes interceptor with the object, and then returns object. - The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. -

    -
    -_.chain([1,2,3,200])
    -  .filter(function(num) { return num % 2 == 0; })
    -  .tap(console.log)
    -  .map(function(num) { return num * num })
    -  .value();
    -=> [2, 200]
    -=> [4, 40000]
    -
    - -

    - isEqual_.isEqual(object, other) -
    - Performs an optimized deep comparison between the two objects, to determine - if they should be considered equal. -

    -
    -var moe   = {name : 'moe', luckyNumbers : [13, 27, 34]};
    -var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
    -moe == clone;
    -=> false
    -_.isEqual(moe, clone);
    -=> true
    -
    - -

    - isEmpty_.isEmpty(object) -
    - Returns true if object contains no values. -

    -
    -_.isEmpty([1, 2, 3]);
    -=> false
    -_.isEmpty({});
    -=> true
    -
    - -

    - isElement_.isElement(object) -
    - Returns true if object is a DOM element. -

    -
    -_.isElement(jQuery('body')[0]);
    -=> true
    -
    - -

    - isArray_.isArray(object) -
    - Returns true if object is an Array. -

    -
    -(function(){ return _.isArray(arguments); })();
    -=> false
    -_.isArray([1,2,3]);
    -=> true
    -
    - -

    - isArguments_.isArguments(object) -
    - Returns true if object is an Arguments object. -

    -
    -(function(){ return _.isArguments(arguments); })(1, 2, 3);
    -=> true
    -_.isArguments([1,2,3]);
    -=> false
    -
    - -

    - isFunction_.isFunction(object) -
    - Returns true if object is a Function. -

    -
    -_.isFunction(alert);
    -=> true
    -
    - -

    - isString_.isString(object) -
    - Returns true if object is a String. -

    -
    -_.isString("moe");
    -=> true
    -
    - -

    - isNumber_.isNumber(object) -
    - Returns true if object is a Number (including NaN). -

    -
    -_.isNumber(8.4 * 5);
    -=> true
    -
    - -

    - isBoolean_.isBoolean(object) -
    - Returns true if object is either true or false. -

    -
    -_.isBoolean(null);
    -=> false
    -
    - -

    - isDate_.isDate(object) -
    - Returns true if object is a Date. -

    -
    -_.isDate(new Date());
    -=> true
    -
    - -

    - isRegExp_.isRegExp(object) -
    - Returns true if object is a RegExp. -

    -
    -_.isRegExp(/moe/);
    -=> true
    -
    - -

    - isNaN_.isNaN(object) -
    - Returns true if object is NaN.
    Note: this is not - the same as the native isNaN function, which will also return - true if the variable is undefined. -

    -
    -_.isNaN(NaN);
    -=> true
    -isNaN(undefined);
    -=> true
    -_.isNaN(undefined);
    -=> false
    -
    - -

    - isNull_.isNull(object) -
    - Returns true if the value of object is null. -

    -
    -_.isNull(null);
    -=> true
    -_.isNull(undefined);
    -=> false
    -
    - -

    - isUndefined_.isUndefined(variable) -
    - Returns true if variable is undefined. -

    -
    -_.isUndefined(window.missingVariable);
    -=> true
    -
    - -

    Utility Functions

    - -

    - noConflict_.noConflict() -
    - Give control of the "_" variable back to its previous owner. Returns - a reference to the Underscore object. -

    -
    -var underscore = _.noConflict();
    - -

    - identity_.identity(value) -
    - Returns the same value that is used as the argument. In math: - f(x) = x
    - This function looks useless, but is used throughout Underscore as - a default iterator. -

    -
    -var moe = {name : 'moe'};
    -moe === _.identity(moe);
    -=> true
    - -

    - times_.times(n, iterator) -
    - Invokes the given iterator function n times. -

    -
    -_(3).times(function(){ genie.grantWish(); });
    - -

    - mixin_.mixin(object) -
    - Allows you to extend Underscore with your own utility functions. Pass - a hash of {name: function} definitions to have your functions - added to the Underscore object, as well as the OOP wrapper. -

    -
    -_.mixin({
    -  capitalize : function(string) {
    -    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
    -  }
    -});
    -_("fabio").capitalize();
    -=> "Fabio"
    -
    - -

    - uniqueId_.uniqueId([prefix]) -
    - Generate a globally-unique id for client-side models or DOM elements - that need one. If prefix is passed, the id will be appended to it. -

    -
    -_.uniqueId('contact_');
    -=> 'contact_104'
    - -

    - escape_.escape(string) -
    - Escapes a string for insertion into HTML, replacing - &, <, >, ", ', and / characters. -

    -
    -_.escape('Curly, Larry & Moe');
    -=> "Curly, Larry &amp; Moe"
    - -

    - template_.template(templateString, [context]) -
    - Compiles JavaScript templates into functions that can be evaluated - for rendering. Useful for rendering complicated bits of HTML from JSON - data sources. Template functions can both interpolate variables, using
    - <%= … %>, as well as execute arbitrary JavaScript code, with - <% … %>. If you wish to interpolate a value, and have - it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a - context object that has properties corresponding to the template's free - variables. If you're writing a one-off, you can pass the context - object as the second parameter to template in order to render - immediately instead of returning a template function. -

    -
    -var compiled = _.template("hello: <%= name %>");
    -compiled({name : 'moe'});
    -=> "hello: moe"
    -
    -var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
    -_.template(list, {people : ['moe', 'curly', 'larry']});
    -=> "<li>moe</li><li>curly</li><li>larry</li>"
    -
    -var template = _.template("<b><%- value %></b>");
    -template({value : '<script>'});
    -=> "<b>&lt;script&gt;</b>"
    - -

    - You can also use print from within JavaScript code. This is - sometimes more convenient than using <%= ... %>. -

    - -
    -var compiled = _.template("<% print('Hello ' + epithet); %>");
    -compiled({epithet: "stooge"});
    -=> "Hello stooge."
    - -

    - If ERB-style delimiters aren't your cup of tea, you can change Underscore's - template settings to use different symbols to set off interpolated code. - Define an interpolate regex to match expressions that should be - interpolated verbatim, an escape regex to match expressions that should - be inserted after being HTML escaped, and an evaluate regex to match - expressions that should be evaluated without insertion into the resulting - string. You may define or omit any combination of the three. - For example, to perform - Mustache.js - style templating: -

    - -
    -_.templateSettings = {
    -  interpolate : /\{\{(.+?)\}\}/g
    -};
    -
    -var template = _.template("Hello {{ name }}!");
    -template({name : "Mustache"});
    -=> "Hello Mustache!"
    - - -

    Chaining

    - -

    - You can use Underscore in either an object-oriented or a functional style, - depending on your preference. The following two lines of code are - identical ways to double a list of numbers. -

    - -
    -_.map([1, 2, 3], function(n){ return n * 2; });
    -_([1, 2, 3]).map(function(n){ return n * 2; });
    - -

    - Using the object-oriented style allows you to chain together methods. Calling - chain on a wrapped object will cause all future method calls to - return wrapped objects as well. When you've finished the computation, - use value to retrieve the final value. Here's an example of chaining - together a map/flatten/reduce, in order to get the word count of - every word in a song. -

    - -
    -var lyrics = [
    -  {line : 1, words : "I'm a lumberjack and I'm okay"},
    -  {line : 2, words : "I sleep all night and I work all day"},
    -  {line : 3, words : "He's a lumberjack and he's okay"},
    -  {line : 4, words : "He sleeps all night and he works all day"}
    -];
    -
    -_.chain(lyrics)
    -  .map(function(line) { return line.words.split(' '); })
    -  .flatten()
    -  .reduce(function(counts, word) {
    -    counts[word] = (counts[word] || 0) + 1;
    -    return counts;
    -}, {}).value();
    -
    -=> {lumberjack : 2, all : 4, night : 2 ... }
    - -

    - In addition, the - Array prototype's methods - are proxied through the chained Underscore object, so you can slip a - reverse or a push into your chain, and continue to - modify the array. -

    - -

    - chain_.chain(obj) -
    - Returns a wrapped object. Calling methods on this object will continue - to return wrapped objects until value is used. -

    -
    -var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
    -var youngest = _.chain(stooges)
    -  .sortBy(function(stooge){ return stooge.age; })
    -  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
    -  .first()
    -  .value();
    -=> "moe is 21"
    -
    - -

    - value_(obj).value() -
    - Extracts the value of a wrapped object. -

    -
    -_([1, 2, 3]).value();
    -=> [1, 2, 3]
    -
    - - - -

    - Underscore.lua, - a Lua port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -

    - -

    - Underscore.php, - a PHP port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -

    - -

    - Underscore-perl, - a Perl port of many of the Underscore.js functions, - aimed at on Perl hashes and arrays, also - available on GitHub. -

    - -

    - Underscore.string, - an Underscore extension that adds functions for string-manipulation: - trim, startsWith, contains, capitalize, - reverse, sprintf, and more. -

    - -

    - Ruby's Enumerable module. -

    - -

    - Prototype.js, which provides - JavaScript with collection functions in the manner closest to Ruby's Enumerable. -

    - -

    - Oliver Steele's - Functional JavaScript, - which includes comprehensive higher-order function support as well as string lambdas. -

    - -

    - Michael Aufreiter's Data.js, - a data manipulation + persistence library for JavaScript. -

    - -

    - Python's itertools. -

    - -

    Change Log

    - -

    - 1.2.4Jan. 4, 2012
    -

      -
    • - You now can (and probably should) write _.chain(list) - instead of _(list).chain(). -
    • -
    • - Fix for escaped characters in Underscore templates, and for supporting - customizations of _.templateSettings that only define one or - two of the required regexes. -
    • -
    • - Fix for passing an array as the first argument to an _.wrap'd function. -
    • -
    • - Improved compatibility with ClojureScript, which adds a call - function to String.prototype. -
    • -
    -

    - -

    - 1.2.3Dec. 7, 2011
    -

      -
    • - Dynamic scope is now preserved for compiled _.template functions, - so you can use the value of this if you like. -
    • -
    • - Sparse array support of _.indexOf, _.lastIndexOf. -
    • -
    • - Both _.reduce and _.reduceRight can now be passed an - explicitly undefined value. (There's no reason why you'd - want to do this.) -
    • -
    -

    - -

    - 1.2.2Nov. 14, 2011
    -

      -
    • - Continued tweaks to _.isEqual semantics. Now JS primitives are - considered equivalent to their wrapped versions, and arrays are compared - by their numeric properties only (#351). -
    • -
    • - _.escape no longer tries to be smart about not double-escaping - already-escaped HTML entities. Now it just escapes regardless (#350). -
    • -
    • - In _.template, you may now leave semicolons out of evaluated - statements if you wish: <% }) %> (#369). -
    • -
    • - _.after(callback, 0) will now trigger the callback immediately, - making "after" easier to use with asynchronous APIs (#366). -
    • -
    -

    - -

    - 1.2.1Oct. 24, 2011
    -

      -
    • - Several important bug fixes for _.isEqual, which should now - do better on mutated Arrays, and on non-Array objects with - length properties. (#329) -
    • -
    • - jrburke contributed Underscore exporting for AMD module loaders, - and tonylukasavage for Appcelerator Titanium. - (#335, #338) -
    • -
    • - You can now _.groupBy(list, 'property') as a shortcut for - grouping values by a particular common property. -
    • -
    • - _.throttle'd functions now fire immediately upon invocation, - and are rate-limited thereafter (#170, #266). -
    • -
    • - Most of the _.is[Type] checks no longer ducktype. -
    • -
    • - The _.bind function now also works on constructors, a-la - ES5 ... but you would never want to use _.bind on a - constructor function. -
    • -
    • - _.clone no longer wraps non-object types in Objects. -
    • -
    • - _.find and _.filter are now the preferred names for - _.detect and _.select. -
    • -
    -

    - -

    - 1.2.0Oct. 5, 2011
    -

      -
    • - The _.isEqual function now - supports true deep equality comparisons, with checks for cyclic structures, - thanks to Kit Cambridge. -
    • -
    • - Underscore templates now support HTML escaping interpolations, using - <%- ... %> syntax. -
    • -
    • - Ryan Tenney contributed _.shuffle, which uses a modified - Fisher-Yates to give you a shuffled copy of an array. -
    • -
    • - _.uniq can now be passed an optional iterator, to determine by - what criteria an object should be considered unique. -
    • -
    • - _.last now takes an optional argument which will return the last - N elements of the list. -
    • -
    • - A new _.initial function was added, as a mirror of _.rest, - which returns all the initial values of a list (except the last N). -
    • -
    -

    - -

    - 1.1.7July 13, 2011
    - Added _.groupBy, which aggregates a collection into groups of like items. - Added _.union and _.difference, to complement the - (re-named) _.intersection. - Various improvements for support of sparse arrays. - _.toArray now returns a clone, if directly passed an array. - _.functions now also returns the names of functions that are present - in the prototype chain. -

    - -

    - 1.1.6April 18, 2011
    - Added _.after, which will return a function that only runs after - first being called a specified number of times. - _.invoke can now take a direct function reference. - _.every now requires an iterator function to be passed, which - mirrors the ECMA5 API. - _.extend no longer copies keys when the value is undefined. - _.bind now errors when trying to bind an undefined value. -

    - -

    - 1.1.5Mar 20, 2011
    - Added an _.defaults function, for use merging together JS objects - representing default options. - Added an _.once function, for manufacturing functions that should - only ever execute a single time. - _.bind now delegates to the native ECMAScript 5 version, - where available. - _.keys now throws an error when used on non-Object values, as in - ECMAScript 5. - Fixed a bug with _.keys when used over sparse arrays. -

    - -

    - 1.1.4Jan 9, 2011
    - Improved compliance with ES5's Array methods when passing null - as a value. _.wrap now correctly sets this for the - wrapped function. _.indexOf now takes an optional flag for - finding the insertion index in an array that is guaranteed to already - be sorted. Avoiding the use of .callee, to allow _.isArray - to work properly in ES5's strict mode. -

    - -

    - 1.1.3Dec 1, 2010
    - In CommonJS, Underscore may now be required with just:
    - var _ = require("underscore"). - Added _.throttle and _.debounce functions. - Removed _.breakLoop, in favor of an ECMA5-style un-break-able - each implementation — this removes the try/catch, and you'll now have - better stack traces for exceptions that are thrown within an Underscore iterator. - Improved the isType family of functions for better interoperability - with Internet Explorer host objects. - _.template now correctly escapes backslashes in templates. - Improved _.reduce compatibility with the ECMA5 version: - if you don't pass an initial value, the first item in the collection is used. - _.each no longer returns the iterated collection, for improved - consistency with ES5's forEach. -

    - -

    - 1.1.2
    - Fixed _.contains, which was mistakenly pointing at - _.intersect instead of _.include, like it should - have been. Added _.unique as an alias for _.uniq. -

    - -

    - 1.1.1
    - Improved the speed of _.template, and its handling of multiline - interpolations. Ryan Tenney contributed optimizations to many Underscore - functions. An annotated version of the source code is now available. -

    - -

    - 1.1.0
    - The method signature of _.reduce has been changed to match - the ECMAScript 5 signature, instead of the Ruby/Prototype.js version. - This is a backwards-incompatible change. _.template may now be - called with no arguments, and preserves whitespace. _.contains - is a new alias for _.include. -

    - -

    - 1.0.4
    - Andri Möll contributed the _.memoize - function, which can be used to speed up expensive repeated computations - by caching the results. -

    - -

    - 1.0.3
    - Patch that makes _.isEqual return false if any property - of the compared object has a NaN value. Technically the correct - thing to do, but of questionable semantics. Watch out for NaN comparisons. -

    - -

    - 1.0.2
    - Fixes _.isArguments in recent versions of Opera, which have - arguments objects as real Arrays. -

    - -

    - 1.0.1
    - Bugfix for _.isEqual, when comparing two objects with the same - number of undefined keys, but with different names. -

    - -

    - 1.0.0
    - Things have been stable for many months now, so Underscore is now - considered to be out of beta, at 1.0. Improvements since 0.6 - include _.isBoolean, and the ability to have _.extend - take multiple source objects. -

    - -

    - 0.6.0
    - Major release. Incorporates a number of - Mile Frawley's refactors for - safer duck-typing on collection functions, and cleaner internals. A new - _.mixin method that allows you to extend Underscore with utility - functions of your own. Added _.times, which works the same as in - Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray, - and Object.keys. -

    - -

    - 0.5.8
    - Fixed Underscore's collection functions to work on - NodeLists and - HTMLCollections - once more, thanks to - Justin Tulloss. -

    - -

    - 0.5.7
    - A safer implementation of _.isArguments, and a - faster _.isNumber,
    thanks to - Jed Schmidt. -

    - -

    - 0.5.6
    - Customizable delimiters for _.template, contributed by - Noah Sloan. -

    - -

    - 0.5.5
    - Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object. -

    - -

    - 0.5.4
    - Fix for multiple single quotes within a template string for - _.template. See: - Rick Strahl's blog post. -

    - -

    - 0.5.2
    - New implementations of isArray, isDate, isFunction, - isNumber, isRegExp, and isString, thanks to - a suggestion from - Robert Kieffer. - Instead of doing Object#toString - comparisons, they now check for expected properties, which is less safe, - but more than an order of magnitude faster. Most other Underscore - functions saw minor speed improvements as a result. - Evgeniy Dolzhenko - contributed _.tap, - similar to Ruby 1.9's, - which is handy for injecting side effects (like logging) into chained calls. -

    - -

    - 0.5.1
    - Added an _.isArguments function. Lots of little safety checks - and optimizations contributed by - Noah Sloan and - Andri Möll. -

    - -

    - 0.5.0
    - [API Changes] _.bindAll now takes the context object as - its first parameter. If no method names are passed, all of the context - object's methods are bound to it, enabling chaining and easier binding. - _.functions now takes a single argument and returns the names - of its Function properties. Calling _.functions(_) will get you - the previous behavior. - Added _.isRegExp so that isEqual can now test for RegExp equality. - All of the "is" functions have been shrunk down into a single definition. - Karl Guertin contributed patches. -

    - -

    - 0.4.7
    - Added isDate, isNaN, and isNull, for completeness. - Optimizations for isEqual when checking equality between Arrays - or Dates. _.keys is now 25%–2X faster (depending on your - browser) which speeds up the functions that rely on it, such as _.each. -

    - -

    - 0.4.6
    - Added the range function, a port of the - Python - function of the same name, for generating flexibly-numbered lists - of integers. Original patch contributed by - Kirill Ishanov. -

    - -

    - 0.4.5
    - Added rest for Arrays and arguments objects, and aliased - first as head, and rest as tail, - thanks to Luke Sutton's patches. - Added tests ensuring that all Underscore Array functions also work on - arguments objects. -

    - -

    - 0.4.4
    - Added isString, and isNumber, for consistency. Fixed - _.isEqual(NaN, NaN) to return true (which is debatable). -

    - -

    - 0.4.3
    - Started using the native StopIteration object in browsers that support it. - Fixed Underscore setup for CommonJS environments. -

    - -

    - 0.4.2
    - Renamed the unwrapping function to value, for clarity. -

    - -

    - 0.4.1
    - Chained Underscore objects now support the Array prototype methods, so - that you can perform the full range of operations on a wrapped array - without having to break your chain. Added a breakLoop method - to break in the middle of any Underscore iteration. Added an - isEmpty function that works on arrays and objects. -

    - -

    - 0.4.0
    - All Underscore functions can now be called in an object-oriented style, - like so: _([1, 2, 3]).map(...);. Original patch provided by - Marc-André Cournoyer. - Wrapped objects can be chained through multiple - method invocations. A functions method - was added, providing a sorted list of all the functions in Underscore. -

    - -

    - 0.3.3
    - Added the JavaScript 1.8 function reduceRight. Aliased it - as foldr, and aliased reduce as foldl. -

    - -

    - 0.3.2
    - Now runs on stock Rhino - interpreters with: load("underscore.js"). - Added identity as a utility function. -

    - -

    - 0.3.1
    - All iterators are now passed in the original collection as their third - argument, the same as JavaScript 1.6's forEach. Iterating over - objects is now called with (value, key, collection), for details - see _.each. -

    - -

    - 0.3.0
    - Added Dmitry Baranovskiy's - comprehensive optimizations, merged in - Kris Kowal's patches to make Underscore - CommonJS and - Narwhal compliant. -

    - -

    - 0.2.0
    - Added compose and lastIndexOf, renamed inject to - reduce, added aliases for inject, filter, - every, some, and forEach. -

    - -

    - 0.1.1
    - Added noConflict, so that the "Underscore" object can be assigned to - other variables. -

    - -

    - 0.1.0
    - Initial release of Underscore.js. -

    - -

    - - A DocumentCloud Project - -

    - -
    - -
    - - - - - - diff --git a/node_modules/underscore/index.js b/node_modules/underscore/index.js deleted file mode 100644 index 2cf0ca5..0000000 --- a/node_modules/underscore/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./underscore'); diff --git a/node_modules/underscore/package.json b/node_modules/underscore/package.json deleted file mode 100644 index d9dcd93..0000000 --- a/node_modules/underscore/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name" : "underscore", - "description" : "JavaScript's functional programming helper library.", - "homepage" : "http://documentcloud.github.com/underscore/", - "keywords" : ["util", "functional", "server", "client", "browser"], - "author" : "Jeremy Ashkenas ", - "contributors" : [], - "repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"}, - "main" : "underscore.js", - "version" : "1.2.4" -} diff --git a/node_modules/underscore/raw/underscore.psd b/node_modules/underscore/raw/underscore.psd deleted file mode 100644 index 73ad2d7..0000000 Binary files a/node_modules/underscore/raw/underscore.psd and /dev/null differ diff --git a/node_modules/underscore/underscore-min.js b/node_modules/underscore/underscore-min.js deleted file mode 100644 index 122914e..0000000 --- a/node_modules/underscore/underscore-min.js +++ /dev/null @@ -1,31 +0,0 @@ -// Underscore.js 1.2.4 -// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. -// Underscore is freely distributable under the MIT license. -// Portions of Underscore are inspired or borrowed from Prototype, -// Oliver Steele's Functional, and John Resig's Micro-Templating. -// For all details and documentation: -// http://documentcloud.github.com/underscore -(function(){function r(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source== -c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&r(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(m.call(a,h)&&(f++,!(g=m.call(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(m.call(c, -h)&&!f--)break;g=!f}}d.pop();return g}var s=this,G=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,H=k.unshift,l=p.toString,m=p.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,q=k.indexOf,D=k.lastIndexOf,p=Array.isArray,I=Object.keys,t=Function.prototype.bind,b=function(a){return new n(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else typeof define==="function"&&define.amd? -define("underscore",function(){return b}):s._=b;b.VERSION="1.2.4";var j=b.each=b.forEach=function(a,c,b){if(a!=null)if(w&&a.forEach===w)a.forEach(c,b);else if(a.length===+a.length)for(var e=0,f=a.length;e2;a==null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&& -(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e; -if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=e&&c.call(b,a,g,h)))return o});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return o});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return q&&a.indexOf===q?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a, -function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a, -b,h){b=c?c.call(d,a,b,h):a;bd?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c= -e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e>1;d(a[g])=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e= -0;e= -0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=I||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)m.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)b[d]!== -void 0&&(a[d]=b[d])});return a};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(m.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)== -"[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!m.call(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"}; -b.isDate=function(a){return l.call(a)=="[object Date]"};b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.noConflict=function(){s._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}; -b.mixin=function(a){j(b.functions(a),function(c){J(c,b[c]=a[c])})};var K=0;b.uniqueId=function(a){var b=K++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var u=/.^/;b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||u,function(a,b){return"',_.escape("+b.replace(/\\'/g,"'")+"),'"}).replace(d.interpolate|| -u,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||u,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ").replace(/\\\\/g,"\\")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var n=function(a){this._wrapped=a};b.prototype=n.prototype;var v=function(a,c){return c?b(a).chain(): -a},J=function(a,c){n.prototype[a]=function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];n.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];n.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}}); -n.prototype.chain=function(){this._chain=true;return this};n.prototype.value=function(){return this._wrapped}}).call(this); diff --git a/node_modules/underscore/underscore.js b/node_modules/underscore/underscore.js deleted file mode 100644 index c8cd1fd..0000000 --- a/node_modules/underscore/underscore.js +++ /dev/null @@ -1,995 +0,0 @@ -// Underscore.js 1.2.4 -// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. -// Underscore is freely distributable under the MIT license. -// Portions of Underscore are inspired or borrowed from Prototype, -// Oliver Steele's Functional, and John Resig's Micro-Templating. -// For all details and documentation: -// http://documentcloud.github.com/underscore - -(function() { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var root = this; - - // Save the previous value of the `_` variable. - var previousUnderscore = root._; - - // Establish the object that gets returned to break out of a loop iteration. - var breaker = {}; - - // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; - - // Create quick reference variables for speed access to core prototypes. - var slice = ArrayProto.slice, - unshift = ArrayProto.unshift, - toString = ObjProto.toString, - hasOwnProperty = ObjProto.hasOwnProperty; - - // All **ECMAScript 5** native function implementations that we hope to use - // are declared here. - var - nativeForEach = ArrayProto.forEach, - nativeMap = ArrayProto.map, - nativeReduce = ArrayProto.reduce, - nativeReduceRight = ArrayProto.reduceRight, - nativeFilter = ArrayProto.filter, - nativeEvery = ArrayProto.every, - nativeSome = ArrayProto.some, - nativeIndexOf = ArrayProto.indexOf, - nativeLastIndexOf = ArrayProto.lastIndexOf, - nativeIsArray = Array.isArray, - nativeKeys = Object.keys, - nativeBind = FuncProto.bind; - - // Create a safe reference to the Underscore object for use below. - var _ = function(obj) { return new wrapper(obj); }; - - // Export the Underscore object for **Node.js** and **"CommonJS"**, with - // backwards-compatibility for the old `require()` API. If we're not in - // CommonJS, add `_` to the global object. - if (typeof exports !== 'undefined') { - if (typeof module !== 'undefined' && module.exports) { - exports = module.exports = _; - } - exports._ = _; - } else if (typeof define === 'function' && define.amd) { - // Register as a named module with AMD. - define('underscore', function() { - return _; - }); - } else { - // Exported as a string, for Closure Compiler "advanced" mode. - root['_'] = _; - } - - // Current version. - _.VERSION = '1.2.4'; - - // Collection Functions - // -------------------- - - // The cornerstone, an `each` implementation, aka `forEach`. - // Handles objects with the built-in `forEach`, arrays, and raw objects. - // Delegates to **ECMAScript 5**'s native `forEach` if available. - var each = _.each = _.forEach = function(obj, iterator, context) { - if (obj == null) return; - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - } else if (obj.length === +obj.length) { - for (var i = 0, l = obj.length; i < l; i++) { - if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; - } - } else { - for (var key in obj) { - if (hasOwnProperty.call(obj, key)) { - if (iterator.call(context, obj[key], key, obj) === breaker) return; - } - } - } - }; - - // Return the results of applying the iterator to each element. - // Delegates to **ECMAScript 5**'s native `map` if available. - _.map = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); - each(obj, function(value, index, list) { - results[results.length] = iterator.call(context, value, index, list); - }); - if (obj.length === +obj.length) results.length = obj.length; - return results; - }; - - // **Reduce** builds up a single result from a list of values, aka `inject`, - // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. - _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { - var initial = arguments.length > 2; - if (obj == null) obj = []; - if (nativeReduce && obj.reduce === nativeReduce) { - if (context) iterator = _.bind(iterator, context); - return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); - } - each(obj, function(value, index, list) { - if (!initial) { - memo = value; - initial = true; - } else { - memo = iterator.call(context, memo, value, index, list); - } - }); - if (!initial) throw new TypeError('Reduce of empty array with no initial value'); - return memo; - }; - - // The right-associative version of reduce, also known as `foldr`. - // Delegates to **ECMAScript 5**'s native `reduceRight` if available. - _.reduceRight = _.foldr = function(obj, iterator, memo, context) { - var initial = arguments.length > 2; - if (obj == null) obj = []; - if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { - if (context) iterator = _.bind(iterator, context); - return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); - } - var reversed = _.toArray(obj).reverse(); - if (context && !initial) iterator = _.bind(iterator, context); - return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); - }; - - // Return the first value which passes a truth test. Aliased as `detect`. - _.find = _.detect = function(obj, iterator, context) { - var result; - any(obj, function(value, index, list) { - if (iterator.call(context, value, index, list)) { - result = value; - return true; - } - }); - return result; - }; - - // Return all the elements that pass a truth test. - // Delegates to **ECMAScript 5**'s native `filter` if available. - // Aliased as `select`. - _.filter = _.select = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); - each(obj, function(value, index, list) { - if (iterator.call(context, value, index, list)) results[results.length] = value; - }); - return results; - }; - - // Return all the elements for which a truth test fails. - _.reject = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - each(obj, function(value, index, list) { - if (!iterator.call(context, value, index, list)) results[results.length] = value; - }); - return results; - }; - - // Determine whether all of the elements match a truth test. - // Delegates to **ECMAScript 5**'s native `every` if available. - // Aliased as `all`. - _.every = _.all = function(obj, iterator, context) { - var result = true; - if (obj == null) return result; - if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); - each(obj, function(value, index, list) { - if (!(result = result && iterator.call(context, value, index, list))) return breaker; - }); - return result; - }; - - // Determine if at least one element in the object matches a truth test. - // Delegates to **ECMAScript 5**'s native `some` if available. - // Aliased as `any`. - var any = _.some = _.any = function(obj, iterator, context) { - iterator || (iterator = _.identity); - var result = false; - if (obj == null) return result; - if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); - each(obj, function(value, index, list) { - if (result || (result = iterator.call(context, value, index, list))) return breaker; - }); - return !!result; - }; - - // Determine if a given value is included in the array or object using `===`. - // Aliased as `contains`. - _.include = _.contains = function(obj, target) { - var found = false; - if (obj == null) return found; - if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; - found = any(obj, function(value) { - return value === target; - }); - return found; - }; - - // Invoke a method (with arguments) on every item in a collection. - _.invoke = function(obj, method) { - var args = slice.call(arguments, 2); - return _.map(obj, function(value) { - return (_.isFunction(method) ? method || value : value[method]).apply(value, args); - }); - }; - - // Convenience version of a common use case of `map`: fetching a property. - _.pluck = function(obj, key) { - return _.map(obj, function(value){ return value[key]; }); - }; - - // Return the maximum element or (element-based computation). - _.max = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); - if (!iterator && _.isEmpty(obj)) return -Infinity; - var result = {computed : -Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed >= result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Return the minimum element (or element-based computation). - _.min = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); - if (!iterator && _.isEmpty(obj)) return Infinity; - var result = {computed : Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed < result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Shuffle an array. - _.shuffle = function(obj) { - var shuffled = [], rand; - each(obj, function(value, index, list) { - if (index == 0) { - shuffled[0] = value; - } else { - rand = Math.floor(Math.random() * (index + 1)); - shuffled[index] = shuffled[rand]; - shuffled[rand] = value; - } - }); - return shuffled; - }; - - // Sort the object's values by a criterion produced by an iterator. - _.sortBy = function(obj, iterator, context) { - return _.pluck(_.map(obj, function(value, index, list) { - return { - value : value, - criteria : iterator.call(context, value, index, list) - }; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }), 'value'); - }; - - // Groups the object's values by a criterion. Pass either a string attribute - // to group by, or a function that returns the criterion. - _.groupBy = function(obj, val) { - var result = {}; - var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; - each(obj, function(value, index) { - var key = iterator(value, index); - (result[key] || (result[key] = [])).push(value); - }); - return result; - }; - - // Use a comparator function to figure out at what index an object should - // be inserted so as to maintain order. Uses binary search. - _.sortedIndex = function(array, obj, iterator) { - iterator || (iterator = _.identity); - var low = 0, high = array.length; - while (low < high) { - var mid = (low + high) >> 1; - iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; - } - return low; - }; - - // Safely convert anything iterable into a real, live array. - _.toArray = function(iterable) { - if (!iterable) return []; - if (iterable.toArray) return iterable.toArray(); - if (_.isArray(iterable)) return slice.call(iterable); - if (_.isArguments(iterable)) return slice.call(iterable); - return _.values(iterable); - }; - - // Return the number of elements in an object. - _.size = function(obj) { - return _.toArray(obj).length; - }; - - // Array Functions - // --------------- - - // Get the first element of an array. Passing **n** will return the first N - // values in the array. Aliased as `head`. The **guard** check allows it to work - // with `_.map`. - _.first = _.head = function(array, n, guard) { - return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; - }; - - // Returns everything but the last entry of the array. Especcialy useful on - // the arguments object. Passing **n** will return all the values in - // the array, excluding the last N. The **guard** check allows it to work with - // `_.map`. - _.initial = function(array, n, guard) { - return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); - }; - - // Get the last element of an array. Passing **n** will return the last N - // values in the array. The **guard** check allows it to work with `_.map`. - _.last = function(array, n, guard) { - if ((n != null) && !guard) { - return slice.call(array, Math.max(array.length - n, 0)); - } else { - return array[array.length - 1]; - } - }; - - // Returns everything but the first entry of the array. Aliased as `tail`. - // Especially useful on the arguments object. Passing an **index** will return - // the rest of the values in the array from that index onward. The **guard** - // check allows it to work with `_.map`. - _.rest = _.tail = function(array, index, guard) { - return slice.call(array, (index == null) || guard ? 1 : index); - }; - - // Trim out all falsy values from an array. - _.compact = function(array) { - return _.filter(array, function(value){ return !!value; }); - }; - - // Return a completely flattened version of an array. - _.flatten = function(array, shallow) { - return _.reduce(array, function(memo, value) { - if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); - memo[memo.length] = value; - return memo; - }, []); - }; - - // Return a version of the array that does not contain the specified value(s). - _.without = function(array) { - return _.difference(array, slice.call(arguments, 1)); - }; - - // Produce a duplicate-free version of the array. If the array has already - // been sorted, you have the option of using a faster algorithm. - // Aliased as `unique`. - _.uniq = _.unique = function(array, isSorted, iterator) { - var initial = iterator ? _.map(array, iterator) : array; - var result = []; - _.reduce(initial, function(memo, el, i) { - if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) { - memo[memo.length] = el; - result[result.length] = array[i]; - } - return memo; - }, []); - return result; - }; - - // Produce an array that contains the union: each distinct element from all of - // the passed-in arrays. - _.union = function() { - return _.uniq(_.flatten(arguments, true)); - }; - - // Produce an array that contains every item shared between all the - // passed-in arrays. (Aliased as "intersect" for back-compat.) - _.intersection = _.intersect = function(array) { - var rest = slice.call(arguments, 1); - return _.filter(_.uniq(array), function(item) { - return _.every(rest, function(other) { - return _.indexOf(other, item) >= 0; - }); - }); - }; - - // Take the difference between one array and a number of other arrays. - // Only the elements present in just the first array will remain. - _.difference = function(array) { - var rest = _.flatten(slice.call(arguments, 1)); - return _.filter(array, function(value){ return !_.include(rest, value); }); - }; - - // Zip together multiple lists into a single array -- elements that share - // an index go together. - _.zip = function() { - var args = slice.call(arguments); - var length = _.max(_.pluck(args, 'length')); - var results = new Array(length); - for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); - return results; - }; - - // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), - // we need this function. Return the position of the first occurrence of an - // item in an array, or -1 if the item is not included in the array. - // Delegates to **ECMAScript 5**'s native `indexOf` if available. - // If the array is large and already in sort order, pass `true` - // for **isSorted** to use binary search. - _.indexOf = function(array, item, isSorted) { - if (array == null) return -1; - var i, l; - if (isSorted) { - i = _.sortedIndex(array, item); - return array[i] === item ? i : -1; - } - if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); - for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; - return -1; - }; - - // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. - _.lastIndexOf = function(array, item) { - if (array == null) return -1; - if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); - var i = array.length; - while (i--) if (i in array && array[i] === item) return i; - return -1; - }; - - // Generate an integer Array containing an arithmetic progression. A port of - // the native Python `range()` function. See - // [the Python documentation](http://docs.python.org/library/functions.html#range). - _.range = function(start, stop, step) { - if (arguments.length <= 1) { - stop = start || 0; - start = 0; - } - step = arguments[2] || 1; - - var len = Math.max(Math.ceil((stop - start) / step), 0); - var idx = 0; - var range = new Array(len); - - while(idx < len) { - range[idx++] = start; - start += step; - } - - return range; - }; - - // Function (ahem) Functions - // ------------------ - - // Reusable constructor function for prototype setting. - var ctor = function(){}; - - // Create a function bound to a given object (assigning `this`, and arguments, - // optionally). Binding with arguments is also known as `curry`. - // Delegates to **ECMAScript 5**'s native `Function.bind` if available. - // We check for `func.bind` first, to fail fast when `func` is undefined. - _.bind = function bind(func, context) { - var bound, args; - if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); - if (!_.isFunction(func)) throw new TypeError; - args = slice.call(arguments, 2); - return bound = function() { - if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); - ctor.prototype = func.prototype; - var self = new ctor; - var result = func.apply(self, args.concat(slice.call(arguments))); - if (Object(result) === result) return result; - return self; - }; - }; - - // Bind all of an object's methods to that object. Useful for ensuring that - // all callbacks defined on an object belong to it. - _.bindAll = function(obj) { - var funcs = slice.call(arguments, 1); - if (funcs.length == 0) funcs = _.functions(obj); - each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); - return obj; - }; - - // Memoize an expensive function by storing its results. - _.memoize = function(func, hasher) { - var memo = {}; - hasher || (hasher = _.identity); - return function() { - var key = hasher.apply(this, arguments); - return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); - }; - }; - - // Delays a function for the given number of milliseconds, and then calls - // it with the arguments supplied. - _.delay = function(func, wait) { - var args = slice.call(arguments, 2); - return setTimeout(function(){ return func.apply(func, args); }, wait); - }; - - // Defers a function, scheduling it to run after the current call stack has - // cleared. - _.defer = function(func) { - return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); - }; - - // Returns a function, that, when invoked, will only be triggered at most once - // during a given window of time. - _.throttle = function(func, wait) { - var context, args, timeout, throttling, more; - var whenDone = _.debounce(function(){ more = throttling = false; }, wait); - return function() { - context = this; args = arguments; - var later = function() { - timeout = null; - if (more) func.apply(context, args); - whenDone(); - }; - if (!timeout) timeout = setTimeout(later, wait); - if (throttling) { - more = true; - } else { - func.apply(context, args); - } - whenDone(); - throttling = true; - }; - }; - - // Returns a function, that, as long as it continues to be invoked, will not - // be triggered. The function will be called after it stops being called for - // N milliseconds. - _.debounce = function(func, wait) { - var timeout; - return function() { - var context = this, args = arguments; - var later = function() { - timeout = null; - func.apply(context, args); - }; - clearTimeout(timeout); - timeout = setTimeout(later, wait); - }; - }; - - // Returns a function that will be executed at most one time, no matter how - // often you call it. Useful for lazy initialization. - _.once = function(func) { - var ran = false, memo; - return function() { - if (ran) return memo; - ran = true; - return memo = func.apply(this, arguments); - }; - }; - - // Returns the first function passed as an argument to the second, - // allowing you to adjust arguments, run code before and after, and - // conditionally execute the original function. - _.wrap = function(func, wrapper) { - return function() { - var args = [func].concat(slice.call(arguments, 0)); - return wrapper.apply(this, args); - }; - }; - - // Returns a function that is the composition of a list of functions, each - // consuming the return value of the function that follows. - _.compose = function() { - var funcs = arguments; - return function() { - var args = arguments; - for (var i = funcs.length - 1; i >= 0; i--) { - args = [funcs[i].apply(this, args)]; - } - return args[0]; - }; - }; - - // Returns a function that will only be executed after being called N times. - _.after = function(times, func) { - if (times <= 0) return func(); - return function() { - if (--times < 1) { return func.apply(this, arguments); } - }; - }; - - // Object Functions - // ---------------- - - // Retrieve the names of an object's properties. - // Delegates to **ECMAScript 5**'s native `Object.keys` - _.keys = nativeKeys || function(obj) { - if (obj !== Object(obj)) throw new TypeError('Invalid object'); - var keys = []; - for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key; - return keys; - }; - - // Retrieve the values of an object's properties. - _.values = function(obj) { - return _.map(obj, _.identity); - }; - - // Return a sorted list of the function names available on the object. - // Aliased as `methods` - _.functions = _.methods = function(obj) { - var names = []; - for (var key in obj) { - if (_.isFunction(obj[key])) names.push(key); - } - return names.sort(); - }; - - // Extend a given object with all the properties in passed-in object(s). - _.extend = function(obj) { - each(slice.call(arguments, 1), function(source) { - for (var prop in source) { - if (source[prop] !== void 0) obj[prop] = source[prop]; - } - }); - return obj; - }; - - // Fill in a given object with default properties. - _.defaults = function(obj) { - each(slice.call(arguments, 1), function(source) { - for (var prop in source) { - if (obj[prop] == null) obj[prop] = source[prop]; - } - }); - return obj; - }; - - // Create a (shallow-cloned) duplicate of an object. - _.clone = function(obj) { - if (!_.isObject(obj)) return obj; - return _.isArray(obj) ? obj.slice() : _.extend({}, obj); - }; - - // Invokes interceptor with the obj, and then returns obj. - // The primary purpose of this method is to "tap into" a method chain, in - // order to perform operations on intermediate results within the chain. - _.tap = function(obj, interceptor) { - interceptor(obj); - return obj; - }; - - // Internal recursive comparison function. - function eq(a, b, stack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. - if (a === b) return a !== 0 || 1 / a == 1 / b; - // A strict comparison is necessary because `null == undefined`. - if (a == null || b == null) return a === b; - // Unwrap any wrapped objects. - if (a._chain) a = a._wrapped; - if (b._chain) b = b._wrapped; - // Invoke a custom `isEqual` method if one is provided. - if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); - if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); - // Compare `[[Class]]` names. - var className = toString.call(a); - if (className != toString.call(b)) return false; - switch (className) { - // Strings, numbers, dates, and booleans are compared by value. - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return a == String(b); - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for - // other numeric values. - return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a == +b; - // RegExps are compared by their source patterns and flags. - case '[object RegExp]': - return a.source == b.source && - a.global == b.global && - a.multiline == b.multiline && - a.ignoreCase == b.ignoreCase; - } - if (typeof a != 'object' || typeof b != 'object') return false; - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - var length = stack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (stack[length] == a) return true; - } - // Add the first object to the stack of traversed objects. - stack.push(a); - var size = 0, result = true; - // Recursively compare objects and arrays. - if (className == '[object Array]') { - // Compare array lengths to determine if a deep comparison is necessary. - size = a.length; - result = size == b.length; - if (result) { - // Deep compare the contents, ignoring non-numeric properties. - while (size--) { - // Ensure commutative equality for sparse arrays. - if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; - } - } - } else { - // Objects with different constructors are not equivalent. - if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; - // Deep compare objects. - for (var key in a) { - if (hasOwnProperty.call(a, key)) { - // Count the expected number of properties. - size++; - // Deep compare each member. - if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break; - } - } - // Ensure that both objects contain the same number of properties. - if (result) { - for (key in b) { - if (hasOwnProperty.call(b, key) && !(size--)) break; - } - result = !size; - } - } - // Remove the first object from the stack of traversed objects. - stack.pop(); - return result; - } - - // Perform a deep comparison to check if two objects are equal. - _.isEqual = function(a, b) { - return eq(a, b, []); - }; - - // Is a given array, string, or object empty? - // An "empty" object has no enumerable own-properties. - _.isEmpty = function(obj) { - if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; - for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; - return true; - }; - - // Is a given value a DOM element? - _.isElement = function(obj) { - return !!(obj && obj.nodeType == 1); - }; - - // Is a given value an array? - // Delegates to ECMA5's native Array.isArray - _.isArray = nativeIsArray || function(obj) { - return toString.call(obj) == '[object Array]'; - }; - - // Is a given variable an object? - _.isObject = function(obj) { - return obj === Object(obj); - }; - - // Is a given variable an arguments object? - _.isArguments = function(obj) { - return toString.call(obj) == '[object Arguments]'; - }; - if (!_.isArguments(arguments)) { - _.isArguments = function(obj) { - return !!(obj && hasOwnProperty.call(obj, 'callee')); - }; - } - - // Is a given value a function? - _.isFunction = function(obj) { - return toString.call(obj) == '[object Function]'; - }; - - // Is a given value a string? - _.isString = function(obj) { - return toString.call(obj) == '[object String]'; - }; - - // Is a given value a number? - _.isNumber = function(obj) { - return toString.call(obj) == '[object Number]'; - }; - - // Is the given value `NaN`? - _.isNaN = function(obj) { - // `NaN` is the only value for which `===` is not reflexive. - return obj !== obj; - }; - - // Is a given value a boolean? - _.isBoolean = function(obj) { - return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; - }; - - // Is a given value a date? - _.isDate = function(obj) { - return toString.call(obj) == '[object Date]'; - }; - - // Is the given value a regular expression? - _.isRegExp = function(obj) { - return toString.call(obj) == '[object RegExp]'; - }; - - // Is a given value equal to null? - _.isNull = function(obj) { - return obj === null; - }; - - // Is a given variable undefined? - _.isUndefined = function(obj) { - return obj === void 0; - }; - - // Utility Functions - // ----------------- - - // Run Underscore.js in *noConflict* mode, returning the `_` variable to its - // previous owner. Returns a reference to the Underscore object. - _.noConflict = function() { - root._ = previousUnderscore; - return this; - }; - - // Keep the identity function around for default iterators. - _.identity = function(value) { - return value; - }; - - // Run a function **n** times. - _.times = function (n, iterator, context) { - for (var i = 0; i < n; i++) iterator.call(context, i); - }; - - // Escape a string for HTML interpolation. - _.escape = function(string) { - return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/'); - }; - - // Add your own custom functions to the Underscore object, ensuring that - // they're correctly added to the OOP wrapper as well. - _.mixin = function(obj) { - each(_.functions(obj), function(name){ - addToWrapper(name, _[name] = obj[name]); - }); - }; - - // Generate a unique integer id (unique within the entire client session). - // Useful for temporary DOM ids. - var idCounter = 0; - _.uniqueId = function(prefix) { - var id = idCounter++; - return prefix ? prefix + id : id; - }; - - // By default, Underscore uses ERB-style template delimiters, change the - // following template settings to use alternative delimiters. - _.templateSettings = { - evaluate : /<%([\s\S]+?)%>/g, - interpolate : /<%=([\s\S]+?)%>/g, - escape : /<%-([\s\S]+?)%>/g - }; - - // When customizing `templateSettings`, if you don't want to define an - // interpolation, evaluation or escaping regex, we need one that is - // guaranteed not to match. - var noMatch = /.^/; - - // JavaScript micro-templating, similar to John Resig's implementation. - // Underscore templating handles arbitrary delimiters, preserves whitespace, - // and correctly escapes quotes within interpolated code. - _.template = function(str, data) { - var c = _.templateSettings; - var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + - 'with(obj||{}){__p.push(\'' + - str.replace(/\\/g, '\\\\') - .replace(/'/g, "\\'") - .replace(c.escape || noMatch, function(match, code) { - return "',_.escape(" + code.replace(/\\'/g, "'") + "),'"; - }) - .replace(c.interpolate || noMatch, function(match, code) { - return "'," + code.replace(/\\'/g, "'") + ",'"; - }) - .replace(c.evaluate || noMatch, function(match, code) { - return "');" + code.replace(/\\'/g, "'") - .replace(/[\r\n\t]/g, ' ') - .replace(/\\\\/g, '\\') + ";__p.push('"; - }) - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/\t/g, '\\t') - + "');}return __p.join('');"; - var func = new Function('obj', '_', tmpl); - if (data) return func(data, _); - return function(data) { - return func.call(this, data, _); - }; - }; - - // Add a "chain" function, which will delegate to the wrapper. - _.chain = function(obj) { - return _(obj).chain(); - }; - - // The OOP Wrapper - // --------------- - - // If Underscore is called as a function, it returns a wrapped object that - // can be used OO-style. This wrapper holds altered versions of all the - // underscore functions. Wrapped objects may be chained. - var wrapper = function(obj) { this._wrapped = obj; }; - - // Expose `wrapper.prototype` as `_.prototype` - _.prototype = wrapper.prototype; - - // Helper function to continue chaining intermediate results. - var result = function(obj, chain) { - return chain ? _(obj).chain() : obj; - }; - - // A method to easily add functions to the OOP wrapper. - var addToWrapper = function(name, func) { - wrapper.prototype[name] = function() { - var args = slice.call(arguments); - unshift.call(args, this._wrapped); - return result(func.apply(_, args), this._chain); - }; - }; - - // Add all of the Underscore functions to the wrapper object. - _.mixin(_); - - // Add all mutator Array functions to the wrapper. - each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - var wrapped = this._wrapped; - method.apply(wrapped, arguments); - var length = wrapped.length; - if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; - return result(wrapped, this._chain); - }; - }); - - // Add all accessor Array functions to the wrapper. - each(['concat', 'join', 'slice'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - return result(method.apply(this._wrapped, arguments), this._chain); - }; - }); - - // Start chaining a wrapped Underscore object. - wrapper.prototype.chain = function() { - this._chain = true; - return this; - }; - - // Extracts the result from a wrapped and chained object. - wrapper.prototype.value = function() { - return this._wrapped; - }; - -}).call(this); diff --git a/node_modules/winston/.npmignore b/node_modules/winston/.npmignore deleted file mode 100644 index 2c5c40a..0000000 --- a/node_modules/winston/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -test/*.log -test/fixtures/*.json -test/fixtures/logs/*.log -node_modules/ -node_modules/* -npm-debug.log \ No newline at end of file diff --git a/node_modules/winston/.travis.yml b/node_modules/winston/.travis.yml deleted file mode 100644 index c958222..0000000 --- a/node_modules/winston/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 - - 0.7 - -notifications: - email: - - travis@nodejitsu.com - irc: "irc.freenode.org#nodejitsu" - diff --git a/node_modules/winston/LICENSE b/node_modules/winston/LICENSE deleted file mode 100644 index 948d80d..0000000 --- a/node_modules/winston/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Charlie Robbins - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/winston/README.md b/node_modules/winston/README.md deleted file mode 100644 index 3893a1a..0000000 --- a/node_modules/winston/README.md +++ /dev/null @@ -1,730 +0,0 @@ -# winston [![Build Status](https://secure.travis-ci.org/flatiron/winston.png)](http://travis-ci.org/flatiron/winston) - -A multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs." - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing winston -``` - [sudo] npm install winston -``` - -## Motivation -Winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. - -There also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible. - -## Usage -There are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose. - -### Using the Default Logger -The default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger: - -``` js - var winston = require('winston'); - - winston.log('info', 'Hello distributed log files!'); - winston.info('Hello again distributed logs'); -``` - -By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods: - -``` js - winston.add(winston.transports.File, { filename: 'somefile.log' }); - winston.remove(winston.transports.Console); -``` - -For more documenation about working with each individual transport supported by Winston see the "Working with Transports" section below. - -### Instantiating your own Logger -If you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself: - -``` js - var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: 'somefile.log' }) - ] - }); -``` - -You can work with this logger in the same way that you work with the default logger: - -``` js - // - // Logging - // - logger.log('info', 'Hello distributed log files!'); - logger.info('Hello again distributed logs'); - - // - // Adding / Removing Transports - // (Yes It's chainable) - // - logger.add(winston.transports.File) - .remove(winston.transports.Console); -``` - -### Handling Uncaught Exceptions with winston - -With `winston`, it is possible to catch and log `uncaughtException` events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance. - -If you want to use this feature with the default logger simply call `.handleExceptions()` with a transport instance. - -``` js - // - // You can add a separate exception logger by passing it to `.handleExceptions` - // - winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' })) - - // - // Alternatively you can set `.handleExceptions` to true when adding transports to winston - // - winston.add(winston.transports.File, { - filename: 'path/to/all-logs.log', - handleExceptions: true - }); -``` - -## to exit or not to exit - -by default, winston will exit after logging an uncaughtException. if this is not the behavior you want, -set `exitOnError = false` - -``` js - var logger = new (winston.Logger)({ exitOnError: false }); - - // - // or, like this: - // - logger.exitOnError = false; -``` - -When working with custom logger instances, you can pass in separate transports to the `exceptionHandlers` property or set `.handleExceptions` on any transport. - -``` js - var logger = new (winston.Logger)({ - transports: [ - new winston.transports.File({ filename: 'path/to/all-logs.log' }) - ] - exceptionHandlers: [ - new winston.transports.File({ filename: 'path/to/exceptions.log' }) - ] - }); -``` - -The `exitOnError` option can also be a function to prevent exit on only certain types of errors: - -``` js - function ignoreEpipe(err) { - return err.code !== 'EPIPE'; - } - - var logger = new (winston.Logger)({ exitOnError: ignoreEpipe }); - - // - // or, like this: - // - logger.exitOnError = ignoreEpipe; -``` - -### Using Logging Levels -Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger. - -``` js - // - // Any logger instance - // - logger.log('info', "127.0.0.1 - there's no place like home"); - logger.info("127.0.0.1 - there's no place like home"); - - // - // Default logger - // - winston.log('info', "127.0.0.1 - there's no place like home"); - winston.info("127.0.0.1 - there's no place like home"); -``` - -As of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy: - -``` js - // - // Change levels on the default winston logger - // - winston.setLevels(winston.config.syslog.levels); - - // - // Change levels on an instance of a logger - // - logger.setLevels(winston.config.syslog.levels); -``` - -Calling `.setLevels` on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels: - -``` js - // - // Logger does not have 'silly' defined since that level is not in the syslog levels - // - logger.silly('some silly message'); -``` - -### Using Custom Logging Levels -In addition to the predefined `npm` and `syslog` levels available in Winston, you can also choose to define your own: - -``` js - var myCustomLevels = { - levels: { - foo: 0, - bar: 1, - baz: 2, - foobar: 3 - }, - colors: { - foo: 'blue', - bar: 'green', - baz: 'yellow', - foobar: 'red' - } - }; - - var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); - customLevelLogger.foobar('some foobar level-ed message'); -``` - -Although there is slight repetition in this data structure, it enables simple encapsulation if you not to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them: - -``` js - // - // Make winston aware of these colors - // - winston.addColors(myCustomLevels.colors); -``` - -This enables transports with the 'colorize' option set to appropriately color the output of custom levels. - -### Events and Callbacks in Winston -Each instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message: - -``` js - logger.on('logging', function (transport, level, msg, meta) { - // [msg] and [meta] have now been logged at [level] to [transport] - }); - - logger.info('CHILL WINSTON!', { seriously: true }); -``` - -It is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions: - -``` js - // - // Handle errors - // - logger.on('error', function (err) { /* Do Something */ }); - - // - // Or just suppress them. - // - logger.emitErrs = false; -``` - -Every logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message. - -``` js - logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) { - // [msg] and [meta] have now been logged at [level] to **every** transport. - }); -``` - -### Working with multiple Loggers in winston - -Often in larger, more complex applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in `winston` in two ways: through `winston.loggers` and instances of `winston.Container`. In fact, `winston.loggers` is just a predefined instance of `winston.Container`: - -``` js - var winston = require('winston'); - - // - // Configure the logger for `category1` - // - winston.loggers.add('category1', { - console: { - level: 'silly', - colorize: 'true' - }, - file: { - filename: '/path/to/some/file' - } - }); - - // - // Configure the logger for `category2` - // - winston.loggers.add('category2', { - couchdb: { - host: '127.0.0.1', - port: 5984 - } - }); -``` - -Now that your loggers are setup you can require winston _in any file in your application_ and access these pre-configured loggers: - -``` js - var winston = require('winston'); - - // - // Grab your preconfigured logger - // - var category1 = winston.loggers.get('category1'); - - category1.info('logging from your IoC container-based logger'); -``` - -If you prefer to manage the `Container` yourself you can simply instantiate one: - -``` js - var winston = require('winston'), - container = new winston.Container(); - - container.add('category1', { - console: { - level: 'silly', - colorize: 'true' - }, - file: { - filename: '/path/to/some/file' - } - }); -``` - -### Sharing transports between Loggers in winston - -``` js - var winston = require('winston'); - - // - // Setup transports to be shared across all loggers - // in three ways: - // - // 1. By setting it on the default Container - // 2. By passing `transports` into the constructor function of winston.Container - // 3. By passing `transports` into the `.get()` or `.add()` methods - // - - // - // 1. By setting it on the default Container - // - winston.loggers.options.transports = [ - // Setup your shared transports here - ]; - - // - // 2. By passing `transports` into the constructor function of winston.Container - // - var container = new winston.Container({ - transports: [ - // Setup your shared transports here - ] - }); - - // - // 3. By passing `transports` into the `.get()` or `.add()` methods - // - winston.loggers.add('some-category', { - transports: [ - // Setup your shared transports here - ] - }); - - container.add('some-category', { - transports: [ - // Setup your shared transports here - ] - }); -``` - -### Logging with Metadata -In addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple: - -``` js - winston.log('info', 'Test Log Message', { anything: 'This is metadata' }); -``` - -The way these objects is stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata: - -1. __Console:__ Logged via util.inspect(meta) -2. __File:__ Logged via util.inspect(meta) -3. __Loggly:__ Logged in suggested [Loggly format][2] - -### Profiling with Winston -In addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger: - -``` js - // - // Start profile of 'test' - // Remark: Consider using Date.now() with async operations - // - winston.profile('test'); - - setTimeout(function () { - // - // Stop profile of 'test'. Logging will now take place: - // "17 Jan 21:00:00 - info: test duration=1000ms" - // - winston.profile('test'); - }, 1000); -``` - -All profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues. - -### Using winston in a CLI tool -A common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the [require-analyzer][15] written by [Nodejitsu][5]: - -``` - info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer - info: Found existing dependencies - data: { - data: colors: '0.x.x', - data: eyes: '0.1.x', - data: findit: '0.0.x', - data: npm: '1.0.x', - data: optimist: '0.2.x', - data: semver: '1.0.x', - data: winston: '0.2.x' - data: } - info: Analyzing dependencies... - info: Done analyzing raw dependencies - info: Retrieved packages from npm - warn: No additional dependencies found -``` - -Configuring output for this style is easy, just use the `.cli()` method on `winston` or an instance of `winston.Logger`: - -``` js - var winston = require('winston'); - - // - // Configure CLI output on the default logger - // - winston.cli(); - - // - // Configure CLI on an instance of winston.Logger - // - var logger = new winston.Logger({ - transports: [ - new (winston.transports.Console)() - ] - }); - - logger.cli(); -``` - -### Extending another object with Logging functionality -Often in a given code base with lots of Loggers it is useful to add logging methods a different object so that these methods can be called with less syntax. Winston exposes this functionality via the 'extend' method: - -``` js - var myObject = {}; - - logger.extend(myObject); - - // - // You can now call logger methods on 'myObject' - // - myObject.info('127.0.0.1 - there's no place like home'); -``` - -## Working with Transports -Right now there are four transports supported by winston core. If you have a transport you would like to add either open an issue or fork and submit a pull request. Commits are welcome, but I'll give you extra street cred if you __add tests too :D__ - -1. __Console:__ Output to the terminal -2. __Files:__ Append to a file -3. __Loggly:__ Log to Logging-as-a-Service platform Loggly - -### Console Transport -``` js - winston.add(winston.transports.Console, options) -``` - -The Console transport takes two simple options: - -* __level:__ Level of messages that this transport should log (default 'debug'). -* __silent:__ Boolean flag indicating whether to suppress output (default false). -* __colorize:__ Boolean flag indicating if we should colorize output (default false). -* __timestamp:__ Boolean flag indicating if we should prepend output with timestamps (default false). - -*Metadata:* Logged via util.inspect(meta); - -### File Transport -``` js - winston.add(winston.transports.File, options) -``` - -The File transport should really be the 'Stream' transport since it will accept any [WritableStream][14]. It is named such because it will also accept filenames via the 'filename' option: - -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. -* __colorize:__ Boolean flag indicating if we should colorize output. -* __filename:__ The filename of the logfile to write output to. -* __maxsize:__ Max size in bytes of the logfile, if the size is exceeded then a new file is created. -* __maxFiles:__ Limit the number of files created when the size of the logfile is exceeded. -* __stream:__ The WriteableStream to write output to. - -*Metadata:* Logged via util.inspect(meta); - -### Loggly Transport -``` js - winston.add(winston.transports.Loggly, options); -``` - -The Loggly transport is based on [Nodejitsu's][5] [node-loggly][6] implementation of the [Loggly][7] API. If you haven't heard of Loggly before, you should probably read their [value proposition][8]. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required: - -* __level:__ Level of messages that this transport should log. -* __subdomain:__ The subdomain of your Loggly account. *[required]* -* __auth__: The authentication information for your Loggly account. *[required with inputName]* -* __inputName:__ The name of the input this instance should log to. -* __inputToken:__ The input token of the input this instance should log to. -* __json:__ If true, messages will be sent to Loggly as JSON. - -*Metadata:* Logged in suggested [Loggly format][2] - -### Riak Transport -As of `0.3.0` the Riak transport has been broken out into a new module: [winston-riak][17]. Using it is just as easy: - -``` js - var Riak = require('winston-riak').Riak; - winston.add(Riak, options); -``` - -In addition to the options accepted by the [riak-js][3] [client][4], the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to *false* by default: - -* __level:__ Level of messages that this transport should log. -* __bucket:__ The name of the Riak bucket you wish your logs to be in or a function to generate bucket names dynamically. - -``` js - // Use a single bucket for all your logs - var singleBucketTransport = new (Riak)({ bucket: 'some-logs-go-here' }); - - // Generate a dynamic bucket based on the date and level - var dynamicBucketTransport = new (Riak)({ - bucket: function (level, msg, meta, now) { - var d = new Date(now); - return level + [d.getDate(), d.getMonth(), d.getFullYear()].join('-'); - } - }); -``` - -*Metadata:* Logged as JSON literal in Riak - -### MongoDB Transport -As of `0.3.0` the MongoDB transport has been broken out into a new module: [winston-mongodb][16]. Using it is just as easy: - -``` js - var MongoDB = require('winston-mongodb').MongoDB; - winston.add(MongoDB, options); -``` - -The MongoDB transport takes the following options. 'db' is required: - -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. -* __db:__ The name of the database you want to log to. *[required]* -* __collection__: The name of the collection you want to store log messages in, defaults to 'log'. -* __safe:__ Boolean indicating if you want eventual consistency on your log messages, if set to true it requires an extra round trip to the server to ensure the write was committed, defaults to true. -* __host:__ The host running MongoDB, defaults to localhost. -* __port:__ The port on the host that MongoDB is running on, defaults to MongoDB's default port. - -*Metadata:* Logged as a native JSON object. - -### SimpleDB Transport - -The [winston-simpledb][18] transport is just as easy: - -``` js - var SimpleDB = require('winston-simpledb').SimpleDB; - winston.add(SimpleDB, options); -``` - -The SimpleDB transport takes the following options. All items marked with an asterisk are required: - -* __awsAccessKey__:* your AWS Access Key -* __secretAccessKey__:* your AWS Secret Access Key -* __awsAccountId__:* your AWS Account Id -* __domainName__:* a string or function that returns the domain name to log to -* __region__:* the region your domain resides in -* __itemName__: a string ('uuid', 'epoch', 'timestamp') or function that returns the item name to log - -*Metadata:* Logged as a native JSON object to the 'meta' attribute of the item. - -### Mail Transport - -The [winston-mail][19] is an email transport: - -``` js - var Mail = require('winston-mail').Mail; - winston.add(Mail, options); -``` - -The Mail transport uses [node-mail][20] behind the scenes. Options are the following, `to` and `host` are required: - -* __to:__ The address(es) you want to send to. *[required]* -* __from:__ The address you want to send from. (default: `winston@[server-host-name]`) -* __host:__ SMTP server hostname -* __port:__ SMTP port (default: 587 or 25) -* __secure:__ Use secure -* __username__ User for server auth -* __password__ Password for server auth -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. - -*Metadata:* Stringified as JSON in email. - -### Amazon SNS (Simple Notification System) Transport - -The [winston-sns][21] transport uses amazon SNS to send emails, texts, or a bunch of other notifications. - -``` js - require('winston-sns').SNS; - winston.add(winston.transports.SNS, options); -``` - -Options: - -* __aws_key:__ Your Amazon Web Services Key. *[required]* -* __aws_secret:__ Your Amazon Web Services Secret. *[required]* -* __subscriber:__ Subscriber number - found in your SNS AWS Console, after clicking on a topic. Same as AWS Account ID. *[required]* -* __topic_arn:__ Also found in SNS AWS Console - listed under a topic as Topic ARN. *[required]* -* __region:__ AWS Region to use. Can be one of: `us-east-1`,`us-west-1`,`eu-west-1`,`ap-southeast-1`,`ap-northeast-1`,`us-gov-west-1`,`sa-east-1`. (default: `us-east-1`) -* __subject:__ Subject for notifications. (default: "Winston Error Report") -* __message:__ Message of notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: "Level '%l' Error:\n%e\n\nMetadata:\n%m") -* __level:__ lowest level this transport will log. (default: `info`) - -### Graylog2 Transport - -[winston-graylog2][22] is a Graylog2 transport: - -``` js - var Graylog2 = require('winston-graylog2').Graylog2; - winston.add(Graylog2, options); -``` - -The Graylog2 transport connects to a Graylog2 server over UDP using the following options: - -* __level:__ Level of messages this transport should log. (default: info) -* __silent:__ Boolean flag indicating whether to suppress output. (default: false) - -* __graylogHost:__ IP address or hostname of the graylog2 server. (default: localhost) -* __graylogPort:__ Port to send messages to on the graylog2 server. (default: 12201) -* __graylogHostname:__ The hostname associated with graylog2 messages. (default: require('os').hostname()) -* __graylogFacility:__ The graylog2 facility to send log messages.. (default: nodejs) - -*Metadata:* Stringified as JSON in the full message GELF field. - -### Adding Custom Transports -Adding a custom transport (say for one of the datastore on the Roadmap) is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston. - -``` js - var util = require('util'), - winston = require('winston'); - - var CustomLogger = winston.transports.CustomerLogger = function (options) { - // - // Name this logger - // - this.name = 'customLogger'; - - // - // Set the level from your options - // - this.level = options.level || 'info'; - - // - // Configure your storage backing as you see fit - // - }; - - // - // Inherit from `winston.Transport` so you can take advantage - // of the base functionality and `.handleExceptions()`. - // - util.inherits(CustomLogger, winston.Transport); - - CustomLogger.prototype.log = function (level, msg, meta, callback) { - // - // Store this message and metadata, maybe use some custom logic - // then callback indicating success. - // - callback(null, true); - }; -``` - -## What's Next? -Winston is stable and under active development. It is supported by and used at [Nodejitsu][5]. - -### Inspirations -1. [npm][0] -2. [log.js][9] -3. [socket.io][10] -4. [node-rlog][11] -5. [BigBrother][12] -6. [Loggly][7] - -### Road Map -1. Improve support for adding custom Transports not defined in Winston core. -2. Create API for reading from logs across all transports. -3. Add more transports: Redis - -## Run Tests -All of the winston tests are written in [vows][13], and cover all of the use cases described above. You will need to add valid credentials for the various transports included to test/fixtures/test-config.json before running tests: - -``` js - { - "transports": { - "loggly": { - "subdomain": "your-subdomain", - "inputToken": "really-long-token-you-got-from-loggly", - "auth": { - "username": "your-username", - "password": "your-password" - } - } - } - } -``` - -Once you have valid configuration and credentials you can run tests with [vows][13]: - -``` - vows --spec --isolate -``` - -#### Author: [Charlie Robbins](http://twitter.com/indexzero) -#### Contributors: [Matthew Bergman](http://github.com/fotoverite), [Marak Squires](http://github.com/marak) - -[0]: https://github.com/isaacs/npm/blob/master/lib/utils/log.js -[1]: http://nodejs.org/docs/v0.3.5/api/events.html#events.EventEmitter -[2]: http://wiki.loggly.com/loggingfromcode -[3]: http://riakjs.org -[4]: https://github.com/frank06/riak-js/blob/master/src/http_client.coffee#L10 -[5]: http://nodejitsu.com -[6]: http://github.com/nodejitsu/node-loggly -[7]: http://loggly.com -[8]: http://www.loggly.com/product/ -[9]: https://github.com/visionmedia/log.js -[10]: http://socket.io -[11]: https://github.com/jbrisbin/node-rlog -[12]: https://github.com/feisty/BigBrother -[13]: http://vowsjs.org -[14]: http://nodejs.org/docs/v0.3.5/api/streams.html#writable_Stream -[15]: http://github.com/nodejitsu/require-analyzer -[16]: http://github.com/indexzero/winston-mongodb -[17]: http://github.com/indexzero/winston-riak -[18]: http://github.com/appsattic/winston-simpledb -[19]: http://github.com/wavded/winston-mail -[20]: https://github.com/weaver/node-mail -[21]: https://github.com/jesseditson/winston-sns -[22]: https://github.com/flite/winston-graylog2 diff --git a/node_modules/winston/docs/docco.css b/node_modules/winston/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/winston/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/winston/docs/winston.html b/node_modules/winston/docs/winston.html deleted file mode 100644 index 0c7f087..0000000 --- a/node_modules/winston/docs/winston.html +++ /dev/null @@ -1,86 +0,0 @@ - winston.js

    winston.js

    /*
    - * winston.js: Top-level include defining Winston.
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var winston = exports;

    Expose version using pkginfo

    require('pkginfo')(module, 'version');

    Include transports defined by default by winston

    winston.transports = require('./winston/transports');
    -
    -var common           = require('./winston/common');
    -winston.hash           = common.hash;
    -winston.clone          = common.clone;
    -winston.longestElement = common.longestElement;
    -winston.exception      = require('./winston/exception');
    -winston.config         = require('./winston/config');
    -winston.addColors      = winston.config.addColors; 
    -winston.Logger         = require('./winston/logger').Logger;
    -winston.Transport      = require('./winston/transports/transport').Transport;

    We create and expose a 'defaultLogger' so that the programmer may do the -following without the need to create an instance of winston.Logger directly:

    - -
    var winston = require('winston');
    -winston.log('info', 'some message');
    -winston.error('some error'); 
    -
    var defaultLogger = new winston.Logger({ 
    -  transports: [new winston.transports.Console()] 
    -});

    Pass through the target methods onto `winston.

    var methods = [
    -  'log', 
    -  'add', 
    -  'remove', 
    -  'profile', 
    -  'extend', 
    -  'cli', 
    -  'handleExceptions', 
    -  'unhandleExceptions'
    -];
    -common.setLevels(winston, null, defaultLogger.levels);
    -methods.forEach(function (method) {
    -  winston[method] = function () {
    -    return defaultLogger[method].apply(defaultLogger, arguments);
    -  };
    -});

    function cli ()

    - -

    Configures the default winston logger to have the -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels.

    winston.cli = function () {
    -  winston.padLevels = true;
    -  common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels);
    -  defaultLogger.setLevels(winston.config.cli.levels);
    -  winston.config.addColors(winston.config.cli.colors);
    -  
    -  if (defaultLogger.transports.console) {
    -    defaultLogger.transports.console.colorize = true;
    -    defaultLogger.transports.console.timestamp = false;
    -  }
    -  
    -  return winston;
    -};

    function setLevels (target)

    - -

    @target {Object} Target levels to use

    - -

    Sets the target levels specified on the default winston logger.

    winston.setLevels = function (target) {
    -  common.setLevels(winston, defaultLogger.levels, target);
    -  defaultLogger.setLevels(target);
    -};

    Define getters / setters for appropriate properties of the -default logger which need to be exposed by winston.

    ['emitErrs', 'padLevels', 'levelLength'].forEach(function (prop) {
    -  Object.defineProperty(winston, prop, {
    -    get: function () {
    -      return defaultLogger[prop];
    -    },
    -    set: function (val) {
    -      defaultLogger[prop] = val;
    -    }
    -  });
    -});

    @default {Object} -The default transports and exceptionHandlers for -the default winston logger.

    Object.defineProperty(winston, 'default', {
    -  get: function () {
    -    return {
    -      transports: defaultLogger.transports,
    -      exceptionHandlers: defaultLogger.exceptionHandlers
    -    };
    -  }
    -});
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/common.html b/node_modules/winston/docs/winston/common.html deleted file mode 100644 index 1ab139c..0000000 --- a/node_modules/winston/docs/winston/common.html +++ /dev/null @@ -1,140 +0,0 @@ - common.js

    common.js

    /*
    - * common.js: Internal helper and utility functions for winston
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var util = require('util'),
    -    crypto = require('crypto'),
    -    loggly = require('loggly'),
    -    config = require('./config');

    function setLevels (target, past, current)

    - -

    @target {Object} Object on which to set levels.

    - -

    @past {Object} Previous levels set on target.

    - -

    @current {Object} Current levels to set on target.

    - -

    Create functions on the target objects for each level -in current.levels. If past is defined, remove functions -for each of those levels.

    exports.setLevels = function (target, past, current, isDefault) {
    -  if (past) {
    -    Object.keys(past).forEach(function (level) {
    -      delete target[level];
    -    });
    -  }
    -
    -  target.levels = current || config.npm.levels;
    -  if (target.padLevels) {
    -    target.levelLength = exports.longestElement(Object.keys(target.levels));
    -  }
    -  

    Define prototype methods for each log level - e.g. target.log('info', msg) <=> target.info(msg)

      Object.keys(target.levels).forEach(function (level) {
    -    target[level] = function (msg) {
    -      var args     = Array.prototype.slice.call(arguments),
    -          callback = typeof args[args.length - 1] === 'function' ? args.pop() : null,
    -          meta     = args.length === 2 ? args.pop() : null;
    -
    -      return target.log(level, msg, meta, callback);
    -    };
    -  });
    -  
    -  return target;
    -};

    function longestElement

    - -

    @xs {Array} Array to calculate against

    - -

    Returns the longest element in the xs array.

    exports.longestElement = function (xs) {
    -  return Math.max.apply(
    -    null,
    -    xs.map(function (x) { return x.length })
    -  );
    -};

    function clone (obj)

    - -

    @obj {Object} Object to clone.

    - -

    Helper method for deep cloning pure JSON objects -i.e. JSON objects that are either literals or objects (no Arrays, etc)

    exports.clone = function (obj) {
    -  var copy = {};
    -  for (var i in obj) {
    -    if (Array.isArray(obj[i])) {
    -      copy[i] = obj[i].slice(0);
    -    }
    -    else {
    -      copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
    -    }
    -  }
    -
    -  return copy;
    -};

    function log (options)

    - -

    @options {Object} All information about the log serialization.

    - -

    Generic logging function for returning timestamped strings -with the following options:

    - -

    { - level: 'level to add to serialized message', - message: 'message to serialize', - meta: 'additional logging metadata to serialize', - colorize: false, // Colorizes output (only if .json is false) - timestamp: true // Adds a timestamp to the serialized message - }

    exports.log = function (options) {
    -  var timestampFn = typeof options.timestamp === 'function' ? options.timestamp : exports.timestamp,
    -      timestamp   = options.timestamp ? timestampFn() : null,
    -      meta        = options.meta ? exports.clone(options.meta) : null,
    -      output;
    -
    -  if (options.json) {
    -    output         = meta || {};
    -    output.level   = options.level;
    -    output.message = options.message;
    -    
    -    if (timestamp) {
    -      output.timestamp = timestamp;
    -    }
    -    
    -    return JSON.stringify(output);
    -  }
    -
    -  output = timestamp ? timestamp + ' - ' : '';
    -  output += options.colorize ? config.colorize(options.level) : options.level;
    -  output += (': ' + options.message);
    -
    -  if (meta && typeof meta === 'object' && Object.keys(meta).length > 0) {
    -    output += ' ' + loggly.serialize(meta);
    -  }
    -
    -  return output;
    -};

    function hash (str)

    - -

    @str {string} String to hash.

    - -

    Utility function for creating unique ids -e.g. Profiling incoming HTTP requests on the same tick

    exports.hash = function (str) {
    -  return crypto.createHash('sha1').update(str).digest('hex');
    -};

    Borrowed from node.js core

    - -

    I wanted a universal lowercase header message, as opposed to the DEBUG -(i.e. all uppercase header) used only in util.debug()

    var months = ['Jan', 'Feb', 'Mar', 'Apr', 
    -              'May', 'Jun', 'Jul', 'Aug', 
    -              'Sep', 'Oct', 'Nov', 'Dec'];

    function pad (n)

    - -

    Returns a padded string if n < 10.

    exports.pad = function (n) {
    -  return n < 10 ? '0' + n.toString(10) : n.toString(10);
    -};

    function timestamp ()

    - -

    Returns a timestamp string for the current time.

    exports.timestamp = function () {
    -  var d = new Date();
    -  var time = [
    -    exports.pad(d.getHours()),
    -    exports.pad(d.getMinutes()),
    -    exports.pad(d.getSeconds())
    -  ].join(':');
    -              
    -  return [d.getDate(), months[d.getMonth()], time].join(' ');
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/config.html b/node_modules/winston/docs/winston/config.html deleted file mode 100644 index c623d64..0000000 --- a/node_modules/winston/docs/winston/config.html +++ /dev/null @@ -1,37 +0,0 @@ - config.js

    config.js

    /*
    - * config.js: Default settings for all levels that winston knows about 
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var colors = require('colors');
    -
    -var config = exports, 
    -    allColors = exports.allColors = {};
    -
    -config.addColors = function (colors) {
    -  mixin(allColors, colors);
    -};
    -
    -config.colorize = function (level) {
    -  return level[allColors[level]];
    -};

    Export config sets

    config.cli    = require('./config/cli-config');
    -config.npm    = require('./config/npm-config');
    -config.syslog = require('./config/syslog-config');

    Add colors for pre-defined config sets

    config.addColors(config.npm.colors);
    -config.addColors(config.syslog.colors);
    -
    -function mixin (target) {
    -  var args = Array.prototype.slice.call(arguments, 1);
    -
    -  args.forEach(function (a) {
    -    var keys = Object.keys(a);
    -    for (var i = 0; i < keys.length; i++) {
    -      target[keys[i]] = a[keys[i]];
    -    }
    -  });
    -  return target;
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/config/cli-config.html b/node_modules/winston/docs/winston/config/cli-config.html deleted file mode 100644 index 075edd0..0000000 --- a/node_modules/winston/docs/winston/config/cli-config.html +++ /dev/null @@ -1,37 +0,0 @@ - cli-config.js

    cli-config.js

    /*
    - * cli-config.js: Config that conform to commonly used CLI logging levels. 
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    - 
    -var cliConfig = exports;
    -
    -cliConfig.levels = {
    -  silly: 0,
    -  input: 1,
    -  verbose: 2,
    -  prompt: 3,
    -  info: 4,
    -  data: 5,
    -  help: 6,
    -  warn: 7,
    -  debug: 8,
    -  error: 9
    -};
    -
    -cliConfig.colors = {
    -  silly: 'magenta',
    -  input: 'grey',
    -  verbose: 'cyan',
    -  prompt: 'grey',
    -  info: 'green',
    -  data: 'grey',
    -  help: 'cyan',
    -  warn: 'yellow',
    -  debug: 'blue',
    -  error: 'red'
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/config/npm-config.html b/node_modules/winston/docs/winston/config/npm-config.html deleted file mode 100644 index 8517430..0000000 --- a/node_modules/winston/docs/winston/config/npm-config.html +++ /dev/null @@ -1,29 +0,0 @@ - npm-config.js

    npm-config.js

    /*
    - * npm-config.js: Config that conform to npm logging levels. 
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    - 
    -var npmConfig = exports;
    -
    -npmConfig.levels = {
    -  silly: 0, 
    -  verbose: 1, 
    -  info: 2, 
    -  warn: 3,
    -  debug: 4, 
    -  error: 5
    -};
    -
    -npmConfig.colors = {
    -  silly: 'magenta',
    -  verbose: 'cyan',
    -  info: 'green',
    -  warn: 'yellow',
    -  debug: 'blue',
    -  error: 'red'
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/config/syslog-config.html b/node_modules/winston/docs/winston/config/syslog-config.html deleted file mode 100644 index 6da0993..0000000 --- a/node_modules/winston/docs/winston/config/syslog-config.html +++ /dev/null @@ -1,33 +0,0 @@ - syslog-config.js

    syslog-config.js

    /*
    - * syslog-config.js: Config that conform to syslog logging levels. 
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    - 
    -var syslogConfig = exports;
    -
    -syslogConfig.levels = {
    -  debug: 0, 
    -  info: 1, 
    -  notice: 2, 
    -  warning: 3,
    -  error: 4, 
    -  crit: 5,
    -  alert: 6,
    -  emerg: 7
    -};
    -
    -syslogConfig.colors = {
    -  debug: 'blue',
    -  info: 'green',
    -  notice: 'yellow',
    -  warning: 'red',
    -  error: 'red', 
    -  crit: 'red',
    -  alert: 'yellow',
    -  emerg: 'red'
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/exception.html b/node_modules/winston/docs/winston/exception.html deleted file mode 100644 index f6a4a6c..0000000 --- a/node_modules/winston/docs/winston/exception.html +++ /dev/null @@ -1,56 +0,0 @@ - exception.js

    exception.js

    /*
    - * exception.js: Utility methods for gathing information about uncaughtExceptions.
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    - 
    -var os = require('os'),
    -    stackTrace = require('stack-trace');
    -    
    -var exception = exports;
    -
    -exception.getAllInfo = function (err) {
    -  return {
    -    process: exception.getProcessInfo(),
    -    os:      exception.getOsInfo(),
    -    trace:   exception.getTrace(err)
    -  };
    -};
    -
    -exception.getProcessInfo = function () {
    -  return {
    -    pid:         process.pid,
    -    uid:         process.getuid(),
    -    gid:         process.getgid(),
    -    cwd:         process.cwd(),
    -    execPath:    process.execPath,
    -    version:     process.version,
    -    argv:        process.argv,
    -    memoryUsage: process.memoryUsage()
    -  };
    -};
    -
    -exception.getOsInfo = function () {
    -  return {
    -    loadavg: os.loadavg(),
    -    uptime:  os.uptime()
    -  };
    -};
    -
    -exception.getTrace = function (err) {
    -  var trace = err ? stackTrace.parse(err) : stackTrace.get();
    -  return trace.map(function (site) {
    -    return {
    -      column:   site.getColumnNumber(),
    -      file:     site.getFileName(),
    -      function: site.getFunctionName(),
    -      line:     site.getLineNumber(),
    -      method:   site.getMethodName(),
    -      native:   site.isNative(),
    -    }
    -  });
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/logger.html b/node_modules/winston/docs/winston/logger.html deleted file mode 100644 index de7038a..0000000 --- a/node_modules/winston/docs/winston/logger.html +++ /dev/null @@ -1,344 +0,0 @@ - logger.js

    logger.js

    /*
    - * logger.js: Core logger object used by winston.
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    - 
    -var events = require('events'),
    -    util = require('util'),
    -    async = require('async'),
    -    config = require('./config'),
    -    common = require('./common'),
    -    exception = require('./exception');
    -
    -function capitalize(str) {
    -  return str && str[0].toUpperCase() + str.slice(1);
    -}

    Time constants

    var ticksPerMillisecond = 10000;

    function Logger (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Logger object responsible -for persisting log messages and metadata to one or more transports.

    var Logger = exports.Logger = function (options) {
    -  events.EventEmitter.call(this);
    -  options = options || {};
    -  
    -  var self = this,
    -      handleExceptions = false;
    -  

    Set Levels and default logging level

      this.padLevels = options.padLevels || false;
    -  this.setLevels(options.levels);
    -  

    Setup other intelligent default settings.

      this.level             = options.level || 'info';
    -  this.emitErrs          = options.emitErrs || false;
    -  this.stripColors       = options.stripColors || false;
    -  this.transports        = {};
    -  this.exceptionHandlers = {};
    -  this.profilers         = {};
    -  this._names            = [];
    -  this._hnames           = [];
    -  
    -  if (options.transports) {
    -    options.transports.forEach(function (transport) {
    -      self.add(transport, null, true);
    -      
    -      if (transport.handleExceptions) {
    -        handleExceptions = true;
    -      }
    -    });
    -  }
    -  
    -  if (options.exceptionHandlers) {
    -    options.exceptionHandlers.forEach(function (handler) {
    -      self._hnames.push(handler.name);
    -      self.exceptionHandlers[handler.name] = handler;
    -    });
    -  }
    -  
    -  if (options.handleExceptions || handleExceptions) {
    -    this.handleExceptions();
    -  }
    -};

    Inherit from events.EventEmitter.

    util.inherits(Logger, events.EventEmitter);

    function extend (target)

    - -

    @target {Object} Target to extend.

    - -

    Extends the target object with a 'log' method -along with a method for each level in this instance.

    Logger.prototype.extend = function (target) {
    -  var self = this;
    -  ['log', 'profile'].concat(Object.keys(this.levels)).forEach(function (method) {
    -    target[method] = function () {
    -      return self[method].apply(self, arguments);
    -    };
    -  });
    -  
    -  return this;
    -};

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    Logger.prototype.log = function (level, msg) {
    -  var self = this, 
    -      callback,
    -      meta;
    -  
    -  if (arguments.length === 3) {
    -    if (typeof arguments[2] === 'function') {
    -      meta = {};
    -      callback = arguments[2];
    -    }
    -    else if (typeof arguments[2] === 'object') {
    -      meta = arguments[2];
    -    }
    -  }
    -  else if (arguments.length === 4) {
    -    meta = arguments[2];
    -    callback = arguments[3];
    -  }

    If we should pad for levels, do so

      if (this.padLevels) {
    -    msg = new Array(this.levelLength - level.length).join(' ') + msg;
    -  }
    -
    -  function onError (err) {
    -    if (callback) {
    -      callback(err);
    -    }
    -    else if (self.emitErrs) {
    -      self.emit('error', err);
    -    };
    -  }
    -  
    -  if (this.transports.length === 0) {
    -    return onError(new Error('Cannot log with no transports.'));
    -  }
    -  else if (typeof self.levels[level] === 'undefined') {
    -    return onError(new Error('Unknown log level: ' + level));
    -  }
    -  

    For consideration of terminal 'color" programs like colors.js, -which can add ANSI escape color codes to strings, we destyle the -ANSI color escape codes when this.stripColors is set.

    - -

    see: http://en.wikipedia.org/wiki/ANSIescapecode

      if (this.stripColors) {
    -    var code = /\u001b\[\d+m/g;
    -    msg = ('' + msg).replace(code, '');
    -  }
    -  
    -  for (var i = 0, l = this._names.length; i < l; i++) {
    -    var transport = this.transports[this._names[i]];
    -    if ((transport.level && self.levels[transport.level] <= self.levels[level])
    -      || (!transport.level && self.levels[self.level] <= self.levels[level])) {
    -      transport.log(level, msg, meta, function (err) {
    -        self.emit('logging', transport, level, msg, meta);
    -      });
    -    }
    -  }
    -  

    Immediately respond to the callback

      if (callback) {
    -    callback(null, level, msg, meta);    
    -  }
    -  
    -  return this;
    -};

    function handleExceptions ()

    - -

    Handles uncaughtException events for the current process

    Logger.prototype.handleExceptions = function () {
    -  var args = Array.prototype.slice.call(arguments),
    -      handlers = [],
    -      self = this;
    -      
    -  args.forEach(function (a) {
    -    if (Array.isArray(a)) {
    -      handlers = handlers.concat(a);
    -    }
    -    else {
    -      handlers.push(a);
    -    }
    -  });
    -  
    -  handlers.forEach(function (handler) {
    -    self.exceptionHandlers[handler.name] = handler;
    -  });
    -  
    -  this._hnames = Object.keys(self.exceptionHandlers);
    -    
    -  if (!this.catchExceptions) {
    -    this.catchExceptions = this._uncaughtException.bind(this);
    -    process.on('uncaughtException', this.catchExceptions);
    -  }
    -};

    function unhandleExceptions ()

    - -

    Removes any handlers to uncaughtException events -for the current process

    Logger.prototype.unhandleExceptions = function () {
    -  var self = this;
    -  
    -  if (this.catchExceptions) {
    -    Object.keys(this.exceptionHandlers).forEach(function (name) {
    -      if (handler.close) {
    -        handler.close();
    -      }
    -    });
    -    
    -    this.exceptionHandlers = {};
    -    Object.keys(this.transports).forEach(function (name) {
    -      var transport = self.transports[name];
    -      if (transport.handleExceptions) {
    -        transport.handleExceptions = false;
    -      }
    -    })
    -    
    -    process.removeListener('uncaughtException', this.catchExceptions);
    -    this.catchExceptions = false;    
    -  }
    -};

    function add (transport, [options])

    - -

    @transport {Transport} Prototype of the Transport object to add.

    - -

    @options {Object} Optional Options for the Transport to add.

    - -

    @instance {Boolean} Optional Value indicating if transport is already instantiated.

    - -

    Adds a transport of the specified type to this instance.

    Logger.prototype.add = function (transport, options, created) {
    -  var instance = created ? transport : (new (transport)(options));
    -  
    -  if (!instance.name && !instance.log) {
    -    throw new Error('Unknown transport with no log() method');
    -  }
    -  else if (this.transports[instance.name]) {
    -    throw new Error('Transport already attached: ' + instance.name);
    -  }
    -  
    -  this.transports[instance.name] = instance;
    -  this._names = Object.keys(this.transports);
    -  

    Listen for the error event on the new Transport

      instance._onError = this._onError.bind(this, instance)
    -  instance.on('error', instance._onError);
    -
    -  return this;
    -};

    function remove (transport)

    - -

    @transport {Transport} Transport to remove.

    - -

    Removes a transport of the specified type from this instance.

    Logger.prototype.remove = function (transport) {
    -  var name = transport.name || transport.prototype.name;
    -    
    -  if (!this.transports[name]) {
    -    throw new Error('Transport ' + name + ' not attached to this instance');
    -  }
    -  
    -  var instance = this.transports[name];
    -  delete this.transports[name];
    -  this._names = Object.keys(this.transports);
    -  
    -  if (instance.close) {
    -    instance.close();
    -  }
    -  
    -  instance.removeListener('error', instance._onError);
    -  return this;
    -};

    function profile (id, [msg, meta, callback])

    - -

    @id {string} Unique id of the profiler

    - -

    @msg {string} Optional Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Optional Continuation to respond to when complete.

    - -

    Tracks the time inbetween subsequent calls to this method -with the same id parameter. The second call to this method -will log the difference in milliseconds along with the message.

    Logger.prototype.profile = function (id) {
    -  var now = Date.now(), then, args,
    -      msg, meta, callback;
    -  
    -  if (this.profilers[id] && arguments.length !== 1) {
    -    then = this.profilers[id];
    -    delete this.profilers[id];
    -    

    Support variable arguments: msg, meta, callback

        args     = Array.prototype.slice.call(arguments);
    -    callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
    -    meta     = typeof args[args.length - 1] === 'object' ? args.pop() : {};
    -    msg      = args.length === 2 ? args[1] : id; 
    -    

    Set the duration property of the metadata

        meta.duration = now - then + 'ms'; 
    -    return this.info(msg, meta, callback);
    -  }
    -  else {
    -    this.profilers[id] = now;
    -  }
    -  
    -  return this;
    -};

    function setLevels (target)

    - -

    @target {Object} Target levels to use on this instance

    - -

    Sets the target levels specified on this instance.

    Logger.prototype.setLevels = function (target) {
    -  return common.setLevels(this, this.levels, target);
    -};

    function cli ()

    - -

    Configures this instance to have the default -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels.

    Logger.prototype.cli = function () {
    -  this.padLevels = true;
    -  this.setLevels(config.cli.levels);
    -  config.addColors(config.cli.colors);
    -  
    -  if (this.transports.console) {
    -    this.transports.console.colorize = true;
    -    this.transports.console.timestamp = false;
    -  }
    -  
    -  return this;
    -};

    @private function _uncaughtException (err)

    - -

    @err {Error} Error to handle

    - -

    Logs all relevant information around the err and -exits the current process.

    Logger.prototype._uncaughtException = function (err) {
    -  var self = this,
    -      responded = false,
    -      info = exception.getAllInfo(err),
    -      handlers = this._getExceptionHandlers(),
    -      timeout;
    -  
    -  function logAndWait (transport, next) {
    -    transport.logException('uncaughtException', info, next);
    -  }
    -  
    -  function gracefulExit () {
    -    if (!responded) {

    Remark: Currently ignoring any exceptions from transports - when catching uncaught exceptions.

          clearTimeout(timeout);
    -      responded = true;
    -      process.exit(1);
    -    }
    -  }
    -  
    -  if (!handlers || handlers.length === 0) {
    -    return gracefulExit();
    -  }
    -  

    Log to all transports and allow the operation to take -only up to 3000ms.

      async.forEach(handlers, logAndWait, gracefulExit);
    -  timeout = setTimeout(gracefulExit, 3000);
    -};

    @private function _getExceptionHandlers ()

    - -

    Returns the list of transports and exceptionHandlers -for this instance.

    Logger.prototype._getExceptionHandlers = function () {
    -  var self = this;
    -
    -  return this._hnames.map(function (name) {
    -    return self.exceptionHandlers[name];
    -  }).concat(this._names.map(function (name) {
    -    return self.transports[name].handleExceptions && self.transports[name];
    -  })).filter(Boolean);
    -};

    @private function _onError (transport, err)

    - -

    @transport {Object} Transport on which the error occured

    - -

    @err {Error} Error that occurred on the transport

    - -

    Bubbles the error, err, that occured on the specified transport -up from this instance if emitErrs has been set.

    Logger.prototype._onError = function (transport, err) {
    -  if (self.emitErrs) {
    -    self.emit('error', err, transport);
    -  }
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports.html b/node_modules/winston/docs/winston/transports.html deleted file mode 100644 index bc92fc8..0000000 --- a/node_modules/winston/docs/winston/transports.html +++ /dev/null @@ -1,29 +0,0 @@ - transports.js

    transports.js

    /*
    - * transports.js: Set of all transports Winston knows about
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var fs = require('fs'),
    -    path = require('path');
    -
    -var transports = exports;
    -
    -function capitalize (str) {
    -  return str && str[0].toUpperCase() + str.slice(1);
    -};

    Setup all transports as lazy-loaded getters.

    fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) {
    -  var transport = file.replace('.js', ''),
    -      name  = capitalize(transport);
    -  
    -  if (transport === 'transport') {
    -    return;
    -  }
    -  
    -  transports.__defineGetter__(name, function () {
    -    return require('./transports/' + transport)[name];
    -  });
    -});
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/console.html b/node_modules/winston/docs/winston/transports/console.html deleted file mode 100644 index 3d45f36..0000000 --- a/node_modules/winston/docs/winston/transports/console.html +++ /dev/null @@ -1,59 +0,0 @@ - console.js

    console.js

    /*
    - * console.js: Transport for outputting to the console
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var events = require('events'),
    -    util = require('util'),
    -    colors = require('colors'),
    -    common = require('../common'),
    -    Transport = require('./transport').Transport;

    function Console (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Console transport object responsible -for persisting log messages and metadata to a terminal or TTY.

    var Console = exports.Console = function (options) {
    -  Transport.call(this, options);
    -  options = options || {};
    -  
    -  this.name      = 'console';
    -  this.json      = options.json     || false;
    -  this.colorize  = options.colorize || false;
    -  this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;
    -};

    Inherit from winston.Transport.

    util.inherits(Console, Transport);

    Expose the name of this Transport on the prototype

    Console.prototype.name = 'console';

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    Console.prototype.log = function (level, msg, meta, callback) {
    -  if (this.silent) {
    -    return callback(null, true);
    -  }
    -    
    -  var self = this, output = common.log({
    -    level:     level,
    -    message:   msg,
    -    meta:      meta,
    -    colorize:  this.colorize, 
    -    timestamp: this.timestamp
    -  });
    -  
    -  if (level === 'error' || level === 'debug') {
    -    util.error(output);
    -  }
    -  else {
    -    util.puts(output);
    -  }

    Emit the logged event immediately because the event loop -will not exit until process.stdout has drained anyway.

      self.emit('logged');
    -  callback(null, true);
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/couchdb.html b/node_modules/winston/docs/winston/transports/couchdb.html deleted file mode 100644 index b7690de..0000000 --- a/node_modules/winston/docs/winston/transports/couchdb.html +++ /dev/null @@ -1,84 +0,0 @@ - couchdb.js

    couchdb.js

    /*
    - * Couchdb.js: Transport for logging to Couchdb
    - *
    - * (C) 2011 Max Ogden
    - * MIT LICENSE
    - *
    - */
    -
    -var events = require('events'),
    -    http = require('http'),
    -    util = require('util'),
    -    common = require('../common'),
    -    Transport = require('./transport').Transport; 

    function Couchdb (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received.

    var Couchdb = exports.Couchdb = function (options) {
    -  Transport.call(this, options);
    -
    -  this.name   = 'Couchdb'; 
    -  this.db     = options.db;
    -  this.user   = options.user;
    -  this.pass   = options.pass;
    -  this.host   = options.host   || 'localhost';
    -  this.port   = options.port   || 5984;
    -
    -  if (options.auth) {

    TODO: add http basic auth options for outgoing HTTP requests

      }
    -  
    -  if (options.ssl) {

    TODO: add ssl support for outgoing HTTP requests

      }  
    -};

    Inherit from winston.Transport.

    util.inherits(Couchdb, Transport);

    Expose the name of this Transport on the prototype

    Couchdb.prototype.name = 'Couchdb';

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    Couchdb.prototype.log = function (level, msg, meta, callback) {
    -  if (this.silent) {
    -    return callback(null, true);
    -  }
    -  
    -  var self = this,
    -      message = common.clone(meta),
    -      options,
    -      req;
    -      
    -  message.level = level;
    -  message.message = msg;

    Prepare options for outgoing HTTP request

      options = {
    -    host: this.host,
    -    port: this.port,
    -    path: "/" + this.db,
    -    method: "POST",
    -    headers: {"content-type": "application/json"}
    -  };
    -  
    -  if (options.user && options.pass) {
    -    options.headers["Authorization"] = "Basic " + new Buffer(options.user + ":" + options.pass).toString('base64');
    -  }
    -  

    Perform HTTP logging request

      req = http.request(options, function (res) { 

    No callback on request, fire and forget about the response

        self.emit('logged', res);
    -  }); 
    -
    -  req.on('error', function (err) {

    Propagate the error back up to the Logger that this -instance belongs to.

        self.emit('error', err);
    -  });
    -  

    Write logging event to the outgoing request body

      req.write(JSON.stringify({ 
    -    method: 'log', 
    -    params: { 
    -      timestamp: new Date(), // RFC3339/ISO8601 format instead of common.timestamp()
    -      msg: msg, 
    -      level: level, 
    -      meta: meta 
    -    } 
    -  }));
    -  
    -  req.end();
    -  

    Always return true, regardless of any errors

      callback(null, true);
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/file.html b/node_modules/winston/docs/winston/transports/file.html deleted file mode 100644 index bba8459..0000000 --- a/node_modules/winston/docs/winston/transports/file.html +++ /dev/null @@ -1,211 +0,0 @@ - file.js

    file.js

    /*
    - * file.js: Transport for outputting to a local log file
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var events = require('events'),
    -    fs = require('fs'),
    -    path = require('path'),
    -    util = require('util'),
    -    colors = require('colors'),
    -    common = require('../common'),
    -    Transport = require('./transport').Transport;
    -    

    function File (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the File transport object responsible -for persisting log messages and metadata to one or more files.

    var File = exports.File = function (options) {
    -  Transport.call(this, options);
    -  

    Helper function which throws an Error in the event -that any of the rest of the arguments is present in options.

      function throwIf (target /*, illegal... */) {
    -    Array.prototype.slice.call(arguments, 1).forEach(function (name) {
    -      if (options[name]) {
    -        throw new Error('Cannot set ' + name + ' and ' + target + 'together');
    -      }
    -    });
    -  }
    -  
    -  if (options.filename || options.dirname) {
    -    throwIf('filename or dirname', 'stream');
    -    this._basename = this.filename = path.basename(options.filename) || 'winston.log';
    -    this.dirname   = options.dirname || path.dirname(options.filename);
    -    this.options   = options.options || { flags: 'a' };    
    -  }
    -  else if (options.stream) {
    -    throwIf('stream', 'filename', 'maxsize');
    -    this.stream = options.stream;
    -  }
    -  else {
    -    throw new Error('Cannot log to file without filename or stream.');
    -  }
    -    
    -  this.json      = options.json !== false;
    -  this.colorize  = options.colorize  || false;
    -  this.maxsize   = options.maxsize   || null;
    -  this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;

    Internal state variables representing the number -of files this instance has created and the current -size (in bytes) of the current logfile.

      this._size    = 0;
    -  this._created = 0;
    -  this._buffer  = [];
    -};

    Inherit from winston.Transport.

    util.inherits(File, Transport);

    Expose the name of this Transport on the prototype

    File.prototype.name = 'file';

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    File.prototype.log = function (level, msg, meta, callback) {
    -  if (this.silent) {
    -    return callback(null, true);
    -  }
    -
    -  var self = this, output = common.log({
    -    level:     level,
    -    message:   msg,
    -    meta:      meta,
    -    json:      this.json,
    -    colorize:  this.colorize,
    -    timestamp: this.timestamp
    -  }) + '\n';
    -  
    -  this._size += output.length;
    -  
    -  function onDrain () {
    -    self.emit('logged');
    -  }
    -  
    -  if (!this.filename) {

    If there is no filename on this instance then it was configured -with a raw WriteableStream instance and we should not perform any -size restrictions.

        this.stream.write(output);
    -    this.stream.once('drain', onDrain);
    -  }
    -  else {
    -    this.open(function (err) {
    -      if (err) {

    If there was an error enqueue the message

            return self._buffer.push(output);
    -      }
    -      
    -      self.stream.write(output);
    -      self.stream.once('drain', onDrain);
    -    });
    -  }
    -
    -  callback(null, true);
    -};

    function open (callback)

    - -

    @callback {function} Continuation to respond to when complete

    - -

    Checks to see if a new file needs to be created based on the maxsize -(if any) and the current size of the file used.

    File.prototype.open = function (callback) {
    -  if (this.opening) {

    If we are already attempting to open the next -available file then respond with a value indicating -that the message should be buffered.

        return callback(true);
    -  }
    -  else if (!this.stream || (this.maxsize && this._size >= this.maxsize)) {

    If we dont have a stream or have exceeded our size, then create -the next stream and respond with a value indicating that -the message should be buffered.

        callback(true);
    -    return this._createStream();
    -  }
    -  

    Otherwise we have a valid (and ready) stream.

      callback();
    -};

    function close ()

    - -

    Closes the stream associated with this instance.

    File.prototype.close = function() {
    -  var self = this;
    -
    -  if (this.stream) {
    -    this.stream.end();
    -    this.stream.destroySoon();
    -    
    -    this.stream.once('drain', function () {
    -      self.emit('flush');
    -      self.emit('closed');
    -    });
    -  }
    -};

    function flush ()

    - -

    Flushes any buffered messages to the current stream -used by this instance.

    File.prototype.flush = function () {
    -  var self = this;

    Iterate over the _buffer of enqueued messaged -and then write them to the newly created stream.

      this._buffer.forEach(function (str) {
    -    process.nextTick(function () {
    -      self.stream.write(str);
    -      self._size += str.length;
    -    });
    -  });
    -  

    Quickly truncate the _buffer once the write operations -have been started

      self._buffer.length = 0;
    -  

    When the stream has drained we have flushed -our buffer.

      self.stream.once('drain', function () {
    -    self.emit('flush');
    -    self.emit('logged');
    -  });
    -};

    @private function _createStream ()

    - -

    Attempts to open the next appropriate file for this instance -based on the common state (such as maxsize and _basename).

    File.prototype._createStream = function () {
    -  var self = this;
    -  this.opening = true;
    -    
    -  (function checkFile (target) {
    -    var fullname = path.join(self.dirname, target);
    -    

    Creates the WriteStream and then flushes any -buffered messages.

        function createAndFlush (size) {
    -      if (self.stream) {
    -        self.stream.end();
    -        self.stream.destroySoon();
    -      }
    -      
    -      self._size = size;
    -      self.filename = target;
    -      self.stream = fs.createWriteStream(fullname, self.options);
    -      

    When the current stream has finished flushing -then we can be sure we have finished opening -and thus can emit the open event.

          self.once('flush', function () {
    -        self.opening = false;
    -        self.emit('open', fullname);
    -      });

    Remark: It is possible that in the time it has taken to find the -next logfile to be written more data than maxsize has been buffered, -but for sensible limits (10s - 100s of MB) this seems unlikely in less -than one second.

          self.flush();
    -    }
    -
    -    fs.stat(fullname, function (err, stats) {
    -      if (err) {
    -        if (err.code !== 'ENOENT') {
    -          return self.emit('error', err);
    -        }
    -        
    -        return createAndFlush(0);
    -      }
    -      
    -      if (!stats || (self.maxsize && stats.size >= self.maxsize)) {

    If stats.size is greater than the maxsize for -this instance then try again

            return checkFile(self._getFile(true));
    -      }
    -      
    -      createAndFlush(stats.size);
    -    });
    -  })(this._getFile());  
    -};

    @private function _getFile ()

    - -

    Gets the next filename to use for this instance -in the case that log filesizes are being capped.

    File.prototype._getFile = function (inc) {
    -  var self = this,
    -      ext = path.extname(this._basename),
    -      basename = path.basename(this._basename, ext);
    -  
    -  if (inc) {

    Increment the number of files created or -checked by this instance.

        this._created += 1;
    -  }
    -  
    -  return this._created 
    -    ? basename + this._created + ext
    -    : basename + ext;
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/loggly.html b/node_modules/winston/docs/winston/transports/loggly.html deleted file mode 100644 index 7652318..0000000 --- a/node_modules/winston/docs/winston/transports/loggly.html +++ /dev/null @@ -1,118 +0,0 @@ - loggly.js

    loggly.js

    /*
    - * loggly.js: Transport for logginh to remote Loggly API
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var events = require('events'),
    -    loggly = require('loggly'),
    -    util = require('util'),
    -    async = require('async'),
    -    common = require('../common'),
    -    Transport = require('./transport').Transport; 

    function Loggly (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Loggly transport object responsible -for persisting log messages and metadata to Loggly; 'LaaS'.

    var Loggly = exports.Loggly = function (options) {
    -  Transport.call(this, options);
    -
    -  if (!options.subdomain) {
    -    throw new Error('Loggly Subdomain is required');
    -  }
    -  
    -  if (!options.inputToken && !options.inputName) {
    -    throw new Error('Target input token or name is required.');
    -  }
    -  
    -  if (!options.auth && options.inputName) {
    -    throw new Error('Loggly authentication is required');
    -  }
    -  
    -  this.name = 'loggly'; 
    -  this.logBuffer = [];
    -  
    -  this.client = loggly.createClient({
    -    subdomain: options.subdomain,
    -    auth: options.auth || null,
    -    json: options.json || false
    -  });
    -  
    -  if (options.inputToken) {
    -    this.inputToken = options.inputToken;
    -    this.ready = true;
    -  }
    -  else if (options.inputName) {
    -    this.ready = false;
    -    this.inputName = options.inputName;
    -    
    -    var self = this;
    -    this.client.getInput(this.inputName, function (err, input) {
    -      if (err) {
    -        throw err;
    -      }
    -      
    -      self.inputToken = input.input_token;
    -      self.ready = true;
    -    });
    -  }
    -};

    Inherit from winston.Transport.

    util.inherits(Loggly, Transport);

    Expose the name of this Transport on the prototype

    Loggly.prototype.name = 'loggly';

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    Loggly.prototype.log = function (level, msg, meta, callback) {
    -  if (this.silent) {
    -    return callback(null, true);
    -  }
    -
    -  var self = this,
    -      message = common.clone(meta);
    -      
    -  message.level = level;
    -  message.message = msg;
    -  
    -  if (!this.ready) {

    If we haven't gotten the input token yet -add this message to the log buffer.

        this.logBuffer.push(message);
    -  }
    -  else if (this.ready && this.logBuffer.length > 0) {

    Otherwise if we have buffered messages -add this message to the buffer and flush them.

        this.logBuffer.push(message);
    -    this.flush();
    -  }
    -  else {

    Otherwise just log the message as normal

        this.client.log(this.inputToken, message, function () {
    -      self.emit('logged');
    -    });
    -  }
    -  
    -  callback(null, true);
    -};

    function flush ()

    - -

    Flushes any buffered messages to the current stream -used by this instance.

    Loggly.prototype.flush = function () {
    -  var self = this;
    -  
    -  function logMsg (msg, next) {
    -    self.client.log(self.inputToken, msg, function (err) {
    -      if (err) {
    -        self.emit('error', err);
    -      }
    -      
    -      next();
    -    });
    -  }
    -  

    Initiate calls to loggly for each message in the buffer

      async.forEach(this.logBuffer, logMsg, function () {
    -    self.emit('logged');
    -  });
    -  
    -  process.nextTick(function () {

    Then quickly truncate the list

        self.logBuffer.length = 0;
    -  });
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/transport.html b/node_modules/winston/docs/winston/transports/transport.html deleted file mode 100644 index f0cc4b9..0000000 --- a/node_modules/winston/docs/winston/transports/transport.html +++ /dev/null @@ -1,50 +0,0 @@ - transport.js

    transport.js

    /*
    - * transport.js: Base Transport object for all Winston transports.
    - *
    - * (C) 2010 Charlie Robbins
    - * MIT LICENCE
    - *
    - */
    -
    -var events = require('events'),
    -    util = require('util'); 

    function Transport (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Tranport object responsible -base functionality for all winston transports.

    var Transport = exports.Transport = function (options) {
    -  events.EventEmitter.call(this);
    -  
    -  options               = options        || {};  
    -  this.level            = options.level  || 'info';
    -  this.silent           = options.silent || false;
    -  this.handleExceptions = options.handleExceptions || false;
    -};

    Inherit from events.EventEmitter.

    util.inherits(Transport, events.EventEmitter);

    function logException (msg, meta, callback)

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Logs the specified msg, meta and responds to the callback once the log -operation is complete to ensure that the event loop will not exit before -all logging has completed.

    Transport.prototype.logException = function (msg, meta, callback) {
    -  var self = this;
    -  
    -  function onLogged () {
    -    self.removeListener('error', onError);
    -    callback();
    -  }
    -  
    -  function onError () {
    -    self.removeListener('logged', onLogged);
    -    callback();
    -  }
    -  
    -  this.once('logged', onLogged);
    -  this.once('error', onError);  
    -  this.log('error', msg, meta, function () { });
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/docs/winston/transports/webhook.html b/node_modules/winston/docs/winston/transports/webhook.html deleted file mode 100644 index 7191495..0000000 --- a/node_modules/winston/docs/winston/transports/webhook.html +++ /dev/null @@ -1,82 +0,0 @@ - webhook.js

    webhook.js

    /*
    - * webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks )
    - *
    - * (C) 2011 Marak Squires
    - * MIT LICENCE
    - *
    - */
    -
    -var events = require('events'),
    -    http = require('http'),
    -    util = require('util'),
    -    common = require('../common'),
    -    Transport = require('./transport').Transport; 

    function WebHook (options)

    - -

    @options {Object} Options for this instance.

    - -

    Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received.

    var Webhook = exports.Webhook = function (options) {
    -  Transport.call(this, options);
    -
    -  this.name   = 'webhook'; 
    -  this.host   = options.host   || 'localhost';
    -  this.port   = options.port   || 8080;
    -  this.method = options.method || 'POST';
    -  this.path   = options.path   || '/winston-log';
    -
    -  if (options.auth) {

    TODO: add http basic auth options for outgoing HTTP requests

      }
    -  
    -  if (options.ssl) {

    TODO: add ssl support for outgoing HTTP requests

      }  
    -};

    Inherit from winston.Transport.

    util.inherits(Webhook, Transport);

    Expose the name of this Transport on the prototype

    Webhook.prototype.name = 'webhook';

    function log (level, msg, [meta], callback)

    - -

    @level {string} Level at which to log the message.

    - -

    @msg {string} Message to log

    - -

    @meta {Object} Optional Additional metadata to attach

    - -

    @callback {function} Continuation to respond to when complete.

    - -

    Core logging method exposed to Winston. Metadata is optional.

    Webhook.prototype.log = function (level, msg, meta, callback) {
    -  if (this.silent) {
    -    return callback(null, true);
    -  }
    -  
    -  var self = this,
    -      message = common.clone(meta),
    -      options,
    -      req;
    -      
    -  message.level = level;
    -  message.message = msg;

    Prepare options for outgoing HTTP request

      options = {
    -    host: this.host,
    -    port: this.port,
    -    path: this.path,
    -    method: this.method
    -  };
    -  

    Perform HTTP logging request

      req = http.request(options, function (res) { 

    No callback on request, fire and forget about the response

        self.emit('logged');
    -  }); 
    -
    -  req.on('error', function (err) {

    Propagate the error back up to the Logger that this -instance belongs to.

        self.emit('error', err);
    -  });
    -  

    Write logging event to the outgoing request body

    - -

    jsonMessage is currently conforming to JSON-RPC v1.0, -but without the unique id since there is no anticipated response -see: http://en.wikipedia.org/wiki/JSON-RPC

      req.write(JSON.stringify({ 
    -    method: 'log', 
    -    params: { 
    -      timestamp: common.timestamp(), 
    -      msg: msg, 
    -      level: level, 
    -      meta: meta 
    -    } 
    -  }));
    -  
    -  req.end();
    -  

    Always return true, regardless of any errors

      callback(null, true);
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/examples/couchdb.js b/node_modules/winston/examples/couchdb.js deleted file mode 100644 index ce2d960..0000000 --- a/node_modules/winston/examples/couchdb.js +++ /dev/null @@ -1,18 +0,0 @@ -var winston = require('../lib/winston'); - -// -// Create a new winston logger instance with two tranports: Console, and Couchdb -// -// -// The Console transport will simply output to the console screen -// The Couchdb tranport will perform an HTTP POST request to the specified CouchDB instance -// -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.Couchdb)({ 'host': 'localhost', 'db': 'logs' }) - // if you need auth do this: new (winston.transports.Couchdb)({ 'user': 'admin', 'pass': 'admin', 'host': 'localhost', 'db': 'logs' }) - ] -}); - -logger.log('info', 'Hello webhook log files!', { 'foo': 'bar' }); diff --git a/node_modules/winston/examples/webhook-post.js b/node_modules/winston/examples/webhook-post.js deleted file mode 100644 index 0fa1c8d..0000000 --- a/node_modules/winston/examples/webhook-post.js +++ /dev/null @@ -1,17 +0,0 @@ -var winston = require('../lib/winston'); - -// -// Create a new winston logger instance with two tranports: Console, and Webhook -// -// -// The Console transport will simply output to the console screen -// The Webhook tranports will perform an HTTP POST request to an abritrary end-point ( for post/recieve webhooks ) -// -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.Webhook)({ 'host': 'localhost', 'port': 8080, 'path': '/collectdata' }) - ] -}); - -logger.log('info', 'Hello webhook log files!', { 'foo': 'bar' }); diff --git a/node_modules/winston/lib/winston.js b/node_modules/winston/lib/winston.js deleted file mode 100644 index 51bfb45..0000000 --- a/node_modules/winston/lib/winston.js +++ /dev/null @@ -1,143 +0,0 @@ -/* - * winston.js: Top-level include defining Winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var winston = exports; - -// -// Expose version using `pkginfo` -// -require('pkginfo')(module, 'version'); - -// -// Include transports defined by default by winston -// -winston.transports = require('./winston/transports'); - -// -// Expose utility methods -// -var common = require('./winston/common'); -winston.hash = common.hash; -winston.clone = common.clone; -winston.longestElement = common.longestElement; -winston.exception = require('./winston/exception'); -winston.config = require('./winston/config'); -winston.addColors = winston.config.addColors; - -// -// Expose core Logging-related prototypes. -// -winston.Container = require('./winston/container').Container; -winston.Logger = require('./winston/logger').Logger; -winston.Transport = require('./winston/transports/transport').Transport; - -// -// We create and expose a default `Container` to `winston.loggers` so that the -// programmer may manage multiple `winston.Logger` instances without any additional overhead. -// -// ### some-file1.js -// -// var logger = require('winston').loggers.get('something'); -// -// ### some-file2.js -// -// var logger = require('winston').loggers.get('something'); -// -winston.loggers = new winston.Container(); - -// -// We create and expose a 'defaultLogger' so that the programmer may do the -// following without the need to create an instance of winston.Logger directly: -// -// var winston = require('winston'); -// winston.log('info', 'some message'); -// winston.error('some error'); -// -var defaultLogger = new winston.Logger({ - transports: [new winston.transports.Console()] -}); - -// -// Pass through the target methods onto `winston. -// -var methods = [ - 'log', - 'add', - 'remove', - 'profile', - 'startTimer', - 'extend', - 'cli', - 'handleExceptions', - 'unhandleExceptions' -]; -common.setLevels(winston, null, defaultLogger.levels); -methods.forEach(function (method) { - winston[method] = function () { - return defaultLogger[method].apply(defaultLogger, arguments); - }; -}); - -// -// ### function cli () -// Configures the default winston logger to have the -// settings for command-line interfaces: no timestamp, -// colors enabled, padded output, and additional levels. -// -winston.cli = function () { - winston.padLevels = true; - common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels); - defaultLogger.setLevels(winston.config.cli.levels); - winston.config.addColors(winston.config.cli.colors); - - if (defaultLogger.transports.console) { - defaultLogger.transports.console.colorize = true; - defaultLogger.transports.console.timestamp = false; - } - - return winston; -}; - -// -// ### function setLevels (target) -// #### @target {Object} Target levels to use -// Sets the `target` levels specified on the default winston logger. -// -winston.setLevels = function (target) { - common.setLevels(winston, defaultLogger.levels, target); - defaultLogger.setLevels(target); -}; - -// -// Define getters / setters for appropriate properties of the -// default logger which need to be exposed by winston. -// -['emitErrs', 'exitOnError', 'padLevels', 'level', 'levelLength', 'stripColors'].forEach(function (prop) { - Object.defineProperty(winston, prop, { - get: function () { - return defaultLogger[prop]; - }, - set: function (val) { - defaultLogger[prop] = val; - } - }); -}); - -// -// @default {Object} -// The default transports and exceptionHandlers for -// the default winston logger. -// -Object.defineProperty(winston, 'default', { - get: function () { - return { - transports: defaultLogger.transports, - exceptionHandlers: defaultLogger.exceptionHandlers - }; - } -}); diff --git a/node_modules/winston/lib/winston/common.js b/node_modules/winston/lib/winston/common.js deleted file mode 100644 index ba65e0f..0000000 --- a/node_modules/winston/lib/winston/common.js +++ /dev/null @@ -1,239 +0,0 @@ -/* - * common.js: Internal helper and utility functions for winston - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var util = require('util'), - crypto = require('crypto'), - config = require('./config'); - -// -// ### function setLevels (target, past, current) -// #### @target {Object} Object on which to set levels. -// #### @past {Object} Previous levels set on target. -// #### @current {Object} Current levels to set on target. -// Create functions on the target objects for each level -// in current.levels. If past is defined, remove functions -// for each of those levels. -// -exports.setLevels = function (target, past, current, isDefault) { - if (past) { - Object.keys(past).forEach(function (level) { - delete target[level]; - }); - } - - target.levels = current || config.npm.levels; - if (target.padLevels) { - target.levelLength = exports.longestElement(Object.keys(target.levels)); - } - - // - // Define prototype methods for each log level - // e.g. target.log('info', msg) <=> target.info(msg) - // - Object.keys(target.levels).forEach(function (level) { - target[level] = function (msg) { - var args = Array.prototype.slice.call(arguments), - callback = typeof args[args.length - 1] === 'function' || !args[args.length - 1] ? args.pop() : null, - meta = args.length === 2 ? args.pop() : null; - - return target.log(level, msg, meta, callback); - }; - }); - - return target; -}; - -// -// ### function longestElement -// #### @xs {Array} Array to calculate against -// Returns the longest element in the `xs` array. -// -exports.longestElement = function (xs) { - return Math.max.apply( - null, - xs.map(function (x) { return x.length }) - ); -}; - -// -// ### function clone (obj) -// #### @obj {Object} Object to clone. -// Helper method for deep cloning pure JSON objects -// i.e. JSON objects that are either literals or objects (no Arrays, etc) -// -exports.clone = function (obj) { - // we only need to clone refrence types (Object) - if (!(obj instanceof Object)) { - return obj; - } - else if (obj instanceof Date) { - return obj; - } - - var copy = {}; - for (var i in obj) { - if (Array.isArray(obj[i])) { - copy[i] = obj[i].slice(0); - } - else { - copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i]; - } - } - - return copy; -}; - -// -// ### function log (options) -// #### @options {Object} All information about the log serialization. -// Generic logging function for returning timestamped strings -// with the following options: -// -// { -// level: 'level to add to serialized message', -// message: 'message to serialize', -// meta: 'additional logging metadata to serialize', -// colorize: false, // Colorizes output (only if `.json` is false) -// timestamp: true // Adds a timestamp to the serialized message -// } -// -exports.log = function (options) { - var timestampFn = typeof options.timestamp === 'function' ? options.timestamp : exports.timestamp, - timestamp = options.timestamp ? timestampFn() : null, - meta = options.meta ? exports.clone(options.meta) : null, - output; - - if (options.json) { - output = meta || {}; - output.level = options.level; - output.message = options.message; - - if (timestamp) { - output.timestamp = timestamp; - } - - return typeof options.stringify === 'function' - ? options.stringify(output) - : JSON.stringify(output); - } - - output = timestamp ? timestamp + ' - ' : ''; - output += options.colorize ? config.colorize(options.level) : options.level; - output += (': ' + options.message); - - if (meta) { - if (typeof meta !== 'object') { - output += ' ' + meta; - } - else if (Object.keys(meta).length > 0) { - output += ' ' + exports.serialize(meta); - } - } - - return output; -}; - -exports.capitalize = function (str) { - return str && str[0].toUpperCase() + str.slice(1); -}; - -// -// ### function hash (str) -// #### @str {string} String to hash. -// Utility function for creating unique ids -// e.g. Profiling incoming HTTP requests on the same tick -// -exports.hash = function (str) { - return crypto.createHash('sha1').update(str).digest('hex'); -}; - -// -// ## Borrowed from node.js core -// I wanted a universal lowercase header message, as opposed to the `DEBUG` -// (i.e. all uppercase header) used only in `util.debug()` -// -var months = ['Jan', 'Feb', 'Mar', 'Apr', - 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec']; - -// -// ### function pad (n) -// Returns a padded string if `n < 10`. -// -exports.pad = function (n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -}; - -// -// ### function timestamp () -// Returns a timestamp string for the current time. -// -exports.timestamp = function () { - var d = new Date(); - var time = [ - exports.pad(d.getHours()), - exports.pad(d.getMinutes()), - exports.pad(d.getSeconds()) - ].join(':'); - - return [d.getDate(), months[d.getMonth()], time].join(' '); -}; - -// -// ### function serialize (obj, key) -// #### @obj {Object|literal} Object to serialize -// #### @key {string} **Optional** Optional key represented by obj in a larger object -// Performs simple comma-separated, `key=value` serialization for Loggly when -// logging to non-JSON inputs. -// -exports.serialize = function (obj, key) { - if (obj === null) { - obj = 'null'; - } - else if (obj === undefined) { - obj = 'undefined'; - } - else if (obj === false) { - obj = 'false'; - } - - if (typeof obj !== 'object') { - return key ? key + '=' + obj : obj; - } - - var msg = '', - keys = Object.keys(obj), - length = keys.length; - - for (var i = 0; i < length; i++) { - if (Array.isArray(obj[keys[i]])) { - msg += keys[i] + '=[' - - for (var j = 0, l = obj[keys[i]].length; j < l; j++) { - msg += exports.serialize(obj[keys[i]][j]); - if (j < l - 1) { - msg += ', '; - } - } - - msg += ']'; - } - else if (obj[keys[i]] instanceof Date) { - msg += keys[i] + '=' + obj[keys[i]]; - } - else { - msg += exports.serialize(obj[keys[i]], keys[i]); - } - - if (i < length - 1) { - msg += ', '; - } - } - - return msg; -}; diff --git a/node_modules/winston/lib/winston/config.js b/node_modules/winston/lib/winston/config.js deleted file mode 100644 index 45e9283..0000000 --- a/node_modules/winston/lib/winston/config.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * config.js: Default settings for all levels that winston knows about - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var colors = require('colors'); - -var config = exports, - allColors = exports.allColors = {}; - -config.addColors = function (colors) { - mixin(allColors, colors); -}; - -config.colorize = function (level) { - return level[allColors[level]]; -}; - -// -// Export config sets -// -config.cli = require('./config/cli-config'); -config.npm = require('./config/npm-config'); -config.syslog = require('./config/syslog-config'); - -// -// Add colors for pre-defined config sets -// -config.addColors(config.npm.colors); -config.addColors(config.syslog.colors); - -function mixin (target) { - var args = Array.prototype.slice.call(arguments, 1); - - args.forEach(function (a) { - var keys = Object.keys(a); - for (var i = 0; i < keys.length; i++) { - target[keys[i]] = a[keys[i]]; - } - }); - return target; -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/config/cli-config.js b/node_modules/winston/lib/winston/config/cli-config.js deleted file mode 100644 index 9798ddc..0000000 --- a/node_modules/winston/lib/winston/config/cli-config.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cli-config.js: Config that conform to commonly used CLI logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var cliConfig = exports; - -cliConfig.levels = { - silly: 0, - input: 1, - verbose: 2, - prompt: 3, - info: 4, - data: 5, - help: 6, - warn: 7, - debug: 8, - error: 9 -}; - -cliConfig.colors = { - silly: 'magenta', - input: 'grey', - verbose: 'cyan', - prompt: 'grey', - info: 'green', - data: 'grey', - help: 'cyan', - warn: 'yellow', - debug: 'blue', - error: 'red' -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/config/npm-config.js b/node_modules/winston/lib/winston/config/npm-config.js deleted file mode 100644 index 464f735..0000000 --- a/node_modules/winston/lib/winston/config/npm-config.js +++ /dev/null @@ -1,27 +0,0 @@ -/* - * npm-config.js: Config that conform to npm logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var npmConfig = exports; - -npmConfig.levels = { - silly: 0, - verbose: 1, - info: 2, - warn: 3, - debug: 4, - error: 5 -}; - -npmConfig.colors = { - silly: 'magenta', - verbose: 'cyan', - info: 'green', - warn: 'yellow', - debug: 'blue', - error: 'red' -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/config/syslog-config.js b/node_modules/winston/lib/winston/config/syslog-config.js deleted file mode 100644 index a198abc..0000000 --- a/node_modules/winston/lib/winston/config/syslog-config.js +++ /dev/null @@ -1,31 +0,0 @@ -/* - * syslog-config.js: Config that conform to syslog logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var syslogConfig = exports; - -syslogConfig.levels = { - debug: 0, - info: 1, - notice: 2, - warning: 3, - error: 4, - crit: 5, - alert: 6, - emerg: 7 -}; - -syslogConfig.colors = { - debug: 'blue', - info: 'green', - notice: 'yellow', - warning: 'red', - error: 'red', - crit: 'red', - alert: 'yellow', - emerg: 'red' -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/container.js b/node_modules/winston/lib/winston/container.js deleted file mode 100644 index 0e67b20..0000000 --- a/node_modules/winston/lib/winston/container.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * container.js: Inversion of control container for winston logger instances - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var common = require('./common'), - winston = require('../winston'); - -// -// ### function Container (options) -// #### @options {Object} Default pass-thru options for Loggers -// Constructor function for the Container object responsible for managing -// a set of `winston.Logger` instances based on string ids. -// -var Container = exports.Container = function (options) { - this.loggers = {}; - this.options = options || {}; - this.default = { - transports: [ - new winston.transports.Console({ - level: 'silly', - colorize: false - }) - ] - } -}; - -// -// ### function get / add (id, options) -// #### @id {string} Id of the Logger to get -// #### @options {Object} **Optional** Options for the Logger instance -// Retreives a `winston.Logger` instance for the specified `id`. If -// an instance does not exist, one is created. -// -Container.prototype.get = Container.prototype.add = function (id, options) { - if (!this.loggers[id]) { - options = common.clone(options || this.options || this.default); - options.transports = options.transports || []; - - if (options.transports.length === 0 && (!options || !options['console'])) { - options.transports.push(this.default.transports[0]); - } - - Object.keys(options).forEach(function (key) { - if (key === 'transports') { - return; - } - - var name = common.capitalize(key); - - if (!winston.transports[name]) { - throw new Error('Cannot add unknown transport: ' + name); - } - - var namedOptions = options[key]; - namedOptions.id = id; - options.transports.push(new (winston.transports[name])(namedOptions)); - }); - - this.loggers[id] = new winston.Logger(options); - } - - return this.loggers[id]; -}; - -// -// ### function close (id) -// #### @id {string} **Optional** Id of the Logger instance to find -// Returns a boolean value indicating if this instance -// has a logger with the specified `id`. -// -Container.prototype.has = function (id) { - return !!this.loggers[id]; -}; - -// -// ### function close (id) -// #### @id {string} **Optional** Id of the Logger instance to close -// Closes a `Logger` instance with the specified `id` if it exists. -// If no `id` is supplied then all Loggers are closed. -// -Container.prototype.close = function (id) { - var self = this; - - function _close (id) { - if (!self.loggers[id]) { - return; - } - - self.loggers[id].close(); - delete self.loggers[id]; - } - - return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) { - _close(id); - }); -}; - diff --git a/node_modules/winston/lib/winston/exception.js b/node_modules/winston/lib/winston/exception.js deleted file mode 100644 index 2a01e91..0000000 --- a/node_modules/winston/lib/winston/exception.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - * exception.js: Utility methods for gathing information about uncaughtExceptions. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var os = require('os'), - stackTrace = require('stack-trace'); - -var exception = exports; - -exception.getAllInfo = function (err) { - return { - process: exception.getProcessInfo(), - os: exception.getOsInfo(), - trace: exception.getTrace(err), - stack: err.stack.split('\n') - }; -}; - -exception.getProcessInfo = function () { - return { - pid: process.pid, - uid: process.getuid(), - gid: process.getgid(), - cwd: process.cwd(), - execPath: process.execPath, - version: process.version, - argv: process.argv, - memoryUsage: process.memoryUsage() - }; -}; - -exception.getOsInfo = function () { - return { - loadavg: os.loadavg(), - uptime: os.uptime() - }; -}; - -exception.getTrace = function (err) { - var trace = err ? stackTrace.parse(err) : stackTrace.get(); - return trace.map(function (site) { - return { - column: site.getColumnNumber(), - file: site.getFileName(), - function: site.getFunctionName(), - line: site.getLineNumber(), - method: site.getMethodName(), - native: site.isNative(), - } - }); -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/logger.js b/node_modules/winston/lib/winston/logger.js deleted file mode 100644 index 5ca51e0..0000000 --- a/node_modules/winston/lib/winston/logger.js +++ /dev/null @@ -1,515 +0,0 @@ -/* - * logger.js: Core logger object used by winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'), - async = require('async'), - config = require('./config'), - common = require('./common'), - exception = require('./exception'); - -// -// Time constants -// -var ticksPerMillisecond = 10000; - -// -// ### function Logger (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Logger object responsible -// for persisting log messages and metadata to one or more transports. -// -var Logger = exports.Logger = function (options) { - events.EventEmitter.call(this); - options = options || {}; - - var self = this, - handleExceptions = false; - - // - // Set Levels and default logging level - // - this.padLevels = options.padLevels || false; - this.setLevels(options.levels); - if (options.colors) { - config.addColors(options.colors); - } - - // - // Hoist other options onto this instance. - // - this.level = options.level || 'info'; - this.emitErrs = options.emitErrs || false; - this.stripColors = options.stripColors || false; - this.exitOnError = typeof options.exitOnError !== 'undefined' - ? options.exitOnError - : true; - - // - // Setup other intelligent default settings. - // - this.transports = {}; - this.rewriters = []; - this.exceptionHandlers = {}; - this.profilers = {}; - this._names = []; - this._hnames = []; - - if (options.transports) { - options.transports.forEach(function (transport) { - self.add(transport, null, true); - - if (transport.handleExceptions) { - handleExceptions = true; - } - }); - } - - if (options.rewriters) { - options.rewriters.forEach(function(rewriter) { - self.addRewriter(rewriter); - }); - } - - if (options.exceptionHandlers) { - handleExceptions = true; - options.exceptionHandlers.forEach(function (handler) { - self._hnames.push(handler.name); - self.exceptionHandlers[handler.name] = handler; - }); - } - - if (options.handleExceptions || handleExceptions) { - this.handleExceptions(); - } -}; - -// -// Inherit from `events.EventEmitter`. -// -util.inherits(Logger, events.EventEmitter); - -// -// ### function extend (target) -// #### @target {Object} Target to extend. -// Extends the target object with a 'log' method -// along with a method for each level in this instance. -// -Logger.prototype.extend = function (target) { - var self = this; - ['log', 'profile', 'startTimer'].concat(Object.keys(this.levels)).forEach(function (method) { - target[method] = function () { - return self[method].apply(self, arguments); - }; - }); - - return this; -}; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Logger.prototype.log = function (level, msg) { - var self = this, - callback, - meta; - - if (arguments.length === 3) { - if (typeof arguments[2] === 'function') { - meta = {}; - callback = arguments[2]; - } - else if (typeof arguments[2] === 'object') { - meta = arguments[2]; - } - } - else if (arguments.length === 4) { - meta = arguments[2]; - callback = arguments[3]; - } - - // If we should pad for levels, do so - if (this.padLevels) { - msg = new Array(this.levelLength - level.length).join(' ') + msg; - } - - function onError (err) { - if (callback) { - callback(err); - } - else if (self.emitErrs) { - self.emit('error', err); - }; - } - - if (this.transports.length === 0) { - return onError(new Error('Cannot log with no transports.')); - } - else if (typeof self.levels[level] === 'undefined') { - return onError(new Error('Unknown log level: ' + level)); - } - - this.rewriters.forEach(function(rewriter) { - meta = rewriter(level, msg, meta); - }); - - // - // For consideration of terminal 'color" programs like colors.js, - // which can add ANSI escape color codes to strings, we destyle the - // ANSI color escape codes when `this.stripColors` is set. - // - // see: http://en.wikipedia.org/wiki/ANSI_escape_code - // - if (this.stripColors) { - var code = /\u001b\[\d+m/g; - msg = ('' + msg).replace(code, ''); - } - - for (var i = 0, l = this._names.length; i < l; i++) { - var transport = this.transports[this._names[i]]; - if ((transport.level && self.levels[transport.level] <= self.levels[level]) - || (!transport.level && self.levels[self.level] <= self.levels[level])) { - transport.log(level, msg, meta, function (err) { - self.emit('logging', transport, level, msg, meta); - }); - } - } - - // - // Immediately respond to the callback - // - if (callback) { - callback(null, level, msg, meta); - } - - return this; -}; - -// -// ### function close () -// Cleans up resources (streams, event listeners) for all -// transports associated with this instance (if necessary). -// -Logger.prototype.close = function () { - var self = this; - - this._names.forEach(function (name) { - var transport = self.transports[name]; - if (transport && transport.close) { - transport.close(); - } - }); -}; - -// -// ### function handleExceptions () -// Handles `uncaughtException` events for the current process -// -Logger.prototype.handleExceptions = function () { - var args = Array.prototype.slice.call(arguments), - handlers = [], - self = this; - - args.forEach(function (a) { - if (Array.isArray(a)) { - handlers = handlers.concat(a); - } - else { - handlers.push(a); - } - }); - - handlers.forEach(function (handler) { - self.exceptionHandlers[handler.name] = handler; - }); - - this._hnames = Object.keys(self.exceptionHandlers); - - if (!this.catchExceptions) { - this.catchExceptions = this._uncaughtException.bind(this); - process.on('uncaughtException', this.catchExceptions); - } -}; - -// -// ### function unhandleExceptions () -// Removes any handlers to `uncaughtException` events -// for the current process -// -Logger.prototype.unhandleExceptions = function () { - var self = this; - - if (this.catchExceptions) { - Object.keys(this.exceptionHandlers).forEach(function (name) { - if (handler.close) { - handler.close(); - } - }); - - this.exceptionHandlers = {}; - Object.keys(this.transports).forEach(function (name) { - var transport = self.transports[name]; - if (transport.handleExceptions) { - transport.handleExceptions = false; - } - }) - - process.removeListener('uncaughtException', this.catchExceptions); - this.catchExceptions = false; - } -}; - -// -// ### function add (transport, [options]) -// #### @transport {Transport} Prototype of the Transport object to add. -// #### @options {Object} **Optional** Options for the Transport to add. -// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. -// Adds a transport of the specified type to this instance. -// -Logger.prototype.add = function (transport, options, created) { - var instance = created ? transport : (new (transport)(options)); - - if (!instance.name && !instance.log) { - throw new Error('Unknown transport with no log() method'); - } - else if (this.transports[instance.name]) { - throw new Error('Transport already attached: ' + instance.name); - } - - this.transports[instance.name] = instance; - this._names = Object.keys(this.transports); - - // - // Listen for the `error` event on the new Transport - // - instance._onError = this._onError.bind(this, instance) - instance.on('error', instance._onError); - - // - // If this transport has `handleExceptions` set to `true` - // and we are not already handling exceptions, do so. - // - if (transport.handleExceptions && !this.catchExceptions) { - this.handleExceptions(); - } - - return this; -}; - -// -// ### function addRewriter (transport, [options]) -// #### @transport {Transport} Prototype of the Transport object to add. -// #### @options {Object} **Optional** Options for the Transport to add. -// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. -// Adds a transport of the specified type to this instance. -// -Logger.prototype.addRewriter = function(rewriter) { - this.rewriters.push(rewriter); -} - -// -// ### function clear () -// Remove all transports from this instance -// -Logger.prototype.clear = function () { - for (var name in this.transports) { - this.remove({ name: name }); - } -}; - -// -// ### function remove (transport) -// #### @transport {Transport} Transport to remove. -// Removes a transport of the specified type from this instance. -// -Logger.prototype.remove = function (transport) { - var name = transport.name || transport.prototype.name; - - if (!this.transports[name]) { - throw new Error('Transport ' + name + ' not attached to this instance'); - } - - var instance = this.transports[name]; - delete this.transports[name]; - this._names = Object.keys(this.transports); - - if (instance.close) { - instance.close(); - } - - instance.removeListener('error', instance._onError); - return this; -}; - -var ProfileHandler = function (logger) { - this.logger = logger; - - this.start = Date.now(); - - this.done = function (msg) { - var args, callback, meta; - args = Array.prototype.slice.call(arguments); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; - meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; - - meta.duration = (Date.now()) - this.start + 'ms'; - - return this.logger.info(msg, meta, callback); - } -} - -Logger.prototype.startTimer = function () { - return new ProfileHandler(this); -} - -// -// ### function profile (id, [msg, meta, callback]) -// #### @id {string} Unique id of the profiler -// #### @msg {string} **Optional** Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} **Optional** Continuation to respond to when complete. -// Tracks the time inbetween subsequent calls to this method -// with the same `id` parameter. The second call to this method -// will log the difference in milliseconds along with the message. -// -Logger.prototype.profile = function (id) { - var now = Date.now(), then, args, - msg, meta, callback; - - if (this.profilers[id]) { - then = this.profilers[id]; - delete this.profilers[id]; - - // Support variable arguments: msg, meta, callback - args = Array.prototype.slice.call(arguments); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; - meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; - msg = args.length === 2 ? args[1] : id; - - // Set the duration property of the metadata - meta.duration = now - then + 'ms'; - return this.info(msg, meta, callback); - } - else { - this.profilers[id] = now; - } - - return this; -}; - -// -// ### function setLevels (target) -// #### @target {Object} Target levels to use on this instance -// Sets the `target` levels specified on this instance. -// -Logger.prototype.setLevels = function (target) { - return common.setLevels(this, this.levels, target); -}; - -// -// ### function cli () -// Configures this instance to have the default -// settings for command-line interfaces: no timestamp, -// colors enabled, padded output, and additional levels. -// -Logger.prototype.cli = function () { - this.padLevels = true; - this.setLevels(config.cli.levels); - config.addColors(config.cli.colors); - - if (this.transports.console) { - this.transports.console.colorize = true; - this.transports.console.timestamp = false; - } - - return this; -}; - -// -// ### @private function _uncaughtException (err) -// #### @err {Error} Error to handle -// Logs all relevant information around the `err` and -// exits the current process. -// -Logger.prototype._uncaughtException = function (err) { - var self = this, - responded = false, - info = exception.getAllInfo(err), - handlers = this._getExceptionHandlers(), - timeout, - doExit; - - // - // Calculate if we should exit on this error - // - doExit = typeof this.exitOnError === 'function' - ? this.exitOnError(err) - : this.exitOnError; - - function logAndWait(transport, next) { - transport.logException('uncaughtException', info, next); - } - - function gracefulExit() { - if (doExit && !responded) { - // - // Remark: Currently ignoring any exceptions from transports - // when catching uncaught exceptions. - // - clearTimeout(timeout); - responded = true; - process.exit(1); - } - } - - if (!handlers || handlers.length === 0) { - return gracefulExit(); - } - - // - // Log to all transports and allow the operation to take - // only up to `3000ms`. - // - async.forEach(handlers, logAndWait, gracefulExit); - if (doExit) { - timeout = setTimeout(gracefulExit, 3000); - } -}; - -// -// ### @private function _getExceptionHandlers () -// Returns the list of transports and exceptionHandlers -// for this instance. -// -Logger.prototype._getExceptionHandlers = function () { - var self = this; - - return this._hnames.map(function (name) { - return self.exceptionHandlers[name]; - }).concat(this._names.map(function (name) { - return self.transports[name].handleExceptions && self.transports[name]; - })).filter(Boolean); -}; - -// -// ### @private function _onError (transport, err) -// #### @transport {Object} Transport on which the error occured -// #### @err {Error} Error that occurred on the transport -// Bubbles the error, `err`, that occured on the specified `transport` -// up from this instance if `emitErrs` has been set. -// -Logger.prototype._onError = function (transport, err) { - if (this.emitErrs) { - this.emit('error', err, transport); - } -}; diff --git a/node_modules/winston/lib/winston/transports.js b/node_modules/winston/lib/winston/transports.js deleted file mode 100644 index 5080634..0000000 --- a/node_modules/winston/lib/winston/transports.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * transports.js: Set of all transports Winston knows about - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var fs = require('fs'), - path = require('path'), - common = require('./common'); - -var transports = exports; - -// -// Setup all transports as lazy-loaded getters. -// -fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) { - var transport = file.replace('.js', ''), - name = common.capitalize(transport); - - if (transport === 'transport') { - return; - } - - transports.__defineGetter__(name, function () { - return require('./transports/' + transport)[name]; - }); -}); \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/console.js b/node_modules/winston/lib/winston/transports/console.js deleted file mode 100644 index b38ef04..0000000 --- a/node_modules/winston/lib/winston/transports/console.js +++ /dev/null @@ -1,83 +0,0 @@ -/* - * console.js: Transport for outputting to the console - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'), - colors = require('colors'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Console (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for persisting log messages and metadata to a terminal or TTY. -// -var Console = exports.Console = function (options) { - Transport.call(this, options); - options = options || {}; - - this.name = 'console'; - this.json = options.json || false; - this.colorize = options.colorize || false; - this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; - - if (this.json) { - this.stringify = options.stringify || function (obj) { - return JSON.stringify(obj, null, 2); - }; - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Console, Transport); - -// -// Expose the name of this Transport on the prototype -// -Console.prototype.name = 'console'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Console.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, output = common.log({ - colorize: this.colorize, - json: this.json, - level: level, - message: msg, - meta: meta, - stringify: this.stringify, - timestamp: this.timestamp - }); - - if (level === 'error' || level === 'debug') { - util.error(output); - } - else { - util.puts(output); - } - - // - // Emit the `logged` event immediately because the event loop - // will not exit until `process.stdout` has drained anyway. - // - self.emit('logged'); - callback(null, true); -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/couchdb.js b/node_modules/winston/lib/winston/transports/couchdb.js deleted file mode 100644 index 61ad74a..0000000 --- a/node_modules/winston/lib/winston/transports/couchdb.js +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Couchdb.js: Transport for logging to Couchdb - * - * (C) 2011 Max Ogden - * MIT LICENSE - * - */ - -var events = require('events'), - http = require('http'), - util = require('util'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Couchdb (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for making arbitrary HTTP requests whenever log messages and metadata -// are received. -// -var Couchdb = exports.Couchdb = function (options) { - Transport.call(this, options); - - this.name = 'Couchdb'; - this.db = options.db; - this.user = options.user; - this.pass = options.pass; - this.host = options.host || 'localhost'; - this.port = options.port || 5984; - - if (options.auth) { - // - // TODO: add http basic auth options for outgoing HTTP requests - // - } - - if (options.ssl) { - // - // TODO: add ssl support for outgoing HTTP requests - // - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Couchdb, Transport); - -// -// Expose the name of this Transport on the prototype -// -Couchdb.prototype.name = 'Couchdb'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Couchdb.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta || {}), - options, - req; - - message.level = level; - message.message = msg; - - // Prepare options for outgoing HTTP request - options = { - host: this.host, - port: this.port, - path: "/" + this.db, - method: "POST", - headers: {"content-type": "application/json"} - }; - - if (options.user && options.pass) { - options.headers["Authorization"] = "Basic " + new Buffer(options.user + ":" + options.pass).toString('base64'); - } - - // Perform HTTP logging request - req = http.request(options, function (res) { - // - // No callback on request, fire and forget about the response - // - self.emit('logged', res); - }); - - req.on('error', function (err) { - // - // Propagate the `error` back up to the `Logger` that this - // instance belongs to. - // - self.emit('error', err); - }); - - // - // Write logging event to the outgoing request body - // - req.write(JSON.stringify({ - method: 'log', - params: { - timestamp: new Date(), // RFC3339/ISO8601 format instead of common.timestamp() - msg: msg, - level: level, - meta: meta - } - })); - - req.end(); - - // Always return true, regardless of any errors - callback(null, true); -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/file.js b/node_modules/winston/lib/winston/transports/file.js deleted file mode 100644 index 0a96c01..0000000 --- a/node_modules/winston/lib/winston/transports/file.js +++ /dev/null @@ -1,332 +0,0 @@ -/* - * file.js: Transport for outputting to a local log file - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - fs = require('fs'), - path = require('path'), - util = require('util'), - colors = require('colors'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function File (options) -// #### @options {Object} Options for this instance. -// Constructor function for the File transport object responsible -// for persisting log messages and metadata to one or more files. -// -var File = exports.File = function (options) { - Transport.call(this, options); - - // - // Helper function which throws an `Error` in the event - // that any of the rest of the arguments is present in `options`. - // - function throwIf (target /*, illegal... */) { - Array.prototype.slice.call(arguments, 1).forEach(function (name) { - if (options[name]) { - throw new Error('Cannot set ' + name + ' and ' + target + 'together'); - } - }); - } - - if (options.filename || options.dirname) { - throwIf('filename or dirname', 'stream'); - this._basename = this.filename = path.basename(options.filename) || 'winston.log'; - this.dirname = options.dirname || path.dirname(options.filename); - this.options = options.options || { flags: 'a' }; - } - else if (options.stream) { - throwIf('stream', 'filename', 'maxsize'); - this.stream = options.stream; - } - else { - throw new Error('Cannot log to file without filename or stream.'); - } - - this.json = options.json !== false; - this.colorize = options.colorize || false; - this.maxsize = options.maxsize || null; - this.maxFiles = options.maxFiles || null; - this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; - - // - // Internal state variables representing the number - // of files this instance has created and the current - // size (in bytes) of the current logfile. - // - this._size = 0; - this._created = 0; - this._buffer = []; - this._draining = false; -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(File, Transport); - -// -// Expose the name of this Transport on the prototype -// -File.prototype.name = 'file'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -File.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, output = common.log({ - level: level, - message: msg, - meta: meta, - json: this.json, - colorize: this.colorize, - timestamp: this.timestamp - }) + '\n'; - - this._size += output.length; - - if (!this.filename) { - // - // If there is no `filename` on this instance then it was configured - // with a raw `WriteableStream` instance and we should not perform any - // size restrictions. - // - this.stream.write(output); - self._lazyDrain(); - } - else { - this.open(function (err) { - if (err) { - // - // If there was an error enqueue the message - // - return self._buffer.push(output); - } - - self.stream.write(output); - self._lazyDrain(); - }); - } - - callback(null, true); -}; - -// -// ### function open (callback) -// #### @callback {function} Continuation to respond to when complete -// Checks to see if a new file needs to be created based on the `maxsize` -// (if any) and the current size of the file used. -// -File.prototype.open = function (callback) { - if (this.opening) { - // - // If we are already attempting to open the next - // available file then respond with a value indicating - // that the message should be buffered. - // - return callback(true); - } - else if (!this.stream || (this.maxsize && this._size >= this.maxsize)) { - // - // If we dont have a stream or have exceeded our size, then create - // the next stream and respond with a value indicating that - // the message should be buffered. - // - callback(true); - return this._createStream(); - } - - // - // Otherwise we have a valid (and ready) stream. - // - callback(); -}; - -// -// ### function close () -// Closes the stream associated with this instance. -// -File.prototype.close = function () { - var self = this; - - if (this.stream) { - this.stream.end(); - this.stream.destroySoon(); - - this.stream.once('drain', function () { - self.emit('flush'); - self.emit('closed'); - }); - } -}; - -// -// ### function flush () -// Flushes any buffered messages to the current `stream` -// used by this instance. -// -File.prototype.flush = function () { - var self = this; - - // - // Iterate over the `_buffer` of enqueued messaged - // and then write them to the newly created stream. - // - this._buffer.forEach(function (str) { - process.nextTick(function () { - self.stream.write(str); - self._size += str.length; - }); - }); - - // - // Quickly truncate the `_buffer` once the write operations - // have been started - // - self._buffer.length = 0; - - // - // When the stream has drained we have flushed - // our buffer. - // - self.stream.once('drain', function () { - self.emit('flush'); - self.emit('logged'); - }); -}; - -// -// ### @private function _createStream () -// Attempts to open the next appropriate file for this instance -// based on the common state (such as `maxsize` and `_basename`). -// -File.prototype._createStream = function () { - var self = this; - this.opening = true; - - (function checkFile (target) { - var fullname = path.join(self.dirname, target); - - // - // Creates the `WriteStream` and then flushes any - // buffered messages. - // - function createAndFlush (size) { - if (self.stream) { - self.stream.end(); - self.stream.destroySoon(); - } - - self._size = size; - self.filename = target; - self.stream = fs.createWriteStream(fullname, self.options); - - // - // When the current stream has finished flushing - // then we can be sure we have finished opening - // and thus can emit the `open` event. - // - self.once('flush', function () { - self.opening = false; - self.emit('open', fullname); - }); - - // - // Remark: It is possible that in the time it has taken to find the - // next logfile to be written more data than `maxsize` has been buffered, - // but for sensible limits (10s - 100s of MB) this seems unlikely in less - // than one second. - // - self.flush(); - } - - fs.stat(fullname, function (err, stats) { - if (err) { - if (err.code !== 'ENOENT') { - return self.emit('error', err); - } - - return createAndFlush(0); - } - - if (!stats || (self.maxsize && stats.size >= self.maxsize)) { - // - // If `stats.size` is greater than the `maxsize` for - // this instance then try again - // - return checkFile(self._getFile(true)); - } - - createAndFlush(stats.size); - }); - })(this._getFile()); -}; - -// -// ### @private function _getFile () -// Gets the next filename to use for this instance -// in the case that log filesizes are being capped. -// -File.prototype._getFile = function (inc) { - var self = this, - ext = path.extname(this._basename), - basename = path.basename(this._basename, ext), - remaining; - - if (inc) { - // - // Increment the number of files created or - // checked by this instance. - // - // Check for maxFiles option and delete file - if (this.maxFiles && (this._created >= (this.maxFiles - 1))) { - remaining = this._created - (this.maxFiles - 1); - if (remaining === 0) { - fs.unlinkSync(path.join(this.dirname, basename + ext)); - } - else { - fs.unlinkSync(path.join(this.dirname, basename + remaining + ext)); - } - } - - this._created += 1; - } - - return this._created - ? basename + this._created + ext - : basename + ext; -}; - -// -// ### @private function _lazyDrain () -// Lazily attempts to emit the `logged` event when `this.stream` has -// drained. This is really just a simple mutex that only works because -// Node.js is single-threaded. -// -File.prototype._lazyDrain = function () { - var self = this; - - if (!this._draining && this.stream) { - this._draining = true; - - this.stream.once('drain', function () { - this._draining = false; - self.emit('logged'); - }); - } -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/loggly.js b/node_modules/winston/lib/winston/transports/loggly.js deleted file mode 100644 index dd5762b..0000000 --- a/node_modules/winston/lib/winston/transports/loggly.js +++ /dev/null @@ -1,161 +0,0 @@ -/* - * loggly.js: Transport for logginh to remote Loggly API - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - loggly = require('loggly'), - util = require('util'), - async = require('async'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Loggly (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Loggly transport object responsible -// for persisting log messages and metadata to Loggly; 'LaaS'. -// -var Loggly = exports.Loggly = function (options) { - Transport.call(this, options); - - function valid() { - return options.inputToken - || options.inputName && options.auth - || options.inputName && options.inputs && options.inputs[options.inputName] - || options.id && options.inputs && options.inputs[options.id]; - } - - if (!options.subdomain) { - throw new Error('Loggly Subdomain is required'); - } - - if (!valid()) { - throw new Error('Target input token or name is required.'); - } - - this.name = 'loggly'; - this.logBuffer = []; - - this.client = loggly.createClient({ - subdomain: options.subdomain, - auth: options.auth || null, - json: options.json || false - }); - - if (options.inputToken) { - this.inputToken = options.inputToken; - this.ready = true; - } - else if (options.inputs && (options.inputs[options.inputName] - || options.inputs[options.id])) { - this.inputToken = options.inputs[options.inputName] || options.inputs[options.id]; - this.ready = true; - } - else if (options.inputName) { - this.ready = false; - this.inputName = options.inputName; - - var self = this; - this.client.getInput(this.inputName, function (err, input) { - if (err) { - throw err; - } - - self.inputToken = input.input_token; - self.ready = true; - }); - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Loggly, Transport); - -// -// Expose the name of this Transport on the prototype -// -Loggly.prototype.name = 'loggly'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Loggly.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta || {}); - - message.level = level; - message.message = msg; - - if (!this.ready) { - // - // If we haven't gotten the input token yet - // add this message to the log buffer. - // - this.logBuffer.push(message); - } - else if (this.ready && this.logBuffer.length > 0) { - // - // Otherwise if we have buffered messages - // add this message to the buffer and flush them. - // - this.logBuffer.push(message); - this.flush(); - } - else { - // - // Otherwise just log the message as normal - // - this.client.log(this.inputToken, message, function () { - self.emit('logged'); - }); - } - - callback(null, true); -}; - -// -// ### function flush () -// Flushes any buffered messages to the current `stream` -// used by this instance. -// -Loggly.prototype.flush = function () { - var self = this; - - function logMsg (msg, next) { - self.client.log(self.inputToken, msg, function (err) { - if (err) { - self.emit('error', err); - } - - next(); - }); - } - - // - // Initiate calls to loggly for each message in the buffer - // - async.forEach(this.logBuffer, logMsg, function () { - self.emit('logged'); - }); - - process.nextTick(function () { - // - // Then quickly truncate the list - // - self.logBuffer.length = 0; - }); -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/transport.js b/node_modules/winston/lib/winston/transports/transport.js deleted file mode 100644 index a2f941c..0000000 --- a/node_modules/winston/lib/winston/transports/transport.js +++ /dev/null @@ -1,57 +0,0 @@ -/* - * transport.js: Base Transport object for all Winston transports. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'); - -// -// ### function Transport (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Tranport object responsible -// base functionality for all winston transports. -// -var Transport = exports.Transport = function (options) { - events.EventEmitter.call(this); - - options = options || {}; - this.level = options.level || 'info'; - this.silent = options.silent || false; - this.handleExceptions = options.handleExceptions || false; -}; - -// -// Inherit from `events.EventEmitter`. -// -util.inherits(Transport, events.EventEmitter); - -// -// ### function logException (msg, meta, callback) -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Logs the specified `msg`, `meta` and responds to the callback once the log -// operation is complete to ensure that the event loop will not exit before -// all logging has completed. -// -Transport.prototype.logException = function (msg, meta, callback) { - var self = this; - - function onLogged () { - self.removeListener('error', onError); - callback(); - } - - function onError () { - self.removeListener('logged', onLogged); - callback(); - } - - this.once('logged', onLogged); - this.once('error', onError); - this.log('error', msg, meta, function () { }); -}; \ No newline at end of file diff --git a/node_modules/winston/lib/winston/transports/webhook.js b/node_modules/winston/lib/winston/transports/webhook.js deleted file mode 100644 index bf8eb27..0000000 --- a/node_modules/winston/lib/winston/transports/webhook.js +++ /dev/null @@ -1,136 +0,0 @@ -/* - * webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks ) - * - * (C) 2011 Marak Squires - * MIT LICENCE - * - */ - -var events = require('events'), - http = require('http'), - https = require('https'), - util = require('util'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function WebHook (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for making arbitrary HTTP requests whenever log messages and metadata -// are received. -// -var Webhook = exports.Webhook = function (options) { - Transport.call(this, options); - - this.name = 'webhook'; - this.host = options.host || 'localhost'; - this.port = options.port || 8080; - this.method = options.method || 'POST'; - this.path = options.path || '/winston-log'; - - if (options.auth) { - this.auth = {}; - this.auth.username = options.auth.username || ''; - this.auth.password = options.auth.password || ''; - } - - if (options.ssl) { - this.ssl = {}; - this.ssl.key = options.ssl.key || null; - this.ssl.cert = options.ssl.cert || null; - this.ssl.ca = options.ssl.ca; - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Webhook, Transport); - -// -// Expose the name of this Transport on the prototype -// -Webhook.prototype.name = 'webhook'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Webhook.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta), - options, - req; - - message.level = level; - message.message = msg; - - // Prepare options for outgoing HTTP request - options = { - host: this.host, - port: this.port, - path: this.path, - method: this.method, - headers: { 'Content-Type': 'application/json' } - }; - - if (this.ssl) { - options.ca = this.ssl.ca; - options.key = this.ssl.key; - options.cert = this.ssl.cert; - } - - if (this.auth) { - // Encode `Authorization` header used by Basic Auth - options.headers['Authorization'] = 'Basic ' + new Buffer( - this.auth.username + ':' + this.auth.password, 'utf8' - ).toString('base64'); - } - - // Perform HTTP logging request - req = (self.ssl ? https : http).request(options, function (res) { - // - // No callback on request, fire and forget about the response - // - self.emit('logged'); - }); - - req.on('error', function (err) { - // - // Propagate the `error` back up to the `Logger` that this - // instance belongs to. - // - self.emit('error', err); - }); - - // - // Write logging event to the outgoing request body - // - // jsonMessage is currently conforming to JSON-RPC v1.0, - // but without the unique id since there is no anticipated response - // see: http://en.wikipedia.org/wiki/JSON-RPC - // - req.write(JSON.stringify({ - method: 'log', - params: { - timestamp: new Date(), - msg: msg, - level: level, - meta: meta - } - })); - - req.end(); - - // Always return true, regardless of any errors - callback(null, true); -}; diff --git a/node_modules/winston/node_modules/colors/MIT-LICENSE.txt b/node_modules/winston/node_modules/colors/MIT-LICENSE.txt deleted file mode 100644 index 7dca107..0000000 --- a/node_modules/winston/node_modules/colors/MIT-LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2010 - -Marak Squires -Alexis Sellier (cloudhead) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/ReadMe.md b/node_modules/winston/node_modules/colors/ReadMe.md deleted file mode 100644 index 1c6b0d0..0000000 --- a/node_modules/winston/node_modules/colors/ReadMe.md +++ /dev/null @@ -1,77 +0,0 @@ -# colors.js - get color and style in your node.js console ( and browser ) like what - - - - -## Installation - - npm install colors - -## colors and styles! - -- bold -- italic -- underline -- inverse -- yellow -- cyan -- white -- magenta -- green -- red -- grey -- blue -- rainbow -- zebra -- random - -## Usage - -``` js -var colors = require('./colors'); - -console.log('hello'.green); // outputs green text -console.log('i like cake and pies'.underline.red) // outputs red underlined text -console.log('inverse the color'.inverse); // inverses the color -console.log('OMG Rainbows!'.rainbow); // rainbow (ignores spaces) -``` - -# Creating Custom themes - -```js - -var require('colors'); - -colors.setTheme({ - silly: 'rainbow', - input: 'grey', - verbose: 'cyan', - prompt: 'grey', - info: 'green', - data: 'grey', - help: 'cyan', - warn: 'yellow', - debug: 'blue', - error: 'red' -}); - -// outputs red text -console.log("this is an error".error); - -// outputs yellow text -console.log("this is a warning".warn); -``` - - -### Contributors - -Marak (Marak Squires) -Alexis Sellier (cloudhead) -mmalecki (Maciej Małecki) -nicoreed (Nico Reed) -morganrallen (Morgan Allen) -JustinCampbell (Justin Campbell) -ded (Dustin Diaz) - - -#### , Marak Squires , Justin Campbell, Dustin Diaz (@ded) diff --git a/node_modules/winston/node_modules/colors/colors.js b/node_modules/winston/node_modules/colors/colors.js deleted file mode 100644 index a7198f1..0000000 --- a/node_modules/winston/node_modules/colors/colors.js +++ /dev/null @@ -1,269 +0,0 @@ -/* -colors.js - -Copyright (c) 2010 - -Marak Squires -Alexis Sellier (cloudhead) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - -var isHeadless = false; - -if (typeof module !== 'undefined') { - isHeadless = true; -} - -if (!isHeadless) { - var exports = {}; - var module = {}; - var colors = exports; - exports.mode = "browser"; -} else { - exports.mode = "console"; -} - -// -// Prototypes the string object to have additional method calls that add terminal colors -// -var addProperty = function (color, func) { - var allowOverride = ['bold']; - exports[color] = function(str) { - return func.apply(str); - }; - String.prototype.__defineGetter__(color, func); -} - -// -// Iterate through all default styles and colors -// - -var x = ['bold', 'underline', 'italic', 'inverse', 'grey', 'black', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; -x.forEach(function (style) { - - // __defineGetter__ at the least works in more browsers - // http://robertnyman.com/javascript/javascript-getters-setters.html - // Object.defineProperty only works in Chrome - addProperty(style, function () { - return stylize(this, style); - }); -}); - -function sequencer(map) { - return function () { - if (!isHeadless) { - return this.replace(/( )/, '$1'); - } - var exploded = this.split(""); - var i = 0; - exploded = exploded.map(map); - return exploded.join(""); - } -} - -var rainbowMap = (function () { - var rainbowColors = ['red','yellow','green','blue','magenta']; //RoY G BiV - return function (letter, i, exploded) { - if (letter == " ") { - return letter; - } else { - return stylize(letter, rainbowColors[i++ % rainbowColors.length]); - } - } -})(); - -exports.addSequencer = function (name, map) { - addProperty(name, sequencer(map)); -} - -exports.addSequencer('rainbow', rainbowMap); -exports.addSequencer('zebra', function (letter, i, exploded) { - return i % 2 === 0 ? letter : letter.inverse; -}); - -exports.setTheme = function (theme) { - Object.keys(theme).forEach(function(prop){ - addProperty(prop, function(){ - return exports[theme[prop]](this); - }); - }); -} - -function stylize(str, style) { - - if (exports.mode == 'console') { - var styles = { - //styles - 'bold' : ['\033[1m', '\033[22m'], - 'italic' : ['\033[3m', '\033[23m'], - 'underline' : ['\033[4m', '\033[24m'], - 'inverse' : ['\033[7m', '\033[27m'], - //grayscale - 'white' : ['\033[37m', '\033[39m'], - 'grey' : ['\033[90m', '\033[39m'], - 'black' : ['\033[30m', '\033[39m'], - //colors - 'blue' : ['\033[34m', '\033[39m'], - 'cyan' : ['\033[36m', '\033[39m'], - 'green' : ['\033[32m', '\033[39m'], - 'magenta' : ['\033[35m', '\033[39m'], - 'red' : ['\033[31m', '\033[39m'], - 'yellow' : ['\033[33m', '\033[39m'] - }; - } else if (exports.mode == 'browser') { - var styles = { - //styles - 'bold' : ['', ''], - 'italic' : ['', ''], - 'underline' : ['', ''], - 'inverse' : ['', ''], - //grayscale - 'white' : ['', ''], - 'grey' : ['', ''], - 'black' : ['', ''], - //colors - 'blue' : ['', ''], - 'cyan' : ['', ''], - 'green' : ['', ''], - 'magenta' : ['', ''], - 'red' : ['', ''], - 'yellow' : ['', ''] - }; - } else if (exports.mode == 'none') { - return str; - } else { - console.log('unsupported mode, try "browser", "console" or "none"'); - } - return styles[style][0] + str + styles[style][1]; -}; - -// don't summon zalgo -addProperty('zalgo', function () { - return zalgo(this); -}); - -// please no -function zalgo(text, options) { - var soul = { - "up" : [ - '̍','̎','̄','̅', - '̿','̑','̆','̐', - '͒','͗','͑','̇', - '̈','̊','͂','̓', - '̈','͊','͋','͌', - '̃','̂','̌','͐', - '̀','́','̋','̏', - '̒','̓','̔','̽', - '̉','ͣ','ͤ','ͥ', - 'ͦ','ͧ','ͨ','ͩ', - 'ͪ','ͫ','ͬ','ͭ', - 'ͮ','ͯ','̾','͛', - '͆','̚' - ], - "down" : [ - '̖','̗','̘','̙', - '̜','̝','̞','̟', - '̠','̤','̥','̦', - '̩','̪','̫','̬', - '̭','̮','̯','̰', - '̱','̲','̳','̹', - '̺','̻','̼','ͅ', - '͇','͈','͉','͍', - '͎','͓','͔','͕', - '͖','͙','͚','̣' - ], - "mid" : [ - '̕','̛','̀','́', - '͘','̡','̢','̧', - '̨','̴','̵','̶', - '͜','͝','͞', - '͟','͠','͢','̸', - '̷','͡',' ҉' - ] - }, - all = [].concat(soul.up, soul.down, soul.mid), - zalgo = {}; - - function randomNumber(range) { - r = Math.floor(Math.random()*range); - return r; - }; - - function is_char(character) { - var bool = false; - all.filter(function(i){ - bool = (i == character); - }); - return bool; - } - - function heComes(text, options){ - result = ''; - options = options || {}; - options["up"] = options["up"] || true; - options["mid"] = options["mid"] || true; - options["down"] = options["down"] || true; - options["size"] = options["size"] || "maxi"; - var counts; - text = text.split(''); - for(var l in text){ - if(is_char(l)) { continue; } - result = result + text[l]; - - counts = {"up" : 0, "down" : 0, "mid" : 0}; - - switch(options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.min= randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.min = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down= randomNumber(8) + 1; - break; - } - - var arr = ["up", "mid", "down"]; - for(var d in arr){ - var index = arr[d]; - for (var i = 0 ; i <= counts[index]; i++) - { - if(options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - }; - return heComes(text); -} - -addProperty('stripColors', function() { - return ("" + this).replace(/\u001b\[\d+m/g,''); -}); diff --git a/node_modules/winston/node_modules/colors/example.html b/node_modules/winston/node_modules/colors/example.html deleted file mode 100644 index ab95649..0000000 --- a/node_modules/winston/node_modules/colors/example.html +++ /dev/null @@ -1,74 +0,0 @@ - - - - - Colors Example - - - - - - \ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/example.js b/node_modules/winston/node_modules/colors/example.js deleted file mode 100644 index 3da2986..0000000 --- a/node_modules/winston/node_modules/colors/example.js +++ /dev/null @@ -1,65 +0,0 @@ -var colors = require('./colors'); - -//colors.mode = "browser"; - -var test = colors.red("hopefully colorless output"); -console.log('Rainbows are fun!'.rainbow); -console.log('So '.italic + 'are'.underline + ' styles! '.bold + 'inverse'.inverse); // styles not widely supported -console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported -//console.log('zalgo time!'.zalgo); -console.log(test.stripColors); -console.log("a".grey + " b".black); - -console.log("Zebras are so fun!".zebra); - -console.log(colors.rainbow('Rainbows are fun!')); -console.log(colors.italic('So ') + colors.underline('are') + colors.bold(' styles! ') + colors.inverse('inverse')); // styles not widely supported -console.log(colors.bold(colors.italic(colors.underline(colors.red('Chains are also cool.'))))); // styles not widely supported -//console.log(colors.zalgo('zalgo time!')); -console.log(colors.stripColors(test)); -console.log(colors.grey("a") + colors.black(" b")); - -colors.addSequencer("america", function(letter, i, exploded) { - if(letter === " ") return letter; - switch(i%3) { - case 0: return letter.red; - case 1: return letter.white; - case 2: return letter.blue; - } -}); - -colors.addSequencer("random", (function() { - var available = ['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; - - return function(letter, i, exploded) { - return letter === " " ? letter : letter[available[Math.round(Math.random() * (available.length - 1))]]; - }; -})()); - -console.log("AMERICA! F--K YEAH!".america); -console.log("So apparently I've been to Mars, with all the little green men. But you know, I don't recall.".random); - -// -// Custom themes -// - -colors.setTheme({ - silly: 'rainbow', - input: 'grey', - verbose: 'cyan', - prompt: 'grey', - info: 'green', - data: 'grey', - help: 'cyan', - warn: 'yellow', - debug: 'blue', - error: 'red' -}); - -// outputs red text -console.log("this is an error".error); - -// outputs yellow text -console.log("this is a warning".warn); - - diff --git a/node_modules/winston/node_modules/colors/package.json b/node_modules/winston/node_modules/colors/package.json deleted file mode 100644 index 3a53d62..0000000 --- a/node_modules/winston/node_modules/colors/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "colors", - "description": "get colors in your node.js console like what", - "version": "0.6.0-1", - "author": "Marak Squires", - "repository": { - "type": "git", - "url": "http://github.com/Marak/colors.js.git" - }, - "engines": { - "node": ">=0.1.90" - }, - "main": "colors" -} diff --git a/node_modules/winston/node_modules/colors/test.js b/node_modules/winston/node_modules/colors/test.js deleted file mode 100644 index 1c03d65..0000000 --- a/node_modules/winston/node_modules/colors/test.js +++ /dev/null @@ -1,65 +0,0 @@ -var assert = require('assert'), - colors = require('./colors'); - -// -// This is a pretty nice example on how tests shouldn't be written. However, -// it's more about API stability than about really testing it (although it's -// a pretty complete test suite). -// - -var s = 'string'; - -function a(s, code) { - return '\033[' + code.toString() + 'm' + s + '\033[39m'; -} - -function aE(s, color, code) { - assert.equal(s[color], a(s, code)); - assert.equal(colors[color](s), a(s, code)); - assert.equal(s[color], colors[color](s)); - assert.equal(s[color].stripColors, s); - assert.equal(s[color].stripColors, colors.stripColors(s)); -} - -function h(s, color) { - return '' + s + ''; - // that's pretty dumb approach to testing it -} - -var stylesColors = ['white', 'grey', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; -var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); - -colors.mode = 'console'; -assert.equal(s.bold, '\033[1m' + s + '\033[22m'); -assert.equal(s.italic, '\033[3m' + s + '\033[23m'); -assert.equal(s.underline, '\033[4m' + s + '\033[24m'); -assert.equal(s.inverse, '\033[7m' + s + '\033[27m'); -assert.ok(s.rainbow); -aE(s, 'white', 37); -aE(s, 'grey', 90); -aE(s, 'black', 30); -aE(s, 'blue', 34); -aE(s, 'cyan', 36); -aE(s, 'green', 32); -aE(s, 'magenta', 35); -aE(s, 'red', 31); -aE(s, 'yellow', 33); -assert.equal(s, 'string'); - -colors.mode = 'browser'; -assert.equal(s.bold, '' + s + ''); -assert.equal(s.italic, '' + s + ''); -assert.equal(s.underline, '' + s + ''); -assert.equal(s.inverse, '' + s + ''); -assert.ok(s.rainbow); -stylesColors.forEach(function (color) { - assert.equal(s[color], h(s, color)); - assert.equal(colors[color](s), h(s, color)); -}); - -colors.mode = 'none'; -stylesAll.forEach(function (style) { - assert.equal(s[style], s); - assert.equal(colors[style](s), s); -}); - diff --git a/node_modules/winston/node_modules/eyes/LICENSE b/node_modules/winston/node_modules/eyes/LICENSE deleted file mode 100644 index a1edd93..0000000 --- a/node_modules/winston/node_modules/eyes/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 cloudhead - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/winston/node_modules/eyes/Makefile b/node_modules/winston/node_modules/eyes/Makefile deleted file mode 100644 index a121dea..0000000 --- a/node_modules/winston/node_modules/eyes/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - @@node test/eyes-test.js - -.PHONY: test diff --git a/node_modules/winston/node_modules/eyes/README.md b/node_modules/winston/node_modules/eyes/README.md deleted file mode 100644 index 7a92158..0000000 --- a/node_modules/winston/node_modules/eyes/README.md +++ /dev/null @@ -1,72 +0,0 @@ -eyes -==== - -a customizable value inspector for Node.js - -synopsis --------- - -I was tired of looking at cluttered output in the console -- something needed to be done, -`sys.inspect()` didn't display regexps correctly, and was too verbose, and I had an hour or two to spare. -So I decided to have some fun. _eyes_ were born. - -![eyes-ss](http://dl.dropbox.com/u/251849/eyes-js-ss.gif) - -_example of the output of a user-customized eyes.js inspector_ - -*eyes* also deals with circular objects in an intelligent way, and can pretty-print object literals. - -usage ------ - - var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); - - inspect(something); // inspect with the settings passed to `inspector` - -or - - var eyes = require('eyes'); - - eyes.inspect(something); // inspect with the default settings - -you can pass a _label_ to `inspect()`, to keep track of your inspections: - - eyes.inspect(something, "a random value"); - -If you want to return the output of eyes without printing it, you can set it up this way: - - var inspect = require('eyes').inspector({ stream: null }); - - sys.puts(inspect({ something: 42 })); - -customization -------------- - -These are the default styles and settings used by _eyes_. - styles: { // Styles applied to stdout - all: 'cyan', // Overall style applied to everything - label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` - other: 'inverted', // Objects which don't have a literal representation, such as functions - key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` - - special: 'grey', // null, undefined... - string: 'green', - number: 'magenta', - bool: 'blue', // true false - regexp: 'green', // /\d+/ - }, - pretty: true, // Indent object literals - hideFunctions: false, // Don't output functions at all - stream: process.stdout, // Stream to write to, or null - maxLength: 2048 // Truncate output if longer - -You can overwrite them with your own, by passing a similar object to `inspector()` or `inspect()`. - - var inspect = require('eyes').inspector({ - styles: { - all: 'magenta', - special: 'bold' - }, - maxLength: 512 - }); - diff --git a/node_modules/winston/node_modules/eyes/lib/eyes.js b/node_modules/winston/node_modules/eyes/lib/eyes.js deleted file mode 100644 index 10d964b..0000000 --- a/node_modules/winston/node_modules/eyes/lib/eyes.js +++ /dev/null @@ -1,236 +0,0 @@ -// -// Eyes.js - a customizable value inspector for Node.js -// -// usage: -// -// var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); -// inspect(something); // inspect with the settings passed to `inspector` -// -// or -// -// var eyes = require('eyes'); -// eyes.inspect(something); // inspect with the default settings -// -var eyes = exports, - stack = []; - -eyes.defaults = { - styles: { // Styles applied to stdout - all: 'cyan', // Overall style applied to everything - label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` - other: 'inverted', // Objects which don't have a literal representation, such as functions - key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` - special: 'grey', // null, undefined... - string: 'green', - number: 'magenta', - bool: 'blue', // true false - regexp: 'green', // /\d+/ - }, - pretty: true, // Indent object literals - hideFunctions: false, - showHidden: false, - stream: process.stdout, - maxLength: 2048 // Truncate output if longer -}; - -// Return a curried inspect() function, with the `options` argument filled in. -eyes.inspector = function (options) { - var that = this; - return function (obj, label, opts) { - return that.inspect.call(that, obj, label, - merge(options || {}, opts || {})); - }; -}; - -// If we have a `stream` defined, use it to print a styled string, -// if not, we just return the stringified object. -eyes.inspect = function (obj, label, options) { - options = merge(this.defaults, options || {}); - - if (options.stream) { - return this.print(stringify(obj, options), label, options); - } else { - return stringify(obj, options) + (options.styles ? '\033[39m' : ''); - } -}; - -// Output using the 'stream', and an optional label -// Loop through `str`, and truncate it after `options.maxLength` has been reached. -// Because escape sequences are, at this point embeded within -// the output string, we can't measure the length of the string -// in a useful way, without separating what is an escape sequence, -// versus a printable character (`c`). So we resort to counting the -// length manually. -eyes.print = function (str, label, options) { - for (var c = 0, i = 0; i < str.length; i++) { - if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5 - else if (c === options.maxLength) { - str = str.slice(0, i - 1) + '…'; - break; - } else { c++ } - } - return options.stream.write.call(options.stream, (label ? - this.stylize(label, options.styles.label, options.styles) + ': ' : '') + - this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n"); -}; - -// Apply a style to a string, eventually, -// I'd like this to support passing multiple -// styles. -eyes.stylize = function (str, style, styles) { - var codes = { - 'bold' : [1, 22], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'cyan' : [36, 39], - 'magenta' : [35, 39], - 'blue' : [34, 39], - 'yellow' : [33, 39], - 'green' : [32, 39], - 'red' : [31, 39], - 'grey' : [90, 39] - }, endCode; - - if (style && codes[style]) { - endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0] - : codes[style][1]; - return '\033[' + codes[style][0] + 'm' + str + - '\033[' + endCode + 'm'; - } else { return str } -}; - -// Convert any object to a string, ready for output. -// When an 'array' or an 'object' are encountered, they are -// passed to specialized functions, which can then recursively call -// stringify(). -function stringify(obj, options) { - var that = this, stylize = function (str, style) { - return eyes.stylize(str, options.styles[style], options.styles) - }, index, result; - - if ((index = stack.indexOf(obj)) !== -1) { - return stylize(new(Array)(stack.length - index + 1).join('.'), 'special'); - } - stack.push(obj); - - result = (function (obj) { - switch (typeOf(obj)) { - case "string" : obj = stringifyString(obj.indexOf("'") === -1 ? "'" + obj + "'" - : '"' + obj + '"'); - return stylize(obj, 'string'); - case "regexp" : return stylize('/' + obj.source + '/', 'regexp'); - case "number" : return stylize(obj + '', 'number'); - case "function" : return options.stream ? stylize("Function", 'other') : '[Function]'; - case "null" : return stylize("null", 'special'); - case "undefined": return stylize("undefined", 'special'); - case "boolean" : return stylize(obj + '', 'bool'); - case "date" : return stylize(obj.toUTCString()); - case "array" : return stringifyArray(obj, options, stack.length); - case "object" : return stringifyObject(obj, options, stack.length); - } - })(obj); - - stack.pop(); - return result; -}; - -// Escape invisible characters in a string -function stringifyString (str, options) { - return str.replace(/\\/g, '\\\\') - .replace(/\n/g, '\\n') - .replace(/[\u0001-\u001F]/g, function (match) { - return '\\0' + match[0].charCodeAt(0).toString(8); - }); -} - -// Convert an array to a string, such as [1, 2, 3]. -// This function calls stringify() for each of the elements -// in the array. -function stringifyArray(ary, options, level) { - var out = []; - var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) { - return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) || - (Array.isArray(o) && o.length > 0); - })); - var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; - - for (var i = 0; i < ary.length; i++) { - out.push(stringify(ary[i], options)); - } - - if (out.length === 0) { - return '[]'; - } else { - return '[' + ws - + out.join(',' + (pretty ? ws : ' ')) - + (pretty ? ws.slice(0, -4) : ws) + - ']'; - } -}; - -// Convert an object to a string, such as {a: 1}. -// This function calls stringify() for each of its values, -// and does not output functions or prototype values. -function stringifyObject(obj, options, level) { - var out = []; - var pretty = options.pretty && (Object.keys(obj).length > 2 || - Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' })); - var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; - - var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj); - keys.forEach(function (k) { - if (Object.prototype.hasOwnProperty.call(obj, k) - && !(obj[k] instanceof Function && options.hideFunctions)) { - out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' + - stringify(obj[k], options)); - } - }); - - if (out.length === 0) { - return '{}'; - } else { - return "{" + ws - + out.join(',' + (pretty ? ws : ' ')) - + (pretty ? ws.slice(0, -4) : ws) + - "}"; - } -}; - -// A better `typeof` -function typeOf(value) { - var s = typeof(value), - types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; - - if (s === 'object' || s === 'function') { - if (value) { - types.forEach(function (t) { - if (value instanceof t) { s = t.name.toLowerCase() } - }); - } else { s = 'null' } - } - return s; -} - -function merge(/* variable args */) { - var objs = Array.prototype.slice.call(arguments); - var target = {}; - - objs.forEach(function (o) { - Object.keys(o).forEach(function (k) { - if (k === 'styles') { - if (! o.styles) { - target.styles = false; - } else { - target.styles = {} - for (var s in o.styles) { - target.styles[s] = o.styles[s]; - } - } - } else { - target[k] = o[k]; - } - }); - }); - return target; -} - diff --git a/node_modules/winston/node_modules/eyes/package.json b/node_modules/winston/node_modules/eyes/package.json deleted file mode 100644 index ffa1063..0000000 --- a/node_modules/winston/node_modules/eyes/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name" : "eyes", - "description" : "a customizable value inspector", - "url" : "http://github.com/cloudhead/eyes.js", - "keywords" : ["inspector", "debug", "inspect", "print"], - "author" : "Alexis Sellier ", - "contributors" : [{ "name": "Charlie Robbins", "email": "charlie@nodejitsu.com" }], - "licenses" : ["MIT"], - "dependencies" : [], - "main" : "./lib/eyes", - "version" : "0.1.7", - "scripts" : { "test": "node test/*-test.js" }, - "directories" : { "lib": "./lib", "test": "./test" }, - "engines" : { "node": "> 0.1.90" } -} diff --git a/node_modules/winston/node_modules/eyes/test/eyes-test.js b/node_modules/winston/node_modules/eyes/test/eyes-test.js deleted file mode 100644 index 1f9606a..0000000 --- a/node_modules/winston/node_modules/eyes/test/eyes-test.js +++ /dev/null @@ -1,56 +0,0 @@ -var util = require('util'); -var eyes = require('../lib/eyes'); - -eyes.inspect({ - number: 42, - string: "John Galt", - regexp: /[a-z]+/, - array: [99, 168, 'x', {}], - func: function () {}, - bool: false, - nil: null, - undef: undefined, - object: {attr: []} -}, "native types"); - -eyes.inspect({ - number: new(Number)(42), - string: new(String)("John Galt"), - regexp: new(RegExp)(/[a-z]+/), - array: new(Array)(99, 168, 'x', {}), - bool: new(Boolean)(false), - object: new(Object)({attr: []}), - date: new(Date) -}, "wrapped types"); - -var obj = {}; -obj.that = { self: obj }; -obj.self = obj; - -eyes.inspect(obj, "circular object"); -eyes.inspect({hello: 'moto'}, "small object"); -eyes.inspect({hello: new(Array)(6) }, "big object"); -eyes.inspect(["hello 'world'", 'hello "world"'], "quotes"); -eyes.inspect({ - recommendations: [{ - id: 'a7a6576c2c822c8e2bd81a27e41437d8', - key: [ 'spree', 3.764316258020699 ], - value: { - _id: 'a7a6576c2c822c8e2bd81a27e41437d8', - _rev: '1-2e2d2f7fd858c4a5984bcf809d22ed98', - type: 'domain', - domain: 'spree', - weight: 3.764316258020699, - product_id: 30 - } - }] -}, 'complex'); - -eyes.inspect([null], "null in array"); - -var inspect = eyes.inspector({ stream: null }); - -util.puts(inspect('something', "something")); -util.puts(inspect("something else")); - -util.puts(inspect(["no color"], null, { styles: false })); diff --git a/node_modules/winston/node_modules/loggly/.npmignore b/node_modules/winston/node_modules/loggly/.npmignore deleted file mode 100644 index 8f08029..0000000 --- a/node_modules/winston/node_modules/loggly/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -test/data -test/data/* -node_modules -npm-debug.log \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/README.md b/node_modules/winston/node_modules/loggly/README.md deleted file mode 100644 index 926cb63..0000000 --- a/node_modules/winston/node_modules/loggly/README.md +++ /dev/null @@ -1,227 +0,0 @@ -# node-loggly - -A client implementation for Loggly in node.js - -## Installation - -### Installing npm (node package manager) -``` bash - $ curl http://npmjs.org/install.sh | sh -``` - -### Installing node-loggly -``` bash - $ [sudo] npm install loggly -``` - -## Usage - -The node-loggly library is compliant with the [Loggly API][0]. Using node-loggly is easy for a variety of scenarios: logging, working with devices and inputs, searching, and facet searching. - -### Getting Started -Before we can do anything with Loggly, we have to create a client with valid credentials. We will authenticate for you automatically: - -``` js - var loggly = require('loggly'); - var config = { - subdomain: "your-subdomain", - auth: { - username: "your-username", - password: "your-password" - } - }; - var client = loggly.createClient(config); -``` - -### Logging -There are two ways to send log information to Loggly via node-loggly. The first is to simply call client.log with an appropriate input token: - -``` js - client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home', function (err, result) { - // Do something once you've logged - }); -``` - -Note that the callback in the above example is optional, if you prefer the 'fire and forget' method of logging: - -``` js - client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home'); -``` - -The second way to send log information to Loggly is to do so once you've retrieved an input directly from Loggly: - -``` js - client.getInput('your-input-name', function (err, input) { - input.log('127.0.0.1 - Theres no place like home'); - }); -``` - -Again the callback in the above example is optional and you can pass it if you'd like to. - -### Logging Shallow JSON Object Literals as a String -In addition to logging pure strings it is also possible to pass shallow JSON object literals (i.e. no nested objects) to client.log(..) or input.log(..) methods, which will get converted into the [Loggly recommended string representation][1]. So - -``` js - var source = { - foo: 1, - bar: 2, - buzz: 3 - }; - - input.log(source); -``` - -will be logged as: - -``` - foo=1,bar=2,buzz=3 -``` - -### Logging Objects to JSON Enabled Loggly Inputs -It is also possible to log complex objects using the new JSON capabilities of Loggly. To enable JSON functionality in the client simply add 'json: true' to the configuration: - -``` js - var config = { - subdomain: "your-subdomain", - auth: { - username: "your-username", - password: "your-password" - }, - json: true - }; -``` - -When the json flag is enabled, objects will be converted to JSON using JSON.stringify before being transmitted to Loggly. So - -``` js - var source = { - foo: 1, - bar: 2, - buzz: { - sheep: 'jumped', - times: 10 - } - }; - - input.log(source); -``` - -will be logged as: - -``` json - { "foo": 1, "bar": 2, "buzz": {"sheep": "jumped", "times": 10 }} -``` - -### Searching -[Searching][3] with node-loggly is easy. All you have to do is use the search() method defined on each Loggly client: - -``` js - var util = require('util'); - - client.search('404', function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The search() exposes a chainable interface that allows you to set additional search parameters such as: ip, input name, rows, start, end, etc. - -``` js - var util = require('util'); - - client.search('404') - .meta({ ip: '127.0.0.1', inputname: test }) - .context({ rows: 10 }) - .run(function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The context of the search (set using the `.context()` method) represents additional parameters in the Loggly API besides the search query itself. See the [Search API documentation][9] for a list of all options. - -Metadata set using the `.meta()` method is data that is set in the query parameter of your Loggly search, but `:` delimited. For more information about search queries in Loggly, check out the [Search Language Guide][4] on the [Loggly Wiki][5]. - -### Facet Searching -Loggly also exposes searches that can return counts of events over a time range. These are called [facets][6]. The valid facets are 'ip', 'date', and 'input'. Performing a facet search is very similar to a normal search: - -``` js - var util = require('util'); - - client.facet('ip', '404') - .context({ buckets: 10 }) - .run(function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The chaining and options for the facet method(s) are the same as the search method above. - -### Working with Devices and Inputs -Loggly exposes several entities that are available through node-loggly: inputs and devices. For more information about these terms, checkout the [Loggly Jargon][7] on the wiki. There are several methods available in node-loggly to work with these entities: - -``` js - // - // Returns all inputs associated with your account - // - client.getInputs(function (err, inputs) { /* ... */ }); - - // - // Returns an input with the specified name - // - client.getInput('input-name', function (err, input) { /* ... */ }); - - // - // Returns all devices associated with your account - // - client.getDevices(function (err, devices) { /* ... */ }); -``` - -## Run Tests -All of the node-loggly tests are written in [vows][8], and cover all of the use cases described above. You will need to add your Loggly username, password, subdomain, and a two test inputs to test/data/test-config.json before running tests. When configuring the test inputs on Loggly, the first test input should be named 'test' using the HTTP service. The second input should be name 'test_json' using the HTTP service with the JSON logging option enabled: - -``` js - { - "subdomain": "your-subdomain", - "auth": { - "username": "your-username", - "password": "your-password" - }, - "inputs": { - "test": { - // - // Token and ID of your plain-text input. - // - "token": "your-really-long-token-you-got-when-you-created-an-http-input", - "id": 000 - }, - "test_json": { - // - // Token and ID of your JSON input. - // - "token": "your-really-long-token-you-got-when-you-created-an-http-input", - "id": 001 - }, - } - } -``` - -Once you have valid Loggly credentials you can run tests with [vows][8]: - -``` bash - $ npm test -``` - -#### Author: [Charlie Robbins](http://www.github.com/indexzero) -#### Contributors: [Marak Squires](http://github.com/marak), [hij1nx](http://github.com/hij1nx), [Kord Campbell](http://loggly.com), [Erik Hedenström](http://github.com/ehedenst), - -[0]: http://wiki.loggly.com/apidocumentation -[1]: http://wiki.loggly.com/loggingfromcode -[3]: http://wiki.loggly.com/retrieve_events#search_uri -[4]: http://wiki.loggly.com/searchguide -[5]: http://wiki.loggly.com/ -[6]: http://wiki.loggly.com/retrieve_events#facet_uris -[7]: http://wiki.loggly.com/loggingjargon -[8]: http://vowsjs.org -[9]: http://wiki.loggly.com/retrieve_events#optional diff --git a/node_modules/winston/node_modules/loggly/docs/docco.css b/node_modules/winston/node_modules/loggly/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/winston/node_modules/loggly/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly.html b/node_modules/winston/node_modules/loggly/docs/loggly.html deleted file mode 100644 index 7afcf68..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly.html +++ /dev/null @@ -1,16 +0,0 @@ - loggly.js

    loggly.js

    /*
    - * loggly.js: Wrapper for node-loggly object
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    -
    -var loggly = exports;

    Export node-loggly core client APIs

    loggly.createClient  = require('./loggly/core').createClient;
    -loggly.Loggly        = require('./loggly/core').Loggly;
    -loggly.Config        = require('./loggly/config').Config;

    Export Resources for node-loggly

    loggly.Input  = require('./loggly/input').Input;
    -loggly.Facet  = require('./loggly/facet').Facet;
    -loggly.Device = require('./loggly/device').Device;
    -loggly.Search = require('./loggly/search').Search;
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/common.html b/node_modules/winston/node_modules/loggly/docs/loggly/common.html deleted file mode 100644 index 94336be..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/common.html +++ /dev/null @@ -1,126 +0,0 @@ - common.js

    common.js

    /*
    - * common.js: Common utility functions for requesting against Loggly APIs
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    -
    -var request = require('request'),
    -    loggly = require('../loggly');
    -
    -var common = exports;

    Failure HTTP Response codes based -off Loggly specification.

    var failCodes = common.failCodes = {
    -  400: "Bad Request",
    -  401: "Unauthorized",
    -  403: "Forbidden",
    -  404: "Not Found",
    -  409: "Conflict / Duplicate",
    -  410: "Gone",
    -  500: "Internal Server Error",
    -  501: "Not Implemented",
    -  503: "Throttled"
    -};

    Success HTTP Response codes based -off Loggly specification.

    var successCodes = common.successCodes = {
    -  200: "OK",
    -  201: "Created", 
    -  202: "Accepted",
    -  203: "Non-authoritative information",
    -  204: "Deleted",
    -};

    Core method that actually sends requests to Loggly. -This method is designed to be flexible w.r.t. arguments -and continuation passing given the wide range of different -requests required to fully implement the Loggly API.

    - -

    Continuations: - 1. 'callback': The callback passed into every node-loggly method - 2. 'success': A callback that will only be called on successful requests. - This is used throughout node-loggly to conditionally - do post-request processing such as JSON parsing.

    - -

    Possible Arguments (1 & 2 are equivalent): - 1. common.loggly('some-fully-qualified-url', auth, callback, success) - 2. common.loggly('GET', 'some-fully-qualified-url', auth, callback, success) - 3. common.loggly('DELETE', 'some-fully-qualified-url', auth, callback, success) - 4. common.loggly({ method: 'POST', uri: 'some-url', body: { some: 'body'} }, callback, success)

    common.loggly = function () {
    -  var args = Array.prototype.slice.call(arguments),
    -      success = args.pop(),
    -      callback = args.pop(),
    -      requestBody, 
    -      headers,
    -      method, 
    -      auth, 
    -      uri;
    -  

    Now that we've popped off the two callbacks -We can make decisions about other arguments

      if (args.length == 1) {
    -    if (typeof args[0] === 'string') {

    If we got a string assume that it's the URI

          method = 'GET';
    -      uri    = args[0];
    -    }
    -    else {
    -      method      = args[0]['method'] || 'GET',
    -      uri         = args[0]['uri'];
    -      requestBody = args[0]['body'];
    -      auth        = args[0]['auth'];
    -      headers     = args[0]['headers'];
    -    }
    -  }
    -  else if (args.length == 2) {
    -    method = 'GET';
    -    uri    = args[0];
    -    auth   = args[1];
    -  }
    -  else {
    -    method = args[0];
    -    uri    = args[1];
    -    auth   = args[2];
    -  }
    -  
    -  function onError (err) {
    -    if (callback) {
    -      callback(err);
    -    }
    -  }
    -  
    -  var requestOptions = {
    -    uri: uri,
    -    method: method,
    -    headers: headers || {}
    -  };
    -  
    -  if (auth) {
    -    requestOptions.headers['authorization'] = 'Basic ' + new Buffer(auth.username + ':' + auth.password).toString('base64');
    -  }
    -  
    -  if (requestBody) {
    -    requestOptions.body = requestBody;
    -  }
    -  
    -  try {
    -    request(requestOptions, function (err, res, body) {
    -      if (err) {
    -        return onError(err);
    -      }
    -
    -      var statusCode = res.statusCode.toString();
    -      if (Object.keys(failCodes).indexOf(statusCode) !== -1) {
    -        return onError((new Error('Loggly Error (' + statusCode + '): ' + failCodes[statusCode])));
    -      }
    -
    -      success(res, body);
    -    });
    -  }
    -  catch (ex) {
    -    onError(ex);
    -  }
    -};

    function clone (obj) - Helper method for deep cloning pure JSON objects - i.e. JSON objects that are either literals or objects (no Arrays, etc)

    common.clone = function (obj) {
    -  var clone = {};
    -  for (var i in obj) {
    -    clone[i] = obj[i] instanceof Object ? common.clone(obj[i]) : obj[i];
    -  }
    -
    -  return clone;
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/config.html b/node_modules/winston/node_modules/loggly/docs/loggly/config.html deleted file mode 100644 index 0f39f4a..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/config.html +++ /dev/null @@ -1,41 +0,0 @@ - config.js

    config.js

    /*
    - * config.js: Configuration information for your Loggly account.
    - *            This information is only used for require('loggly')./\.+/ methods
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */

    function createConfig (defaults) - Creates a new instance of the configuration - object based on default values

    exports.createConfig = function (defaults) {
    -  return new Config(defaults);
    -};

    Config (defaults) - Constructor for the Config object

    var Config = exports.Config = function (defaults) {
    -  if (!defaults.subdomain) {
    -    throw new Error('Subdomain is required to create an instance of Config');
    -  }
    -  
    -  this.subdomain = defaults.subdomain;
    -  this.json = defaults.json || null;
    -  this.auth = defaults.auth || null;
    -};
    - 
    -Config.prototype = {
    -  get subdomain () {
    -   return this._subdomain; 
    -  },
    -
    -  set subdomain (value) {
    -    this._subdomain = value;
    -  },
    -  
    -  get logglyUrl () {
    -    return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api';
    -  },
    -  
    -  get inputUrl () {
    -    return 'https://logs.loggly.com/inputs/';
    -  }
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/core.html b/node_modules/winston/node_modules/loggly/docs/loggly/core.html deleted file mode 100644 index 7d1a4bf..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/core.html +++ /dev/null @@ -1,150 +0,0 @@ - core.js

    core.js

    /*
    - * core.js: Core functions for accessing Loggly
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    -
    -var events = require('events'),
    -    qs = require('querystring'),
    -    config = require('./config'),
    -    common = require('./common'),
    -    Search = require('./search').Search,
    -    Facet = require('./facet').Facet,
    -    loggly = require('../loggly');

    function createClient (options) - Creates a new instance of a Loggly client.

    exports.createClient = function (options) {
    -  return new Loggly(config.createConfig(options));
    -};

    Loggly (config) - Constructor for the Loggly object

    var Loggly = exports.Loggly = function (config) {
    -  this.config = config;
    -};

    function log (callback) - logs args to input device

    Loggly.prototype.log = function (inputId, msg, callback) {
    -  var emitter = new (events.EventEmitter)(),
    -      message;
    -      
    -  if (msg instanceof Object) {
    -    message = this.config.json ? JSON.stringify(msg) : qs.unescape(qs.stringify(msg, ','));
    -  } else {
    -    message = this.config.json ? JSON.stringify({ message : msg }) : msg;
    -  }
    -
    -  var logOptions = {
    -    uri: this.config.inputUrl + inputId,
    -    method: 'POST', 
    -    body: message,
    -    headers: {
    -      'Content-Type': this.config.json ? 'application/json' : 'text/plain'
    -    }
    -  };
    -
    -  common.loggly(logOptions, callback, function (res, body) {
    -    try {
    -      var result = JSON.parse(body);
    -      if (callback) {
    -        callback(null, result);
    -      }
    -      
    -      emitter.emit('log', result);
    -    }
    -    catch (ex) {
    -      if (callback) {
    -        callback(new Error('Unspecified error from Loggly: ' + ex));
    -      }
    -    }
    -  }); 
    -  
    -  return emitter; 
    -};

    function search (query, callback) - Returns a new search object which can be chained - with options or called directly if @callback is passed - initially.

    - -

    Sample Usage:

    - -

    client.search('404') - .meta({ ip: '127.0.0.1' }) - .context({ rows: 100 }) - .run(function () { /* ... */ });

    Loggly.prototype.search = function (query, callback) {
    -  return new Search(query, this, callback);
    -};

    function facet (facet, query, [options], callback) - Performs a facet search against loggly with the - specified facet, query and options.

    Loggly.prototype.facet = function (facet, query, callback) {
    -  return new Facet(facet, query, this, callback);
    -};

    function getInputs ([raw], callback) - Returns a list of all inputs for the authenicated account

    Loggly.prototype.getInputs = function () {
    -  var self = this,
    -      args = Array.prototype.slice.call(arguments),
    -      callback = args.pop(),
    -      raw = args.length > 0 ? args[0] : false;
    -  
    -  common.loggly(this.logglyUrl('inputs'), this.config.auth, callback, function (res, body) {
    -    var inputs = [], 
    -        results = JSON.parse(body);
    -        
    -    if (!raw) {
    -      results.forEach(function (result) {
    -        inputs.push(new (loggly.Input)(self, result));
    -      });
    -      
    -      return callback(null, inputs);
    -    }
    -    
    -    callback(null, results);
    -  });
    -};

    function getInput (name, callback) - Returns the input with the specified name

    Loggly.prototype.getInput = function (name, callback) {
    -  var self = this;
    -  this.getInputs(true, function (err, results) {
    -    if (err) {
    -      return callback(err);
    -    }
    -    
    -    var matches = results.filter(function (r) { return r.name === name }),
    -        input = null;
    -        
    -    if (matches.length > 0) {
    -      input = new (loggly.Input)(self, matches[0]);
    -    }
    -    
    -    callback(null, input);
    -  });
    -};

    function addDevice (inputId, address, callback) - Adds the device at address to the input specified by inputId

    Loggly.prototype.addDeviceToInput = function (inputId, address, callback) {
    -  var addOptions = {
    -    uri: this.logglyUrl('devices'),
    -    auth: this.config.auth,
    -    method: 'POST', 
    -    headers: {
    -      'Content-Type': 'application/x-www-form-urlencoded'
    -    },
    -    body: qs.stringify({ 'input_id': inputId, 'ip': address }).replace('"', '')
    -  };
    -
    -  common.loggly(addOptions, callback, function (res, body) {
    -    callback(null, res);
    -  });
    -};

    function addDevice (inputId, callback) - Adds the calling device to the input

    Loggly.prototype.addDevice = function (inputId, callback) {

    Remark: This is not fully implemented yet

      callback(new Error('Not Implemented Yet...'));
    -  

    common.loggly(this.logglyUrl('inputs', inputId, 'adddevice'), this.config.auth, callback, function (res, body) { -});

    };

    function getDevices (callback) - Returns a list of all devices for the authenicated account

    Loggly.prototype.getDevices = function (callback) {
    -  var self = this;
    -  common.loggly(this.logglyUrl('devices'), this.config.auth, callback, function (res, body) {
    -    var results = JSON.parse(body),
    -        devices = [];
    -        
    -    results.forEach(function (result) {
    -      devices.push(new (loggly.Device)(self, result));
    -    });
    -    
    -    callback(null, devices);
    -  });
    -};

    function logglyUrl ([path, to, resource]) - Helper method that concats the string params into a url - to request against a loggly serverUrl.

    Loggly.prototype.logglyUrl = function (/* path, to, resource */) {
    -  var args = Array.prototype.slice.call(arguments);
    -  return [this.config.logglyUrl].concat(args).join('/');
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/device.html b/node_modules/winston/node_modules/loggly/docs/loggly/device.html deleted file mode 100644 index 3cc7fc5..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/device.html +++ /dev/null @@ -1,26 +0,0 @@ - device.js

    device.js

    /*
    - * device.js: Instance of a single Loggly device
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    - 
    -var Device = exports.Device = function (client, details) {
    -  if (!details) throw new Error("Device must be constructed with at least basic details.")
    -
    -  this.client = client;
    -  this._setProperties(details);
    -};
    -
    -Device.prototype.addToInput = function (inputId, callback) {
    -  this.client.addDeviceToInput(inputId, this.id, callback);
    -};
    -  

    Sets the properties for this instance -Parameters: details

    Device.prototype._setProperties = function (details) {

    Copy the properties to this instance

      var self = this;
    -  Object.keys(details).forEach(function (key) {
    -    self[key] = details[key];
    -  });
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/facet.html b/node_modules/winston/node_modules/loggly/docs/loggly/facet.html deleted file mode 100644 index 39fe2b3..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/facet.html +++ /dev/null @@ -1,26 +0,0 @@ - facet.js

    facet.js

    /*
    - * facet.js: Chainable search functions for Loggly facet searches.
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    -
    -var util = require('util'),
    -    Search = require('./search').Search;

    function Facet (facet, query, client, callback) - Chainable facet search object for Loggly API

    var Facet = exports.Facet = function (facet, query, client, callback) {
    -  if (['date', 'ip', 'input'].indexOf(facet) === -1) {
    -    var error = new Error('Cannot search with unknown facet: ' + facet); 
    -    
    -    if (callback) {
    -      return callback(error);
    -    }
    -    else {
    -      throw error;
    -    }
    -  }
    -  

    Set the baseUrl to be facet/:facet?

      this.baseUrl = ['facets', facet + '?'].join('/');
    -  

    Call the base constructor.

      Search.call(this, query, client, callback);
    -};

    Inherit from loggly.Search.

    util.inherits(Facet, Search);
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/input.html b/node_modules/winston/node_modules/loggly/docs/loggly/input.html deleted file mode 100644 index 22bcac2..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/input.html +++ /dev/null @@ -1,32 +0,0 @@ - input.js

    input.js

    /*
    - * input.js: Instance of a single Loggly input
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    - 
    -var Input = exports.Input = function (client, details) {
    -  if (!details) {
    -    throw new Error("Input must be constructed with at least basic details.");
    -  }
    -  
    -  this.client = client;
    -  this._setProperties(details);
    -};
    -
    -Input.prototype.log = function (msg, callback) {
    -  return this.client.log(this.input_token, msg, callback);
    -};
    -  
    -Input.prototype.addDevice = function (address, callback) {
    -  this.client.addDeviceToInput(this.id, address, callback);
    -};
    -  

    Sets the properties for this instance -Parameters: details

    Input.prototype._setProperties = function (details) {

    Copy the properties to this instance

      var self = this;
    -  Object.keys(details).forEach(function (key) {
    -    self[key] = details[key];
    -  });
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/docs/loggly/search.html b/node_modules/winston/node_modules/loggly/docs/loggly/search.html deleted file mode 100644 index 0a13c0e..0000000 --- a/node_modules/winston/node_modules/loggly/docs/loggly/search.html +++ /dev/null @@ -1,89 +0,0 @@ - search.js

    search.js

    /*
    - * search.js: chainable search functions for Loggly
    - *
    - * (C) 2010 Nodejitsu Inc.
    - * MIT LICENSE
    - *
    - */
    -
    -var qs = require('querystring'),
    -    timespan = require('timespan'),
    -    common = require('./common');

    function Search (query, client, callback) - Chainable search object for Loggly API

    var Search = exports.Search = function (query, client, callback) {
    -  this.query = query;
    -  this.client = client;
    -  
    -  if (!this.baseUrl) {
    -    this.baseUrl = 'search?';
    -  }
    -  

    If we're passed a callback, run immediately.

      if (callback) {
    -    this.callback = callback;
    -    this.run();
    -  }
    -};

    function meta (meta) - Sets the appropriate metadata for this search query: - e.g. ip, inputname

    Search.prototype.meta = function (meta) {
    -  this._meta = meta;
    -  return this;
    -};

    function context (context) - Sets the appropriate context for this search query: - e.g. rows, start, from, until, order, format, fields

    Search.prototype.context = function (context) {
    -  this._context = context;
    -  return this;
    -};

    function run (callback)

    - -

    @callback {function} Continuation to respond to when complete

    - -

    Runs the search query for for this instance with the query, metadata, -context, and other parameters that have been configured on it.

    Search.prototype.run = function (callback) {
    -  var rangeError;
    -  

    Trim the search query

      this.query.trim();
    -  

    Update the callback for this instance if it's passed

      this.callback = callback || this.callback;
    -  if (!this.callback) {
    -    throw new Error('Cannot run search without a callback function.');
    -  }
    -  

    If meta was passed, update the search query appropriately

      if (this._meta) {
    -    this.query += ' ' + qs.unescape(qs.stringify(this._meta, ' ', ':'));
    -  }

    Set the context for the query string

      this._context = this._context || {};
    -  this._context.q = this.query;
    -  this._checkRange();
    -
    -  var self = this, searchOptions = {
    -    uri: this.client.logglyUrl(this.baseUrl + qs.stringify(this._context)),
    -    auth: this.client.config.auth
    -  };
    -  
    -  common.loggly(searchOptions, this.callback, function (res, body) {
    -    self.callback(null, JSON.parse(body));
    -  });
    -  
    -  return this;
    -};

    function _checkRange ()

    - -

    Checks if the range that has been configured for this -instance is valid and updates if it is not.

    Search.prototype._checkRange = function () {
    -  if (!this._context || (!this._context.until && !this._context.from)) {
    -    return;
    -  }
    -  
    -  this._context.until = this._context.until || 'NOW';
    -  this._context.from  = this._context.from  || 'NOW-24HOURS';
    -  
    -  if (!timespan.parseDate(this._context.until)) {
    -    this._context.until = 'NOW';
    -  }
    -  
    -  if (!timespan.parseDate(this._context.from)) {
    -    this._context.from = 'NOW-24HOURS';
    -  }
    -  
    -  if (timespan.fromDates(this._context.from, this._context.until) < 0
    -    || this._context.until === this._context.from) {

    If the length of the timespan for this Search instance is -negative then set it to default values

        this._context.until = 'NOW';
    -    this._context.from = 'NOW-24HOURS';
    -  }
    -  
    -  return this;
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly.js b/node_modules/winston/node_modules/loggly/lib/loggly.js deleted file mode 100644 index e55d2c2..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * loggly.js: Wrapper for node-loggly object - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var loggly = exports; - -// -// Export node-loggly core client APIs -// -loggly.createClient = require('./loggly/core').createClient; -loggly.serialize = require('./loggly/common').serialize; -loggly.Loggly = require('./loggly/core').Loggly; -loggly.Config = require('./loggly/config').Config; - -// -// Export Resources for node-loggly -// -loggly.Input = require('./loggly/input').Input; -loggly.Facet = require('./loggly/facet').Facet; -loggly.Device = require('./loggly/device').Device; -loggly.Search = require('./loggly/search').Search; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/common.js b/node_modules/winston/node_modules/loggly/lib/loggly/common.js deleted file mode 100644 index dae938e..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/common.js +++ /dev/null @@ -1,204 +0,0 @@ -/* - * common.js: Common utility functions for requesting against Loggly APIs - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var util = require('util'), - request = require('request'), - loggly = require('../loggly'); - -var common = exports; - -// -// Failure HTTP Response codes based -// off Loggly specification. -// -var failCodes = common.failCodes = { - 400: "Bad Request", - 401: "Unauthorized", - 403: "Forbidden", - 404: "Not Found", - 409: "Conflict / Duplicate", - 410: "Gone", - 500: "Internal Server Error", - 501: "Not Implemented", - 503: "Throttled" -}; - -// -// Success HTTP Response codes based -// off Loggly specification. -// -var successCodes = common.successCodes = { - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-authoritative information", - 204: "Deleted", -}; - -// -// Core method that actually sends requests to Loggly. -// This method is designed to be flexible w.r.t. arguments -// and continuation passing given the wide range of different -// requests required to fully implement the Loggly API. -// -// Continuations: -// 1. 'callback': The callback passed into every node-loggly method -// 2. 'success': A callback that will only be called on successful requests. -// This is used throughout node-loggly to conditionally -// do post-request processing such as JSON parsing. -// -// Possible Arguments (1 & 2 are equivalent): -// 1. common.loggly('some-fully-qualified-url', auth, callback, success) -// 2. common.loggly('GET', 'some-fully-qualified-url', auth, callback, success) -// 3. common.loggly('DELETE', 'some-fully-qualified-url', auth, callback, success) -// 4. common.loggly({ method: 'POST', uri: 'some-url', body: { some: 'body'} }, callback, success) -// -common.loggly = function () { - var args = Array.prototype.slice.call(arguments), - success = args.pop(), - callback = args.pop(), - requestBody, - headers, - method, - auth, - uri; - - // - // Now that we've popped off the two callbacks - // We can make decisions about other arguments - // - if (args.length == 1) { - if (typeof args[0] === 'string') { - // - // If we got a string assume that it's the URI - // - method = 'GET'; - uri = args[0]; - } - else { - method = args[0]['method'] || 'GET', - uri = args[0]['uri']; - requestBody = args[0]['body']; - auth = args[0]['auth']; - headers = args[0]['headers']; - } - } - else if (args.length == 2) { - method = 'GET'; - uri = args[0]; - auth = args[1]; - } - else { - method = args[0]; - uri = args[1]; - auth = args[2]; - } - - function onError (err) { - if (callback) { - callback(err); - } - } - - var requestOptions = { - uri: uri, - method: method, - headers: headers || {} - }; - - if (auth) { - requestOptions.headers['authorization'] = 'Basic ' + new Buffer(auth.username + ':' + auth.password).toString('base64'); - } - - if (requestBody) { - requestOptions.body = requestBody; - } - - try { - request(requestOptions, function (err, res, body) { - if (err) { - return onError(err); - } - - var statusCode = res.statusCode.toString(); - if (Object.keys(failCodes).indexOf(statusCode) !== -1) { - return onError((new Error('Loggly Error (' + statusCode + '): ' + failCodes[statusCode]))); - } - - success(res, body); - }); - } - catch (ex) { - onError(ex); - } -}; - -// -// ### function serialize (obj, key) -// #### @obj {Object|literal} Object to serialize -// #### @key {string} **Optional** Optional key represented by obj in a larger object -// Performs simple comma-separated, `key=value` serialization for Loggly when -// logging to non-JSON inputs. -// -common.serialize = function (obj, key) { - if (obj === null) { - obj = 'null'; - } - else if (obj === undefined) { - obj = 'undefined'; - } - else if (obj === false) { - obj = 'false'; - } - - if (typeof obj !== 'object') { - return key ? key + '=' + obj : obj; - } - - var msg = '', - keys = Object.keys(obj), - length = keys.length; - - for (var i = 0; i < length; i++) { - if (Array.isArray(obj[keys[i]])) { - msg += keys[i] + '=[' - - for (var j = 0, l = obj[keys[i]].length; j < l; j++) { - msg += common.serialize(obj[keys[i]][j]); - if (j < l - 1) { - msg += ', '; - } - } - - msg += ']'; - } - else { - msg += common.serialize(obj[keys[i]], keys[i]); - } - - if (i < length - 1) { - msg += ', '; - } - } - - return msg; -}; - -// -// function clone (obj) -// Helper method for deep cloning pure JSON objects -// i.e. JSON objects that are either literals or objects (no Arrays, etc) -// -common.clone = function (obj) { - var clone = {}; - for (var i in obj) { - clone[i] = obj[i] instanceof Object ? common.clone(obj[i]) : obj[i]; - } - - return clone; -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/config.js b/node_modules/winston/node_modules/loggly/lib/loggly/config.js deleted file mode 100644 index 2156ceb..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/config.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - * config.js: Configuration information for your Loggly account. - * This information is only used for require('loggly')./\.+/ methods - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -// -// function createConfig (defaults) -// Creates a new instance of the configuration -// object based on default values -// -exports.createConfig = function (defaults) { - return new Config(defaults); -}; - -// -// Config (defaults) -// Constructor for the Config object -// -var Config = exports.Config = function (defaults) { - if (!defaults.subdomain) { - throw new Error('Subdomain is required to create an instance of Config'); - } - - this.subdomain = defaults.subdomain; - this.json = defaults.json || null; - this.auth = defaults.auth || null; -}; - -Config.prototype = { - get subdomain () { - return this._subdomain; - }, - - set subdomain (value) { - this._subdomain = value; - }, - - get logglyUrl () { - return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; - }, - - get inputUrl () { - return 'https://logs.loggly.com/inputs/'; - } -}; diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/core.js b/node_modules/winston/node_modules/loggly/lib/loggly/core.js deleted file mode 100644 index 9be1553..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/core.js +++ /dev/null @@ -1,211 +0,0 @@ -/* - * core.js: Core functions for accessing Loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var events = require('events'), - qs = require('querystring'), - config = require('./config'), - common = require('./common'), - Search = require('./search').Search, - Facet = require('./facet').Facet, - loggly = require('../loggly'); - -// -// function createClient (options) -// Creates a new instance of a Loggly client. -// -exports.createClient = function (options) { - return new Loggly(config.createConfig(options)); -}; - -// -// Loggly (config) -// Constructor for the Loggly object -// -var Loggly = exports.Loggly = function (config) { - this.config = config; -}; - -// -// function log (callback) -// logs args to input device -// -Loggly.prototype.log = function (inputId, msg, callback) { - var emitter = new (events.EventEmitter)(), - message; - - if (msg instanceof Object) { - message = this.config.json ? JSON.stringify(msg) : common.serialize(msg); - } - else { - message = this.config.json ? JSON.stringify({ message : msg }) : msg; - } - - var logOptions = { - uri: this.config.inputUrl + inputId, - method: 'POST', - body: message, - headers: { - 'Content-Type': this.config.json ? 'application/json' : 'text/plain' - } - }; - - common.loggly(logOptions, callback, function (res, body) { - try { - var result = JSON.parse(body); - if (callback) { - callback(null, result); - } - - emitter.emit('log', result); - } - catch (ex) { - if (callback) { - callback(new Error('Unspecified error from Loggly: ' + ex)); - } - } - }); - - return emitter; -}; - -// -// function search (query, callback) -// Returns a new search object which can be chained -// with options or called directly if @callback is passed -// initially. -// -// Sample Usage: -// -// client.search('404') -// .meta({ ip: '127.0.0.1' }) -// .context({ rows: 100 }) -// .run(function () { /* ... */ }); -// -Loggly.prototype.search = function (query, callback) { - return new Search(query, this, callback); -}; - -// -// function facet (facet, query, [options], callback) -// Performs a facet search against loggly with the -// specified facet, query and options. -// -Loggly.prototype.facet = function (facet, query, callback) { - return new Facet(facet, query, this, callback); -}; - - -// -// function getInputs ([raw], callback) -// Returns a list of all inputs for the authenicated account -// -Loggly.prototype.getInputs = function () { - var self = this, - args = Array.prototype.slice.call(arguments), - callback = args.pop(), - raw = args.length > 0 ? args[0] : false; - - common.loggly(this.logglyUrl('inputs'), this.config.auth, callback, function (res, body) { - var inputs = [], - results = JSON.parse(body); - - if (!raw) { - results.forEach(function (result) { - inputs.push(new (loggly.Input)(self, result)); - }); - - return callback(null, inputs); - } - - callback(null, results); - }); -}; - -// -// function getInput (name, callback) -// Returns the input with the specified name -// -Loggly.prototype.getInput = function (name, callback) { - var self = this; - this.getInputs(true, function (err, results) { - if (err) { - return callback(err); - } - - var matches = results.filter(function (r) { return r.name === name }), - input = null; - - if (matches.length > 0) { - input = new (loggly.Input)(self, matches[0]); - } - - callback(null, input); - }); -}; - -// -// function addDevice (inputId, address, callback) -// Adds the device at address to the input specified by inputId -// -Loggly.prototype.addDeviceToInput = function (inputId, address, callback) { - var addOptions = { - uri: this.logglyUrl('devices'), - auth: this.config.auth, - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: qs.stringify({ 'input_id': inputId, 'ip': address }).replace('"', '') - }; - - common.loggly(addOptions, callback, function (res, body) { - callback(null, res); - }); -}; - -// -// function addDevice (inputId, callback) -// Adds the calling device to the input -// -Loggly.prototype.addDevice = function (inputId, callback) { - // - // Remark: This is not fully implemented yet - // - callback(new Error('Not Implemented Yet...')); - - //common.loggly(this.logglyUrl('inputs', inputId, 'adddevice'), this.config.auth, callback, function (res, body) { - //}); -}; - -// -// function getDevices (callback) -// Returns a list of all devices for the authenicated account -// -Loggly.prototype.getDevices = function (callback) { - var self = this; - common.loggly(this.logglyUrl('devices'), this.config.auth, callback, function (res, body) { - var results = JSON.parse(body), - devices = []; - - results.forEach(function (result) { - devices.push(new (loggly.Device)(self, result)); - }); - - callback(null, devices); - }); -}; - -// -// function logglyUrl ([path, to, resource]) -// Helper method that concats the string params into a url -// to request against a loggly serverUrl. -// -Loggly.prototype.logglyUrl = function (/* path, to, resource */) { - var args = Array.prototype.slice.call(arguments); - return [this.config.logglyUrl].concat(args).join('/'); -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/device.js b/node_modules/winston/node_modules/loggly/lib/loggly/device.js deleted file mode 100644 index a06d74a..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/device.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * device.js: Instance of a single Loggly device - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var Device = exports.Device = function (client, details) { - if (!details) throw new Error("Device must be constructed with at least basic details.") - - this.client = client; - this._setProperties(details); -}; - -Device.prototype.addToInput = function (inputId, callback) { - this.client.addDeviceToInput(inputId, this.id, callback); -}; - -// -// Sets the properties for this instance -// Parameters: details -// -Device.prototype._setProperties = function (details) { - // Copy the properties to this instance - var self = this; - Object.keys(details).forEach(function (key) { - self[key] = details[key]; - }); -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/facet.js b/node_modules/winston/node_modules/loggly/lib/loggly/facet.js deleted file mode 100644 index a17abf9..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/facet.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * facet.js: Chainable search functions for Loggly facet searches. - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var util = require('util'), - Search = require('./search').Search; - -// -// function Facet (facet, query, client, callback) -// Chainable facet search object for Loggly API -// -var Facet = exports.Facet = function (facet, query, client, callback) { - if (['date', 'ip', 'input'].indexOf(facet) === -1) { - var error = new Error('Cannot search with unknown facet: ' + facet); - - if (callback) { - return callback(error); - } - else { - throw error; - } - } - - // - // Set the baseUrl to be facet/:facet? - // - this.baseUrl = ['facets', facet + '?'].join('/'); - - // - // Call the base constructor. - // - Search.call(this, query, client, callback); -}; - -// -// Inherit from `loggly.Search`. -// -util.inherits(Facet, Search); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/input.js b/node_modules/winston/node_modules/loggly/lib/loggly/input.js deleted file mode 100644 index 1e02b85..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/input.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - * input.js: Instance of a single Loggly input - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var Input = exports.Input = function (client, details) { - if (!details) { - throw new Error("Input must be constructed with at least basic details."); - } - - this.client = client; - this._setProperties(details); -}; - -Input.prototype.log = function (msg, callback) { - return this.client.log(this.input_token, msg, callback); -}; - -Input.prototype.addDevice = function (address, callback) { - this.client.addDeviceToInput(this.id, address, callback); -}; - -// -// Sets the properties for this instance -// Parameters: details -// -Input.prototype._setProperties = function (details) { - // Copy the properties to this instance - var self = this; - Object.keys(details).forEach(function (key) { - self[key] = details[key]; - }); -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/lib/loggly/search.js b/node_modules/winston/node_modules/loggly/lib/loggly/search.js deleted file mode 100644 index 09dd437..0000000 --- a/node_modules/winston/node_modules/loggly/lib/loggly/search.js +++ /dev/null @@ -1,130 +0,0 @@ -/* - * search.js: chainable search functions for Loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var qs = require('querystring'), - timespan = require('timespan'), - common = require('./common'); - -// -// function Search (query, client, callback) -// Chainable search object for Loggly API -// -var Search = exports.Search = function (query, client, callback) { - this.query = query; - this.client = client; - - if (!this.baseUrl) { - this.baseUrl = 'search?'; - } - - // - // If we're passed a callback, run immediately. - // - if (callback) { - this.callback = callback; - this.run(); - } -}; - -// -// function meta (meta) -// Sets the appropriate metadata for this search query: -// e.g. ip, inputname -// -Search.prototype.meta = function (meta) { - this._meta = meta; - return this; -}; - -// -// function context (context) -// Sets the appropriate context for this search query: -// e.g. rows, start, from, until, order, format, fields -// -Search.prototype.context = function (context) { - this._context = context; - return this; -}; - -// -// ### function run (callback) -// #### @callback {function} Continuation to respond to when complete -// Runs the search query for for this instance with the query, metadata, -// context, and other parameters that have been configured on it. -// -Search.prototype.run = function (callback) { - var rangeError; - - // - // Trim the search query - // - this.query.trim(); - - // - // Update the callback for this instance if it's passed - // - this.callback = callback || this.callback; - if (!this.callback) { - throw new Error('Cannot run search without a callback function.'); - } - - // If meta was passed, update the search query appropriately - if (this._meta) { - this.query += ' ' + qs.unescape(qs.stringify(this._meta, ' ', ':')); - } - - // Set the context for the query string - this._context = this._context || {}; - this._context.q = this.query; - this._checkRange(); - - var self = this, searchOptions = { - uri: this.client.logglyUrl(this.baseUrl + qs.stringify(this._context)), - auth: this.client.config.auth - }; - - common.loggly(searchOptions, this.callback, function (res, body) { - self.callback(null, JSON.parse(body)); - }); - - return this; -}; - -// -// ### function _checkRange () -// Checks if the range that has been configured for this -// instance is valid and updates if it is not. -// -Search.prototype._checkRange = function () { - if (!this._context || (!this._context.until && !this._context.from)) { - return; - } - - this._context.until = this._context.until || 'NOW'; - this._context.from = this._context.from || 'NOW-24HOURS'; - - if (!timespan.parseDate(this._context.until)) { - this._context.until = 'NOW'; - } - - if (!timespan.parseDate(this._context.from)) { - this._context.from = 'NOW-24HOURS'; - } - - if (timespan.fromDates(this._context.from, this._context.until) < 0 - || this._context.until === this._context.from) { - // - // If the length of the timespan for this Search instance is - // negative then set it to default values - // - this._context.until = 'NOW'; - this._context.from = 'NOW-24HOURS'; - } - - return this; -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/LICENSE b/node_modules/winston/node_modules/loggly/node_modules/request/LICENSE deleted file mode 100644 index a4a9aee..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and - -You must cause any modified files to carry prominent notices stating that You changed the files; and - -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/README.md b/node_modules/winston/node_modules/loggly/node_modules/request/README.md deleted file mode 100644 index e5839b5..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/README.md +++ /dev/null @@ -1,288 +0,0 @@ -# Request -- Simplified HTTP request method - -## Install - -
    -  npm install request
    -
    - -Or from source: - -
    -  git clone git://github.com/mikeal/request.git 
    -  cd request
    -  npm link
    -
    - -## Super simple to use - -Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default. - -```javascript -var request = require('request'); -request('http://www.google.com', function (error, response, body) { - if (!error && response.statusCode == 200) { - console.log(body) // Print the google web page. - } -}) -``` - -## Streaming - -You can stream any response to a file stream. - -```javascript -request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) -``` - -You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers. - -```javascript -fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) -``` - -Request can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers. - -```javascript -request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) -``` - -Now let's get fancy. - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - if (req.method === 'PUT') { - req.pipe(request.put('http://mysite.com/doodle.png')) - } else if (req.method === 'GET' || req.method === 'HEAD') { - request.get('http://mysite.com/doodle.png').pipe(resp) - } - } -}) -``` - -You can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do: - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - var x = request('http://mysite.com/doodle.png') - req.pipe(x) - x.pipe(resp) - } -}) -``` - -And since pipe() returns the destination stream in node 0.5.x you can do one line proxying :) - -```javascript -req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) -``` - -Also, none of this new functionality conflicts with requests previous features, it just expands them. - -```javascript -var r = request.defaults({'proxy':'http://localproxy.com'}) - -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - r.get('http://google.com/doodle.png').pipe(resp) - } -}) -``` - -You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. - -## OAuth Signing - -```javascript -// Twitter OAuth -var qs = require('querystring') - , oauth = - { callback: 'http://mysite.com/callback/' - , consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - } - , url = 'https://api.twitter.com/oauth/request_token' - ; -request.post({url:url, oauth:oauth}, function (e, r, body) { - // Assume by some stretch of magic you aquired the verifier - var access_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: access_token.oauth_token - , verifier: VERIFIER - , token_secret: access_token.oauth_token_secret - } - , url = 'https://api.twitter.com/oauth/access_token' - ; - request.post({url:url, oauth:oauth}, function (e, r, body) { - var perm_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: perm_token.oauth_token - , token_secret: perm_token.oauth_token_secret - } - , url = 'https://api.twitter.com/1/users/show.json?' - , params = - { screen_name: perm_token.screen_name - , user_id: perm_token.user_id - } - ; - url += qs.stringify(params) - request.get({url:url, oauth:oauth, json:true}, function (e, r, user) { - console.log(user) - }) - }) -}) -``` - - - -### request(options, callback) - -The first argument can be either a url or an options object. The only required option is uri, all others are optional. - -* `uri` || `url` - fully qualified uri or a parsed url object from url.parse() -* `qs` - object containing querystring values to be appended to the uri -* `method` - http method, defaults to GET -* `headers` - http headers, defaults to {} -* `body` - entity body for POST and PUT requests. Must be buffer or string. -* `form` - sets `body` but to querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. -* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. -* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below. -* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true. -* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false. -* `maxRedirects` - the maximum number of redirects to follow, defaults to 10. -* `onResponse` - If true the callback will be fired on the "response" event instead of "end". If a function it will be called on "response" and not effect the regular semantics of the main callback on "end". -* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer. -* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets. -* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool. -* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request -* `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri. -* `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above. -* `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option. -* `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section) - - -The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer. - -## Convenience methods - -There are also shorthand methods for different HTTP METHODs and some other conveniences. - -### request.defaults(options) - -This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it. - -### request.put - -Same as request() but defaults to `method: "PUT"`. - -```javascript -request.put(url) -``` - -### request.post - -Same as request() but defaults to `method: "POST"`. - -```javascript -request.post(url) -``` - -### request.head - -Same as request() but defaults to `method: "HEAD"`. - -```javascript -request.head(url) -``` - -### request.del - -Same as request() but defaults to `method: "DELETE"`. - -```javascript -request.del(url) -``` - -### request.get - -Alias to normal request method for uniformity. - -```javascript -request.get(url) -``` -### request.cookie - -Function that creates a new cookie. - -```javascript -request.cookie('cookie_string_here') -``` -### request.jar - -Function that creates a new cookie jar. - -```javascript -request.jar() -``` - - -## Examples: - -```javascript - var request = require('request') - , rand = Math.floor(Math.random()*100000000).toString() - ; - request( - { method: 'PUT' - , uri: 'http://mikeal.iriscouch.com/testjs/' + rand - , multipart: - [ { 'content-type': 'application/json' - , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) - } - , { body: 'I am an attachment' } - ] - } - , function (error, response, body) { - if(response.statusCode == 201){ - console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) - } else { - console.log('error: '+ response.statusCode) - console.log(body) - } - } - ) -``` -Cookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent). - -```javascript -var request = request.defaults({jar: false}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` - -If you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option: - -```javascript -var j = request.jar() -var request = request.defaults({jar:j}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` -OR - -```javascript -var j = request.jar() -var cookie = request.cookie('your_cookie_here') -j.add(cookie) -request({url: 'http://www.google.com', jar: j}, function () { - request('http://images.google.com') -}) -``` diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/forever.js b/node_modules/winston/node_modules/loggly/node_modules/request/forever.js deleted file mode 100644 index e6531a2..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/forever.js +++ /dev/null @@ -1,84 +0,0 @@ -module.exports = ForeverAgent - -var util = require('util') - , Agent = require('http').Agent - , net = require('net') - -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = host + ':' + port - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - function onIdleError() { - socket.destroy() - } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) - } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy(); - } - }) - self.createConnection = net.createConnection -} -util.inherits(ForeverAgent, Agent) - -ForeverAgent.defaultMinSockets = 5 - -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = host + ':' + port - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} - -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s); - if (index !== -1) { - this.sockets[name].splice(index, 1); - } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name]; - delete this.requests[name]; - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] - } - } - } - - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free'); - } -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/main.js b/node_modules/winston/node_modules/loggly/node_modules/request/main.js deleted file mode 100644 index 6530598..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/main.js +++ /dev/null @@ -1,804 +0,0 @@ -// Copyright 2010-2012 Mikeal Rogers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -var http = require('http') - , https = false - , tls = false - , url = require('url') - , util = require('util') - , stream = require('stream') - , qs = require('querystring') - , mimetypes = require('./mimetypes') - , oauth = require('./oauth') - , uuid = require('./uuid') - , ForeverAgent = require('./forever') - , Cookie = require('./vendor/cookie') - , CookieJar = require('./vendor/cookie/jar') - , cookieJar = new CookieJar - ; - -if (process.logging) { - var log = process.logging('request') -} - -try { - https = require('https') -} catch (e) {} - -try { - tls = require('tls') -} catch (e) {} - -function toBase64 (str) { - return (new Buffer(str || "", "ascii")).toString("base64") -} - -// Hacky fix for pre-0.4.4 https -if (https && !https.Agent) { - https.Agent = function (options) { - http.Agent.call(this, options) - } - util.inherits(https.Agent, http.Agent) - https.Agent.prototype._getConnection = function(host, port, cb) { - var s = tls.connect(port, host, this.options, function() { - // do other checks here? - if (cb) cb() - }) - return s - } -} - -function isReadStream (rs) { - if (rs.readable && rs.path && rs.mode) { - return true - } -} - -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] - }) - return o -} - -var isUrl = /^https?:/ - -var globalPool = {} - -function Request (options) { - stream.Stream.call(this) - this.readable = true - this.writable = true - - if (typeof options === 'string') { - options = {uri:options} - } - - var reserved = Object.keys(Request.prototype) - for (var i in options) { - if (reserved.indexOf(i) === -1) { - this[i] = options[i] - } else { - if (typeof options[i] === 'function') { - delete options[i] - } - } - } - options = copy(options) - - this.init(options) -} -util.inherits(Request, stream.Stream) -Request.prototype.init = function (options) { - var self = this - - if (!options) options = {} - - if (!self.pool) self.pool = globalPool - self.dests = [] - self.__isRequestRequest = true - - // Protect against double callback - if (!self._callback && self.callback) { - self._callback = self.callback - self.callback = function () { - if (self._callbackCalled) return // Print a warning maybe? - self._callback.apply(self, arguments) - self._callbackCalled = true - } - } - - if (self.url) { - // People use this property instead all the time so why not just support it. - self.uri = self.url - delete self.url - } - - if (!self.uri) { - throw new Error("options.uri is a required argument") - } else { - if (typeof self.uri == "string") self.uri = url.parse(self.uri) - } - if (self.proxy) { - if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy) - } - - self._redirectsFollowed = self._redirectsFollowed || 0 - self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10 - self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true - self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false; - if (self.followRedirect || self.followAllRedirects) - self.redirects = self.redirects || [] - - self.headers = self.headers ? copy(self.headers) : {} - - self.setHost = false - if (!self.headers.host) { - self.headers.host = self.uri.hostname - if (self.uri.port) { - if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') && - !(self.uri.port === 443 && self.uri.protocol === 'https:') ) - self.headers.host += (':'+self.uri.port) - } - self.setHost = true - } - - self.jar(options.jar) - - if (!self.uri.pathname) {self.uri.pathname = '/'} - if (!self.uri.port) { - if (self.uri.protocol == 'http:') {self.uri.port = 80} - else if (self.uri.protocol == 'https:') {self.uri.port = 443} - } - - if (self.proxy) { - self.port = self.proxy.port - self.host = self.proxy.hostname - } else { - self.port = self.uri.port - self.host = self.uri.hostname - } - - if (self.onResponse === true) { - self.onResponse = self.callback - delete self.callback - } - - self.clientErrorHandler = function (error) { - if (self._aborted) return - - if (self.setHost) delete self.headers.host - if (self.req._reusedSocket && error.code === 'ECONNRESET') { - self.agent = {addRequest: ForeverAgent.prototype.addRequestNoreuse.bind(self.agent)} - self.start() - self.req.end() - return - } - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer); - self.timeoutTimer = null; - } - self.emit('error', error) - } - if (self.onResponse) self.on('error', function (e) {self.onResponse(e)}) - if (self.callback) self.on('error', function (e) {self.callback(e)}) - - if (options.form) { - self.form(options.form) - } - - if (options.oauth) { - self.oauth(options.oauth) - } - - if (self.uri.auth && !self.headers.authorization) { - self.headers.authorization = "Basic " + toBase64(self.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization']) { - self.headers['proxy-authorization'] = "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - - if (options.qs) self.qs(options.qs) - - if (self.uri.path) { - self.path = self.uri.path - } else { - self.path = self.uri.pathname + (self.uri.search || "") - } - - if (self.path.length === 0) self.path = '/' - - if (self.proxy) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) - - if (options.json) { - self.json(options.json) - } else if (options.multipart) { - self.multipart(options.multipart) - } - - if (self.body) { - var length = 0 - if (!Buffer.isBuffer(self.body)) { - if (Array.isArray(self.body)) { - for (var i = 0; i < self.body.length; i++) { - length += self.body[i].length - } - } else { - self.body = new Buffer(self.body) - length = self.body.length - } - } else { - length = self.body.length - } - if (length) { - self.headers['content-length'] = length - } else { - throw new Error('Argument error, options.body.') - } - } - - var protocol = self.proxy ? self.proxy.protocol : self.uri.protocol - , defaultModules = {'http:':http, 'https:':https} - , httpModules = self.httpModules || {} - ; - self.httpModule = httpModules[protocol] || defaultModules[protocol] - - if (!self.httpModule) throw new Error("Invalid protocol") - - if (self.pool === false) { - self.agent = false - } else { - if (self.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent = self.agent || self.httpModule.globalAgent || self.getAgent(self.host, self.port) - self.agent.maxSockets = self.maxSockets - } - if (self.pool.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent = self.agent || self.httpModule.globalAgent || self.getAgent(self.host, self.port) - self.agent.maxSockets = self.pool.maxSockets - } - } - - self.once('pipe', function (src) { - if (self.ntick) throw new Error("You cannot pipe to this stream after the first nextTick() after creation of the request stream.") - self.src = src - if (isReadStream(src)) { - if (!self.headers['content-type'] && !self.headers['Content-Type']) - self.headers['content-type'] = mimetypes.lookup(src.path.slice(src.path.lastIndexOf('.')+1)) - } else { - if (src.headers) { - for (var i in src.headers) { - if (!self.headers[i]) { - self.headers[i] = src.headers[i] - } - } - } - if (src.method && !self.method) { - self.method = src.method - } - } - - self.on('pipe', function () { - console.error("You have already piped to this stream. Pipeing twice is likely to break the request.") - }) - }) - - process.nextTick(function () { - if (self._aborted) return - - if (self.body) { - if (Array.isArray(self.body)) { - self.body.forEach(function(part) { - self.write(part) - }) - } else { - self.write(self.body) - } - self.end() - } else if (self.requestBodyStream) { - console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.") - self.requestBodyStream.pipe(self) - } else if (!self.src) { - self.headers['content-length'] = 0 - self.end() - } - self.ntick = true - }) -} -Request.prototype.getAgent = function (host, port) { - if (!this.pool[host+':'+port]) { - this.pool[host+':'+port] = new this.httpModule.Agent({host:host, port:port}) - } - return this.pool[host+':'+port] -} -Request.prototype.start = function () { - var self = this - - if (self._aborted) return - - self._started = true - self.method = self.method || 'GET' - self.href = self.uri.href - if (log) log('%method %href', self) - self.req = self.httpModule.request(self, function (response) { - if (self._aborted) return - - self.response = response - response.request = self - - if (self.httpModule === https && - self.strictSSL && - !response.client.authorized) { - var sslErr = response.client.authorizationError - self.emit('error', new Error('SSL Error: '+ sslErr)) - return - } - - if (self.setHost) delete self.headers.host - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer); - self.timeoutTimer = null; - } - - if (response.headers['set-cookie'] && (!self._disableCookies)) { - response.headers['set-cookie'].forEach(function(cookie) { - if (self._jar) self._jar.add(new Cookie(cookie)) - else cookieJar.add(new Cookie(cookie)) - }) - } - - if (response.statusCode >= 300 && response.statusCode < 400 && - (self.followAllRedirects || - (self.followRedirect && (self.method !== 'PUT' && self.method !== 'POST'))) && - response.headers.location) { - if (self._redirectsFollowed >= self.maxRedirects) { - self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop.")) - return - } - self._redirectsFollowed += 1 - - if (!isUrl.test(response.headers.location)) { - response.headers.location = url.resolve(self.uri.href, response.headers.location) - } - self.uri = response.headers.location - self.redirects.push( - { statusCode : response.statusCode - , redirectUri: response.headers.location - } - ) - self.method = 'GET'; // Force all redirects to use GET - delete self.req - delete self.agent - delete self._started - if (self.headers) { - delete self.headers.host - } - if (log) log('Redirect to %uri', self) - self.init() - return // Ignore the rest of the response - } else { - self._redirectsFollowed = self._redirectsFollowed || 0 - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) self.response.emit('end') - }) - - if (self.encoding) { - if (self.dests.length !== 0) { - console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") - } else { - response.setEncoding(self.encoding) - } - } - - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) - - response.on("data", function (chunk) { - self._destdata = true - self.emit("data", chunk) - }) - response.on("end", function (chunk) { - self._ended = true - self.emit("end", chunk) - }) - response.on("close", function () {self.emit("close")}) - - self.emit('response', response) - - if (self.onResponse) { - self.onResponse(null, response) - } - if (self.callback) { - var buffer = [] - var bodyLen = 0 - self.on("data", function (chunk) { - buffer.push(chunk) - bodyLen += chunk.length - }) - self.on("end", function () { - if (self._aborted) return - - if (buffer.length && Buffer.isBuffer(buffer[0])) { - var body = new Buffer(bodyLen) - var i = 0 - buffer.forEach(function (chunk) { - chunk.copy(body, i, 0, chunk.length) - i += chunk.length - }) - if (self.encoding === null) { - response.body = body - } else { - response.body = body.toString() - } - } else if (buffer.length) { - response.body = buffer.join('') - } - - if (self._json) { - try { - response.body = JSON.parse(response.body) - } catch (e) {} - } - - self.callback(null, response, response.body) - }) - } - } - }) - - if (self.timeout && !self.timeoutTimer) { - self.timeoutTimer = setTimeout(function() { - self.req.abort() - var e = new Error("ETIMEDOUT") - e.code = "ETIMEDOUT" - self.emit("error", e) - }, self.timeout) - - // Set additional timeout on socket - in case if remote - // server freeze after sending headers - self.req.setTimeout(self.timeout, function(){ - if (self.req) { - self.req.abort() - var e = new Error("ESOCKETTIMEDOUT") - e.code = "ESOCKETTIMEDOUT" - self.emit("error", e) - } - }); - } - - self.req.on('error', self.clientErrorHandler) - - self.emit('request', self.req) -} - -Request.prototype.abort = function() { - this._aborted = true; - - if (this.req) { - this.req.abort() - } - else if (this.response) { - this.response.abort() - } - - this.emit("abort") -} - -Request.prototype.pipeDest = function (dest) { - var response = this.response - // Called after the response is received - if (dest.headers) { - dest.headers['content-type'] = response.headers['content-type'] - if (response.headers['content-length']) { - dest.headers['content-length'] = response.headers['content-length'] - } - } - if (dest.setHeader) { - for (var i in response.headers) { - dest.setHeader(i, response.headers[i]) - } - dest.statusCode = response.statusCode - } - if (this.pipefilter) this.pipefilter(response, dest) -} - -// Composable API -Request.prototype.setHeader = function (name, value, clobber) { - if (clobber === undefined) clobber = true - if (clobber || !this.headers.hasOwnProperty(name)) this.headers[name] = value - else this.headers[name] += ',' + value - return this -} -Request.prototype.setHeaders = function (headers) { - for (i in headers) {this.setHeader(i, headers[i])} - return this -} -Request.prototype.qs = function (q, clobber) { - var uri = { - protocol: this.uri.protocol, - host: this.uri.host, - pathname: this.uri.pathname, - query: clobber ? q : qs.parse(this.uri.query), - hash: this.uri.hash - }; - if (!clobber) for (var i in q) uri.query[i] = q[i] - - this.uri= url.parse(url.format(uri)) - - return this -} -Request.prototype.form = function (form) { - this.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' - this.body = qs.stringify(form).toString('utf8') - return this -} -Request.prototype.multipart = function (multipart) { - var self = this - self.body = [] - - if (!self.headers['content-type']) { - self.headers['content-type'] = 'multipart/related;boundary="frontier"'; - } else { - self.headers['content-type'] = self.headers['content-type'].split(';')[0] + ';boundary="frontier"'; - } - - if (!multipart.forEach) throw new Error('Argument error, options.multipart.') - - multipart.forEach(function (part) { - var body = part.body - if(!body) throw Error('Body attribute missing in multipart.') - delete part.body - var preamble = '--frontier\r\n' - Object.keys(part).forEach(function(key){ - preamble += key + ': ' + part[key] + '\r\n' - }) - preamble += '\r\n' - self.body.push(new Buffer(preamble)) - self.body.push(new Buffer(body)) - self.body.push(new Buffer('\r\n')) - }) - self.body.push(new Buffer('--frontier--')) - return self -} -Request.prototype.json = function (val) { - this.setHeader('content-type', 'application/json') - this.setHeader('accept', 'application/json') - this._json = true - if (typeof val === 'boolean') { - if (typeof this.body === 'object') this.body = JSON.stringify(this.body) - } else { - this.body = JSON.stringify(val) - } - return this -} -Request.prototype.oauth = function (_oauth) { - var form - if (this.headers['content-type'] && - this.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) === - 'application/x-www-form-urlencoded' - ) { - form = qs.parse(this.body) - } - if (this.uri.query) { - form = qs.parse(this.uri.query) - } - if (!form) form = {} - var oa = {} - for (var i in form) oa[i] = form[i] - for (var i in _oauth) oa['oauth_'+i] = _oauth[i] - if (!oa.oauth_version) oa.oauth_version = '1.0' - if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( (new Date()).getTime() / 1000 ).toString() - if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '') - - oa.oauth_signature_method = 'HMAC-SHA1' - - var consumer_secret = oa.oauth_consumer_secret - delete oa.oauth_consumer_secret - var token_secret = oa.oauth_token_secret - delete oa.oauth_token_secret - - var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname - var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret) - - // oa.oauth_signature = signature - for (var i in form) { - if ( i.slice(0, 'oauth_') in _oauth) { - // skip - } else { - delete oa['oauth_'+i] - } - } - this.headers.authorization = - 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',') - this.headers.authorization += ',oauth_signature="'+oauth.rfc3986(signature)+'"' - return this -} -Request.prototype.jar = function (jar) { - var cookies - - if (this._redirectsFollowed === 0) { - this.originalCookieHeader = this.headers.cookie - } - - if (jar === false) { - // disable cookies - cookies = false; - this._disableCookies = true; - } else if (jar) { - // fetch cookie from the user defined cookie jar - cookies = jar.get({ url: this.uri.href }) - } else { - // fetch cookie from the global cookie jar - cookies = cookieJar.get({ url: this.uri.href }) - } - - if (cookies && cookies.length) { - var cookieString = cookies.map(function (c) { - return c.name + "=" + c.value - }).join("; ") - - if (this.originalCookieHeader) { - // Don't overwrite existing Cookie header - this.headers.cookie = this.originalCookieHeader + '; ' + cookieString - } else { - this.headers.cookie = cookieString - } - } - this._jar = jar - return this -} - - -// Stream API -Request.prototype.pipe = function (dest, opts) { - if (this.response) { - if (this._destdata) { - throw new Error("You cannot pipe after data has been emitted from the response.") - } else if (this._ended) { - throw new Error("You cannot pipe after the response has been ended.") - } else { - stream.Stream.prototype.pipe.call(this, dest, opts) - this.pipeDest(dest) - return dest - } - } else { - this.dests.push(dest) - stream.Stream.prototype.pipe.call(this, dest, opts) - return dest - } -} -Request.prototype.write = function () { - if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.write.apply(this.req, arguments) -} -Request.prototype.end = function (chunk) { - if (chunk) this.write(chunk) - if (!this._started) this.start() - if (!this.req) throw new Error("This request has been piped before http.request() was called.") - this.req.end() -} -Request.prototype.pause = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.pause.apply(this.response, arguments) -} -Request.prototype.resume = function () { - if (!this.response) throw new Error("This request has been piped before http.request() was called.") - this.response.resume.apply(this.response, arguments) -} -Request.prototype.destroy = function () { - if (!this._ended) this.end() -} - -// organize params for post, put, head, del -function initParams(uri, options, callback) { - if ((typeof options === 'function') && !callback) callback = options; - if (typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - uri = options.uri; - } - return { uri: uri, options: options, callback: callback }; -} - -function request (uri, options, callback) { - if ((typeof options === 'function') && !callback) callback = options; - if (typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - } - - if (callback) options.callback = callback; - var r = new Request(options) - return r -} - -module.exports = request - -request.defaults = function (options) { - var def = function (method) { - var d = function (uri, opts, callback) { - var params = initParams(uri, opts, callback); - for (var i in options) { - if (params.options[i] === undefined) params.options[i] = options[i] - } - return method(params.uri, params.options, params.callback) - } - return d - } - var de = def(request) - de.get = def(request.get) - de.post = def(request.post) - de.put = def(request.put) - de.head = def(request.head) - de.del = def(request.del) - de.cookie = def(request.cookie) - de.jar = def(request.jar) - return de -} - -request.forever = function (agentOptions, optionsArg) { - var options = {} - if (agentOptions) { - for (option in optionsArg) { - options[option] = optionsArg[option] - } - } - options.agent = new ForeverAgent(agentOptions) - return request.defaults(options) -} - -request.get = request -request.post = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'POST'; - return request(params.uri, params.options, params.callback) -} -request.put = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'PUT' - return request(params.uri, params.options, params.callback) -} -request.head = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'HEAD' - if (params.options.body || params.options.requestBodyStream || params.options.json || params.options.multipart) { - throw new Error("HTTP HEAD requests MUST NOT include a request body.") - } - return request(params.uri, params.options, params.callback) -} -request.del = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'DELETE' - return request(params.uri, params.options, params.callback) -} -request.jar = function () { - return new CookieJar -} -request.cookie = function (str) { - if (str && str.uri) str = str.uri - if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param") - return new Cookie(str) -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js b/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js deleted file mode 100644 index 59b21b4..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js +++ /dev/null @@ -1,152 +0,0 @@ -// from http://github.com/felixge/node-paperboy -exports.types = { - "3gp":"video/3gpp", - "aiff":"audio/x-aiff", - "arj":"application/x-arj-compressed", - "asf":"video/x-ms-asf", - "asx":"video/x-ms-asx", - "au":"audio/ulaw", - "avi":"video/x-msvideo", - "bcpio":"application/x-bcpio", - "ccad":"application/clariscad", - "cod":"application/vnd.rim.cod", - "com":"application/x-msdos-program", - "cpio":"application/x-cpio", - "cpt":"application/mac-compactpro", - "csh":"application/x-csh", - "css":"text/css", - "deb":"application/x-debian-package", - "dl":"video/dl", - "doc":"application/msword", - "drw":"application/drafting", - "dvi":"application/x-dvi", - "dwg":"application/acad", - "dxf":"application/dxf", - "dxr":"application/x-director", - "etx":"text/x-setext", - "ez":"application/andrew-inset", - "fli":"video/x-fli", - "flv":"video/x-flv", - "gif":"image/gif", - "gl":"video/gl", - "gtar":"application/x-gtar", - "gz":"application/x-gzip", - "hdf":"application/x-hdf", - "hqx":"application/mac-binhex40", - "html":"text/html", - "ice":"x-conference/x-cooltalk", - "ico":"image/x-icon", - "ief":"image/ief", - "igs":"model/iges", - "ips":"application/x-ipscript", - "ipx":"application/x-ipix", - "jad":"text/vnd.sun.j2me.app-descriptor", - "jar":"application/java-archive", - "jpeg":"image/jpeg", - "jpg":"image/jpeg", - "js":"text/javascript", - "json":"application/json", - "latex":"application/x-latex", - "lsp":"application/x-lisp", - "lzh":"application/octet-stream", - "m":"text/plain", - "m3u":"audio/x-mpegurl", - "m4v":"video/mp4", - "man":"application/x-troff-man", - "me":"application/x-troff-me", - "midi":"audio/midi", - "mif":"application/x-mif", - "mime":"www/mime", - "mkv":" video/x-matrosk", - "movie":"video/x-sgi-movie", - "mp4":"video/mp4", - "mp41":"video/mp4", - "mp42":"video/mp4", - "mpg":"video/mpeg", - "mpga":"audio/mpeg", - "ms":"application/x-troff-ms", - "mustache":"text/plain", - "nc":"application/x-netcdf", - "oda":"application/oda", - "ogm":"application/ogg", - "pbm":"image/x-portable-bitmap", - "pdf":"application/pdf", - "pgm":"image/x-portable-graymap", - "pgn":"application/x-chess-pgn", - "pgp":"application/pgp", - "pm":"application/x-perl", - "png":"image/png", - "pnm":"image/x-portable-anymap", - "ppm":"image/x-portable-pixmap", - "ppz":"application/vnd.ms-powerpoint", - "pre":"application/x-freelance", - "prt":"application/pro_eng", - "ps":"application/postscript", - "qt":"video/quicktime", - "ra":"audio/x-realaudio", - "rar":"application/x-rar-compressed", - "ras":"image/x-cmu-raster", - "rgb":"image/x-rgb", - "rm":"audio/x-pn-realaudio", - "rpm":"audio/x-pn-realaudio-plugin", - "rtf":"text/rtf", - "rtx":"text/richtext", - "scm":"application/x-lotusscreencam", - "set":"application/set", - "sgml":"text/sgml", - "sh":"application/x-sh", - "shar":"application/x-shar", - "silo":"model/mesh", - "sit":"application/x-stuffit", - "skt":"application/x-koan", - "smil":"application/smil", - "snd":"audio/basic", - "sol":"application/solids", - "spl":"application/x-futuresplash", - "src":"application/x-wais-source", - "stl":"application/SLA", - "stp":"application/STEP", - "sv4cpio":"application/x-sv4cpio", - "sv4crc":"application/x-sv4crc", - "svg":"image/svg+xml", - "swf":"application/x-shockwave-flash", - "tar":"application/x-tar", - "tcl":"application/x-tcl", - "tex":"application/x-tex", - "texinfo":"application/x-texinfo", - "tgz":"application/x-tar-gz", - "tiff":"image/tiff", - "tr":"application/x-troff", - "tsi":"audio/TSP-audio", - "tsp":"application/dsptype", - "tsv":"text/tab-separated-values", - "unv":"application/i-deas", - "ustar":"application/x-ustar", - "vcd":"application/x-cdlink", - "vda":"application/vda", - "vivo":"video/vnd.vivo", - "vrm":"x-world/x-vrml", - "wav":"audio/x-wav", - "wax":"audio/x-ms-wax", - "webm":"video/webm", - "wma":"audio/x-ms-wma", - "wmv":"video/x-ms-wmv", - "wmx":"video/x-ms-wmx", - "wrl":"model/vrml", - "wvx":"video/x-ms-wvx", - "xbm":"image/x-xbitmap", - "xlw":"application/vnd.ms-excel", - "xml":"text/xml", - "xpm":"image/x-xpixmap", - "xwd":"image/x-xwindowdump", - "xyz":"chemical/x-pdb", - "zip":"application/zip" -}; - -exports.lookup = function(ext, defaultType) { - defaultType = defaultType || 'application/octet-stream'; - - return (ext in exports.types) - ? exports.types[ext] - : defaultType; -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js b/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js deleted file mode 100644 index 31b9dc6..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js +++ /dev/null @@ -1,34 +0,0 @@ -var crypto = require('crypto') - , qs = require('querystring') - ; - -function sha1 (key, body) { - return crypto.createHmac('sha1', key).update(body).digest('base64') -} - -function rfc3986 (str) { - return encodeURIComponent(str) - .replace('!','%21') - .replace('*','%2A') - .replace('(','%28') - .replace(')','%29') - .replace("'",'%27') - ; -} - -function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) { - // adapted from https://dev.twitter.com/docs/auth/oauth - var base = - (httpMethod || 'GET') + "&" + - encodeURIComponent( base_uri ) + "&" + - Object.keys(params).sort().map(function (i) { - // big WTF here with the escape + encoding but it's what twitter wants - return escape(rfc3986(i)) + "%3D" + escape(rfc3986(params[i])) - }).join("%26") - var key = consumer_secret + '&' - if (token_secret) key += token_secret - return sha1(key, base) -} - -exports.hmacsign = hmacsign -exports.rfc3986 = rfc3986 \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/package.json b/node_modules/winston/node_modules/loggly/node_modules/request/package.json deleted file mode 100644 index 71eca50..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ "name" : "request" -, "description" : "Simplified HTTP request client." -, "tags" : ["http", "simple", "util", "utility"] -, "version" : "2.9.152" -, "author" : "Mikeal Rogers " -, "repository" : - { "type" : "git" - , "url" : "http://github.com/mikeal/request.git" - } -, "bugs" : - { "url" : "http://github.com/mikeal/request/issues" } -, "engines" : ["node >= 0.3.6"] -, "main" : "./main" -, "scripts": { "test": "node tests/run.js" } -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/googledoodle.png b/node_modules/winston/node_modules/loggly/node_modules/request/tests/googledoodle.png deleted file mode 100644 index f80c9c5..0000000 Binary files a/node_modules/winston/node_modules/loggly/node_modules/request/tests/googledoodle.png and /dev/null differ diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js deleted file mode 100644 index cca7e18..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js +++ /dev/null @@ -1,35 +0,0 @@ -var spawn = require('child_process').spawn - , exitCode = 0 - ; - -var tests = [ - 'test-body.js' - , 'test-cookie.js' - , 'test-cookiejar.js' - , 'test-defaults.js' - , 'test-errors.js' - , 'test-headers.js' - , 'test-httpModule.js' - , 'test-https.js' - , 'test-oauth.js' - , 'test-pipes.js' - , 'test-proxy.js' - , 'test-qs.js' - , 'test-redirect.js' - , 'test-timeout.js' -] - -var next = function () { - if (tests.length === 0) process.exit(exitCode); - - var file = tests.shift() - console.log(file) - var proc = spawn('node', [ 'tests/' + file ]) - proc.stdout.pipe(process.stdout) - proc.stderr.pipe(process.stderr) - proc.on('exit', function (code) { - exitCode += code || 0 - next() - }) -} -next() \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js deleted file mode 100644 index 2e1889f..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js +++ /dev/null @@ -1,75 +0,0 @@ -var fs = require('fs') - , http = require('http') - , path = require('path') - , https = require('https') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - ; - -exports.createServer = function (port) { - port = port || 6767 - var s = http.createServer(function (req, resp) { - s.emit(req.url, req, resp); - }) - s.port = port - s.url = 'http://localhost:'+port - return s; -} - -exports.createSSLServer = function(port) { - port = port || 16767 - - var options = { 'key' : fs.readFileSync(path.join(__dirname, 'ssl', 'test.key')) - , 'cert': fs.readFileSync(path.join(__dirname, 'ssl', 'test.crt')) - } - - var s = https.createServer(options, function (req, resp) { - s.emit(req.url, req, resp); - }) - s.port = port - s.url = 'https://localhost:'+port - return s; -} - -exports.createPostStream = function (text) { - var postStream = new stream.Stream(); - postStream.writeable = true; - postStream.readable = true; - setTimeout(function () {postStream.emit('data', new Buffer(text)); postStream.emit('end')}, 0); - return postStream; -} -exports.createPostValidator = function (text) { - var l = function (req, resp) { - var r = ''; - req.on('data', function (chunk) {r += chunk}) - req.on('end', function () { - if (r !== text) console.log(r, text); - assert.equal(r, text) - resp.writeHead(200, {'content-type':'text/plain'}) - resp.write('OK') - resp.end() - }) - } - return l; -} -exports.createGetResponse = function (text, contentType) { - var l = function (req, resp) { - contentType = contentType || 'text/plain' - resp.writeHead(200, {'content-type':contentType}) - resp.write(text) - resp.end() - } - return l; -} -exports.createChunkResponse = function (chunks, contentType) { - var l = function (req, resp) { - contentType = contentType || 'text/plain' - resp.writeHead(200, {'content-type':contentType}) - chunks.forEach(function (chunk) { - resp.write(chunk) - }) - resp.end() - } - return l; -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.crt b/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.crt deleted file mode 100644 index b357f86..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.crt +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICQzCCAawCCQCO/XWtRFck1jANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJU -SDEQMA4GA1UECBMHQmFuZ2tvazEOMAwGA1UEBxMFU2lsb20xGzAZBgNVBAoTElRo -ZSBSZXF1ZXN0IE1vZHVsZTEYMBYGA1UEAxMPcmVxdWVzdC5leGFtcGxlMB4XDTEx -MTIwMzAyMjkyM1oXDTIxMTEzMDAyMjkyM1owZjELMAkGA1UEBhMCVEgxEDAOBgNV -BAgTB0Jhbmdrb2sxDjAMBgNVBAcTBVNpbG9tMRswGQYDVQQKExJUaGUgUmVxdWVz -dCBNb2R1bGUxGDAWBgNVBAMTD3JlcXVlc3QuZXhhbXBsZTCBnzANBgkqhkiG9w0B -AQEFAAOBjQAwgYkCgYEAwmctddZqlA48+NXs0yOy92DijcQV1jf87zMiYAIlNUto -wghVbTWgJU5r0pdKrD16AptnWJTzKanhItEX8XCCPgsNkq1afgTtJP7rNkwu3xcj -eIMkhJg/ay4ZnkbnhYdsii5VTU5prix6AqWRAhbkBgoA+iVyHyof8wvZyKBoFTMC -AwEAATANBgkqhkiG9w0BAQUFAAOBgQB6BybMJbpeiABgihDfEVBcAjDoQ8gUMgwV -l4NulugfKTDmArqnR9aPd4ET5jX5dkMP4bwCHYsvrcYDeWEQy7x5WWuylOdKhua4 -L4cEi2uDCjqEErIG3cc1MCOk6Cl6Ld6tkIzQSf953qfdEACRytOeUqLNQcrXrqeE -c7U8F6MWLQ== ------END CERTIFICATE----- diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.key b/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.key deleted file mode 100644 index b85810d..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.key +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXgIBAAKBgQDCZy111mqUDjz41ezTI7L3YOKNxBXWN/zvMyJgAiU1S2jCCFVt -NaAlTmvSl0qsPXoCm2dYlPMpqeEi0RfxcII+Cw2SrVp+BO0k/us2TC7fFyN4gySE -mD9rLhmeRueFh2yKLlVNTmmuLHoCpZECFuQGCgD6JXIfKh/zC9nIoGgVMwIDAQAB -AoGBALXFwfUf8vHTSmGlrdZS2AGFPvEtuvldyoxi9K5u8xmdFCvxnOcLsF2RsTHt -Mu5QYWhUpNJoG+IGLTPf7RJdj/kNtEs7xXqWy4jR36kt5z5MJzqiK+QIgiO9UFWZ -fjUb6oeDnTIJA9YFBdYi97MDuL89iU/UK3LkJN3hd4rciSbpAkEA+MCkowF5kSFb -rkOTBYBXZfiAG78itDXN6DXmqb9XYY+YBh3BiQM28oxCeQYyFy6pk/nstnd4TXk6 -V/ryA2g5NwJBAMgRKTY9KvxJWbESeMEFe2iBIV0c26/72Amgi7ZKUCLukLfD4tLF -+WSZdmTbbqI1079YtwaiOVfiLm45Q/3B0eUCQAaQ/0eWSGE+Yi8tdXoVszjr4GXb -G81qBi91DMu6U1It+jNfIba+MPsiHLcZJMVb4/oWBNukN7bD1nhwFWdlnu0CQQCf -Is9WHkdvz2RxbZDxb8verz/7kXXJQJhx5+rZf7jIYFxqX3yvTNv3wf2jcctJaWlZ -fVZwB193YSivcgt778xlAkEAprYUz3jczjF5r2hrgbizPzPDR94tM5BTO3ki2v3w -kbf+j2g7FNAx6kZiVN8XwfLc8xEeUGiPKwtq3ddPDFh17w== ------END RSA PRIVATE KEY----- diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js deleted file mode 100644 index 9d2e188..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js +++ /dev/null @@ -1,95 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetBuffer : - { resp : server.createGetResponse(new Buffer("TESTING!")) - , encoding: null - , expectBody: new Buffer("TESTING!") - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - test.uri = s.url + '/' + i - request(test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) - diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookie.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookie.js deleted file mode 100644 index f17cfb3..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookie.js +++ /dev/null @@ -1,29 +0,0 @@ -var Cookie = require('../vendor/cookie') - , assert = require('assert'); - -var str = 'sid="s543qactge.wKE61E01Bs%2BKhzmxrwrnug="; path=/; httpOnly; expires=Sat, 04 Dec 2010 23:27:28 GMT'; -var cookie = new Cookie(str); - -// test .toString() -assert.equal(cookie.toString(), str); - -// test .path -assert.equal(cookie.path, '/'); - -// test .httpOnly -assert.equal(cookie.httpOnly, true); - -// test .name -assert.equal(cookie.name, 'sid'); - -// test .value -assert.equal(cookie.value, '"s543qactge.wKE61E01Bs%2BKhzmxrwrnug="'); - -// test .expires -assert.equal(cookie.expires instanceof Date, true); - -// test .path default -var cookie = new Cookie('foo=bar', { url: 'http://foo.com/bar' }); -assert.equal(cookie.path, '/bar'); - -console.log('All tests passed'); diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookiejar.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookiejar.js deleted file mode 100644 index 76fcd71..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookiejar.js +++ /dev/null @@ -1,90 +0,0 @@ -var Cookie = require('../vendor/cookie') - , Jar = require('../vendor/cookie/jar') - , assert = require('assert'); - -function expires(ms) { - return new Date(Date.now() + ms).toUTCString(); -} - -// test .get() expiration -(function() { - var jar = new Jar; - var cookie = new Cookie('sid=1234; path=/; expires=' + expires(1000)); - jar.add(cookie); - setTimeout(function(){ - var cookies = jar.get({ url: 'http://foo.com/foo' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], cookie); - setTimeout(function(){ - var cookies = jar.get({ url: 'http://foo.com/foo' }); - assert.equal(cookies.length, 0); - }, 1000); - }, 5); -})(); - -// test .get() path support -(function() { - var jar = new Jar; - var a = new Cookie('sid=1234; path=/'); - var b = new Cookie('sid=1111; path=/foo/bar'); - var c = new Cookie('sid=2222; path=/'); - jar.add(a); - jar.add(b); - jar.add(c); - - // should remove the duplicates - assert.equal(jar.cookies.length, 2); - - // same name, same path, latter prevails - var cookies = jar.get({ url: 'http://foo.com/' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], c); - - // same name, diff path, path specifity prevails, latter prevails - var cookies = jar.get({ url: 'http://foo.com/foo/bar' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], b); - - var jar = new Jar; - var a = new Cookie('sid=1111; path=/foo/bar'); - var b = new Cookie('sid=1234; path=/'); - jar.add(a); - jar.add(b); - - var cookies = jar.get({ url: 'http://foo.com/foo/bar' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], a); - - var cookies = jar.get({ url: 'http://foo.com/' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], b); - - var jar = new Jar; - var a = new Cookie('sid=1111; path=/foo/bar'); - var b = new Cookie('sid=3333; path=/foo/bar'); - var c = new Cookie('pid=3333; path=/foo/bar'); - var d = new Cookie('sid=2222; path=/foo/'); - var e = new Cookie('sid=1234; path=/'); - jar.add(a); - jar.add(b); - jar.add(c); - jar.add(d); - jar.add(e); - - var cookies = jar.get({ url: 'http://foo.com/foo/bar' }); - assert.equal(cookies.length, 2); - assert.equal(cookies[0], b); - assert.equal(cookies[1], c); - - var cookies = jar.get({ url: 'http://foo.com/foo/' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], d); - - var cookies = jar.get({ url: 'http://foo.com/' }); - assert.equal(cookies.length, 1); - assert.equal(cookies[0], e); -})(); - -setTimeout(function() { - console.log('All tests passed'); -}, 1200); diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js deleted file mode 100644 index 6c8b58f..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js +++ /dev/null @@ -1,68 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -s.listen(s.port, function () { - var counter = 0; - s.on('/get', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'GET') - resp.writeHead(200, {'Content-Type': 'text/plain'}); - resp.end('TESTING!'); - }); - - // test get(string, function) - request.defaults({headers:{foo:"bar"}})(s.url + '/get', function (e, r, b){ - if (e) throw e; - assert.deepEqual("TESTING!", b); - counter += 1; - }); - - s.on('/post', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.headers['content-type'], 'application/json'); - assert.equal(req.method, 'POST') - resp.writeHead(200, {'Content-Type': 'application/json'}); - resp.end(JSON.stringify({foo:'bar'})); - }); - - // test post(string, object, function) - request.defaults({headers:{foo:"bar"}}).post(s.url + '/post', {json: true}, function (e, r, b){ - if (e) throw e; - assert.deepEqual('bar', b.foo); - counter += 1; - }); - - s.on('/del', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'DELETE') - resp.writeHead(200, {'Content-Type': 'application/json'}); - resp.end(JSON.stringify({foo:'bar'})); - }); - - // test .del(string, function) - request.defaults({headers:{foo:"bar"}, json:true}).del(s.url + '/del', function (e, r, b){ - if (e) throw e; - assert.deepEqual('bar', b.foo); - counter += 1; - }); - - s.on('/head', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'HEAD') - resp.writeHead(200, {'Content-Type': 'text/plain'}); - resp.end(); - }); - - // test head.(object, function) - request.defaults({headers:{foo:"bar"}}).head({uri: s.url + '/head'}, function (e, r, b){ - if (e) throw e; - counter += 1; - console.log(counter.toString() + " tests passed.") - s.close() - }); - -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-errors.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-errors.js deleted file mode 100644 index 1986a59..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-errors.js +++ /dev/null @@ -1,37 +0,0 @@ -var server = require('./server') - , events = require('events') - , assert = require('assert') - , request = require('../main.js') - ; - -var local = 'http://localhost:8888/asdf' - -try { - request({uri:local, body:{}}) - assert.fail("Should have throw") -} catch(e) { - assert.equal(e.message, 'Argument error, options.body.') -} - -try { - request({uri:local, multipart: 'foo'}) - assert.fail("Should have throw") -} catch(e) { - assert.equal(e.message, 'Argument error, options.multipart.') -} - -try { - request({uri:local, multipart: [{}]}) - assert.fail("Should have throw") -} catch(e) { - assert.equal(e.message, 'Body attribute missing in multipart.') -} - -try { - request(local, {multipart: [{}]}) - assert.fail("Should have throw") -} catch(e) { - assert.equal(e.message, 'Body attribute missing in multipart.') -} - -console.log("All tests passed.") diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-headers.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-headers.js deleted file mode 100644 index 31fe3f4..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-headers.js +++ /dev/null @@ -1,52 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - , Cookie = require('../vendor/cookie') - , Jar = require('../vendor/cookie/jar') - , s = server.createServer() - -s.listen(s.port, function () { - var serverUri = 'http://localhost:' + s.port - , numTests = 0 - , numOutstandingTests = 0 - - function createTest(requestObj, serverAssertFn) { - var testNumber = numTests; - numTests += 1; - numOutstandingTests += 1; - s.on('/' + testNumber, function (req, res) { - serverAssertFn(req, res); - res.writeHead(200); - res.end(); - }); - requestObj.url = serverUri + '/' + testNumber - request(requestObj, function (err, res, body) { - assert.ok(!err) - assert.equal(res.statusCode, 200) - numOutstandingTests -= 1 - if (numOutstandingTests === 0) { - console.log(numTests + ' tests passed.') - s.close() - } - }) - } - - // Issue #125: headers.cookie shouldn't be replaced when a cookie jar isn't specified - createTest({headers: {cookie: 'foo=bar'}}, function (req, res) { - assert.ok(req.headers.cookie) - assert.equal(req.headers.cookie, 'foo=bar') - }) - - // Issue #125: headers.cookie + cookie jar - var jar = new Jar() - jar.add(new Cookie('quux=baz')); - createTest({jar: jar, headers: {cookie: 'foo=bar'}}, function (req, res) { - assert.ok(req.headers.cookie) - assert.equal(req.headers.cookie, 'foo=bar; quux=baz') - }) - - // There should be no cookie header when neither headers.cookie nor a cookie jar is specified - createTest({}, function (req, res) { - assert.ok(!req.headers.cookie) - }) -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-httpModule.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-httpModule.js deleted file mode 100644 index 1866de2..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-httpModule.js +++ /dev/null @@ -1,94 +0,0 @@ -var http = require('http') - , https = require('https') - , server = require('./server') - , assert = require('assert') - , request = require('../main.js') - - -var faux_requests_made = {'http':0, 'https':0} -function wrap_request(name, module) { - // Just like the http or https module, but note when a request is made. - var wrapped = {} - Object.keys(module).forEach(function(key) { - var value = module[key]; - - if(key != 'request') - wrapped[key] = value; - else - wrapped[key] = function(options, callback) { - faux_requests_made[name] += 1 - return value.apply(this, arguments) - } - }) - - return wrapped; -} - - -var faux_http = wrap_request('http', http) - , faux_https = wrap_request('https', https) - , plain_server = server.createServer() - , https_server = server.createSSLServer() - - -plain_server.listen(plain_server.port, function() { - plain_server.on('/plain', function (req, res) { - res.writeHead(200) - res.end('plain') - }) - plain_server.on('/to_https', function (req, res) { - res.writeHead(301, {'location':'https://localhost:'+https_server.port + '/https'}) - res.end() - }) - - https_server.listen(https_server.port, function() { - https_server.on('/https', function (req, res) { - res.writeHead(200) - res.end('https') - }) - https_server.on('/to_plain', function (req, res) { - res.writeHead(302, {'location':'http://localhost:'+plain_server.port + '/plain'}) - res.end() - }) - - run_tests() - run_tests({}) - run_tests({'http:':faux_http}) - run_tests({'https:':faux_https}) - run_tests({'http:':faux_http, 'https:':faux_https}) - }) -}) - -function run_tests(httpModules) { - var to_https = 'http://localhost:'+plain_server.port+'/to_https' - var to_plain = 'https://localhost:'+https_server.port+'/to_plain' - - request(to_https, {'httpModules':httpModules}, function (er, res, body) { - assert.ok(!er, 'Bounce to SSL worked') - assert.equal(body, 'https', 'Received HTTPS server body') - done() - }) - - request(to_plain, {'httpModules':httpModules}, function (er, res, body) { - assert.ok(!er, 'Bounce to plaintext server worked') - assert.equal(body, 'plain', 'Received HTTPS server body') - done() - }) -} - - -var passed = 0; -function done() { - passed += 1 - var expected = 10 - - if(passed == expected) { - plain_server.close() - https_server.close() - - assert.equal(faux_requests_made.http, 4, 'Wrapped http module called appropriately') - assert.equal(faux_requests_made.https, 4, 'Wrapped https module called appropriately') - - console.log((expected+2) + ' tests passed.') - } -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js deleted file mode 100644 index df7330b..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js +++ /dev/null @@ -1,86 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - -var s = server.createSSLServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - test.uri = s.url + '/' + i - request(test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-oauth.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-oauth.js deleted file mode 100644 index e9d3290..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-oauth.js +++ /dev/null @@ -1,117 +0,0 @@ -var hmacsign = require('../oauth').hmacsign - , assert = require('assert') - , qs = require('querystring') - , request = require('../main') - ; - -function getsignature (r) { - var sign - r.headers.authorization.slice('OAuth '.length).replace(/,\ /g, ',').split(',').forEach(function (v) { - if (v.slice(0, 'oauth_signature="'.length) === 'oauth_signature="') sign = v.slice('oauth_signature="'.length, -1) - }) - return decodeURIComponent(sign) -} - -// Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth - -var reqsign = hmacsign('POST', 'https://api.twitter.com/oauth/request_token', - { oauth_callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11' - , oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' - , oauth_nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk' - , oauth_signature_method: 'HMAC-SHA1' - , oauth_timestamp: '1272323042' - , oauth_version: '1.0' - }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") - -console.log(reqsign) -console.log('8wUi7m5HFQy76nowoCThusfgB+Q=') -assert.equal(reqsign, '8wUi7m5HFQy76nowoCThusfgB+Q=') - -var accsign = hmacsign('POST', 'https://api.twitter.com/oauth/access_token', - { oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' - , oauth_nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8' - , oauth_signature_method: 'HMAC-SHA1' - , oauth_token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc' - , oauth_timestamp: '1272323047' - , oauth_verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY' - , oauth_version: '1.0' - }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") - -console.log(accsign) -console.log('PUw/dHA4fnlJYM6RhXk5IU/0fCc=') -assert.equal(accsign, 'PUw/dHA4fnlJYM6RhXk5IU/0fCc=') - -var upsign = hmacsign('POST', 'http://api.twitter.com/1/statuses/update.json', - { oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" - , oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" - , oauth_signature_method: "HMAC-SHA1" - , oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" - , oauth_timestamp: "1272325550" - , oauth_version: "1.0" - , status: 'setting up my twitter 私のさえずりを設定する' - }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") - -console.log(upsign) -console.log('yOahq5m0YjDDjfjxHaXEsW9D+X0=') -assert.equal(upsign, 'yOahq5m0YjDDjfjxHaXEsW9D+X0=') - - -var rsign = request.post( - { url: 'https://api.twitter.com/oauth/request_token' - , oauth: - { callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11' - , consumer_key: 'GDdmIQH6jhtmLUypg82g' - , nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk' - , timestamp: '1272323042' - , version: '1.0' - , consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98" - } - }) - -setTimeout(function () { - console.log(getsignature(rsign)) - assert.equal(reqsign, getsignature(rsign)) -}) - -var raccsign = request.post( - { url: 'https://api.twitter.com/oauth/access_token' - , oauth: - { consumer_key: 'GDdmIQH6jhtmLUypg82g' - , nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8' - , signature_method: 'HMAC-SHA1' - , token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc' - , timestamp: '1272323047' - , verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY' - , version: '1.0' - , consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98" - , token_secret: "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA" - } - }) - -setTimeout(function () { - console.log(getsignature(raccsign)) - assert.equal(accsign, getsignature(raccsign)) -}, 1) - -var rupsign = request.post( - { url: 'http://api.twitter.com/1/statuses/update.json' - , oauth: - { consumer_key: "GDdmIQH6jhtmLUypg82g" - , nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" - , signature_method: "HMAC-SHA1" - , token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" - , timestamp: "1272325550" - , version: "1.0" - , consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98" - , token_secret: "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA" - } - , form: {status: 'setting up my twitter 私のさえずりを設定する'} - }) -setTimeout(function () { - console.log(getsignature(rupsign)) - assert.equal(upsign, getsignature(rupsign)) -}, 1) - - - - diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js deleted file mode 100644 index 8354f6d..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js +++ /dev/null @@ -1,92 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetBuffer : - { resp : server.createGetResponse(new Buffer("TESTING!")) - , encoding: null - , expectBody: new Buffer("TESTING!") - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - //test.uri = s.url + '/' + i - request(s.url + '/' + i, test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js deleted file mode 100644 index 1869874..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js +++ /dev/null @@ -1,202 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , fs = require('fs') - , request = require('../main.js') - , path = require('path') - , util = require('util') - ; - -var s = server.createServer(3453); - -function ValidationStream(str) { - this.str = str - this.buf = '' - this.on('data', function (data) { - this.buf += data - }) - this.on('end', function () { - assert.equal(this.str, this.buf) - }) - this.writable = true -} -util.inherits(ValidationStream, stream.Stream) -ValidationStream.prototype.write = function (chunk) { - this.emit('data', chunk) -} -ValidationStream.prototype.end = function (chunk) { - if (chunk) emit('data', chunk) - this.emit('end') -} - -s.listen(s.port, function () { - counter = 0; - - var check = function () { - counter = counter - 1 - if (counter === 0) { - console.log('All tests passed.') - setTimeout(function () { - process.exit(); - }, 500) - } - } - - // Test pipeing to a request object - s.once('/push', server.createPostValidator("mydata")); - - var mydata = new stream.Stream(); - mydata.readable = true - - counter++ - var r1 = request.put({url:'http://localhost:3453/push'}, function () { - check(); - }) - mydata.pipe(r1) - - mydata.emit('data', 'mydata'); - mydata.emit('end'); - - - // Test pipeing from a request object. - s.once('/pull', server.createGetResponse("mypulldata")); - - var mypulldata = new stream.Stream(); - mypulldata.writable = true - - counter++ - request({url:'http://localhost:3453/pull'}).pipe(mypulldata) - - var d = ''; - - mypulldata.write = function (chunk) { - d += chunk; - } - mypulldata.end = function () { - assert.equal(d, 'mypulldata'); - check(); - }; - - - s.on('/cat', function (req, resp) { - if (req.method === "GET") { - resp.writeHead(200, {'content-type':'text/plain-test', 'content-length':4}); - resp.end('asdf') - } else if (req.method === "PUT") { - assert.equal(req.headers['content-type'], 'text/plain-test'); - assert.equal(req.headers['content-length'], 4) - var validate = ''; - - req.on('data', function (chunk) {validate += chunk}) - req.on('end', function () { - resp.writeHead(201); - resp.end(); - assert.equal(validate, 'asdf'); - check(); - }) - } - }) - s.on('/pushjs', function (req, resp) { - if (req.method === "PUT") { - assert.equal(req.headers['content-type'], 'text/javascript'); - check(); - } - }) - s.on('/catresp', function (req, resp) { - request.get('http://localhost:3453/cat').pipe(resp) - }) - s.on('/doodle', function (req, resp) { - if (req.headers['x-oneline-proxy']) { - resp.setHeader('x-oneline-proxy', 'yup') - } - resp.writeHead('200', {'content-type':'image/png'}) - fs.createReadStream(path.join(__dirname, 'googledoodle.png')).pipe(resp) - }) - s.on('/onelineproxy', function (req, resp) { - var x = request('http://localhost:3453/doodle') - req.pipe(x) - x.pipe(resp) - }) - - counter++ - fs.createReadStream(__filename).pipe(request.put('http://localhost:3453/pushjs')) - - counter++ - request.get('http://localhost:3453/cat').pipe(request.put('http://localhost:3453/cat')) - - counter++ - request.get('http://localhost:3453/catresp', function (e, resp, body) { - assert.equal(resp.headers['content-type'], 'text/plain-test'); - assert.equal(resp.headers['content-length'], 4) - check(); - }) - - var doodleWrite = fs.createWriteStream(path.join(__dirname, 'test.png')) - - counter++ - request.get('http://localhost:3453/doodle').pipe(doodleWrite) - - doodleWrite.on('close', function () { - assert.deepEqual(fs.readFileSync(path.join(__dirname, 'googledoodle.png')), fs.readFileSync(path.join(__dirname, 'test.png'))) - check() - }) - - process.on('exit', function () { - fs.unlinkSync(path.join(__dirname, 'test.png')) - }) - - counter++ - request.get({uri:'http://localhost:3453/onelineproxy', headers:{'x-oneline-proxy':'nope'}}, function (err, resp, body) { - assert.equal(resp.headers['x-oneline-proxy'], 'yup') - check() - }) - - s.on('/afterresponse', function (req, resp) { - resp.write('d') - resp.end() - }) - - counter++ - var afterresp = request.post('http://localhost:3453/afterresponse').on('response', function () { - var v = new ValidationStream('d') - afterresp.pipe(v) - v.on('end', check) - }) - - s.on('/forward1', function (req, resp) { - resp.writeHead(302, {location:'/forward2'}) - resp.end() - }) - s.on('/forward2', function (req, resp) { - resp.writeHead('200', {'content-type':'image/png'}) - resp.write('d') - resp.end() - }) - - counter++ - var validateForward = new ValidationStream('d') - validateForward.on('end', check) - request.get('http://localhost:3453/forward1').pipe(validateForward) - - // Test pipe options - s.once('/opts', server.createGetResponse('opts response')); - - var optsStream = new stream.Stream(); - optsStream.writable = true - - var optsData = ''; - optsStream.write = function (buf) { - optsData += buf; - if (optsData === 'opts response') { - setTimeout(check, 10); - } - } - - optsStream.end = function () { - assert.fail('end called') - }; - - counter++ - request({url:'http://localhost:3453/opts'}).pipe(optsStream, { end : false }) -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-proxy.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-proxy.js deleted file mode 100644 index 647157c..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-proxy.js +++ /dev/null @@ -1,39 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , fs = require('fs') - , request = require('../main.js') - , path = require('path') - , util = require('util') - ; - -var port = 6768 - , called = false - , proxiedHost = 'google.com' - ; - -var s = server.createServer(port) -s.listen(port, function () { - s.on('http://google.com/', function (req, res) { - called = true - assert.equal(req.headers.host, proxiedHost) - res.writeHeader(200) - res.end() - }) - request ({ - url: 'http://'+proxiedHost, - proxy: 'http://localhost:'+port - /* - //should behave as if these arguments where passed: - url: 'http://localhost:'+port, - headers: {host: proxiedHost} - //*/ - }, function (err, res, body) { - s.close() - }) -}) - -process.on('exit', function () { - assert.ok(called, 'the request must be made to the proxy server') -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-qs.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-qs.js deleted file mode 100644 index 1aac22b..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-qs.js +++ /dev/null @@ -1,28 +0,0 @@ -var request = request = require('../main.js') - , assert = require('assert') - ; - - -// Test adding a querystring -var req1 = request.get({ uri: 'http://www.google.com', qs: { q : 'search' }}) -setTimeout(function() { - assert.equal('/?q=search', req1.path) -}, 1) - -// Test replacing a querystring value -var req2 = request.get({ uri: 'http://www.google.com?q=abc', qs: { q : 'search' }}) -setTimeout(function() { - assert.equal('/?q=search', req2.path) -}, 1) - -// Test appending a querystring value to the ones present in the uri -var req3 = request.get({ uri: 'http://www.google.com?x=y', qs: { q : 'search' }}) -setTimeout(function() { - assert.equal('/?x=y&q=search', req3.path) -}, 1) - -// Test leaving a querystring alone -var req4 = request.get({ uri: 'http://www.google.com?x=y'}) -setTimeout(function() { - assert.equal('/?x=y', req4.path) -}, 1) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-redirect.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-redirect.js deleted file mode 100644 index 937f1df..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-redirect.js +++ /dev/null @@ -1,123 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - , Cookie = require('../vendor/cookie') - , Jar = require('../vendor/cookie/jar') - -var s = server.createServer() - -s.listen(s.port, function () { - var server = 'http://localhost:' + s.port; - var hits = {} - var passed = 0; - - bouncer(301, 'temp') - bouncer(302, 'perm') - bouncer(302, 'nope') - - function bouncer(code, label) { - var landing = label+'_landing'; - - s.on('/'+label, function (req, res) { - hits[label] = true; - res.writeHead(code, {'location':server + '/'+landing}) - res.end() - }) - - s.on('/'+landing, function (req, res) { - if (req.method !== 'GET') { // We should only accept GET redirects - console.error("Got a non-GET request to the redirect destination URL"); - resp.writeHead(400); - resp.end(); - return; - } - // Make sure the cookie doesn't get included twice, see #139: - assert.equal(req.headers.cookie, 'foo=bar; quux=baz'); - hits[landing] = true; - res.writeHead(200) - res.end(landing) - }) - } - - // Permanent bounce - var jar = new Jar() - jar.add(new Cookie('quux=baz')) - request({uri: server+'/perm', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) { - try { - assert.ok(hits.perm, 'Original request is to /perm') - assert.ok(hits.perm_landing, 'Forward to permanent landing URL') - assert.equal(body, 'perm_landing', 'Got permanent landing content') - passed += 1 - } finally { - done() - } - }) - - // Temporary bounce - request({uri: server+'/temp', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) { - try { - assert.ok(hits.temp, 'Original request is to /temp') - assert.ok(hits.temp_landing, 'Forward to temporary landing URL') - assert.equal(body, 'temp_landing', 'Got temporary landing content') - passed += 1 - } finally { - done() - } - }) - - // Prevent bouncing. - request({uri:server+'/nope', jar: jar, headers: {cookie: 'foo=bar'}, followRedirect:false}, function (er, res, body) { - try { - assert.ok(hits.nope, 'Original request to /nope') - assert.ok(!hits.nope_landing, 'No chasing the redirect') - assert.equal(res.statusCode, 302, 'Response is the bounce itself') - passed += 1 - } finally { - done() - } - }) - - // Should not follow post redirects by default - request.post(server+'/temp', { jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) { - try { - assert.ok(hits.temp, 'Original request is to /temp') - assert.ok(!hits.temp_landing, 'No chasing the redirect when post') - assert.equal(res.statusCode, 301, 'Response is the bounce itself') - passed += 1 - } finally { - done() - } - }) - - // Should follow post redirects when followAllRedirects true - request.post({uri:server+'/temp', followAllRedirects:true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) { - try { - assert.ok(hits.temp, 'Original request is to /temp') - assert.ok(hits.temp_landing, 'Forward to temporary landing URL') - assert.equal(body, 'temp_landing', 'Got temporary landing content') - passed += 1 - } finally { - done() - } - }) - - request.post({uri:server+'/temp', followAllRedirects:false, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) { - try { - assert.ok(hits.temp, 'Original request is to /temp') - assert.ok(!hits.temp_landing, 'No chasing the redirect') - assert.equal(res.statusCode, 301, 'Response is the bounce itself') - passed += 1 - } finally { - done() - } - }) - - var reqs_done = 0; - function done() { - reqs_done += 1; - if(reqs_done == 6) { - console.log(passed + ' tests passed.') - s.close() - } - } -}) diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-timeout.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-timeout.js deleted file mode 100644 index 673f8ad..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-timeout.js +++ /dev/null @@ -1,87 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); -var expectedBody = "waited"; -var remainingTests = 5; - -s.listen(s.port, function () { - // Request that waits for 200ms - s.on('/timeout', function (req, resp) { - setTimeout(function(){ - resp.writeHead(200, {'content-type':'text/plain'}) - resp.write(expectedBody) - resp.end() - }, 200); - }); - - // Scenario that should timeout - var shouldTimeout = { - url: s.url + "/timeout", - timeout:100 - } - - - request(shouldTimeout, function (err, resp, body) { - assert.equal(err.code, "ETIMEDOUT"); - checkDone(); - }) - - - // Scenario that shouldn't timeout - var shouldntTimeout = { - url: s.url + "/timeout", - timeout:300 - } - - request(shouldntTimeout, function (err, resp, body) { - assert.equal(err, null); - assert.equal(expectedBody, body) - checkDone(); - }) - - // Scenario with no timeout set, so shouldn't timeout - var noTimeout = { - url: s.url + "/timeout" - } - - request(noTimeout, function (err, resp, body) { - assert.equal(err); - assert.equal(expectedBody, body) - checkDone(); - }) - - // Scenario with a negative timeout value, should be treated a zero or the minimum delay - var negativeTimeout = { - url: s.url + "/timeout", - timeout:-1000 - } - - request(negativeTimeout, function (err, resp, body) { - assert.equal(err.code, "ETIMEDOUT"); - checkDone(); - }) - - // Scenario with a float timeout value, should be rounded by setTimeout anyway - var floatTimeout = { - url: s.url + "/timeout", - timeout: 100.76 - } - - request(floatTimeout, function (err, resp, body) { - assert.equal(err.code, "ETIMEDOUT"); - checkDone(); - }) - - function checkDone() { - if(--remainingTests == 0) { - s.close(); - console.log("All tests passed."); - } - } -}) - diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/uuid.js b/node_modules/winston/node_modules/loggly/node_modules/request/uuid.js deleted file mode 100644 index 1d83bd5..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/uuid.js +++ /dev/null @@ -1,19 +0,0 @@ -module.exports = function () { - var s = [], itoh = '0123456789ABCDEF'; - - // Make array of random hex digits. The UUID only has 32 digits in it, but we - // allocate an extra items to make room for the '-'s we'll be inserting. - for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10); - - // Conform to RFC-4122, section 4.4 - s[14] = 4; // Set 4 high bits of time_high field to version - s[19] = (s[19] & 0x3) | 0x8; // Specify 2 high bits of clock sequence - - // Convert to hex chars - for (var i = 0; i <36; i++) s[i] = itoh[s[i]]; - - // Insert '-'s - s[8] = s[13] = s[18] = s[23] = '-'; - - return s.join(''); -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/index.js b/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/index.js deleted file mode 100644 index 1eb2eaa..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/index.js +++ /dev/null @@ -1,60 +0,0 @@ -/*! - * Tobi - Cookie - * Copyright(c) 2010 LearnBoost - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var url = require('url'); - -/** - * Initialize a new `Cookie` with the given cookie `str` and `req`. - * - * @param {String} str - * @param {IncomingRequest} req - * @api private - */ - -var Cookie = exports = module.exports = function Cookie(str, req) { - this.str = str; - - // First key is the name - this.name = str.substr(0, str.indexOf('=')).trim(); - - // Map the key/val pairs - str.split(/ *; */).reduce(function(obj, pair){ - var p = pair.indexOf('='); - if(p > 0) - obj[pair.substring(0, p).trim()] = pair.substring(p + 1).trim(); - else - obj[pair.trim()] = true; - return obj; - }, this); - - // Assign value - this.value = this[this.name]; - - // Expires - this.expires = this.expires - ? new Date(this.expires) - : Infinity; - - // Default or trim path - this.path = this.path - ? this.path.trim(): req - ? url.parse(req.url).pathname: '/'; -}; - -/** - * Return the original cookie string. - * - * @return {String} - * @api public - */ - -Cookie.prototype.toString = function(){ - return this.str; -}; diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/jar.js b/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/jar.js deleted file mode 100644 index 34920e0..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/jar.js +++ /dev/null @@ -1,72 +0,0 @@ -/*! -* Tobi - CookieJar -* Copyright(c) 2010 LearnBoost -* MIT Licensed -*/ - -/** -* Module dependencies. -*/ - -var url = require('url'); - -/** -* Initialize a new `CookieJar`. -* -* @api private -*/ - -var CookieJar = exports = module.exports = function CookieJar() { - this.cookies = []; -}; - -/** -* Add the given `cookie` to the jar. -* -* @param {Cookie} cookie -* @api private -*/ - -CookieJar.prototype.add = function(cookie){ - this.cookies = this.cookies.filter(function(c){ - // Avoid duplication (same path, same name) - return !(c.name == cookie.name && c.path == cookie.path); - }); - this.cookies.push(cookie); -}; - -/** -* Get cookies for the given `req`. -* -* @param {IncomingRequest} req -* @return {Array} -* @api private -*/ - -CookieJar.prototype.get = function(req){ - var path = url.parse(req.url).pathname - , now = new Date - , specificity = {}; - return this.cookies.filter(function(cookie){ - if (0 == path.indexOf(cookie.path) && now < cookie.expires - && cookie.path.length > (specificity[cookie.name] || 0)) - return specificity[cookie.name] = cookie.path.length; - }); -}; - -/** -* Return Cookie string for the given `req`. -* -* @param {IncomingRequest} req -* @return {String} -* @api private -*/ - -CookieJar.prototype.cookieString = function(req){ - var cookies = this.get(req); - if (cookies.length) { - return cookies.map(function(cookie){ - return cookie.name + '=' + cookie.value; - }).join('; '); - } -}; diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore b/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore deleted file mode 100644 index e3bc275..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -node_modules/* -npm-debug.log \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md b/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md deleted file mode 100644 index 1effdd2..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md +++ /dev/null @@ -1,15 +0,0 @@ -#VERSION HISTORY - -##2.0 -* [Breaking] Refactored this to work in node.js. Backwards compatibility to existing browser API coming in future 2.x releases. (indexzero) - -## 1.2 -* Added TimeSpan.FromDates Constructor to take two dates - and create a TimeSpan from the difference. (mstum) - -## 1.1 -* Changed naming to follow JavaScript standards (mstum) -* Added Documentation (mstum) - -## 1.0 -* Initial Revision (mstum) diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE b/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE deleted file mode 100644 index 071d8fb..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Michael Stum, Charlie Robbins - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md b/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md deleted file mode 100644 index 2bb9904..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# timespan - -A simple implementation of TimeSpans in Javascript. - -## Installation in node.js - -### Installing npm (node package manager) -``` bash - $ curl http://npmjs.org/install.sh | sh -``` - -### Installing timespan -``` bash - [sudo] npm install timespan -``` - -## Usage -You have two options when creating a new TimeSpan object: either explicitly instantiate it using the TimeSpan constructor function or use a helper method to create from a specific length of time. - -### Using the new constructor - -``` js - var timespan = require('timespan'); - var ts = new timespan.TimeSpan(); -``` - -The constructor takes 5 parameters, all which are optional and which can be used to initialize the TimeSpan to a given value. These parameters are: `milliseconds`, `seconds`, `minutes`, `hours`, `days`. - -``` js - // - // Initializes the TimeSpan to 4 Minutes, 16 Seconds and 0 Milliseconds. - // - var ts = new TimeSpan(0,16,4) - - // - // Initializes the TimeSpan to 3 hours, 4 minutes, 10 seconds and 0 msecs. - // - var ts = new TimeSpan(0,10,64,2); -``` - -### Using Construction Helper Method(s) -You can initialize a new TimeSpan by calling one of these Functions: - -``` js - timespan.FromSeconds(/* seconds */); - timespan.FromMinutes(/* minutes */); - timespan.FromHours(/* hours */); - timespan.FromDays(/* hours */); - - // - // This behaves differently, see below - // - timespan.FromDates(start, end); -``` - -The first four helper methods take a single numeric parameter and create a new TimeSpan instance. e.g. `timespan.FromSeconds(45)` is equivalent to `new TimeSpan(0,45)`. If the parameter is invalid/not a number, it will just be treated as 0 no error will be thrown. - -`timespan.FromDates()` is different as it takes two dates. The TimeSpan will be the difference between these dates. - -If the second date is earlier than the first date, the TimeSpan will have a negative value. You can pass in "true" as the third parameter to force the TimeSpan to be positive always. - -``` js - var date1 = new Date(2010, 3, 1, 10, 10, 5, 0); - var date2 = new Date(2010, 3, 1, 10, 10, 10, 0); - var ts = TimeSpan.FromDates(date2, date1); - var ts2 = TimeSpan.FromDates(date2, date1, true); - - // - // -5, because we put the later date first - // - console.log(ts.totalSeconds()); - - // - // 5, because we passed true as third parameter - // - console.log(ts2.totalSeconds()); -``` - - -### Adding / Subtracting TimeSpans -There are several functions to add or subtract time: - -``` js - ts.addMilliseconds() - ts.addSeconds() - ts.addMinutes() - ts.addHours() - ts.addDays() - ts.subtractMilliseconds() - ts.subtractSeconds() - ts.subtractMinutes() - ts.subtractHours() - ts.subtractDays() -``` - -All these functions take a single numeric parameter. If the parameter is invalid, not a number, or missing it will be ignored and no Error is thrown. - -``` js - var ts = new TimeSpan(); - ts.addSeconds(30); - ts.addMinutes(2); - ts.subtractSeconds(60); - - // - // ts will now be a timespan of 1 minute and 30 seconds - // -``` - -The parameter can be negative to negate the operation `ts.addSeconds(-30)` is equivalent to `ts.subtractSeconds(30)`. - -### Interacting with Other TimeSpan instances -These are the functions that interact with another TimeSpan: - -``` js - ts.add() - ts.subtract() - ts.equals() -``` - -add and subtract add/subtract the other TimeSpan to the current one: - -``` js - var ts = TimeSpan.FromSeconds(30); - var ts2 = TimeSpan.FromMinutes(2); - ts.add(ts2); - - // - // ts is now a TimeSpan of 2 Minutes, 30 Seconds - // ts2 is unchanged - // -``` - -equals checks if two TimeSpans have the same time: - -``` js - var ts = TimeSpan.FromSeconds(30); - var ts2 = TimeSpan.FromSeconds(30); - var eq = ts.equals(ts2); // true - ts2.addSeconds(1); - var eq2 = ts.equals(ts2); // false -``` - -### Retrieving the Value of a TimeSpan -There are two sets of functions to retreive the function of the TimeSpan: those that deal with the full value in various measurements and another that gets the individual components. - -#### Retrieve the full value - -``` js - ts.totalMilliseconds() - ts.totalSeconds() - ts.totalMinutes() - ts.totalHours() - ts.totalDays() -``` - -These functions convert the value to the given format and return it. The result can be a floating point number. These functions take a single parameter roundDown which can be set to true to round the value down to an Integer. - -``` js - var ts = TimeSpan.fromSeconds(90); - console.log(ts.totalMilliseconds()); // 90000 - console.log(ts.totalSeconds()); // 90 - console.log(ts.totalMinutes()); // 1.5 - console.log(ts.totalMinutes(true)); // 1 -``` - -#### Retrieve a component of the TimeSpan - -``` js - ts.milliseconds - ts.seconds - ts.minutes - ts.hours - ts.days -``` - -These functions return a component of the TimeSpan that could be used to represent a clock. - -``` js - var ts = TimeSpan.FromSeconds(90); - console.log(ts.seconds()); // 30 - console.log(ts.minutes()); // 1 -``` - -Basically these value never "overflow" - seconds will only return 0 to 59, hours only 0 to 23 etc. Days could grow infinitely. All of these functions automatically round down the result: - -``` js - var ts = TimeSpan.FromDays(2); - ts.addHours(12); - console.log(ts.days()); // 2 - console.log(ts.hours()); // 12 -``` - -## Remark about Backwards Compatibility -Version 0.2.x was designed to work with [node.js][0] and backwards compatibility to the browser-based usage was not considered a high priority. This will be fixed in future versions, but for now if you need to use this in the browser, you can find the 0.1.x code under `/browser`. - -#### Author: [Michael Stum](http://www.stum.de) -#### Contributors: [Charlie Robbins](http://github.com/indexzero) - -[0]: http://nodejs.org \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js deleted file mode 100644 index bc8149d..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js +++ /dev/null @@ -1,226 +0,0 @@ -/*! -* JavaScript TimeSpan Library -* -* Copyright (c) 2010 Michael Stum, http://www.Stum.de/ -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -/*global window: false */ -"use strict"; -(function () { - // Constructor function, all parameters are optional - var TimeSpan = window.TimeSpan = function (milliseconds, seconds, minutes, hours, days) { - var version = "1.2", - // Millisecond-constants - msecPerSecond = 1000, - msecPerMinute = 60000, - msecPerHour = 3600000, - msecPerDay = 86400000, - // Internally we store the TimeSpan as Milliseconds - msecs = 0, - - // Helper functions - isNumeric = function (input) { - return !isNaN(parseFloat(input)) && isFinite(input); - }; - - // Constructor Logic - if (isNumeric(days)) { - msecs += (days * msecPerDay); - } - if (isNumeric(hours)) { - msecs += (hours * msecPerHour); - } - if (isNumeric(minutes)) { - msecs += (minutes * msecPerMinute); - } - if (isNumeric(seconds)) { - msecs += (seconds * msecPerSecond); - } - if (isNumeric(milliseconds)) { - msecs += milliseconds; - } - - // Addition Functions - this.addMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { - return; - } - msecs += milliseconds; - }; - this.addSeconds = function (seconds) { - if (!isNumeric(seconds)) { - return; - } - msecs += (seconds * msecPerSecond); - }; - this.addMinutes = function (minutes) { - if (!isNumeric(minutes)) { - return; - } - msecs += (minutes * msecPerMinute); - }; - this.addHours = function (hours) { - if (!isNumeric(hours)) { - return; - } - msecs += (hours * msecPerHour); - }; - this.addDays = function (days) { - if (!isNumeric(days)) { - return; - } - msecs += (days * msecPerDay); - }; - - // Subtraction Functions - this.subtractMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { - return; - } - msecs -= milliseconds; - }; - this.subtractSeconds = function (seconds) { - if (!isNumeric(seconds)) { - return; - } - msecs -= (seconds * msecPerSecond); - }; - this.subtractMinutes = function (minutes) { - if (!isNumeric(minutes)) { - return; - } - msecs -= (minutes * msecPerMinute); - }; - this.subtractHours = function (hours) { - if (!isNumeric(hours)) { - return; - } - msecs -= (hours * msecPerHour); - }; - this.subtractDays = function (days) { - if (!isNumeric(days)) { - return; - } - msecs -= (days * msecPerDay); - }; - - // Functions to interact with other TimeSpans - this.isTimeSpan = true; - this.add = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - msecs += otherTimeSpan.totalMilliseconds(); - }; - this.subtract = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - msecs -= otherTimeSpan.totalMilliseconds(); - }; - this.equals = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - return msecs === otherTimeSpan.totalMilliseconds(); - }; - - // Getters - this.totalMilliseconds = function (roundDown) { - var result = msecs; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalSeconds = function (roundDown) { - var result = msecs / msecPerSecond; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalMinutes = function (roundDown) { - var result = msecs / msecPerMinute; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalHours = function (roundDown) { - var result = msecs / msecPerHour; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalDays = function (roundDown) { - var result = msecs / msecPerDay; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - // Return a Fraction of the TimeSpan - this.milliseconds = function () { - return msecs % 1000; - }; - this.seconds = function () { - return Math.floor(msecs / msecPerSecond) % 60; - }; - this.minutes = function () { - return Math.floor(msecs / msecPerMinute) % 60; - }; - this.hours = function () { - return Math.floor(msecs / msecPerHour) % 24; - }; - this.days = function () { - return Math.floor(msecs / msecPerDay); - }; - - // Misc. Functions - this.getVersion = function () { - return version; - }; - }; - - // "Static Constructors" - TimeSpan.FromSeconds = function (seconds) { - return new TimeSpan(0, seconds, 0, 0, 0); - }; - TimeSpan.FromMinutes = function (minutes) { - return new TimeSpan(0, 0, minutes, 0, 0); - }; - TimeSpan.FromHours = function (hours) { - return new TimeSpan(0, 0, 0, hours, 0); - }; - TimeSpan.FromDays = function (days) { - return new TimeSpan(0, 0, 0, 0, days); - }; - TimeSpan.FromDates = function (firstDate, secondDate, forcePositive) { - var differenceMsecs = secondDate.valueOf() - firstDate.valueOf(); - if(forcePositive === true) { - differenceMsecs = Math.abs(differenceMsecs); - } - return new TimeSpan(differenceMsecs, 0, 0, 0, 0); - }; -}()); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js deleted file mode 100644 index 0326cbb..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(function(){var a=window.TimeSpan=function(g,i,h,j,k){var l="1.2",d=1e3,c=6e4,e=3.6e6,f=8.64e7,a=0,b=function(a){return !isNaN(parseFloat(a))&&isFinite(a)};if(b(k))a+=k*f;if(b(j))a+=j*e;if(b(h))a+=h*c;if(b(i))a+=i*d;if(b(g))a+=g;this.addMilliseconds=function(c){if(!b(c))return;a+=c};this.addSeconds=function(c){if(!b(c))return;a+=c*d};this.addMinutes=function(d){if(!b(d))return;a+=d*c};this.addHours=function(c){if(!b(c))return;a+=c*e};this.addDays=function(c){if(!b(c))return;a+=c*f};this.subtractMilliseconds=function(c){if(!b(c))return;a-=c};this.subtractSeconds=function(c){if(!b(c))return;a-=c*d};this.subtractMinutes=function(d){if(!b(d))return;a-=d*c};this.subtractHours=function(c){if(!b(c))return;a-=c*e};this.subtractDays=function(c){if(!b(c))return;a-=c*f};this.isTimeSpan=true;this.add=function(b){if(!b.isTimeSpan)return;a+=b.totalMilliseconds()};this.subtract=function(b){if(!b.isTimeSpan)return;a-=b.totalMilliseconds()};this.equals=function(b){if(!b.isTimeSpan)return;return a===b.totalMilliseconds()};this.totalMilliseconds=function(c){var b=a;if(c===true)b=Math.floor(b);return b};this.totalSeconds=function(c){var b=a/d;if(c===true)b=Math.floor(b);return b};this.totalMinutes=function(d){var b=a/c;if(d===true)b=Math.floor(b);return b};this.totalHours=function(c){var b=a/e;if(c===true)b=Math.floor(b);return b};this.totalDays=function(c){var b=a/f;if(c===true)b=Math.floor(b);return b};this.milliseconds=function(){return a%1e3};this.seconds=function(){return Math.floor(a/d)%60};this.minutes=function(){return Math.floor(a/c)%60};this.hours=function(){return Math.floor(a/e)%24};this.days=function(){return Math.floor(a/f)};this.getVersion=function(){return l}};a.FromSeconds=function(b){return new a(0,b,0,0,0)};a.FromMinutes=function(b){return new a(0,0,b,0,0)};a.FromHours=function(b){return new a(0,0,0,b,0)};a.FromDays=function(b){return new a(0,0,0,0,b)};a.FromDates=function(e,d,c){var b=d.valueOf()-e.valueOf();if(c===true)b=Math.abs(b);return new a(b,0,0,0,0)}})() \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css b/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html b/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html deleted file mode 100644 index 9eb2cc9..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html +++ /dev/null @@ -1,692 +0,0 @@ - time-span.js

    time-span.js

    /*
    -* JavaScript TimeSpan Library
    -*
    -* Copyright (c) 2010 Michael Stum, Charlie Robbins
    -* 
    -* Permission is hereby granted, free of charge, to any person obtaining
    -* a copy of this software and associated documentation files (the
    -* "Software"), to deal in the Software without restriction, including
    -* without limitation the rights to use, copy, modify, merge, publish,
    -* distribute, sublicense, and/or sell copies of the Software, and to
    -* permit persons to whom the Software is furnished to do so, subject to
    -* the following conditions:
    -* 
    -* The above copyright notice and this permission notice shall be
    -* included in all copies or substantial portions of the Software.
    -* 
    -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    -* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    -* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    -* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    -*/

    Time constants

    var msecPerSecond = 1000,
    -    msecPerMinute = 60000,
    -    msecPerHour = 3600000,
    -    msecPerDay = 86400000;

    Timespan Parsers

    var timeSpanWithDays = /^(\d+):(\d+):(\d+):(\d+)(\.\d+)?/,
    -    timeSpanNoDays = /^(\d+):(\d+):(\d+)(\.\d+)?/;

    function TimeSpan (milliseconds, seconds, minutes, hours, days)

    - -

    @milliseconds {Number} Number of milliseconds for this instance.

    - -

    @seconds {Number} Number of seconds for this instance.

    - -

    @minutes {Number} Number of minutes for this instance.

    - -

    @hours {Number} Number of hours for this instance.

    - -

    @days {Number} Number of days for this instance.

    - -

    Constructor function for the TimeSpan object which represents a length -of positive or negative milliseconds componentized into milliseconds, -seconds, hours, and days.

    var TimeSpan = exports.TimeSpan = function (milliseconds, seconds, minutes, hours, days) {
    -  this.msecs = 0;
    -  
    -  if (isNumeric(days)) {
    -    this.msecs += (days * msecPerDay);
    -  }
    -  
    -  if (isNumeric(hours)) {
    -    this.msecs += (hours * msecPerHour);
    -  }
    -  
    -  if (isNumeric(minutes)) {
    -    this.msecs += (minutes * msecPerMinute);
    -  }
    -  
    -  if (isNumeric(seconds)) {
    -    this.msecs += (seconds * msecPerSecond);
    -  }
    -  
    -  if (isNumeric(milliseconds)) {
    -    this.msecs += milliseconds;
    -  }
    -};

    Factory methods

    - -

    Helper methods for creating new TimeSpan objects -from various criteria: milliseconds, seconds, minutes, -hours, days, strings and other TimeSpan instances.

    function fromMilliseconds (milliseconds)

    - -

    @milliseconds {Number} Amount of milliseconds for the new TimeSpan instance.

    - -

    Creates a new TimeSpan instance with the specified milliseconds.

    exports.fromMilliseconds = function (milliseconds) {
    -  if (!isNumeric(milliseconds)) {
    -    return;
    -  }
    -  
    -  return new TimeSpan(milliseconds, 0, 0, 0, 0);
    -}

    function fromSeconds (seconds)

    - -

    @milliseconds {Number} Amount of seconds for the new TimeSpan instance.

    - -

    Creates a new TimeSpan instance with the specified seconds.

    exports.fromSeconds = function (seconds) {
    -  if (!isNumeric(seconds)) {
    -    return;
    -  }
    -  
    -  return new TimeSpan(0, seconds, 0, 0, 0);
    -};

    function fromMinutes (milliseconds)

    - -

    @milliseconds {Number} Amount of minutes for the new TimeSpan instance.

    - -

    Creates a new TimeSpan instance with the specified minutes.

    exports.fromMinutes = function (minutes) {
    -  if (!isNumeric(minutes)) {
    -    return;
    -  }
    -  
    -  return new TimeSpan(0, 0, minutes, 0, 0);
    -};

    function fromHours (hours)

    - -

    @milliseconds {Number} Amount of hours for the new TimeSpan instance.

    - -

    Creates a new TimeSpan instance with the specified hours.

    exports.fromHours = function (hours) {
    -  if (!isNumeric(hours)) {
    -    return;
    -  }
    -  
    -  return new TimeSpan(0, 0, 0, hours, 0);
    -};

    function fromDays (days)

    - -

    @milliseconds {Number} Amount of days for the new TimeSpan instance.

    - -

    Creates a new TimeSpan instance with the specified days.

    exports.fromDays = function (days) {
    -  if (!isNumeric(days)) {
    -    return;
    -  }
    -  
    -  return new TimeSpan(0, 0, 0, 0, days);
    -};

    function parse (str)

    - -

    @str {string} Timespan string to parse.

    - -

    Creates a new TimeSpan instance from the specified -string, str.

    exports.parse = function (str) {
    -  var match, milliseconds;
    -  
    -  function parseMilliseconds (value) {
    -    return value ? parseFloat('0' + value) * 1000 : 0;
    -  }
    -  

    If we match against a full TimeSpan:

      if ((match = str.match(timeSpanWithDays))) {
    -    return new TimeSpan(parseMilliseconds(match[5]), match[4], match[3], match[2], match[1]);
    -  }
    -  

    If we match against a partial TimeSpan:

      if ((match = str.match(timeSpanNoDays))) {
    -    return new TimeSpan(parseMilliseconds(match[4]), match[3], match[2], match[1], 0);
    -  }
    -  
    -  return null;
    -};
    -
    -var months  = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    List of default singular time modifiers and associated -computation algoritm. Assumes in order, smallest to greatest -performing carry forward additiona / subtraction for each -Date-Time component.

    var parsers = {
    -  'milliseconds': {
    -    exp: /(\d+)milli[second]?[s]?/i,
    -    get: function (date) { return date.getMilliseconds(date) },
    -    set: function (val, date) { date.setMilliseconds(val) },
    -    compute: function (delta, date, computed) {
    -      var round = delta > 0 ? Math.floor : Math.ceil;
    -      if (delta) {
    -        computed.seconds += round.call(null, delta / 1000);
    -        computed.milliseconds += delta % 1000;
    -      }
    -      
    -      if (Math.abs(computed.milliseconds) >= 1000) {
    -        computed.seconds += round.call(null, computed.milliseconds / 1000)
    -        computed.milliseconds = computed.milliseconds % 1000;
    -      }
    -
    -      return computed;
    -    }
    -  },
    -  'seconds': {
    -    exp: /(\d+)second[s]?/i,
    -    get: function (date) { return date.getSeconds(date) },
    -    set: function (val, date) { date.setSeconds(val) },
    -    compute: function (delta, date, computed) {
    -      var round = delta > 0 ? Math.floor : Math.ceil;
    -      if (delta) {
    -        computed.minutes += round.call(null, delta / 60);
    -        computed.seconds += delta % 60;
    -      }
    -      
    -      if (Math.abs(computed.seconds) >= 60) {
    -        computed.minutes += round.call(null, computed.seconds / 60);
    -        computed.seconds = computed.seconds % 60; 
    -      }
    -      
    -      return computed;
    -    }
    -  },
    -  'minutes': {
    -    exp: /(\d+)minute[s]?/i,
    -    get: function (date) { return date.getMinutes(date) },
    -    set: function (val, date) { date.setMinutes(val) },
    -    compute: function (delta, date, computed) {
    -      var round = delta > 0 ? Math.floor : Math.ceil;
    -      if (delta) { 
    -        computed.hours += round.call(null, delta / 60);
    -        computed.minutes += delta % 60;
    -      }
    -      
    -      if (Math.abs(computed.minutes) >= 60) {
    -        computed.hours += round.call(null, computed.minutes / 60);
    -        computed.minutes = computed.minutes % 60; 
    -      }
    -      
    -      return computed;
    -    }
    -  },
    -  'hours': {
    -    exp: /(\d+)hour[s]?/i,
    -    get: function (date) { return date.getHours(date) },
    -    set: function (val, date) { date.setHours(val) },
    -    compute: function (delta, date, computed) {
    -      var round = delta > 0 ? Math.floor : Math.ceil;
    -      if (delta) { 
    -        computed.days += round.call(null, delta / 24);
    -        computed.hours += delta % 24;
    -      }
    -      
    -      if (Math.abs(computed.hours) >= 24) {
    -        computed.days += round.call(null, computed.hours / 24);
    -        computed.hours = computed.hours % 24;
    -      }
    -      
    -      return computed;
    -    }
    -  },
    -  'days': {
    -    exp: /(\d+)day[s]?/i,
    -    get: function (date) { return date.getDate(date) },
    -    set: function (val, date) { date.setDate(val) },
    -    compute: function (delta, date, computed) {
    -      var sign     = delta >= 0 ? 1 : -1,
    -          opsign   = delta >= 0 ? -1 : 1,
    -          clean    = 0,
    -          original = delta,
    -          month    = computed.months,
    -          days     = months[month];
    -      
    -      if (delta) {          
    -        while (Math.abs(delta) >= days) {
    -          month += sign * 1;
    -          computed.months += sign * 1;
    -          delta += opsign * days;
    -        
    -          if (month < 0) { month = 11 }
    -          else if (month > 11) { month = 0 }
    -        
    -          days = months[month];
    -        }
    -      
    -        computed.days += (sign * delta);
    -      }
    -      
    -      if (computed.days < 0) {
    -        clean = -1;
    -      }
    -      else if (computed.days > months[computed.months]) {
    -        clean = 1;
    -      }
    -      
    -      if (clean !== 0) {
    -        computed.months += clean;
    -        if (computed.months < 0) { computed.months = 11 }
    -        else if (computed.months > 11) { computed.months = 0 }
    -        computed.days = months[computed.months] + computed.days;
    -      }
    -            
    -      return computed;
    -    }
    -  },
    -  'months': {
    -    exp: /(\d+)month[s]?/i,
    -    get: function (date) { return date.getMonth(date) },
    -    set: function (val, date) { date.setMonth(val) },
    -    compute: function (delta, date, computed) {
    -      var round = delta > 0 ? Math.floor : Math.ceil;
    -      if (delta) { 
    -        computed.years += round.call(null, delta / 12);
    -        computed.months += delta % 12;
    -      }
    -      
    -      if (computed.months > 11) {
    -        computed.years += Math.floor((computed.months + 1) / 12);
    -        computed.months = ((computed.months + 1) % 12) - 1;
    -      }
    -      
    -      return computed;
    -    }
    -  },
    -  'years': {
    -    exp: /(\d+)year[s]?/i,
    -    get: function (date) { return date.getFullYear(date) },
    -    set: function (val, date) { date.setFullYear(val) },
    -    compute: function (delta, date, computed) {
    -      if (delta) { 
    -        computed.years += delta;
    -      }
    -      
    -      return computed;
    -    }
    -  }
    -};

    Compute the list of parser names for -later use.

    var parserNames = Object.keys(parsers);

    function parseDate (str)

    - -

    @str {string} String to parse into a date

    - -

    Parses the specified liberal Date-Time string according to -ISO8601 and:

    - -
      -
    1. 2010-04-03T12:34:15Z+12MINUTES
    2. -
    3. NOW-4HOURS
    4. -
    - -

    Valid modifiers for the more liberal Date-Time string(s):

    - -
    YEAR, YEARS
    -MONTH, MONTHS
    -DAY, DAYS
    -HOUR, HOURS
    -MINUTE, MINUTES
    -SECOND, SECONDS
    -MILLI, MILLIS, MILLISECOND, MILLISECONDS
    -
    exports.parseDate = function (str) {
    -  var simple = Date.parse(str),
    -      iso = '^([^Z]+)',
    -      zulu = 'Z([\\+|\\-])?',
    -      diff = {},
    -      base,
    -      sign,
    -      complex,
    -      inspect,
    -      dateTime,
    -      modifiers;
    -
    -  if (/now/i.test(str)) {
    -    iso = '^(NOW)';
    -    zulu = zulu.replace(/Z/, 'NOW');
    -  }

    If Date string supplied actually conforms -to UTC Time (ISO8601), return a new Date.

      if (!isNaN(simple)) {
    -    return new Date(simple);
    -  }
    -  

    Create the RegExp for the end component -of the target str to parse.

      parserNames.forEach(function (group) {
    -    zulu += '(\\d+[a-zA-Z]+)?';
    -  });
    -  

    Parse the ISO8601 component, and the end -component from the target str.

      dateTime = str.match(new RegExp(iso, 'i'));
    -  modifiers = str.match(new RegExp(zulu, 'i'));
    -  

    If there was no match on either part then -it must be a bad value.

      if (!dateTime || !modifiers) {
    -    return null;
    -  }
    -    

    Create a new Date object from the ISO8601 -component of the target str.

      base = /now/i.test(dateTime[1]) ? Date.now() : Date.parse(dateTime[1]);
    -  complex = new Date(base);
    -  sign = modifiers[1] === '+' ? 1 : -1;
    -  

    Parse the individual component spans (months, years, etc) -from the modifier strings that we parsed from the end -of the target str.

      modifiers.slice(2).filter(Boolean).forEach(function (modifier) {
    -    parserNames.forEach(function (name) {
    -      var match;
    -      if (!(match = modifier.match(parsers[name].exp))) {
    -        return;
    -      }
    -      
    -      diff[name] = sign * parseInt(match[1], 10);
    -    })
    -  });
    -  

    Compute the total diff by iteratively computing -the partial components from smallest to largest.

      var computed = {
    -    milliseconds: complex.getMilliseconds(),
    -    seconds: complex.getSeconds(),
    -    minutes: complex.getMinutes(),
    -    hours: complex.getHours(),
    -    days: complex.getDate(),
    -    months: complex.getMonth(),
    -    years: complex.getFullYear()
    -  };
    -  
    -  parserNames.forEach(function (name) {    
    -    computed = parsers[name].compute(diff[name], complex, computed);
    -  });
    -  
    -  return new Date(
    -    Date.UTC(
    -      computed.years,
    -      computed.months,
    -      computed.days,
    -      computed.hours,
    -      computed.minutes,
    -      computed.seconds,
    -      computed.milliseconds
    -    )
    -  );
    -};

    function fromDates (start, end, abs)

    - -

    @start {Date} Start date of the TimeSpan instance to return

    - -

    @end {Date} End date of the TimeSpan instance to return

    - -

    @abs {boolean} Value indicating to return an absolute value

    - -

    Returns a new TimeSpan instance representing the difference between -the start and end Dates.

    exports.fromDates = function (start, end, abs) {
    -  if (!start instanceof Date) {
    -    start = exports.parseDate(start);
    -  }
    -  
    -  if (!end instanceof Date) {
    -    end = exports.parseDate(end);
    -  }
    -  
    -  var differenceMsecs = end.valueOf() - start.valueOf();
    -  if (abs) {
    -    differenceMsecs = Math.abs(differenceMsecs);
    -  }
    -
    -  return new TimeSpan(differenceMsecs, 0, 0, 0, 0);
    -};

    Module Helpers

    - -

    Module-level helpers for various utilities such as: -instanceOf, parsability, and cloning.

    function test (str)

    - -

    @str {string} String value to test if it is a TimeSpan

    - -

    Returns a value indicating if the specified string, str, -is a parsable TimeSpan value.

    exports.test = function (str) {
    -  return timeSpanWithDays.test(str) || timeSpanNoDays.test(str);
    -};

    function instanceOf (timeSpan)

    - -

    @timeSpan {Object} Object to check TimeSpan quality.

    - -

    Returns a value indicating if the specified timeSpan is -in fact a TimeSpan instance.

    exports.instanceOf = function (timeSpan) {
    -  return timeSpan instanceof TimeSpan;
    -};

    function clone (timeSpan)

    - -

    @timeSpan {TimeSpan} TimeSpan object to clone.

    - -

    Returns a new TimeSpan instance with the same value -as the timeSpan object supplied.

    exports.clone = function (timeSpan) {
    -  if (!(timeSpan instanceof TimeSpan)) {
    -    return;
    -  }
    -  
    -  return exports.fromMilliseconds(timeSpan.totalMilliseconds());
    -};

    Addition

    - -

    Methods for adding TimeSpan instances, -milliseconds, seconds, hours, and days to other -TimeSpan instances.

    function add (timeSpan)

    - -

    @timeSpan {TimeSpan} TimeSpan to add to this instance

    - -

    Adds the specified timeSpan to this instance.

    TimeSpan.prototype.add = function (timeSpan) {
    -  if (!(timeSpan instanceof TimeSpan)) {
    -    return;
    -  }
    -  
    -  this.msecs += timeSpan.totalMilliseconds();
    -};

    function addMilliseconds (milliseconds)

    - -

    @milliseconds {Number} Number of milliseconds to add.

    - -

    Adds the specified milliseconds to this instance.

    TimeSpan.prototype.addMilliseconds = function (milliseconds) {
    -  if (!isNumeric(milliseconds)) {
    -    return;
    -  }
    -  
    -  this.msecs += milliseconds;
    -};

    function addSeconds (seconds)

    - -

    @seconds {Number} Number of seconds to add.

    - -

    Adds the specified seconds to this instance.

    TimeSpan.prototype.addSeconds = function (seconds) {
    -  if (!isNumeric(seconds)) {
    -    return;
    -  }
    -  
    -  this.msecs += (seconds * msecPerSecond);
    -};

    function addMinutes (minutes)

    - -

    @minutes {Number} Number of minutes to add.

    - -

    Adds the specified minutes to this instance.

    TimeSpan.prototype.addMinutes = function (minutes) {
    -  if (!isNumeric(minutes)) {
    -    return;
    -  }
    -  
    -  this.msecs += (minutes * msecPerMinute);
    -};

    function addHours (hours)

    - -

    @hours {Number} Number of hours to add.

    - -

    Adds the specified hours to this instance.

    TimeSpan.prototype.addHours = function (hours) {
    -  if (!isNumeric(hours)) {
    -    return;
    -  }
    -  
    -  this.msecs += (hours * msecPerHour);
    -};

    function addDays (days)

    - -

    @days {Number} Number of days to add.

    - -

    Adds the specified days to this instance.

    TimeSpan.prototype.addDays = function (days) {
    -  if (!isNumeric(days)) {
    -    return;
    -  }
    -  
    -  this.msecs += (days * msecPerDay);
    -};

    Subtraction

    - -

    Methods for subtracting TimeSpan instances, -milliseconds, seconds, hours, and days from other -TimeSpan instances.

    function subtract (timeSpan)

    - -

    @timeSpan {TimeSpan} TimeSpan to subtract from this instance.

    - -

    Subtracts the specified timeSpan from this instance.

    TimeSpan.prototype.subtract = function (timeSpan) {
    -  if (!(timeSpan instanceof TimeSpan)) {
    -    return;
    -  }
    -  
    -  this.msecs -= timeSpan.totalMilliseconds();
    -};

    function subtractMilliseconds (milliseconds)

    - -

    @milliseconds {Number} Number of milliseconds to subtract.

    - -

    Subtracts the specified milliseconds from this instance.

    TimeSpan.prototype.subtractMilliseconds = function (milliseconds) {
    -  if (!isNumeric(milliseconds)) {
    -    return;
    -  }
    -  
    -  this.msecs -= milliseconds;
    -};

    function subtractSeconds (seconds)

    - -

    @seconds {Number} Number of seconds to subtract.

    - -

    Subtracts the specified seconds from this instance.

    TimeSpan.prototype.subtractSeconds = function (seconds) {
    -  if (!isNumeric(seconds)) {
    -    return;
    -  }
    -  
    -  this.msecs -= (seconds * msecPerSecond);
    -};

    function subtractMinutes (minutes)

    - -

    @minutes {Number} Number of minutes to subtract.

    - -

    Subtracts the specified minutes from this instance.

    TimeSpan.prototype.subtractMinutes = function (minutes) {
    -  if (!isNumeric(minutes)) {
    -    return;
    -  }
    -  
    -  this.msecs -= (minutes * msecPerMinute);
    -};

    function subtractHours (hours)

    - -

    @hours {Number} Number of hours to subtract.

    - -

    Subtracts the specified hours from this instance.

    TimeSpan.prototype.subtractHours = function (hours) {
    -  if (!isNumeric(hours)) {
    -    return;
    -  }
    -  
    -  this.msecs -= (hours * msecPerHour);
    -};

    function subtractDays (days)

    - -

    @days {Number} Number of days to subtract.

    - -

    Subtracts the specified days from this instance.

    TimeSpan.prototype.subtractDays = function (days) {
    -  if (!isNumeric(days)) {
    -    return;
    -  }
    -  
    -  this.msecs -= (days * msecPerDay);
    -};

    Getters

    - -

    Methods for retrieving components of a TimeSpan -instance: milliseconds, seconds, minutes, hours, and days.

    function totalMilliseconds (roundDown)

    - -

    @roundDown {boolean} Value indicating if the value should be rounded down.

    - -

    Returns the total number of milliseconds for this instance, rounding down -to the nearest integer if roundDown is set.

    TimeSpan.prototype.totalMilliseconds = function (roundDown) {
    -  var result = this.msecs;
    -  if (roundDown === true) {
    -    result = Math.floor(result);
    -  }
    -  
    -  return result;
    -};

    function totalSeconds (roundDown)

    - -

    @roundDown {boolean} Value indicating if the value should be rounded down.

    - -

    Returns the total number of seconds for this instance, rounding down -to the nearest integer if roundDown is set.

    TimeSpan.prototype.totalSeconds = function (roundDown) {
    -  var result = this.msecs / msecPerSecond;
    -  if (roundDown === true) {
    -    result = Math.floor(result);
    -  }
    -  
    -  return result;
    -};

    function totalMinutes (roundDown)

    - -

    @roundDown {boolean} Value indicating if the value should be rounded down.

    - -

    Returns the total number of minutes for this instance, rounding down -to the nearest integer if roundDown is set.

    TimeSpan.prototype.totalMinutes = function (roundDown) {
    -  var result = this.msecs / msecPerMinute;
    -  if (roundDown === true) {
    -    result = Math.floor(result);
    -  }
    -  
    -  return result;
    -};

    function totalHours (roundDown)

    - -

    @roundDown {boolean} Value indicating if the value should be rounded down.

    - -

    Returns the total number of hours for this instance, rounding down -to the nearest integer if roundDown is set.

    TimeSpan.prototype.totalHours = function (roundDown) {
    -  var result = this.msecs / msecPerHour;
    -  if (roundDown === true) {
    -    result = Math.floor(result);
    -  }
    -  
    -  return result;
    -};

    function totalDays (roundDown)

    - -

    @roundDown {boolean} Value indicating if the value should be rounded down.

    - -

    Returns the total number of days for this instance, rounding down -to the nearest integer if roundDown is set.

    TimeSpan.prototype.totalDays = function (roundDown) {
    -  var result = this.msecs / msecPerDay;
    -  if (roundDown === true) {
    -    result = Math.floor(result);
    -  }
    -  
    -  return result;
    -};

    @milliseconds

    - -

    Returns the length of this TimeSpan instance in milliseconds.

    TimeSpan.prototype.__defineGetter__('milliseconds', function () {
    -  return this.msecs % 1000;
    -});

    @seconds

    - -

    Returns the length of this TimeSpan instance in seconds.

    TimeSpan.prototype.__defineGetter__('seconds', function () {
    -  return Math.floor(this.msecs / msecPerSecond) % 60;
    -});

    @minutes

    - -

    Returns the length of this TimeSpan instance in minutes.

    TimeSpan.prototype.__defineGetter__('minutes', function () {
    -  return Math.floor(this.msecs / msecPerMinute) % 60;
    -});

    @hours

    - -

    Returns the length of this TimeSpan instance in hours.

    TimeSpan.prototype.__defineGetter__('hours', function () {
    -  return Math.floor(this.msecs / msecPerHour) % 24;
    -});

    @days

    - -

    Returns the length of this TimeSpan instance in days.

    TimeSpan.prototype.__defineGetter__('days', function () {
    -  return Math.floor(this.msecs / msecPerDay);
    -});

    Instance Helpers

    - -

    Various help methods for performing utilities -such as equality and serialization

    function equals (timeSpan)

    - -

    @timeSpan {TimeSpan} TimeSpan instance to assert equal

    - -

    Returns a value indicating if the specified timeSpan is equal -in milliseconds to this instance.

    TimeSpan.prototype.equals = function (timeSpan) {
    -  if (!(timeSpan instanceof TimeSpan)) {
    -    return;
    -  }
    -  
    -  return this.msecs === timeSpan.totalMilliseconds();
    -};

    function toString ()

    - -

    Returns a string representation of this TimeSpan -instance according to current format.

    TimeSpan.prototype.toString = function () {
    -  if (!this.format) {
    -    return this._format();
    -  };
    -  
    -  return this.format(this);
    -};

    @private function _format ()

    - -

    Returns the default string representation of this instance.

    TimeSpan.prototype._format = function () {
    -  return [
    -    this.days,
    -    this.hours,
    -    this.minutes,
    -    this.seconds + '.' + this.milliseconds
    -  ].join(':')
    -};

    @private function isNumeric (input)

    - -

    @input {Number} Value to check numeric quality of.

    - -

    Returns a value indicating the numeric quality of the -specified input.

    function isNumeric (input) {
    -  return input && !isNaN(parseFloat(input)) && isFinite(input);
    -};
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js deleted file mode 100644 index 23a9cc8..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js +++ /dev/null @@ -1,827 +0,0 @@ -/* -* JavaScript TimeSpan Library -* -* Copyright (c) 2010 Michael Stum, Charlie Robbins -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -// -// ### Time constants -// -var msecPerSecond = 1000, - msecPerMinute = 60000, - msecPerHour = 3600000, - msecPerDay = 86400000; - -// -// ### Timespan Parsers -// -var timeSpanWithDays = /^(\d+):(\d+):(\d+):(\d+)(\.\d+)?/, - timeSpanNoDays = /^(\d+):(\d+):(\d+)(\.\d+)?/; - -// -// ### function TimeSpan (milliseconds, seconds, minutes, hours, days) -// #### @milliseconds {Number} Number of milliseconds for this instance. -// #### @seconds {Number} Number of seconds for this instance. -// #### @minutes {Number} Number of minutes for this instance. -// #### @hours {Number} Number of hours for this instance. -// #### @days {Number} Number of days for this instance. -// Constructor function for the `TimeSpan` object which represents a length -// of positive or negative milliseconds componentized into milliseconds, -// seconds, hours, and days. -// -var TimeSpan = exports.TimeSpan = function (milliseconds, seconds, minutes, hours, days) { - this.msecs = 0; - - if (isNumeric(days)) { - this.msecs += (days * msecPerDay); - } - - if (isNumeric(hours)) { - this.msecs += (hours * msecPerHour); - } - - if (isNumeric(minutes)) { - this.msecs += (minutes * msecPerMinute); - } - - if (isNumeric(seconds)) { - this.msecs += (seconds * msecPerSecond); - } - - if (isNumeric(milliseconds)) { - this.msecs += milliseconds; - } -}; - -// -// ## Factory methods -// Helper methods for creating new TimeSpan objects -// from various criteria: milliseconds, seconds, minutes, -// hours, days, strings and other `TimeSpan` instances. -// - -// -// ### function fromMilliseconds (milliseconds) -// #### @milliseconds {Number} Amount of milliseconds for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `milliseconds`. -// -exports.fromMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - return new TimeSpan(milliseconds, 0, 0, 0, 0); -} - -// -// ### function fromSeconds (seconds) -// #### @milliseconds {Number} Amount of seconds for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `seconds`. -// -exports.fromSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - return new TimeSpan(0, seconds, 0, 0, 0); -}; - -// -// ### function fromMinutes (milliseconds) -// #### @milliseconds {Number} Amount of minutes for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `minutes`. -// -exports.fromMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - return new TimeSpan(0, 0, minutes, 0, 0); -}; - -// -// ### function fromHours (hours) -// #### @milliseconds {Number} Amount of hours for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `hours`. -// -exports.fromHours = function (hours) { - if (!isNumeric(hours)) { return } - return new TimeSpan(0, 0, 0, hours, 0); -}; - -// -// ### function fromDays (days) -// #### @milliseconds {Number} Amount of days for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `days`. -// -exports.fromDays = function (days) { - if (!isNumeric(days)) { return } - return new TimeSpan(0, 0, 0, 0, days); -}; - -// -// ### function parse (str) -// #### @str {string} Timespan string to parse. -// Creates a new `TimeSpan` instance from the specified -// string, `str`. -// -exports.parse = function (str) { - var match, milliseconds; - - function parseMilliseconds (value) { - return value ? parseFloat('0' + value) * 1000 : 0; - } - - // If we match against a full TimeSpan: - // [days]:[hours]:[minutes]:[seconds].[milliseconds]? - if ((match = str.match(timeSpanWithDays))) { - return new TimeSpan(parseMilliseconds(match[5]), match[4], match[3], match[2], match[1]); - } - - // If we match against a partial TimeSpan: - // [hours]:[minutes]:[seconds].[milliseconds]? - if ((match = str.match(timeSpanNoDays))) { - return new TimeSpan(parseMilliseconds(match[4]), match[3], match[2], match[1], 0); - } - - return null; -}; - -// -// List of default singular time modifiers and associated -// computation algoritm. Assumes in order, smallest to greatest -// performing carry forward additiona / subtraction for each -// Date-Time component. -// -var parsers = { - 'milliseconds': { - exp: /(\d+)milli(?:second)?[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'milliseconds', - next: 'seconds', - max: 1000 - }); - } - }, - 'seconds': { - exp: /(\d+)second[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'seconds', - next: 'minutes', - max: 60 - }); - } - }, - 'minutes': { - exp: /(\d+)minute[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'minutes', - next: 'hours', - max: 60 - }); - } - }, - 'hours': { - exp: /(\d+)hour[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'hours', - next: 'days', - max: 24 - }); - } - }, - 'days': { - exp: /(\d+)day[s]?/i, - compute: function (delta, computed) { - var days = monthDays(computed.months, computed.years), - sign = delta >= 0 ? 1 : -1, - opsign = delta >= 0 ? -1 : 1, - clean = 0; - - function update (months) { - if (months < 0) { - computed.years -= 1; - return 11; - } - else if (months > 11) { - computed.years += 1; - return 0 - } - - return months; - } - - if (delta) { - while (Math.abs(delta) >= days) { - computed.months += sign * 1; - computed.months = update(computed.months); - delta += opsign * days; - days = monthDays(computed.months, computed.years); - } - - computed.days += (opsign * delta); - } - - if (computed.days < 0) { clean = -1 } - else if (computed.days > months[computed.months]) { clean = 1 } - - if (clean === -1 || clean === 1) { - computed.months += clean; - computed.months = update(computed.months); - computed.days = months[computed.months] + computed.days; - } - - return computed; - } - }, - 'months': { - exp: /(\d+)month[s]?/i, - compute: function (delta, computed) { - var round = delta > 0 ? Math.floor : Math.ceil; - if (delta) { - computed.years += round.call(null, delta / 12); - computed.months += delta % 12; - } - - if (computed.months > 11) { - computed.years += Math.floor((computed.months + 1) / 12); - computed.months = ((computed.months + 1) % 12) - 1; - } - - return computed; - } - }, - 'years': { - exp: /(\d+)year[s]?/i, - compute: function (delta, computed) { - if (delta) { computed.years += delta; } - return computed; - } - } -}; - -// -// Compute the list of parser names for -// later use. -// -var parserNames = Object.keys(parsers); - -// -// ### function parseDate (str) -// #### @str {string} String to parse into a date -// Parses the specified liberal Date-Time string according to -// ISO8601 **and**: -// -// 1. `2010-04-03T12:34:15Z+12MINUTES` -// 2. `NOW-4HOURS` -// -// Valid modifiers for the more liberal Date-Time string(s): -// -// YEAR, YEARS -// MONTH, MONTHS -// DAY, DAYS -// HOUR, HOURS -// MINUTE, MINUTES -// SECOND, SECONDS -// MILLI, MILLIS, MILLISECOND, MILLISECONDS -// -exports.parseDate = function (str) { - var dateTime = Date.parse(str), - iso = '^([^Z]+)', - zulu = 'Z([\\+|\\-])?', - diff = {}, - computed, - modifiers, - sign; - - // - // If Date string supplied actually conforms - // to UTC Time (ISO8601), return a new Date. - // - if (!isNaN(dateTime)) { - return new Date(dateTime); - } - - // - // Create the `RegExp` for the end component - // of the target `str` to parse. - // - parserNames.forEach(function (group) { - zulu += '(\\d+[a-zA-Z]+)?'; - }); - - if (/^NOW/i.test(str)) { - // - // If the target `str` is a liberal `NOW-*`, - // then set the base `dateTime` appropriately. - // - dateTime = Date.now(); - zulu = zulu.replace(/Z/, 'NOW'); - } - else { - // - // Parse the `ISO8601` component, and the end - // component from the target `str`. - // - dateTime = str.match(new RegExp(iso, 'i')); - dateTime = Date.parse(dateTime[1]); - } - - // - // If there was no match on either part then - // it must be a bad value. - // - if (!dateTime || !(modifiers = str.match(new RegExp(zulu, 'i')))) { - return null; - } - - // - // Create a new `Date` object from the `ISO8601` - // component of the target `str`. - // - dateTime = new Date(dateTime); - sign = modifiers[1] === '+' ? 1 : -1; - - // - // Create an Object-literal for consistently accessing - // the various components of the computed Date. - // - var computed = { - milliseconds: dateTime.getMilliseconds(), - seconds: dateTime.getSeconds(), - minutes: dateTime.getMinutes(), - hours: dateTime.getHours(), - days: dateTime.getDate(), - months: dateTime.getMonth(), - years: dateTime.getFullYear() - }; - - // - // Parse the individual component spans (months, years, etc) - // from the modifier strings that we parsed from the end - // of the target `str`. - // - modifiers.slice(2).filter(Boolean).forEach(function (modifier) { - parserNames.forEach(function (name) { - var match; - if (!(match = modifier.match(parsers[name].exp))) { - return; - } - - diff[name] = sign * parseInt(match[1], 10); - }) - }); - - // - // Compute the total `diff` by iteratively computing - // the partial components from smallest to largest. - // - parserNames.forEach(function (name) { - computed = parsers[name].compute(diff[name], computed); - }); - - return new Date( - Date.UTC( - computed.years, - computed.months, - computed.days, - computed.hours, - computed.minutes, - computed.seconds, - computed.milliseconds - ) - ); -}; - -// -// ### function fromDates (start, end, abs) -// #### @start {Date} Start date of the `TimeSpan` instance to return -// #### @end {Date} End date of the `TimeSpan` instance to return -// #### @abs {boolean} Value indicating to return an absolute value -// Returns a new `TimeSpan` instance representing the difference between -// the `start` and `end` Dates. -// -exports.fromDates = function (start, end, abs) { - if (typeof start === 'string') { - start = exports.parseDate(start); - } - - if (typeof end === 'string') { - end = exports.parseDate(end); - } - - if (!(start instanceof Date && end instanceof Date)) { - return null; - } - - var differenceMsecs = end.valueOf() - start.valueOf(); - if (abs) { - differenceMsecs = Math.abs(differenceMsecs); - } - - return new TimeSpan(differenceMsecs, 0, 0, 0, 0); -}; - -// -// ## Module Helpers -// Module-level helpers for various utilities such as: -// instanceOf, parsability, and cloning. -// - -// -// ### function test (str) -// #### @str {string} String value to test if it is a TimeSpan -// Returns a value indicating if the specified string, `str`, -// is a parsable `TimeSpan` value. -// -exports.test = function (str) { - return timeSpanWithDays.test(str) || timeSpanNoDays.test(str); -}; - -// -// ### function instanceOf (timeSpan) -// #### @timeSpan {Object} Object to check TimeSpan quality. -// Returns a value indicating if the specified `timeSpan` is -// in fact a `TimeSpan` instance. -// -exports.instanceOf = function (timeSpan) { - return timeSpan instanceof TimeSpan; -}; - -// -// ### function clone (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan object to clone. -// Returns a new `TimeSpan` instance with the same value -// as the `timeSpan` object supplied. -// -exports.clone = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - return exports.fromMilliseconds(timeSpan.totalMilliseconds()); -}; - -// -// ## Addition -// Methods for adding `TimeSpan` instances, -// milliseconds, seconds, hours, and days to other -// `TimeSpan` instances. -// - -// -// ### function add (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan to add to this instance -// Adds the specified `timeSpan` to this instance. -// -TimeSpan.prototype.add = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - this.msecs += timeSpan.totalMilliseconds(); -}; - -// -// ### function addMilliseconds (milliseconds) -// #### @milliseconds {Number} Number of milliseconds to add. -// Adds the specified `milliseconds` to this instance. -// -TimeSpan.prototype.addMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - this.msecs += milliseconds; -}; - -// -// ### function addSeconds (seconds) -// #### @seconds {Number} Number of seconds to add. -// Adds the specified `seconds` to this instance. -// -TimeSpan.prototype.addSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - - this.msecs += (seconds * msecPerSecond); -}; - -// -// ### function addMinutes (minutes) -// #### @minutes {Number} Number of minutes to add. -// Adds the specified `minutes` to this instance. -// -TimeSpan.prototype.addMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - this.msecs += (minutes * msecPerMinute); -}; - -// -// ### function addHours (hours) -// #### @hours {Number} Number of hours to add. -// Adds the specified `hours` to this instance. -// -TimeSpan.prototype.addHours = function (hours) { - if (!isNumeric(hours)) { return } - this.msecs += (hours * msecPerHour); -}; - -// -// ### function addDays (days) -// #### @days {Number} Number of days to add. -// Adds the specified `days` to this instance. -// -TimeSpan.prototype.addDays = function (days) { - if (!isNumeric(days)) { return } - this.msecs += (days * msecPerDay); -}; - -// -// ## Subtraction -// Methods for subtracting `TimeSpan` instances, -// milliseconds, seconds, hours, and days from other -// `TimeSpan` instances. -// - -// -// ### function subtract (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan to subtract from this instance. -// Subtracts the specified `timeSpan` from this instance. -// -TimeSpan.prototype.subtract = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - this.msecs -= timeSpan.totalMilliseconds(); -}; - -// -// ### function subtractMilliseconds (milliseconds) -// #### @milliseconds {Number} Number of milliseconds to subtract. -// Subtracts the specified `milliseconds` from this instance. -// -TimeSpan.prototype.subtractMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - this.msecs -= milliseconds; -}; - -// -// ### function subtractSeconds (seconds) -// #### @seconds {Number} Number of seconds to subtract. -// Subtracts the specified `seconds` from this instance. -// -TimeSpan.prototype.subtractSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - this.msecs -= (seconds * msecPerSecond); -}; - -// -// ### function subtractMinutes (minutes) -// #### @minutes {Number} Number of minutes to subtract. -// Subtracts the specified `minutes` from this instance. -// -TimeSpan.prototype.subtractMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - this.msecs -= (minutes * msecPerMinute); -}; - -// -// ### function subtractHours (hours) -// #### @hours {Number} Number of hours to subtract. -// Subtracts the specified `hours` from this instance. -// -TimeSpan.prototype.subtractHours = function (hours) { - if (!isNumeric(hours)) { return } - this.msecs -= (hours * msecPerHour); -}; - -// -// ### function subtractDays (days) -// #### @days {Number} Number of days to subtract. -// Subtracts the specified `days` from this instance. -// -TimeSpan.prototype.subtractDays = function (days) { - if (!isNumeric(days)) { return } - this.msecs -= (days * msecPerDay); -}; - -// -// ## Getters -// Methods for retrieving components of a `TimeSpan` -// instance: milliseconds, seconds, minutes, hours, and days. -// - -// -// ### function totalMilliseconds (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of milliseconds for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalMilliseconds = function (roundDown) { - var result = this.msecs; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalSeconds (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of seconds for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalSeconds = function (roundDown) { - var result = this.msecs / msecPerSecond; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalMinutes (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of minutes for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalMinutes = function (roundDown) { - var result = this.msecs / msecPerMinute; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalHours (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of hours for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalHours = function (roundDown) { - var result = this.msecs / msecPerHour; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalDays (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of days for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalDays = function (roundDown) { - var result = this.msecs / msecPerDay; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### @milliseconds -// Returns the length of this `TimeSpan` instance in milliseconds. -// -TimeSpan.prototype.__defineGetter__('milliseconds', function () { - return this.msecs % 1000; -}); - -// -// ### @seconds -// Returns the length of this `TimeSpan` instance in seconds. -// -TimeSpan.prototype.__defineGetter__('seconds', function () { - return Math.floor(this.msecs / msecPerSecond) % 60; -}); - -// -// ### @minutes -// Returns the length of this `TimeSpan` instance in minutes. -// -TimeSpan.prototype.__defineGetter__('minutes', function () { - return Math.floor(this.msecs / msecPerMinute) % 60; -}); - -// -// ### @hours -// Returns the length of this `TimeSpan` instance in hours. -// -TimeSpan.prototype.__defineGetter__('hours', function () { - return Math.floor(this.msecs / msecPerHour) % 24; -}); - -// -// ### @days -// Returns the length of this `TimeSpan` instance in days. -// -TimeSpan.prototype.__defineGetter__('days', function () { - return Math.floor(this.msecs / msecPerDay); -}); - -// -// ## Instance Helpers -// Various help methods for performing utilities -// such as equality and serialization -// - -// -// ### function equals (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan instance to assert equal -// Returns a value indicating if the specified `timeSpan` is equal -// in milliseconds to this instance. -// -TimeSpan.prototype.equals = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - return this.msecs === timeSpan.totalMilliseconds(); -}; - -// -// ### function toString () -// Returns a string representation of this `TimeSpan` -// instance according to current `format`. -// -TimeSpan.prototype.toString = function () { - if (!this.format) { return this._format() } - return this.format(this); -}; - -// -// ### @private function _format () -// Returns the default string representation of this instance. -// -TimeSpan.prototype._format = function () { - return [ - this.days, - this.hours, - this.minutes, - this.seconds + '.' + this.milliseconds - ].join(':') -}; - -// -// ### @private function isNumeric (input) -// #### @input {Number} Value to check numeric quality of. -// Returns a value indicating the numeric quality of the -// specified `input`. -// -function isNumeric (input) { - return input && !isNaN(parseFloat(input)) && isFinite(input); -}; - -// -// ### @private function _compute (delta, date, computed, options) -// #### @delta {Number} Channge in this component of the date -// #### @computed {Object} Currently computed date. -// #### @options {Object} Options for the computation -// Performs carry forward addition or subtraction for the -// `options.current` component of the `computed` date, carrying -// it forward to `options.next` depending on the maximum value, -// `options.max`. -// -function _compute (delta, computed, options) { - var current = options.current, - next = options.next, - max = options.max, - round = delta > 0 ? Math.floor : Math.ceil; - - if (delta) { - computed[next] += round.call(null, delta / max); - computed[current] += delta % max; - } - - if (Math.abs(computed[current]) >= max) { - computed[next] += round.call(null, computed[current] / max) - computed[current] = computed[current] % max; - } - - return computed; -} - - -// -// ### @private monthDays (month, year) -// #### @month {Number} Month to get days for. -// #### @year {Number} Year of the month to get days for. -// Returns the number of days in the specified `month` observing -// leap years. -// -var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -function monthDays (month, year) { - if (((year % 100 !== 0 && year % 4 === 0) - || year % 400 === 0) && month === 1) { - return 29; - } - - return months[month]; -} \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json b/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json deleted file mode 100644 index ba99201..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "timespan", - "description": "A JavaScript TimeSpan library for node.js (and soon the browser)", - "version": "2.2.0", - "author": "Michael Stum ", - "contributors": [ - { "name": "Charlie Robbins", "email": "charlie.robbins@gmail.com" } - ], - "repository": { - "type": "git", - "url": "http://github.com/indexzero/timespan.git" - }, - "keywords": ["time", "dates", "utilities", "timespan"], - "devDependencies": { - "vows": ">= 0.5.2" - }, - "main": "./lib/time-span.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.2.0" } -} diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js deleted file mode 100644 index 6f08973..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js +++ /dev/null @@ -1,72 +0,0 @@ -/* - * time-span-test.js: Tests for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var vows = require('vows'), - assert = require('assert'), - timeSpan = require('../lib/time-span'); - -vows.describe('time-span/date-time').addBatch({ - "When using the TimeSpan module": { - "the parseDate() method": { - "when passed a TimeSpan string using ISO8601 with explicit time modifiers": { - "which do not carry over": { - "should return the correct value": function () { - var target = new Date(Date.parse('2010-04-03T10:04:15Z')), - parsed = timeSpan.parseDate('2010-04-03T12:34:15Z-2HOURS30MINUTES'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry under": { - "should return the correct value": function () { - var target = new Date(Date.parse('2010-03-29T12:34:15Z')), - parsed = timeSpan.parseDate('2010-04-01T12:34:15Z-72HOURS'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry under a leap year": { - "should return the correct value": function () { - var target = new Date(Date.parse('2007-03-31T12:00:00Z')), - parsed = timeSpan.parseDate('2010-03-31T12:00:00Z-1096DAYS'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry over": { - "should return the correct value": function () { - var target = new Date(Date.parse('2013-04-03T12:34:15Z')), - parsed = timeSpan.parseDate('2010-04-03T12:34:15Z+2YEARS365DAYS'); - - assert.equal(target.toString(), parsed.toString()); - } - } - }, - "when passed a TimeSpan string using NOW with explicit time modifiers": { - "which do not carry over": { - "should return the correct value": function () { - var now = new Date(Date.now()), - parsed = timeSpan.parseDate('NOW-2HOURS'); - - now.setHours(now.getHours() - 2 - (now.getTimezoneOffset() / 60)); - assert.equal(now.getHours(), parsed.getHours()); - } - }, - "which carry under": { - "should return the correct value": function () { - var now = new Date(Date.now()), - parsed = timeSpan.parseDate('NOW-72HOURS'); - - now.setHours(now.getHours() - 72 - (now.getTimezoneOffset() / 60)); - assert.equal(now.getHours(), parsed.getHours()); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js deleted file mode 100644 index 4a1b84a..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - * helpers.js: Tests helpers for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - timeSpan = require('../lib/time-span') - -function capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -var helpers = exports, - components = ['milliseconds', 'seconds', 'minutes', 'hours', 'days']; - -// -// Tests all of the factory methods for the `TimeSpan` object: -// `fromMilliseconds`, `fromSeconds`, etc. -// -exports.testFactories = function (num) { - var context = {}; - - components.forEach(function (component) { - var method = 'from' + capitalize(component); - - context['the ' + method + '() method'] = function () { - var value = timeSpan[method](num); - assert.equal(value[component], num); - } - }); - - return context; -}; \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js b/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js deleted file mode 100644 index 66a7be5..0000000 --- a/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * time-span-test.js: Tests for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var vows = require('vows'), - assert = require('assert'), - timeSpan = require('../lib/time-span'), - helpers = require('./helpers'); - -vows.describe('time-span').addBatch({ - "When using the TimeSpan module": { - "the parse() method": { - "when passed a TimeSpan string with no days": { - "should return a valid TimeSpan object": function () { - var ts = timeSpan.parse("04:03:02.10"); - assert.equal(ts.hours, 4); - assert.equal(ts.minutes, 3); - assert.equal(ts.seconds, 2); - assert.equal(ts.milliseconds, 100); - } - }, - "when passed a TimeSpan string with days": { - "should return a valid TimeSpan object": function () { - var ts = timeSpan.parse("01:04:03:02.10"); - assert.equal(ts.days, 1); - assert.equal(ts.hours, 4); - assert.equal(ts.minutes, 3); - assert.equal(ts.seconds, 2); - assert.equal(ts.milliseconds, 100); - } - } - }, - "the test() method": { - "when passed a TimeSpan string with no days": { - "should return true": function () { - assert.isTrue(timeSpan.test("04:03:02.10")); - } - }, - "when passed a TimeSpan string with days": { - "should return true": function () { - assert.isTrue(timeSpan.test("01:04:03:02.10")); - } - }, - "when passed an invalid TimeSpan string": { - "should return false": function () { - assert.isFalse(timeSpan.test('xx:00:invalid')); - } - } - }, - "the fromDates() method": { - "with two Date values": function () { - var diff = 1000 * 60 * 60 * 12, - end = new Date(), - start = new Date(end.getTime() - diff); - - assert.equal(12, timeSpan.fromDates(start, end).hours); - }, - "with two string values": function () { - assert.equal(2, timeSpan.fromDates('NOW-4DAYS', 'NOW-2DAYS').days); - } - }, - "the factory methods": helpers.testFactories(10) - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/package.json b/node_modules/winston/node_modules/loggly/package.json deleted file mode 100644 index 266434b..0000000 --- a/node_modules/winston/node_modules/loggly/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "loggly", - "description": "A client implementation for Loggly cloud Logging-as-a-Service API", - "version": "0.3.11", - "author": "Charlie Robbins ", - "contributors": [ - { "name": "Marak Squires", "email": "marak.squires@gmail.com" }, - { "name": "hij1nx", "email": "hij1nx@me.com" }, - { "name": "Kord Campbell", "email": "kordless@loggly.com" }, - { "name": "Erik Hedenstrom", "email": "erik@hedenstroem.com" } - ], - "repository": { - "type": "git", - "url": "http://github.com/nodejitsu/node-loggly.git" - }, - "keywords": ["cloud computing", "api", "logging", "loggly"], - "dependencies": { - "request": "2.9.x", - "timespan": "2.x.x" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/loggly", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/test/common-test.js b/node_modules/winston/node_modules/loggly/test/common-test.js deleted file mode 100644 index 51c6b4a..0000000 --- a/node_modules/winston/node_modules/loggly/test/common-test.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - * common-test.js: Tests for Loggly `common` utility module - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - common = require('../lib/loggly/common'); - -vows.describe('node-loggly/common').addBatch({ - "When using the common module": { - "the clone() method": { - topic: function () { - this.obj = { - name: 'common', - deep: { - first: 'first', - second: 'second' - } - }; - return common.clone(this.obj); - }, - "should return a deep clone of the object": function (clone) { - assert.isFalse(this.obj.deep === clone.deep); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/test/device-test.js b/node_modules/winston/node_modules/loggly/test/device-test.js deleted file mode 100644 index 8124180..0000000 --- a/node_modules/winston/node_modules/loggly/test/device-test.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * device-test.js: Tests for Loggly device requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config); - -vows.describe('node-loggly/devices').addBatch({ - "When using the node-loggly client": { - "the getDevices() method": { - topic: function () { - loggly.getDevices(this.callback); - }, - "should return a list of valid devices": function (err, devices) { - assert.isNull(err); - devices.forEach(function (device) { - helpers.assertDevice(device); - }); - } - }, - "the addDeviceToInput() method": { - topic: function () { - loggly.addDeviceToInput(config.inputs.test.id, '127.0.0.1', this.callback); - }, - "should respond with 200 status code": function (err, res) { - assert.isNull(err); - assert.equal(res.statusCode, 200); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/test/helpers.js b/node_modules/winston/node_modules/loggly/test/helpers.js deleted file mode 100644 index b8ed45c..0000000 --- a/node_modules/winston/node_modules/loggly/test/helpers.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * helpers.js: Test helpers for node-loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var fs = require('fs'), - util = require('util'), - path = require('path'), - vows = require('vows'), - assert = require('assert'), - loggly = require('../lib/loggly'); - -var helpers = exports; - -helpers.validConfig = function (config) { - return config - && config.subdomain !== 'test-subdomain' - && config.auth - && config.auth.username !== 'test-username' - && config.auth.password !== 'test-password' - && config.inputs - && config.inputs.test - && config.inputs.test_json; -}; - -helpers.loadConfig = function () { - try { - var configFile = path.join(__dirname, 'data', 'test-config.json'), - stats = fs.statSync(configFile) - config = JSON.parse(fs.readFileSync(configFile).toString()); - - if (!helpers.validConfig(config)) { - util.puts('Config file test-config.json must be updated with valid data before running tests'); - process.exit(0); - } - - helpers.config = config || {} - return config || {}; - } - catch (ex) { - util.puts('Error parsing test-config.json'); - ex.stack.split('\n').forEach(function (line) { - console.log(line); - }); - - process.exit(0); - } -}; - -helpers.assertInput = function (input) { - assert.instanceOf(input, loggly.Input); - assert.isNotNull(input.id); - assert.isNotNull(input.name); - assert.isNotNull(input.service); - assert.isNotNull(input.create); - assert.isNotNull(input.discover); - assert.isNotNull(input.discoverTime); - assert.isNotNull(input.description); -}; - -helpers.assertDevice = function (device) { - assert.instanceOf(device, loggly.Device); - assert.isNotNull(device.id); - assert.isNotNull(device.input); - assert.isNotNull(device.ipAddress); - assert.isNotNull(device.launched); - assert.isNotNull(device.resourceUri); -}; - -helpers.assertSearch = function (err, results) { - assert.isNull(err); - assert.isObject(results); - assert.isTrue(typeof results.data !== 'undefined'); - assert.isTrue(typeof results.numFound !== 'undefined'); - assert.isTrue(typeof results.context !== 'undefined'); -}; diff --git a/node_modules/winston/node_modules/loggly/test/input-test.js b/node_modules/winston/node_modules/loggly/test/input-test.js deleted file mode 100644 index 06cd763..0000000 --- a/node_modules/winston/node_modules/loggly/test/input-test.js +++ /dev/null @@ -1,197 +0,0 @@ -/* - * input-test.js: Tests for Loggly input requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - testContext = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config), - logglyJSON = require('../lib/loggly').createClient(config); - -logglyJSON.config.json = true; - -vows.describe('node-loggly/inputs').addBatch({ - "When using the node-loggly client": { - "the getInputs() method": { - topic: function () { - loggly.getInputs(this.callback); - }, - "should return a list of valid inputs": function (err, inputs) { - assert.isNull(err); - inputs.forEach(function (input) { - helpers.assertInput(input); - }); - } - }, - "the getInput method": { - "when called with a plaintext input": { - topic: function () { - loggly.getInput('test', this.callback); - }, - "should return a valid input": function (err, input) { - assert.isNull(err); - helpers.assertInput(input); - }, - "of the format 'text'": function (err, input) { - assert.isNull(err); - assert.equal(input.format, 'text'); - }, - "that matches the first input in the test configuration": function (err, input) { - assert.equal(config.inputs.test.token,input.input_token); - assert.equal(config.inputs.test.id,input.id); - testContext.input = input; - } - }, - "when called with a json input": { - topic: function () { - logglyJSON.getInput('test_json', this.callback); - }, - "should return a valid input": function (err, input) { - assert.isNull(err); - helpers.assertInput(input); - }, - "of the format 'json'": function (err, input) { - assert.isNull(err); - assert.equal(input.format, 'json'); - }, - "that matches the second input in the test configuration": function (err, input) { - assert.equal(config.inputs.test_json.token,input.input_token); - assert.equal(config.inputs.test_json.id,input.id); - testContext.inputJSON = input; - } - } - } - } -}).addBatch({ - "When using the node-loggly client": { - "the log() method": { - "to a 'text' input": { - "when passed a callback": { - topic: function () { - loggly.log( - config.inputs.test.token, - 'this is a test logging message from /test/input-test.js', - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = loggly.log(config.inputs.test.token, 'this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "to a 'json' input": { - "when passed a callback": { - topic: function () { - logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - } - ); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } - } -}).addBatch({ - "When using an instance of an input": { - "the log() method of the 'text' instance": { - "when passed a callback": { - topic: function () { - testContext.input.log('this is a test logging message from /test/input-test.js', this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = testContext.input.log('this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "the log() method of the 'json' instance": { - "when passed a callback": { - topic: function () { - testContext.inputJSON.log( - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = testContext.inputJSON.log({ - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/test/log-test.js b/node_modules/winston/node_modules/loggly/test/log-test.js deleted file mode 100644 index 876db63..0000000 --- a/node_modules/winston/node_modules/loggly/test/log-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * log-test.js: Tests for vanilla logging with no authentication. - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient({ subdomain: config.subdomain }), - logglyJSON = require('../lib/loggly').createClient({ subdomain: config.subdomain, json: true }); - -vows.describe('node-loggly/inputs (no auth)').addBatch({ - "When using the node-loggly client without authentication": { - "the log() method": { - "to a 'text' input": { - "when passed a callback": { - topic: function () { - loggly.log( - config.inputs.test.token, - 'this is a test logging message from /test/input-test.js', - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = loggly.log(config.inputs.test.token, 'this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "to a 'json' input": { - "when passed a callback": { - topic: function () { - logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - } - ); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/loggly/test/search-test.js b/node_modules/winston/node_modules/loggly/test/search-test.js deleted file mode 100644 index dac9da7..0000000 --- a/node_modules/winston/node_modules/loggly/test/search-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * input-test.js: Tests for Loggly input requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - testContext = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config); - -vows.describe('node-loggly/search').addBatch({ - "When using the node-loggly client": { - "the search() method": { - "when searching without chaining": { - topic: function () { - loggly.search('logging message', this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - }, - "when searching with chaining": { - topic: function () { - loggly.search('logging message') - .meta({ inputname: 'test' }) - .run(this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - } - }, - "the facet() method": { - "when searching by ip": { - topic: function () { - loggly.facet('ip', 'test', this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - }, - "when using chained searches": { - topic: function () { - loggly.facet('ip', 'test') - .context({ from: 'NOW-1MONTH' }) - .run(this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - } - }, - "the _checkRange() method": { - "with invalid options set": { - "should correct them": function () { - var search = loggly.search('logging message') - .context({ from: 'NOW', until: '1DAY' }) - ._checkRange(); - - assert.equal(search._context.from, 'NOW-24HOURS'); - assert.equal(search._context.until, 'NOW'); - } - }, - "with valid options set": { - "should not modify them": function () { - var search = loggly.search('logging message') - .context({ from: 'NOW-2MONTHS', until: 'NOW' }) - ._checkRange(); - - assert.equal(search._context.from, 'NOW-2MONTHS'); - assert.equal(search._context.until, 'NOW'); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/.npmignore b/node_modules/winston/node_modules/pkginfo/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/winston/node_modules/pkginfo/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/README.md b/node_modules/winston/node_modules/pkginfo/README.md deleted file mode 100644 index 07ba942..0000000 --- a/node_modules/winston/node_modules/pkginfo/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# node-pkginfo - -An easy way to expose properties on a module from a package.json - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing pkginfo -``` - [sudo] npm install pkginfo -``` - -## Motivation -How often when writing node.js modules have you written the following line(s) of code? - -* Hard code your version string into your code - -``` js - exports.version = '0.1.0'; -``` - -* Programmatically expose the version from the package.json - -``` js - exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version; -``` - -In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** - -## Usage - -Using `pkginfo` is idiot-proof, just require and invoke it. - -``` js - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); -``` - -By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). - -Here's a sample of the output: - -``` - { name: 'simple-app', - description: 'A test fixture for pkginfo', - version: '0.1.0', - author: 'Charlie Robbins ', - keywords: [ 'test', 'fixture' ], - main: './index.js', - scripts: { test: 'vows test/*-test.js --spec' }, - engines: { node: '>= 0.4.0' } } -``` - -### Expose specific properties -If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: - -``` js - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); -``` - -``` - { version: '0.1.0', - author: 'Charlie Robbins ' } -``` - -If you're looking for further usage see the [examples][0] included in this repository. - -## Run Tests -Tests are written in [vows][1] and give complete coverage of all APIs. - -``` - vows test/*-test.js --spec -``` - -[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples -[1]: http://vowsjs.org - -#### Author: [Charlie Robbins](http://nodejitsu.com) \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/docs/docco.css b/node_modules/winston/node_modules/pkginfo/docs/docco.css deleted file mode 100644 index bd54134..0000000 --- a/node_modules/winston/node_modules/pkginfo/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html b/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html deleted file mode 100644 index bf615fa..0000000 --- a/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html +++ /dev/null @@ -1,101 +0,0 @@ - pkginfo.js

    pkginfo.js

    /*
    - * pkginfo.js: Top-level include for the pkginfo module
    - *
    - * (C) 2011, Charlie Robbins
    - *
    - */
    - 
    -var fs = require('fs'),
    -    path = require('path');

    function pkginfo ([options, 'property', 'property' ..])

    - -

    @pmodule {Module} Parent module to read from.

    - -

    @options {Object|Array|string} Optional Options used when exposing properties.

    - -

    @arguments {string...} Optional Specified properties to expose.

    - -

    Exposes properties from the package.json file for the parent module on -it's exports. Valid usage:

    - -

    require('pkginfo')()

    - -

    require('pkginfo')('version', 'author');

    - -

    require('pkginfo')(['version', 'author']);

    - -

    require('pkginfo')({ include: ['version', 'author'] });

    var pkginfo = module.exports = function (pmodule, options) {
    -  var args = [].slice.call(arguments, 2).filter(function (arg) {
    -    return typeof arg === 'string';
    -  });
    -  

    Parse variable arguments

      if (Array.isArray(options)) {

    If the options passed in is an Array assume that -it is the Array of properties to expose from the -on the package.json file on the parent module.

        options = { include: options };
    -  }
    -  else if (typeof options === 'string') {

    Otherwise if the first argument is a string, then -assume that it is the first property to expose from -the package.json file on the parent module.

        options = { include: [options] };
    -  }
    -  

    Setup default options

      options = options || { include: [] };
    -  
    -  if (args.length > 0) {

    If additional string arguments have been passed in -then add them to the properties to expose on the -parent module.

        options.include = options.include.concat(args);
    -  }
    -  
    -  var pkg = pkginfo.read(pmodule, options.dir).package;
    -  Object.keys(pkg).forEach(function (key) {
    -    if (options.include.length > 0 && !~options.include.indexOf(key)) {
    -      return;
    -    }
    -    
    -    if (!pmodule.exports[key]) {
    -      pmodule.exports[key] = pkg[key];
    -    }
    -  });
    -  
    -  return pkginfo;
    -};

    function find (dir)

    - -

    @pmodule {Module} Parent module to read from.

    - -

    @dir {string} Optional Directory to start search from.

    - -

    Searches up the directory tree from dir until it finds a directory -which contains a package.json file.

    pkginfo.find = function (pmodule, dir) {
    -  dir = dir || pmodule.filename;
    -  dir = path.dirname(dir); 
    -  
    -  var files = fs.readdirSync(dir);
    -  
    -  if (~files.indexOf('package.json')) {
    -    return path.join(dir, 'package.json');
    -  }
    -  
    -  if (dir === '/') {
    -    throw new Error('Could not find package.json up from: ' + dir);
    -  }
    -  
    -  return pkginfo.find(dir);
    -};

    function read (pmodule, dir)

    - -

    @pmodule {Module} Parent module to read from.

    - -

    @dir {string} Optional Directory to start search from.

    - -

    Searches up the directory tree from dir until it finds a directory -which contains a package.json file and returns the package information.

    pkginfo.read = function (pmodule, dir) { 
    -  dir = pkginfo.find(pmodule, dir);
    -  
    -  var data = fs.readFileSync(dir).toString();
    -      
    -  return {
    -    dir: dir, 
    -    package: JSON.parse(data)
    -  };
    -};

    Call pkginfo on this module and expose version.

    pkginfo(module, {
    -  dir: __dirname,
    -  include: ['version'],
    -  target: pkginfo
    -});
    -
    -
    \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/all-properties.js b/node_modules/winston/node_modules/pkginfo/examples/all-properties.js deleted file mode 100644 index fd1d831..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/all-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * all-properties.js: Sample of including all properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/array-argument.js b/node_modules/winston/node_modules/pkginfo/examples/array-argument.js deleted file mode 100644 index b1b6848..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/array-argument.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * array-argument.js: Sample of including specific properties from a package.json file - * using Array argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js b/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js deleted file mode 100644 index b4b5fd6..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/object-argument.js b/node_modules/winston/node_modules/pkginfo/examples/object-argument.js deleted file mode 100644 index 28420c8..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/object-argument.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * object-argument.js: Sample of including specific properties from a package.json file - * using Object argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, { - include: ['version', 'author'] - }); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/package.json b/node_modules/winston/node_modules/pkginfo/examples/package.json deleted file mode 100644 index 1f2f01c..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "simple-app", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node_modules/winston/node_modules/pkginfo/examples/single-property.js b/node_modules/winston/node_modules/pkginfo/examples/single-property.js deleted file mode 100644 index 4f44561..0000000 --- a/node_modules/winston/node_modules/pkginfo/examples/single-property.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * single-property.js: Sample of including a single specific properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js b/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js deleted file mode 100644 index a4a6227..0000000 --- a/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * pkginfo.js: Top-level include for the pkginfo module - * - * (C) 2011, Charlie Robbins - * - */ - -var fs = require('fs'), - path = require('path'); - -// -// ### function pkginfo ([options, 'property', 'property' ..]) -// #### @pmodule {Module} Parent module to read from. -// #### @options {Object|Array|string} **Optional** Options used when exposing properties. -// #### @arguments {string...} **Optional** Specified properties to expose. -// Exposes properties from the package.json file for the parent module on -// it's exports. Valid usage: -// -// `require('pkginfo')()` -// -// `require('pkginfo')('version', 'author');` -// -// `require('pkginfo')(['version', 'author']);` -// -// `require('pkginfo')({ include: ['version', 'author'] });` -// -var pkginfo = module.exports = function (pmodule, options) { - var args = [].slice.call(arguments, 2).filter(function (arg) { - return typeof arg === 'string'; - }); - - // - // **Parse variable arguments** - // - if (Array.isArray(options)) { - // - // If the options passed in is an Array assume that - // it is the Array of properties to expose from the - // on the package.json file on the parent module. - // - options = { include: options }; - } - else if (typeof options === 'string') { - // - // Otherwise if the first argument is a string, then - // assume that it is the first property to expose from - // the package.json file on the parent module. - // - options = { include: [options] }; - } - - // - // **Setup default options** - // - options = options || { include: [] }; - - if (args.length > 0) { - // - // If additional string arguments have been passed in - // then add them to the properties to expose on the - // parent module. - // - options.include = options.include.concat(args); - } - - var pkg = pkginfo.read(pmodule, options.dir).package; - Object.keys(pkg).forEach(function (key) { - if (options.include.length > 0 && !~options.include.indexOf(key)) { - return; - } - - if (!pmodule.exports[key]) { - pmodule.exports[key] = pkg[key]; - } - }); - - return pkginfo; -}; - -// -// ### function find (dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file. -// -pkginfo.find = function (pmodule, dir) { - dir = dir || pmodule.filename; - dir = path.dirname(dir); - - var files = fs.readdirSync(dir); - - if (~files.indexOf('package.json')) { - return path.join(dir, 'package.json'); - } - - if (dir === '/') { - throw new Error('Could not find package.json up from: ' + dir); - } - else if (!dir || dir === '.') { - throw new Error('Cannot find package.json from unspecified directory'); - } - - return pkginfo.find(pmodule, dir); -}; - -// -// ### function read (pmodule, dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file and returns the package information. -// -pkginfo.read = function (pmodule, dir) { - dir = pkginfo.find(pmodule, dir); - - var data = fs.readFileSync(dir).toString(); - - return { - dir: dir, - package: JSON.parse(data) - }; -}; - -// -// Call `pkginfo` on this module and expose version. -// -pkginfo(module, { - dir: __dirname, - include: ['version'], - target: pkginfo -}); \ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/package.json b/node_modules/winston/node_modules/pkginfo/package.json deleted file mode 100644 index 0e9e4e7..0000000 --- a/node_modules/winston/node_modules/pkginfo/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "pkginfo", - "version": "0.2.3", - "description": "An easy way to expose properties on a module from a package.json", - "author": "Charlie Robbins ", - "repository": { - "type": "git", - "url": "http://github.com/indexzero/node-pkginfo.git" - }, - "keywords": ["info", "tools", "package.json"], - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/pkginfo", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js b/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js deleted file mode 100644 index 3156c00..0000000 --- a/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * pkginfo-test.js: Tests for the pkginfo module. - * - * (C) 2011, Charlie Robbins - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - pkginfo = require('../lib/pkginfo'); - -function assertProperties (source, target) { - assert.lengthOf(source, target.length + 1); - target.forEach(function (prop) { - assert.isTrue(!!~source.indexOf(prop)); - }); -} - -function testExposes (options) { - return { - topic: function () { - exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); - }, - "should expose that property correctly": function (err, stdout, stderr) { - assert.isNull(err); - - var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { - return p.substring(1, p.length - 1); - }); - - return !options.assert - ? assertProperties(exposed, options.properties) - : options.assert(exposed); - } - } -} - -vows.describe('pkginfo').addBatch({ - "When using the pkginfo module": { - "and passed a single `string` argument": testExposes({ - script: 'single-property.js', - properties: ['version'] - }), - "and passed multiple `string` arguments": testExposes({ - script: 'multiple-properties.js', - properties: ['version', 'author'] - }), - "and passed an `object` argument": testExposes({ - script: 'object-argument.js', - properties: ['version', 'author'] - }), - "and passed an `array` argument": testExposes({ - script: 'array-argument.js', - properties: ['version', 'author'] - }), - "and passed no arguments": testExposes({ - script: 'all-properties.js', - assert: function (exposed) { - var pkg = fs.readFileSync(path.join(__dirname, '..', 'examples', 'package.json')).toString(), - keys = Object.keys(JSON.parse(pkg)); - - assertProperties(exposed, keys); - } - }) - } -}).export(module); diff --git a/node_modules/winston/node_modules/stack-trace/.License.un~ b/node_modules/winston/node_modules/stack-trace/.License.un~ deleted file mode 100644 index 75169d3..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/.License.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/.Readme.md.un~ b/node_modules/winston/node_modules/stack-trace/.Readme.md.un~ deleted file mode 100644 index 7e945a1..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/.Readme.md.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/.npmignore b/node_modules/winston/node_modules/stack-trace/.npmignore deleted file mode 100644 index 3f31ac2..0000000 --- a/node_modules/winston/node_modules/stack-trace/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.un~ -/node_modules diff --git a/node_modules/winston/node_modules/stack-trace/.package.json.un~ b/node_modules/winston/node_modules/stack-trace/.package.json.un~ deleted file mode 100644 index f3f2c31..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/.package.json.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/.test-get.js.un~ b/node_modules/winston/node_modules/stack-trace/.test-get.js.un~ deleted file mode 100644 index 5bea0cb..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/.test-get.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/License b/node_modules/winston/node_modules/stack-trace/License deleted file mode 100644 index 11ec094..0000000 --- a/node_modules/winston/node_modules/stack-trace/License +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. diff --git a/node_modules/winston/node_modules/stack-trace/Makefile b/node_modules/winston/node_modules/stack-trace/Makefile deleted file mode 100644 index a7ce31d..0000000 --- a/node_modules/winston/node_modules/stack-trace/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -SHELL := /bin/bash - -test: - @./test/run.js - -release: - git push - git push --tags - npm publish . - -.PHONY: test diff --git a/node_modules/winston/node_modules/stack-trace/Readme.md b/node_modules/winston/node_modules/stack-trace/Readme.md deleted file mode 100644 index fcd1b97..0000000 --- a/node_modules/winston/node_modules/stack-trace/Readme.md +++ /dev/null @@ -1,98 +0,0 @@ -# stack-trace - -Get v8 stack traces as an array of CallSite objects. - -## Install - -``` bash -npm install stack-trace -``` - -## Usage - -The stack-trace module makes it easy for you to capture the current stack: - -``` javascript -var stackTrace = require('stack-trace'); -var trace = stackTrace.get(); - -require('assert').strictEqual(trace[0].getFileName(), __filename); -``` - -However, sometimes you have already popped the stack you are interested in, -and all you have left is an `Error` object. This module can help: - -``` javascript -var stackTrace = require('stack-trace'); -var err = new Error('something went wrong'); -var trace = stackTrace.parse(err); - -require('assert').strictEqual(trace[0].getFileName(), __filename); -``` - -Please note that parsing the `Error#stack` property is not perfect, only -certain properties can be retrieved with it as noted in the API docs below. - -## Long stack traces - -stack-trace works great with [long-stack-traces][], when parsing an `err.stack` -that has crossed the event loop boundary, a `CallSite` object returning -`'----------------------------------------'` for `getFileName()` is created. -All other methods of the event loop boundary call site return `null`. - -[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces - -## API - -### stackTrace.get([belowFn]) - -Returns an array of `CallSite` objects, where element `0` is the current call -site. - -When passing a function on the current stack as the `belowFn` parameter, the -returned array will only include `CallSite` objects below this function. - -### stackTrace.parse(err) - -Parses the `err.stack` property of an `Error` object into an array compatible -with those returned by `stackTrace.get()`. However, only the following methods -are implemented on the returned `CallSite` objects. - -* getTypeName -* getFunctionName -* getMethodName -* getFileName -* getLineNumber -* getColumnNumber -* isNative - -Note: Except `getFunctionName()`, all of the above methods return exactly the -same values as you would get from `stackTrace.get()`. `getFunctionName()` -is sometimes a little different, but still useful. - -### CallSite - -The official v8 CallSite object API can be found [here][v8stackapi]. A quick -excerpt: - -> A CallSite object defines the following methods: -> -> * **getThis**: returns the value of this -> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. -> * **getFunction**: returns the current function -> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. -> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function -> * **getFileName**: if this function was defined in a script returns the name of the script -> * **getLineNumber**: if this function was defined in a script returns the current line number -> * **getColumnNumber**: if this function was defined in a script returns the current column number -> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called -> * **isToplevel**: is this a toplevel invocation, that is, is this the global object? -> * **isEval**: does this call take place in code defined by a call to eval? -> * **isNative**: is this call in native V8 code? -> * **isConstructor**: is this a constructor call? - -[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - -## License - -stack-trace is licensed under the MIT license. diff --git a/node_modules/winston/node_modules/stack-trace/lib/.stack-trace.js.un~ b/node_modules/winston/node_modules/stack-trace/lib/.stack-trace.js.un~ deleted file mode 100644 index 05d61a5..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/lib/.stack-trace.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js b/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js deleted file mode 100644 index 085ff40..0000000 --- a/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js +++ /dev/null @@ -1,111 +0,0 @@ -exports.get = function(belowFn) { - var oldLimit = Error.stackTraceLimit; - Error.stackTraceLimit = Infinity; - - var dummyObject = {}; - Error.captureStackTrace(dummyObject, belowFn || exports.get); - - var v8Handler = Error.prepareStackTrace; - Error.prepareStackTrace = function(dummyObject, v8StackTrace) { - return v8StackTrace; - }; - - var v8StackTrace = dummyObject.stack; - Error.prepareStackTrace = v8Handler; - Error.stackTraceLimit = oldLimit; - - return v8StackTrace; -}; - -exports.parse = function(err) { - if (!err.stack) { - return []; - } - - var self = this; - var lines = err.stack.split('\n').slice(1); - - return lines - .map(function(line) { - if (line.match(/^\s*[-]{4,}$/)) { - return self._createParsedCallSite({ - fileName: line, - lineNumber: null, - functionName: null, - typeName: null, - methodName: null, - columnNumber: null, - 'native': null, - }); - } - - var lineMatch = line.match(/at (?:([^\s]+)\s+)?\(?(?:(.+?):(\d+):(\d+)|([^)]+))\)?/); - if (!lineMatch) { - return; - } - - var object = null; - var method = null; - var functionName = null; - var typeName = null; - var methodName = null; - var isNative = (lineMatch[5] === 'native'); - - if (lineMatch[1]) { - var methodMatch = lineMatch[1].match(/([^\.]+)(?:\.(.+))?/); - object = methodMatch[1]; - method = methodMatch[2]; - functionName = lineMatch[1]; - typeName = 'Object'; - } - - if (method) { - typeName = object; - methodName = method; - } - - if (method === '') { - methodName = null; - functionName = ''; - } - - var properties = { - fileName: lineMatch[2] || null, - lineNumber: parseInt(lineMatch[3], 10) || null, - functionName: functionName, - typeName: typeName, - methodName: methodName, - columnNumber: parseInt(lineMatch[4], 10) || null, - 'native': isNative, - }; - - return self._createParsedCallSite(properties); - }) - .filter(function(callSite) { - return !!callSite; - }); -}; - -exports._createParsedCallSite = function(properties) { - var methods = {}; - for (var property in properties) { - var prefix = 'get'; - if (property === 'native') { - prefix = 'is'; - } - var method = prefix + property.substr(0, 1).toUpperCase() + property.substr(1); - - (function(property) { - methods[method] = function() { - return properties[property]; - } - })(property); - } - - var callSite = Object.create(methods); - for (var property in properties) { - callSite[property] = properties[property]; - } - - return callSite; -}; diff --git a/node_modules/winston/node_modules/stack-trace/package.json b/node_modules/winston/node_modules/stack-trace/package.json deleted file mode 100644 index 87bc6e9..0000000 --- a/node_modules/winston/node_modules/stack-trace/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "author": "Felix Geisendörfer (http://debuggable.com/)", - "name": "stack-trace", - "description": "Get v8 stack traces as an array of CallSite objects.", - "version": "0.0.6", - "homepage": "https://github.com/felixge/node-stack-trace", - "repository": { - "type": "git", - "url": "git://github.com/felixge/node-stack-trace.git" - }, - "main": "./lib/stack-trace", - "engines": { - "node": "*" - }, - "dependencies": {}, - "devDependencies": { - "far": "0.0.3", - "long-stack-traces": "0.1.2" - } -} \ No newline at end of file diff --git a/node_modules/winston/node_modules/stack-trace/test/.common.js.un~ b/node_modules/winston/node_modules/stack-trace/test/.common.js.un~ deleted file mode 100644 index 0192c5b..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/test/.common.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/test/common.js b/node_modules/winston/node_modules/stack-trace/test/common.js deleted file mode 100644 index 2985c2f..0000000 --- a/node_modules/winston/node_modules/stack-trace/test/common.js +++ /dev/null @@ -1,10 +0,0 @@ -var common = exports; - -var path = require('path'); -var root = path.dirname(__dirname); - -common.dir = { - lib: root + '/lib', -}; - -common.assert = require('assert'); diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/.test-basic.js.un~ b/node_modules/winston/node_modules/stack-trace/test/integration/.test-basic.js.un~ deleted file mode 100644 index 14af278..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/test/integration/.test-basic.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/.test-get.js.un~ b/node_modules/winston/node_modules/stack-trace/test/integration/.test-get.js.un~ deleted file mode 100644 index a660684..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/test/integration/.test-get.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/.test-long-stack-trace.js.un~ b/node_modules/winston/node_modules/stack-trace/test/integration/.test-long-stack-trace.js.un~ deleted file mode 100644 index 46f367d..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/test/integration/.test-long-stack-trace.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/.test-parse.js.un~ b/node_modules/winston/node_modules/stack-trace/test/integration/.test-parse.js.un~ deleted file mode 100644 index 20d7374..0000000 Binary files a/node_modules/winston/node_modules/stack-trace/test/integration/.test-parse.js.un~ and /dev/null differ diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js b/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js deleted file mode 100644 index 53b2e61..0000000 --- a/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js +++ /dev/null @@ -1,49 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -(function testBasic() { - var trace = stackTrace.get(); - - assert.strictEqual(trace[0].getFunction(), testBasic); - assert.strictEqual(trace[0].getFunctionName(), 'testBasic'); - assert.strictEqual(trace[0].getFileName(), __filename); -})(); - -(function testWrapper() { - (function testBelowFn() { - var trace = stackTrace.get(testBelowFn); - assert.strictEqual(trace[0].getFunction(), testWrapper); - assert.strictEqual(trace[0].getFunctionName(), 'testWrapper'); - })(); -})(); - - -(function deep1() { - (function deep2() { - (function deep3() { - (function deep4() { - (function deep5() { - (function deep6() { - (function deep7() { - (function deep8() { - (function deep9() { - (function deep10() { - (function deep10() { - var trace = stackTrace.get(); - var hasFirstCallSite = trace.some(function(callSite) { - return callSite.getFunctionName() === 'deep1'; - }); - - assert.ok(hasFirstCallSite); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); -})(); diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js b/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js deleted file mode 100644 index 6106c4a..0000000 --- a/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js +++ /dev/null @@ -1,14 +0,0 @@ -var common = require('../common'); - -require('long-stack-traces'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -function badFn() { - var err = new Error('oh no'); - var trace = stackTrace.parse(err); - - assert.ok(trace[2].getFileName().match(/-----/)); -}; - -setTimeout(badFn, 10); diff --git a/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js b/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js deleted file mode 100644 index 4171a68..0000000 --- a/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js +++ /dev/null @@ -1,135 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -(function testBasic() { - var err = new Error('something went wrong'); - var trace = stackTrace.parse(err); - - assert.strictEqual(trace[0].getFileName(), __filename); - assert.strictEqual(trace[0].getFunctionName(), 'testBasic'); -})(); - -(function testWrapper() { - (function testBelowFn() { - var err = new Error('something went wrong'); - var trace = stackTrace.parse(err); - assert.strictEqual(trace[0].getFunctionName(), 'testBelowFn'); - assert.strictEqual(trace[1].getFunctionName(), 'testWrapper'); - })(); -})(); - -(function testNoStack() { - var err = {stack: undefined}; - var trace = stackTrace.parse(err); - - assert.deepEqual(trace, []); -})(); - - -(function testCorruptStack() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' fuck' + -' at Test.run (/Users/felix/code/node-fast-or-slow/lib/test.js:45:10)\n' + -'oh no' + -' at TestCase.run (/Users/felix/code/node-fast-or-slow/lib/test_case.js:61:8)\n'; - - var trace = stackTrace.parse(err); - assert.equal(trace.length, 2); -})(); - -(function testCompareRealWithParsedStackTrace() { - var realTrace = stackTrace.get(); var err = new Error('something went wrong'); - var parsedTrace = stackTrace.parse(err); - - realTrace.forEach(function(real, i) { - var parsed = parsedTrace[i]; - - function compare(method, exceptions) { - var realValue = real[method](); - var parsedValue = parsed[method](); - - if (exceptions && exceptions[i]) { - realValue = exceptions[i]; - } - - var realJson = JSON.stringify(realValue); - var parsedJson = JSON.stringify(parsedValue); - - var message = - method + ': ' + realJson + ' != ' + parsedJson + ' (#' + i + ')'; - - assert.strictEqual(realValue, parsedValue, message); - } - - compare('getFileName'); - compare('getFunctionName', { - 3: 'Object..js', - 5: 'Function._load', - 6: 'Array.0', - 7: 'EventEmitter._tickCallback', - }); - compare('getTypeName'); - compare('getMethodName'); - compare('getLineNumber'); - compare('getColumnNumber', { - 0: 47 - }); - compare('isNative'); - }); -})(); - -(function testStackWithNativeCall() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' at Test.fn (/Users/felix/code/node-fast-or-slow/test/fast/example/test-example.js:6:10)\n' + -' at Test.run (/Users/felix/code/node-fast-or-slow/lib/test.js:45:10)\n' + -' at TestCase.runNext (/Users/felix/code/node-fast-or-slow/lib/test_case.js:73:8)\n' + -' at TestCase.run (/Users/felix/code/node-fast-or-slow/lib/test_case.js:61:8)\n' + -' at Array.0 (native)\n' + -' at EventEmitter._tickCallback (node.js:126:26)'; - - var trace = stackTrace.parse(err); - var nativeCallSite = trace[4]; - - assert.strictEqual(nativeCallSite.getFileName(), null); - assert.strictEqual(nativeCallSite.getFunctionName(), 'Array.0'); - assert.strictEqual(nativeCallSite.getTypeName(), 'Array'); - assert.strictEqual(nativeCallSite.getMethodName(), '0'); - assert.strictEqual(nativeCallSite.getLineNumber(), null); - assert.strictEqual(nativeCallSite.getColumnNumber(), null); - assert.strictEqual(nativeCallSite.isNative(), true); -})(); - -(function testStackWithFileOnly() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' at /Users/felix/code/node-fast-or-slow/lib/test_case.js:80:10'; - - var trace = stackTrace.parse(err); - var callSite = trace[0]; - - assert.strictEqual(callSite.getFileName(), '/Users/felix/code/node-fast-or-slow/lib/test_case.js'); - assert.strictEqual(callSite.getFunctionName(), null); - assert.strictEqual(callSite.getTypeName(), null); - assert.strictEqual(callSite.getMethodName(), null); - assert.strictEqual(callSite.getLineNumber(), 80); - assert.strictEqual(callSite.getColumnNumber(), 10); - assert.strictEqual(callSite.isNative(), false); -})(); - -(function testStackWithMultilineMessage() { - var err = {}; - err.stack = -'AssertionError: true == false\nAnd some more shit\n' + -' at /Users/felix/code/node-fast-or-slow/lib/test_case.js:80:10'; - - var trace = stackTrace.parse(err); - var callSite = trace[0]; - - assert.strictEqual(callSite.getFileName(), '/Users/felix/code/node-fast-or-slow/lib/test_case.js'); -})(); diff --git a/node_modules/winston/node_modules/stack-trace/test/run.js b/node_modules/winston/node_modules/stack-trace/test/run.js deleted file mode 100755 index 0bb8e82..0000000 --- a/node_modules/winston/node_modules/stack-trace/test/run.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var far = require('far').create(); - -far.add(__dirname); -far.include(/test-.*\.js$/); - -far.execute(); diff --git a/node_modules/winston/package.json b/node_modules/winston/package.json deleted file mode 100644 index 4132bdb..0000000 --- a/node_modules/winston/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "winston", - "description": "A multi-transport async logging library for Node.js", - "version": "0.5.10", - "author": "Charlie Robbins ", - "contributors": [ - { "name": "Matthew Bergman", "email": "mzbphoto@gmail.com" }, - { "name": "Marak Squires", "email": "marak@nodejitsu.com" } - ], - "repository": { - "type": "git", - "url": "https://github.com/flatiron/winston.git" - }, - "keywords": ["logging", "sysadmin", "tools"], - "dependencies": { - "async": "0.1.x", - "colors": "0.x.x", - "eyes": "0.1.x", - "loggly": "0.3.x >=0.3.7", - "pkginfo": "0.2.x", - "stack-trace": "0.0.x" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/winston", - "scripts": { "test": "vows --spec --isolate" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node_modules/winston/test/cli-test.js b/node_modules/winston/test/cli-test.js deleted file mode 100644 index 365fba3..0000000 --- a/node_modules/winston/test/cli-test.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * cli-test.js: Tests for the cli levels available in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/cli').addBatch({ - "When an instance of winston.Logger": { - topic: function () { - return new winston.Logger({ - transports: [ - new winston.transports.Console() - ] - }) - }, - "the cli() method": { - "should set the appropriate values on the logger": function (logger) { - logger.cli(); - assert.isTrue(logger.padLevels); - assert.isTrue(logger.transports.console.colorize); - assert.isFalse(logger.transports.console.timestamp); - Object.keys(winston.config.cli.levels).forEach(function (level) { - assert.isNumber(logger.levels[level]); - }); - - Object.keys(winston.config.cli.colors).forEach(function (color) { - assert.isString(winston.config.allColors[color]); - }); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/container-test.js b/node_modules/winston/test/container-test.js deleted file mode 100644 index 2fcc26a..0000000 --- a/node_modules/winston/test/container-test.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * container-test.js: Tests for the Container object - * - * (C) 2011 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - fs = require('fs'), - http = require('http'), - path = require('path'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/container').addBatch({ - "An instance of winston.Container": { - topic: new winston.Container(), - "the add() method": { - topic: function (container) { - return container.add('default-test'); - }, - "should correctly instantiate a Logger": function (logger) { - assert.instanceOf(logger, winston.Logger); - }, - "the get() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should respond with the logger previously created": function (existing, container) { - var logger = container.get('default-test'); - assert.isTrue(existing === logger); - } - }, - "the has() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should indicate `default-test` logger exists": function (existing, container) { - assert.isTrue(container.has('default-test')); - }, - "should indicate `not-has` logger doesnt exists": function (existing, container) { - assert.isFalse(container.has('not-has')); - } - }, - "the close() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should remove the specified logger": function (logger, container) { - container.close('default-test'); - assert.isTrue(!container.loggers['default-test']); - } - } - } - }, - "An instance of winston.Container with explicit transports": { - topic: function () { - this.port = 9412; - this.transports = [ - new winston.transports.Webhook({ - port: this.port - }) - ]; - - this.container = new winston.Container({ - transports: this.transports - }); - - return null; - }, - "the get() method": { - topic: function (container) { - var server = http.createServer(function (req, res) { - res.end(); - }); - - server.listen(this.port, this.callback.bind(this, null)); - }, - "should add the logger correctly": function () { - this.someLogger = this.container.get('some-logger'); - assert.isObject(this.someLogger.transports); - assert.instanceOf(this.someLogger.transports['webhook'], winston.transports.Webhook); - assert.strictEqual(this.someLogger.transports['webhook'], this.transports[0]); - }, - "a second call to get()": { - "should respond with the same transport object": function () { - this.someOtherLogger = this.container.get('some-other-logger'); - - assert.isObject(this.someOtherLogger.transports); - assert.instanceOf(this.someOtherLogger.transports['webhook'], winston.transports.Webhook); - assert.strictEqual(this.someOtherLogger.transports['webhook'], this.transports[0]); - assert.strictEqual(this.someOtherLogger.transports['webhook'], this.someLogger.transports['webhook']); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/custom-timestamp-test.js b/node_modules/winston/test/custom-timestamp-test.js deleted file mode 100644 index c9753e2..0000000 --- a/node_modules/winston/test/custom-timestamp-test.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * custom-timestamp-test.js: Test function as timestamp option for transport `{ timestamp: function () {} }` - * - * (C) 2011 Charlie Robbins, Tom Shinnick - * MIT LICENSE - * - */ - -var assert = require('assert'), - events = require('events'), - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -function assertTimestamp (basename, options) { - var filename = path.join(__dirname, 'fixtures', 'logs', basename + '.log'); - - try { fs.unlinkSync(filename) } - catch (ex) { } - - return { - topic: function () { - options.filename = filename; - var transport = new (winston.transports.File)(options); - - // We must wait until transport file has emitted the 'flush' - // event to be sure the file has been created and written - transport.once('flush', this.callback.bind(this, null, filename)); - transport.log('info', 'When a fake tree falls in the forest...', null, function () {}); - }, - "should log with the appropriate timestamp": function (_, filename) { - var data = fs.readFileSync(filename, 'utf8'); - assert.isNotNull(data.match(options.pattern)); - } - } -} - -vows.describe('winston/transport/timestamp').addBatch({ - "When timestamp option is used": { - "with file transport": { - "with value set to false": assertTimestamp('noTimestamp', { - pattern: /^info\:/, - json: false, - timestamp: false - }), - "with value set to true ": assertTimestamp('defaultTimestamp', { - pattern: /^\d\d? \w{3}/, - json: false, - timestamp: true - }), - "and function value": assertTimestamp('customTimestamp', { - pattern: /^\d{8}\./, - json: false, - timestamp: function () { - return '20110803.171657'; - } - }) - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/exception-test.js b/node_modules/winston/test/exception-test.js deleted file mode 100644 index 6bc8aec..0000000 --- a/node_modules/winston/test/exception-test.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * exception-test.js: Tests for exception data gathering in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/exception').addBatch({ - "When using the winston exception module": { - "the getProcessInfo() method": { - topic: winston.exception.getProcessInfo(), - "should respond with the appropriate data": function (info) { - helpers.assertProcessInfo(info); - } - }, - "the getOsInfo() method": { - topic: winston.exception.getOsInfo(), - "should respond with the appropriate data": function (info) { - helpers.assertOsInfo(info); - } - }, - "the getTrace() method": { - topic: winston.exception.getTrace(new Error()), - "should have the appropriate info": function (trace) { - helpers.assertTrace(trace); - } - }, - "the getAllInfo() method": { - topic: winston.exception.getAllInfo(new Error()), - "should have the appropriate info": function (info) { - assert.isObject(info); - assert.isArray(info.stack); - helpers.assertProcessInfo(info.process); - helpers.assertOsInfo(info.os); - helpers.assertTrace(info.trace); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/fixtures/.gitkeep b/node_modules/winston/test/fixtures/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/winston/test/fixtures/keys/agent2-cert.pem b/node_modules/winston/test/fixtures/keys/agent2-cert.pem deleted file mode 100644 index 8e4354d..0000000 --- a/node_modules/winston/test/fixtures/keys/agent2-cert.pem +++ /dev/null @@ -1,13 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV -UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO -BgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR -cnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy -WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD -VQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg -MB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF -AANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC -WKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA -C8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9 -1LHwrmh29rK8kBPEjmymCQ== ------END CERTIFICATE----- diff --git a/node_modules/winston/test/fixtures/keys/agent2-key.pem b/node_modules/winston/test/fixtures/keys/agent2-key.pem deleted file mode 100644 index 522903c..0000000 --- a/node_modules/winston/test/fixtures/keys/agent2-key.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5 -QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH -9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p -OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf -WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb -AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa -cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I ------END RSA PRIVATE KEY----- diff --git a/node_modules/winston/test/fixtures/logs/.gitkeep b/node_modules/winston/test/fixtures/logs/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/winston/test/fixtures/scripts/default-exceptions.js b/node_modules/winston/test/fixtures/scripts/default-exceptions.js deleted file mode 100644 index ab26aa5..0000000 --- a/node_modules/winston/test/fixtures/scripts/default-exceptions.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * default-exceptions.js: A test fixture for logging exceptions with the default winston logger. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -winston.handleExceptions([ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'default-exception.log'), - handleExceptions: true - }) -]); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node_modules/winston/test/fixtures/scripts/exit-on-error.js b/node_modules/winston/test/fixtures/scripts/exit-on-error.js deleted file mode 100644 index fa3dd65..0000000 --- a/node_modules/winston/test/fixtures/scripts/exit-on-error.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * default-exceptions.js: A test fixture for logging exceptions with the default winston logger. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -winston.exitOnError = function (err) { - return err.message !== 'Ignore this error'; -}; - -winston.handleExceptions([ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'exit-on-error.log'), - handleExceptions: true - }) -]); - -setTimeout(function () { - throw new Error('Ignore this error'); -}, 1000); \ No newline at end of file diff --git a/node_modules/winston/test/fixtures/scripts/log-exceptions.js b/node_modules/winston/test/fixtures/scripts/log-exceptions.js deleted file mode 100644 index 43ce7eb..0000000 --- a/node_modules/winston/test/fixtures/scripts/log-exceptions.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * log-exceptions.js: A test fixture for logging exceptions in winston. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'exception.log'), - handleExceptions: true - }) - ] -}); - -logger.handleExceptions(); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js b/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js deleted file mode 100644 index 5d722a7..0000000 --- a/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * unhandle-exceptions.js: A test fixture for using `.unhandleExceptions()` winston. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'unhandle-exception.log'), - handleExceptions: true - }) - ] -}); - -logger.handleExceptions(); -logger.unhandleExceptions(); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node_modules/winston/test/helpers.js b/node_modules/winston/test/helpers.js deleted file mode 100644 index f961f85..0000000 --- a/node_modules/winston/test/helpers.js +++ /dev/null @@ -1,179 +0,0 @@ -/* - * helpers.js: Test helpers for winston - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - fs = require('fs'), - path = require('path'), - spawn = require('child_process').spawn, - util = require('util'), - loggly = require('loggly'), - vows = require('vows'), - winston = require('../lib/winston'); - -var helpers = exports; - -helpers.loadConfig = function (dir) { - try { - if (helpers.config) return helpers.config; - var configFile = path.join(dir || __dirname, 'fixtures', 'test-config.json'), - stats = fs.statSync(configFile), - config = JSON.parse(fs.readFileSync(configFile).toString()); - - helpers.config = config; - return config; - } - catch (ex) { - console.error('test/fixtures/test-config.json must be created with valid data before running tests'); - return false; - } -}; - -helpers.size = function (obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - size++; - } - } - - return size; -}; - -helpers.tryUnlink = function (file) { - try { fs.unlinkSync(file) } - catch (ex) { } -}; - -helpers.assertProcessInfo = function (info) { - assert.isNumber(info.pid); - assert.isNumber(info.uid); - assert.isNumber(info.gid); - assert.isString(info.cwd); - assert.isString(info.execPath); - assert.isString(info.version); - assert.isArray(info.argv); - assert.isObject(info.memoryUsage); -}; - -helpers.assertOsInfo = function (info) { - assert.isArray(info.loadavg); - assert.isNumber(info.uptime); -}; - -helpers.assertTrace = function (trace) { - trace.forEach(function (site) { - assert.isTrue(!site.column || typeof site.column === 'number'); - assert.isTrue(!site.line || typeof site.line === 'number'); - assert.isTrue(!site.file || typeof site.file === 'string'); - assert.isTrue(!site.method || typeof site.method === 'string'); - assert.isTrue(!site.function || typeof site.function === 'string'); - assert.isTrue(typeof site.native === 'boolean'); - }); -}; - -helpers.assertLogger = function (logger, level) { - assert.instanceOf(logger, winston.Logger); - assert.isFunction(logger.log); - assert.isFunction(logger.add); - assert.isFunction(logger.remove); - assert.equal(logger.level, level || "info"); - Object.keys(logger.levels).forEach(function (method) { - assert.isFunction(logger[method]); - }); -}; - -helpers.assertConsole = function (transport) { - assert.instanceOf(transport, winston.transports.Console); - assert.isFunction(transport.log); -}; - -helpers.assertFile = function (transport) { - assert.instanceOf(transport, winston.transports.File); - assert.isFunction(transport.log); -} - -helpers.assertLoggly = function (transport) { - assert.instanceOf(transport, winston.transports.Loggly); - assert.isFunction(transport.log); -}; - -helpers.assertWebhook = function (transport) { - assert.instanceOf(transport, winston.transports.Webhook); - assert.isFunction(transport.log); -}; - -helpers.assertCouchdb = function (transport) { - assert.instanceOf(transport, winston.transports.Couchdb); - assert.isFunction(transport.log); -}; - -helpers.assertHandleExceptions = function (options) { - return { - topic: function () { - var that = this, - child = spawn('node', [options.script]); - - helpers.tryUnlink(options.logfile); - child.on('exit', function () { - fs.readFile(options.logfile, that.callback); - }); - }, - "should save the error information to the specified file": function (err, data) { - assert.isTrue(!err); - data = JSON.parse(data); - - assert.isObject(data); - helpers.assertProcessInfo(data.process); - helpers.assertOsInfo(data.os); - helpers.assertTrace(data.trace); - } - } -} - -helpers.testNpmLevels = function (transport, assertMsg, assertFn) { - return helpers.testLevels(winston.config.npm.levels, transport, assertMsg, assertFn); -}; - -helpers.testSyslogLevels = function (transport, assertMsg, assertFn) { - return helpers.testLevels(winston.config.syslog.levels, transport, assertMsg, assertFn); -}; - -helpers.testLevels = function (levels, transport, assertMsg, assertFn) { - var tests = {}; - - Object.keys(levels).forEach(function (level) { - var test = { - topic: function () { - transport.log(level, 'test message', {}, this.callback.bind(this, null)); - } - }; - - test[assertMsg] = assertFn; - tests['with the ' + level + ' level'] = test; - }); - - var metadatatest = { - topic: function () { - transport.log('info', 'test message', { metadata: true }, this.callback.bind(this, null)); - } - }; - - metadatatest[assertMsg] = assertFn; - tests['when passed metadata'] = metadatatest; - - var primmetadatatest = { - topic: function () { - transport.log('info', 'test message', 'metadata', this.callback.bind(this, null)); - } - }; - - primmetadatatest[assertMsg] = assertFn; - tests['when passed primitive metadata'] = primmetadatatest; - - return tests; -}; diff --git a/node_modules/winston/test/log-exception-test.js b/node_modules/winston/test/log-exception-test.js deleted file mode 100644 index b077a0a..0000000 --- a/node_modules/winston/test/log-exception-test.js +++ /dev/null @@ -1,58 +0,0 @@ -/* - * exception-test.js: Tests for exception data gathering in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - path = require('path'), - spawn = require('child_process').spawn, - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/exceptions').addBatch({ - "When using winston": { - "the handleException() method": { - "with a custom winston.Logger instance": helpers.assertHandleExceptions({ - script: path.join(__dirname, 'fixtures', 'scripts', 'log-exceptions.js'), - logfile: path.join(__dirname, 'fixtures', 'logs', 'exception.log') - }), - "with the default winston logger": helpers.assertHandleExceptions({ - script: path.join(__dirname, 'fixtures', 'scripts', 'default-exceptions.js'), - logfile: path.join(__dirname, 'fixtures', 'logs', 'default-exception.log') - }), - "when a custom exitOnError function is set": { - topic: function () { - var that = this, - scriptDir = path.join(__dirname, 'fixtures', 'scripts'); - - that.child = spawn('node', [path.join(scriptDir, 'exit-on-error.js')]); - setTimeout(this.callback.bind(this), 1500); - }, - "should not exit the process": function () { - assert.isFalse(this.child.killed); - this.child.kill(); - } - } - }, - "the unhandleException() method": { - topic: function () { - var that = this, - child = spawn('node', [path.join(__dirname, 'fixtures', 'scripts', 'unhandle-exceptions.js')]), - exception = path.join(__dirname, 'fixtures', 'logs', 'unhandle-exception.log'); - - helpers.tryUnlink(exception); - child.on('exit', function () { - path.exists(exception, that.callback.bind(this, null)); - }); - }, - "should not write to the specified error file": function (err, exists) { - assert.isTrue(!err); - assert.isFalse(exists); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/log-rewriter-test.js b/node_modules/winston/test/log-rewriter-test.js deleted file mode 100644 index 4753fcc..0000000 --- a/node_modules/winston/test/log-rewriter-test.js +++ /dev/null @@ -1,98 +0,0 @@ -/* - * log-rewriter-test.js: Tests for rewriting metadata in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/rewriter').addBatch({ - "An instance of winston.Logger": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info' }) - ]}), - "the addRewriter() method": { - topic: function(logger) { - logger.addRewriter(function(level, msg, meta) { - meta.level = level; - meta.msg = msg; - meta.foo = 'bar'; - return meta; - }); - return logger; - }, - "should add the rewriter": function(logger) { - assert.equal(helpers.size(logger.rewriters), 1); - }, - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"a": "b"}); - }, - "should run the rewriter": function(transport, level, msg, meta) { - assert.equal(meta.a, 'b'); - assert.equal(meta.level, 'info'); - assert.equal(meta.msg, 'test message'); - assert.equal(meta.foo, 'bar'); - } - } - } - } -}).addBatch({ - "An instance of winston.Logger with explicit rewriter": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info'}) - ], rewriters: [ - function(level, msg, meta) { - meta.level = level; - meta.msg = msg; - meta.foo = 'bar'; - return meta; - } - ]}), - "should add the rewriter": function(logger) { - assert.equal(helpers.size(logger.rewriters), 1); - }, - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"a": "b"}); - }, - "should run the rewriter": function(transport, level, msg, meta) { - assert.equal(meta.a, 'b'); - assert.equal(meta.level, 'info'); - assert.equal(meta.msg, 'test message'); - assert.equal(meta.foo, 'bar'); - } - } - } -}).addBatch({ - "An instance of winston.Logger with rewriters": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info' }) - ], rewriters: [ - function(level, msg, meta) { - meta.numbers.push(1); - return meta; - }, - function(level, msg, meta) { - meta.numbers.push(2); - return meta; - } - ]}), - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"numbers": [0]}); - }, - "should run the rewriters in correct order": function(transport, level, msg, meta) { - assert.deepEqual(meta.numbers, [0, 1, 2]); - } - } - } -}).export(module); diff --git a/node_modules/winston/test/logger-test.js b/node_modules/winston/test/logger-test.js deleted file mode 100644 index 0105825..0000000 --- a/node_modules/winston/test/logger-test.js +++ /dev/null @@ -1,199 +0,0 @@ -/* - * logger-test.js: Tests for instances of the winston Logger - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winton/logger').addBatch({ - "An instance of winston.Logger": { - topic: new (winston.Logger)({ transports: [new (winston.transports.Console)({ level: 'info' })] }), - "should have the correct methods / properties defined": function (logger) { - helpers.assertLogger(logger); - }, - "the add() with an unsupported transport": { - "should throw an error": function () { - assert.throws(function () { logger.add('unsupported') }, Error); - } - } - } -}).addBatch({ - "An instance of winston.Logger with no transports": { - topic: new (winston.Logger)({ emitErrs: true }), - "the log() method should throw an error": function (logger) { - assert.throws(function () { logger.log('anything') }, Error); - }, - "the extend() method called on an empty object": { - topic: function (logger) { - var empty = {}; - logger.extend(empty); - return empty; - }, - "should define the appropriate methods": function (extended) { - ['log', 'profile', 'startTimer'].concat(Object.keys(winston.config.npm.levels)).forEach(function (method) { - assert.isFunction(extended[method]); - }); - } - }, - "the add() method with a supported transport": { - topic: function (logger) { - return logger.add(winston.transports.Console); - }, - "should add the console Transport onto transports": function (logger) { - assert.equal(helpers.size(logger.transports), 1); - helpers.assertConsole(logger.transports.console); - }, - "should throw an error when the same Transport is added": function (logger) { - assert.throws(function () { logger.add(winston.transports.Console) }, Error); - }, - "the log() method": { - topic: function (logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message'); - }, - "should emit the 'log' event with the appropriate transport": function (transport, ign) { - helpers.assertConsole(transport); - } - }, - "the profile() method": { - "when passed a callback": { - topic: function (logger) { - var that = this; - logger.profile('test1'); - setTimeout(function () { - logger.profile('test1', function (err, level, msg, meta) { - that.callback(err, level, msg, meta, logger); - }); - }, 1000); - }, - "should respond with the appropriate profile message": function (err, level, msg, meta, logger) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - assert.isTrue(typeof logger.profilers['test'] === 'undefined'); - } - }, - "when not passed a callback": { - topic: function (logger) { - var that = this; - logger.profile('test2'); - logger.once('logging', that.callback.bind(null, null)); - setTimeout(function () { - logger.profile('test2'); - }, 1000); - }, - "should respond with the appropriate profile message": function (err, transport, level, msg, meta) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - } - } - }, - "the startTimer() method": { - "when passed a callback": { - topic: function (logger) { - var that = this; - var timer = logger.startTimer() - setTimeout(function () { - timer.done('test', function (err, level, msg, meta) { - that.callback(err, level, msg, meta, logger); - }); - }, 1000); - }, - "should respond with the appropriate message": function (err, level, msg, meta, logger) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - } - }, - "when not passed a callback": { - topic: function (logger) { - var that = this; - var timer = logger.startTimer() - logger.once('logging', that.callback.bind(null, null)); - setTimeout(function () { - timer.done(); - }, 1000); - }, - "should respond with the appropriate message": function (err, transport, level, msg, meta) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - - var duration = parseInt(meta.duration); - assert.isNumber(duration); - assert.isTrue(duration > 900 && duration < 1100); - } - } - }, - "and adding an additional transport": { - topic: function (logger) { - return logger.add(winston.transports.File, { - filename: path.join(__dirname, 'fixtures', 'logs', 'testfile2.log') - }); - }, - "should be able to add multiple transports": function (logger) { - assert.equal(helpers.size(logger.transports), 2); - helpers.assertConsole(logger.transports.console); - helpers.assertFile(logger.transports.file); - } - } - } - } -}).addBatch({ - "The winston logger": { - topic: new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: path.join(__dirname, 'fixtures', 'logs', 'filelog.log' )}) - ] - }), - "should return have two transports": function (logger) { - assert.equal(helpers.size(logger.transports), 2); - }, - "the remove() with an unadded transport": { - "should throw an Error": function (logger) { - assert.throws(function () { logger.remove(winston.transports.Loggly) }, Error); - } - }, - "the remove() method with an added transport": { - topic: function (logger) { - return logger.remove(winston.transports.Console); - }, - "should remove the Console transport from transports": function (logger) { - assert.equal(helpers.size(logger.transports), 1); - helpers.assertFile(logger.transports.file); - }, - "and removing an additional transport": { - topic: function (logger) { - return logger.remove(winston.transports.File); - }, - "should remove File transport from transports": function (logger) { - assert.equal(helpers.size(logger.transports), 0); - } - } - } - } -}).addBatch({ - "The winston logger": { - topic: new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: path.join(__dirname, 'fixtures', 'logs', 'filelog.log' )}) - ] - }), - "the clear() method": { - "should remove all transports": function (logger) { - logger.clear(); - assert.equal(helpers.size(logger.transports), 0); - } - } - } -}).export(module); diff --git a/node_modules/winston/test/transports/console-test.js b/node_modules/winston/test/transports/console-test.js deleted file mode 100644 index 07f5a6e..0000000 --- a/node_modules/winston/test/transports/console-test.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * console-test.js: Tests for instances of the Console transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var npmTransport = new (winston.transports.Console)(), - syslogTransport = new (winston.transports.Console)({ levels: winston.config.syslog.levels }); - -vows.describe('winston/transports/console').addBatch({ - "An instance of the Console Transport": { - "with npm levels": { - "should have the proper methods defined": function () { - helpers.assertConsole(npmTransport); - }, - "the log() method": helpers.testNpmLevels(npmTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - }, - "with syslog levels": { - "should have the proper methods defined": function () { - helpers.assertConsole(syslogTransport); - }, - "the log() method": helpers.testSyslogLevels(syslogTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/transports/couchdb-test.js b/node_modules/winston/test/transports/couchdb-test.js deleted file mode 100644 index d0057e8..0000000 --- a/node_modules/winston/test/transports/couchdb-test.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * couchdb-test.js: Tests for instances of the Couchdb transport - * - * (C) 2011 Max Ogden - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - http = require('http'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var couchdbTransport = new (winston.transports.Couchdb)({ - "host": "localhost", - "port": 4567, - "db": "logs" -}); - -var server = http.createServer(function (req, res) { - res.end(); -}); - -server.listen(4567); - -vows.describe('winston/transports/couchdb').addBatch({ - "An instance of the Couchdb Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertCouchdb(couchdbTransport); - }, - "the log() method": helpers.testNpmLevels(couchdbTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "When the tests are over": { - "the server should cleanup": function () { - server.close(); - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/transports/file-maxfiles-test.js b/node_modules/winston/test/transports/file-maxfiles-test.js deleted file mode 100644 index a9fa89e..0000000 --- a/node_modules/winston/test/transports/file-maxfiles-test.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * file-maxfiles-test.js: Tests for instances of the File transport setting the max file size, - * and setting a number for max files created. - * maxSize * maxFiles = total storage used by winston. - * - * (C) 2011 Daniel Aristizabal - * MIT LICENSE - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var maxfilesTransport = new winston.transports.File({ - timestamp: false, - json: false, - filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles.log'), - maxsize: 4096, - maxFiles: 3 -}); - -vows.describe('winston/transports/file/maxfiles').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - topic: maxfilesTransport, - "should be a valid transporter": function (transportTest) { - helpers.assertFile(transportTest); - }, - "should set the maxFiles option correctly": function (transportTest) { - assert.isNumber(transportTest.maxFiles); - } - }, - "when delete old test files": { - topic: function () { - exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles*'), this.callback); - }, - "and when passed more files than the maxFiles": { - topic: function () { - var that = this, - created = 0; - - function data(ch) { - return new Array(1018).join(String.fromCharCode(65 + ch)); - }; - - function logKbytes(kbytes, txt) { - // - // With no timestamp and at the info level, - // winston adds exactly 7 characters: - // [info](4)[ :](2)[\n](1) - // - for (var i = 0; i < kbytes; i++) { - maxfilesTransport.log('info', data(txt), null, function () { }); - } - } - - maxfilesTransport.on('logged', function () { - if (++created === 6) { - return that.callback(); - } - - logKbytes(4, created); - }); - - logKbytes(4, created); - }, - "should be only 3 files called 5.log, 4.log and 3.log": function () { - for (var num = 0; num < 6; num++) { - var file = !num ? 'testmaxfiles.log' : 'testmaxfiles' + num + '.log', - fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file); - - // There should be no files with that name - if (num >= 0 && num < 3) { - return assert.throws(function () { - fs.statSync(file); - }, Error); - } - - // The other files should be exist - assert.doesNotThrow(function () { - fs.statSync(file); - }, Error); - } - }, - "should have the correct content": function () { - ['D', 'E', 'F'].forEach(function (name, inx) { - var counter = inx + 3, - logsDir = path.join(__dirname, '..', 'fixtures', 'logs'), - content = fs.readFileSync(path.join(logsDir, 'testmaxfiles' + counter + '.log'), 'utf-8'); - // The content minus the 7 characters added by winston - assert.lengthOf(content.match(new RegExp(name, 'g')), 4068); - }); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/transports/file-maxsize-test.js b/node_modules/winston/test/transports/file-maxsize-test.js deleted file mode 100644 index 7d20e08..0000000 --- a/node_modules/winston/test/transports/file-maxsize-test.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * file-test.js: Tests for instances of the File transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var maxsizeTransport = new winston.transports.File({ - timestamp: false, - json: false, - filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize.log'), - maxsize: 4096 -}); - -vows.describe('winston/transports/file/maxsize').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - "the log() method": { - topic: function () { - exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize*'), this.callback); - }, - "when passed more than the maxsize": { - topic: function () { - var that = this, - data = new Array(1018).join('-'); - - // - // Setup a list of files which we will later stat. - // - that.files = []; - - function logKbytes (kbytes) { - // - // With no timestamp and at the info level, - // winston adds exactly 7 characters: - // [info](4)[ :](2)[\n](1) - // - for (var i = 0; i < kbytes; i++) { - maxsizeTransport.log('info', data, null, function () { }); - } - } - - maxsizeTransport.on('open', function (file) { - var match = file.match(/(\d+)\.log$/), - count = match ? match[1] : 0; - - that.files.push(file); - - if (that.files.length === 5) { - return that.callback(); - } - - logKbytes(4); - }); - - logKbytes(4); - }, - "should create multiple files correctly": function () { - this.files.forEach(function (file) { - try { - var stats = fs.statSync(file); - assert.equal(stats.size, 4096); - } - catch (ex) { - assert.isNull(ex); - } - }); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/transports/file-test.js b/node_modules/winston/test/transports/file-test.js deleted file mode 100644 index c287794..0000000 --- a/node_modules/winston/test/transports/file-test.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * file-test.js: Tests for instances of the File transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var stream = fs.createWriteStream(path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log')), - fileTransport = new (winston.transports.File)({ filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfilename.log') }), - streamTransport = new (winston.transports.File)({ stream: stream }); - -vows.describe('winston/transports/file').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - "should have the proper methods defined": function () { - helpers.assertFile(fileTransport); - }, - "the log() method": helpers.testNpmLevels(fileTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - }, - "when passed a valid file stream": { - "should have the proper methods defined": function () { - helpers.assertFile(streamTransport); - }, - "the log() method": helpers.testNpmLevels(streamTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "These tests have a non-deterministic end": { - topic: function () { - setTimeout(this.callback, 200); - }, - "and this should be fixed before releasing": function () { - assert.isTrue(true); - } - } -}).export(module); \ No newline at end of file diff --git a/node_modules/winston/test/transports/loggly-test.js b/node_modules/winston/test/transports/loggly-test.js deleted file mode 100644 index 8271b90..0000000 --- a/node_modules/winston/test/transports/loggly-test.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * loggly-test.js: Tests for instances of the Loggly transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var config = helpers.loadConfig(); - -if (!config) { - return; -} - -var tokenTransport = new (winston.transports.Loggly)({ - subdomain: config.transports.loggly.subdomain, - inputToken: config.transports.loggly.inputToken - }), - nameTransport = new (winston.transports.Loggly)({ - subdomain: config.transports.loggly.subdomain, - inputName: config.transports.loggly.inputName, - auth: config.transports.loggly.auth - }); - -vows.describe('winston/transports/loggly').addBatch({ - "An instance of the Loggly Transport": { - "when passed an input token": { - "should have the proper methods defined": function () { - helpers.assertLoggly(tokenTransport); - }, - "the log() method": helpers.testNpmLevels(tokenTransport, "should log messages to loggly", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }), - "the log() method with no metadata": { - topic: function () { - tokenTransport.log('info', 'test-message', null, this.callback.bind(null, null)); - }, - "should respond immediately": function () { - assert.isTrue(true); - } - } - }, - "when passed an input name": { - "should have the proper methods defined": function () { - helpers.assertLoggly(nameTransport); - }, - "the log() method": helpers.testNpmLevels(nameTransport, "should log messages to loggly", function (ign, err, result) { - assert.isNull(err); - assert.isTrue(result === true || result.response === 'ok'); - }) - } - } -}).export(module); - diff --git a/node_modules/winston/test/transports/webhook-test.js b/node_modules/winston/test/transports/webhook-test.js deleted file mode 100644 index e106374..0000000 --- a/node_modules/winston/test/transports/webhook-test.js +++ /dev/null @@ -1,119 +0,0 @@ -/* - * webhook-test.js: Tests for instances of the Webhook transport - * - * (C) 2011 Marak Squires - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - http = require('http'), - https = require('https'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var webhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8080, - "path": "/winston-test" -}); - -var httpsWebhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8081, - "path": "/winston-test", - "ssl": true -}); - -var authWebhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8080, - "path": "/winston-auth-test", - "auth": { - "username": "winston", - "password": "churchill" - } -}); - -var requestsAuthenticated = true; - -var server = http.createServer(function (req, res) { - if (req.url == '/winston-auth-test') { - // - // Test if request has been correctly authenticated - // - // Strip 'Basic' from Authorization header - var signature = req.headers['authorization'].substr(6); - requestsAuthenticated = requestsAuthenticated && - new Buffer(signature, 'base64').toString('utf8') == 'winston:churchill'; - } - res.end(); -}); - -server.listen(8080); - - -var httpsServer = https.createServer({ - cert: fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'keys', 'agent2-cert.pem')), - key: fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'keys', 'agent2-key.pem')) -}, function (req, res) { - res.end(); -}); - -httpsServer.listen(8081); - -vows.describe('winston/transports/webhook').addBatch({ - "An instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(webhookTransport); - }, - "the log() method": helpers.testNpmLevels(webhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - }, - "An https instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(httpsWebhookTransport); - }, - "the log() method": helpers.testNpmLevels(httpsWebhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - }, - "An http Basic Auth instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(authWebhookTransport); - }, - "the log() method": helpers.testNpmLevels(authWebhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "When the tests are over": { - topic: function () { - // - // Delay destruction of the server since the - // WebHook transport responds before the request - // has actually be completed. - // - setTimeout(this.callback, 1000); - }, - "the server should cleanup": function () { - server.close(); - }, - "requests have been correctly authenticated": function () { - assert.ok(requestsAuthenticated); - } - } -}).export(module); diff --git a/node_modules/winston/test/winston-test.js b/node_modules/winston/test/winston-test.js deleted file mode 100644 index e790cb9..0000000 --- a/node_modules/winston/test/winston-test.js +++ /dev/null @@ -1,100 +0,0 @@ -/* - * logger-test.js: Tests for instances of the winston Logger - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var fs = require('fs'), - path = require('path'), - vows = require('vows'), - http = require('http'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston').addBatch({ - "The winston module": { - topic: function () { - winston.default.transports.console.level = 'silly'; - return null; - }, - "should have the correct methods defined": function () { - assert.isObject(winston.transports); - assert.isFunction(winston.Transport); - assert.isTrue(!winston.transports.Transport); - assert.isFunction(winston.transports.Console); - assert.isFunction(winston.transports.File); - assert.isFunction(winston.transports.Loggly); - assert.isFunction(winston.transports.Webhook); - assert.isObject(winston.default.transports.console); - assert.isFalse(winston.emitErrs); - assert.isObject(winston.config); - ['Logger', 'add', 'remove', 'extend'] - .concat(Object.keys(winston.config.npm.levels)) - .forEach(function (key) { - assert.isFunction(winston[key]); - }); - }, - "it should": { - topic: function () { - fs.readFile(path.join(__dirname, '..', 'package.json'), this.callback); - }, - "have the correct version set": function (err, data) { - assert.isNull(err); - data = JSON.parse(data.toString()); - assert.equal(winston.version, data.version); - } - }, - "the log() method": helpers.testNpmLevels(winston, "should respond without an error", function (err) { - assert.isNull(err); - }), - "the extend() method called on an empty object": { - topic: function (logger) { - var empty = {}; - winston.extend(empty); - return empty; - }, - "should define the appropriate methods": function (extended) { - ['log', 'profile', 'startTimer'].concat(Object.keys(winston.config.npm.levels)).forEach(function (method) { - assert.isFunction(extended[method]); - }); - } - } - } -}).addBatch({ - "The winston module": { - "the setLevels() method": { - topic: function () { - winston.setLevels(winston.config.syslog.levels); - return null; - }, - "should have the proper methods defined": function () { - assert.isObject(winston.transports); - assert.isFunction(winston.transports.Console); - assert.isFunction(winston.transports.Loggly); - assert.isFunction(winston.transports.Webhook); - assert.isObject(winston.default.transports.console); - assert.isFalse(winston.emitErrs); - assert.isObject(winston.config); - - var newLevels = Object.keys(winston.config.syslog.levels); - ['Logger', 'add', 'remove', 'extend'] - .concat(newLevels) - .forEach(function (key) { - assert.isFunction(winston[key]); - }); - - - Object.keys(winston.config.npm.levels) - .filter(function (key) { - return newLevels.indexOf(key) === -1; - }) - .forEach(function (key) { - assert.isTrue(typeof winston[key] === 'undefined'); - }); - } - } - } -}).export(module);