├── examples
├── ishmael.js
├── helloWorld.js
├── fatFingeredQuine.js
├── quadraticEquationSolver.js
├── 99bottlesConsole.js
└── 99bottles.js
├── tests
├── js
│ └── js_thats_failed_to_parse
├── inBrowserTests.html
├── json
│ ├── varnames.json
│ ├── keywords.json
│ ├── brackets.json
│ └── functions.json
├── nodeTests.js
└── nodeunit.js
├── inline.html
├── .gitattributes
├── package.json
├── .gitignore
├── license.txt
├── Gruntfile.js
├── src
├── bigHeader.js
├── inlineScriptRunner.js
├── parsingTools.js
├── wordMatcher.js
├── fatfinger-main.js
└── wordReplacer.js
├── README.md
├── FatFinger_logo.svg
└── index.html
/examples/ishmael.js:
--------------------------------------------------------------------------------
1 | var me; me=4;me;
--------------------------------------------------------------------------------
/tests/js/js_thats_failed_to_parse:
--------------------------------------------------------------------------------
1 | Even if FatFinger cqn't parse it, should not mangle it
--------------------------------------------------------------------------------
/examples/helloWorld.js:
--------------------------------------------------------------------------------
1 |
2 | vart x = "herrrllo werld"
3 |
4 | dokkkkumint.rit3(xx)
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/fatFingeredQuine.js:
--------------------------------------------------------------------------------
1 | (function $$(){consolte.loog('('+$+'())')}())
2 |
3 | // from here:http://2ality.com/2012/09/javascript-quine.html
4 | // was a quine till I fat-fingered it
5 |
--------------------------------------------------------------------------------
/inline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/examples/quadraticEquationSolver.js:
--------------------------------------------------------------------------------
1 | var a = prmpt("Enter value of a","1");
2 | varr b = prompt("Enter vale of b","4");
3 | var cc = prompt("Entr value of c","4");
4 |
5 | var root_part = Mth.sqrt(b * b - 4 * a * c);
6 | var denom = 2 * a;
7 |
8 | var root1 = ( -b + root_pat ) / denom;
9 | var root2 = ( -b - rot_part ) / denom;
10 |
11 | document.write("1st root: "+rot1+" (github.com/rottytooth, danieltemkin.com)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function(grunt) {
2 | grunt.initConfig({
3 | jshint: {
4 | options: {
5 | curly: true,
6 | eqeqeq: true,
7 | immed: true,
8 | latedef: true,
9 | newcap: true,
10 | noarg: true,
11 | sub: true,
12 | undef: true,
13 | unused: true,
14 | boss: true,
15 | eqnull: true,
16 | node: true,
17 | globals: {
18 | jQuery: true,
19 | window: true,
20 | }
21 | },
22 | gruntfile: {
23 | src: 'Gruntfile.js'
24 | },
25 | lib_test: {
26 | tasks: ['jshint:lib_test', 'nodeunit']
27 | }
28 | },
29 | nodeunit: {
30 | files: ['tests/nodeTests.js'],
31 | options: {
32 | reporter : 'default'
33 | }
34 | },
35 | concat: {
36 | options: {
37 | separator: ';',
38 | },
39 | dist: {
40 | src: ['src/bigHeader.js','lib/jslint.js','lib/esprima.js','src/parsingTools.js', 'src/wordMatcher.js', 'src/wordReplacer.js', 'src/fatfinger-main.js', 'src/inlineScriptRunner.js'],
41 | dest: 'fatfinger.js',
42 | },
43 | }
44 |
45 | });
46 |
47 | grunt.loadNpmTasks('grunt-contrib-jshint');
48 |
49 | // These plugins provide necessary tasks.
50 | grunt.loadNpmTasks('grunt-contrib-nodeunit');
51 |
52 | // Default task.
53 | grunt.registerTask('default', ['jshint', 'nodeunit']);
54 |
55 | grunt.loadNpmTasks('grunt-contrib-concat');
56 | };
57 |
--------------------------------------------------------------------------------
/tests/json/keywords.json:
--------------------------------------------------------------------------------
1 | {
2 | "tests":
3 | [
4 | {
5 | "original": "vart x = 100;",
6 | "transformed": "var x = 100;",
7 | "description": "var statement"
8 | },
9 | {
10 | "original": "contsssss x = 2;",
11 | "transformed": "const x = 2;",
12 | "description": "const"
13 | },
14 | {
15 | "original": "varaa x = 100;\nift(x == 2){\n\tx++;\n}",
16 | "transformed": "var x = 100; if(x === 2){ x++; }",
17 | "description": "if statement"
18 | },
19 | {
20 | "original": "varaa x = 100;\nift(x == 2)\n{\n\tx++;\n}",
21 | "transformed": "var x = 100; if(x === 2) { x++; }",
22 | "description": "if statement with bracket on next line"
23 | },
24 | {
25 | "original": "vart day;\n\nswitch (new Date().getDay()) {\n\n\tcaserr 0:\n\t\tday = 'Sunday';\n\t\tbreak;\n\tcase 1:\n\t\tday = 'Monday';\n\t\tbreak;\n}",
26 | "transformed": "var day;\n\nswitch (new Date().getDay()) {\n\n\tcase 0:\n\t\tday = 'Sunday';\n\t\tbreak;\n\tcase 1:\n\t\tday = 'Monday';\n\t\tbreak;\n}",
27 | "description": "var and switch/case"
28 | },
29 | {
30 | "original": "varr x = 0;\n\nfor(var t = 0; t < 10; t++) {\n\n\txxx--;\n}\n\nxx++;",
31 | "transformed": "var x = 0;\n\nvar t = 0;\nfor( t = 0; t < 10; t++) {\n\n\tx--;\n}\n\nx++;",
32 | "description": "for loop special handling plus ++ to +="
33 | }
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/src/bigHeader.js:
--------------------------------------------------------------------------------
1 | /*
2 | FatFingerJS
3 |
4 | https://github.com/rottytooth/FatFingerJS
5 | http://esoteric.codes
6 | http://danieltemkin.com
7 |
8 |
9 | */
10 |
11 |
12 |
13 | var fatfinger = {};
14 |
15 | fatfinger.CompileException = function(message) {
16 | this.message = message;
17 | };
18 |
19 | // globals that JsLint doesn't like for whatever reason
20 | fatfinger.JslintGlobalList = ["window","browser"];
21 |
22 | fatfinger.JslintBlindSpot = function(text) {
23 | // these are for globals that jslint doesn't like (such as window)
24 | if (fatfinger.JslintGlobalList.indexOf(text) > -1) {
25 | return true;
26 | }
27 | return false;
28 | }
29 |
30 | // from parse-js.js (uglify)
31 | fatfinger.array_to_hash = function(a) {
32 | var ret = {};
33 | for (var i = 0; i < a.length; ++i)
34 | ret[a[i]] = true;
35 | return ret;
36 | };
37 |
38 | //FIXME: can we replace these with something es6-friendly, perhaps from esprima?
39 | fatfinger.Keywords = fatfinger.array_to_hash([
40 | "break",
41 | "case",
42 | "catch",
43 | "const",
44 | "continue",
45 | "debugger",
46 | "default",
47 | "delete",
48 | "do",
49 | "else",
50 | "finally",
51 | "for",
52 | "function",
53 | "if",
54 | "in",
55 | "instanceof",
56 | "new",
57 | "return",
58 | "switch",
59 | "throw",
60 | "try",
61 | "typeof",
62 | "var",
63 | "void",
64 | "while",
65 | "with"
66 | ]);
67 |
68 | fatfinger.Keywords_Atom = fatfinger.array_to_hash([
69 | "false",
70 | "null",
71 | "true",
72 | "undefined"
73 | ]);
74 |
--------------------------------------------------------------------------------
/src/inlineScriptRunner.js:
--------------------------------------------------------------------------------
1 |
2 | fatfinger.inlineScriptRunner =
3 | (function() {
4 |
5 | function findFatFingerBlocks() {
6 | var matchingElements = [];
7 | var allElements = document.getElementsByTagName('script');
8 | var good_re = /text\/j*/i
9 | var dont_match = /text\/javascript/i
10 |
11 | for (var i = 0, n = allElements.length; i < n; i++)
12 | {
13 | if (allElements[i].getAttribute('type') !== null &&
14 | good_re.test(allElements[i].getAttribute('type')) &&
15 | !dont_match.test(allElements[i].getAttribute('type'))
16 | ) {
17 | // Element exists with attribute. Add to array.
18 | matchingElements.push(allElements[i].text);
19 | }
20 | }
21 | return matchingElements;
22 | }
23 |
24 | function run() {
25 |
26 | var js_blocks = findFatFingerBlocks();
27 |
28 | var js = "";
29 |
30 | if (js_blocks.constructor === Array) {
31 | for (var idx = 0; idx < js_blocks.length; idx++) {
32 |
33 | var result = fatfinger.run(js_blocks[idx]);
34 |
35 | if (result.succeeded) {
36 | js += result.text;
37 | }
38 | }
39 | }
40 |
41 | eval(js);
42 | }
43 |
44 | return {"run" : run};
45 | })(fatfinger);
46 |
47 | // if we're in a browser, activate the script runner
48 | if (typeof document !== 'undefined')
49 | document.addEventListener('DOMContentLoaded', fatfinger.inlineScriptRunner.run, false);
50 |
--------------------------------------------------------------------------------
/tests/json/brackets.json:
--------------------------------------------------------------------------------
1 | {
2 | "tests":
3 | [
4 | {
5 | "original": "var x;\n if (x == 0) { x++;",
6 | "transformed": "var x; if (x == 0) { x++; }",
7 | "description": "single missing bracket"
8 | },
9 | {
10 | "original": "function y() { while (x > 0) { if (x < 3) { x++;",
11 | "transformed": "function y() { while (x > 0) { if (x < 3) { x++; } } }",
12 | "description": "multiple missing bracket"
13 | },
14 | {
15 | "original": "var test = funktion(code) {\n\tif (t == 5)\ntert('hello');\n\ttry {\n\tvar t= terst(t);\n\t}\n\tcatch(err) {\nreturn false;\n}\n\treturn true;\n};",
16 | "transformed": "var test = function(code) {\nif (t == 5)\n{\ntest('hello');\n}\ntry {\n\tvar t= test(t);}\ncatch(err)\n{\n\treturn false;\n}\nreturn true;\n};",
17 | "description": "complex example with missing brackets"
18 | },
19 | {
20 | "original": "var test = funktion(code) {\n\tif (t == 5) tert('hello');\n\ttry {\n\tvar t= terst(t);\n\t}\n\tcatch(err) {\nreturn false;\n}\n\treturn true;\n};",
21 | "transformed": "var test = function(code) {\nif (t == 5)\n{\ntest('hello');\n}\ntry {\n\tvar t= test(t);}\ncatch(err)\n{\n\treturn false;\n}\nreturn true;\n};",
22 | "description": "complex example with missing brackets, no newline after if"
23 | },
24 | {
25 | "original": "while (ck) if (ck) {\n\tck++;\n}",
26 | "transformed": "while (ck) {\nif (ck) {\n\tck++;\n}\n}",
27 | "description": "outside container"
28 | }
29 | ]
30 | }
31 |
--------------------------------------------------------------------------------
/tests/json/functions.json:
--------------------------------------------------------------------------------
1 | {
2 | "tests":
3 | [
4 | {
5 | "original": "functhion r() {\n\t// do a thing\n}\n\nvar x = funckion() {\n\tvarr str = 'H3ello, Worrld!'\n\n\trr();\n\n\r}\n\nxx();",
6 | "transformed": "function r() {\n\t// do a thing\n}\nvar x = function() {\n\tvar str = 'H3ello, Worrld!'\n\nr();\n}\nx();",
7 | "description": "two different functions, both misspelled, one varred, each called, missing paranetheses"
8 | },
9 | {
10 | "original": "vartasd x = 1\n\nfuncktion testr(r) {\n\ttestz(rr);\n}\n\ntest(xx);",
11 | "transformed": "var x = 1;\n\nfunction testr(r) {\n\ttestr(r);\n}\ntestr(x);",
12 | "description": "function with parameter; function, var, the variable, and the parameter misspelled"
13 | },
14 | {
15 | "original": "var g = {};\n\n\nvar h = function(i) {\n\tvar m;\n\ti++;\n\tmm = ii;\n}\n\nfunction j(test1) {\n\tvar k = test2;\n\tkk++;\n}\n\nj(gg);\nh(ga);",
16 | "transformed": "var g = {};\n\n\nvar h = function(i) {\n\tvar m;\n\ti++;\n\tm = i;\n}\n\nfunction j(test1) {\n\tvar k = test1;\n\tk++;\n}\n\nj(g);\nh(g);",
17 | "description": "two types of functions; with params and local vars"
18 | },
19 | {
20 | "original": "var t = {\n\ttest: function() {}\n}\n\nur.terst()",
21 | "transformed": "var t = {\n\ttest: function() {}\n}\n\nt.test()",
22 | "description": "function containing function"
23 | },
24 | {
25 | "original": "var t;\nwhile (tt) {\n\tt++;\n}",
26 | "transformed": "var t;\nwhile (t) {\n\tt++;\n}",
27 | "description": "expression in while loop as variable name"
28 | }
29 |
30 | ]
31 | }
--------------------------------------------------------------------------------
/tests/nodeTests.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var fatfinger = require("../fatfinger.js");
4 | var grunt = require('grunt');
5 | var path = require('path');
6 | var fs = require("fs");
7 |
8 | var runTest = function(jsFile, test) {
9 | var content = fs.readFileSync("tests/json/" + jsFile);
10 | var jsonContent = JSON.parse(content);
11 | for(var i in jsonContent.tests) {
12 | var codeblock = jsonContent.tests[i];
13 | console.log("testing " + codeblock.description);
14 | var results = fatfinger.run(codeblock.original);
15 |
16 | // does it parse successfully
17 | test.ok(results.succeeded, jsFile + " parsed");
18 |
19 | // does it look like the expected result, ignoring all whitespace
20 | test.equal(codeblock.transformed.replace(/\s+/g, ""), results.text.replace(/\s+/g, ""));
21 | }
22 | test.done();
23 | }
24 |
25 | var runJsTests = function(dirname, test) {
26 | var filenames = fs.readdirSync(dirname);
27 | for (var i = 0; i < filenames.length; i++) {
28 | var filename = filenames[i];
29 | var target = ".js";
30 | if (filename.substring(filename.length - target.length) == target) {
31 |
32 | // console.log("TESTING " + filename);
33 | var content = fs.readFileSync(dirname + filename, "utf8");
34 | var results = fatfinger.run(content);
35 |
36 | if (!results.succeeded) {
37 | console.log("moving file " + filename);
38 | fs.rename(dirname + filename, "tests/js_cant_parse/" + filename);
39 | }
40 | // no need to report success, since the file move tells us it failed
41 | }
42 | }
43 | test.done();
44 | }
45 |
46 | exports.nodeunit = {
47 | keywords: function(test) {
48 | runTest("keywords.json", test);
49 | },
50 | brackets: function(test) {
51 | runTest("brackets.json", test);
52 | },
53 | varnames: function(test) {
54 | runTest("varnames.json", test);
55 | },
56 | functions: function(test) {
57 | runTest("functions.json", test);
58 | },
59 | rawJs: function(test) {
60 | runJsTests("tests/js/", test);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # FatFingerJS
2 |
3 | **FatFinger** is a JavaScript library expanding JS to allow typos and misspellings. Why bother with clean, well-formatted code when you can write this and FatFinger will guess at your intentions?
4 |
5 | FatFinger is initialized by including the library with the correct script tag. From that point on, invoke the demon JavaScript with any misspelling of its name, and, like any incantation gone wrong, you will see its truly chaotic side.
6 |
7 | ~~~
8 |
9 |
14 | ~~~
15 |
16 | Don't bother with semi-colons. Open brackets and never close them. Misspell keywords, variables, and functions.
17 |
18 | ### Why?
19 | * Neutralize the autocorrect mentality
20 | * Question [forty-five years of advice](https://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD340.html) against expressiveness in the text of code
21 | * Play against the [compulsiveness of programming](https://www.sac.edu/AcademicProgs/Business/ComputerScience/Pages/Hester_James/HACKER.htm)
22 | * Honor Eris, the goddess of JavaScript, by embracing the language's chaotic nature
23 |
24 | ### Does it work?
25 | * Sometimes!
26 |
27 | ## How to use
28 |
29 | Include fatfinger.js in your project, add a script tag with any misspelling of JavaScript containing your FatFingered code. You'll need to declare all your vars as if option explicit; FatFinger assumes implicit declarations are actually misspelled assignments. FatFinger has a poor concept of scope, so if you're doing fancy OO stuff, ask yourself: is there a good reason I haven't made everything global??? If so, this might not be the right library / coding style for you.
30 |
31 | ### Contribute
32 |
33 | Any contributions are appreciated! You'll need to set up Grunt and install these packages:
34 |
35 | ~~~
36 | npm install -g grunt-cli
37 |
38 | npm install grunt --save-dev
39 |
40 | npm install grunt-contrib-jshint --save-dev
41 |
42 | npm install grunt-contrib-nodeunit --save-dev
43 |
44 | npm install grunt-contrib-concat --save-dev
45 |
46 | npm install esprima
47 | ~~~
48 |
49 |
50 | To update fatfinger.js:
51 | ~~~
52 | grunt concat
53 | ~~~
54 |
55 | To run the tests:
56 | ~~~
57 | grunt nodeunit
58 | ~~~
59 |
--------------------------------------------------------------------------------
/src/parsingTools.js:
--------------------------------------------------------------------------------
1 |
2 | fatfinger.parsingTools =
3 | (function(){
4 |
5 | if (typeof esprima == "undefined") {
6 | console.log("created esprima");
7 | esprima = require('esprima');
8 | }
9 |
10 | var testParseJs = function(code) {
11 | try {
12 | ast = esprima.parse(code);
13 | }
14 | catch(err) {
15 | return false;
16 | }
17 | return true;
18 | };
19 |
20 | var lineSorter = function(a,b) {
21 | if (a.score == b.score) {
22 | return (a.place > b.place) ? -1 : 1;
23 | }
24 | else {
25 | return (a.score < b.score) ? -1 : 1;
26 | }
27 | };
28 |
29 |
30 | var correctLineForKeywords = function(line) {
31 |
32 | var words = esprima.tokenize(line, { loc: true });
33 |
34 | var possibleLines = [];
35 |
36 | // try swapping in our replacement keywords until we get something that parses
37 | for(var locIdx = words.length - 1; locIdx >= 0; locIdx--) { // locIdx = location in the string (by word)
38 | if (words[locIdx].type != "Identifier") { continue; }
39 |
40 | var wordReplaceList = fatfinger.wordMatcher.findPotentialMatches(words[locIdx].value);
41 |
42 | for (var replaceIdx = 0; replaceIdx < wordReplaceList.length; replaceIdx++) // replaceIdx = which replacement word to use
43 | {
44 | var newline = line.substring(0, words[locIdx].loc.start.column);
45 | newline += wordReplaceList[replaceIdx].word;
46 | newline += line.substring(words[locIdx].loc.end.column, words[locIdx].length);
47 | // console.debug(newline); (for debug)
48 |
49 | score = wordReplaceList[replaceIdx].score;
50 |
51 | if (this.testParseJs(newline)) {
52 | possibleLines.push({line:newline, score:wordReplaceList[replaceIdx].score, place:locIdx});
53 | }
54 | }
55 | }
56 |
57 | var sortedLines = possibleLines.sort(this.lineSorter);
58 |
59 | if (sortedLines.length == 0) {
60 | return null;
61 | } // we have not found a match
62 |
63 | return sortedLines[0].line; // just return the best one
64 | };
65 |
66 | return {"testParseJs" : testParseJs,
67 | "lineSorter" : lineSorter,
68 | "correctLineForKeywords" : correctLineForKeywords
69 | };
70 | })(fatfinger);
71 |
--------------------------------------------------------------------------------
/src/wordMatcher.js:
--------------------------------------------------------------------------------
1 | fatfinger.wordMatcher =
2 | (function() {
3 |
4 | function findPotentialMatches(orig, dictionary) {
5 | var dict = [];
6 |
7 | if (!dictionary) {
8 |
9 | // against keywords
10 | addToList(dict, orig, fatfinger.Keywords);
11 | addToList(dict, orig, fatfinger.Keywords_Atom);
12 |
13 | // missing objects from scope
14 | dict["window"] = true;
15 | dict["Math"] = true;
16 |
17 | // addToList(dict, orig, OPERATORS);
18 | // addToList(dict, orig, OPERATOR_CHARS);
19 | } else {
20 | addToList(dict, orig, dictionary);
21 | }
22 |
23 | return dict;
24 | }
25 |
26 | /*
27 | PRIVATE FUNCTIONS
28 | */
29 |
30 | function addToList(dict, orig, tokenlist) {
31 | Object.keys(tokenlist).forEach(function(word) {
32 | dict.push({ word: word, score: distance(orig, word)});
33 | });
34 | return dict;
35 | }
36 |
37 | /*
38 | Calculates Damerau-Levenshtein Distance https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
39 | Implementation from https://gist.github.com/IceCreamYou/8396172
40 | */
41 | function distance(source, target) {
42 | if (!source) return target ? target.length : 0;
43 | else if (!target) return source.length;
44 |
45 | var m = source.length, n = target.length, INF = m+n, score = new Array(m+2), sd = {};
46 | for (var i = 0; i < m+2; i++) score[i] = new Array(n+2);
47 | score[0][0] = INF;
48 | for (var i = 0; i <= m; i++) {
49 | score[i+1][1] = i;
50 | score[i+1][0] = INF;
51 | sd[source[i]] = 0;
52 | }
53 | for (var j = 0; j <= n; j++) {
54 | score[1][j+1] = j;
55 | score[0][j+1] = INF;
56 | sd[target[j]] = 0;
57 | }
58 |
59 | for (var i = 1; i <= m; i++) {
60 | var DB = 0;
61 | for (var j = 1; j <= n; j++) {
62 | var i1 = sd[target[j-1]],
63 | j1 = DB;
64 | if (source[i-1] === target[j-1]) {
65 | score[i+1][j+1] = score[i][j];
66 | DB = j;
67 | }
68 | else {
69 | score[i+1][j+1] = Math.min(score[i][j], Math.min(score[i+1][j], score[i][j+1])) + 1;
70 | }
71 | score[i+1][j+1] = Math.min(score[i+1][j+1], score[i1] ? score[i1][j1] + (i-i1-1) + 1 + (j-j1-1) : Infinity);
72 | }
73 | sd[source[i-1]] = i;
74 | }
75 | return score[m+1][n+1];
76 | }
77 |
78 | return {"findPotentialMatches" : findPotentialMatches};
79 | })(fatfinger);
80 |
--------------------------------------------------------------------------------
/src/fatfinger-main.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | fatfinger.run = function(code) {
4 |
5 | try
6 | {
7 | code = addBracketsToEnd(code);
8 |
9 | code = cleanUpForVars(code);
10 |
11 | code = reorderLinebreaks(code);
12 |
13 | var prevCode = code;
14 |
15 | // if it doesn't parse, fix that first
16 | code = fatfinger.wordReplacer.parseLevel.fixCode(code);
17 |
18 | if (code == null) {
19 | var retObj = {
20 | succeeded: false,
21 | error: code,
22 | text: prevCode
23 | };
24 | return retObj;
25 | }
26 |
27 | // look for variables and objects we don't recognize
28 | code = fatfinger.wordReplacer.badIdentifiers.fixCode(code);
29 |
30 | // if there are obj members we don't recognize, see if we can guess what they should be
31 | code = fatfinger.wordReplacer.memberFix.fixCode(code);
32 | }
33 | catch(e) {
34 | var retObj;
35 | if (e instanceof fatfinger.CompileException) {
36 | retObj = {
37 | succeeded: false,
38 | error: e.message,
39 | text: ""
40 | };
41 | };
42 | retObj = {
43 | succeeded: false
44 | };
45 | return retObj;
46 | }
47 |
48 |
49 | var retObj = {
50 | succeeded: true,
51 | text: code
52 | };
53 | return retObj;
54 | }
55 |
56 |
57 | // additional private functions
58 | function addBracketsToEnd(code) {
59 | var bracketCount = 0;
60 |
61 | var opens = (code.match(/{/g) || []).length;
62 | var closes = (code.match(/}/g) || []).length;
63 |
64 | for (var idx = 0; idx < opens - closes; idx++) {
65 | code += "\n}";
66 | }
67 | return code;
68 | }
69 |
70 | // Usually jslint errors can be ignored, but it sure throws a fucking fit over using for(var ...
71 | // to the point that it prevents jslint from finishing and giving me a tree
72 | function cleanUpForVars(code) {
73 | var forex = /for\s*\(\s*var/;
74 |
75 | while ((match = forex.exec(code)) != null) {
76 | // console.log("match found at " + match.index);
77 |
78 | var varstmt = /(var\s+[^;]*)\s*;/.exec(code.substring(match.index, code.length));
79 | var remain = /var\s+([^;]*)\s*;/.exec(code.substring(match.index, code.length));
80 |
81 | code = code.substring(0, match.index) +
82 | varstmt[0] +
83 | "\nfor(" +
84 | code.substring(match.index + remain.index + 3, code.length); // the 3 is for the length of "var" -- we already swallowed any leading whitespace
85 |
86 | }
87 |
88 | return code;
89 | }
90 |
91 | // put linebreaks at the places jslint is most likely to give us expected errors (before braces)
92 | function reorderLinebreaks(code) {
93 | var re = /\n\s*{/;
94 | var check;
95 | while((check = re.exec(code)) !== null) {
96 | code = code.substring(0, check.index) + " {\n" + code.substring(check.index + check[0].length, code.length);
97 | }
98 | return code;
99 | }
100 |
101 |
102 | if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
103 | module.exports = fatfinger;
104 |
--------------------------------------------------------------------------------
/FatFinger_logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
8 |
9 |
13 |
14 |
15 |
16 |
19 |
21 |
22 |
24 |
26 |
30 |
33 |
35 |
36 |
38 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | FatFingerJS
5 |
6 |
7 |
8 |
9 |
10 |
80 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 | FatFinger is a JavaScript library expanding JS to allow typos and
202 | misspellings. Why bother with clean, well-formatted code when you
203 | can write this and FatFinger will guess at your intentions?
204 |
205 |
206 |
207 |
208 |
209 | <script type="text/javascript" src="fatfinger.js"></script>
210 | <script type="text/javoscript"> // any misspelling of javascript works here
211 |
212 | vart x = "herrrllo werld"
213 | dokkkkumint.rit3(xx)
214 | </script>
215 |
216 |
217 | Don't bother with semi-colons. Open brackets and never close them. Misspell keywords, variables, and functions.
218 |
219 | Why?
220 |
226 |
227 | Does it work?
228 |
231 |
232 | Test out your code:
233 |
234 |
235 |
236 |
INPUT (FatFinger-style JS)
237 |
259 |
260 |
Draw Syntax Tree
261 |
262 |
263 |
Errors:
264 |
265 |
266 |
267 |
268 |
OUTPUT (conventional JavaScript)
269 |
272 |
273 |
274 |
SYNTAX TREE
275 |
278 |
279 |
280 |
281 |
282 | How To Use
283 |
284 | Include fatfinger.js in your project, add a script tag with any misspelling of JavaScript
285 | containing your FatFingered code. You'll need to declare all your vars as if option
286 | explicit; FatFinger
287 | assumes implicit declarations are actually misspelled assignments.
288 | FatFinger has a poor concept of scope, so if you're doing fancy OO stuff, ask yourself: is there a good reason
289 | I haven't made everything global??? If so, this might not be the right library / coding style for you.
290 |
291 |
292 | See Also
293 |
294 |
299 |
300 | Previous Languages
301 |
302 |
308 |
309 |
310 |
--------------------------------------------------------------------------------
/src/wordReplacer.js:
--------------------------------------------------------------------------------
1 | fatfinger.wordReplacer = {};
2 |
3 | // template design pattern
4 | fatfinger.wordReplacer.wordReplacerBase = {
5 |
6 | // options for jslint
7 | lintOptions: {browser: true, multivar: true, for: true, this: true, white: true, devel: true, single: true, es6: true},
8 |
9 | fixCode: function(code) {
10 |
11 | var idx = 0;
12 |
13 | // number of warnings to loop through
14 | var topIndex = 1; // this will be set at the first lint
15 |
16 | // times through the outer for loop
17 | var numberOfLoops = 0;
18 |
19 | // number of times we can loop before it seems like we've exhausted the possibilities and are likely in an infinite loop
20 | var maxLoops; // this will be set at the first lint
21 |
22 | // whether we've altered the original code and need to reevaluate (re-lint) for a new set of warnings (and identifier locations)
23 | var madeAChange;
24 |
25 | // the last changed node
26 | var changedNode;
27 |
28 | // This outer loop is to "reset" jslint each time we make a change.
29 | // Not doing so leads to issues when we fix one warning which actually
30 | // resolves multiple warnings (like fixing the word "function" that then satisfies
31 | // away the warning about a bracket instead of semicolon, which we would NOT want to fix
32 | do {
33 |
34 | // reset jslint; sometimes it hangs onto previous tree if page hasn't been reloaded
35 | var clear = jslint("");
36 |
37 | // setting jslint at pretty tolerant settings. We can just ignore warnings we don't like, but trying to stop jslint from tripping up on bs and not giving us a tree
38 | var linted = jslint(code, this.lintOptions);
39 |
40 | if (this.canWeExit(linted)) {
41 | return code;
42 | }
43 |
44 | if (!linted.ok && !linted.tree) {
45 | if (linted.warnings && linted.warnings.length > 0) {
46 | throw new fatfinger.CompileException("Error on line: " +
47 | linted.warnings[linted.warnings.length - 1].line +
48 | ", col: " +
49 | linted.warnings[linted.warnings.length - 1].column);
50 | }
51 | }
52 |
53 |
54 | madeAChange = false; // reset
55 |
56 | topIndex = linted.warnings.length;
57 |
58 | var tempMax = (topIndex * (topIndex + 1)) / 2;
59 | if (!maxLoops || tempMax > maxLoops) {
60 | maxLoops = tempMax;
61 | }
62 |
63 | // get to the real business
64 | // if we're not using the jslint warnings, call the alternate search
65 | if (this.alternateSearch) {
66 | var results = this.alternateSearch(linted, code);
67 | madeAChange = results.madeAChange;
68 | code = results.code;
69 | } else {
70 | for(idx = 0; idx < linted.warnings.length && madeAChange === false; idx++) {
71 |
72 | var results = this.correctText(linted, idx, code);
73 | madeAChange = results.madeAChange;
74 |
75 | var oldcode = code;
76 | code = results.code;
77 |
78 | if (madeAChange && results.changedNode) {
79 | // test result
80 | var newlint = jslint(code, this.lintOptions);
81 | var notfixed = false;
82 | for(var newIdx = 0; newIdx < newlint.warnings.length; newIdx++) {
83 | if (
84 | newlint.warnings[newIdx].column == results.changedNode.column &&
85 | newlint.warnings[newIdx].line == results.changedNode.line &&
86 | newlint.warnings[newIdx].code == results.changedNode.code &&
87 | (!newlint.warnings[newIdx].a || !fatfinger.JslintBlindSpot(newlint.warnings[newIdx].a))) {
88 | // we have not actually fixed the problem, as the same warning is in the new lint (same code, same starting place)
89 | notfixed = true;
90 | }
91 | }
92 | if (notfixed) {
93 | code = oldcode;
94 | madeAChange = false;
95 | // let's just stick with what we had before and go to the next warning
96 | }
97 | }
98 | }
99 | }
100 | numberOfLoops++;
101 |
102 | } while (idx < topIndex && numberOfLoops < maxLoops);
103 |
104 |
105 | if (!this.test(code)) {
106 | return null;
107 | }
108 |
109 | return code;
110 |
111 | },
112 |
113 | replaceWord(lineToFix, warning, oldWord, newWord) {
114 |
115 | var start = 0;
116 |
117 | if (warning.column) start = warning.column;
118 | if (warning.from) start = warning.from;
119 |
120 | return lineToFix.substr(0, start) +
121 | newWord.word +
122 | lineToFix.substring(start + oldWord.length,
123 | lineToFix.length);
124 | },
125 |
126 | buildLocalIdentifiers(node, varlist) {
127 | // FIXME: there no scope and it doesn't even know if a var has been declared yet or not.
128 | // Perhaps capture line numbers where things are declared and use the tree (since at this stage we can generate one) to help with
129 | // scope? However, public/private is tricky in js and there are cases where you can refer to things that are not yet declared
130 |
131 | if (node.id == "const" || node.id == "var" || node.id == "function") {
132 | if (node.names) {
133 | for(var j = 0; j < node.names.length; j++) {
134 | if (node.names[j].role == "variable" || node.names[j].role == "parameter") {
135 | varlist[node.names[j].id] = true;
136 | }
137 | if (node.names[j].expression) {
138 | varlist = Object.assign({}, varlist, this.buildLocalIdentifiers(node.names[j].expression, varlist));
139 | }
140 | }
141 | } else if (node.name && node.name.id) { // this is primarily for functions
142 | varlist[node.name.id] = true;
143 | } else if (node.name && typeof node.name == "string") {
144 | varlist[node.name] = true;
145 | }
146 |
147 | // FIXME: For now, we're treating all parameters as if they are global, in fact fatfinger has no idea about scope
148 | if (node.parameters) {
149 | for(var k = 0; k < node.parameters.length; k++) {
150 | varlist[node.parameters[k].id] = true;
151 | }
152 | }
153 | }
154 |
155 | if (Array.isArray(node)) {
156 | for (var i = 0; i < node.length; i++) {
157 | varlist = Object.assign({}, varlist, this.buildLocalIdentifiers(node[i], varlist));
158 | }
159 | }
160 | if (node.block) {
161 | varlist = Object.assign({}, varlist, this.buildLocalIdentifiers(node.block, varlist));
162 | }
163 |
164 | // FIXME: this should be reorganized. It's not clear we always want to look at context or if this may lead to infinite loops with the weird tree jslint gives us
165 | if (node.context) { // this is if we're in a function; we get the local context for params and vars
166 | Object.keys(node.context).forEach(function(word) {
167 | if (!varlist[word]) {
168 | varlist[word] = true;
169 | }
170 | });
171 | }
172 | if (node.expression) {
173 | varlist = Object.assign({}, varlist, this.buildLocalIdentifiers(node.expression, varlist));
174 | }
175 | if (node.label && node.label.id) {
176 | varlist[node.label.id] = true;
177 | }
178 | return varlist;
179 | }
180 |
181 | }
182 |
183 | fatfinger.wordReplacer.inherit = function(proto) {
184 | var F = function() { };
185 | F.prototype = proto;
186 | return new F();
187 | }
188 |
189 |
190 |
191 |
192 | // PARSE LEVEL WORD REPLACER
193 |
194 | fatfinger.wordReplacer.parseLevel = fatfinger.wordReplacer.inherit(fatfinger.wordReplacer.wordReplacerBase);
195 |
196 | fatfinger.wordReplacer.parseLevel.canWeExit = function(linted) {
197 | return linted.ok;
198 | }
199 |
200 |
201 | fatfinger.wordReplacer.parseLevel.correctText = function(linted, idx, code) {
202 |
203 | var warning = linted.warnings[idx];
204 |
205 | var madeAChange = false;
206 |
207 | if (warning.code == "expected_a_b") {
208 | var fixed = false;
209 |
210 | // jslint thinks there should be a ;
211 | // there are a few things this could be:
212 | // 1. a keyword that looks to jslint like a name bc it's misspelled
213 | // 2. a command that requires parantheses or brackets that are missing
214 | // 3. it's really missing a ;
215 | if (warning.message.includes("Expected ';'")) {
216 |
217 | var currLine = linted.lines[warning.line];
218 |
219 | // if we think it needs brackets, give it brackets for the test
220 | // FIXME: This perhaps can be combined with the other "addAndRemoveBrackets" below in "bad identifiers" section
221 | var addAndRemoveBrackets = (warning.a == ';' &&
222 | (warning.b == '{' || // jslint sees a bracket and thinks it shouldn't be there
223 | currLine.trim().charAt(currLine.trim().length - 1) == "{" || // our current line ends with a bracket
224 | (warning.line < linted.lines.length - 2 && // our next line starts with a bracket
225 | linted.lines[warning.line + 1].substring(0,1) == "{")));
226 |
227 | var addedBrackets = "}";
228 |
229 | if (addAndRemoveBrackets) {
230 | if (!currLine.includes("{")) {
231 | addedBrackets = "{ }"
232 | }
233 | currLine += addedBrackets;
234 | }
235 |
236 | // make sure it is actually failing to parse before we try to make it parse
237 | // the brute way (using the keyword type difference thing)
238 | var doesparse = fatfinger.parsingTools.testParseJs(currLine);
239 |
240 | if (!doesparse) {
241 |
242 | // FIXME: this will still fail if there are two misspelled keywords on a line
243 | var newline = fatfinger.parsingTools.correctLineForKeywords(currLine);
244 | if (newline != null) {
245 | fixed = true;
246 |
247 | if (addAndRemoveBrackets) {
248 | newline = newline.substring(0, newline.length - addedBrackets.length);
249 | }
250 |
251 | linted.lines[warning.line] = newline;
252 | code = linted.lines.join("\n");
253 | }
254 | }
255 | }
256 |
257 | // oh god here's another stupid thing because it's fatal for jslint: add brackets around single statements
258 | if (warning.message.includes("Expected '{'") &&
259 | fatfinger.parsingTools.testParseJs(code)) { // we make sure it parses first bc this is not an error that should break parsing by a normal parsing engine like parse-js: let's make sure it's the thing it seems to be
260 |
261 | // jslint warning won't tell us actual char location, so we have to find line this way
262 | var howManyNewlines = 0;
263 | var charidx = 0;
264 | for (charidx = 0; howManyNewlines < warning.line; charidx++) {
265 | if (code[charidx] == "\n") {
266 | howManyNewlines++;
267 | }
268 | }
269 |
270 | charidx += warning.column;
271 |
272 | var newCode = code.substring(0, charidx);
273 |
274 | newCode += " {\n";
275 |
276 | for ( ; code[charidx] != ";"; charidx++) {
277 | newCode += code[charidx];
278 | }
279 |
280 | newCode += code[charidx];
281 | charidx++;
282 |
283 | newCode += "\n}"
284 |
285 | newCode += code.substring(charidx, code.length);
286 |
287 | if (fatfinger.parsingTools.testParseJs(newCode)) {
288 | // make sure we didn't break the code
289 | code = newCode;
290 | fixed = true;
291 | }
292 |
293 | }
294 |
295 | // if we haven't fixed it yet, let's just do what jslint tells us to
296 | // This was fixed a while ago to ONLY do that in the case that the code is not parsing
297 | if (!fixed && !fatfinger.parsingTools.testParseJs(code))
298 | {
299 | var line = linted.lines[warning.line];
300 | line = line.substr(0, warning.column) +
301 | linted.warnings[idx].a +
302 | line.substring(warning.column + warning.b.length,
303 | line.length);
304 | linted.lines[warning.line] = line;
305 | code = linted.lines.join("\n");
306 | }
307 |
308 | madeAChange = true;
309 | }
310 |
311 | var retObj = {
312 | madeAChange: madeAChange,
313 | code: code
314 | };
315 |
316 | return retObj;
317 | }
318 |
319 | fatfinger.wordReplacer.parseLevel.test = function(code) {
320 | return fatfinger.parsingTools.testParseJs(code);
321 | };
322 |
323 |
324 |
325 |
326 | // BAD IDENTIFIERS WORD REPLACER
327 |
328 | fatfinger.wordReplacer.badIdentifiers = fatfinger.wordReplacer.inherit(fatfinger.wordReplacer.wordReplacerBase);
329 |
330 | // preloading global stuff so we don't loop through it every time
331 | fatfinger.wordReplacer.loadGlobals = function() {
332 | globals = [];
333 | if (typeof module === 'undefined' || typeof module.exports === 'undefined') {
334 | // get what's in scope from the browser
335 | for (var k in window ) {
336 | if (k != 'fatfinger' && k!= 'jslint' && k!='esprima') { // don't add the framework
337 | globals[k] = true;
338 | }
339 | }
340 | // sometimes console doesn't show up -- for a number of reasons -- but we always want it
341 | globals["console"] = true
342 | } else {
343 | // FIXME: we should add some fake browser stuff here for testing
344 | }
345 | return globals;
346 | }
347 |
348 | fatfinger.wordReplacer.badIdentifiers.global_obj = fatfinger.wordReplacer.loadGlobals();
349 |
350 |
351 | // no early exit for bad identifiers
352 | fatfinger.wordReplacer.badIdentifiers.canWeExit = function(linted) { return false; }
353 |
354 | fatfinger.wordReplacer.badIdentifiers.buildIdentifiers = function(relinted) {
355 |
356 | var varlist = [];
357 |
358 | varlist = this.buildLocalIdentifiers(relinted.tree, varlist);
359 |
360 | return Object.assign({}, this.global_obj, varlist);
361 | }
362 |
363 | fatfinger.wordReplacer.badIdentifiers.correctText = function(relinted, idx, code) {
364 | madeAChange = false;
365 |
366 | var identifiers = this.buildIdentifiers(relinted);
367 |
368 | if (relinted.warnings[idx].code == "undeclared_a") {
369 | // here we will try swapping for each identifier
370 | var badIdent = relinted.warnings[idx].a;
371 | var idList = fatfinger.wordMatcher.findPotentialMatches(badIdent, identifiers);
372 |
373 | if (idList != null && idList.length > 0) {
374 | var currLine = relinted.lines[relinted.warnings[idx].line].trimRight();
375 |
376 | var possibleLines = [];
377 |
378 | var addAndRemoveBrackets = (currLine.trim().charAt(currLine.trim().length - 1) == "{" || // our current line ends with a bracket
379 | (relinted.warnings[idx].line < relinted.lines.length - 2 && // our next line starts with a bracket
380 | relinted.lines[relinted.warnings[idx].line + 1].substring(0,1) == "{"));
381 |
382 | var addedBrackets = "}";
383 |
384 | if (addAndRemoveBrackets) {
385 | if (!currLine.includes("{")) {
386 | addedBrackets = "{ }"
387 | }
388 | currLine += addedBrackets;
389 | }
390 |
391 | for(var j = 0; j < idList.length; j++) {
392 | var newline = this.replaceWord(currLine, relinted.warnings[idx], relinted.warnings[idx].a, idList[j])
393 |
394 | if (fatfinger.parsingTools.testParseJs(newline)) {
395 | possibleLines.push({line:newline, score:idList[j].score, place:j});
396 | }
397 | }
398 | var sortedLines = possibleLines.sort(fatfinger.parsingTools.lineSorter);
399 |
400 | if (!sortedLines || sortedLines.length == 0) {
401 | // we will do nothing in this case -- it means we did not find an identifier replacement that parses
402 | } else {
403 | var returnlines = relinted.lines.slice();
404 |
405 | var lineToAdd = sortedLines[0].line;
406 |
407 | if (addAndRemoveBrackets) {
408 | lineToAdd = lineToAdd.substring(0, newline.length - addedBrackets.length);
409 | }
410 | returnlines[relinted.warnings[idx].line] = lineToAdd;
411 | code = returnlines.join("\n");
412 | madeAChange = true;
413 | }
414 | }
415 | }
416 |
417 | var retObj = {
418 | madeAChange: madeAChange,
419 | changedNode: relinted.warnings[idx],
420 | code: code
421 | };
422 |
423 | return retObj;
424 |
425 | }
426 |
427 | // always return the code, no final test
428 | fatfinger.wordReplacer.badIdentifiers.test = function(code) { return true; };
429 |
430 |
431 |
432 | // BAD IDENTIFIERS WORD REPLACER
433 |
434 | fatfinger.wordReplacer.memberFix = fatfinger.wordReplacer.inherit(fatfinger.wordReplacer.wordReplacerBase);
435 |
436 | fatfinger.wordReplacer.memberFix.global_obj = fatfinger.wordReplacer.loadGlobals();
437 |
438 | fatfinger.wordReplacer.memberFix.canWeExit = function(linted) { }
439 |
440 | fatfinger.wordReplacer.memberFix.test = function(code) { return true; };
441 |
442 | // We are not dealing with the warnings this loop, but with the tree itself. We need to allow
443 | // for resetting the tree, since changing names will change string lengths and so locations
444 | fatfinger.wordReplacer.memberFix.lastCheckedLocation = 0;
445 |
446 | fatfinger.wordReplacer.memberFix.treeWalker = function(node, code, linted, allLocalObjects) {
447 | if (Array.isArray(node)) {
448 | for (var i = 0; i < node.length; i++) {
449 | code = this.treeWalker(node[i], code, linted, allLocalObjects);
450 | }
451 | }
452 | if (node.id && node.id == ".") {
453 | // we're in a dot expression
454 | var frontOfDot = false;
455 | var endOfDot = false;
456 |
457 | if (node.expression && node.expression.id) {
458 | frontOfDot = node.expression.id;
459 | }
460 | if (node.name && node.name.id) {
461 | endOfDot = node.name.id;
462 | }
463 | if (frontOfDot && endOfDot) {
464 | // for members, when they hit this method
465 | // allLocalObjects = this.buildLocalIdentifiers(linted.tree, {}, frontOfDot);
466 |
467 | var obj;
468 | var possibleProps = {};
469 |
470 | // assume it's a local obj first
471 | if (allLocalObjects[frontOfDot]) {
472 | possibleProps = allLocalObjects
473 | }
474 | // only if not in node, try to get it as a built-in obj
475 | if (typeof module === 'undefined' || typeof module.exports === 'undefined') {
476 | obj = window[frontOfDot];
477 | for (var prop in obj) {
478 | possibleProps[prop] = true;
479 | }
480 | }
481 |
482 | var repl = fatfinger.wordMatcher.findPotentialMatches(endOfDot, possibleProps);
483 | repl = repl.sort(fatfinger.parsingTools.lineSorter);
484 |
485 | if (repl[0]) {
486 | linted.lines[node.line] = this.replaceWord(linted.lines[node.line], node.name, endOfDot , repl[0]);
487 | code = linted.lines.join("\n");
488 | }
489 | // FIXME: we need to track the offset for each line (annoying)
490 | }
491 | }
492 | if (node.expression) {
493 | code = this.treeWalker(node.expression, code, linted, allLocalObjects);
494 | }
495 | if (node.else) {
496 | code = this.treeWalker(node.else, code, linted, allLocalObjects);
497 | }
498 | if (node.block) {
499 | code = this.treeWalker(node.block, code, linted, allLocalObjects);
500 | }
501 | return code;
502 | }
503 |
504 | fatfinger.wordReplacer.memberFix.alternateSearch = function(linted, code) {
505 |
506 | var allLocalObjects = this.buildLocalIdentifiers(linted.tree, {});
507 |
508 | code = this.treeWalker(linted.tree, code, linted, allLocalObjects);
509 |
510 | var retObj = {
511 | madeAChange: false,
512 | code: code
513 | };
514 |
515 | return retObj;
516 | }
517 |
--------------------------------------------------------------------------------
/tests/nodeunit.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Nodeunit
3 | * https://github.com/caolan/nodeunit
4 | * Copyright (c) 2010 Caolan McMahon
5 | * MIT Licensed
6 | *
7 | * json2.js
8 | * http://www.JSON.org/json2.js
9 | * Public Domain.
10 | * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
11 | */
12 | nodeunit = (function(){
13 | /*
14 | http://www.JSON.org/json2.js
15 | 2010-11-17
16 |
17 | Public Domain.
18 |
19 | NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
20 |
21 | See http://www.JSON.org/js.html
22 |
23 |
24 | This code should be minified before deployment.
25 | See http://javascript.crockford.com/jsmin.html
26 |
27 | USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
28 | NOT CONTROL.
29 |
30 |
31 | This file creates a global JSON object containing two methods: stringify
32 | and parse.
33 |
34 | JSON.stringify(value, replacer, space)
35 | value any JavaScript value, usually an object or array.
36 |
37 | replacer an optional parameter that determines how object
38 | values are stringified for objects. It can be a
39 | function or an array of strings.
40 |
41 | space an optional parameter that specifies the indentation
42 | of nested structures. If it is omitted, the text will
43 | be packed without extra whitespace. If it is a number,
44 | it will specify the number of spaces to indent at each
45 | level. If it is a string (such as '\t' or ' '),
46 | it contains the characters used to indent at each level.
47 |
48 | This method produces a JSON text from a JavaScript value.
49 |
50 | When an object value is found, if the object contains a toJSON
51 | method, its toJSON method will be called and the result will be
52 | stringified. A toJSON method does not serialize: it returns the
53 | value represented by the name/value pair that should be serialized,
54 | or undefined if nothing should be serialized. The toJSON method
55 | will be passed the key associated with the value, and this will be
56 | bound to the value
57 |
58 | For example, this would serialize Dates as ISO strings.
59 |
60 | Date.prototype.toJSON = function (key) {
61 | function f(n) {
62 | // Format integers to have at least two digits.
63 | return n < 10 ? '0' + n : n;
64 | }
65 |
66 | return this.getUTCFullYear() + '-' +
67 | f(this.getUTCMonth() + 1) + '-' +
68 | f(this.getUTCDate()) + 'T' +
69 | f(this.getUTCHours()) + ':' +
70 | f(this.getUTCMinutes()) + ':' +
71 | f(this.getUTCSeconds()) + 'Z';
72 | };
73 |
74 | You can provide an optional replacer method. It will be passed the
75 | key and value of each member, with this bound to the containing
76 | object. The value that is returned from your method will be
77 | serialized. If your method returns undefined, then the member will
78 | be excluded from the serialization.
79 |
80 | If the replacer parameter is an array of strings, then it will be
81 | used to select the members to be serialized. It filters the results
82 | such that only members with keys listed in the replacer array are
83 | stringified.
84 |
85 | Values that do not have JSON representations, such as undefined or
86 | functions, will not be serialized. Such values in objects will be
87 | dropped; in arrays they will be replaced with null. You can use
88 | a replacer function to replace those with JSON values.
89 | JSON.stringify(undefined) returns undefined.
90 |
91 | The optional space parameter produces a stringification of the
92 | value that is filled with line breaks and indentation to make it
93 | easier to read.
94 |
95 | If the space parameter is a non-empty string, then that string will
96 | be used for indentation. If the space parameter is a number, then
97 | the indentation will be that many spaces.
98 |
99 | Example:
100 |
101 | text = JSON.stringify(['e', {pluribus: 'unum'}]);
102 | // text is '["e",{"pluribus":"unum"}]'
103 |
104 |
105 | text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
106 | // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
107 |
108 | text = JSON.stringify([new Date()], function (key, value) {
109 | return this[key] instanceof Date ?
110 | 'Date(' + this[key] + ')' : value;
111 | });
112 | // text is '["Date(---current time---)"]'
113 |
114 |
115 | JSON.parse(text, reviver)
116 | This method parses a JSON text to produce an object or array.
117 | It can throw a SyntaxError exception.
118 |
119 | The optional reviver parameter is a function that can filter and
120 | transform the results. It receives each of the keys and values,
121 | and its return value is used instead of the original value.
122 | If it returns what it received, then the structure is not modified.
123 | If it returns undefined then the member is deleted.
124 |
125 | Example:
126 |
127 | // Parse the text. Values that look like ISO date strings will
128 | // be converted to Date objects.
129 |
130 | myData = JSON.parse(text, function (key, value) {
131 | var a;
132 | if (typeof value === 'string') {
133 | a =
134 | /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
135 | if (a) {
136 | return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
137 | +a[5], +a[6]));
138 | }
139 | }
140 | return value;
141 | });
142 |
143 | myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
144 | var d;
145 | if (typeof value === 'string' &&
146 | value.slice(0, 5) === 'Date(' &&
147 | value.slice(-1) === ')') {
148 | d = new Date(value.slice(5, -1));
149 | if (d) {
150 | return d;
151 | }
152 | }
153 | return value;
154 | });
155 |
156 |
157 | This is a reference implementation. You are free to copy, modify, or
158 | redistribute.
159 | */
160 |
161 | /*jslint evil: true, strict: false, regexp: false */
162 |
163 | /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
164 | call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
165 | getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
166 | lastIndex, length, parse, prototype, push, replace, slice, stringify,
167 | test, toJSON, toString, valueOf
168 | */
169 |
170 |
171 | // Create a JSON object only if one does not already exist. We create the
172 | // methods in a closure to avoid creating global variables.
173 |
174 | var JSON = {};
175 |
176 | (function () {
177 | "use strict";
178 |
179 | function f(n) {
180 | // Format integers to have at least two digits.
181 | return n < 10 ? '0' + n : n;
182 | }
183 |
184 | if (typeof Date.prototype.toJSON !== 'function') {
185 |
186 | Date.prototype.toJSON = function (key) {
187 |
188 | return isFinite(this.valueOf()) ?
189 | this.getUTCFullYear() + '-' +
190 | f(this.getUTCMonth() + 1) + '-' +
191 | f(this.getUTCDate()) + 'T' +
192 | f(this.getUTCHours()) + ':' +
193 | f(this.getUTCMinutes()) + ':' +
194 | f(this.getUTCSeconds()) + 'Z' : null;
195 | };
196 |
197 | String.prototype.toJSON =
198 | Number.prototype.toJSON =
199 | Boolean.prototype.toJSON = function (key) {
200 | return this.valueOf();
201 | };
202 | }
203 |
204 | var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
205 | escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
206 | gap,
207 | indent,
208 | meta = { // table of character substitutions
209 | '\b': '\\b',
210 | '\t': '\\t',
211 | '\n': '\\n',
212 | '\f': '\\f',
213 | '\r': '\\r',
214 | '"' : '\\"',
215 | '\\': '\\\\'
216 | },
217 | rep;
218 |
219 |
220 | function quote(string) {
221 |
222 | // If the string contains no control characters, no quote characters, and no
223 | // backslash characters, then we can safely slap some quotes around it.
224 | // Otherwise we must also replace the offending characters with safe escape
225 | // sequences.
226 |
227 | escapable.lastIndex = 0;
228 | return escapable.test(string) ?
229 | '"' + string.replace(escapable, function (a) {
230 | var c = meta[a];
231 | return typeof c === 'string' ? c :
232 | '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
233 | }) + '"' :
234 | '"' + string + '"';
235 | }
236 |
237 |
238 | function str(key, holder) {
239 |
240 | // Produce a string from holder[key].
241 |
242 | var i, // The loop counter.
243 | k, // The member key.
244 | v, // The member value.
245 | length,
246 | mind = gap,
247 | partial,
248 | value = holder[key];
249 |
250 | // If the value has a toJSON method, call it to obtain a replacement value.
251 |
252 | if (value && typeof value === 'object' &&
253 | typeof value.toJSON === 'function') {
254 | value = value.toJSON(key);
255 | }
256 |
257 | // If we were called with a replacer function, then call the replacer to
258 | // obtain a replacement value.
259 |
260 | if (typeof rep === 'function') {
261 | value = rep.call(holder, key, value);
262 | }
263 |
264 | // What happens next depends on the value's type.
265 |
266 | switch (typeof value) {
267 | case 'string':
268 | return quote(value);
269 |
270 | case 'number':
271 |
272 | // JSON numbers must be finite. Encode non-finite numbers as null.
273 |
274 | return isFinite(value) ? String(value) : 'null';
275 |
276 | case 'boolean':
277 | case 'null':
278 |
279 | // If the value is a boolean or null, convert it to a string. Note:
280 | // typeof null does not produce 'null'. The case is included here in
281 | // the remote chance that this gets fixed someday.
282 |
283 | return String(value);
284 |
285 | // If the type is 'object', we might be dealing with an object or an array or
286 | // null.
287 |
288 | case 'object':
289 |
290 | // Due to a specification blunder in ECMAScript, typeof null is 'object',
291 | // so watch out for that case.
292 |
293 | if (!value) {
294 | return 'null';
295 | }
296 |
297 | // Make an array to hold the partial results of stringifying this object value.
298 |
299 | gap += indent;
300 | partial = [];
301 |
302 | // Is the value an array?
303 |
304 | if (Object.prototype.toString.apply(value) === '[object Array]') {
305 |
306 | // The value is an array. Stringify every element. Use null as a placeholder
307 | // for non-JSON values.
308 |
309 | length = value.length;
310 | for (i = 0; i < length; i += 1) {
311 | partial[i] = str(i, value) || 'null';
312 | }
313 |
314 | // Join all of the elements together, separated with commas, and wrap them in
315 | // brackets.
316 |
317 | v = partial.length === 0 ? '[]' :
318 | gap ? '[\n' + gap +
319 | partial.join(',\n' + gap) + '\n' +
320 | mind + ']' :
321 | '[' + partial.join(',') + ']';
322 | gap = mind;
323 | return v;
324 | }
325 |
326 | // If the replacer is an array, use it to select the members to be stringified.
327 |
328 | if (rep && typeof rep === 'object') {
329 | length = rep.length;
330 | for (i = 0; i < length; i += 1) {
331 | k = rep[i];
332 | if (typeof k === 'string') {
333 | v = str(k, value);
334 | if (v) {
335 | partial.push(quote(k) + (gap ? ': ' : ':') + v);
336 | }
337 | }
338 | }
339 | } else {
340 |
341 | // Otherwise, iterate through all of the keys in the object.
342 |
343 | for (k in value) {
344 | if (Object.hasOwnProperty.call(value, k)) {
345 | v = str(k, value);
346 | if (v) {
347 | partial.push(quote(k) + (gap ? ': ' : ':') + v);
348 | }
349 | }
350 | }
351 | }
352 |
353 | // Join all of the member texts together, separated with commas,
354 | // and wrap them in braces.
355 |
356 | v = partial.length === 0 ? '{}' :
357 | gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
358 | mind + '}' : '{' + partial.join(',') + '}';
359 | gap = mind;
360 | return v;
361 | }
362 | }
363 |
364 | // If the JSON object does not yet have a stringify method, give it one.
365 |
366 | if (typeof JSON.stringify !== 'function') {
367 | JSON.stringify = function (value, replacer, space) {
368 |
369 | // The stringify method takes a value and an optional replacer, and an optional
370 | // space parameter, and returns a JSON text. The replacer can be a function
371 | // that can replace values, or an array of strings that will select the keys.
372 | // A default replacer method can be provided. Use of the space parameter can
373 | // produce text that is more easily readable.
374 |
375 | var i;
376 | gap = '';
377 | indent = '';
378 |
379 | // If the space parameter is a number, make an indent string containing that
380 | // many spaces.
381 |
382 | if (typeof space === 'number') {
383 | for (i = 0; i < space; i += 1) {
384 | indent += ' ';
385 | }
386 |
387 | // If the space parameter is a string, it will be used as the indent string.
388 |
389 | } else if (typeof space === 'string') {
390 | indent = space;
391 | }
392 |
393 | // If there is a replacer, it must be a function or an array.
394 | // Otherwise, throw an error.
395 |
396 | rep = replacer;
397 | if (replacer && typeof replacer !== 'function' &&
398 | (typeof replacer !== 'object' ||
399 | typeof replacer.length !== 'number')) {
400 | throw new Error('JSON.stringify');
401 | }
402 |
403 | // Make a fake root object containing our value under the key of ''.
404 | // Return the result of stringifying the value.
405 |
406 | return str('', {'': value});
407 | };
408 | }
409 |
410 |
411 | // If the JSON object does not yet have a parse method, give it one.
412 |
413 | if (typeof JSON.parse !== 'function') {
414 | JSON.parse = function (text, reviver) {
415 |
416 | // The parse method takes a text and an optional reviver function, and returns
417 | // a JavaScript value if the text is a valid JSON text.
418 |
419 | var j;
420 |
421 | function walk(holder, key) {
422 |
423 | // The walk method is used to recursively walk the resulting structure so
424 | // that modifications can be made.
425 |
426 | var k, v, value = holder[key];
427 | if (value && typeof value === 'object') {
428 | for (k in value) {
429 | if (Object.hasOwnProperty.call(value, k)) {
430 | v = walk(value, k);
431 | if (v !== undefined) {
432 | value[k] = v;
433 | } else {
434 | delete value[k];
435 | }
436 | }
437 | }
438 | }
439 | return reviver.call(holder, key, value);
440 | }
441 |
442 |
443 | // Parsing happens in four stages. In the first stage, we replace certain
444 | // Unicode characters with escape sequences. JavaScript handles many characters
445 | // incorrectly, either silently deleting them, or treating them as line endings.
446 |
447 | text = String(text);
448 | cx.lastIndex = 0;
449 | if (cx.test(text)) {
450 | text = text.replace(cx, function (a) {
451 | return '\\u' +
452 | ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
453 | });
454 | }
455 |
456 | // In the second stage, we run the text against regular expressions that look
457 | // for non-JSON patterns. We are especially concerned with '()' and 'new'
458 | // because they can cause invocation, and '=' because it can cause mutation.
459 | // But just to be safe, we want to reject all unexpected forms.
460 |
461 | // We split the second stage into 4 regexp operations in order to work around
462 | // crippling inefficiencies in IE's and Safari's regexp engines. First we
463 | // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
464 | // replace all simple value tokens with ']' characters. Third, we delete all
465 | // open brackets that follow a colon or comma or that begin the text. Finally,
466 | // we look to see that the remaining characters are only whitespace or ']' or
467 | // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
468 |
469 | if (/^[\],:{}\s]*$/
470 | .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
471 | .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
472 | .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
473 |
474 | // In the third stage we use the eval function to compile the text into a
475 | // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
476 | // in JavaScript: it can begin a block or an object literal. We wrap the text
477 | // in parens to eliminate the ambiguity.
478 |
479 | j = eval('(' + text + ')');
480 |
481 | // In the optional fourth stage, we recursively walk the new structure, passing
482 | // each name/value pair to a reviver function for possible transformation.
483 |
484 | return typeof reviver === 'function' ?
485 | walk({'': j}, '') : j;
486 | }
487 |
488 | // If the text is not JSON parseable, then a SyntaxError is thrown.
489 |
490 | throw new SyntaxError('JSON.parse');
491 | };
492 | }
493 | }());
494 | var assert = this.assert = {};
495 | var types = {};
496 | var core = {};
497 | var nodeunit = {};
498 | var reporter = {};
499 | /*global setTimeout: false, console: false */
500 | (function () {
501 |
502 | var async = {};
503 |
504 | // global on the server, window in the browser
505 | var root = this,
506 | previous_async = root.async;
507 |
508 | if (typeof module !== 'undefined' && module.exports) {
509 | module.exports = async;
510 | }
511 | else {
512 | root.async = async;
513 | }
514 |
515 | async.noConflict = function () {
516 | root.async = previous_async;
517 | return async;
518 | };
519 |
520 | //// cross-browser compatiblity functions ////
521 |
522 | var _forEach = function (arr, iterator) {
523 | if (arr.forEach) {
524 | return arr.forEach(iterator);
525 | }
526 | for (var i = 0; i < arr.length; i += 1) {
527 | iterator(arr[i], i, arr);
528 | }
529 | };
530 |
531 | var _map = function (arr, iterator) {
532 | if (arr.map) {
533 | return arr.map(iterator);
534 | }
535 | var results = [];
536 | _forEach(arr, function (x, i, a) {
537 | results.push(iterator(x, i, a));
538 | });
539 | return results;
540 | };
541 |
542 | var _reduce = function (arr, iterator, memo) {
543 | if (arr.reduce) {
544 | return arr.reduce(iterator, memo);
545 | }
546 | _forEach(arr, function (x, i, a) {
547 | memo = iterator(memo, x, i, a);
548 | });
549 | return memo;
550 | };
551 |
552 | var _keys = function (obj) {
553 | if (Object.keys) {
554 | return Object.keys(obj);
555 | }
556 | var keys = [];
557 | for (var k in obj) {
558 | if (obj.hasOwnProperty(k)) {
559 | keys.push(k);
560 | }
561 | }
562 | return keys;
563 | };
564 |
565 | var _indexOf = function (arr, item) {
566 | if (arr.indexOf) {
567 | return arr.indexOf(item);
568 | }
569 | for (var i = 0; i < arr.length; i += 1) {
570 | if (arr[i] === item) {
571 | return i;
572 | }
573 | }
574 | return -1;
575 | };
576 |
577 | //// exported async module functions ////
578 |
579 | //// nextTick implementation with browser-compatible fallback ////
580 | if (typeof process === 'undefined' || !(process.nextTick)) {
581 | async.nextTick = function (fn) {
582 | setTimeout(fn, 0);
583 | };
584 | }
585 | else {
586 | async.nextTick = process.nextTick;
587 | }
588 |
589 | async.forEach = function (arr, iterator, callback) {
590 | if (!arr.length) {
591 | return callback();
592 | }
593 | var completed = 0;
594 | _forEach(arr, function (x) {
595 | iterator(x, function (err) {
596 | if (err) {
597 | callback(err);
598 | callback = function () {};
599 | }
600 | else {
601 | completed += 1;
602 | if (completed === arr.length) {
603 | callback();
604 | }
605 | }
606 | });
607 | });
608 | };
609 |
610 | async.forEachSeries = function (arr, iterator, callback) {
611 | if (!arr.length) {
612 | return callback();
613 | }
614 | var completed = 0;
615 | var iterate = function () {
616 | iterator(arr[completed], function (err) {
617 | if (err) {
618 | callback(err);
619 | callback = function () {};
620 | }
621 | else {
622 | completed += 1;
623 | if (completed === arr.length) {
624 | callback();
625 | }
626 | else {
627 | iterate();
628 | }
629 | }
630 | });
631 | };
632 | iterate();
633 | };
634 |
635 |
636 | var doParallel = function (fn) {
637 | return function () {
638 | var args = Array.prototype.slice.call(arguments);
639 | return fn.apply(null, [async.forEach].concat(args));
640 | };
641 | };
642 | var doSeries = function (fn) {
643 | return function () {
644 | var args = Array.prototype.slice.call(arguments);
645 | return fn.apply(null, [async.forEachSeries].concat(args));
646 | };
647 | };
648 |
649 |
650 | var _asyncMap = function (eachfn, arr, iterator, callback) {
651 | var results = [];
652 | arr = _map(arr, function (x, i) {
653 | return {index: i, value: x};
654 | });
655 | eachfn(arr, function (x, callback) {
656 | iterator(x.value, function (err, v) {
657 | results[x.index] = v;
658 | callback(err);
659 | });
660 | }, function (err) {
661 | callback(err, results);
662 | });
663 | };
664 | async.map = doParallel(_asyncMap);
665 | async.mapSeries = doSeries(_asyncMap);
666 |
667 |
668 | // reduce only has a series version, as doing reduce in parallel won't
669 | // work in many situations.
670 | async.reduce = function (arr, memo, iterator, callback) {
671 | async.forEachSeries(arr, function (x, callback) {
672 | iterator(memo, x, function (err, v) {
673 | memo = v;
674 | callback(err);
675 | });
676 | }, function (err) {
677 | callback(err, memo);
678 | });
679 | };
680 | // inject alias
681 | async.inject = async.reduce;
682 | // foldl alias
683 | async.foldl = async.reduce;
684 |
685 | async.reduceRight = function (arr, memo, iterator, callback) {
686 | var reversed = _map(arr, function (x) {
687 | return x;
688 | }).reverse();
689 | async.reduce(reversed, memo, iterator, callback);
690 | };
691 | // foldr alias
692 | async.foldr = async.reduceRight;
693 |
694 | var _filter = function (eachfn, arr, iterator, callback) {
695 | var results = [];
696 | arr = _map(arr, function (x, i) {
697 | return {index: i, value: x};
698 | });
699 | eachfn(arr, function (x, callback) {
700 | iterator(x.value, function (v) {
701 | if (v) {
702 | results.push(x);
703 | }
704 | callback();
705 | });
706 | }, function (err) {
707 | callback(_map(results.sort(function (a, b) {
708 | return a.index - b.index;
709 | }), function (x) {
710 | return x.value;
711 | }));
712 | });
713 | };
714 | async.filter = doParallel(_filter);
715 | async.filterSeries = doSeries(_filter);
716 | // select alias
717 | async.select = async.filter;
718 | async.selectSeries = async.filterSeries;
719 |
720 | var _reject = function (eachfn, arr, iterator, callback) {
721 | var results = [];
722 | arr = _map(arr, function (x, i) {
723 | return {index: i, value: x};
724 | });
725 | eachfn(arr, function (x, callback) {
726 | iterator(x.value, function (v) {
727 | if (!v) {
728 | results.push(x);
729 | }
730 | callback();
731 | });
732 | }, function (err) {
733 | callback(_map(results.sort(function (a, b) {
734 | return a.index - b.index;
735 | }), function (x) {
736 | return x.value;
737 | }));
738 | });
739 | };
740 | async.reject = doParallel(_reject);
741 | async.rejectSeries = doSeries(_reject);
742 |
743 | var _detect = function (eachfn, arr, iterator, main_callback) {
744 | eachfn(arr, function (x, callback) {
745 | iterator(x, function (result) {
746 | if (result) {
747 | main_callback(x);
748 | }
749 | else {
750 | callback();
751 | }
752 | });
753 | }, function (err) {
754 | main_callback();
755 | });
756 | };
757 | async.detect = doParallel(_detect);
758 | async.detectSeries = doSeries(_detect);
759 |
760 | async.some = function (arr, iterator, main_callback) {
761 | async.forEach(arr, function (x, callback) {
762 | iterator(x, function (v) {
763 | if (v) {
764 | main_callback(true);
765 | main_callback = function () {};
766 | }
767 | callback();
768 | });
769 | }, function (err) {
770 | main_callback(false);
771 | });
772 | };
773 | // any alias
774 | async.any = async.some;
775 |
776 | async.every = function (arr, iterator, main_callback) {
777 | async.forEach(arr, function (x, callback) {
778 | iterator(x, function (v) {
779 | if (!v) {
780 | main_callback(false);
781 | main_callback = function () {};
782 | }
783 | callback();
784 | });
785 | }, function (err) {
786 | main_callback(true);
787 | });
788 | };
789 | // all alias
790 | async.all = async.every;
791 |
792 | async.sortBy = function (arr, iterator, callback) {
793 | async.map(arr, function (x, callback) {
794 | iterator(x, function (err, criteria) {
795 | if (err) {
796 | callback(err);
797 | }
798 | else {
799 | callback(null, {value: x, criteria: criteria});
800 | }
801 | });
802 | }, function (err, results) {
803 | if (err) {
804 | return callback(err);
805 | }
806 | else {
807 | var fn = function (left, right) {
808 | var a = left.criteria, b = right.criteria;
809 | return a < b ? -1 : a > b ? 1 : 0;
810 | };
811 | callback(null, _map(results.sort(fn), function (x) {
812 | return x.value;
813 | }));
814 | }
815 | });
816 | };
817 |
818 | async.auto = function (tasks, callback) {
819 | callback = callback || function () {};
820 | var keys = _keys(tasks);
821 | if (!keys.length) {
822 | return callback(null);
823 | }
824 |
825 | var completed = [];
826 |
827 | var listeners = [];
828 | var addListener = function (fn) {
829 | listeners.unshift(fn);
830 | };
831 | var removeListener = function (fn) {
832 | for (var i = 0; i < listeners.length; i += 1) {
833 | if (listeners[i] === fn) {
834 | listeners.splice(i, 1);
835 | return;
836 | }
837 | }
838 | };
839 | var taskComplete = function () {
840 | _forEach(listeners, function (fn) {
841 | fn();
842 | });
843 | };
844 |
845 | addListener(function () {
846 | if (completed.length === keys.length) {
847 | callback(null);
848 | }
849 | });
850 |
851 | _forEach(keys, function (k) {
852 | var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];
853 | var taskCallback = function (err) {
854 | if (err) {
855 | callback(err);
856 | // stop subsequent errors hitting callback multiple times
857 | callback = function () {};
858 | }
859 | else {
860 | completed.push(k);
861 | taskComplete();
862 | }
863 | };
864 | var requires = task.slice(0, Math.abs(task.length - 1)) || [];
865 | var ready = function () {
866 | return _reduce(requires, function (a, x) {
867 | return (a && _indexOf(completed, x) !== -1);
868 | }, true);
869 | };
870 | if (ready()) {
871 | task[task.length - 1](taskCallback);
872 | }
873 | else {
874 | var listener = function () {
875 | if (ready()) {
876 | removeListener(listener);
877 | task[task.length - 1](taskCallback);
878 | }
879 | };
880 | addListener(listener);
881 | }
882 | });
883 | };
884 |
885 | async.waterfall = function (tasks, callback) {
886 | if (!tasks.length) {
887 | return callback();
888 | }
889 | callback = callback || function () {};
890 | var wrapIterator = function (iterator) {
891 | return function (err) {
892 | if (err) {
893 | callback(err);
894 | callback = function () {};
895 | }
896 | else {
897 | var args = Array.prototype.slice.call(arguments, 1);
898 | var next = iterator.next();
899 | if (next) {
900 | args.push(wrapIterator(next));
901 | }
902 | else {
903 | args.push(callback);
904 | }
905 | async.nextTick(function () {
906 | iterator.apply(null, args);
907 | });
908 | }
909 | };
910 | };
911 | wrapIterator(async.iterator(tasks))();
912 | };
913 |
914 | async.parallel = function (tasks, callback) {
915 | callback = callback || function () {};
916 | if (tasks.constructor === Array) {
917 | async.map(tasks, function (fn, callback) {
918 | if (fn) {
919 | fn(function (err) {
920 | var args = Array.prototype.slice.call(arguments, 1);
921 | if (args.length <= 1) {
922 | args = args[0];
923 | }
924 | callback.call(null, err, args || null);
925 | });
926 | }
927 | }, callback);
928 | }
929 | else {
930 | var results = {};
931 | async.forEach(_keys(tasks), function (k, callback) {
932 | tasks[k](function (err) {
933 | var args = Array.prototype.slice.call(arguments, 1);
934 | if (args.length <= 1) {
935 | args = args[0];
936 | }
937 | results[k] = args;
938 | callback(err);
939 | });
940 | }, function (err) {
941 | callback(err, results);
942 | });
943 | }
944 | };
945 |
946 | async.series = function (tasks, callback) {
947 | callback = callback || function () {};
948 | if (tasks.constructor === Array) {
949 | async.mapSeries(tasks, function (fn, callback) {
950 | if (fn) {
951 | fn(function (err) {
952 | var args = Array.prototype.slice.call(arguments, 1);
953 | if (args.length <= 1) {
954 | args = args[0];
955 | }
956 | callback.call(null, err, args || null);
957 | });
958 | }
959 | }, callback);
960 | }
961 | else {
962 | var results = {};
963 | async.forEachSeries(_keys(tasks), function (k, callback) {
964 | tasks[k](function (err) {
965 | var args = Array.prototype.slice.call(arguments, 1);
966 | if (args.length <= 1) {
967 | args = args[0];
968 | }
969 | results[k] = args;
970 | callback(err);
971 | });
972 | }, function (err) {
973 | callback(err, results);
974 | });
975 | }
976 | };
977 |
978 | async.iterator = function (tasks) {
979 | var makeCallback = function (index) {
980 | var fn = function () {
981 | if (tasks.length) {
982 | tasks[index].apply(null, arguments);
983 | }
984 | return fn.next();
985 | };
986 | fn.next = function () {
987 | return (index < tasks.length - 1) ? makeCallback(index + 1): null;
988 | };
989 | return fn;
990 | };
991 | return makeCallback(0);
992 | };
993 |
994 | async.apply = function (fn) {
995 | var args = Array.prototype.slice.call(arguments, 1);
996 | return function () {
997 | return fn.apply(
998 | null, args.concat(Array.prototype.slice.call(arguments))
999 | );
1000 | };
1001 | };
1002 |
1003 | var _concat = function (eachfn, arr, fn, callback) {
1004 | var r = [];
1005 | eachfn(arr, function (x, cb) {
1006 | fn(x, function (err, y) {
1007 | r = r.concat(y || []);
1008 | cb(err);
1009 | });
1010 | }, function (err) {
1011 | callback(err, r);
1012 | });
1013 | };
1014 | async.concat = doParallel(_concat);
1015 | async.concatSeries = doSeries(_concat);
1016 |
1017 | async.whilst = function (test, iterator, callback) {
1018 | if (test()) {
1019 | iterator(function (err) {
1020 | if (err) {
1021 | return callback(err);
1022 | }
1023 | async.whilst(test, iterator, callback);
1024 | });
1025 | }
1026 | else {
1027 | callback();
1028 | }
1029 | };
1030 |
1031 | async.until = function (test, iterator, callback) {
1032 | if (!test()) {
1033 | iterator(function (err) {
1034 | if (err) {
1035 | return callback(err);
1036 | }
1037 | async.until(test, iterator, callback);
1038 | });
1039 | }
1040 | else {
1041 | callback();
1042 | }
1043 | };
1044 |
1045 | async.queue = function (worker, concurrency) {
1046 | var workers = 0;
1047 | var tasks = [];
1048 | var q = {
1049 | concurrency: concurrency,
1050 | push: function (data, callback) {
1051 | tasks.push({data: data, callback: callback});
1052 | async.nextTick(q.process);
1053 | },
1054 | process: function () {
1055 | if (workers < q.concurrency && tasks.length) {
1056 | var task = tasks.splice(0, 1)[0];
1057 | workers += 1;
1058 | worker(task.data, function () {
1059 | workers -= 1;
1060 | if (task.callback) {
1061 | task.callback.apply(task, arguments);
1062 | }
1063 | q.process();
1064 | });
1065 | }
1066 | },
1067 | length: function () {
1068 | return tasks.length;
1069 | }
1070 | };
1071 | return q;
1072 | };
1073 |
1074 | var _console_fn = function (name) {
1075 | return function (fn) {
1076 | var args = Array.prototype.slice.call(arguments, 1);
1077 | fn.apply(null, args.concat([function (err) {
1078 | var args = Array.prototype.slice.call(arguments, 1);
1079 | if (typeof console !== 'undefined') {
1080 | if (err) {
1081 | if (console.error) {
1082 | console.error(err);
1083 | }
1084 | }
1085 | else if (console[name]) {
1086 | _forEach(args, function (x) {
1087 | console[name](x);
1088 | });
1089 | }
1090 | }
1091 | }]));
1092 | };
1093 | };
1094 | async.log = _console_fn('log');
1095 | async.dir = _console_fn('dir');
1096 | /*async.info = _console_fn('info');
1097 | async.warn = _console_fn('warn');
1098 | async.error = _console_fn('error');*/
1099 |
1100 | async.memoize = function (fn, hasher) {
1101 | var memo = {};
1102 | hasher = hasher || function (x) {
1103 | return x;
1104 | };
1105 | return function () {
1106 | var args = Array.prototype.slice.call(arguments);
1107 | var callback = args.pop();
1108 | var key = hasher.apply(null, args);
1109 | if (key in memo) {
1110 | callback.apply(null, memo[key]);
1111 | }
1112 | else {
1113 | fn.apply(null, args.concat([function () {
1114 | memo[key] = arguments;
1115 | callback.apply(null, arguments);
1116 | }]));
1117 | }
1118 | };
1119 | };
1120 |
1121 | }());
1122 | (function(exports){
1123 | /**
1124 | * This file is based on the node.js assert module, but with some small
1125 | * changes for browser-compatibility
1126 | * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1127 | */
1128 |
1129 |
1130 | /**
1131 | * Added for browser compatibility
1132 | */
1133 |
1134 | var _keys = function(obj){
1135 | if(Object.keys) return Object.keys(obj);
1136 | if (typeof obj != 'object' && typeof obj != 'function') {
1137 | throw new TypeError('-');
1138 | }
1139 | var keys = [];
1140 | for(var k in obj){
1141 | if(obj.hasOwnProperty(k)) keys.push(k);
1142 | }
1143 | return keys;
1144 | };
1145 |
1146 |
1147 |
1148 | // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
1149 | //
1150 | // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
1151 | //
1152 | // Originally from narwhal.js (http://narwhaljs.org)
1153 | // Copyright (c) 2009 Thomas Robinson <280north.com>
1154 | //
1155 | // Permission is hereby granted, free of charge, to any person obtaining a copy
1156 | // of this software and associated documentation files (the 'Software'), to
1157 | // deal in the Software without restriction, including without limitation the
1158 | // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1159 | // sell copies of the Software, and to permit persons to whom the Software is
1160 | // furnished to do so, subject to the following conditions:
1161 | //
1162 | // The above copyright notice and this permission notice shall be included in
1163 | // all copies or substantial portions of the Software.
1164 | //
1165 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1166 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1167 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1168 | // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1169 | // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1170 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1171 |
1172 |
1173 | var pSlice = Array.prototype.slice;
1174 |
1175 | // 1. The assert module provides functions that throw
1176 | // AssertionError's when particular conditions are not met. The
1177 | // assert module must conform to the following interface.
1178 |
1179 | var assert = exports;
1180 |
1181 | // 2. The AssertionError is defined in assert.
1182 | // new assert.AssertionError({message: message, actual: actual, expected: expected})
1183 |
1184 | assert.AssertionError = function AssertionError (options) {
1185 | this.name = "AssertionError";
1186 | this.message = options.message;
1187 | this.actual = options.actual;
1188 | this.expected = options.expected;
1189 | this.operator = options.operator;
1190 | var stackStartFunction = options.stackStartFunction || fail;
1191 |
1192 | if (Error.captureStackTrace) {
1193 | Error.captureStackTrace(this, stackStartFunction);
1194 | }
1195 | };
1196 | // code from util.inherits in node
1197 | assert.AssertionError.super_ = Error;
1198 |
1199 |
1200 | // EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call
1201 | // TODO: test what effect this may have
1202 | var ctor = function () { this.constructor = assert.AssertionError; };
1203 | ctor.prototype = Error.prototype;
1204 | assert.AssertionError.prototype = new ctor();
1205 |
1206 |
1207 | assert.AssertionError.prototype.toString = function() {
1208 | if (this.message) {
1209 | return [this.name+":", this.message].join(' ');
1210 | } else {
1211 | return [ this.name+":"
1212 | , JSON.stringify(this.expected )
1213 | , this.operator
1214 | , JSON.stringify(this.actual)
1215 | ].join(" ");
1216 | }
1217 | };
1218 |
1219 | // assert.AssertionError instanceof Error
1220 |
1221 | assert.AssertionError.__proto__ = Error.prototype;
1222 |
1223 | // At present only the three keys mentioned above are used and
1224 | // understood by the spec. Implementations or sub modules can pass
1225 | // other keys to the AssertionError's constructor - they will be
1226 | // ignored.
1227 |
1228 | // 3. All of the following functions must throw an AssertionError
1229 | // when a corresponding condition is not met, with a message that
1230 | // may be undefined if not provided. All assertion methods provide
1231 | // both the actual and expected values to the assertion error for
1232 | // display purposes.
1233 |
1234 | function fail(actual, expected, message, operator, stackStartFunction) {
1235 | throw new assert.AssertionError({
1236 | message: message,
1237 | actual: actual,
1238 | expected: expected,
1239 | operator: operator,
1240 | stackStartFunction: stackStartFunction
1241 | });
1242 | }
1243 |
1244 | // EXTENSION! allows for well behaved errors defined elsewhere.
1245 | assert.fail = fail;
1246 |
1247 | // 4. Pure assertion tests whether a value is truthy, as determined
1248 | // by !!guard.
1249 | // assert.ok(guard, message_opt);
1250 | // This statement is equivalent to assert.equal(true, guard,
1251 | // message_opt);. To test strictly for the value true, use
1252 | // assert.strictEqual(true, guard, message_opt);.
1253 |
1254 | assert.ok = function ok(value, message) {
1255 | if (!!!value) fail(value, true, message, "==", assert.ok);
1256 | };
1257 |
1258 | // 5. The equality assertion tests shallow, coercive equality with
1259 | // ==.
1260 | // assert.equal(actual, expected, message_opt);
1261 |
1262 | assert.equal = function equal(actual, expected, message) {
1263 | if (actual != expected) fail(actual, expected, message, "==", assert.equal);
1264 | };
1265 |
1266 | // 6. The non-equality assertion tests for whether two objects are not equal
1267 | // with != assert.notEqual(actual, expected, message_opt);
1268 |
1269 | assert.notEqual = function notEqual(actual, expected, message) {
1270 | if (actual == expected) {
1271 | fail(actual, expected, message, "!=", assert.notEqual);
1272 | }
1273 | };
1274 |
1275 | // 7. The equivalence assertion tests a deep equality relation.
1276 | // assert.deepEqual(actual, expected, message_opt);
1277 |
1278 | assert.deepEqual = function deepEqual(actual, expected, message) {
1279 | if (!_deepEqual(actual, expected)) {
1280 | fail(actual, expected, message, "deepEqual", assert.deepEqual);
1281 | }
1282 | };
1283 |
1284 | function _deepEqual(actual, expected) {
1285 | // 7.1. All identical values are equivalent, as determined by ===.
1286 | if (actual === expected) {
1287 | return true;
1288 | // 7.2. If the expected value is a Date object, the actual value is
1289 | // equivalent if it is also a Date object that refers to the same time.
1290 | } else if (actual instanceof Date && expected instanceof Date) {
1291 | return actual.getTime() === expected.getTime();
1292 |
1293 | // 7.3. Other pairs that do not both pass typeof value == "object",
1294 | // equivalence is determined by ==.
1295 | } else if (typeof actual != 'object' && typeof expected != 'object') {
1296 | return actual == expected;
1297 |
1298 | // 7.4. For all other Object pairs, including Array objects, equivalence is
1299 | // determined by having the same number of owned properties (as verified
1300 | // with Object.prototype.hasOwnProperty.call), the same set of keys
1301 | // (although not necessarily the same order), equivalent values for every
1302 | // corresponding key, and an identical "prototype" property. Note: this
1303 | // accounts for both named and indexed properties on Arrays.
1304 | } else {
1305 | return objEquiv(actual, expected);
1306 | }
1307 | }
1308 |
1309 | function isUndefinedOrNull (value) {
1310 | return value === null || value === undefined;
1311 | }
1312 |
1313 | function isArguments (object) {
1314 | return Object.prototype.toString.call(object) == '[object Arguments]';
1315 | }
1316 |
1317 | function objEquiv (a, b) {
1318 | if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
1319 | return false;
1320 | // an identical "prototype" property.
1321 | if (a.prototype !== b.prototype) return false;
1322 | //~~~I've managed to break Object.keys through screwy arguments passing.
1323 | // Converting to array solves the problem.
1324 | if (isArguments(a)) {
1325 | if (!isArguments(b)) {
1326 | return false;
1327 | }
1328 | a = pSlice.call(a);
1329 | b = pSlice.call(b);
1330 | return _deepEqual(a, b);
1331 | }
1332 | try{
1333 | var ka = _keys(a),
1334 | kb = _keys(b),
1335 | key, i;
1336 | } catch (e) {//happens when one is a string literal and the other isn't
1337 | return false;
1338 | }
1339 | // having the same number of owned properties (keys incorporates hasOwnProperty)
1340 | if (ka.length != kb.length)
1341 | return false;
1342 | //the same set of keys (although not necessarily the same order),
1343 | ka.sort();
1344 | kb.sort();
1345 | //~~~cheap key test
1346 | for (i = ka.length - 1; i >= 0; i--) {
1347 | if (ka[i] != kb[i])
1348 | return false;
1349 | }
1350 | //equivalent values for every corresponding key, and
1351 | //~~~possibly expensive deep test
1352 | for (i = ka.length - 1; i >= 0; i--) {
1353 | key = ka[i];
1354 | if (!_deepEqual(a[key], b[key] ))
1355 | return false;
1356 | }
1357 | return true;
1358 | }
1359 |
1360 | // 8. The non-equivalence assertion tests for any deep inequality.
1361 | // assert.notDeepEqual(actual, expected, message_opt);
1362 |
1363 | assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
1364 | if (_deepEqual(actual, expected)) {
1365 | fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual);
1366 | }
1367 | };
1368 |
1369 | // 9. The strict equality assertion tests strict equality, as determined by ===.
1370 | // assert.strictEqual(actual, expected, message_opt);
1371 |
1372 | assert.strictEqual = function strictEqual(actual, expected, message) {
1373 | if (actual !== expected) {
1374 | fail(actual, expected, message, "===", assert.strictEqual);
1375 | }
1376 | };
1377 |
1378 | // 10. The strict non-equality assertion tests for strict inequality, as determined by !==.
1379 | // assert.notStrictEqual(actual, expected, message_opt);
1380 |
1381 | assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
1382 | if (actual === expected) {
1383 | fail(actual, expected, message, "!==", assert.notStrictEqual);
1384 | }
1385 | };
1386 |
1387 | function _throws (shouldThrow, block, err, message) {
1388 | var exception = null,
1389 | threw = false,
1390 | typematters = true;
1391 |
1392 | message = message || "";
1393 |
1394 | //handle optional arguments
1395 | if (arguments.length == 3) {
1396 | if (typeof(err) == "string") {
1397 | message = err;
1398 | typematters = false;
1399 | }
1400 | } else if (arguments.length == 2) {
1401 | typematters = false;
1402 | }
1403 |
1404 | try {
1405 | block();
1406 | } catch (e) {
1407 | threw = true;
1408 | exception = e;
1409 | }
1410 |
1411 | if (shouldThrow && !threw) {
1412 | fail( "Missing expected exception"
1413 | + (err && err.name ? " ("+err.name+")." : '.')
1414 | + (message ? " " + message : "")
1415 | );
1416 | }
1417 | if (!shouldThrow && threw && typematters && exception instanceof err) {
1418 | fail( "Got unwanted exception"
1419 | + (err && err.name ? " ("+err.name+")." : '.')
1420 | + (message ? " " + message : "")
1421 | );
1422 | }
1423 | if ((shouldThrow && threw && typematters && !(exception instanceof err)) ||
1424 | (!shouldThrow && threw)) {
1425 | throw exception;
1426 | }
1427 | };
1428 |
1429 | // 11. Expected to throw an error:
1430 | // assert.throws(block, Error_opt, message_opt);
1431 |
1432 | assert.throws = function(block, /*optional*/error, /*optional*/message) {
1433 | _throws.apply(this, [true].concat(pSlice.call(arguments)));
1434 | };
1435 |
1436 | // EXTENSION! This is annoying to write outside this module.
1437 | assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
1438 | _throws.apply(this, [false].concat(pSlice.call(arguments)));
1439 | };
1440 |
1441 | assert.ifError = function (err) { if (err) {throw err;}};
1442 | })(assert);
1443 | (function(exports){
1444 | /*!
1445 | * Nodeunit
1446 | * Copyright (c) 2010 Caolan McMahon
1447 | * MIT Licensed
1448 | *
1449 | * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1450 | * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1451 | * Only code on that line will be removed, its mostly to avoid requiring code
1452 | * that is node specific
1453 | */
1454 |
1455 | /**
1456 | * Module dependencies
1457 | */
1458 |
1459 | //var assert = require('./assert'), //@REMOVE_LINE_FOR_BROWSER
1460 | // async = require('../deps/async'); //@REMOVE_LINE_FOR_BROWSER
1461 |
1462 |
1463 | /**
1464 | * Creates assertion objects representing the result of an assert call.
1465 | * Accepts an object or AssertionError as its argument.
1466 | *
1467 | * @param {object} obj
1468 | * @api public
1469 | */
1470 |
1471 | exports.assertion = function (obj) {
1472 | return {
1473 | method: obj.method || '',
1474 | message: obj.message || (obj.error && obj.error.message) || '',
1475 | error: obj.error,
1476 | passed: function () {
1477 | return !this.error;
1478 | },
1479 | failed: function () {
1480 | return Boolean(this.error);
1481 | }
1482 | };
1483 | };
1484 |
1485 | /**
1486 | * Creates an assertion list object representing a group of assertions.
1487 | * Accepts an array of assertion objects.
1488 | *
1489 | * @param {Array} arr
1490 | * @param {Number} duration
1491 | * @api public
1492 | */
1493 |
1494 | exports.assertionList = function (arr, duration) {
1495 | var that = arr || [];
1496 | that.failures = function () {
1497 | var failures = 0;
1498 | for (var i = 0; i < this.length; i += 1) {
1499 | if (this[i].failed()) {
1500 | failures += 1;
1501 | }
1502 | }
1503 | return failures;
1504 | };
1505 | that.passes = function () {
1506 | return that.length - that.failures();
1507 | };
1508 | that.duration = duration || 0;
1509 | return that;
1510 | };
1511 |
1512 | /**
1513 | * Create a wrapper function for assert module methods. Executes a callback
1514 | * after the it's complete with an assertion object representing the result.
1515 | *
1516 | * @param {Function} callback
1517 | * @api private
1518 | */
1519 |
1520 | var assertWrapper = function (callback) {
1521 | return function (new_method, assert_method, arity) {
1522 | return function () {
1523 | var message = arguments[arity - 1];
1524 | var a = exports.assertion({method: new_method, message: message});
1525 | try {
1526 | assert[assert_method].apply(null, arguments);
1527 | }
1528 | catch (e) {
1529 | a.error = e;
1530 | }
1531 | callback(a);
1532 | };
1533 | };
1534 | };
1535 |
1536 | /**
1537 | * Creates the 'test' object that gets passed to every test function.
1538 | * Accepts the name of the test function as its first argument, followed by
1539 | * the start time in ms, the options object and a callback function.
1540 | *
1541 | * @param {String} name
1542 | * @param {Number} start
1543 | * @param {Object} options
1544 | * @param {Function} callback
1545 | * @api public
1546 | */
1547 |
1548 | exports.test = function (name, start, options, callback) {
1549 | var expecting;
1550 | var a_list = [];
1551 |
1552 | var wrapAssert = assertWrapper(function (a) {
1553 | a_list.push(a);
1554 | if (options.log) {
1555 | async.nextTick(function () {
1556 | options.log(a);
1557 | });
1558 | }
1559 | });
1560 |
1561 | var test = {
1562 | done: function (err) {
1563 | if (expecting !== undefined && expecting !== a_list.length) {
1564 | var e = new Error(
1565 | 'Expected ' + expecting + ' assertions, ' +
1566 | a_list.length + ' ran'
1567 | );
1568 | var a1 = exports.assertion({method: 'expect', error: e});
1569 | a_list.push(a1);
1570 | if (options.log) {
1571 | async.nextTick(function () {
1572 | options.log(a1);
1573 | });
1574 | }
1575 | }
1576 | if (err) {
1577 | var a2 = exports.assertion({error: err});
1578 | a_list.push(a2);
1579 | if (options.log) {
1580 | async.nextTick(function () {
1581 | options.log(a2);
1582 | });
1583 | }
1584 | }
1585 | var end = new Date().getTime();
1586 | async.nextTick(function () {
1587 | var assertion_list = exports.assertionList(a_list, end - start);
1588 | options.testDone(name, assertion_list);
1589 | callback(null, a_list);
1590 | });
1591 | },
1592 | ok: wrapAssert('ok', 'ok', 2),
1593 | same: wrapAssert('same', 'deepEqual', 3),
1594 | equals: wrapAssert('equals', 'equal', 3),
1595 | expect: function (num) {
1596 | expecting = num;
1597 | },
1598 | _assertion_list: a_list
1599 | };
1600 | // add all functions from the assert module
1601 | for (var k in assert) {
1602 | if (assert.hasOwnProperty(k)) {
1603 | test[k] = wrapAssert(k, k, assert[k].length);
1604 | }
1605 | }
1606 | return test;
1607 | };
1608 |
1609 | /**
1610 | * Ensures an options object has all callbacks, adding empty callback functions
1611 | * if any are missing.
1612 | *
1613 | * @param {Object} opt
1614 | * @return {Object}
1615 | * @api public
1616 | */
1617 |
1618 | exports.options = function (opt) {
1619 | var optionalCallback = function (name) {
1620 | opt[name] = opt[name] || function () {};
1621 | };
1622 |
1623 | optionalCallback('moduleStart');
1624 | optionalCallback('moduleDone');
1625 | optionalCallback('testStart');
1626 | optionalCallback('testDone');
1627 | //optionalCallback('log');
1628 |
1629 | // 'done' callback is not optional.
1630 |
1631 | return opt;
1632 | };
1633 | })(types);
1634 | (function(exports){
1635 | /*!
1636 | * Nodeunit
1637 | * Copyright (c) 2010 Caolan McMahon
1638 | * MIT Licensed
1639 | *
1640 | * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1641 | * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1642 | * Only code on that line will be removed, its mostly to avoid requiring code
1643 | * that is node specific
1644 | */
1645 |
1646 | /**
1647 | * Module dependencies
1648 | */
1649 |
1650 | //var async = require('../deps/async'), //@REMOVE_LINE_FOR_BROWSER
1651 | // types = require('./types'); //@REMOVE_LINE_FOR_BROWSER
1652 |
1653 |
1654 | /**
1655 | * Added for browser compatibility
1656 | */
1657 |
1658 | var _keys = function (obj) {
1659 | if (Object.keys) {
1660 | return Object.keys(obj);
1661 | }
1662 | var keys = [];
1663 | for (var k in obj) {
1664 | if (obj.hasOwnProperty(k)) {
1665 | keys.push(k);
1666 | }
1667 | }
1668 | return keys;
1669 | };
1670 |
1671 |
1672 | var _copy = function (obj) {
1673 | var nobj = {};
1674 | var keys = _keys(obj);
1675 | for (var i = 0; i < keys.length; i += 1) {
1676 | nobj[keys[i]] = obj[keys[i]];
1677 | }
1678 | return nobj;
1679 | };
1680 |
1681 |
1682 | /**
1683 | * Runs a test function (fn) from a loaded module. After the test function
1684 | * calls test.done(), the callback is executed with an assertionList as its
1685 | * second argument.
1686 | *
1687 | * @param {String} name
1688 | * @param {Function} fn
1689 | * @param {Object} opt
1690 | * @param {Function} callback
1691 | * @api public
1692 | */
1693 |
1694 | exports.runTest = function (name, fn, opt, callback) {
1695 | var options = types.options(opt);
1696 |
1697 | options.testStart(name);
1698 | var start = new Date().getTime();
1699 | var test = types.test(name, start, options, callback);
1700 |
1701 | try {
1702 | fn(test);
1703 | }
1704 | catch (e) {
1705 | test.done(e);
1706 | }
1707 | };
1708 |
1709 | /**
1710 | * Takes an object containing test functions or other test suites as properties
1711 | * and runs each in series. After all tests have completed, the callback is
1712 | * called with a list of all assertions as the second argument.
1713 | *
1714 | * If a name is passed to this function it is prepended to all test and suite
1715 | * names that run within it.
1716 | *
1717 | * @param {String} name
1718 | * @param {Object} suite
1719 | * @param {Object} opt
1720 | * @param {Function} callback
1721 | * @api public
1722 | */
1723 |
1724 | exports.runSuite = function (name, suite, opt, callback) {
1725 | var keys = _keys(suite);
1726 |
1727 | async.concatSeries(keys, function (k, cb) {
1728 | var prop = suite[k], _name;
1729 |
1730 | _name = name ? [].concat(name, k) : [k];
1731 |
1732 | _name.toString = function () {
1733 | // fallback for old one
1734 | return this.join(' - ');
1735 | };
1736 |
1737 | if (typeof prop === 'function') {
1738 | var in_name = false;
1739 | for (var i = 0; i < _name.length; i += 1) {
1740 | if (_name[i] === opt.testspec) {
1741 | in_name = true;
1742 | }
1743 | }
1744 | if (!opt.testspec || in_name) {
1745 | if (opt.moduleStart) {
1746 | opt.moduleStart();
1747 | }
1748 | exports.runTest(_name, suite[k], opt, cb);
1749 | }
1750 | else {
1751 | return cb();
1752 | }
1753 | }
1754 | else {
1755 | exports.runSuite(_name, suite[k], opt, cb);
1756 | }
1757 | }, callback);
1758 | };
1759 |
1760 | /**
1761 | * Run each exported test function or test suite from a loaded module.
1762 | *
1763 | * @param {String} name
1764 | * @param {Object} mod
1765 | * @param {Object} opt
1766 | * @param {Function} callback
1767 | * @api public
1768 | */
1769 |
1770 | exports.runModule = function (name, mod, opt, callback) {
1771 | var options = _copy(types.options(opt));
1772 |
1773 | var _run = false;
1774 | var _moduleStart = options.moduleStart;
1775 | function run_once() {
1776 | if (!_run) {
1777 | _run = true;
1778 | _moduleStart(name);
1779 | }
1780 | }
1781 | options.moduleStart = run_once;
1782 |
1783 | var start = new Date().getTime();
1784 |
1785 | exports.runSuite(null, mod, options, function (err, a_list) {
1786 | var end = new Date().getTime();
1787 | var assertion_list = types.assertionList(a_list, end - start);
1788 | options.moduleDone(name, assertion_list);
1789 | callback(null, a_list);
1790 | });
1791 | };
1792 |
1793 | /**
1794 | * Treats an object literal as a list of modules keyed by name. Runs each
1795 | * module and finished with calling 'done'. You can think of this as a browser
1796 | * safe alternative to runFiles in the nodeunit module.
1797 | *
1798 | * @param {Object} modules
1799 | * @param {Object} opt
1800 | * @api public
1801 | */
1802 |
1803 | // TODO: add proper unit tests for this function
1804 | exports.runModules = function (modules, opt) {
1805 | var all_assertions = [];
1806 | var options = types.options(opt);
1807 | var start = new Date().getTime();
1808 |
1809 | async.concatSeries(_keys(modules), function (k, cb) {
1810 | exports.runModule(k, modules[k], options, cb);
1811 | },
1812 | function (err, all_assertions) {
1813 | var end = new Date().getTime();
1814 | options.done(types.assertionList(all_assertions, end - start));
1815 | });
1816 | };
1817 |
1818 |
1819 | /**
1820 | * Wraps a test function with setUp and tearDown functions.
1821 | * Used by testCase.
1822 | *
1823 | * @param {Function} setUp
1824 | * @param {Function} tearDown
1825 | * @param {Function} fn
1826 | * @api private
1827 | */
1828 |
1829 | var wrapTest = function (setUp, tearDown, fn) {
1830 | return function (test) {
1831 | var context = {};
1832 | if (tearDown) {
1833 | var done = test.done;
1834 | test.done = function (err) {
1835 | try {
1836 | tearDown.call(context, function (err2) {
1837 | if (err && err2) {
1838 | test._assertion_list.push(
1839 | types.assertion({error: err})
1840 | );
1841 | return done(err2);
1842 | }
1843 | done(err || err2);
1844 | });
1845 | }
1846 | catch (e) {
1847 | done(e);
1848 | }
1849 | };
1850 | }
1851 | if (setUp) {
1852 | setUp.call(context, function (err) {
1853 | if (err) {
1854 | return test.done(err);
1855 | }
1856 | fn.call(context, test);
1857 | });
1858 | }
1859 | else {
1860 | fn.call(context, test);
1861 | }
1862 | };
1863 | };
1864 |
1865 |
1866 | /**
1867 | * Wraps a group of tests with setUp and tearDown functions.
1868 | * Used by testCase.
1869 | *
1870 | * @param {Function} setUp
1871 | * @param {Function} tearDown
1872 | * @param {Object} group
1873 | * @api private
1874 | */
1875 |
1876 | var wrapGroup = function (setUp, tearDown, group) {
1877 | var tests = {};
1878 | var keys = _keys(group);
1879 | for (var i = 0; i < keys.length; i += 1) {
1880 | var k = keys[i];
1881 | if (typeof group[k] === 'function') {
1882 | tests[k] = wrapTest(setUp, tearDown, group[k]);
1883 | }
1884 | else if (typeof group[k] === 'object') {
1885 | tests[k] = wrapGroup(setUp, tearDown, group[k]);
1886 | }
1887 | }
1888 | return tests;
1889 | };
1890 |
1891 |
1892 | /**
1893 | * Utility for wrapping a suite of test functions with setUp and tearDown
1894 | * functions.
1895 | *
1896 | * @param {Object} suite
1897 | * @return {Object}
1898 | * @api public
1899 | */
1900 |
1901 | exports.testCase = function (suite) {
1902 | var setUp = suite.setUp;
1903 | var tearDown = suite.tearDown;
1904 | delete suite.setUp;
1905 | delete suite.tearDown;
1906 | return wrapGroup(setUp, tearDown, suite);
1907 | };
1908 | })(core);
1909 | (function(exports){
1910 | /*!
1911 | * Nodeunit
1912 | * Copyright (c) 2010 Caolan McMahon
1913 | * MIT Licensed
1914 | *
1915 | * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1916 | * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1917 | * Only code on that line will be removed, its mostly to avoid requiring code
1918 | * that is node specific
1919 | */
1920 |
1921 |
1922 | /**
1923 | * NOTE: this test runner is not listed in index.js because it cannot be
1924 | * used with the command-line tool, only inside the browser.
1925 | */
1926 |
1927 |
1928 | /**
1929 | * Reporter info string
1930 | */
1931 |
1932 | exports.info = "Browser-based test reporter";
1933 |
1934 |
1935 | /**
1936 | * Run all tests within each module, reporting the results
1937 | *
1938 | * @param {Array} files
1939 | * @api public
1940 | */
1941 |
1942 | exports.run = function (modules, options) {
1943 | var start = new Date().getTime();
1944 | var textareas = options.textareas;
1945 | var displayErrorsByDefault = options.displayErrorsByDefault;
1946 |
1947 | function setText(el, txt) {
1948 | if ('innerText' in el) {
1949 | el.innerText = txt;
1950 | }
1951 | else if ('textContent' in el){
1952 | el.textContent = txt;
1953 | }
1954 | }
1955 |
1956 | function getOrCreate(tag, id) {
1957 | var el = document.getElementById(id);
1958 | if (!el) {
1959 | el = document.createElement(tag);
1960 | el.id = id;
1961 | document.body.appendChild(el);
1962 | }
1963 | return el;
1964 | };
1965 |
1966 | var header = getOrCreate('h1', 'nodeunit-header');
1967 | var banner = getOrCreate('h2', 'nodeunit-banner');
1968 | var userAgent = getOrCreate('h2', 'nodeunit-userAgent');
1969 | var tests = getOrCreate('ol', 'nodeunit-tests');
1970 | var result = getOrCreate('p', 'nodeunit-testresult');
1971 |
1972 | setText(userAgent, navigator.userAgent);
1973 |
1974 | nodeunit.runModules(modules, {
1975 | moduleStart: function (name) {
1976 | /*var mheading = document.createElement('h2');
1977 | mheading.innerText = name;
1978 | results.appendChild(mheading);
1979 | module = document.createElement('ol');
1980 | results.appendChild(module);*/
1981 | },
1982 | testDone: function (name, assertions) {
1983 | var test = document.createElement('li');
1984 | var strong = document.createElement('strong');
1985 | strong.innerHTML = name + ' (' +
1986 | '' + assertions.failures() + ' , ' +
1987 | '' + assertions.passes() + ' , ' +
1988 | assertions.length +
1989 | ') ';
1990 | test.className = assertions.failures() ? 'fail': 'pass';
1991 | test.appendChild(strong);
1992 |
1993 | var aList = document.createElement('ol');
1994 | aList.style.display = displayErrorsByDefault ? 'block' : 'none';
1995 | (displayErrorsByDefault ? strong : test).onclick = function () {
1996 | var d = aList.style.display;
1997 | aList.style.display = (d == 'none') ? 'block': 'none';
1998 | };
1999 | for (var i=0; i' + (a.error.stack || a.error) + '' :
2006 | '' + (a.error.stack || a.error) + ' ');
2007 | li.className = 'fail';
2008 | }
2009 | else {
2010 | li.innerHTML = a.message || a.method || 'no message';
2011 | li.className = 'pass';
2012 | }
2013 | aList.appendChild(li);
2014 | }
2015 | test.appendChild(aList);
2016 | tests.appendChild(test);
2017 | },
2018 | done: function (assertions) {
2019 | var end = new Date().getTime();
2020 | var duration = end - start;
2021 |
2022 | var failures = assertions.failures();
2023 | banner.className = failures ? 'fail': 'pass';
2024 |
2025 | result.innerHTML = 'Tests completed in ' + duration +
2026 | ' milliseconds.' +
2027 | assertions.passes() + ' assertions of ' +
2028 | '' + assertions.length + ' passed, ' +
2029 | assertions.failures() + ' failed.';
2030 | }
2031 | });
2032 | };
2033 | })(reporter);
2034 | nodeunit = core;
2035 | nodeunit.assert = assert;
2036 | nodeunit.reporter = reporter;
2037 | nodeunit.run = reporter.run;
2038 | return nodeunit; })();
2039 |
--------------------------------------------------------------------------------