├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── examples ├── app │ ├── footer.partial.html │ ├── header.partial.html │ ├── index.dot.html │ ├── polyfilled.html │ └── sw.js └── index.js ├── karma.conf.js ├── package.json ├── streaming-dot.js ├── streaming-dot.min.js ├── test └── streaming-dot.test.js └── update-version.sh /.gitignore: -------------------------------------------------------------------------------- 1 | npm-debug.log 2 | node_modules 3 | *.pem 4 | *.gz 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | sudo: required 3 | language: node_js 4 | node_js: 5 | - "5" 6 | - "6" 7 | - "7" 8 | before_install: 9 | - export CHROME_BIN=/usr/bin/google-chrome 10 | - export DISPLAY=:99.0 11 | - sh -e /etc/init.d/xvfb start 12 | - sudo apt-get update 13 | - sudo apt-get install -y libappindicator1 fonts-liberation 14 | - wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb 15 | - sudo dpkg -i google-chrome*.deb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Google Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streaming doT 2 | [![Build Status](https://travis-ci.org/surma/streaming-dot.svg?branch=master)](https://travis-ci.org/surma/streaming-dot) 3 | 4 | Streaming doT is a [doT]-based streaming templating language. 5 | 6 | Quick facts: 7 | 8 | * Generates a stream 9 | * Can consume streams and promises 10 | * Built for Node and for the web (with ServiceWorkers in mind) 11 | * 2KB small (1KB gzip’d) 12 | * Conditionals built-in 13 | * Compiles templates to JavaScript 14 | * Templates can contain arbitrary JavaScript 15 | 16 | ## Usage 17 | 18 | ### `doT.compile(templateString, opts)` 19 | Compiles `templateString` to JavaScript. By default, it returns a function that takes the data object as an argument. Inside the template string the following expressions can be used: 20 | 21 | * `{{=}}`: Inserts `` into the template. `` must be a string, a `Uint8Array` or a Promise that resolves to a value of any of these types. The data object is accessible as `it`. 22 | * `{{?}}...A...{{??}}...B...{{?}}`: Only inserts A if `` is truthy or is a Promise that resolves to a truthy value. Otherwise, B is inserted. The B block is optional. 23 | * `{{~}}`: Inserts `` into the template. `` must be a stream. 24 | * `{{}}`: Inserts `` into the [generator function]. The code can `yield` Promises to insert their value into the template. For example, `{{=it.name}}` is equivalent to `{{yield Promise.resolve(it.name)}}` 25 | 26 | `opts` is an object with any subset of the following default values: 27 | 28 | ```js 29 | { 30 | evaluate: /\{\{(([^\}]+|\\.)+)\}\}/g, 31 | interpolate: /\{\{=\s*([^\}]+)\}\}/g, 32 | stream: /\{\{~\s*([^\}]+)\}\}/g, 33 | conditional: /\{\{\?(\?)?\s*([^\}]*)?\}\}/g, 34 | node: typeof(process) === 'object', 35 | noEval: false, 36 | varname: "it" 37 | } 38 | ``` 39 | 40 | * `evaluate`, `interpolate`, `stream` and `conditional` are the RegExps for the previously mentioned template expressions. 41 | * `node`: If `true`, the generated code will be targeted for Node, otherwise for browsers. 42 | * `noEval`: If `true`, return the functions code instead of a callable. 43 | * `varname`: The name under which the data object is accessible in the template expressions. 44 | 45 | ## Compatibility 46 | 47 | | Browser | Support | Links | 48 | |---------|---------|-------| 49 | | Node | ✅ ≥5 | | 50 | | Chrome | ✅ ≥52 | | 51 | | Firefox | ⏰ In Development | Missing [ReadableStream] on fetch (https://bugzilla.mozilla.org/show_bug.cgi?id=1128959) | 52 | | Safari | ⏰ In Development | Missing TextDecoder ([polyfillable][TextDecoder polyfill]) | 53 | | Edge | ⏰ In Development | Missing TextDecoder ([polyfillable][TextDecoder polyfill]) and ReadableStream ([polyfillable][ReadableStream polyfill]) | 54 | 55 | ## Current shortcomings and potential tripwires 56 | 57 | * The parser itself is not streaming (i.e. `doT.compile()` cannot consume a stream). 58 | * ~~Currently, the body of a conditional cannot contain template expressions~~ 59 | * Nested conditionals are not possible due to the RegExp-based nature of the parser 60 | 61 | ## Example 62 | 63 | A fully runnable example can be found in the `example` folder. It is a node webserver using streaming doT as a templating language. The website has a service worker that uses streaming doT as well. 64 | 65 | To run the example, start the webserver by running `node index.js` in the `example` folder or visit https://streaming-dot-example.hyperdev.space/ for a hosted version of the example code (thanks [HyperDev]). 66 | 67 | ### Template 68 | 69 | ``` 70 | {{~it.header}} 71 | 72 |

This is a doT template

73 |

74 | This content was generated 75 | {{?it.location}} 76 | {{=it.location}} 77 | {{??}} 78 | server-side (refresh for ServiceWorker) 79 | {{?}} 80 |

81 | 82 | {{~it.footer}}} 83 | ``` 84 | 85 | ### Node 86 | 87 | ```js 88 | function handler(req, res) { 89 | fs.readFile('app/index.dot', 'utf-8', (_, data) => { 90 | var template = doT.compile(data); 91 | var stream = template({ 92 | header: fs.createReadStream('app/header.partial.html'), 93 | footer: fs.createReadStream('app/footer.partial.html'), 94 | }); 95 | res.set('Content-Type', 'text/html'); 96 | stream.pipe(res) 97 | }); 98 | } 99 | ``` 100 | 101 | ### ServiceWorker 102 | 103 | ```js 104 | self.onfetch = event => event.respondWith( 105 | getTemplateSomehow() 106 | .then(body => { 107 | const template = doT.compile(body); 108 | const response = template({ 109 | header: caches.match('/header.partial.html').then(r => r.body), 110 | footer: caches.match('/footer.partial.html').then(r => r.body), 111 | serviceworker: timeoutPromise(2000).then(_ => true) 112 | }); 113 | return new Response(response, {headers: {'Content-Type': 'text/html'}}); 114 | ); 115 | ``` 116 | 117 | ## License 118 | Apache 2.0 119 | 120 | --- 121 | Version 1.1.1 122 | 123 | [doT]: https://github.com/olado/doT 124 | [HyperDev]: https://hyperdev.com/ 125 | [generator function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* 126 | [TextDecoder polyfill]: https://github.com/inexorabletash/text-encoding 127 | [ReadableStream polyfill]: https://github.com/creatorrr/web-streams-polyfill 128 | -------------------------------------------------------------------------------- /examples/app/footer.partial.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /examples/app/header.partial.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Streaming doT 5 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /examples/app/index.dot.html: -------------------------------------------------------------------------------- 1 | {{~it.header}} 2 | 3 |

This is a doT template

4 |

5 | This content was generated 6 | {{?it.location}} 7 | {{=it.location}} 8 | {{??}} 9 | server-side (refresh for ServiceWorker, or click here for a polyfilled demo) 10 | {{?}} 11 |

12 |

streaming doT version: v{{=it.version}}

13 | 14 | {{~it.footer}} -------------------------------------------------------------------------------- /examples/app/polyfilled.html: -------------------------------------------------------------------------------- 1 | 2 | 13 |

Stream output

14 |

15 | 
16 | 
17 | 
18 | 
19 | 


--------------------------------------------------------------------------------
/examples/app/sw.js:
--------------------------------------------------------------------------------
 1 | importScripts('/streaming-dot.min.js');
 2 | 
 3 | const ASSETS = [
 4 |   '/header.partial.html',
 5 |   '/footer.partial.html',
 6 |   '/index.dot.html'
 7 | ];
 8 | 
 9 | self.oninstall = event => event.waitUntil(
10 |   caches.open('static')
11 |     .then(cache => cache.addAll(ASSETS))
12 |     .then(_ => self.skipWaiting())
13 | );
14 | 
15 | self.onactivate = event => event.waitUntil(self.clients.claim());
16 | 
17 | function timeoutPromise(t) {
18 |   return new Promise(resolve =>
19 |     setTimeout(resolve, t)
20 |   );
21 | }
22 | 
23 | self.onfetch = event => {
24 |   event.parsedUrl = new URL(event.request.url);
25 |   if (event.parsedUrl.pathname !== '/') return event.respondWith(fetch(event.request));
26 |   event.respondWith(
27 |     caches.match('/index.dot.html')
28 |       .then(response => response.text())
29 |       .then(body => {
30 |         const template = doT.compile(body);
31 |         const response = template({
32 |           header: caches.match('/header.partial.html').then(r => r.body),
33 |           footer: caches.match('/footer.partial.html').then(r => r.body),
34 |           location: timeoutPromise(2000).then(_ => 'in a service worker'),
35 |           version: doT.version
36 |         });
37 |         return new Response(response, {headers: {'Content-Type': 'text/html'}});
38 |       })
39 |   );
40 | };
41 | 


--------------------------------------------------------------------------------
/examples/index.js:
--------------------------------------------------------------------------------
 1 | var doT = require('../streaming-dot.js');
 2 | var fs = require('fs');
 3 | var express = require('express');
 4 | 
 5 | var app = express();
 6 | 
 7 | app.get('/streaming-dot.js', express.static('../'));
 8 | app.get('/streaming-dot.min.js', express.static('../'));
 9 | app.use('/node_modules', express.static('../node_modules'));
10 | app.get('/', (req, res, next) => {
11 |   fs.readFile('app/index.dot.html', 'utf-8', (_, data) => {
12 |     var template = doT.compile(data);
13 |     var stream = template({
14 |       header: fs.createReadStream('app/header.partial.html'),
15 |       footer: fs.createReadStream('app/footer.partial.html'),
16 |       version: doT.version
17 |     });
18 |     res.set('Content-Type', 'text/html');
19 |     stream.pipe(res);
20 |   });
21 | });
22 | app.use('/', express.static('app'));
23 | 
24 | console.log('Starting webserver on http://localhost:8080');
25 | require('http').createServer(app).listen(8080);


--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
 1 | module.exports = function(config) {
 2 |   const configuration = {
 3 |     basePath: '',
 4 |     frameworks: ['mocha'],
 5 |     files: [
 6 |       'streaming-dot.js',
 7 |       'node_modules/chai/chai.js',
 8 |       'test/*.test.js'
 9 |     ],
10 |     exclude: [
11 |     ],
12 |     preprocessors: {
13 |     },
14 |     reporters: ['progress'],
15 |     port: 9876,
16 |     colors: true,
17 |     logLevel: config.LOG_INFO,
18 |     autoWatch: true,
19 |     browsers: ['Chrome'],
20 |     singleRun: true,
21 |     concurrency: Infinity,
22 |     customLaunchers: {
23 |         Chrome_travis_ci: {
24 |             base: 'Chrome',
25 |             flags: ['--no-sandbox']
26 |         }
27 |     }
28 |   };
29 | 
30 |   if (process.env.TRAVIS) {
31 |       configuration.browsers = ['Chrome_travis_ci'];
32 |   }
33 | 
34 |   config.set(configuration);
35 | };


--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "name": "streaming-dot",
 3 |   "version": "1.1.1",
 4 |   "description": "doT-based streaming templating engine for Node and the web",
 5 |   "main": "streaming-dot.js",
 6 |   "scripts": {
 7 |     "test": "npm run test-node && npm run test-browser",
 8 |     "test-node": "mocha",
 9 |     "test-browser": "karma start",
10 |     "version": "./update-version.sh",
11 |     "build": "babili streaming-dot.js -o streaming-dot.min.js"
12 |   },
13 |   "repository": {
14 |     "type": "git",
15 |     "url": "git+https://github.com/surma/streaming-dot.git"
16 |   },
17 |   "author": "Surma ",
18 |   "license": "Apache-2.0",
19 |   "bugs": {
20 |     "url": "https://github.com/surma/streaming-dot/issues"
21 |   },
22 |   "homepage": "https://github.com/surma/streaming-dot#readme",
23 |   "devDependencies": {
24 |     "babili": "^0.0.8",
25 |     "chai": "^3.5.0",
26 |     "karma": "^1.3.0",
27 |     "karma-chrome-launcher": "^2.0.0",
28 |     "karma-mocha": "^1.3.0",
29 |     "mocha": "^3.1.2"
30 |   },
31 |   "optionalDependencies": {
32 |     "express": "^4.14.0",
33 |     "text-encoding": "^0.6.1",
34 |     "web-streams-polyfill": "^1.3.0"
35 |   }
36 | }
37 | 


--------------------------------------------------------------------------------
/streaming-dot.js:
--------------------------------------------------------------------------------
  1 | /**!
  2 |  *
  3 |  * Copyright 2016 Google Inc. All rights reserved.
  4 |  *
  5 |  * Licensed under the Apache License, Version 2.0 (the "License");
  6 |  * you may not use this file except in compliance with the License.
  7 |  * You may obtain a copy of the License at
  8 |  *
  9 |  *     http://www.apache.org/licenses/LICENSE-2.0
 10 |  *
 11 |  * Unless required by applicable law or agreed to in writing, software
 12 |  * distributed under the License is distributed on an "AS IS" BASIS,
 13 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14 |  * See the License for the specific language governing permissions and
 15 |  * limitations under the License.
 16 |  */
 17 | 
 18 | (function (root, factory) {
 19 |   if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
 20 |       factory(exports);
 21 |   } else {
 22 |       factory((root.doT = {}));
 23 |   }
 24 | }(this, function (exports) {
 25 |   "use strict";
 26 | 
 27 |   Object.assign(exports, {
 28 |     version: "1.1.1",
 29 |     templateSettings: {
 30 |       evaluate: /\{\{(([^\}]+|\\.)+)\}\}/g,
 31 |       interpolate: /\{\{=\s*([^\}]+)\}\}/g,
 32 |       stream: /\{\{~\s*([^\}]+)\}\}/g,
 33 |       conditional: /\{\{\?(\?)?\s*([^\}]*)?\}\}/g,
 34 |       node: typeof(process) === 'object',
 35 |       varname: "it",
 36 |     }
 37 |   });
 38 | 
 39 |   function unescape(code) {
 40 |     return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, " ");
 41 |   }
 42 | 
 43 |   exports.compile = function(tmpl, c, def) {
 44 |     c = Object.assign({}, exports.templateSettings, c);
 45 |     var helpers = 
 46 |       "var P=Promise.resolve.bind(Promise);" +
 47 |       "function* f(p,a,b){yield p.then(v=>(a=v?a:b)&&'');yield* (a||(_=>[]))();};";
 48 |     var streamToGenerator;
 49 |     if (c.node) {
 50 |       streamToGenerator = 
 51 | `var s=r=>{
 52 | var d=!1,l,b=[];
 53 | r.then(r=>{
 54 | r.on('end',_=>{d=!0;l&&l()});
 55 | r.on('data',c=>(l&&(v=>{var t=l;l=null;t(v)})||(d=>b.push(d)))(c));
 56 | });
 57 | return i={next:_=>({done:b.length===0&&d,value:P(b.shift()||new Promise(r=>l=r))}),[Symbol.iterator]:_=>i};};`;
 58 |     } else {
 59 |       streamToGenerator = 
 60 | `var s=r=>{
 61 | r=r.then(l=>l.getReader());
 62 | var d=!1;
 63 | return i={next:_=>({done:d,value:r.then(r=>r.read()).then(v=>{d=v.done;return P(v.value)})}),[Symbol.iterator]:_=>i};
 64 | };`;
 65 |     }
 66 | 
 67 |     tmpl = helpers + streamToGenerator +
 68 |         "var g=function*(){yield P('"
 69 |         + tmpl
 70 |             .replace(/'|\\/g, "\\$&")
 71 |             .replace(c.interpolate, function(_, code) {
 72 |               return "');yield P(" + unescape(code) + ");yield P('";
 73 |             })
 74 |             .replace(c.conditional, function(_, els, code) {
 75 |               if (code && !els) { // {{?}} === if
 76 |                 return "');yield* f(P(" + unescape(code) + "),function*(){yield P('"
 77 |               } else if (!code && els) { // {{??}} === else
 78 |                 return "')},function*(){yield P('";
 79 |               } else { // {{?}} === "endif"
 80 |                 return "')});yield P('";
 81 |               }
 82 |             })
 83 |             .replace(c.stream, function(_, code) {
 84 |               return "');yield* s(P(" + unescape(code) + "));yield P('";
 85 |             })
 86 |             .replace(c.evaluate, function(_, code) {
 87 |               return "');" + unescape(code) + ";yield P('";
 88 |             })
 89 |             .replace(/\n/g, "\\n")
 90 |             .replace(/\t/g, '\\t')
 91 |             .replace(/\r/g, "\\r")
 92 |          + "');}();";
 93 | 
 94 |     if(c.node) {
 95 |       tmpl +=
 96 | `var r = new R({read:function f() {
 97 | var d=g.next();
 98 | if(d.done) return r.push(null);
 99 | P(d.value).then(v=>{if(v)return r.push(Buffer.from(v));else f()});
100 | }});
101 | return r;
102 | `;
103 |     } else {
104 |       tmpl +=
105 | `var e=new TextEncoder();
106 | return new ReadableStream({
107 | pull: c=>{
108 | var v=g.next();
109 | if(v.done)return c.close();
110 | v.value.then(d=>{
111 | if(typeof(d)=="string")d=e.encode(d);
112 | d&&c.enqueue(d);
113 | });
114 | return v.value;
115 | }});`;
116 |     }
117 | 
118 |     try {
119 |       if (c.noEval) return tmpl;
120 |       if (c.node) {
121 |         const f = new Function(c.varname, 'R', tmpl); 
122 |         return it => f(it, require('stream').Readable);
123 |       } 
124 |       return new Function(c.varname, tmpl);
125 |     } catch (e) {
126 |       console.log("Could not create a template function: " + tmpl);
127 |       throw e;
128 |     }
129 |   };
130 | }));
131 | 


--------------------------------------------------------------------------------
/streaming-dot.min.js:
--------------------------------------------------------------------------------
 1 | (function(a,b){'object'==typeof exports&&'string'!=typeof exports.nodeName?b(exports):b(a.doT={})})(this,function(a){'use strict';function b(d){return d.replace(/\\('|\\)/g,'$1').replace(/[\r\t\n]/g,' ')}Object.assign(a,{version:'1.1.1',templateSettings:{evaluate:/\{\{(([^\}]+|\\.)+)\}\}/g,interpolate:/\{\{=\s*([^\}]+)\}\}/g,stream:/\{\{~\s*([^\}]+)\}\}/g,conditional:/\{\{\?(\?)?\s*([^\}]*)?\}\}/g,node:'object'==typeof process,varname:'it'}}),a.compile=function(d,g){g=Object.assign({},a.templateSettings,g);var h;h=g.node?`var s=(r)=>{
 2 | var d=!1,l,b=[];
 3 | r.then(r=>{
 4 | r.on('end',_=>{d=!0;l&&l()});
 5 | r.on('data',c=>(l&&(v=>{var t=l;l=null;t(v)})||(d=>b.push(d)))(c));
 6 | });
 7 | return i={next:_=>({done:b.length===0&&d,value:P(b.shift()||new Promise(r=>l=r))}),[Symbol.iterator]:_=>i};};`:`var s = (r) => {
 8 | r=r.then(r=>r.getReader());
 9 | var d=!1;
10 | return i={next:_=>({done:d,value:r.then(r=>r.read()).then(v=>{d=v.done;return P(v.value)})}),[Symbol.iterator]:_=>i};
11 | };`,d='var P=Promise.resolve.bind(Promise);function* f(p,a,b){yield p.then(v=>(a=v?a:b)&&\'\');yield* (a||(_=>[]))();}'+h+'var g=function*(){yield P(\''+d.replace(/'|\\/g,'\\$&').replace(g.interpolate,function(i,j){return'\');yield P('+b(j)+');yield P(\''}).replace(g.conditional,function(i,j,k){if(k&&!j)// {{?}} === if
12 | return'\');yield* f(P('+b(k)+'),function*(){yield P(\'';return!k&&j?'\')},function*(){yield P(\'':'\')});yield P(\'';// {{?}} === "endif"
13 | }).replace(g.stream,function(i,j){return'\');yield* s(P('+b(j)+'));yield P(\''}).replace(g.evaluate,function(i,j){return'\');'+b(j)+';yield P(\''}).replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\r/g,'\\r')+'\');}();',d+=g.node?`var r = new R({read:function f() {
14 | var d=g.next();
15 | if(d.done) return r.push(null);
16 | P(d.value).then(v=>{if(v)return r.push(Buffer.from(v));else f()});
17 | }});
18 | return r;
19 | `:`var e=new TextEncoder();
20 | return new ReadableStream({
21 | pull: c=>{
22 | var v=g.next();
23 | if(v.done)return c.close();
24 | v.value.then(d=>{
25 | if(typeof(d)=="string")d=e.encode(d);
26 | d&&c.enqueue(d);
27 | });
28 | return v.value;
29 | }});`;try{if(g.noEval)return d;if(g.node){const i=new Function(g.varname,'R',d);return j=>i(j,require('stream').Readable)}return new Function(g.varname,d)}catch(i){throw console.log('Could not create a template function: '+d),i}}});
30 | 


--------------------------------------------------------------------------------
/test/streaming-dot.test.js:
--------------------------------------------------------------------------------
  1 | (function (root) {
  2 |   'use strict';
  3 | 
  4 |   const isNode = typeof(process) === 'object';
  5 |   const doT = root.doT || require('../streaming-dot.js');
  6 |   const expect = root.chai && root.chai.expect || require('chai').expect;
  7 | 
  8 |   // Defined below depending on `isNode`
  9 |   let readStream, readStreamAsString, stringToStream;
 10 | 
 11 |   describe('doT', function () {
 12 |     it('compiles a template to functions', function () {
 13 |       const template = doT.compile('lol');
 14 |       return readStreamAsString(template({})) 
 15 |         .then(s => expect(s).to.equal('lol'));
 16 |     });
 17 | 
 18 |     it('compiles a template to JavaScript', function () {
 19 |       const template = doT.compile('lol', {noEval: true});
 20 |       expect(typeof(template)).to.equal('string');
 21 |     });
 22 | 
 23 |     it('inserts values correctly', function () {
 24 |       const template = doT.compile('{{=it.syncThing}}_placeholder_{{=it.asyncThing}}');
 25 |       return readStreamAsString(template({
 26 |         syncThing: 'test',
 27 |         asyncThing: new Promise(resolve => setTimeout(_ => resolve('async'), 10))
 28 |       })).then(s => expect(s).to.equal('test_placeholder_async'));
 29 |     });
 30 | 
 31 |     it('inserts literals correctly', function () {
 32 |       const template = doT.compile('{{=""+(1+1)}}_placeholder_{{=""+(5*5)}}');
 33 |       return readStreamAsString(template({
 34 |         syncThing: 'test',
 35 |         asyncThing: new Promise(resolve => setTimeout(_ => resolve('async'), 10))
 36 |       })).then(s => expect(s).to.equal('2_placeholder_25'));
 37 |     });
 38 | 
 39 | 
 40 |     it('inserts streams correctly', function () {
 41 |       const template = doT.compile('{{~it.input1}}_placeholder_{{~it.input2}}');
 42 |       return readStreamAsString(template({
 43 |         input1: stringToStream('stream1'),
 44 |         input2: stringToStream('stream2')
 45 |       })).then(s => expect(s).to.equal('stream1_placeholder_stream2'));
 46 |     });
 47 | 
 48 |     it('handles conditionals correctly', function () {
 49 |       const template = doT.compile('{{?it.c1}}C1{{?}}_placeholder_{{?it.c2}}C2{{?}}_placeholder_{{?it.c3}}C3T{{??}}C3F{{?}}');
 50 |       return readStreamAsString(template({
 51 |         c1: false,
 52 |         c2: true,
 53 |         c3: false
 54 |       })).then(s => expect(s).to.equal('_placeholder_C2_placeholder_C3F'));
 55 |     });
 56 | 
 57 |     it('handles values in conditionals', function () {
 58 |       const template = doT.compile('{{?it.c1}}{{=it.v1}}{{?}}_placeholder_{{?it.c2}}NO{{??}}{{=it.v2}}{{?}}');
 59 |       return readStreamAsString(template({
 60 |         c1: true,
 61 |         c2: false,
 62 |         v1: "value1",
 63 |         v2: "value2"
 64 |       })).then(s => expect(s).to.equal('value1_placeholder_value2'));
 65 |     });
 66 | 
 67 |     // Node-specific tests
 68 |     if(isNode) {
 69 |       describe('in node', function () {
 70 |         it('handles waiting correctly', function () {
 71 |           const template = doT.compile('{{~it.r}}');
 72 |           let chunks = [Buffer.from('a'), Buffer.from('b')];
 73 |           let r = new require('stream').Readable({
 74 |             read: function () {
 75 |               let chunk = chunks.shift();
 76 |               if (!chunk) this.push(null);
 77 |               setTimeout(_ => this.push(chunk), 10);
 78 |             }
 79 |           });
 80 |           return readStreamAsString(template({r: r}))
 81 |             .then(s => expect(s).to.equal('ab'));
 82 |         });
 83 |       });
 84 |     }
 85 |   });
 86 | 
 87 |   if (isNode) {
 88 |     readStream = function readStreamNode(s) {
 89 |       return new Promise(resolve => {
 90 |         var buffers = [];
 91 |         s.on('data', chunk => buffers.push(chunk));
 92 |         s.on('end', _ => resolve(Buffer.concat(buffers)));
 93 |       });
 94 |     }
 95 | 
 96 |     readStreamAsString = function readStreamAsStringNode(s) {
 97 |       return readStream(s)
 98 |         .then(buffer => buffer.toString());
 99 |     }
100 | 
101 |     stringToStream = function stringToStreamWeb(s) {
102 |       return new require('stream').Readable({
103 |         read: function() {
104 |           this.push(Buffer.from(s.substr(0, s.length/2)));
105 |           this.push(Buffer.from(s.substr(s.length/2)));
106 |           this.push(null);
107 |         }
108 |       });
109 |     };
110 |   } else {
111 |     readStream = function readStreamWeb(s) {
112 |       let buffer = [];
113 |       const reader = s.getReader();
114 |       return reader.read().then(function process(v) {
115 |         if (v.done) return new Uint8Array(buffer);
116 |         buffer = [...buffer, ...v.value];
117 |         return reader.read().then(process);
118 |       });
119 |     };
120 | 
121 |     readStreamAsString = function readStreamAsStringWeb(s) {
122 |       return readStream(s)
123 |         .then(buffer => new TextDecoder().decode(buffer));
124 |     };
125 | 
126 |     stringToStream = function stringToStreamWeb(s) {
127 |       return new Response(s).body; // lol
128 |     };
129 |   }
130 | 
131 | 
132 | })(this);


--------------------------------------------------------------------------------
/update-version.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | 
3 | VERSION=$(cat package.json | grep version | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+")
4 | sed -i '' "s/^Version.*$/Version $VERSION/" README.md
5 | sed -i '' "s/version: ".*",$/version: \"$VERSION\",/" streaming-dot.js 
6 | npm run build
7 | git add README.md streaming-dot.js streaming-dot.min.js
8 | 


--------------------------------------------------------------------------------