ejs.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /*
  3. * EJS Embedded JavaScript templates
  4. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. 'use strict';
  20. /**
  21. * @file Embedded JavaScript templating engine. {@link http://ejs.co}
  22. * @author Matthew Eernisse <mde@fleegix.org>
  23. * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
  24. * @project EJS
  25. * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
  26. */
  27. /**
  28. * EJS internal functions.
  29. *
  30. * Technically this "module" lies in the same file as {@link module:ejs}, for
  31. * the sake of organization all the private functions re grouped into this
  32. * module.
  33. *
  34. * @module ejs-internal
  35. * @private
  36. */
  37. /**
  38. * Embedded JavaScript templating engine.
  39. *
  40. * @module ejs
  41. * @public
  42. */
  43. var fs = require('fs');
  44. var path = require('path');
  45. var utils = require('./utils');
  46. var scopeOptionWarned = false;
  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. /**
  62. * EJS template function cache. This can be a LRU object from lru-cache NPM
  63. * module. By default, it is {@link module:utils.cache}, a simple in-process
  64. * cache that grows continuously.
  65. *
  66. * @type {Cache}
  67. */
  68. exports.cache = utils.cache;
  69. /**
  70. * Custom file loader. Useful for template preprocessing or restricting access
  71. * to a certain part of the filesystem.
  72. *
  73. * @type {fileLoader}
  74. */
  75. exports.fileLoader = fs.readFileSync;
  76. /**
  77. * Name of the object containing the locals.
  78. *
  79. * This variable is overridden by {@link Options}`.localsName` if it is not
  80. * `undefined`.
  81. *
  82. * @type {String}
  83. * @public
  84. */
  85. exports.localsName = _DEFAULT_LOCALS_NAME;
  86. /**
  87. * Promise implementation -- defaults to the native implementation if available
  88. * This is mostly just for testability
  89. *
  90. * @type {Function}
  91. * @public
  92. */
  93. exports.promiseImpl = (new Function('return this;'))().Promise;
  94. /**
  95. * Get the path to the included file from the parent file path and the
  96. * specified path.
  97. *
  98. * @param {String} name specified path
  99. * @param {String} filename parent file path
  100. * @param {Boolean} isDir parent file path whether is directory
  101. * @return {String}
  102. */
  103. exports.resolveInclude = function(name, filename, isDir) {
  104. var dirname = path.dirname;
  105. var extname = path.extname;
  106. var resolve = path.resolve;
  107. var includePath = resolve(isDir ? filename : dirname(filename), name);
  108. var ext = extname(name);
  109. if (!ext) {
  110. includePath += '.ejs';
  111. }
  112. return includePath;
  113. };
  114. /**
  115. * Get the path to the included file by Options
  116. *
  117. * @param {String} path specified path
  118. * @param {Options} options compilation options
  119. * @return {String}
  120. */
  121. function getIncludePath(path, options) {
  122. var includePath;
  123. var filePath;
  124. var views = options.views;
  125. var match = /^[A-Za-z]+:\\|^\//.exec(path);
  126. // Abs path
  127. if (match && match.length) {
  128. includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true);
  129. }
  130. // Relative paths
  131. else {
  132. // Look relative to a passed filename first
  133. if (options.filename) {
  134. filePath = exports.resolveInclude(path, options.filename);
  135. if (fs.existsSync(filePath)) {
  136. includePath = filePath;
  137. }
  138. }
  139. // Then look in any views directories
  140. if (!includePath) {
  141. if (Array.isArray(views) && views.some(function (v) {
  142. filePath = exports.resolveInclude(path, v, true);
  143. return fs.existsSync(filePath);
  144. })) {
  145. includePath = filePath;
  146. }
  147. }
  148. if (!includePath) {
  149. throw new Error('Could not find the include file "' +
  150. options.escapeFunction(path) + '"');
  151. }
  152. }
  153. return includePath;
  154. }
  155. /**
  156. * Get the template from a string or a file, either compiled on-the-fly or
  157. * read from cache (if enabled), and cache the template if needed.
  158. *
  159. * If `template` is not set, the file specified in `options.filename` will be
  160. * read.
  161. *
  162. * If `options.cache` is true, this function reads the file from
  163. * `options.filename` so it must be set prior to calling this function.
  164. *
  165. * @memberof module:ejs-internal
  166. * @param {Options} options compilation options
  167. * @param {String} [template] template source
  168. * @return {(TemplateFunction|ClientFunction)}
  169. * Depending on the value of `options.client`, either type might be returned.
  170. * @static
  171. */
  172. function handleCache(options, template) {
  173. var func;
  174. var filename = options.filename;
  175. var hasTemplate = arguments.length > 1;
  176. if (options.cache) {
  177. if (!filename) {
  178. throw new Error('cache option requires a filename');
  179. }
  180. func = exports.cache.get(filename);
  181. if (func) {
  182. return func;
  183. }
  184. if (!hasTemplate) {
  185. template = fileLoader(filename).toString().replace(_BOM, '');
  186. }
  187. }
  188. else if (!hasTemplate) {
  189. // istanbul ignore if: should not happen at all
  190. if (!filename) {
  191. throw new Error('Internal EJS error: no file name or template '
  192. + 'provided');
  193. }
  194. template = fileLoader(filename).toString().replace(_BOM, '');
  195. }
  196. func = exports.compile(template, options);
  197. if (options.cache) {
  198. exports.cache.set(filename, func);
  199. }
  200. return func;
  201. }
  202. /**
  203. * Try calling handleCache with the given options and data and call the
  204. * callback with the result. If an error occurs, call the callback with
  205. * the error. Used by renderFile().
  206. *
  207. * @memberof module:ejs-internal
  208. * @param {Options} options compilation options
  209. * @param {Object} data template data
  210. * @param {RenderFileCallback} cb callback
  211. * @static
  212. */
  213. function tryHandleCache(options, data, cb) {
  214. var result;
  215. if (!cb) {
  216. if (typeof exports.promiseImpl == 'function') {
  217. return new exports.promiseImpl(function (resolve, reject) {
  218. try {
  219. result = handleCache(options)(data);
  220. resolve(result);
  221. }
  222. catch (err) {
  223. reject(err);
  224. }
  225. });
  226. }
  227. else {
  228. throw new Error('Please provide a callback function');
  229. }
  230. }
  231. else {
  232. try {
  233. result = handleCache(options)(data);
  234. }
  235. catch (err) {
  236. return cb(err);
  237. }
  238. cb(null, result);
  239. }
  240. }
  241. /**
  242. * fileLoader is independent
  243. *
  244. * @param {String} filePath ejs file path.
  245. * @return {String} The contents of the specified file.
  246. * @static
  247. */
  248. function fileLoader(filePath){
  249. return exports.fileLoader(filePath);
  250. }
  251. /**
  252. * Get the template function.
  253. *
  254. * If `options.cache` is `true`, then the template is cached.
  255. *
  256. * @memberof module:ejs-internal
  257. * @param {String} path path for the specified file
  258. * @param {Options} options compilation options
  259. * @return {(TemplateFunction|ClientFunction)}
  260. * Depending on the value of `options.client`, either type might be returned
  261. * @static
  262. */
  263. function includeFile(path, options) {
  264. var opts = utils.shallowCopy({}, options);
  265. opts.filename = getIncludePath(path, opts);
  266. return handleCache(opts);
  267. }
  268. /**
  269. * Get the JavaScript source of an included file.
  270. *
  271. * @memberof module:ejs-internal
  272. * @param {String} path path for the specified file
  273. * @param {Options} options compilation options
  274. * @return {Object}
  275. * @static
  276. */
  277. function includeSource(path, options) {
  278. var opts = utils.shallowCopy({}, options);
  279. var includePath;
  280. var template;
  281. includePath = getIncludePath(path, opts);
  282. template = fileLoader(includePath).toString().replace(_BOM, '');
  283. opts.filename = includePath;
  284. var templ = new Template(template, opts);
  285. templ.generateSource();
  286. return {
  287. source: templ.source,
  288. filename: includePath,
  289. template: template
  290. };
  291. }
  292. /**
  293. * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
  294. * `lineno`.
  295. *
  296. * @implements RethrowCallback
  297. * @memberof module:ejs-internal
  298. * @param {Error} err Error object
  299. * @param {String} str EJS source
  300. * @param {String} filename file name of the EJS file
  301. * @param {String} lineno line number of the error
  302. * @static
  303. */
  304. function rethrow(err, str, flnm, lineno, esc){
  305. var lines = str.split('\n');
  306. var start = Math.max(lineno - 3, 0);
  307. var end = Math.min(lines.length, lineno + 3);
  308. var filename = esc(flnm); // eslint-disable-line
  309. // Error context
  310. var context = lines.slice(start, end).map(function (line, i){
  311. var curr = i + start + 1;
  312. return (curr == lineno ? ' >> ' : ' ')
  313. + curr
  314. + '| '
  315. + line;
  316. }).join('\n');
  317. // Alter exception message
  318. err.path = filename;
  319. err.message = (filename || 'ejs') + ':'
  320. + lineno + '\n'
  321. + context + '\n\n'
  322. + err.message;
  323. throw err;
  324. }
  325. function stripSemi(str){
  326. return str.replace(/;(\s*$)/, '$1');
  327. }
  328. /**
  329. * Compile the given `str` of ejs into a template function.
  330. *
  331. * @param {String} template EJS template
  332. *
  333. * @param {Options} opts compilation options
  334. *
  335. * @return {(TemplateFunction|ClientFunction)}
  336. * Depending on the value of `opts.client`, either type might be returned.
  337. * Note that the return type of the function also depends on the value of `opts.async`.
  338. * @public
  339. */
  340. exports.compile = function compile(template, opts) {
  341. var templ;
  342. // v1 compat
  343. // 'scope' is 'context'
  344. // FIXME: Remove this in a future version
  345. if (opts && opts.scope) {
  346. if (!scopeOptionWarned){
  347. console.warn('`scope` option is deprecated and will be removed in EJS 3');
  348. scopeOptionWarned = true;
  349. }
  350. if (!opts.context) {
  351. opts.context = opts.scope;
  352. }
  353. delete opts.scope;
  354. }
  355. templ = new Template(template, opts);
  356. return templ.compile();
  357. };
  358. /**
  359. * Render the given `template` of ejs.
  360. *
  361. * If you would like to include options but not data, you need to explicitly
  362. * call this function with `data` being an empty object or `null`.
  363. *
  364. * @param {String} template EJS template
  365. * @param {Object} [data={}] template data
  366. * @param {Options} [opts={}] compilation and rendering options
  367. * @return {(String|Promise<String>)}
  368. * Return value type depends on `opts.async`.
  369. * @public
  370. */
  371. exports.render = function (template, d, o) {
  372. var data = d || {};
  373. var opts = o || {};
  374. // No options object -- if there are optiony names
  375. // in the data, copy them to options
  376. if (arguments.length == 2) {
  377. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
  378. }
  379. return handleCache(opts, template)(data);
  380. };
  381. /**
  382. * Render an EJS file at the given `path` and callback `cb(err, str)`.
  383. *
  384. * If you would like to include options but not data, you need to explicitly
  385. * call this function with `data` being an empty object or `null`.
  386. *
  387. * @param {String} path path to the EJS file
  388. * @param {Object} [data={}] template data
  389. * @param {Options} [opts={}] compilation and rendering options
  390. * @param {RenderFileCallback} cb callback
  391. * @public
  392. */
  393. exports.renderFile = function () {
  394. var args = Array.prototype.slice.call(arguments);
  395. var filename = args.shift();
  396. var cb;
  397. var opts = {filename: filename};
  398. var data;
  399. var viewOpts;
  400. // Do we have a callback?
  401. if (typeof arguments[arguments.length - 1] == 'function') {
  402. cb = args.pop();
  403. }
  404. // Do we have data/opts?
  405. if (args.length) {
  406. // Should always have data obj
  407. data = args.shift();
  408. // Normal passed opts (data obj + opts obj)
  409. if (args.length) {
  410. // Use shallowCopy so we don't pollute passed in opts obj with new vals
  411. utils.shallowCopy(opts, args.pop());
  412. }
  413. // Special casing for Express (settings + opts-in-data)
  414. else {
  415. // Express 3 and 4
  416. if (data.settings) {
  417. // Pull a few things from known locations
  418. if (data.settings.views) {
  419. opts.views = data.settings.views;
  420. }
  421. if (data.settings['view cache']) {
  422. opts.cache = true;
  423. }
  424. // Undocumented after Express 2, but still usable, esp. for
  425. // items that are unsafe to be passed along with data, like `root`
  426. viewOpts = data.settings['view options'];
  427. if (viewOpts) {
  428. utils.shallowCopy(opts, viewOpts);
  429. }
  430. }
  431. // Express 2 and lower, values set in app.locals, or people who just
  432. // want to pass options in their data. NOTE: These values will override
  433. // anything previously set in settings or settings['view options']
  434. utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
  435. }
  436. opts.filename = filename;
  437. }
  438. else {
  439. data = {};
  440. }
  441. return tryHandleCache(opts, data, cb);
  442. };
  443. /**
  444. * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
  445. * @public
  446. */
  447. /**
  448. * EJS template class
  449. * @public
  450. */
  451. exports.Template = Template;
  452. exports.clearCache = function () {
  453. exports.cache.reset();
  454. };
  455. function Template(text, opts) {
  456. opts = opts || {};
  457. var options = {};
  458. this.templateText = text;
  459. this.mode = null;
  460. this.truncate = false;
  461. this.currentLine = 1;
  462. this.source = '';
  463. this.dependencies = [];
  464. options.client = opts.client || false;
  465. options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
  466. options.compileDebug = opts.compileDebug !== false;
  467. options.debug = !!opts.debug;
  468. options.filename = opts.filename;
  469. options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
  470. options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
  471. options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
  472. options.strict = opts.strict || false;
  473. options.context = opts.context;
  474. options.cache = opts.cache || false;
  475. options.rmWhitespace = opts.rmWhitespace;
  476. options.root = opts.root;
  477. options.outputFunctionName = opts.outputFunctionName;
  478. options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
  479. options.views = opts.views;
  480. options.async = opts.async;
  481. options.destructuredLocals = opts.destructuredLocals;
  482. options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
  483. if (options.strict) {
  484. options._with = false;
  485. }
  486. else {
  487. options._with = typeof opts._with != 'undefined' ? opts._with : true;
  488. }
  489. this.opts = options;
  490. this.regex = this.createRegex();
  491. }
  492. Template.modes = {
  493. EVAL: 'eval',
  494. ESCAPED: 'escaped',
  495. RAW: 'raw',
  496. COMMENT: 'comment',
  497. LITERAL: 'literal'
  498. };
  499. Template.prototype = {
  500. createRegex: function () {
  501. var str = _REGEX_STRING;
  502. var delim = utils.escapeRegExpChars(this.opts.delimiter);
  503. var open = utils.escapeRegExpChars(this.opts.openDelimiter);
  504. var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
  505. str = str.replace(/%/g, delim)
  506. .replace(/</g, open)
  507. .replace(/>/g, close);
  508. return new RegExp(str);
  509. },
  510. compile: function () {
  511. var src;
  512. var fn;
  513. var opts = this.opts;
  514. var prepended = '';
  515. var appended = '';
  516. var escapeFn = opts.escapeFunction;
  517. var ctor;
  518. if (!this.source) {
  519. this.generateSource();
  520. prepended +=
  521. ' var __output = "";\n' +
  522. ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
  523. if (opts.outputFunctionName) {
  524. prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
  525. }
  526. if (opts.destructuredLocals && opts.destructuredLocals.length) {
  527. var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
  528. for (var i = 0; i < opts.destructuredLocals.length; i++) {
  529. var name = opts.destructuredLocals[i];
  530. if (i > 0) {
  531. destructuring += ',\n ';
  532. }
  533. destructuring += name + ' = __locals.' + name;
  534. }
  535. prepended += destructuring + ';\n';
  536. }
  537. if (opts._with !== false) {
  538. prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
  539. appended += ' }' + '\n';
  540. }
  541. appended += ' return __output;' + '\n';
  542. this.source = prepended + this.source + appended;
  543. }
  544. if (opts.compileDebug) {
  545. src = 'var __line = 1' + '\n'
  546. + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
  547. + ' , __filename = ' + (opts.filename ?
  548. JSON.stringify(opts.filename) : 'undefined') + ';' + '\n'
  549. + 'try {' + '\n'
  550. + this.source
  551. + '} catch (e) {' + '\n'
  552. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  553. + '}' + '\n';
  554. }
  555. else {
  556. src = this.source;
  557. }
  558. if (opts.client) {
  559. src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
  560. if (opts.compileDebug) {
  561. src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
  562. }
  563. }
  564. if (opts.strict) {
  565. src = '"use strict";\n' + src;
  566. }
  567. if (opts.debug) {
  568. console.log(src);
  569. }
  570. if (opts.compileDebug && opts.filename) {
  571. src = src + '\n'
  572. + '//# sourceURL=' + opts.filename + '\n';
  573. }
  574. try {
  575. if (opts.async) {
  576. // Have to use generated function for this, since in envs without support,
  577. // it breaks in parsing
  578. try {
  579. ctor = (new Function('return (async function(){}).constructor;'))();
  580. }
  581. catch(e) {
  582. if (e instanceof SyntaxError) {
  583. throw new Error('This environment does not support async/await');
  584. }
  585. else {
  586. throw e;
  587. }
  588. }
  589. }
  590. else {
  591. ctor = Function;
  592. }
  593. fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
  594. }
  595. catch(e) {
  596. // istanbul ignore else
  597. if (e instanceof SyntaxError) {
  598. if (opts.filename) {
  599. e.message += ' in ' + opts.filename;
  600. }
  601. e.message += ' while compiling ejs\n\n';
  602. e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
  603. e.message += 'https://github.com/RyanZim/EJS-Lint';
  604. if (!opts.async) {
  605. e.message += '\n';
  606. e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
  607. }
  608. }
  609. throw e;
  610. }
  611. // Return a callable function which will execute the function
  612. // created by the source-code, with the passed data as locals
  613. // Adds a local `include` function which allows full recursive include
  614. var returnedFn = opts.client ? fn : function anonymous(data) {
  615. var include = function (path, includeData) {
  616. var d = utils.shallowCopy({}, data);
  617. if (includeData) {
  618. d = utils.shallowCopy(d, includeData);
  619. }
  620. return includeFile(path, opts)(d);
  621. };
  622. return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
  623. };
  624. returnedFn.dependencies = this.dependencies;
  625. if (opts.filename && typeof Object.defineProperty === 'function') {
  626. var filename = opts.filename;
  627. var basename = path.basename(filename, path.extname(filename));
  628. try {
  629. Object.defineProperty(returnedFn, 'name', {
  630. value: basename,
  631. writable: false,
  632. enumerable: false,
  633. configurable: true
  634. });
  635. } catch (e) {/* ignore */}
  636. }
  637. return returnedFn;
  638. },
  639. generateSource: function () {
  640. var opts = this.opts;
  641. if (opts.rmWhitespace) {
  642. // Have to use two separate replace here as `^` and `$` operators don't
  643. // work well with `\r` and empty lines don't work well with the `m` flag.
  644. this.templateText =
  645. this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
  646. }
  647. // Slurp spaces and tabs before <%_ and after _%>
  648. this.templateText =
  649. this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
  650. var self = this;
  651. var matches = this.parseTemplateText();
  652. var d = this.opts.delimiter;
  653. var o = this.opts.openDelimiter;
  654. var c = this.opts.closeDelimiter;
  655. if (matches && matches.length) {
  656. matches.forEach(function (line, index) {
  657. var opening;
  658. var closing;
  659. var include;
  660. var includeOpts;
  661. var includeObj;
  662. var includeSrc;
  663. // If this is an opening tag, check for closing tags
  664. // FIXME: May end up with some false positives here
  665. // Better to store modes as k/v with openDelimiter + delimiter as key
  666. // Then this can simply check against the map
  667. if ( line.indexOf(o + d) === 0 // If it is a tag
  668. && line.indexOf(o + d + d) !== 0) { // and is not escaped
  669. closing = matches[index + 2];
  670. if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
  671. throw new Error('Could not find matching close tag for "' + line + '".');
  672. }
  673. }
  674. // HACK: backward-compat `include` preprocessor directives
  675. if (opts.legacyInclude && (include = line.match(/^\s*include\s+(\S+)/))) {
  676. opening = matches[index - 1];
  677. // Must be in EVAL or RAW mode
  678. if (opening && (opening == o + d || opening == o + d + '-' || opening == o + d + '_')) {
  679. includeOpts = utils.shallowCopy({}, self.opts);
  680. includeObj = includeSource(include[1], includeOpts);
  681. if (self.opts.compileDebug) {
  682. includeSrc =
  683. ' ; (function(){' + '\n'
  684. + ' var __line = 1' + '\n'
  685. + ' , __lines = ' + JSON.stringify(includeObj.template) + '\n'
  686. + ' , __filename = ' + JSON.stringify(includeObj.filename) + ';' + '\n'
  687. + ' try {' + '\n'
  688. + includeObj.source
  689. + ' } catch (e) {' + '\n'
  690. + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
  691. + ' }' + '\n'
  692. + ' ; }).call(this)' + '\n';
  693. }else{
  694. includeSrc = ' ; (function(){' + '\n' + includeObj.source +
  695. ' ; }).call(this)' + '\n';
  696. }
  697. self.source += includeSrc;
  698. self.dependencies.push(exports.resolveInclude(include[1],
  699. includeOpts.filename));
  700. return;
  701. }
  702. }
  703. self.scanLine(line);
  704. });
  705. }
  706. },
  707. parseTemplateText: function () {
  708. var str = this.templateText;
  709. var pat = this.regex;
  710. var result = pat.exec(str);
  711. var arr = [];
  712. var firstPos;
  713. while (result) {
  714. firstPos = result.index;
  715. if (firstPos !== 0) {
  716. arr.push(str.substring(0, firstPos));
  717. str = str.slice(firstPos);
  718. }
  719. arr.push(result[0]);
  720. str = str.slice(result[0].length);
  721. result = pat.exec(str);
  722. }
  723. if (str) {
  724. arr.push(str);
  725. }
  726. return arr;
  727. },
  728. _addOutput: function (line) {
  729. if (this.truncate) {
  730. // Only replace single leading linebreak in the line after
  731. // -%> tag -- this is the single, trailing linebreak
  732. // after the tag that the truncation mode replaces
  733. // Handle Win / Unix / old Mac linebreaks -- do the \r\n
  734. // combo first in the regex-or
  735. line = line.replace(/^(?:\r\n|\r|\n)/, '');
  736. this.truncate = false;
  737. }
  738. if (!line) {
  739. return line;
  740. }
  741. // Preserve literal slashes
  742. line = line.replace(/\\/g, '\\\\');
  743. // Convert linebreaks
  744. line = line.replace(/\n/g, '\\n');
  745. line = line.replace(/\r/g, '\\r');
  746. // Escape double-quotes
  747. // - this will be the delimiter during execution
  748. line = line.replace(/"/g, '\\"');
  749. this.source += ' ; __append("' + line + '")' + '\n';
  750. },
  751. scanLine: function (line) {
  752. var self = this;
  753. var d = this.opts.delimiter;
  754. var o = this.opts.openDelimiter;
  755. var c = this.opts.closeDelimiter;
  756. var newLineCount = 0;
  757. newLineCount = (line.split('\n').length - 1);
  758. switch (line) {
  759. case o + d:
  760. case o + d + '_':
  761. this.mode = Template.modes.EVAL;
  762. break;
  763. case o + d + '=':
  764. this.mode = Template.modes.ESCAPED;
  765. break;
  766. case o + d + '-':
  767. this.mode = Template.modes.RAW;
  768. break;
  769. case o + d + '#':
  770. this.mode = Template.modes.COMMENT;
  771. break;
  772. case o + d + d:
  773. this.mode = Template.modes.LITERAL;
  774. this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
  775. break;
  776. case d + d + c:
  777. this.mode = Template.modes.LITERAL;
  778. this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
  779. break;
  780. case d + c:
  781. case '-' + d + c:
  782. case '_' + d + c:
  783. if (this.mode == Template.modes.LITERAL) {
  784. this._addOutput(line);
  785. }
  786. this.mode = null;
  787. this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
  788. break;
  789. default:
  790. // In script mode, depends on type of tag
  791. if (this.mode) {
  792. // If '//' is found without a line break, add a line break.
  793. switch (this.mode) {
  794. case Template.modes.EVAL:
  795. case Template.modes.ESCAPED:
  796. case Template.modes.RAW:
  797. if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
  798. line += '\n';
  799. }
  800. }
  801. switch (this.mode) {
  802. // Just executing code
  803. case Template.modes.EVAL:
  804. this.source += ' ; ' + line + '\n';
  805. break;
  806. // Exec, esc, and output
  807. case Template.modes.ESCAPED:
  808. this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
  809. break;
  810. // Exec and output
  811. case Template.modes.RAW:
  812. this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
  813. break;
  814. case Template.modes.COMMENT:
  815. // Do nothing
  816. break;
  817. // Literal <%% mode, append as raw output
  818. case Template.modes.LITERAL:
  819. this._addOutput(line);
  820. break;
  821. }
  822. }
  823. // In string mode, just add the output
  824. else {
  825. this._addOutput(line);
  826. }
  827. }
  828. if (self.opts.compileDebug && newLineCount) {
  829. this.currentLine += newLineCount;
  830. this.source += ' ; __line = ' + this.currentLine + '\n';
  831. }
  832. }
  833. };
  834. /**
  835. * Escape characters reserved in XML.
  836. *
  837. * This is simply an export of {@link module:utils.escapeXML}.
  838. *
  839. * If `markup` is `undefined` or `null`, the empty string is returned.
  840. *
  841. * @param {String} markup Input string
  842. * @return {String} Escaped string
  843. * @public
  844. * @func
  845. * */
  846. exports.escapeXML = utils.escapeXML;
  847. /**
  848. * Express.js support.
  849. *
  850. * This is an alias for {@link module:ejs.renderFile}, in order to support
  851. * Express.js out-of-the-box.
  852. *
  853. * @func
  854. */
  855. exports.__express = exports.renderFile;
  856. // Add require support
  857. /* istanbul ignore else */
  858. if (require.extensions) {
  859. require.extensions['.ejs'] = function (module, flnm) {
  860. console.log('Deprecated: this API will go away in EJS v2.8');
  861. var filename = flnm || /* istanbul ignore next */ module.filename;
  862. var options = {
  863. filename: filename,
  864. client: true
  865. };
  866. var template = fileLoader(filename).toString();
  867. var fn = exports.compile(template, options);
  868. module._compile('module.exports = ' + fn.toString() + ';', filename);
  869. };
  870. }
  871. /**
  872. * Version of EJS.
  873. *
  874. * @readonly
  875. * @type {String}
  876. * @public
  877. */
  878. exports.VERSION = _VERSION_STRING;
  879. /**
  880. * Name for detection of EJS.
  881. *
  882. * @readonly
  883. * @type {String}
  884. * @public
  885. */
  886. exports.name = _NAME;
  887. /* istanbul ignore if */
  888. if (typeof window != 'undefined') {
  889. window.ejs = exports;
  890. }
  891. },{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){
  892. /*
  893. * EJS Embedded JavaScript templates
  894. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  895. *
  896. * Licensed under the Apache License, Version 2.0 (the "License");
  897. * you may not use this file except in compliance with the License.
  898. * You may obtain a copy of the License at
  899. *
  900. * http://www.apache.org/licenses/LICENSE-2.0
  901. *
  902. * Unless required by applicable law or agreed to in writing, software
  903. * distributed under the License is distributed on an "AS IS" BASIS,
  904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  905. * See the License for the specific language governing permissions and
  906. * limitations under the License.
  907. *
  908. */
  909. /**
  910. * Private utility functions
  911. * @module utils
  912. * @private
  913. */
  914. 'use strict';
  915. var regExpChars = /[|\\{}()[\]^$+*?.]/g;
  916. /**
  917. * Escape characters reserved in regular expressions.
  918. *
  919. * If `string` is `undefined` or `null`, the empty string is returned.
  920. *
  921. * @param {String} string Input string
  922. * @return {String} Escaped string
  923. * @static
  924. * @private
  925. */
  926. exports.escapeRegExpChars = function (string) {
  927. // istanbul ignore if
  928. if (!string) {
  929. return '';
  930. }
  931. return String(string).replace(regExpChars, '\\$&');
  932. };
  933. var _ENCODE_HTML_RULES = {
  934. '&': '&amp;',
  935. '<': '&lt;',
  936. '>': '&gt;',
  937. '"': '&#34;',
  938. "'": '&#39;'
  939. };
  940. var _MATCH_HTML = /[&<>'"]/g;
  941. function encode_char(c) {
  942. return _ENCODE_HTML_RULES[c] || c;
  943. }
  944. /**
  945. * Stringified version of constants used by {@link module:utils.escapeXML}.
  946. *
  947. * It is used in the process of generating {@link ClientFunction}s.
  948. *
  949. * @readonly
  950. * @type {String}
  951. */
  952. var escapeFuncStr =
  953. 'var _ENCODE_HTML_RULES = {\n'
  954. + ' "&": "&amp;"\n'
  955. + ' , "<": "&lt;"\n'
  956. + ' , ">": "&gt;"\n'
  957. + ' , \'"\': "&#34;"\n'
  958. + ' , "\'": "&#39;"\n'
  959. + ' }\n'
  960. + ' , _MATCH_HTML = /[&<>\'"]/g;\n'
  961. + 'function encode_char(c) {\n'
  962. + ' return _ENCODE_HTML_RULES[c] || c;\n'
  963. + '};\n';
  964. /**
  965. * Escape characters reserved in XML.
  966. *
  967. * If `markup` is `undefined` or `null`, the empty string is returned.
  968. *
  969. * @implements {EscapeCallback}
  970. * @param {String} markup Input string
  971. * @return {String} Escaped string
  972. * @static
  973. * @private
  974. */
  975. exports.escapeXML = function (markup) {
  976. return markup == undefined
  977. ? ''
  978. : String(markup)
  979. .replace(_MATCH_HTML, encode_char);
  980. };
  981. exports.escapeXML.toString = function () {
  982. return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
  983. };
  984. /**
  985. * Naive copy of properties from one object to another.
  986. * Does not recurse into non-scalar properties
  987. * Does not check to see if the property has a value before copying
  988. *
  989. * @param {Object} to Destination object
  990. * @param {Object} from Source object
  991. * @return {Object} Destination object
  992. * @static
  993. * @private
  994. */
  995. exports.shallowCopy = function (to, from) {
  996. from = from || {};
  997. for (var p in from) {
  998. to[p] = from[p];
  999. }
  1000. return to;
  1001. };
  1002. /**
  1003. * Naive copy of a list of key names, from one object to another.
  1004. * Only copies property if it is actually defined
  1005. * Does not recurse into non-scalar properties
  1006. *
  1007. * @param {Object} to Destination object
  1008. * @param {Object} from Source object
  1009. * @param {Array} list List of properties to copy
  1010. * @return {Object} Destination object
  1011. * @static
  1012. * @private
  1013. */
  1014. exports.shallowCopyFromList = function (to, from, list) {
  1015. for (var i = 0; i < list.length; i++) {
  1016. var p = list[i];
  1017. if (typeof from[p] != 'undefined') {
  1018. to[p] = from[p];
  1019. }
  1020. }
  1021. return to;
  1022. };
  1023. /**
  1024. * Simple in-process cache implementation. Does not implement limits of any
  1025. * sort.
  1026. *
  1027. * @implements Cache
  1028. * @static
  1029. * @private
  1030. */
  1031. exports.cache = {
  1032. _data: {},
  1033. set: function (key, val) {
  1034. this._data[key] = val;
  1035. },
  1036. get: function (key) {
  1037. return this._data[key];
  1038. },
  1039. remove: function (key) {
  1040. delete this._data[key];
  1041. },
  1042. reset: function () {
  1043. this._data = {};
  1044. }
  1045. };
  1046. },{}],3:[function(require,module,exports){
  1047. },{}],4:[function(require,module,exports){
  1048. (function (process){
  1049. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  1050. // backported and transplited with Babel, with backwards-compat fixes
  1051. // Copyright Joyent, Inc. and other Node contributors.
  1052. //
  1053. // Permission is hereby granted, free of charge, to any person obtaining a
  1054. // copy of this software and associated documentation files (the
  1055. // "Software"), to deal in the Software without restriction, including
  1056. // without limitation the rights to use, copy, modify, merge, publish,
  1057. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1058. // persons to whom the Software is furnished to do so, subject to the
  1059. // following conditions:
  1060. //
  1061. // The above copyright notice and this permission notice shall be included
  1062. // in all copies or substantial portions of the Software.
  1063. //
  1064. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1065. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1066. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1067. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1068. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1069. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1070. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1071. // resolves . and .. elements in a path array with directory names there
  1072. // must be no slashes, empty elements, or device names (c:\) in the array
  1073. // (so also no leading and trailing slashes - it does not distinguish
  1074. // relative and absolute paths)
  1075. function normalizeArray(parts, allowAboveRoot) {
  1076. // if the path tries to go above the root, `up` ends up > 0
  1077. var up = 0;
  1078. for (var i = parts.length - 1; i >= 0; i--) {
  1079. var last = parts[i];
  1080. if (last === '.') {
  1081. parts.splice(i, 1);
  1082. } else if (last === '..') {
  1083. parts.splice(i, 1);
  1084. up++;
  1085. } else if (up) {
  1086. parts.splice(i, 1);
  1087. up--;
  1088. }
  1089. }
  1090. // if the path is allowed to go above the root, restore leading ..s
  1091. if (allowAboveRoot) {
  1092. for (; up--; up) {
  1093. parts.unshift('..');
  1094. }
  1095. }
  1096. return parts;
  1097. }
  1098. // path.resolve([from ...], to)
  1099. // posix version
  1100. exports.resolve = function() {
  1101. var resolvedPath = '',
  1102. resolvedAbsolute = false;
  1103. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1104. var path = (i >= 0) ? arguments[i] : process.cwd();
  1105. // Skip empty and invalid entries
  1106. if (typeof path !== 'string') {
  1107. throw new TypeError('Arguments to path.resolve must be strings');
  1108. } else if (!path) {
  1109. continue;
  1110. }
  1111. resolvedPath = path + '/' + resolvedPath;
  1112. resolvedAbsolute = path.charAt(0) === '/';
  1113. }
  1114. // At this point the path should be resolved to a full absolute path, but
  1115. // handle relative paths to be safe (might happen when process.cwd() fails)
  1116. // Normalize the path
  1117. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  1118. return !!p;
  1119. }), !resolvedAbsolute).join('/');
  1120. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1121. };
  1122. // path.normalize(path)
  1123. // posix version
  1124. exports.normalize = function(path) {
  1125. var isAbsolute = exports.isAbsolute(path),
  1126. trailingSlash = substr(path, -1) === '/';
  1127. // Normalize the path
  1128. path = normalizeArray(filter(path.split('/'), function(p) {
  1129. return !!p;
  1130. }), !isAbsolute).join('/');
  1131. if (!path && !isAbsolute) {
  1132. path = '.';
  1133. }
  1134. if (path && trailingSlash) {
  1135. path += '/';
  1136. }
  1137. return (isAbsolute ? '/' : '') + path;
  1138. };
  1139. // posix version
  1140. exports.isAbsolute = function(path) {
  1141. return path.charAt(0) === '/';
  1142. };
  1143. // posix version
  1144. exports.join = function() {
  1145. var paths = Array.prototype.slice.call(arguments, 0);
  1146. return exports.normalize(filter(paths, function(p, index) {
  1147. if (typeof p !== 'string') {
  1148. throw new TypeError('Arguments to path.join must be strings');
  1149. }
  1150. return p;
  1151. }).join('/'));
  1152. };
  1153. // path.relative(from, to)
  1154. // posix version
  1155. exports.relative = function(from, to) {
  1156. from = exports.resolve(from).substr(1);
  1157. to = exports.resolve(to).substr(1);
  1158. function trim(arr) {
  1159. var start = 0;
  1160. for (; start < arr.length; start++) {
  1161. if (arr[start] !== '') break;
  1162. }
  1163. var end = arr.length - 1;
  1164. for (; end >= 0; end--) {
  1165. if (arr[end] !== '') break;
  1166. }
  1167. if (start > end) return [];
  1168. return arr.slice(start, end - start + 1);
  1169. }
  1170. var fromParts = trim(from.split('/'));
  1171. var toParts = trim(to.split('/'));
  1172. var length = Math.min(fromParts.length, toParts.length);
  1173. var samePartsLength = length;
  1174. for (var i = 0; i < length; i++) {
  1175. if (fromParts[i] !== toParts[i]) {
  1176. samePartsLength = i;
  1177. break;
  1178. }
  1179. }
  1180. var outputParts = [];
  1181. for (var i = samePartsLength; i < fromParts.length; i++) {
  1182. outputParts.push('..');
  1183. }
  1184. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1185. return outputParts.join('/');
  1186. };
  1187. exports.sep = '/';
  1188. exports.delimiter = ':';
  1189. exports.dirname = function (path) {
  1190. if (typeof path !== 'string') path = path + '';
  1191. if (path.length === 0) return '.';
  1192. var code = path.charCodeAt(0);
  1193. var hasRoot = code === 47 /*/*/;
  1194. var end = -1;
  1195. var matchedSlash = true;
  1196. for (var i = path.length - 1; i >= 1; --i) {
  1197. code = path.charCodeAt(i);
  1198. if (code === 47 /*/*/) {
  1199. if (!matchedSlash) {
  1200. end = i;
  1201. break;
  1202. }
  1203. } else {
  1204. // We saw the first non-path separator
  1205. matchedSlash = false;
  1206. }
  1207. }
  1208. if (end === -1) return hasRoot ? '/' : '.';
  1209. if (hasRoot && end === 1) {
  1210. // return '//';
  1211. // Backwards-compat fix:
  1212. return '/';
  1213. }
  1214. return path.slice(0, end);
  1215. };
  1216. function basename(path) {
  1217. if (typeof path !== 'string') path = path + '';
  1218. var start = 0;
  1219. var end = -1;
  1220. var matchedSlash = true;
  1221. var i;
  1222. for (i = path.length - 1; i >= 0; --i) {
  1223. if (path.charCodeAt(i) === 47 /*/*/) {
  1224. // If we reached a path separator that was not part of a set of path
  1225. // separators at the end of the string, stop now
  1226. if (!matchedSlash) {
  1227. start = i + 1;
  1228. break;
  1229. }
  1230. } else if (end === -1) {
  1231. // We saw the first non-path separator, mark this as the end of our
  1232. // path component
  1233. matchedSlash = false;
  1234. end = i + 1;
  1235. }
  1236. }
  1237. if (end === -1) return '';
  1238. return path.slice(start, end);
  1239. }
  1240. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  1241. // in new Node.js versions, so only basename() above is backported here
  1242. exports.basename = function (path, ext) {
  1243. var f = basename(path);
  1244. if (ext && f.substr(-1 * ext.length) === ext) {
  1245. f = f.substr(0, f.length - ext.length);
  1246. }
  1247. return f;
  1248. };
  1249. exports.extname = function (path) {
  1250. if (typeof path !== 'string') path = path + '';
  1251. var startDot = -1;
  1252. var startPart = 0;
  1253. var end = -1;
  1254. var matchedSlash = true;
  1255. // Track the state of characters (if any) we see before our first dot and
  1256. // after any path separator we find
  1257. var preDotState = 0;
  1258. for (var i = path.length - 1; i >= 0; --i) {
  1259. var code = path.charCodeAt(i);
  1260. if (code === 47 /*/*/) {
  1261. // If we reached a path separator that was not part of a set of path
  1262. // separators at the end of the string, stop now
  1263. if (!matchedSlash) {
  1264. startPart = i + 1;
  1265. break;
  1266. }
  1267. continue;
  1268. }
  1269. if (end === -1) {
  1270. // We saw the first non-path separator, mark this as the end of our
  1271. // extension
  1272. matchedSlash = false;
  1273. end = i + 1;
  1274. }
  1275. if (code === 46 /*.*/) {
  1276. // If this is our first dot, mark it as the start of our extension
  1277. if (startDot === -1)
  1278. startDot = i;
  1279. else if (preDotState !== 1)
  1280. preDotState = 1;
  1281. } else if (startDot !== -1) {
  1282. // We saw a non-dot and non-path separator before our dot, so we should
  1283. // have a good chance at having a non-empty extension
  1284. preDotState = -1;
  1285. }
  1286. }
  1287. if (startDot === -1 || end === -1 ||
  1288. // We saw a non-dot character immediately before the dot
  1289. preDotState === 0 ||
  1290. // The (right-most) trimmed path component is exactly '..'
  1291. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  1292. return '';
  1293. }
  1294. return path.slice(startDot, end);
  1295. };
  1296. function filter (xs, f) {
  1297. if (xs.filter) return xs.filter(f);
  1298. var res = [];
  1299. for (var i = 0; i < xs.length; i++) {
  1300. if (f(xs[i], i, xs)) res.push(xs[i]);
  1301. }
  1302. return res;
  1303. }
  1304. // String.prototype.substr - negative index don't work in IE8
  1305. var substr = 'ab'.substr(-1) === 'b'
  1306. ? function (str, start, len) { return str.substr(start, len) }
  1307. : function (str, start, len) {
  1308. if (start < 0) start = str.length + start;
  1309. return str.substr(start, len);
  1310. }
  1311. ;
  1312. }).call(this,require('_process'))
  1313. },{"_process":5}],5:[function(require,module,exports){
  1314. // shim for using process in browser
  1315. var process = module.exports = {};
  1316. // cached from whatever global is present so that test runners that stub it
  1317. // don't break things. But we need to wrap it in a try catch in case it is
  1318. // wrapped in strict mode code which doesn't define any globals. It's inside a
  1319. // function because try/catches deoptimize in certain engines.
  1320. var cachedSetTimeout;
  1321. var cachedClearTimeout;
  1322. function defaultSetTimout() {
  1323. throw new Error('setTimeout has not been defined');
  1324. }
  1325. function defaultClearTimeout () {
  1326. throw new Error('clearTimeout has not been defined');
  1327. }
  1328. (function () {
  1329. try {
  1330. if (typeof setTimeout === 'function') {
  1331. cachedSetTimeout = setTimeout;
  1332. } else {
  1333. cachedSetTimeout = defaultSetTimout;
  1334. }
  1335. } catch (e) {
  1336. cachedSetTimeout = defaultSetTimout;
  1337. }
  1338. try {
  1339. if (typeof clearTimeout === 'function') {
  1340. cachedClearTimeout = clearTimeout;
  1341. } else {
  1342. cachedClearTimeout = defaultClearTimeout;
  1343. }
  1344. } catch (e) {
  1345. cachedClearTimeout = defaultClearTimeout;
  1346. }
  1347. } ())
  1348. function runTimeout(fun) {
  1349. if (cachedSetTimeout === setTimeout) {
  1350. //normal enviroments in sane situations
  1351. return setTimeout(fun, 0);
  1352. }
  1353. // if setTimeout wasn't available but was latter defined
  1354. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1355. cachedSetTimeout = setTimeout;
  1356. return setTimeout(fun, 0);
  1357. }
  1358. try {
  1359. // when when somebody has screwed with setTimeout but no I.E. maddness
  1360. return cachedSetTimeout(fun, 0);
  1361. } catch(e){
  1362. try {
  1363. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1364. return cachedSetTimeout.call(null, fun, 0);
  1365. } catch(e){
  1366. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  1367. return cachedSetTimeout.call(this, fun, 0);
  1368. }
  1369. }
  1370. }
  1371. function runClearTimeout(marker) {
  1372. if (cachedClearTimeout === clearTimeout) {
  1373. //normal enviroments in sane situations
  1374. return clearTimeout(marker);
  1375. }
  1376. // if clearTimeout wasn't available but was latter defined
  1377. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1378. cachedClearTimeout = clearTimeout;
  1379. return clearTimeout(marker);
  1380. }
  1381. try {
  1382. // when when somebody has screwed with setTimeout but no I.E. maddness
  1383. return cachedClearTimeout(marker);
  1384. } catch (e){
  1385. try {
  1386. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  1387. return cachedClearTimeout.call(null, marker);
  1388. } catch (e){
  1389. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  1390. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  1391. return cachedClearTimeout.call(this, marker);
  1392. }
  1393. }
  1394. }
  1395. var queue = [];
  1396. var draining = false;
  1397. var currentQueue;
  1398. var queueIndex = -1;
  1399. function cleanUpNextTick() {
  1400. if (!draining || !currentQueue) {
  1401. return;
  1402. }
  1403. draining = false;
  1404. if (currentQueue.length) {
  1405. queue = currentQueue.concat(queue);
  1406. } else {
  1407. queueIndex = -1;
  1408. }
  1409. if (queue.length) {
  1410. drainQueue();
  1411. }
  1412. }
  1413. function drainQueue() {
  1414. if (draining) {
  1415. return;
  1416. }
  1417. var timeout = runTimeout(cleanUpNextTick);
  1418. draining = true;
  1419. var len = queue.length;
  1420. while(len) {
  1421. currentQueue = queue;
  1422. queue = [];
  1423. while (++queueIndex < len) {
  1424. if (currentQueue) {
  1425. currentQueue[queueIndex].run();
  1426. }
  1427. }
  1428. queueIndex = -1;
  1429. len = queue.length;
  1430. }
  1431. currentQueue = null;
  1432. draining = false;
  1433. runClearTimeout(timeout);
  1434. }
  1435. process.nextTick = function (fun) {
  1436. var args = new Array(arguments.length - 1);
  1437. if (arguments.length > 1) {
  1438. for (var i = 1; i < arguments.length; i++) {
  1439. args[i - 1] = arguments[i];
  1440. }
  1441. }
  1442. queue.push(new Item(fun, args));
  1443. if (queue.length === 1 && !draining) {
  1444. runTimeout(drainQueue);
  1445. }
  1446. };
  1447. // v8 likes predictible objects
  1448. function Item(fun, array) {
  1449. this.fun = fun;
  1450. this.array = array;
  1451. }
  1452. Item.prototype.run = function () {
  1453. this.fun.apply(null, this.array);
  1454. };
  1455. process.title = 'browser';
  1456. process.browser = true;
  1457. process.env = {};
  1458. process.argv = [];
  1459. process.version = ''; // empty string to avoid regexp issues
  1460. process.versions = {};
  1461. function noop() {}
  1462. process.on = noop;
  1463. process.addListener = noop;
  1464. process.once = noop;
  1465. process.off = noop;
  1466. process.removeListener = noop;
  1467. process.removeAllListeners = noop;
  1468. process.emit = noop;
  1469. process.prependListener = noop;
  1470. process.prependOnceListener = noop;
  1471. process.listeners = function (name) { return [] }
  1472. process.binding = function (name) {
  1473. throw new Error('process.binding is not supported');
  1474. };
  1475. process.cwd = function () { return '/' };
  1476. process.chdir = function (dir) {
  1477. throw new Error('process.chdir is not supported');
  1478. };
  1479. process.umask = function() { return 0; };
  1480. },{}],6:[function(require,module,exports){
  1481. module.exports={
  1482. "name": "ejs",
  1483. "description": "Embedded JavaScript templates",
  1484. "keywords": [
  1485. "template",
  1486. "engine",
  1487. "ejs"
  1488. ],
  1489. "version": "2.7.4",
  1490. "author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
  1491. "license": "Apache-2.0",
  1492. "main": "./lib/ejs.js",
  1493. "repository": {
  1494. "type": "git",
  1495. "url": "git://github.com/mde/ejs.git"
  1496. },
  1497. "bugs": "https://github.com/mde/ejs/issues",
  1498. "homepage": "https://github.com/mde/ejs",
  1499. "dependencies": {},
  1500. "devDependencies": {
  1501. "browserify": "^13.1.1",
  1502. "eslint": "^4.14.0",
  1503. "git-directory-deploy": "^1.5.1",
  1504. "jake": "^10.3.1",
  1505. "jsdoc": "^3.4.0",
  1506. "lru-cache": "^4.0.1",
  1507. "mocha": "^5.0.5",
  1508. "uglify-js": "^3.3.16"
  1509. },
  1510. "engines": {
  1511. "node": ">=0.10.0"
  1512. },
  1513. "scripts": {
  1514. "test": "mocha",
  1515. "postinstall": "node ./postinstall.js"
  1516. }
  1517. }
  1518. },{}]},{},[1])(1)
  1519. });