UNPKG

14.1 kBTypeScriptView Raw
1export as namespace ejs;
2
3/**
4 * Version of EJS.
5 */
6export const VERSION: string;
7
8/**
9 * Name for detection of EJS.
10 */
11export const name: "ejs";
12
13/**
14 * Get the path to the included file from the parent file path and the
15 * specified path.
16 *
17 * @param name specified path
18 * @param filename parent file path
19 * @param isDir whether the parent file path is a directory
20 */
21export function resolveInclude(name: string, filename: string, isDir?: boolean): string;
22
23/**
24 * Compile the given `str` of ejs into a template function.
25 */
26export function compile(
27 template: string,
28 opts: Options & { async: true; client?: false | undefined },
29): AsyncTemplateFunction;
30export function compile(template: string, opts: Options & { async: true; client: true }): AsyncClientFunction;
31export function compile(
32 template: string,
33 opts?: Options & { async?: false | undefined; client?: false | undefined },
34): TemplateFunction;
35export function compile(template: string, opts?: Options & { async?: false | undefined; client: true }): ClientFunction;
36export function compile(template: string, opts?: Options): TemplateFunction | AsyncTemplateFunction;
37
38/**
39 * Render the given `template` of ejs.
40 *
41 * If you would like to include options but not data, you need to explicitly
42 * call this function with `data` being an empty object or `null`.
43 */
44export function render(template: string, data?: Data, opts?: Options & { async: false }): string;
45export function render(template: string, data: Data | undefined, opts: Options & { async: true }): Promise<string>;
46export function render(template: string, data: Data | undefined, opts: Options & { async?: never | undefined }): string;
47export function render(template: string, data?: Data, opts?: Options): string | Promise<string>;
48
49/**
50 * Callback for receiving data from `renderFile`.
51 *
52 * @param err error, if any resulted from the rendering process
53 * @param str output string, is `undefined` if there is an error
54 */
55export type RenderFileCallback<T> = (err: Error | null, str: string) => T;
56
57/**
58 * Render an EJS file at the given `path` and callback `cb(err, str)`.
59 *
60 * If you would like to include options but not data, you need to explicitly
61 * call this function with `data` being an empty object or `null`.
62 */
63export function renderFile<T>(path: string, cb: RenderFileCallback<T>): T;
64export function renderFile<T>(path: string, data: Data, cb: RenderFileCallback<T>): T;
65export function renderFile<T>(path: string, data: Data, opts: Options, cb: RenderFileCallback<T>): T;
66export function renderFile(path: string, data?: Data, opts?: Options): Promise<string>;
67
68/**
69 * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
70 */
71export function clearCache(): void;
72
73/**
74 * EJS template function cache. This can be a LRU object from lru-cache
75 * NPM module. By default, it is `utils.cache`, a simple in-process
76 * cache that grows continuously.
77 */
78export let cache: Cache;
79
80/**
81 * Custom file loader. Useful for template preprocessing or restricting access
82 * to a certain part of the filesystem.
83 *
84 * @param path the path of the file to be read
85 * @return the contents of the file as a string or object that implements the toString() method
86 *
87 * @default fs.readFileSync
88 */
89export type fileLoader = (path: string) => string | { toString(): string };
90export let fileLoader: fileLoader;
91
92/**
93 * Name of the object containing the locals.
94 *
95 * This variable is overridden by {@link Options}`.localsName` if it is not
96 * `undefined`.
97 *
98 * @default 'locals'
99 */
100export let localsName: string;
101
102/**
103 * The opening delimiter for all statements. This allows you to clearly delinate
104 * the difference between template code and existing delimiters. (It is recommended
105 * to synchronize this with the closeDelimiter property.)
106 *
107 * @default '<'
108 */
109export let openDelimiter: string;
110
111/**
112 * The closing delimiter for all statements. This allows to to clearly delinate
113 * the difference between template code and existing delimiters. (It is recommended
114 * to synchronize this with the openDelimiter property.)
115 *
116 * @default '>'
117 */
118export let closeDelimiter: string;
119
120/**
121 * The delimiter used in template compilation.
122 *
123 * @default '%'
124 */
125export let delimiter: string | undefined;
126
127/**
128 * Promise implementation -- defaults to the native implementation if available
129 * This is mostly just for testability
130 *
131 * @default Promise
132 */
133export let promiseImpl: PromiseConstructorLike | undefined;
134
135/**
136 * Escape characters reserved in XML.
137 *
138 * This is simply an export of `utils.escapeXML`.
139 *
140 * If `markup` is `undefined` or `null`, the empty string is returned.
141 */
142export function escapeXML(markup?: any): string;
143
144export class Template {
145 /**
146 * The EJS template source text.
147 */
148 readonly templateText: string;
149
150 /**
151 * The compiled JavaScript function source, or the empty string
152 * if the template hasn't been compiled yet.
153 */
154 readonly source: string;
155
156 constructor(text: string, opts?: Options);
157
158 /**
159 * Compiles the EJS template.
160 */
161 compile(): TemplateFunction | AsyncTemplateFunction | ClientFunction | AsyncClientFunction;
162}
163
164export namespace Template {
165 enum modes {
166 EVAL = "eval",
167 ESCAPED = "escaped",
168 RAW = "raw",
169 COMMENT = "comment",
170 LITERAL = "literal",
171 }
172}
173
174export interface Data {
175 [name: string]: any;
176}
177
178/**
179 * This type of function is returned from `compile`, when
180 * `Options.client` is false.
181 *
182 * @param data an object of data to be passed into the template.
183 * @return Return type depends on `Options.async`.
184 */
185export type TemplateFunction = (data?: Data) => string;
186
187/**
188 * This type of function is returned from `compile`, when
189 * `Options.client` is false.
190 *
191 * @param data an object of data to be passed into the template.
192 * @return Return type depends on `Options.async`.
193 */
194export type AsyncTemplateFunction = (data?: Data) => Promise<string>;
195
196/**
197 * This type of function is returned from `compile`, when
198 * `Options.client` is true.
199 *
200 * This is also used internally to generate a `TemplateFunction`.
201 *
202 * @param locals an object of data to be passed into the template.
203 * The name of this variable is adjustable through `localsName`.
204 *
205 * @param escape callback used to escape variables
206 * @param include callback used to include files at runtime with `include()`
207 * @param rethrow callback used to handle and rethrow errors
208 *
209 * @return Return type depends on `Options.async`.
210 */
211export type ClientFunction = (
212 locals?: Data,
213 escape?: EscapeCallback,
214 include?: IncludeCallback,
215 rethrow?: RethrowCallback,
216) => string;
217
218/**
219 * This type of function is returned from `compile`, when
220 * `Options.client` is true.
221 *
222 * This is also used internally to generate a `TemplateFunction`.
223 *
224 * @param locals an object of data to be passed into the template.
225 * The name of this variable is adjustable through `localsName`.
226 *
227 * @param escape callback used to escape variables
228 * @param include callback used to include files at runtime with `include()`
229 * @param rethrow callback used to handle and rethrow errors
230 *
231 * @return Return type depends on `Options.async`.
232 */
233export type AsyncClientFunction = (
234 locals?: Data,
235 escape?: EscapeCallback,
236 include?: IncludeCallback,
237 rethrow?: RethrowCallback,
238) => Promise<string>;
239
240/**
241 * Escapes a string using HTML/XML escaping rules.
242 *
243 * Returns the empty string for `null` or `undefined`.
244 *
245 * @param markup Input string
246 * @return Escaped string
247 */
248export type EscapeCallback = (markup?: any) => string;
249
250/**
251 * This type of callback is used when `Options.compileDebug`
252 * is `true`, and an error in the template is thrown.
253 *
254 * By default it is used to rethrow an error in a better-formatted way.
255 *
256 * @param err Error object
257 * @param str full EJS source
258 * @param filename file name of the EJS source
259 * @param lineno line number of the error
260 */
261export type RethrowCallback = (
262 err: Error,
263 str: string,
264 filename: string | null | undefined,
265 lineno: number,
266 esc: EscapeCallback,
267) => never;
268
269/**
270 * The callback called by `ClientFunction` to include files at runtime with `include()`
271 *
272 * @param path Path to be included
273 * @param data Data passed to the template
274 * @return Contents of the file requested
275 */
276export type IncludeCallback = (path: string, data?: Data) => string;
277
278/**
279 * An object where {@link filename} is the final parsed path or {@link template} is the content of the included template
280 */
281export type IncluderResult = { filename: string; template?: never } | { template: string; filename?: never };
282
283/**
284 * @param originalPath the path as it appears in the include statement
285 * @param parsedPath the previously resolved path
286 *
287 * @return An {@link IncluderResult} object containing the filename or template data.
288 */
289export type IncluderCallback = (originalPath: string, parsedPath: string) => IncluderResult;
290
291export interface Options {
292 /**
293 * Log the generated JavaScript source for the EJS template to the console.
294 *
295 * @default false
296 */
297 debug?: boolean | undefined;
298
299 /**
300 * Include additional runtime debugging information in generated template
301 * functions.
302 *
303 * @default true
304 */
305 compileDebug?: boolean | undefined;
306
307 /**
308 * Whether or not to use `with () {}` construct in the generated template
309 * functions. If set to `false`, data is still accessible through the object
310 * whose name is specified by `ejs.localsName` (defaults to `locals`).
311 *
312 * @default true
313 */
314 _with?: boolean | undefined;
315
316 /**
317 * Whether to run in strict mode or not.
318 * Enforces `_with=false`.
319 *
320 * @default false
321 */
322 strict?: boolean | undefined;
323
324 /**
325 * An array of local variables that are always destructured from `localsName`,
326 * available even in strict mode.
327 *
328 * @default []
329 */
330 destructuredLocals?: string[] | undefined;
331
332 /**
333 * Remove all safe-to-remove whitespace, including leading and trailing
334 * whitespace. It also enables a safer version of `-%>` line slurping for all
335 * scriptlet tags (it does not strip new lines of tags in the middle of a
336 * line).
337 *
338 * @default false
339 */
340 rmWhitespace?: boolean | undefined;
341
342 /**
343 * Whether or not to compile a `ClientFunction` that can be rendered
344 * in the browser without depending on ejs.js. Otherwise, a `TemplateFunction`
345 * will be compiled.
346 *
347 * @default false
348 */
349 client?: boolean | undefined;
350
351 /**
352 * The escaping function used with `<%=` construct. It is used in rendering
353 * and is `.toString()`ed in the generation of client functions.
354 *
355 * @default ejs.escapeXML
356 */
357 escape?: EscapeCallback | undefined;
358
359 /**
360 * The filename of the template. Required for inclusion and caching unless
361 * you are using `renderFile`. Also used for error reporting.
362 *
363 * @default undefined
364 */
365 filename?: string | undefined;
366
367 /**
368 * The path to templates root(s). When this is set, absolute paths for includes
369 * (/filename.ejs) will be relative to the templates root(s).
370 *
371 * @default undefined
372 */
373 root?: string[] | string | undefined;
374
375 /**
376 * The opening delimiter for all statements. This allows you to clearly delinate
377 * the difference between template code and existing delimiters. (It is recommended
378 * to synchronize this with the closeDelimiter property.)
379 *
380 * @default ejs.openDelimiter
381 */
382 openDelimiter?: string | undefined;
383
384 /**
385 * The closing delimiter for all statements. This allows to to clearly delinate
386 * the difference between template code and existing delimiters. (It is recommended
387 * to synchronize this with the openDelimiter property.)
388 *
389 * @default ejs.closeDelimiter
390 */
391 closeDelimiter?: string | undefined;
392
393 /**
394 * Character to use with angle brackets for open/close
395 * @default '%'
396 */
397 delimiter?: string | undefined;
398
399 /**
400 * Whether or not to enable caching of template functions. Beware that
401 * the options of compilation are not checked as being the same, so
402 * special handling is required if, for example, you want to cache client
403 * and regular functions of the same file.
404 *
405 * Requires `filename` to be set. Only works with rendering function.
406 *
407 * @default false
408 */
409 cache?: boolean | undefined;
410
411 /**
412 * The Object to which `this` is set during rendering.
413 *
414 * @default this
415 */
416 context?: any;
417
418 /**
419 * Whether or not to create an async function instead of a regular function.
420 * This requires language support.
421 *
422 * @default false
423 */
424 async?: boolean | undefined;
425
426 /**
427 * Make sure to set this to 'false' in order to skip UglifyJS parsing,
428 * when using ES6 features (`const`, etc) as UglifyJS doesn't understand them.
429 * @default true
430 */
431 beautify?: boolean | undefined;
432
433 /**
434 * Name to use for the object storing local variables when not using `with` or destructuring.
435 *
436 * @default ejs.localsName
437 */
438 localsName?: string | undefined;
439
440 /** Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags. */
441 outputFunctionName?: string | undefined;
442
443 /**
444 * An array of paths to use when resolving includes with relative paths
445 */
446 views?: string[] | undefined;
447
448 /**
449 * Custom function to handle EJS includes
450 */
451 includer?: IncluderCallback;
452}
453
454export interface Cache {
455 /**
456 * Cache the intermediate JavaScript function for a template.
457 *
458 * @param key key for caching
459 * @param val cached function
460 */
461 set(key: string, val: TemplateFunction): void;
462
463 /**
464 * Get the cached intermediate JavaScript function for a template.
465 *
466 * @param key key for caching
467 */
468 get(key: string): TemplateFunction | undefined;
469
470 /**
471 * Clear the entire cache.
472 */
473 reset(): void;
474}