Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

initial commit

  • Loading branch information...
commit 170b3e22f1710286a1a534a9687ff9fb28c900c1 0 parents
authored
1  .gitignore
... ...
@@ -0,0 +1 @@
  1
+/nbproject
19  Makefile
... ...
@@ -0,0 +1,19 @@
  1
+#
  2
+# Run all tests
  3
+#
  4
+test:
  5
+	node test/server.js
  6
+
  7
+#
  8
+# Run the benchmarks
  9
+#
  10
+bench:
  11
+	node benchmark/server.js
  12
+
  13
+#
  14
+# Build the docs
  15
+#
  16
+docs:
  17
+	node docs/build.js
  18
+
  19
+.PHONY: test docs bench
0  README.md
Source Rendered
No changes.
163  benchmark/index.html
... ...
@@ -0,0 +1,163 @@
  1
+<!DOCTYPE HTML>
  2
+<html>
  3
+  <head>
  4
+    <title>shootout</title>
  5
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6
+    <style type="text/css">
  7
+      body {
  8
+        background-color: #eee;
  9
+        font-family: Helvetica, Arial, sans-serif;
  10
+        margin: 0 10%;
  11
+        text-shadow: white 1px 1px 0px;
  12
+      }
  13
+
  14
+      p {
  15
+        color: #777;
  16
+      }
  17
+
  18
+      #header p {
  19
+        color: #555;
  20
+        font-size: 1.1em;
  21
+        font-weight: bold;
  22
+      }
  23
+
  24
+      h1 {
  25
+        font-size: 7em;
  26
+        font-weight: bold;
  27
+        color: #333;
  28
+        margin-top: 0.10em;
  29
+        margin-bottom: -0.25em;
  30
+      }
  31
+
  32
+      .chart {
  33
+        border: 4px solid #ccc;
  34
+        float: left;
  35
+        margin-right: 1em;
  36
+        margin-bottom: 1em;
  37
+      }
  38
+
  39
+      #control {
  40
+        margin-bottom: 1em;
  41
+      }
  42
+
  43
+      #progress {
  44
+        -moz-border-radius: 4px;
  45
+        -webkit-border-radius: 4px;
  46
+        border: 1px solid #aaa;
  47
+        padding: 2px;
  48
+      }
  49
+
  50
+      #progress div {
  51
+        -moz-border-radius: 4px;
  52
+        -webkit-border-radius: 4px;
  53
+        height: 25px;
  54
+        width: 0%;
  55
+        background-color: #888;
  56
+      }
  57
+    </style>
  58
+  </head>
  59
+  <body>
  60
+    <div id="header">
  61
+      <h1>shootout</h1>
  62
+      <p>Template benchmarks (ops per millisecond)</p>
  63
+    </div>
  64
+
  65
+    <div id="control">
  66
+      <div id="progress"><div></div></div>
  67
+      <button id="run" style="display:none;">Run</button>
  68
+    </div>
  69
+
  70
+    <div id="content">
  71
+      <div id="charts"></div>
  72
+      <p style="clear: both">Targets: <a href="http://akdubya.github.com/dustjs">Dust</a>, <a href="http://github.com/wycats/handlebars.js">Handlebars</a>, <a href="http://mustache.github.com/">Mustache</a>, <a href="http://api.jquery.com/tmpl/">jquery-tmpl</a>. Each benchmark runs once using an adaptive test cycles algorithm similar to the one found in <a href="http://github.com/broofa/jslitmus">jslitmus</a>.</p>
  73
+    </div>
  74
+
  75
+    <script src="../vendor/jquery.min.js"></script>
  76
+    <script src="uubench.js"></script>
  77
+    <script src="../lib/parser.js"></script>
  78
+    <script src="../lib/compiler.js"></script>
  79
+    <script src="../lib/dust.js"></script>
  80
+    <script src="suites/dust_suite.js"></script>
  81
+    <script src="suites/mustache_suite.js"></script>
  82
+    <script src="suites/handlebars_suite.js"></script>
  83
+    <script src="suites/jquery_suite.js"></script>
  84
+    <script src="http://github.com/wycats/handlebars.js/raw/master/lib/handlebars.js"></script>
  85
+    <script src="http://github.com/janl/mustache.js/raw/master/mustache.js"</script>
  86
+    <script src="http://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js"></script>
  87
+    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  88
+    <script type="text/javascript">
  89
+      google.load('visualization', '1.0', {packages: ['imagechart']});
  90
+    </script>
  91
+
  92
+    <script>
  93
