'));
+ el.append(stack[0]);
+ });
+
+ runner.on('suite end', function(suite){
+ if (suite.root) return;
+ stack.shift();
+ });
+
+ runner.on('fail', function(test, err){
+ if (err.uncaught) runner.emit('test end', test);
+ });
+
+ runner.on('test end', function(test){
+ // TODO: add to stats
+ var percent = stats.tests / total * 100 | 0;
+
+ if (progress) {
+ progress.update(percent).draw(ctx);
+ }
+
+ // 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 = $('
' + escape(test.title) + '
')
+ } else if (test.pending) {
+ var el = $('
' + escape(test.title) + '
')
+ } else {
+ var el = $('
' + escape(test.title) + '
');
+ var str = test.err.stack || test.err;
+
+ // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+ // check for the result of the stringifying.
+ if ('[object Error]' == str) str = test.err.message;
+
+ $('
' + escape(str) + '
').appendTo(el);
+ }
+
+ // toggle code
+ el.find('h2').toggle(function(){
+ pre && pre.slideDown('fast');
+ }, function(){
+ pre && pre.slideUp('fast');
+ });
+
+ // code
+ // TODO: defer
+ if (!test.pending) {
+ var code = escape(clean(test.fn.toString()));
+ var pre = $('
'));
+ el.append(stack[0]);
+ });
+
+ runner.on('suite end', function(suite){
+ if (suite.root) return;
+ stack.shift();
+ });
+
+ runner.on('fail', function(test, err){
+ if (err.uncaught) runner.emit('test end', test);
+ });
+
+ runner.on('test end', function(test){
+ // TODO: add to stats
+ var percent = stats.tests / total * 100 | 0;
+
+ if (progress) {
+ progress.update(percent).draw(ctx);
+ }
+
+ // 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 = $('
' + escape(test.title) + '
')
+ } else if (test.pending) {
+ var el = $('
' + escape(test.title) + '
')
+ } else {
+ var el = $('
' + escape(test.title) + '
');
+ var str = test.err.stack || test.err;
+
+ // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+ // check for the result of the stringifying.
+ if ('[object Error]' == str) str = test.err.message;
+
+ $('
' + escape(str) + '
').appendTo(el);
+ }
+
+ // toggle code
+ el.find('h2').toggle(function(){
+ pre && pre.slideDown('fast');
+ }, function(){
+ pre && pre.slideUp('fast');
+ });
+
+ // code
+ // TODO: defer
+ if (!test.pending) {
+ var code = escape(clean(test.fn.toString()));
+ var pre = $('
'));
+ el.append(stack[0]);
+ });
+
+ runner.on('suite end', function(suite){
+ if (suite.root) return;
+ stack.shift();
+ });
+
+ runner.on('fail', function(test, err){
+ if (err.uncaught) runner.emit('test end', test);
+ });
+
+ runner.on('test end', function(test){
+ // TODO: add to stats
+ var percent = stats.tests / total * 100 | 0;
+
+ if (progress) {
+ progress.update(percent).draw(ctx);
+ }
+
+ // 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 = $('
' + escape(test.title) + '
')
+ } else if (test.pending) {
+ var el = $('
' + escape(test.title) + '
')
+ } else {
+ var el = $('
' + escape(test.title) + '
');
+ var str = test.err.stack || test.err;
+
+ // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+ // check for the result of the stringifying.
+ if ('[object Error]' == str) str = test.err.message;
+
+ $('
' + escape(str) + '
').appendTo(el);
+ }
+
+ // toggle code
+ el.find('h2').toggle(function(){
+ pre && pre.slideDown('fast');
+ }, function(){
+ pre && pre.slideUp('fast');
+ });
+
+ // code
+ // TODO: defer
+ if (!test.pending) {
+ var code = escape(clean(test.fn.toString()));
+ var pre = $('
1 UglifyJS — a JavaScript parser/compressor/beautifier
+
+
+
+
+This package implements a general-purpose JavaScript
+parser/compressor/beautifier toolkit. It is developed on NodeJS, but it
+should work on any JavaScript platform supporting the CommonJS module system
+(and if your platform of choice doesn't support CommonJS, you can easily
+implement it, or discard the exports.* lines from UglifyJS sources).
+
+
+The tokenizer/parser generates an abstract syntax tree from JS code. You
+can then traverse the AST to learn more about the code, or do various
+manipulations on it. This part is implemented in parse-js.js and it's a
+port to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke.
+
+
+( See cl-uglify-js if you're looking for the Common Lisp version of
+UglifyJS. )
+
+
+The second part of this package, implemented in process.js, inspects and
+manipulates the AST generated by the parser to provide the following:
+
+
+
ability to re-generate JavaScript code from the AST. Optionally
+ indented—you can use this if you want to “beautify” a program that has
+ been compressed, so that you can inspect the source. But you can also run
+ our code generator to print out an AST without any whitespace, so you
+ achieve compression as well.
+
+
+
shorten variable names (usually to single characters). Our mangler will
+ analyze the code and generate proper variable names, depending on scope
+ and usage, and is smart enough to deal with globals defined elsewhere, or
+ with eval() calls or with{} statements. In short, if eval() or
+ with{} are used in some scope, then all variables in that scope and any
+ variables in the parent scopes will remain unmangled, and any references
+ to such variables remain unmangled as well.
+
+
+
various small optimizations that may lead to faster code but certainly
+ lead to smaller code. Where possible, we do the following:
+
+
+
foo["bar"] ==> foo.bar
+
+
+
remove block brackets {}
+
+
+
join consecutive var declarations:
+ var a = 10; var b = 20; ==> var a=10,b=20;
+
+
+
resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
+ replacement if the result occupies less bytes; for example 1/3 would
+ translate to 0.333333333333, so in this case we don't replace it.
+
+
+
consecutive statements in blocks are merged into a sequence; in many
+ cases, this leaves blocks with a single statement, so then we can remove
+ the block brackets.
+
+
+
various optimizations for IF statements:
+
+
+
if (foo) bar(); else baz(); ==> foo?bar():baz();
+
+
if (!foo) bar(); else baz(); ==> foo?baz():bar();
+
remove some unreachable code and warn about it (code that follows a
+ return, throw, break or continue statement, except
+ function/variable declarations).
+
+
+
act a limited version of a pre-processor (c.f. the pre-processor of
+ C/C++) to allow you to safely replace selected global symbols with
+ specified values. When combined with the optimisations above this can
+ make UglifyJS operate slightly more like a compilation process, in
+ that when certain symbols are replaced by constant values, entire code
+ blocks may be optimised away as unreachable.
+
+
+
+
+
+
+
+
+
+
+
+
1.1Unsafe transformations
+
+
+
+
+The following transformations can in theory break code, although they're
+probably safe in most practical cases. To enable them you need to pass the
+--unsafe flag.
+
+
+
+
+
+
1.1.1 Calls involving the global Array constructor
+These are all safe if the Array name isn't redefined. JavaScript does allow
+one to globally redefine Array (and pretty much everything, in fact) but I
+personally don't see why would anyone do that.
+
+
+UglifyJS does handle the case where Array is redefined locally, or even
+globally but with a function or var declaration. Therefore, in the
+following cases UglifyJS doesn't touch calls or instantiations of Array:
+
+
+
+
+
// case 1. globally declared variable
+ varArray;
+ newArray(1, 2, 3);
+ Array(a, b);
+
+ // or (can be declared later)
+ newArray(1, 2, 3);
+ varArray;
+
+ // or (can be a function)
+ newArray(1, 2, 3);
+ functionArray() { ... }
+
+// case 2. declared in a function
+ (function(){
+ a = newArray(1, 2, 3);
+ b = Array(5, 6);
+ varArray;
+ })();
+
+ // or
+ (function(Array){
+ return Array(5, 6, 7);
+ })();
+
+ // or
+ (function(){
+ returnnewArray(1, 2, 3, 4);
+ functionArray() { ... }
+ })();
+
+ // etc.
+
+
+
+
+
+
+
+
+
1.1.2obj.toString() ==> obj+“”
+
+
+
+
+
+
+
+
+
+
1.2 Install (NPM)
+
+
+
+
+UglifyJS is now available through NPM — npm install uglify-js should do
+the job.
+
+
+
+
+
+
+
1.3 Install latest code from GitHub
+
+
+
+
+
+
+
## clone the repository
+mkdir -p /where/you/wanna/put/it
+cd /where/you/wanna/put/it
+git clone git://github.com/mishoo/UglifyJS.git
+
+## make the module available to Node
+mkdir -p ~/.node_libraries/
+cd ~/.node_libraries/
+ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
+
+## and if you want the CLI script too:
+mkdir -p ~/bin
+cd ~/bin
+ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
+ # (then add ~/bin to your $PATH if it's not there already)
+
+
+
+
+
+
+
+
+
1.4 Usage
+
+
+
+
+There is a command-line tool that exposes the functionality of this library
+for your shell-scripting needs:
+
+
+
+
+
uglifyjs [ options... ] [ filename ]
+
+
+
+
+filename should be the last argument and should name the file from which
+to read the JavaScript code. If you don't specify it, it will read code
+from STDIN.
+
+
+Supported options:
+
+
+
-b or --beautify — output indented code; when passed, additional
+ options control the beautifier:
+
+
+
-i N or --indent N — indentation level (number of spaces)
+
+
+
-q or --quote-keys — quote keys in literal objects (by default,
+ only keys that cannot be identifier names will be quotes).
+
+
+
+
+
+
--ascii — pass this argument to encode non-ASCII characters as
+ \uXXXX sequences. By default UglifyJS won't bother to do it and will
+ output Unicode characters instead. (the output is always encoded in UTF8,
+ but if you pass this option you'll only get ASCII).
+
+
+
-nm or --no-mangle — don't mangle names.
+
+
+
-nmf or --no-mangle-functions – in case you want to mangle variable
+ names, but not touch function names.
+
+
+
-ns or --no-squeeze — don't call ast_squeeze() (which does various
+ optimizations that result in smaller, less readable code).
+
+
+
-mt or --mangle-toplevel — mangle names in the toplevel scope too
+ (by default we don't do this).
+
+
+
--no-seqs — when ast_squeeze() is called (thus, unless you pass
+ --no-squeeze) it will reduce consecutive statements in blocks into a
+ sequence. For example, "a = 10; b = 20; foo();" will be written as
+ "a=10,b=20,foo();". In various occasions, this allows us to discard the
+ block brackets (since the block becomes a single statement). This is ON
+ by default because it seems safe and saves a few hundred bytes on some
+ libs that I tested it on, but pass --no-seqs to disable it.
+
+
+
--no-dead-code — by default, UglifyJS will remove code that is
+ obviously unreachable (code that follows a return, throw, break or
+ continue statement and is not a function/variable declaration). Pass
+ this option to disable this optimization.
+
+
+
-nc or --no-copyright — by default, uglifyjs will keep the initial
+ comment tokens in the generated code (assumed to be copyright information
+ etc.). If you pass this it will discard it.
+
+
+
-o filename or --output filename — put the result in filename. If
+ this isn't given, the result goes to standard output (or see next one).
+
+
+
--overwrite — if the code is read from a file (not from STDIN) and you
+ pass --overwrite then the output will be written in the same file.
+
+
+
--ast — pass this if you want to get the Abstract Syntax Tree instead
+ of JavaScript as output. Useful for debugging or learning more about the
+ internals.
+
+
+
-v or --verbose — output some notes on STDERR (for now just how long
+ each operation takes).
+
+
+
-d SYMBOL[=VALUE] or --define SYMBOL[=VALUE] — will replace
+ all instances of the specified symbol where used as an identifier
+ (except where symbol has properly declared by a var declaration or
+ use as function parameter or similar) with the specified value. This
+ argument may be specified multiple times to define multiple
+ symbols - if no value is specified the symbol will be replaced with
+ the value true, or you can specify a numeric value (such as
+ 1024), a quoted string value (such as ="object"= or
+ ='https://github.com'), or the name of another symbol or keyword (such as =null or document).
+ This allows you, for example, to assign meaningful names to key
+ constant values but discard the symbolic names in the uglified
+ version for brevity/efficiency, or when used wth care, allows
+ UglifyJS to operate as a form of conditional compilation
+ whereby defining appropriate values may, by dint of the constant
+ folding and dead code removal features above, remove entire
+ superfluous code blocks (e.g. completely remove instrumentation or
+ trace code for production use).
+ Where string values are being defined, the handling of quotes are
+ likely to be subject to the specifics of your command shell
+ environment, so you may need to experiment with quoting styles
+ depending on your platform, or you may find the option
+ --define-from-module more suitable for use.
+
+
+
-define-from-module SOMEMODULE — will load the named module (as
+ per the NodeJS require() function) and iterate all the exported
+ properties of the module defining them as symbol names to be defined
+ (as if by the --define option) per the name of each property
+ (i.e. without the module name prefix) and given the value of the
+ property. This is a much easier way to handle and document groups of
+ symbols to be defined rather than a large number of --define
+ options.
+
+
+
--unsafe — enable other additional optimizations that are known to be
+ unsafe in some contrived situations, but could still be generally useful.
+ For now only these:
+
+
+
foo.toString() ==> foo+""
+
+
new Array(x,…) ==> [x,…]
+
+
new Array(x) ==> Array(x)
+
+
+
+
+
+
--max-line-len (default 32K characters) — add a newline after around
+ 32K characters. I've seen both FF and Chrome croak when all the code was
+ on a single line of around 670K. Pass –max-line-len 0 to disable this
+ safety feature.
+
+
+
--reserved-names — some libraries rely on certain names to be used, as
+ pointed out in issue #92 and #81, so this option allow you to exclude such
+ names from the mangler. For example, to keep names require and $super
+ intact you'd specify –reserved-names "require,$super".
+
+
+
--inline-script – when you want to include the output literally in an
+ HTML <script> tag you can use this option to prevent </script from
+ showing up in the output.
+
+
+
--lift-vars – when you pass this, UglifyJS will apply the following
+ transformations (see the notes in API, ast_lift_variables):
+
+
+
put all var declarations at the start of the scope
+
+
make sure a variable is declared only once
+
+
discard unused function arguments
+
+
discard unused inner (named) functions
+
+
finally, try to merge assignments into that one var declaration, if
+ possible.
+
+
+
+
+
+
+
+
+
+
+
+
1.4.1 API
+
+
+
+
+To use the library from JavaScript, you'd do the following (example for
+NodeJS):
+
+
+
+
+
varjsp = require("uglify-js").parser;
+varpro = require("uglify-js").uglify;
+
+varorig_code = "... JS code here";
+varast = jsp.parse(orig_code); // parse code and get the initial AST
+ast = pro.ast_mangle(ast); // get a new AST with mangled names
+ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
+varfinal_code = pro.gen_code(ast); // compressed code here
+
+
+
+
+The above performs the full compression that is possible right now. As you
+can see, there are a sequence of steps which you can apply. For example if
+you want compressed output but for some reason you don't want to mangle
+variable names, you would simply skip the line that calls
+pro.ast_mangle(ast).
+
+
+Some of these functions take optional arguments. Here's a description:
+
+
+
jsp.parse(code, strict_semicolons) – parses JS code and returns an AST.
+ strict_semicolons is optional and defaults to false. If you pass
+ true then the parser will throw an error when it expects a semicolon and
+ it doesn't find it. For most JS code you don't want that, but it's useful
+ if you want to strictly sanitize your code.
+
+
+
pro.ast_lift_variables(ast) – merge and move var declarations to the
+ scop of the scope; discard unused function arguments or variables; discard
+ unused (named) inner functions. It also tries to merge assignments
+ following the var declaration into it.
+
+
+ If your code is very hand-optimized concerning var declarations, this
+ lifting variable declarations might actually increase size. For me it
+ helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
+ note that (since it's not enabled by default) this operation isn't yet
+ heavily tested (please report if you find issues!).
+
+
+ Note that although it might increase the image size (on jQuery it gains
+ 865 bytes, 243 after gzip) it's technically more correct: in certain
+ situations, dead code removal might drop variable declarations, which
+ would not happen if the variables are lifted in advance.
+
+
+ Here's an example of what it does:
+
+
+
+
+
+
+
+
functionf(a, b, c, d, e) {
+ varq;
+ varw;
+ w = 10;
+ q = 20;
+ for (vari = 1; i < 10; ++i) {
+ varboo = foo(a);
+ }
+ for (vari = 0; i < 1; ++i) {
+ varboo = bar(c);
+ }
+ functionfoo(){ ... }
+ functionbar(){ ... }
+ functionbaz(){ ... }
+}
+
+// transforms into ==>
+
+functionf(a, b, c) {
+ vari, boo, w = 10, q = 20;
+ for (i = 1; i < 10; ++i) {
+ boo = foo(a);
+ }
+ for (i = 0; i < 1; ++i) {
+ boo = bar(c);
+ }
+ functionfoo() { ... }
+ functionbar() { ... }
+}
+
+
+
+
+
pro.ast_mangle(ast, options) – generates a new AST containing mangled
+ (compressed) variable and function names. It supports the following
+ options:
+
+
except – an array of names to exclude from compression.
+
+
defines – an object with properties named after symbols to
+ replace (see the --define option for the script) and the values
+ representing the AST replacement value.
+
+
+
+
+
+
pro.ast_squeeze(ast, options) – employs further optimizations designed
+ to reduce the size of the code that gen_code would generate from the
+ AST. Returns a new AST. options can be a hash; the supported options
+ are:
+
+
+
make_seqs (default true) which will cause consecutive statements in a
+ block to be merged using the "sequence" (comma) operator
+
+
+
dead_code (default true) which will remove unreachable code.
+
+
+
+
+
+
pro.gen_code(ast, options) – generates JS code from the AST. By
+ default it's minified, but using the options argument you can get nicely
+ formatted output. options is, well, optional :-) and if you pass it it
+ must be an object and supports the following properties (below you can see
+ the default values):
+
+
+
beautify: false – pass true if you want indented output
+
+
indent_start: 0 (only applies when beautify is true) – initial
+ indentation in spaces
+
+
indent_level: 4 (only applies when beautify is true) --
+ indentation level, in spaces (pass an even number)
+
+
quote_keys: false – if you pass true it will quote all keys in
+ literal objects
+
+
space_colon: false (only applies when beautify is true) – wether
+ to put a space before the colon in object literals
+
+
ascii_only: false – pass true if you want to encode non-ASCII
+ characters as \uXXXX.
+
+
inline_script: false – pass true to escape occurrences of
+ </script in strings
+
+
+
+
+
+
+
+
+
+
+
+
+
1.4.2 Beautifier shortcoming – no more comments
+
+
+
+
+The beautifier can be used as a general purpose indentation tool. It's
+useful when you want to make a minified file readable. One limitation,
+though, is that it discards all comments, so you don't really want to use it
+to reformat your code, unless you don't have, or don't care about, comments.
+
+
+In fact it's not the beautifier who discards comments — they are dumped at
+the parsing stage, when we build the initial AST. Comments don't really
+make sense in the AST, and while we could add nodes for them, it would be
+inconvenient because we'd have to add special rules to ignore them at all
+the processing stages.
+
+
+
+
+
+
+
1.4.3 Use as a code pre-processor
+
+
+
+
+The --define option can be used, particularly when combined with the
+constant folding logic, as a form of pre-processor to enable or remove
+particular constructions, such as might be used for instrumenting
+development code, or to produce variations aimed at a specific
+platform.
+
+
+The code below illustrates the way this can be done, and how the
+symbol replacement is performed.
+
+When the above code is normally executed, the undeclared global
+variable DEVMODE will be assigned the value true (see CLAUSE1)
+and so the init() function (CLAUSE2) will write messages to the
+console log when executed, but in CLAUSE3 a locally declared
+variable will mask access to the DEVMODE global symbol.
+
+
+If the above code is processed by UglifyJS with an argument of
+--define DEVMODE=false then UglifyJS will replace DEVMODE with the
+boolean constant value false within CLAUSE1 and CLAUSE2, but it
+will leave CLAUSE3 as it stands because there DEVMODE resolves to
+a validly declared variable.
+
+
+And more so, the constant-folding features of UglifyJS will recognise
+that the if condition of CLAUSE1 is thus always false, and so will
+remove the test and body of CLAUSE1 altogether (including the
+otherwise slightly problematical statement false = true; which it
+will have formed by replacing DEVMODE in the body). Similarly,
+within CLAUSE2 both calls to console.log() will be removed
+altogether.
+
+
+In this way you can mimic, to a limited degree, the functionality of
+the C/C++ pre-processor to enable or completely remove blocks
+depending on how certain symbols are defined - perhaps using UglifyJS
+to generate different versions of source aimed at different
+environments
+
+
+It is recommmended (but not made mandatory) that symbols designed for
+this purpose are given names consisting of UPPER_CASE_LETTERS to
+distinguish them from other (normal) symbols and avoid the sort of
+clash that CLAUSE3 above illustrates.
+
+
+
+
+
+
+
+
1.5 Compression – how good is it?
+
+
+
+
+Here are updated statistics. (I also updated my Google Closure and YUI
+installations).
+
+
+We're still a lot better than YUI in terms of compression, though slightly
+slower. We're still a lot faster than Closure, and compression after gzip
+is comparable.
+
+
+
+
+
+
+
File
UglifyJS
UglifyJS+gzip
Closure
Closure+gzip
YUI
YUI+gzip
+
+
+
jquery-1.6.2.js
91001 (0:01.59)
31896
90678 (0:07.40)
31979
101527 (0:01.82)
34646
+
paper.js
142023 (0:01.65)
43334
134301 (0:07.42)
42495
173383 (0:01.58)
48785
+
prototype.js
88544 (0:01.09)
26680
86955 (0:06.97)
26326
92130 (0:00.79)
28624
+
thelib-full.js (DynarchLIB)
251939 (0:02.55)
72535
249911 (0:09.05)
72696
258869 (0:01.94)
76584
+
+
+
+
+
+
+
+
+
+
1.6 Bugs?
+
+
+
+
+Unfortunately, for the time being there is no automated test suite. But I
+ran the compressor manually on non-trivial code, and then I tested that the
+generated code works as expected. A few hundred times.
+
+
+DynarchLIB was started in times when there was no good JS minifier.
+Therefore I was quite religious about trying to write short code manually,
+and as such DL contains a lot of syntactic hacks1 such as “foo == bar ? a
+= 10 : b = 20”, though the more readable version would clearly be to use
+“if/else”.
+
+
+Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
+that it's solid enough for production use. If you can identify any bugs,
+I'd love to hear about them (use the Google Group or email me directly).
+
Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
+Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+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.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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.
+
+
+
+
+
Footnotes:
+
+
1 I even reported a few bugs and suggested some fixes in the original
+ parse-js library, and Marijn pushed fixes literally in minutes.
+
+
+
diff --git a/node_modules/uglify-js/README.org b/node_modules/uglify-js/README.org
new file mode 100644
index 0000000..4d01fdf
--- /dev/null
+++ b/node_modules/uglify-js/README.org
@@ -0,0 +1,574 @@
+#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier
+#+KEYWORDS: javascript, js, parser, compiler, compressor, mangle, minify, minifier
+#+DESCRIPTION: a JavaScript parser/compressor/beautifier in JavaScript
+#+STYLE:
+#+AUTHOR: Mihai Bazon
+#+EMAIL: mihai.bazon@gmail.com
+
+* UglifyJS --- a JavaScript parser/compressor/beautifier
+
+This package implements a general-purpose JavaScript
+parser/compressor/beautifier toolkit. It is developed on [[http://nodejs.org/][NodeJS]], but it
+should work on any JavaScript platform supporting the CommonJS module system
+(and if your platform of choice doesn't support CommonJS, you can easily
+implement it, or discard the =exports.*= lines from UglifyJS sources).
+
+The tokenizer/parser generates an abstract syntax tree from JS code. You
+can then traverse the AST to learn more about the code, or do various
+manipulations on it. This part is implemented in [[../lib/parse-js.js][parse-js.js]] and it's a
+port to JavaScript of the excellent [[http://marijn.haverbeke.nl/parse-js/][parse-js]] Common Lisp library from [[http://marijn.haverbeke.nl/][Marijn
+Haverbeke]].
+
+( See [[http://github.com/mishoo/cl-uglify-js][cl-uglify-js]] if you're looking for the Common Lisp version of
+UglifyJS. )
+
+The second part of this package, implemented in [[../lib/process.js][process.js]], inspects and
+manipulates the AST generated by the parser to provide the following:
+
+- ability to re-generate JavaScript code from the AST. Optionally
+ indented---you can use this if you want to “beautify” a program that has
+ been compressed, so that you can inspect the source. But you can also run
+ our code generator to print out an AST without any whitespace, so you
+ achieve compression as well.
+
+- shorten variable names (usually to single characters). Our mangler will
+ analyze the code and generate proper variable names, depending on scope
+ and usage, and is smart enough to deal with globals defined elsewhere, or
+ with =eval()= calls or =with{}= statements. In short, if =eval()= or
+ =with{}= are used in some scope, then all variables in that scope and any
+ variables in the parent scopes will remain unmangled, and any references
+ to such variables remain unmangled as well.
+
+- various small optimizations that may lead to faster code but certainly
+ lead to smaller code. Where possible, we do the following:
+
+ - foo["bar"] ==> foo.bar
+
+ - remove block brackets ={}=
+
+ - join consecutive var declarations:
+ var a = 10; var b = 20; ==> var a=10,b=20;
+
+ - resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
+ replacement if the result occupies less bytes; for example 1/3 would
+ translate to 0.333333333333, so in this case we don't replace it.
+
+ - consecutive statements in blocks are merged into a sequence; in many
+ cases, this leaves blocks with a single statement, so then we can remove
+ the block brackets.
+
+ - various optimizations for IF statements:
+
+ - if (foo) bar(); else baz(); ==> foo?bar():baz();
+ - if (!foo) bar(); else baz(); ==> foo?baz():bar();
+ - if (foo) bar(); ==> foo&&bar();
+ - if (!foo) bar(); ==> foo||bar();
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
+
+ - remove some unreachable code and warn about it (code that follows a
+ =return=, =throw=, =break= or =continue= statement, except
+ function/variable declarations).
+
+ - act a limited version of a pre-processor (c.f. the pre-processor of
+ C/C++) to allow you to safely replace selected global symbols with
+ specified values. When combined with the optimisations above this can
+ make UglifyJS operate slightly more like a compilation process, in
+ that when certain symbols are replaced by constant values, entire code
+ blocks may be optimised away as unreachable.
+
+** <>
+
+The following transformations can in theory break code, although they're
+probably safe in most practical cases. To enable them you need to pass the
+=--unsafe= flag.
+
+*** Calls involving the global Array constructor
+
+The following transformations occur:
+
+#+BEGIN_SRC js
+new Array(1, 2, 3, 4) => [1,2,3,4]
+Array(a, b, c) => [a,b,c]
+new Array(5) => Array(5)
+new Array(a) => Array(a)
+#+END_SRC
+
+These are all safe if the Array name isn't redefined. JavaScript does allow
+one to globally redefine Array (and pretty much everything, in fact) but I
+personally don't see why would anyone do that.
+
+UglifyJS does handle the case where Array is redefined locally, or even
+globally but with a =function= or =var= declaration. Therefore, in the
+following cases UglifyJS *doesn't touch* calls or instantiations of Array:
+
+#+BEGIN_SRC js
+// case 1. globally declared variable
+ var Array;
+ new Array(1, 2, 3);
+ Array(a, b);
+
+ // or (can be declared later)
+ new Array(1, 2, 3);
+ var Array;
+
+ // or (can be a function)
+ new Array(1, 2, 3);
+ function Array() { ... }
+
+// case 2. declared in a function
+ (function(){
+ a = new Array(1, 2, 3);
+ b = Array(5, 6);
+ var Array;
+ })();
+
+ // or
+ (function(Array){
+ return Array(5, 6, 7);
+ })();
+
+ // or
+ (function(){
+ return new Array(1, 2, 3, 4);
+ function Array() { ... }
+ })();
+
+ // etc.
+#+END_SRC
+
+*** =obj.toString()= ==> =obj+“”=
+
+** Install (NPM)
+
+UglifyJS is now available through NPM --- =npm install uglify-js= should do
+the job.
+
+** Install latest code from GitHub
+
+#+BEGIN_SRC sh
+## clone the repository
+mkdir -p /where/you/wanna/put/it
+cd /where/you/wanna/put/it
+git clone git://github.com/mishoo/UglifyJS.git
+
+## make the module available to Node
+mkdir -p ~/.node_libraries/
+cd ~/.node_libraries/
+ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
+
+## and if you want the CLI script too:
+mkdir -p ~/bin
+cd ~/bin
+ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
+ # (then add ~/bin to your $PATH if it's not there already)
+#+END_SRC
+
+** Usage
+
+There is a command-line tool that exposes the functionality of this library
+for your shell-scripting needs:
+
+#+BEGIN_SRC sh
+uglifyjs [ options... ] [ filename ]
+#+END_SRC
+
+=filename= should be the last argument and should name the file from which
+to read the JavaScript code. If you don't specify it, it will read code
+from STDIN.
+
+Supported options:
+
+- =-b= or =--beautify= --- output indented code; when passed, additional
+ options control the beautifier:
+
+ - =-i N= or =--indent N= --- indentation level (number of spaces)
+
+ - =-q= or =--quote-keys= --- quote keys in literal objects (by default,
+ only keys that cannot be identifier names will be quotes).
+
+- =--ascii= --- pass this argument to encode non-ASCII characters as
+ =\uXXXX= sequences. By default UglifyJS won't bother to do it and will
+ output Unicode characters instead. (the output is always encoded in UTF8,
+ but if you pass this option you'll only get ASCII).
+
+- =-nm= or =--no-mangle= --- don't mangle names.
+
+- =-nmf= or =--no-mangle-functions= -- in case you want to mangle variable
+ names, but not touch function names.
+
+- =-ns= or =--no-squeeze= --- don't call =ast_squeeze()= (which does various
+ optimizations that result in smaller, less readable code).
+
+- =-mt= or =--mangle-toplevel= --- mangle names in the toplevel scope too
+ (by default we don't do this).
+
+- =--no-seqs= --- when =ast_squeeze()= is called (thus, unless you pass
+ =--no-squeeze=) it will reduce consecutive statements in blocks into a
+ sequence. For example, "a = 10; b = 20; foo();" will be written as
+ "a=10,b=20,foo();". In various occasions, this allows us to discard the
+ block brackets (since the block becomes a single statement). This is ON
+ by default because it seems safe and saves a few hundred bytes on some
+ libs that I tested it on, but pass =--no-seqs= to disable it.
+
+- =--no-dead-code= --- by default, UglifyJS will remove code that is
+ obviously unreachable (code that follows a =return=, =throw=, =break= or
+ =continue= statement and is not a function/variable declaration). Pass
+ this option to disable this optimization.
+
+- =-nc= or =--no-copyright= --- by default, =uglifyjs= will keep the initial
+ comment tokens in the generated code (assumed to be copyright information
+ etc.). If you pass this it will discard it.
+
+- =-o filename= or =--output filename= --- put the result in =filename=. If
+ this isn't given, the result goes to standard output (or see next one).
+
+- =--overwrite= --- if the code is read from a file (not from STDIN) and you
+ pass =--overwrite= then the output will be written in the same file.
+
+- =--ast= --- pass this if you want to get the Abstract Syntax Tree instead
+ of JavaScript as output. Useful for debugging or learning more about the
+ internals.
+
+- =-v= or =--verbose= --- output some notes on STDERR (for now just how long
+ each operation takes).
+
+- =-d SYMBOL[=VALUE]= or =--define SYMBOL[=VALUE]= --- will replace
+ all instances of the specified symbol where used as an identifier
+ (except where symbol has properly declared by a var declaration or
+ use as function parameter or similar) with the specified value. This
+ argument may be specified multiple times to define multiple
+ symbols - if no value is specified the symbol will be replaced with
+ the value =true=, or you can specify a numeric value (such as
+ =1024=), a quoted string value (such as ="object"= or
+ ='https://github.com'=), or the name of another symbol or keyword
+ (such as =null= or =document=).
+ This allows you, for example, to assign meaningful names to key
+ constant values but discard the symbolic names in the uglified
+ version for brevity/efficiency, or when used wth care, allows
+ UglifyJS to operate as a form of *conditional compilation*
+ whereby defining appropriate values may, by dint of the constant
+ folding and dead code removal features above, remove entire
+ superfluous code blocks (e.g. completely remove instrumentation or
+ trace code for production use).
+ Where string values are being defined, the handling of quotes are
+ likely to be subject to the specifics of your command shell
+ environment, so you may need to experiment with quoting styles
+ depending on your platform, or you may find the option
+ =--define-from-module= more suitable for use.
+
+- =-define-from-module SOMEMODULE= --- will load the named module (as
+ per the NodeJS =require()= function) and iterate all the exported
+ properties of the module defining them as symbol names to be defined
+ (as if by the =--define= option) per the name of each property
+ (i.e. without the module name prefix) and given the value of the
+ property. This is a much easier way to handle and document groups of
+ symbols to be defined rather than a large number of =--define=
+ options.
+
+- =--unsafe= --- enable other additional optimizations that are known to be
+ unsafe in some contrived situations, but could still be generally useful.
+ For now only these:
+
+ - foo.toString() ==> foo+""
+ - new Array(x,...) ==> [x,...]
+ - new Array(x) ==> Array(x)
+
+- =--max-line-len= (default 32K characters) --- add a newline after around
+ 32K characters. I've seen both FF and Chrome croak when all the code was
+ on a single line of around 670K. Pass --max-line-len 0 to disable this
+ safety feature.
+
+- =--reserved-names= --- some libraries rely on certain names to be used, as
+ pointed out in issue #92 and #81, so this option allow you to exclude such
+ names from the mangler. For example, to keep names =require= and =$super=
+ intact you'd specify --reserved-names "require,$super".
+
+- =--inline-script= -- when you want to include the output literally in an
+ HTML =
+
+function f(a, b, c) {
+ var i, boo, w = 10, q = 20;
+ for (i = 1; i < 10; ++i) {
+ boo = foo(a);
+ }
+ for (i = 0; i < 1; ++i) {
+ boo = bar(c);
+ }
+ function foo() { ... }
+ function bar() { ... }
+}
+#+END_SRC
+
+- =pro.ast_mangle(ast, options)= -- generates a new AST containing mangled
+ (compressed) variable and function names. It supports the following
+ options:
+
+ - =toplevel= -- mangle toplevel names (by default we don't touch them).
+ - =except= -- an array of names to exclude from compression.
+ - =defines= -- an object with properties named after symbols to
+ replace (see the =--define= option for the script) and the values
+ representing the AST replacement value.
+
+- =pro.ast_squeeze(ast, options)= -- employs further optimizations designed
+ to reduce the size of the code that =gen_code= would generate from the
+ AST. Returns a new AST. =options= can be a hash; the supported options
+ are:
+
+ - =make_seqs= (default true) which will cause consecutive statements in a
+ block to be merged using the "sequence" (comma) operator
+
+ - =dead_code= (default true) which will remove unreachable code.
+
+- =pro.gen_code(ast, options)= -- generates JS code from the AST. By
+ default it's minified, but using the =options= argument you can get nicely
+ formatted output. =options= is, well, optional :-) and if you pass it it
+ must be an object and supports the following properties (below you can see
+ the default values):
+
+ - =beautify: false= -- pass =true= if you want indented output
+ - =indent_start: 0= (only applies when =beautify= is =true=) -- initial
+ indentation in spaces
+ - =indent_level: 4= (only applies when =beautify= is =true=) --
+ indentation level, in spaces (pass an even number)
+ - =quote_keys: false= -- if you pass =true= it will quote all keys in
+ literal objects
+ - =space_colon: false= (only applies when =beautify= is =true=) -- wether
+ to put a space before the colon in object literals
+ - =ascii_only: false= -- pass =true= if you want to encode non-ASCII
+ characters as =\uXXXX=.
+ - =inline_script: false= -- pass =true= to escape occurrences of
+ =
+Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+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.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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.
+#+END_EXAMPLE
diff --git a/node_modules/uglify-js/bin/uglifyjs b/node_modules/uglify-js/bin/uglifyjs
new file mode 100755
index 0000000..e7ba627
--- /dev/null
+++ b/node_modules/uglify-js/bin/uglifyjs
@@ -0,0 +1,323 @@
+#!/usr/bin/env node
+// -*- js -*-
+
+global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
+var fs = require("fs");
+var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js
+ jsp = uglify.parser,
+ pro = uglify.uglify;
+
+var options = {
+ ast: false,
+ mangle: true,
+ mangle_toplevel: false,
+ no_mangle_functions: false,
+ squeeze: true,
+ make_seqs: true,
+ dead_code: true,
+ verbose: false,
+ show_copyright: true,
+ out_same_file: false,
+ max_line_length: 32 * 1024,
+ unsafe: false,
+ reserved_names: null,
+ defines: { },
+ lift_vars: false,
+ codegen_options: {
+ ascii_only: false,
+ beautify: false,
+ indent_level: 4,
+ indent_start: 0,
+ quote_keys: false,
+ space_colon: false,
+ inline_script: false
+ },
+ make: false,
+ output: true // stdout
+};
+
+var args = jsp.slice(process.argv, 2);
+var filename;
+
+out: while (args.length > 0) {
+ var v = args.shift();
+ switch (v) {
+ case "-b":
+ case "--beautify":
+ options.codegen_options.beautify = true;
+ break;
+ case "-i":
+ case "--indent":
+ options.codegen_options.indent_level = args.shift();
+ break;
+ case "-q":
+ case "--quote-keys":
+ options.codegen_options.quote_keys = true;
+ break;
+ case "-mt":
+ case "--mangle-toplevel":
+ options.mangle_toplevel = true;
+ break;
+ case "-nmf":
+ case "--no-mangle-functions":
+ options.no_mangle_functions = true;
+ break;
+ case "--no-mangle":
+ case "-nm":
+ options.mangle = false;
+ break;
+ case "--no-squeeze":
+ case "-ns":
+ options.squeeze = false;
+ break;
+ case "--no-seqs":
+ options.make_seqs = false;
+ break;
+ case "--no-dead-code":
+ options.dead_code = false;
+ break;
+ case "--no-copyright":
+ case "-nc":
+ options.show_copyright = false;
+ break;
+ case "-o":
+ case "--output":
+ options.output = args.shift();
+ break;
+ case "--overwrite":
+ options.out_same_file = true;
+ break;
+ case "-v":
+ case "--verbose":
+ options.verbose = true;
+ break;
+ case "--ast":
+ options.ast = true;
+ break;
+ case "--unsafe":
+ options.unsafe = true;
+ break;
+ case "--max-line-len":
+ options.max_line_length = parseInt(args.shift(), 10);
+ break;
+ case "--reserved-names":
+ options.reserved_names = args.shift().split(",");
+ break;
+ case "--lift-vars":
+ options.lift_vars = true;
+ break;
+ case "-d":
+ case "--define":
+ var defarg = args.shift();
+ try {
+ var defsym = function(sym) {
+ // KEYWORDS_ATOM doesn't include NaN or Infinity - should we check
+ // for them too ?? We don't check reserved words and the like as the
+ // define values are only substituted AFTER parsing
+ if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) {
+ throw "Don't define values for inbuilt constant '"+sym+"'";
+ }
+ return sym;
+ },
+ defval = function(v) {
+ if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) {
+ return [ "string", RegExp.$1 ];
+ }
+ else if (!isNaN(parseFloat(v))) {
+ return [ "num", parseFloat(v) ];
+ }
+ else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) {
+ return [ "name", v ];
+ }
+ else if (!v.match(/"/)) {
+ return [ "string", v ];
+ }
+ else if (!v.match(/'/)) {
+ return [ "string", v ];
+ }
+ throw "Can't understand the specified value: "+v;
+ };
+ if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) {
+ var sym = defsym(RegExp.$1),
+ val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ];
+ options.defines[sym] = val;
+ }
+ else {
+ throw "The --define option expects SYMBOL[=value]";
+ }
+ } catch(ex) {
+ sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n");
+ process.exit(1);
+ }
+ break;
+ case "--define-from-module":
+ var defmodarg = args.shift(),
+ defmodule = require(defmodarg),
+ sym,
+ val;
+ for (sym in defmodule) {
+ if (defmodule.hasOwnProperty(sym)) {
+ options.defines[sym] = function(val) {
+ if (typeof val == "string")
+ return [ "string", val ];
+ if (typeof val == "number")
+ return [ "num", val ];
+ if (val === true)
+ return [ 'name', 'true' ];
+ if (val === false)
+ return [ 'name', 'false' ];
+ if (val === null)
+ return [ 'name', 'null' ];
+ if (val === undefined)
+ return [ 'name', 'undefined' ];
+ sys.print("ERROR: In option --define-from-module "+defmodarg+"\n");
+ sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n");
+ process.exit(1);
+ return null;
+ }(defmodule[sym]);
+ }
+ }
+ break;
+ case "--ascii":
+ options.codegen_options.ascii_only = true;
+ break;
+ case "--make":
+ options.make = true;
+ break;
+ case "--inline-script":
+ options.codegen_options.inline_script = true;
+ break;
+ default:
+ filename = v;
+ break out;
+ }
+}
+
+if (options.verbose) {
+ pro.set_logger(function(msg){
+ sys.debug(msg);
+ });
+}
+
+jsp.set_logger(function(msg){
+ sys.debug(msg);
+});
+
+if (options.make) {
+ options.out_same_file = false; // doesn't make sense in this case
+ var makefile = JSON.parse(fs.readFileSync(filename || "Makefile.uglify.js").toString());
+ output(makefile.files.map(function(file){
+ var code = fs.readFileSync(file.name);
+ if (file.module) {
+ code = "!function(exports, global){global = this;\n" + code + "\n;this." + file.module + " = exports;}({})";
+ }
+ else if (file.hide) {
+ code = "(function(){" + code + "}());";
+ }
+ return squeeze_it(code);
+ }).join("\n"));
+}
+else if (filename) {
+ fs.readFile(filename, "utf8", function(err, text){
+ if (err) throw err;
+ output(squeeze_it(text));
+ });
+}
+else {
+ var stdin = process.openStdin();
+ stdin.setEncoding("utf8");
+ var text = "";
+ stdin.on("data", function(chunk){
+ text += chunk;
+ });
+ stdin.on("end", function() {
+ output(squeeze_it(text));
+ });
+}
+
+function output(text) {
+ var out;
+ if (options.out_same_file && filename)
+ options.output = filename;
+ if (options.output === true) {
+ out = process.stdout;
+ } else {
+ out = fs.createWriteStream(options.output, {
+ flags: "w",
+ encoding: "utf8",
+ mode: 0644
+ });
+ }
+ out.write(text.replace(/;*$/, ";"));
+ if (options.output !== true) {
+ out.end();
+ }
+};
+
+// --------- main ends here.
+
+function show_copyright(comments) {
+ var ret = "";
+ for (var i = 0; i < comments.length; ++i) {
+ var c = comments[i];
+ if (c.type == "comment1") {
+ ret += "//" + c.value + "\n";
+ } else {
+ ret += "/*" + c.value + "*/";
+ }
+ }
+ return ret;
+};
+
+function squeeze_it(code) {
+ var result = "";
+ if (options.show_copyright) {
+ var tok = jsp.tokenizer(code), c;
+ c = tok();
+ result += show_copyright(c.comments_before);
+ }
+ try {
+ var ast = time_it("parse", function(){ return jsp.parse(code); });
+ if (options.lift_vars) {
+ ast = time_it("lift", function(){ return pro.ast_lift_variables(ast); });
+ }
+ if (options.mangle) ast = time_it("mangle", function(){
+ return pro.ast_mangle(ast, {
+ toplevel : options.mangle_toplevel,
+ defines : options.defines,
+ except : options.reserved_names,
+ no_functions : options.no_mangle_functions
+ });
+ });
+ if (options.squeeze) ast = time_it("squeeze", function(){
+ ast = pro.ast_squeeze(ast, {
+ make_seqs : options.make_seqs,
+ dead_code : options.dead_code,
+ keep_comps : !options.unsafe
+ });
+ if (options.unsafe)
+ ast = pro.ast_squeeze_more(ast);
+ return ast;
+ });
+ if (options.ast)
+ return sys.inspect(ast, null, null);
+ result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) });
+ if (!options.codegen_options.beautify && options.max_line_length) {
+ result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) });
+ }
+ return result;
+ } catch(ex) {
+ sys.debug(ex.stack);
+ sys.debug(sys.inspect(ex));
+ sys.debug(JSON.stringify(ex));
+ process.exit(1);
+ }
+};
+
+function time_it(name, cont) {
+ if (!options.verbose)
+ return cont();
+ var t1 = new Date().getTime();
+ try { return cont(); }
+ finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
+};
diff --git a/node_modules/uglify-js/docstyle.css b/node_modules/uglify-js/docstyle.css
new file mode 100644
index 0000000..412481f
--- /dev/null
+++ b/node_modules/uglify-js/docstyle.css
@@ -0,0 +1,75 @@
+html { font-family: "Lucida Grande","Trebuchet MS",sans-serif; font-size: 12pt; }
+body { max-width: 60em; }
+.title { text-align: center; }
+.todo { color: red; }
+.done { color: green; }
+.tag { background-color:lightblue; font-weight:normal }
+.target { }
+.timestamp { color: grey }
+.timestamp-kwd { color: CadetBlue }
+p.verse { margin-left: 3% }
+pre {
+ border: 1pt solid #AEBDCC;
+ background-color: #F3F5F7;
+ padding: 5pt;
+ font-family: monospace;
+ font-size: 90%;
+ overflow:auto;
+}
+pre.src {
+ background-color: #eee; color: #112; border: 1px solid #000;
+}
+table { border-collapse: collapse; }
+td, th { vertical-align: top; }
+dt { font-weight: bold; }
+div.figure { padding: 0.5em; }
+div.figure p { text-align: center; }
+.linenr { font-size:smaller }
+.code-highlighted {background-color:#ffff00;}
+.org-info-js_info-navigation { border-style:none; }
+#org-info-js_console-label { font-size:10px; font-weight:bold;
+ white-space:nowrap; }
+.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
+ font-weight:bold; }
+
+sup {
+ vertical-align: baseline;
+ position: relative;
+ top: -0.5em;
+ font-size: 80%;
+}
+
+sup a:link, sup a:visited {
+ text-decoration: none;
+ color: #c00;
+}
+
+sup a:before { content: "["; color: #999; }
+sup a:after { content: "]"; color: #999; }
+
+h1.title { border-bottom: 4px solid #000; padding-bottom: 5px; margin-bottom: 2em; }
+
+#postamble {
+ color: #777;
+ font-size: 90%;
+ padding-top: 1em; padding-bottom: 1em; border-top: 1px solid #999;
+ margin-top: 2em;
+ padding-left: 2em;
+ padding-right: 2em;
+ text-align: right;
+}
+
+#postamble p { margin: 0; }
+
+#footnotes { border-top: 1px solid #000; }
+
+h1 { font-size: 200% }
+h2 { font-size: 175% }
+h3 { font-size: 150% }
+h4 { font-size: 125% }
+
+h1, h2, h3, h4 { font-family: "Bookman",Georgia,"Times New Roman",serif; font-weight: normal; }
+
+@media print {
+ html { font-size: 11pt; }
+}
diff --git a/node_modules/uglify-js/lib/object-ast.js b/node_modules/uglify-js/lib/object-ast.js
new file mode 100644
index 0000000..afdb69f
--- /dev/null
+++ b/node_modules/uglify-js/lib/object-ast.js
@@ -0,0 +1,75 @@
+var jsp = require("./parse-js"),
+ pro = require("./process");
+
+var BY_TYPE = {};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+function AST_Node(parent) {
+ this.parent = parent;
+};
+
+AST_Node.prototype.init = function(){};
+
+function DEFINE_NODE_CLASS(type, props, methods) {
+ var base = methods && methods.BASE || AST_Node;
+ if (!base) base = AST_Node;
+ function D(parent, data) {
+ base.apply(this, arguments);
+ if (props) props.forEach(function(name, i){
+ this["_" + name] = data[i];
+ });
+ this.init();
+ };
+ var P = D.prototype = new AST_Node;
+ P.node_type = function(){ return type };
+ if (props) props.forEach(function(name){
+ var propname = "_" + name;
+ P["set_" + name] = function(val) {
+ this[propname] = val;
+ return this;
+ };
+ P["get_" + name] = function() {
+ return this[propname];
+ };
+ });
+ if (type != null) BY_TYPE[type] = D;
+ if (methods) for (var i in methods) if (HOP(methods, i)) {
+ P[i] = methods[i];
+ }
+ return D;
+};
+
+var AST_String_Node = DEFINE_NODE_CLASS("string", ["value"]);
+var AST_Number_Node = DEFINE_NODE_CLASS("num", ["value"]);
+var AST_Name_Node = DEFINE_NODE_CLASS("name", ["value"]);
+
+var AST_Statlist_Node = DEFINE_NODE_CLASS(null, ["body"]);
+var AST_Root_Node = DEFINE_NODE_CLASS("toplevel", null, { BASE: AST_Statlist_Node });
+var AST_Block_Node = DEFINE_NODE_CLASS("block", null, { BASE: AST_Statlist_Node });
+var AST_Splice_Node = DEFINE_NODE_CLASS("splice", null, { BASE: AST_Statlist_Node });
+
+var AST_Var_Node = DEFINE_NODE_CLASS("var", ["definitions"]);
+var AST_Const_Node = DEFINE_NODE_CLASS("const", ["definitions"]);
+
+var AST_Try_Node = DEFINE_NODE_CLASS("try", ["body", "catch", "finally"]);
+var AST_Throw_Node = DEFINE_NODE_CLASS("throw", ["exception"]);
+
+var AST_New_Node = DEFINE_NODE_CLASS("new", ["constructor", "arguments"]);
+
+var AST_Switch_Node = DEFINE_NODE_CLASS("switch", ["expression", "branches"]);
+var AST_Switch_Branch_Node = DEFINE_NODE_CLASS(null, ["expression", "body"]);
+
+var AST_Break_Node = DEFINE_NODE_CLASS("break", ["label"]);
+var AST_Continue_Node = DEFINE_NODE_CLASS("continue", ["label"]);
+var AST_Assign_Node = DEFINE_NODE_CLASS("assign", ["operator", "lvalue", "rvalue"]);
+var AST_Dot_Node = DEFINE_NODE_CLASS("dot", ["expression", "name"]);
+var AST_Call_Node = DEFINE_NODE_CLASS("call", ["function", "arguments"]);
+
+var AST_Lambda_Node = DEFINE_NODE_CLASS(null, ["name", "arguments", "body"])
+var AST_Function_Node = DEFINE_NODE_CLASS("function", null, AST_Lambda_Node);
+var AST_Defun_Node = DEFINE_NODE_CLASS("defun", null, AST_Lambda_Node);
+
+var AST_If_Node = DEFINE_NODE_CLASS("if", ["condition", "then", "else"]);
diff --git a/node_modules/uglify-js/lib/parse-js.js b/node_modules/uglify-js/lib/parse-js.js
new file mode 100644
index 0000000..44dcc33
--- /dev/null
+++ b/node_modules/uglify-js/lib/parse-js.js
@@ -0,0 +1,1342 @@
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file contains the tokenizer/parser. It is a port to JavaScript
+ of parse-js [1], a JavaScript parser library written in Common Lisp
+ by Marijn Haverbeke. Thank you Marijn!
+
+ [1] http://marijn.haverbeke.nl/parse-js/
+
+ Exported functions:
+
+ - tokenizer(code) -- returns a function. Call the returned
+ function to fetch the next token.
+
+ - parse(code) -- returns an AST of the given JavaScript code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon
+ Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+ 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.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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.
+
+ ***********************************************************************/
+
+/* -----[ Tokenizer (constants) ]----- */
+
+var KEYWORDS = array_to_hash([
+ "break",
+ "case",
+ "catch",
+ "const",
+ "continue",
+ "debugger",
+ "default",
+ "delete",
+ "do",
+ "else",
+ "finally",
+ "for",
+ "function",
+ "if",
+ "in",
+ "instanceof",
+ "new",
+ "return",
+ "switch",
+ "throw",
+ "try",
+ "typeof",
+ "var",
+ "void",
+ "while",
+ "with"
+]);
+
+var RESERVED_WORDS = array_to_hash([
+ "abstract",
+ "boolean",
+ "byte",
+ "char",
+ "class",
+ "double",
+ "enum",
+ "export",
+ "extends",
+ "final",
+ "float",
+ "goto",
+ "implements",
+ "import",
+ "int",
+ "interface",
+ "long",
+ "native",
+ "package",
+ "private",
+ "protected",
+ "public",
+ "short",
+ "static",
+ "super",
+ "synchronized",
+ "throws",
+ "transient",
+ "volatile"
+]);
+
+var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
+ "return",
+ "new",
+ "delete",
+ "throw",
+ "else",
+ "case"
+]);
+
+var KEYWORDS_ATOM = array_to_hash([
+ "false",
+ "null",
+ "true",
+ "undefined"
+]);
+
+var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
+
+var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
+var RE_OCT_NUMBER = /^0[0-7]+$/;
+var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
+
+var OPERATORS = array_to_hash([
+ "in",
+ "instanceof",
+ "typeof",
+ "new",
+ "void",
+ "delete",
+ "++",
+ "--",
+ "+",
+ "-",
+ "!",
+ "~",
+ "&",
+ "|",
+ "^",
+ "*",
+ "/",
+ "%",
+ ">>",
+ "<<",
+ ">>>",
+ "<",
+ ">",
+ "<=",
+ ">=",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ "?",
+ "=",
+ "+=",
+ "-=",
+ "/=",
+ "*=",
+ "%=",
+ ">>=",
+ "<<=",
+ ">>>=",
+ "|=",
+ "^=",
+ "&=",
+ "&&",
+ "||"
+]);
+
+var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
+
+var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{}(,.;:"));
+
+var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
+
+var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
+
+/* -----[ Tokenizer ]----- */
+
+// regexps adapted from http://xregexp.com/plugins/#unicode
+var UNICODE = {
+ letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
+ non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
+ space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
+ connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
+};
+
+function is_letter(ch) {
+ return UNICODE.letter.test(ch);
+};
+
+function is_digit(ch) {
+ ch = ch.charCodeAt(0);
+ return ch >= 48 && ch <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
+};
+
+function is_alphanumeric_char(ch) {
+ return is_digit(ch) || is_letter(ch);
+};
+
+function is_unicode_combining_mark(ch) {
+ return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
+};
+
+function is_unicode_connector_punctuation(ch) {
+ return UNICODE.connector_punctuation.test(ch);
+};
+
+function is_identifier_start(ch) {
+ return ch == "$" || ch == "_" || is_letter(ch);
+};
+
+function is_identifier_char(ch) {
+ return is_identifier_start(ch)
+ || is_unicode_combining_mark(ch)
+ || is_digit(ch)
+ || is_unicode_connector_punctuation(ch)
+ || ch == "\u200c" // zero-width non-joiner
+ || ch == "\u200d" // zero-width joiner (in my ECMA-262 PDF, this is also 200c)
+ ;
+};
+
+function parse_js_number(num) {
+ if (RE_HEX_NUMBER.test(num)) {
+ return parseInt(num.substr(2), 16);
+ } else if (RE_OCT_NUMBER.test(num)) {
+ return parseInt(num.substr(1), 8);
+ } else if (RE_DEC_NUMBER.test(num)) {
+ return parseFloat(num);
+ }
+};
+
+function JS_Parse_Error(message, line, col, pos) {
+ this.message = message;
+ this.line = line + 1;
+ this.col = col + 1;
+ this.pos = pos + 1;
+ this.stack = new Error().stack;
+};
+
+JS_Parse_Error.prototype.toString = function() {
+ return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
+};
+
+function js_error(message, line, col, pos) {
+ throw new JS_Parse_Error(message, line, col, pos);
+};
+
+function is_token(token, type, val) {
+ return token.type == type && (val == null || token.value == val);
+};
+
+var EX_EOF = {};
+
+function tokenizer($TEXT) {
+
+ var S = {
+ text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
+ pos : 0,
+ tokpos : 0,
+ line : 0,
+ tokline : 0,
+ col : 0,
+ tokcol : 0,
+ newline_before : false,
+ regex_allowed : false,
+ comments_before : []
+ };
+
+ function peek() { return S.text.charAt(S.pos); };
+
+ function next(signal_eof, in_string) {
+ var ch = S.text.charAt(S.pos++);
+ if (signal_eof && !ch)
+ throw EX_EOF;
+ if (ch == "\n") {
+ S.newline_before = S.newline_before || !in_string;
+ ++S.line;
+ S.col = 0;
+ } else {
+ ++S.col;
+ }
+ return ch;
+ };
+
+ function eof() {
+ return !S.peek();
+ };
+
+ function find(what, signal_eof) {
+ var pos = S.text.indexOf(what, S.pos);
+ if (signal_eof && pos == -1) throw EX_EOF;
+ return pos;
+ };
+
+ function start_token() {
+ S.tokline = S.line;
+ S.tokcol = S.col;
+ S.tokpos = S.pos;
+ };
+
+ function token(type, value, is_comment) {
+ S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
+ (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
+ (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
+ var ret = {
+ type : type,
+ value : value,
+ line : S.tokline,
+ col : S.tokcol,
+ pos : S.tokpos,
+ endpos : S.pos,
+ nlb : S.newline_before
+ };
+ if (!is_comment) {
+ ret.comments_before = S.comments_before;
+ S.comments_before = [];
+ }
+ S.newline_before = false;
+ return ret;
+ };
+
+ function skip_whitespace() {
+ while (HOP(WHITESPACE_CHARS, peek()))
+ next();
+ };
+
+ function read_while(pred) {
+ var ret = "", ch = peek(), i = 0;
+ while (ch && pred(ch, i++)) {
+ ret += next();
+ ch = peek();
+ }
+ return ret;
+ };
+
+ function parse_error(err) {
+ js_error(err, S.tokline, S.tokcol, S.tokpos);
+ };
+
+ function read_num(prefix) {
+ var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
+ var num = read_while(function(ch, i){
+ if (ch == "x" || ch == "X") {
+ if (has_x) return false;
+ return has_x = true;
+ }
+ if (!has_x && (ch == "E" || ch == "e")) {
+ if (has_e) return false;
+ return has_e = after_e = true;
+ }
+ if (ch == "-") {
+ if (after_e || (i == 0 && !prefix)) return true;
+ return false;
+ }
+ if (ch == "+") return after_e;
+ after_e = false;
+ if (ch == ".") {
+ if (!has_dot && !has_x)
+ return has_dot = true;
+ return false;
+ }
+ return is_alphanumeric_char(ch);
+ });
+ if (prefix)
+ num = prefix + num;
+ var valid = parse_js_number(num);
+ if (!isNaN(valid)) {
+ return token("num", valid);
+ } else {
+ parse_error("Invalid syntax: " + num);
+ }
+ };
+
+ function read_escaped_char(in_string) {
+ var ch = next(true, in_string);
+ switch (ch) {
+ case "n" : return "\n";
+ case "r" : return "\r";
+ case "t" : return "\t";
+ case "b" : return "\b";
+ case "v" : return "\u000b";
+ case "f" : return "\f";
+ case "0" : return "\0";
+ case "x" : return String.fromCharCode(hex_bytes(2));
+ case "u" : return String.fromCharCode(hex_bytes(4));
+ case "\n": return "";
+ default : return ch;
+ }
+ };
+
+ function hex_bytes(n) {
+ var num = 0;
+ for (; n > 0; --n) {
+ var digit = parseInt(next(true), 16);
+ if (isNaN(digit))
+ parse_error("Invalid hex-character pattern in string");
+ num = (num << 4) | digit;
+ }
+ return num;
+ };
+
+ function read_string() {
+ return with_eof_error("Unterminated string constant", function(){
+ var quote = next(), ret = "";
+ for (;;) {
+ var ch = next(true);
+ if (ch == "\\") {
+ // read OctalEscapeSequence (XXX: deprecated if "strict mode")
+ // https://github.com/mishoo/UglifyJS/issues/178
+ var octal_len = 0, first = null;
+ ch = read_while(function(ch){
+ if (ch >= "0" && ch <= "7") {
+ if (!first) {
+ first = ch;
+ return ++octal_len;
+ }
+ else if (first <= "3" && octal_len <= 2) return ++octal_len;
+ else if (first >= "4" && octal_len <= 1) return ++octal_len;
+ }
+ return false;
+ });
+ if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
+ else ch = read_escaped_char(true);
+ }
+ else if (ch == quote) break;
+ ret += ch;
+ }
+ return token("string", ret);
+ });
+ };
+
+ function read_line_comment() {
+ next();
+ var i = find("\n"), ret;
+ if (i == -1) {
+ ret = S.text.substr(S.pos);
+ S.pos = S.text.length;
+ } else {
+ ret = S.text.substring(S.pos, i);
+ S.pos = i;
+ }
+ return token("comment1", ret, true);
+ };
+
+ function read_multiline_comment() {
+ next();
+ return with_eof_error("Unterminated multiline comment", function(){
+ var i = find("*/", true),
+ text = S.text.substring(S.pos, i);
+ S.pos = i + 2;
+ S.line += text.split("\n").length - 1;
+ S.newline_before = text.indexOf("\n") >= 0;
+
+ // https://github.com/mishoo/UglifyJS/issues/#issue/100
+ if (/^@cc_on/i.test(text)) {
+ warn("WARNING: at line " + S.line);
+ warn("*** Found \"conditional comment\": " + text);
+ warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
+ }
+
+ return token("comment2", text, true);
+ });
+ };
+
+ function read_name() {
+ var backslash = false, name = "", ch;
+ while ((ch = peek()) != null) {
+ if (!backslash) {
+ if (ch == "\\") backslash = true, next();
+ else if (is_identifier_char(ch)) name += next();
+ else break;
+ }
+ else {
+ if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
+ ch = read_escaped_char();
+ if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
+ name += ch;
+ backslash = false;
+ }
+ }
+ return name;
+ };
+
+ function read_regexp(regexp) {
+ return with_eof_error("Unterminated regular expression", function(){
+ var prev_backslash = false, ch, in_class = false;
+ while ((ch = next(true))) if (prev_backslash) {
+ regexp += "\\" + ch;
+ prev_backslash = false;
+ } else if (ch == "[") {
+ in_class = true;
+ regexp += ch;
+ } else if (ch == "]" && in_class) {
+ in_class = false;
+ regexp += ch;
+ } else if (ch == "/" && !in_class) {
+ break;
+ } else if (ch == "\\") {
+ prev_backslash = true;
+ } else {
+ regexp += ch;
+ }
+ var mods = read_name();
+ return token("regexp", [ regexp, mods ]);
+ });
+ };
+
+ function read_operator(prefix) {
+ function grow(op) {
+ if (!peek()) return op;
+ var bigger = op + peek();
+ if (HOP(OPERATORS, bigger)) {
+ next();
+ return grow(bigger);
+ } else {
+ return op;
+ }
+ };
+ return token("operator", grow(prefix || next()));
+ };
+
+ function handle_slash() {
+ next();
+ var regex_allowed = S.regex_allowed;
+ switch (peek()) {
+ case "/":
+ S.comments_before.push(read_line_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ case "*":
+ S.comments_before.push(read_multiline_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ }
+ return S.regex_allowed ? read_regexp("") : read_operator("/");
+ };
+
+ function handle_dot() {
+ next();
+ return is_digit(peek())
+ ? read_num(".")
+ : token("punc", ".");
+ };
+
+ function read_word() {
+ var word = read_name();
+ return !HOP(KEYWORDS, word)
+ ? token("name", word)
+ : HOP(OPERATORS, word)
+ ? token("operator", word)
+ : HOP(KEYWORDS_ATOM, word)
+ ? token("atom", word)
+ : token("keyword", word);
+ };
+
+ function with_eof_error(eof_error, cont) {
+ try {
+ return cont();
+ } catch(ex) {
+ if (ex === EX_EOF) parse_error(eof_error);
+ else throw ex;
+ }
+ };
+
+ function next_token(force_regexp) {
+ if (force_regexp != null)
+ return read_regexp(force_regexp);
+ skip_whitespace();
+ start_token();
+ var ch = peek();
+ if (!ch) return token("eof");
+ if (is_digit(ch)) return read_num();
+ if (ch == '"' || ch == "'") return read_string();
+ if (HOP(PUNC_CHARS, ch)) return token("punc", next());
+ if (ch == ".") return handle_dot();
+ if (ch == "/") return handle_slash();
+ if (HOP(OPERATOR_CHARS, ch)) return read_operator();
+ if (ch == "\\" || is_identifier_start(ch)) return read_word();
+ parse_error("Unexpected character '" + ch + "'");
+ };
+
+ next_token.context = function(nc) {
+ if (nc) S = nc;
+ return S;
+ };
+
+ return next_token;
+
+};
+
+/* -----[ Parser (constants) ]----- */
+
+var UNARY_PREFIX = array_to_hash([
+ "typeof",
+ "void",
+ "delete",
+ "--",
+ "++",
+ "!",
+ "~",
+ "-",
+ "+"
+]);
+
+var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
+
+var ASSIGNMENT = (function(a, ret, i){
+ while (i < a.length) {
+ ret[a[i]] = a[i].substr(0, a[i].length - 1);
+ i++;
+ }
+ return ret;
+})(
+ ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
+ { "=": true },
+ 0
+);
+
+var PRECEDENCE = (function(a, ret){
+ for (var i = 0, n = 1; i < a.length; ++i, ++n) {
+ var b = a[i];
+ for (var j = 0; j < b.length; ++j) {
+ ret[b[j]] = n;
+ }
+ }
+ return ret;
+})(
+ [
+ ["||"],
+ ["&&"],
+ ["|"],
+ ["^"],
+ ["&"],
+ ["==", "===", "!=", "!=="],
+ ["<", ">", "<=", ">=", "in", "instanceof"],
+ [">>", "<<", ">>>"],
+ ["+", "-"],
+ ["*", "/", "%"]
+ ],
+ {}
+);
+
+var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
+
+var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
+
+/* -----[ Parser ]----- */
+
+function NodeWithToken(str, start, end) {
+ this.name = str;
+ this.start = start;
+ this.end = end;
+};
+
+NodeWithToken.prototype.toString = function() { return this.name; };
+
+function parse($TEXT, exigent_mode, embed_tokens) {
+
+ var S = {
+ input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
+ token : null,
+ prev : null,
+ peeked : null,
+ in_function : 0,
+ in_loop : 0,
+ labels : []
+ };
+
+ S.token = next();
+
+ function is(type, value) {
+ return is_token(S.token, type, value);
+ };
+
+ function peek() { return S.peeked || (S.peeked = S.input()); };
+
+ function next() {
+ S.prev = S.token;
+ if (S.peeked) {
+ S.token = S.peeked;
+ S.peeked = null;
+ } else {
+ S.token = S.input();
+ }
+ return S.token;
+ };
+
+ function prev() {
+ return S.prev;
+ };
+
+ function croak(msg, line, col, pos) {
+ var ctx = S.input.context();
+ js_error(msg,
+ line != null ? line : ctx.tokline,
+ col != null ? col : ctx.tokcol,
+ pos != null ? pos : ctx.tokpos);
+ };
+
+ function token_error(token, msg) {
+ croak(msg, token.line, token.col);
+ };
+
+ function unexpected(token) {
+ if (token == null)
+ token = S.token;
+ token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
+ };
+
+ function expect_token(type, val) {
+ if (is(type, val)) {
+ return next();
+ }
+ token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
+ };
+
+ function expect(punc) { return expect_token("punc", punc); };
+
+ function can_insert_semicolon() {
+ return !exigent_mode && (
+ S.token.nlb || is("eof") || is("punc", "}")
+ );
+ };
+
+ function semicolon() {
+ if (is("punc", ";")) next();
+ else if (!can_insert_semicolon()) unexpected();
+ };
+
+ function as() {
+ return slice(arguments);
+ };
+
+ function parenthesised() {
+ expect("(");
+ var ex = expression();
+ expect(")");
+ return ex;
+ };
+
+ function add_tokens(str, start, end) {
+ return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
+ };
+
+ function maybe_embed_tokens(parser) {
+ if (embed_tokens) return function() {
+ var start = S.token;
+ var ast = parser.apply(this, arguments);
+ ast[0] = add_tokens(ast[0], start, prev());
+ return ast;
+ };
+ else return parser;
+ };
+
+ var statement = maybe_embed_tokens(function() {
+ if (is("operator", "/") || is("operator", "/=")) {
+ S.peeked = null;
+ S.token = S.input(S.token.value.substr(1)); // force regexp
+ }
+ switch (S.token.type) {
+ case "num":
+ case "string":
+ case "regexp":
+ case "operator":
+ case "atom":
+ return simple_statement();
+
+ case "name":
+ return is_token(peek(), "punc", ":")
+ ? labeled_statement(prog1(S.token.value, next, next))
+ : simple_statement();
+
+ case "punc":
+ switch (S.token.value) {
+ case "{":
+ return as("block", block_());
+ case "[":
+ case "(":
+ return simple_statement();
+ case ";":
+ next();
+ return as("block");
+ default:
+ unexpected();
+ }
+
+ case "keyword":
+ switch (prog1(S.token.value, next)) {
+ case "break":
+ return break_cont("break");
+
+ case "continue":
+ return break_cont("continue");
+
+ case "debugger":
+ semicolon();
+ return as("debugger");
+
+ case "do":
+ return (function(body){
+ expect_token("keyword", "while");
+ return as("do", prog1(parenthesised, semicolon), body);
+ })(in_loop(statement));
+
+ case "for":
+ return for_();
+
+ case "function":
+ return function_(true);
+
+ case "if":
+ return if_();
+
+ case "return":
+ if (S.in_function == 0)
+ croak("'return' outside of function");
+ return as("return",
+ is("punc", ";")
+ ? (next(), null)
+ : can_insert_semicolon()
+ ? null
+ : prog1(expression, semicolon));
+
+ case "switch":
+ return as("switch", parenthesised(), switch_block_());
+
+ case "throw":
+ if (S.token.nlb)
+ croak("Illegal newline after 'throw'");
+ return as("throw", prog1(expression, semicolon));
+
+ case "try":
+ return try_();
+
+ case "var":
+ return prog1(var_, semicolon);
+
+ case "const":
+ return prog1(const_, semicolon);
+
+ case "while":
+ return as("while", parenthesised(), in_loop(statement));
+
+ case "with":
+ return as("with", parenthesised(), statement());
+
+ default:
+ unexpected();
+ }
+ }
+ });
+
+ function labeled_statement(label) {
+ S.labels.push(label);
+ var start = S.token, stat = statement();
+ if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
+ unexpected(start);
+ S.labels.pop();
+ return as("label", label, stat);
+ };
+
+ function simple_statement() {
+ return as("stat", prog1(expression, semicolon));
+ };
+
+ function break_cont(type) {
+ var name;
+ if (!can_insert_semicolon()) {
+ name = is("name") ? S.token.value : null;
+ }
+ if (name != null) {
+ next();
+ if (!member(name, S.labels))
+ croak("Label " + name + " without matching loop or statement");
+ }
+ else if (S.in_loop == 0)
+ croak(type + " not inside a loop or switch");
+ semicolon();
+ return as(type, name);
+ };
+
+ function for_() {
+ expect("(");
+ var init = null;
+ if (!is("punc", ";")) {
+ init = is("keyword", "var")
+ ? (next(), var_(true))
+ : expression(true, true);
+ if (is("operator", "in")) {
+ if (init[0] == "var" && init[1].length > 1)
+ croak("Only one variable declaration allowed in for..in loop");
+ return for_in(init);
+ }
+ }
+ return regular_for(init);
+ };
+
+ function regular_for(init) {
+ expect(";");
+ var test = is("punc", ";") ? null : expression();
+ expect(";");
+ var step = is("punc", ")") ? null : expression();
+ expect(")");
+ return as("for", init, test, step, in_loop(statement));
+ };
+
+ function for_in(init) {
+ var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
+ next();
+ var obj = expression();
+ expect(")");
+ return as("for-in", init, lhs, obj, in_loop(statement));
+ };
+
+ var function_ = function(in_statement) {
+ var name = is("name") ? prog1(S.token.value, next) : null;
+ if (in_statement && !name)
+ unexpected();
+ expect("(");
+ return as(in_statement ? "defun" : "function",
+ name,
+ // arguments
+ (function(first, a){
+ while (!is("punc", ")")) {
+ if (first) first = false; else expect(",");
+ if (!is("name")) unexpected();
+ a.push(S.token.value);
+ next();
+ }
+ next();
+ return a;
+ })(true, []),
+ // body
+ (function(){
+ ++S.in_function;
+ var loop = S.in_loop;
+ S.in_loop = 0;
+ var a = block_();
+ --S.in_function;
+ S.in_loop = loop;
+ return a;
+ })());
+ };
+
+ function if_() {
+ var cond = parenthesised(), body = statement(), belse;
+ if (is("keyword", "else")) {
+ next();
+ belse = statement();
+ }
+ return as("if", cond, body, belse);
+ };
+
+ function block_() {
+ expect("{");
+ var a = [];
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ a.push(statement());
+ }
+ next();
+ return a;
+ };
+
+ var switch_block_ = curry(in_loop, function(){
+ expect("{");
+ var a = [], cur = null;
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ if (is("keyword", "case")) {
+ next();
+ cur = [];
+ a.push([ expression(), cur ]);
+ expect(":");
+ }
+ else if (is("keyword", "default")) {
+ next();
+ expect(":");
+ cur = [];
+ a.push([ null, cur ]);
+ }
+ else {
+ if (!cur) unexpected();
+ cur.push(statement());
+ }
+ }
+ next();
+ return a;
+ });
+
+ function try_() {
+ var body = block_(), bcatch, bfinally;
+ if (is("keyword", "catch")) {
+ next();
+ expect("(");
+ if (!is("name"))
+ croak("Name expected");
+ var name = S.token.value;
+ next();
+ expect(")");
+ bcatch = [ name, block_() ];
+ }
+ if (is("keyword", "finally")) {
+ next();
+ bfinally = block_();
+ }
+ if (!bcatch && !bfinally)
+ croak("Missing catch/finally blocks");
+ return as("try", body, bcatch, bfinally);
+ };
+
+ function vardefs(no_in) {
+ var a = [];
+ for (;;) {
+ if (!is("name"))
+ unexpected();
+ var name = S.token.value;
+ next();
+ if (is("operator", "=")) {
+ next();
+ a.push([ name, expression(false, no_in) ]);
+ } else {
+ a.push([ name ]);
+ }
+ if (!is("punc", ","))
+ break;
+ next();
+ }
+ return a;
+ };
+
+ function var_(no_in) {
+ return as("var", vardefs(no_in));
+ };
+
+ function const_() {
+ return as("const", vardefs());
+ };
+
+ function new_() {
+ var newexp = expr_atom(false), args;
+ if (is("punc", "(")) {
+ next();
+ args = expr_list(")");
+ } else {
+ args = [];
+ }
+ return subscripts(as("new", newexp, args), true);
+ };
+
+ var expr_atom = maybe_embed_tokens(function(allow_calls) {
+ if (is("operator", "new")) {
+ next();
+ return new_();
+ }
+ if (is("punc")) {
+ switch (S.token.value) {
+ case "(":
+ next();
+ return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
+ case "[":
+ next();
+ return subscripts(array_(), allow_calls);
+ case "{":
+ next();
+ return subscripts(object_(), allow_calls);
+ }
+ unexpected();
+ }
+ if (is("keyword", "function")) {
+ next();
+ return subscripts(function_(false), allow_calls);
+ }
+ if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
+ var atom = S.token.type == "regexp"
+ ? as("regexp", S.token.value[0], S.token.value[1])
+ : as(S.token.type, S.token.value);
+ return subscripts(prog1(atom, next), allow_calls);
+ }
+ unexpected();
+ });
+
+ function expr_list(closing, allow_trailing_comma, allow_empty) {
+ var first = true, a = [];
+ while (!is("punc", closing)) {
+ if (first) first = false; else expect(",");
+ if (allow_trailing_comma && is("punc", closing)) break;
+ if (is("punc", ",") && allow_empty) {
+ a.push([ "atom", "undefined" ]);
+ } else {
+ a.push(expression(false));
+ }
+ }
+ next();
+ return a;
+ };
+
+ function array_() {
+ return as("array", expr_list("]", !exigent_mode, true));
+ };
+
+ function object_() {
+ var first = true, a = [];
+ while (!is("punc", "}")) {
+ if (first) first = false; else expect(",");
+ if (!exigent_mode && is("punc", "}"))
+ // allow trailing comma
+ break;
+ var type = S.token.type;
+ var name = as_property_name();
+ if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
+ a.push([ as_name(), function_(false), name ]);
+ } else {
+ expect(":");
+ a.push([ name, expression(false) ]);
+ }
+ }
+ next();
+ return as("object", a);
+ };
+
+ function as_property_name() {
+ switch (S.token.type) {
+ case "num":
+ case "string":
+ return prog1(S.token.value, next);
+ }
+ return as_name();
+ };
+
+ function as_name() {
+ switch (S.token.type) {
+ case "name":
+ case "operator":
+ case "keyword":
+ case "atom":
+ return prog1(S.token.value, next);
+ default:
+ unexpected();
+ }
+ };
+
+ function subscripts(expr, allow_calls) {
+ if (is("punc", ".")) {
+ next();
+ return subscripts(as("dot", expr, as_name()), allow_calls);
+ }
+ if (is("punc", "[")) {
+ next();
+ return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
+ }
+ if (allow_calls && is("punc", "(")) {
+ next();
+ return subscripts(as("call", expr, expr_list(")")), true);
+ }
+ return expr;
+ };
+
+ function maybe_unary(allow_calls) {
+ if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
+ return make_unary("unary-prefix",
+ prog1(S.token.value, next),
+ maybe_unary(allow_calls));
+ }
+ var val = expr_atom(allow_calls);
+ while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
+ val = make_unary("unary-postfix", S.token.value, val);
+ next();
+ }
+ return val;
+ };
+
+ function make_unary(tag, op, expr) {
+ if ((op == "++" || op == "--") && !is_assignable(expr))
+ croak("Invalid use of " + op + " operator");
+ return as(tag, op, expr);
+ };
+
+ function expr_op(left, min_prec, no_in) {
+ var op = is("operator") ? S.token.value : null;
+ if (op && op == "in" && no_in) op = null;
+ var prec = op != null ? PRECEDENCE[op] : null;
+ if (prec != null && prec > min_prec) {
+ next();
+ var right = expr_op(maybe_unary(true), prec, no_in);
+ return expr_op(as("binary", op, left, right), min_prec, no_in);
+ }
+ return left;
+ };
+
+ function expr_ops(no_in) {
+ return expr_op(maybe_unary(true), 0, no_in);
+ };
+
+ function maybe_conditional(no_in) {
+ var expr = expr_ops(no_in);
+ if (is("operator", "?")) {
+ next();
+ var yes = expression(false);
+ expect(":");
+ return as("conditional", expr, yes, expression(false, no_in));
+ }
+ return expr;
+ };
+
+ function is_assignable(expr) {
+ if (!exigent_mode) return true;
+ switch (expr[0]+"") {
+ case "dot":
+ case "sub":
+ case "new":
+ case "call":
+ return true;
+ case "name":
+ return expr[1] != "this";
+ }
+ };
+
+ function maybe_assign(no_in) {
+ var left = maybe_conditional(no_in), val = S.token.value;
+ if (is("operator") && HOP(ASSIGNMENT, val)) {
+ if (is_assignable(left)) {
+ next();
+ return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
+ }
+ croak("Invalid assignment");
+ }
+ return left;
+ };
+
+ var expression = maybe_embed_tokens(function(commas, no_in) {
+ if (arguments.length == 0)
+ commas = true;
+ var expr = maybe_assign(no_in);
+ if (commas && is("punc", ",")) {
+ next();
+ return as("seq", expr, expression(true, no_in));
+ }
+ return expr;
+ });
+
+ function in_loop(cont) {
+ try {
+ ++S.in_loop;
+ return cont();
+ } finally {
+ --S.in_loop;
+ }
+ };
+
+ return as("toplevel", (function(a){
+ while (!is("eof"))
+ a.push(statement());
+ return a;
+ })([]));
+
+};
+
+/* -----[ Utilities ]----- */
+
+function curry(f) {
+ var args = slice(arguments, 1);
+ return function() { return f.apply(this, args.concat(slice(arguments))); };
+};
+
+function prog1(ret) {
+ if (ret instanceof Function)
+ ret = ret();
+ for (var i = 1, n = arguments.length; --n > 0; ++i)
+ arguments[i]();
+ return ret;
+};
+
+function array_to_hash(a) {
+ var ret = {};
+ for (var i = 0; i < a.length; ++i)
+ ret[a[i]] = true;
+ return ret;
+};
+
+function slice(a, start) {
+ return Array.prototype.slice.call(a, start || 0);
+};
+
+function characters(str) {
+ return str.split("");
+};
+
+function member(name, array) {
+ for (var i = array.length; --i >= 0;)
+ if (array[i] == name)
+ return true;
+ return false;
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+var warn = function() {};
+
+/* -----[ Exports ]----- */
+
+exports.tokenizer = tokenizer;
+exports.parse = parse;
+exports.slice = slice;
+exports.curry = curry;
+exports.member = member;
+exports.array_to_hash = array_to_hash;
+exports.PRECEDENCE = PRECEDENCE;
+exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
+exports.RESERVED_WORDS = RESERVED_WORDS;
+exports.KEYWORDS = KEYWORDS;
+exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
+exports.OPERATORS = OPERATORS;
+exports.is_alphanumeric_char = is_alphanumeric_char;
+exports.set_logger = function(logger) {
+ warn = logger;
+};
diff --git a/node_modules/uglify-js/lib/process.js b/node_modules/uglify-js/lib/process.js
new file mode 100644
index 0000000..5b2fe45
--- /dev/null
+++ b/node_modules/uglify-js/lib/process.js
@@ -0,0 +1,2011 @@
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file implements some AST processors. They work on data built
+ by parse-js.
+
+ Exported functions:
+
+ - ast_mangle(ast, options) -- mangles the variable/function names
+ in the AST. Returns an AST.
+
+ - ast_squeeze(ast) -- employs various optimizations to make the
+ final generated code even smaller. Returns an AST.
+
+ - gen_code(ast, options) -- generates JS code from the AST. Pass
+ true (or an object, see the code for some options) as second
+ argument to get "pretty" (indented) code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon
+
+ 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.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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.
+
+ ***********************************************************************/
+
+var jsp = require("./parse-js"),
+ slice = jsp.slice,
+ member = jsp.member,
+ PRECEDENCE = jsp.PRECEDENCE,
+ OPERATORS = jsp.OPERATORS;
+
+/* -----[ helper for AST traversal ]----- */
+
+function ast_walker() {
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(def){
+ var a = [ def[0] ];
+ if (def.length > 1)
+ a[1] = walk(def[1]);
+ return a;
+ }) ];
+ };
+ function _block(statements) {
+ var out = [ this[0] ];
+ if (statements != null)
+ out.push(MAP(statements, walk));
+ return out;
+ };
+ var walkers = {
+ "string": function(str) {
+ return [ this[0], str ];
+ },
+ "num": function(num) {
+ return [ this[0], num ];
+ },
+ "name": function(name) {
+ return [ this[0], name ];
+ },
+ "toplevel": function(statements) {
+ return [ this[0], MAP(statements, walk) ];
+ },
+ "block": _block,
+ "splice": _block,
+ "var": _vardefs,
+ "const": _vardefs,
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ MAP(t, walk),
+ c != null ? [ c[0], MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "throw": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "new": function(ctor, args) {
+ return [ this[0], walk(ctor), MAP(args, walk) ];
+ },
+ "switch": function(expr, body) {
+ return [ this[0], walk(expr), MAP(body, function(branch){
+ return [ branch[0] ? walk(branch[0]) : null,
+ MAP(branch[1], walk) ];
+ }) ];
+ },
+ "break": function(label) {
+ return [ this[0], label ];
+ },
+ "continue": function(label) {
+ return [ this[0], label ];
+ },
+ "conditional": function(cond, t, e) {
+ return [ this[0], walk(cond), walk(t), walk(e) ];
+ },
+ "assign": function(op, lvalue, rvalue) {
+ return [ this[0], op, walk(lvalue), walk(rvalue) ];
+ },
+ "dot": function(expr) {
+ return [ this[0], walk(expr) ].concat(slice(arguments, 1));
+ },
+ "call": function(expr, args) {
+ return [ this[0], walk(expr), MAP(args, walk) ];
+ },
+ "function": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "debugger": function() {
+ return [ this[0] ];
+ },
+ "defun": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "if": function(conditional, t, e) {
+ return [ this[0], walk(conditional), walk(t), walk(e) ];
+ },
+ "for": function(init, cond, step, block) {
+ return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
+ },
+ "while": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "do": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "return": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "binary": function(op, left, right) {
+ return [ this[0], op, walk(left), walk(right) ];
+ },
+ "unary-prefix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "unary-postfix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "sub": function(expr, subscript) {
+ return [ this[0], walk(expr), walk(subscript) ];
+ },
+ "object": function(props) {
+ return [ this[0], MAP(props, function(p){
+ return p.length == 2
+ ? [ p[0], walk(p[1]) ]
+ : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
+ }) ];
+ },
+ "regexp": function(rx, mods) {
+ return [ this[0], rx, mods ];
+ },
+ "array": function(elements) {
+ return [ this[0], MAP(elements, walk) ];
+ },
+ "stat": function(stat) {
+ return [ this[0], walk(stat) ];
+ },
+ "seq": function() {
+ return [ this[0] ].concat(MAP(slice(arguments), walk));
+ },
+ "label": function(name, block) {
+ return [ this[0], name, walk(block) ];
+ },
+ "with": function(expr, block) {
+ return [ this[0], walk(expr), walk(block) ];
+ },
+ "atom": function(name) {
+ return [ this[0], name ];
+ }
+ };
+
+ var user = {};
+ var stack = [];
+ function walk(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ var type = ast[0];
+ var gen = user[type];
+ if (gen) {
+ var ret = gen.apply(ast, ast.slice(1));
+ if (ret != null)
+ return ret;
+ }
+ gen = walkers[type];
+ return gen.apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function dive(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ return walkers[ast[0]].apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function with_walkers(walkers, cont){
+ var save = {}, i;
+ for (i in walkers) if (HOP(walkers, i)) {
+ save[i] = user[i];
+ user[i] = walkers[i];
+ }
+ var ret = cont();
+ for (i in save) if (HOP(save, i)) {
+ if (!save[i]) delete user[i];
+ else user[i] = save[i];
+ }
+ return ret;
+ };
+
+ return {
+ walk: walk,
+ dive: dive,
+ with_walkers: with_walkers,
+ parent: function() {
+ return stack[stack.length - 2]; // last one is current node
+ },
+ stack: function() {
+ return stack;
+ }
+ };
+};
+
+/* -----[ Scope and mangling ]----- */
+
+function Scope(parent) {
+ this.names = {}; // names defined in this scope
+ this.mangled = {}; // mangled names (orig.name => mangled)
+ this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
+ this.cname = -1; // current mangled name
+ this.refs = {}; // names referenced from this scope
+ this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
+ this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
+ this.parent = parent; // parent scope
+ this.children = []; // sub-scopes
+ if (parent) {
+ this.level = parent.level + 1;
+ parent.children.push(this);
+ } else {
+ this.level = 0;
+ }
+};
+
+var base54 = (function(){
+ var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
+ return function(num) {
+ var ret = "";
+ do {
+ ret = DIGITS.charAt(num % 54) + ret;
+ num = Math.floor(num / 54);
+ } while (num > 0);
+ return ret;
+ };
+})();
+
+Scope.prototype = {
+ has: function(name) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.names, name))
+ return s;
+ },
+ has_mangled: function(mname) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.rev_mangled, mname))
+ return s;
+ },
+ toJSON: function() {
+ return {
+ names: this.names,
+ uses_eval: this.uses_eval,
+ uses_with: this.uses_with
+ };
+ },
+
+ next_mangled: function() {
+ // we must be careful that the new mangled name:
+ //
+ // 1. doesn't shadow a mangled name from a parent
+ // scope, unless we don't reference the original
+ // name from this scope OR from any sub-scopes!
+ // This will get slow.
+ //
+ // 2. doesn't shadow an original name from a parent
+ // scope, in the event that the name is not mangled
+ // in the parent scope and we reference that name
+ // here OR IN ANY SUBSCOPES!
+ //
+ // 3. doesn't shadow a name that is referenced but not
+ // defined (possibly global defined elsewhere).
+ for (;;) {
+ var m = base54(++this.cname), prior;
+
+ // case 1.
+ prior = this.has_mangled(m);
+ if (prior && this.refs[prior.rev_mangled[m]] === prior)
+ continue;
+
+ // case 2.
+ prior = this.has(m);
+ if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
+ continue;
+
+ // case 3.
+ if (HOP(this.refs, m) && this.refs[m] == null)
+ continue;
+
+ // I got "do" once. :-/
+ if (!is_identifier(m))
+ continue;
+
+ return m;
+ }
+ },
+ set_mangle: function(name, m) {
+ this.rev_mangled[m] = name;
+ return this.mangled[name] = m;
+ },
+ get_mangled: function(name, newMangle) {
+ if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
+ var s = this.has(name);
+ if (!s) return name; // not in visible scope, no mangle
+ if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
+ if (!newMangle) return name; // not found and no mangling requested
+ return s.set_mangle(name, s.next_mangled());
+ },
+ references: function(name) {
+ return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
+ },
+ define: function(name, type) {
+ if (name != null) {
+ if (type == "var" || !HOP(this.names, name))
+ this.names[name] = type || "var";
+ return name;
+ }
+ }
+};
+
+function ast_add_scope(ast) {
+
+ var current_scope = null;
+ var w = ast_walker(), walk = w.walk;
+ var having_eval = [];
+
+ function with_new_scope(cont) {
+ current_scope = new Scope(current_scope);
+ current_scope.labels = new Scope();
+ var ret = current_scope.body = cont();
+ ret.scope = current_scope;
+ current_scope = current_scope.parent;
+ return ret;
+ };
+
+ function define(name, type) {
+ return current_scope.define(name, type);
+ };
+
+ function reference(name) {
+ current_scope.refs[name] = true;
+ };
+
+ function _lambda(name, args, body) {
+ var is_defun = this[0] == "defun";
+ return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
+ if (!is_defun) define(name, "lambda");
+ MAP(args, function(name){ define(name, "arg") });
+ return MAP(body, walk);
+ })];
+ };
+
+ function _vardefs(type) {
+ return function(defs) {
+ MAP(defs, function(d){
+ define(d[0], type);
+ if (d[1]) reference(d[0]);
+ });
+ };
+ };
+
+ function _breacont(label) {
+ if (label)
+ current_scope.labels.refs[label] = true;
+ };
+
+ return with_new_scope(function(){
+ // process AST
+ var ret = w.with_walkers({
+ "function": _lambda,
+ "defun": _lambda,
+ "label": function(name, stat) { current_scope.labels.define(name) },
+ "break": _breacont,
+ "continue": _breacont,
+ "with": function(expr, block) {
+ for (var s = current_scope; s; s = s.parent)
+ s.uses_with = true;
+ },
+ "var": _vardefs("var"),
+ "const": _vardefs("const"),
+ "try": function(t, c, f) {
+ if (c != null) return [
+ this[0],
+ MAP(t, walk),
+ [ define(c[0], "catch"), MAP(c[1], walk) ],
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "name": function(name) {
+ if (name == "eval")
+ having_eval.push(current_scope);
+ reference(name);
+ }
+ }, function(){
+ return walk(ast);
+ });
+
+ // the reason why we need an additional pass here is
+ // that names can be used prior to their definition.
+
+ // scopes where eval was detected and their parents
+ // are marked with uses_eval, unless they define the
+ // "eval" name.
+ MAP(having_eval, function(scope){
+ if (!scope.has("eval")) while (scope) {
+ scope.uses_eval = true;
+ scope = scope.parent;
+ }
+ });
+
+ // for referenced names it might be useful to know
+ // their origin scope. current_scope here is the
+ // toplevel one.
+ function fixrefs(scope, i) {
+ // do children first; order shouldn't matter
+ for (i = scope.children.length; --i >= 0;)
+ fixrefs(scope.children[i]);
+ for (i in scope.refs) if (HOP(scope.refs, i)) {
+ // find origin scope and propagate the reference to origin
+ for (var origin = scope.has(i), s = scope; s; s = s.parent) {
+ s.refs[i] = origin;
+ if (s === origin) break;
+ }
+ }
+ };
+ fixrefs(current_scope);
+
+ return ret;
+ });
+
+};
+
+/* -----[ mangle names ]----- */
+
+function ast_mangle(ast, options) {
+ var w = ast_walker(), walk = w.walk, scope;
+ options = options || {};
+
+ function get_mangled(name, newMangle) {
+ if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
+ if (options.except && member(name, options.except))
+ return name;
+ return scope.get_mangled(name, newMangle);
+ };
+
+ function get_define(name) {
+ if (options.defines) {
+ // we always lookup a defined symbol for the current scope FIRST, so declared
+ // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
+ if (!scope.has(name)) {
+ if (HOP(options.defines, name)) {
+ return options.defines[name];
+ }
+ }
+ return null;
+ }
+ };
+
+ function _lambda(name, args, body) {
+ if (!options.no_functions) {
+ var is_defun = this[0] == "defun", extra;
+ if (name) {
+ if (is_defun) name = get_mangled(name);
+ else if (body.scope.references(name)) {
+ extra = {};
+ if (!(scope.uses_eval || scope.uses_with))
+ name = extra[name] = scope.next_mangled();
+ else
+ extra[name] = name;
+ }
+ else name = null;
+ }
+ }
+ body = with_scope(body.scope, function(){
+ args = MAP(args, function(name){ return get_mangled(name) });
+ return MAP(body, walk);
+ }, extra);
+ return [ this[0], name, args, body ];
+ };
+
+ function with_scope(s, cont, extra) {
+ var _scope = scope;
+ scope = s;
+ if (extra) for (var i in extra) if (HOP(extra, i)) {
+ s.set_mangle(i, extra[i]);
+ }
+ for (var i in s.names) if (HOP(s.names, i)) {
+ get_mangled(i, true);
+ }
+ var ret = cont();
+ ret.scope = s;
+ scope = _scope;
+ return ret;
+ };
+
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(d){
+ return [ get_mangled(d[0]), walk(d[1]) ];
+ }) ];
+ };
+
+ function _breacont(label) {
+ if (label) return [ this[0], scope.labels.get_mangled(label) ];
+ };
+
+ return w.with_walkers({
+ "function": _lambda,
+ "defun": function() {
+ // move function declarations to the top when
+ // they are not in some block.
+ var ast = _lambda.apply(this, arguments);
+ switch (w.parent()[0]) {
+ case "toplevel":
+ case "function":
+ case "defun":
+ return MAP.at_top(ast);
+ }
+ return ast;
+ },
+ "label": function(label, stat) {
+ if (scope.labels.refs[label]) return [
+ this[0],
+ scope.labels.get_mangled(label, true),
+ walk(stat)
+ ];
+ return walk(stat);
+ },
+ "break": _breacont,
+ "continue": _breacont,
+ "var": _vardefs,
+ "const": _vardefs,
+ "name": function(name) {
+ return get_define(name) || [ this[0], get_mangled(name) ];
+ },
+ "try": function(t, c, f) {
+ return [ this[0],
+ MAP(t, walk),
+ c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null ];
+ },
+ "toplevel": function(body) {
+ var self = this;
+ return with_scope(self.scope, function(){
+ return [ self[0], MAP(body, walk) ];
+ });
+ }
+ }, function() {
+ return walk(ast_add_scope(ast));
+ });
+};
+
+/* -----[
+ - compress foo["bar"] into foo.bar,
+ - remove block brackets {} where possible
+ - join consecutive var declarations
+ - various optimizations for IFs:
+ - if (cond) foo(); else bar(); ==> cond?foo():bar();
+ - if (cond) foo(); ==> cond&&foo();
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
+ ]----- */
+
+var warn = function(){};
+
+function best_of(ast1, ast2) {
+ return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
+};
+
+function last_stat(b) {
+ if (b[0] == "block" && b[1] && b[1].length > 0)
+ return b[1][b[1].length - 1];
+ return b;
+}
+
+function aborts(t) {
+ if (t) switch (last_stat(t)[0]) {
+ case "return":
+ case "break":
+ case "continue":
+ case "throw":
+ return true;
+ }
+};
+
+function boolean_expr(expr) {
+ return ( (expr[0] == "unary-prefix"
+ && member(expr[1], [ "!", "delete" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "&&", "||" ])
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "conditional"
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "assign"
+ && expr[1] === true
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "seq"
+ && boolean_expr(expr[expr.length - 1]))
+ );
+};
+
+function empty(b) {
+ return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
+};
+
+function is_string(node) {
+ return (node[0] == "string" ||
+ node[0] == "unary-prefix" && node[1] == "typeof" ||
+ node[0] == "binary" && node[1] == "+" &&
+ (is_string(node[2]) || is_string(node[3])));
+};
+
+var when_constant = (function(){
+
+ var $NOT_CONSTANT = {};
+
+ // this can only evaluate constant expressions. If it finds anything
+ // not constant, it throws $NOT_CONSTANT.
+ function evaluate(expr) {
+ switch (expr[0]) {
+ case "string":
+ case "num":
+ return expr[1];
+ case "name":
+ case "atom":
+ switch (expr[1]) {
+ case "true": return true;
+ case "false": return false;
+ case "null": return null;
+ }
+ break;
+ case "unary-prefix":
+ switch (expr[1]) {
+ case "!": return !evaluate(expr[2]);
+ case "typeof": return typeof evaluate(expr[2]);
+ case "~": return ~evaluate(expr[2]);
+ case "-": return -evaluate(expr[2]);
+ case "+": return +evaluate(expr[2]);
+ }
+ break;
+ case "binary":
+ var left = expr[2], right = expr[3];
+ switch (expr[1]) {
+ case "&&" : return evaluate(left) && evaluate(right);
+ case "||" : return evaluate(left) || evaluate(right);
+ case "|" : return evaluate(left) | evaluate(right);
+ case "&" : return evaluate(left) & evaluate(right);
+ case "^" : return evaluate(left) ^ evaluate(right);
+ case "+" : return evaluate(left) + evaluate(right);
+ case "*" : return evaluate(left) * evaluate(right);
+ case "/" : return evaluate(left) / evaluate(right);
+ case "%" : return evaluate(left) % evaluate(right);
+ case "-" : return evaluate(left) - evaluate(right);
+ case "<<" : return evaluate(left) << evaluate(right);
+ case ">>" : return evaluate(left) >> evaluate(right);
+ case ">>>" : return evaluate(left) >>> evaluate(right);
+ case "==" : return evaluate(left) == evaluate(right);
+ case "===" : return evaluate(left) === evaluate(right);
+ case "!=" : return evaluate(left) != evaluate(right);
+ case "!==" : return evaluate(left) !== evaluate(right);
+ case "<" : return evaluate(left) < evaluate(right);
+ case "<=" : return evaluate(left) <= evaluate(right);
+ case ">" : return evaluate(left) > evaluate(right);
+ case ">=" : return evaluate(left) >= evaluate(right);
+ case "in" : return evaluate(left) in evaluate(right);
+ case "instanceof" : return evaluate(left) instanceof evaluate(right);
+ }
+ }
+ throw $NOT_CONSTANT;
+ };
+
+ return function(expr, yes, no) {
+ try {
+ var val = evaluate(expr), ast;
+ switch (typeof val) {
+ case "string": ast = [ "string", val ]; break;
+ case "number": ast = [ "num", val ]; break;
+ case "boolean": ast = [ "name", String(val) ]; break;
+ default:
+ if (val === null) { ast = [ "atom", "null" ]; break; }
+ throw new Error("Can't handle constant of type: " + (typeof val));
+ }
+ return yes.call(expr, ast, val);
+ } catch(ex) {
+ if (ex === $NOT_CONSTANT) {
+ if (expr[0] == "binary"
+ && (expr[1] == "===" || expr[1] == "!==")
+ && ((is_string(expr[2]) && is_string(expr[3]))
+ || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
+ expr[1] = expr[1].substr(0, 2);
+ }
+ else if (no && expr[0] == "binary"
+ && (expr[1] == "||" || expr[1] == "&&")) {
+ // the whole expression is not constant but the lval may be...
+ try {
+ var lval = evaluate(expr[2]);
+ expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
+ (expr[1] == "||" && (lval ? lval : expr[3])) ||
+ expr);
+ } catch(ex2) {
+ // IGNORE... lval is not constant
+ }
+ }
+ return no ? no.call(expr, expr) : null;
+ }
+ else throw ex;
+ }
+ };
+
+})();
+
+function warn_unreachable(ast) {
+ if (!empty(ast))
+ warn("Dropping unreachable code: " + gen_code(ast, true));
+};
+
+function prepare_ifs(ast) {
+ var w = ast_walker(), walk = w.walk;
+ // In this first pass, we rewrite ifs which abort with no else with an
+ // if-else. For example:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // }
+ // foobar();
+ //
+ // is rewritten into:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // } else {
+ // foobar();
+ // }
+ function redo_if(statements) {
+ statements = MAP(statements, walk);
+
+ for (var i = 0; i < statements.length; ++i) {
+ var fi = statements[i];
+ if (fi[0] != "if") continue;
+
+ if (fi[3] && walk(fi[3])) continue;
+
+ var t = walk(fi[2]);
+ if (!aborts(t)) continue;
+
+ var conditional = walk(fi[1]);
+
+ var e_body = redo_if(statements.slice(i + 1));
+ var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
+
+ return statements.slice(0, i).concat([ [
+ fi[0], // "if"
+ conditional, // conditional
+ t, // then
+ e // else
+ ] ]);
+ }
+
+ return statements;
+ };
+
+ function redo_if_lambda(name, args, body) {
+ body = redo_if(body);
+ return [ this[0], name, args, body ];
+ };
+
+ function redo_if_block(statements) {
+ return [ this[0], statements != null ? redo_if(statements) : null ];
+ };
+
+ return w.with_walkers({
+ "defun": redo_if_lambda,
+ "function": redo_if_lambda,
+ "block": redo_if_block,
+ "splice": redo_if_block,
+ "toplevel": function(statements) {
+ return [ this[0], redo_if(statements) ];
+ },
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ redo_if(t),
+ c != null ? [ c[0], redo_if(c[1]) ] : null,
+ f != null ? redo_if(f) : null
+ ];
+ }
+ }, function() {
+ return walk(ast);
+ });
+};
+
+function for_side_effects(ast, handler) {
+ var w = ast_walker(), walk = w.walk;
+ var $stop = {}, $restart = {};
+ function stop() { throw $stop };
+ function restart() { throw $restart };
+ function found(){ return handler.call(this, this, w, stop, restart) };
+ function unary(op) {
+ if (op == "++" || op == "--")
+ return found.apply(this, arguments);
+ };
+ return w.with_walkers({
+ "try": found,
+ "throw": found,
+ "return": found,
+ "new": found,
+ "switch": found,
+ "break": found,
+ "continue": found,
+ "assign": found,
+ "call": found,
+ "if": found,
+ "for": found,
+ "for-in": found,
+ "while": found,
+ "do": found,
+ "return": found,
+ "unary-prefix": unary,
+ "unary-postfix": unary,
+ "defun": found
+ }, function(){
+ while (true) try {
+ walk(ast);
+ break;
+ } catch(ex) {
+ if (ex === $stop) break;
+ if (ex === $restart) continue;
+ throw ex;
+ }
+ });
+};
+
+function ast_lift_variables(ast) {
+ var w = ast_walker(), walk = w.walk, scope;
+ function do_body(body, env) {
+ var _scope = scope;
+ scope = env;
+ body = MAP(body, walk);
+ var hash = {}, names = MAP(env.names, function(type, name){
+ if (type != "var") return MAP.skip;
+ if (!env.references(name)) return MAP.skip;
+ hash[name] = true;
+ return [ name ];
+ });
+ if (names.length > 0) {
+ // looking for assignments to any of these variables.
+ // we can save considerable space by moving the definitions
+ // in the var declaration.
+ for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
+ if (ast[0] == "assign"
+ && ast[1] === true
+ && ast[2][0] == "name"
+ && HOP(hash, ast[2][1])) {
+ // insert the definition into the var declaration
+ for (var i = names.length; --i >= 0;) {
+ if (names[i][0] == ast[2][1]) {
+ if (names[i][1]) // this name already defined, we must stop
+ stop();
+ names[i][1] = ast[3]; // definition
+ names.push(names.splice(i, 1)[0]);
+ break;
+ }
+ }
+ // remove this assignment from the AST.
+ var p = walker.parent();
+ if (p[0] == "seq") {
+ var a = p[2];
+ a.unshift(0, p.length);
+ p.splice.apply(p, a);
+ }
+ else if (p[0] == "stat") {
+ p.splice(0, p.length, "block"); // empty statement
+ }
+ else {
+ stop();
+ }
+ restart();
+ }
+ stop();
+ });
+ body.unshift([ "var", names ]);
+ }
+ scope = _scope;
+ return body;
+ };
+ function _vardefs(defs) {
+ var ret = null;
+ for (var i = defs.length; --i >= 0;) {
+ var d = defs[i];
+ if (!d[1]) continue;
+ d = [ "assign", true, [ "name", d[0] ], d[1] ];
+ if (ret == null) ret = d;
+ else ret = [ "seq", d, ret ];
+ }
+ if (ret == null) {
+ if (w.parent()[0] == "for-in")
+ return [ "name", defs[0][0] ];
+ return MAP.skip;
+ }
+ return [ "stat", ret ];
+ };
+ function _toplevel(body) {
+ return [ this[0], do_body(body, this.scope) ];
+ };
+ return w.with_walkers({
+ "function": function(name, args, body){
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ if (!body.scope.references(name)) name = null;
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "defun": function(name, args, body){
+ if (!scope.references(name)) return MAP.skip;
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "var": _vardefs,
+ "toplevel": _toplevel
+ }, function(){
+ return walk(ast_add_scope(ast));
+ });
+};
+
+function ast_squeeze(ast, options) {
+ options = defaults(options, {
+ make_seqs : true,
+ dead_code : true,
+ no_warnings : false,
+ keep_comps : true
+ });
+
+ var w = ast_walker(), walk = w.walk;
+
+ function negate(c) {
+ var not_c = [ "unary-prefix", "!", c ];
+ switch (c[0]) {
+ case "unary-prefix":
+ return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
+ case "seq":
+ c = slice(c);
+ c[c.length - 1] = negate(c[c.length - 1]);
+ return c;
+ case "conditional":
+ return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
+ case "binary":
+ var op = c[1], left = c[2], right = c[3];
+ if (!options.keep_comps) switch (op) {
+ case "<=" : return [ "binary", ">", left, right ];
+ case "<" : return [ "binary", ">=", left, right ];
+ case ">=" : return [ "binary", "<", left, right ];
+ case ">" : return [ "binary", "<=", left, right ];
+ }
+ switch (op) {
+ case "==" : return [ "binary", "!=", left, right ];
+ case "!=" : return [ "binary", "==", left, right ];
+ case "===" : return [ "binary", "!==", left, right ];
+ case "!==" : return [ "binary", "===", left, right ];
+ case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
+ case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
+ }
+ break;
+ }
+ return not_c;
+ };
+
+ function make_conditional(c, t, e) {
+ var make_real_conditional = function() {
+ if (c[0] == "unary-prefix" && c[1] == "!") {
+ return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
+ } else {
+ return e ? best_of(
+ [ "conditional", c, t, e ],
+ [ "conditional", negate(c), e, t ]
+ ) : [ "binary", "&&", c, t ];
+ }
+ };
+ // shortcut the conditional if the expression has a constant value
+ return when_constant(c, function(ast, val){
+ warn_unreachable(val ? e : t);
+ return (val ? t : e);
+ }, make_real_conditional);
+ };
+
+ function rmblock(block) {
+ if (block != null && block[0] == "block" && block[1]) {
+ if (block[1].length == 1)
+ block = block[1][0];
+ else if (block[1].length == 0)
+ block = [ "block" ];
+ }
+ return block;
+ };
+
+ function _lambda(name, args, body) {
+ return [ this[0], name, args, tighten(body, "lambda") ];
+ };
+
+ // this function does a few things:
+ // 1. discard useless blocks
+ // 2. join consecutive var declarations
+ // 3. remove obviously dead code
+ // 4. transform consecutive statements using the comma operator
+ // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
+ function tighten(statements, block_type) {
+ statements = MAP(statements, walk);
+
+ statements = statements.reduce(function(a, stat){
+ if (stat[0] == "block") {
+ if (stat[1]) {
+ a.push.apply(a, stat[1]);
+ }
+ } else {
+ a.push(stat);
+ }
+ return a;
+ }, []);
+
+ statements = (function(a, prev){
+ statements.forEach(function(cur){
+ if (prev && ((cur[0] == "var" && prev[0] == "var") ||
+ (cur[0] == "const" && prev[0] == "const"))) {
+ prev[1] = prev[1].concat(cur[1]);
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.dead_code) statements = (function(a, has_quit){
+ statements.forEach(function(st){
+ if (has_quit) {
+ if (st[0] == "function" || st[0] == "defun") {
+ a.push(st);
+ }
+ else if (st[0] == "var" || st[0] == "const") {
+ if (!options.no_warnings)
+ warn("Variables declared in unreachable code");
+ st[1] = MAP(st[1], function(def){
+ if (def[1] && !options.no_warnings)
+ warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
+ return [ def[0] ];
+ });
+ a.push(st);
+ }
+ else if (!options.no_warnings)
+ warn_unreachable(st);
+ }
+ else {
+ a.push(st);
+ if (member(st[0], [ "return", "throw", "break", "continue" ]))
+ has_quit = true;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.make_seqs) statements = (function(a, prev) {
+ statements.forEach(function(cur){
+ if (prev && prev[0] == "stat" && cur[0] == "stat") {
+ prev[1] = [ "seq", prev[1], cur[1] ];
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ if (a.length >= 2
+ && a[a.length-2][0] == "stat"
+ && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
+ && a[a.length-1][1])
+ {
+ a.splice(a.length - 2, 2,
+ [ a[a.length-1][0],
+ [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
+ }
+ return a;
+ })([]);
+
+ // this increases jQuery by 1K. Probably not such a good idea after all..
+ // part of this is done in prepare_ifs anyway.
+ // if (block_type == "lambda") statements = (function(i, a, stat){
+ // while (i < statements.length) {
+ // stat = statements[i++];
+ // if (stat[0] == "if" && !stat[3]) {
+ // if (stat[2][0] == "return" && stat[2][1] == null) {
+ // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // var last = last_stat(stat[2]);
+ // if (last[0] == "return" && last[1] == null) {
+ // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // }
+ // a.push(stat);
+ // }
+ // return a;
+ // })(0, []);
+
+ return statements;
+ };
+
+ function make_if(c, t, e) {
+ return when_constant(c, function(ast, val){
+ if (val) {
+ t = walk(t);
+ warn_unreachable(e);
+ return t || [ "block" ];
+ } else {
+ e = walk(e);
+ warn_unreachable(t);
+ return e || [ "block" ];
+ }
+ }, function() {
+ return make_real_if(c, t, e);
+ });
+ };
+
+ function abort_else(c, t, e) {
+ var ret = [ [ "if", negate(c), e ] ];
+ if (t[0] == "block") {
+ if (t[1]) ret = ret.concat(t[1]);
+ } else {
+ ret.push(t);
+ }
+ return walk([ "block", ret ]);
+ };
+
+ function make_real_if(c, t, e) {
+ c = walk(c);
+ t = walk(t);
+ e = walk(e);
+
+ if (empty(t)) {
+ c = negate(c);
+ t = e;
+ e = null;
+ } else if (empty(e)) {
+ e = null;
+ } else {
+ // if we have both else and then, maybe it makes sense to switch them?
+ (function(){
+ var a = gen_code(c);
+ var n = negate(c);
+ var b = gen_code(n);
+ if (b.length < a.length) {
+ var tmp = t;
+ t = e;
+ e = tmp;
+ c = n;
+ }
+ })();
+ }
+ if (empty(e) && empty(t))
+ return [ "stat", c ];
+ var ret = [ "if", c, t, e ];
+ if (t[0] == "if" && empty(t[3]) && empty(e)) {
+ ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
+ }
+ else if (t[0] == "stat") {
+ if (e) {
+ if (e[0] == "stat")
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
+ else if (aborts(e))
+ ret = abort_else(c, t, e);
+ }
+ else {
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
+ }
+ }
+ else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
+ ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
+ }
+ else if (e && aborts(t)) {
+ ret = [ [ "if", c, t ] ];
+ if (e[0] == "block") {
+ if (e[1]) ret = ret.concat(e[1]);
+ }
+ else {
+ ret.push(e);
+ }
+ ret = walk([ "block", ret ]);
+ }
+ else if (t && aborts(e)) {
+ ret = abort_else(c, t, e);
+ }
+ return ret;
+ };
+
+ function _do_while(cond, body) {
+ return when_constant(cond, function(cond, val){
+ if (!val) {
+ warn_unreachable(body);
+ return [ "block" ];
+ } else {
+ return [ "for", null, null, null, walk(body) ];
+ }
+ });
+ };
+
+ return w.with_walkers({
+ "sub": function(expr, subscript) {
+ if (subscript[0] == "string") {
+ var name = subscript[1];
+ if (is_identifier(name))
+ return [ "dot", walk(expr), name ];
+ else if (/^[1-9][0-9]*$/.test(name) || name === "0")
+ return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
+ }
+ },
+ "if": make_if,
+ "toplevel": function(body) {
+ return [ "toplevel", tighten(body) ];
+ },
+ "switch": function(expr, body) {
+ var last = body.length - 1;
+ return [ "switch", walk(expr), MAP(body, function(branch, i){
+ var block = tighten(branch[1]);
+ if (i == last && block.length > 0) {
+ var node = block[block.length - 1];
+ if (node[0] == "break" && !node[1])
+ block.pop();
+ }
+ return [ branch[0] ? walk(branch[0]) : null, block ];
+ }) ];
+ },
+ "function": _lambda,
+ "defun": _lambda,
+ "block": function(body) {
+ if (body) return rmblock([ "block", tighten(body) ]);
+ },
+ "binary": function(op, left, right) {
+ return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
+ return best_of(walk(c), this);
+ }, function no() {
+ return function(){
+ if(op != "==" && op != "!=") return;
+ var l = walk(left), r = walk(right);
+ if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
+ left = ['num', +!l[2][1]];
+ else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
+ right = ['num', +!r[2][1]];
+ return ["binary", op, left, right];
+ }() || this;
+ });
+ },
+ "conditional": function(c, t, e) {
+ return make_conditional(walk(c), walk(t), walk(e));
+ },
+ "try": function(t, c, f) {
+ return [
+ "try",
+ tighten(t),
+ c != null ? [ c[0], tighten(c[1]) ] : null,
+ f != null ? tighten(f) : null
+ ];
+ },
+ "unary-prefix": function(op, expr) {
+ expr = walk(expr);
+ var ret = [ "unary-prefix", op, expr ];
+ if (op == "!")
+ ret = best_of(ret, negate(expr));
+ return when_constant(ret, function(ast, val){
+ return walk(ast); // it's either true or false, so minifies to !0 or !1
+ }, function() { return ret });
+ },
+ "name": function(name) {
+ switch (name) {
+ case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
+ case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
+ }
+ },
+ "while": _do_while,
+ "assign": function(op, lvalue, rvalue) {
+ lvalue = walk(lvalue);
+ rvalue = walk(rvalue);
+ var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
+ if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
+ ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
+ rvalue[2][1] === lvalue[1]) {
+ return [ this[0], rvalue[1], lvalue, rvalue[3] ]
+ }
+ return [ this[0], op, lvalue, rvalue ];
+ }
+ }, function() {
+ for (var i = 0; i < 2; ++i) {
+ ast = prepare_ifs(ast);
+ ast = walk(ast);
+ }
+ return ast;
+ });
+};
+
+/* -----[ re-generate code from the AST ]----- */
+
+var DOT_CALL_NO_PARENS = jsp.array_to_hash([
+ "name",
+ "array",
+ "object",
+ "string",
+ "dot",
+ "sub",
+ "call",
+ "regexp",
+ "defun"
+]);
+
+function make_string(str, ascii_only) {
+ var dq = 0, sq = 0;
+ str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
+ switch (s) {
+ case "\\": return "\\\\";
+ case "\b": return "\\b";
+ case "\f": return "\\f";
+ case "\n": return "\\n";
+ case "\r": return "\\r";
+ case "\t": return "\\t";
+ case "\u2028": return "\\u2028";
+ case "\u2029": return "\\u2029";
+ case '"': ++dq; return '"';
+ case "'": ++sq; return "'";
+ case "\0": return "\\0";
+ }
+ return s;
+ });
+ if (ascii_only) str = to_ascii(str);
+ if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
+ else return '"' + str.replace(/\x22/g, '\\"') + '"';
+};
+
+function to_ascii(str) {
+ return str.replace(/[\u0080-\uffff]/g, function(ch) {
+ var code = ch.charCodeAt(0).toString(16);
+ while (code.length < 4) code = "0" + code;
+ return "\\u" + code;
+ });
+};
+
+var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
+
+function gen_code(ast, options) {
+ options = defaults(options, {
+ indent_start : 0,
+ indent_level : 4,
+ quote_keys : false,
+ space_colon : false,
+ beautify : false,
+ ascii_only : false,
+ inline_script: false
+ });
+ var beautify = !!options.beautify;
+ var indentation = 0,
+ newline = beautify ? "\n" : "",
+ space = beautify ? " " : "";
+
+ function encode_string(str) {
+ var ret = make_string(str, options.ascii_only);
+ if (options.inline_script)
+ ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
+ return ret;
+ };
+
+ function make_name(name) {
+ name = name.toString();
+ if (options.ascii_only)
+ name = to_ascii(name);
+ return name;
+ };
+
+ function indent(line) {
+ if (line == null)
+ line = "";
+ if (beautify)
+ line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
+ return line;
+ };
+
+ function with_indent(cont, incr) {
+ if (incr == null) incr = 1;
+ indentation += incr;
+ try { return cont.apply(null, slice(arguments, 1)); }
+ finally { indentation -= incr; }
+ };
+
+ function add_spaces(a) {
+ if (beautify)
+ return a.join(" ");
+ var b = [];
+ for (var i = 0; i < a.length; ++i) {
+ var next = a[i + 1];
+ b.push(a[i]);
+ if (next &&
+ ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) ||
+ (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) {
+ b.push(" ");
+ }
+ }
+ return b.join("");
+ };
+
+ function add_commas(a) {
+ return a.join("," + space);
+ };
+
+ function parenthesize(expr) {
+ var gen = make(expr);
+ for (var i = 1; i < arguments.length; ++i) {
+ var el = arguments[i];
+ if ((el instanceof Function && el(expr)) || expr[0] == el)
+ return "(" + gen + ")";
+ }
+ return gen;
+ };
+
+ function best_of(a) {
+ if (a.length == 1) {
+ return a[0];
+ }
+ if (a.length == 2) {
+ var b = a[1];
+ a = a[0];
+ return a.length <= b.length ? a : b;
+ }
+ return best_of([ a[0], best_of(a.slice(1)) ]);
+ };
+
+ function needs_parens(expr) {
+ if (expr[0] == "function" || expr[0] == "object") {
+ // dot/call on a literal function requires the
+ // function literal itself to be parenthesized
+ // only if it's the first "thing" in a
+ // statement. This means that the parent is
+ // "stat", but it could also be a "seq" and
+ // we're the first in this "seq" and the
+ // parent is "stat", and so on. Messy stuff,
+ // but it worths the trouble.
+ var a = slice(w.stack()), self = a.pop(), p = a.pop();
+ while (p) {
+ if (p[0] == "stat") return true;
+ if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
+ ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
+ self = p;
+ p = a.pop();
+ } else {
+ return false;
+ }
+ }
+ }
+ return !HOP(DOT_CALL_NO_PARENS, expr[0]);
+ };
+
+ function make_num(num) {
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m;
+ if (Math.floor(num) === num) {
+ if (num >= 0) {
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
+ "0" + num.toString(8)); // same.
+ } else {
+ a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
+ "-0" + (-num).toString(8)); // same.
+ }
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
+ a.push(m[1] + "e" + m[2].length);
+ }
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
+ a.push(m[2] + "e-" + (m[1].length + m[2].length),
+ str.substr(str.indexOf(".")));
+ }
+ return best_of(a);
+ };
+
+ var w = ast_walker();
+ var make = w.walk;
+ return w.with_walkers({
+ "string": encode_string,
+ "num": make_num,
+ "name": make_name,
+ "debugger": function(){ return "debugger" },
+ "toplevel": function(statements) {
+ return make_block_statements(statements)
+ .join(newline + newline);
+ },
+ "splice": function(statements) {
+ var parent = w.parent();
+ if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
+ // we need block brackets in this case
+ return make_block.apply(this, arguments);
+ } else {
+ return MAP(make_block_statements(statements, true),
+ function(line, i) {
+ // the first line is already indented
+ return i > 0 ? indent(line) : line;
+ }).join(newline);
+ }
+ },
+ "block": make_block,
+ "var": function(defs) {
+ return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "const": function(defs) {
+ return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "try": function(tr, ca, fi) {
+ var out = [ "try", make_block(tr) ];
+ if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
+ if (fi) out.push("finally", make_block(fi));
+ return add_spaces(out);
+ },
+ "throw": function(expr) {
+ return add_spaces([ "throw", make(expr) ]) + ";";
+ },
+ "new": function(ctor, args) {
+ args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")" : "";
+ return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
+ var w = ast_walker(), has_call = {};
+ try {
+ w.with_walkers({
+ "call": function() { throw has_call },
+ "function": function() { return this }
+ }, function(){
+ w.walk(expr);
+ });
+ } catch(ex) {
+ if (ex === has_call)
+ return true;
+ throw ex;
+ }
+ }) + args ]);
+ },
+ "switch": function(expr, body) {
+ return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
+ },
+ "break": function(label) {
+ var out = "break";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "continue": function(label) {
+ var out = "continue";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "conditional": function(co, th, el) {
+ return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
+ parenthesize(th, "seq"), ":",
+ parenthesize(el, "seq") ]);
+ },
+ "assign": function(op, lvalue, rvalue) {
+ if (op && op !== true) op += "=";
+ else op = "=";
+ return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
+ },
+ "dot": function(expr) {
+ var out = make(expr), i = 1;
+ if (expr[0] == "num") {
+ if (!/\./.test(expr[1]))
+ out += ".";
+ } else if (needs_parens(expr))
+ out = "(" + out + ")";
+ while (i < arguments.length)
+ out += "." + make_name(arguments[i++]);
+ return out;
+ },
+ "call": function(func, args) {
+ var f = make(func);
+ if (f.charAt(0) != "(" && needs_parens(func))
+ f = "(" + f + ")";
+ return f + "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")";
+ },
+ "function": make_function,
+ "defun": make_function,
+ "if": function(co, th, el) {
+ var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
+ if (el) {
+ out.push("else", make(el));
+ }
+ return add_spaces(out);
+ },
+ "for": function(init, cond, step, block) {
+ var out = [ "for" ];
+ init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
+ cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
+ step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
+ var args = init + cond + step;
+ if (args == "; ; ") args = ";;";
+ out.push("(" + args + ")", make(block));
+ return add_spaces(out);
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return add_spaces([ "for", "(" +
+ (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
+ "in",
+ make(hash) + ")", make(block) ]);
+ },
+ "while": function(condition, block) {
+ return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
+ },
+ "do": function(condition, block) {
+ return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
+ },
+ "return": function(expr) {
+ var out = [ "return" ];
+ if (expr != null) out.push(make(expr));
+ return add_spaces(out) + ";";
+ },
+ "binary": function(operator, lvalue, rvalue) {
+ var left = make(lvalue), right = make(rvalue);
+ // XXX: I'm pretty sure other cases will bite here.
+ // we need to be smarter.
+ // adding parens all the time is the safest bet.
+ if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
+ lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
+ lvalue[0] == "function" && needs_parens(this)) {
+ left = "(" + left + ")";
+ }
+ if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
+ rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
+ !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
+ right = "(" + right + ")";
+ }
+ else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
+ && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
+ right = " " + right;
+ }
+ return add_spaces([ left, operator, right ]);
+ },
+ "unary-prefix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
+ },
+ "unary-postfix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return val + operator;
+ },
+ "sub": function(expr, subscript) {
+ var hash = make(expr);
+ if (needs_parens(expr))
+ hash = "(" + hash + ")";
+ return hash + "[" + make(subscript) + "]";
+ },
+ "object": function(props) {
+ var obj_needs_parens = needs_parens(this);
+ if (props.length == 0)
+ return obj_needs_parens ? "({})" : "{}";
+ var out = "{" + newline + with_indent(function(){
+ return MAP(props, function(p){
+ if (p.length == 3) {
+ // getter/setter. The name is in p[0], the arg.list in p[1][2], the
+ // body in p[1][3] and type ("get" / "set") in p[2].
+ return indent(make_function(p[0], p[1][2], p[1][3], p[2]));
+ }
+ var key = p[0], val = parenthesize(p[1], "seq");
+ if (options.quote_keys) {
+ key = encode_string(key);
+ } else if ((typeof key == "number" || !beautify && +key + "" == key)
+ && parseFloat(key) >= 0) {
+ key = make_num(+key);
+ } else if (!is_identifier(key)) {
+ key = encode_string(key);
+ }
+ return indent(add_spaces(beautify && options.space_colon
+ ? [ key, ":", val ]
+ : [ key + ":", val ]));
+ }).join("," + newline);
+ }) + newline + indent("}");
+ return obj_needs_parens ? "(" + out + ")" : out;
+ },
+ "regexp": function(rx, mods) {
+ return "/" + rx + "/" + mods;
+ },
+ "array": function(elements) {
+ if (elements.length == 0) return "[]";
+ return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
+ if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
+ return parenthesize(el, "seq");
+ })), "]" ]);
+ },
+ "stat": function(stmt) {
+ return make(stmt).replace(/;*\s*$/, ";");
+ },
+ "seq": function() {
+ return add_commas(MAP(slice(arguments), make));
+ },
+ "label": function(name, block) {
+ return add_spaces([ make_name(name), ":", make(block) ]);
+ },
+ "with": function(expr, block) {
+ return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
+ },
+ "atom": function(name) {
+ return make_name(name);
+ }
+ }, function(){ return make(ast) });
+
+ // The squeezer replaces "block"-s that contain only a single
+ // statement with the statement itself; technically, the AST
+ // is correct, but this can create problems when we output an
+ // IF having an ELSE clause where the THEN clause ends in an
+ // IF *without* an ELSE block (then the outer ELSE would refer
+ // to the inner IF). This function checks for this case and
+ // adds the block brackets if needed.
+ function make_then(th) {
+ if (th == null) return ";";
+ if (th[0] == "do") {
+ // https://github.com/mishoo/UglifyJS/issues/#issue/57
+ // IE croaks with "syntax error" on code like this:
+ // if (foo) do ... while(cond); else ...
+ // we need block brackets around do/while
+ return make_block([ th ]);
+ }
+ var b = th;
+ while (true) {
+ var type = b[0];
+ if (type == "if") {
+ if (!b[3])
+ // no else, we must add the block
+ return make([ "block", [ th ]]);
+ b = b[3];
+ }
+ else if (type == "while" || type == "do") b = b[2];
+ else if (type == "for" || type == "for-in") b = b[4];
+ else break;
+ }
+ return make(th);
+ };
+
+ function make_function(name, args, body, keyword) {
+ var out = keyword || "function";
+ if (name) {
+ out += " " + make_name(name);
+ }
+ out += "(" + add_commas(MAP(args, make_name)) + ")";
+ out = add_spaces([ out, make_block(body) ]);
+ return needs_parens(this) ? "(" + out + ")" : out;
+ };
+
+ function must_has_semicolon(node) {
+ switch (node[0]) {
+ case "with":
+ case "while":
+ return empty(node[2]); // `with' or `while' with empty body?
+ case "for":
+ case "for-in":
+ return empty(node[4]); // `for' with empty body?
+ case "if":
+ if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
+ if (node[3]) {
+ if (empty(node[3])) return true; // `else' present but empty
+ return must_has_semicolon(node[3]); // dive into the `else' branch
+ }
+ return must_has_semicolon(node[2]); // dive into the `then' branch
+ }
+ };
+
+ function make_block_statements(statements, noindent) {
+ for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
+ var stat = statements[i];
+ var code = make(stat);
+ if (code != ";") {
+ if (!beautify && i == last && !must_has_semicolon(stat)) {
+ code = code.replace(/;+\s*$/, "");
+ }
+ a.push(code);
+ }
+ }
+ return noindent ? a : MAP(a, indent);
+ };
+
+ function make_switch_block(body) {
+ var n = body.length;
+ if (n == 0) return "{}";
+ return "{" + newline + MAP(body, function(branch, i){
+ var has_body = branch[1].length > 0, code = with_indent(function(){
+ return indent(branch[0]
+ ? add_spaces([ "case", make(branch[0]) + ":" ])
+ : "default:");
+ }, 0.5) + (has_body ? newline + with_indent(function(){
+ return make_block_statements(branch[1]).join(newline);
+ }) : "");
+ if (!beautify && has_body && i < n - 1)
+ code += ";";
+ return code;
+ }).join(newline) + newline + indent("}");
+ };
+
+ function make_block(statements) {
+ if (!statements) return ";";
+ if (statements.length == 0) return "{}";
+ return "{" + newline + with_indent(function(){
+ return make_block_statements(statements).join(newline);
+ }) + newline + indent("}");
+ };
+
+ function make_1vardef(def) {
+ var name = def[0], val = def[1];
+ if (val != null)
+ name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
+ return name;
+ };
+
+};
+
+function split_lines(code, max_line_length) {
+ var splits = [ 0 ];
+ jsp.parse(function(){
+ var next_token = jsp.tokenizer(code);
+ var last_split = 0;
+ var prev_token;
+ function current_length(tok) {
+ return tok.pos - last_split;
+ };
+ function split_here(tok) {
+ last_split = tok.pos;
+ splits.push(last_split);
+ };
+ function custom(){
+ var tok = next_token.apply(this, arguments);
+ out: {
+ if (prev_token) {
+ if (prev_token.type == "keyword") break out;
+ }
+ if (current_length(tok) > max_line_length) {
+ switch (tok.type) {
+ case "keyword":
+ case "atom":
+ case "name":
+ case "punc":
+ split_here(tok);
+ break out;
+ }
+ }
+ }
+ prev_token = tok;
+ return tok;
+ };
+ custom.context = function() {
+ return next_token.context.apply(this, arguments);
+ };
+ return custom;
+ }());
+ return splits.map(function(pos, i){
+ return code.substring(pos, splits[i + 1] || code.length);
+ }).join("\n");
+};
+
+/* -----[ Utilities ]----- */
+
+function repeat_string(str, i) {
+ if (i <= 0) return "";
+ if (i == 1) return str;
+ var d = repeat_string(str, i >> 1);
+ d += d;
+ if (i & 1) d += str;
+ return d;
+};
+
+function defaults(args, defs) {
+ var ret = {};
+ if (args === true)
+ args = {};
+ for (var i in defs) if (HOP(defs, i)) {
+ ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
+ }
+ return ret;
+};
+
+function is_identifier(name) {
+ return /^[a-z_$][a-z0-9_$]*$/i.test(name)
+ && name != "this"
+ && !HOP(jsp.KEYWORDS_ATOM, name)
+ && !HOP(jsp.RESERVED_WORDS, name)
+ && !HOP(jsp.KEYWORDS, name);
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+// some utilities
+
+var MAP;
+
+(function(){
+ MAP = function(a, f, o) {
+ var ret = [], top = [], i;
+ function doit() {
+ var val = f.call(o, a[i], i);
+ if (val instanceof AtTop) {
+ val = val.v;
+ if (val instanceof Splice) {
+ top.push.apply(top, val.v);
+ } else {
+ top.push(val);
+ }
+ }
+ else if (val != skip) {
+ if (val instanceof Splice) {
+ ret.push.apply(ret, val.v);
+ } else {
+ ret.push(val);
+ }
+ }
+ };
+ if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
+ else for (i in a) if (HOP(a, i)) doit();
+ return top.concat(ret);
+ };
+ MAP.at_top = function(val) { return new AtTop(val) };
+ MAP.splice = function(val) { return new Splice(val) };
+ var skip = MAP.skip = {};
+ function AtTop(val) { this.v = val };
+ function Splice(val) { this.v = val };
+})();
+
+/* -----[ Exports ]----- */
+
+exports.ast_walker = ast_walker;
+exports.ast_mangle = ast_mangle;
+exports.ast_squeeze = ast_squeeze;
+exports.ast_lift_variables = ast_lift_variables;
+exports.gen_code = gen_code;
+exports.ast_add_scope = ast_add_scope;
+exports.set_logger = function(logger) { warn = logger };
+exports.make_string = make_string;
+exports.split_lines = split_lines;
+exports.MAP = MAP;
+
+// keep this last!
+exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
diff --git a/node_modules/uglify-js/lib/squeeze-more.js b/node_modules/uglify-js/lib/squeeze-more.js
new file mode 100644
index 0000000..fbf3733
--- /dev/null
+++ b/node_modules/uglify-js/lib/squeeze-more.js
@@ -0,0 +1,69 @@
+var jsp = require("./parse-js"),
+ pro = require("./process"),
+ slice = jsp.slice,
+ member = jsp.member,
+ curry = jsp.curry,
+ MAP = pro.MAP,
+ PRECEDENCE = jsp.PRECEDENCE,
+ OPERATORS = jsp.OPERATORS;
+
+function ast_squeeze_more(ast) {
+ var w = pro.ast_walker(), walk = w.walk, scope;
+ function with_scope(s, cont) {
+ var save = scope, ret;
+ scope = s;
+ ret = cont();
+ scope = save;
+ return ret;
+ };
+ function _lambda(name, args, body) {
+ return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
+ };
+ return w.with_walkers({
+ "toplevel": function(body) {
+ return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
+ },
+ "function": _lambda,
+ "defun": _lambda,
+ "new": function(ctor, args) {
+ if (ctor[0] == "name") {
+ if (ctor[1] == "Array" && !scope.has("Array")) {
+ if (args.length != 1) {
+ return [ "array", args ];
+ } else {
+ return walk([ "call", [ "name", "Array" ], args ]);
+ }
+ } else if (ctor[1] == "Object" && !scope.has("Object")) {
+ if (!args.length) {
+ return [ "object", [] ];
+ } else {
+ return walk([ "call", [ "name", "Object" ], args ]);
+ }
+ } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
+ return walk([ "call", [ "name", ctor[1] ], args]);
+ }
+ }
+ },
+ "call": function(expr, args) {
+ if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
+ // foo.toString() ==> foo+""
+ return [ "binary", "+", expr[1], [ "string", "" ]];
+ }
+ if (expr[0] == "name") {
+ if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
+ return [ "array", args ];
+ }
+ if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
+ return [ "object", [] ];
+ }
+ if (expr[1] == "String" && !scope.has("String")) {
+ return [ "binary", "+", args[0], [ "string", "" ]];
+ }
+ }
+ }
+ }, function() {
+ return walk(pro.ast_add_scope(ast));
+ });
+};
+
+exports.ast_squeeze_more = ast_squeeze_more;
diff --git a/node_modules/uglify-js/package.json b/node_modules/uglify-js/package.json
new file mode 100644
index 0000000..1c3e52e
--- /dev/null
+++ b/node_modules/uglify-js/package.json
@@ -0,0 +1,24 @@
+{
+ "name" : "uglify-js",
+
+ "description" : "JavaScript parser and compressor/beautifier toolkit",
+
+ "author" : {
+ "name" : "Mihai Bazon",
+ "email" : "mihai.bazon@gmail.com",
+ "url" : "http://mihai.bazon.net/blog"
+ },
+
+ "version" : "1.2.5",
+
+ "main" : "./uglify-js.js",
+
+ "bin" : {
+ "uglifyjs" : "./bin/uglifyjs"
+ },
+
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:mishoo/UglifyJS.git"
+ }
+}
diff --git a/node_modules/uglify-js/package.json~ b/node_modules/uglify-js/package.json~
new file mode 100644
index 0000000..e4cb23d
--- /dev/null
+++ b/node_modules/uglify-js/package.json~
@@ -0,0 +1,24 @@
+{
+ "name" : "uglify-js",
+
+ "description" : "JavaScript parser and compressor/beautifier toolkit",
+
+ "author" : {
+ "name" : "Mihai Bazon",
+ "email" : "mihai.bazon@gmail.com",
+ "url" : "http://mihai.bazon.net/blog"
+ },
+
+ "version" : "1.2.3",
+
+ "main" : "./uglify-js.js",
+
+ "bin" : {
+ "uglifyjs" : "./bin/uglifyjs"
+ },
+
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:mishoo/UglifyJS.git"
+ }
+}
diff --git a/node_modules/uglify-js/test/beautify.js b/node_modules/uglify-js/test/beautify.js
new file mode 100755
index 0000000..f19369e
--- /dev/null
+++ b/node_modules/uglify-js/test/beautify.js
@@ -0,0 +1,28 @@
+#! /usr/bin/env node
+
+global.sys = require("sys");
+var fs = require("fs");
+
+var jsp = require("../lib/parse-js");
+var pro = require("../lib/process");
+
+var filename = process.argv[2];
+fs.readFile(filename, "utf8", function(err, text){
+ try {
+ var ast = time_it("parse", function(){ return jsp.parse(text); });
+ ast = time_it("mangle", function(){ return pro.ast_mangle(ast); });
+ ast = time_it("squeeze", function(){ return pro.ast_squeeze(ast); });
+ var gen = time_it("generate", function(){ return pro.gen_code(ast, false); });
+ sys.puts(gen);
+ } catch(ex) {
+ sys.debug(ex.stack);
+ sys.debug(sys.inspect(ex));
+ sys.debug(JSON.stringify(ex));
+ }
+});
+
+function time_it(name, cont) {
+ var t1 = new Date().getTime();
+ try { return cont(); }
+ finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
+};
diff --git a/node_modules/uglify-js/test/testparser.js b/node_modules/uglify-js/test/testparser.js
new file mode 100755
index 0000000..02c19a9
--- /dev/null
+++ b/node_modules/uglify-js/test/testparser.js
@@ -0,0 +1,403 @@
+#! /usr/bin/env node
+
+var parseJS = require("../lib/parse-js");
+var sys = require("sys");
+
+// write debug in a very straightforward manner
+var debug = function(){
+ sys.log(Array.prototype.slice.call(arguments).join(', '));
+};
+
+ParserTestSuite(function(i, input, desc){
+ try {
+ parseJS.parse(input);
+ debug("ok " + i + ": " + desc);
+ } catch(e){
+ debug("FAIL " + i + " " + desc + " (" + e + ")");
+ }
+});
+
+function ParserTestSuite(callback){
+ var inps = [
+ ["var abc;", "Regular variable statement w/o assignment"],
+ ["var abc = 5;", "Regular variable statement with assignment"],
+ ["/* */;", "Multiline comment"],
+ ['/** **/;', 'Double star multiline comment'],
+ ["var f = function(){;};", "Function expression in var assignment"],
+ ['hi; // moo\n;', 'single line comment'],
+ ['var varwithfunction;', 'Dont match keywords as substrings'], // difference between `var withsomevar` and `"str"` (local search and lits)
+ ['a + b;', 'addition'],
+ ["'a';", 'single string literal'],
+ ["'a\\n';", 'single string literal with escaped return'],
+ ['"a";', 'double string literal'],
+ ['"a\\n";', 'double string literal with escaped return'],
+ ['"var";', 'string is a keyword'],
+ ['"variable";', 'string starts with a keyword'],
+ ['"somevariable";', 'string contains a keyword'],
+ ['"somevar";', 'string ends with a keyword'],
+ ['500;', 'int literal'],
+ ['500.;', 'float literal w/o decimals'],
+ ['500.432;', 'float literal with decimals'],
+ ['.432432;', 'float literal w/o int'],
+ ['(a,b,c);', 'parens and comma'],
+ ['[1,2,abc];', 'array literal'],
+ ['var o = {a:1};', 'object literal unquoted key'],
+ ['var o = {"b":2};', 'object literal quoted key'], // opening curly may not be at the start of a statement...
+ ['var o = {c:c};', 'object literal keyname is identifier'],
+ ['var o = {a:1,"b":2,c:c};', 'object literal combinations'],
+ ['var x;\nvar y;', 'two lines'],
+ ['var x;\nfunction n(){; }', 'function def'],
+ ['var x;\nfunction n(abc){; }', 'function def with arg'],
+ ['var x;\nfunction n(abc, def){ ;}', 'function def with args'],
+ ['function n(){ "hello"; }', 'function def with body'],
+ ['/a/;', 'regex literal'],
+ ['/a/b;', 'regex literal with flag'],
+ ['/a/ / /b/;', 'regex div regex'],
+ ['a/b/c;', 'triple division looks like regex'],
+ ['+function(){/regex/;};', 'regex at start of function body'],
+ // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=86
+ // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=430
+
+ // first tests for the lexer, should also parse as program (when you append a semi)
+
+ // comments
+ ['//foo!@#^&$1234\nbar;', 'single line comment'],
+ ['/* abcd!@#@$* { } && null*/;', 'single line multi line comment'],
+ ['/*foo\nbar*/;','multi line comment'],
+ ['/*x*x*/;','multi line comment with *'],
+ ['/**/;','empty comment'],
+ // identifiers
+ ["x;",'1 identifier'],
+ ["_x;",'2 identifier'],
+ ["xyz;",'3 identifier'],
+ ["$x;",'4 identifier'],
+ ["x$;",'5 identifier'],
+ ["_;",'6 identifier'],
+ ["x5;",'7 identifier'],
+ ["x_y;",'8 identifier'],
+ ["x+5;",'9 identifier'],
+ ["xyz123;",'10 identifier'],
+ ["x1y1z1;",'11 identifier'],
+ ["foo\\u00D8bar;",'12 identifier unicode escape'],
+ //["foo�bar;",'13 identifier unicode embedded (might fail)'],
+ // numbers
+ ["5;", '1 number'],
+ ["5.5;", '2 number'],
+ ["0;", '3 number'],
+ ["0.0;", '4 number'],
+ ["0.001;", '5 number'],
+ ["1.e2;", '6 number'],
+ ["1.e-2;", '7 number'],
+ ["1.E2;", '8 number'],
+ ["1.E-2;", '9 number'],
+ [".5;", '10 number'],
+ [".5e3;", '11 number'],
+ [".5e-3;", '12 number'],
+ ["0.5e3;", '13 number'],
+ ["55;", '14 number'],
+ ["123;", '15 number'],
+ ["55.55;", '16 number'],
+ ["55.55e10;", '17 number'],
+ ["123.456;", '18 number'],
+ ["1+e;", '20 number'],
+ ["0x01;", '22 number'],
+ ["0XCAFE;", '23 number'],
+ ["0x12345678;", '24 number'],
+ ["0x1234ABCD;", '25 number'],
+ ["0x0001;", '26 number'],
+ // strings
+ ["\"foo\";", '1 string'],
+ ["\'foo\';", '2 string'],
+ ["\"x\";", '3 string'],
+ ["\'\';", '4 string'],
+ ["\"foo\\tbar\";", '5 string'],
+ ["\"!@#$%^&*()_+{}[]\";", '6 string'],
+ ["\"/*test*/\";", '7 string'],
+ ["\"//test\";", '8 string'],
+ ["\"\\\\\";", '9 string'],
+ ["\"\\u0001\";", '10 string'],
+ ["\"\\uFEFF\";", '11 string'],
+ ["\"\\u10002\";", '12 string'],
+ ["\"\\x55\";", '13 string'],
+ ["\"\\x55a\";", '14 string'],
+ ["\"a\\\\nb\";", '15 string'],
+ ['";"', '16 string: semi in a string'],
+ ['"a\\\nb";', '17 string: line terminator escape'],
+ // literals
+ ["null;", "null"],
+ ["true;", "true"],
+ ["false;", "false"],
+ // regex
+ ["/a/;", "1 regex"],
+ ["/abc/;", "2 regex"],
+ ["/abc[a-z]*def/g;", "3 regex"],
+ ["/\\b/;", "4 regex"],
+ ["/[a-zA-Z]/;", "5 regex"],
+
+ // program tests (for as far as they havent been covered above)
+
+ // regexp
+ ["/foo(.*)/g;", "another regexp"],
+ // arrays
+ ["[];", "1 array"],
+ ["[ ];", "2 array"],
+ ["[1];", "3 array"],
+ ["[1,2];", "4 array"],
+ ["[1,2,,];", "5 array"],
+ ["[1,2,3];", "6 array"],
+ ["[1,2,3,,,];", "7 array"],
+ // objects
+ ["{};", "1 object"],
+ ["({x:5});", "2 object"],
+ ["({x:5,y:6});", "3 object"],
+ ["({x:5,});", "4 object"],
+ ["({if:5});", "5 object"],
+ ["({ get x() {42;} });", "6 object"],
+ ["({ set y(a) {1;} });", "7 object"],
+ // member expression
+ ["o.m;", "1 member expression"],
+ ["o['m'];", "2 member expression"],
+ ["o['n']['m'];", "3 member expression"],
+ ["o.n.m;", "4 member expression"],
+ ["o.if;", "5 member expression"],
+ // call and invoke expressions
+ ["f();", "1 call/invoke expression"],
+ ["f(x);", "2 call/invoke expression"],
+ ["f(x,y);", "3 call/invoke expression"],
+ ["o.m();", "4 call/invoke expression"],
+ ["o['m'];", "5 call/invoke expression"],
+ ["o.m(x);", "6 call/invoke expression"],
+ ["o['m'](x);", "7 call/invoke expression"],
+ ["o.m(x,y);", "8 call/invoke expression"],
+ ["o['m'](x,y);", "9 call/invoke expression"],
+ ["f(x)(y);", "10 call/invoke expression"],
+ ["f().x;", "11 call/invoke expression"],
+
+ // eval
+ ["eval('x');", "1 eval"],
+ ["(eval)('x');", "2 eval"],
+ ["(1,eval)('x');", "3 eval"],
+ ["eval(x,y);", "4 eval"],
+ // new expression
+ ["new f();", "1 new expression"],
+ ["new o;", "2 new expression"],
+ ["new o.m;", "3 new expression"],
+ ["new o.m(x);", "4 new expression"],
+ ["new o.m(x,y);", "5 new expression"],
+ // prefix/postfix
+ ["++x;", "1 pre/postfix"],
+ ["x++;", "2 pre/postfix"],
+ ["--x;", "3 pre/postfix"],
+ ["x--;", "4 pre/postfix"],
+ ["x ++;", "5 pre/postfix"],
+ ["x /* comment */ ++;", "6 pre/postfix"],
+ ["++ /* comment */ x;", "7 pre/postfix"],
+ // unary operators
+ ["delete x;", "1 unary operator"],
+ ["void x;", "2 unary operator"],
+ ["+ x;", "3 unary operator"],
+ ["-x;", "4 unary operator"],
+ ["~x;", "5 unary operator"],
+ ["!x;", "6 unary operator"],
+ // meh
+ ["new Date++;", "new date ++"],
+ ["+x++;", " + x ++"],
+ // expression expressions
+ ["1 * 2;", "1 expression expressions"],
+ ["1 / 2;", "2 expression expressions"],
+ ["1 % 2;", "3 expression expressions"],
+ ["1 + 2;", "4 expression expressions"],
+ ["1 - 2;", "5 expression expressions"],
+ ["1 << 2;", "6 expression expressions"],
+ ["1 >>> 2;", "7 expression expressions"],
+ ["1 >> 2;", "8 expression expressions"],
+ ["1 * 2 + 3;", "9 expression expressions"],
+ ["(1+2)*3;", "10 expression expressions"],
+ ["1*(2+3);", "11 expression expressions"],
+ ["xy;", "13 expression expressions"],
+ ["x<=y;", "14 expression expressions"],
+ ["x>=y;", "15 expression expressions"],
+ ["x instanceof y;", "16 expression expressions"],
+ ["x in y;", "17 expression expressions"],
+ ["x&y;", "18 expression expressions"],
+ ["x^y;", "19 expression expressions"],
+ ["x|y;", "20 expression expressions"],
+ ["x+y>>= y;", "1 assignment"],
+ ["x <<= y;", "2 assignment"],
+ ["x = y;", "3 assignment"],
+ ["x += y;", "4 assignment"],
+ ["x /= y;", "5 assignment"],
+ // comma
+ ["x, y;", "comma"],
+ // block
+ ["{};", "1 block"],
+ ["{x;};", "2 block"],
+ ["{x;y;};", "3 block"],
+ // vars
+ ["var x;", "1 var"],
+ ["var x,y;", "2 var"],
+ ["var x=1,y=2;", "3 var"],
+ ["var x,y=2;", "4 var"],
+ // empty
+ [";", "1 empty"],
+ ["\n;", "2 empty"],
+ // expression statement
+ ["x;", "1 expression statement"],
+ ["5;", "2 expression statement"],
+ ["1+2;", "3 expression statement"],
+ // if
+ ["if (c) x; else y;", "1 if statement"],
+ ["if (c) x;", "2 if statement"],
+ ["if (c) {} else {};", "3 if statement"],
+ ["if (c1) if (c2) s1; else s2;", "4 if statement"],
+ // while
+ ["do s; while (e);", "1 while statement"],
+ ["do { s; } while (e);", "2 while statement"],
+ ["while (e) s;", "3 while statement"],
+ ["while (e) { s; };", "4 while statement"],
+ // for
+ ["for (;;) ;", "1 for statement"],
+ ["for (;c;x++) x;", "2 for statement"],
+ ["for (i;i> 1;
+var c = 8 >>> 1;
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue34.js b/node_modules/uglify-js/test/unit/compress/test/issue34.js
new file mode 100644
index 0000000..022f7a3
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue34.js
@@ -0,0 +1,3 @@
+var a = {};
+a["this"] = 1;
+a["that"] = 2;
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue4.js b/node_modules/uglify-js/test/unit/compress/test/issue4.js
new file mode 100644
index 0000000..0b76103
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue4.js
@@ -0,0 +1,3 @@
+var a = 2e3;
+var b = 2e-3;
+var c = 2e-5;
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue48.js b/node_modules/uglify-js/test/unit/compress/test/issue48.js
new file mode 100644
index 0000000..031e85b
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue48.js
@@ -0,0 +1 @@
+var s, i; s = ''; i = 0;
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue50.js b/node_modules/uglify-js/test/unit/compress/test/issue50.js
new file mode 100644
index 0000000..060f9df
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue50.js
@@ -0,0 +1,9 @@
+function bar(a) {
+ try {
+ foo();
+ } catch(e) {
+ alert("Exception caught (foo not defined)");
+ }
+ alert(a); // 10 in FF, "[object Error]" in IE
+}
+bar(10);
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue53.js b/node_modules/uglify-js/test/unit/compress/test/issue53.js
new file mode 100644
index 0000000..4f8b32f
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue53.js
@@ -0,0 +1 @@
+x = (y, z)
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue54.1.js b/node_modules/uglify-js/test/unit/compress/test/issue54.1.js
new file mode 100644
index 0000000..967052e
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue54.1.js
@@ -0,0 +1,3 @@
+foo.toString();
+a.toString(16);
+b.toString.call(c);
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue68.js b/node_modules/uglify-js/test/unit/compress/test/issue68.js
new file mode 100644
index 0000000..14054d0
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue68.js
@@ -0,0 +1,5 @@
+function f() {
+ if (a) return;
+ g();
+ function g(){}
+};
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue69.js b/node_modules/uglify-js/test/unit/compress/test/issue69.js
new file mode 100644
index 0000000..d25ecd6
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue69.js
@@ -0,0 +1 @@
+[(a,b)]
diff --git a/node_modules/uglify-js/test/unit/compress/test/issue9.js b/node_modules/uglify-js/test/unit/compress/test/issue9.js
new file mode 100644
index 0000000..6158861
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/issue9.js
@@ -0,0 +1,4 @@
+var a = {
+ a: 1,
+ b: 2, // <-- trailing comma
+};
diff --git a/node_modules/uglify-js/test/unit/compress/test/mangle.js b/node_modules/uglify-js/test/unit/compress/test/mangle.js
new file mode 100644
index 0000000..c271a26
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/mangle.js
@@ -0,0 +1,5 @@
+(function() {
+ var x = function fun(a, fun, b) {
+ return fun;
+ };
+}());
diff --git a/node_modules/uglify-js/test/unit/compress/test/null_string.js b/node_modules/uglify-js/test/unit/compress/test/null_string.js
new file mode 100644
index 0000000..a675b1c
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/null_string.js
@@ -0,0 +1 @@
+var nullString = "\0"
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/strict-equals.js b/node_modules/uglify-js/test/unit/compress/test/strict-equals.js
new file mode 100644
index 0000000..b631f4c
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/strict-equals.js
@@ -0,0 +1,3 @@
+typeof a === 'string'
+b + "" !== c + ""
+d < e === f < g
diff --git a/node_modules/uglify-js/test/unit/compress/test/var.js b/node_modules/uglify-js/test/unit/compress/test/var.js
new file mode 100644
index 0000000..609a35d
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/var.js
@@ -0,0 +1,3 @@
+// var declarations after each other should be combined
+var a = 1;
+var b = 2;
\ No newline at end of file
diff --git a/node_modules/uglify-js/test/unit/compress/test/whitespace.js b/node_modules/uglify-js/test/unit/compress/test/whitespace.js
new file mode 100644
index 0000000..6a15c46
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/whitespace.js
@@ -0,0 +1,21 @@
+function id(a) {
+ // Form-Feed
+ // Vertical Tab
+ // No-Break Space
+ // Mongolian Vowel Separator
+ // En quad
+ // Em quad
+ // En space
+ // Em space
+ // Three-Per-Em Space
+ // Four-Per-Em Space
+ // Six-Per-Em Space
+ // Figure Space
+ // Punctuation Space
+ // Thin Space
+ // Hair Space
+ // Narrow No-Break Space
+ // Medium Mathematical Space
+ // Ideographic Space
+ return a;
+}
diff --git a/node_modules/uglify-js/test/unit/compress/test/with.js b/node_modules/uglify-js/test/unit/compress/test/with.js
new file mode 100644
index 0000000..de266ed
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/compress/test/with.js
@@ -0,0 +1,2 @@
+with({}) {
+};
diff --git a/node_modules/uglify-js/test/unit/scripts.js b/node_modules/uglify-js/test/unit/scripts.js
new file mode 100644
index 0000000..5d334ff
--- /dev/null
+++ b/node_modules/uglify-js/test/unit/scripts.js
@@ -0,0 +1,55 @@
+var fs = require('fs'),
+ uglify = require('../../uglify-js'),
+ jsp = uglify.parser,
+ nodeunit = require('nodeunit'),
+ path = require('path'),
+ pro = uglify.uglify;
+
+var Script = process.binding('evals').Script;
+
+var scriptsPath = __dirname;
+
+function compress(code) {
+ var ast = jsp.parse(code);
+ ast = pro.ast_mangle(ast);
+ ast = pro.ast_squeeze(ast, { no_warnings: true });
+ ast = pro.ast_squeeze_more(ast);
+ return pro.gen_code(ast);
+};
+
+var testDir = path.join(scriptsPath, "compress", "test");
+var expectedDir = path.join(scriptsPath, "compress", "expected");
+
+function getTester(script) {
+ return function(test) {
+ var testPath = path.join(testDir, script);
+ var expectedPath = path.join(expectedDir, script);
+ var content = fs.readFileSync(testPath, 'utf-8');
+ var outputCompress = compress(content);
+
+ // Check if the noncompressdata is larger or same size as the compressed data
+ test.ok(content.length >= outputCompress.length);
+
+ // Check that a recompress gives the same result
+ var outputReCompress = compress(content);
+ test.equal(outputCompress, outputReCompress);
+
+ // Check if the compressed output is what is expected
+ var expected = fs.readFileSync(expectedPath, 'utf-8');
+ test.equal(outputCompress, expected.replace(/(\r?\n)+$/, ""));
+
+ test.done();
+ };
+};
+
+var tests = {};
+
+var scripts = fs.readdirSync(testDir);
+for (var i in scripts) {
+ var script = scripts[i];
+ if (/\.js$/.test(script)) {
+ tests[script] = getTester(script);
+ }
+}
+
+module.exports = nodeunit.testCase(tests);
diff --git a/node_modules/uglify-js/tmp/269.js b/node_modules/uglify-js/tmp/269.js
new file mode 100644
index 0000000..256ad1c
--- /dev/null
+++ b/node_modules/uglify-js/tmp/269.js
@@ -0,0 +1,13 @@
+var jsp = require("uglify-js").parser;
+var pro = require("uglify-js").uglify;
+
+var test_code = "var JSON;JSON||(JSON={});";
+
+var ast = jsp.parse(test_code, false, false);
+var nonembed_token_code = pro.gen_code(ast);
+ast = jsp.parse(test_code, false, true);
+var embed_token_code = pro.gen_code(ast);
+
+console.log("original: " + test_code);
+console.log("no token: " + nonembed_token_code);
+console.log(" token: " + embed_token_code);
diff --git a/node_modules/uglify-js/tmp/app.js b/node_modules/uglify-js/tmp/app.js
new file mode 100644
index 0000000..2c6257e
--- /dev/null
+++ b/node_modules/uglify-js/tmp/app.js
@@ -0,0 +1,22315 @@
+/* Modernizr 2.0.6 (Custom Build) | MIT & BSD
+ * Build: http://www.modernizr.com/download/#-iepp
+ */
+;window.Modernizr=function(a,b,c){function w(a,b){return!!~(""+a).indexOf(b)}function v(a,b){return typeof a===b}function u(a,b){return t(prefixes.join(a+";")+(b||""))}function t(a){j.cssText=a}var d="2.0.6",e={},f=b.documentElement,g=b.head||b.getElementsByTagName("head")[0],h="modernizr",i=b.createElement(h),j=i.style,k,l=Object.prototype.toString,m={},n={},o={},p=[],q,r={}.hasOwnProperty,s;!v(r,c)&&!v(r.call,c)?s=function(a,b){return r.call(a,b)}:s=function(a,b){return b in a&&v(a.constructor.prototype[b],c)};for(var x in m)s(m,x)&&(q=x.toLowerCase(),e[q]=m[x](),p.push((e[q]?"":"no-")+q));t(""),i=k=null,a.attachEvent&&function(){var a=b.createElement("div");a.innerHTML="";return a.childNodes.length!==1}()&&function(a,b){function s(a){var b=-1;while(++b to avoid XSS via location.hash (#9521)
+ quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
+
+ // Check if a string has a non-whitespace character in it
+ rnotwhite = /\S/,
+
+ // Used for trimming whitespace
+ trimLeft = /^\s+/,
+ trimRight = /\s+$/,
+
+ // Check for digits
+ rdigit = /\d/,
+
+ // Match a standalone tag
+ rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+ // JSON RegExp
+ rvalidchars = /^[\],:{}\s]*$/,
+ rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
+ rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
+ rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+
+ // Useragent RegExp
+ rwebkit = /(webkit)[ \/]([\w.]+)/,
+ ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
+ rmsie = /(msie) ([\w.]+)/,
+ rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
+
+ // Matches dashed string for camelizing
+ rdashAlpha = /-([a-z]|[0-9])/ig,
+ rmsPrefix = /^-ms-/,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return ( letter + "" ).toUpperCase();
+ },
+
+ // Keep a UserAgent string for use with jQuery.browser
+ userAgent = navigator.userAgent,
+
+ // For matching the engine and version of the browser
+ browserMatch,
+
+ // The deferred used on DOM ready
+ readyList,
+
+ // The ready event handler
+ DOMContentLoaded,
+
+ // Save a reference to some core methods
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ push = Array.prototype.push,
+ slice = Array.prototype.slice,
+ trim = String.prototype.trim,
+ indexOf = Array.prototype.indexOf,
+
+ // [[Class]] -> type pairs
+ class2type = {};
+
+jQuery.fn = jQuery.prototype = {
+ constructor: jQuery,
+ init: function( selector, context, rootjQuery ) {
+ var match, elem, ret, doc;
+
+ // Handle $(""), $(null), or $(undefined)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // The body element only exists once, optimize finding it
+ if ( selector === "body" && !context && document.body ) {
+ this.context = document;
+ this[0] = document.body;
+ this.selector = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ // Are we dealing with HTML string or an ID?
+ if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = quickExpr.exec( selector );
+ }
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+ doc = (context ? context.ownerDocument || context : document);
+
+ // If a single string is passed in and it's a single tag
+ // just do a createElement and skip the rest
+ ret = rsingleTag.exec( selector );
+
+ if ( ret ) {
+ if ( jQuery.isPlainObject( context ) ) {
+ selector = [ document.createElement( ret[1] ) ];
+ jQuery.fn.attr.call( selector, context, true );
+
+ } else {
+ selector = [ doc.createElement( ret[1] ) ];
+ }
+
+ } else {
+ ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
+ selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
+ }
+
+ return jQuery.merge( this, selector );
+
+ // HANDLE: $("#id")
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[2] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return (context || rootjQuery).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return rootjQuery.ready( selector );
+ }
+
+ if (selector.selector !== undefined) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ },
+
+ // Start with an empty selector
+ selector: "",
+
+ // The current version of jQuery being used
+ jquery: "1.6.3",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ toArray: function() {
+ return slice.call( this, 0 );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num == null ?
+
+ // Return a 'clean' array
+ this.toArray() :
+
+ // Return just the object
+ ( num < 0 ? this[ this.length + num ] : this[ num ] );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems, name, selector ) {
+ // Build a new jQuery matched element set
+ var ret = this.constructor();
+
+ if ( jQuery.isArray( elems ) ) {
+ push.apply( ret, elems );
+
+ } else {
+ jQuery.merge( ret, elems );
+ }
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ ret.context = this.context;
+
+ if ( name === "find" ) {
+ ret.selector = this.selector + (this.selector ? " " : "") + selector;
+ } else if ( name ) {
+ ret.selector = this.selector + "." + name + "(" + selector + ")";
+ }
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ ready: function( fn ) {
+ // Attach the listeners
+ jQuery.bindReady();
+
+ // Add the callback
+ readyList.done( fn );
+
+ return this;
+ },
+
+ eq: function( i ) {
+ return i === -1 ?
+ this.slice( i ) :
+ this.slice( i, +i + 1 );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ),
+ "slice", slice.call(arguments).join(",") );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // extend jQuery itself if only one argument is passed
+ if ( length === i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+ },
+
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+ // Either a released hold or an DOMready/load event and not yet ready
+ if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( !document.body ) {
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
+ }
+ }
+ },
+
+ bindReady: function() {
+ if ( readyList ) {
+ return;
+ }
+
+ readyList = jQuery._Deferred();
+
+ // Catch cases where $(document).ready() is called after the
+ // browser event has already occurred.
+ if ( document.readyState === "complete" ) {
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Mozilla, Opera and webkit nightlies currently support this event
+ if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", jQuery.ready, false );
+
+ // If IE event model is used
+ } else if ( document.attachEvent ) {
+ // ensure firing before onload,
+ // maybe late but safe also for iframes
+ document.attachEvent( "onreadystatechange", DOMContentLoaded );
+
+ // A fallback to window.onload, that will always work
+ window.attachEvent( "onload", jQuery.ready );
+
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var toplevel = false;
+
+ try {
+ toplevel = window.frameElement == null;
+ } catch(e) {}
+
+ if ( document.documentElement.doScroll && toplevel ) {
+ doScrollCheck();
+ }
+ }
+ },
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray || function( obj ) {
+ return jQuery.type(obj) === "array";
+ },
+
+ // A crude way of determining if an object is a window
+ isWindow: function( obj ) {
+ return obj && typeof obj === "object" && "setInterval" in obj;
+ },
+
+ isNaN: function( obj ) {
+ return obj == null || !rdigit.test( obj ) || isNaN( obj );
+ },
+
+ type: function( obj ) {
+ return obj == null ?
+ String( obj ) :
+ class2type[ toString.call(obj) ] || "object";
+ },
+
+ isPlainObject: function( obj ) {
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ try {
+ // Not own constructor property must be Object
+ if ( obj.constructor &&
+ !hasOwn.call(obj, "constructor") &&
+ !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+ return false;
+ }
+ } catch ( e ) {
+ // IE8,9 Will throw exceptions on certain host objects #9897
+ return false;
+ }
+
+ // Own properties are enumerated firstly, so to speed up,
+ // if last one is own, then all properties are own.
+
+ var key;
+ for ( key in obj ) {}
+
+ return key === undefined || hasOwn.call( obj, key );
+ },
+
+ isEmptyObject: function( obj ) {
+ for ( var name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ error: function( msg ) {
+ throw msg;
+ },
+
+ parseJSON: function( data ) {
+ if ( typeof data !== "string" || !data ) {
+ return null;
+ }
+
+ // Make sure leading/trailing whitespace is removed (IE can't handle it)
+ data = jQuery.trim( data );
+
+ // Attempt to parse using the native JSON parser first
+ if ( window.JSON && window.JSON.parse ) {
+ return window.JSON.parse( data );
+ }
+
+ // Make sure the incoming data is actual JSON
+ // Logic borrowed from http://json.org/json2.js
+ if ( rvalidchars.test( data.replace( rvalidescape, "@" )
+ .replace( rvalidtokens, "]" )
+ .replace( rvalidbraces, "")) ) {
+
+ return (new Function( "return " + data ))();
+
+ }
+ jQuery.error( "Invalid JSON: " + data );
+ },
+
+ // Cross-browser xml parsing
+ parseXML: function( data ) {
+ var xml, tmp;
+ try {
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data , "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+ } catch( e ) {
+ xml = undefined;
+ }
+ if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+ return xml;
+ },
+
+ noop: function() {},
+
+ // Evaluates a script in a global context
+ // Workarounds based on findings by Jim Driscoll
+ // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+ globalEval: function( data ) {
+ if ( data && rnotwhite.test( data ) ) {
+ // We use execScript on Internet Explorer
+ // We use an anonymous function so that context is window
+ // rather than jQuery in Firefox
+ ( window.execScript || function( data ) {
+ window[ "eval" ].call( window, data );
+ } )( data );
+ }
+ },
+
+ // Convert dashed to camelCase; used by the css and data modules
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0,
+ length = object.length,
+ isObj = length === undefined || jQuery.isFunction( object );
+
+ if ( args ) {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.apply( object[ name ], args ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.apply( object[ i++ ], args ) === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return object;
+ },
+
+ // Use native String.trim function wherever possible
+ trim: trim ?
+ function( text ) {
+ return text == null ?
+ "" :
+ trim.call( text );
+ } :
+
+ // Otherwise use our own trimming functionality
+ function( text ) {
+ return text == null ?
+ "" :
+ text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( array, results ) {
+ var ret = results || [];
+
+ if ( array != null ) {
+ // The window, strings (and functions) also have 'length'
+ // The extra typeof function check is to prevent crashes
+ // in Safari 2 (See: #3039)
+ // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
+ var type = jQuery.type( array );
+
+ if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
+ push.call( ret, array );
+ } else {
+ jQuery.merge( ret, array );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ if ( !array ) {
+ return -1;
+ }
+
+ if ( indexOf ) {
+ return indexOf.call( array, elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ var i = first.length,
+ j = 0;
+
+ if ( typeof second.length === "number" ) {
+ for ( var l = second.length; j < l; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ } else {
+ while ( second[j] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [], retVal;
+ inv = !!inv;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ retVal = !!callback( elems[ i ], i );
+ if ( inv !== retVal ) {
+ ret.push( elems[ i ] );
+ }
+ }
+
+ return ret;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var value, key, ret = [],
+ i = 0,
+ length = elems.length,
+ // jquery objects are treated as arrays
+ isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
+
+ // Go through the array, translating each of the items to their
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( key in elems ) {
+ value = callback( elems[ key ], key, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return ret.concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ if ( typeof context === "string" ) {
+ var tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !jQuery.isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ var args = slice.call( arguments, 2 ),
+ proxy = function() {
+ return fn.apply( context, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ // Mutifunctional method to get and set values to a collection
+ // The value/s can optionally be executed if it's a function
+ access: function( elems, key, value, exec, fn, pass ) {
+ var length = elems.length;
+
+ // Setting many attributes
+ if ( typeof key === "object" ) {
+ for ( var k in key ) {
+ jQuery.access( elems, k, key[k], exec, fn, value );
+ }
+ return elems;
+ }
+
+ // Setting one attribute
+ if ( value !== undefined ) {
+ // Optionally, function values get executed if exec is true
+ exec = !pass && exec && jQuery.isFunction(value);
+
+ for ( var i = 0; i < length; i++ ) {
+ fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
+ }
+
+ return elems;
+ }
+
+ // Getting an attribute
+ return length ? fn( elems[0], key ) : undefined;
+ },
+
+ now: function() {
+ return (new Date()).getTime();
+ },
+
+ // Use of jQuery.browser is frowned upon.
+ // More details: http://docs.jquery.com/Utilities/jQuery.browser
+ uaMatch: function( ua ) {
+ ua = ua.toLowerCase();
+
+ var match = rwebkit.exec( ua ) ||
+ ropera.exec( ua ) ||
+ rmsie.exec( ua ) ||
+ ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
+ [];
+
+ return { browser: match[1] || "", version: match[2] || "0" };
+ },
+
+ sub: function() {
+ function jQuerySub( selector, context ) {
+ return new jQuerySub.fn.init( selector, context );
+ }
+ jQuery.extend( true, jQuerySub, this );
+ jQuerySub.superclass = this;
+ jQuerySub.fn = jQuerySub.prototype = this();
+ jQuerySub.fn.constructor = jQuerySub;
+ jQuerySub.sub = this.sub;
+ jQuerySub.fn.init = function init( selector, context ) {
+ if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
+ context = jQuerySub( context );
+ }
+
+ return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
+ };
+ jQuerySub.fn.init.prototype = jQuerySub.fn;
+ var rootjQuerySub = jQuerySub(document);
+ return jQuerySub;
+ },
+
+ browser: {}
+});
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+browserMatch = jQuery.uaMatch( userAgent );
+if ( browserMatch.browser ) {
+ jQuery.browser[ browserMatch.browser ] = true;
+ jQuery.browser.version = browserMatch.version;
+}
+
+// Deprecated, use jQuery.browser.webkit instead
+if ( jQuery.browser.webkit ) {
+ jQuery.browser.safari = true;
+}
+
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
+ trimLeft = /^[\s\xA0]+/;
+ trimRight = /[\s\xA0]+$/;
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+
+// Cleanup functions for the document ready method
+if ( document.addEventListener ) {
+ DOMContentLoaded = function() {
+ document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+ jQuery.ready();
+ };
+
+} else if ( document.attachEvent ) {
+ DOMContentLoaded = function() {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( document.readyState === "complete" ) {
+ document.detachEvent( "onreadystatechange", DOMContentLoaded );
+ jQuery.ready();
+ }
+ };
+}
+
+// The DOM ready check for Internet Explorer
+function doScrollCheck() {
+ if ( jQuery.isReady ) {
+ return;
+ }
+
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch(e) {
+ setTimeout( doScrollCheck, 1 );
+ return;
+ }
+
+ // and execute any waiting functions
+ jQuery.ready();
+}
+
+return jQuery;
+
+})();
+
+
+var // Promise methods
+ promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
+ // Static reference to slice
+ sliceDeferred = [].slice;
+
+jQuery.extend({
+ // Create a simple deferred (one callbacks list)
+ _Deferred: function() {
+ var // callbacks list
+ callbacks = [],
+ // stored [ context , args ]
+ fired,
+ // to avoid firing when already doing so
+ firing,
+ // flag to know if the deferred has been cancelled
+ cancelled,
+ // the deferred itself
+ deferred = {
+
+ // done( f1, f2, ...)
+ done: function() {
+ if ( !cancelled ) {
+ var args = arguments,
+ i,
+ length,
+ elem,
+ type,
+ _fired;
+ if ( fired ) {
+ _fired = fired;
+ fired = 0;
+ }
+ for ( i = 0, length = args.length; i < length; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
+ if ( type === "array" ) {
+ deferred.done.apply( deferred, elem );
+ } else if ( type === "function" ) {
+ callbacks.push( elem );
+ }
+ }
+ if ( _fired ) {
+ deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+ }
+ }
+ return this;
+ },
+
+ // resolve with given context and args
+ resolveWith: function( context, args ) {
+ if ( !cancelled && !fired && !firing ) {
+ // make sure args are available (#8421)
+ args = args || [];
+ firing = 1;
+ try {
+ while( callbacks[ 0 ] ) {
+ callbacks.shift().apply( context, args );
+ }
+ }
+ finally {
+ fired = [ context, args ];
+ firing = 0;
+ }
+ }
+ return this;
+ },
+
+ // resolve with this as context and given arguments
+ resolve: function() {
+ deferred.resolveWith( this, arguments );
+ return this;
+ },
+
+ // Has this deferred been resolved?
+ isResolved: function() {
+ return !!( firing || fired );
+ },
+
+ // Cancel
+ cancel: function() {
+ cancelled = 1;
+ callbacks = [];
+ return this;
+ }
+ };
+
+ return deferred;
+ },
+
+ // Full fledged deferred (two callbacks list)
+ Deferred: function( func ) {
+ var deferred = jQuery._Deferred(),
+ failDeferred = jQuery._Deferred(),
+ promise;
+ // Add errorDeferred methods, then and promise
+ jQuery.extend( deferred, {
+ then: function( doneCallbacks, failCallbacks ) {
+ deferred.done( doneCallbacks ).fail( failCallbacks );
+ return this;
+ },
+ always: function() {
+ return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
+ },
+ fail: failDeferred.done,
+ rejectWith: failDeferred.resolveWith,
+ reject: failDeferred.resolve,
+ isRejected: failDeferred.isResolved,
+ pipe: function( fnDone, fnFail ) {
+ return jQuery.Deferred(function( newDefer ) {
+ jQuery.each( {
+ done: [ fnDone, "resolve" ],
+ fail: [ fnFail, "reject" ]
+ }, function( handler, data ) {
+ var fn = data[ 0 ],
+ action = data[ 1 ],
+ returned;
+ if ( jQuery.isFunction( fn ) ) {
+ deferred[ handler ](function() {
+ returned = fn.apply( this, arguments );
+ if ( returned && jQuery.isFunction( returned.promise ) ) {
+ returned.promise().then( newDefer.resolve, newDefer.reject );
+ } else {
+ newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
+ }
+ });
+ } else {
+ deferred[ handler ]( newDefer[ action ] );
+ }
+ });
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ if ( obj == null ) {
+ if ( promise ) {
+ return promise;
+ }
+ promise = obj = {};
+ }
+ var i = promiseMethods.length;
+ while( i-- ) {
+ obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
+ }
+ return obj;
+ }
+ });
+ // Make sure only one callback list will be used
+ deferred.done( failDeferred.cancel ).fail( deferred.cancel );
+ // Unexpose cancel
+ delete deferred.cancel;
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( firstParam ) {
+ var args = arguments,
+ i = 0,
+ length = args.length,
+ count = length,
+ deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
+ firstParam :
+ jQuery.Deferred();
+ function resolveFunc( i ) {
+ return function( value ) {
+ args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
+ if ( !( --count ) ) {
+ // Strange bug in FF4:
+ // Values changed onto the arguments object sometimes end up as undefined values
+ // outside the $.when method. Cloning the object into a fresh array solves the issue
+ deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
+ }
+ };
+ }
+ if ( length > 1 ) {
+ for( ; i < length; i++ ) {
+ if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
+ args[ i ].promise().then( resolveFunc(i), deferred.reject );
+ } else {
+ --count;
+ }
+ }
+ if ( !count ) {
+ deferred.resolveWith( deferred, args );
+ }
+ } else if ( deferred !== firstParam ) {
+ deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
+ }
+ return deferred.promise();
+ }
+});
+
+
+
+jQuery.support = (function() {
+
+ var div = document.createElement( "div" ),
+ documentElement = document.documentElement,
+ all,
+ a,
+ select,
+ opt,
+ input,
+ marginDiv,
+ support,
+ fragment,
+ body,
+ testElementParent,
+ testElement,
+ testElementStyle,
+ tds,
+ events,
+ eventName,
+ i,
+ isSupported;
+
+ // Preliminary tests
+ div.setAttribute("className", "t");
+ div.innerHTML = "
a";
+
+
+ all = div.getElementsByTagName( "*" );
+ a = div.getElementsByTagName( "a" )[ 0 ];
+
+ // Can't get basic test support
+ if ( !all || !all.length || !a ) {
+ return {};
+ }
+
+ // First batch of supports tests
+ select = document.createElement( "select" );
+ opt = select.appendChild( document.createElement("option") );
+ input = div.getElementsByTagName( "input" )[ 0 ];
+
+ support = {
+ // IE strips leading whitespace when .innerHTML is used
+ leadingWhitespace: ( div.firstChild.nodeType === 3 ),
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ tbody: !div.getElementsByTagName( "tbody" ).length,
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ htmlSerialize: !!div.getElementsByTagName( "link" ).length,
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText instead)
+ style: /top/.test( a.getAttribute("style") ),
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
+
+ // Make sure that element opacity exists
+ // (IE uses filter instead)
+ // Use a regex to work around a WebKit issue. See #5145
+ opacity: /^0.55$/.test( a.style.opacity ),
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ cssFloat: !!a.style.cssFloat,
+
+ // Make sure that if no value is specified for a checkbox
+ // that it defaults to "on".
+ // (WebKit defaults to "" instead)
+ checkOn: ( input.value === "on" ),
+
+ // Make sure that a selected-by-default option has a working selected property.
+ // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+ optSelected: opt.selected,
+
+ // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+ getSetAttribute: div.className !== "t",
+
+ // Will be defined later
+ submitBubbles: true,
+ changeBubbles: true,
+ focusinBubbles: false,
+ deleteExpando: true,
+ noCloneEvent: true,
+ inlineBlockNeedsLayout: false,
+ shrinkWrapBlocks: false,
+ reliableMarginRight: true
+ };
+
+ // Make sure checked status is properly cloned
+ input.checked = true;
+ support.noCloneChecked = input.cloneNode( true ).checked;
+
+ // Make sure that the options inside disabled selects aren't marked as disabled
+ // (WebKit marks them as disabled)
+ select.disabled = true;
+ support.optDisabled = !opt.disabled;
+
+ // Test to see if it's possible to delete an expando from an element
+ // Fails in Internet Explorer
+ try {
+ delete div.test;
+ } catch( e ) {
+ support.deleteExpando = false;
+ }
+
+ if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
+ div.attachEvent( "onclick", function() {
+ // Cloning a node shouldn't copy over any
+ // bound event handlers (IE does this)
+ support.noCloneEvent = false;
+ });
+ div.cloneNode( true ).fireEvent( "onclick" );
+ }
+
+ // Check if a radio maintains it's value
+ // after being appended to the DOM
+ input = document.createElement("input");
+ input.value = "t";
+ input.setAttribute("type", "radio");
+ support.radioValue = input.value === "t";
+
+ input.setAttribute("checked", "checked");
+ div.appendChild( input );
+ fragment = document.createDocumentFragment();
+ fragment.appendChild( div.firstChild );
+
+ // WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ div.innerHTML = "";
+
+ // Figure out if the W3C box model works as expected
+ div.style.width = div.style.paddingLeft = "1px";
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ // We use our own, invisible, body unless the body is already present
+ // in which case we use a div (#9239)
+ testElement = document.createElement( body ? "div" : "body" );
+ testElementStyle = {
+ visibility: "hidden",
+ width: 0,
+ height: 0,
+ border: 0,
+ margin: 0,
+ background: "none"
+ };
+ if ( body ) {
+ jQuery.extend( testElementStyle, {
+ position: "absolute",
+ left: "-1000px",
+ top: "-1000px"
+ });
+ }
+ for ( i in testElementStyle ) {
+ testElement.style[ i ] = testElementStyle[ i ];
+ }
+ testElement.appendChild( div );
+ testElementParent = body || documentElement;
+ testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+ // Check if a disconnected checkbox will retain its checked
+ // value of true after appended to the DOM (IE6/7)
+ support.appendChecked = input.checked;
+
+ support.boxModel = div.offsetWidth === 2;
+
+ if ( "zoom" in div.style ) {
+ // Check if natively block-level elements act like inline-block
+ // elements when setting their display to 'inline' and giving
+ // them layout
+ // (IE < 8 does this)
+ div.style.display = "inline";
+ div.style.zoom = 1;
+ support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
+
+ // Check if elements with layout shrink-wrap their children
+ // (IE 6 does this)
+ div.style.display = "";
+ div.innerHTML = "";
+ support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
+ }
+
+ div.innerHTML = "
t
";
+ tds = div.getElementsByTagName( "td" );
+
+ // Check if table cells still have offsetWidth/Height when they are set
+ // to display:none and there are still other visible table cells in a
+ // table row; if so, offsetWidth/Height are not reliable for use when
+ // determining if an element has been hidden directly using
+ // display:none (it is still safe to use offsets if a parent element is
+ // hidden; don safety goggles and see bug #4512 for more information).
+ // (only IE 8 fails this test)
+ isSupported = ( tds[ 0 ].offsetHeight === 0 );
+
+ tds[ 0 ].style.display = "";
+ tds[ 1 ].style.display = "none";
+
+ // Check if empty table cells still have offsetWidth/Height
+ // (IE < 8 fail this test)
+ support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
+ div.innerHTML = "";
+
+ // Check if div with explicit width and no margin-right incorrectly
+ // gets computed margin-right based on width of container. For more
+ // info see bug #3333
+ // Fails in WebKit before Feb 2011 nightlies
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ if ( document.defaultView && document.defaultView.getComputedStyle ) {
+ marginDiv = document.createElement( "div" );
+ marginDiv.style.width = "0";
+ marginDiv.style.marginRight = "0";
+ div.appendChild( marginDiv );
+ support.reliableMarginRight =
+ ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
+ }
+
+ // Remove the body element we added
+ testElement.innerHTML = "";
+ testElementParent.removeChild( testElement );
+
+ // Technique from Juriy Zaytsev
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+ // We only care about the case where non-standard event systems
+ // are used, namely in IE. Short-circuiting here helps us to
+ // avoid an eval call (in setAttribute) which can cause CSP
+ // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+ if ( div.attachEvent ) {
+ for( i in {
+ submit: 1,
+ change: 1,
+ focusin: 1
+ } ) {
+ eventName = "on" + i;
+ isSupported = ( eventName in div );
+ if ( !isSupported ) {
+ div.setAttribute( eventName, "return;" );
+ isSupported = ( typeof div[ eventName ] === "function" );
+ }
+ support[ i + "Bubbles" ] = isSupported;
+ }
+ }
+
+ // Null connected elements to avoid leaks in IE
+ testElement = fragment = select = opt = body = marginDiv = div = input = null;
+
+ return support;
+})();
+
+// Keep track of boxModel
+jQuery.boxModel = jQuery.support.boxModel;
+
+
+
+
+var rbrace = /^(?:\{.*\}|\[.*\])$/,
+ rmultiDash = /([a-z])([A-Z])/g;
+
+jQuery.extend({
+ cache: {},
+
+ // Please use with caution
+ uuid: 0,
+
+ // Unique for each copy of jQuery on the page
+ // Non-digits removed to match rinlinejQuery
+ expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
+
+ // The following elements throw uncatchable exceptions if you
+ // attempt to add expando properties to them.
+ noData: {
+ "embed": true,
+ // Ban all objects except for Flash (which handle expandos)
+ "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
+ "applet": true
+ },
+
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+ return !!elem && !isEmptyDataObject( elem );
+ },
+
+ data: function( elem, name, data, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var thisCache, ret,
+ internalKey = jQuery.expando,
+ getByName = typeof name === "string",
+
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
+
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) {
+ return;
+ }
+
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ } else {
+ id = jQuery.expando;
+ }
+ }
+
+ if ( !cache[ id ] ) {
+ cache[ id ] = {};
+
+ // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+ // metadata on plain JS objects when the object is serialized using
+ // JSON.stringify
+ if ( !isNode ) {
+ cache[ id ].toJSON = jQuery.noop;
+ }
+ }
+
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
+ if ( typeof name === "object" || typeof name === "function" ) {
+ if ( pvt ) {
+ cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+ } else {
+ cache[ id ] = jQuery.extend(cache[ id ], name);
+ }
+ }
+
+ thisCache = cache[ id ];
+
+ // Internal jQuery data is stored in a separate object inside the object's data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data
+ if ( pvt ) {
+ if ( !thisCache[ internalKey ] ) {
+ thisCache[ internalKey ] = {};
+ }
+
+ thisCache = thisCache[ internalKey ];
+ }
+
+ if ( data !== undefined ) {
+ thisCache[ jQuery.camelCase( name ) ] = data;
+ }
+
+ // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+ // not attempt to inspect the internal events object using jQuery.data, as this
+ // internal data object is undocumented and subject to change.
+ if ( name === "events" && !thisCache[name] ) {
+ return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+ }
+
+ // Check for both converted-to-camel and non-converted data property names
+ // If a data property was specified
+ if ( getByName ) {
+
+ // First Try to find as-is property data
+ ret = thisCache[ name ];
+
+ // Test for null|undefined property data
+ if ( ret == null ) {
+
+ // Try to find the camelCased property
+ ret = thisCache[ jQuery.camelCase( name ) ];
+ }
+ } else {
+ ret = thisCache;
+ }
+
+ return ret;
+ },
+
+ removeData: function( elem, name, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var thisCache,
+
+ // Reference to internal data cache key
+ internalKey = jQuery.expando,
+
+ isNode = elem.nodeType,
+
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+
+ // See jQuery.data for more information
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
+
+ if ( name ) {
+
+ thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
+ if ( thisCache ) {
+
+ // Support interoperable removal of hyphenated or camelcased keys
+ if ( !thisCache[ name ] ) {
+ name = jQuery.camelCase( name );
+ }
+
+ delete thisCache[ name ];
+
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( !isEmptyDataObject(thisCache) ) {
+ return;
+ }
+ }
+ }
+
+ // See jQuery.data for more information
+ if ( pvt ) {
+ delete cache[ id ][ internalKey ];
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !isEmptyDataObject(cache[ id ]) ) {
+ return;
+ }
+ }
+
+ var internalCache = cache[ id ][ internalKey ];
+
+ // Browsers that fail expando deletion also refuse to delete expandos on
+ // the window, but it will allow it on all other JS objects; other browsers
+ // don't care
+ // Ensure that `cache` is not a window object #10080
+ if ( jQuery.support.deleteExpando || !cache.setInterval ) {
+ delete cache[ id ];
+ } else {
+ cache[ id ] = null;
+ }
+
+ // We destroyed the entire user cache at once because it's faster than
+ // iterating through each key, but we need to continue to persist internal
+ // data if it existed
+ if ( internalCache ) {
+ cache[ id ] = {};
+ // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+ // metadata on plain JS objects when the object is serialized using
+ // JSON.stringify
+ if ( !isNode ) {
+ cache[ id ].toJSON = jQuery.noop;
+ }
+
+ cache[ id ][ internalKey ] = internalCache;
+
+ // Otherwise, we need to eliminate the expando on the node to avoid
+ // false lookups in the cache for entries that no longer exist
+ } else if ( isNode ) {
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( jQuery.support.deleteExpando ) {
+ delete elem[ jQuery.expando ];
+ } else if ( elem.removeAttribute ) {
+ elem.removeAttribute( jQuery.expando );
+ } else {
+ elem[ jQuery.expando ] = null;
+ }
+ }
+ },
+
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return jQuery.data( elem, name, data, true );
+ },
+
+ // A method for determining if a DOM node can handle the data expando
+ acceptData: function( elem ) {
+ if ( elem.nodeName ) {
+ var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+ if ( match ) {
+ return !(match === true || elem.getAttribute("classid") !== match);
+ }
+ }
+
+ return true;
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ var data = null;
+
+ if ( typeof key === "undefined" ) {
+ if ( this.length ) {
+ data = jQuery.data( this[0] );
+
+ if ( this[0].nodeType === 1 ) {
+ var attr = this[0].attributes, name;
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
+
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = jQuery.camelCase( name.substring(5) );
+
+ dataAttr( this[0], name, data[ name ] );
+ }
+ }
+ }
+ }
+
+ return data;
+
+ } else if ( typeof key === "object" ) {
+ return this.each(function() {
+ jQuery.data( this, key );
+ });
+ }
+
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ // Try to fetch any internally stored data first
+ if ( data === undefined && this.length ) {
+ data = jQuery.data( this[0], key );
+ data = dataAttr( this[0], key, data );
+ }
+
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+
+ } else {
+ return this.each(function() {
+ var $this = jQuery( this ),
+ args = [ parts[0], value ];
+
+ $this.triggerHandler( "setData" + parts[1] + "!", args );
+ jQuery.data( this, key, value );
+ $this.triggerHandler( "changeData" + parts[1] + "!", args );
+ });
+ }
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ jQuery.removeData( this, key );
+ });
+ }
+});
+
+function dataAttr( elem, key, data ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
+
+ data = elem.getAttribute( name );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ !jQuery.isNaN( data ) ? parseFloat( data ) :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
+
+ } else {
+ data = undefined;
+ }
+ }
+
+ return data;
+}
+
+// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
+// property to be considered empty objects; this property always exists in
+// order to make sure JSON.stringify does not expose internal metadata
+function isEmptyDataObject( obj ) {
+ for ( var name in obj ) {
+ if ( name !== "toJSON" ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+
+
+
+function handleQueueMarkDefer( elem, type, src ) {
+ var deferDataKey = type + "defer",
+ queueDataKey = type + "queue",
+ markDataKey = type + "mark",
+ defer = jQuery.data( elem, deferDataKey, undefined, true );
+ if ( defer &&
+ ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
+ ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
+ // Give room for hard-coded callbacks to fire first
+ // and eventually mark/queue something else on the element
+ setTimeout( function() {
+ if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
+ !jQuery.data( elem, markDataKey, undefined, true ) ) {
+ jQuery.removeData( elem, deferDataKey, true );
+ defer.resolve();
+ }
+ }, 0 );
+ }
+}
+
+jQuery.extend({
+
+ _mark: function( elem, type ) {
+ if ( elem ) {
+ type = (type || "fx") + "mark";
+ jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
+ }
+ },
+
+ _unmark: function( force, elem, type ) {
+ if ( force !== true ) {
+ type = elem;
+ elem = force;
+ force = false;
+ }
+ if ( elem ) {
+ type = type || "fx";
+ var key = type + "mark",
+ count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
+ if ( count ) {
+ jQuery.data( elem, key, count, true );
+ } else {
+ jQuery.removeData( elem, key, true );
+ handleQueueMarkDefer( elem, type, "mark" );
+ }
+ }
+ },
+
+ queue: function( elem, type, data ) {
+ if ( elem ) {
+ type = (type || "fx") + "queue";
+ var q = jQuery.data( elem, type, undefined, true );
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !q || jQuery.isArray(data) ) {
+ q = jQuery.data( elem, type, jQuery.makeArray(data), true );
+ } else {
+ q.push( data );
+ }
+ }
+ return q || [];
+ }
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ fn = queue.shift(),
+ defer;
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ }
+
+ if ( fn ) {
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift("inprogress");
+ }
+
+ fn.call(elem, function() {
+ jQuery.dequeue(elem, type);
+ });
+ }
+
+ if ( !queue.length ) {
+ jQuery.removeData( elem, type + "queue", true );
+ handleQueueMarkDefer( elem, type, "queue" );
+ }
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ }
+
+ if ( data === undefined ) {
+ return jQuery.queue( this[0], type );
+ }
+ return this.each(function() {
+ var queue = jQuery.queue( this, type, data );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+ // Based off of the plugin by Clint Helfers, with permission.
+ // http://blindsignals.com/index.php/2009/07/jquery-delay/
+ delay: function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function() {
+ var elem = this;
+ setTimeout(function() {
+ jQuery.dequeue( elem, type );
+ }, time );
+ });
+ },
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ },
+ // Get a promise resolved when queues of a certain type
+ // are emptied (fx is the type by default)
+ promise: function( type, object ) {
+ if ( typeof type !== "string" ) {
+ object = type;
+ type = undefined;
+ }
+ type = type || "fx";
+ var defer = jQuery.Deferred(),
+ elements = this,
+ i = elements.length,
+ count = 1,
+ deferDataKey = type + "defer",
+ queueDataKey = type + "queue",
+ markDataKey = type + "mark",
+ tmp;
+ function resolve() {
+ if ( !( --count ) ) {
+ defer.resolveWith( elements, [ elements ] );
+ }
+ }
+ while( i-- ) {
+ if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
+ ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
+ jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
+ jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
+ count++;
+ tmp.done( resolve );
+ }
+ }
+ resolve();
+ return defer.promise();
+ }
+});
+
+
+
+
+var rclass = /[\n\t\r]/g,
+ rspace = /\s+/,
+ rreturn = /\r/g,
+ rtype = /^(?:button|input)$/i,
+ rfocusable = /^(?:button|input|object|select|textarea)$/i,
+ rclickable = /^a(?:rea)?$/i,
+ rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
+ nodeHook, boolHook;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return jQuery.access( this, name, value, true, jQuery.attr );
+ },
+
+ removeAttr: function( name ) {
+ return this.each(function() {
+ jQuery.removeAttr( this, name );
+ });
+ },
+
+ prop: function( name, value ) {
+ return jQuery.access( this, name, value, true, jQuery.prop );
+ },
+
+ removeProp: function( name ) {
+ name = jQuery.propFix[ name ] || name;
+ return this.each(function() {
+ // try/catch handles cases where IE balks (such as removing a property on window)
+ try {
+ this[ name ] = undefined;
+ delete this[ name ];
+ } catch( e ) {}
+ });
+ },
+
+ addClass: function( value ) {
+ var classNames, i, l, elem,
+ setClass, c, cl;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).addClass( value.call(this, j, this.className) );
+ });
+ }
+
+ if ( value && typeof value === "string" ) {
+ classNames = value.split( rspace );
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ elem = this[ i ];
+
+ if ( elem.nodeType === 1 ) {
+ if ( !elem.className && classNames.length === 1 ) {
+ elem.className = value;
+
+ } else {
+ setClass = " " + elem.className + " ";
+
+ for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+ if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
+ setClass += classNames[ c ] + " ";
+ }
+ }
+ elem.className = jQuery.trim( setClass );
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classNames, i, l, elem, className, c, cl;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).removeClass( value.call(this, j, this.className) );
+ });
+ }
+
+ if ( (value && typeof value === "string") || value === undefined ) {
+ classNames = (value || "").split( rspace );
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ elem = this[ i ];
+
+ if ( elem.nodeType === 1 && elem.className ) {
+ if ( value ) {
+ className = (" " + elem.className + " ").replace( rclass, " " );
+ for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+ className = className.replace(" " + classNames[ c ] + " ", " ");
+ }
+ elem.className = jQuery.trim( className );
+
+ } else {
+ elem.className = "";
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value,
+ isBool = typeof stateVal === "boolean";
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // toggle individual class names
+ var className,
+ i = 0,
+ self = jQuery( this ),
+ state = stateVal,
+ classNames = value.split( rspace );
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space seperated list
+ state = isBool ? state : !self.hasClass( className );
+ self[ state ? "addClass" : "removeClass" ]( className );
+ }
+
+ } else if ( type === "undefined" || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ jQuery._data( this, "__className__", this.className );
+ }
+
+ // toggle whole className
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ";
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ val: function( value ) {
+ var hooks, ret,
+ elem = this[0];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
+
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ return typeof ret === "string" ?
+ // handle most common string cases
+ ret.replace(rreturn, "") :
+ // handle cases where value is null/undef or number
+ ret == null ? "" : ret;
+ }
+
+ return undefined;
+ }
+
+ var isFunction = jQuery.isFunction( value );
+
+ return this.each(function( i ) {
+ var self = jQuery(this), val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call( this, i, self.val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+ } else if ( typeof val === "number" ) {
+ val += "";
+ } else if ( jQuery.isArray( val ) ) {
+ val = jQuery.map(val, function ( value ) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ valHooks: {
+ option: {
+ get: function( elem ) {
+ // attributes.value is undefined in Blackberry 4.7 but
+ // uses .value. See #6932
+ var val = elem.attributes.value;
+ return !val || val.specified ? elem.value : elem.text;
+ }
+ },
+ select: {
+ get: function( elem ) {
+ var value,
+ index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type === "select-one";
+
+ // Nothing was selected
+ if ( index < 0 ) {
+ return null;
+ }
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ // Don't return options that are disabled or in a disabled optgroup
+ if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+ (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
+
+ // Get the specific value for the option
+ value = jQuery( option ).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ // Fixes Bug #2551 -- select.val() broken in IE after form.reset()
+ if ( one && !values.length && options.length ) {
+ return jQuery( options[ index ] ).val();
+ }
+
+ return values;
+ },
+
+ set: function( elem, value ) {
+ var values = jQuery.makeArray( value );
+
+ jQuery(elem).find("option").each(function() {
+ this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
+ });
+
+ if ( !values.length ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ },
+
+ attrFn: {
+ val: true,
+ css: true,
+ html: true,
+ text: true,
+ data: true,
+ width: true,
+ height: true,
+ offset: true
+ },
+
+ attrFix: {
+ // Always normalize to ensure hook usage
+ tabindex: "tabIndex"
+ },
+
+ attr: function( elem, name, value, pass ) {
+ var nType = elem.nodeType;
+
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return undefined;
+ }
+
+ if ( pass && name in jQuery.attrFn ) {
+ return jQuery( elem )[ name ]( value );
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( !("getAttribute" in elem) ) {
+ return jQuery.prop( elem, name, value );
+ }
+
+ var ret, hooks,
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ // Normalize the name if needed
+ if ( notxml ) {
+ name = jQuery.attrFix[ name ] || name;
+
+ hooks = jQuery.attrHooks[ name ];
+
+ if ( !hooks ) {
+ // Use boolHook for boolean attributes
+ if ( rboolean.test( name ) ) {
+ hooks = boolHook;
+
+ // Use nodeHook if available( IE6/7 )
+ } else if ( nodeHook ) {
+ hooks = nodeHook;
+ }
+ }
+ }
+
+ if ( value !== undefined ) {
+
+ if ( value === null ) {
+ jQuery.removeAttr( elem, name );
+ return undefined;
+
+ } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ elem.setAttribute( name, "" + value );
+ return value;
+ }
+
+ } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+
+ ret = elem.getAttribute( name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret === null ?
+ undefined :
+ ret;
+ }
+ },
+
+ removeAttr: function( elem, name ) {
+ var propName;
+ if ( elem.nodeType === 1 ) {
+ name = jQuery.attrFix[ name ] || name;
+
+ jQuery.attr( elem, name, "" );
+ elem.removeAttribute( name );
+
+ // Set corresponding property to false for boolean attributes
+ if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
+ elem[ propName ] = false;
+ }
+ }
+ },
+
+ attrHooks: {
+ type: {
+ set: function( elem, value ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
+ } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+ // Setting the type on a radio button after the value resets the value in IE6-9
+ // Reset value to it's default in case type is set after value
+ // This is for element creation
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ },
+ // Use the value property for back compat
+ // Use the nodeHook for button elements in IE6/7 (#1954)
+ value: {
+ get: function( elem, name ) {
+ if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+ return nodeHook.get( elem, name );
+ }
+ return name in elem ?
+ elem.value :
+ null;
+ },
+ set: function( elem, value, name ) {
+ if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+ return nodeHook.set( elem, value, name );
+ }
+ // Does not return so that setAttribute is also used
+ elem.value = value;
+ }
+ }
+ },
+
+ propFix: {
+ tabindex: "tabIndex",
+ readonly: "readOnly",
+ "for": "htmlFor",
+ "class": "className",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ cellpadding: "cellPadding",
+ rowspan: "rowSpan",
+ colspan: "colSpan",
+ usemap: "useMap",
+ frameborder: "frameBorder",
+ contenteditable: "contentEditable"
+ },
+
+ prop: function( elem, name, value ) {
+ var nType = elem.nodeType;
+
+ // don't get/set properties on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return undefined;
+ }
+
+ var ret, hooks,
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ if ( notxml ) {
+ // Fix name and attach hooks
+ name = jQuery.propFix[ name ] || name;
+ hooks = jQuery.propHooks[ name ];
+ }
+
+ if ( value !== undefined ) {
+ if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ return (elem[ name ] = value);
+ }
+
+ } else {
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+ return elem[ name ];
+ }
+ }
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function( elem ) {
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ var attributeNode = elem.getAttributeNode("tabindex");
+
+ return attributeNode && attributeNode.specified ?
+ parseInt( attributeNode.value, 10 ) :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
+ }
+ }
+ }
+});
+
+// Add the tabindex propHook to attrHooks for back-compat
+jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex;
+
+// Hook for boolean attributes
+boolHook = {
+ get: function( elem, name ) {
+ // Align boolean attributes with corresponding properties
+ // Fall back to attribute presence where some booleans are not supported
+ var attrNode;
+ return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ?
+ name.toLowerCase() :
+ undefined;
+ },
+ set: function( elem, value, name ) {
+ var propName;
+ if ( value === false ) {
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr( elem, name );
+ } else {
+ // value is true since we know at this point it's type boolean and not false
+ // Set boolean attributes to the same name and set the DOM property
+ propName = jQuery.propFix[ name ] || name;
+ if ( propName in elem ) {
+ // Only set the IDL specifically if it already exists on the element
+ elem[ propName ] = true;
+ }
+
+ elem.setAttribute( name, name.toLowerCase() );
+ }
+ return name;
+ }
+};
+
+// IE6/7 do not support getting/setting some attributes with get/setAttribute
+if ( !jQuery.support.getSetAttribute ) {
+
+ // Use this for any attribute in IE6/7
+ // This fixes almost every IE6/7 issue
+ nodeHook = jQuery.valHooks.button = {
+ get: function( elem, name ) {
+ var ret;
+ ret = elem.getAttributeNode( name );
+ // Return undefined if nodeValue is empty string
+ return ret && ret.nodeValue !== "" ?
+ ret.nodeValue :
+ undefined;
+ },
+ set: function( elem, value, name ) {
+ // Set the existing or create a new attribute node
+ var ret = elem.getAttributeNode( name );
+ if ( !ret ) {
+ ret = document.createAttribute( name );
+ elem.setAttributeNode( ret );
+ }
+ return (ret.nodeValue = value + "");
+ }
+ };
+
+ // Set width and height to auto instead of 0 on empty string( Bug #8150 )
+ // This is for removals
+ jQuery.each([ "width", "height" ], function( i, name ) {
+ jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+ set: function( elem, value ) {
+ if ( value === "" ) {
+ elem.setAttribute( name, "auto" );
+ return value;
+ }
+ }
+ });
+ });
+}
+
+
+// Some attributes require a special call on IE
+if ( !jQuery.support.hrefNormalized ) {
+ jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
+ jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+ get: function( elem ) {
+ var ret = elem.getAttribute( name, 2 );
+ return ret === null ? undefined : ret;
+ }
+ });
+ });
+}
+
+if ( !jQuery.support.style ) {
+ jQuery.attrHooks.style = {
+ get: function( elem ) {
+ // Return undefined in the case of empty string
+ // Normalize to lowercase since IE uppercases css property names
+ return elem.style.cssText.toLowerCase() || undefined;
+ },
+ set: function( elem, value ) {
+ return (elem.style.cssText = "" + value);
+ }
+ };
+}
+
+// Safari mis-reports the default selected property of an option
+// Accessing the parent's selectedIndex property fixes it
+if ( !jQuery.support.optSelected ) {
+ jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
+ get: function( elem ) {
+ var parent = elem.parentNode;
+
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ return null;
+ }
+ });
+}
+
+// Radios and checkboxes getter/setter
+if ( !jQuery.support.checkOn ) {
+ jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = {
+ get: function( elem ) {
+ // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ }
+ };
+ });
+}
+jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
+ set: function( elem, value ) {
+ if ( jQuery.isArray( value ) ) {
+ return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
+ }
+ }
+ });
+});
+
+
+
+
+var rnamespaces = /\.(.*)$/,
+ rformElems = /^(?:textarea|input|select)$/i,
+ rperiod = /\./g,
+ rspaces = / /g,
+ rescape = /[^\w\s.|`]/g,
+ fcleanup = function( nm ) {
+ return nm.replace(rescape, "\\$&");
+ };
+
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function( elem, types, handler, data ) {
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ } else if ( !handler ) {
+ // Fixes bug #7229. Fix recommended by jdalton
+ return;
+ }
+
+ var handleObjIn, handleObj;
+
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ }
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure
+ var elemData = jQuery._data( elem );
+
+ // If no elemData is found then we must be trying to bind to one of the
+ // banned noData elements
+ if ( !elemData ) {
+ return;
+ }
+
+ var events = elemData.events,
+ eventHandle = elemData.handle;
+
+ if ( !events ) {
+ elemData.events = events = {};
+ }
+
+ if ( !eventHandle ) {
+ elemData.handle = eventHandle = function( e ) {
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
+ jQuery.event.handle.apply( eventHandle.elem, arguments ) :
+ undefined;
+ };
+ }
+
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native events in IE.
+ eventHandle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ var type, i = 0, namespaces;
+
+ while ( (type = types[ i++ ]) ) {
+ handleObj = handleObjIn ?
+ jQuery.extend({}, handleObjIn) :
+ { handler: handler, data: data };
+
+ // Namespaced event handlers
+ if ( type.indexOf(".") > -1 ) {
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ handleObj.namespace = namespaces.slice(0).sort().join(".");
+
+ } else {
+ namespaces = [];
+ handleObj.namespace = "";
+ }
+
+ handleObj.type = type;
+ if ( !handleObj.guid ) {
+ handleObj.guid = handler.guid;
+ }
+
+ // Get the current list of functions bound to this event
+ var handlers = events[ type ],
+ special = jQuery.event.special[ type ] || {};
+
+ // Init the event handler queue
+ if ( !handlers ) {
+ handlers = events[ type ] = [];
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ // Bind the global event handler to the element
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle, false );
+
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, eventHandle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers.push( handleObj );
+
+ // Keep track of which events have been used, for event optimization
+ jQuery.event.global[ type ] = true;
+ }
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, pos ) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ }
+
+ var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
+ events = elemData && elemData.events;
+
+ if ( !elemData || !events ) {
+ return;
+ }
+
+ // types is actually an event object here
+ if ( types && types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Unbind all events for the element
+ if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
+ types = types || "";
+
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types );
+ }
+
+ return;
+ }
+
+ // Handle multiple events separated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ while ( (type = types[ i++ ]) ) {
+ origType = type;
+ handleObj = null;
+ all = type.indexOf(".") < 0;
+ namespaces = [];
+
+ if ( !all ) {
+ // Namespaced event handlers
+ namespaces = type.split(".");
+ type = namespaces.shift();
+
+ namespace = new RegExp("(^|\\.)" +
+ jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ eventType = events[ type ];
+
+ if ( !eventType ) {
+ continue;
+ }
+
+ if ( !handler ) {
+ for ( j = 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ jQuery.event.remove( elem, origType, handleObj.handler, j );
+ eventType.splice( j--, 1 );
+ }
+ }
+
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+
+ for ( j = pos || 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( handler.guid === handleObj.guid ) {
+ // remove the given handler for the given type
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ if ( pos == null ) {
+ eventType.splice( j--, 1 );
+ }
+
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+
+ if ( pos != null ) {
+ break;
+ }
+ }
+ }
+
+ // remove generic event handler if no more handlers exist
+ if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ ret = null;
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ var handle = elemData.handle;
+ if ( handle ) {
+ handle.elem = null;
+ }
+
+ delete elemData.events;
+ delete elemData.handle;
+
+ if ( jQuery.isEmptyObject( elemData ) ) {
+ jQuery.removeData( elem, undefined, true );
+ }
+ }
+ },
+
+ // Events that are safe to short-circuit if no handlers are attached.
+ // Native DOM events should not be added, they may have inline handlers.
+ customEvent: {
+ "getData": true,
+ "setData": true,
+ "changeData": true
+ },
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+ // Event object or event type
+ var type = event.type || event,
+ namespaces = [],
+ exclusive;
+
+ if ( type.indexOf("!") >= 0 ) {
+ // Exclusive events trigger only for the exact event (no namespaces)
+ type = type.slice(0, -1);
+ exclusive = true;
+ }
+
+ if ( type.indexOf(".") >= 0 ) {
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+
+ if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
+ // No jQuery handlers for this event type, and it can't have inline handlers
+ return;
+ }
+
+ // Caller can pass in an Event, Object, or just an event type string
+ event = typeof event === "object" ?
+ // jQuery.Event object
+ event[ jQuery.expando ] ? event :
+ // Object literal
+ new jQuery.Event( type, event ) :
+ // Just the event type (string)
+ new jQuery.Event( type );
+
+ event.type = type;
+ event.exclusive = exclusive;
+ event.namespace = namespaces.join(".");
+ event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
+
+ // triggerHandler() and global events don't bubble or run the default action
+ if ( onlyHandlers || !elem ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // TODO: Stop taunting the data cache; remove global events and always attach to document
+ jQuery.each( jQuery.cache, function() {
+ // internalKey variable is just used to make it easier to find
+ // and potentially change this stuff later; currently it just
+ // points to jQuery.expando
+ var internalKey = jQuery.expando,
+ internalCache = this[ internalKey ];
+ if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
+ jQuery.event.trigger( event, data, internalCache.handle.elem );
+ }
+ });
+ return;
+ }
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ event.target = elem;
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data != null ? jQuery.makeArray( data ) : [];
+ data.unshift( event );
+
+ var cur = elem,
+ // IE doesn't like method names with a colon (#3533, #8272)
+ ontype = type.indexOf(":") < 0 ? "on" + type : "";
+
+ // Fire event on the current element, then bubble up the DOM tree
+ do {
+ var handle = jQuery._data( cur, "handle" );
+
+ event.currentTarget = cur;
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Trigger an inline bound script
+ if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
+ event.result = false;
+ event.preventDefault();
+ }
+
+ // Bubble up to document, then to window
+ cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
+ } while ( cur && !event.isPropagationStopped() );
+
+ // If nobody prevented the default action, do it now
+ if ( !event.isDefaultPrevented() ) {
+ var old,
+ special = jQuery.event.special[ type ] || {};
+
+ if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
+ !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Can't use an .isFunction)() check here because IE6/7 fails that test.
+ // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
+ try {
+ if ( ontype && elem[ type ] ) {
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ old = elem[ ontype ];
+
+ if ( old ) {
+ elem[ ontype ] = null;
+ }
+
+ jQuery.event.triggered = type;
+ elem[ type ]();
+ }
+ } catch ( ieError ) {}
+
+ if ( old ) {
+ elem[ ontype ] = old;
+ }
+
+ jQuery.event.triggered = undefined;
+ }
+ }
+
+ return event.result;
+ },
+
+ handle: function( event ) {
+ event = jQuery.event.fix( event || window.event );
+ // Snapshot the handlers list since a called handler may add/remove events.
+ var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
+ run_all = !event.exclusive && !event.namespace,
+ args = Array.prototype.slice.call( arguments, 0 );
+
+ // Use the fix-ed Event rather than the (read-only) native event
+ args[0] = event;
+ event.currentTarget = this;
+
+ for ( var j = 0, l = handlers.length; j < l; j++ ) {
+ var handleObj = handlers[ j ];
+
+ // Triggered event must 1) be non-exclusive and have no namespace, or
+ // 2) have namespace(s) a subset or equal to those in the bound event.
+ if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handleObj.handler;
+ event.data = handleObj.data;
+ event.handleObj = handleObj;
+
+ var ret = handleObj.handler.apply( this, args );
+
+ if ( ret !== undefined ) {
+ event.result = ret;
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+ return event.result;
+ },
+
+ props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = jQuery.Event( originalEvent );
+
+ for ( var i = this.props.length, prop; i; ) {
+ prop = this.props[ --i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Fix target property, if necessary
+ if ( !event.target ) {
+ // Fixes #1925 where srcElement might not be defined either
+ event.target = event.srcElement || document;
+ }
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement ) {
+ event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
+ }
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var eventDocument = event.target.ownerDocument || document,
+ doc = eventDocument.documentElement,
+ body = eventDocument.body;
+
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
+ event.which = event.charCode != null ? event.charCode : event.keyCode;
+ }
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey ) {
+ event.metaKey = event.ctrlKey;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button !== undefined ) {
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+ }
+
+ return event;
+ },
+
+ // Deprecated, use jQuery.guid instead
+ guid: 1E8,
+
+ // Deprecated, use jQuery.proxy instead
+ proxy: jQuery.proxy,
+
+ special: {
+ ready: {
+ // Make sure the ready event is setup
+ setup: jQuery.bindReady,
+ teardown: jQuery.noop
+ },
+
+ live: {
+ add: function( handleObj ) {
+ jQuery.event.add( this,
+ liveConvert( handleObj.origType, handleObj.selector ),
+ jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+ },
+
+ remove: function( handleObj ) {
+ jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
+ }
+ },
+
+ beforeunload: {
+ setup: function( data, namespaces, eventHandle ) {
+ // We only want to do this special case on windows
+ if ( jQuery.isWindow( this ) ) {
+ this.onbeforeunload = eventHandle;
+ }
+ },
+
+ teardown: function( namespaces, eventHandle ) {
+ if ( this.onbeforeunload === eventHandle ) {
+ this.onbeforeunload = null;
+ }
+ }
+ }
+ }
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+ function( elem, type, handle ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle, false );
+ }
+ } :
+ function( elem, type, handle ) {
+ if ( elem.detachEvent ) {
+ elem.detachEvent( "on" + type, handle );
+ }
+ };
+
+jQuery.Event = function( src, props ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !this.preventDefault ) {
+ return new jQuery.Event( src, props );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+ src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // timeStamp is buggy for some events on Firefox(#3843)
+ // So we won't rely on the native value
+ this.timeStamp = jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+function returnFalse() {
+ return false;
+}
+function returnTrue() {
+ return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ preventDefault: function() {
+ this.isDefaultPrevented = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+
+ // if preventDefault exists run it on the original event
+ if ( e.preventDefault ) {
+ e.preventDefault();
+
+ // otherwise set the returnValue property of the original event to false (IE)
+ } else {
+ e.returnValue = false;
+ }
+ },
+ stopPropagation: function() {
+ this.isPropagationStopped = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+ // if stopPropagation exists run it on the original event
+ if ( e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation: function() {
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ },
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse
+};
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function( event ) {
+
+ // Check if mouse(over|out) are still within the same parent element
+ var related = event.relatedTarget,
+ inside = false,
+ eventType = event.type;
+
+ event.type = event.data;
+
+ if ( related !== this ) {
+
+ if ( related ) {
+ inside = jQuery.contains( this, related );
+ }
+
+ if ( !inside ) {
+
+ jQuery.event.handle.apply( this, arguments );
+
+ event.type = eventType;
+ }
+ }
+},
+
+// In case of event delegation, we only need to rename the event.type,
+// liveHandler will take care of the rest.
+delegate = function( event ) {
+ event.type = event.data;
+ jQuery.event.handle.apply( this, arguments );
+};
+
+// Create mouseenter and mouseleave events
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ setup: function( data ) {
+ jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
+ },
+ teardown: function( data ) {
+ jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
+ }
+ };
+});
+
+// submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+ jQuery.event.special.submit = {
+ setup: function( data, namespaces ) {
+ if ( !jQuery.nodeName( this, "form" ) ) {
+ jQuery.event.add(this, "click.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
+ trigger( "submit", this, arguments );
+ }
+ });
+
+ jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
+ trigger( "submit", this, arguments );
+ }
+ });
+
+ } else {
+ return false;
+ }
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialSubmit" );
+ }
+ };
+
+}
+
+// change delegation, happens here so we have bind.
+if ( !jQuery.support.changeBubbles ) {
+
+ var changeFilters,
+
+ getVal = function( elem ) {
+ var type = jQuery.nodeName( elem, "input" ) ? elem.type : "",
+ val = elem.value;
+
+ if ( type === "radio" || type === "checkbox" ) {
+ val = elem.checked;
+
+ } else if ( type === "select-multiple" ) {
+ val = elem.selectedIndex > -1 ?
+ jQuery.map( elem.options, function( elem ) {
+ return elem.selected;
+ }).join("-") :
+ "";
+
+ } else if ( jQuery.nodeName( elem, "select" ) ) {
+ val = elem.selectedIndex;
+ }
+
+ return val;
+ },
+
+ testChange = function testChange( e ) {
+ var elem = e.target, data, val;
+
+ if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
+ return;
+ }
+
+ data = jQuery._data( elem, "_change_data" );
+ val = getVal(elem);
+
+ // the current data will be also retrieved by beforeactivate
+ if ( e.type !== "focusout" || elem.type !== "radio" ) {
+ jQuery._data( elem, "_change_data", val );
+ }
+
+ if ( data === undefined || val === data ) {
+ return;
+ }
+
+ if ( data != null || val ) {
+ e.type = "change";
+ e.liveFired = undefined;
+ jQuery.event.trigger( e, arguments[1], elem );
+ }
+ };
+
+ jQuery.event.special.change = {
+ filters: {
+ focusout: testChange,
+
+ beforedeactivate: testChange,
+
+ click: function( e ) {
+ var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
+ testChange.call( this, e );
+ }
+ },
+
+ // Change has to be called before submit
+ // Keydown will be called before keypress, which is used in submit-event delegation
+ keydown: function( e ) {
+ var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
+ (e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
+ type === "select-multiple" ) {
+ testChange.call( this, e );
+ }
+ },
+
+ // Beforeactivate happens also before the previous element is blurred
+ // with this event you can't trigger a change event, but you can store
+ // information
+ beforeactivate: function( e ) {
+ var elem = e.target;
+ jQuery._data( elem, "_change_data", getVal(elem) );
+ }
+ },
+
+ setup: function( data, namespaces ) {
+ if ( this.type === "file" ) {
+ return false;
+ }
+
+ for ( var type in changeFilters ) {
+ jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
+ }
+
+ return rformElems.test( this.nodeName );
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialChange" );
+
+ return rformElems.test( this.nodeName );
+ }
+ };
+
+ changeFilters = jQuery.event.special.change.filters;
+
+ // Handle when the input is .focus()'d
+ changeFilters.focus = changeFilters.beforeactivate;
+}
+
+function trigger( type, elem, args ) {
+ // Piggyback on a donor event to simulate a different one.
+ // Fake originalEvent to avoid donor's stopPropagation, but if the
+ // simulated event prevents default then we do the same on the donor.
+ // Don't pass args or remember liveFired; they apply to the donor event.
+ var event = jQuery.extend( {}, args[ 0 ] );
+ event.type = type;
+ event.originalEvent = {};
+ event.liveFired = undefined;
+ jQuery.event.handle.call( elem, event );
+ if ( event.isDefaultPrevented() ) {
+ args[ 0 ].preventDefault();
+ }
+}
+
+// Create "bubbling" focus and blur events
+if ( !jQuery.support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler while someone wants focusin/focusout
+ var attaches = 0;
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ if ( attaches++ === 0 ) {
+ document.addEventListener( orig, handler, true );
+ }
+ },
+ teardown: function() {
+ if ( --attaches === 0 ) {
+ document.removeEventListener( orig, handler, true );
+ }
+ }
+ };
+
+ function handler( donor ) {
+ // Donor event is always a native one; fix it and switch its type.
+ // Let focusin/out handler cancel the donor focus/blur event.
+ var e = jQuery.event.fix( donor );
+ e.type = fix;
+ e.originalEvent = {};
+ jQuery.event.trigger( e, null, e.target );
+ if ( e.isDefaultPrevented() ) {
+ donor.preventDefault();
+ }
+ }
+ });
+}
+
+jQuery.each(["bind", "one"], function( i, name ) {
+ jQuery.fn[ name ] = function( type, data, fn ) {
+ var handler;
+
+ // Handle object literals
+ if ( typeof type === "object" ) {
+ for ( var key in type ) {
+ this[ name ](key, data, type[key], fn);
+ }
+ return this;
+ }
+
+ if ( arguments.length === 2 || data === false ) {
+ fn = data;
+ data = undefined;
+ }
+
+ if ( name === "one" ) {
+ handler = function( event ) {
+ jQuery( this ).unbind( event, handler );
+ return fn.apply( this, arguments );
+ };
+ handler.guid = fn.guid || jQuery.guid++;
+ } else {
+ handler = fn;
+ }
+
+ if ( type === "unload" && name !== "one" ) {
+ this.one( type, data, fn );
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.add( this[i], type, handler, data );
+ }
+ }
+
+ return this;
+ };
+});
+
+jQuery.fn.extend({
+ unbind: function( type, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" && !type.preventDefault ) {
+ for ( var key in type ) {
+ this.unbind(key, type[key]);
+ }
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.remove( this[i], type, fn );
+ }
+ }
+
+ return this;
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.live( types, data, fn, selector );
+ },
+
+ undelegate: function( selector, types, fn ) {
+ if ( arguments.length === 0 ) {
+ return this.unbind( "live" );
+
+ } else {
+ return this.die( types, null, fn, selector );
+ }
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+
+ triggerHandler: function( type, data ) {
+ if ( this[0] ) {
+ return jQuery.event.trigger( type, data, this[0], true );
+ }
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments,
+ guid = fn.guid || jQuery.guid++,
+ i = 0,
+ toggler = function( event ) {
+ // Figure out which function to execute
+ var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+ jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ lastToggle ].apply( this, arguments ) || false;
+ };
+
+ // link all the functions, so any of them can unbind this click handler
+ toggler.guid = guid;
+ while ( i < args.length ) {
+ args[ i++ ].guid = guid;
+ }
+
+ return this.click( toggler );
+ },
+
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ }
+});
+
+var liveMap = {
+ focus: "focusin",
+ blur: "focusout",
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+};
+
+jQuery.each(["live", "die"], function( i, name ) {
+ jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
+ var type, i = 0, match, namespaces, preType,
+ selector = origSelector || this.selector,
+ context = origSelector ? this : jQuery( this.context );
+
+ if ( typeof types === "object" && !types.preventDefault ) {
+ for ( var key in types ) {
+ context[ name ]( key, data, types[key], selector );
+ }
+
+ return this;
+ }
+
+ if ( name === "die" && !types &&
+ origSelector && origSelector.charAt(0) === "." ) {
+
+ context.unbind( origSelector );
+
+ return this;
+ }
+
+ if ( data === false || jQuery.isFunction( data ) ) {
+ fn = data || returnFalse;
+ data = undefined;
+ }
+
+ types = (types || "").split(" ");
+
+ while ( (type = types[ i++ ]) != null ) {
+ match = rnamespaces.exec( type );
+ namespaces = "";
+
+ if ( match ) {
+ namespaces = match[0];
+ type = type.replace( rnamespaces, "" );
+ }
+
+ if ( type === "hover" ) {
+ types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
+ continue;
+ }
+
+ preType = type;
+
+ if ( liveMap[ type ] ) {
+ types.push( liveMap[ type ] + namespaces );
+ type = type + namespaces;
+
+ } else {
+ type = (liveMap[ type ] || type) + namespaces;
+ }
+
+ if ( name === "live" ) {
+ // bind live handler
+ for ( var j = 0, l = context.length; j < l; j++ ) {
+ jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
+ { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
+ }
+
+ } else {
+ // unbind live handler
+ context.unbind( "live." + liveConvert( type, selector ), fn );
+ }
+ }
+
+ return this;
+ };
+});
+
+function liveHandler( event ) {
+ var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+ elems = [],
+ selectors = [],
+ events = jQuery._data( this, "events" );
+
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+ if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
+ return;
+ }
+
+ if ( event.namespace ) {
+ namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ event.liveFired = this;
+
+ var live = events.live.slice(0);
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
+ selectors.push( handleObj.selector );
+
+ } else {
+ live.splice( j--, 1 );
+ }
+ }
+
+ match = jQuery( event.target ).closest( selectors, event.currentTarget );
+
+ for ( i = 0, l = match.length; i < l; i++ ) {
+ close = match[i];
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
+ elem = close.elem;
+ related = null;
+
+ // Those two events require additional checking
+ if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
+ event.type = handleObj.preType;
+ related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
+
+ // Make sure not to accidentally match a child element with the same selector
+ if ( related && jQuery.contains( elem, related ) ) {
+ related = elem;
+ }
+ }
+
+ if ( !related || related !== elem ) {
+ elems.push({ elem: elem, handleObj: handleObj, level: close.level });
+ }
+ }
+ }
+ }
+
+ for ( i = 0, l = elems.length; i < l; i++ ) {
+ match = elems[i];
+
+ if ( maxLevel && match.level > maxLevel ) {
+ break;
+ }
+
+ event.currentTarget = match.elem;
+ event.data = match.handleObj.data;
+ event.handleObj = match.handleObj;
+
+ ret = match.handleObj.origHandler.apply( match.elem, arguments );
+
+ if ( ret === false || event.isPropagationStopped() ) {
+ maxLevel = match.level;
+
+ if ( ret === false ) {
+ stop = false;
+ }
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+
+ return stop;
+}
+
+function liveConvert( type, selector ) {
+ return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
+}
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ if ( fn == null ) {
+ fn = data;
+ data = null;
+ }
+
+ return arguments.length > 0 ?
+ this.bind( name, data, fn ) :
+ this.trigger( name );
+ };
+
+ if ( jQuery.attrFn ) {
+ jQuery.attrFn[ name ] = true;
+ }
+});
+
+
+
+/*!
+ * Sizzle CSS Selector Engine
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+ done = 0,
+ toString = Object.prototype.toString,
+ hasDuplicate = false,
+ baseHasDuplicate = true,
+ rBackslash = /\\/g,
+ rNonWord = /\W/;
+
+// Here we check if the JavaScript engine is using some sort of
+// optimization where it does not always call our comparision
+// function. If that is the case, discard the hasDuplicate value.
+// Thus far that includes Google Chrome.
+[0, 0].sort(function() {
+ baseHasDuplicate = false;
+ return 0;
+});
+
+var Sizzle = function( selector, context, results, seed ) {
+ results = results || [];
+ context = context || document;
+
+ var origContext = context;
+
+ if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ var m, set, checkSet, extra, ret, cur, pop, i,
+ prune = true,
+ contextXML = Sizzle.isXML( context ),
+ parts = [],
+ soFar = selector;
+
+ // Reset the position of the chunker regexp (start from head)
+ do {
+ chunker.exec( "" );
+ m = chunker.exec( soFar );
+
+ if ( m ) {
+ soFar = m[3];
+
+ parts.push( m[1] );
+
+ if ( m[2] ) {
+ extra = m[3];
+ break;
+ }
+ }
+ } while ( m );
+
+ if ( parts.length > 1 && origPOS.exec( selector ) ) {
+
+ if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+ set = posProcess( parts[0] + parts[1], context );
+
+ } else {
+ set = Expr.relative[ parts[0] ] ?
+ [ context ] :
+ Sizzle( parts.shift(), context );
+
+ while ( parts.length ) {
+ selector = parts.shift();
+
+ if ( Expr.relative[ selector ] ) {
+ selector += parts.shift();
+ }
+
+ set = posProcess( selector, set );
+ }
+ }
+
+ } else {
+ // Take a shortcut and set the context if the root selector is an ID
+ // (but not if it'll be faster if the inner selector is an ID)
+ if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+ Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+
+ ret = Sizzle.find( parts.shift(), context, contextXML );
+ context = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set )[0] :
+ ret.set[0];
+ }
+
+ if ( context ) {
+ ret = seed ?
+ { expr: parts.pop(), set: makeArray(seed) } :
+ Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
+
+ set = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set ) :
+ ret.set;
+
+ if ( parts.length > 0 ) {
+ checkSet = makeArray( set );
+
+ } else {
+ prune = false;
+ }
+
+ while ( parts.length ) {
+ cur = parts.pop();
+ pop = cur;
+
+ if ( !Expr.relative[ cur ] ) {
+ cur = "";
+ } else {
+ pop = parts.pop();
+ }
+
+ if ( pop == null ) {
+ pop = context;
+ }
+
+ Expr.relative[ cur ]( checkSet, pop, contextXML );
+ }
+
+ } else {
+ checkSet = parts = [];
+ }
+ }
+
+ if ( !checkSet ) {
+ checkSet = set;
+ }
+
+ if ( !checkSet ) {
+ Sizzle.error( cur || selector );
+ }
+
+ if ( toString.call(checkSet) === "[object Array]" ) {
+ if ( !prune ) {
+ results.push.apply( results, checkSet );
+
+ } else if ( context && context.nodeType === 1 ) {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
+ results.push( set[i] );
+ }
+ }
+
+ } else {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+ results.push( set[i] );
+ }
+ }
+ }
+
+ } else {
+ makeArray( checkSet, results );
+ }
+
+ if ( extra ) {
+ Sizzle( extra, origContext, results, seed );
+ Sizzle.uniqueSort( results );
+ }
+
+ return results;
+};
+
+Sizzle.uniqueSort = function( results ) {
+ if ( sortOrder ) {
+ hasDuplicate = baseHasDuplicate;
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ for ( var i = 1; i < results.length; i++ ) {
+ if ( results[i] === results[ i - 1 ] ) {
+ results.splice( i--, 1 );
+ }
+ }
+ }
+ }
+
+ return results;
+};
+
+Sizzle.matches = function( expr, set ) {
+ return Sizzle( expr, null, null, set );
+};
+
+Sizzle.matchesSelector = function( node, expr ) {
+ return Sizzle( expr, null, null, [node] ).length > 0;
+};
+
+Sizzle.find = function( expr, context, isXML ) {
+ var set;
+
+ if ( !expr ) {
+ return [];
+ }
+
+ for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+ var match,
+ type = Expr.order[i];
+
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
+ var left = match[1];
+ match.splice( 1, 1 );
+
+ if ( left.substr( left.length - 1 ) !== "\\" ) {
+ match[1] = (match[1] || "").replace( rBackslash, "" );
+ set = Expr.find[ type ]( match, context, isXML );
+
+ if ( set != null ) {
+ expr = expr.replace( Expr.match[ type ], "" );
+ break;
+ }
+ }
+ }
+ }
+
+ if ( !set ) {
+ set = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( "*" ) :
+ [];
+ }
+
+ return { set: set, expr: expr };
+};
+
+Sizzle.filter = function( expr, set, inplace, not ) {
+ var match, anyFound,
+ old = expr,
+ result = [],
+ curLoop = set,
+ isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
+
+ while ( expr && set.length ) {
+ for ( var type in Expr.filter ) {
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
+ var found, item,
+ filter = Expr.filter[ type ],
+ left = match[1];
+
+ anyFound = false;
+
+ match.splice(1,1);
+
+ if ( left.substr( left.length - 1 ) === "\\" ) {
+ continue;
+ }
+
+ if ( curLoop === result ) {
+ result = [];
+ }
+
+ if ( Expr.preFilter[ type ] ) {
+ match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+ if ( !match ) {
+ anyFound = found = true;
+
+ } else if ( match === true ) {
+ continue;
+ }
+ }
+
+ if ( match ) {
+ for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+ if ( item ) {
+ found = filter( item, match, i, curLoop );
+ var pass = not ^ !!found;
+
+ if ( inplace && found != null ) {
+ if ( pass ) {
+ anyFound = true;
+
+ } else {
+ curLoop[i] = false;
+ }
+
+ } else if ( pass ) {
+ result.push( item );
+ anyFound = true;
+ }
+ }
+ }
+ }
+
+ if ( found !== undefined ) {
+ if ( !inplace ) {
+ curLoop = result;
+ }
+
+ expr = expr.replace( Expr.match[ type ], "" );
+
+ if ( !anyFound ) {
+ return [];
+ }
+
+ break;
+ }
+ }
+ }
+
+ // Improper expression
+ if ( expr === old ) {
+ if ( anyFound == null ) {
+ Sizzle.error( expr );
+
+ } else {
+ break;
+ }
+ }
+
+ old = expr;
+ }
+
+ return curLoop;
+};
+
+Sizzle.error = function( msg ) {
+ throw "Syntax error, unrecognized expression: " + msg;
+};
+
+var Expr = Sizzle.selectors = {
+ order: [ "ID", "NAME", "TAG" ],
+
+ match: {
+ ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
+ TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
+ CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
+ POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
+ PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+ },
+
+ leftMatch: {},
+
+ attrMap: {
+ "class": "className",
+ "for": "htmlFor"
+ },
+
+ attrHandle: {
+ href: function( elem ) {
+ return elem.getAttribute( "href" );
+ },
+ type: function( elem ) {
+ return elem.getAttribute( "type" );
+ }
+ },
+
+ relative: {
+ "+": function(checkSet, part){
+ var isPartStr = typeof part === "string",
+ isTag = isPartStr && !rNonWord.test( part ),
+ isPartStrNotTag = isPartStr && !isTag;
+
+ if ( isTag ) {
+ part = part.toLowerCase();
+ }
+
+ for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+ if ( (elem = checkSet[i]) ) {
+ while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+ checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+ elem || false :
+ elem === part;
+ }
+ }
+
+ if ( isPartStrNotTag ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ },
+
+ ">": function( checkSet, part ) {
+ var elem,
+ isPartStr = typeof part === "string",
+ i = 0,
+ l = checkSet.length;
+
+ if ( isPartStr && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ var parent = elem.parentNode;
+ checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+ }
+ }
+
+ } else {
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ checkSet[i] = isPartStr ?
+ elem.parentNode :
+ elem.parentNode === part;
+ }
+ }
+
+ if ( isPartStr ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ }
+ },
+
+ "": function(checkSet, part, isXML){
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
+ },
+
+ "~": function( checkSet, part, isXML ) {
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
+ }
+ },
+
+ find: {
+ ID: function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ return m && m.parentNode ? [m] : [];
+ }
+ },
+
+ NAME: function( match, context ) {
+ if ( typeof context.getElementsByName !== "undefined" ) {
+ var ret = [],
+ results = context.getElementsByName( match[1] );
+
+ for ( var i = 0, l = results.length; i < l; i++ ) {
+ if ( results[i].getAttribute("name") === match[1] ) {
+ ret.push( results[i] );
+ }
+ }
+
+ return ret.length === 0 ? null : ret;
+ }
+ },
+
+ TAG: function( match, context ) {
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( match[1] );
+ }
+ }
+ },
+ preFilter: {
+ CLASS: function( match, curLoop, inplace, result, not, isXML ) {
+ match = " " + match[1].replace( rBackslash, "" ) + " ";
+
+ if ( isXML ) {
+ return match;
+ }
+
+ for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
+ if ( elem ) {
+ if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
+ if ( !inplace ) {
+ result.push( elem );
+ }
+
+ } else if ( inplace ) {
+ curLoop[i] = false;
+ }
+ }
+ }
+
+ return false;
+ },
+
+ ID: function( match ) {
+ return match[1].replace( rBackslash, "" );
+ },
+
+ TAG: function( match, curLoop ) {
+ return match[1].replace( rBackslash, "" ).toLowerCase();
+ },
+
+ CHILD: function( match ) {
+ if ( match[1] === "nth" ) {
+ if ( !match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ match[2] = match[2].replace(/^\+|\s*/g, '');
+
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
+ match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+ !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+ // calculate the numbers (first)n+(last) including if they are negative
+ match[2] = (test[1] + (test[2] || 1)) - 0;
+ match[3] = test[3] - 0;
+ }
+ else if ( match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ // TODO: Move to normal caching system
+ match[0] = done++;
+
+ return match;
+ },
+
+ ATTR: function( match, curLoop, inplace, result, not, isXML ) {
+ var name = match[1] = match[1].replace( rBackslash, "" );
+
+ if ( !isXML && Expr.attrMap[name] ) {
+ match[1] = Expr.attrMap[name];
+ }
+
+ // Handle if an un-quoted value was used
+ match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
+
+ if ( match[2] === "~=" ) {
+ match[4] = " " + match[4] + " ";
+ }
+
+ return match;
+ },
+
+ PSEUDO: function( match, curLoop, inplace, result, not ) {
+ if ( match[1] === "not" ) {
+ // If we're dealing with a complex expression, or a simple one
+ if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
+ match[3] = Sizzle(match[3], null, null, curLoop);
+
+ } else {
+ var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
+ if ( !inplace ) {
+ result.push.apply( result, ret );
+ }
+
+ return false;
+ }
+
+ } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+ return true;
+ }
+
+ return match;
+ },
+
+ POS: function( match ) {
+ match.unshift( true );
+
+ return match;
+ }
+ },
+
+ filters: {
+ enabled: function( elem ) {
+ return elem.disabled === false && elem.type !== "hidden";
+ },
+
+ disabled: function( elem ) {
+ return elem.disabled === true;
+ },
+
+ checked: function( elem ) {
+ return elem.checked === true;
+ },
+
+ selected: function( elem ) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ parent: function( elem ) {
+ return !!elem.firstChild;
+ },
+
+ empty: function( elem ) {
+ return !elem.firstChild;
+ },
+
+ has: function( elem, i, match ) {
+ return !!Sizzle( match[3], elem ).length;
+ },
+
+ header: function( elem ) {
+ return (/h\d/i).test( elem.nodeName );
+ },
+
+ text: function( elem ) {
+ var attr = elem.getAttribute( "type" ), type = elem.type;
+ // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+ // use getAttribute instead to test this case
+ return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
+ },
+
+ radio: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
+ },
+
+ checkbox: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
+ },
+
+ file: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
+ },
+
+ password: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
+ },
+
+ submit: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return (name === "input" || name === "button") && "submit" === elem.type;
+ },
+
+ image: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
+ },
+
+ reset: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return (name === "input" || name === "button") && "reset" === elem.type;
+ },
+
+ button: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && "button" === elem.type || name === "button";
+ },
+
+ input: function( elem ) {
+ return (/input|select|textarea|button/i).test( elem.nodeName );
+ },
+
+ focus: function( elem ) {
+ return elem === elem.ownerDocument.activeElement;
+ }
+ },
+ setFilters: {
+ first: function( elem, i ) {
+ return i === 0;
+ },
+
+ last: function( elem, i, match, array ) {
+ return i === array.length - 1;
+ },
+
+ even: function( elem, i ) {
+ return i % 2 === 0;
+ },
+
+ odd: function( elem, i ) {
+ return i % 2 === 1;
+ },
+
+ lt: function( elem, i, match ) {
+ return i < match[3] - 0;
+ },
+
+ gt: function( elem, i, match ) {
+ return i > match[3] - 0;
+ },
+
+ nth: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ },
+
+ eq: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ }
+ },
+ filter: {
+ PSEUDO: function( elem, match, i, array ) {
+ var name = match[1],
+ filter = Expr.filters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+
+ } else if ( name === "contains" ) {
+ return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
+ } else if ( name === "not" ) {
+ var not = match[3];
+
+ for ( var j = 0, l = not.length; j < l; j++ ) {
+ if ( not[j] === elem ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ } else {
+ Sizzle.error( name );
+ }
+ },
+
+ CHILD: function( elem, match ) {
+ var type = match[1],
+ node = elem;
+
+ switch ( type ) {
+ case "only":
+ case "first":
+ while ( (node = node.previousSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ if ( type === "first" ) {
+ return true;
+ }
+
+ node = elem;
+
+ case "last":
+ while ( (node = node.nextSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ case "nth":
+ var first = match[2],
+ last = match[3];
+
+ if ( first === 1 && last === 0 ) {
+ return true;
+ }
+
+ var doneName = match[0],
+ parent = elem.parentNode;
+
+ if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+ var count = 0;
+
+ for ( node = parent.firstChild; node; node = node.nextSibling ) {
+ if ( node.nodeType === 1 ) {
+ node.nodeIndex = ++count;
+ }
+ }
+
+ parent.sizcache = doneName;
+ }
+
+ var diff = elem.nodeIndex - last;
+
+ if ( first === 0 ) {
+ return diff === 0;
+
+ } else {
+ return ( diff % first === 0 && diff / first >= 0 );
+ }
+ }
+ },
+
+ ID: function( elem, match ) {
+ return elem.nodeType === 1 && elem.getAttribute("id") === match;
+ },
+
+ TAG: function( elem, match ) {
+ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+ },
+
+ CLASS: function( elem, match ) {
+ return (" " + (elem.className || elem.getAttribute("class")) + " ")
+ .indexOf( match ) > -1;
+ },
+
+ ATTR: function( elem, match ) {
+ var name = match[1],
+ result = Expr.attrHandle[ name ] ?
+ Expr.attrHandle[ name ]( elem ) :
+ elem[ name ] != null ?
+ elem[ name ] :
+ elem.getAttribute( name ),
+ value = result + "",
+ type = match[2],
+ check = match[4];
+
+ return result == null ?
+ type === "!=" :
+ type === "=" ?
+ value === check :
+ type === "*=" ?
+ value.indexOf(check) >= 0 :
+ type === "~=" ?
+ (" " + value + " ").indexOf(check) >= 0 :
+ !check ?
+ value && result !== false :
+ type === "!=" ?
+ value !== check :
+ type === "^=" ?
+ value.indexOf(check) === 0 :
+ type === "$=" ?
+ value.substr(value.length - check.length) === check :
+ type === "|=" ?
+ value === check || value.substr(0, check.length + 1) === check + "-" :
+ false;
+ },
+
+ POS: function( elem, match, i, array ) {
+ var name = match[2],
+ filter = Expr.setFilters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ }
+ }
+ }
+};
+
+var origPOS = Expr.match.POS,
+ fescape = function(all, num){
+ return "\\" + (num - 0 + 1);
+ };
+
+for ( var type in Expr.match ) {
+ Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
+ Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
+}
+
+var makeArray = function( array, results ) {
+ array = Array.prototype.slice.call( array, 0 );
+
+ if ( results ) {
+ results.push.apply( results, array );
+ return results;
+ }
+
+ return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+// Also verifies that the returned array holds DOM nodes
+// (which is not the case in the Blackberry browser)
+try {
+ Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
+
+// Provide a fallback method if it does not work
+} catch( e ) {
+ makeArray = function( array, results ) {
+ var i = 0,
+ ret = results || [];
+
+ if ( toString.call(array) === "[object Array]" ) {
+ Array.prototype.push.apply( ret, array );
+
+ } else {
+ if ( typeof array.length === "number" ) {
+ for ( var l = array.length; i < l; i++ ) {
+ ret.push( array[i] );
+ }
+
+ } else {
+ for ( ; array[i]; i++ ) {
+ ret.push( array[i] );
+ }
+ }
+ }
+
+ return ret;
+ };
+}
+
+var sortOrder, siblingCheck;
+
+if ( document.documentElement.compareDocumentPosition ) {
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
+ return a.compareDocumentPosition ? -1 : 1;
+ }
+
+ return a.compareDocumentPosition(b) & 4 ? -1 : 1;
+ };
+
+} else {
+ sortOrder = function( a, b ) {
+ // The nodes are identical, we can exit early
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+
+ // Fallback to using sourceIndex (in IE) if it's available on both nodes
+ } else if ( a.sourceIndex && b.sourceIndex ) {
+ return a.sourceIndex - b.sourceIndex;
+ }
+
+ var al, bl,
+ ap = [],
+ bp = [],
+ aup = a.parentNode,
+ bup = b.parentNode,
+ cur = aup;
+
+ // If the nodes are siblings (or identical) we can do a quick check
+ if ( aup === bup ) {
+ return siblingCheck( a, b );
+
+ // If no parents were found then the nodes are disconnected
+ } else if ( !aup ) {
+ return -1;
+
+ } else if ( !bup ) {
+ return 1;
+ }
+
+ // Otherwise they're somewhere else in the tree so we need
+ // to build up a full list of the parentNodes for comparison
+ while ( cur ) {
+ ap.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ cur = bup;
+
+ while ( cur ) {
+ bp.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ al = ap.length;
+ bl = bp.length;
+
+ // Start walking down the tree looking for a discrepancy
+ for ( var i = 0; i < al && i < bl; i++ ) {
+ if ( ap[i] !== bp[i] ) {
+ return siblingCheck( ap[i], bp[i] );
+ }
+ }
+
+ // We ended someplace up the tree so do a sibling check
+ return i === al ?
+ siblingCheck( a, bp[i], -1 ) :
+ siblingCheck( ap[i], b, 1 );
+ };
+
+ siblingCheck = function( a, b, ret ) {
+ if ( a === b ) {
+ return ret;
+ }
+
+ var cur = a.nextSibling;
+
+ while ( cur ) {
+ if ( cur === b ) {
+ return -1;
+ }
+
+ cur = cur.nextSibling;
+ }
+
+ return 1;
+ };
+}
+
+// Utility function for retreiving the text value of an array of DOM nodes
+Sizzle.getText = function( elems ) {
+ var ret = "", elem;
+
+ for ( var i = 0; elems[i]; i++ ) {
+ elem = elems[i];
+
+ // Get the text from text nodes and CDATA nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
+ ret += elem.nodeValue;
+
+ // Traverse everything else, except comment nodes
+ } else if ( elem.nodeType !== 8 ) {
+ ret += Sizzle.getText( elem.childNodes );
+ }
+ }
+
+ return ret;
+};
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+ // We're going to inject a fake input element with a specified name
+ var form = document.createElement("div"),
+ id = "script" + (new Date()).getTime(),
+ root = document.documentElement;
+
+ form.innerHTML = "";
+
+ // Inject it into the root element, check its status, and remove it quickly
+ root.insertBefore( form, root.firstChild );
+
+ // The workaround has to do additional checks after a getElementById
+ // Which slows things down for other browsers (hence the branching)
+ if ( document.getElementById( id ) ) {
+ Expr.find.ID = function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+
+ return m ?
+ m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+ [m] :
+ undefined :
+ [];
+ }
+ };
+
+ Expr.filter.ID = function( elem, match ) {
+ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
+ return elem.nodeType === 1 && node && node.nodeValue === match;
+ };
+ }
+
+ root.removeChild( form );
+
+ // release memory in IE
+ root = form = null;
+})();
+
+(function(){
+ // Check to see if the browser returns only elements
+ // when doing getElementsByTagName("*")
+
+ // Create a fake element
+ var div = document.createElement("div");
+ div.appendChild( document.createComment("") );
+
+ // Make sure no comments are found
+ if ( div.getElementsByTagName("*").length > 0 ) {
+ Expr.find.TAG = function( match, context ) {
+ var results = context.getElementsByTagName( match[1] );
+
+ // Filter out possible comments
+ if ( match[1] === "*" ) {
+ var tmp = [];
+
+ for ( var i = 0; results[i]; i++ ) {
+ if ( results[i].nodeType === 1 ) {
+ tmp.push( results[i] );
+ }
+ }
+
+ results = tmp;
+ }
+
+ return results;
+ };
+ }
+
+ // Check to see if an attribute returns normalized href attributes
+ div.innerHTML = "";
+
+ if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+ div.firstChild.getAttribute("href") !== "#" ) {
+
+ Expr.attrHandle.href = function( elem ) {
+ return elem.getAttribute( "href", 2 );
+ };
+ }
+
+ // release memory in IE
+ div = null;
+})();
+
+if ( document.querySelectorAll ) {
+ (function(){
+ var oldSizzle = Sizzle,
+ div = document.createElement("div"),
+ id = "__sizzle__";
+
+ div.innerHTML = "";
+
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode.
+ if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+ return;
+ }
+
+ Sizzle = function( query, context, extra, seed ) {
+ context = context || document;
+
+ // Only use querySelectorAll on non-XML documents
+ // (ID selectors don't work in non-HTML documents)
+ if ( !seed && !Sizzle.isXML(context) ) {
+ // See if we find a selector to speed up
+ var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+ if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+ // Speed-up: Sizzle("TAG")
+ if ( match[1] ) {
+ return makeArray( context.getElementsByTagName( query ), extra );
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+ return makeArray( context.getElementsByClassName( match[2] ), extra );
+ }
+ }
+
+ if ( context.nodeType === 9 ) {
+ // Speed-up: Sizzle("body")
+ // The body element only exists once, optimize finding it
+ if ( query === "body" && context.body ) {
+ return makeArray( [ context.body ], extra );
+
+ // Speed-up: Sizzle("#ID")
+ } else if ( match && match[3] ) {
+ var elem = context.getElementById( match[3] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id === match[3] ) {
+ return makeArray( [ elem ], extra );
+ }
+
+ } else {
+ return makeArray( [], extra );
+ }
+ }
+
+ try {
+ return makeArray( context.querySelectorAll(query), extra );
+ } catch(qsaError) {}
+
+ // qSA works strangely on Element-rooted queries
+ // We can work around this by specifying an extra ID on the root
+ // and working up from there (Thanks to Andrew Dupont for the technique)
+ // IE 8 doesn't work on object elements
+ } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+ var oldContext = context,
+ old = context.getAttribute( "id" ),
+ nid = old || id,
+ hasParent = context.parentNode,
+ relativeHierarchySelector = /^\s*[+~]/.test( query );
+
+ if ( !old ) {
+ context.setAttribute( "id", nid );
+ } else {
+ nid = nid.replace( /'/g, "\\$&" );
+ }
+ if ( relativeHierarchySelector && hasParent ) {
+ context = context.parentNode;
+ }
+
+ try {
+ if ( !relativeHierarchySelector || hasParent ) {
+ return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+ }
+
+ } catch(pseudoError) {
+ } finally {
+ if ( !old ) {
+ oldContext.removeAttribute( "id" );
+ }
+ }
+ }
+ }
+
+ return oldSizzle(query, context, extra, seed);
+ };
+
+ for ( var prop in oldSizzle ) {
+ Sizzle[ prop ] = oldSizzle[ prop ];
+ }
+
+ // release memory in IE
+ div = null;
+ })();
+}
+
+(function(){
+ var html = document.documentElement,
+ matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
+
+ if ( matches ) {
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9 fails this)
+ var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
+ pseudoWorks = false;
+
+ try {
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( document.documentElement, "[test!='']:sizzle" );
+
+ } catch( pseudoError ) {
+ pseudoWorks = true;
+ }
+
+ Sizzle.matchesSelector = function( node, expr ) {
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+ if ( !Sizzle.isXML( node ) ) {
+ try {
+ if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
+ var ret = matches.call( node, expr );
+
+ // IE 9's matchesSelector returns false on disconnected nodes
+ if ( ret || !disconnectedMatch ||
+ // As well, disconnected nodes are said to be in a document
+ // fragment in IE 9, so check for that
+ node.document && node.document.nodeType !== 11 ) {
+ return ret;
+ }
+ }
+ } catch(e) {}
+ }
+
+ return Sizzle(expr, null, null, [node]).length > 0;
+ };
+ }
+})();
+
+(function(){
+ var div = document.createElement("div");
+
+ div.innerHTML = "";
+
+ // Opera can't find a second classname (in 9.6)
+ // Also, make sure that getElementsByClassName actually exists
+ if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
+ return;
+ }
+
+ // Safari caches class attributes, doesn't catch changes (in 3.2)
+ div.lastChild.className = "e";
+
+ if ( div.getElementsByClassName("e").length === 1 ) {
+ return;
+ }
+
+ Expr.order.splice(1, 0, "CLASS");
+ Expr.find.CLASS = function( match, context, isXML ) {
+ if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+ return context.getElementsByClassName(match[1]);
+ }
+ };
+
+ // release memory in IE
+ div = null;
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 && !isXML ){
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( elem.nodeName.toLowerCase() === cur ) {
+ match = elem;
+ break;
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 ) {
+ if ( !isXML ) {
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( typeof cur !== "string" ) {
+ if ( elem === cur ) {
+ match = true;
+ break;
+ }
+
+ } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+ match = elem;
+ break;
+ }
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+if ( document.documentElement.contains ) {
+ Sizzle.contains = function( a, b ) {
+ return a !== b && (a.contains ? a.contains(b) : true);
+ };
+
+} else if ( document.documentElement.compareDocumentPosition ) {
+ Sizzle.contains = function( a, b ) {
+ return !!(a.compareDocumentPosition(b) & 16);
+ };
+
+} else {
+ Sizzle.contains = function() {
+ return false;
+ };
+}
+
+Sizzle.isXML = function( elem ) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+var posProcess = function( selector, context ) {
+ var match,
+ tmpSet = [],
+ later = "",
+ root = context.nodeType ? [context] : context;
+
+ // Position selectors must be done after the filter
+ // And so must :not(positional) so we move all PSEUDOs to the end
+ while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+ later += match[0];
+ selector = selector.replace( Expr.match.PSEUDO, "" );
+ }
+
+ selector = Expr.relative[selector] ? selector + "*" : selector;
+
+ for ( var i = 0, l = root.length; i < l; i++ ) {
+ Sizzle( selector, root[i], tmpSet );
+ }
+
+ return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})();
+
+
+var runtil = /Until$/,
+ rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+ // Note: This RegExp should be improved, or likely pulled from Sizzle
+ rmultiselector = /,/,
+ isSimple = /^.[^:#\[\.,]*$/,
+ slice = Array.prototype.slice,
+ POS = jQuery.expr.match.POS,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var self = this,
+ i, l;
+
+ if ( typeof selector !== "string" ) {
+ return jQuery( selector ).filter(function() {
+ for ( i = 0, l = self.length; i < l; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ });
+ }
+
+ var ret = this.pushStack( "", "find", selector ),
+ length, n, r;
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ length = ret.length;
+ jQuery.find( selector, this[i], ret );
+
+ if ( i > 0 ) {
+ // Make sure that the results are unique
+ for ( n = length; n < ret.length; n++ ) {
+ for ( r = 0; r < length; r++ ) {
+ if ( ret[r] === ret[n] ) {
+ ret.splice(n--, 1);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ has: function( target ) {
+ var targets = jQuery( target );
+ return this.filter(function() {
+ for ( var i = 0, l = targets.length; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector, false), "not", selector);
+ },
+
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector, true), "filter", selector );
+ },
+
+ is: function( selector ) {
+ return !!selector && ( typeof selector === "string" ?
+ jQuery.filter( selector, this ).length > 0 :
+ this.filter( selector ).length > 0 );
+ },
+
+ closest: function( selectors, context ) {
+ var ret = [], i, l, cur = this[0];
+
+ // Array
+ if ( jQuery.isArray( selectors ) ) {
+ var match, selector,
+ matches = {},
+ level = 1;
+
+ if ( cur && selectors.length ) {
+ for ( i = 0, l = selectors.length; i < l; i++ ) {
+ selector = selectors[i];
+
+ if ( !matches[ selector ] ) {
+ matches[ selector ] = POS.test( selector ) ?
+ jQuery( selector, context || this.context ) :
+ selector;
+ }
+ }
+
+ while ( cur && cur.ownerDocument && cur !== context ) {
+ for ( selector in matches ) {
+ match = matches[ selector ];
+
+ if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
+ ret.push({ selector: selector, elem: cur, level: level });
+ }
+ }
+
+ cur = cur.parentNode;
+ level++;
+ }
+ }
+
+ return ret;
+ }
+
+ // String
+ var pos = POS.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ cur = this[i];
+
+ while ( cur ) {
+ if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
+ ret.push( cur );
+ break;
+
+ } else {
+ cur = cur.parentNode;
+ if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
+ break;
+ }
+ }
+ }
+ }
+
+ ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
+
+ return this.pushStack( ret, "closest", selectors );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
+ }
+
+ // index in selector
+ if ( typeof elem === "string" ) {
+ return jQuery.inArray( this[0], jQuery( elem ) );
+ }
+
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[0] : elem, this );
+ },
+
+ add: function( selector, context ) {
+ var set = typeof selector === "string" ?
+ jQuery( selector, context ) :
+ jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+ all = jQuery.merge( this.get(), set );
+
+ return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
+ all :
+ jQuery.unique( all ) );
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ }
+});
+
+// A painfully simple check to see if an element is disconnected
+// from a document (should be improved, where feasible).
+function isDisconnected( node ) {
+ return !node || !node.parentNode || node.parentNode.nodeType === 11;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return jQuery.nth( elem, 2, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return jQuery.nth( elem, 2, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( elem.parentNode.firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.makeArray( elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var ret = jQuery.map( this, fn, until ),
+ // The variable 'args' was introduced in
+ // https://github.com/jquery/jquery/commit/52a0238
+ // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+ // http://code.google.com/p/v8/issues/detail?id=1050
+ args = slice.call(arguments);
+
+ if ( !runtil.test( name ) ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ ret = jQuery.filter( selector, ret );
+ }
+
+ ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
+
+ if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
+ ret = ret.reverse();
+ }
+
+ return this.pushStack( ret, name, args.join(",") );
+ };
+});
+
+jQuery.extend({
+ filter: function( expr, elems, not ) {
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 ?
+ jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
+ jQuery.find.matches(expr, elems);
+ },
+
+ dir: function( elem, dir, until ) {
+ var matched = [],
+ cur = elem[ dir ];
+
+ while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+ if ( cur.nodeType === 1 ) {
+ matched.push( cur );
+ }
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ nth: function( cur, result, dir, elem ) {
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] ) {
+ if ( cur.nodeType === 1 && ++num === result ) {
+ break;
+ }
+ }
+
+ return cur;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ r.push( n );
+ }
+ }
+
+ return r;
+ }
+});
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, keep ) {
+
+ // Can't pass null or undefined to indexOf in Firefox 4
+ // Set to 0 to skip string check
+ qualifier = qualifier || 0;
+
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ var retVal = !!qualifier.call( elem, i, elem );
+ return retVal === keep;
+ });
+
+ } else if ( qualifier.nodeType ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ return (elem === qualifier) === keep;
+ });
+
+ } else if ( typeof qualifier === "string" ) {
+ var filtered = jQuery.grep(elements, function( elem ) {
+ return elem.nodeType === 1;
+ });
+
+ if ( isSimple.test( qualifier ) ) {
+ return jQuery.filter(qualifier, filtered, !keep);
+ } else {
+ qualifier = jQuery.filter( qualifier, filtered );
+ }
+ }
+
+ return jQuery.grep(elements, function( elem, i ) {
+ return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
+ });
+}
+
+
+
+
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+ rleadingWhitespace = /^\s+/,
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
+ rtagName = /<([\w:]+)/,
+ rtbody = /", "" ],
+ legend: [ 1, "" ],
+ thead: [ 1, "
Javascript library for localised formatting and parsing of:
+ *
+ *
Numbers
+ *
Dates and times
+ *
Currency
+ *
+ *
+ *
The library classes are configured with standard POSIX locale definitions
+ * derived from Unicode's Common Locale Data Repository (CLDR).
+ *
+ *
Website: JsWorld
+ *
+ * @author Vladimir Dzhuvinov
+ * @version 2.5 (2011-12-23)
+ */
+
+
+
+/**
+ * @namespace Namespace container for the JsWorld library objects.
+ */
+jsworld = {};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 date/time
+ * string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the
+ * current date/time will be used.
+ * @param {Boolean} [withTZ] Include timezone offset, default false.
+ *
+ * @returns {String} The date/time formatted as YYYY-MM-DD HH:MM:SS.
+ */
+jsworld.formatIsoDateTime = function(d, withTZ) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ if (typeof withTZ === "undefined")
+ withTZ = false;
+
+ var s = jsworld.formatIsoDate(d) + " " + jsworld.formatIsoTime(d);
+
+ if (withTZ) {
+
+ var diff = d.getHours() - d.getUTCHours();
+ var hourDiff = Math.abs(diff);
+
+ var minuteUTC = d.getUTCMinutes();
+ var minute = d.getMinutes();
+
+ if (minute != minuteUTC && minuteUTC < 30 && diff < 0)
+ hourDiff--;
+
+ if (minute != minuteUTC && minuteUTC > 30 && diff > 0)
+ hourDiff--;
+
+ var minuteDiff;
+ if (minute != minuteUTC)
+ minuteDiff = ":30";
+ else
+ minuteDiff = ":00";
+
+ var timezone;
+ if (hourDiff < 10)
+ timezone = "0" + hourDiff + minuteDiff;
+
+ else
+ timezone = "" + hourDiff + minuteDiff;
+
+ if (diff < 0)
+ timezone = "-" + timezone;
+
+ else
+ timezone = "+" + timezone;
+
+ s = s + timezone;
+ }
+
+ return s;
+};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 date string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the current
+ * date will be used.
+ *
+ * @returns {String} The date formatted as YYYY-MM-DD.
+ */
+jsworld.formatIsoDate = function(d) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ var year = d.getFullYear();
+ var month = d.getMonth() + 1;
+ var day = d.getDate();
+
+ return year + "-" + jsworld._zeroPad(month, 2) + "-" + jsworld._zeroPad(day, 2);
+};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 time string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the current
+ * time will be used.
+ *
+ * @returns {String} The time formatted as HH:MM:SS.
+ */
+jsworld.formatIsoTime = function(d) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ var hour = d.getHours();
+ var minute = d.getMinutes();
+ var second = d.getSeconds();
+
+ return jsworld._zeroPad(hour, 2) + ":" + jsworld._zeroPad(minute, 2) + ":" + jsworld._zeroPad(second, 2);
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted date/time string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoDateTimeVal An ISO-8601 formatted date/time string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
YYYY-MM-DD HH:MM:SS
+ *
YYYYMMDD HHMMSS
+ *
YYYY-MM-DD HHMMSS
+ *
YYYYMMDD HH:MM:SS
+ *
+ *
+ * @returns {Date} The corresponding Date object.
+ *
+ * @throws Error on a badly formatted date/time string or on a invalid date.
+ */
+jsworld.parseIsoDateTime = function(isoDateTimeVal) {
+
+ if (typeof isoDateTimeVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "YYYY-MM-DD HH:MM:SS" format
+ var matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)/);
+
+ // If unsuccessful, try to match "YYYYMMDD HHMMSS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)(\d\d)(\d\d)[T ](\d\d)(\d\d)(\d\d)/);
+
+ // ... try to match "YYYY-MM-DD HHMMSS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d)(\d\d)(\d\d)/);
+
+ // ... try to match "YYYYMMDD HH:MM:SS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date/time string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var year = parseInt(matches[1], 10);
+ var month = parseInt(matches[2], 10);
+ var day = parseInt(matches[3], 10);
+
+ var hour = parseInt(matches[4], 10);
+ var mins = parseInt(matches[5], 10);
+ var secs = parseInt(matches[6], 10);
+
+ // Simple value range check, leap years not checked
+ // Note: the originial ISO time spec for leap hours (24:00:00) and seconds (00:00:60) is not supported
+ if (month < 1 || month > 12 ||
+ day < 1 || day > 31 ||
+ hour < 0 || hour > 23 ||
+ mins < 0 || mins > 59 ||
+ secs < 0 || secs > 59 )
+
+ throw "Error: Invalid ISO-8601 date/time value";
+
+ var d = new Date(year, month - 1, day, hour, mins, secs);
+
+ // Check if the input date was valid
+ // (JS Date does automatic forward correction)
+ if (d.getDate() != day || d.getMonth() +1 != month)
+ throw "Error: Invalid date";
+
+ return d;
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted date string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoDateVal An ISO-8601 formatted date string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
YYYY-MM-DD
+ *
YYYYMMDD
+ *
+ *
+ * @returns {Date} The corresponding Date object.
+ *
+ * @throws Error on a badly formatted date string or on a invalid date.
+ */
+jsworld.parseIsoDate = function(isoDateVal) {
+
+ if (typeof isoDateVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "YYYY-MM-DD" format
+ var matches = isoDateVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/);
+
+ // If unsuccessful, try to match "YYYYMMDD" format
+ if (matches === null)
+ matches = isoDateVal.match(/^(\d\d\d\d)(\d\d)(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var year = parseInt(matches[1], 10);
+ var month = parseInt(matches[2], 10);
+ var day = parseInt(matches[3], 10);
+
+ // Simple value range check, leap years not checked
+ if (month < 1 || month > 12 ||
+ day < 1 || day > 31 )
+
+ throw "Error: Invalid ISO-8601 date value";
+
+ var d = new Date(year, month - 1, day);
+
+ // Check if the input date was valid
+ // (JS Date does automatic forward correction)
+ if (d.getDate() != day || d.getMonth() +1 != month)
+ throw "Error: Invalid date";
+
+ return d;
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted time string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoTimeVal An ISO-8601 formatted time string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
HH:MM:SS
+ *
HHMMSS
+ *
+ *
+ * @returns {Date} The corresponding Date object, with year, month and day set
+ * to zero.
+ *
+ * @throws Error on a badly formatted time string.
+ */
+jsworld.parseIsoTime = function(isoTimeVal) {
+
+ if (typeof isoTimeVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "HH:MM:SS" format
+ var matches = isoTimeVal.match(/^(\d\d):(\d\d):(\d\d)/);
+
+ // If unsuccessful, try to match "HHMMSS" format
+ if (matches === null)
+ matches = isoTimeVal.match(/^(\d\d)(\d\d)(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date/time string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var hour = parseInt(matches[1], 10);
+ var mins = parseInt(matches[2], 10);
+ var secs = parseInt(matches[3], 10);
+
+ // Simple value range check, leap years not checked
+ if (hour < 0 || hour > 23 ||
+ mins < 0 || mins > 59 ||
+ secs < 0 || secs > 59 )
+
+ throw "Error: Invalid ISO-8601 time value";
+
+ return new Date(0, 0, 0, hour, mins, secs);
+};
+
+
+/**
+ * @private
+ *
+ * @description Trims leading and trailing whitespace from a string.
+ *
+ *
Used non-regexp the method from http://blog.stevenlevithan.com/archives/faster-trim-javascript
+ *
+ * @param {String} str The string to trim.
+ *
+ * @returns {String} The trimmed string.
+ */
+jsworld._trim = function(str) {
+
+ var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
+
+ for (var i = 0; i < str.length; i++) {
+
+ if (whitespace.indexOf(str.charAt(i)) === -1) {
+ str = str.substring(i);
+ break;
+ }
+ }
+
+ for (i = str.length - 1; i >= 0; i--) {
+ if (whitespace.indexOf(str.charAt(i)) === -1) {
+ str = str.substring(0, i + 1);
+ break;
+ }
+ }
+
+ return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
+};
+
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal number.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents a decimal number,
+ * otherwise false.
+ */
+jsworld._isNumber = function(arg) {
+
+ if (typeof arg == "number")
+ return true;
+
+ if (typeof arg != "string")
+ return false;
+
+ // ensure string
+ var s = arg + "";
+
+ return (/^-?(\d+|\d*\.\d+)$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal integer.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents an integer, otherwise
+ * false.
+ */
+jsworld._isInteger = function(arg) {
+
+ if (typeof arg != "number" && typeof arg != "string")
+ return false;
+
+ // convert to string
+ var s = arg + "";
+
+ return (/^-?\d+$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal float.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents a float, otherwise false.
+ */
+jsworld._isFloat = function(arg) {
+
+ if (typeof arg != "number" && typeof arg != "string")
+ return false;
+
+ // convert to string
+ var s = arg + "";
+
+ return (/^-?\.\d+?$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Checks if the specified formatting option is contained
+ * within the options string.
+ *
+ * @param {String} option The option to search for.
+ * @param {String} optionsString The options string.
+ *
+ * @returns {Boolean} true if the flag is found, else false
+ */
+jsworld._hasOption = function(option, optionsString) {
+
+ if (typeof option != "string" || typeof optionsString != "string")
+ return false;
+
+ if (optionsString.indexOf(option) != -1)
+ return true;
+ else
+ return false;
+};
+
+
+/**
+ * @private
+ *
+ * @description String replacement function.
+ *
+ * @param {String} s The string to work on.
+ * @param {String} target The string to search for.
+ * @param {String} replacement The replacement.
+ *
+ * @returns {String} The new string.
+ */
+jsworld._stringReplaceAll = function(s, target, replacement) {
+
+ var out;
+
+ if (target.length == 1 && replacement.length == 1) {
+ // simple char/char case somewhat faster
+ out = "";
+
+ for (var i = 0; i < s.length; i++) {
+
+ if (s.charAt(i) == target.charAt(0))
+ out = out + replacement.charAt(0);
+ else
+ out = out + s.charAt(i);
+ }
+
+ return out;
+ }
+ else {
+ // longer target and replacement strings
+ out = s;
+
+ var index = out.indexOf(target);
+
+ while (index != -1) {
+
+ out = out.replace(target, replacement);
+
+ index = out.indexOf(target);
+ }
+
+ return out;
+ }
+};
+
+
+/**
+ * @private
+ *
+ * @description Tests if a string starts with the specified substring.
+ *
+ * @param {String} testedString The string to test.
+ * @param {String} sub The string to match.
+ *
+ * @returns {Boolean} true if the test succeeds.
+ */
+jsworld._stringStartsWith = function (testedString, sub) {
+
+ if (testedString.length < sub.length)
+ return false;
+
+ for (var i = 0; i < sub.length; i++) {
+ if (testedString.charAt(i) != sub.charAt(i))
+ return false;
+ }
+
+ return true;
+};
+
+
+/**
+ * @private
+ *
+ * @description Gets the requested precision from an options string.
+ *
+ *
Example: ".3" returns 3 decimal places precision.
+ *
+ * @param {String} optionsString The options string.
+ *
+ * @returns {integer Number} The requested precision, -1 if not specified.
+ */
+jsworld._getPrecision = function (optionsString) {
+
+ if (typeof optionsString != "string")
+ return -1;
+
+ var m = optionsString.match(/\.(\d)/);
+ if (m)
+ return parseInt(m[1], 10);
+ else
+ return -1;
+};
+
+
+/**
+ * @private
+ *
+ * @description Takes a decimal numeric amount (optionally as string) and
+ * returns its integer and fractional parts packed into an object.
+ *
+ * @param {Number|String} amount The amount, e.g. "123.45" or "-56.78"
+ *
+ * @returns {object} Parsed amount object with properties:
+ * {String} integer : the integer part
+ * {String} fraction : the fraction part
+ */
+jsworld._splitNumber = function (amount) {
+
+ if (typeof amount == "number")
+ amount = amount + "";
+
+ var obj = {};
+
+ // remove negative sign
+ if (amount.charAt(0) == "-")
+ amount = amount.substring(1);
+
+ // split amount into integer and decimal parts
+ var amountParts = amount.split(".");
+ if (!amountParts[1])
+ amountParts[1] = ""; // we need "" instead of null
+
+ obj.integer = amountParts[0];
+ obj.fraction = amountParts[1];
+
+ return obj;
+};
+
+
+/**
+ * @private
+ *
+ * @description Formats the integer part using the specified grouping
+ * and thousands separator.
+ *
+ * @param {String} intPart The integer part of the amount, as string.
+ * @param {String} grouping The grouping definition.
+ * @param {String} thousandsSep The thousands separator.
+ *
+ * @returns {String} The formatted integer part.
+ */
+jsworld._formatIntegerPart = function (intPart, grouping, thousandsSep) {
+
+ // empty separator string? no grouping?
+ // -> return immediately with no formatting!
+ if (thousandsSep == "" || grouping == "-1")
+ return intPart;
+
+ // turn the semicolon-separated string of integers into an array
+ var groupSizes = grouping.split(";");
+
+ // the formatted output string
+ var out = "";
+
+ // the intPart string position to process next,
+ // start at string end, e.g. "10000000 0) {
+
+ // get next group size (if any, otherwise keep last)
+ if (groupSizes.length > 0)
+ size = parseInt(groupSizes.shift(), 10);
+
+ // int parse error?
+ if (isNaN(size))
+ throw "Error: Invalid grouping";
+
+ // size is -1? -> no more grouping, so just copy string remainder
+ if (size == -1) {
+ out = intPart.substring(0, pos) + out;
+ break;
+ }
+
+ pos -= size; // move to next sep. char. position
+
+ // position underrun? -> just copy string remainder
+ if (pos < 1) {
+ out = intPart.substring(0, pos + size) + out;
+ break;
+ }
+
+ // extract group and apply sep. char.
+ out = thousandsSep + intPart.substring(pos, pos + size) + out;
+ }
+
+ return out;
+};
+
+
+/**
+ * @private
+ *
+ * @description Formats the fractional part to the specified decimal
+ * precision.
+ *
+ * @param {String} fracPart The fractional part of the amount
+ * @param {integer Number} precision The desired decimal precision
+ *
+ * @returns {String} The formatted fractional part.
+ */
+jsworld._formatFractionPart = function (fracPart, precision) {
+
+ // append zeroes up to precision if necessary
+ for (var i=0; fracPart.length < precision; i++)
+ fracPart = fracPart + "0";
+
+ return fracPart;
+};
+
+
+/**
+ * @private
+ *
+ * @desription Converts a number to string and pad it with leading zeroes if the
+ * string is shorter than length.
+ *
+ * @param {integer Number} number The number value subjected to selective padding.
+ * @param {integer Number} length If the number has fewer digits than this length
+ * apply padding.
+ *
+ * @returns {String} The formatted string.
+ */
+jsworld._zeroPad = function(number, length) {
+
+ // ensure string
+ var s = number + "";
+
+ while (s.length < length)
+ s = "0" + s;
+
+ return s;
+};
+
+
+/**
+ * @private
+ * @description Converts a number to string and pads it with leading spaces if
+ * the string is shorter than length.
+ *
+ * @param {integer Number} number The number value subjected to selective padding.
+ * @param {integer Number} length If the number has fewer digits than this length
+ * apply padding.
+ *
+ * @returns {String} The formatted string.
+ */
+jsworld._spacePad = function(number, length) {
+
+ // ensure string
+ var s = number + "";
+
+ while (s.length < length)
+ s = " " + s;
+
+ return s;
+};
+
+
+
+/**
+ * @class
+ * Represents a POSIX-style locale with its numeric, monetary and date/time
+ * properties. Also provides a set of locale helper methods.
+ *
+ *
The locale properties follow the POSIX standards:
+ *
+ *
+ *
+ * @public
+ * @constructor
+ * @description Creates a new locale object (POSIX-style) with the specified
+ * properties.
+ *
+ * @param {object} properties An object containing the raw locale properties:
+ *
+ * @param {String} properties.decimal_point
+ *
+ * A string containing the symbol that shall be used as the decimal
+ * delimiter (radix character) in numeric, non-monetary formatted
+ * quantities. This property cannot be omitted and cannot be set to the
+ * empty string.
+ *
+ *
+ * @param {String} properties.thousands_sep
+ *
+ * A string containing the symbol that shall be used as a separator for
+ * groups of digits to the left of the decimal delimiter in numeric,
+ * non-monetary formatted monetary quantities.
+ *
+ *
+ * @param {String} properties.grouping
+ *
+ * Defines the size of each group of digits in formatted non-monetary
+ * quantities. The operand is a sequence of integers separated by
+ * semicolons. Each integer specifies the number of digits in each group,
+ * with the initial integer defining the size of the group immediately
+ * preceding the decimal delimiter, and the following integers defining
+ * the preceding groups. If the last integer is not -1, then the size of
+ * the previous group (if any) shall be repeatedly used for the
+ * remainder of the digits. If the last integer is -1, then no further
+ * grouping shall be performed.
+ *
+ *
+ * @param {String} properties.int_curr_symbol
+ *
+ * The first three letters signify the ISO-4217 currency code,
+ * the fourth letter is the international symbol separation character
+ * (normally a space).
+ *
+ *
+ * @param {String} properties.currency_symbol
+ *
+ * The local shorthand currency symbol, e.g. "$" for the en_US locale
+ *
+ *
+ * @param {String} properties.mon_decimal_point
+ *
+ * The symbol to be used as the decimal delimiter (radix character)
+ *
+ *
+ * @param {String} properties.mon_thousands_sep
+ *
+ * The symbol to be used as a separator for groups of digits to the
+ * left of the decimal delimiter.
+ *
+ *
+ * @param {String} properties.mon_grouping
+ *
+ * A string that defines the size of each group of digits. The
+ * operand is a sequence of integers separated by semicolons (";").
+ * Each integer specifies the number of digits in each group, with the
+ * initial integer defining the size of the group preceding the
+ * decimal delimiter, and the following integers defining the
+ * preceding groups. If the last integer is not -1, then the size of
+ * the previous group (if any) must be repeatedly used for the
+ * remainder of the digits. If the last integer is -1, then no
+ * further grouping is to be performed.
+ *
+ *
+ * @param {String} properties.positive_sign
+ *
+ * The string to indicate a non-negative monetary amount.
+ *
+ *
+ * @param {String} properties.negative_sign
+ *
+ * The string to indicate a negative monetary amount.
+ *
+ *
+ * @param {integer Number} properties.frac_digits
+ *
+ * An integer representing the number of fractional digits (those to
+ * the right of the decimal delimiter) to be written in a formatted
+ * monetary quantity using currency_symbol.
+ *
+ *
+ * @param {integer Number} properties.int_frac_digits
+ *
+ * An integer representing the number of fractional digits (those to
+ * the right of the decimal delimiter) to be written in a formatted
+ * monetary quantity using int_curr_symbol.
+ *
+ *
+ * @param {integer Number} properties.p_cs_precedes
+ *
+ * An integer set to 1 if the currency_symbol precedes the value for a
+ * monetary quantity with a non-negative value, and set to 0 if the
+ * symbol succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.n_cs_precedes
+ *
+ * An integer set to 1 if the currency_symbol precedes the value for a
+ * monetary quantity with a negative value, and set to 0 if the symbol
+ * succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.p_sep_by_space
+ *
+ * Set to a value indicating the separation of the currency_symbol,
+ * the sign string, and the value for a non-negative formatted monetary
+ * quantity:
+ *
+ *
0 No space separates the currency symbol and value.
+ *
+ *
1 If the currency symbol and sign string are adjacent, a space
+ * separates them from the value; otherwise, a space separates
+ * the currency symbol from the value.
+ *
+ *
2 If the currency symbol and sign string are adjacent, a space
+ * separates them; otherwise, a space separates the sign string
+ * from the value.
+ *
+ *
+ * @param {integer Number} properties.n_sep_by_space
+ *
+ * Set to a value indicating the separation of the currency_symbol,
+ * the sign string, and the value for a negative formatted monetary
+ * quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.p_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * positive_sign for a monetary quantity with a non-negative value:
+ *
+ *
0 Parentheses enclose the quantity and the currency_symbol.
+ *
+ *
1 The sign string precedes the quantity and the currency_symbol.
+ *
+ *
2 The sign string succeeds the quantity and the currency_symbol.
+ *
+ *
3 The sign string precedes the currency_symbol.
+ *
+ *
4 The sign string succeeds the currency_symbol.
+ *
+ *
+ * @param {integer Number} properties.n_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * negative_sign for a negative formatted monetary quantity. Rules same
+ * as for p_sign_posn.
+ *
+ *
+ * @param {integer Number} properties.int_p_cs_precedes
+ *
+ * An integer set to 1 if the int_curr_symbol precedes the value for a
+ * monetary quantity with a non-negative value, and set to 0 if the
+ * symbol succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.int_n_cs_precedes
+ *
+ * An integer set to 1 if the int_curr_symbol precedes the value for a
+ * monetary quantity with a negative value, and set to 0 if the symbol
+ * succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.int_p_sep_by_space
+ *
+ * Set to a value indicating the separation of the int_curr_symbol,
+ * the sign string, and the value for a non-negative internationally
+ * formatted monetary quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.int_n_sep_by_space
+ *
+ * Set to a value indicating the separation of the int_curr_symbol,
+ * the sign string, and the value for a negative internationally
+ * formatted monetary quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.int_p_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * positive_sign for a positive monetary quantity formatted with the
+ * international format. Rules same as for p_sign_posn.
+ *
+ *
+ * @param {integer Number} properties.int_n_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * negative_sign for a negative monetary quantity formatted with the
+ * international format. Rules same as for p_sign_posn.
+ *
+ *
+ * @param {String[] | String} properties.abday
+ *
+ * The abbreviated weekday names, corresponding to the %a conversion
+ * specification. The property must be either an array of 7 strings or
+ * a string consisting of 7 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the abbreviated name
+ * of the day corresponding to Sunday, the second the abbreviated name
+ * of the day corresponding to Monday, and so on.
+ *
+ *
+ * @param {String[] | String} properties.day
+ *
+ * The full weekday names, corresponding to the %A conversion
+ * specification. The property must be either an array of 7 strings or
+ * a string consisting of 7 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the full name of the
+ * day corresponding to Sunday, the second the full name of the day
+ * corresponding to Monday, and so on.
+ *
+ *
+ * @param {String[] | String} properties.abmon
+ *
+ * The abbreviated month names, corresponding to the %b conversion
+ * specification. The property must be either an array of 12 strings or
+ * a string consisting of 12 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the abbreviated name
+ * of the first month of the year (January), the second the abbreviated
+ * name of the second month, and so on.
+ *
+ *
+ * @param {String[] | String} properties.mon
+ *
+ * The full month names, corresponding to the %B conversion
+ * specification. The property must be either an array of 12 strings or
+ * a string consisting of 12 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the full name of the
+ * first month of the year (January), the second the full name of the second
+ * month, and so on.
+ *
+ *
+ * @param {String} properties.d_fmt
+ *
+ * The appropriate date representation. The string may contain any
+ * combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String} properties.t_fmt
+ *
+ * The appropriate time representation. The string may contain any
+ * combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String} properties.d_t_fmt
+ *
+ * The appropriate date and time representation. The string may contain
+ * any combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String[] | String} properties.am_pm
+ *
+ * The appropriate representation of the ante-meridiem and post-meridiem
+ * strings, corresponding to the %p conversion specification. The property
+ * must be either an array of 2 strings or a string consisting of 2
+ * semicolon-separated substrings, each surrounded by double-quotes.
+ * The first string must represent the ante-meridiem designation, the
+ * last string the post-meridiem designation.
+ *
+ *
+ * @throws @throws Error on a undefined or invalid locale property.
+ */
+jsworld.Locale = function(properties) {
+
+
+ /**
+ * @private
+ *
+ * @description Identifies the class for internal library purposes.
+ */
+ this._className = "jsworld.Locale";
+
+
+ /**
+ * @private
+ *
+ * @description Parses a day or month name definition list, which
+ * could be a ready JS array, e.g. ["Mon", "Tue", "Wed"...] or
+ * it could be a string formatted according to the classic POSIX
+ * definition e.g. "Mon";"Tue";"Wed";...
+ *
+ * @param {String[] | String} namesAn array or string defining
+ * the week/month names.
+ * @param {integer Number} expectedItems The number of expected list
+ * items, e.g. 7 for weekdays, 12 for months.
+ *
+ * @returns {String[]} The parsed (and checked) items.
+ *
+ * @throws Error on missing definition, unexpected item count or
+ * missing double-quotes.
+ */
+ this._parseList = function(names, expectedItems) {
+
+ var array = [];
+
+ if (names == null) {
+ throw "Names not defined";
+ }
+ else if (typeof names == "object") {
+ // we got a ready array
+ array = names;
+ }
+ else if (typeof names == "string") {
+ // we got the names in the classic POSIX form, do parse
+ array = names.split(";", expectedItems);
+
+ for (var i = 0; i < array.length; i++) {
+ // check for and strip double quotes
+ if (array[i][0] == "\"" && array[i][array[i].length - 1] == "\"")
+ array[i] = array[i].slice(1, -1);
+ else
+ throw "Missing double quotes";
+ }
+ }
+ else {
+ throw "Names must be an array or a string";
+ }
+
+ if (array.length != expectedItems)
+ throw "Expected " + expectedItems + " items, got " + array.length;
+
+ return array;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Validates a date/time format string, such as "H:%M:%S".
+ * Checks that the argument is of type "string" and is not empty.
+ *
+ * @param {String} formatString The format string.
+ *
+ * @returns {String} The validated string.
+ *
+ * @throws Error on null or empty string.
+ */
+ this._validateFormatString = function(formatString) {
+
+ if (typeof formatString == "string" && formatString.length > 0)
+ return formatString;
+ else
+ throw "Empty or no string";
+ };
+
+
+ // LC_NUMERIC
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing locale properties";
+
+
+ if (typeof properties.decimal_point != "string")
+ throw "Error: Invalid/missing decimal_point property";
+
+ this.decimal_point = properties.decimal_point;
+
+
+ if (typeof properties.thousands_sep != "string")
+ throw "Error: Invalid/missing thousands_sep property";
+
+ this.thousands_sep = properties.thousands_sep;
+
+
+ if (typeof properties.grouping != "string")
+ throw "Error: Invalid/missing grouping property";
+
+ this.grouping = properties.grouping;
+
+
+ // LC_MONETARY
+
+ if (typeof properties.int_curr_symbol != "string")
+ throw "Error: Invalid/missing int_curr_symbol property";
+
+ if (! /[A-Za-z]{3}.?/.test(properties.int_curr_symbol))
+ throw "Error: Invalid int_curr_symbol property";
+
+ this.int_curr_symbol = properties.int_curr_symbol;
+
+
+ if (typeof properties.currency_symbol != "string")
+ throw "Error: Invalid/missing currency_symbol property";
+
+ this.currency_symbol = properties.currency_symbol;
+
+
+ if (typeof properties.frac_digits != "number" && properties.frac_digits < 0)
+ throw "Error: Invalid/missing frac_digits property";
+
+ this.frac_digits = properties.frac_digits;
+
+
+ // may be empty string/null for currencies with no fractional part
+ if (properties.mon_decimal_point === null || properties.mon_decimal_point == "") {
+
+ if (this.frac_digits > 0)
+ throw "Error: Undefined mon_decimal_point property";
+ else
+ properties.mon_decimal_point = "";
+ }
+
+ if (typeof properties.mon_decimal_point != "string")
+ throw "Error: Invalid/missing mon_decimal_point property";
+
+ this.mon_decimal_point = properties.mon_decimal_point;
+
+
+ if (typeof properties.mon_thousands_sep != "string")
+ throw "Error: Invalid/missing mon_thousands_sep property";
+
+ this.mon_thousands_sep = properties.mon_thousands_sep;
+
+
+ if (typeof properties.mon_grouping != "string")
+ throw "Error: Invalid/missing mon_grouping property";
+
+ this.mon_grouping = properties.mon_grouping;
+
+
+ if (typeof properties.positive_sign != "string")
+ throw "Error: Invalid/missing positive_sign property";
+
+ this.positive_sign = properties.positive_sign;
+
+
+ if (typeof properties.negative_sign != "string")
+ throw "Error: Invalid/missing negative_sign property";
+
+ this.negative_sign = properties.negative_sign;
+
+
+
+ if (properties.p_cs_precedes !== 0 && properties.p_cs_precedes !== 1)
+ throw "Error: Invalid/missing p_cs_precedes property, must be 0 or 1";
+
+ this.p_cs_precedes = properties.p_cs_precedes;
+
+
+ if (properties.n_cs_precedes !== 0 && properties.n_cs_precedes !== 1)
+ throw "Error: Invalid/missing n_cs_precedes, must be 0 or 1";
+
+ this.n_cs_precedes = properties.n_cs_precedes;
+
+
+ if (properties.p_sep_by_space !== 0 &&
+ properties.p_sep_by_space !== 1 &&
+ properties.p_sep_by_space !== 2)
+ throw "Error: Invalid/missing p_sep_by_space property, must be 0, 1 or 2";
+
+ this.p_sep_by_space = properties.p_sep_by_space;
+
+
+ if (properties.n_sep_by_space !== 0 &&
+ properties.n_sep_by_space !== 1 &&
+ properties.n_sep_by_space !== 2)
+ throw "Error: Invalid/missing n_sep_by_space property, must be 0, 1, or 2";
+
+ this.n_sep_by_space = properties.n_sep_by_space;
+
+
+ if (properties.p_sign_posn !== 0 &&
+ properties.p_sign_posn !== 1 &&
+ properties.p_sign_posn !== 2 &&
+ properties.p_sign_posn !== 3 &&
+ properties.p_sign_posn !== 4)
+ throw "Error: Invalid/missing p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.p_sign_posn = properties.p_sign_posn;
+
+
+ if (properties.n_sign_posn !== 0 &&
+ properties.n_sign_posn !== 1 &&
+ properties.n_sign_posn !== 2 &&
+ properties.n_sign_posn !== 3 &&
+ properties.n_sign_posn !== 4)
+ throw "Error: Invalid/missing n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.n_sign_posn = properties.n_sign_posn;
+
+
+ if (typeof properties.int_frac_digits != "number" && properties.int_frac_digits < 0)
+ throw "Error: Invalid/missing int_frac_digits property";
+
+ this.int_frac_digits = properties.int_frac_digits;
+
+
+ if (properties.int_p_cs_precedes !== 0 && properties.int_p_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_p_cs_precedes property, must be 0 or 1";
+
+ this.int_p_cs_precedes = properties.int_p_cs_precedes;
+
+
+ if (properties.int_n_cs_precedes !== 0 && properties.int_n_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_n_cs_precedes property, must be 0 or 1";
+
+ this.int_n_cs_precedes = properties.int_n_cs_precedes;
+
+
+ if (properties.int_p_sep_by_space !== 0 &&
+ properties.int_p_sep_by_space !== 1 &&
+ properties.int_p_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_p_sep_by_spacev, must be 0, 1 or 2";
+
+ this.int_p_sep_by_space = properties.int_p_sep_by_space;
+
+
+ if (properties.int_n_sep_by_space !== 0 &&
+ properties.int_n_sep_by_space !== 1 &&
+ properties.int_n_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_n_sep_by_space property, must be 0, 1, or 2";
+
+ this.int_n_sep_by_space = properties.int_n_sep_by_space;
+
+
+ if (properties.int_p_sign_posn !== 0 &&
+ properties.int_p_sign_posn !== 1 &&
+ properties.int_p_sign_posn !== 2 &&
+ properties.int_p_sign_posn !== 3 &&
+ properties.int_p_sign_posn !== 4)
+ throw "Error: Invalid/missing int_p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_p_sign_posn = properties.int_p_sign_posn;
+
+
+ if (properties.int_n_sign_posn !== 0 &&
+ properties.int_n_sign_posn !== 1 &&
+ properties.int_n_sign_posn !== 2 &&
+ properties.int_n_sign_posn !== 3 &&
+ properties.int_n_sign_posn !== 4)
+ throw "Error: Invalid/missing int_n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_n_sign_posn = properties.int_n_sign_posn;
+
+
+ // LC_TIME
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing time locale properties";
+
+
+ // parse the supported POSIX LC_TIME properties
+
+ // abday
+ try {
+ this.abday = this._parseList(properties.abday, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid abday property: " + error;
+ }
+
+ // day
+ try {
+ this.day = this._parseList(properties.day, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid day property: " + error;
+ }
+
+ // abmon
+ try {
+ this.abmon = this._parseList(properties.abmon, 12);
+ } catch (error) {
+ throw "Error: Invalid abmon property: " + error;
+ }
+
+ // mon
+ try {
+ this.mon = this._parseList(properties.mon, 12);
+ } catch (error) {
+ throw "Error: Invalid mon property: " + error;
+ }
+
+ // d_fmt
+ try {
+ this.d_fmt = this._validateFormatString(properties.d_fmt);
+ } catch (error) {
+ throw "Error: Invalid d_fmt property: " + error;
+ }
+
+ // t_fmt
+ try {
+ this.t_fmt = this._validateFormatString(properties.t_fmt);
+ } catch (error) {
+ throw "Error: Invalid t_fmt property: " + error;
+ }
+
+ // d_t_fmt
+ try {
+ this.d_t_fmt = this._validateFormatString(properties.d_t_fmt);
+ } catch (error) {
+ throw "Error: Invalid d_t_fmt property: " + error;
+ }
+
+ // am_pm
+ try {
+ var am_pm_strings = this._parseList(properties.am_pm, 2);
+ this.am = am_pm_strings[0];
+ this.pm = am_pm_strings[1];
+ } catch (error) {
+ // ignore empty/null string errors
+ this.am = "";
+ this.pm = "";
+ }
+
+
+ /**
+ * @public
+ *
+ * @description Returns the abbreviated name of the specified weekday.
+ *
+ * @param {integer Number} [weekdayNum] An integer between 0 and 6. Zero
+ * corresponds to Sunday, one to Monday, etc. If omitted the
+ * method will return an array of all abbreviated weekday
+ * names.
+ *
+ * @returns {String | String[]} The abbreviated name of the specified weekday
+ * or an array of all abbreviated weekday names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getAbbreviatedWeekdayName = function(weekdayNum) {
+
+ if (typeof weekdayNum == "undefined" || weekdayNum === null)
+ return this.abday;
+
+ if (! jsworld._isInteger(weekdayNum) || weekdayNum < 0 || weekdayNum > 6)
+ throw "Error: Invalid weekday argument, must be an integer [0..6]";
+
+ return this.abday[weekdayNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the name of the specified weekday.
+ *
+ * @param {integer Number} [weekdayNum] An integer between 0 and 6. Zero
+ * corresponds to Sunday, one to Monday, etc. If omitted the
+ * method will return an array of all weekday names.
+ *
+ * @returns {String | String[]} The name of the specified weekday or an
+ * array of all weekday names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getWeekdayName = function(weekdayNum) {
+
+ if (typeof weekdayNum == "undefined" || weekdayNum === null)
+ return this.day;
+
+ if (! jsworld._isInteger(weekdayNum) || weekdayNum < 0 || weekdayNum > 6)
+ throw "Error: Invalid weekday argument, must be an integer [0..6]";
+
+ return this.day[weekdayNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the abbreviated name of the specified month.
+ *
+ * @param {integer Number} [monthNum] An integer between 0 and 11. Zero
+ * corresponds to January, one to February, etc. If omitted the
+ * method will return an array of all abbreviated month names.
+ *
+ * @returns {String | String[]} The abbreviated name of the specified month
+ * or an array of all abbreviated month names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getAbbreviatedMonthName = function(monthNum) {
+
+ if (typeof monthNum == "undefined" || monthNum === null)
+ return this.abmon;
+
+ if (! jsworld._isInteger(monthNum) || monthNum < 0 || monthNum > 11)
+ throw "Error: Invalid month argument, must be an integer [0..11]";
+
+ return this.abmon[monthNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the name of the specified month.
+ *
+ * @param {integer Number} [monthNum] An integer between 0 and 11. Zero
+ * corresponds to January, one to February, etc. If omitted the
+ * method will return an array of all month names.
+ *
+ * @returns {String | String[]} The name of the specified month or an array
+ * of all month names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getMonthName = function(monthNum) {
+
+ if (typeof monthNum == "undefined" || monthNum === null)
+ return this.mon;
+
+ if (! jsworld._isInteger(monthNum) || monthNum < 0 || monthNum > 11)
+ throw "Error: Invalid month argument, must be an integer [0..11]";
+
+ return this.mon[monthNum];
+ };
+
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) character for
+ * numeric quantities.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getDecimalPoint = function() {
+
+ return this.decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the local shorthand currency symbol.
+ *
+ * @returns {String} The currency symbol.
+ */
+ this.getCurrencySymbol = function() {
+
+ return this.currency_symbol;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the internaltion currency symbol (ISO-4217 code).
+ *
+ * @returns {String} The international currency symbol.
+ */
+ this.getIntCurrencySymbol = function() {
+
+ return this.int_curr_symbol.substring(0,3);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the local (shorthand) currency
+ * symbol relative to the amount. Assumes a non-negative amount.
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.currencySymbolPrecedes = function() {
+
+ if (this.p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the international (ISO-4217 code)
+ * currency symbol relative to the amount. Assumes a non-negative
+ * amount.
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.intCurrencySymbolPrecedes = function() {
+
+ if (this.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) for monetary
+ * quantities.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getMonetaryDecimalPoint = function() {
+
+ return this.mon_decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits for local
+ * (shorthand) symbol formatting.
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getFractionalDigits = function() {
+
+ return this.frac_digits;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits for
+ * international (ISO-4217 code) formatting.
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getIntFractionalDigits = function() {
+
+ return this.int_frac_digits;
+ };
+};
+
+
+
+/**
+ * @class
+ * Class for localised formatting of numbers.
+ *
+ *
See:
+ * POSIX LC_NUMERIC.
+ *
+ *
+ * @public
+ * @constructor
+ * @description Creates a new numeric formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_NUMERIC formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.NumericFormatter = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Formats a decimal numeric value according to the preset
+ * locale.
+ *
+ * @param {Number|String} number The number to format.
+ * @param {String} [options] Options to modify the formatted output:
+ *
+ *
"^" suppress grouping
+ *
"+" force positive sign for positive amounts
+ *
"~" suppress positive/negative sign
+ *
".n" specify decimal precision 'n'
+ *
+ *
+ * @returns {String} The formatted number.
+ *
+ * @throws "Error: Invalid input" on bad input.
+ */
+ this.format = function(number, options) {
+
+ if (typeof number == "string")
+ number = jsworld._trim(number);
+
+ if (! jsworld._isNumber(number))
+ throw "Error: The input is not a number";
+
+ var floatAmount = parseFloat(number, 10);
+
+ // get the required precision
+ var reqPrecision = jsworld._getPrecision(options);
+
+ // round to required precision
+ if (reqPrecision != -1)
+ floatAmount = Math.round(floatAmount * Math.pow(10, reqPrecision)) / Math.pow(10, reqPrecision);
+
+
+ // convert the float number to string and parse into
+ // object with properties integer and fraction
+ var parsedAmount = jsworld._splitNumber(String(floatAmount));
+
+ // format integer part with grouping chars
+ var formattedIntegerPart;
+
+ if (floatAmount === 0)
+ formattedIntegerPart = "0";
+ else
+ formattedIntegerPart = jsworld._hasOption("^", options) ?
+ parsedAmount.integer :
+ jsworld._formatIntegerPart(parsedAmount.integer,
+ this.lc.grouping,
+ this.lc.thousands_sep);
+
+ // format the fractional part
+ var formattedFractionPart =
+ reqPrecision != -1 ?
+ jsworld._formatFractionPart(parsedAmount.fraction, reqPrecision) :
+ parsedAmount.fraction;
+
+
+ // join the integer and fraction parts using the decimal_point property
+ var formattedAmount =
+ formattedFractionPart.length ?
+ formattedIntegerPart + this.lc.decimal_point + formattedFractionPart :
+ formattedIntegerPart;
+
+ // prepend sign?
+ if (jsworld._hasOption("~", options) || floatAmount === 0) {
+ // suppress both '+' and '-' signs, i.e. return abs value
+ return formattedAmount;
+ }
+ else {
+ if (jsworld._hasOption("+", options) || floatAmount < 0) {
+ if (floatAmount > 0)
+ // force '+' sign for positive amounts
+ return "+" + formattedAmount;
+ else if (floatAmount < 0)
+ // prepend '-' sign
+ return "-" + formattedAmount;
+ else
+ // zero case
+ return formattedAmount;
+ }
+ else {
+ // positive amount with no '+' sign
+ return formattedAmount;
+ }
+ }
+ };
+};
+
+
+/**
+ * @class
+ * Class for localised formatting of dates and times.
+ *
+ *
See:
+ * POSIX LC_TIME.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new date/time formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_TIME formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.DateTimeFormatter = function(locale) {
+
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance.";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Formats a date according to the preset locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted date, e.g. "2010-31-03"
+ * or "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted date
+ *
+ * @throws Error on invalid date argument
+ */
+ this.formatDate = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 date string
+ try {
+ d = jsworld.parseIsoDate(date);
+ } catch (error) {
+ // try full ISO-8601 date/time string
+ d = jsworld.parseIsoDateTime(date);
+ }
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.d_fmt);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a time according to the preset locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted time, e.g. "23:59:59"
+ * or "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted time.
+ *
+ * @throws Error on invalid date argument.
+ */
+ this.formatTime = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 time string
+ try {
+ d = jsworld.parseIsoTime(date);
+ } catch (error) {
+ // try full ISO-8601 date/time string
+ d = jsworld.parseIsoDateTime(date);
+ }
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.t_fmt);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a date/time value according to the preset
+ * locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted date/time, e.g.
+ * "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted time.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.formatDateTime = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 format
+ d = jsworld.parseIsoDateTime(date);
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.d_t_fmt);
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Apples formatting to the Date object according to the
+ * format string.
+ *
+ * @param {Date} d A valid Date instance.
+ * @param {String} s The formatting string with '%' placeholders.
+ *
+ * @returns {String} The formatted string.
+ */
+ this._applyFormatting = function(d, s) {
+
+ s = s.replace(/%%/g, '%');
+ s = s.replace(/%a/g, this.lc.abday[d.getDay()]);
+ s = s.replace(/%A/g, this.lc.day[d.getDay()]);
+ s = s.replace(/%b/g, this.lc.abmon[d.getMonth()]);
+ s = s.replace(/%B/g, this.lc.mon[d.getMonth()]);
+ s = s.replace(/%d/g, jsworld._zeroPad(d.getDate(), 2));
+ s = s.replace(/%e/g, jsworld._spacePad(d.getDate(), 2));
+ s = s.replace(/%F/g, d.getFullYear() +
+ "-" +
+ jsworld._zeroPad(d.getMonth()+1, 2) +
+ "-" +
+ jsworld._zeroPad(d.getDate(), 2));
+ s = s.replace(/%h/g, this.lc.abmon[d.getMonth()]); // same as %b
+ s = s.replace(/%H/g, jsworld._zeroPad(d.getHours(), 2));
+ s = s.replace(/%I/g, jsworld._zeroPad(this._hours12(d.getHours()), 2));
+ s = s.replace(/%k/g, d.getHours());
+ s = s.replace(/%l/g, this._hours12(d.getHours()));
+ s = s.replace(/%m/g, jsworld._zeroPad(d.getMonth()+1, 2));
+ s = s.replace(/%n/g, "\n");
+ s = s.replace(/%M/g, jsworld._zeroPad(d.getMinutes(), 2));
+ s = s.replace(/%p/g, this._getAmPm(d.getHours()));
+ s = s.replace(/%P/g, this._getAmPm(d.getHours()).toLocaleLowerCase()); // safe?
+ s = s.replace(/%R/g, jsworld._zeroPad(d.getHours(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getMinutes(), 2));
+ s = s.replace(/%S/g, jsworld._zeroPad(d.getSeconds(), 2));
+ s = s.replace(/%T/g, jsworld._zeroPad(d.getHours(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getMinutes(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getSeconds(), 2));
+ s = s.replace(/%w/g, this.lc.day[d.getDay()]);
+ s = s.replace(/%y/g, new String(d.getFullYear()).substring(2));
+ s = s.replace(/%Y/g, d.getFullYear());
+
+ s = s.replace(/%Z/g, ""); // to do: ignored until a reliable TMZ method found
+
+ s = s.replace(/%[a-zA-Z]/g, ""); // ignore all other % sequences
+
+ return s;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Does 24 to 12 hour conversion.
+ *
+ * @param {integer Number} hour24 Hour [0..23].
+ *
+ * @returns {integer Number} Corresponding hour [1..12].
+ */
+ this._hours12 = function(hour24) {
+
+ if (hour24 === 0)
+ return 12; // 00h is 12AM
+
+ else if (hour24 > 12)
+ return hour24 - 12; // 1PM to 11PM
+
+ else
+ return hour24; // 1AM to 12PM
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Gets the appropriate localised AM or PM string depending
+ * on the day hour. Special cases: midnight is 12AM, noon is 12PM.
+ *
+ * @param {integer Number} hour24 Hour [0..23].
+ *
+ * @returns {String} The corresponding localised AM or PM string.
+ */
+ this._getAmPm = function(hour24) {
+
+ if (hour24 < 12)
+ return this.lc.am;
+ else
+ return this.lc.pm;
+ };
+};
+
+
+
+/**
+ * @class Class for localised formatting of currency amounts.
+ *
+ *
See:
+ * POSIX LC_MONETARY.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new monetary formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_MONETARY formatting properties.
+ * @param {String} [currencyCode] Set the currency explicitly by
+ * passing its international ISO-4217 code, e.g. "USD", "EUR", "GBP".
+ * Use this optional parameter to override the default local currency
+ * @param {String} [altIntSymbol] Non-local currencies are formatted
+ * with their international ISO-4217 code to prevent ambiguity.
+ * Use this optional argument to force a different symbol, such as the
+ * currency's shorthand sign. This is mostly useful when the shorthand
+ * sign is both internationally recognised and identifies the currency
+ * uniquely (e.g. the Euro sign).
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.MonetaryFormatter = function(locale, currencyCode, altIntSymbol) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+ /**
+ * @private
+ * @description Lookup table to determine the fraction digits for a
+ * specific currency; most currencies subdivide at 1/100 (2 fractional
+ * digits), so we store only those that deviate from the default.
+ *
+ *
The data is from Unicode's CLDR version 1.7.0. The two currencies
+ * with non-decimal subunits (MGA and MRO) are marked as having no
+ * fractional digits as well as all currencies that have no subunits
+ * in circulation.
+ *
+ *
It is "hard-wired" for referential convenience and is only looked
+ * up when an overriding currencyCode parameter is supplied.
+ */
+ this.currencyFractionDigits = {
+ "AFN" : 0, "ALL" : 0, "AMD" : 0, "BHD" : 3, "BIF" : 0,
+ "BYR" : 0, "CLF" : 0, "CLP" : 0, "COP" : 0, "CRC" : 0,
+ "DJF" : 0, "GNF" : 0, "GYD" : 0, "HUF" : 0, "IDR" : 0,
+ "IQD" : 0, "IRR" : 0, "ISK" : 0, "JOD" : 3, "JPY" : 0,
+ "KMF" : 0, "KRW" : 0, "KWD" : 3, "LAK" : 0, "LBP" : 0,
+ "LYD" : 3, "MGA" : 0, "MMK" : 0, "MNT" : 0, "MRO" : 0,
+ "MUR" : 0, "OMR" : 3, "PKR" : 0, "PYG" : 0, "RSD" : 0,
+ "RWF" : 0, "SLL" : 0, "SOS" : 0, "STD" : 0, "SYP" : 0,
+ "TND" : 3, "TWD" : 0, "TZS" : 0, "UGX" : 0, "UZS" : 0,
+ "VND" : 0, "VUV" : 0, "XAF" : 0, "XOF" : 0, "XPF" : 0,
+ "YER" : 0, "ZMK" : 0
+ };
+
+
+ // optional currencyCode argument?
+ if (typeof currencyCode == "string") {
+ // user wanted to override the local currency
+ this.currencyCode = currencyCode.toUpperCase();
+
+ // must override the frac digits too, for some
+ // currencies have 0, 2 or 3!
+ var numDigits = this.currencyFractionDigits[this.currencyCode];
+ if (typeof numDigits != "number")
+ numDigits = 2; // default for most currencies
+ this.lc.frac_digits = numDigits;
+ this.lc.int_frac_digits = numDigits;
+ }
+ else {
+ // use local currency
+ this.currencyCode = this.lc.int_curr_symbol.substring(0,3).toUpperCase();
+ }
+
+ // extract intl. currency separator
+ this.intSep = this.lc.int_curr_symbol.charAt(3);
+
+ // flag local or intl. sign formatting?
+ if (this.currencyCode == this.lc.int_curr_symbol.substring(0,3)) {
+ // currency matches the local one? ->
+ // formatting with local symbol and parameters
+ this.internationalFormatting = false;
+ this.curSym = this.lc.currency_symbol;
+ }
+ else {
+ // currency doesn't match the local ->
+
+ // do we have an overriding currency symbol?
+ if (typeof altIntSymbol == "string") {
+ // -> force formatting with local parameters, using alt symbol
+ this.curSym = altIntSymbol;
+ this.internationalFormatting = false;
+ }
+ else {
+ // -> force formatting with intl. sign and parameters
+ this.internationalFormatting = true;
+ }
+ }
+
+
+ /**
+ * @public
+ *
+ * @description Gets the currency symbol used in formatting.
+ *
+ * @returns {String} The currency symbol.
+ */
+ this.getCurrencySymbol = function() {
+
+ return this.curSym;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the currency symbol relative to
+ * the amount. Assumes a non-negative amount and local formatting.
+ *
+ * @param {String} intFlag Optional flag to force international
+ * formatting by passing the string "i".
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.currencySymbolPrecedes = function(intFlag) {
+
+ if (typeof intFlag == "string" && intFlag == "i") {
+ // international formatting was forced
+ if (this.lc.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+
+ }
+ else {
+ // check whether local formatting is on or off
+ if (this.internationalFormatting) {
+ if (this.lc.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ }
+ else {
+ if (this.lc.p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ }
+ }
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) used in formatting.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getDecimalPoint = function() {
+
+ return this.lc.mon_decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits. Assumes local
+ * formatting.
+ *
+ * @param {String} intFlag Optional flag to force international
+ * formatting by passing the string "i".
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getFractionalDigits = function(intFlag) {
+
+ if (typeof intFlag == "string" && intFlag == "i") {
+ // international formatting was forced
+ return this.lc.int_frac_digits;
+ }
+ else {
+ // check whether local formatting is on or off
+ if (this.internationalFormatting)
+ return this.lc.int_frac_digits;
+ else
+ return this.lc.frac_digits;
+ }
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a monetary amount according to the preset
+ * locale.
+ *
+ *
+ * For local currencies the native shorthand symbol will be used for
+ * formatting.
+ * Example:
+ * locale is en_US
+ * currency is USD
+ * -> the "$" symbol will be used, e.g. $123.45
+ *
+ * For non-local currencies the international ISO-4217 code will be
+ * used for formatting.
+ * Example:
+ * locale is en_US (which has USD as currency)
+ * currency is EUR
+ * -> the ISO three-letter code will be used, e.g. EUR 123.45
+ *
+ * If the currency is non-local, but an alternative currency symbol was
+ * provided, this will be used instead.
+ * Example
+ * locale is en_US (which has USD as currency)
+ * currency is EUR
+ * an alternative symbol is provided - "€"
+ * -> the alternative symbol will be used, e.g. €123.45
+ *
+ *
+ * @param {Number|String} amount The amount to format as currency.
+ * @param {String} [options] Options to modify the formatted output:
+ *
+ *
"^" suppress grouping
+ *
"!" suppress the currency symbol
+ *
"~" suppress the currency symbol and the sign (positive or negative)
+ *
"i" force international sign (ISO-4217 code) formatting
+ *
".n" specify decimal precision
+ *
+ * @returns The formatted currency amount as string.
+ *
+ * @throws "Error: Invalid amount" on bad amount.
+ */
+ this.format = function(amount, options) {
+
+ // if the amount is passed as string, check that it parses to a float
+ var floatAmount;
+
+ if (typeof amount == "string") {
+ amount = jsworld._trim(amount);
+ floatAmount = parseFloat(amount);
+
+ if (typeof floatAmount != "number" || isNaN(floatAmount))
+ throw "Error: Amount string not a number";
+ }
+ else if (typeof amount == "number") {
+ floatAmount = amount;
+ }
+ else {
+ throw "Error: Amount not a number";
+ }
+
+ // get the required precision, ".n" option arg overrides default locale config
+ var reqPrecision = jsworld._getPrecision(options);
+
+ if (reqPrecision == -1) {
+ if (this.internationalFormatting || jsworld._hasOption("i", options))
+ reqPrecision = this.lc.int_frac_digits;
+ else
+ reqPrecision = this.lc.frac_digits;
+ }
+
+ // round
+ floatAmount = Math.round(floatAmount * Math.pow(10, reqPrecision)) / Math.pow(10, reqPrecision);
+
+
+ // convert the float amount to string and parse into
+ // object with properties integer and fraction
+ var parsedAmount = jsworld._splitNumber(String(floatAmount));
+
+ // format integer part with grouping chars
+ var formattedIntegerPart;
+
+ if (floatAmount === 0)
+ formattedIntegerPart = "0";
+ else
+ formattedIntegerPart = jsworld._hasOption("^", options) ?
+ parsedAmount.integer :
+ jsworld._formatIntegerPart(parsedAmount.integer,
+ this.lc.mon_grouping,
+ this.lc.mon_thousands_sep);
+
+
+ // format the fractional part
+ var formattedFractionPart;
+
+ if (reqPrecision == -1) {
+ // pad fraction with trailing zeros accoring to default locale [int_]frac_digits
+ if (this.internationalFormatting || jsworld._hasOption("i", options))
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, this.lc.int_frac_digits);
+ else
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, this.lc.frac_digits);
+ }
+ else {
+ // pad fraction with trailing zeros according to optional format parameter
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, reqPrecision);
+ }
+
+
+ // join integer and decimal parts using the mon_decimal_point property
+ var quantity;
+
+ if (this.lc.frac_digits > 0 || formattedFractionPart.length)
+ quantity = formattedIntegerPart + this.lc.mon_decimal_point + formattedFractionPart;
+ else
+ quantity = formattedIntegerPart;
+
+
+ // do final formatting with sign and symbol
+ if (jsworld._hasOption("~", options)) {
+ return quantity;
+ }
+ else {
+ var suppressSymbol = jsworld._hasOption("!", options) ? true : false;
+
+ var sign = floatAmount < 0 ? "-" : "+";
+
+ if (this.internationalFormatting || jsworld._hasOption("i", options)) {
+
+ // format with ISO-4217 code (suppressed or not)
+ if (suppressSymbol)
+ return this._formatAsInternationalCurrencyWithNoSym(sign, quantity);
+ else
+ return this._formatAsInternationalCurrency(sign, quantity);
+ }
+ else {
+ // format with local currency code (suppressed or not)
+ if (suppressSymbol)
+ return this._formatAsLocalCurrencyWithNoSym(sign, quantity);
+ else
+ return this._formatAsLocalCurrency(sign, quantity);
+ }
+ }
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign, separator and symbol as local
+ * currency.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsLocalCurrency = function (sign, q) {
+
+ // assemble final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return "(" + q + this.curSym + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return "(" + this.curSym + q + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return "(" + q + " " + this.curSym + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return "(" + this.curSym + " " + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + " " + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + " " + q + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + this.curSym + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + " " + q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + q + " " + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + " " + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + this.curSym + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + " " + this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return "(" + q + this.curSym + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return "(" + this.curSym + q + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return "(" + q + " " + this.curSym + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return "(" + this.curSym + " " + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + " " + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + " " + q + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + this.curSym + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + " " + q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + q + " " + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + " " + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + this.curSym + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + " " + this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign, separator and ISO-4217
+ * currency code.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsInternationalCurrency = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return "(" + q + this.currencyCode + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return "(" + this.currencyCode + q + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return "(" + q + this.intSep + this.currencyCode + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return "(" + this.currencyCode + this.intSep + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + this.intSep + q + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + q + this.intSep + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return "(" + q + this.currencyCode + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return "(" + this.currencyCode + q + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return "(" + q + this.intSep + this.currencyCode + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return "(" + this.currencyCode + this.intSep + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + this.intSep + q + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + q + this.intSep + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign and separator, but suppress the
+ * local currency symbol.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string
+ */
+ this._formatAsLocalCurrencyWithNoSym = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.p_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return q + " " + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.n_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return q + " " + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign and separator, but suppress
+ * the ISO-4217 currency code.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsInternationalCurrencyWithNoSym = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.int_p_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.int_n_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC_MONETARY definition";
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised number strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new numeric parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_NUMERIC formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.NumericParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a numeric string formatted according to the
+ * preset locale. Leading and trailing whitespace is ignored; the number
+ * may also be formatted without thousands separators.
+ *
+ * @param {String} formattedNumber The formatted number.
+ *
+ * @returns {Number} The parsed number.
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parse = function(formattedNumber) {
+
+ if (typeof formattedNumber != "string")
+ throw "Parse error: Argument must be a string";
+
+ // trim whitespace
+ var s = jsworld._trim(formattedNumber);
+
+ // remove any thousand separator symbols
+ s = jsworld._stringReplaceAll(formattedNumber, this.lc.thousands_sep, "");
+
+ // replace any local decimal point symbols with the symbol used
+ // in JavaScript "."
+ s = jsworld._stringReplaceAll(s, this.lc.decimal_point, ".");
+
+ // test if the string represents a number
+ if (jsworld._isNumber(s))
+ return parseFloat(s, 10);
+ else
+ throw "Parse error: Invalid number string";
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised date and time strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new date/time parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_TIME formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.DateTimeParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance.";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a time string formatted according to the
+ * POSIX LC_TIME t_fmt property of the preset locale.
+ *
+ * @param {String} formattedTime The formatted time.
+ *
+ * @returns {String} The parsed time in ISO-8601 format (HH:MM:SS), e.g.
+ * "23:59:59".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseTime = function(formattedTime) {
+
+ if (typeof formattedTime != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.t_fmt, formattedTime);
+
+ var timeDefined = false;
+
+ if (dt.hour !== null && dt.minute !== null && dt.second !== null) {
+ timeDefined = true;
+ }
+ else if (dt.hourAmPm !== null && dt.am !== null && dt.minute !== null && dt.second !== null) {
+ if (dt.am) {
+ // AM [12(midnight), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 0;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10);
+ }
+ else {
+ // PM [12(noon), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 12;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10) + 12;
+ }
+ timeDefined = true;
+ }
+
+ if (timeDefined)
+ return jsworld._zeroPad(dt.hour, 2) +
+ ":" +
+ jsworld._zeroPad(dt.minute, 2) +
+ ":" +
+ jsworld._zeroPad(dt.second, 2);
+ else
+ throw "Parse error: Invalid/ambiguous time string";
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Parses a date string formatted according to the
+ * POSIX LC_TIME d_fmt property of the preset locale.
+ *
+ * @param {String} formattedDate The formatted date, must be valid.
+ *
+ * @returns {String} The parsed date in ISO-8601 format (YYYY-MM-DD),
+ * e.g. "2010-03-31".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseDate = function(formattedDate) {
+
+ if (typeof formattedDate != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.d_fmt, formattedDate);
+
+ var dateDefined = false;
+
+ if (dt.year !== null && dt.month !== null && dt.day !== null) {
+ dateDefined = true;
+ }
+
+ if (dateDefined)
+ return jsworld._zeroPad(dt.year, 4) +
+ "-" +
+ jsworld._zeroPad(dt.month, 2) +
+ "-" +
+ jsworld._zeroPad(dt.day, 2);
+ else
+ throw "Parse error: Invalid date string";
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Parses a date/time string formatted according to the
+ * POSIX LC_TIME d_t_fmt property of the preset locale.
+ *
+ * @param {String} formattedDateTime The formatted date/time, must be
+ * valid.
+ *
+ * @returns {String} The parsed date/time in ISO-8601 format
+ * (YYYY-MM-DD HH:MM:SS), e.g. "2010-03-31 23:59:59".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseDateTime = function(formattedDateTime) {
+
+ if (typeof formattedDateTime != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.d_t_fmt, formattedDateTime);
+
+ var timeDefined = false;
+ var dateDefined = false;
+
+ if (dt.hour !== null && dt.minute !== null && dt.second !== null) {
+ timeDefined = true;
+ }
+ else if (dt.hourAmPm !== null && dt.am !== null && dt.minute !== null && dt.second !== null) {
+ if (dt.am) {
+ // AM [12(midnight), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 0;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10);
+ }
+ else {
+ // PM [12(noon), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 12;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10) + 12;
+ }
+ timeDefined = true;
+ }
+
+ if (dt.year !== null && dt.month !== null && dt.day !== null) {
+ dateDefined = true;
+ }
+
+ if (dateDefined && timeDefined)
+ return jsworld._zeroPad(dt.year, 4) +
+ "-" +
+ jsworld._zeroPad(dt.month, 2) +
+ "-" +
+ jsworld._zeroPad(dt.day, 2) +
+ " " +
+ jsworld._zeroPad(dt.hour, 2) +
+ ":" +
+ jsworld._zeroPad(dt.minute, 2) +
+ ":" +
+ jsworld._zeroPad(dt.second, 2);
+ else
+ throw "Parse error: Invalid/ambiguous date/time string";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Parses a string according to the specified format
+ * specification.
+ *
+ * @param {String} fmtSpec The format specification, e.g. "%I:%M:%S %p".
+ * @param {String} s The string to parse.
+ *
+ * @returns {object} An object with set properties year, month, day,
+ * hour, minute and second if the corresponding values are
+ * found in the parsed string.
+ *
+ * @throws Error on a parse exception.
+ */
+ this._extractTokens = function(fmtSpec, s) {
+
+ // the return object containing the parsed date/time properties
+ var dt = {
+ // for date and date/time strings
+ "year" : null,
+ "month" : null,
+ "day" : null,
+
+ // for time and date/time strings
+ "hour" : null,
+ "hourAmPm" : null,
+ "am" : null,
+ "minute" : null,
+ "second" : null,
+
+ // used internally only
+ "weekday" : null
+ };
+
+
+ // extract and process each token in the date/time spec
+ while (fmtSpec.length > 0) {
+
+ // Do we have a valid "%\w" placeholder in stream?
+ if (fmtSpec.charAt(0) == "%" && fmtSpec.charAt(1) != "") {
+
+ // get placeholder
+ var placeholder = fmtSpec.substring(0,2);
+
+ if (placeholder == "%%") {
+ // escaped '%''
+ s = s.substring(1);
+ }
+ else if (placeholder == "%a") {
+ // abbreviated weekday name
+ for (var i = 0; i < this.lc.abday.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.abday[i])) {
+ dt.weekday = i;
+ s = s.substring(this.lc.abday[i].length);
+ break;
+ }
+ }
+
+ if (dt.weekday === null)
+ throw "Parse error: Unrecognised abbreviated weekday name (%a)";
+ }
+ else if (placeholder == "%A") {
+ // weekday name
+ for (var i = 0; i < this.lc.day.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.day[i])) {
+ dt.weekday = i;
+ s = s.substring(this.lc.day[i].length);
+ break;
+ }
+ }
+
+ if (dt.weekday === null)
+ throw "Parse error: Unrecognised weekday name (%A)";
+ }
+ else if (placeholder == "%b" || placeholder == "%h") {
+ // abbreviated month name
+ for (var i = 0; i < this.lc.abmon.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.abmon[i])) {
+ dt.month = i + 1;
+ s = s.substring(this.lc.abmon[i].length);
+ break;
+ }
+ }
+
+ if (dt.month === null)
+ throw "Parse error: Unrecognised abbreviated month name (%b)";
+ }
+ else if (placeholder == "%B") {
+ // month name
+ for (var i = 0; i < this.lc.mon.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.mon[i])) {
+ dt.month = i + 1;
+ s = s.substring(this.lc.mon[i].length);
+ break;
+ }
+ }
+
+ if (dt.month === null)
+ throw "Parse error: Unrecognised month name (%B)";
+ }
+ else if (placeholder == "%d") {
+ // day of the month [01..31]
+ if (/^0[1-9]|[1-2][0-9]|3[0-1]/.test(s)) {
+ dt.day = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised day of the month (%d)";
+ }
+ else if (placeholder == "%e") {
+ // day of the month [1..31]
+
+ // Note: if %e is leading in fmt string -> space padded!
+
+ var day = s.match(/^\s?(\d{1,2})/);
+ dt.day = parseInt(day, 10);
+
+ if (isNaN(dt.day) || dt.day < 1 || dt.day > 31)
+ throw "Parse error: Unrecognised day of the month (%e)";
+
+ s = s.substring(day.length);
+ }
+ else if (placeholder == "%F") {
+ // equivalent to %Y-%m-%d (ISO-8601 date format)
+
+ // year [nnnn]
+ if (/^\d\d\d\d/.test(s)) {
+ dt.year = parseInt(s.substring(0,4), 10);
+ s = s.substring(4);
+ }
+ else {
+ throw "Parse error: Unrecognised date (%F)";
+ }
+
+ // -
+ if (jsworld._stringStartsWith(s, "-"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // month [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.month = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // -
+ if (jsworld._stringStartsWith(s, "-"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // day of the month [01..31]
+ if (/^0[1-9]|[1-2][0-9]|3[0-1]/.test(s)) {
+ dt.day = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised date (%F)";
+ }
+ else if (placeholder == "%H") {
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised hour (%H)";
+ }
+ else if (placeholder == "%I") {
+ // hour [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.hourAmPm = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised hour (%I)";
+ }
+ else if (placeholder == "%k") {
+ // hour [0..23]
+ var h = s.match(/^(\d{1,2})/);
+ dt.hour = parseInt(h, 10);
+
+ if (isNaN(dt.hour) || dt.hour < 0 || dt.hour > 23)
+ throw "Parse error: Unrecognised hour (%k)";
+
+ s = s.substring(h.length);
+ }
+ else if (placeholder == "%l") {
+ // hour AM/PM [1..12]
+ var h = s.match(/^(\d{1,2})/);
+ dt.hourAmPm = parseInt(h, 10);
+
+ if (isNaN(dt.hourAmPm) || dt.hourAmPm < 1 || dt.hourAmPm > 12)
+ throw "Parse error: Unrecognised hour (%l)";
+
+ s = s.substring(h.length);
+ }
+ else if (placeholder == "%m") {
+ // month [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.month = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised month (%m)";
+ }
+ else if (placeholder == "%M") {
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised minute (%M)";
+ }
+ else if (placeholder == "%n") {
+ // new line
+
+ if (s.charAt(0) == "\n")
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised new line (%n)";
+ }
+ else if (placeholder == "%p") {
+ // locale's equivalent of AM/PM
+ if (jsworld._stringStartsWith(s, this.lc.am)) {
+ dt.am = true;
+ s = s.substring(this.lc.am.length);
+ }
+ else if (jsworld._stringStartsWith(s, this.lc.pm)) {
+ dt.am = false;
+ s = s.substring(this.lc.pm.length);
+ }
+ else
+ throw "Parse error: Unrecognised AM/PM value (%p)";
+ }
+ else if (placeholder == "%P") {
+ // same as %p but forced lower case
+ if (jsworld._stringStartsWith(s, this.lc.am.toLowerCase())) {
+ dt.am = true;
+ s = s.substring(this.lc.am.length);
+ }
+ else if (jsworld._stringStartsWith(s, this.lc.pm.toLowerCase())) {
+ dt.am = false;
+ s = s.substring(this.lc.pm.length);
+ }
+ else
+ throw "Parse error: Unrecognised AM/PM value (%P)";
+ }
+ else if (placeholder == "%R") {
+ // same as %H:%M
+
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ }
+ else if (placeholder == "%S") {
+ // second [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.second = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised second (%S)";
+ }
+ else if (placeholder == "%T") {
+ // same as %H:%M:%S
+
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // second [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.second = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+ }
+ else if (placeholder == "%w") {
+ // weekday [0..6]
+ if (/^\d/.test(s)) {
+ dt.weekday = parseInt(s.substring(0,1), 10);
+ s = s.substring(1);
+ }
+ else
+ throw "Parse error: Unrecognised weekday number (%w)";
+ }
+ else if (placeholder == "%y") {
+ // year [00..99]
+ if (/^\d\d/.test(s)) {
+ var year2digits = parseInt(s.substring(0,2), 10);
+
+ // this conversion to year[nnnn] is arbitrary!!!
+ if (year2digits > 50)
+ dt.year = 1900 + year2digits;
+ else
+ dt.year = 2000 + year2digits;
+
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised year (%y)";
+ }
+ else if (placeholder == "%Y") {
+ // year [nnnn]
+ if (/^\d\d\d\d/.test(s)) {
+ dt.year = parseInt(s.substring(0,4), 10);
+ s = s.substring(4);
+ }
+ else
+ throw "Parse error: Unrecognised year (%Y)";
+ }
+
+ else if (placeholder == "%Z") {
+ // time-zone place holder is not supported
+
+ if (fmtSpec.length === 0)
+ break; // ignore rest of fmt spec
+ }
+
+ // remove the spec placeholder that was just parsed
+ fmtSpec = fmtSpec.substring(2);
+ }
+ else {
+ // If we don't have a placeholder, the chars
+ // at pos. 0 of format spec and parsed string must match
+
+ // Note: Space chars treated 1:1 !
+
+ if (fmtSpec.charAt(0) != s.charAt(0))
+ throw "Parse error: Unexpected symbol \"" + s.charAt(0) + "\" in date/time string";
+
+ fmtSpec = fmtSpec.substring(1);
+ s = s.substring(1);
+ }
+ }
+
+ // parsing finished, return composite date/time object
+ return dt;
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised currency amount strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new monetary parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_MONETARY formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.MonetaryParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a currency amount string formatted according to
+ * the preset locale. Leading and trailing whitespace is ignored; the
+ * amount may also be formatted without thousands separators. Both
+ * the local (shorthand) symbol and the ISO 4217 code are accepted to
+ * designate the currency in the formatted amount.
+ *
+ * @param {String} formattedCurrency The formatted currency amount.
+ *
+ * @returns {Number} The parsed amount.
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parse = function(formattedCurrency) {
+
+ if (typeof formattedCurrency != "string")
+ throw "Parse error: Argument must be a string";
+
+ // Detect the format type and remove the currency symbol
+ var symbolType = this._detectCurrencySymbolType(formattedCurrency);
+
+ var formatType, s;
+
+ if (symbolType == "local") {
+ formatType = "local";
+ s = formattedCurrency.replace(this.lc.getCurrencySymbol(), "");
+ }
+ else if (symbolType == "int") {
+ formatType = "int";
+ s = formattedCurrency.replace(this.lc.getIntCurrencySymbol(), "");
+ }
+ else if (symbolType == "none") {
+ formatType = "local"; // assume local
+ s = formattedCurrency;
+ }
+ else
+ throw "Parse error: Internal assert failure";
+
+ // Remove any thousands separators
+ s = jsworld._stringReplaceAll(s, this.lc.mon_thousands_sep, "");
+
+ // Replace any local radix char with JavaScript's "."
+ s = s.replace(this.lc.mon_decimal_point, ".");
+
+ // Remove all whitespaces
+ s = s.replace(/\s*/g, "");
+
+ // Remove any local non-negative sign
+ s = this._removeLocalNonNegativeSign(s, formatType);
+
+ // Replace any local minus sign with JavaScript's "-" and put
+ // it in front of the amount if necessary
+ // (special parentheses rule checked too)
+ s = this._normaliseNegativeSign(s, formatType);
+
+ // Finally, we should be left with a bare parsable decimal number
+ if (jsworld._isNumber(s))
+ return parseFloat(s, 10);
+ else
+ throw "Parse error: Invalid currency amount string";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Tries to detect the symbol type used in the specified
+ * formatted currency string: local(shorthand),
+ * international (ISO-4217 code) or none.
+ *
+ * @param {String} formattedCurrency The the formatted currency string.
+ *
+ * @return {String} With possible values "local", "int" or "none".
+ */
+ this._detectCurrencySymbolType = function(formattedCurrency) {
+
+ // Check for whichever sign (int/local) is longer first
+ // to cover cases such as MOP/MOP$ and ZAR/R
+
+ if (this.lc.getCurrencySymbol().length > this.lc.getIntCurrencySymbol().length) {
+
+ if (formattedCurrency.indexOf(this.lc.getCurrencySymbol()) != -1)
+ return "local";
+ else if (formattedCurrency.indexOf(this.lc.getIntCurrencySymbol()) != -1)
+ return "int";
+ else
+ return "none";
+ }
+ else {
+ if (formattedCurrency.indexOf(this.lc.getIntCurrencySymbol()) != -1)
+ return "int";
+ else if (formattedCurrency.indexOf(this.lc.getCurrencySymbol()) != -1)
+ return "local";
+ else
+ return "none";
+ }
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Removes a local non-negative sign in a formatted
+ * currency string if it is found. This is done according to the
+ * locale properties p_sign_posn and int_p_sign_posn.
+ *
+ * @param {String} s The input string.
+ * @param {String} formatType With possible values "local" or "int".
+ *
+ * @returns {String} The processed string.
+ */
+ this._removeLocalNonNegativeSign = function(s, formatType) {
+
+ s = s.replace(this.lc.positive_sign, "");
+
+ // check for enclosing parentheses rule
+ if (((formatType == "local" && this.lc.p_sign_posn === 0) ||
+ (formatType == "int" && this.lc.int_p_sign_posn === 0) ) &&
+ /\(\d+\.?\d*\)/.test(s)) {
+ s = s.replace("(", "");
+ s = s.replace(")", "");
+ }
+
+ return s;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Replaces a local negative sign with the standard
+ * JavaScript minus ("-") sign placed in the correct position
+ * (preceding the amount). This is done according to the locale
+ * properties for negative sign symbol and relative position.
+ *
+ * @param {String} s The input string.
+ * @param {String} formatType With possible values "local" or "int".
+ *
+ * @returns {String} The processed string.
+ */
+ this._normaliseNegativeSign = function(s, formatType) {
+
+ // replace local negative symbol with JavaScript's "-"
+ s = s.replace(this.lc.negative_sign, "-");
+
+ // check for enclosing parentheses rule and replace them
+ // with negative sign before the amount
+ if ((formatType == "local" && this.lc.n_sign_posn === 0) ||
+ (formatType == "int" && this.lc.int_n_sign_posn === 0) ) {
+
+ if (/^\(\d+\.?\d*\)$/.test(s)) {
+
+ s = s.replace("(", "");
+ s = s.replace(")", "");
+ return "-" + s;
+ }
+ }
+
+ // check for rule negative sign succeeding the amount
+ if (formatType == "local" && this.lc.n_sign_posn == 2 ||
+ formatType == "int" && this.lc.int_n_sign_posn == 2 ) {
+
+ if (/^\d+\.?\d*-$/.test(s)) {
+ s = s.replace("-", "");
+ return "-" + s;
+ }
+ }
+
+ // check for rule cur. sym. succeeds and sign adjacent
+ if (formatType == "local" && this.lc.n_cs_precedes === 0 && this.lc.n_sign_posn == 3 ||
+ formatType == "local" && this.lc.n_cs_precedes === 0 && this.lc.n_sign_posn == 4 ||
+ formatType == "int" && this.lc.int_n_cs_precedes === 0 && this.lc.int_n_sign_posn == 3 ||
+ formatType == "int" && this.lc.int_n_cs_precedes === 0 && this.lc.int_n_sign_posn == 4 ) {
+
+ if (/^\d+\.?\d*-$/.test(s)) {
+ s = s.replace("-", "");
+ return "-" + s;
+ }
+ }
+
+ return s;
+ };
+};
+
+// end-of-file
diff --git a/node_modules/uglify-js/tmp/uglify-hangs2.js b/node_modules/uglify-js/tmp/uglify-hangs2.js
new file mode 100644
index 0000000..4e9f967
--- /dev/null
+++ b/node_modules/uglify-js/tmp/uglify-hangs2.js
@@ -0,0 +1,166 @@
+jsworld.Locale = function(properties) {
+
+ // LC_NUMERIC
+
+
+ this.frac_digits = properties.frac_digits;
+
+
+ // may be empty string/null for currencies with no fractional part
+ if (properties.mon_decimal_point === null || properties.mon_decimal_point == "") {
+
+ if (this.frac_digits > 0)
+ throw "Error: Undefined mon_decimal_point property";
+ else
+ properties.mon_decimal_point = "";
+ }
+
+ if (typeof properties.mon_decimal_point != "string")
+ throw "Error: Invalid/missing mon_decimal_point property";
+
+ this.mon_decimal_point = properties.mon_decimal_point;
+
+
+ if (typeof properties.mon_thousands_sep != "string")
+ throw "Error: Invalid/missing mon_thousands_sep property";
+
+ this.mon_thousands_sep = properties.mon_thousands_sep;
+
+
+ if (typeof properties.mon_grouping != "string")
+ throw "Error: Invalid/missing mon_grouping property";
+
+ this.mon_grouping = properties.mon_grouping;
+
+
+ if (typeof properties.positive_sign != "string")
+ throw "Error: Invalid/missing positive_sign property";
+
+ this.positive_sign = properties.positive_sign;
+
+
+ if (typeof properties.negative_sign != "string")
+ throw "Error: Invalid/missing negative_sign property";
+
+ this.negative_sign = properties.negative_sign;
+
+
+ if (properties.p_cs_precedes !== 0 && properties.p_cs_precedes !== 1)
+ throw "Error: Invalid/missing p_cs_precedes property, must be 0 or 1";
+
+ this.p_cs_precedes = properties.p_cs_precedes;
+
+
+ if (properties.n_cs_precedes !== 0 && properties.n_cs_precedes !== 1)
+ throw "Error: Invalid/missing n_cs_precedes, must be 0 or 1";
+
+ this.n_cs_precedes = properties.n_cs_precedes;
+
+
+ if (properties.p_sep_by_space !== 0 &&
+ properties.p_sep_by_space !== 1 &&
+ properties.p_sep_by_space !== 2)
+ throw "Error: Invalid/missing p_sep_by_space property, must be 0, 1 or 2";
+
+ this.p_sep_by_space = properties.p_sep_by_space;
+
+
+ if (properties.n_sep_by_space !== 0 &&
+ properties.n_sep_by_space !== 1 &&
+ properties.n_sep_by_space !== 2)
+ throw "Error: Invalid/missing n_sep_by_space property, must be 0, 1, or 2";
+
+ this.n_sep_by_space = properties.n_sep_by_space;
+
+
+ if (properties.p_sign_posn !== 0 &&
+ properties.p_sign_posn !== 1 &&
+ properties.p_sign_posn !== 2 &&
+ properties.p_sign_posn !== 3 &&
+ properties.p_sign_posn !== 4)
+ throw "Error: Invalid/missing p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.p_sign_posn = properties.p_sign_posn;
+
+
+ if (properties.n_sign_posn !== 0 &&
+ properties.n_sign_posn !== 1 &&
+ properties.n_sign_posn !== 2 &&
+ properties.n_sign_posn !== 3 &&
+ properties.n_sign_posn !== 4)
+ throw "Error: Invalid/missing n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.n_sign_posn = properties.n_sign_posn;
+
+
+ if (typeof properties.int_frac_digits != "number" && properties.int_frac_digits < 0)
+ throw "Error: Invalid/missing int_frac_digits property";
+
+ this.int_frac_digits = properties.int_frac_digits;
+
+
+ if (properties.int_p_cs_precedes !== 0 && properties.int_p_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_p_cs_precedes property, must be 0 or 1";
+
+ this.int_p_cs_precedes = properties.int_p_cs_precedes;
+
+
+ if (properties.int_n_cs_precedes !== 0 && properties.int_n_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_n_cs_precedes property, must be 0 or 1";
+
+ this.int_n_cs_precedes = properties.int_n_cs_precedes;
+
+
+ if (properties.int_p_sep_by_space !== 0 &&
+ properties.int_p_sep_by_space !== 1 &&
+ properties.int_p_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_p_sep_by_spacev, must be 0, 1 or 2";
+
+ this.int_p_sep_by_space = properties.int_p_sep_by_space;
+
+
+ if (properties.int_n_sep_by_space !== 0 &&
+ properties.int_n_sep_by_space !== 1 &&
+ properties.int_n_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_n_sep_by_space property, must be 0, 1, or 2";
+
+ this.int_n_sep_by_space = properties.int_n_sep_by_space;
+
+
+ if (properties.int_p_sign_posn !== 0 &&
+ properties.int_p_sign_posn !== 1 &&
+ properties.int_p_sign_posn !== 2 &&
+ properties.int_p_sign_posn !== 3 &&
+ properties.int_p_sign_posn !== 4)
+ throw "Error: Invalid/missing int_p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_p_sign_posn = properties.int_p_sign_posn;
+
+
+ if (properties.int_n_sign_posn !== 0 &&
+ properties.int_n_sign_posn !== 1 &&
+ properties.int_n_sign_posn !== 2 &&
+ properties.int_n_sign_posn !== 3 &&
+ properties.int_n_sign_posn !== 4)
+ throw "Error: Invalid/missing int_n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_n_sign_posn = properties.int_n_sign_posn;
+
+
+ // LC_TIME
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing time locale properties";
+
+
+ // parse the supported POSIX LC_TIME properties
+
+ // abday
+ try {
+ this.abday = this._parseList(properties.abday, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid abday property: " + error;
+ }
+
+}
diff --git a/node_modules/uglify-js/uglify-js.js b/node_modules/uglify-js/uglify-js.js
new file mode 100644
index 0000000..4305e23
--- /dev/null
+++ b/node_modules/uglify-js/uglify-js.js
@@ -0,0 +1,17 @@
+//convienence function(src, [options]);
+function uglify(orig_code, options){
+ options || (options = {});
+ var jsp = uglify.parser;
+ var pro = uglify.uglify;
+
+ var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
+ ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
+ ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
+ var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
+ return final_code;
+};
+
+uglify.parser = require("./lib/parse-js");
+uglify.uglify = require("./lib/process");
+
+module.exports = uglify
\ No newline at end of file
diff --git a/node_modules/winston/.npmignore b/node_modules/winston/.npmignore
new file mode 100644
index 0000000..2c5c40a
--- /dev/null
+++ b/node_modules/winston/.npmignore
@@ -0,0 +1,6 @@
+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
new file mode 100644
index 0000000..63e4183
--- /dev/null
+++ b/node_modules/winston/.travis.yml
@@ -0,0 +1,10 @@
+language: node_js
+node_js:
+ - 0.4
+ - 0.6
+
+notifications:
+ email:
+ - travis@nodejitsu.com
+ irc: "irc.freenode.org#nodejitsu"
+
diff --git a/node_modules/winston/LICENSE b/node_modules/winston/LICENSE
new file mode 100644
index 0000000..948d80d
--- /dev/null
+++ b/node_modules/winston/LICENSE
@@ -0,0 +1,19 @@
+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
new file mode 100644
index 0000000..1719b05
--- /dev/null
+++ b/node_modules/winston/README.md
@@ -0,0 +1,690 @@
+# 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
+ });
+
+ winston.handleExceptions();
+```
+
+## 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 true).
+* __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(MongoDB, 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-simpledb').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.
+
+### 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. Graylog2 format support.
+2. Improve support for adding custom Transports not defined in Winston core.
+3. Create API for reading from logs across all transports.
+4. 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
diff --git a/node_modules/winston/docs/docco.css b/node_modules/winston/docs/docco.css
new file mode 100644
index 0000000..bd54134
--- /dev/null
+++ b/node_modules/winston/docs/docco.css
@@ -0,0 +1,194 @@
+/*--------------------- 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
new file mode 100644
index 0000000..0c7f087
--- /dev/null
+++ b/node_modules/winston/docs/winston.html
@@ -0,0 +1,86 @@
+ winston.js
Configures the default winston logger to have the
+settings for command-line interfaces: no timestamp,
+colors enabled, padded output, and additional levels.
\ No newline at end of file
diff --git a/node_modules/winston/docs/winston/common.html b/node_modules/winston/docs/winston/common.html
new file mode 100644
index 0000000..1ab139c
--- /dev/null
+++ b/node_modules/winston/docs/winston/common.html
@@ -0,0 +1,140 @@
+ common.js
@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
+ }
\ No newline at end of file
diff --git a/node_modules/winston/docs/winston/config.html b/node_modules/winston/docs/winston/config.html
new file mode 100644
index 0000000..c623d64
--- /dev/null
+++ b/node_modules/winston/docs/winston/config.html
@@ -0,0 +1,37 @@
+ config.js
\ 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
new file mode 100644
index 0000000..075edd0
--- /dev/null
+++ b/node_modules/winston/docs/winston/config/cli-config.html
@@ -0,0 +1,37 @@
+ cli-config.js
\ 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
new file mode 100644
index 0000000..8517430
--- /dev/null
+++ b/node_modules/winston/docs/winston/config/npm-config.html
@@ -0,0 +1,29 @@
+ npm-config.js
\ 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
new file mode 100644
index 0000000..6da0993
--- /dev/null
+++ b/node_modules/winston/docs/winston/config/syslog-config.html
@@ -0,0 +1,33 @@
+ syslog-config.js
\ No newline at end of file
diff --git a/node_modules/winston/docs/winston/exception.html b/node_modules/winston/docs/winston/exception.html
new file mode 100644
index 0000000..f6a4a6c
--- /dev/null
+++ b/node_modules/winston/docs/winston/exception.html
@@ -0,0 +1,56 @@
+ exception.js
\ No newline at end of file
diff --git a/node_modules/winston/docs/winston/logger.html b/node_modules/winston/docs/winston/logger.html
new file mode 100644
index 0000000..de7038a
--- /dev/null
+++ b/node_modules/winston/docs/winston/logger.html
@@ -0,0 +1,344 @@
+ logger.js
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.
@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.
Configures this instance to have the default
+settings for command-line interfaces: no timestamp,
+colors enabled, padded output, and additional levels.
\ No newline at end of file
diff --git a/node_modules/winston/docs/winston/transports.html b/node_modules/winston/docs/winston/transports.html
new file mode 100644
index 0000000..bc92fc8
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports.html
@@ -0,0 +1,29 @@
+ transports.js
\ 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
new file mode 100644
index 0000000..3d45f36
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/console.html
@@ -0,0 +1,59 @@
+ console.js
\ 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
new file mode 100644
index 0000000..b7690de
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/couchdb.html
@@ -0,0 +1,84 @@
+ couchdb.js
Constructor function for the Console transport object responsible
+for making arbitrary HTTP requests whenever log messages and metadata
+are received.
\ 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
new file mode 100644
index 0000000..bba8459
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/file.html
@@ -0,0 +1,211 @@
+ file.js
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.
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.
\ 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
new file mode 100644
index 0000000..7652318
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/loggly.html
@@ -0,0 +1,118 @@
+ loggly.js
\ 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
new file mode 100644
index 0000000..f0cc4b9
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/transport.html
@@ -0,0 +1,50 @@
+ transport.js
@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.
\ 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
new file mode 100644
index 0000000..7191495
--- /dev/null
+++ b/node_modules/winston/docs/winston/transports/webhook.html
@@ -0,0 +1,82 @@
+ webhook.js
Constructor function for the Console transport object responsible
+for making arbitrary HTTP requests whenever log messages and metadata
+are received.
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
\ No newline at end of file
diff --git a/node_modules/winston/examples/couchdb.js b/node_modules/winston/examples/couchdb.js
new file mode 100644
index 0000000..ce2d960
--- /dev/null
+++ b/node_modules/winston/examples/couchdb.js
@@ -0,0 +1,18 @@
+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
new file mode 100644
index 0000000..0fa1c8d
--- /dev/null
+++ b/node_modules/winston/examples/webhook-post.js
@@ -0,0 +1,17 @@
+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
new file mode 100644
index 0000000..51bfb45
--- /dev/null
+++ b/node_modules/winston/lib/winston.js
@@ -0,0 +1,143 @@
+/*
+ * 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
new file mode 100644
index 0000000..c8807d3
--- /dev/null
+++ b/node_modules/winston/lib/winston/common.js
@@ -0,0 +1,233 @@
+/*
+ * 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;
+ }
+
+ 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 {
+ 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
new file mode 100644
index 0000000..45e9283
--- /dev/null
+++ b/node_modules/winston/lib/winston/config.js
@@ -0,0 +1,45 @@
+/*
+ * 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
new file mode 100644
index 0000000..9798ddc
--- /dev/null
+++ b/node_modules/winston/lib/winston/config/cli-config.js
@@ -0,0 +1,35 @@
+/*
+ * 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
new file mode 100644
index 0000000..464f735
--- /dev/null
+++ b/node_modules/winston/lib/winston/config/npm-config.js
@@ -0,0 +1,27 @@
+/*
+ * 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
new file mode 100644
index 0000000..a198abc
--- /dev/null
+++ b/node_modules/winston/lib/winston/config/syslog-config.js
@@ -0,0 +1,31 @@
+/*
+ * 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
new file mode 100644
index 0000000..1131311
--- /dev/null
+++ b/node_modules/winston/lib/winston/container.js
@@ -0,0 +1,100 @@
+/*
+ * 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;
+ }
+
+ 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);
+ });
+};
\ No newline at end of file
diff --git a/node_modules/winston/lib/winston/exception.js b/node_modules/winston/lib/winston/exception.js
new file mode 100644
index 0000000..2a01e91
--- /dev/null
+++ b/node_modules/winston/lib/winston/exception.js
@@ -0,0 +1,55 @@
+/*
+ * 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
new file mode 100644
index 0000000..9332402
--- /dev/null
+++ b/node_modules/winston/lib/winston/logger.js
@@ -0,0 +1,473 @@
+/*
+ * 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.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', '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));
+ }
+
+ //
+ // 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);
+
+ 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;
+};
+
+var ProfileHandler = function(logger){
+ this.logger = logger;
+
+ this.start = Date.now();
+
+ this.done = function(msg){
+ 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
new file mode 100644
index 0000000..5080634
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports.js
@@ -0,0 +1,29 @@
+/*
+ * 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
new file mode 100644
index 0000000..b38ef04
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/console.js
@@ -0,0 +1,83 @@
+/*
+ * 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
new file mode 100644
index 0000000..66f5e75
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/couchdb.js
@@ -0,0 +1,122 @@
+/*
+ * 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
new file mode 100644
index 0000000..2a679ff
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/file.js
@@ -0,0 +1,332 @@
+/*
+ * 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
new file mode 100644
index 0000000..dd5762b
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/loggly.js
@@ -0,0 +1,161 @@
+/*
+ * 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
new file mode 100644
index 0000000..a2f941c
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/transport.js
@@ -0,0 +1,57 @@
+/*
+ * 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
new file mode 100644
index 0000000..bf8eb27
--- /dev/null
+++ b/node_modules/winston/lib/winston/transports/webhook.js
@@ -0,0 +1,136 @@
+/*
+ * 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/async/.gitmodules b/node_modules/winston/node_modules/async/.gitmodules
new file mode 100644
index 0000000..a9aae98
--- /dev/null
+++ b/node_modules/winston/node_modules/async/.gitmodules
@@ -0,0 +1,9 @@
+[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/winston/node_modules/async/LICENSE b/node_modules/winston/node_modules/async/LICENSE
new file mode 100644
index 0000000..b7f9d50
--- /dev/null
+++ b/node_modules/winston/node_modules/async/LICENSE
@@ -0,0 +1,19 @@
+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/winston/node_modules/async/Makefile b/node_modules/winston/node_modules/async/Makefile
new file mode 100644
index 0000000..00f07ea
--- /dev/null
+++ b/node_modules/winston/node_modules/async/Makefile
@@ -0,0 +1,21 @@
+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/winston/node_modules/async/README.md b/node_modules/winston/node_modules/async/README.md
new file mode 100644
index 0000000..f3c44ac
--- /dev/null
+++ b/node_modules/winston/node_modules/async/README.md
@@ -0,0 +1,1009 @@
+# 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/winston/node_modules/async/deps/nodeunit.css b/node_modules/winston/node_modules/async/deps/nodeunit.css
new file mode 100644
index 0000000..274434a
--- /dev/null
+++ b/node_modules/winston/node_modules/async/deps/nodeunit.css
@@ -0,0 +1,70 @@
+/*!
+ * 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/winston/node_modules/async/deps/nodeunit.js b/node_modules/winston/node_modules/async/deps/nodeunit.js
new file mode 100644
index 0000000..5957184
--- /dev/null
+++ b/node_modules/winston/node_modules/async/deps/nodeunit.js
@@ -0,0 +1,1966 @@
+/*!
+ * 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 +
+ ')
\ 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
new file mode 100644
index 0000000..94336be
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/common.html
@@ -0,0 +1,126 @@
+ common.js
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.
\ 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
new file mode 100644
index 0000000..0f39f4a
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/config.html
@@ -0,0 +1,41 @@
+ 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
+ *
+ */
\ 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
new file mode 100644
index 0000000..7d1a4bf
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/core.html
@@ -0,0 +1,150 @@
+ core.js
function search (query, callback)
+ Returns a new search object which can be chained
+ with options or called directly if @callback is passed
+ initially.
\ 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
new file mode 100644
index 0000000..3cc7fc5
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/device.html
@@ -0,0 +1,26 @@
+ device.js
/*
+ * device.js: Instance of a single Loggly device
+ *
+ * (C) 2010 Nodejitsu Inc.
+ * MIT LICENSE
+ *
+ */
+
+varDevice=exports.Device=function(client,details){
+ if(!details)thrownewError("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);
+};
+
\ 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
new file mode 100644
index 0000000..39fe2b3
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/facet.html
@@ -0,0 +1,26 @@
+ facet.js
\ 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
new file mode 100644
index 0000000..22bcac2
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/input.html
@@ -0,0 +1,32 @@
+ input.js
\ 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
new file mode 100644
index 0000000..0a13c0e
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/docs/loggly/search.html
@@ -0,0 +1,89 @@
+ search.js
\ 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
new file mode 100644
index 0000000..e55d2c2
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly.js
@@ -0,0 +1,25 @@
+/*
+ * 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
new file mode 100644
index 0000000..dae938e
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/common.js
@@ -0,0 +1,204 @@
+/*
+ * 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
new file mode 100644
index 0000000..2156ceb
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/config.js
@@ -0,0 +1,49 @@
+/*
+ * 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
new file mode 100644
index 0000000..9be1553
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/core.js
@@ -0,0 +1,211 @@
+/*
+ * 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
new file mode 100644
index 0000000..a06d74a
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/device.js
@@ -0,0 +1,30 @@
+/*
+ * 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
new file mode 100644
index 0000000..a17abf9
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/facet.js
@@ -0,0 +1,42 @@
+/*
+ * 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
new file mode 100644
index 0000000..1e02b85
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/input.js
@@ -0,0 +1,36 @@
+/*
+ * 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
new file mode 100644
index 0000000..09dd437
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/lib/loggly/search.js
@@ -0,0 +1,130 @@
+/*
+ * 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
new file mode 100644
index 0000000..a4a9aee
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/LICENSE
@@ -0,0 +1,55 @@
+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
new file mode 100644
index 0000000..4ea89f7
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/README.md
@@ -0,0 +1,286 @@
+# 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.readStream('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()
+* `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.
+* `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
new file mode 100644
index 0000000..e6531a2
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/forever.js
@@ -0,0 +1,84 @@
+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
new file mode 100644
index 0000000..a25393e
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/main.js
@@ -0,0 +1,652 @@
+// Copyright 2010-2011 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 = {}
+ for (var i in obj) 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}
+ }
+
+ for (var i in options) {
+ this[i] = options[i]
+ }
+ if (!this.pool) this.pool = globalPool
+ this.dests = []
+ this.__isRequestRequest = true
+}
+util.inherits(Request, stream.Stream)
+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.request = function () {
+ var self = this
+
+ // 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
+ if (self.followRedirect)
+ self.redirects = self.redirects || []
+
+ self.headers = self.headers ? copy(self.headers) : {}
+
+ var 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)
+ }
+ setHost = true
+ }
+
+ if (self.jar === false) {
+ // disable cookies
+ var cookies = false;
+ self._disableCookies = true;
+ } else if (self.jar) {
+ // fetch cookie from the user defined cookie jar
+ var cookies = self.jar.get({ url: self.uri.href })
+ } else {
+ // fetch cookie from the global cookie jar
+ var cookies = cookieJar.get({ url: self.uri.href })
+ }
+ if (cookies) {
+ var cookieString = cookies.map(function (c) {
+ return c.name + "=" + c.value;
+ }).join("; ");
+
+ self.headers.Cookie = cookieString;
+ }
+
+ 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
+ }
+
+ var clientErrorHandler = function (error) {
+ if (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.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 (self.form) {
+ self.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8'
+ self.body = qs.stringify(self.form).toString('utf8')
+ }
+
+ if (self.oauth) {
+ var form
+ if (self.headers['content-type'] &&
+ self.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) ===
+ 'application/x-www-form-urlencoded'
+ ) {
+ form = qs.parse(self.body)
+ }
+ if (self.uri.query) {
+ form = qs.parse(self.uri.query)
+ }
+ if (!form) form = {}
+ var oa = {}
+ for (var i in form) oa[i] = form[i]
+ for (var i in self.oauth) oa['oauth_'+i] = self.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 = self.uri.protocol + '//' + self.uri.host + self.uri.pathname
+ var signature = oauth.hmacsign(self.method, baseurl, oa, consumer_secret, token_secret)
+
+ // oa.oauth_signature = signature
+ for (var i in form) {
+ if ( i.slice(0, 'oauth_') in self.oauth) {
+ // skip
+ } else {
+ delete oa['oauth_'+i]
+ }
+ }
+ self.headers.authorization =
+ 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',')
+ self.headers.authorization += ',oauth_signature="'+oauth.rfc3986(signature)+'"'
+ }
+
+ 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 (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 (self.json) {
+ self.headers['content-type'] = 'application/json'
+ if (typeof self.json === 'boolean') {
+ if (typeof self.body === 'object') self.body = JSON.stringify(self.body)
+ } else {
+ self.body = JSON.stringify(self.json)
+ }
+
+ } else if (self.multipart) {
+ 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 (!self.multipart.forEach) throw new Error('Argument error, options.multipart.')
+
+ self.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--'))
+ }
+
+ 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.start = function () {
+ 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) {
+ 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 (setHost) delete self.headers.host
+ if (self.timeout && self.timeoutTimer) clearTimeout(self.timeoutTimer)
+
+ 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.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
+ }
+ )
+ delete self.req
+ delete self.agent
+ delete self._started
+ if (self.headers) {
+ delete self.headers.host
+ }
+ if (log) log('Redirect to %uri', self)
+ request(self, self.callback)
+ 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.pipeDest = function (dest) {
+ 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 (self.pipefilter) self.pipefilter(response, dest)
+ }
+
+ 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 (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)
+ }
+
+ self.req.on('error', clientErrorHandler)
+ }
+
+ 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.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.pipe = function (dest) {
+ 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)
+ this.pipeDest(dest)
+ return dest
+ }
+ } else {
+ this.dests.push(dest)
+ stream.Stream.prototype.pipe.call(this, dest)
+ 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 () {
+ if (!this._started) this.start()
+ if (!this.req) throw new Error("This request has been piped before http.request() was called.")
+ this.req.end.apply(this.req, arguments)
+}
+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)
+}
+
+function request (options, callback) {
+ if (typeof options === 'string') options = {uri:options}
+ if (callback) options.callback = callback
+ var r = new Request(options)
+ r.request()
+ return r
+}
+
+module.exports = request
+
+request.defaults = function (options) {
+ var def = function (method) {
+ var d = function (opts, callback) {
+ if (typeof opts === 'string') opts = {uri:opts}
+ for (var i in options) {
+ if (opts[i] === undefined) opts[i] = options[i]
+ }
+ return method(opts, 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 (options, callback) {
+ if (typeof options === 'string') options = {uri:options}
+ options.method = 'POST'
+ return request(options, callback)
+}
+request.put = function (options, callback) {
+ if (typeof options === 'string') options = {uri:options}
+ options.method = 'PUT'
+ return request(options, callback)
+}
+request.head = function (options, callback) {
+ if (typeof options === 'string') options = {uri:options}
+ options.method = 'HEAD'
+ if (options.body || options.requestBodyStream || options.json || options.multipart) {
+ throw new Error("HTTP HEAD requests MUST NOT include a request body.")
+ }
+ return request(options, callback)
+}
+request.del = function (options, callback) {
+ if (typeof options === 'string') options = {uri:options}
+ options.method = 'DELETE'
+ return request(options, callback)
+}
+request.jar = function () {
+ return new CookieJar
+}
+request.cookie = function (str) {
+ 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
new file mode 100644
index 0000000..8691006
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/mimetypes.js
@@ -0,0 +1,146 @@
+// from http://github.com/felixge/node-paperboy
+exports.types = {
+ "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",
+ "man":"application/x-troff-man",
+ "me":"application/x-troff-me",
+ "midi":"audio/midi",
+ "mif":"application/x-mif",
+ "mime":"www/mime",
+ "movie":"video/x-sgi-movie",
+ "mustache":"text/plain",
+ "mp4":"video/mp4",
+ "mpg":"video/mpeg",
+ "mpga":"audio/mpeg",
+ "ms":"application/x-troff-ms",
+ "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",
+ "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
new file mode 100644
index 0000000..25db669
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/oauth.js
@@ -0,0 +1,34 @@
+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 + "&" +
+ 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
new file mode 100644
index 0000000..7e194d5
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/package.json
@@ -0,0 +1,15 @@
+{ "name" : "request"
+, "description" : "Simplified HTTP request client."
+, "tags" : ["http", "simple", "util", "utility"]
+, "version" : "2.9.100"
+, "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": "bash tests/run.sh" }
+}
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
new file mode 100644
index 0000000..f80c9c5
Binary files /dev/null and b/node_modules/winston/node_modules/loggly/node_modules/request/tests/googledoodle.png differ
diff --git a/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.sh b/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.sh
new file mode 100755
index 0000000..57d0f64
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.sh
@@ -0,0 +1,6 @@
+FAILS=0
+for i in tests/test-*.js; do
+ echo $i
+ node $i || let FAILS++
+done
+exit $FAILS
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
new file mode 100644
index 0000000..2e1889f
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js
@@ -0,0 +1,75 @@
+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
new file mode 100644
index 0000000..b357f86
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.crt
@@ -0,0 +1,15 @@
+-----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
new file mode 100644
index 0000000..b85810d
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/ssl/test.key
@@ -0,0 +1,15 @@
+-----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
new file mode 100644
index 0000000..9d2e188
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js
@@ -0,0 +1,95 @@
+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
new file mode 100644
index 0000000..f17cfb3
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookie.js
@@ -0,0 +1,29 @@
+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
new file mode 100644
index 0000000..76fcd71
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-cookiejar.js
@@ -0,0 +1,90 @@
+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-errors.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-errors.js
new file mode 100644
index 0000000..a7db1f7
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-errors.js
@@ -0,0 +1,30 @@
+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.')
+}
+
+console.log("All tests passed.")
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
new file mode 100644
index 0000000..6d8c83f
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-httpModule.js
@@ -0,0 +1,94 @@
+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 = {'httpModules':httpModules, 'uri':'http://localhost:'+plain_server.port+'/to_https'}
+ var to_plain = {'httpModules':httpModules, 'uri':'https://localhost:'+https_server.port+'/to_plain'}
+
+ request(to_https, function (er, res, body) {
+ assert.ok(!er, 'Bounce to SSL worked')
+ assert.equal(body, 'https', 'Received HTTPS server body')
+ done()
+ })
+
+ request(to_plain, 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
new file mode 100644
index 0000000..df7330b
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js
@@ -0,0 +1,86 @@
+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
new file mode 100644
index 0000000..e9d3290
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-oauth.js
@@ -0,0 +1,117 @@
+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-pipes.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js
new file mode 100644
index 0000000..5785475
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js
@@ -0,0 +1,182 @@
+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)
+
+})
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
new file mode 100644
index 0000000..647157c
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-proxy.js
@@ -0,0 +1,39 @@
+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-redirect.js b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-redirect.js
new file mode 100644
index 0000000..dfa086d
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-redirect.js
@@ -0,0 +1,76 @@
+var server = require('./server')
+ , assert = require('assert')
+ , request = require('../main.js')
+
+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) {
+ hits[landing] = true;
+ res.writeHead(200)
+ res.end(landing)
+ })
+ }
+
+ // Permanent bounce
+ request(server+'/perm', 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(server+'/temp', 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', 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()
+ }
+ })
+
+ var reqs_done = 0;
+ function done() {
+ reqs_done += 1;
+ if(reqs_done == 3) {
+ 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
new file mode 100644
index 0000000..673f8ad
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-timeout.js
@@ -0,0 +1,87 @@
+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
new file mode 100644
index 0000000..1d83bd5
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/uuid.js
@@ -0,0 +1,19 @@
+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
new file mode 100644
index 0000000..1eb2eaa
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/index.js
@@ -0,0 +1,60 @@
+/*!
+ * 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
new file mode 100644
index 0000000..34920e0
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/request/vendor/cookie/jar.js
@@ -0,0 +1,72 @@
+/*!
+* 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
new file mode 100644
index 0000000..e3bc275
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore
@@ -0,0 +1,3 @@
+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
new file mode 100644
index 0000000..1effdd2
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md
@@ -0,0 +1,15 @@
+#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
new file mode 100644
index 0000000..071d8fb
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE
@@ -0,0 +1,19 @@
+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
new file mode 100644
index 0000000..2bb9904
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md
@@ -0,0 +1,199 @@
+# 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
new file mode 100644
index 0000000..bc8149d
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js
@@ -0,0 +1,226 @@
+/*!
+* 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
new file mode 100644
index 0000000..0326cbb
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js
@@ -0,0 +1 @@
+"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
new file mode 100644
index 0000000..bd54134
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css
@@ -0,0 +1,194 @@
+/*--------------------- 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
new file mode 100644
index 0000000..9eb2cc9
--- /dev/null
+++ b/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html
@@ -0,0 +1,692 @@
+ 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.
+*/
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.
Helper methods for creating new TimeSpan objects
+from various criteria: milliseconds, seconds, minutes,
+hours, days, strings and other TimeSpan instances.
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.