second
[josuexyz/.git] / node_modules / ejs / lib / ejs.js
1 /*
2  * EJS Embedded JavaScript templates
3  * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
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
19 'use strict';
20
21 /**
22  * @file Embedded JavaScript templating engine. {@link http://ejs.co}
23  * @author Matthew Eernisse <mde@fleegix.org>
24  * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
25  * @project EJS
26  * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
27  */
28
29 /**
30  * EJS internal functions.
31  *
32  * Technically this "module" lies in the same file as {@link module:ejs}, for
33  * the sake of organization all the private functions re grouped into this
34  * module.
35  *
36  * @module ejs-internal
37  * @private
38  */
39
40 /**
41  * Embedded JavaScript templating engine.
42  *
43  * @module ejs
44  * @public
45  */
46
47 var fs = require('fs');
48 var path = require('path');
49 var utils = require('./utils');
50
51 var scopeOptionWarned = false;
52 var _VERSION_STRING = require('../package.json').version;
53 var _DEFAULT_OPEN_DELIMITER = '<';
54 var _DEFAULT_CLOSE_DELIMITER = '>';
55 var _DEFAULT_DELIMITER = '%';
56 var _DEFAULT_LOCALS_NAME = 'locals';
57 var _NAME = 'ejs';
58 var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
59 var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
60   'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
61 // We don't allow 'cache' option to be passed in the data obj for
62 // the normal `render` call, but this is where Express 2 & 3 put it
63 // so we make an exception for `renderFile`
64 var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
65 var _BOM = /^\uFEFF/;
66
67 /**
68  * EJS template function cache. This can be a LRU object from lru-cache NPM
69  * module. By default, it is {@link module:utils.cache}, a simple in-process
70  * cache that grows continuously.
71  *
72  * @type {Cache}
73  */
74
75 exports.cache = utils.cache;
76
77 /**
78  * Custom file loader. Useful for template preprocessing or restricting access
79  * to a certain part of the filesystem.
80  *
81  * @type {fileLoader}
82  */
83
84 exports.fileLoader = fs.readFileSync;
85
86 /**
87  * Name of the object containing the locals.
88  *
89  * This variable is overridden by {@link Options}`.localsName` if it is not
90  * `undefined`.
91  *
92  * @type {String}
93  * @public
94  */
95
96 exports.localsName = _DEFAULT_LOCALS_NAME;
97
98 /**
99  * Promise implementation -- defaults to the native implementation if available
100  * This is mostly just for testability
101  *
102  * @type {Function}
103  * @public
104  */
105
106 exports.promiseImpl = (new Function('return this;'))().Promise;
107
108 /**
109  * Get the path to the included file from the parent file path and the
110  * specified path.
111  *
112  * @param {String}  name     specified path
113  * @param {String}  filename parent file path
114  * @param {Boolean} isDir    parent file path whether is directory
115  * @return {String}
116  */
117 exports.resolveInclude = function(name, filename, isDir) {
118   var dirname = path.dirname;
119   var extname = path.extname;
120   var resolve = path.resolve;
121   var includePath = resolve(isDir ? filename : dirname(filename), name);
122   var ext = extname(name);
123   if (!ext) {
124     includePath += '.ejs';
125   }
126   return includePath;
127 };
128
129 /**
130  * Get the path to the included file by Options
131  *
132  * @param  {String}  path    specified path
133  * @param  {Options} options compilation options
134  * @return {String}
135  */
136 function getIncludePath(path, options) {
137   var includePath;
138   var filePath;
139   var views = options.views;
140   var match = /^[A-Za-z]+:\\|^\//.exec(path);
141
142   // Abs path
143   if (match && match.length) {
144     includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true);
145   }
146   // Relative paths
147   else {
148     // Look relative to a passed filename first
149     if (options.filename) {
150       filePath = exports.resolveInclude(path, options.filename);
151       if (fs.existsSync(filePath)) {
152         includePath = filePath;
153       }
154     }
155     // Then look in any views directories
156     if (!includePath) {
157       if (Array.isArray(views) && views.some(function (v) {
158         filePath = exports.resolveInclude(path, v, true);
159         return fs.existsSync(filePath);
160       })) {
161         includePath = filePath;
162       }
163     }
164     if (!includePath) {
165       throw new Error('Could not find the include file "' +
166           options.escapeFunction(path) + '"');
167     }
168   }
169   return includePath;
170 }
171
172 /**
173  * Get the template from a string or a file, either compiled on-the-fly or
174  * read from cache (if enabled), and cache the template if needed.
175  *
176  * If `template` is not set, the file specified in `options.filename` will be
177  * read.
178  *
179  * If `options.cache` is true, this function reads the file from
180  * `options.filename` so it must be set prior to calling this function.
181  *
182  * @memberof module:ejs-internal
183  * @param {Options} options   compilation options
184  * @param {String} [template] template source
185  * @return {(TemplateFunction|ClientFunction)}
186  * Depending on the value of `options.client`, either type might be returned.
187  * @static
188  */
189
190 function handleCache(options, template) {
191   var func;
192   var filename = options.filename;
193   var hasTemplate = arguments.length > 1;
194
195   if (options.cache) {
196     if (!filename) {
197       throw new Error('cache option requires a filename');
198     }
199     func = exports.cache.get(filename);
200     if (func) {
201       return func;
202     }
203     if (!hasTemplate) {
204       template = fileLoader(filename).toString().replace(_BOM, '');
205     }
206   }
207   else if (!hasTemplate) {
208     // istanbul ignore if: should not happen at all
209     if (!filename) {
210       throw new Error('Internal EJS error: no file name or template '
211                     + 'provided');
212     }
213     template = fileLoader(filename).toString().replace(_BOM, '');
214   }
215   func = exports.compile(template, options);
216   if (options.cache) {
217     exports.cache.set(filename, func);
218   }
219   return func;
220 }
221
222 /**
223  * Try calling handleCache with the given options and data and call the
224  * callback with the result. If an error occurs, call the callback with
225  * the error. Used by renderFile().
226  *
227  * @memberof module:ejs-internal
228  * @param {Options} options    compilation options
229  * @param {Object} data        template data
230  * @param {RenderFileCallback} cb callback
231  * @static
232  */
233
234 function tryHandleCache(options, data, cb) {
235   var result;
236   if (!cb) {
237     if (typeof exports.promiseImpl == 'function') {
238       return new exports.promiseImpl(function (resolve, reject) {
239         try {
240           result = handleCache(options)(data);
241           resolve(result);
242         }
243         catch (err) {
244           reject(err);
245         }
246       });
247     }
248     else {
249       throw new Error('Please provide a callback function');
250     }
251   }
252   else {
253     try {
254       result = handleCache(options)(data);
255     }
256     catch (err) {
257       return cb(err);
258     }
259
260     cb(null, result);
261   }
262 }
263
264 /**
265  * fileLoader is independent
266  *
267  * @param {String} filePath ejs file path.
268  * @return {String} The contents of the specified file.
269  * @static
270  */
271
272 function fileLoader(filePath){
273   return exports.fileLoader(filePath);
274 }
275
276 /**
277  * Get the template function.
278  *
279  * If `options.cache` is `true`, then the template is cached.
280  *
281  * @memberof module:ejs-internal
282  * @param {String}  path    path for the specified file
283  * @param {Options} options compilation options
284  * @return {(TemplateFunction|ClientFunction)}
285  * Depending on the value of `options.client`, either type might be returned
286  * @static
287  */
288
289 function includeFile(path, options) {
290   var opts = utils.shallowCopy({}, options);
291   opts.filename = getIncludePath(path, opts);
292   return handleCache(opts);
293 }
294
295 /**
296  * Get the JavaScript source of an included file.
297  *
298  * @memberof module:ejs-internal
299  * @param {String}  path    path for the specified file
300  * @param {Options} options compilation options
301  * @return {Object}
302  * @static
303  */
304
305 function includeSource(path, options) {
306   var opts = utils.shallowCopy({}, options);
307   var includePath;
308   var template;
309   includePath = getIncludePath(path, opts);
310   template = fileLoader(includePath).toString().replace(_BOM, '');
311   opts.filename = includePath;
312   var templ = new Template(template, opts);
313   templ.generateSource();
314   return {
315     source: templ.source,
316     filename: includePath,
317     template: template
318   };
319 }
320
321 /**
322  * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
323  * `lineno`.
324  *
325  * @implements RethrowCallback
326  * @memberof module:ejs-internal
327  * @param {Error}  err      Error object
328  * @param {String} str      EJS source
329  * @param {String} filename file name of the EJS file
330  * @param {String} lineno   line number of the error
331  * @static
332  */
333
334 function rethrow(err, str, flnm, lineno, esc){
335   var lines = str.split('\n');
336   var start = Math.max(lineno - 3, 0);
337   var end = Math.min(lines.length, lineno + 3);
338   var filename = esc(flnm); // eslint-disable-line
339   // Error context
340   var context = lines.slice(start, end).map(function (line, i){
341     var curr = i + start + 1;
342     return (curr == lineno ? ' >> ' : '    ')
343       + curr
344       + '| '
345       + line;
346   }).join('\n');
347
348   // Alter exception message
349   err.path = filename;
350   err.message = (filename || 'ejs') + ':'
351     + lineno + '\n'
352     + context + '\n\n'
353     + err.message;
354
355   throw err;
356 }
357
358 function stripSemi(str){
359   return str.replace(/;(\s*$)/, '$1');
360 }
361
362 /**
363  * Compile the given `str` of ejs into a template function.
364  *
365  * @param {String}  template EJS template
366  *
367  * @param {Options} opts     compilation options
368  *
369  * @return {(TemplateFunction|ClientFunction)}
370  * Depending on the value of `opts.client`, either type might be returned.
371  * Note that the return type of the function also depends on the value of `opts.async`.
372  * @public
373  */
374
375 exports.compile = function compile(template, opts) {
376   var templ;
377
378   // v1 compat
379   // 'scope' is 'context'
380   // FIXME: Remove this in a future version
381   if (opts && opts.scope) {
382     if (!scopeOptionWarned){
383       console.warn('`scope` option is deprecated and will be removed in EJS 3');
384       scopeOptionWarned = true;
385     }
386     if (!opts.context) {
387       opts.context = opts.scope;
388     }
389     delete opts.scope;
390   }
391   templ = new Template(template, opts);
392   return templ.compile();
393 };
394
395 /**
396  * Render the given `template` of ejs.
397  *
398  * If you would like to include options but not data, you need to explicitly
399  * call this function with `data` being an empty object or `null`.
400  *
401  * @param {String}   template EJS template
402  * @param {Object}  [data={}] template data
403  * @param {Options} [opts={}] compilation and rendering options
404  * @return {(String|Promise<String>)}
405  * Return value type depends on `opts.async`.
406  * @public
407  */
408
409 exports.render = function (template, d, o) {
410   var data = d || {};
411   var opts = o || {};
412
413   // No options object -- if there are optiony names
414   // in the data, copy them to options
415   if (arguments.length == 2) {
416     utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
417   }
418
419   return handleCache(opts, template)(data);
420 };
421
422 /**
423  * Render an EJS file at the given `path` and callback `cb(err, str)`.
424  *
425  * If you would like to include options but not data, you need to explicitly
426  * call this function with `data` being an empty object or `null`.
427  *
428  * @param {String}             path     path to the EJS file
429  * @param {Object}            [data={}] template data
430  * @param {Options}           [opts={}] compilation and rendering options
431  * @param {RenderFileCallback} cb callback
432  * @public
433  */
434
435 exports.renderFile = function () {
436   var args = Array.prototype.slice.call(arguments);
437   var filename = args.shift();
438   var cb;
439   var opts = {filename: filename};
440   var data;
441   var viewOpts;
442
443   // Do we have a callback?
444   if (typeof arguments[arguments.length - 1] == 'function') {
445     cb = args.pop();
446   }
447   // Do we have data/opts?
448   if (args.length) {
449     // Should always have data obj
450     data = args.shift();
451     // Normal passed opts (data obj + opts obj)
452     if (args.length) {
453       // Use shallowCopy so we don't pollute passed in opts obj with new vals
454       utils.shallowCopy(opts, args.pop());
455     }
456     // Special casing for Express (settings + opts-in-data)
457     else {
458       // Express 3 and 4
459       if (data.settings) {
460         // Pull a few things from known locations
461         if (data.settings.views) {
462           opts.views = data.settings.views;
463         }
464         if (data.settings['view cache']) {
465           opts.cache = true;
466         }
467         // Undocumented after Express 2, but still usable, esp. for
468         // items that are unsafe to be passed along with data, like `root`
469         viewOpts = data.settings['view options'];
470         if (viewOpts) {
471           utils.shallowCopy(opts, viewOpts);
472         }
473       }
474       // Express 2 and lower, values set in app.locals, or people who just
475       // want to pass options in their data. NOTE: These values will override
476       // anything previously set in settings  or settings['view options']
477       utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
478     }
479     opts.filename = filename;
480   }
481   else {
482     data = {};
483   }
484
485   return tryHandleCache(opts, data, cb);
486 };
487
488 /**
489  * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
490  * @public
491  */
492
493 /**
494  * EJS template class
495  * @public
496  */
497 exports.Template = Template;
498
499 exports.clearCache = function () {
500   exports.cache.reset();
501 };
502
503 function Template(text, opts) {
504   opts = opts || {};
505   var options = {};
506   this.templateText = text;
507   this.mode = null;
508   this.truncate = false;
509   this.currentLine = 1;
510   this.source = '';
511   this.dependencies = [];
512   options.client = opts.client || false;
513   options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
514   options.compileDebug = opts.compileDebug !== false;
515   options.debug = !!opts.debug;
516   options.filename = opts.filename;
517   options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
518   options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
519   options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
520   options.strict = opts.strict || false;
521   options.context = opts.context;
522   options.cache = opts.cache || false;
523   options.rmWhitespace = opts.rmWhitespace;
524   options.root = opts.root;
525   options.outputFunctionName = opts.outputFunctionName;
526   options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
527   options.views = opts.views;
528   options.async = opts.async;
529
530   if (options.strict) {
531     options._with = false;
532   }
533   else {
534     options._with = typeof opts._with != 'undefined' ? opts._with : true;
535   }
536
537   this.opts = options;
538
539   this.regex = this.createRegex();
540 }
541
542 Template.modes = {
543   EVAL: 'eval',
544   ESCAPED: 'escaped',
545   RAW: 'raw',
546   COMMENT: 'comment',
547   LITERAL: 'literal'
548 };
549
550 Template.prototype = {
551   createRegex: function () {
552     var str = _REGEX_STRING;
553     var delim = utils.escapeRegExpChars(this.opts.delimiter);
554     var open = utils.escapeRegExpChars(this.opts.openDelimiter);
555     var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
556     str = str.replace(/%/g, delim)
557       .replace(/</g, open)
558       .replace(/>/g, close);
559     return new RegExp(str);
560   },
561
562   compile: function () {
563     var src;
564     var fn;
565     var opts = this.opts;
566     var prepended = '';
567     var appended = '';
568     var escapeFn = opts.escapeFunction;
569     var ctor;
570
571     if (!this.source) {
572       this.generateSource();
573       prepended += '  var __output = [], __append = __output.push.bind(__output);' + '\n';
574       if (opts.outputFunctionName) {
575         prepended += '  var ' + opts.outputFunctionName + ' = __append;' + '\n';
576       }
577       if (opts._with !== false) {
578         prepended +=  '  with (' + opts.localsName + ' || {}) {' + '\n';
579         appended += '  }' + '\n';
580       }
581       appended += '  return __output.join("");' + '\n';
582       this.source = prepended + this.source + appended;
583     }
584
585     if (opts.compileDebug) {
586       src = 'var __line = 1' + '\n'
587         + '  , __lines = ' + JSON.stringify(this.templateText) + '\n'
588         + '  , __filename = ' + (opts.filename ?
589         JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
590         + 'try {' + '\n'
591         + this.source
592         + '} catch (e) {' + '\n'
593         + '  rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
594         + '}' + '\n';
595     }
596     else {
597       src = this.source;
598     }
599
600     if (opts.client) {
601       src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
602       if (opts.compileDebug) {
603         src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
604       }
605     }
606
607     if (opts.strict) {
608       src = '"use strict";\n' + src;
609     }
610     if (opts.debug) {
611       console.log(src);
612     }
613
614     try {
615       if (opts.async) {
616         // Have to use generated function for this, since in envs without support,
617         // it breaks in parsing
618         try {
619           ctor = (new Function('return (async function(){}).constructor;'))();
620         }
621         catch(e) {
622           if (e instanceof SyntaxError) {
623             throw new Error('This environment does not support async/await');
624           }
625           else {
626             throw e;
627           }
628         }
629       }
630       else {
631         ctor = Function;
632       }
633       fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
634     }
635     catch(e) {
636       // istanbul ignore else
637       if (e instanceof SyntaxError) {
638         if (opts.filename) {
639           e.message += ' in ' + opts.filename;
640         }
641         e.message += ' while compiling ejs\n\n';
642         e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
643         e.message += 'https://github.com/RyanZim/EJS-Lint';
644         if (!e.async) {
645           e.message += '\n';
646           e.message += 'Or, if you meant to create an async function, pass async: true as an option.';
647         }
648       }
649       throw e;
650     }
651
652     if (opts.client) {
653       fn.dependencies = this.dependencies;
654       return fn;
655     }
656
657     // Return a callable function which will execute the function
658     // created by the source-code, with the passed data as locals
659     // Adds a local `include` function which allows full recursive include
660     var returnedFn = function (data) {
661       var include = function (path, includeData) {
662         var d = utils.shallowCopy({}, data);
663         if (includeData) {
664           d = utils.shallowCopy(d, includeData);
665         }
666         return includeFile(path, opts)(d);
667       };
668       return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
669     };
670     returnedFn.dependencies = this.dependencies;
671     return returnedFn;
672   },
673
674   generateSource: function () {
675     var opts = this.opts;
676
677     if (opts.rmWhitespace) {
678       // Have to use two separate replace here as `^` and `$` operators don't
679       // work well with `\r` and empty lines don't work well with the `m` flag.
680       this.templateText =
681         this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
682     }
683
684     // Slurp spaces and tabs before <%_ and after _%>
685     this.templateText =
686       this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
687
688     var self = this;
689     var matches = this.parseTemplateText();
690     var d = this.opts.delimiter;
691     var o = this.opts.openDelimiter;
692     var c = this.opts.closeDelimiter;
693
694     if (matches && matches.length) {
695       matches.forEach(function (line, index) {
696         var opening;
697         var closing;
698         var include;
699         var includeOpts;
700         var includeObj;
701         var includeSrc;
702         // If this is an opening tag, check for closing tags
703         // FIXME: May end up with some false positives here
704         // Better to store modes as k/v with openDelimiter + delimiter as key
705         // Then this can simply check against the map
706         if ( line.indexOf(o + d) === 0        // If it is a tag
707           && line.indexOf(o + d + d) !== 0) { // and is not escaped
708           closing = matches[index + 2];
709           if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
710             throw new Error('Could not find matching close tag for "' + line + '".');
711           }
712         }
713         // HACK: backward-compat `include` preprocessor directives
714         if ((include = line.match(/^\s*include\s+(\S+)/))) {
715           opening = matches[index - 1];
716           // Must be in EVAL or RAW mode
717           if (opening && (opening == o + d || opening == o + d + '-' || opening == o + d + '_')) {
718             includeOpts = utils.shallowCopy({}, self.opts);
719             includeObj = includeSource(include[1], includeOpts);
720             if (self.opts.compileDebug) {
721               includeSrc =
722                   '    ; (function(){' + '\n'
723                   + '      var __line = 1' + '\n'
724                   + '      , __lines = ' + JSON.stringify(includeObj.template) + '\n'
725                   + '      , __filename = ' + JSON.stringify(includeObj.filename) + ';' + '\n'
726                   + '      try {' + '\n'
727                   + includeObj.source
728                   + '      } catch (e) {' + '\n'
729                   + '        rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
730                   + '      }' + '\n'
731                   + '    ; }).call(this)' + '\n';
732             }else{
733               includeSrc = '    ; (function(){' + '\n' + includeObj.source +
734                   '    ; }).call(this)' + '\n';
735             }
736             self.source += includeSrc;
737             self.dependencies.push(exports.resolveInclude(include[1],
738               includeOpts.filename));
739             return;
740           }
741         }
742         self.scanLine(line);
743       });
744     }
745
746   },
747
748   parseTemplateText: function () {
749     var str = this.templateText;
750     var pat = this.regex;
751     var result = pat.exec(str);
752     var arr = [];
753     var firstPos;
754
755     while (result) {
756       firstPos = result.index;
757
758       if (firstPos !== 0) {
759         arr.push(str.substring(0, firstPos));
760         str = str.slice(firstPos);
761       }
762
763       arr.push(result[0]);
764       str = str.slice(result[0].length);
765       result = pat.exec(str);
766     }
767
768     if (str) {
769       arr.push(str);
770     }
771
772     return arr;
773   },
774
775   _addOutput: function (line) {
776     if (this.truncate) {
777       // Only replace single leading linebreak in the line after
778       // -%> tag -- this is the single, trailing linebreak
779       // after the tag that the truncation mode replaces
780       // Handle Win / Unix / old Mac linebreaks -- do the \r\n
781       // combo first in the regex-or
782       line = line.replace(/^(?:\r\n|\r|\n)/, '');
783       this.truncate = false;
784     }
785     if (!line) {
786       return line;
787     }
788
789     // Preserve literal slashes
790     line = line.replace(/\\/g, '\\\\');
791
792     // Convert linebreaks
793     line = line.replace(/\n/g, '\\n');
794     line = line.replace(/\r/g, '\\r');
795
796     // Escape double-quotes
797     // - this will be the delimiter during execution
798     line = line.replace(/"/g, '\\"');
799     this.source += '    ; __append("' + line + '")' + '\n';
800   },
801
802   scanLine: function (line) {
803     var self = this;
804     var d = this.opts.delimiter;
805     var o = this.opts.openDelimiter;
806     var c = this.opts.closeDelimiter;
807     var newLineCount = 0;
808
809     newLineCount = (line.split('\n').length - 1);
810
811     switch (line) {
812     case o + d:
813     case o + d + '_':
814       this.mode = Template.modes.EVAL;
815       break;
816     case o + d + '=':
817       this.mode = Template.modes.ESCAPED;
818       break;
819     case o + d + '-':
820       this.mode = Template.modes.RAW;
821       break;
822     case o + d + '#':
823       this.mode = Template.modes.COMMENT;
824       break;
825     case o + d + d:
826       this.mode = Template.modes.LITERAL;
827       this.source += '    ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
828       break;
829     case d + d + c:
830       this.mode = Template.modes.LITERAL;
831       this.source += '    ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
832       break;
833     case d + c:
834     case '-' + d + c:
835     case '_' + d + c:
836       if (this.mode == Template.modes.LITERAL) {
837         this._addOutput(line);
838       }
839
840       this.mode = null;
841       this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
842       break;
843     default:
844       // In script mode, depends on type of tag
845       if (this.mode) {
846         // If '//' is found without a line break, add a line break.
847         switch (this.mode) {
848         case Template.modes.EVAL:
849         case Template.modes.ESCAPED:
850         case Template.modes.RAW:
851           if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
852             line += '\n';
853           }
854         }
855         switch (this.mode) {
856         // Just executing code
857         case Template.modes.EVAL:
858           this.source += '    ; ' + line + '\n';
859           break;
860           // Exec, esc, and output
861         case Template.modes.ESCAPED:
862           this.source += '    ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
863           break;
864           // Exec and output
865         case Template.modes.RAW:
866           this.source += '    ; __append(' + stripSemi(line) + ')' + '\n';
867           break;
868         case Template.modes.COMMENT:
869           // Do nothing
870           break;
871           // Literal <%% mode, append as raw output
872         case Template.modes.LITERAL:
873           this._addOutput(line);
874           break;
875         }
876       }
877       // In string mode, just add the output
878       else {
879         this._addOutput(line);
880       }
881     }
882
883     if (self.opts.compileDebug && newLineCount) {
884       this.currentLine += newLineCount;
885       this.source += '    ; __line = ' + this.currentLine + '\n';
886     }
887   }
888 };
889
890 /**
891  * Escape characters reserved in XML.
892  *
893  * This is simply an export of {@link module:utils.escapeXML}.
894  *
895  * If `markup` is `undefined` or `null`, the empty string is returned.
896  *
897  * @param {String} markup Input string
898  * @return {String} Escaped string
899  * @public
900  * @func
901  * */
902 exports.escapeXML = utils.escapeXML;
903
904 /**
905  * Express.js support.
906  *
907  * This is an alias for {@link module:ejs.renderFile}, in order to support
908  * Express.js out-of-the-box.
909  *
910  * @func
911  */
912
913 exports.__express = exports.renderFile;
914
915 // Add require support
916 /* istanbul ignore else */
917 if (require.extensions) {
918   require.extensions['.ejs'] = function (module, flnm) {
919     var filename = flnm || /* istanbul ignore next */ module.filename;
920     var options = {
921       filename: filename,
922       client: true
923     };
924     var template = fileLoader(filename).toString();
925     var fn = exports.compile(template, options);
926     module._compile('module.exports = ' + fn.toString() + ';', filename);
927   };
928 }
929
930 /**
931  * Version of EJS.
932  *
933  * @readonly
934  * @type {String}
935  * @public
936  */
937
938 exports.VERSION = _VERSION_STRING;
939
940 /**
941  * Name for detection of EJS.
942  *
943  * @readonly
944  * @type {String}
945  * @public
946  */
947
948 exports.name = _NAME;
949
950 /* istanbul ignore if */
951 if (typeof window != 'undefined') {
952   window.ejs = exports;
953 }