+      $(document).ready(function(){
  94
+        var testQueue = [];
  95
+        var $bar = $('#progress > div');
  96
+        var tick;
  97
+
  98
+        function runAll() {
  99
+          $bar.css('width', "0%");
  100
+          $('#progress').show();
  101
+          for (var key in dustBench.benches) { testQueue.push(key) }
  102
+          tick = 100 / testQueue.length;
  103
+          $('#charts').empty();
  104
+          next();
  105
+        }
  106
+
  107
+        function next() {
  108
+          var test = testQueue.shift();
  109
+          if (test) {
  110
+            runSuite(test);
  111
+          } else {
  112
+            $('#progress').fadeOut(1000, function() {
  113
+              $('#run').fadeIn();
  114
+            });
  115
+          }
  116
+        }
  117
+
  118
+        function runSuite(type) {
  119
+          var rows = [];
  120
+          var suite = new uubench.Suite({
  121
+            iterations: 1000,
  122
+            result: function(name, stats) {
  123
+              var opms = stats.iterations/stats.elapsed;
  124
+              rows.push([name, opms]);
  125
+            },
  126
+            start: function() {
  127
+              $('#charts').append("<div id=\"" + type + "\" class=\"chart\"></div>");
  128
+            },
  129
+            done: function() {
  130
+              var pct = parseFloat($bar.css('width')) + tick;
  131
+              drawBarChart(type, rows);
  132
+              $('#progress > div').css('width', pct + "%");
  133
+              next();
  134
+            }
  135
+          });
  136
+          dustBench(suite, type, "dust");
  137
+          handlebarsBench(suite, type, "handlebars");
  138
+          mustacheBench(suite, type, "mustache");
  139
+          jqueryBench(suite, type, "jquery");
  140
+          suite.run();
  141
+        }
  142
+
  143
+        function drawBarChart(type, rows) {
  144
+          var dataTable = new google.visualization.DataTable();
  145
+          dataTable.addColumn("string", "engine");
  146
+          dataTable.addColumn("number", "ops");
  147
+          dataTable.addRows(rows);
  148
+
  149
+          var chart = new google.visualization.ImageChart(document.getElementById(type));
  150
+          chart.draw(dataTable, {title: type, cht: 'bhs', chs: '420x175'});
  151
+        }
  152
+
  153
+        $('#run').click(function() {
  154
+          $('#run').hide();
  155
+          runAll();
  156
+          return false;
  157
+        });
  158
+
  159
+        runAll();
  160
+      });
  161
+    </script>
  162
+  </body>
  163
+</html>
31  benchmark/server.js
... ...
@@ -0,0 +1,31 @@
  1
+var uubench    = require('./uubench'),
  2
+    dust       = require('../lib/dust'),
  3
+    dustBench  = require('./suites/dust_suite').dustBench;
  4
+
  5
+uubench.nextTick = process.nextTick;
  6
+
  7
+var suite = new uubench.Suite({
  8
+  iterations: 10000,
  9
+  result: function(name, stats) {
  10
+    var opms = stats.iterations/stats.elapsed;
  11
+    console.log(pad(12, name + ": "), pad(5, Math.round(opms), true));
  12
+  }
  13
+});
  14
+
  15
+function pad(amt, val, pre) {
  16
+  val = String(val);
  17
+  var len = amt - val.length, out = '';
  18
+  for (var i=0; i<len; i++) {
  19
+    out += ' ';
  20
+  }
  21
+  return pre ? out + val : val + out;
  22
+}
  23
+
  24
+console.log("ops/ms");
  25
+console.log("------");
  26
+
  27
+for (var key in dustBench.benches) {
  28
+  dustBench(suite, key);
  29
+}
  30
+
  31
+suite.run();
111  benchmark/suites/dust_suite.js
... ...
@@ -0,0 +1,111 @@
  1
+(function(exports){
  2
+
  3
+var benches = {
  4
+
  5
+  string: {
  6
+    source:  "Hello World!",
  7
+    context: {}
  8
+  },
  9
+
  10
+  replace: {
  11
+    source:  "Hello {name}! You have {count} new messages.",
  12
+    context: { name: "Mick", count: 30 }
  13
+  },
  14
+
  15
+  array: {
  16
+    source:  "{#names}{name}{/names}",
  17
+    context: { names: [
  18
+                 { name: "Moe" },
  19
+                 { name: "Larry" },
  20
+                 { name: "Curly" },
  21
+                 { name: "Shemp" }
  22
+               ]
  23
+             }
  24
+  },
  25
+
  26
+  object: {
  27
+    source:  "{#person}{name}{age}{/person}",
  28
+    context: { person: { name: "Larry", age: 45 } }
  29
+  },
  30
+
  31
+  partial: {
  32
+    source:  "{#peeps}{>replace/}{/peeps}",
  33
+    context: { peeps: [
  34
+                 { name: "Moe", count: 15 },
  35
+                 { name: "Larry", count: 5 },
  36
+                 { name: "Curly", count: 0 }
  37
+               ]
  38
+             }
  39
+  },
  40
+
  41
+  recursion: {
  42
+    source:  "{name}{#kids}{>recursion:./}{/kids}",
  43
+    context: {
  44
+                name: '1',
  45
+                kids: [
  46
+                  {
  47
+                    name: '1.1',
  48
+                    kids: [
  49
+                      {name: '1.1.1'}
  50
+                    ]
  51
+                  }
  52
+                ]
  53
+             }
  54
+  },
  55
+
  56
+  filter: {
  57
+    source:  "{#filter}foo {bar}{/filter}",
  58
+    context: {
  59
+                filter: function(chunk, context, bodies) {
  60
+                  return chunk.tap(function(data) {
  61
+                    return data.toUpperCase();
  62
+                  }).render(bodies.block, context).untap();
  63
+                },
  64
+                bar: "bar"
  65
+             }
  66
+  },
  67
+
  68
+  complex: {
  69
+    source:  "<h1>{header}</h1>\n"                             +
  70
+             "{?items}\n"                                      +
  71
+             "  <ul>\n"                                        +
  72
+             "    {#items}\n"                                  +
  73
+             "      {#current}\n"                              +
  74
+             "        <li><strong>{name}</strong></li>\n"      +
  75
+             "      {:else}\n"                                 +
  76
+             "        <li><a href=\"{url}\">{name}</a></li>\n" +
  77
+             "      {/current}\n"                              +
  78
+             "    {/items}\n"                                  +
  79
+             "  </ul>\n"                                       +
  80
+             "{:else}\n"                                       +
  81
+             "  <p>The list is empty.</p>\n"                   +
  82
+             "{/items}",
  83
+    context: {
  84
+               header: function() {
  85
+                 return "Colors";
  86
+               },
  87
+               items: [
  88
+                 {name: "red", current: true, url: "#Red"},
  89
+                 {name: "green", current: false, url: "#Green"},
  90
+                 {name: "blue", current: false, url: "#Blue"}
  91
+               ]
  92
+             }
  93
+  }
  94
+
  95
+}
  96
+
  97
+exports.dustBench = function(suite, name, id) {
  98
+  var bench = benches[name],
  99
+      ctx = bench.context;
  100
+
  101
+  dust.loadSource(dust.compile(bench.source, name));
  102
+  suite.bench(id || name, function(next) {
  103
+    dust.render(name, ctx, function() {
  104
+      next();
  105
+    });
  106
+  });
  107
+};
  108
+
  109
+exports.dustBench.benches = benches;
  110
+
  111
+})(typeof exports !== "undefined" ? exports : window);
101  benchmark/suites/handlebars_suite.js
... ...
@@ -0,0 +1,101 @@
  1
