[Pkg-javascript-commits] [jsondiffpatch.js] 01/02: Imported Upstream version 0.1.8+dfsg

Andrew Kelley andrewrk-guest at moszumanska.debian.org
Mon Sep 15 18:06:32 UTC 2014


This is an automated email from the git hooks/post-receive script.

andrewrk-guest pushed a commit to branch master
in repository jsondiffpatch.js.

commit 0584e8104260806bc7177169eea0193a4a920149
Author: Andrew Kelley <superjoe30 at gmail.com>
Date:   Mon Sep 15 18:05:28 2014 +0000

    Imported Upstream version 0.1.8+dfsg
---
 .gitignore                   |   16 +
 .jshintrc                    |   86 +
 .travis.yml                  |    7 +
 MIT-LICENSE.txt              |   21 +
 Makefile                     |   12 +
 README.md                    |  280 ++
 bower.json                   |   28 +
 demo/consoledemo.js          |  124 +
 demo/consoledemo.png         |  Bin 0 -> 24536 bytes
 demo/demo.js                 |  606 +++++
 demo/index.html              |  109 +
 demo/left.json               |    9 +
 demo/numeric-plugin.js       |   76 +
 demo/right.json              |   10 +
 demo/style.css               |  144 ++
 docs/arrays.md               |   88 +
 docs/deltas.md               |  120 +
 docs/formatters.md           |   63 +
 docs/plugins.md              |   96 +
 gulpfile.js                  |  130 +
 karma.conf.js                |   13 +
 package.json                 |   81 +
 src/contexts/context.js      |   49 +
 src/contexts/diff.js         |   12 +
 src/contexts/patch.js        |   12 +
 src/contexts/reverse.js      |   11 +
 src/date-reviver.js          |   13 +
 src/diffpatcher.js           |   62 +
 src/filters/arrays.js        |  367 +++
 src/filters/dates.js         |   19 +
 src/filters/lcs.js           |   74 +
 src/filters/nested.js        |  109 +
 src/filters/texts.js         |  111 +
 src/filters/trivial.js       |   98 +
 src/formatters/annotated.css |   56 +
 src/formatters/annotated.js  |  198 ++
 src/formatters/base.js       |  210 ++
 src/formatters/console.js    |  182 ++
 src/formatters/html.css      |  186 ++
 src/formatters/html.js       |  258 ++
 src/formatters/index.js      |    8 +
 src/main.js                  |   50 +
 src/pipe.js                  |  111 +
 src/processor.js             |   60 +
 test-external/expect.js      | 1284 ++++++++++
 test-external/mocha.css      |  270 ++
 test-external/mocha.js       | 5812 ++++++++++++++++++++++++++++++++++++++++++
 test/examples/diffpatch.js   |  560 ++++
 test/index.html              |   20 +
 test/test.js                 |  169 ++
 50 files changed, 12490 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..87a4ef1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
+node_modules
+lib-cov
+*.seed
+*.log
+*.csv
+*.dat
+*.out
+*.pid
+*.gz
+.DS_Store
+
+pids
+logs
+results
+
+npm-debug.log
diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 0000000..1b46814
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,86 @@
+{
+    // JSHint Default Configuration File (as on JSHint website)
+    // See http://jshint.com/docs/ for more details
+
+    "maxerr"        : 10,       // {int} Maximum error before stopping
+
+    // Enforcing
+    "bitwise"       : true,     // true: Prohibit bitwise operators (&, |, ^, etc.)
+    "camelcase"     : true,     // true: Identifiers must be in camelCase
+    "curly"         : true,     // true: Require {} for every new block or scope
+    "eqeqeq"        : true,     // true: Require triple equals (===) for comparison
+    "forin"         : false,     // true: Require filtering for..in loops with obj.hasOwnProperty()
+    "immed"         : true,     // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
+    "indent"        : 4,        // {int} Number of spaces to use for indentation
+    "latedef"       : true,     // true: Require variables/functions to be defined before being used
+    "newcap"        : true,    // true: Require capitalization of all constructor functions e.g. `new F()`
+    "noarg"         : true,     // true: Prohibit use of `arguments.caller` and `arguments.callee`
+    "noempty"       : false,    // true: Prohibit use of empty blocks
+    "nonew"         : true,     // true: Prohibit use of constructors for side-effects (without assignment)
+    "plusplus"      : false,    // true: Prohibit use of `++` & `--`
+    "quotmark"      : "single",    // Quotation mark consistency:
+                                //   false    : do nothing (default)
+                                //   true     : ensure whatever is used is consistent
+                                //   "single" : require single quotes
+                                //   "double" : require double quotes
+    "undef"         : true,     // true: Require all non-global variables to be declared (prevents global leaks)
+    "unused"        : true,     // true: Require all defined variables be used
+    "strict"        : false,     // true: Requires all functions run in ES5 Strict Mode
+    "trailing"      : true,     // true: Prohibit trailing whitespaces
+    "maxparams"     : 7,    // {int} Max number of formal params allowed per function
+    "maxdepth"      : 6,    // {int} Max depth of nested blocks (within functions)
+    "maxstatements" : false,    // {int} Max number statements per function
+    "maxcomplexity" : false,    // {int} Max cyclomatic complexity per function
+    "maxlen"        : 120,    // {int} Max number of characters per line
+
+    // Relaxing
+    "asi"           : false,     // true: Tolerate Automatic Semicolon Insertion (no semicolons)
+    "boss"          : false,     // true: Tolerate assignments where comparisons would be expected
+    "debug"         : false,     // true: Allow debugger statements e.g. browser breakpoints.
+    "eqnull"        : false,     // true: Tolerate use of `== null`
+    "es5"           : false,     // true: Allow ES5 syntax (ex: getters and setters)
+    "esnext"        : false,     // true: Allow ES.next (ES6) syntax (ex: `const`)
+    "moz"           : false,     // true: Allow Mozilla specific syntax (extends and overrides esnext features)
+                                 // (ex: `for each`, multiple try/catch, function expression…)
+    "evil"          : false,     // true: Tolerate use of `eval` and `new Function()`
+    "expr"          : false,     // true: Tolerate `ExpressionStatement` as Programs
+    "funcscope"     : false,     // true: Tolerate defining variables inside control statements"
+    "globalstrict"  : false,     // true: Allow global "use strict" (also enables 'strict')
+    "iterator"      : false,     // true: Tolerate using the `__iterator__` property
+    "lastsemic"     : false,     // true: Tolerate omitting a semicolon for the last statement of a 1-line block
+    "laxbreak"      : false,     // true: Tolerate possibly unsafe line breakings
+    "laxcomma"      : false,     // true: Tolerate comma-first style coding
+    "loopfunc"      : false,     // true: Tolerate functions being defined in loops
+    "multistr"      : false,     // true: Tolerate multi-line strings
+    "proto"         : false,     // true: Tolerate using the `__proto__` property
+    "scripturl"     : false,     // true: Tolerate script-targeted URLs
+    "smarttabs"     : false,     // true: Tolerate mixed tabs/spaces when used for alignment
+    "shadow"        : false,     // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
+    "sub"           : false,     // true: Tolerate using `[]` notation when it can still be expressed in dot notation
+    "supernew"      : false,     // true: Tolerate `new function () { ... };` and `new Object;`
+    "validthis"     : false,     // true: Tolerate using this in a non-constructor function
+
+    // Environments
+    "browser"       : true,     // Web Browser (window, document, etc)
+    "couch"         : false,    // CouchDB
+    "devel"         : false,    // Development/debugging (alert, confirm, etc)
+    "dojo"          : false,    // Dojo Toolkit
+    "jquery"        : false,    // jQuery
+    "mootools"      : false,    // MooTools
+    "node"          : true,    // Node.js
+    "nonstandard"   : false,    // Widely adopted globals (escape, unescape, etc)
+    "prototypejs"   : false,    // Prototype and Scriptaculous
+    "rhino"         : false,    // Rhino
+    "worker"        : false,    // Web Workers
+    "wsh"           : false,    // Windows Scripting Host
+    "yui"           : false,    // Yahoo User Interface
+
+    // Legacy
+    "nomen"         : false,    // true: Prohibit dangling `_` in variables
+    "onevar"        : false,    // true: Allow only one `var` statement per function
+    "passfail"      : false,    // true: Stop on first error
+    "white"         : false,    // true: Check against strict whitespace and indentation rules
+
+    // Custom Globals
+    "predef"        : [ ]       // additional predefined global variables
+}
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..162fb01
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,7 @@
+language: node_js
+node_js:
+  - 0.10
+before_install:
+  - "export BROWSERS=Firefox"
+  - "export DISPLAY=:99.0"
+  - "sh -e /etc/init.d/xvfb start"
\ No newline at end of file
diff --git a/MIT-LICENSE.txt b/MIT-LICENSE.txt
new file mode 100644
index 0000000..668e253
--- /dev/null
+++ b/MIT-LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2014 Benjam�n Eidelman twitter.com/beneidel
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..ace9364
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,12 @@
+
+build: node_modules
+	@./node_modules/.bin/gulp build
+node_modules:
+	npm install
+test: node_modules
+	@./node_modules/.bin/gulp test
+test-browser: node_modules
+	@./node_modules/.bin/gulp test-browser
+watch: node_modules
+	@./node_modules/.bin/gulp watch
+.PHONY: build test test-browser watch
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..31154f4
--- /dev/null
+++ b/README.md
@@ -0,0 +1,280 @@
+jsondiffpatch
+=============
+
+<!--- badges -->
+[![Build Status](https://secure.travis-ci.org/benjamine/jsondiffpatch.png)](http://travis-ci.org/benjamine/jsondiffpatch)
+[![NPM version](https://badge.fury.io/js/jsondiffpatch.png)](http://badge.fury.io/js/jsondiffpatch)
+[![NPM dependencies](https://david-dm.org/benjamine/jsondiffpatch.png)](https://david-dm.org/benjamine/jsondiffpatch)
+[![Bower version](https://badge.fury.io/bo/jsondiffpatch.png)](http://badge.fury.io/bo/jsondiffpatch)
+
+Diff & patch JavaScript objects
+
+-----
+**[Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html)**
+-----
+
+- min+gzipped < 6KB
+- browser (```/build/bundle.js```) and server (eg. node.js)
+- includes [google-diff-match-patch](http://code.google.com/p/google-diff-match-patch/) for long text diffs (diff at character level)
+- smart array diffing using [LCS](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem), ***IMPORTANT NOTE:*** to match objects inside an array you ***must*** provide an ```objectHash``` function, check [Array diff documentation](docs/arrays.md)
+- reverse a delta
+- unpatch (eg. revert object to its original state using a delta)
+- simplistic, pure JSON, low footprint [delta format](docs/deltas.md)
+- multiple output formatters:
+    - html (check it at the [Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html))
+    - annotated json (html), makes the JSON delta format self-explained
+    - console (colored), try running ```./node_modules/.bin/jsondiffpatch left.json right.json```
+    - write your own! check [Formatters documentation](docs/formatters.md)
+
+Supported platforms
+----------------
+
+* Any modern browser and IE8+
+
+[![Testling Status](https://ci.testling.com/benjamine/jsondiffpatch.png)](https://ci.testling.com/benjamine/jsondiffpatch)
+
+And you can test your current browser visiting the [test page](http://benjamine.github.com/jsondiffpatch/test/index.html).
+
+* Node.js [![Build Status](https://secure.travis-ci.org/benjamine/jsondiffpatch.png)](http://travis-ci.org/benjamine/jsondiffpatch)
+
+If you want to run tests locally:
+``` sh
+npm i
+# will test in node.js and phantomjs (headless browser)
+npm test
+# or test on specific browsers (using karma.js)
+BROWSERS=chrome,phantomjs npm test
+```
+Usage
+-----
+
+``` javascript
+    // sample data
+    var country = {
+        name: "Argentina",
+        capital: "Buenos Aires",
+        independence: new Date(1816, 6, 9),
+        unasur: true
+    };
+
+    // clone country, using dateReviver for Date objects
+    var country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver);
+
+    // make some changes
+    country2.name = "Republica Argentina";
+    country2.population = 41324992;
+    delete country2.capital;
+
+    var delta = jsondiffpatch.diff(country, country2);
+
+    assertSame(delta, {
+        "name":["Argentina","Republica Argentina"], // old value, new value
+        "population":["41324992"], // new value
+        "capital":["Buenos Aires", 0, 0] // deleted
+    });
+
+    // patch original
+    jsondiffpatch.patch(country, delta);
+
+    // reverse diff
+    var reverseDelta = jsondiffpatch.reverse(delta);
+    // also country2 can be return to original value with: jsondiffpatch.unpatch(country2, delta);
+
+    var delta2 = jsondiffpatch.diff(country, country2);
+    assert(delta2 === undefined)
+    // undefined => no difference
+```
+
+Array diffing:
+
+``` javascript
+    // sample data
+    var country = {
+        name: "Argentina",
+        cities: [
+        {
+            name: 'Buenos Aires',
+            population: 13028000,
+        },
+        {
+            name: 'Cordoba',
+            population: 1430023,
+        },
+        {
+            name: 'Rosario',
+            population: 1136286,
+        },
+        {
+            name: 'Mendoza',
+            population: 901126,
+        },
+        {
+            name: 'San Miguel de Tucuman',
+            population: 800000,
+        }
+        ]
+    };
+
+    // clone country
+    var country2 = JSON.parse(JSON.stringify(country));
+
+    // delete Cordoba
+    country.cities.splice(1, 1);
+
+    // add La Plata
+    country.cities.splice(4, 0, {
+        name: 'La Plata'
+        });
+
+    // modify Rosario, and move it
+    var rosario = country.cities.splice(1, 1)[0];
+    rosario.population += 1234;
+    country.cities.push(rosario);
+
+    // create a configured instance, match objects by name
+    var diffpatcher = jsondiffpatch.create({
+        objectHash: function(obj) {
+            return obj.name;
+        }
+    });
+
+    var delta = diffpatcher.diff(country, country2);
+
+    assertSame(delta, {
+        "cities": {
+            "_t": "a", // indicates this node is an array (not an object)
+            "1": [
+                // inserted at index 1
+                {
+                    "name": "Cordoba",
+                    "population": 1430023
+                }]
+            ,
+            "2": {
+                // population modified at index 2 (Rosario)
+                "population": [
+                    1137520,
+                    1136286
+                ]
+            },
+            "_3": [
+                // removed from index 3
+                {
+                    "name": "La Plata"
+                }, 0, 0],
+            "_4": [
+                // move from index 4 to index 2
+                '', 2, 3]
+        }
+    });
+```
+
+For more example cases (nested objects or arrays, long text diffs) check ```test/examples/```
+
+If you want to understand deltas, see [delta format documentation](docs/deltas.md)
+
+Installing
+---------------
+
+### npm (node.js)
+
+``` sh
+npm install jsondiffpatch
+```
+
+``` js
+var jsondiffpatch = require('jsondiffpatch').create(options);
+```
+
+### bower (browser)
+
+``` sh
+bower install jsondiffpatch
+```
+
+browser bundles are in the ```/build``` folder (run ```make``` or ```gulp``` to generate these):
+- ```bundle.js``` main bundle
+- ```bundle.full.js``` main bundle + [google-diff-match-patch](http://code.google.com/p/google-diff-match-patch/) library for text diffs
+- ```formatters.js``` builtin formatters (only those useful in a browser)
+
+(all these come in minified versions: ```.min.js```)
+
+Options
+-------
+
+``` javascript
+var jsondiffpatch = require('jsondiffpatch').create({
+    // used to match objects when diffing arrays, by default only === operator is used
+    objectHash: function(obj) {
+        // this function is used only to when objects are not equal by ref
+        return obj._id || obj.id;
+    },
+    arrays: {
+        // default true, detect items moved inside the array (otherwise they will be registered as remove+add)
+        detectMove: true,
+        // default false, the value of items moved is not included in deltas
+        includeValueOnMove: false
+    },
+    textDiff: {
+        // default 60, minimum string length (left and right sides) to use text diff algorythm: google-diff-match-patch
+        minLength: 60
+    }
+});
+```
+
+Visual Diff
+----------------
+
+``` html
+<!DOCTYPE html>
+<html>
+    <head>
+        <script type="text/javascript" src="build/bundle.min.js"></script>
+        <script type="text/javascript" src="build/formatters.min.js"></script>
+        <link rel="stylesheet" href="src/formatters/html.css" type="text/css" />
+        <link rel="stylesheet" href="src/formatters/annotated.css" type="text/css" />
+    </head>
+    <body>
+        <div id="visual"></div>
+        <hr/>
+        <div id="annotated"></div>
+        <script>
+            var left = { a: 3, b: 4 };
+            var right = { a: 5, c: 9 };
+            var delta = jsondiffpatch.diff(left, right);
+
+            // beautiful html diff
+            document.getElementById('visual').innerHTML = jsondiffpatch.formatters.html.format(delta, left);
+
+            // self-explained json
+            document.getElementById('annotated').innerHTML = jsondiffpatch.formatters.annotated.format(delta, left);
+        </script>
+    </body>
+</html>
+```
+
+To see formatters in action check the [Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html).
+
+For more details check [Formatters documentation](docs/formatters.md)
+
+Console
+--------
+
+``` sh
+# diff two json files, colored output (using chalk lib)
+./node_modules/.bin/jsondiffpatch ./left.json ./right.json
+
+# or install globally
+npm install -g jsondiffpatch
+
+jsondiffpatch ./demo/left.json ./demo/right.json
+```
+
+![console_demo!](demo/consoledemo.png)
+
+Plugins
+-------
+
+```diff()```, ```patch()``` and ```reverse()``` functions are implemented using Pipes &Filters pattern, making it extremely customizable by adding or replacing filters on a pipe.
+
+Check [Plugins documentation](docs/plugins.md) for details.
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000..c0e68f8
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,28 @@
+{
+  "name": "jsondiffpatch",
+  "description": "Diff & Patch for Javascript objects",
+  "main": "build/bundle.js",
+  "license": "MIT",
+  "authors": [
+    "Benjamin Eidelman <beneidel at gmail.com>"
+  ],
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/benjamine/jsondiffpatch.git"
+  },
+  "keywords": [
+    "json",
+    "diff",
+    "patch",
+    "jsondiffpatch"
+  ],
+  "ignore": [
+    "test",
+    "test-external",
+    "demo",
+    "docs",
+    ".travis.yml",
+    "karma.conf.js",
+    "gulpfile.js"
+  ]
+}
diff --git a/demo/consoledemo.js b/demo/consoledemo.js
new file mode 100644
index 0000000..6c07890
--- /dev/null
+++ b/demo/consoledemo.js
@@ -0,0 +1,124 @@
+
+var jsondiffpatch = require('../src/main');
+
+var instance = jsondiffpatch.create({
+    objectHash: function(obj) {
+        return obj._id || obj.id || obj.name || JSON.stringify(obj);
+    }
+});
+
+var data = {
+    name: 'South America',
+    summary: 'South America (Spanish: América del Sur, Sudamérica or Suramérica; Portuguese: América do Sul;' +
+        ' Quechua and Aymara: Urin Awya Yala; Guarani: Ñembyamérika; Dutch: Zuid-Amerika; French: Amérique' +
+        ' du Sud) is a continent situated in the Western Hemisphere, mostly in the Southern Hemisphere,' +
+        ' with a relatively small portion in the Northern Hemisphere. The continent is also considered a' +
+        ' subcontinent of the Americas.[2][3] It is bordered on the west by the Pacific Ocean and on the ' +
+        'north and east by the Atlantic Ocean; North America and the Caribbean Sea lie to the northwest. ' +
+        'It includes twelve countries: Argentina, Bolivia, Brazil, Chile, Colombia, Ecuador, Guyana, Paraguay' +
+        ', Peru, Suriname, Uruguay, and Venezuela. The South American nations that border the Caribbean ' +
+        'Sea—including Colombia, Venezuela, Guyana, Suriname, as well as French Guiana, which is an overseas' +
+        ' region of France—are also known as Caribbean South America. South America has an area of 17,840,000' +
+        ' square kilometers (6,890,000 sq mi). Its population as of 2005 has been estimated at more than ' +
+        '371,090,000. South America ranks fourth in area (after Asia, Africa, and North America) and fifth ' +
+        'in population (after Asia, Africa, Europe, and North America). The word America was coined in 1507 by' +
+        ' cartographers Martin Waldseemüller and Matthias Ringmann, after Amerigo Vespucci, who was the first ' +
+        'European to suggest that the lands newly discovered by Europeans were not India, but a New World ' +
+        'unknown to Europeans.',
+
+    surface: 17840000,
+    timezone: [-4, -2],
+    demographics: {
+        population: 385742554,
+        largestCities: ['São Paulo', 'Buenos Aires', 'Rio de Janeiro', 'Lima', 'Bogotá']
+    },
+    languages: ['spanish', 'portuguese', 'english', 'dutch', 'french', 'quechua', 'guaraní', 'aimara', 'mapudungun'],
+    countries: [{
+        name: 'Argentina',
+        capital: 'Buenos Aires',
+        independence: new Date(1816, 6, 9),
+        unasur: true
+    }, {
+        name: 'Bolivia',
+        capital: 'La Paz',
+        independence: new Date(1825, 7, 6),
+        unasur: true
+    }, {
+        name: 'Brazil',
+        capital: 'Brasilia',
+        independence: new Date(1822, 8, 7),
+        unasur: true
+    }, {
+        name: 'Chile',
+        capital: 'Santiago',
+        independence: new Date(1818, 1, 12),
+        unasur: true
+    }, {
+        name: 'Colombia',
+        capital: 'Bogotá',
+        independence: new Date(1810, 6, 20),
+        unasur: true
+    }, {
+        name: 'Ecuador',
+        capital: 'Quito',
+        independence: new Date(1809, 7, 10),
+        unasur: true
+    }, {
+        name: 'Guyana',
+        capital: 'Georgetown',
+        independence: new Date(1966, 4, 26),
+        unasur: true
+    }, {
+        name: 'Paraguay',
+        capital: 'Asunción',
+        independence: new Date(1811, 4, 14),
+        unasur: true
+    }, {
+        name: 'Peru',
+        capital: 'Lima',
+        independence: new Date(1821, 6, 28),
+        unasur: true
+    }, {
+        name: 'Suriname',
+        capital: 'Paramaribo',
+        independence: new Date(1975, 10, 25),
+        unasur: true
+    }, {
+        name: 'Uruguay',
+        capital: 'Montevideo',
+        independence: new Date(1825, 7, 25),
+        unasur: true
+    }, {
+        name: 'Venezuela',
+        capital: 'Caracas',
+        independence: new Date(1811, 6, 5),
+        unasur: true
+    }]
+};
+
+var left = JSON.parse((JSON.stringify(data)), jsondiffpatch.dateReviver);
+
+data.summary = data.summary.replace('Brazil', 'Brasil').replace('also known as', 'a.k.a.');
+data.languages[2] = 'inglés';
+data.countries.pop();
+data.countries.pop();
+data.countries[0].capital = 'Rawson';
+data.countries.push({
+    name: 'Antártida',
+    unasur: false
+});
+
+// modify and move
+data.countries[4].population = 42888594;
+data.countries.splice(11, 0, data.countries.splice(4, 1)[0]);
+
+data.countries.splice(2, 0, data.countries.splice(7, 1)[0]);
+
+delete data.surface;
+data.spanishName = 'Sudamérica';
+data.demographics.population += 2342;
+
+var right = data;
+var delta = instance.diff(left, right);
+
+jsondiffpatch.console.log(delta);
\ No newline at end of file
diff --git a/demo/consoledemo.png b/demo/consoledemo.png
new file mode 100644
index 0000000..e53d008
Binary files /dev/null and b/demo/consoledemo.png differ
diff --git a/demo/demo.js b/demo/demo.js
new file mode 100644
index 0000000..885ad49
--- /dev/null
+++ b/demo/demo.js
@@ -0,0 +1,606 @@
+(function demo(){
+
+    var getExampleJson = function() {
+        var data = {
+            name: 'South America',
+            summary: 'South America (Spanish: América del Sur, Sudamérica or  \n' +
+                'Suramérica; Portuguese: América do Sul; Quechua and Aymara:  \n' +
+                'Urin Awya Yala; Guarani: Ñembyamérika; Dutch: Zuid-Amerika;  \n' +
+                'French: Amérique du Sud) is a continent situated in the  \n' +
+                'Western Hemisphere, mostly in the Southern Hemisphere, with  \n' +
+                'a relatively small portion in the Northern Hemisphere.  \n' +
+                'The continent is also considered a subcontinent of the  \n' +
+                'Americas.[2][3] It is bordered on the west by the Pacific  \n' +
+                'Ocean and on the north and east by the Atlantic Ocean;  \n' +
+                'North America and the Caribbean Sea lie to the northwest.  \n' +
+                'It includes twelve countries: Argentina, Bolivia, Brazil,  \n' +
+                'Chile, Colombia, Ecuador, Guyana, Paraguay, Peru, Suriname,  \n' +
+                'Uruguay, and Venezuela. The South American nations that  \n' +
+                'border the Caribbean Sea—including Colombia, Venezuela,  \n' +
+                'Guyana, Suriname, as well as French Guiana, which is an  \n' +
+                'overseas region of France—are also known as Caribbean South  \n' +
+                'America. South America has an area of 17,840,000 square  \n' +
+                'kilometers (6,890,000 sq mi). Its population as of 2005  \n' +
+                'has been estimated at more than 371,090,000. South America  \n' +
+                'ranks fourth in area (after Asia, Africa, and North America)  \n' +
+                'and fifth in population (after Asia, Africa, Europe, and  \n' +
+                'North America). The word America was coined in 1507 by  \n' +
+                'cartographers Martin Waldseemüller and Matthias Ringmann,  \n' +
+                'after Amerigo Vespucci, who was the first European to  \n' +
+                'suggest that the lands newly discovered by Europeans were  \n' +
+                'not India, but a New World unknown to Europeans.',
+
+            surface: 17840000,
+            timezone: [-4, -2],
+            demographics: {
+                population: 385742554,
+                largestCities: ['São Paulo', 'Buenos Aires', 'Rio de Janeiro', 'Lima', 'Bogotá']
+            },
+            languages: ['spanish', 'portuguese', 'english', 'dutch',
+            'french', 'quechua', 'guaraní', 'aimara', 'mapudungun'],
+            countries: [{
+                name: 'Argentina',
+                capital: 'Buenos Aires',
+                independence: new Date(1816, 6, 9),
+                unasur: true
+            }, {
+                name: 'Bolivia',
+                capital: 'La Paz',
+                independence: new Date(1825, 7, 6),
+                unasur: true
+            }, {
+                name: 'Brazil',
+                capital: 'Brasilia',
+                independence: new Date(1822, 8, 7),
+                unasur: true
+            }, {
+                name: 'Chile',
+                capital: 'Santiago',
+                independence: new Date(1818, 1, 12),
+                unasur: true
+            }, {
+                name: 'Colombia',
+                capital: 'Bogotá',
+                independence: new Date(1810, 6, 20),
+                unasur: true
+            }, {
+                name: 'Ecuador',
+                capital: 'Quito',
+                independence: new Date(1809, 7, 10),
+                unasur: true
+            }, {
+                name: 'Guyana',
+                capital: 'Georgetown',
+                independence: new Date(1966, 4, 26),
+                unasur: true
+            }, {
+                name: 'Paraguay',
+                capital: 'Asunción',
+                independence: new Date(1811, 4, 14),
+                unasur: true
+            }, {
+                name: 'Peru',
+                capital: 'Lima',
+                independence: new Date(1821, 6, 28),
+                unasur: true
+            }, {
+                name: 'Suriname',
+                capital: 'Paramaribo',
+                independence: new Date(1975, 10, 25),
+                unasur: true
+            }, {
+                name: 'Uruguay',
+                capital: 'Montevideo',
+                independence: new Date(1825, 7, 25),
+                unasur: true
+            }, {
+                name: 'Venezuela',
+                capital: 'Caracas',
+                independence: new Date(1811, 6, 5),
+                unasur: true
+            }]
+        };
+
+        var json = [JSON.stringify(data, null, 2)];
+
+        data.summary = data.summary.replace('Brazil', 'Brasil').replace('also known as', 'a.k.a.');
+        data.languages[2] = 'inglés';
+        data.countries.pop();
+        data.countries.pop();
+        data.countries[0].capital = 'Rawson';
+        data.countries.push({
+            name: 'Antártida',
+            unasur: false
+        });
+
+        // modify and move
+        data.countries[4].population = 42888594;
+        data.countries.splice(11, 0, data.countries.splice(4, 1)[0]);
+
+        data.countries.splice(2, 0, data.countries.splice(7, 1)[0]);
+
+        delete data.surface;
+        data.spanishName = 'Sudamérica';
+        data.demographics.population += 2342;
+
+        json.push(JSON.stringify(data, null, 2));
+
+        return json;
+    };
+
+
+    /* global jsondiffpatch */
+    var instance = jsondiffpatch.create({
+        objectHash: function(obj) {
+            return obj._id || obj.id || obj.name || JSON.stringify(obj);
+        }
+    });
+
+    var dom = {
+        addClass: function(el, className) {
+            if (el.classList) {
+                el.classList.add(className);
+            } else {
+                el.className += ' ' + className;
+            }
+        },
+        removeClass: function(el, className) {
+            if (el.classList) {
+                el.classList.remove(className);
+            } else {
+                el.className = el.className.replace(new RegExp('(^|\\b)' +
+                    className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
+            }
+        },
+        text: function(el, text) {
+            if (typeof el.textContent !== 'undefined') {
+                if (typeof text === 'undefined') {
+                    return el.textContent;
+                }
+                el.textContent = text;
+            } else {
+                if (typeof text === 'undefined') {
+                    return el.innerText;
+                }
+                el.innerText = text;
+            }
+        },
+        on: function(el, eventName, handler) {
+            if (el.addEventListener) {
+                el.addEventListener(eventName, handler);
+            } else {
+                el.attachEvent('on' + eventName, handler);
+            }
+        },
+        ready: function(fn) {
+            if (document.addEventListener) {
+                document.addEventListener('DOMContentLoaded', fn);
+            } else {
+                document.attachEvent('onreadystatechange', function() {
+                    if (document.readyState === 'interactive') { fn(); }
+                });
+            }
+        },
+        getJson: function(url, callback) {
+            var request = new XMLHttpRequest();
+            request.open('GET', url, true);
+            request.onreadystatechange = function() {
+                if (this.readyState === 4){
+                    var data;
+                    try {
+                        data = JSON.parse(this.responseText, jsondiffpatch.dateReviver);
+                    } catch (parseError) {
+                        callback('parse error: ' + parseError);
+                    }
+                    if (this.status >= 200 && this.status < 400){
+                        callback(null, data);
+                    } else {
+                        callback(new Error('request failed'), data);
+                    }
+                }
+            };
+            request.send();
+            request = null;
+        },
+        runScriptTags: function(el) {
+            var scripts = el.querySelectorAll('script');
+            for (var i = 0; i < scripts.length; i++) {
+                var s = scripts[i];
+                /* jshint evil: true */
+                eval(s.innerHTML);
+            }
+        }
+    };
+
+    var trim = function(str) {
+        return str.replace(/^\s+|\s+$/g, '');
+    };
+
+    var JsonArea = function JsonArea(element) {
+        this.element = element;
+        this.container = element.parentNode;
+        var self = this;
+        var prettifyButton = this.container.querySelector('.prettyfy');
+        if (prettifyButton) {
+            dom.on(prettifyButton, 'click', function() {
+                self.prettyfy();
+            });
+        }
+    };
+
+    JsonArea.prototype.error = function(err) {
+        var errorElement = this.container.querySelector('.error-message');
+        if (!err) {
+            dom.removeClass(this.container, 'json-error');
+            errorElement.innerHTML = '';
+            return;
+        }
+        errorElement.innerHTML = err+'';
+        dom.addClass(this.container, 'json-error');
+    };
+
+    JsonArea.prototype.getValue = function(){
+        if (!this.editor) { return this.element.value; }
+        return this.editor.getValue();
+    };
+
+    JsonArea.prototype.parse = function() {
+        var txt = trim(this.getValue());
+        try {
+            this.error(false);
+            if (/^\d+(.\d+)?(e[\+\-]?\d+)?$/i.test(txt) ||
+                /^(true|false)$/.test(txt) ||
+                /^["].*["]$/.test(txt) ||
+                /^[\{\[](.|\n)*[\}\]]$/.test(txt)) {
+                return JSON.parse(txt, jsondiffpatch.dateReviver);
+            }
+            return this.getValue();
+        } catch(err) {
+            this.error(err);
+            throw err;
+        }
+    };
+
+    JsonArea.prototype.setValue = function(value) {
+        if (!this.editor) { this.element.value = value; return; }
+        this.editor.setValue(value);
+    };
+
+    JsonArea.prototype.prettyfy = function() {
+        var value = this.parse();
+        var prettyJson = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
+        this.setValue(prettyJson);
+    };
+
+    /* global CodeMirror */
+    JsonArea.prototype.makeEditor = function(readOnly) {
+        if (typeof CodeMirror === 'undefined') { return; }
+        this.editor = CodeMirror.fromTextArea(this.element, {
+            mode:  'javascript',
+            json: true,
+            readOnly: readOnly
+        });
+        if (!readOnly) {
+            this.editor.on('change', compare);
+        }
+    };
+
+    var areas = {
+        left: new JsonArea(document.getElementById('json-input-left')),
+        right: new JsonArea(document.getElementById('json-input-right')),
+        delta: new JsonArea(document.getElementById('json-delta'))
+    };
+
+    var compare = function() {
+        var left, right, error;
+        document.getElementById('results').style.display = 'none';
+        try {
+            left = areas.left.parse();
+        } catch(err) {
+            error = err;
+        }
+        try {
+            right = areas.right.parse();
+        } catch(err) {
+            error = err;
+        }
+        areas.delta.error(false);
+        if (error) {
+            areas.delta.setValue('');
+            return;
+        }
+        var selectedType = getSelectedDeltaType();
+        var visualdiff = document.getElementById('visualdiff');
+        var annotateddiff = document.getElementById('annotateddiff');
+        var jsondifflength = document.getElementById('jsondifflength');
+        try {
+            var delta = instance.diff(left, right);
+
+            if (typeof delta === 'undefined') {
+                switch (selectedType) {
+                    case 'visual':
+                        visualdiff.innerHTML = 'no diff';
+                        break;
+                    case 'annotated':
+                        annotateddiff.innerHTML = 'no diff';
+                        break;
+                    case 'json':
+                        areas.delta.setValue('no diff');
+                        jsondifflength.innerHTML = '0';
+                        break;
+                }
+            } else {
+                switch (selectedType) {
+                    case 'visual':
+                        visualdiff.innerHTML = jsondiffpatch.formatters.html.format(delta, left);
+                        if (!document.getElementById('showunchanged').checked) {
+                            jsondiffpatch.formatters.html.hideUnchanged();
+                        }
+                        dom.runScriptTags(visualdiff);
+                        break;
+                    case 'annotated':
+                        annotateddiff.innerHTML = jsondiffpatch.formatters.annotated.format(delta);
+                        break;
+                    case 'json':
+                        areas.delta.setValue(JSON.stringify(delta, null, 2));
+                        jsondifflength.innerHTML = (Math.round(JSON.stringify(delta).length / 102.4) / 10.0)+'';
+                        break;
+                }
+            }
+        } catch(err) {
+            jsondifflength.innerHTML = '0';
+            visualdiff.innerHTML = '';
+            annotateddiff.innerHTML = '';
+            areas.delta.setValue('');
+            areas.delta.error(err);
+            if (typeof console !== 'undefined' && console.error) {
+                console.error(err);
+                console.error(err.stack);
+            }
+        }
+        document.getElementById('results').style.display = '';
+    };
+
+    areas.left.makeEditor();
+    areas.right.makeEditor();
+
+    dom.on(areas.left.element, 'change', compare);
+    dom.on(areas.right.element, 'change', compare);
+    dom.on(areas.left.element, 'keyup', compare);
+    dom.on(areas.right.element, 'keyup', compare);
+
+    var getSelectedDeltaType = function() {
+        if (document.getElementById('show-delta-type-visual').checked) {
+            return 'visual';
+        }
+        if (document.getElementById('show-delta-type-annotated').checked) {
+            return 'annotated';
+        }
+        if (document.getElementById('show-delta-type-json').checked) {
+            return 'json';
+        }
+    };
+
+    var showSelectedDeltaType = function() {
+        var type = getSelectedDeltaType();
+        document.getElementById('delta-panel-visual').style.display =
+            type === 'visual' ? '' : 'none';
+        document.getElementById('delta-panel-annotated').style.display =
+            type === 'annotated' ? '' : 'none';
+        document.getElementById('delta-panel-json').style.display =
+            type === 'json' ? '' : 'none';
+        compare();
+    };
+
+    dom.on(document.getElementById('show-delta-type-visual'), 'click', showSelectedDeltaType);
+    dom.on(document.getElementById('show-delta-type-annotated'), 'click', showSelectedDeltaType);
+    dom.on(document.getElementById('show-delta-type-json'), 'click', showSelectedDeltaType);
+
+    dom.on(document.getElementById('swap'), 'click', function(){
+        var leftValue = areas.left.getValue();
+        areas.left.setValue(areas.right.getValue());
+        areas.right.setValue(leftValue);
+        compare();
+    });
+
+    dom.on(document.getElementById('clear'), 'click', function(){
+        areas.left.setValue('');
+        areas.right.setValue('');
+        compare();
+    });
+
+    dom.on(document.getElementById('showunchanged'), 'change', function(){
+        jsondiffpatch.formatters.html.showUnchanged(document.getElementById('showunchanged').checked, null, 800);
+    });
+
+    dom.ready(setTimeout(compare));
+
+    var load = {};
+
+    load.data = function(data) {
+        data = data || {};
+        dom.text(document.getElementById('description'), data.description || '');
+        if (data.url && trim(data.url).substr(0, 10) !== 'javascript') {
+            document.getElementById('external-link').setAttribute('href', data.url);
+            document.getElementById('external-link').style.display = '';
+        } else {
+            document.getElementById('external-link').style.display = 'none';
+        }
+        var leftValue = data.left ? (data.left.content || data.left) : '';
+        areas.left.setValue(leftValue);
+        var rightValue = data.right ? (data.right.content || data.right) : '';
+        areas.right.setValue(rightValue);
+
+        dom.text(document.getElementById('json-panel-left').querySelector('h2'),
+            (data.left && data.left.name) || 'left.json');
+        dom.text(document.getElementById('json-panel-right').querySelector('h2'),
+            (data.right && data.right.name) || 'right.json');
+
+        document.getElementById('json-panel-left').querySelector('h2').setAttribute(
+            'title', (data.left && data.left.fullname) || '');
+        document.getElementById('json-panel-right').querySelector('h2').setAttribute(
+            'title', (data.right && data.right.fullname) || '');
+
+        if (data.error) {
+            areas.left.setValue('ERROR LOADING: ' + data.error);
+            areas.right.setValue('');
+        }
+    };
+
+    load.gist = function(id) {
+        id = /\d+/.exec(id+'')[0];
+        dom.getJson('https://api.github.com/gists/'+id, function(error, data) {
+            if (error) {
+                var message = error + ((data && data.message) ? data.message : '');
+                load.data({ error: message });
+                return;
+            }
+            var filenames = [];
+            for (var filename in data.files) {
+                var file = data.files[filename];
+                if (file.language === 'JSON') {
+                    filenames.push(filename);
+                }
+            }
+            filenames.sort();
+            var files = [
+                data.files[filenames[0]],
+                data.files[filenames[1]]
+            ];
+             /*jshint camelcase: false */
+            load.data({
+                url: data.html_url,
+                description: data.description,
+                left: {
+                    name: files[0].filename,
+                    content: files[0].content
+                },
+                right: {
+                    name: files[1].filename,
+                    content: files[1].content
+                }
+            });
+        });
+    };
+
+    load.leftright = function(description, leftValue, rightValue) {
+        try {
+            description = decodeURIComponent(description || '');
+            leftValue = decodeURIComponent(leftValue);
+            rightValue = decodeURIComponent(rightValue);
+            var urlmatch = /https?:\/\/.*\/([^\/]+\.json)(?:[\?#].*)?/;
+            var dataLoaded = {
+                description: description,
+                left: {},
+                right: {}
+            };
+            var loadIfReady = function(){
+                if (typeof dataLoaded.left.content !== 'undefined' &&
+                    typeof dataLoaded.right.content !== 'undefined') {
+                    load.data(dataLoaded);
+                }
+            };
+            if (urlmatch.test(leftValue)) {
+                dataLoaded.left.name = urlmatch.exec(leftValue)[1];
+                dataLoaded.left.fullname = leftValue;
+                dom.getJson(leftValue, function(error, data){
+                    if (error) {
+                        dataLoaded.left.content = error + ((data && data.message) ? data.message : '');
+                    } else {
+                        dataLoaded.left.content = JSON.stringify(data, null, 2);
+                    }
+                    loadIfReady();
+                });
+            } else {
+                dataLoaded.left.content = leftValue;
+            }
+            if (urlmatch.test(rightValue)) {
+                dataLoaded.right.name = urlmatch.exec(rightValue)[1];
+                dataLoaded.right.fullname = rightValue;
+                dom.getJson(rightValue, function(error, data){
+                    if (error) {
+                        dataLoaded.right.content = error + ((data && data.message) ? data.message : '');
+                    } else {
+                        dataLoaded.right.content = JSON.stringify(data, null, 2);
+                    }
+                    loadIfReady();
+                });
+            } else {
+                dataLoaded.right.content = rightValue;
+            }
+            loadIfReady();
+        } catch (err) {
+            load({ error: err });
+        }
+    };
+
+    load.key = function(key) {
+        var matchers = {
+            gist: /^(?:https?:\/\/)?(?:gist\.github\.com\/)?(?:[\w0-9\-]+\/)?(\d+)$/i,
+            leftright: /^(?:desc=(.*)?&)?left=(.*)&right=(.*)&?$/i,
+        };
+        for (var loader in matchers) {
+            var match = matchers[loader].exec(key);
+            if (match) {
+                return load[loader].apply(load, match.slice(1));
+            }
+        }
+        load.data({ error: 'unsupported source: ' + key });
+    };
+
+    var urlQuery = /^[^?]*\?([^\#]+)/.exec(document.location.href);
+    if (urlQuery) {
+        load.key(urlQuery[1]);
+    } else {
+        var exampleJson = getExampleJson();
+        load.data({
+            left: exampleJson[0],
+            right: exampleJson[1]
+        });
+    }
+
+    dom.on(document.getElementById('examples'), 'change', function(){
+        var example = trim(this.value);
+        switch(example) {
+            case 'text':
+                var exampleJson = getExampleJson();
+                load.data({
+                    left: {
+                        name: 'left.txt',
+                        content: JSON.parse(exampleJson[0]).summary
+                    },
+                    right: {
+                        name: 'right.txt',
+                        content: JSON.parse(exampleJson[1]).summary
+                    }
+                });
+                break;
+            case 'gist':
+                document.location = '?benjamine/9188826';
+                break;
+            case 'moving':
+                document.location = '?desc=moving%20around&left=' +
+                    encodeURIComponent(JSON.stringify([0,1,2,3,4,5,6,7,8,9,10])) +
+                    '&right=' +
+                    encodeURIComponent(JSON.stringify([10,0,1,7,2,4,5,6,88,9,3]));
+                break;
+            case 'query':
+                document.location = '?desc=encoded%20in%20url&left=' +
+                    /* jshint quotmark: false */
+                    encodeURIComponent(JSON.stringify({"don't":"abuse","with": ["large","urls"]})) +
+                    '&right=' +
+                    encodeURIComponent(JSON.stringify({"don't":"use","with": [">", 2,"KB urls"]}));
+                break;
+            case 'urls':
+                document.location = '?desc=http%20raw%20file%20urls&left=' +
+                    encodeURIComponent('https://rawgithub.com/benjamine/JsonDiffPatch/' +
+                        'c83e942971c627f61ef874df3cfdd50a95f1c5a2/package.json') +
+                    '&right=' +
+                    encodeURIComponent('https://rawgithub.com/benjamine/JsonDiffPatch/master/package.json');
+                break;
+            default:
+                document.location = '?';
+                break;
+        }
+    });
+})();
\ No newline at end of file
diff --git a/demo/index.html b/demo/index.html
new file mode 100644
index 0000000..bf4c418
--- /dev/null
+++ b/demo/index.html
@@ -0,0 +1,109 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>JsonDiffPatch</title>
+        <meta http-equiv="X-UA-Compatible" content="IE=edge">
+        <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
+        <link rel="stylesheet" href="../src/formatters/html.css" type="text/css" media="screen" />
+        <link rel="stylesheet" href="../src/formatters/annotated.css" type="text/css" media="screen" />
+        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/codemirror.min.css" type="text/css" media="screen" />
+        <script type='text/javascript' src='../build/bundle.js'>
+        </script>
+        <script type='text/javascript' src='../build/formatters.js'>
+        </script>
+        <script type='text/javascript' src='../external/diff_match_patch_uncompressed.js'>
+        </script>
+        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/codemirror.js"></script>
+        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/javascript/javascript.min.js"></script>
+    </head>
+    <body>
+        <a href='https://github.com/benjamine/jsondiffpatch' id='fork_me'>
+            <img alt='Fork me on GitHub' src='http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png'>
+        </a>
+        <header>
+            <h1>Js<span class="jsondiffpatch-textdiff-deleted"><span>on</span></span><span class="jsondiffpatch-textdiff-added"><span>Diff</span></span>Patch</h1>
+            <span id="description"></span>
+            <a id="external-link" style="display: none;">source</a>
+        </header>
+        <div class="buttons">
+            <div>
+                <input id="swap" type="button" value="Swap">
+                <input id="clear" type="button" value="Clear">
+                <select id="examples">
+                    <option value="" disabled selected>examples</option>
+                    <option value="default">default</option>
+                    <option value="text">text</option>
+                    <option value="moving">moving around</option>
+                    <option value="gist">from a gist</option>
+                    <option value="query">query params</option>
+                    <option value="urls">raw urls</option>
+                </select>
+            </div>
+        </div>
+        <div class="json-input">
+            <div id="json-panel-left">
+                <label for="json-input-left">
+                    <h2>JSON Left</h2>
+                </label>
+                <button class="prettyfy" type="button" title="Pretty print">{ }</button>
+                <textarea id="json-input-left">
+                    loading...
+                </textarea>
+                <span class="error-message"></span>
+            </div>
+            <div id="json-panel-right">
+                <label for="json-input-right">
+                    <h2>JSON Right</h2>
+                </label>
+                <button class="prettyfy" type="button" title="Pretty print">{ }</button>
+                <textarea id="json-input-right">
+                    loading...
+                </textarea>
+                <span class="error-message"></span>
+            </div>
+        </div>
+        <div id="results">
+            <h2>Delta</h2>
+            <label>
+                <input id="show-delta-type-visual" type="radio" name="delta-type" checked>
+                Visual
+            </label>
+            <label>
+                <input id="show-delta-type-json" type="radio" name="delta-type">
+                JSON
+            </label>
+            <label>
+                <input id="show-delta-type-annotated" type="radio" name="delta-type">
+                JSON (Annotated)
+            </label>
+            <div id="delta-panel-visual">
+                <div class="header-options">
+                    <input id="showunchanged" type="checkbox">
+                    <label for="showunchanged">
+                        Show unchanged values
+                    </label>
+                </div>
+                <p id="visualdiff">
+                </p>
+            </div>
+            <div id="delta-panel-annotated" style="display: none;">
+                <p id="annotateddiff">
+                </p>
+            </div>
+            <div id="delta-panel-json" style="display: none;">
+                <p>
+                    (<span id="jsondifflength"></span>
+                    KB)
+                </p>
+                <textarea id="json-delta" readonly>
+                </textarea>
+                <span class="error-message"></span>
+            </div>
+        </div>
+        <footer>
+            <a href="https://github.com/benjamine/jsondiffpatch">Get JsonDiffPatch</a><br>
+            <p class="credits">JsonDiffPatch was developed by <a href="http://twitter.com/beneidel">Benjam�n Eidelman</a></p>
+        </footer>
+        <script type="text/javascript" src="demo.js"></script>
+    </body>
+</html>
diff --git a/demo/left.json b/demo/left.json
new file mode 100644
index 0000000..19c2284
--- /dev/null
+++ b/demo/left.json
@@ -0,0 +1,9 @@
+{
+	"name": "Pluto",
+	"orbital_speed_kms": 4.7,
+	"category": "planet",
+	"composition": [
+		"methane",
+		"nitrogen"
+	]
+}
\ No newline at end of file
diff --git a/demo/numeric-plugin.js b/demo/numeric-plugin.js
new file mode 100644
index 0000000..eeb66c3
--- /dev/null
+++ b/demo/numeric-plugin.js
@@ -0,0 +1,76 @@
+
+/*
+Plugin a new diff filter
+*/
+(function(){
+  var assertSame = function(){};
+
+  var diffpatcher = jsondiffpatch.create();
+  var NUMERIC_DIFFERENCE = -8;
+
+  var numericDiffFilter = function(context) {
+    if (typeof context.left === 'number' && typeof context.right === 'number') {
+      context.setResult([0, context.right - context.left, NUMERIC_DIFFERENCE]).exit();
+    }
+  };
+  // a filterName is useful if I want to allow other filters to be inserted before/after this one
+  numericDiffFilter.filterName = 'numeric';
+
+  // to decide where to insert your filter you can look at the pipe's filter list
+  assertSame(diffpatcher.processor.pipes.diff.list(),
+    ["collectChildren", "trivial", "dates", "texts", "objects", "arrays"]);
+
+  // insert my new filter, right before trivial one
+  diffpatcher.processor.pipes.diff.before('trivial', numericDiffFilter);
+
+  // try it
+  var delta = diffpatcher.diff({ population: 400 }, { population: 403 });
+  assertSame(delta, [0, 3, NUMERIC_DIFFERENCE]);
+
+/*
+Let's make the corresponding patch filter that will handle the new delta type
+*/
+
+  var numericPatchFilter = function(context) {
+    if (context.delta && Array.isArray(context.delta) && context.delta[2] === NUMERIC_DIFFERENCE) {
+      context.setResult(context.left + context.delta[1]).exit();
+    }
+  };
+  numericPatchFilter.filterName = 'numeric';
+  diffpatcher.processor.pipes.patch.before('trivial', numericPatchFilter);
+
+  // try it
+  var right = diffpatcher.patch({ population: 400 }, delta);
+  assertSame(right, { population: 403 });
+
+  // patch twice!
+  diffpatcher.patch(right, delta);
+  assertSame(right, { population: 406 });
+
+/*
+To complete the plugin, let's add the reverse filter, so numeric deltas can be reversed
+(this is needed for unpatching too)
+*/
+
+  var numericReverseFilter = function(context) {
+    if (context.nested) { return; }
+    if (context.delta && Array.isArray(context.delta) && context.delta[2] === NUMERIC_DIFFERENCE) {
+      context.setResult([0, -context.delta[1], NUMERIC_DIFFERENCE]).exit();
+    }
+  };
+  numericReverseFilter.filterName = 'numeric';
+  diffpatcher.processor.pipes.reverse.after('trivial', numericReverseFilter);
+
+  // log pipe steps
+  diffpatcher.processor.pipes.reverse.debug = true;
+
+  // try it
+  var reverseDelta = diffpatcher.reverse(delta);
+  assertSame(reverseDelta, [0, -3, NUMERIC_DIFFERENCE]);
+
+  // unpatch twice!
+  diffpatcher.unpatch(right, delta);
+  diffpatcher.unpatch(right, delta);
+  assertSame(right, { population: 400 });
+
+})();
diff --git a/demo/right.json b/demo/right.json
new file mode 100644
index 0000000..58eafd6
--- /dev/null
+++ b/demo/right.json
@@ -0,0 +1,10 @@
+{
+	"name": "Pluto",
+	"orbital_speed_kms": 4.7,
+	"category": "dwarf planet",
+	"composition": [
+		"nitrogen",
+		"methane",
+		"carbon monoxide"
+	]
+}
\ No newline at end of file
diff --git a/demo/style.css b/demo/style.css
new file mode 100644
index 0000000..ba15857
--- /dev/null
+++ b/demo/style.css
@@ -0,0 +1,144 @@
+body {
+    font-family: Georgia, serif;
+    min-width: 600px;
+}
+
+h1 {
+    margin: 4px;
+}
+
+header > * {
+    display: inline-block;
+}
+
+#description {
+    margin-left: 10px;
+    font-size: x-large;
+}
+
+#external-link {
+    font-size: smaller;
+    vertical-align: top;
+    margin-top: 10px;
+}
+
+h2 {
+    display: inline-block;
+    margin: 5px 0;
+}
+
+
+a#fork_me {
+    position: absolute;
+    top: 0;
+    right: 0;
+}
+
+.json-input > div {
+    float: left;
+    width: 50%;
+}
+
+.json-input > div
+{
+    text-align: center;
+}
+
+.CodeMirror
+{
+    text-align: initial;
+    border: 1px solid #ccc;
+}
+
+.json-input > div > textarea {
+    width: 95%;
+    height: 200px;
+}
+
+.prettyfy {
+    font-weight: bold;
+    font-size: smaller;
+    margin-left: 5px;
+}
+
+.buttons {
+    width: 100%;
+    text-align:center;
+    height: 1px;
+}
+
+.buttons > div
+{
+    margin: 0 auto;
+}
+
+.json-error {
+    background: #ffdfdf;
+    -webkit-transition: all 1s;
+    transition: all 1s;
+}
+
+.error-message {
+    font-weight: bold;
+    color: red;
+    font-size: smaller;
+    min-height: 20px;
+    display: block;
+}
+
+.header-options {
+    font-weight: normal;
+    margin-left: 30px;
+    display: inline-block;
+}
+
+#delta-panel-visual {
+    width: 100%;
+    overflow: auto;
+}
+
+#visualdiff {
+    margin-top: 4px;
+}
+
+#json-delta {
+    font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
+    font-size: 12px;
+    margin: 0;
+    padding: 0;
+    width: 100%;
+    height: 200px;
+}
+
+#delta-panel-json > p {
+    margin: 4px;
+}
+
+footer {
+    font-size: small;
+    text-align: center;
+    margin: 40px;
+}
+
+.credits {
+    font-size: smaller;
+}
+
+.credits a {
+    text-decoration: none;
+    color: black;
+}
+
+.credits a:hover {
+    text-decoration: underline;
+}
+
+.results {
+    margin-top: 20px;
+}
+
+.results > div {
+    vertical-align: top;
+    display: inline-block;
+}
+
diff --git a/docs/arrays.md b/docs/arrays.md
new file mode 100644
index 0000000..3616fc1
--- /dev/null
+++ b/docs/arrays.md
@@ -0,0 +1,88 @@
+Array Diffing
+===========
+
+Array diffing is implemented using [LCS](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem), which is the classic algorythm used by text diff tools (here using array items instead of text lines).
+
+This means array deltas are pretty smart about items added and removed to a sequence (array).
+But there's a big gotcha here, ***by default, objects inside arrays will always be considered different, even if they "look" equal to you***, to fix that you need...
+
+An Object Hash
+------------
+
+for LCS to work, it needs a way to match items between previous/original (or left/right) arrays.
+In traditional text diff tools this is trivial, as two lines of text are compared char by char.
+
+By default the ```===``` operator is used, which is good enough to match all JavaScript value types (number, string, bool), and object references (in case you kept references between left/right states).
+But when objects are found on both sides, if they are not equal by reference (ie. the same object) both objects are  considered different values, as there is no trivial solution to compare two arbritrary objects in JavaScript.
+
+At first, you might be surprised by this...
+
+### Counter-intuitive result
+``` javascript
+var delta = jsondiffpatch.diff({ name: 'tito' }, { name: 'tito' });
+
+assertSame(delta, {
+  _0: [{ name: 'tito' }, 0, 0],
+  0: [{ name: 'tito' }]
+});
+// reads as: remove { name: 'tito' } at 0,
+//           insert { name: 'tito' } at 0
+```
+
+That's because two objects aren't ```===``` equal, unless they are really the same object (by reference).
+
+But you can make this work as you need by providing a function to hash objects in an array (so hashes are compared instead), here is...
+
+### An example of solution
+``` javascript
+var delta = jsondiffpatch.create({
+    objectHash: function(obj) {
+      // try to find an id property, otherwise serialize it all
+      return obj.name || obj.id || obj._id || obj._id || JSON.stringify(obj);
+    }
+  }).diff({ name: 'tito' }, { name: 'tito' });
+
+assert(delta === undefined); // no diff
+```
+
+Moves
+-----
+
+As a posterior refinement to LCS, items that were moved from position inside the same array are detected, are registered as such.
+
+This introduces a few benefits:
+- deltas are potentially much smaller, by not including the whole value of the item 2 times (add and remove)
+- patching will only move the item in the target array, instead of deleting and inserting a new instance. this is more efficient and might prevent breaking existing references in the object graph.
+- if the moved item is an object or array, diff continues inside (nested diff)
+
+moves are detected by default, you can turn move detection off with:
+``` javascript
+  var customDiffPatch = jsondiffpatch.create({
+    arrays: {
+      detectMove: false
+    }
+  };
+```
+
+### Representation
+
+#### JSON deltas
+
+``` js
+{
+  "_originalIndex": // this is the item original position in the array
+  [
+    '', // the moved item value, supressed by default
+    destinationIndex, // this is the item final position in the array
+    3 // magic number to indicate: array move
+  ]
+}
+```
+
+> Note: in some cases, ```originalIndex``` and ```destinationIndex``` could be the same number, this might look weird, but remember the first refers to the original state (that's what the underscore means), and the later to the final state. When patching items are first all removed, and finally all inserted, so the composition of the array might be have changed in the middle.
+
+For more details check [delta format documentation](deltas.md)
+
+#### Html
+
+On html you will see moves as fancy curved arrows (check [Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html) ), these are implemented using SVG elements and an embedded script tag, they will only show up [if your browser supports SVG](http://caniuse.com/svg)
diff --git a/docs/deltas.md b/docs/deltas.md
new file mode 100644
index 0000000..5612665
--- /dev/null
+++ b/docs/deltas.md
@@ -0,0 +1,120 @@
+Delta Format
+============
+
+This page intends to be a reference for JSON format used to represent deltas (ie. the output of ```jsondiffpatch.diff```).
+
+This format was created with a balance between readability and low footprint in mind.
+
+- when diffing 2 objects, the delta will reflect the same object structure (common part on both sides)
+- to represent changed parts, arrays and magic numbers are used to keep a low footprint (ie. you won't see verbosity like ```"type": "added"```)
+- keep it pure JSON serializable
+
+A great way to understand this format is using the "Annotated JSON" option in the [Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html), and try the different left/right examples, or edit left/right JSON to see the annotated delta update as your type.
+
+Here's a complete reference of this format.
+
+Added
+-----
+a value is added, ie. it was ```undefined``` and now has a value.
+``` javascript
+delta = [ newValue ]
+```
+
+Modified
+-----
+a value was replaced by another value
+``` javascript
+delta = [ oldValue, newValue ]
+```
+
+Deleted
+-----
+value deleted, ie. it had a value and is now ```undefined```
+``` javascript
+delta = [ oldValue, 0, 0 ]
+```
+
+Object with inner changes
+-----
+value is an object, and there are nested changes inside its properties
+
+``` javascript
+delta = {
+  property1: innerDelta1,
+  property2: innerDelta2,
+  property5: innerDelta5
+}
+```
+
+> Note: only properties with inner deltas are included
+
+Here's an example combining what we have:
+
+```
+delta = {
+  property1: [ newValue1 ], // obj[property1] = newValue1
+  property2: [ oldValue2, newValue2 ] // obj[property2] = newValue2 (and previous value was oldValue2)
+  property5: [ oldValue5, 0, 0 ] // delete obj[property5] (and previous value was oldValue5)
+}
+```
+
+Array with inner changes
+-----
+value is an array, and there are nested changes inside its items
+
+``` javascript
+delta = {
+  _t: 'a',
+  index1: innerDelta1,
+  index2: innerDelta2,
+  index5: innerDelta5
+}
+```
+
+> Note: only indices with inner deltas are included
+
+> Note: _t: 'a', indicates this applies to an array, when patching if a regular object (or a value type) is found, an error will be thrown
+
+### Index Notation
+
+Indices on array deltas can be expressed in two ways:
+- number: refers to the index in the final (right) state of the array, this is used to indicate items inserted.
+- underscore + number: refers to the index in the original (left) state of the array, this is used to indicate items removed, or moved.
+
+### Array Moves
+an item was moved to a different position in the same array
+``` javascript
+delta = [ '', destinationIndex, 3]
+```
+> Note: '', represents the moved item value, suppresed by default
+
+> Note: 3, is the magical number that indicates "array move"
+
+Text Diffs
+----------
+
+If two strigns are compared and they are different, you will see as you expect:
+``` javascript
+delta = [ "some text", "some text modified" ]
+```
+But if both strings are long enough, [a text diffing algorythm](https://code.google.com/p/google-diff-match-patch/) will be used to efficiently detect changes in parts of the text.
+
+You can modify the minimum length with:
+``` javascript
+var customDiffPatch = jsondiffpatch.create({
+  textDiff: {
+    minLength: 60 // default value
+  }
+});
+```
+
+And the delta will look like this:
+
+``` javascript
+delta = [ unidiff, 0, 2 ]
+
+```
+> Note: 2, is the magical number that indicates "text diff"
+
+> Note: unidiff is actually a character-based variation of Unidiff format that is explained [here](https://code.google.com/p/google-diff-match-patch/wiki/Unidiff)
+
diff --git a/docs/formatters.md b/docs/formatters.md
new file mode 100644
index 0000000..1e8fa3d
--- /dev/null
+++ b/docs/formatters.md
@@ -0,0 +1,63 @@
+Formatters
+==========
+
+Some formatters are included that let you convert a JSON delta into other formats, you can see some of these used in the [Live Demo](http://benjamine.github.com/jsondiffpatch/demo/index.html)
+
+Html
+----
+
+add ```build/formatters.js``` and ```src/formatters/html.css``` to your page, and:
+
+``` javascript
+  var delta = jsondiffpatch.diff(left, right);
+  // left is optional, if specified unchanged values will be visible too
+  document.getElementBy('the-diff').innerHTML = jsondiffpatch.formatters.html.format(delta, left);
+
+
+  // Also you can dinamically show/hide unchanged values
+  jsondiffpatch.formatters.html.showUnchanged();
+  jsondiffpatch.formatters.html.hideUnchanged();
+  // these will also adjust array move arrows (SVG), which is useful if something alters the html layout
+```
+
+Html can be generated sever-side the same way, just remember to include (or embed) ```/src/formatters/html.css``` when rendering.
+
+Annotated JSON
+----
+
+This will render the original JSON delta in html, with annotations aside explaining the meaning of each part. This attempts to make the JSON delta format self-explained.
+
+add ```build/formatters.js``` and ```src/formatters/annotated.css``` to your page, and:
+
+``` javascript
+  var delta = jsondiffpatch.diff(left, right);
+  document.getElementBy('the-diff').innerHTML = jsondiffpatch.formatters.annotated.format(delta);
+```
+
+Html can be generated sever-side the same way, just remember to include (or embed) ```/src/formatters/annotated.css``` when rendering.
+
+Console
+-------
+
+Node.js colored output (thanks to [chalk](https://github.com/sindresorhus/chalk)!).
+It's used by the CLI:
+
+![console_demo!](../demo/consoledemo.png)
+
+but you can use it programmatically too:
+
+``` javascript
+var delta = jsondiffpatch.diff(left, right);
+var output = jsondiffpatch.formatters.console.format(delta);
+console.log(delta);
+
+// or simply
+jsondiffpatch.console.log(delta);
+```
+
+Create one
+----------
+
+Of course, first step to create a formatters is understanding the [delta format](deltas.md).
+
+To simplify the creation of new formatters, you can base yours in the ```BaseFormatter``` included. All the builtin formatters do, check the [formatters](../src/formatters) folder to get started.
diff --git a/docs/plugins.md b/docs/plugins.md
new file mode 100644
index 0000000..4df722c
--- /dev/null
+++ b/docs/plugins.md
@@ -0,0 +1,96 @@
+Plugins
+=======
+
+```diff()```, ```patch()``` and ```reverse()``` functions are implemented using a pipes &filters pattern, making them extremely customizable by adding or replacing filters.
+
+Some examples of what you can acheive writing your own filter:
+- diff special custom objects (eg. DOM nodes, native objects, functions, RegExp, node.js streams?)
+- ignore parts of the graph using any custom rule (type, path, flags)
+- change diff strategy in specific parts of the graph, eg. rely on change tracking info for Knockout.js tracked objects
+- implement custom diff mechanisms, like relative numeric deltas
+- suprise me! :)
+
+Check the ```/src/filters``` folder for filter examples.
+
+Plugin Example
+------
+
+Here is an example to provide number differences in deltas (when left and right values are both numbers)
+This, way when diffing 2 numbers instead of obtaining ```[ oldValue, newValue ] ```, the difference between both values will be saved, this could be useful for counters simultaneously incremented in multiple client applications (patches that both increment a value would be combined, instead of failing with a conflict).
+
+``` javascript
+
+/*
+Plugin a new diff filter
+*/
+
+  var diffpatcher = jsondiffpatch.create();
+  var NUMERIC_DIFFERENCE = -8;
+
+  var numericDiffFilter = function(context) {
+    if (typeof context.left === 'number' && typeof context.right === 'number') {
+      context.setResult([0, context.right - context.left, NUMERIC_DIFFERENCE]).exit();
+    }
+  };
+  // a filterName is useful if I want to allow other filters to be inserted before/after this one
+  numericDiffFilter.filterName = 'numeric';
+
+  // to decide where to insert your filter you can look at the pipe's filter list
+  assertSame(diffpatcher.processor.pipes.diff.list(),
+    ["collectChildren", "trivial", "dates", "texts", "objects", "arrays"]);
+
+  // insert my new filter, right before trivial one
+  diffpatcher.processor.pipes.diff.before('trivial', numericDiffFilter);
+
+  // for debugging, log each filter
+  diffpatcher.processor.pipes.diff.debug = true;
+
+  // try it
+  var delta = diffpatcher.diff({ population: 400 }, { population: 403 });
+  assertSame(delta, [0, 3, NUMERIC_DIFFERENCE]);
+
+/*
+Let's make the corresponding patch filter that will handle the new delta type
+*/
+
+  var numericPatchFilter = function(context) {
+    if (context.delta && Array.isArray(context.delta) && context.delta[2] === NUMERIC_DIFFERENCE) {
+      context.setResult(context.left + context.delta[1]).exit();
+    }
+  };
+  numericPatchFilter.filterName = 'numeric';
+  diffpatcher.processor.pipes.patch.before('trivial', numericPatchFilter);
+
+  // try it
+  var right = diffpatcher.patch({ population: 400 }, delta);
+  assertSame(right, { population: 403 });
+
+  // patch twice!
+  diffpatcher.patch(right, delta);
+  assertSame(right, { population: 406 });
+
+/*
+To complete the plugin, let's add the reverse filter, so numeric deltas can be reversed
+(this is needed for unpatching too)
+*/
+
+  var numericReverseFilter = function(context) {
+    if (context.nested) { return; }
+    if (context.delta && Array.isArray(context.delta) && context.delta[2] === NUMERIC_DIFFERENCE) {
+      context.setResult([0, -context.delta[1], NUMERIC_DIFFERENCE]).exit();
+    }
+  };
+  numericReverseFilter.filterName = 'numeric';
+  diffpatcher.processor.pipes.reverse.after('trivial', numericReverseFilter);
+
+  // try it
+  var reverseDelta = diffpatcher.reverse(delta);
+  assertSame(reverseDelta, [0, -3, NUMERIC_DIFFERENCE]);
+
+  // unpatch twice!
+  diffpatcher.unpatch(right, delta);
+  assertSame(right, { population: 403 });
+  diffpatcher.unpatch(right, delta);
+  assertSame(right, { population: 400 });
+```
+
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000..9de784e
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,130 @@
+var fs = require('fs');
+var gulp = require('gulp');
+var gutil = require('gulp-util');
+var plugins = require('gulp-load-plugins')();
+
+var packageInfo = JSON.parse(fs.readFileSync('./package.json'));
+var browsers = process.env.BROWSERS || process.env.BROWSER || 'PhantomJS';
+browsers = browsers ? browsers.split(' ') : undefined;
+
+gulp.task('default', ['build', 'test']);
+
+gulp.task('clean', function() {
+    return gulp.src(['./build', './test-external'], {read: false})
+        .pipe(plugins.clean());
+});
+
+var watching = false;
+var plumber = function() {
+    return watching ? plugins.plumber() : gutil.noop();
+};
+
+gulp.task('lint', function() {
+    var jshintOptions = fs.readFileSync('./.jshintrc').toString().replace(/\/\/.*/g, '');
+    jshintOptions = JSON.parse(jshintOptions);
+    return gulp.src([
+            'gulpfile.js',
+            './src/**/*.js',
+            './test/**/*.js',
+            '!./src/jsondiffpatch*.js',
+            '!**/*_old.js'
+        ])
+        .pipe(plumber())
+        .pipe(plugins.jshint(jshintOptions))
+        .pipe(plugins.jshint.reporter('jshint-stylish'))
+        .pipe(plugins.jshint.reporter('fail'))
+        .pipe(plumber());
+});
+
+var buildDependencies = ['lint'];
+var bundle = function(options) {
+    var name = options.name || 'bundle';
+    var src = options.src || './src/main.js';
+    var minify = options.minify !== false;
+    gulp.task(name, ['clean'], function() {
+        if (fs.existsSync('./build/'+name+'.js') && (!minify || fs.existsSync('./build/'+name+'.min.js'))) {
+            console.log(name + ' already exists');
+            return;
+        }
+
+        var stream = gulp.src(src)
+            .pipe(plugins.replace('{{package-version}}', packageInfo.version))
+            .pipe(plugins.replace('{{package-homepage}}', packageInfo.homepage))
+            .pipe(plugins.browserify(options.browserifyOptions || {}))
+            .pipe(plugins.rename(name+'.js'))
+            .pipe(gulp.dest('./build'));
+        if (!minify) { return stream; }
+        return stream.pipe(plugins.uglify())
+            .pipe(plugins.rename(name+'.min.js'))
+            .pipe(gulp.dest('./build'));
+    });
+    buildDependencies.push(name);
+};
+
+bundle({
+    browserifyOptions: {
+        standalone: packageInfo.name,
+        exclude: '../../external/diff_match_patch_uncompressed'
+    }
+});
+bundle({
+    name: 'bundle-full',
+    browserifyOptions: {
+        standalone: packageInfo.name
+    }
+});
+
+bundle({
+    name: 'formatters',
+    src: './src/formatters/index.js',
+    browserifyOptions: {
+        standalone: packageInfo.name + '.formatters'
+    }
+});
+
+bundle({
+    name: 'test-bundle',
+    src: './test/test.js',
+    minify: false
+});
+
+gulp.task('copy-test-res', ['clean'], function() {
+    gulp.src('./node_modules/expect.js/index.js')
+      .pipe(plugins.rename('expect.js'))
+      .pipe(gulp.dest('./test-external'));
+    gulp.src('./node_modules/mocha/mocha.js')
+      .pipe(gulp.dest('./test-external'));
+    gulp.src('./node_modules/mocha/mocha.css')
+      .pipe(gulp.dest('./test-external'));
+});
+
+buildDependencies.push('copy-test-res');
+
+gulp.task('build', buildDependencies, function() {
+});
+
+gulp.task('test', ['lint'], function () {
+    return gulp.src('./test/**.js')
+        .pipe(plumber())
+        .pipe(plugins.mocha({
+            grep: process.env.FILTER || undefined,
+            reporter: 'spec',
+            growl: true
+        }))
+        .pipe(plumber());
+});
+
+gulp.task('test-browser', ['build'], function() {
+    return gulp.src('./file-list-at-karma-conf-file')
+        .pipe(plugins.karma({
+            configFile: 'karma.conf.js',
+            browsers: browsers,
+            action: 'run'
+        }));
+});
+
+gulp.task('watch', ['test'], function() {
+    watching = true;
+    return gulp.watch(['external/**', 'src/**', 'test/**'], ['test'])
+    .on('error', gutil.log);
+});
\ No newline at end of file
diff --git a/karma.conf.js b/karma.conf.js
new file mode 100644
index 0000000..8a0c205
--- /dev/null
+++ b/karma.conf.js
@@ -0,0 +1,13 @@
+module.exports = function(config) {
+    config.set({
+        basePath: '.',
+        frameworks: ['mocha'],
+        files: [
+            'build/bundle.js',
+            'external/diff_match_patch_uncompressed.js',
+            'test-external/expect.js',
+            'build/test-bundle.js'
+        ],
+        reporters : ['spec', 'growler']
+    });
+};
\ No newline at end of file
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..8abf960
--- /dev/null
+++ b/package.json
@@ -0,0 +1,81 @@
+{
+  "name": "jsondiffpatch",
+  "version": "0.1.8",
+  "author": "Benjamin Eidelman <beneidel at gmail.com>",
+  "description": "Diff & Patch for Javascript objects",
+  "contributors": [
+    "Benjamin Eidelman <beneidel at gmail.com>"
+  ],
+  "bin": {
+    "jsondiffpatch": "./bin/jsondiffpatch"
+  },
+  "scripts": {
+    "test": "npm install && ./node_modules/.bin/gulp test test-browser"
+  },
+  "main": "./src/main",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/benjamine/jsondiffpatch.git"
+  },
+  "keywords": [
+    "json",
+    "diff",
+    "patch"
+  ],
+  "devDependencies": {
+    "expect.js": "~0.3.1",
+    "gulp": "~3.5.2",
+    "gulp-browserify": "~0.4.4",
+    "gulp-clean": "~0.2.4",
+    "gulp-jshint": "~1.5.0",
+    "gulp-karma": "0.0.4",
+    "gulp-load-plugins": "~0.3.0",
+    "gulp-mocha": "~0.4.1",
+    "gulp-plumber": "~0.5.6",
+    "gulp-rename": "~1.1.0",
+    "gulp-replace": "~0.2.0",
+    "gulp-uglify": "~0.2.1",
+    "gulp-util": "~2.2.14",
+    "jshint-stylish": "~0.1.5",
+    "karma": "~0.12.16",
+    "karma-chrome-launcher": "~0.1.2",
+    "karma-firefox-launcher": "~0.1.3",
+    "karma-growler-reporter": "~0.0.1",
+    "karma-html2js-preprocessor": "~0.1.0",
+    "karma-mocha": "~0.1.4",
+    "karma-phantomjs-launcher": "~0.1.2",
+    "karma-script-launcher": "~0.1.0",
+    "karma-spec-reporter": "~0.0.10",
+    "mocha": "~1.17.1"
+  },
+  "bundleDependencies": [],
+  "license": "MIT",
+  "engine": {
+    "node": ">=0.10"
+  },
+  "dependencies": {
+    "chalk": "~0.4.0"
+  },
+  "testling": {
+    "harness": "mocha",
+    "files": "test/*.js",
+    "scripts": [
+      "build/bundle.js",
+      "external/diff_match_patch_uncompressed.js"
+    ],
+    "browsers": [
+      "ie/8..latest",
+      "chrome/27..latest",
+      "firefox/22..latest",
+      "safari/5.1..latest",
+      "opera/12..latest",
+      "iphone/6..latest",
+      "ipad/6..latest",
+      "android-browser/4.2..latest"
+    ]
+  },
+  "engines": {
+    "node": "*"
+  },
+  "homepage": "https://github.com/benjamine/jsondiffpatch"
+}
diff --git a/src/contexts/context.js b/src/contexts/context.js
new file mode 100644
index 0000000..5ac44e5
--- /dev/null
+++ b/src/contexts/context.js
@@ -0,0 +1,49 @@
+
+var Pipe = require('../pipe').Pipe;
+
+var Context = function Context(){
+};
+
+Context.prototype.setResult = function(result) {
+	this.result = result;
+	this.hasResult = true;
+	return this;
+};
+
+Context.prototype.exit = function() {
+	this.exiting = true;
+	return this;
+};
+
+Context.prototype.switchTo = function(next, pipe) {
+	if (typeof next === 'string' || next instanceof Pipe) {
+		this.nextPipe = next;
+	} else {
+		this.next = next;
+		if (pipe) {
+			this.nextPipe = pipe;
+		}
+	}
+	return this;
+};
+
+Context.prototype.push = function(child, name) {
+	child.parent = this;
+	if (typeof name !== 'undefined') {
+		child.childName = name;
+	}
+	child.root = this.root || this;
+	child.options = child.options || this.options;
+	if (!this.children) {
+		this.children = [child];
+		this.nextAfterChildren = this.next || null;
+		this.next = child;
+	} else {
+		this.children[this.children.length - 1].next = child;
+		this.children.push(child);
+	}
+	child.next = this;
+	return this;
+};
+
+exports.Context = Context;
\ No newline at end of file
diff --git a/src/contexts/diff.js b/src/contexts/diff.js
new file mode 100644
index 0000000..1c0a554
--- /dev/null
+++ b/src/contexts/diff.js
@@ -0,0 +1,12 @@
+
+var Context = require('./context').Context;
+
+var DiffContext = function DiffContext(left, right){
+    this.left = left;
+    this.right = right;
+    this.pipe = 'diff';
+};
+
+DiffContext.prototype = new Context();
+
+exports.DiffContext = DiffContext;
\ No newline at end of file
diff --git a/src/contexts/patch.js b/src/contexts/patch.js
new file mode 100644
index 0000000..58d5c09
--- /dev/null
+++ b/src/contexts/patch.js
@@ -0,0 +1,12 @@
+
+var Context = require('./context').Context;
+
+var PatchContext = function PatchContext(left, delta){
+    this.left = left;
+    this.delta = delta;
+    this.pipe = 'patch';
+};
+
+PatchContext.prototype = new Context();
+
+exports.PatchContext = PatchContext;
\ No newline at end of file
diff --git a/src/contexts/reverse.js b/src/contexts/reverse.js
new file mode 100644
index 0000000..0f5846f
--- /dev/null
+++ b/src/contexts/reverse.js
@@ -0,0 +1,11 @@
+
+var Context = require('./context').Context;
+
+var ReverseContext = function ReverseContext(delta){
+    this.delta = delta;
+    this.pipe = 'reverse';
+};
+
+ReverseContext.prototype = new Context();
+
+exports.ReverseContext = ReverseContext;
\ No newline at end of file
diff --git a/src/date-reviver.js b/src/date-reviver.js
new file mode 100644
index 0000000..7282ac8
--- /dev/null
+++ b/src/date-reviver.js
@@ -0,0 +1,13 @@
+
+// use as 2nd parameter for JSON.parse to revive Date instances
+module.exports = function dateReviver(key, value) {
+    var parts;
+    if (typeof value === 'string') {
+        parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+\-])(\d{2}):(\d{2}))$/.exec(value);
+        if (parts) {
+            return new Date(Date.UTC(+parts[1], +parts[2] - 1, +parts[3],
+              +parts[4], +parts[5], +parts[6], +(parts[7] || 0)));
+        }
+    }
+    return value;
+};
diff --git a/src/diffpatcher.js b/src/diffpatcher.js
new file mode 100644
index 0000000..e463e8c
--- /dev/null
+++ b/src/diffpatcher.js
@@ -0,0 +1,62 @@
+
+var Processor = require('./processor').Processor;
+var Pipe = require('./pipe').Pipe;
+var DiffContext = require('./contexts/diff').DiffContext;
+var PatchContext = require('./contexts/patch').PatchContext;
+var ReverseContext = require('./contexts/reverse').ReverseContext;
+
+var trivial = require('./filters/trivial');
+var nested = require('./filters/nested');
+var arrays = require('./filters/arrays');
+var dates = require('./filters/dates');
+var texts = require('./filters/texts');
+
+var DiffPatcher = function DiffPatcher(options){
+    this.processor = new Processor(options);
+    this.processor.pipe(new Pipe('diff').append(
+        nested.collectChildrenDiffFilter,
+        trivial.diffFilter,
+        dates.diffFilter,
+        texts.diffFilter,
+        nested.objectsDiffFilter,
+        arrays.diffFilter
+        ).shouldHaveResult());
+    this.processor.pipe(new Pipe('patch').append(
+        nested.collectChildrenPatchFilter,
+        arrays.collectChildrenPatchFilter,
+        trivial.patchFilter,
+        texts.patchFilter,
+        nested.patchFilter,
+        arrays.patchFilter
+        ).shouldHaveResult());
+    this.processor.pipe(new Pipe('reverse').append(
+        nested.collectChildrenReverseFilter,
+        arrays.collectChildrenReverseFilter,
+        trivial.reverseFilter,
+        texts.reverseFilter,
+        nested.reverseFilter,
+        arrays.reverseFilter
+        ).shouldHaveResult());
+};
+
+DiffPatcher.prototype.options = function() {
+    return this.processor.options.apply(this.processor, arguments);
+};
+
+DiffPatcher.prototype.diff = function(left, right) {
+    return this.processor.process(new DiffContext(left, right));
+};
+
+DiffPatcher.prototype.patch = function(left, delta) {
+    return this.processor.process(new PatchContext(left, delta));
+};
+
+DiffPatcher.prototype.reverse = function(delta) {
+    return this.processor.process(new ReverseContext(delta));
+};
+
+DiffPatcher.prototype.unpatch = function(right, delta) {
+    return this.patch(right, this.reverse(delta));
+};
+
+exports.DiffPatcher = DiffPatcher;
diff --git a/src/filters/arrays.js b/src/filters/arrays.js
new file mode 100644
index 0000000..05613c8
--- /dev/null
+++ b/src/filters/arrays.js
@@ -0,0 +1,367 @@
+
+var DiffContext = require('../contexts/diff').DiffContext;
+var PatchContext = require('../contexts/patch').PatchContext;
+var ReverseContext = require('../contexts/reverse').ReverseContext;
+
+var lcs = require('./lcs');
+
+var ARRAY_MOVE = 3;
+
+var isArray = (typeof Array.isArray === 'function') ?
+    // use native function
+    Array.isArray :
+    // use instanceof operator
+    function(a) {
+        return a instanceof Array;
+    };
+
+var arrayIndexOf = typeof Array.prototype.indexOf === 'function' ?
+    function(array, item) {
+        return array.indexOf(item);
+    } : function(array, item) {
+        var length = array.length;
+        for (var i = 0; i < length; i++) {
+            if (array[i] === item) {
+                return i;
+            }
+        }
+        return -1;
+    };
+
+var diffFilter = function arraysDiffFilter(context){
+    if (!context.leftIsArray) { return; }
+
+    var objectHash = context.options && context.options.objectHash;
+
+    var match = function(array1, array2, index1, index2, context) {
+        var value1 = array1[index1];
+        var value2 = array2[index2];
+        if (value1 === value2) {
+            return true;
+        }
+        if (typeof value1 !== 'object' || typeof value2 !== 'object') {
+            return false;
+        }
+        if (!objectHash) { return false; }
+        var hash1, hash2;
+        if (typeof index1 === 'number') {
+            context.hashCache1 = context.hashCache1 || [];
+            hash1 = context.hashCache1[index1];
+            if (typeof hash1 === 'undefined') {
+                context.hashCache1[index1] = hash1 = objectHash(value1, index1);
+            }
+        } else {
+            hash1 = objectHash(value1);
+        }
+        if (typeof hash1 === 'undefined') {
+            return false;
+        }
+        if (typeof index2 === 'number') {
+            context.hashCache2 = context.hashCache2 || [];
+            hash2 = context.hashCache2[index2];
+            if (typeof hash2 === 'undefined') {
+                context.hashCache2[index2] = hash2 = objectHash(value2, index2);
+            }
+        } else {
+            hash2 = objectHash(value2);
+        }
+        if (typeof hash2 === 'undefined') {
+            return false;
+        }
+        return hash1 === hash2;
+    };
+
+    var matchContext = {};
+    var commonHead = 0, commonTail = 0, index, index1, index2;
+    var array1 = context.left;
+    var array2 = context.right;
+    var len1 = array1.length;
+    var len2 = array2.length;
+
+    var child;
+
+    // separate common head
+    while (commonHead < len1 && commonHead < len2 &&
+        match(array1, array2, commonHead, commonHead, matchContext)) {
+        index = commonHead;
+        child = new DiffContext(context.left[index], context.right[index]);
+        context.push(child, index);
+        commonHead++;
+    }
+    // separate common tail
+    while (commonTail + commonHead < len1 && commonTail + commonHead < len2 &&
+        match(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
+        index1 = len1 - 1 - commonTail;
+        index2 = len2 - 1 - commonTail;
+        child = new DiffContext(context.left[index1], context.right[index2]);
+        context.push(child, index2);
+        commonTail++;
+    }
+    var result;
+    if (commonHead + commonTail === len1) {
+        if (len1 === len2) {
+            // arrays are identical
+            context.setResult(undefined).exit();
+            return;
+        }
+        // trivial case, a block (1 or more consecutive items) was added
+        result = result || { _t: 'a' };
+        for (index = commonHead; index < len2 - commonTail; index++) {
+            result[index] = [array2[index]];
+        }
+        context.setResult(result).exit();
+        return;
+    }
+    if (commonHead + commonTail === len2) {
+        // trivial case, a block (1 or more consecutive items) was removed
+        result = result || { _t: 'a' };
+        for (index = commonHead; index < len1 - commonTail; index++) {
+            result['_'+index] = [array1[index], 0, 0];
+        }
+        context.setResult(result).exit();
+        return;
+    }
+    // reset hash cache
+    matchContext = {};
+    // diff is not trivial, find the LCS (Longest Common Subsequence)
+    var trimmed1 = array1.slice(commonHead, len1 - commonTail);
+    var trimmed2 = array2.slice(commonHead, len2 - commonTail);
+    var seq = lcs.get(
+        trimmed1, trimmed2,
+        match,
+        matchContext
+    );
+    var removedItems = [];
+    result = result || { _t: 'a' };
+    for (index = commonHead; index < len1 - commonTail; index++) {
+        if (arrayIndexOf(seq.indices1, index - commonHead) < 0) {
+            // removed
+            result['_'+index] = [array1[index], 0, 0];
+            removedItems.push(index);
+        }
+    }
+
+    var detectMove = true;
+    if (context.options && context.options.arrays && context.options.arrays.detectMove === false) {
+        detectMove = false;
+    }
+    var includeValueOnMove = false;
+    if (context.options && context.options.arrays && context.options.arrays.includeValueOnMove) {
+        includeValueOnMove = true;
+    }
+
+    var removedItemsLength = removedItems.length;
+    for (index = commonHead; index < len2 - commonTail; index++) {
+        var indexOnArray2 = arrayIndexOf(seq.indices2, index - commonHead);
+        if (indexOnArray2 < 0) {
+            // added, try to match with a removed item and register as position move
+            var isMove = false;
+            if (detectMove && removedItemsLength > 0) {
+                for (var removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
+                    index1 = removedItems[removeItemIndex1];
+                    if (match(trimmed1, trimmed2, index1 - commonHead,
+                        index - commonHead, matchContext)) {
+                        // store position move as: [originalValue, newPosition, ARRAY_MOVE]
+                        result['_' + index1].splice(1, 2, index, ARRAY_MOVE);
+                        if (!includeValueOnMove) {
+                            // don't include moved value on diff, to save bytes
+                            result['_' + index1][0] = '';
+                        }
+
+                        index2 = index;
+                        child = new DiffContext(context.left[index1], context.right[index2]);
+                        context.push(child, index2);
+                        removedItems.splice(removeItemIndex1, 1);
+                        isMove = true;
+                        break;
+                    }
+                }
+            }
+            if (!isMove) {
+                // added
+                result[index] = [array2[index]];
+            }
+        } else {
+            // match, do inner diff
+            index1 = seq.indices1[indexOnArray2] + commonHead;
+            index2 = seq.indices2[indexOnArray2] + commonHead;
+            child = new DiffContext(context.left[index1], context.right[index2]);
+            context.push(child, index2);
+        }
+    }
+
+    context.setResult(result).exit();
+
+};
+diffFilter.filterName = 'arrays';
+
+var compare = {
+    numerically: function(a, b) {
+        return a - b;
+    },
+    numericallyBy: function(name) {
+        return function(a, b) {
+            return a[name] - b[name];
+        };
+    }
+};
+
+var patchFilter = function nestedPatchFilter(context) {
+    if (!context.nested) { return; }
+    if (context.delta._t !== 'a') { return; }
+    var index, index1;
+
+    var delta = context.delta;
+    var array = context.left;
+
+    // first, separate removals, insertions and modifications
+    var toRemove = [];
+    var toInsert = [];
+    var toModify = [];
+    for (index in delta) {
+        if (index !== '_t') {
+            if (index[0] === '_') {
+                // removed item from original array
+                if (delta[index][2] === 0 || delta[index][2] === ARRAY_MOVE) {
+                    toRemove.push(parseInt(index.slice(1), 10));
+                } else {
+                    throw new Error('only removal or move can be applied at original array indices' +
+                        ', invalid diff type: ' + delta[index][2]);
+                }
+            } else {
+                if (delta[index].length === 1) {
+                    // added item at new array
+                    toInsert.push({
+                        index: parseInt(index, 10),
+                        value: delta[index][0]
+                    });
+                } else {
+                    // modified item at new array
+                    toModify.push({
+                        index: parseInt(index, 10),
+                        delta: delta[index]
+                    });
+                }
+            }
+        }
+    }
+
+    // remove items, in reverse order to avoid sawing our own floor
+    toRemove = toRemove.sort(compare.numerically);
+    for (index = toRemove.length - 1; index >= 0; index--) {
+        index1 = toRemove[index];
+        var indexDiff = delta['_' + index1];
+        var removedValue = array.splice(index1, 1)[0];
+        if (indexDiff[2] === ARRAY_MOVE) {
+            // reinsert later
+            toInsert.push({
+                index: indexDiff[1],
+                value: removedValue
+            });
+        }
+    }
+
+    // insert items, in reverse order to avoid moving our own floor
+    toInsert = toInsert.sort(compare.numericallyBy('index'));
+    var toInsertLength = toInsert.length;
+    for (index = 0; index < toInsertLength; index++) {
+        var insertion = toInsert[index];
+        array.splice(insertion.index, 0, insertion.value);
+    }
+
+    // apply modifications
+    var toModifyLength = toModify.length;
+    var child;
+    if (toModifyLength > 0) {
+        for (index = 0; index < toModifyLength; index++) {
+            var modification = toModify[index];
+            child = new PatchContext(context.left[modification.index], modification.delta);
+            context.push(child, modification.index);
+        }
+    }
+
+    if (!context.children) {
+        context.setResult(context.left).exit();
+        return;
+    }
+    context.exit();
+};
+patchFilter.filterName = 'arrays';
+
+var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
+    if (!context || !context.children) { return; }
+    if (context.delta._t !== 'a') { return; }
+    var length = context.children.length;
+    var child;
+    for (var index = 0; index < length; index++) {
+        child = context.children[index];
+        context.left[child.childName] = child.result;
+    }
+    context.setResult(context.left).exit();
+};
+collectChildrenPatchFilter.filterName = 'arraysCollectChildren';
+
+var reverseFilter = function arraysReverseFilter(context) {
+    if (!context.nested) {
+        if (context.delta[2] === ARRAY_MOVE) {
+            context.newName = '_' + context.delta[1];
+            context.setResult([context.delta[0], parseInt(context.childName.substr(1), 10), ARRAY_MOVE]).exit();
+        }
+        return;
+    }
+    if (context.delta._t !== 'a') { return; }
+    var name, child;
+    for (name in context.delta) {
+        if (name === '_t') { continue; }
+        child = new ReverseContext(context.delta[name]);
+        context.push(child, name);
+    }
+    context.exit();
+};
+reverseFilter.filterName = 'arrays';
+
+var reverseArrayDeltaIndex = function(delta, index, itemDelta) {
+    var newIndex = index;
+    if (typeof index === 'string' && index[0] === '_') {
+        newIndex = parseInt(index.substr(1), 10);
+    } else {
+        var uindex = '_' + index;
+        if (isArray(itemDelta) && itemDelta[2] === 0) {
+            newIndex = uindex;
+        } else {
+            for (var index2 in delta) {
+                var itemDelta2 = delta[index2];
+                if (isArray(itemDelta2) && itemDelta2[2] === ARRAY_MOVE && itemDelta2[1].toString() === index) {
+                    newIndex = index2.substr(1);
+                }
+            }
+        }
+    }
+    return newIndex;
+};
+
+var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
+    if (!context || !context.children) { return; }
+    if (context.delta._t !== 'a') { return; }
+    var length = context.children.length;
+    var child;
+    var delta = { _t: 'a' };
+    for (var index = 0; index < length; index++) {
+        child = context.children[index];
+        var name = child.newName;
+        if (typeof name === 'undefined') {
+            name = reverseArrayDeltaIndex(context.delta, child.childName, child.result);
+        }
+        if (delta[name] !== child.result) {
+            delta[name] = child.result;
+        }
+    }
+    context.setResult(delta).exit();
+};
+collectChildrenReverseFilter.filterName = 'arraysCollectChildren';
+
+exports.diffFilter = diffFilter;
+exports.patchFilter = patchFilter;
+exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
+exports.reverseFilter = reverseFilter;
+exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
diff --git a/src/filters/dates.js b/src/filters/dates.js
new file mode 100644
index 0000000..1964427
--- /dev/null
+++ b/src/filters/dates.js
@@ -0,0 +1,19 @@
+var diffFilter = function datesDiffFilter(context) {
+    if (context.left instanceof Date) {
+        if (context.right instanceof Date) {
+            if (context.left.getTime() !== context.right.getTime()) {
+                context.setResult([context.left, context.right]);
+            } else {
+                context.setResult(undefined);
+            }
+        } else {
+            context.setResult([context.left, context.right]);
+        }
+        context.exit();
+    } else if (context.right instanceof Date) {
+        context.setResult([context.left, context.right]).exit();
+    }
+};
+diffFilter.filterName = 'dates';
+
+exports.diffFilter = diffFilter;
\ No newline at end of file
diff --git a/src/filters/lcs.js b/src/filters/lcs.js
new file mode 100644
index 0000000..bccdc01
--- /dev/null
+++ b/src/filters/lcs.js
@@ -0,0 +1,74 @@
+/*
+
+LCS implementation that supports arrays or strings
+
+reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
+
+*/
+
+var defaultMatch = function(array1, array2, index1, index2) {
+    return array1[index1] === array2[index2];
+};
+
+var lengthMatrix = function(array1, array2, match, context) {
+    var len1 = array1.length;
+    var len2 = array2.length;
+    var x, y;
+
+    // initialize empty matrix of len1+1 x len2+1
+    var matrix = [len1 + 1];
+    for (x = 0; x < len1 + 1; x++) {
+        matrix[x] = [len2 + 1];
+        for (y = 0; y < len2 + 1; y++) {
+            matrix[x][y] = 0;
+        }
+    }
+    matrix.match = match;
+    // save sequence lengths for each coordinate
+    for (x = 1; x < len1 + 1; x++) {
+        for (y = 1; y < len2 + 1; y++) {
+            if (match(array1, array2, x - 1, y - 1, context)) {
+                matrix[x][y] = matrix[x - 1][y - 1] + 1;
+            } else {
+                matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);
+            }
+        }
+    }
+    return matrix;
+};
+
+var backtrack = function(matrix, array1, array2, index1, index2, context) {
+    if (index1 === 0 || index2 === 0) {
+        return {
+            sequence: [],
+            indices1: [],
+            indices2: []
+        };
+    }
+
+    if (matrix.match(array1, array2, index1 - 1, index2 - 1, context)) {
+        var subsequence = backtrack(matrix, array1, array2, index1 - 1, index2 - 1, context);
+        subsequence.sequence.push(array1[index1 - 1]);
+        subsequence.indices1.push(index1 - 1);
+        subsequence.indices2.push(index2 - 1);
+        return subsequence;
+    }
+
+    if (matrix[index1][index2 - 1] > matrix[index1 - 1][index2]) {
+        return backtrack(matrix, array1, array2, index1, index2 - 1, context);
+    } else {
+        return backtrack(matrix, array1, array2, index1 - 1, index2, context);
+    }
+};
+
+var get = function(array1, array2, match, context) {
+    context = context || {};
+    var matrix = lengthMatrix(array1, array2, match || defaultMatch, context);
+    var result = backtrack(matrix, array1, array2, array1.length, array2.length, context);
+    if (typeof array1 === 'string' && typeof array2 === 'string') {
+        result.sequence = result.sequence.join('');
+    }
+    return result;
+};
+
+exports.get = get;
diff --git a/src/filters/nested.js b/src/filters/nested.js
new file mode 100644
index 0000000..933cf74
--- /dev/null
+++ b/src/filters/nested.js
@@ -0,0 +1,109 @@
+
+var DiffContext = require('../contexts/diff').DiffContext;
+var PatchContext = require('../contexts/patch').PatchContext;
+var ReverseContext = require('../contexts/reverse').ReverseContext;
+
+var collectChildrenDiffFilter = function collectChildrenDiffFilter(context) {
+    if (!context || !context.children) { return; }
+    var length = context.children.length;
+    var child;
+    var result = context.result;
+    for (var index = 0; index < length; index++) {
+        child = context.children[index];
+        if (typeof child.result === 'undefined') {
+            continue;
+        }
+        result = result || {};
+        result[child.childName] = child.result;
+    }
+    if (result && context.leftIsArray) {
+        result._t = 'a';
+    }
+    context.setResult(result).exit();
+};
+collectChildrenDiffFilter.filterName = 'collectChildren';
+
+var objectsDiffFilter = function objectsDiffFilter(context) {
+    if (context.leftIsArray || context.leftType !== 'object') { return; }
+
+    var name, child;
+    for (name in context.left) {
+        child = new DiffContext(context.left[name], context.right[name]);
+        context.push(child, name);
+    }
+    for (name in context.right) {
+        if (typeof context.left[name] === 'undefined') {
+            child = new DiffContext(undefined, context.right[name]);
+            context.push(child, name);
+        }
+    }
+
+    if (!context.children || context.children.length === 0) {
+        context.setResult(undefined).exit();
+        return;
+    }
+    context.exit();
+};
+objectsDiffFilter.filterName = 'objects';
+
+var patchFilter = function nestedPatchFilter(context) {
+    if (!context.nested) { return; }
+    if (context.delta._t) { return; }
+    var name, child;
+    for (name in context.delta) {
+        child = new PatchContext(context.left[name], context.delta[name]);
+        context.push(child, name);
+    }
+    context.exit();
+};
+patchFilter.filterName = 'objects';
+
+var collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
+    if (!context || !context.children) { return; }
+    if (context.delta._t) { return; }
+    var length = context.children.length;
+    var child;
+    for (var index = 0; index < length; index++) {
+        child = context.children[index];
+        if (context.left[child.childName] !== child.result) {
+            context.left[child.childName] = child.result;
+        }
+    }
+    context.setResult(context.left).exit();
+};
+collectChildrenPatchFilter.filterName = 'collectChildren';
+
+var reverseFilter = function nestedReverseFilter(context) {
+    if (!context.nested) { return; }
+    if (context.delta._t) { return; }
+    var name, child;
+    for (name in context.delta) {
+        child = new ReverseContext(context.delta[name]);
+        context.push(child, name);
+    }
+    context.exit();
+};
+reverseFilter.filterName = 'objects';
+
+var collectChildrenReverseFilter = function collectChildrenReverseFilter(context) {
+    if (!context || !context.children) { return; }
+    if (context.delta._t) { return; }
+    var length = context.children.length;
+    var child;
+    var delta = {};
+    for (var index = 0; index < length; index++) {
+        child = context.children[index];
+        if (delta[child.childName] !== child.result) {
+            delta[child.childName] = child.result;
+        }
+    }
+    context.setResult(delta).exit();
+};
+collectChildrenReverseFilter.filterName = 'collectChildren';
+
+exports.collectChildrenDiffFilter = collectChildrenDiffFilter;
+exports.objectsDiffFilter = objectsDiffFilter;
+exports.patchFilter = patchFilter;
+exports.collectChildrenPatchFilter = collectChildrenPatchFilter;
+exports.reverseFilter = reverseFilter;
+exports.collectChildrenReverseFilter = collectChildrenReverseFilter;
\ No newline at end of file
diff --git a/src/filters/texts.js b/src/filters/texts.js
new file mode 100644
index 0000000..a17b0f4
--- /dev/null
+++ b/src/filters/texts.js
@@ -0,0 +1,111 @@
+/* global diff_match_patch */
+var TEXT_DIFF = 2;
+var DEFAULT_MIN_LENGTH = 60;
+var cachedDiffPatch = null;
+
+var getDiffMatchPatch = function(){
+    /*jshint camelcase: false */
+
+    if (!cachedDiffPatch) {
+        var instance;
+        if (typeof diff_match_patch !== 'undefined') {
+            // already loaded, probably a browser
+            instance = new diff_match_patch();
+        } else if (typeof require === 'function') {
+            var dmp = require('../../external/diff_match_patch_uncompressed');
+            instance = new dmp.diff_match_patch();
+        }
+        if (!instance) {
+            var error = new Error('text diff_match_patch library not found');
+            error.diff_match_patch_not_found = true;
+            throw error;
+        }
+        cachedDiffPatch = {
+            diff: function(txt1, txt2){
+                return instance.patch_toText(instance.patch_make(txt1, txt2));
+            },
+            patch: function(txt1, patch){
+                var results = instance.patch_apply(instance.patch_fromText(patch), txt1);
+                for (var i = 0; i < results[1].length; i++) {
+                    if (!results[1][i]) {
+                        var error = new Error('text patch failed');
+                        error.textPatchFailed = true;
+                    }
+                }
+                return results[0];
+            }
+        };
+    }
+    return cachedDiffPatch;
+};
+
+var diffFilter = function textsDiffFilter(context) {
+    if (context.leftType !== 'string') { return; }
+    var minLength = (context.options && context.options.textDiff &&
+        context.options.textDiff.minLength) || DEFAULT_MIN_LENGTH;
+    if (context.left.length < minLength ||
+        context.right.length < minLength) {
+        context.setResult([context.left, context.right]).exit();
+        return;
+    }
+    // large text, use a text-diff algorithm
+    var diff = getDiffMatchPatch().diff;
+    context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit();
+};
+diffFilter.filterName = 'texts';
+
+var patchFilter = function textsPatchFilter(context) {
+    if (context.nested) { return; }
+    if (context.delta[2] !== TEXT_DIFF) { return; }
+
+    // text-diff, use a text-patch algorithm
+    var patch = getDiffMatchPatch().patch;
+    context.setResult(patch(context.left, context.delta[0])).exit();
+};
+patchFilter.filterName = 'texts';
+
+var textDeltaReverse = function(delta){
+    var i, l, lines, line, lineTmp, header = null,
+    headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/,
+    lineHeader, lineAdd, lineRemove;
+    lines = delta.split('\n');
+    for (i = 0, l = lines.length; i<l; i++) {
+        line = lines[i];
+        var lineStart = line.slice(0,1);
+        if (lineStart==='@'){
+            header = headerRegex.exec(line);
+            lineHeader = i;
+            lineAdd = null;
+            lineRemove = null;
+
+            // fix header
+            lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';
+        } else if (lineStart === '+'){
+            lineAdd = i;
+            lines[i] = '-' + lines[i].slice(1);
+            if (lines[i-1].slice(0,1)==='+') {
+                // swap lines to keep default order (-+)
+                lineTmp = lines[i];
+                lines[i] = lines[i-1];
+                lines[i-1] = lineTmp;
+            }
+        } else if (lineStart === '-'){
+            lineRemove = i;
+            lines[i] = '+' + lines[i].slice(1);
+        }
+    }
+    return lines.join('\n');
+};
+
+var reverseFilter = function textsReverseFilter(context) {
+    if (context.nested) { return; }
+    if (context.delta[2] !== TEXT_DIFF) { return; }
+
+    // text-diff, use a text-diff algorithm
+    context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit();
+};
+reverseFilter.filterName = 'texts';
+
+exports.diffFilter = diffFilter;
+exports.patchFilter = patchFilter;
+exports.reverseFilter = reverseFilter;
\ No newline at end of file
diff --git a/src/filters/trivial.js b/src/filters/trivial.js
new file mode 100644
index 0000000..583eeaa
--- /dev/null
+++ b/src/filters/trivial.js
@@ -0,0 +1,98 @@
+
+var isArray = (typeof Array.isArray === 'function') ?
+    // use native function
+    Array.isArray :
+    // use instanceof operator
+    function(a) {
+        return a instanceof Array;
+    };
+
+var diffFilter = function trivialMatchesDiffFilter(context) {
+    if (context.left === context.right) {
+        context.setResult(undefined).exit();
+        return;
+    }
+    if (typeof context.left === 'undefined') {
+        if (typeof context.right === 'function') {
+            throw new Error('functions are not supported');
+        }
+        context.setResult([context.right]).exit();
+        return;
+    }
+    if (typeof context.right === 'undefined') {
+        context.setResult([context.left, 0, 0]).exit();
+        return;
+    }
+    if (typeof context.left === 'function' || typeof context.right === 'function' ) {
+        throw new Error('functions are not supported');
+    }
+    context.leftType = context.left === null ? 'null' : typeof context.left;
+    context.rightType = context.right === null ? 'null' : typeof context.right;
+    if (context.leftType !== context.rightType) {
+        context.setResult([context.left, context.right]).exit();
+        return;
+    }
+    if (context.leftType === 'boolean' || context.leftType === 'number') {
+        context.setResult([context.left, context.right]).exit();
+        return;
+    }
+    if (context.leftType === 'object') {
+        context.leftIsArray = isArray(context.left);
+    }
+    if (context.rightType === 'object') {
+        context.rightIsArray = isArray(context.right);
+    }
+    if (context.leftIsArray !== context.rightIsArray) {
+        context.setResult([context.left, context.right]).exit();
+        return;
+    }
+};
+diffFilter.filterName = 'trivial';
+
+var patchFilter = function trivialMatchesPatchFilter(context) {
+    if (typeof context.delta === 'undefined') {
+        context.setResult(context.left).exit();
+        return;
+    }
+    context.nested = !isArray(context.delta);
+    if (context.nested) { return; }
+    if (context.delta.length === 1) {
+        context.setResult(context.delta[0]).exit();
+        return;
+    }
+    if (context.delta.length === 2) {
+        context.setResult(context.delta[1]).exit();
+        return;
+    }
+    if (context.delta.length === 3 && context.delta[2] === 0) {
+        context.setResult(undefined).exit();
+        return;
+    }
+};
+patchFilter.filterName = 'trivial';
+
+var reverseFilter = function trivialReferseFilter(context) {
+    if (typeof context.delta === 'undefined') {
+        context.setResult(context.delta).exit();
+        return;
+    }
+    context.nested = !isArray(context.delta);
+    if (context.nested) { return; }
+    if (context.delta.length === 1) {
+        context.setResult([context.delta[0], 0, 0]).exit();
+        return;
+    }
+    if (context.delta.length === 2) {
+        context.setResult([context.delta[1], context.delta[0]]).exit();
+        return;
+    }
+    if (context.delta.length === 3 && context.delta[2] === 0) {
+        context.setResult([context.delta[0]]).exit();
+        return;
+    }
+};
+reverseFilter.filterName = 'trivial';
+
+exports.diffFilter = diffFilter;
+exports.patchFilter = patchFilter;
+exports.reverseFilter = reverseFilter;
diff --git a/src/formatters/annotated.css b/src/formatters/annotated.css
new file mode 100644
index 0000000..d0e8250
--- /dev/null
+++ b/src/formatters/annotated.css
@@ -0,0 +1,56 @@
+.jsondiffpatch-annotated-delta {
+    font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
+    font-size: 12px;
+    margin: 0;
+    padding: 0 0 0 12px;
+    display: inline-block;
+}
+
+.jsondiffpatch-annotated-delta pre {
+    font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
+    font-size: 12px;
+    margin: 0;
+    padding: 0;
+    display: inline-block;
+}
+
+.jsondiffpatch-annotated-delta td {
+    margin: 0;
+    padding: 0;
+}
+
+.jsondiffpatch-annotated-delta td pre:hover {
+    font-weight: bold;
+}
+
+td.jsondiffpatch-delta-note {
+    font-style: italic;
+    padding-left: 10px;
+}
+
+.jsondiffpatch-delta-note > div {
+    margin: 0;
+    padding: 0;
+}
+
+.jsondiffpatch-delta-note pre {
+    font-style: normal;
+}
+
+.jsondiffpatch-annotated-delta .jsondiffpatch-delta-note {
+    color: #777;
+}
+
+.jsondiffpatch-annotated-delta tr:hover {
+    background: #ffc;
+}
+
+.jsondiffpatch-annotated-delta tr:hover > td.jsondiffpatch-delta-note {
+    color: black;
+}
+
+.jsondiffpatch-error {
+    background: red;
+    color: white;
+    font-weight: bold;
+}
\ No newline at end of file
diff --git a/src/formatters/annotated.js b/src/formatters/annotated.js
new file mode 100644
index 0000000..4bd44ea
--- /dev/null
+++ b/src/formatters/annotated.js
@@ -0,0 +1,198 @@
+
+var base = require('./base');
+var BaseFormatter = base.BaseFormatter;
+
+var AnnotatedFormatter = function AnnotatedFormatter() {
+    this.includeMoveDestinations = false;
+};
+
+AnnotatedFormatter.prototype = new BaseFormatter();
+
+AnnotatedFormatter.prototype.prepareContext = function(context) {
+    BaseFormatter.prototype.prepareContext.call(this, context);
+    context.indent = function(levels) {
+        this.indentLevel = (this.indentLevel || 0) +
+            (typeof levels === 'undefined' ? 1 : levels);
+        this.indentPad = new Array(this.indentLevel + 1).join('  ');
+    };
+    context.row = function(json, htmlNote) {
+        context.out('<tr><td style="white-space: nowrap;">' +
+            '<pre class="jsondiffpatch-annotated-indent" style="display: inline-block">');
+        context.out(context.indentPad);
+        context.out('</pre><pre style="display: inline-block">');
+        context.out(json);
+        context.out('</pre></td><td class="jsondiffpatch-delta-note"><div>');
+        context.out(htmlNote);
+        context.out('</div></td></tr>');
+    };
+};
+
+AnnotatedFormatter.prototype.typeFormattterErrorFormatter = function(context, err) {
+    context.row('','<pre class="jsondiffpatch-error">' + err + '</pre>');
+};
+
+AnnotatedFormatter.prototype.formatTextDiffString = function(context, value) {
+    var lines = this.parseTextDiff(value);
+    context.out('<ul class="jsondiffpatch-textdiff">');
+    for (var i = 0, l = lines.length; i < l; i++) {
+        var line = lines[i];
+        context.out('<li>' +
+        '<div class="jsondiffpatch-textdiff-location">' +
+        '<span class="jsondiffpatch-textdiff-line-number">' +
+        line.location.line +
+        '</span>' +
+        '<span class="jsondiffpatch-textdiff-char">' +
+        line.location.chr +
+        '</span>' +
+        '</div>' +
+        '<div class="jsondiffpatch-textdiff-line">');
+        var pieces = line.pieces;
+        for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
+            var piece = pieces[pieceIndex];
+            context.out('<span class="jsondiffpatch-textdiff-' + piece.type + '">' +
+                piece.text + '</span>');
+        }
+        context.out('</div></li>');
+    }
+    context.out('</ul>');
+};
+
+AnnotatedFormatter.prototype.rootBegin = function(context, type, nodeType) {
+    context.out('<table class="jsondiffpatch-annotated-delta">');
+    if (type ==='node') {
+        context.row('{');
+        context.indent();
+    }
+    if (nodeType === 'array') {
+        context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
+    }
+};
+
+AnnotatedFormatter.prototype.rootEnd = function(context, type) {
+    if (type ==='node') {
+        context.indent(-1);
+        context.row('}');
+    }
+    context.out('</table>');
+};
+
+AnnotatedFormatter.prototype.nodeBegin = function(context, key, leftKey, type, nodeType) {
+    context.row('"'+key+'": {');
+    if (type === 'node') {
+        context.indent();
+    }
+    if (nodeType === 'array') {
+        context.row('"_t": "a",', 'Array delta (member names indicate array indices)');
+    }
+};
+
+AnnotatedFormatter.prototype.nodeEnd = function(context, key, leftKey, type, nodeType, isLast) {
+    if (type ==='node') {
+        context.indent(-1);
+    }
+    context.row('}' + (isLast ? '' : ','));
+};
+
+/* jshint camelcase: false */
+
+AnnotatedFormatter.prototype.format_unchanged = function() {
+    return;
+};
+
+AnnotatedFormatter.prototype.format_movedestination = function() {
+    return;
+};
+
+
+AnnotatedFormatter.prototype.format_node = function(context, delta, left) {
+    // recurse
+    this.formatDeltaChildren(context, delta, left);
+};
+
+var wrapPropertyName = function(name) {
+    return '<pre style="display:inline-block">"' + name + '"</pre>';
+};
+
+var deltaAnnotations = {
+    added: function(delta, left, key, leftKey) {
+        var formatLegend = ' <pre>([newValue])</pre>';
+        if (typeof leftKey === 'undefined') {
+            return 'new value' + formatLegend;
+        }
+        if (typeof leftKey === 'number') {
+            return 'insert at index ' + leftKey + formatLegend;
+        }
+        return 'add property ' + wrapPropertyName(leftKey) + formatLegend;
+    },
+    modified: function(delta, left, key, leftKey) {
+        var formatLegend = ' <pre>([previousValue, newValue])</pre>';
+        if (typeof leftKey === 'undefined') {
+            return 'modify value' + formatLegend;
+        }
+        if (typeof leftKey === 'number') {
+            return 'modify at index ' + leftKey + formatLegend;
+        }
+        return 'modify property ' + wrapPropertyName(leftKey) + formatLegend;
+    },
+    deleted: function(delta, left, key, leftKey) {
+        var formatLegend = ' <pre>([previousValue, 0, 0])</pre>';
+        if (typeof leftKey === 'undefined') {
+            return 'delete value' + formatLegend;
+        }
+        if (typeof leftKey === 'number') {
+            return 'remove index ' + leftKey + formatLegend;
+        }
+        return 'delete property ' + wrapPropertyName(leftKey) + formatLegend;
+    },
+    moved: function(delta, left, key, leftKey) {
+        return 'move from <span title="(position to remove at original state)">index ' +
+            leftKey + '</span> to ' +
+            '<span title="(position to insert at final state)">index ' +
+            delta[1] + '</span>';
+    },
+    textdiff: function(delta, left, key, leftKey) {
+        var location = (typeof leftKey === 'undefined') ?
+            '' : (
+                (typeof leftKey === 'number') ?
+                ' at index ' + leftKey :
+                ' at property ' + wrapPropertyName(leftKey)
+            );
+        return 'text diff' + location + ', format is ' +
+        '<a href="https://code.google.com/p/google-diff-match-patch/wiki/Unidiff">' +
+        'a variation of Unidiff</a>';
+    }
+};
+
+var formatAnyChange = function(context, delta) {
+    var deltaType = this.getDeltaType(delta);
+    var annotator = deltaAnnotations[deltaType];
+    var htmlNote = annotator && annotator.apply(annotator,
+        Array.prototype.slice.call(arguments, 1));
+    var json = JSON.stringify(delta, null, 2);
+    if (deltaType === 'textdiff') {
+        // split text diffs lines
+        json = json.split('\\n').join('\\n"+\n   "');
+    }
+    context.indent();
+    context.row(json, htmlNote);
+    context.indent(-1);
+};
+
+AnnotatedFormatter.prototype.format_added = formatAnyChange;
+AnnotatedFormatter.prototype.format_modified = formatAnyChange;
+AnnotatedFormatter.prototype.format_deleted = formatAnyChange;
+AnnotatedFormatter.prototype.format_moved = formatAnyChange;
+AnnotatedFormatter.prototype.format_textdiff = formatAnyChange;
+
+/* jshint camelcase: true */
+
+exports.AnnotatedFormatter = AnnotatedFormatter;
+
+var defaultInstance;
+
+exports.format = function(delta, left) {
+    if (!defaultInstance) {
+        defaultInstance = new AnnotatedFormatter();
+    }
+    return defaultInstance.format(delta, left);
+};
\ No newline at end of file
diff --git a/src/formatters/base.js b/src/formatters/base.js
new file mode 100644
index 0000000..f2c7fc8
--- /dev/null
+++ b/src/formatters/base.js
@@ -0,0 +1,210 @@
+
+var isArray = (typeof Array.isArray === 'function') ?
+    // use native function
+    Array.isArray :
+    // use instanceof operator
+    function(a) {
+        return a instanceof Array;
+    };
+
+var getObjectKeys = typeof Object.keys === 'function' ?
+    function(obj) {
+        return Object.keys(obj);
+    } : function(obj) {
+        var names = [];
+        for (var property in obj) {
+            if (obj.hasOwnProperty(property)) {
+                names.push(property);
+            }
+        }
+        return names;
+    };
+
+var trimUnderscore = function(str) {
+    if (str.substr(0, 1) === '_') {
+        return str.slice(1);
+    }
+    return str;
+};
+
+var arrayKeyToSortNumber = function(key) {
+    if (key === '_t') {
+        return -1;
+    } else {
+        if (key.substr(0, 1) === '_') {
+            return parseInt(key.slice(1), 10);
+        } else {
+            return parseInt(key, 10) + 0.1;
+        }
+    }
+};
+
+var arrayKeyComparer = function(key1, key2) {
+    return arrayKeyToSortNumber(key1) - arrayKeyToSortNumber(key2);
+};
+
+var BaseFormatter = function BaseFormatter() {
+};
+
+BaseFormatter.prototype.format = function(delta, left) {
+    var context = {};
+    this.prepareContext(context);
+    this.recurse(context, delta, left);
+    return this.finalize(context);
+};
+
+BaseFormatter.prototype.prepareContext = function(context) {
+    context.buffer = [];
+    context.out = function() {
+        this.buffer.push.apply(this.buffer, arguments);
+    };
+};
+
+BaseFormatter.prototype.typeFormattterNotFound = function(context, deltaType) {
+    throw new Error('cannot format delta type: ' + deltaType);
+};
+
+BaseFormatter.prototype.typeFormattterErrorFormatter = function(context, err) {
+    return err.toString();
+};
+
+BaseFormatter.prototype.finalize = function(context) {
+    if (isArray(context.buffer)) {
+        return context.buffer.join('');
+    }
+};
+
+BaseFormatter.prototype.recurse = function(context, delta, left, key, leftKey, movedFrom, isLast) {
+    if (typeof delta === 'undefined' && typeof key === 'undefined') {
+        return undefined;
+    }
+    var type = this.getDeltaType(delta, movedFrom);
+    var nodeType = type === 'node' ? (delta._t === 'a' ? 'array' : 'object') : '';
+
+    if (typeof key !== 'undefined') {
+        this.nodeBegin(context, key, leftKey, type, nodeType, isLast);
+    } else {
+        this.rootBegin(context, type, nodeType);
+    }
+
+    var typeFormattter;
+    try {
+        typeFormattter = this['format_' + type] || this.typeFormattterNotFound(context, type);
+        typeFormattter.call(this, context, delta, left, key, leftKey, movedFrom);
+    } catch (err) {
+        this.typeFormattterErrorFormatter(context, err, delta, left, key, leftKey, movedFrom);
+        if (typeof console !== 'undefined' && console.error) {
+            console.error(err.stack);
+        }
+    }
+
+    if (typeof key !== 'undefined') {
+        this.nodeEnd(context, key, leftKey, type, nodeType, isLast);
+    } else {
+        this.rootEnd(context, type, nodeType);
+    }
+};
+
+BaseFormatter.prototype.formatDeltaChildren = function(context, delta, left) {
+    var self = this;
+    this.forEachDeltaKey(delta, left, function(key, leftKey, movedFrom, isLast) {
+        self.recurse(context, delta[key], left ? left[leftKey] : undefined,
+            key, leftKey, movedFrom, isLast);
+    });
+};
+
+BaseFormatter.prototype.forEachDeltaKey = function(delta, left, fn) {
+    var keys = getObjectKeys(delta);
+    var arrayKeys = delta._t === 'a';
+    var moveDestinations = {};
+    var name;
+    if (typeof left !== 'undefined') {
+        for (name in left) {
+            if (typeof delta[name] === 'undefined' &&
+                ((!arrayKeys) || typeof delta['_' + name] === 'undefined')) {
+                keys.push(name);
+            }
+        }
+    }
+    // look for move destinations
+    for (name in delta) {
+        var value = delta[name];
+        if (isArray(value) && value[2] === 3) {
+            moveDestinations[value[1].toString()] = value[0];
+            if (this.includeMoveDestinations !== false) {
+                if ((typeof left === 'undefined') &&
+                    (typeof delta[value[1]] === 'undefined')) {
+                    keys.push(value[1].toString());
+                }
+            }
+        }
+    }
+    if (arrayKeys) {
+        keys.sort(arrayKeyComparer);
+    } else {
+        keys.sort();
+    }
+    for (var index = 0, length = keys.length; index < length; index++) {
+        var key = keys[index];
+        if (arrayKeys && key === '_t') { continue; }
+        var leftKey = arrayKeys ?
+            (typeof key === 'number' ? key : parseInt(trimUnderscore(key), 10)) :
+            key;
+        var isLast = (index === length - 1);
+        fn(key, leftKey, moveDestinations[leftKey], isLast);
+    }
+};
+
+BaseFormatter.prototype.getDeltaType = function(delta, movedFrom) {
+    if (typeof delta === 'undefined') {
+        if (typeof movedFrom !== 'undefined') {
+            return 'movedestination';
+        }
+        return 'unchanged';
+    }
+    if (isArray(delta)) {
+        if (delta.length === 1) { return 'added'; }
+        if (delta.length === 2) { return 'modified'; }
+        if (delta.length === 3 && delta[2] === 0) { return 'deleted'; }
+        if (delta.length === 3 && delta[2] === 2) { return 'textdiff'; }
+        if (delta.length === 3 && delta[2] === 3) { return 'moved'; }
+    } else if (typeof delta === 'object') {
+        return 'node';
+    }
+    return 'unknown';
+};
+
+BaseFormatter.prototype.parseTextDiff = function(value) {
+    var output = [];
+    var lines = value.split('\n@@ ');
+    for (var i = 0, l = lines.length; i < l; i++) {
+        var line = lines[i];
+        var lineOutput = {
+            pieces: []
+        };
+        var location = /^(?:@@ )?[-+]?(\d+),(\d+)/.exec(line).slice(1);
+        lineOutput.location = {
+            line: location[0],
+            chr: location[1]
+        };
+        var pieces = line.split('\n').slice(1);
+        for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
+            var piece = pieces[pieceIndex];
+            if (!piece.length) { continue; }
+            var pieceOutput = { type: 'context' };
+            if (piece.substr(0, 1) === '+') {
+                pieceOutput.type = 'added';
+            } else if (piece.substr(0, 1) === '-') {
+                pieceOutput.type = 'deleted';
+            }
+            pieceOutput.text = piece.slice(1);
+            lineOutput.pieces.push(pieceOutput);
+        }
+        output.push(lineOutput);
+    }
+    return output;
+};
+
+exports.BaseFormatter = BaseFormatter;
+
+
diff --git a/src/formatters/console.js b/src/formatters/console.js
new file mode 100644
index 0000000..897ad54
--- /dev/null
+++ b/src/formatters/console.js
@@ -0,0 +1,182 @@
+
+var chalk = require('chalk');
+var base = require('./base');
+var BaseFormatter = base.BaseFormatter;
+
+var colors = {
+    added: chalk.green,
+    deleted: chalk.red,
+    movedestination: chalk.gray,
+    moved: chalk.yellow,
+    unchanged: chalk.gray,
+    error: chalk.white.bgRed,
+    textDiffLine: chalk.gray
+};
+
+var ConsoleFormatter = function ConsoleFormatter() {
+    this.includeMoveDestinations = false;
+};
+
+ConsoleFormatter.prototype = new BaseFormatter();
+
+ConsoleFormatter.prototype.prepareContext = function(context) {
+    BaseFormatter.prototype.prepareContext.call(this, context);
+    context.indent = function(levels) {
+        this.indentLevel = (this.indentLevel || 0) +
+            (typeof levels === 'undefined' ? 1 : levels);
+        this.indentPad = new Array(this.indentLevel + 1).join('  ');
+        this.outLine();
+    };
+    context.outLine = function() {
+        this.buffer.push('\n' + (this.indentPad || ''));
+    };
+    context.out = function() {
+        for (var i = 0, l = arguments.length; i < l; i++) {
+            var lines = arguments[i].split('\n');
+            var text = lines.join('\n' + (this.indentPad || ''));
+            if (this.color && this.color[0]) {
+                text = this.color[0](text);
+            }
+            this.buffer.push(text);
+        }
+    };
+    context.pushColor = function(color) {
+        this.color = this.color || [];
+        this.color.unshift(color);
+    };
+    context.popColor = function() {
+        this.color = this.color || [];
+        this.color.shift();
+    };
+};
+
+ConsoleFormatter.prototype.typeFormattterErrorFormatter = function(context, err) {
+    context.pushColor(colors.error);
+    context.out('[ERROR]' + err);
+    context.popColor();
+};
+
+ConsoleFormatter.prototype.formatValue = function(context, value) {
+    context.out(JSON.stringify(value, null, 2));
+};
+
+ConsoleFormatter.prototype.formatTextDiffString = function(context, value) {
+    var lines = this.parseTextDiff(value);
+    context.indent();
+    for (var i = 0, l = lines.length; i < l; i++) {
+        var line = lines[i];
+        context.pushColor(colors.textDiffLine);
+        context.out(line.location.line + ',' + line.location.chr + ' ');
+        context.popColor();
+        var pieces = line.pieces;
+        for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
+            var piece = pieces[pieceIndex];
+            context.pushColor(colors[piece.type]);
+            context.out(piece.text);
+            context.popColor();
+        }
+        if (i < l - 1) {
+            context.outLine();
+        }
+    }
+    context.indent(-1);
+};
+
+ConsoleFormatter.prototype.rootBegin = function(context, type, nodeType) {
+    context.pushColor(colors[type]);
+    if (type ==='node') {
+        context.out(nodeType === 'array' ? '[' : '{');
+        context.indent();
+    }
+};
+
+ConsoleFormatter.prototype.rootEnd = function(context, type, nodeType) {
+    if (type ==='node') {
+        context.indent(-1);
+        context.out(nodeType === 'array' ? ']' : '}');
+    }
+    context.popColor();
+};
+
+ConsoleFormatter.prototype.nodeBegin = function(context, key, leftKey, type, nodeType) {
+    context.pushColor(colors[type]);
+    context.out(leftKey +  ': ');
+    if (type ==='node') {
+        context.out(nodeType === 'array' ? '[' : '{');
+        context.indent();
+    }
+};
+
+ConsoleFormatter.prototype.nodeEnd = function(context, key, leftKey, type, nodeType, isLast) {
+    if (type ==='node') {
+        context.indent(-1);
+        context.out(nodeType === 'array' ? ']' : '}' +
+            (isLast ? '' : ','));
+    }
+    if (!isLast) {
+        context.outLine();
+    }
+    context.popColor();
+};
+
+/* jshint camelcase: false */
+
+ConsoleFormatter.prototype.format_unchanged = function(context, delta, left) {
+    if (typeof left === 'undefined') { return; }
+    this.formatValue(context, left);
+};
+
+ConsoleFormatter.prototype.format_movedestination = function(context, delta, left) {
+    if (typeof left === 'undefined') { return; }
+    this.formatValue(context, left);
+};
+
+ConsoleFormatter.prototype.format_node = function(context, delta, left) {
+    // recurse
+    this.formatDeltaChildren(context, delta, left);
+};
+
+ConsoleFormatter.prototype.format_added = function(context, delta) {
+    this.formatValue(context, delta[0]);
+};
+
+ConsoleFormatter.prototype.format_modified = function(context, delta) {
+    context.pushColor(colors.deleted);
+    this.formatValue(context, delta[0]);
+    context.popColor();
+    context.out(' => ');
+    context.pushColor(colors.added);
+    this.formatValue(context, delta[1]);
+    context.popColor();
+};
+
+ConsoleFormatter.prototype.format_deleted = function(context, delta) {
+    this.formatValue(context, delta[0]);
+};
+
+ConsoleFormatter.prototype.format_moved = function(context, delta) {
+    context.out('==> ' + delta[1]);
+};
+
+ConsoleFormatter.prototype.format_textdiff = function(context, delta) {
+    this.formatTextDiffString(context, delta[0]);
+};
+
+/* jshint camelcase: true */
+
+exports.ConsoleFormatter = ConsoleFormatter;
+
+var defaultInstance;
+
+var format = function(delta, left) {
+    if (!defaultInstance) {
+        defaultInstance = new ConsoleFormatter();
+    }
+    return defaultInstance.format(delta, left);
+};
+
+exports.log = function(delta, left) {
+    console.log(format(delta, left));
+};
+
+exports.format = format;
\ No newline at end of file
diff --git a/src/formatters/html.css b/src/formatters/html.css
new file mode 100644
index 0000000..bec04bd
--- /dev/null
+++ b/src/formatters/html.css
@@ -0,0 +1,186 @@
+.jsondiffpatch-delta {
+    font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
+    font-size: 12px;
+    margin: 0;
+    padding: 0 0 0 12px;
+    display: inline-block;
+}
+
+.jsondiffpatch-delta pre {
+    font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
+    font-size: 12px;
+    margin: 0;
+    padding: 0;
+    display: inline-block;
+}
+
+ul.jsondiffpatch-delta {
+    list-style-type: none;
+    padding: 0 0 0 20px;
+    margin: 0;
+}
+
+.jsondiffpatch-delta ul {
+    list-style-type: none;
+    padding: 0 0 0 20px;
+    margin: 0;
+}
+
+.jsondiffpatch-added .jsondiffpatch-property-name,
+.jsondiffpatch-added .jsondiffpatch-value pre,
+.jsondiffpatch-modified .jsondiffpatch-right-value,
+.jsondiffpatch-textdiff-added
+{
+    background: #bbffbb;
+}
+
+.jsondiffpatch-deleted .jsondiffpatch-property-name,
+.jsondiffpatch-deleted pre,
+.jsondiffpatch-modified .jsondiffpatch-left-value pre,
+.jsondiffpatch-textdiff-deleted
+{
+    background: #ffbbbb;
+    text-decoration: line-through;
+}
+
+.jsondiffpatch-unchanged, .jsondiffpatch-movedestination {
+    color: gray;
+}
+
+.jsondiffpatch-unchanged, .jsondiffpatch-movedestination > .jsondiffpatch-value {
+    transition: all 0.5s;
+    -webkit-transition: all 0.5s;
+    overflow-y: hidden;
+}
+
+.jsondiffpatch-unchanged-showing .jsondiffpatch-unchanged,
+.jsondiffpatch-unchanged-showing .jsondiffpatch-movedestination > .jsondiffpatch-value  {
+    max-height: 100px;
+}
+
+.jsondiffpatch-unchanged-hidden .jsondiffpatch-unchanged,
+.jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value {
+    max-height: 0;
+}
+
+.jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value,
+.jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value {
+    display: block;
+}
+
+.jsondiffpatch-unchanged-visible .jsondiffpatch-unchanged,
+.jsondiffpatch-unchanged-visible .jsondiffpatch-movedestination > .jsondiffpatch-value {
+    max-height: 100px;
+}
+
+.jsondiffpatch-unchanged-hiding .jsondiffpatch-unchanged,
+.jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value  {
+    max-height: 0;
+}
+
+.jsondiffpatch-unchanged-showing .jsondiffpatch-arrow,
+.jsondiffpatch-unchanged-hiding .jsondiffpatch-arrow {
+    display: none;
+}
+
+.jsondiffpatch-value {
+    display: inline-block;
+}
+
+.jsondiffpatch-property-name {
+    display: inline-block;
+    padding-right: 5px;
+    vertical-align: top;
+}
+
+.jsondiffpatch-property-name:after {
+    content: ': ';
+}
+
+.jsondiffpatch-child-node-type-array > .jsondiffpatch-property-name:after {
+    content: ': [';
+}
+
+.jsondiffpatch-child-node-type-array:after {
+    content: '],';
+}
+
+div.jsondiffpatch-child-node-type-array:before {
+    content: '[';
+}
+
+div.jsondiffpatch-child-node-type-array:after {
+    content: ']';
+}
+
+.jsondiffpatch-child-node-type-object > .jsondiffpatch-property-name:after {
+    content: ': {';
+}
+
+.jsondiffpatch-child-node-type-object:after {
+    content: '},';
+}
+
+div.jsondiffpatch-child-node-type-object:before {
+    content: '{';
+}
+
+div.jsondiffpatch-child-node-type-object:after {
+    content: '}';
+}
+
+.jsondiffpatch-value pre:after {
+    content: ',';
+}
+
+li:last-child > .jsondiffpatch-value pre:after,
+.jsondiffpatch-modified > .jsondiffpatch-left-value pre:after
+{
+    content: '';
+}
+
+.jsondiffpatch-modified .jsondiffpatch-value {
+    display: inline-block;
+}
+
+.jsondiffpatch-modified .jsondiffpatch-right-value {
+    margin-left: 5px;
+}
+
+.jsondiffpatch-moved .jsondiffpatch-value {
+    display: none;
+}
+
+.jsondiffpatch-moved .jsondiffpatch-moved-destination {
+    display: inline-block;
+    background: #ffffbb;
+    color: #888;
+}
+
+.jsondiffpatch-moved .jsondiffpatch-moved-destination:before {
+    content: ' => ';
+}
+
+ul.jsondiffpatch-textdiff {
+    padding: 0;
+}
+
+.jsondiffpatch-textdiff-location {
+    color: #bbb;
+    display: inline-block;
+    min-width: 60px;
+}
+
+.jsondiffpatch-textdiff-line {
+    display: inline-block;
+}
+
+.jsondiffpatch-textdiff-line-number:after {
+    content: ',';
+}
+
+.jsondiffpatch-error {
+    background: red;
+    color: white;
+    font-weight: bold;
+}
\ No newline at end of file
diff --git a/src/formatters/html.js b/src/formatters/html.js
new file mode 100644
index 0000000..5988d80
--- /dev/null
+++ b/src/formatters/html.js
@@ -0,0 +1,258 @@
+
+var base = require('./base');
+var BaseFormatter = base.BaseFormatter;
+
+var HtmlFormatter = function HtmlFormatter() {
+};
+
+HtmlFormatter.prototype = new BaseFormatter();
+
+HtmlFormatter.prototype.typeFormattterErrorFormatter = function(context, err) {
+    context.out('<pre class="jsondiffpatch-error">' + err + '</pre>');
+};
+
+HtmlFormatter.prototype.formatValue = function(context, value) {
+    context.out('<pre>' + JSON.stringify(value, null, 2) + '</pre>');
+};
+
+HtmlFormatter.prototype.formatTextDiffString = function(context, value) {
+    var lines = this.parseTextDiff(value);
+    context.out('<ul class="jsondiffpatch-textdiff">');
+    for (var i = 0, l = lines.length; i < l; i++) {
+        var line = lines[i];
+        context.out('<li>' +
+        '<div class="jsondiffpatch-textdiff-location">' +
+        '<span class="jsondiffpatch-textdiff-line-number">' +
+        line.location.line +
+        '</span>' +
+        '<span class="jsondiffpatch-textdiff-char">' +
+        line.location.chr +
+        '</span>' +
+        '</div>' +
+        '<div class="jsondiffpatch-textdiff-line">');
+        var pieces = line.pieces;
+        for (var pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
+            var piece = pieces[pieceIndex];
+            context.out('<span class="jsondiffpatch-textdiff-' + piece.type + '">' +
+                piece.text + '</span>');
+        }
+        context.out('</div></li>');
+    }
+    context.out('</ul>');
+};
+
+var adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(node) {
+    node = node || document;
+    var getElementText = function(el) {
+        return el.textContent || el.innerText;
+    };
+    var eachByQuery = function(el, query, fn) {
+        var elems = el.querySelectorAll(query);
+        for (var i = 0, l = elems.length; i < l; i++) {
+            fn(elems[i]);
+        }
+    };
+    var eachChildren = function(el, fn) {
+        for (var i = 0, l = el.children.length; i < l; i++) {
+            fn(el.children[i], i);
+        }
+    };
+    eachByQuery(node, '.jsondiffpatch-arrow', function(arrow) {
+        var arrowParent = arrow.parentNode;
+        var svg = arrow.children[0], path = svg.children[1];
+        svg.style.display = 'none';
+        var destination = getElementText(arrowParent.querySelector('.jsondiffpatch-moved-destination'));
+        var container = arrowParent.parentNode;
+        var destinationElem;
+        eachChildren(container, function(child) {
+            if (child.getAttribute('data-key') === destination) {
+                destinationElem = child;
+            }
+        });
+        if (!destinationElem) { return; }
+        try {
+            var distance = destinationElem.offsetTop - arrowParent.offsetTop;
+            svg.setAttribute('height', Math.abs(distance) + 6);
+            arrow.style.top = (- 8 + (distance > 0 ? 0 : distance)) + 'px';
+            var curve = distance > 0 ?
+                'M30,0 Q-10,' + Math.round(distance / 2) + ' 26,' + (distance - 4) :
+                'M30,' + (-distance) + ' Q-10,' + Math.round(-distance / 2) + ' 26,4';
+            path.setAttribute('d', curve);
+            svg.style.display = '';
+        } catch(err) {
+            return;
+        }
+    });
+};
+
+HtmlFormatter.prototype.rootBegin = function(context, type, nodeType) {
+    var nodeClass = 'jsondiffpatch-' + type +
+        (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');
+    context.out('<div class="jsondiffpatch-delta ' + nodeClass + '">');
+};
+
+HtmlFormatter.prototype.rootEnd = function(context) {
+    context.out('</div>' + (context.hasArrows ?
+        ('<script type="text/javascript">setTimeout(' +
+            adjustArrows.toString() +
+            ',10);</script>') : ''));
+};
+
+HtmlFormatter.prototype.nodeBegin = function(context, key, leftKey, type, nodeType) {
+    var nodeClass = 'jsondiffpatch-' + type +
+        (nodeType ? ' jsondiffpatch-child-node-type-' + nodeType : '');
+    context.out('<li class="' + nodeClass + '" data-key="' + leftKey + '">' +
+        '<div class="jsondiffpatch-property-name">' + leftKey + '</div>');
+};
+
+
+HtmlFormatter.prototype.nodeEnd = function(context) {
+    context.out('</li>');
+};
+
+/* jshint camelcase: false */
+
+HtmlFormatter.prototype.format_unchanged = function(context, delta, left) {
+    if (typeof left === 'undefined') { return; }
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatValue(context, left);
+    context.out('</div>');
+};
+
+HtmlFormatter.prototype.format_movedestination = function(context, delta, left) {
+    if (typeof left === 'undefined') { return; }
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatValue(context, left);
+    context.out('</div>');
+};
+
+HtmlFormatter.prototype.format_node = function(context, delta, left) {
+    // recurse
+    var nodeType = (delta._t === 'a') ? 'array': 'object';
+    context.out('<ul class="jsondiffpatch-node jsondiffpatch-node-type-' + nodeType + '">');
+    this.formatDeltaChildren(context, delta, left);
+    context.out('</ul>');
+};
+
+HtmlFormatter.prototype.format_added = function(context, delta) {
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatValue(context, delta[0]);
+    context.out('</div>');
+};
+
+HtmlFormatter.prototype.format_modified = function(context, delta) {
+    context.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">');
+    this.formatValue(context, delta[0]);
+    context.out('</div>' +
+        '<div class="jsondiffpatch-value jsondiffpatch-right-value">');
+    this.formatValue(context, delta[1]);
+    context.out('</div>');
+};
+
+HtmlFormatter.prototype.format_deleted = function(context, delta) {
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatValue(context, delta[0]);
+    context.out('</div>');
+};
+
+HtmlFormatter.prototype.format_moved = function(context, delta) {
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatValue(context, delta[0]);
+    context.out('</div><div class="jsondiffpatch-moved-destination">' + delta[1] + '</div>');
+
+    // draw an SVG arrow from here to move destination
+    context.out(
+        /*jshint multistr: true */
+        '<div class="jsondiffpatch-arrow" style="position: relative; left: -34px;">\
+        <svg width="30" height="60" style="position: absolute; display: none;">\
+        <defs>\
+            <marker id="markerArrow" markerWidth="8" markerHeight="8" refx="2" refy="4"\
+                   orient="auto" markerUnits="userSpaceOnUse">\
+                <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" />\
+            </marker>\
+        </defs>\
+        <path d="M30,0 Q-10,25 26,50" style="stroke: #88f; stroke-width: 2px; fill: none;\
+        stroke-opacity: 0.5; marker-end: url(#markerArrow);"></path>\
+        </svg>\
+        </div>');
+    context.hasArrows = true;
+};
+
+HtmlFormatter.prototype.format_textdiff = function(context, delta) {
+    context.out('<div class="jsondiffpatch-value">');
+    this.formatTextDiffString(context, delta[0]);
+    context.out('</div>');
+};
+
+/* jshint camelcase: true */
+
+var showUnchanged = function(show, node, delay) {
+    var el = node || document.body;
+    var prefix = 'jsondiffpatch-unchanged-';
+    var classes = {
+        showing: prefix + 'showing',
+        hiding: prefix + 'hiding',
+        visible: prefix + 'visible',
+        hidden: prefix + 'hidden',
+    };
+    var list = el.classList;
+    if (!list) { return; }
+    if (!delay) {
+        list.remove(classes.showing);
+        list.remove(classes.hiding);
+        list.remove(classes.visible);
+        list.remove(classes.hidden);
+        if (show === false) {
+            list.add(classes.hidden);
+        }
+        return;
+    }
+    if (show === false) {
+        list.remove(classes.showing);
+        list.add(classes.visible);
+        setTimeout(function(){
+            list.add(classes.hiding);
+        }, 10);
+    } else {
+        list.remove(classes.hiding);
+        list.add(classes.showing);
+        list.remove(classes.hidden);
+    }
+    var intervalId = setInterval(function(){
+        adjustArrows(el);
+    }, 100);
+    setTimeout(function(){
+        list.remove(classes.showing);
+        list.remove(classes.hiding);
+        if (show === false) {
+            list.add(classes.hidden);
+            list.remove(classes.visible);
+        } else {
+            list.add(classes.visible);
+            list.remove(classes.hidden);
+        }
+        setTimeout(function(){
+            list.remove(classes.visible);
+            clearInterval(intervalId);
+        }, delay + 400);
+    }, delay);
+};
+
+var hideUnchanged = function(node, delay) {
+    return showUnchanged(false, node, delay);
+};
+
+exports.HtmlFormatter = HtmlFormatter;
+
+exports.showUnchanged = showUnchanged;
+
+exports.hideUnchanged = hideUnchanged;
+
+var defaultInstance;
+
+exports.format = function(delta, left) {
+    if (!defaultInstance) {
+        defaultInstance = new HtmlFormatter();
+    }
+    return defaultInstance.format(delta, left);
+};
\ No newline at end of file
diff --git a/src/formatters/index.js b/src/formatters/index.js
new file mode 100644
index 0000000..a67fc1b
--- /dev/null
+++ b/src/formatters/index.js
@@ -0,0 +1,8 @@
+
+exports.html = require('./html');
+exports.annotated = require('./annotated');
+
+var inNode = typeof process !== 'undefined' && typeof process.execPath === 'string';
+if (inNode) {
+	exports.console = require('./' + 'console');
+}
\ No newline at end of file
diff --git a/src/main.js b/src/main.js
new file mode 100644
index 0000000..4731b80
--- /dev/null
+++ b/src/main.js
@@ -0,0 +1,50 @@
+
+var DiffPatcher = require('./diffpatcher').DiffPatcher;
+exports.DiffPatcher = DiffPatcher;
+
+exports.create = function(options){
+	return new DiffPatcher(options);
+};
+
+exports.dateReviver = require('./date-reviver');
+
+var defaultInstance;
+
+exports.diff = function() {
+	if (!defaultInstance) {
+		defaultInstance = new DiffPatcher();
+	}
+	return defaultInstance.diff.apply(defaultInstance, arguments);
+};
+
+exports.patch = function() {
+	if (!defaultInstance) {
+		defaultInstance = new DiffPatcher();
+	}
+	return defaultInstance.patch.apply(defaultInstance, arguments);
+};
+
+exports.unpatch = function() {
+	if (!defaultInstance) {
+		defaultInstance = new DiffPatcher();
+	}
+	return defaultInstance.unpatch.apply(defaultInstance, arguments);
+};
+
+exports.reverse = function() {
+	if (!defaultInstance) {
+		defaultInstance = new DiffPatcher();
+	}
+	return defaultInstance.reverse.apply(defaultInstance, arguments);
+};
+
+var inNode = typeof process !== 'undefined' && typeof process.execPath === 'string';
+if (inNode) {
+	var formatters = require('./formatters' + '/index');
+	exports.formatters = formatters;
+	// shortcut for console
+	exports.console = formatters.console;
+} else {
+	exports.homepage = '{{package-homepage}}';
+	exports.version = '{{package-version}}';
+}
diff --git a/src/pipe.js b/src/pipe.js
new file mode 100644
index 0000000..7b5e9c8
--- /dev/null
+++ b/src/pipe.js
@@ -0,0 +1,111 @@
+
+var Pipe = function Pipe(name){
+    this.name = name;
+    this.filters = [];
+};
+
+Pipe.prototype.process = function(input) {
+    if (!this.processor) {
+        throw new Error('add this pipe to a processor before using it');
+    }
+    var debug = this.debug;
+    var length = this.filters.length;
+    var context = input;
+    for (var index = 0; index < length; index++) {
+        var filter = this.filters[index];
+        if (debug) {
+            this.log('filter: ' + filter.filterName);
+        }
+        filter(context);
+        if (typeof context === 'object' && context.exiting) {
+            context.exiting = false;
+            break;
+        }
+    }
+    if (!context.next && this.resultCheck) {
+        this.resultCheck(context);
+    }
+};
+
+Pipe.prototype.log = function(msg) {
+    console.log('[jsondiffpatch] ' + this.name + ' pipe, ' + msg);
+};
+
+Pipe.prototype.append = function() {
+    this.filters.push.apply(this.filters, arguments);
+    return this;
+};
+
+Pipe.prototype.prepend = function() {
+    this.filters.unshift.apply(this.filters, arguments);
+    return this;
+};
+
+Pipe.prototype.indexOf = function(filterName) {
+    if (!filterName) {
+        throw new Error('a filter name is required');
+    }
+    for (var index = 0; index < this.filters.length; index++) {
+        var filter = this.filters[index];
+        if (filter.filterName === filterName) {
+            return index;
+        }
+    }
+    throw new Error('filter not found: ' + filterName);
+};
+
+Pipe.prototype.list = function() {
+    var names = [];
+    for (var index = 0; index < this.filters.length; index++) {
+        var filter = this.filters[index];
+        names.push(filter.filterName);
+    }
+    return names;
+};
+
+Pipe.prototype.after = function(filterName) {
+    var index = this.indexOf(filterName);
+    var params = Array.prototype.slice.call(arguments, 1);
+    if (!params.length) {
+        throw new Error('a filter is required');
+    }
+    params.unshift(index + 1, 0);
+    Array.prototype.splice.apply(this.filters, params);
+    return this;
+};
+
+Pipe.prototype.before = function(filterName) {
+    var index = this.indexOf(filterName);
+    var params = Array.prototype.slice.call(arguments, 1);
+    if (!params.length) {
+        throw new Error('a filter is required');
+    }
+    params.unshift(index, 0);
+    Array.prototype.splice.apply(this.filters, params);
+    return this;
+};
+
+Pipe.prototype.clear = function() {
+    this.filters.length = 0;
+    return this;
+};
+
+Pipe.prototype.shouldHaveResult = function(should) {
+    if (should === false) {
+        this.resultCheck = null;
+        return;
+    }
+    if (this.resultCheck) { return; }
+    var pipe = this;
+    this.resultCheck = function(context) {
+        if (!context.hasResult) {
+            console.log(context);
+            var error = new Error(pipe.name + ' failed');
+            error.noResult = true;
+            throw error;
+        }
+    };
+    return this;
+};
+
+exports.Pipe = Pipe;
\ No newline at end of file
diff --git a/src/processor.js b/src/processor.js
new file mode 100644
index 0000000..02b7eb2
--- /dev/null
+++ b/src/processor.js
@@ -0,0 +1,60 @@
+
+var Processor = function Processor(options){
+	this.selfOptions = options;
+	this.pipes = {};
+};
+
+Processor.prototype.options = function(options) {
+	if (options) {
+		this.selfOptions = options;
+	}
+	return this.selfOptions;
+};
+
+Processor.prototype.pipe = function(name, pipe) {
+	if (typeof name === 'string') {
+		if (typeof pipe === 'undefined') {
+			return this.pipes[name];
+		} else {
+			this.pipes[name] = pipe;
+		}
+	}
+	if (name && name.name) {
+		pipe = name;
+		if (pipe.processor === this) { return pipe; }
+		this.pipes[pipe.name] = pipe;
+	}
+	pipe.processor = this;
+	return pipe;
+};
+
+Processor.prototype.process = function(input, pipe) {
+	var context = input;
+	context.options = this.options();
+	var nextPipe = pipe || input.pipe || 'default';
+	var lastPipe, lastContext;
+	while (nextPipe) {
+		if (typeof context.nextAfterChildren !== 'undefined') {
+			// children processed and coming back to parent
+			context.next = context.nextAfterChildren;
+			context.nextAfterChildren = null;
+		}
+
+		if (typeof nextPipe === 'string') {
+			nextPipe = this.pipe(nextPipe);
+		}
+		nextPipe.process(context);
+		lastContext = context;
+		lastPipe = nextPipe;
+		nextPipe = null;
+		if (context) {
+			if (context.next) {
+				context = context.next;
+				nextPipe = lastContext.nextPipe || context.pipe || lastPipe;
+			}
+		}
+	}
+	return context.hasResult ? context.result : undefined;
+};
+
+exports.Processor = Processor;
diff --git a/test-external/expect.js b/test-external/expect.js
new file mode 100644
index 0000000..b1e921d
--- /dev/null
+++ b/test-external/expect.js
@@ -0,0 +1,1284 @@
+(function (global, module) {
+
+  var exports = module.exports;
+
+  /**
+   * Exports.
+   */
+
+  module.exports = expect;
+  expect.Assertion = Assertion;
+
+  /**
+   * Exports version.
+   */
+
+  expect.version = '0.3.1';
+
+  /**
+   * Possible assertion flags.
+   */
+
+  var flags = {
+      not: ['to', 'be', 'have', 'include', 'only']
+    , to: ['be', 'have', 'include', 'only', 'not']
+    , only: ['have']
+    , have: ['own']
+    , be: ['an']
+  };
+
+  function expect (obj) {
+    return new Assertion(obj);
+  }
+
+  /**
+   * Constructor
+   *
+   * @api private
+   */
+
+  function Assertion (obj, flag, parent) {
+    this.obj = obj;
+    this.flags = {};
+
+    if (undefined != parent) {
+      this.flags[flag] = true;
+
+      for (var i in parent.flags) {
+        if (parent.flags.hasOwnProperty(i)) {
+          this.flags[i] = true;
+        }
+      }
+    }
+
+    var $flags = flag ? flags[flag] : keys(flags)
+      , self = this;
+
+    if ($flags) {
+      for (var i = 0, l = $flags.length; i < l; i++) {
+        // avoid recursion
+        if (this.flags[$flags[i]]) continue;
+
+        var name = $flags[i]
+          , assertion = new Assertion(this.obj, name, this)
+
+        if ('function' == typeof Assertion.prototype[name]) {
+          // clone the function, make sure we dont touch the prot reference
+          var old = this[name];
+          this[name] = function () {
+            return old.apply(self, arguments);
+          };
+
+          for (var fn in Assertion.prototype) {
+            if (Assertion.prototype.hasOwnProperty(fn) && fn != name) {
+              this[name][fn] = bind(assertion[fn], assertion);
+            }
+          }
+        } else {
+          this[name] = assertion;
+        }
+      }
+    }
+  }
+
+  /**
+   * Performs an assertion
+   *
+   * @api private
+   */
+
+  Assertion.prototype.assert = function (truth, msg, error, expected) {
+    var msg = this.flags.not ? error : msg
+      , ok = this.flags.not ? !truth : truth
+      , err;
+
+    if (!ok) {
+      err = new Error(msg.call(this));
+      if (arguments.length > 3) {
+        err.actual = this.obj;
+        err.expected = expected;
+        err.showDiff = true;
+      }
+      throw err;
+    }
+
+    this.and = new Assertion(this.obj);
+  };
+
+  /**
+   * Check if the value is truthy
+   *
+   * @api public
+   */
+
+  Assertion.prototype.ok = function () {
+    this.assert(
+        !!this.obj
+      , function(){ return 'expected ' + i(this.obj) + ' to be truthy' }
+      , function(){ return 'expected ' + i(this.obj) + ' to be falsy' });
+  };
+
+  /**
+   * Creates an anonymous function which calls fn with arguments.
+   *
+   * @api public
+   */
+
+  Assertion.prototype.withArgs = function() {
+    expect(this.obj).to.be.a('function');
+    var fn = this.obj;
+    var args = Array.prototype.slice.call(arguments);
+    return expect(function() { fn.apply(null, args); });
+  };
+
+  /**
+   * Assert that the function throws.
+   *
+   * @param {Function|RegExp} callback, or regexp to match error string against
+   * @api public
+   */
+
+  Assertion.prototype.throwError =
+  Assertion.prototype.throwException = function (fn) {
+    expect(this.obj).to.be.a('function');
+
+    var thrown = false
+      , not = this.flags.not;
+
+    try {
+      this.obj();
+    } catch (e) {
+      if (isRegExp(fn)) {
+        var subject = 'string' == typeof e ? e : e.message;
+        if (not) {
+          expect(subject).to.not.match(fn);
+        } else {
+          expect(subject).to.match(fn);
+        }
+      } else if ('function' == typeof fn) {
+        fn(e);
+      }
+      thrown = true;
+    }
+
+    if (isRegExp(fn) && not) {
+      // in the presence of a matcher, ensure the `not` only applies to
+      // the matching.
+      this.flags.not = false;
+    }
+
+    var name = this.obj.name || 'fn';
+    this.assert(
+        thrown
+      , function(){ return 'expected ' + name + ' to throw an exception' }
+      , function(){ return 'expected ' + name + ' not to throw an exception' });
+  };
+
+  /**
+   * Checks if the array is empty.
+   *
+   * @api public
+   */
+
+  Assertion.prototype.empty = function () {
+    var expectation;
+
+    if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) {
+      if ('number' == typeof this.obj.length) {
+        expectation = !this.obj.length;
+      } else {
+        expectation = !keys(this.obj).length;
+      }
+    } else {
+      if ('string' != typeof this.obj) {
+        expect(this.obj).to.be.an('object');
+      }
+
+      expect(this.obj).to.have.property('length');
+      expectation = !this.obj.length;
+    }
+
+    this.assert(
+        expectation
+      , function(){ return 'expected ' + i(this.obj) + ' to be empty' }
+      , function(){ return 'expected ' + i(this.obj) + ' to not be empty' });
+    return this;
+  };
+
+  /**
+   * Checks if the obj exactly equals another.
+   *
+   * @api public
+   */
+
+  Assertion.prototype.be =
+  Assertion.prototype.equal = function (obj) {
+    this.assert(
+        obj === this.obj
+      , function(){ return 'expected ' + i(this.obj) + ' to equal ' + i(obj) }
+      , function(){ return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) });
+    return this;
+  };
+
+  /**
+   * Checks if the obj sortof equals another.
+   *
+   * @api public
+   */
+
+  Assertion.prototype.eql = function (obj) {
+    this.assert(
+        expect.eql(this.obj, obj)
+      , function(){ return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) }
+      , function(){ return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) }
+      , obj);
+    return this;
+  };
+
+  /**
+   * Assert within start to finish (inclusive).
+   *
+   * @param {Number} start
+   * @param {Number} finish
+   * @api public
+   */
+
+  Assertion.prototype.within = function (start, finish) {
+    var range = start + '..' + finish;
+    this.assert(
+        this.obj >= start && this.obj <= finish
+      , function(){ return 'expected ' + i(this.obj) + ' to be within ' + range }
+      , function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range });
+    return this;
+  };
+
+  /**
+   * Assert typeof / instance of
+   *
+   * @api public
+   */
+
+  Assertion.prototype.a =
+  Assertion.prototype.an = function (type) {
+    if ('string' == typeof type) {
+      // proper english in error msg
+      var n = /^[aeiou]/.test(type) ? 'n' : '';
+
+      // typeof with support for 'array'
+      this.assert(
+          'array' == type ? isArray(this.obj) :
+            'regexp' == type ? isRegExp(this.obj) :
+              'object' == type
+                ? 'object' == typeof this.obj && null !== this.obj
+                : type == typeof this.obj
+        , function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type }
+        , function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type });
+    } else {
+      // instanceof
+      var name = type.name || 'supplied constructor';
+      this.assert(
+          this.obj instanceof type
+        , function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name }
+        , function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name });
+    }
+
+    return this;
+  };
+
+  /**
+   * Assert numeric value above _n_.
+   *
+   * @param {Number} n
+   * @api public
+   */
+
+  Assertion.prototype.greaterThan =
+  Assertion.prototype.above = function (n) {
+    this.assert(
+        this.obj > n
+      , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }
+      , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n });
+    return this;
+  };
+
+  /**
+   * Assert numeric value below _n_.
+   *
+   * @param {Number} n
+   * @api public
+   */
+
+  Assertion.prototype.lessThan =
+  Assertion.prototype.below = function (n) {
+    this.assert(
+        this.obj < n
+      , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }
+      , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n });
+    return this;
+  };
+
+  /**
+   * Assert string value matches _regexp_.
+   *
+   * @param {RegExp} regexp
+   * @api public
+   */
+
+  Assertion.prototype.match = function (regexp) {
+    this.assert(
+        regexp.exec(this.obj)
+      , function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp }
+      , function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp });
+    return this;
+  };
+
+  /**
+   * Assert property "length" exists and has value of _n_.
+   *
+   * @param {Number} n
+   * @api public
+   */
+
+  Assertion.prototype.length = function (n) {
+    expect(this.obj).to.have.property('length');
+    var len = this.obj.length;
+    this.assert(
+        n == len
+      , function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len }
+      , function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len });
+    return this;
+  };
+
+  /**
+   * Assert property _name_ exists, with optional _val_.
+   *
+   * @param {String} name
+   * @param {Mixed} val
+   * @api public
+   */
+
+  Assertion.prototype.property = function (name, val) {
+    if (this.flags.own) {
+      this.assert(
+          Object.prototype.hasOwnProperty.call(this.obj, name)
+        , function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) }
+        , function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) });
+      return this;
+    }
+
+    if (this.flags.not && undefined !== val) {
+      if (undefined === this.obj[name]) {
+        throw new Error(i(this.obj) + ' has no property ' + i(name));
+      }
+    } else {
+      var hasProp;
+      try {
+        hasProp = name in this.obj
+      } catch (e) {
+        hasProp = undefined !== this.obj[name]
+      }
+
+      this.assert(
+          hasProp
+        , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) }
+        , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) });
+    }
+
+    if (undefined !== val) {
+      this.assert(
+          val === this.obj[name]
+        , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name)
+          + ' of ' + i(val) + ', but got ' + i(this.obj[name]) }
+        , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name)
+          + ' of ' + i(val) });
+    }
+
+    this.obj = this.obj[name];
+    return this;
+  };
+
+  /**
+   * Assert that the array contains _obj_ or string contains _obj_.
+   *
+   * @param {Mixed} obj|string
+   * @api public
+   */
+
+  Assertion.prototype.string =
+  Assertion.prototype.contain = function (obj) {
+    if ('string' == typeof this.obj) {
+      this.assert(
+          ~this.obj.indexOf(obj)
+        , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
+        , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
+    } else {
+      this.assert(
+          ~indexOf(this.obj, obj)
+        , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
+        , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
+    }
+    return this;
+  };
+
+  /**
+   * Assert exact keys or inclusion of keys by using
+   * the `.own` modifier.
+   *
+   * @param {Array|String ...} keys
+   * @api public
+   */
+
+  Assertion.prototype.key =
+  Assertion.prototype.keys = function ($keys) {
+    var str
+      , ok = true;
+
+    $keys = isArray($keys)
+      ? $keys
+      : Array.prototype.slice.call(arguments);
+
+    if (!$keys.length) throw new Error('keys required');
+
+    var actual = keys(this.obj)
+      , len = $keys.length;
+
+    // Inclusion
+    ok = every($keys, function (key) {
+      return ~indexOf(actual, key);
+    });
+
+    // Strict
+    if (!this.flags.not && this.flags.only) {
+      ok = ok && $keys.length == actual.length;
+    }
+
+    // Key string
+    if (len > 1) {
+      $keys = map($keys, function (key) {
+        return i(key);
+      });
+      var last = $keys.pop();
+      str = $keys.join(', ') + ', and ' + last;
+    } else {
+      str = i($keys[0]);
+    }
+
+    // Form
+    str = (len > 1 ? 'keys ' : 'key ') + str;
+
+    // Have / include
+    str = (!this.flags.only ? 'include ' : 'only have ') + str;
+
+    // Assertion
+    this.assert(
+        ok
+      , function(){ return 'expected ' + i(this.obj) + ' to ' + str }
+      , function(){ return 'expected ' + i(this.obj) + ' to not ' + str });
+
+    return this;
+  };
+
+  /**
+   * Assert a failure.
+   *
+   * @param {String ...} custom message
+   * @api public
+   */
+  Assertion.prototype.fail = function (msg) {
+    var error = function() { return msg || "explicit failure"; }
+    this.assert(false, error, error);
+    return this;
+  };
+
+  /**
+   * Function bind implementation.
+   */
+
+  function bind (fn, scope) {
+    return function () {
+      return fn.apply(scope, arguments);
+    }
+  }
+
+  /**
+   * Array every compatibility
+   *
+   * @see bit.ly/5Fq1N2
+   * @api public
+   */
+
+  function every (arr, fn, thisObj) {
+    var scope = thisObj || global;
+    for (var i = 0, j = arr.length; i < j; ++i) {
+      if (!fn.call(scope, arr[i], i, arr)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Array indexOf compatibility.
+   *
+   * @see bit.ly/a5Dxa2
+   * @api public
+   */
+
+  function indexOf (arr, o, i) {
+    if (Array.prototype.indexOf) {
+      return Array.prototype.indexOf.call(arr, o, i);
+    }
+
+    if (arr.length === undefined) {
+      return -1;
+    }
+
+    for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0
+        ; i < j && arr[i] !== o; i++);
+
+    return j <= i ? -1 : i;
+  }
+
+  // https://gist.github.com/1044128/
+  var getOuterHTML = function(element) {
+    if ('outerHTML' in element) return element.outerHTML;
+    var ns = "http://www.w3.org/1999/xhtml";
+    var container = document.createElementNS(ns, '_');
+    var xmlSerializer = new XMLSerializer();
+    var html;
+    if (document.xmlVersion) {
+      return xmlSerializer.serializeToString(element);
+    } else {
+      container.appendChild(element.cloneNode(false));
+      html = container.innerHTML.replace('><', '>' + element.innerHTML + '<');
+      container.innerHTML = '';
+      return html;
+    }
+  };
+
+  // Returns true if object is a DOM element.
+  var isDOMElement = function (object) {
+    if (typeof HTMLElement === 'object') {
+      return object instanceof HTMLElement;
+    } else {
+      return object &&
+        typeof object === 'object' &&
+        object.nodeType === 1 &&
+        typeof object.nodeName === 'string';
+    }
+  };
+
+  /**
+   * Inspects an object.
+   *
+   * @see taken from node.js `util` module (copyright Joyent, MIT license)
+   * @api private
+   */
+
+  function i (obj, showHidden, depth) {
+    var seen = [];
+
+    function stylize (str) {
+      return str;
+    }
+
+    function format (value, recurseTimes) {
+      // Provide a hook for user-specified inspect functions.
+      // Check that value is an object with an inspect function on it
+      if (value && typeof value.inspect === 'function' &&
+          // Filter out the util module, it's inspect function is special
+          value !== exports &&
+          // Also filter out any prototype objects using the circular check.
+          !(value.constructor && value.constructor.prototype === value)) {
+        return value.inspect(recurseTimes);
+      }
+
+      // Primitive types cannot have properties
+      switch (typeof value) {
+        case 'undefined':
+          return stylize('undefined', 'undefined');
+
+        case 'string':
+          var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '')
+                                                   .replace(/'/g, "\\'")
+                                                   .replace(/\\"/g, '"') + '\'';
+          return stylize(simple, 'string');
+
+        case 'number':
+          return stylize('' + value, 'number');
+
+        case 'boolean':
+          return stylize('' + value, 'boolean');
+      }
+      // For some reason typeof null is "object", so special case here.
+      if (value === null) {
+        return stylize('null', 'null');
+      }
+
+      if (isDOMElement(value)) {
+        return getOuterHTML(value);
+      }
+
+      // Look up the keys of the object.
+      var visible_keys = keys(value);
+      var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys;
+
+      // Functions without properties can be shortcutted.
+      if (typeof value === 'function' && $keys.length === 0) {
+        if (isRegExp(value)) {
+          return stylize('' + value, 'regexp');
+        } else {
+          var name = value.name ? ': ' + value.name : '';
+          return stylize('[Function' + name + ']', 'special');
+        }
+      }
+
+      // Dates without properties can be shortcutted
+      if (isDate(value) && $keys.length === 0) {
+        return stylize(value.toUTCString(), 'date');
+      }
+      
+      // Error objects can be shortcutted
+      if (value instanceof Error) {
+        return stylize("["+value.toString()+"]", 'Error');
+      }
+
+      var base, type, braces;
+      // Determine the object type
+      if (isArray(value)) {
+        type = 'Array';
+        braces = ['[', ']'];
+      } else {
+        type = 'Object';
+        braces = ['{', '}'];
+      }
+
+      // Make functions say that they are functions
+      if (typeof value === 'function') {
+        var n = value.name ? ': ' + value.name : '';
+        base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
+      } else {
+        base = '';
+      }
+
+      // Make dates with properties first say the date
+      if (isDate(value)) {
+        base = ' ' + value.toUTCString();
+      }
+
+      if ($keys.length === 0) {
+        return braces[0] + base + braces[1];
+      }
+
+      if (recurseTimes < 0) {
+        if (isRegExp(value)) {
+          return stylize('' + value, 'regexp');
+        } else {
+          return stylize('[Object]', 'special');
+        }
+      }
+
+      seen.push(value);
+
+      var output = map($keys, function (key) {
+        var name, str;
+        if (value.__lookupGetter__) {
+          if (value.__lookupGetter__(key)) {
+            if (value.__lookupSetter__(key)) {
+              str = stylize('[Getter/Setter]', 'special');
+            } else {
+              str = stylize('[Getter]', 'special');
+            }
+          } else {
+            if (value.__lookupSetter__(key)) {
+              str = stylize('[Setter]', 'special');
+            }
+          }
+        }
+        if (indexOf(visible_keys, key) < 0) {
+          name = '[' + key + ']';
+        }
+        if (!str) {
+          if (indexOf(seen, value[key]) < 0) {
+            if (recurseTimes === null) {
+              str = format(value[key]);
+            } else {
+              str = format(value[key], recurseTimes - 1);
+            }
+            if (str.indexOf('\n') > -1) {
+              if (isArray(value)) {
+                str = map(str.split('\n'), function (line) {
+                  return '  ' + line;
+                }).join('\n').substr(2);
+              } else {
+                str = '\n' + map(str.split('\n'), function (line) {
+                  return '   ' + line;
+                }).join('\n');
+              }
+            }
+          } else {
+            str = stylize('[Circular]', 'special');
+          }
+        }
+        if (typeof name === 'undefined') {
+          if (type === 'Array' && key.match(/^\d+$/)) {
+            return str;
+          }
+          name = json.stringify('' + key);
+          if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+            name = name.substr(1, name.length - 2);
+            name = stylize(name, 'name');
+          } else {
+            name = name.replace(/'/g, "\\'")
+                       .replace(/\\"/g, '"')
+                       .replace(/(^"|"$)/g, "'");
+            name = stylize(name, 'string');
+          }
+        }
+
+        return name + ': ' + str;
+      });
+
+      seen.pop();
+
+      var numLinesEst = 0;
+      var length = reduce(output, function (prev, cur) {
+        numLinesEst++;
+        if (indexOf(cur, '\n') >= 0) numLinesEst++;
+        return prev + cur.length + 1;
+      }, 0);
+
+      if (length > 50) {
+        output = braces[0] +
+                 (base === '' ? '' : base + '\n ') +
+                 ' ' +
+                 output.join(',\n  ') +
+                 ' ' +
+                 braces[1];
+
+      } else {
+        output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+      }
+
+      return output;
+    }
+    return format(obj, (typeof depth === 'undefined' ? 2 : depth));
+  }
+
+  expect.stringify = i;
+
+  function isArray (ar) {
+    return Object.prototype.toString.call(ar) === '[object Array]';
+  }
+
+  function isRegExp(re) {
+    var s;
+    try {
+      s = '' + re;
+    } catch (e) {
+      return false;
+    }
+
+    return re instanceof RegExp || // easy case
+           // duck-type for context-switching evalcx case
+           typeof(re) === 'function' &&
+           re.constructor.name === 'RegExp' &&
+           re.compile &&
+           re.test &&
+           re.exec &&
+           s.match(/^\/.*\/[gim]{0,3}$/);
+  }
+
+  function isDate(d) {
+    return d instanceof Date;
+  }
+
+  function keys (obj) {
+    if (Object.keys) {
+      return Object.keys(obj);
+    }
+
+    var keys = [];
+
+    for (var i in obj) {
+      if (Object.prototype.hasOwnProperty.call(obj, i)) {
+        keys.push(i);
+      }
+    }
+
+    return keys;
+  }
+
+  function map (arr, mapper, that) {
+    if (Array.prototype.map) {
+      return Array.prototype.map.call(arr, mapper, that);
+    }
+
+    var other= new Array(arr.length);
+
+    for (var i= 0, n = arr.length; i<n; i++)
+      if (i in arr)
+        other[i] = mapper.call(that, arr[i], i, arr);
+
+    return other;
+  }
+
+  function reduce (arr, fun) {
+    if (Array.prototype.reduce) {
+      return Array.prototype.reduce.apply(
+          arr
+        , Array.prototype.slice.call(arguments, 1)
+      );
+    }
+
+    var len = +this.length;
+
+    if (typeof fun !== "function")
+      throw new TypeError();
+
+    // no value to return if no initial value and an empty array
+    if (len === 0 && arguments.length === 1)
+      throw new TypeError();
+
+    var i = 0;
+    if (arguments.length >= 2) {
+      var rv = arguments[1];
+    } else {
+      do {
+        if (i in this) {
+          rv = this[i++];
+          break;
+        }
+
+        // if array contains no values, no initial value to return
+        if (++i >= len)
+          throw new TypeError();
+      } while (true);
+    }
+
+    for (; i < len; i++) {
+      if (i in this)
+        rv = fun.call(null, rv, this[i], i, this);
+    }
+
+    return rv;
+  }
+
+  /**
+   * Asserts deep equality
+   *
+   * @see taken from node.js `assert` module (copyright Joyent, MIT license)
+   * @api private
+   */
+
+  expect.eql = function eql(actual, expected) {
+    // 7.1. All identical values are equivalent, as determined by ===.
+    if (actual === expected) {
+      return true;
+    } else if ('undefined' != typeof Buffer
+      && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
+      if (actual.length != expected.length) return false;
+
+      for (var i = 0; i < actual.length; i++) {
+        if (actual[i] !== expected[i]) return false;
+      }
+
+      return true;
+
+      // 7.2. If the expected value is a Date object, the actual value is
+      // equivalent if it is also a Date object that refers to the same time.
+    } else if (actual instanceof Date && expected instanceof Date) {
+      return actual.getTime() === expected.getTime();
+
+      // 7.3. Other pairs that do not both pass typeof value == "object",
+      // equivalence is determined by ==.
+    } else if (typeof actual != 'object' && typeof expected != 'object') {
+      return actual == expected;
+    // If both are regular expression use the special `regExpEquiv` method
+    // to determine equivalence.
+    } else if (isRegExp(actual) && isRegExp(expected)) {
+      return regExpEquiv(actual, expected);
+    // 7.4. For all other Object pairs, including Array objects, equivalence is
+    // determined by having the same number of owned properties (as verified
+    // with Object.prototype.hasOwnProperty.call), the same set of keys
+    // (although not necessarily the same order), equivalent values for every
+    // corresponding key, and an identical "prototype" property. Note: this
+    // accounts for both named and indexed properties on Arrays.
+    } else {
+      return objEquiv(actual, expected);
+    }
+  };
+
+  function isUndefinedOrNull (value) {
+    return value === null || value === undefined;
+  }
+
+  function isArguments (object) {
+    return Object.prototype.toString.call(object) == '[object Arguments]';
+  }
+
+  function regExpEquiv (a, b) {
+    return a.source === b.source && a.global === b.global &&
+           a.ignoreCase === b.ignoreCase && a.multiline === b.multiline;
+  }
+
+  function objEquiv (a, b) {
+    if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
+      return false;
+    // an identical "prototype" property.
+    if (a.prototype !== b.prototype) return false;
+    //~~~I've managed to break Object.keys through screwy arguments passing.
+    //   Converting to array solves the problem.
+    if (isArguments(a)) {
+      if (!isArguments(b)) {
+        return false;
+      }
+      a = pSlice.call(a);
+      b = pSlice.call(b);
+      return expect.eql(a, b);
+    }
+    try{
+      var ka = keys(a),
+        kb = keys(b),
+        key, i;
+    } catch (e) {//happens when one is a string literal and the other isn't
+      return false;
+    }
+    // having the same number of owned properties (keys incorporates hasOwnProperty)
+    if (ka.length != kb.length)
+      return false;
+    //the same set of keys (although not necessarily the same order),
+    ka.sort();
+    kb.sort();
+    //~~~cheap key test
+    for (i = ka.length - 1; i >= 0; i--) {
+      if (ka[i] != kb[i])
+        return false;
+    }
+    //equivalent values for every corresponding key, and
+    //~~~possibly expensive deep test
+    for (i = ka.length - 1; i >= 0; i--) {
+      key = ka[i];
+      if (!expect.eql(a[key], b[key]))
+         return false;
+    }
+    return true;
+  }
+
+  var json = (function () {
+    "use strict";
+
+    if ('object' == typeof JSON && JSON.parse && JSON.stringify) {
+      return {
+          parse: nativeJSON.parse
+        , stringify: nativeJSON.stringify
+      }
+    }
+
+    var JSON = {};
+
+    function f(n) {
+        // Format integers to have at least two digits.
+        return n < 10 ? '0' + n : n;
+    }
+
+    function date(d, key) {
+      return isFinite(d.valueOf()) ?
+          d.getUTCFullYear()     + '-' +
+          f(d.getUTCMonth() + 1) + '-' +
+          f(d.getUTCDate())      + 'T' +
+          f(d.getUTCHours())     + ':' +
+          f(d.getUTCMinutes())   + ':' +
+          f(d.getUTCSeconds())   + 'Z' : null;
+    }
+
+    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        gap,
+        indent,
+        meta = {    // table of character substitutions
+            '\b': '\\b',
+            '\t': '\\t',
+            '\n': '\\n',
+            '\f': '\\f',
+            '\r': '\\r',
+            '"' : '\\"',
+            '\\': '\\\\'
+        },
+        rep;
+
+
+    function quote(string) {
+
+  // If the string contains no control characters, no quote characters, and no
+  // backslash characters, then we can safely slap some quotes around it.
+  // Otherwise we must also replace the offending characters with safe escape
+  // sequences.
+
+        escapable.lastIndex = 0;
+        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+            var c = meta[a];
+            return typeof c === 'string' ? c :
+                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+        }) + '"' : '"' + string + '"';
+    }
+
+
+    function str(key, holder) {
+
+  // Produce a string from holder[key].
+
+        var i,          // The loop counter.
+            k,          // The member key.
+            v,          // The member value.
+            length,
+            mind = gap,
+            partial,
+            value = holder[key];
+
+  // If the value has a toJSON method, call it to obtain a replacement value.
+
+        if (value instanceof Date) {
+            value = date(key);
+        }
+
+  // If we were called with a replacer function, then call the replacer to
+  // obtain a replacement value.
+
+        if (typeof rep === 'function') {
+            value = rep.call(holder, key, value);
+        }
+
+  // What happens next depends on the value's type.
+
+        switch (typeof value) {
+        case 'string':
+            return quote(value);
+
+        case 'number':
+
+  // JSON numbers must be finite. Encode non-finite numbers as null.
+
+            return isFinite(value) ? String(value) : 'null';
+
+        case 'boolean':
+        case 'null':
+
+  // If the value is a boolean or null, convert it to a string. Note:
+  // typeof null does not produce 'null'. The case is included here in
+  // the remote chance that this gets fixed someday.
+
+            return String(value);
+
+  // If the type is 'object', we might be dealing with an object or an array or
+  // null.
+
+        case 'object':
+
+  // Due to a specification blunder in ECMAScript, typeof null is 'object',
+  // so watch out for that case.
+
+            if (!value) {
+                return 'null';
+            }
+
+  // Make an array to hold the partial results of stringifying this object value.
+
+            gap += indent;
+            partial = [];
+
+  // Is the value an array?
+
+            if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+  // The value is an array. Stringify every element. Use null as a placeholder
+  // for non-JSON values.
+
+                length = value.length;
+                for (i = 0; i < length; i += 1) {
+                    partial[i] = str(i, value) || 'null';
+                }
+
+  // Join all of the elements together, separated with commas, and wrap them in
+  // brackets.
+
+                v = partial.length === 0 ? '[]' : gap ?
+                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
+                    '[' + partial.join(',') + ']';
+                gap = mind;
+                return v;
+            }
+
+  // If the replacer is an array, use it to select the members to be stringified.
+
+            if (rep && typeof rep === 'object') {
+                length = rep.length;
+                for (i = 0; i < length; i += 1) {
+                    if (typeof rep[i] === 'string') {
+                        k = rep[i];
+                        v = str(k, value);
+                        if (v) {
+                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
+                        }
+                    }
+                }
+            } else {
+
+  // Otherwise, iterate through all of the keys in the object.
+
+                for (k in value) {
+                    if (Object.prototype.hasOwnProperty.call(value, k)) {
+                        v = str(k, value);
+                        if (v) {
+                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
+                        }
+                    }
+                }
+            }
+
+  // Join all of the member texts together, separated with commas,
+  // and wrap them in braces.
+
+            v = partial.length === 0 ? '{}' : gap ?
+                '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
+                '{' + partial.join(',') + '}';
+            gap = mind;
+            return v;
+        }
+    }
+
+  // If the JSON object does not yet have a stringify method, give it one.
+
+    JSON.stringify = function (value, replacer, space) {
+
+  // The stringify method takes a value and an optional replacer, and an optional
+  // space parameter, and returns a JSON text. The replacer can be a function
+  // that can replace values, or an array of strings that will select the keys.
+  // A default replacer method can be provided. Use of the space parameter can
+  // produce text that is more easily readable.
+
+        var i;
+        gap = '';
+        indent = '';
+
+  // If the space parameter is a number, make an indent string containing that
+  // many spaces.
+
+        if (typeof space === 'number') {
+            for (i = 0; i < space; i += 1) {
+                indent += ' ';
+            }
+
+  // If the space parameter is a string, it will be used as the indent string.
+
+        } else if (typeof space === 'string') {
+            indent = space;
+        }
+
+  // If there is a replacer, it must be a function or an array.
+  // Otherwise, throw an error.
+
+        rep = replacer;
+        if (replacer && typeof replacer !== 'function' &&
+                (typeof replacer !== 'object' ||
+                typeof replacer.length !== 'number')) {
+            throw new Error('JSON.stringify');
+        }
+
+  // Make a fake root object containing our value under the key of ''.
+  // Return the result of stringifying the value.
+
+        return str('', {'': value});
+    };
+
+  // If the JSON object does not yet have a parse method, give it one.
+
+    JSON.parse = function (text, reviver) {
+    // The parse method takes a text and an optional reviver function, and returns
+    // a JavaScript value if the text is a valid JSON text.
+
+        var j;
+
+        function walk(holder, key) {
+
+    // The walk method is used to recursively walk the resulting structure so
+    // that modifications can be made.
+
+            var k, v, value = holder[key];
+            if (value && typeof value === 'object') {
+                for (k in value) {
+                    if (Object.prototype.hasOwnProperty.call(value, k)) {
+                        v = walk(value, k);
+                        if (v !== undefined) {
+                            value[k] = v;
+                        } else {
+                            delete value[k];
+                        }
+                    }
+                }
+            }
+            return reviver.call(holder, key, value);
+        }
+
+
+    // Parsing happens in four stages. In the first stage, we replace certain
+    // Unicode characters with escape sequences. JavaScript handles many characters
+    // incorrectly, either silently deleting them, or treating them as line endings.
+
+        text = String(text);
+        cx.lastIndex = 0;
+        if (cx.test(text)) {
+            text = text.replace(cx, function (a) {
+                return '\\u' +
+                    ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+            });
+        }
+
+    // In the second stage, we run the text against regular expressions that look
+    // for non-JSON patterns. We are especially concerned with '()' and 'new'
+    // because they can cause invocation, and '=' because it can cause mutation.
+    // But just to be safe, we want to reject all unexpected forms.
+
+    // We split the second stage into 4 regexp operations in order to work around
+    // crippling inefficiencies in IE's and Safari's regexp engines. First we
+    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+    // replace all simple value tokens with ']' characters. Third, we delete all
+    // open brackets that follow a colon or comma or that begin the text. Finally,
+    // we look to see that the remaining characters are only whitespace or ']' or
+    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+        if (/^[\],:{}\s]*$/
+                .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+                    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+                    .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+    // In the third stage we use the eval function to compile the text into a
+    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+    // in JavaScript: it can begin a block or an object literal. We wrap the text
+    // in parens to eliminate the ambiguity.
+
+            j = eval('(' + text + ')');
+
+    // In the optional fourth stage, we recursively walk the new structure, passing
+    // each name/value pair to a reviver function for possible transformation.
+
+            return typeof reviver === 'function' ?
+                walk({'': j}, '') : j;
+        }
+
+    // If the text is not JSON parseable, then a SyntaxError is thrown.
+
+        throw new SyntaxError('JSON.parse');
+    };
+
+    return JSON;
+  })();
+
+  if ('undefined' != typeof window) {
+    window.expect = module.exports;
+  }
+
+})(
+    this
+  , 'undefined' != typeof module ? module : {exports: {}}
+);
diff --git a/test-external/mocha.css b/test-external/mocha.css
new file mode 100644
index 0000000..42b9798
--- /dev/null
+++ b/test-external/mocha.css
@@ -0,0 +1,270 @@
+ at charset "utf-8";
+
+body {
+  margin:0;
+}
+
+#mocha {
+  font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
+  margin: 60px 50px;
+}
+
+#mocha ul,
+#mocha li {
+  margin: 0;
+  padding: 0;
+}
+
+#mocha ul {
+  list-style: none;
+}
+
+#mocha h1,
+#mocha h2 {
+  margin: 0;
+}
+
+#mocha h1 {
+  margin-top: 15px;
+  font-size: 1em;
+  font-weight: 200;
+}
+
+#mocha h1 a {
+  text-decoration: none;
+  color: inherit;
+}
+
+#mocha h1 a:hover {
+  text-decoration: underline;
+}
+
+#mocha .suite .suite h1 {
+  margin-top: 0;
+  font-size: .8em;
+}
+
+#mocha .hidden {
+  display: none;
+}
+
+#mocha h2 {
+  font-size: 12px;
+  font-weight: normal;
+  cursor: pointer;
+}
+
+#mocha .suite {
+  margin-left: 15px;
+}
+
+#mocha .test {
+  margin-left: 15px;
+  overflow: hidden;
+}
+
+#mocha .test.pending:hover h2::after {
+  content: '(pending)';
+  font-family: arial, sans-serif;
+}
+
+#mocha .test.pass.medium .duration {
+  background: #c09853;
+}
+
+#mocha .test.pass.slow .duration {
+  background: #b94a48;
+}
+
+#mocha .test.pass::before {
+  content: '✓';
+  font-size: 12px;
+  display: block;
+  float: left;
+  margin-right: 5px;
+  color: #00d6b2;
+}
+
+#mocha .test.pass .duration {
+  font-size: 9px;
+  margin-left: 5px;
+  padding: 2px 5px;
+  color: #fff;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
+  -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
+  box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
+  -webkit-border-radius: 5px;
+  -moz-border-radius: 5px;
+  -ms-border-radius: 5px;
+  -o-border-radius: 5px;
+  border-radius: 5px;
+}
+
+#mocha .test.pass.fast .duration {
+  display: none;
+}
+
+#mocha .test.pending {
+  color: #0b97c4;
+}
+
+#mocha .test.pending::before {
+  content: '◦';
+  color: #0b97c4;
+}
+
+#mocha .test.fail {
+  color: #c00;
+}
+
+#mocha .test.fail pre {
+  color: black;
+}
+
+#mocha .test.fail::before {
+  content: '✖';
+  font-size: 12px;
+  display: block;
+  float: left;
+  margin-right: 5px;
+  color: #c00;
+}
+
+#mocha .test pre.error {
+  color: #c00;
+  max-height: 300px;
+  overflow: auto;
+}
+
+/**
+ * (1): approximate for browsers not supporting calc
+ * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
+ *      ^^ seriously
+ */
+#mocha .test pre {
+  display: block;
+  float: left;
+  clear: left;
+  font: 12px/1.5 monaco, monospace;
+  margin: 5px;
+  padding: 15px;
+  border: 1px solid #eee;
+  max-width: 85%; /*(1)*/
+  max-width: calc(100% - 42px); /*(2)*/
+  word-wrap: break-word;
+  border-bottom-color: #ddd;
+  -webkit-border-radius: 3px;
+  -webkit-box-shadow: 0 1px 3px #eee;
+  -moz-border-radius: 3px;
+  -moz-box-shadow: 0 1px 3px #eee;
+  border-radius: 3px;
+}
+
+#mocha .test h2 {
+  position: relative;
+}
+
+#mocha .test a.replay {
+  position: absolute;
+  top: 3px;
+  right: 0;
+  text-decoration: none;
+  vertical-align: middle;
+  display: block;
+  width: 15px;
+  height: 15px;
+  line-height: 15px;
+  text-align: center;
+  background: #eee;
+  font-size: 15px;
+  -moz-border-radius: 15px;
+  border-radius: 15px;
+  -webkit-transition: opacity 200ms;
+  -moz-transition: opacity 200ms;
+  transition: opacity 200ms;
+  opacity: 0.3;
+  color: #888;
+}
+
+#mocha .test:hover a.replay {
+  opacity: 1;
+}
+
+#mocha-report.pass .test.fail {
+  display: none;
+}
+
+#mocha-report.fail .test.pass {
+  display: none;
+}
+
+#mocha-report.pending .test.pass,
+#mocha-report.pending .test.fail {
+  display: none;
+}
+#mocha-report.pending .test.pass.pending {
+  display: block;
+}
+
+#mocha-error {
+  color: #c00;
+  font-size: 1.5em;
+  font-weight: 100;
+  letter-spacing: 1px;
+}
+
+#mocha-stats {
+  position: fixed;
+  top: 15px;
+  right: 10px;
+  font-size: 12px;
+  margin: 0;
+  color: #888;
+  z-index: 1;
+}
+
+#mocha-stats .progress {
+  float: right;
+  padding-top: 0;
+}
+
+#mocha-stats em {
+  color: black;
+}
+
+#mocha-stats a {
+  text-decoration: none;
+  color: inherit;
+}
+
+#mocha-stats a:hover {
+  border-bottom: 1px solid #eee;
+}
+
+#mocha-stats li {
+  display: inline-block;
+  margin: 0 5px;
+  list-style: none;
+  padding-top: 11px;
+}
+
+#mocha-stats canvas {
+  width: 40px;
+  height: 40px;
+}
+
+#mocha code .comment { color: #ddd; }
+#mocha code .init { color: #2f6fad; }
+#mocha code .string { color: #5890ad; }
+#mocha code .keyword { color: #8a6343; }
+#mocha code .number { color: #2f6fad; }
+
+ at media screen and (max-device-width: 480px) {
+  #mocha {
+    margin: 60px 0px;
+  }
+
+  #mocha #stats {
+    position: absolute;
+  }
+}
diff --git a/test-external/mocha.js b/test-external/mocha.js
new file mode 100644
index 0000000..3dcdae6
--- /dev/null
+++ b/test-external/mocha.js
@@ -0,0 +1,5812 @@
+;(function(){
+
+// CommonJS require()
+
+function require(p){
+    var path = require.resolve(p)
+      , mod = require.modules[path];
+    if (!mod) throw new Error('failed to require "' + p + '"');
+    if (!mod.exports) {
+      mod.exports = {};
+      mod.call(mod.exports, mod, mod.exports, require.relative(path));
+    }
+    return mod.exports;
+  }
+
+require.modules = {};
+
+require.resolve = function (path){
+    var orig = path
+      , reg = path + '.js'
+      , index = path + '/index.js';
+    return require.modules[reg] && reg
+      || require.modules[index] && index
+      || orig;
+  };
+
+require.register = function (path, fn){
+    require.modules[path] = fn;
+  };
+
+require.relative = function (parent) {
+    return function(p){
+      if ('.' != p.charAt(0)) return require(p);
+
+      var path = parent.split('/')
+        , segs = p.split('/');
+      path.pop();
+
+      for (var i = 0; i < segs.length; i++) {
+        var seg = segs[i];
+        if ('..' == seg) path.pop();
+        else if ('.' != seg) path.push(seg);
+      }
+
+      return require(path.join('/'));
+    };
+  };
+
+
+require.register("browser/debug.js", function(module, exports, require){
+
+module.exports = function(type){
+  return function(){
+  }
+};
+
+}); // module: browser/debug.js
+
+require.register("browser/diff.js", function(module, exports, require){
+/* See LICENSE file for terms of use */
+
+/*
+ * Text diff implementation.
+ *
+ * This library supports the following APIS:
+ * JsDiff.diffChars: Character by character diff
+ * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+ * JsDiff.diffLines: Line based diff
+ *
+ * JsDiff.diffCss: Diff targeted at CSS content
+ *
+ * These methods are based on the implementation proposed in
+ * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+ */
+var JsDiff = (function() {
+  /*jshint maxparams: 5*/
+  function clonePath(path) {
+    return { newPos: path.newPos, components: path.components.slice(0) };
+  }
+  function removeEmpty(array) {
+    var ret = [];
+    for (var i = 0; i < array.length; i++) {
+      if (array[i]) {
+        ret.push(array[i]);
+      }
+    }
+    return ret;
+  }
+  function escapeHTML(s) {
+    var n = s;
+    n = n.replace(/&/g, '&');
+    n = n.replace(/</g, '<');
+    n = n.replace(/>/g, '>');
+    n = n.replace(/"/g, '"');
+
+    return n;
+  }
+
+  var Diff = function(ignoreWhitespace) {
+    this.ignoreWhitespace = ignoreWhitespace;
+  };
+  Diff.prototype = {
+      diff: function(oldString, newString) {
+        // Handle the identity case (this is due to unrolling editLength == 0
+        if (newString === oldString) {
+          return [{ value: newString }];
+        }
+        if (!newString) {
+          return [{ value: oldString, removed: true }];
+        }
+        if (!oldString) {
+          return [{ value: newString, added: true }];
+        }
+
+        newString = this.tokenize(newString);
+        oldString = this.tokenize(oldString);
+
+        var newLen = newString.length, oldLen = oldString.length;
+        var maxEditLength = newLen + oldLen;
+        var bestPath = [{ newPos: -1, components: [] }];
+
+        // Seed editLength = 0
+        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+        if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
+          return bestPath[0].components;
+        }
+
+        for (var editLength = 1; editLength <= maxEditLength; editLength++) {
+          for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
+            var basePath;
+            var addPath = bestPath[diagonalPath-1],
+                removePath = bestPath[diagonalPath+1];
+            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+            if (addPath) {
+              // No one else is going to attempt to use this value, clear it
+              bestPath[diagonalPath-1] = undefined;
+            }
+
+            var canAdd = addPath && addPath.newPos+1 < newLen;
+            var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
+            if (!canAdd && !canRemove) {
+              bestPath[diagonalPath] = undefined;
+              continue;
+            }
+
+            // Select the diagonal that we want to branch from. We select the prior
+            // path whose position in the new string is the farthest from the origin
+            // and does not pass the bounds of the diff graph
+            if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
+              basePath = clonePath(removePath);
+              this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
+            } else {
+              basePath = clonePath(addPath);
+              basePath.newPos++;
+              this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
+            }
+
+            var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
+
+            if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
+              return basePath.components;
+            } else {
+              bestPath[diagonalPath] = basePath;
+            }
+          }
+        }
+      },
+
+      pushComponent: function(components, value, added, removed) {
+        var last = components[components.length-1];
+        if (last && last.added === added && last.removed === removed) {
+          // We need to clone here as the component clone operation is just
+          // as shallow array clone
+          components[components.length-1] =
+            {value: this.join(last.value, value), added: added, removed: removed };
+        } else {
+          components.push({value: value, added: added, removed: removed });
+        }
+      },
+      extractCommon: function(basePath, newString, oldString, diagonalPath) {
+        var newLen = newString.length,
+            oldLen = oldString.length,
+            newPos = basePath.newPos,
+            oldPos = newPos - diagonalPath;
+        while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
+          newPos++;
+          oldPos++;
+
+          this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
+        }
+        basePath.newPos = newPos;
+        return oldPos;
+      },
+
+      equals: function(left, right) {
+        var reWhitespace = /\S/;
+        if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
+          return true;
+        } else {
+          return left === right;
+        }
+      },
+      join: function(left, right) {
+        return left + right;
+      },
+      tokenize: function(value) {
+        return value;
+      }
+  };
+
+  var CharDiff = new Diff();
+
+  var WordDiff = new Diff(true);
+  var WordWithSpaceDiff = new Diff();
+  WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
+    return removeEmpty(value.split(/(\s+|\b)/));
+  };
+
+  var CssDiff = new Diff(true);
+  CssDiff.tokenize = function(value) {
+    return removeEmpty(value.split(/([{}:;,]|\s+)/));
+  };
+
+  var LineDiff = new Diff();
+  LineDiff.tokenize = function(value) {
+    return value.split(/^/m);
+  };
+
+  return {
+    Diff: Diff,
+
+    diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
+    diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
+    diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
+    diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
+
+    diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
+
+    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
+      var ret = [];
+
+      ret.push('Index: ' + fileName);
+      ret.push('===================================================================');
+      ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
+      ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
+
+      var diff = LineDiff.diff(oldStr, newStr);
+      if (!diff[diff.length-1].value) {
+        diff.pop();   // Remove trailing newline add
+      }
+      diff.push({value: '', lines: []});   // Append an empty value to make cleanup easier
+
+      function contextLines(lines) {
+        return lines.map(function(entry) { return ' ' + entry; });
+      }
+      function eofNL(curRange, i, current) {
+        var last = diff[diff.length-2],
+            isLast = i === diff.length-2,
+            isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
+
+        // Figure out if this is the last line for the given file and missing NL
+        if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
+          curRange.push('\\ No newline at end of file');
+        }
+      }
+
+      var oldRangeStart = 0, newRangeStart = 0, curRange = [],
+          oldLine = 1, newLine = 1;
+      for (var i = 0; i < diff.length; i++) {
+        var current = diff[i],
+            lines = current.lines || current.value.replace(/\n$/, '').split('\n');
+        current.lines = lines;
+
+        if (current.added || current.removed) {
+          if (!oldRangeStart) {
+            var prev = diff[i-1];
+            oldRangeStart = oldLine;
+            newRangeStart = newLine;
+
+            if (prev) {
+              curRange = contextLines(prev.lines.slice(-4));
+              oldRangeStart -= curRange.length;
+              newRangeStart -= curRange.length;
+            }
+          }
+          curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
+          eofNL(curRange, i, current);
+
+          if (current.added) {
+            newLine += lines.length;
+          } else {
+            oldLine += lines.length;
+          }
+        } else {
+          if (oldRangeStart) {
+            // Close out any changes that have been output (or join overlapping)
+            if (lines.length <= 8 && i < diff.length-2) {
+              // Overlapping
+              curRange.push.apply(curRange, contextLines(lines));
+            } else {
+              // end the range and output
+              var contextSize = Math.min(lines.length, 4);
+              ret.push(
+                  '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+                  + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+                  + ' @@');
+              ret.push.apply(ret, curRange);
+              ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
+              if (lines.length <= 4) {
+                eofNL(ret, i, current);
+              }
+
+              oldRangeStart = 0;  newRangeStart = 0; curRange = [];
+            }
+          }
+          oldLine += lines.length;
+          newLine += lines.length;
+        }
+      }
+
+      return ret.join('\n') + '\n';
+    },
+
+    applyPatch: function(oldStr, uniDiff) {
+      var diffstr = uniDiff.split('\n');
+      var diff = [];
+      var remEOFNL = false,
+          addEOFNL = false;
+
+      for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
+        if(diffstr[i][0] === '@') {
+          var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
+          diff.unshift({
+            start:meh[3],
+            oldlength:meh[2],
+            oldlines:[],
+            newlength:meh[4],
+            newlines:[]
+          });
+        } else if(diffstr[i][0] === '+') {
+          diff[0].newlines.push(diffstr[i].substr(1));
+        } else if(diffstr[i][0] === '-') {
+          diff[0].oldlines.push(diffstr[i].substr(1));
+        } else if(diffstr[i][0] === ' ') {
+          diff[0].newlines.push(diffstr[i].substr(1));
+          diff[0].oldlines.push(diffstr[i].substr(1));
+        } else if(diffstr[i][0] === '\\') {
+          if (diffstr[i-1][0] === '+') {
+            remEOFNL = true;
+          } else if(diffstr[i-1][0] === '-') {
+            addEOFNL = true;
+          }
+        }
+      }
+
+      var str = oldStr.split('\n');
+      for (var i = diff.length - 1; i >= 0; i--) {
+        var d = diff[i];
+        for (var j = 0; j < d.oldlength; j++) {
+          if(str[d.start-1+j] !== d.oldlines[j]) {
+            return false;
+          }
+        }
+        Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
+      }
+
+      if (remEOFNL) {
+        while (!str[str.length-1]) {
+          str.pop();
+        }
+      } else if (addEOFNL) {
+        str.push('');
+      }
+      return str.join('\n');
+    },
+
+    convertChangesToXML: function(changes){
+      var ret = [];
+      for ( var i = 0; i < changes.length; i++) {
+        var change = changes[i];
+        if (change.added) {
+          ret.push('<ins>');
+        } else if (change.removed) {
+          ret.push('<del>');
+        }
+
+        ret.push(escapeHTML(change.value));
+
+        if (change.added) {
+          ret.push('</ins>');
+        } else if (change.removed) {
+          ret.push('</del>');
+        }
+      }
+      return ret.join('');
+    },
+
+    // See: http://code.google.com/p/google-diff-match-patch/wiki/API
+    convertChangesToDMP: function(changes){
+      var ret = [], change;
+      for ( var i = 0; i < changes.length; i++) {
+        change = changes[i];
+        ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
+      }
+      return ret;
+    }
+  };
+})();
+
+if (typeof module !== 'undefined') {
+    module.exports = JsDiff;
+}
+
+}); // module: browser/diff.js
+
+require.register("browser/events.js", function(module, exports, require){
+
+/**
+ * Module exports.
+ */
+
+exports.EventEmitter = EventEmitter;
+
+/**
+ * Check if `obj` is an array.
+ */
+
+function isArray(obj) {
+  return '[object Array]' == {}.toString.call(obj);
+}
+
+/**
+ * Event emitter constructor.
+ *
+ * @api public
+ */
+
+function EventEmitter(){};
+
+/**
+ * Adds a listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.on = function (name, fn) {
+  if (!this.$events) {
+    this.$events = {};
+  }
+
+  if (!this.$events[name]) {
+    this.$events[name] = fn;
+  } else if (isArray(this.$events[name])) {
+    this.$events[name].push(fn);
+  } else {
+    this.$events[name] = [this.$events[name], fn];
+  }
+
+  return this;
+};
+
+EventEmitter.prototype.addListener = EventEmitter.prototype.on;
+
+/**
+ * Adds a volatile listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.once = function (name, fn) {
+  var self = this;
+
+  function on () {
+    self.removeListener(name, on);
+    fn.apply(this, arguments);
+  };
+
+  on.listener = fn;
+  this.on(name, on);
+
+  return this;
+};
+
+/**
+ * Removes a listener.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.removeListener = function (name, fn) {
+  if (this.$events && this.$events[name]) {
+    var list = this.$events[name];
+
+    if (isArray(list)) {
+      var pos = -1;
+
+      for (var i = 0, l = list.length; i < l; i++) {
+        if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
+          pos = i;
+          break;
+        }
+      }
+
+      if (pos < 0) {
+        return this;
+      }
+
+      list.splice(pos, 1);
+
+      if (!list.length) {
+        delete this.$events[name];
+      }
+    } else if (list === fn || (list.listener && list.listener === fn)) {
+      delete this.$events[name];
+    }
+  }
+
+  return this;
+};
+
+/**
+ * Removes all listeners for an event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.removeAllListeners = function (name) {
+  if (name === undefined) {
+    this.$events = {};
+    return this;
+  }
+
+  if (this.$events && this.$events[name]) {
+    this.$events[name] = null;
+  }
+
+  return this;
+};
+
+/**
+ * Gets all listeners for a certain event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.listeners = function (name) {
+  if (!this.$events) {
+    this.$events = {};
+  }
+
+  if (!this.$events[name]) {
+    this.$events[name] = [];
+  }
+
+  if (!isArray(this.$events[name])) {
+    this.$events[name] = [this.$events[name]];
+  }
+
+  return this.$events[name];
+};
+
+/**
+ * Emits an event.
+ *
+ * @api public
+ */
+
+EventEmitter.prototype.emit = function (name) {
+  if (!this.$events) {
+    return false;
+  }
+
+  var handler = this.$events[name];
+
+  if (!handler) {
+    return false;
+  }
+
+  var args = [].slice.call(arguments, 1);
+
+  if ('function' == typeof handler) {
+    handler.apply(this, args);
+  } else if (isArray(handler)) {
+    var listeners = handler.slice();
+
+    for (var i = 0, l = listeners.length; i < l; i++) {
+      listeners[i].apply(this, args);
+    }
+  } else {
+    return false;
+  }
+
+  return true;
+};
+}); // module: browser/events.js
+
+require.register("browser/fs.js", function(module, exports, require){
+
+}); // module: browser/fs.js
+
+require.register("browser/path.js", function(module, exports, require){
+
+}); // module: browser/path.js
+
+require.register("browser/progress.js", function(module, exports, require){
+/**
+ * Expose `Progress`.
+ */
+
+module.exports = Progress;
+
+/**
+ * Initialize a new `Progress` indicator.
+ */
+
+function Progress() {
+  this.percent = 0;
+  this.size(0);
+  this.fontSize(11);
+  this.font('helvetica, arial, sans-serif');
+}
+
+/**
+ * Set progress size to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.size = function(n){
+  this._size = n;
+  return this;
+};
+
+/**
+ * Set text to `str`.
+ *
+ * @param {String} str
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.text = function(str){
+  this._text = str;
+  return this;
+};
+
+/**
+ * Set font size to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ * @api public
+ */
+
+Progress.prototype.fontSize = function(n){
+  this._fontSize = n;
+  return this;
+};
+
+/**
+ * Set font `family`.
+ *
+ * @param {String} family
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.font = function(family){
+  this._font = family;
+  return this;
+};
+
+/**
+ * Update percentage to `n`.
+ *
+ * @param {Number} n
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.update = function(n){
+  this.percent = n;
+  return this;
+};
+
+/**
+ * Draw on `ctx`.
+ *
+ * @param {CanvasRenderingContext2d} ctx
+ * @return {Progress} for chaining
+ */
+
+Progress.prototype.draw = function(ctx){
+  try {
+    var percent = Math.min(this.percent, 100)
+      , size = this._size
+      , half = size / 2
+      , x = half
+      , y = half
+      , rad = half - 1
+      , fontSize = this._fontSize;
+  
+    ctx.font = fontSize + 'px ' + this._font;
+  
+    var angle = Math.PI * 2 * (percent / 100);
+    ctx.clearRect(0, 0, size, size);
+  
+    // outer circle
+    ctx.strokeStyle = '#9f9f9f';
+    ctx.beginPath();
+    ctx.arc(x, y, rad, 0, angle, false);
+    ctx.stroke();
+  
+    // inner circle
+    ctx.strokeStyle = '#eee';
+    ctx.beginPath();
+    ctx.arc(x, y, rad - 1, 0, angle, true);
+    ctx.stroke();
+  
+    // text
+    var text = this._text || (percent | 0) + '%'
+      , w = ctx.measureText(text).width;
+  
+    ctx.fillText(
+        text
+      , x - w / 2 + 1
+      , y + fontSize / 2 - 1);
+  } catch (ex) {} //don't fail if we can't render progress
+  return this;
+};
+
+}); // module: browser/progress.js
+
+require.register("browser/tty.js", function(module, exports, require){
+
+exports.isatty = function(){
+  return true;
+};
+
+exports.getWindowSize = function(){
+  if ('innerHeight' in global) {
+    return [global.innerHeight, global.innerWidth];
+  } else {
+    // In a Web Worker, the DOM Window is not available.
+    return [640, 480];
+  }
+};
+
+}); // module: browser/tty.js
+
+require.register("context.js", function(module, exports, require){
+
+/**
+ * Expose `Context`.
+ */
+
+module.exports = Context;
+
+/**
+ * Initialize a new `Context`.
+ *
+ * @api private
+ */
+
+function Context(){}
+
+/**
+ * Set or get the context `Runnable` to `runnable`.
+ *
+ * @param {Runnable} runnable
+ * @return {Context}
+ * @api private
+ */
+
+Context.prototype.runnable = function(runnable){
+  if (0 == arguments.length) return this._runnable;
+  this.test = this._runnable = runnable;
+  return this;
+};
+
+/**
+ * Set test timeout `ms`.
+ *
+ * @param {Number} ms
+ * @return {Context} self
+ * @api private
+ */
+
+Context.prototype.timeout = function(ms){
+  this.runnable().timeout(ms);
+  return this;
+};
+
+/**
+ * Set test slowness threshold `ms`.
+ *
+ * @param {Number} ms
+ * @return {Context} self
+ * @api private
+ */
+
+Context.prototype.slow = function(ms){
+  this.runnable().slow(ms);
+  return this;
+};
+
+/**
+ * Inspect the context void of `._runnable`.
+ *
+ * @return {String}
+ * @api private
+ */
+
+Context.prototype.inspect = function(){
+  return JSON.stringify(this, function(key, val){
+    if ('_runnable' == key) return;
+    if ('test' == key) return;
+    return val;
+  }, 2);
+};
+
+}); // module: context.js
+
+require.register("hook.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Runnable = require('./runnable');
+
+/**
+ * Expose `Hook`.
+ */
+
+module.exports = Hook;
+
+/**
+ * Initialize a new `Hook` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Hook(title, fn) {
+  Runnable.call(this, title, fn);
+  this.type = 'hook';
+}
+
+/**
+ * Inherit from `Runnable.prototype`.
+ */
+
+function F(){};
+F.prototype = Runnable.prototype;
+Hook.prototype = new F;
+Hook.prototype.constructor = Hook;
+
+
+/**
+ * Get or set the test `err`.
+ *
+ * @param {Error} err
+ * @return {Error}
+ * @api public
+ */
+
+Hook.prototype.error = function(err){
+  if (0 == arguments.length) {
+    var err = this._error;
+    this._error = null;
+    return err;
+  }
+
+  this._error = err;
+};
+
+}); // module: hook.js
+
+require.register("interfaces/bdd.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+  , Test = require('../test')
+  , utils = require('../utils');
+
+/**
+ * BDD-style interface:
+ *
+ *      describe('Array', function(){
+ *        describe('#indexOf()', function(){
+ *          it('should return -1 when not present', function(){
+ *
+ *          });
+ *
+ *          it('should return the index when present', function(){
+ *
+ *          });
+ *        });
+ *      });
+ *
+ */
+
+module.exports = function(suite){
+  var suites = [suite];
+
+  suite.on('pre-require', function(context, file, mocha){
+
+    /**
+     * Execute before running tests.
+     */
+
+    context.before = function(fn){
+      suites[0].beforeAll(fn);
+    };
+
+    /**
+     * Execute after running tests.
+     */
+
+    context.after = function(fn){
+      suites[0].afterAll(fn);
+    };
+
+    /**
+     * Execute before each test case.
+     */
+
+    context.beforeEach = function(fn){
+      suites[0].beforeEach(fn);
+    };
+
+    /**
+     * Execute after each test case.
+     */
+
+    context.afterEach = function(fn){
+      suites[0].afterEach(fn);
+    };
+
+    /**
+     * Describe a "suite" with the given `title`
+     * and callback `fn` containing nested suites
+     * and/or tests.
+     */
+
+    context.describe = context.context = function(title, fn){
+      var suite = Suite.create(suites[0], title);
+      suites.unshift(suite);
+      fn.call(suite);
+      suites.shift();
+      return suite;
+    };
+
+    /**
+     * Pending describe.
+     */
+
+    context.xdescribe =
+    context.xcontext =
+    context.describe.skip = function(title, fn){
+      var suite = Suite.create(suites[0], title);
+      suite.pending = true;
+      suites.unshift(suite);
+      fn.call(suite);
+      suites.shift();
+    };
+
+    /**
+     * Exclusive suite.
+     */
+
+    context.describe.only = function(title, fn){
+      var suite = context.describe(title, fn);
+      mocha.grep(suite.fullTitle());
+      return suite;
+    };
+
+    /**
+     * Describe a specification or test-case
+     * with the given `title` and callback `fn`
+     * acting as a thunk.
+     */
+
+    context.it = context.specify = function(title, fn){
+      var suite = suites[0];
+      if (suite.pending) var fn = null;
+      var test = new Test(title, fn);
+      suite.addTest(test);
+      return test;
+    };
+
+    /**
+     * Exclusive test-case.
+     */
+
+    context.it.only = function(title, fn){
+      var test = context.it(title, fn);
+      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+      mocha.grep(new RegExp(reString));
+      return test;
+    };
+
+    /**
+     * Pending test case.
+     */
+
+    context.xit =
+    context.xspecify =
+    context.it.skip = function(title){
+      context.it(title);
+    };
+  });
+};
+
+}); // module: interfaces/bdd.js
+
+require.register("interfaces/exports.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+  , Test = require('../test');
+
+/**
+ * TDD-style interface:
+ *
+ *     exports.Array = {
+ *       '#indexOf()': {
+ *         'should return -1 when the value is not present': function(){
+ *
+ *         },
+ *
+ *         'should return the correct index when the value is present': function(){
+ *
+ *         }
+ *       }
+ *     };
+ *
+ */
+
+module.exports = function(suite){
+  var suites = [suite];
+
+  suite.on('require', visit);
+
+  function visit(obj) {
+    var suite;
+    for (var key in obj) {
+      if ('function' == typeof obj[key]) {
+        var fn = obj[key];
+        switch (key) {
+          case 'before':
+            suites[0].beforeAll(fn);
+            break;
+          case 'after':
+            suites[0].afterAll(fn);
+            break;
+          case 'beforeEach':
+            suites[0].beforeEach(fn);
+            break;
+          case 'afterEach':
+            suites[0].afterEach(fn);
+            break;
+          default:
+            suites[0].addTest(new Test(key, fn));
+        }
+      } else {
+        var suite = Suite.create(suites[0], key);
+        suites.unshift(suite);
+        visit(obj[key]);
+        suites.shift();
+      }
+    }
+  }
+};
+
+}); // module: interfaces/exports.js
+
+require.register("interfaces/index.js", function(module, exports, require){
+
+exports.bdd = require('./bdd');
+exports.tdd = require('./tdd');
+exports.qunit = require('./qunit');
+exports.exports = require('./exports');
+
+}); // module: interfaces/index.js
+
+require.register("interfaces/qunit.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+  , Test = require('../test')
+  , utils = require('../utils');
+
+/**
+ * QUnit-style interface:
+ *
+ *     suite('Array');
+ *
+ *     test('#length', function(){
+ *       var arr = [1,2,3];
+ *       ok(arr.length == 3);
+ *     });
+ *
+ *     test('#indexOf()', function(){
+ *       var arr = [1,2,3];
+ *       ok(arr.indexOf(1) == 0);
+ *       ok(arr.indexOf(2) == 1);
+ *       ok(arr.indexOf(3) == 2);
+ *     });
+ *
+ *     suite('String');
+ *
+ *     test('#length', function(){
+ *       ok('foo'.length == 3);
+ *     });
+ *
+ */
+
+module.exports = function(suite){
+  var suites = [suite];
+
+  suite.on('pre-require', function(context, file, mocha){
+
+    /**
+     * Execute before running tests.
+     */
+
+    context.before = function(fn){
+      suites[0].beforeAll(fn);
+    };
+
+    /**
+     * Execute after running tests.
+     */
+
+    context.after = function(fn){
+      suites[0].afterAll(fn);
+    };
+
+    /**
+     * Execute before each test case.
+     */
+
+    context.beforeEach = function(fn){
+      suites[0].beforeEach(fn);
+    };
+
+    /**
+     * Execute after each test case.
+     */
+
+    context.afterEach = function(fn){
+      suites[0].afterEach(fn);
+    };
+
+    /**
+     * Describe a "suite" with the given `title`.
+     */
+
+    context.suite = function(title){
+      if (suites.length > 1) suites.shift();
+      var suite = Suite.create(suites[0], title);
+      suites.unshift(suite);
+      return suite;
+    };
+
+    /**
+     * Exclusive test-case.
+     */
+
+    context.suite.only = function(title, fn){
+      var suite = context.suite(title, fn);
+      mocha.grep(suite.fullTitle());
+    };
+
+    /**
+     * Describe a specification or test-case
+     * with the given `title` and callback `fn`
+     * acting as a thunk.
+     */
+
+    context.test = function(title, fn){
+      var test = new Test(title, fn);
+      suites[0].addTest(test);
+      return test;
+    };
+
+    /**
+     * Exclusive test-case.
+     */
+
+    context.test.only = function(title, fn){
+      var test = context.test(title, fn);
+      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+      mocha.grep(new RegExp(reString));
+    };
+
+    /**
+     * Pending test case.
+     */
+
+    context.test.skip = function(title){
+      context.test(title);
+    };
+  });
+};
+
+}); // module: interfaces/qunit.js
+
+require.register("interfaces/tdd.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Suite = require('../suite')
+  , Test = require('../test')
+  , utils = require('../utils');;
+
+/**
+ * TDD-style interface:
+ *
+ *      suite('Array', function(){
+ *        suite('#indexOf()', function(){
+ *          suiteSetup(function(){
+ *
+ *          });
+ *
+ *          test('should return -1 when not present', function(){
+ *
+ *          });
+ *
+ *          test('should return the index when present', function(){
+ *
+ *          });
+ *
+ *          suiteTeardown(function(){
+ *
+ *          });
+ *        });
+ *      });
+ *
+ */
+
+module.exports = function(suite){
+  var suites = [suite];
+
+  suite.on('pre-require', function(context, file, mocha){
+
+    /**
+     * Execute before each test case.
+     */
+
+    context.setup = function(fn){
+      suites[0].beforeEach(fn);
+    };
+
+    /**
+     * Execute after each test case.
+     */
+
+    context.teardown = function(fn){
+      suites[0].afterEach(fn);
+    };
+
+    /**
+     * Execute before the suite.
+     */
+
+    context.suiteSetup = function(fn){
+      suites[0].beforeAll(fn);
+    };
+
+    /**
+     * Execute after the suite.
+     */
+
+    context.suiteTeardown = function(fn){
+      suites[0].afterAll(fn);
+    };
+
+    /**
+     * Describe a "suite" with the given `title`
+     * and callback `fn` containing nested suites
+     * and/or tests.
+     */
+
+    context.suite = function(title, fn){
+      var suite = Suite.create(suites[0], title);
+      suites.unshift(suite);
+      fn.call(suite);
+      suites.shift();
+      return suite;
+    };
+
+    /**
+     * Pending suite.
+     */
+    context.suite.skip = function(title, fn) {
+      var suite = Suite.create(suites[0], title);
+      suite.pending = true;
+      suites.unshift(suite);
+      fn.call(suite);
+      suites.shift();
+    };
+
+    /**
+     * Exclusive test-case.
+     */
+
+    context.suite.only = function(title, fn){
+      var suite = context.suite(title, fn);
+      mocha.grep(suite.fullTitle());
+    };
+
+    /**
+     * Describe a specification or test-case
+     * with the given `title` and callback `fn`
+     * acting as a thunk.
+     */
+
+    context.test = function(title, fn){
+      var suite = suites[0];
+      if (suite.pending) var fn = null;
+      var test = new Test(title, fn);
+      suite.addTest(test);
+      return test;
+    };
+
+    /**
+     * Exclusive test-case.
+     */
+
+    context.test.only = function(title, fn){
+      var test = context.test(title, fn);
+      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+      mocha.grep(new RegExp(reString));
+    };
+
+    /**
+     * Pending test case.
+     */
+
+    context.test.skip = function(title){
+      context.test(title);
+    };
+  });
+};
+
+}); // module: interfaces/tdd.js
+
+require.register("mocha.js", function(module, exports, require){
+/*!
+ * mocha
+ * Copyright(c) 2011 TJ Holowaychuk <tj at vision-media.ca>
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ */
+
+var path = require('browser/path')
+  , utils = require('./utils');
+
+/**
+ * Expose `Mocha`.
+ */
+
+exports = module.exports = Mocha;
+
+/**
+ * Expose internals.
+ */
+
+exports.utils = utils;
+exports.interfaces = require('./interfaces');
+exports.reporters = require('./reporters');
+exports.Runnable = require('./runnable');
+exports.Context = require('./context');
+exports.Runner = require('./runner');
+exports.Suite = require('./suite');
+exports.Hook = require('./hook');
+exports.Test = require('./test');
+
+/**
+ * Return image `name` path.
+ *
+ * @param {String} name
+ * @return {String}
+ * @api private
+ */
+
+function image(name) {
+  return __dirname + '/../images/' + name + '.png';
+}
+
+/**
+ * Setup mocha with `options`.
+ *
+ * Options:
+ *
+ *   - `ui` name "bdd", "tdd", "exports" etc
+ *   - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
+ *   - `globals` array of accepted globals
+ *   - `timeout` timeout in milliseconds
+ *   - `bail` bail on the first test failure
+ *   - `slow` milliseconds to wait before considering a test slow
+ *   - `ignoreLeaks` ignore global leaks
+ *   - `grep` string or regexp to filter tests with
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+function Mocha(options) {
+  options = options || {};
+  this.files = [];
+  this.options = options;
+  this.grep(options.grep);
+  this.suite = new exports.Suite('', new exports.Context);
+  this.ui(options.ui);
+  this.bail(options.bail);
+  this.reporter(options.reporter);
+  if (null != options.timeout) this.timeout(options.timeout);
+  this.useColors(options.useColors)
+  if (options.slow) this.slow(options.slow);
+
+  this.suite.on('pre-require', function (context) {
+    exports.afterEach = context.afterEach || context.teardown;
+    exports.after = context.after || context.suiteTeardown;
+    exports.beforeEach = context.beforeEach || context.setup;
+    exports.before = context.before || context.suiteSetup;
+    exports.describe = context.describe || context.suite;
+    exports.it = context.it || context.test;
+    exports.setup = context.setup || context.beforeEach;
+    exports.suiteSetup = context.suiteSetup || context.before;
+    exports.suiteTeardown = context.suiteTeardown || context.after;
+    exports.suite = context.suite || context.describe;
+    exports.teardown = context.teardown || context.afterEach;
+    exports.test = context.test || context.it;
+  });
+}
+
+/**
+ * Enable or disable bailing on the first failure.
+ *
+ * @param {Boolean} [bail]
+ * @api public
+ */
+
+Mocha.prototype.bail = function(bail){
+  if (0 == arguments.length) bail = true;
+  this.suite.bail(bail);
+  return this;
+};
+
+/**
+ * Add test `file`.
+ *
+ * @param {String} file
+ * @api public
+ */
+
+Mocha.prototype.addFile = function(file){
+  this.files.push(file);
+  return this;
+};
+
+/**
+ * Set reporter to `reporter`, defaults to "dot".
+ *
+ * @param {String|Function} reporter name or constructor
+ * @api public
+ */
+
+Mocha.prototype.reporter = function(reporter){
+  if ('function' == typeof reporter) {
+    this._reporter = reporter;
+  } else {
+    reporter = reporter || 'dot';
+    var _reporter;
+    try { _reporter = require('./reporters/' + reporter); } catch (err) {};
+    if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
+    if (!_reporter && reporter === 'teamcity')
+      console.warn('The Teamcity reporter was moved to a package named ' +
+        'mocha-teamcity-reporter ' +
+        '(https://npmjs.org/package/mocha-teamcity-reporter).');
+    if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
+    this._reporter = _reporter;
+  }
+  return this;
+};
+
+/**
+ * Set test UI `name`, defaults to "bdd".
+ *
+ * @param {String} bdd
+ * @api public
+ */
+
+Mocha.prototype.ui = function(name){
+  name = name || 'bdd';
+  this._ui = exports.interfaces[name];
+  if (!this._ui) try { this._ui = require(name); } catch (err) {};
+  if (!this._ui) throw new Error('invalid interface "' + name + '"');
+  this._ui = this._ui(this.suite);
+  return this;
+};
+
+/**
+ * Load registered files.
+ *
+ * @api private
+ */
+
+Mocha.prototype.loadFiles = function(fn){
+  var self = this;
+  var suite = this.suite;
+  var pending = this.files.length;
+  this.files.forEach(function(file){
+    file = path.resolve(file);
+    suite.emit('pre-require', global, file, self);
+    suite.emit('require', require(file), file, self);
+    suite.emit('post-require', global, file, self);
+    --pending || (fn && fn());
+  });
+};
+
+/**
+ * Enable growl support.
+ *
+ * @api private
+ */
+
+Mocha.prototype._growl = function(runner, reporter) {
+  var notify = require('growl');
+
+  runner.on('end', function(){
+    var stats = reporter.stats;
+    if (stats.failures) {
+      var msg = stats.failures + ' of ' + runner.total + ' tests failed';
+      notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
+    } else {
+      notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
+          name: 'mocha'
+        , title: 'Passed'
+        , image: image('ok')
+      });
+    }
+  });
+};
+
+/**
+ * Add regexp to grep, if `re` is a string it is escaped.
+ *
+ * @param {RegExp|String} re
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.grep = function(re){
+  this.options.grep = 'string' == typeof re
+    ? new RegExp(utils.escapeRegexp(re))
+    : re;
+  return this;
+};
+
+/**
+ * Invert `.grep()` matches.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.invert = function(){
+  this.options.invert = true;
+  return this;
+};
+
+/**
+ * Ignore global leaks.
+ *
+ * @param {Boolean} ignore
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.ignoreLeaks = function(ignore){
+  this.options.ignoreLeaks = !!ignore;
+  return this;
+};
+
+/**
+ * Enable global leak checking.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.checkLeaks = function(){
+  this.options.ignoreLeaks = false;
+  return this;
+};
+
+/**
+ * Enable growl support.
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.growl = function(){
+  this.options.growl = true;
+  return this;
+};
+
+/**
+ * Ignore `globals` array or string.
+ *
+ * @param {Array|String} globals
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.globals = function(globals){
+  this.options.globals = (this.options.globals || []).concat(globals);
+  return this;
+};
+
+/**
+ * Emit color output.
+ *
+ * @param {Boolean} colors
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.useColors = function(colors){
+  this.options.useColors = arguments.length && colors != undefined
+    ? colors
+    : true;
+  return this;
+};
+
+/**
+ * Use inline diffs rather than +/-.
+ *
+ * @param {Boolean} inlineDiffs
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
+  this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
+  ? inlineDiffs
+  : false;
+  return this;
+};
+
+/**
+ * Set the timeout in milliseconds.
+ *
+ * @param {Number} timeout
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.timeout = function(timeout){
+  this.suite.timeout(timeout);
+  return this;
+};
+
+/**
+ * Set slowness threshold in milliseconds.
+ *
+ * @param {Number} slow
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.slow = function(slow){
+  this.suite.slow(slow);
+  return this;
+};
+
+/**
+ * Makes all tests async (accepting a callback)
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.asyncOnly = function(){
+  this.options.asyncOnly = true;
+  return this;
+};
+
+/**
+ * Run tests and invoke `fn()` when complete.
+ *
+ * @param {Function} fn
+ * @return {Runner}
+ * @api public
+ */
+
+Mocha.prototype.run = function(fn){
+  if (this.files.length) this.loadFiles();
+  var suite = this.suite;
+  var options = this.options;
+  var runner = new exports.Runner(suite);
+  var reporter = new this._reporter(runner);
+  runner.ignoreLeaks = false !== options.ignoreLeaks;
+  runner.asyncOnly = options.asyncOnly;
+  if (options.grep) runner.grep(options.grep, options.invert);
+  if (options.globals) runner.globals(options.globals);
+  if (options.growl) this._growl(runner, reporter);
+  exports.reporters.Base.useColors = options.useColors;
+  exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
+  return runner.run(fn);
+};
+
+}); // module: mocha.js
+
+require.register("ms.js", function(module, exports, require){
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ *  - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} options
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options){
+  options = options || {};
+  if ('string' == typeof val) return parse(val);
+  return options.long ? longFormat(val) : shortFormat(val);
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+  var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
+  if (!match) return;
+  var n = parseFloat(match[1]);
+  var type = (match[2] || 'ms').toLowerCase();
+  switch (type) {
+    case 'years':
+    case 'year':
+    case 'y':
+      return n * y;
+    case 'days':
+    case 'day':
+    case 'd':
+      return n * d;
+    case 'hours':
+    case 'hour':
+    case 'h':
+      return n * h;
+    case 'minutes':
+    case 'minute':
+    case 'm':
+      return n * m;
+    case 'seconds':
+    case 'second':
+    case 's':
+      return n * s;
+    case 'ms':
+      return n;
+  }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function shortFormat(ms) {
+  if (ms >= d) return Math.round(ms / d) + 'd';
+  if (ms >= h) return Math.round(ms / h) + 'h';
+  if (ms >= m) return Math.round(ms / m) + 'm';
+  if (ms >= s) return Math.round(ms / s) + 's';
+  return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function longFormat(ms) {
+  return plural(ms, d, 'day')
+    || plural(ms, h, 'hour')
+    || plural(ms, m, 'minute')
+    || plural(ms, s, 'second')
+    || ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, n, name) {
+  if (ms < n) return;
+  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
+  return Math.ceil(ms / n) + ' ' + name + 's';
+}
+
+}); // module: ms.js
+
+require.register("reporters/base.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var tty = require('browser/tty')
+  , diff = require('browser/diff')
+  , ms = require('../ms')
+  , utils = require('../utils');
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+  , setTimeout = global.setTimeout
+  , setInterval = global.setInterval
+  , clearTimeout = global.clearTimeout
+  , clearInterval = global.clearInterval;
+
+/**
+ * Check if both stdio streams are associated with a tty.
+ */
+
+var isatty = tty.isatty(1) && tty.isatty(2);
+
+/**
+ * Expose `Base`.
+ */
+
+exports = module.exports = Base;
+
+/**
+ * Enable coloring by default.
+ */
+
+exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined);
+
+/**
+ * Inline diffs instead of +/-
+ */
+
+exports.inlineDiffs = false;
+
+/**
+ * Default color map.
+ */
+
+exports.colors = {
+    'pass': 90
+  , 'fail': 31
+  , 'bright pass': 92
+  , 'bright fail': 91
+  , 'bright yellow': 93
+  , 'pending': 36
+  , 'suite': 0
+  , 'error title': 0
+  , 'error message': 31
+  , 'error stack': 90
+  , 'checkmark': 32
+  , 'fast': 90
+  , 'medium': 33
+  , 'slow': 31
+  , 'green': 32
+  , 'light': 90
+  , 'diff gutter': 90
+  , 'diff added': 42
+  , 'diff removed': 41
+};
+
+/**
+ * Default symbol map.
+ */
+
+exports.symbols = {
+  ok: '✓',
+  err: '✖',
+  dot: '․'
+};
+
+// With node.js on Windows: use symbols available in terminal default fonts
+if ('win32' == process.platform) {
+  exports.symbols.ok = '\u221A';
+  exports.symbols.err = '\u00D7';
+  exports.symbols.dot = '.';
+}
+
+/**
+ * Color `str` with the given `type`,
+ * allowing colors to be disabled,
+ * as well as user-defined color
+ * schemes.
+ *
+ * @param {String} type
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+var color = exports.color = function(type, str) {
+  if (!exports.useColors) return str;
+  return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
+};
+
+/**
+ * Expose term window size, with some
+ * defaults for when stderr is not a tty.
+ */
+
+exports.window = {
+  width: isatty
+    ? process.stdout.getWindowSize
+      ? process.stdout.getWindowSize(1)[0]
+      : tty.getWindowSize()[1]
+    : 75
+};
+
+/**
+ * Expose some basic cursor interactions
+ * that are common among reporters.
+ */
+
+exports.cursor = {
+  hide: function(){
+    isatty && process.stdout.write('\u001b[?25l');
+  },
+
+  show: function(){
+    isatty && process.stdout.write('\u001b[?25h');
+  },
+
+  deleteLine: function(){
+    isatty && process.stdout.write('\u001b[2K');
+  },
+
+  beginningOfLine: function(){
+    isatty && process.stdout.write('\u001b[0G');
+  },
+
+  CR: function(){
+    if (isatty) {
+      exports.cursor.deleteLine();
+      exports.cursor.beginningOfLine();
+    } else {
+      process.stdout.write('\r');
+    }
+  }
+};
+
+/**
+ * Outut the given `failures` as a list.
+ *
+ * @param {Array} failures
+ * @api public
+ */
+
+exports.list = function(failures){
+  console.error();
+  failures.forEach(function(test, i){
+    // format
+    var fmt = color('error title', '  %s) %s:\n')
+      + color('error message', '     %s')
+      + color('error stack', '\n%s\n');
+
+    // msg
+    var err = test.err
+      , message = err.message || ''
+      , stack = err.stack || message
+      , index = stack.indexOf(message) + message.length
+      , msg = stack.slice(0, index)
+      , actual = err.actual
+      , expected = err.expected
+      , escape = true;
+
+    // uncaught
+    if (err.uncaught) {
+      msg = 'Uncaught ' + msg;
+    }
+
+    // explicitly show diff
+    if (err.showDiff && sameType(actual, expected)) {
+      escape = false;
+      err.actual = actual = stringify(canonicalize(actual));
+      err.expected = expected = stringify(canonicalize(expected));
+    }
+
+    // actual / expected diff
+    if ('string' == typeof actual && 'string' == typeof expected) {
+      fmt = color('error title', '  %s) %s:\n%s') + color('error stack', '\n%s\n');
+      var match = message.match(/^([^:]+): expected/);
+      msg = '\n      ' + color('error message', match ? match[1] : msg);
+
+      if (exports.inlineDiffs) {
+        msg += inlineDiff(err, escape);
+      } else {
+        msg += unifiedDiff(err, escape);
+      }
+    }
+
+    // indent stack trace without msg
+    stack = stack.slice(index ? index + 1 : index)
+      .replace(/^/gm, '  ');
+
+    console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
+  });
+};
+
+/**
+ * Initialize a new `Base` reporter.
+ *
+ * All other reporters generally
+ * inherit from this reporter, providing
+ * stats such as test duration, number
+ * of tests passed / failed etc.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Base(runner) {
+  var self = this
+    , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
+    , failures = this.failures = [];
+
+  if (!runner) return;
+  this.runner = runner;
+
+  runner.stats = stats;
+
+  runner.on('start', function(){
+    stats.start = new Date;
+  });
+
+  runner.on('suite', function(suite){
+    stats.suites = stats.suites || 0;
+    suite.root || stats.suites++;
+  });
+
+  runner.on('test end', function(test){
+    stats.tests = stats.tests || 0;
+    stats.tests++;
+  });
+
+  runner.on('pass', function(test){
+    stats.passes = stats.passes || 0;
+
+    var medium = test.slow() / 2;
+    test.speed = test.duration > test.slow()
+      ? 'slow'
+      : test.duration > medium
+        ? 'medium'
+        : 'fast';
+
+    stats.passes++;
+  });
+
+  runner.on('fail', function(test, err){
+    stats.failures = stats.failures || 0;
+    stats.failures++;
+    test.err = err;
+    failures.push(test);
+  });
+
+  runner.on('end', function(){
+    stats.end = new Date;
+    stats.duration = new Date - stats.start;
+  });
+
+  runner.on('pending', function(){
+    stats.pending++;
+  });
+}
+
+/**
+ * Output common epilogue used by many of
+ * the bundled reporters.
+ *
+ * @api public
+ */
+
+Base.prototype.epilogue = function(){
+  var stats = this.stats;
+  var tests;
+  var fmt;
+
+  console.log();
+
+  // passes
+  fmt = color('bright pass', ' ')
+    + color('green', ' %d passing')
+    + color('light', ' (%s)');
+
+  console.log(fmt,
+    stats.passes || 0,
+    ms(stats.duration));
+
+  // pending
+  if (stats.pending) {
+    fmt = color('pending', ' ')
+      + color('pending', ' %d pending');
+
+    console.log(fmt, stats.pending);
+  }
+
+  // failures
+  if (stats.failures) {
+    fmt = color('fail', '  %d failing');
+
+    console.error(fmt,
+      stats.failures);
+
+    Base.list(this.failures);
+    console.error();
+  }
+
+  console.log();
+};
+
+/**
+ * Pad the given `str` to `len`.
+ *
+ * @param {String} str
+ * @param {String} len
+ * @return {String}
+ * @api private
+ */
+
+function pad(str, len) {
+  str = String(str);
+  return Array(len - str.length + 1).join(' ') + str;
+}
+
+
+/**
+ * Returns an inline diff between 2 strings with coloured ANSI output
+ *
+ * @param {Error} Error with actual/expected
+ * @return {String} Diff
+ * @api private
+ */
+
+function inlineDiff(err, escape) {
+  var msg = errorDiff(err, 'WordsWithSpace', escape);
+
+  // linenos
+  var lines = msg.split('\n');
+  if (lines.length > 4) {
+    var width = String(lines.length).length;
+    msg = lines.map(function(str, i){
+      return pad(++i, width) + ' |' + ' ' + str;
+    }).join('\n');
+  }
+
+  // legend
+  msg = '\n'
+    + color('diff removed', 'actual')
+    + ' '
+    + color('diff added', 'expected')
+    + '\n\n'
+    + msg
+    + '\n';
+
+  // indent
+  msg = msg.replace(/^/gm, '      ');
+  return msg;
+}
+
+/**
+ * Returns a unified diff between 2 strings
+ *
+ * @param {Error} Error with actual/expected
+ * @return {String} Diff
+ * @api private
+ */
+
+function unifiedDiff(err, escape) {
+  var indent = '      ';
+  function cleanUp(line) {
+    if (escape) {
+      line = escapeInvisibles(line);
+    }
+    if (line[0] === '+') return indent + colorLines('diff added', line);
+    if (line[0] === '-') return indent + colorLines('diff removed', line);
+    if (line.match(/\@\@/)) return null;
+    if (line.match(/\\ No newline/)) return null;
+    else return indent + line;
+  }
+  function notBlank(line) {
+    return line != null;
+  }
+  msg = diff.createPatch('string', err.actual, err.expected);
+  var lines = msg.split('\n').splice(4);
+  return '\n      '
+         + colorLines('diff added',   '+ expected') + ' '
+         + colorLines('diff removed', '- actual')
+         + '\n\n'
+         + lines.map(cleanUp).filter(notBlank).join('\n');
+}
+
+/**
+ * Return a character diff for `err`.
+ *
+ * @param {Error} err
+ * @return {String}
+ * @api private
+ */
+
+function errorDiff(err, type, escape) {
+  var actual   = escape ? escapeInvisibles(err.actual)   : err.actual;
+  var expected = escape ? escapeInvisibles(err.expected) : err.expected;
+  return diff['diff' + type](actual, expected).map(function(str){
+    if (str.added) return colorLines('diff added', str.value);
+    if (str.removed) return colorLines('diff removed', str.value);
+    return str.value;
+  }).join('');
+}
+
+/**
+ * Returns a string with all invisible characters in plain text
+ *
+ * @param {String} line
+ * @return {String}
+ * @api private
+ */
+function escapeInvisibles(line) {
+    return line.replace(/\t/g, '<tab>')
+               .replace(/\r/g, '<CR>')
+               .replace(/\n/g, '<LF>\n');
+}
+
+/**
+ * Color lines for `str`, using the color `name`.
+ *
+ * @param {String} name
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+function colorLines(name, str) {
+  return str.split('\n').map(function(str){
+    return color(name, str);
+  }).join('\n');
+}
+
+/**
+ * Stringify `obj`.
+ *
+ * @param {Object} obj
+ * @return {String}
+ * @api private
+ */
+
+function stringify(obj) {
+  if (obj instanceof RegExp) return obj.toString();
+  return JSON.stringify(obj, null, 2);
+}
+
+/**
+ * Return a new object that has the keys in sorted order.
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+ function canonicalize(obj, stack) {
+   stack = stack || [];
+
+   if (utils.indexOf(stack, obj) !== -1) return obj;
+
+   var canonicalizedObj;
+
+   if ('[object Array]' == {}.toString.call(obj)) {
+     stack.push(obj);
+     canonicalizedObj = utils.map(obj, function(item) {
+       return canonicalize(item, stack);
+     });
+     stack.pop();
+   } else if (typeof obj === 'object' && obj !== null) {
+     stack.push(obj);
+     canonicalizedObj = {};
+     utils.forEach(utils.keys(obj).sort(), function(key) {
+       canonicalizedObj[key] = canonicalize(obj[key], stack);
+     });
+     stack.pop();
+   } else {
+     canonicalizedObj = obj;
+   }
+
+   return canonicalizedObj;
+ }
+
+/**
+ * Check that a / b have the same type.
+ *
+ * @param {Object} a
+ * @param {Object} b
+ * @return {Boolean}
+ * @api private
+ */
+
+function sameType(a, b) {
+  a = Object.prototype.toString.call(a);
+  b = Object.prototype.toString.call(b);
+  return a == b;
+}
+
+
+}); // module: reporters/base.js
+
+require.register("reporters/doc.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , utils = require('../utils');
+
+/**
+ * Expose `Doc`.
+ */
+
+exports = module.exports = Doc;
+
+/**
+ * Initialize a new `Doc` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Doc(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , total = runner.total
+    , indents = 2;
+
+  function indent() {
+    return Array(indents).join('  ');
+  }
+
+  runner.on('suite', function(suite){
+    if (suite.root) return;
+    ++indents;
+    console.log('%s<section class="suite">', indent());
+    ++indents;
+    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
+    console.log('%s<dl>', indent());
+  });
+
+  runner.on('suite end', function(suite){
+    if (suite.root) return;
+    console.log('%s</dl>', indent());
+    --indents;
+    console.log('%s</section>', indent());
+    --indents;
+  });
+
+  runner.on('pass', function(test){
+    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title));
+    var code = utils.escape(utils.clean(test.fn.toString()));
+    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code);
+  });
+}
+
+}); // module: reporters/doc.js
+
+require.register("reporters/dot.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , color = Base.color;
+
+/**
+ * Expose `Dot`.
+ */
+
+exports = module.exports = Dot;
+
+/**
+ * Initialize a new `Dot` matrix test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Dot(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , width = Base.window.width * .75 | 0
+    , n = 0;
+
+  runner.on('start', function(){
+    process.stdout.write('\n  ');
+  });
+
+  runner.on('pending', function(test){
+    process.stdout.write(color('pending', Base.symbols.dot));
+  });
+
+  runner.on('pass', function(test){
+    if (++n % width == 0) process.stdout.write('\n  ');
+    if ('slow' == test.speed) {
+      process.stdout.write(color('bright yellow', Base.symbols.dot));
+    } else {
+      process.stdout.write(color(test.speed, Base.symbols.dot));
+    }
+  });
+
+  runner.on('fail', function(test, err){
+    if (++n % width == 0) process.stdout.write('\n  ');
+    process.stdout.write(color('fail', Base.symbols.dot));
+  });
+
+  runner.on('end', function(){
+    console.log();
+    self.epilogue();
+  });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Dot.prototype = new F;
+Dot.prototype.constructor = Dot;
+
+}); // module: reporters/dot.js
+
+require.register("reporters/html-cov.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var JSONCov = require('./json-cov')
+  , fs = require('browser/fs');
+
+/**
+ * Expose `HTMLCov`.
+ */
+
+exports = module.exports = HTMLCov;
+
+/**
+ * Initialize a new `JsCoverage` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function HTMLCov(runner) {
+  var jade = require('jade')
+    , file = __dirname + '/templates/coverage.jade'
+    , str = fs.readFileSync(file, 'utf8')
+    , fn = jade.compile(str, { filename: file })
+    , self = this;
+
+  JSONCov.call(this, runner, false);
+
+  runner.on('end', function(){
+    process.stdout.write(fn({
+        cov: self.cov
+      , coverageClass: coverageClass
+    }));
+  });
+}
+
+/**
+ * Return coverage class for `n`.
+ *
+ * @return {String}
+ * @api private
+ */
+
+function coverageClass(n) {
+  if (n >= 75) return 'high';
+  if (n >= 50) return 'medium';
+  if (n >= 25) return 'low';
+  return 'terrible';
+}
+}); // module: reporters/html-cov.js
+
+require.register("reporters/html.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , utils = require('../utils')
+  , Progress = require('../browser/progress')
+  , escape = utils.escape;
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+  , setTimeout = global.setTimeout
+  , setInterval = global.setInterval
+  , clearTimeout = global.clearTimeout
+  , clearInterval = global.clearInterval;
+
+/**
+ * Expose `HTML`.
+ */
+
+exports = module.exports = HTML;
+
+/**
+ * Stats template.
+ */
+
+var statsTemplate = '<ul id="mocha-stats">'
+  + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
+  + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
+  + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
+  + '<li class="duration">duration: <em>0</em>s</li>'
+  + '</ul>';
+
+/**
+ * Initialize a new `HTML` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function HTML(runner, root) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , total = runner.total
+    , stat = fragment(statsTemplate)
+    , items = stat.getElementsByTagName('li')
+    , passes = items[1].getElementsByTagName('em')[0]
+    , passesLink = items[1].getElementsByTagName('a')[0]
+    , failures = items[2].getElementsByTagName('em')[0]
+    , failuresLink = items[2].getElementsByTagName('a')[0]
+    , duration = items[3].getElementsByTagName('em')[0]
+    , canvas = stat.getElementsByTagName('canvas')[0]
+    , report = fragment('<ul id="mocha-report"></ul>')
+    , stack = [report]
+    , progress
+    , ctx
+
+  root = root || document.getElementById('mocha');
+
+  if (canvas.getContext) {
+    var ratio = window.devicePixelRatio || 1;
+    canvas.style.width = canvas.width;
+    canvas.style.height = canvas.height;
+    canvas.width *= ratio;
+    canvas.height *= ratio;
+    ctx = canvas.getContext('2d');
+    ctx.scale(ratio, ratio);
+    progress = new Progress;
+  }
+
+  if (!root) return error('#mocha div missing, add it to your document');
+
+  // pass toggle
+  on(passesLink, 'click', function(){
+    unhide();
+    var name = /pass/.test(report.className) ? '' : ' pass';
+    report.className = report.className.replace(/fail|pass/g, '') + name;
+    if (report.className.trim()) hideSuitesWithout('test pass');
+  });
+
+  // failure toggle
+  on(failuresLink, 'click', function(){
+    unhide();
+    var name = /fail/.test(report.className) ? '' : ' fail';
+    report.className = report.className.replace(/fail|pass/g, '') + name;
+    if (report.className.trim()) hideSuitesWithout('test fail');
+  });
+
+  root.appendChild(stat);
+  root.appendChild(report);
+
+  if (progress) progress.size(40);
+
+  runner.on('suite', function(suite){
+    if (suite.root) return;
+
+    // suite
+    var url = self.suiteURL(suite);
+    var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
+
+    // container
+    stack[0].appendChild(el);
+    stack.unshift(document.createElement('ul'));
+    el.appendChild(stack[0]);
+  });
+
+  runner.on('suite end', function(suite){
+    if (suite.root) return;
+    stack.shift();
+  });
+
+  runner.on('fail', function(test, err){
+    if ('hook' == test.type) runner.emit('test end', test);
+  });
+
+  runner.on('test end', function(test){
+    // TODO: add to stats
+    var percent = stats.tests / this.total * 100 | 0;
+    if (progress) progress.update(percent).draw(ctx);
+
+    // update stats
+    var ms = new Date - stats.start;
+    text(passes, stats.passes);
+    text(failures, stats.failures);
+    text(duration, (ms / 1000).toFixed(2));
+
+    // test
+    if ('passed' == test.state) {
+      var url = self.testURL(test);
+      var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
+    } else if (test.pending) {
+      var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
+    } else {
+      var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
+      var str = test.err.stack || test.err.toString();
+
+      // FF / Opera do not add the message
+      if (!~str.indexOf(test.err.message)) {
+        str = test.err.message + '\n' + str;
+      }
+
+      // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
+      // check for the result of the stringifying.
+      if ('[object Error]' == str) str = test.err.message;
+
+      // Safari doesn't give you a stack. Let's at least provide a source line.
+      if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
+        str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
+      }
+
+      el.appendChild(fragment('<pre class="error">%e</pre>', str));
+    }
+
+    // toggle code
+    // TODO: defer
+    if (!test.pending) {
+      var h2 = el.getElementsByTagName('h2')[0];
+
+      on(h2, 'click', function(){
+        pre.style.display = 'none' == pre.style.display
+          ? 'block'
+          : 'none';
+      });
+
+      var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
+      el.appendChild(pre);
+      pre.style.display = 'none';
+    }
+
+    // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
+    if (stack[0]) stack[0].appendChild(el);
+  });
+}
+
+/**
+ * Provide suite URL
+ *
+ * @param {Object} [suite]
+ */
+
+HTML.prototype.suiteURL = function(suite){
+  return '?grep=' + encodeURIComponent(suite.fullTitle());
+};
+
+/**
+ * Provide test URL
+ *
+ * @param {Object} [test]
+ */
+
+HTML.prototype.testURL = function(test){
+  return '?grep=' + encodeURIComponent(test.fullTitle());
+};
+
+/**
+ * Display error `msg`.
+ */
+
+function error(msg) {
+  document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
+}
+
+/**
+ * Return a DOM fragment from `html`.
+ */
+
+function fragment(html) {
+  var args = arguments
+    , div = document.createElement('div')
+    , i = 1;
+
+  div.innerHTML = html.replace(/%([se])/g, function(_, type){
+    switch (type) {
+      case 's': return String(args[i++]);
+      case 'e': return escape(args[i++]);
+    }
+  });
+
+  return div.firstChild;
+}
+
+/**
+ * Check for suites that do not have elements
+ * with `classname`, and hide them.
+ */
+
+function hideSuitesWithout(classname) {
+  var suites = document.getElementsByClassName('suite');
+  for (var i = 0; i < suites.length; i++) {
+    var els = suites[i].getElementsByClassName(classname);
+    if (0 == els.length) suites[i].className += ' hidden';
+  }
+}
+
+/**
+ * Unhide .hidden suites.
+ */
+
+function unhide() {
+  var els = document.getElementsByClassName('suite hidden');
+  for (var i = 0; i < els.length; ++i) {
+    els[i].className = els[i].className.replace('suite hidden', 'suite');
+  }
+}
+
+/**
+ * Set `el` text to `str`.
+ */
+
+function text(el, str) {
+  if (el.textContent) {
+    el.textContent = str;
+  } else {
+    el.innerText = str;
+  }
+}
+
+/**
+ * Listen on `event` with callback `fn`.
+ */
+
+function on(el, event, fn) {
+  if (el.addEventListener) {
+    el.addEventListener(event, fn, false);
+  } else {
+    el.attachEvent('on' + event, fn);
+  }
+}
+
+}); // module: reporters/html.js
+
+require.register("reporters/index.js", function(module, exports, require){
+
+exports.Base = require('./base');
+exports.Dot = require('./dot');
+exports.Doc = require('./doc');
+exports.TAP = require('./tap');
+exports.JSON = require('./json');
+exports.HTML = require('./html');
+exports.List = require('./list');
+exports.Min = require('./min');
+exports.Spec = require('./spec');
+exports.Nyan = require('./nyan');
+exports.XUnit = require('./xunit');
+exports.Markdown = require('./markdown');
+exports.Progress = require('./progress');
+exports.Landing = require('./landing');
+exports.JSONCov = require('./json-cov');
+exports.HTMLCov = require('./html-cov');
+exports.JSONStream = require('./json-stream');
+
+}); // module: reporters/index.js
+
+require.register("reporters/json-cov.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base');
+
+/**
+ * Expose `JSONCov`.
+ */
+
+exports = module.exports = JSONCov;
+
+/**
+ * Initialize a new `JsCoverage` reporter.
+ *
+ * @param {Runner} runner
+ * @param {Boolean} output
+ * @api public
+ */
+
+function JSONCov(runner, output) {
+  var self = this
+    , output = 1 == arguments.length ? true : output;
+
+  Base.call(this, runner);
+
+  var tests = []
+    , failures = []
+    , passes = [];
+
+  runner.on('test end', function(test){
+    tests.push(test);
+  });
+
+  runner.on('pass', function(test){
+    passes.push(test);
+  });
+
+  runner.on('fail', function(test){
+    failures.push(test);
+  });
+
+  runner.on('end', function(){
+    var cov = global._$jscoverage || {};
+    var result = self.cov = map(cov);
+    result.stats = self.stats;
+    result.tests = tests.map(clean);
+    result.failures = failures.map(clean);
+    result.passes = passes.map(clean);
+    if (!output) return;
+    process.stdout.write(JSON.stringify(result, null, 2 ));
+  });
+}
+
+/**
+ * Map jscoverage data to a JSON structure
+ * suitable for reporting.
+ *
+ * @param {Object} cov
+ * @return {Object}
+ * @api private
+ */
+
+function map(cov) {
+  var ret = {
+      instrumentation: 'node-jscoverage'
+    , sloc: 0
+    , hits: 0
+    , misses: 0
+    , coverage: 0
+    , files: []
+  };
+
+  for (var filename in cov) {
+    var data = coverage(filename, cov[filename]);
+    ret.files.push(data);
+    ret.hits += data.hits;
+    ret.misses += data.misses;
+    ret.sloc += data.sloc;
+  }
+
+  ret.files.sort(function(a, b) {
+    return a.filename.localeCompare(b.filename);
+  });
+
+  if (ret.sloc > 0) {
+    ret.coverage = (ret.hits / ret.sloc) * 100;
+  }
+
+  return ret;
+};
+
+/**
+ * Map jscoverage data for a single source file
+ * to a JSON structure suitable for reporting.
+ *
+ * @param {String} filename name of the source file
+ * @param {Object} data jscoverage coverage data
+ * @return {Object}
+ * @api private
+ */
+
+function coverage(filename, data) {
+  var ret = {
+    filename: filename,
+    coverage: 0,
+    hits: 0,
+    misses: 0,
+    sloc: 0,
+    source: {}
+  };
+
+  data.source.forEach(function(line, num){
+    num++;
+
+    if (data[num] === 0) {
+      ret.misses++;
+      ret.sloc++;
+    } else if (data[num] !== undefined) {
+      ret.hits++;
+      ret.sloc++;
+    }
+
+    ret.source[num] = {
+        source: line
+      , coverage: data[num] === undefined
+        ? ''
+        : data[num]
+    };
+  });
+
+  ret.coverage = ret.hits / ret.sloc * 100;
+
+  return ret;
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+  return {
+      title: test.title
+    , fullTitle: test.fullTitle()
+    , duration: test.duration
+  }
+}
+
+}); // module: reporters/json-cov.js
+
+require.register("reporters/json-stream.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , color = Base.color;
+
+/**
+ * Expose `List`.
+ */
+
+exports = module.exports = List;
+
+/**
+ * Initialize a new `List` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function List(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , total = runner.total;
+
+  runner.on('start', function(){
+    console.log(JSON.stringify(['start', { total: total }]));
+  });
+
+  runner.on('pass', function(test){
+    console.log(JSON.stringify(['pass', clean(test)]));
+  });
+
+  runner.on('fail', function(test, err){
+    console.log(JSON.stringify(['fail', clean(test)]));
+  });
+
+  runner.on('end', function(){
+    process.stdout.write(JSON.stringify(['end', self.stats]));
+  });
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+  return {
+      title: test.title
+    , fullTitle: test.fullTitle()
+    , duration: test.duration
+  }
+}
+}); // module: reporters/json-stream.js
+
+require.register("reporters/json.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `JSON`.
+ */
+
+exports = module.exports = JSONReporter;
+
+/**
+ * Initialize a new `JSON` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function JSONReporter(runner) {
+  var self = this;
+  Base.call(this, runner);
+
+  var tests = []
+    , failures = []
+    , passes = [];
+
+  runner.on('test end', function(test){
+    tests.push(test);
+  });
+
+  runner.on('pass', function(test){
+    passes.push(test);
+  });
+
+  runner.on('fail', function(test){
+    failures.push(test);
+  });
+
+  runner.on('end', function(){
+    var obj = {
+        stats: self.stats
+      , tests: tests.map(clean)
+      , failures: failures.map(clean)
+      , passes: passes.map(clean)
+    };
+
+    process.stdout.write(JSON.stringify(obj, null, 2));
+  });
+}
+
+/**
+ * Return a plain-object representation of `test`
+ * free of cyclic properties etc.
+ *
+ * @param {Object} test
+ * @return {Object}
+ * @api private
+ */
+
+function clean(test) {
+  return {
+      title: test.title
+    , fullTitle: test.fullTitle()
+    , duration: test.duration
+  }
+}
+}); // module: reporters/json.js
+
+require.register("reporters/landing.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `Landing`.
+ */
+
+exports = module.exports = Landing;
+
+/**
+ * Airplane color.
+ */
+
+Base.colors.plane = 0;
+
+/**
+ * Airplane crash color.
+ */
+
+Base.colors['plane crash'] = 31;
+
+/**
+ * Runway color.
+ */
+
+Base.colors.runway = 90;
+
+/**
+ * Initialize a new `Landing` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Landing(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , width = Base.window.width * .75 | 0
+    , total = runner.total
+    , stream = process.stdout
+    , plane = color('plane', '✈')
+    , crashed = -1
+    , n = 0;
+
+  function runway() {
+    var buf = Array(width).join('-');
+    return '  ' + color('runway', buf);
+  }
+
+  runner.on('start', function(){
+    stream.write('\n  ');
+    cursor.hide();
+  });
+
+  runner.on('test end', function(test){
+    // check if the plane crashed
+    var col = -1 == crashed
+      ? width * ++n / total | 0
+      : crashed;
+
+    // show the crash
+    if ('failed' == test.state) {
+      plane = color('plane crash', '✈');
+      crashed = col;
+    }
+
+    // render landing strip
+    stream.write('\u001b[4F\n\n');
+    stream.write(runway());
+    stream.write('\n  ');
+    stream.write(color('runway', Array(col).join('⋅')));
+    stream.write(plane)
+    stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
+    stream.write(runway());
+    stream.write('\u001b[0m');
+  });
+
+  runner.on('end', function(){
+    cursor.show();
+    console.log();
+    self.epilogue();
+  });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Landing.prototype = new F;
+Landing.prototype.constructor = Landing;
+
+}); // module: reporters/landing.js
+
+require.register("reporters/list.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `List`.
+ */
+
+exports = module.exports = List;
+
+/**
+ * Initialize a new `List` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function List(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , n = 0;
+
+  runner.on('start', function(){
+    console.log();
+  });
+
+  runner.on('test', function(test){
+    process.stdout.write(color('pass', '    ' + test.fullTitle() + ': '));
+  });
+
+  runner.on('pending', function(test){
+    var fmt = color('checkmark', '  -')
+      + color('pending', ' %s');
+    console.log(fmt, test.fullTitle());
+  });
+
+  runner.on('pass', function(test){
+    var fmt = color('checkmark', '  '+Base.symbols.dot)
+      + color('pass', ' %s: ')
+      + color(test.speed, '%dms');
+    cursor.CR();
+    console.log(fmt, test.fullTitle(), test.duration);
+  });
+
+  runner.on('fail', function(test, err){
+    cursor.CR();
+    console.log(color('fail', '  %d) %s'), ++n, test.fullTitle());
+  });
+
+  runner.on('end', self.epilogue.bind(self));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+List.prototype = new F;
+List.prototype.constructor = List;
+
+
+}); // module: reporters/list.js
+
+require.register("reporters/markdown.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , utils = require('../utils');
+
+/**
+ * Expose `Markdown`.
+ */
+
+exports = module.exports = Markdown;
+
+/**
+ * Initialize a new `Markdown` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Markdown(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , level = 0
+    , buf = '';
+
+  function title(str) {
+    return Array(level).join('#') + ' ' + str;
+  }
+
+  function indent() {
+    return Array(level).join('  ');
+  }
+
+  function mapTOC(suite, obj) {
+    var ret = obj;
+    obj = obj[suite.title] = obj[suite.title] || { suite: suite };
+    suite.suites.forEach(function(suite){
+      mapTOC(suite, obj);
+    });
+    return ret;
+  }
+
+  function stringifyTOC(obj, level) {
+    ++level;
+    var buf = '';
+    var link;
+    for (var key in obj) {
+      if ('suite' == key) continue;
+      if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
+      if (key) buf += Array(level).join('  ') + link;
+      buf += stringifyTOC(obj[key], level);
+    }
+    --level;
+    return buf;
+  }
+
+  function generateTOC(suite) {
+    var obj = mapTOC(suite, {});
+    return stringifyTOC(obj, 0);
+  }
+
+  generateTOC(runner.suite);
+
+  runner.on('suite', function(suite){
+    ++level;
+    var slug = utils.slug(suite.fullTitle());
+    buf += '<a name="' + slug + '"></a>' + '\n';
+    buf += title(suite.title) + '\n';
+  });
+
+  runner.on('suite end', function(suite){
+    --level;
+  });
+
+  runner.on('pass', function(test){
+    var code = utils.clean(test.fn.toString());
+    buf += test.title + '.\n';
+    buf += '\n```js\n';
+    buf += code + '\n';
+    buf += '```\n\n';
+  });
+
+  runner.on('end', function(){
+    process.stdout.write('# TOC\n');
+    process.stdout.write(generateTOC(runner.suite));
+    process.stdout.write(buf);
+  });
+}
+}); // module: reporters/markdown.js
+
+require.register("reporters/min.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base');
+
+/**
+ * Expose `Min`.
+ */
+
+exports = module.exports = Min;
+
+/**
+ * Initialize a new `Min` minimal test reporter (best used with --watch).
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Min(runner) {
+  Base.call(this, runner);
+
+  runner.on('start', function(){
+    // clear screen
+    process.stdout.write('\u001b[2J');
+    // set cursor position
+    process.stdout.write('\u001b[1;3H');
+  });
+
+  runner.on('end', this.epilogue.bind(this));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Min.prototype = new F;
+Min.prototype.constructor = Min;
+
+
+}); // module: reporters/min.js
+
+require.register("reporters/nyan.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , color = Base.color;
+
+/**
+ * Expose `Dot`.
+ */
+
+exports = module.exports = NyanCat;
+
+/**
+ * Initialize a new `Dot` matrix test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function NyanCat(runner) {
+  Base.call(this, runner);
+  var self = this
+    , stats = this.stats
+    , width = Base.window.width * .75 | 0
+    , rainbowColors = this.rainbowColors = self.generateColors()
+    , colorIndex = this.colorIndex = 0
+    , numerOfLines = this.numberOfLines = 4
+    , trajectories = this.trajectories = [[], [], [], []]
+    , nyanCatWidth = this.nyanCatWidth = 11
+    , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
+    , scoreboardWidth = this.scoreboardWidth = 5
+    , tick = this.tick = 0
+    , n = 0;
+
+  runner.on('start', function(){
+    Base.cursor.hide();
+    self.draw();
+  });
+
+  runner.on('pending', function(test){
+    self.draw();
+  });
+
+  runner.on('pass', function(test){
+    self.draw();
+  });
+
+  runner.on('fail', function(test, err){
+    self.draw();
+  });
+
+  runner.on('end', function(){
+    Base.cursor.show();
+    for (var i = 0; i < self.numberOfLines; i++) write('\n');
+    self.epilogue();
+  });
+}
+
+/**
+ * Draw the nyan cat
+ *
+ * @api private
+ */
+
+NyanCat.prototype.draw = function(){
+  this.appendRainbow();
+  this.drawScoreboard();
+  this.drawRainbow();
+  this.drawNyanCat();
+  this.tick = !this.tick;
+};
+
+/**
+ * Draw the "scoreboard" showing the number
+ * of passes, failures and pending tests.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawScoreboard = function(){
+  var stats = this.stats;
+  var colors = Base.colors;
+
+  function draw(color, n) {
+    write(' ');
+    write('\u001b[' + color + 'm' + n + '\u001b[0m');
+    write('\n');
+  }
+
+  draw(colors.green, stats.passes);
+  draw(colors.fail, stats.failures);
+  draw(colors.pending, stats.pending);
+  write('\n');
+
+  this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Append the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.appendRainbow = function(){
+  var segment = this.tick ? '_' : '-';
+  var rainbowified = this.rainbowify(segment);
+
+  for (var index = 0; index < this.numberOfLines; index++) {
+    var trajectory = this.trajectories[index];
+    if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
+    trajectory.push(rainbowified);
+  }
+};
+
+/**
+ * Draw the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawRainbow = function(){
+  var self = this;
+
+  this.trajectories.forEach(function(line, index) {
+    write('\u001b[' + self.scoreboardWidth + 'C');
+    write(line.join(''));
+    write('\n');
+  });
+
+  this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Draw the nyan cat
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawNyanCat = function() {
+  var self = this;
+  var startWidth = this.scoreboardWidth + this.trajectories[0].length;
+  var color = '\u001b[' + startWidth + 'C';
+  var padding = '';
+
+  write(color);
+  write('_,------,');
+  write('\n');
+
+  write(color);
+  padding = self.tick ? '  ' : '   ';
+  write('_|' + padding + '/\\_/\\ ');
+  write('\n');
+
+  write(color);
+  padding = self.tick ? '_' : '__';
+  var tail = self.tick ? '~' : '^';
+  var face;
+  write(tail + '|' + padding + this.face() + ' ');
+  write('\n');
+
+  write(color);
+  padding = self.tick ? ' ' : '  ';
+  write(padding + '""  "" ');
+  write('\n');
+
+  this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Draw nyan cat face.
+ *
+ * @return {String}
+ * @api private
+ */
+
+NyanCat.prototype.face = function() {
+  var stats = this.stats;
+  if (stats.failures) {
+    return '( x .x)';
+  } else if (stats.pending) {
+    return '( o .o)';
+  } else if(stats.passes) {
+    return '( ^ .^)';
+  } else {
+    return '( - .-)';
+  }
+}
+
+/**
+ * Move cursor up `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorUp = function(n) {
+  write('\u001b[' + n + 'A');
+};
+
+/**
+ * Move cursor down `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorDown = function(n) {
+  write('\u001b[' + n + 'B');
+};
+
+/**
+ * Generate rainbow colors.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+NyanCat.prototype.generateColors = function(){
+  var colors = [];
+
+  for (var i = 0; i < (6 * 7); i++) {
+    var pi3 = Math.floor(Math.PI / 3);
+    var n = (i * (1.0 / 6));
+    var r = Math.floor(3 * Math.sin(n) + 3);
+    var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
+    var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
+    colors.push(36 * r + 6 * g + b + 16);
+  }
+
+  return colors;
+};
+
+/**
+ * Apply rainbow to the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+NyanCat.prototype.rainbowify = function(str){
+  var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
+  this.colorIndex += 1;
+  return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
+};
+
+/**
+ * Stdout helper.
+ */
+
+function write(string) {
+  process.stdout.write(string);
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+NyanCat.prototype = new F;
+NyanCat.prototype.constructor = NyanCat;
+
+
+}); // module: reporters/nyan.js
+
+require.register("reporters/progress.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `Progress`.
+ */
+
+exports = module.exports = Progress;
+
+/**
+ * General progress bar color.
+ */
+
+Base.colors.progress = 90;
+
+/**
+ * Initialize a new `Progress` bar test reporter.
+ *
+ * @param {Runner} runner
+ * @param {Object} options
+ * @api public
+ */
+
+function Progress(runner, options) {
+  Base.call(this, runner);
+
+  var self = this
+    , options = options || {}
+    , stats = this.stats
+    , width = Base.window.width * .50 | 0
+    , total = runner.total
+    , complete = 0
+    , max = Math.max;
+
+  // default chars
+  options.open = options.open || '[';
+  options.complete = options.complete || '▬';
+  options.incomplete = options.incomplete || Base.symbols.dot;
+  options.close = options.close || ']';
+  options.verbose = false;
+
+  // tests started
+  runner.on('start', function(){
+    console.log();
+    cursor.hide();
+  });
+
+  // tests complete
+  runner.on('test end', function(){
+    complete++;
+    var incomplete = total - complete
+      , percent = complete / total
+      , n = width * percent | 0
+      , i = width - n;
+
+    cursor.CR();
+    process.stdout.write('\u001b[J');
+    process.stdout.write(color('progress', '  ' + options.open));
+    process.stdout.write(Array(n).join(options.complete));
+    process.stdout.write(Array(i).join(options.incomplete));
+    process.stdout.write(color('progress', options.close));
+    if (options.verbose) {
+      process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
+    }
+  });
+
+  // tests are complete, output some stats
+  // and the failures if any
+  runner.on('end', function(){
+    cursor.show();
+    console.log();
+    self.epilogue();
+  });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Progress.prototype = new F;
+Progress.prototype.constructor = Progress;
+
+
+}); // module: reporters/progress.js
+
+require.register("reporters/spec.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `Spec`.
+ */
+
+exports = module.exports = Spec;
+
+/**
+ * Initialize a new `Spec` test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function Spec(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , indents = 0
+    , n = 0;
+
+  function indent() {
+    return Array(indents).join('  ')
+  }
+
+  runner.on('start', function(){
+    console.log();
+  });
+
+  runner.on('suite', function(suite){
+    ++indents;
+    console.log(color('suite', '%s%s'), indent(), suite.title);
+  });
+
+  runner.on('suite end', function(suite){
+    --indents;
+    if (1 == indents) console.log();
+  });
+
+  runner.on('pending', function(test){
+    var fmt = indent() + color('pending', '  - %s');
+    console.log(fmt, test.title);
+  });
+
+  runner.on('pass', function(test){
+    if ('fast' == test.speed) {
+      var fmt = indent()
+        + color('checkmark', '  ' + Base.symbols.ok)
+        + color('pass', ' %s ');
+      cursor.CR();
+      console.log(fmt, test.title);
+    } else {
+      var fmt = indent()
+        + color('checkmark', '  ' + Base.symbols.ok)
+        + color('pass', ' %s ')
+        + color(test.speed, '(%dms)');
+      cursor.CR();
+      console.log(fmt, test.title, test.duration);
+    }
+  });
+
+  runner.on('fail', function(test, err){
+    cursor.CR();
+    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
+  });
+
+  runner.on('end', self.epilogue.bind(self));
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+Spec.prototype = new F;
+Spec.prototype.constructor = Spec;
+
+
+}); // module: reporters/spec.js
+
+require.register("reporters/tap.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , cursor = Base.cursor
+  , color = Base.color;
+
+/**
+ * Expose `TAP`.
+ */
+
+exports = module.exports = TAP;
+
+/**
+ * Initialize a new `TAP` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function TAP(runner) {
+  Base.call(this, runner);
+
+  var self = this
+    , stats = this.stats
+    , n = 1
+    , passes = 0
+    , failures = 0;
+
+  runner.on('start', function(){
+    var total = runner.grepTotal(runner.suite);
+    console.log('%d..%d', 1, total);
+  });
+
+  runner.on('test end', function(){
+    ++n;
+  });
+
+  runner.on('pending', function(test){
+    console.log('ok %d %s # SKIP -', n, title(test));
+  });
+
+  runner.on('pass', function(test){
+    passes++;
+    console.log('ok %d %s', n, title(test));
+  });
+
+  runner.on('fail', function(test, err){
+    failures++;
+    console.log('not ok %d %s', n, title(test));
+    if (err.stack) console.log(err.stack.replace(/^/gm, '  '));
+  });
+
+  runner.on('end', function(){
+    console.log('# tests ' + (passes + failures));
+    console.log('# pass ' + passes);
+    console.log('# fail ' + failures);
+  });
+}
+
+/**
+ * Return a TAP-safe title of `test`
+ *
+ * @param {Object} test
+ * @return {String}
+ * @api private
+ */
+
+function title(test) {
+  return test.fullTitle().replace(/#/g, '');
+}
+
+}); // module: reporters/tap.js
+
+require.register("reporters/xunit.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+  , utils = require('../utils')
+  , escape = utils.escape;
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+  , setTimeout = global.setTimeout
+  , setInterval = global.setInterval
+  , clearTimeout = global.clearTimeout
+  , clearInterval = global.clearInterval;
+
+/**
+ * Expose `XUnit`.
+ */
+
+exports = module.exports = XUnit;
+
+/**
+ * Initialize a new `XUnit` reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function XUnit(runner) {
+  Base.call(this, runner);
+  var stats = this.stats
+    , tests = []
+    , self = this;
+
+  runner.on('pending', function(test){
+    tests.push(test);
+  });
+
+  runner.on('pass', function(test){
+    tests.push(test);
+  });
+
+  runner.on('fail', function(test){
+    tests.push(test);
+  });
+
+  runner.on('end', function(){
+    console.log(tag('testsuite', {
+        name: 'Mocha Tests'
+      , tests: stats.tests
+      , failures: stats.failures
+      , errors: stats.failures
+      , skipped: stats.tests - stats.failures - stats.passes
+      , timestamp: (new Date).toUTCString()
+      , time: (stats.duration / 1000) || 0
+    }, false));
+
+    tests.forEach(test);
+    console.log('</testsuite>');
+  });
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+XUnit.prototype = new F;
+XUnit.prototype.constructor = XUnit;
+
+
+/**
+ * Output tag for the given `test.`
+ */
+
+function test(test) {
+  var attrs = {
+      classname: test.parent.fullTitle()
+    , name: test.title
+    , time: (test.duration / 1000) || 0
+  };
+
+  if ('failed' == test.state) {
+    var err = test.err;
+    attrs.message = escape(err.message);
+    console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
+  } else if (test.pending) {
+    console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
+  } else {
+    console.log(tag('testcase', attrs, true) );
+  }
+}
+
+/**
+ * HTML tag helper.
+ */
+
+function tag(name, attrs, close, content) {
+  var end = close ? '/>' : '>'
+    , pairs = []
+    , tag;
+
+  for (var key in attrs) {
+    pairs.push(key + '="' + escape(attrs[key]) + '"');
+  }
+
+  tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
+  if (content) tag += content + '</' + name + end;
+  return tag;
+}
+
+/**
+ * Return cdata escaped CDATA `str`.
+ */
+
+function cdata(str) {
+  return '<![CDATA[' + escape(str) + ']]>';
+}
+
+}); // module: reporters/xunit.js
+
+require.register("runnable.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+  , debug = require('browser/debug')('mocha:runnable')
+  , milliseconds = require('./ms');
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+  , setTimeout = global.setTimeout
+  , setInterval = global.setInterval
+  , clearTimeout = global.clearTimeout
+  , clearInterval = global.clearInterval;
+
+/**
+ * Object#toString().
+ */
+
+var toString = Object.prototype.toString;
+
+/**
+ * Expose `Runnable`.
+ */
+
+module.exports = Runnable;
+
+/**
+ * Initialize a new `Runnable` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Runnable(title, fn) {
+  this.title = title;
+  this.fn = fn;
+  this.async = fn && fn.length;
+  this.sync = ! this.async;
+  this._timeout = 2000;
+  this._slow = 75;
+  this.timedOut = false;
+}
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runnable.prototype = new F;
+Runnable.prototype.constructor = Runnable;
+
+
+/**
+ * Set & get timeout `ms`.
+ *
+ * @param {Number|String} ms
+ * @return {Runnable|Number} ms or self
+ * @api private
+ */
+
+Runnable.prototype.timeout = function(ms){
+  if (0 == arguments.length) return this._timeout;
+  if ('string' == typeof ms) ms = milliseconds(ms);
+  debug('timeout %d', ms);
+  this._timeout = ms;
+  if (this.timer) this.resetTimeout();
+  return this;
+};
+
+/**
+ * Set & get slow `ms`.
+ *
+ * @param {Number|String} ms
+ * @return {Runnable|Number} ms or self
+ * @api private
+ */
+
+Runnable.prototype.slow = function(ms){
+  if (0 === arguments.length) return this._slow;
+  if ('string' == typeof ms) ms = milliseconds(ms);
+  debug('timeout %d', ms);
+  this._slow = ms;
+  return this;
+};
+
+/**
+ * Return the full title generated by recursively
+ * concatenating the parent's full title.
+ *
+ * @return {String}
+ * @api public
+ */
+
+Runnable.prototype.fullTitle = function(){
+  return this.parent.fullTitle() + ' ' + this.title;
+};
+
+/**
+ * Clear the timeout.
+ *
+ * @api private
+ */
+
+Runnable.prototype.clearTimeout = function(){
+  clearTimeout(this.timer);
+};
+
+/**
+ * Inspect the runnable void of private properties.
+ *
+ * @return {String}
+ * @api private
+ */
+
+Runnable.prototype.inspect = function(){
+  return JSON.stringify(this, function(key, val){
+    if ('_' == key[0]) return;
+    if ('parent' == key) return '#<Suite>';
+    if ('ctx' == key) return '#<Context>';
+    return val;
+  }, 2);
+};
+
+/**
+ * Reset the timeout.
+ *
+ * @api private
+ */
+
+Runnable.prototype.resetTimeout = function(){
+  var self = this;
+  var ms = this.timeout() || 1e9;
+
+  this.clearTimeout();
+  this.timer = setTimeout(function(){
+    self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
+    self.timedOut = true;
+  }, ms);
+};
+
+/**
+ * Whitelist these globals for this test run
+ *
+ * @api private
+ */
+Runnable.prototype.globals = function(arr){
+  var self = this;
+  this._allowedGlobals = arr;
+};
+
+/**
+ * Run the test and invoke `fn(err)`.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runnable.prototype.run = function(fn){
+  var self = this
+    , ms = this.timeout()
+    , start = new Date
+    , ctx = this.ctx
+    , finished
+    , emitted;
+
+  if (ctx) ctx.runnable(this);
+
+  // timeout
+  if (this.async) {
+    if (ms) {
+      this.timer = setTimeout(function(){
+        done(new Error('timeout of ' + ms + 'ms exceeded'));
+        self.timedOut = true;
+      }, ms);
+    }
+  }
+
+  // called multiple times
+  function multiple(err) {
+    if (emitted) return;
+    emitted = true;
+    self.emit('error', err || new Error('done() called multiple times'));
+  }
+
+  // finished
+  function done(err) {
+    if (self.timedOut) return;
+    if (finished) return multiple(err);
+    self.clearTimeout();
+    self.duration = new Date - start;
+    finished = true;
+    fn(err);
+  }
+
+  // for .resetTimeout()
+  this.callback = done;
+
+  // async
+  if (this.async) {
+    try {
+      this.fn.call(ctx, function(err){
+        if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
+        if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
+        done();
+      });
+    } catch (err) {
+      done(err);
+    }
+    return;
+  }
+
+  if (this.asyncOnly) {
+    return done(new Error('--async-only option in use without declaring `done()`'));
+  }
+
+  // sync
+  try {
+    if (!this.pending) this.fn.call(ctx);
+    this.duration = new Date - start;
+    fn();
+  } catch (err) {
+    fn(err);
+  }
+};
+
+}); // module: runnable.js
+
+require.register("runner.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+  , debug = require('browser/debug')('mocha:runner')
+  , Test = require('./test')
+  , utils = require('./utils')
+  , filter = utils.filter
+  , keys = utils.keys;
+
+/**
+ * Non-enumerable globals.
+ */
+
+var globals = [
+  'setTimeout',
+  'clearTimeout',
+  'setInterval',
+  'clearInterval',
+  'XMLHttpRequest',
+  'Date'
+];
+
+/**
+ * Expose `Runner`.
+ */
+
+module.exports = Runner;
+
+/**
+ * Initialize a `Runner` for the given `suite`.
+ *
+ * Events:
+ *
+ *   - `start`  execution started
+ *   - `end`  execution complete
+ *   - `suite`  (suite) test suite execution started
+ *   - `suite end`  (suite) all tests (and sub-suites) have finished
+ *   - `test`  (test) test execution started
+ *   - `test end`  (test) test completed
+ *   - `hook`  (hook) hook execution started
+ *   - `hook end`  (hook) hook complete
+ *   - `pass`  (test) test passed
+ *   - `fail`  (test, err) test failed
+ *   - `pending`  (test) test pending
+ *
+ * @api public
+ */
+
+function Runner(suite) {
+  var self = this;
+  this._globals = [];
+  this._abort = false;
+  this.suite = suite;
+  this.total = suite.total();
+  this.failures = 0;
+  this.on('test end', function(test){ self.checkGlobals(test); });
+  this.on('hook end', function(hook){ self.checkGlobals(hook); });
+  this.grep(/.*/);
+  this.globals(this.globalProps().concat(extraGlobals()));
+}
+
+/**
+ * Wrapper for setImmediate, process.nextTick, or browser polyfill.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.immediately = global.setImmediate || process.nextTick;
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runner.prototype = new F;
+Runner.prototype.constructor = Runner;
+
+
+/**
+ * Run tests with full titles matching `re`. Updates runner.total
+ * with number of tests matched.
+ *
+ * @param {RegExp} re
+ * @param {Boolean} invert
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.grep = function(re, invert){
+  debug('grep %s', re);
+  this._grep = re;
+  this._invert = invert;
+  this.total = this.grepTotal(this.suite);
+  return this;
+};
+
+/**
+ * Returns the number of tests matching the grep search for the
+ * given suite.
+ *
+ * @param {Suite} suite
+ * @return {Number}
+ * @api public
+ */
+
+Runner.prototype.grepTotal = function(suite) {
+  var self = this;
+  var total = 0;
+
+  suite.eachTest(function(test){
+    var match = self._grep.test(test.fullTitle());
+    if (self._invert) match = !match;
+    if (match) total++;
+  });
+
+  return total;
+};
+
+/**
+ * Return a list of global properties.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+Runner.prototype.globalProps = function() {
+  var props = utils.keys(global);
+
+  // non-enumerables
+  for (var i = 0; i < globals.length; ++i) {
+    if (~utils.indexOf(props, globals[i])) continue;
+    props.push(globals[i]);
+  }
+
+  return props;
+};
+
+/**
+ * Allow the given `arr` of globals.
+ *
+ * @param {Array} arr
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.globals = function(arr){
+  if (0 == arguments.length) return this._globals;
+  debug('globals %j', arr);
+  this._globals = this._globals.concat(arr);
+  return this;
+};
+
+/**
+ * Check for global variable leaks.
+ *
+ * @api private
+ */
+
+Runner.prototype.checkGlobals = function(test){
+  if (this.ignoreLeaks) return;
+  var ok = this._globals;
+
+  var globals = this.globalProps();
+  var isNode = process.kill;
+  var leaks;
+
+  if (test) {
+    ok = ok.concat(test._allowedGlobals || []);
+  }
+
+  if(this.prevGlobalsLength == globals.length) return;
+  this.prevGlobalsLength = globals.length;
+
+  leaks = filterLeaks(ok, globals);
+  this._globals = this._globals.concat(leaks);
+
+  if (leaks.length > 1) {
+    this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
+  } else if (leaks.length) {
+    this.fail(test, new Error('global leak detected: ' + leaks[0]));
+  }
+};
+
+/**
+ * Fail the given `test`.
+ *
+ * @param {Test} test
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.fail = function(test, err){
+  ++this.failures;
+  test.state = 'failed';
+
+  if ('string' == typeof err) {
+    err = new Error('the string "' + err + '" was thrown, throw an Error :)');
+  }
+
+  this.emit('fail', test, err);
+};
+
+/**
+ * Fail the given `hook` with `err`.
+ *
+ * Hook failures work in the following pattern:
+ * - If bail, then exit
+ * - Failed `before` hook skips all tests in a suite and subsuites,
+ *   but jumps to corresponding `after` hook
+ * - Failed `before each` hook skips remaining tests in a
+ *   suite and jumps to corresponding `after each` hook,
+ *   which is run only once
+ * - Failed `after` hook does not alter
+ *   execution order
+ * - Failed `after each` hook skips remaining tests in a
+ *   suite and subsuites, but executes other `after each`
+ *   hooks
+ *
+ * @param {Hook} hook
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.failHook = function(hook, err){
+  this.fail(hook, err);
+  if (this.suite.bail()) {
+    this.emit('end');
+  }
+};
+
+/**
+ * Run hook `name` callbacks and then invoke `fn()`.
+ *
+ * @param {String} name
+ * @param {Function} function
+ * @api private
+ */
+
+Runner.prototype.hook = function(name, fn){
+  var suite = this.suite
+    , hooks = suite['_' + name]
+    , self = this
+    , timer;
+
+  function next(i) {
+    var hook = hooks[i];
+    if (!hook) return fn();
+    if (self.failures && suite.bail()) return fn();
+    self.currentRunnable = hook;
+
+    hook.ctx.currentTest = self.test;
+
+    self.emit('hook', hook);
+
+    hook.on('error', function(err){
+      self.failHook(hook, err);
+    });
+
+    hook.run(function(err){
+      hook.removeAllListeners('error');
+      var testError = hook.error();
+      if (testError) self.fail(self.test, testError);
+      if (err) {
+        self.failHook(hook, err);
+
+        // stop executing hooks, notify callee of hook err
+        return fn(err);
+      }
+      self.emit('hook end', hook);
+      delete hook.ctx.currentTest;
+      next(++i);
+    });
+  }
+
+  Runner.immediately(function(){
+    next(0);
+  });
+};
+
+/**
+ * Run hook `name` for the given array of `suites`
+ * in order, and callback `fn(err, errSuite)`.
+ *
+ * @param {String} name
+ * @param {Array} suites
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hooks = function(name, suites, fn){
+  var self = this
+    , orig = this.suite;
+
+  function next(suite) {
+    self.suite = suite;
+
+    if (!suite) {
+      self.suite = orig;
+      return fn();
+    }
+
+    self.hook(name, function(err){
+      if (err) {
+        var errSuite = self.suite;
+        self.suite = orig;
+        return fn(err, errSuite);
+      }
+
+      next(suites.pop());
+    });
+  }
+
+  next(suites.pop());
+};
+
+/**
+ * Run hooks from the top level down.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hookUp = function(name, fn){
+  var suites = [this.suite].concat(this.parents()).reverse();
+  this.hooks(name, suites, fn);
+};
+
+/**
+ * Run hooks from the bottom up.
+ *
+ * @param {String} name
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.hookDown = function(name, fn){
+  var suites = [this.suite].concat(this.parents());
+  this.hooks(name, suites, fn);
+};
+
+/**
+ * Return an array of parent Suites from
+ * closest to furthest.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+Runner.prototype.parents = function(){
+  var suite = this.suite
+    , suites = [];
+  while (suite = suite.parent) suites.push(suite);
+  return suites;
+};
+
+/**
+ * Run the current test and callback `fn(err)`.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runTest = function(fn){
+  var test = this.test
+    , self = this;
+
+  if (this.asyncOnly) test.asyncOnly = true;
+
+  try {
+    test.on('error', function(err){
+      self.fail(test, err);
+    });
+    test.run(fn);
+  } catch (err) {
+    fn(err);
+  }
+};
+
+/**
+ * Run tests in the given `suite` and invoke
+ * the callback `fn()` when complete.
+ *
+ * @param {Suite} suite
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runTests = function(suite, fn){
+  var self = this
+    , tests = suite.tests.slice()
+    , test;
+
+
+  function hookErr(err, errSuite, after) {
+    // before/after Each hook for errSuite failed:
+    var orig = self.suite;
+
+    // for failed 'after each' hook start from errSuite parent,
+    // otherwise start from errSuite itself
+    self.suite = after ? errSuite.parent : errSuite;
+
+    if (self.suite) {
+      // call hookUp afterEach
+      self.hookUp('afterEach', function(err2, errSuite2) {
+        self.suite = orig;
+        // some hooks may fail even now
+        if (err2) return hookErr(err2, errSuite2, true);
+        // report error suite
+        fn(errSuite);
+      });
+    } else {
+      // there is no need calling other 'after each' hooks
+      self.suite = orig;
+      fn(errSuite);
+    }
+  }
+
+  function next(err, errSuite) {
+    // if we bail after first err
+    if (self.failures && suite._bail) return fn();
+
+    if (self._abort) return fn();
+
+    if (err) return hookErr(err, errSuite, true);
+
+    // next test
+    test = tests.shift();
+
+    // all done
+    if (!test) return fn();
+
+    // grep
+    var match = self._grep.test(test.fullTitle());
+    if (self._invert) match = !match;
+    if (!match) return next();
+
+    // pending
+    if (test.pending) {
+      self.emit('pending', test);
+      self.emit('test end', test);
+      return next();
+    }
+
+    // execute test and hook(s)
+    self.emit('test', self.test = test);
+    self.hookDown('beforeEach', function(err, errSuite){
+
+      if (err) return hookErr(err, errSuite, false);
+
+      self.currentRunnable = self.test;
+      self.runTest(function(err){
+        test = self.test;
+
+        if (err) {
+          self.fail(test, err);
+          self.emit('test end', test);
+          return self.hookUp('afterEach', next);
+        }
+
+        test.state = 'passed';
+        self.emit('pass', test);
+        self.emit('test end', test);
+        self.hookUp('afterEach', next);
+      });
+    });
+  }
+
+  this.next = next;
+  next();
+};
+
+/**
+ * Run the given `suite` and invoke the
+ * callback `fn()` when complete.
+ *
+ * @param {Suite} suite
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.prototype.runSuite = function(suite, fn){
+  var total = this.grepTotal(suite)
+    , self = this
+    , i = 0;
+
+  debug('run suite %s', suite.fullTitle());
+
+  if (!total) return fn();
+
+  this.emit('suite', this.suite = suite);
+
+  function next(errSuite) {
+    if (errSuite) {
+      // current suite failed on a hook from errSuite
+      if (errSuite == suite) {
+        // if errSuite is current suite
+        // continue to the next sibling suite
+        return done();
+      } else {
+        // errSuite is among the parents of current suite
+        // stop execution of errSuite and all sub-suites
+        return done(errSuite);
+      }
+    }
+
+    if (self._abort) return done();
+
+    var curr = suite.suites[i++];
+    if (!curr) return done();
+    self.runSuite(curr, next);
+  }
+
+  function done(errSuite) {
+    self.suite = suite;
+    self.hook('afterAll', function(){
+      self.emit('suite end', suite);
+      fn(errSuite);
+    });
+  }
+
+  this.hook('beforeAll', function(err){
+    if (err) return done();
+    self.runTests(suite, next);
+  });
+};
+
+/**
+ * Handle uncaught exceptions.
+ *
+ * @param {Error} err
+ * @api private
+ */
+
+Runner.prototype.uncaught = function(err){
+  debug('uncaught exception %s', err.message);
+  var runnable = this.currentRunnable;
+  if (!runnable || 'failed' == runnable.state) return;
+  runnable.clearTimeout();
+  err.uncaught = true;
+  this.fail(runnable, err);
+
+  // recover from test
+  if ('test' == runnable.type) {
+    this.emit('test end', runnable);
+    this.hookUp('afterEach', this.next);
+    return;
+  }
+
+  // bail on hooks
+  this.emit('end');
+};
+
+/**
+ * Run the root suite and invoke `fn(failures)`
+ * on completion.
+ *
+ * @param {Function} fn
+ * @return {Runner} for chaining
+ * @api public
+ */
+
+Runner.prototype.run = function(fn){
+  var self = this
+    , fn = fn || function(){};
+
+  function uncaught(err){
+    self.uncaught(err);
+  }
+
+  debug('start');
+
+  // callback
+  this.on('end', function(){
+    debug('end');
+    process.removeListener('uncaughtException', uncaught);
+    fn(self.failures);
+  });
+
+  // run suites
+  this.emit('start');
+  this.runSuite(this.suite, function(){
+    debug('finished running');
+    self.emit('end');
+  });
+
+  // uncaught exception
+  process.on('uncaughtException', uncaught);
+
+  return this;
+};
+
+/**
+ * Cleanly abort execution
+ *
+ * @return {Runner} for chaining
+ * @api public
+ */
+Runner.prototype.abort = function(){
+  debug('aborting');
+  this._abort = true;
+}
+
+/**
+ * Filter leaks with the given globals flagged as `ok`.
+ *
+ * @param {Array} ok
+ * @param {Array} globals
+ * @return {Array}
+ * @api private
+ */
+
+function filterLeaks(ok, globals) {
+  return filter(globals, function(key){
+    // Firefox and Chrome exposes iframes as index inside the window object
+    if (/^d+/.test(key)) return false;
+
+    // in firefox
+    // if runner runs in an iframe, this iframe's window.getInterface method not init at first
+    // it is assigned in some seconds
+    if (global.navigator && /^getInterface/.test(key)) return false;
+
+    // an iframe could be approached by window[iframeIndex]
+    // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
+    if (global.navigator && /^\d+/.test(key)) return false;
+
+    // Opera and IE expose global variables for HTML element IDs (issue #243)
+    if (/^mocha-/.test(key)) return false;
+
+    var matched = filter(ok, function(ok){
+      if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
+      return key == ok;
+    });
+    return matched.length == 0 && (!global.navigator || 'onerror' !== key);
+  });
+}
+
+/**
+ * Array of globals dependent on the environment.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+ function extraGlobals() {
+  if (typeof(process) === 'object' &&
+      typeof(process.version) === 'string') {
+
+    var nodeVersion = process.version.split('.').reduce(function(a, v) {
+      return a << 8 | v;
+    });
+
+    // 'errno' was renamed to process._errno in v0.9.11.
+
+    if (nodeVersion < 0x00090B) {
+      return ['errno'];
+    }
+  }
+
+  return [];
+ }
+
+}); // module: runner.js
+
+require.register("suite.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var EventEmitter = require('browser/events').EventEmitter
+  , debug = require('browser/debug')('mocha:suite')
+  , milliseconds = require('./ms')
+  , utils = require('./utils')
+  , Hook = require('./hook');
+
+/**
+ * Expose `Suite`.
+ */
+
+exports = module.exports = Suite;
+
+/**
+ * Create a new `Suite` with the given `title`
+ * and parent `Suite`. When a suite with the
+ * same title is already present, that suite
+ * is returned to provide nicer reporter
+ * and more flexible meta-testing.
+ *
+ * @param {Suite} parent
+ * @param {String} title
+ * @return {Suite}
+ * @api public
+ */
+
+exports.create = function(parent, title){
+  var suite = new Suite(title, parent.ctx);
+  suite.parent = parent;
+  if (parent.pending) suite.pending = true;
+  title = suite.fullTitle();
+  parent.addSuite(suite);
+  return suite;
+};
+
+/**
+ * Initialize a new `Suite` with the given
+ * `title` and `ctx`.
+ *
+ * @param {String} title
+ * @param {Context} ctx
+ * @api private
+ */
+
+function Suite(title, ctx) {
+  this.title = title;
+  this.ctx = ctx;
+  this.suites = [];
+  this.tests = [];
+  this.pending = false;
+  this._beforeEach = [];
+  this._beforeAll = [];
+  this._afterEach = [];
+  this._afterAll = [];
+  this.root = !title;
+  this._timeout = 2000;
+  this._slow = 75;
+  this._bail = false;
+}
+
+/**
+ * Inherit from `EventEmitter.prototype`.
+ */
+
+function F(){};
+F.prototype = EventEmitter.prototype;
+Suite.prototype = new F;
+Suite.prototype.constructor = Suite;
+
+
+/**
+ * Return a clone of this `Suite`.
+ *
+ * @return {Suite}
+ * @api private
+ */
+
+Suite.prototype.clone = function(){
+  var suite = new Suite(this.title);
+  debug('clone');
+  suite.ctx = this.ctx;
+  suite.timeout(this.timeout());
+  suite.slow(this.slow());
+  suite.bail(this.bail());
+  return suite;
+};
+
+/**
+ * Set timeout `ms` or short-hand such as "2s".
+ *
+ * @param {Number|String} ms
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.timeout = function(ms){
+  if (0 == arguments.length) return this._timeout;
+  if ('string' == typeof ms) ms = milliseconds(ms);
+  debug('timeout %d', ms);
+  this._timeout = parseInt(ms, 10);
+  return this;
+};
+
+/**
+ * Set slow `ms` or short-hand such as "2s".
+ *
+ * @param {Number|String} ms
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.slow = function(ms){
+  if (0 === arguments.length) return this._slow;
+  if ('string' == typeof ms) ms = milliseconds(ms);
+  debug('slow %d', ms);
+  this._slow = ms;
+  return this;
+};
+
+/**
+ * Sets whether to bail after first error.
+ *
+ * @parma {Boolean} bail
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.bail = function(bail){
+  if (0 == arguments.length) return this._bail;
+  debug('bail %s', bail);
+  this._bail = bail;
+  return this;
+};
+
+/**
+ * Run `fn(test[, done])` before running tests.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.beforeAll = function(fn){
+  if (this.pending) return this;
+  var hook = new Hook('"before all" hook', fn);
+  hook.parent = this;
+  hook.timeout(this.timeout());
+  hook.slow(this.slow());
+  hook.ctx = this.ctx;
+  this._beforeAll.push(hook);
+  this.emit('beforeAll', hook);
+  return this;
+};
+
+/**
+ * Run `fn(test[, done])` after running tests.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.afterAll = function(fn){
+  if (this.pending) return this;
+  var hook = new Hook('"after all" hook', fn);
+  hook.parent = this;
+  hook.timeout(this.timeout());
+  hook.slow(this.slow());
+  hook.ctx = this.ctx;
+  this._afterAll.push(hook);
+  this.emit('afterAll', hook);
+  return this;
+};
+
+/**
+ * Run `fn(test[, done])` before each test case.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.beforeEach = function(fn){
+  if (this.pending) return this;
+  var hook = new Hook('"before each" hook', fn);
+  hook.parent = this;
+  hook.timeout(this.timeout());
+  hook.slow(this.slow());
+  hook.ctx = this.ctx;
+  this._beforeEach.push(hook);
+  this.emit('beforeEach', hook);
+  return this;
+};
+
+/**
+ * Run `fn(test[, done])` after each test case.
+ *
+ * @param {Function} fn
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.afterEach = function(fn){
+  if (this.pending) return this;
+  var hook = new Hook('"after each" hook', fn);
+  hook.parent = this;
+  hook.timeout(this.timeout());
+  hook.slow(this.slow());
+  hook.ctx = this.ctx;
+  this._afterEach.push(hook);
+  this.emit('afterEach', hook);
+  return this;
+};
+
+/**
+ * Add a test `suite`.
+ *
+ * @param {Suite} suite
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.addSuite = function(suite){
+  suite.parent = this;
+  suite.timeout(this.timeout());
+  suite.slow(this.slow());
+  suite.bail(this.bail());
+  this.suites.push(suite);
+  this.emit('suite', suite);
+  return this;
+};
+
+/**
+ * Add a `test` to this suite.
+ *
+ * @param {Test} test
+ * @return {Suite} for chaining
+ * @api private
+ */
+
+Suite.prototype.addTest = function(test){
+  test.parent = this;
+  test.timeout(this.timeout());
+  test.slow(this.slow());
+  test.ctx = this.ctx;
+  this.tests.push(test);
+  this.emit('test', test);
+  return this;
+};
+
+/**
+ * Return the full title generated by recursively
+ * concatenating the parent's full title.
+ *
+ * @return {String}
+ * @api public
+ */
+
+Suite.prototype.fullTitle = function(){
+  if (this.parent) {
+    var full = this.parent.fullTitle();
+    if (full) return full + ' ' + this.title;
+  }
+  return this.title;
+};
+
+/**
+ * Return the total number of tests.
+ *
+ * @return {Number}
+ * @api public
+ */
+
+Suite.prototype.total = function(){
+  return utils.reduce(this.suites, function(sum, suite){
+    return sum + suite.total();
+  }, 0) + this.tests.length;
+};
+
+/**
+ * Iterates through each suite recursively to find
+ * all tests. Applies a function in the format
+ * `fn(test)`.
+ *
+ * @param {Function} fn
+ * @return {Suite}
+ * @api private
+ */
+
+Suite.prototype.eachTest = function(fn){
+  utils.forEach(this.tests, fn);
+  utils.forEach(this.suites, function(suite){
+    suite.eachTest(fn);
+  });
+  return this;
+};
+
+}); // module: suite.js
+
+require.register("test.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var Runnable = require('./runnable');
+
+/**
+ * Expose `Test`.
+ */
+
+module.exports = Test;
+
+/**
+ * Initialize a new `Test` with the given `title` and callback `fn`.
+ *
+ * @param {String} title
+ * @param {Function} fn
+ * @api private
+ */
+
+function Test(title, fn) {
+  Runnable.call(this, title, fn);
+  this.pending = !fn;
+  this.type = 'test';
+}
+
+/**
+ * Inherit from `Runnable.prototype`.
+ */
+
+function F(){};
+F.prototype = Runnable.prototype;
+Test.prototype = new F;
+Test.prototype.constructor = Test;
+
+
+}); // module: test.js
+
+require.register("utils.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var fs = require('browser/fs')
+  , path = require('browser/path')
+  , join = path.join
+  , debug = require('browser/debug')('mocha:watch');
+
+/**
+ * Ignored directories.
+ */
+
+var ignore = ['node_modules', '.git'];
+
+/**
+ * Escape special characters in the given string of html.
+ *
+ * @param  {String} html
+ * @return {String}
+ * @api private
+ */
+
+exports.escape = function(html){
+  return String(html)
+    .replace(/&/g, '&')
+    .replace(/"/g, '"')
+    .replace(/</g, '<')
+    .replace(/>/g, '>');
+};
+
+/**
+ * Array#forEach (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @param {Object} scope
+ * @api private
+ */
+
+exports.forEach = function(arr, fn, scope){
+  for (var i = 0, l = arr.length; i < l; i++)
+    fn.call(scope, arr[i], i);
+};
+
+/**
+ * Array#map (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @param {Object} scope
+ * @api private
+ */
+
+exports.map = function(arr, fn, scope){
+  var result = [];
+  for (var i = 0, l = arr.length; i < l; i++)
+    result.push(fn.call(scope, arr[i], i));
+  return result;
+};
+
+/**
+ * Array#indexOf (<=IE8)
+ *
+ * @parma {Array} arr
+ * @param {Object} obj to find index of
+ * @param {Number} start
+ * @api private
+ */
+
+exports.indexOf = function(arr, obj, start){
+  for (var i = start || 0, l = arr.length; i < l; i++) {
+    if (arr[i] === obj)
+      return i;
+  }
+  return -1;
+};
+
+/**
+ * Array#reduce (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @param {Object} initial value
+ * @api private
+ */
+
+exports.reduce = function(arr, fn, val){
+  var rval = val;
+
+  for (var i = 0, l = arr.length; i < l; i++) {
+    rval = fn(rval, arr[i], i, arr);
+  }
+
+  return rval;
+};
+
+/**
+ * Array#filter (<=IE8)
+ *
+ * @param {Array} array
+ * @param {Function} fn
+ * @api private
+ */
+
+exports.filter = function(arr, fn){
+  var ret = [];
+
+  for (var i = 0, l = arr.length; i < l; i++) {
+    var val = arr[i];
+    if (fn(val, i, arr)) ret.push(val);
+  }
+
+  return ret;
+};
+
+/**
+ * Object.keys (<=IE8)
+ *
+ * @param {Object} obj
+ * @return {Array} keys
+ * @api private
+ */
+
+exports.keys = Object.keys || function(obj) {
+  var keys = []
+    , has = Object.prototype.hasOwnProperty // for `window` on <=IE8
+
+  for (var key in obj) {
+    if (has.call(obj, key)) {
+      keys.push(key);
+    }
+  }
+
+  return keys;
+};
+
+/**
+ * Watch the given `files` for changes
+ * and invoke `fn(file)` on modification.
+ *
+ * @param {Array} files
+ * @param {Function} fn
+ * @api private
+ */
+
+exports.watch = function(files, fn){
+  var options = { interval: 100 };
+  files.forEach(function(file){
+    debug('file %s', file);
+    fs.watchFile(file, options, function(curr, prev){
+      if (prev.mtime < curr.mtime) fn(file);
+    });
+  });
+};
+
+/**
+ * Ignored files.
+ */
+
+function ignored(path){
+  return !~ignore.indexOf(path);
+}
+
+/**
+ * Lookup files in the given `dir`.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+exports.files = function(dir, ret){
+  ret = ret || [];
+
+  fs.readdirSync(dir)
+  .filter(ignored)
+  .forEach(function(path){
+    path = join(dir, path);
+    if (fs.statSync(path).isDirectory()) {
+      exports.files(path, ret);
+    } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
+      ret.push(path);
+    }
+  });
+
+  return ret;
+};
+
+/**
+ * Compute a slug from the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.slug = function(str){
+  return str
+    .toLowerCase()
+    .replace(/ +/g, '-')
+    .replace(/[^-\w]/g, '');
+};
+
+/**
+ * Strip the function definition from `str`,
+ * and re-indent for pre whitespace.
+ */
+
+exports.clean = function(str) {
+  str = str
+    .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
+    .replace(/^function *\(.*\) *{/, '')
+    .replace(/\s+\}$/, '');
+
+  var spaces = str.match(/^\n?( *)/)[1].length
+    , tabs = str.match(/^\n?(\t*)/)[1].length
+    , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');
+
+  str = str.replace(re, '');
+
+  return exports.trim(str);
+};
+
+/**
+ * Escape regular expression characters in `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.escapeRegexp = function(str){
+  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
+};
+
+/**
+ * Trim the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+exports.trim = function(str){
+  return str.replace(/^\s+|\s+$/g, '');
+};
+
+/**
+ * Parse the given `qs`.
+ *
+ * @param {String} qs
+ * @return {Object}
+ * @api private
+ */
+
+exports.parseQuery = function(qs){
+  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
+    var i = pair.indexOf('=')
+      , key = pair.slice(0, i)
+      , val = pair.slice(++i);
+
+    obj[key] = decodeURIComponent(val);
+    return obj;
+  }, {});
+};
+
+/**
+ * Highlight the given string of `js`.
+ *
+ * @param {String} js
+ * @return {String}
+ * @api private
+ */
+
+function highlight(js) {
+  return js
+    .replace(/</g, '<')
+    .replace(/>/g, '>')
+    .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
+    .replace(/('.*?')/gm, '<span class="string">$1</span>')
+    .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
+    .replace(/(\d+)/gm, '<span class="number">$1</span>')
+    .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
+    .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
+}
+
+/**
+ * Highlight the contents of tag `name`.
+ *
+ * @param {String} name
+ * @api private
+ */
+
+exports.highlightTags = function(name) {
+  var code = document.getElementsByTagName(name);
+  for (var i = 0, len = code.length; i < len; ++i) {
+    code[i].innerHTML = highlight(code[i].innerHTML);
+  }
+};
+
+}); // module: utils.js
+// The global object is "self" in Web Workers.
+global = (function() { return this; })();
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date;
+var setTimeout = global.setTimeout;
+var setInterval = global.setInterval;
+var clearTimeout = global.clearTimeout;
+var clearInterval = global.clearInterval;
+
+/**
+ * Node shims.
+ *
+ * These are meant only to allow
+ * mocha.js to run untouched, not
+ * to allow running node code in
+ * the browser.
+ */
+
+var process = {};
+process.exit = function(status){};
+process.stdout = {};
+
+var uncaughtExceptionHandlers = [];
+
+/**
+ * Remove uncaughtException listener.
+ */
+
+process.removeListener = function(e, fn){
+  if ('uncaughtException' == e) {
+    global.onerror = function() {};
+    var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn);
+    if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); }
+  }
+};
+
+/**
+ * Implements uncaughtException listener.
+ */
+
+process.on = function(e, fn){
+  if ('uncaughtException' == e) {
+    global.onerror = function(err, url, line){
+      fn(new Error(err + ' (' + url + ':' + line + ')'));
+      return true;
+    };
+    uncaughtExceptionHandlers.push(fn);
+  }
+};
+
+/**
+ * Expose mocha.
+ */
+
+var Mocha = global.Mocha = require('mocha'),
+    mocha = global.mocha = new Mocha({ reporter: 'html' });
+
+// The BDD UI is registered by default, but no UI will be functional in the
+// browser without an explicit call to the overridden `mocha.ui` (see below).
+// Ensure that this default UI does not expose its methods to the global scope.
+mocha.suite.removeAllListeners('pre-require');
+
+var immediateQueue = []
+  , immediateTimeout;
+
+function timeslice() {
+  var immediateStart = new Date().getTime();
+  while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
+    immediateQueue.shift()();
+  }
+  if (immediateQueue.length) {
+    immediateTimeout = setTimeout(timeslice, 0);
+  } else {
+    immediateTimeout = null;
+  }
+}
+
+/**
+ * High-performance override of Runner.immediately.
+ */
+
+Mocha.Runner.immediately = function(callback) {
+  immediateQueue.push(callback);
+  if (!immediateTimeout) {
+    immediateTimeout = setTimeout(timeslice, 0);
+  }
+};
+
+/**
+ * Function to allow assertion libraries to throw errors directly into mocha.
+ * This is useful when running tests in a browser because window.onerror will
+ * only receive the 'message' attribute of the Error.
+ */
+mocha.throwError = function(err) {
+  Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) {
+    fn(err);
+  });
+  throw err;
+};
+
+/**
+ * Override ui to ensure that the ui functions are initialized.
+ * Normally this would happen in Mocha.prototype.loadFiles.
+ */
+
+mocha.ui = function(ui){
+  Mocha.prototype.ui.call(this, ui);
+  this.suite.emit('pre-require', global, null, this);
+  return this;
+};
+
+/**
+ * Setup mocha with the given setting options.
+ */
+
+mocha.setup = function(opts){
+  if ('string' == typeof opts) opts = { ui: opts };
+  for (var opt in opts) this[opt](opts[opt]);
+  return this;
+};
+
+/**
+ * Run mocha, returning the Runner.
+ */
+
+mocha.run = function(fn){
+  var options = mocha.options;
+  mocha.globals('location');
+
+  var query = Mocha.utils.parseQuery(global.location.search || '');
+  if (query.grep) mocha.grep(query.grep);
+  if (query.invert) mocha.invert();
+
+  return Mocha.prototype.run.call(mocha, function(){
+    // The DOM Document is not available in Web Workers.
+    if (global.document) {
+      Mocha.utils.highlightTags('code');
+    }
+    if (fn) fn();
+  });
+};
+
+/**
+ * Expose the process shim.
+ */
+
+Mocha.process = process;
+})();
\ No newline at end of file
diff --git a/test/examples/diffpatch.js b/test/examples/diffpatch.js
new file mode 100644
index 0000000..57e0d8a
--- /dev/null
+++ b/test/examples/diffpatch.js
@@ -0,0 +1,560 @@
+
+var examples = {};
+
+var exampleDate = function() {
+	return new Date(2020, 10, 30, 15, 10, 03);
+};
+
+/*jshint camelcase: false */
+/*jshint multistr: true */
+
+examples.atomic_values = [
+
+	// undefined
+	{
+		left: undefined,
+		right: undefined,
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: undefined,
+		right: null,
+		delta: [null],
+		reverse: [null, 0, 0]
+	},
+	{
+		left: undefined,
+		right: false,
+		delta: [false],
+		reverse: [false, 0, 0]
+	},
+	{
+		left: undefined,
+		right: true,
+		delta: [true],
+		reverse: [true, 0, 0]
+	},
+	{
+		left: undefined,
+		right: 42,
+		delta: [42],
+		reverse: [42, 0, 0]
+	},
+	{
+		left: undefined,
+		right: 'some text',
+		delta: ['some text'],
+		reverse: ['some text', 0, 0]
+	},
+	{
+		left: undefined,
+		right: exampleDate(),
+		delta: [exampleDate()],
+		reverse: [exampleDate(), 0, 0]
+	},
+	{
+		left: undefined,
+		right: { a: 1, b: 2 },
+		delta: [{ a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, 0, 0]
+	},
+	{
+		left: undefined,
+		right: [1, 2, 3],
+		delta: [[1, 2, 3]],
+		reverse: [[1, 2, 3], 0, 0]
+	},
+	{
+		left: undefined,
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+	// null
+	{
+		left: null,
+		right: null,
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: null,
+		right: false,
+		delta: [null, false],
+		reverse: [false, null]
+	},
+	{
+		left: null,
+		right: true,
+		delta: [null, true],
+		reverse: [true, null]
+	},
+	{
+		left: null,
+		right: 42,
+		delta: [null, 42],
+		reverse: [42, null]
+	},
+	{
+		left: null,
+		right: 'some text',
+		delta: [null, 'some text'],
+		reverse: ['some text', null]
+	},
+	{
+		left: null,
+		right: exampleDate(),
+		delta: [null, exampleDate()],
+		reverse: [exampleDate(), null]
+	},
+	{
+		left: null,
+		right: { a: 1, b: 2 },
+		delta: [null, { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, null]
+	},
+	{
+		left: null,
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+
+	// false
+	{
+		left: false,
+		right: false,
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: false,
+		right: true,
+		delta: [false, true],
+		reverse: [true, false]
+	},
+	{
+		left: false,
+		right: 42,
+		delta: [false, 42],
+		reverse: [42, false]
+	},
+	{
+		left: false,
+		right: 'some text',
+		delta: [false, 'some text'],
+		reverse: ['some text', false]
+	},
+	{
+		left: false,
+		right: exampleDate(),
+		delta: [false, exampleDate()],
+		reverse: [exampleDate(), false]
+	},
+	{
+		left: false,
+		right: { a: 1, b: 2 },
+		delta: [false, { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, false]
+	},
+	{
+		left: false,
+		right: [1, 2, 3],
+		delta: [false, [1, 2, 3]],
+		reverse: [[1, 2, 3], false]
+	},
+	{
+		left: false,
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+
+
+	// true
+	{
+		left: true,
+		right: true,
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: true,
+		right: 42,
+		delta: [true, 42],
+		reverse: [42, true]
+	},
+	{
+		left: true,
+		right: 'some text',
+		delta: [true, 'some text'],
+		reverse: ['some text', true]
+	},
+	{
+		left: true,
+		right: exampleDate(),
+		delta: [true, exampleDate()],
+		reverse: [exampleDate(), true]
+	},
+	{
+		left: true,
+		right: { a: 1, b: 2 },
+		delta: [true, { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, true]
+	},
+	{
+		left: true,
+		right: [1, 2, 3],
+		delta: [true, [1, 2, 3]],
+		reverse: [[1, 2, 3], true]
+	},
+	{
+		left: true,
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+
+	// number
+	{
+		name: 'number -> same number',
+		left: 42,
+		right: 42,
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: 42,
+		right: -1,
+		delta: [42, -1],
+		reverse: [-1, 42]
+	},
+	{
+		left: 42,
+		right: 'some text',
+		delta: [42, 'some text'],
+		reverse: ['some text', 42]
+	},
+	{
+		left: 42,
+		right: exampleDate(),
+		delta: [42, exampleDate()],
+		reverse: [exampleDate(), 42]
+	},
+	{
+		left: 42,
+		right: { a: 1, b: 2 },
+		delta: [42, { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, 42]
+	},
+	{
+		left: 42,
+		right: [1, 2, 3],
+		delta: [42, [1, 2, 3]],
+		reverse: [[1, 2, 3], 42]
+	},
+	{
+		left: 42,
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+	// string
+	{
+		name: 'string -> same string',
+		left: 'some text',
+		right: 'some text',
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: 'some text',
+		right: 'some fext',
+		delta: ['some text', 'some fext'],
+		reverse: ['some fext', 'some text']
+	},
+	{
+		left: 'some text',
+		right: exampleDate(),
+		delta: ['some text', exampleDate()],
+		reverse: [exampleDate(), 'some text']
+	},
+	{
+		left: 'some text',
+		right: { a: 1, b: 2 },
+		delta: ['some text', { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, 'some text']
+	},
+	{
+		left: 'some text',
+		right: [1, 2, 3],
+		delta: ['some text', [1, 2, 3]],
+		reverse: [[1, 2, 3], 'some text']
+	},
+	{
+		left: 'some text',
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+
+	// Date
+	{
+		name: 'Date -> same Date',
+		left: exampleDate(),
+		right: exampleDate(),
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: exampleDate(),
+		right: new Date(2020, 5, 31, 15, 12, 30),
+		delta: [exampleDate(), new Date(2020, 5, 31, 15, 12, 30)],
+		reverse: [new Date(2020, 5, 31, 15, 12, 30), exampleDate()]
+	},
+	{
+		left: exampleDate(),
+		right: { a: 1, b: 2 },
+		delta: [exampleDate(), { a: 1, b: 2 }],
+		reverse: [{ a: 1, b: 2 }, exampleDate()]
+	},
+	{
+		left: exampleDate(),
+		right: [1, 2, 3],
+		delta: [exampleDate(), [1, 2, 3]],
+		reverse: [[1, 2, 3], exampleDate()]
+	},
+	{
+		left: exampleDate(),
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+	// object
+	{
+		name: 'object -> same object',
+		left: { a: 1, b: 2 },
+		right: { a: 1, b: 2 },
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: { a: 1, b: 2 },
+		right: [1, 2, 3],
+		delta: [{ a: 1, b: 2 }, [1, 2, 3]],
+		reverse: [[1, 2, 3], { a: 1, b: 2 }]
+	},
+	{
+		left: { a: 1, b: 2 },
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+
+	// array
+	{
+		name: 'array -> same array',
+		left: [1, 2, 3],
+		right: [1, 2, 3],
+		delta: undefined,
+		reverse: undefined
+	},
+	{
+		left: [1, 2, 3],
+		right: function(x){ return x * x; },
+		error: /not supported/,
+	},
+	0
+];
+
+var shortText = 'Madre,\n\
+cuando yo sea grande\n\
+quisiera hacer versos';
+var largeText = '-Madre,\n\
+cuando yo sea grande\n\
+seré marinero.\n\
+\n\
+Ahora estoy jugando\n\
+que aquello es un puerto\n\
+y que éste es un barco\n\
+y éstos son dos remos\n\
+y por ese río\n\
+navego y navego.\n\
+\n\
+(Agua, arena, piedras\n\
+y dos palos viejos:\n\
+un río y un barco,\n\
+un puerto y dos remos).\n\
+\n\
+-Madre,\n\
+cuando yo sea grande\n\
+seré jardinero.\n\
+\n\
+Ahora estoy jugando\n\
+que esto es un cantero,\n\
+aquél un rosal,\n\
+éste un jazminero\n\
+y ése es un camino\n\
+que va por el medio.\n\
+\n\
+(Tierra, flores, hojas\n\
+y unos tallos secos:\n\
+cantero, camino,\n\
+rosal, jazminero).\n\
+\n\
+-Madre,\n\
+cuando yo sea grande\n\
+quisiera hacer versos.\n\
+\n\
+-¿Con qué estás jugando?\n\
+\n\
+-Madre, miro el cielo.\n\
+\n\
+(En dos ojos claros\n\
+todo el Universo).';
+examples.text = [
+	{
+		left: shortText,
+		right: largeText,
+		delta: [shortText, largeText],
+		reverse: [largeText, shortText]
+	},
+	{
+		left: largeText,
+		right: largeText.replace(/jazminero/g, 'rosal'),
+		delta: ['@@ -360,25 +360,21 @@\n %C3%A9ste un \n-jazminero\n+rosal' +
+			'\n %0Ay %C3%A9se e\n@@ -479,17 +479,13 @@\n al, \n-jazminero\n+rosal\n ).%0A%0A\n',0,2],
+		reverse: ['@@ -360,21 +360,25 @@\n %C3%A9ste un \n-rosal\n+jazminero\n %0Ay' +
+			' %C3%A9se e\n@@ -479,21 +479,25 @@\n %0Arosal, \n-rosal\n+jazminero\n ).%0A%0A-Mad\n',0,2],
+		exactReverse: false
+	},
+	{
+		name: 'larger than min length',
+		options: {
+			textDiff: {
+				minLength: 10
+			}
+		},
+		left: largeText.substr(0, 10),
+		right: largeText.substr(0, 11).replace(/Madre/g, 'Padre'),
+		delta: ['@@ -1,10 +1,11 @@\n -\n-M\n+P\n adre,%0Acu\n+a\n',0,2],
+		reverse: ['@@ -1,11 +1,10 @@\n -\n-P\n+M\n adre,%0Acu\n-a\n',0,2],
+		exactReverse: false
+	},
+	{
+		name: 'shorter than min length',
+		options: {
+			textDiff: {
+				minLength: 10
+			}
+		},
+		left: largeText.substr(0, 9),
+		right: largeText.substr(0, 11).replace(/Madre/g, 'Padre'),
+		delta: ['-Madre,\nc','-Padre,\ncua'],
+		reverse: ['-Padre,\ncua','-Madre,\nc'],
+		exactReverse: false
+	},
+	0
+];
+
+examples.objects = [
+	{
+		name: 'first level',
+		left: { a: 1, b: 2 },
+		right: { a: 42, b: 2 },
+		delta: { a: [1, 42] },
+		reverse: { a: [42, 1] }
+	},
+	{
+		name: 'deep level',
+		left: { a: { j: { k: { l: { m: { n: { o: 3 } } } } } }, b: 2 },
+		right: { a: { j: { k: { l: { m: { n: { o: true } } } } } }, b: 2 },
+		delta: { a: { j: { k: { l: { m: { n: { o: [3, true] } } } } } } },
+		reverse: { a: { j: { k: { l: { m: { n: { o: [true, 3] } } } } } } }
+	},
+	{
+		name: 'multiple changes',
+		left: { a: { j: { k: { l: { m: { n: { o: 3 } } } } } }, b: 2, c: 5 },
+		right: { a: { j: { k: { l: { m: { n: { o: 5, w: 12 } } } } } }, b: 2},
+		delta: { a: { j: { k: { l: { m: { n: { o: [3, 5], w: [12] } } } } } }, c: [5, 0, 0] },
+		reverse: { a: { j: { k: { l: { m: { n: { o: [5, 3], w: [12, 0, 0] } } } } } }, c: [5] }
+	},
+	0
+];
+
+examples.arrays = [
+	{
+		name: 'simple values',
+		left: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+		right: [1, 3, 4, 5, 8, 9, 9.1, 10],
+		delta: { _t: 'a', _1: [ 2, 0, 0], _5: [6, 0, 0], _6: [7, 0, 0], 6: [9.1] },
+		reverse: { _t: 'a',  1: [2], 5: [6], 6: [7], _6: [9.1, 0, 0] }
+	},
+	{
+		name: 'added block',
+		left: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+		right: [1, 2, 3, 4, 5, 5.1, 5.2, 5.3, 6, 7, 8, 9, 10],
+		delta: { _t: 'a', 5: [ 5.1 ], 6: [ 5.2 ], 7: [ 5.3 ] },
+		reverse: { _t: 'a',  _5: [ 5.1, 0, 0 ], _6: [ 5.2, 0, 0 ], _7: [ 5.3, 0, 0 ] }
+	},
+	{
+		name: 'movements',
+		left: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+		right: [1, 2, 3, 7, 5, 6, 8, 9, 4, 10],
+		delta: { _t: 'a', _3: ['', 8, 3], _6: ['', 3, 3] },
+		reverse: { _t: 'a', _3: ['', 6, 3], _8 :['', 3, 3] }
+	},
+	{
+		name: 'movements(2)',
+		left: [1, 2, 3, 4],
+		right: [2, 4, 1, 3],
+		delta: { _t: 'a', _1: ['', 0, 3], _3: ['', 1, 3] },
+		reverse: { _t: 'a', _2: ['', 0, 3], _3 :['', 2, 3] },
+		exactReverse: false
+	},
+	{
+		name: 'nested',
+		options: {
+			objectHash: function(obj) {
+				if (obj && obj.id) {
+					return obj.id;
+				}
+			}
+		},
+		left: [ 1, 2, { id: 4, width: 10 }, 4, { id: 'five', width: 4 }, 6, 7, 8, 9, 10],
+		right: [ 1, 2, { id: 4, width: 12 }, 4, { id: 'five', width: 4 }, 6, 7, 8, 9, 10],
+		delta: { _t: 'a', 2: { width: [10, 12] } },
+		reverse: { _t: 'a', 2: { width: [12, 10] } }
+	},
+	{
+		name: 'nested with movement',
+		options: {
+			objectHash: function(obj) {
+				if (obj && obj.id) {
+					return obj.id;
+				}
+			}
+		},
+		left: [ 1, 2, 4, { id: 'five', width: 4 }, 6, 7, 8, { id: 4, width: 10, height: 3 }, 9, 10],
+		right: [ 1, 2, { id: 4, width: 12 }, 4, { id: 'five', width: 4 }, 6, 7, 8, 9, 10],
+		delta: { _t: 'a', 2: { width: [10, 12], height: [3, 0, 0] }, _7: ['', 2, 3] },
+		reverse: { _t: 'a', 7: { width: [12, 10], height: [3] }, _2: ['', 7, 3] }
+	},
+	{
+		name: 'nested with movements using custom objectHash',
+		options: {
+			objectHash: function(obj) {
+				if (obj && obj.item_key) {
+					return obj.item_key;
+				}
+			}
+		},
+		left: [ 1, 2, 4, { item_key: 'five', width: 4 }, 6, 7, 8, { item_key: 4, width: 10, height: 3 }, 9, 10],
+		right: [ 1, 2, { item_key: 4, width: 12 }, 4, { item_key: 'five', width: 4 }, 6, 7, 8, 9, 10],
+		delta: { _t: 'a', 2: { width: [10, 12], height: [3, 0, 0] }, _7: ['', 2, 3] },
+		reverse: { _t: 'a', 7: { width: [12, 10], height: [3] }, _2: ['', 7, 3] }
+	},
+	0
+];
+
+module.exports = examples;
diff --git a/test/index.html b/test/index.html
new file mode 100644
index 0000000..008cd76
--- /dev/null
+++ b/test/index.html
@@ -0,0 +1,20 @@
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Mocha Tests</title>
+  <link rel="stylesheet" href="../test-external/mocha.css" />
+  <script src="../test-external/expect.js"></script>
+  <script src="../test-external/mocha.js"></script>
+  <script>mocha.setup('bdd')</script>
+  <script src="../build/bundle.js"></script>
+  <script src="../external/diff_match_patch_uncompressed.js"></script>
+  <script src="../build/test-bundle.js"></script>
+</head>
+<body>
+  <div id="mocha"></div>
+  <script>
+    mocha.checkLeaks();
+    mocha.run();
+  </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/test/test.js b/test/test.js
new file mode 100644
index 0000000..2ed6b6c
--- /dev/null
+++ b/test/test.js
@@ -0,0 +1,169 @@
+/* global describe, it, before */
+
+var expect = (typeof window !== 'undefined' && window.expect) ? window.expect : require('expect.js');
+var jsondiffpatch = (typeof window !== 'undefined') ? window.jsondiffpatch : require('../src/' + 'main.js');
+var DiffPatcher = jsondiffpatch.DiffPatcher;
+
+var isArray = (typeof Array.isArray === 'function') ?
+    // use native function
+    Array.isArray :
+    // use instanceof operator
+    function(a) {
+        return typeof a === 'object' && a instanceof Array;
+    };
+
+var dateReviver = jsondiffpatch.dateReviver;
+
+var deepEqual = function(obj1, obj2) {
+    if (obj1 === obj2) {
+        return true;
+    }
+    if (obj1 === null || obj2 === null) { return false; }
+    if ((typeof obj1 === 'object') && (typeof obj2 === 'object')) {
+        if (obj1 instanceof Date) {
+            if (!(obj2 instanceof Date)) { return false; }
+            return obj1.toString() === obj2.toString();
+        }
+        if (isArray(obj1)) {
+            if (!isArray(obj2)) { return false; }
+            if (obj1.length !== obj2.length) { return false; }
+            var length = obj1.length;
+            for (var i = 0; i < length; i++) {
+                if (!deepEqual(obj1[i], obj2[i])) { return false; }
+            }
+            return true;
+        } else {
+            if (isArray(obj2)) { return false; }
+        }
+        var name;
+        for (name in obj2) {
+            if (typeof obj1[name] === 'undefined') { return false; }
+        }
+        for (name in obj1) {
+            if (!deepEqual(obj1[name], obj2[name])) { return false; }
+        }
+        return true;
+    }
+    return false;
+};
+
+expect.Assertion.prototype.deepEqual = function(obj) {
+    this.assert(
+        deepEqual(this.obj, obj),
+        function(){
+            return 'expected ' + JSON.stringify(this.obj) + ' to be ' + JSON.stringify(obj);
+        },
+        function(){
+            return 'expected ' + JSON.stringify(this.obj) + ' not to be ' + JSON.stringify(obj);
+        });
+    return this;
+};
+
+var valueDescription = function(value) {
+    if (value === null) {
+        return 'null';
+    }
+    if (typeof value === 'boolean') {
+        return value.toString();
+    }
+    if (value instanceof Date) {
+        return 'Date';
+    }
+    if (isArray(value)) {
+        return 'array';
+    }
+    if (typeof value === 'string') {
+        if (value.length >= 60) {
+            return 'large text';
+        }
+    }
+    return typeof value;
+};
+
+var clone = function(obj) {
+    if (typeof obj === 'undefined') {
+        return undefined;
+    }
+    return JSON.parse(JSON.stringify(obj), dateReviver);
+};
+
+// Object.keys polyfill
+var objectKeys = (typeof Object.keys === 'function') ?
+function(obj) {
+    return Object.keys(obj);
+} :
+function(obj) {
+    var keys = [];
+    for (var key in obj) {
+        if (obj.hasOwnProperty(key)) {
+            keys.push(key);
+        }
+    }
+    return keys;
+};
+
+// Array.prototype.forEach polyfill
+var arrayForEach = (typeof Array.prototype.forEach === 'function') ?
+function(array, fn) {
+    return array.forEach(fn);
+} :
+function(array, fn) {
+    for (var index = 0, length = array.length; index < length; index++) {
+        fn(array[index], index, array);
+    }
+};
+
+describe('DiffPatcher', function(){
+    var examples = require('./examples/diffpatch');
+    arrayForEach(objectKeys(examples), function(groupName){
+        var group = examples[groupName];
+        describe(groupName, function(){
+            arrayForEach(group, function(example){
+                if (!example) { return; }
+                var name = example.name || valueDescription(example.left) + ' -> ' + valueDescription(example.right);
+                describe(name, function(){
+                    before(function(){
+                        this.instance = new DiffPatcher(example.options);
+                    });
+                    if (example.error) {
+                        it('diff should fail with: ' + example.error, function(){
+                            var instance = this.instance;
+                            expect(function(){
+                                instance.diff(example.left, example.right);
+                            }).to.throwException(example.error);
+                        });
+                        return;
+                    }
+                    it('can diff', function(){
+                        var delta = this.instance.diff(example.left, example.right);
+                        expect(delta).to.be.deepEqual(example.delta);
+                    });
+                    it('can diff backwards', function(){
+                        var reverse = this.instance.diff(example.right, example.left);
+                        expect(reverse).to.be.deepEqual(example.reverse);
+                    });
+                    it('can patch', function(){
+                        var right = this.instance.patch(clone(example.left), example.delta);
+                        expect(right).to.be.deepEqual(example.right);
+                    });
+                    it('can reverse delta', function(){
+                        var reverse = this.instance.reverse(example.delta);
+                        if (example.exactReverse !== false) {
+                            expect(reverse).to.be.deepEqual(example.reverse);
+                        } else {
+                            // reversed delta and the swapped-diff delta are not always equal,
+                            // to verify they're equivalent, patch and compare the results
+                            expect(this.instance.patch(clone(example.right), reverse)).to.be.deepEqual(example.left);
+                            reverse = this.instance.diff(example.right, example.left);
+                            expect(this.instance.patch(clone(example.right), reverse)).to.be.deepEqual(example.left);
+                        }
+                    });
+                    it('can unpatch', function(){
+                        var left = this.instance.unpatch(clone(example.right), example.delta);
+                        expect(left).to.be.deepEqual(example.left);
+                    });
+                });
+            });
+        });
+    });
+});
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/jsondiffpatch.js.git



More information about the Pkg-javascript-commits mailing list