ejs.js 27 KB

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