+(function(exports){
  2
+
  3
+var benches = {
  4
+
  5
+  string: {
  6
+    source:  "Hello World!",
  7
+    context: {}
  8
+  },
  9
+
  10
+  replace: {
  11
+    source:  "Hello {{name}}! You have {{count}} new messages.",
  12
+    context: { name: "Mick", count: 30 }
  13
+  },
  14
+
  15
+  array: {
  16
+    source:   "{{#names}}{{name}}{{/names}}",
  17
+    context:  { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
  18
+  },
  19
+
  20
+  object: {
  21
+    source:   "{{#person}}{{name}}{{age}}{{/person}}",
  22
+    context:  { person: { name: "Larry", age: 45 } }
  23
+  },
  24
+
  25
+  partial: {
  26
+    source:   "{{#peeps}}{{>replace}}{{/peeps}}",
  27
+    context:  { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] },
  28
+    partials: { replace: "Hello {{name}}! You have {{count}} new messages." }
  29
+  },
  30
+
  31
+  recursion: {
  32
+    source:   "{{name}}{{#kids}}{{>recursion}}{{/kids}}",
  33
+    context:  {
  34
+                name: '1',
  35
+                kids: [
  36
+                  {
  37
+                    name: '1.1',
  38
+                    kids: [
  39
+                      {name: '1.1.1'}
  40
+                    ]
  41
+                  }
  42
+                ]
  43
+              },
  44
+    partials: { recursion: "{{name}}{{#kids}}{{>recursion}}{{/kids}}" }
  45
+  },
  46
+
  47
+  filter: {
  48
+    source:   "{{#filter}}foo {{bar}}{{/filter}}",
  49
+    context:  {
  50
+                filter: function(ctx, fn) {
  51
+                  return fn(ctx).toUpperCase();
  52
+                },
  53
+                bar: "bar"
  54
+              }
  55
+  },
  56
+
  57
+  complex: {
  58
+    source:  "<h1>{{header}}</h1>{{#hasItems}}<ul>{{#items}}{{#current}}" +
  59
+             "<li><strong>{{name}}</strong></li>{{/current}}{{^current}}" +
  60
+             "<li><a href=\"{{url}}\">{{name}}</a></li>{{/current}}"      +
  61
+             "{{/items}}</ul>{{^}}<p>The list is empty.</p>{{/hasItems}}",
  62
+    context: {
  63
+               header: function() {
  64
+                 return "Colors";
  65
+               },
  66
+               items: [
  67
+                 {name: "red", current: true, url: "#Red"},
  68
+                 {name: "green", current: false, url: "#Green"},
  69
+                 {name: "blue", current: false, url: "#Blue"}
  70
+               ],
  71
+               hasItems: function(ctx, fn) {
  72
+                 if (ctx.items.length) {
  73
+                   return fn(ctx);
  74
+                 }
  75
+               }
  76
+             }
  77
+  }
  78
+
  79
+}
  80
+
  81
+exports.handlebarsBench = function(suite, name, id) {
  82
+  var bench = benches[name],
  83
+      fn = Handlebars.compile(bench.source),
  84
+      ctx = bench.context,
  85
+      partials = {};
  86
+
  87
+  if (bench.partials) {
  88
+    for (var key in bench.partials) {
  89
+      partials[key] = Handlebars.compile(bench.partials[key]);
  90
+    }
  91
+  }
  92
+
  93
+  suite.bench(id || name, function(next) {
  94
+    fn(ctx, {partials: partials});
  95
+    next();
  96
+  });
  97
+}
  98
+
  99
+exports.handlebarsBench.benches = benches;
  100
+
  101
+})(typeof exports !== "undefined" ? exports : window);
84  benchmark/suites/jquery_suite.js
... ...
@@ -0,0 +1,84 @@
  1
