ejs.js 49 KB

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