+(function(exports){
  2
+
  3
+var benches = {
  4
+
  5
+  string: {
  6
+    source:  "Hello World!",
  7
+    context: {}
  8
+  },
  9
+
  10
+  replace: {
  11
+    source:  "Hello ${name}! You have ${count} new messages.",
  12
+    context: { name: "Mick", count: 30 }
  13
+  },
  14
+
  15
+  array: {
  16
+    source:  "{{each names}}${name}{{/each}}",
  17
+    context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
  18
+  },
  19
+
  20
+  object: {
  21
+    source:  "${person.name}${person.age}",
  22
+    context: { person: { name: "Larry", age: 45 } }
  23
+  },
  24
+
  25
+  partial: {
  26
+    source:   "{{tmpl(peeps) \"replace\"}}",
  27
+    context:  { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] }
  28
+  },
  29
+
  30
+  recursion: {
  31
+    source:   "${name}{{tmpl(kids) \"recursion\"}}",
  32
+    context:  {
  33
+                name: '1',
  34
+                kids: [
  35
+                  {
  36
+                    name: '1.1',
  37
+                    kids: [
  38
+                      {name: '1.1.1', kids: []}
  39
+                    ]
  40
+                  }
  41
+                ]
  42
+              }
  43
+  },
  44
+
  45
+  filter: {
  46
+    source:   "FOO ${bar.toUpperCase()}",
  47
+    context:  {
  48
+                bar: "bar"
  49
+              }
  50
+  },
  51
+
  52
+  complex: {
  53
+    source:  "<h1>${header}</h1>{{if items.length}}<ul>{{each items}}{{if current}}" +
  54
+             "<li><strong>${name}</strong></li>{{else}}" +
  55
+             "<li><a href=\"${url}\">${name}</a></li>{{/if}}"      +
  56
+             "{{/each}}</ul>{{else}}<p>The list is empty.</p>{{/if}}",
  57
+    context: {
  58
+               header: function() {
  59
+                 return "Colors";
  60
+               },
  61
+               items: [
  62
+                 {name: "red", current: true, url: "#Red"},
  63
+                 {name: "green", current: false, url: "#Green"},
  64
+                 {name: "blue", current: false, url: "#Blue"}
  65
+               ]
  66
+             }
  67
+  }
  68
+
  69
+}
  70
+
  71
+exports.jqueryBench = function(suite, name, id) {
  72
+  var bench = benches[name],
  73
+      fn = $.template(name, bench.source),
  74
+      ctx = bench.context;
  75
+
  76
+  suite.bench(id || name, function(next) {
  77
+    $.tmpl(fn, ctx);
  78
+    next();
  79
+  });
  80
+}
  81
+
  82
+exports.jqueryBench.benches = benches;
  83
+
  84
+})(typeof exports !== "undefined" ? exports : window);
97  benchmark/suites/mustache_suite.js
... ...
@@ -0,0 +1,97 @@
  1
+(function(exports){
  2
+
  3
+var benches = {
  4
+
  5
+  string: {
  6
+    source:  "Hello World!",
  7
+    context: {}
  8
+  },
  9
+
  10
+  replace: {
  11
+    source:  "Hello {{name}}! You have {{count}} new messages.",
  12
+    context: { name: "Mick", count: 30 }
  13
+  },
  14
+
  15
+  array: {
  16
+    source:  "{{#names}}{{name}}{{/names}}",
  17
+    context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
  18
+  },
  19
+
  20
+  object: {
  21
+    source:  "{{#person}}{{name}}{{age}}{{/person}}",
  22
+    context: { person: { name: "Larry", age: 45 } }
  23
+  },
  24
+
  25
+  partial: {
  26
+    source:   "{{#peeps}}{{>replace}}{{/peeps}}",
  27
+    context:  { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] },
  28
+    partials: { replace: "Hello {{name}}! You have {{count}} new messages." }
  29
+  },
  30
+
  31
+  recursion: {
  32
+    source:   "{{name}}{{#kids}}{{>recursion}}{{/kids}}",
  33
+    context:  {
  34
+                name: '1',
  35
+                kids: [
  36
+                  {
  37
+                    name: '1.1',
  38
+                    kids: [
  39
+                      {name: '1.1.1', kids: []}
  40
+                    ]
  41
+                  }
  42
+                ]
  43
+              },
  44
+    partials: { recursion: "{{name}}{{#kids}}{{>recursion}}{{/kids}}" }
  45
+  },
  46
+
  47
+  filter: {
  48
+    source:   "{{#filter}}foo {{bar}}{{/filter}}",
  49
+    context:  {
  50
+                filter: function() {
  51
+                  return function(text, render) {
  52
+                    return render(text).toUpperCase();
  53
+                  }
  54
+                },
  55
+                bar: "bar"
  56
+              }
  57
+  },
  58
+
  59
+  complex: {
  60
+    source:  "<h1>{{header}}</h1>{{#hasItems}}<ul>{{#items}}{{#current}}" +
  61
+             "<li><strong>{{name}}</strong></li>{{/current}}{{^current}}" +
  62
+             "<li><a href=\"{{url}}\">{{name}}</a></li>{{/current}}"      +
  63
+             "{{/items}}</ul>{{/hasItems}}{{^hasItems}}<p>The list is empty.</p>{{/hasItems}}",
  64
+    context: {
  65
+               header: function() {
  66
+                 return "Colors";
  67
+               },
  68
+               items: [
  69
+                 {name: "red", current: true, url: "#Red"},
  70
+                 {name: "green", current: false, url: "#Green"},
  71
+                 {name: "blue", current: false, url: "#Blue"}
  72
+               ],
  73
+               hasItems: function() {
  74
+                 return this.items.length !== 0;
  75
+               },
  76
+               empty: function() {
  77
+                 return this.items.length === 0;
  78
+               }
  79
+             }
  80
+  }
  81
+}
  82
+
  83
+exports.mustacheBench = function(suite, name, id) {
  84
+  var bench = benches[name],
  85
+      src = bench.source,
  86
+      ctx = bench.context,
  87
+      partials = bench.partials;
  88
+
  89
+  suite.bench(id || name, function(next) {
  90
+    Mustache.to_html(src, ctx, partials);
  91
+    next();
  92
+  });
  93
+}
  94
+
  95
+exports.mustacheBench.benches = benches;
  96
+
  97
+})(typeof exports !== "undefined" ? exports : window);
107  benchmark/uubench.js
... ...
@@ -0,0 +1,107 @@
  1
+(function(uubench){
  2
+
  3
+function Bench(id, test, options, callback) {
  4
+  this.id = id;
  5
+  this.options = options;
  6
+  this.test = test;
  7
+  this.loop = test.length > 1;
  8
+  this.callback = callback;
  9
+}
  10
+
  11
+Bench.prototype.run = function(iter) {
  12
+  var self = this, fn = self.test,
  13
+      checkfn = self.options.type === "adaptive" ? adaptive : fixed,
  14
+      i = iter, pend = i,
  15
+      min = self.options.min, start;
  16
+
  17
+  if (self.loop) {
  18
+    pend = 1;
  19
+    start = new Date();
  20
+    fn(checkfn, i);
  21
+  } else {
  22
+    start = new Date();
  23
+    while (i--) {
  24
+      fn(checkfn);
  25
+    }
  26
+  }
  27
+
  28
+  function fixed() {
  29
+    if (--pend === 0) {
  30
+      var elapsed = new Date() - start;
  31
+      self.callback({iterations: iter, elapsed: elapsed});
  32
+    }
  33
+  }
  34
+
  35
+  function adaptive() {
  36
+    if (--pend === 0) {
  37
+      var elapsed = new Date() - start;
  38
+      if (elapsed < min) {
  39
+        self.run(iter*2);
  40
+      } else {
  41
+        self.callback({iterations: iter, elapsed: elapsed});
  42
+      }
  43
+    }
  44
+  }
  45
+}
  46
+
  47
+uubench.Bench = Bench;
  48
+
  49
+uubench.defaults = {
  50
+  type:       "adaptive", // adaptive or fixed
  51
+  iterations: 10,         // starting iterations
  52
+  min:        100,        // minimum run time (ms) - adaptive only
  53
+  delay:      100         // delay between tests (ms)
  54
+}
  55
+
  56
+function Suite(opts) {
  57
+  for (var key in uubench.defaults) {
  58
+    if (opts[key] === undefined) {
  59
+      opts[key] = uubench.defaults[key];
  60
+    }
  61
+  }
  62
+  this.options = opts;
  63
+  this.tests = [];
  64
+}
  65
+
  66
+Suite.prototype.bench = function(name, fn) {
  67
+  var self = this;
  68
+  self.tests.push(new Bench(name, fn, this.options, function(stats) {
  69
+    self.emit("result", name, stats);
  70
+    self.pending--;
  71
+    self.check();
  72
+  }));
  73
+}
  74
+
  75
+Suite.prototype.run = function() {
  76
+  if (this.pending) return;
  77
+  var self = this, len = self.tests.length;
  78
+  self.emit("start", self.tests);
  79
+  self.start = new Date().getTime();
  80
+  self.pending = len;
  81
+  for (var i=0; i<len; i++) {
  82
+    self.runOne(i);
  83
+  }
  84
+}
  85
+
  86
+Suite.prototype.runOne = function(idx) {
  87
+  var self = this;
  88
+  setTimeout(function() {
  89
+    self.tests[idx].run(self.options.iterations);
  90
+  }, self.options.delay);
  91
+}
  92
+
  93
+Suite.prototype.check = function() {
  94
+  if (this.pending) return;
  95
+  this.emit("done", new Date().getTime() - this.start);
  96
+}
  97
+
  98
+Suite.prototype.emit = function(type) {
  99
+  var event = this.options[type];
  100
+  if (event) {
  101
+    event.apply(this, Array.prototype.slice.call(arguments, 1));
  102
+  }
  103
+}
  104
+
  105
+uubench.Suite = Suite;
  106
+
  107
+})(typeof exports !== 'undefined' ? exports : window.uubench = {});
14  docs/about.md
Source Rendered
... ...
@@ -0,0 +1,14 @@
  1
+Why Dust? Why another templating engine when there are so many alternatives? Dust is based on the philosophy that an ideal templating environment should be:
  2
+
  3
++ __Markup-like__: _A templating syntax should not encompass operations that are better left to a programming language_. Templates should make it easy to format content for presentation while keeping application logic where it belongs: in the application.
  4
++ __Asynchronous__: Template helpers should be callable _asynchronously_ and in _parallel_ so that expensive operations (caching, deferred loading, filtering) can run as the template is being rendered.
  5
++ __Streaming__: Templates should allow (but not require) data to be flushed to the output in user-defined chunks.
  6
++ __Browser and server compatible__: Templates should render in both server and browser environments without hacks or extensive configuration.
  7
++ __Storage agnostic__: _The templating engine should not impose a particular loading scheme_. Developers should be free to load templates via the filesystem, a database or an army of carrier pigeons.
  8
++ __Composable__: Designers should be able to break presentation markup into manageable components and combine these components at runtime. _It should not be necessary to statically link templates or manually assemble 'layouts' inside application code._
  9
++ __Format agnostic__: While HTML generation and DOM manipulation are useful in specific instances, a general-purpose template system should not be tied to a particular output format.
  10
++ __Precise__: The parser should be accurate enough that designers rarely have to use escape sequences to achieve the desired result. Similarly, templates shouldn't mysteriously generate or eliminate whitespace.
  11
++ __Safe(r)__: At the very least, the engine should be configurable such that it is reasonably safe to render untrusted templates in a server environment.
  12
++ __Fast__: Server-side templates cannot always be cached. Browser-side templates may be rendered on devices with limited system resources. _A template engine should be fast enough to render in real time without bottlenecking its environment_.
  13
+
  14
+If this list leaves you nodding your head in agreement you should [give Dust a try](http://akdubya.github.com/dustjs).
291  docs/api.md
Source Rendered
... ...
@@ -0,0 +1,291 @@
  1
+A pure JavaScript library, Dust is runs in both browser-side and server-side environments. Dust templates are precompiled and then loaded where they are needed along with the `dust.js` runtime library. The library doesn't make any assumptions about how templates are loaded; you are free to integrate templating into your environment as you see fit.
  2
+
  3
+### Installation
  4
+
  5
+To run Dust within Node.js, clone the repository and require `dust.js`:
  6
+
  7
+    var dust = require("path/to/dust/lib/dust");
  8
+
  9
+This will import everything needed to parse, compile and render templates.
  10
+
  11
+To render Dust templates in the browser, include the `dust.js` runtime in your script tags, along with your precompiled templates. You may run the parser and compiler within the browser if you like (as in the online demo), but precompilation is a much cleaner approach.
  12
+
  13
+### Compiling Templates
  14
+
  15
+Use `dust.compile` to compile a template body into a string of JavaScript source code:
  16
+
  17
+    var compiled = dust.compile("Hello {name}!", "intro");
  18
+
  19
+The variable `compiled` now contains the following string:
  20
+
  21
+    '(function(){dust.register("intro",body_0) ...'
  22
+
  23
+If you save this source to a file and include the file in your HTML script tags, the compiled template will automatically register itself with the local runtime, under the name "intro". To evaluate a compiled template string manually, use `dust.loadSource`:
  24
+
  25
+    dust.loadSource(compiled);
  26
+
  27
+The template is now available within the `dust.cache` object.
  28
+
  29
+### Rendering Templates
  30
+
  31
+The rendering engine provides both callback and streaming interfaces.
  32
+
  33
+#### The Callback Interface
  34
+
  35
+To render a template, call `dust.render` with the template name, a context object and a callback function:
  36
+
  37
+    dust.render("intro", {name: "Fred"}, function(err, out) {
  38
+      console.log(out);
  39
+    });
  40
+
  41
+The code above will write the following to the console:
  42
+
  43
+    Hello Fred!
  44
+
  45
+#### The Streaming Interface
  46
+
  47
+Templates may also be streamed. `dust.stream` returns a handler very similar to a Node `EventEmitter`:
  48
+
  49
+    dust.stream("index", context)
  50
+        .on("data", function(data) {
  51
+          console.log(data);
  52
+        })
  53
+        .on("end", function() {
  54
+          console.log("I'm finished!");
  55
+        })
  56
+        .on("error", function(err) {
  57
+          console.log("Something terrible happened!");
  58
+        });
  59
+
  60
+When used with specially crafted context handlers, the streaming interface provides chunked template rendering.
  61
+
  62
+### Contexts
  63
+
  64
+The context is a special object that handles variable lookups and controls template behavior. It is the interface between your application logic and your templates. The context can be visualized as a stack of objects that grows as we descend into nested sections:
  65
+
  66
+    global     --> { helper: function() { ... }, ... }
  67
+    root       --> { profile: { ... }, ... }
  68
+    profile    --> { friends: [ ... ], ... }
  69
+    friends[0] --> { name: "Jorge", ... }
  70
+
  71
+When looking up a key, Dust searches the context stack from the bottom up. There is no need to merge helper functions into the template data; instead, create a base context onto which you can push your local template data:
  72
+
  73
+    // Set up a base context with global helpers
  74
+    var base = dust.Context.base({
  75
+      sayHello: function() { return "Hello!" }
  76
+    });
  77
+
  78
+    // Push to the base context at render time
  79
+    dust.render("index", base.push({foo: "bar"}), function(err, out) {
  80
+      console.log(out);
  81
+    });
  82
+
  83
+Dust does not care how your reference objects are built. You may, for example, push prototyped objects onto the stack. The system leaves the `this` keyword intact when calling handler functions on your objects.
  84
+
  85
+### Handlers
  86
+
  87
+When Dust encounters a function in the context, it calls the function, passing in arguments that reflect the current state of the template. In the simplest case, a handler can pass a value back to the template engine:
  88
+
  89
+    {
  90
+      name: function() {
  91
+        return "Bob";
  92
+      }
  93
+    }
  94
+
  95
+#### Chunks
  96
+
  97
+But handlers can do much more than return values: they have complete control over the flow of the template, using the same API Dust uses internally. For example, the handler below writes a string directly to the current template chunk:
  98
+
  99
+    {
  100
+      name: function(chunk) {
  101
+        return chunk.write("Bob");
  102
+      }
  103
+    }
  104
+
  105
+A `Chunk` is a Dust primitive for controlling the flow of the template. Depending upon the behaviors defined in the context, templates may output one or more chunks during rendering. A handler that writes to a chunk directly must return the modified chunk.
  106
+
  107
+#### Accessing the Context
  108
+
  109
+Handlers have access to the context object:
  110
+
  111
+    {
  112
+      wrap: function(chunk, context) {
  113
+        return chunk.write(context.get("foo"));
  114
+      }
  115
+    }
  116
+
  117
+`context.get("foo")` searches for _foo_ within the context stack. `context.current()` retrieves the value most recently pushed onto the context stack.
  118
+
  119
+#### Accessing Body Parameters
  120
+
  121
+The `bodies` object provides access to any bodies defined within the calling block.
  122
+
  123
+    {#guide}foo{:else}bar{/guide}
  124
+
  125
+The template above will either render "foo" or "bar" depending on the behavior of the handler below:
  126
+
  127
+    {
  128
+      guide: function(chunk, context, bodies) {
  129
+        if (secret === 42) {
  130
+          return chunk.render(bodies.block, context);
  131
+        } else {
  132
+          return chunk.render(bodies['else'], context);
  133
+        }
  134
+      }
  135
+    }
  136
+
  137
+`bodies.block` is a special parameter that returns the default (unnamed) block. `chunk.render` renders the chosen block.
  138
+
  139
+#### Accessing Inline Parameters
  140
+
  141
+The `params` object contains any inline parameters passed to a section tag:
  142
+
  143
+    {
  144
+      hello: function(chunk, context, bodies, params) {
  145
+        if (params.greet === "true") {
  146
+          return chunk.write("Hello!");
  147
+        }
  148
+        return chunk;
  149
+      }
  150
+    }
  151
+
  152
+#### Asynchronous Handlers
  153
+
  154
+You may define handlers that execute asynchronously and in parallel:
  155
+
  156
+    {
  157
+      type: function(chunk) {
  158
+        return chunk.map(function(chunk) {
  159
+          setTimeout(function() {
  160
+            chunk.end("Async");
  161
+          });
  162
+        });
  163
+      }
  164
+    }
  165
+
  166
+`chunk.map` tells Dust to manufacture a new chunk, reserving a slot in the output stream before continuing on to render the rest of the template. You must (eventually) call `chunk.end()` on a mapped chunk to weave its content back into the stream.
  167
+
  168
+`chunk.map` provides a convenient way to split up templates rendered via `dust.stream`. For example, you might wrap the head of an HTML document in a special `{#head} ... {/head}` tag that is flushed to the browser before the rest of the body has finished rendering.
  169
+
  170
+### Reference
  171
+
  172
+#### Compiling
  173
+
  174
+    dust.compile(source, name)
  175
+
  176
+Compiles `source` into a JavaScript template string. Registers itself under `name` when evaluated.
  177
+
  178
+    dust.optimizers
  179
+
  180
+Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression:
  181
+
  182
+    dust.optimizers.format = function(ctx, node) { return node };
  183
+
  184
+#### Loading
  185
+
  186
+    dust.register(name, function)
  187
+
  188
+Used internally to register templates with the runtime environment. Override to customize the way Dust caches templates.
  189
+
  190
+    dust.load(name, chunk, context)
  191
+
  192
+Used internally to loads and render the named template. Override to change the way templates are loaded (e.g., to load templates from the filesystem or a database).
  193
+
  194
+    dust.loadSource(source, [filename])
  195
+
  196
+Evaluates compiled `source` string. In Node.js, evaluates `source` as if it were loaded from `filename`. `filename` is optional.
  197
+
  198
+#### Rendering
  199
+
  200
+    dust.render(name, context, callback(error, output))
  201
+
  202
+Renders the named template and calls `callback` on completion. `context` may be a plain object or an instance of `dust.Context`.
  203
+
  204
+    dust.stream(name, context)
  205
+
  206
+Streams the named template. `context` may be a plain object or an instance of `dust.Context`. Returns an instance of `dust.Stream`.
  207
+
  208
+    stream.on("data", listener(data))
  209
+    stream.on("end", listener)
  210
+    stream.on("error", listener(error))
  211
+
  212
+Registers an event listener. Streams accept a single listener for a given event.
  213
+
  214
+#### Contexts
  215
+
  216
+    dust.Context.base(object)
  217
+
  218
+Manufactures a `dust.Context` instance, with its global object set to `object`.
  219
+
  220
+    context.get(key)
  221
+
  222
+Retrieves the value at `key` from the context stack.
  223
+
  224
+    context.push(head, [index], [length])
  225
+
  226
+Pushes an arbitrary value onto the context stack and returns a new context instance. Specify `index` and/or `length` to enable enumeration helpers.
  227
+
  228
+    context.rebase(head)
  229
+
  230
+Returns a new context instance consisting only of the value at `head`, plus any previously defined global object.
  231
+
  232
+    context.current()
  233
+
  234
+Returns the `head` of the context stack.
  235
+
  236
+#### Chunks
  237
+
  238
+The operations below always return a chunk object.
  239
+
  240
+    chunk.write(data)
  241
+
  242
+Writes `data` to this chunk's buffer.
  243
+
  244
+    chunk.map(callback(chunk))
  245
+
  246
+Creates a new chunk and passes it to `callback`. Use `map` to wrap asynchronous functions and to partition the template for streaming.
  247
+
  248
+    chunk.end(data)
  249
+
  250
+Writes `data` to this chunk's buffer and marks it as flushable. This method _must_ be called on any chunks created via `chunk.map`. Do _not_ call this method on a handler's main chunk -- `dust.render` and `dust.stream` take care of this for you.
  251
+
  252
+    chunk.tap(function)
  253
+    chunk.untap()
  254
+
  255
+Convenience methods for applying filters to a stream. See the _filter_ demo for an example.
  256
+
  257
+    chunk.render(body, context)
  258
+
  259
+Renders a template block, such as a default block or an `else` block. Basically equivalent to `body(chunk, context)`.
  260
+
  261
+    chunk.setError(error)
  262
+
  263
+Sets an error on this chunk and immediately flushes the output.
  264
+
  265
+    chunk.reference(elem, context, auto, filters)
  266
+    chunk.section(elem, context, bodies, params)
  267
+    chunk.exists(elem, context, bodies)
  268
+    chunk.notexists(elem, context, bodies)
  269
+    chunk.block(elem, context, bodies)
  270
+    chunk.partial(elem, context)
  271
+    chunk.helper(name, context, bodies, params)
  272
+
  273
+These methods implement Dust's default behavior for keys, sections, blocks, partials and context helpers. While it is unlikely you'll need to modify these methods or invoke them from within handlers, the source code may be a useful point of reference for developers.
  274
+
  275
+#### Utilities
  276
+
  277
+    dust.filters
  278
+
  279
+Object containing built-in key filters. Can be customized with additional filters.
  280
+
  281
+    dust.helpers
  282
+
  283
+Object containing the built-in context helpers. These may also be customized.
  284
+
  285
+    dust.escapeHtml
  286
+
  287
+HTML escape function used by `dust.filters.h`.
  288
+
  289
+    dust.escapeJs
  290
+
  291
+JavaScript string escape function used by `dust.filters.j`.
68  docs/build.js
... ...
@@ -0,0 +1,68 @@
  1
+var path   = require('path'),
  2
+    fs     = require('fs'),
  3
+    Script = process.binding('evals').Script,
  4
+    dust   = require('../lib/dust'),
  5
+    root   = path.join(path.dirname(__filename), "..");
  6
+
  7
+var src = fs.readFileSync(path.join(root, 'docs/index.dust.html'), 'utf8');
  8
+dust.loadSource(dust.compile(src, "index"));
  9
+
  10
+var sd = process.compile(fs.readFileSync(path.join(root, 'vendor/showdown.js'), 'utf8'), 'showdown.js');
  11
+
  12
+var inliners = {
  13
+  css: function(names) {
  14
+    var out = "<style type=\"text/css\">";
  15
+    names.forEach(function(name) {
  16
+      out += fs.readFileSync(path.join(root, 'docs', name + '.css'), 'utf8');
  17
+    });
  18
+    out += "</style>";
  19
+    return out;
  20
+  },
  21
+
  22
+  js: function(names) {
  23
+    var out = "<script type=\"text/javascript\">";
  24
+    names.forEach(function(name) {
  25
+      out += fs.readFileSync(path.join(root, 'docs', name + '.js'), 'utf8');
  26
+    });
  27
+    out += "</script>";
  28
+    return out;
  29
+  }
  30
+}
  31
+
  32
+var context = {
  33
+  inline: function(chk, ctx, bod, prm) {
  34
+    var names = prm.names.split(' ');
  35
+    return chk.write(inliners[prm.ext](names));
  36
+  },
  37
+
  38
+  tmpl: function(chk, ctx, bod, prm) {
  39
+    var names = prm.names.split(' ');
  40
+    var out = "<script type=\"text/javascript\">";
  41
+    names.forEach(function(name) {
  42
+      out += dust.compile(fs.readFileSync(path.join(root, 'docs', name + '.dust.html'), 'utf8'), "select");
  43
+    });
  44
+    out += "</script>";
  45
+    return chk.write(out);
  46
+  },
  47
+
  48
+  md: function(chk, ctx, bod, prm) {
  49
+    var converter = new sd();
  50
+    return chk.tap(function(data) {
  51
+      return converter.makeHtml(data);
  52
+    }).render(bod.block, ctx).untap();
  53
+  },
  54
+
  55
+  file: function(chk, ctx, bod, prm) {
  56
+    var name = prm.name;
  57
+    return chk.write(fs.readFileSync(path.join(root, 'docs', name), 'utf8'));
  58
+  }
  59
+}
  60
+
  61
+function render() {
  62
+  dust.render("index", context, function(err, output) {
  63
+    if (err) throw err;
  64
+    fs.writeFileSync(path.join(root, 'index.html'), output);
  65
+  });
  66
+}
  67
+
  68
+render();
202  docs/index.css
... ...
@@ -0,0 +1,202 @@
  1
+body {
  2
+  font-family: 'Georgia', serif;
  3
+  font-size: 18px;
  4
+  margin: 0;
  5
+  padding: 0;
  6
+}
  7
+
  8
+p, h4, h3, .content ul {
  9
+  line-height: 26px;
  10
+  margin-top: 26px;
  11
+  margin-bottom: 26px;
  12
+}
  13
+
  14
+.content ul li {
  15
+  margin-top: 13px;
  16
+  margin-bottom: 13px;
  17
+}
  18
+
  19
+h1, h2 {
  20
+  font-size: 32px;
  21
+  font-weight: normal;
  22
+  margin: 12px 0 12px 2%;
  23
+}
  24
+
  25
+h1 {
  26
+  float: left;
  27
+}
  28
+
  29
+h3 {
  30
+  font-size: 24px;
  31
+}
  32
+
  33
+h4 {
  34
+  font-size: 1em;
  35
+}
  36
+
  37
+h1, h2, pre, code, .console, .status, #nav, #tagline {
  38
+  font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
  39
+}
  40
+
  41
+a:link, a:visited {
  42
+  color: #ef674a;
  43
+}
  44
+
  45
+p code {
  46
+  font-size: 16px;
  47
+  line-height: 16px;
  48
+}
  49
+
  50
+pre, .console {
  51
+  background-color: #191919;
  52
+  white-space: pre-wrap;
  53
+  word-wrap: break-word;
  54
+}
  55
+
  56
+.console {
  57
+  font-size: 16px;
  58
+  height: 270px;
  59
+  color: #dddddd;
  60
+}
  61
+
  62
+#nav {
  63
+  position: fixed;
  64
+  top: 18px;
  65
+  right: 2%;
  66
+  font-size: 22px;
  67
+  z-index: 99;
  68
+}
  69
+
  70
+#nav a:link, #nav a:visited {
  71
+  color: #EAF2D9;
  72
+}
  73
+
  74
+#nav a {