diff --git a/.eslintignore b/.eslintignore index 0d77eda..3868b08 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1,3 @@ node_modules typings dist -deno_dist -src/*.deno.ts diff --git a/.github/workflows/size-limit.yml b/.github/workflows/size-limit.yml index d1c72c9..a4713d5 100644 --- a/.github/workflows/size-limit.yml +++ b/.github/workflows/size-limit.yml @@ -1,4 +1,4 @@ -name: 'size' +name: "size" on: pull_request: branches: @@ -10,9 +10,6 @@ jobs: CI_JOB_NUMBER: 1 steps: - uses: actions/checkout@v2 - - uses: denolib/setup-deno@v2 - with: - deno-version: v1.x - uses: andresz1/size-limit-action@v1.7.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.prettierignore b/.prettierignore index 4b411ce..6fb965e 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,5 +1,4 @@ dist -deno_dist coverage .rpt2_cache node_modules diff --git a/.travis.yml b/.travis.yml index 951a072..d39e1be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,17 +2,12 @@ language: node_js cache: directories: - ~/.npm - - "$HOME/.deno" notifications: email: false node_js: - "14" - "16" -before_install: # Install Deno - - curl -fsSL https://deno.land/x/install/install.sh | sh - - export PATH="$HOME/.deno/bin:$PATH" script: - - deno --version # Log the Deno version - npm run build && npm run test:prod after_success: - npm run travis-deploy-once "npm run report-coverage" diff --git a/README.md b/README.md index 0fe5042..9b47afa 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,6 @@ [![GitHub package.json version (master)](https://img.shields.io/github/package-json/v/eta-dev/eta/master?label=current%20version)](https://www.npmjs.com/package/eta) -[![deno module](https://img.shields.io/badge/deno-module-informational?logo=deno)](https://deno.land/x/eta) [![Travis](https://img.shields.io/travis/com/eta-dev/eta/master.svg)](https://travis-ci.com/eta-dev/eta) [![All Contributors][logo]](#contributors-) [![Coveralls](https://img.shields.io/coveralls/eta-dev/eta.svg)](https://coveralls.io/github/eta-dev/eta) @@ -261,7 +260,7 @@ To be added - [Docusaurus v2](https://v2.docusaurus.io): open-source documentation framework that uses Eta to generate a SSR build - [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api): Open source typescript api codegenerator from Swagger. Uses Eta as codegenerator by templates - [html-bundler-webpack-plugin](https://github.com/webdiscus/html-bundler-webpack-plugin): Webpack plugin make easily to bundle HTML pages from templates, source styles and scripts -- [SmartDeno](https://github.com/guildenstern70/SmartDeno): SmartDeno is an easy to setup web template using Deno & Oak +- [SmartDeno](https://github.com/guildenstern70/SmartDeno): SmartDeno is an easy to setup web template using Deno & Oak - [Add yours!](https://github.com/eta-dev/eta/edit/master/README.md) ## Contributors diff --git a/deno_dist/LICENSE b/deno_dist/LICENSE deleted file mode 100644 index c6734d9..0000000 --- a/deno_dist/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2023 Ben Gubler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deno_dist/README.md b/deno_dist/README.md deleted file mode 100644 index 0fe5042..0000000 --- a/deno_dist/README.md +++ /dev/null @@ -1,303 +0,0 @@ -

- -

- -

eta (Ξ·)

- -

- Documentation - - Chat - - RunKit Demo - - Playground -

- - - -[logo]: https://img.shields.io/badge/all_contributors-10-orange.svg "Number of contributors on All-Contributors" - - - - - -[![GitHub package.json version (master)](https://img.shields.io/github/package-json/v/eta-dev/eta/master?label=current%20version)](https://www.npmjs.com/package/eta) -[![deno module](https://img.shields.io/badge/deno-module-informational?logo=deno)](https://deno.land/x/eta) -[![Travis](https://img.shields.io/travis/com/eta-dev/eta/master.svg)](https://travis-ci.com/eta-dev/eta) -[![All Contributors][logo]](#contributors-) -[![Coveralls](https://img.shields.io/coveralls/eta-dev/eta.svg)](https://coveralls.io/github/eta-dev/eta) -[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://paypal.me/bengubler) - - - -**Summary** - -Eta is a lightweight and blazing fast embedded JS templating engine that works inside Node, Deno, and the browser. Created by the developers of [Squirrelly](https://squirrelly.js.org), it's written in TypeScript and emphasizes phenomenal performance, configurability, and low bundle size. - -### 🌟 Features - -- πŸ“¦ 0 dependencies -- πŸ’‘ 2.3KB minzipped; size restricted to <3KB forever with [size-limit](https://github.com/ai/size-limit) -- ⚑️ Written in TypeScript -- ✨ Deno support (+ Node and browser) -- πŸš€ Super Fast - - Check out [these benchmarks](https://raw.githack.com/eta-dev/eta/master/browser-tests/benchmark.html) -- πŸ”§ Configurable - - Plugins, custom delimiters, caching -- πŸ”¨ Powerful - - Precompilation, partials, async - - **Layout support**! - - ExpressJS support out-of-the-box -- πŸ”₯ Reliable - - Better quotes/comments support - - _ex._ `<%= someval + "string %>" %>` compiles correctly, while it fails with doT or EJS - - Great error reporting -- ⚑️ Exports ES Modules as well as UMD -- πŸ“ Easy template syntax - -## Eta vs other template engines - -
- - Eta vs EJS - - -Eta's syntax is very similar to EJS' (most templates should work with either engine), Eta has a similar API, and Eta and EJS share the same file-handling logic. Here are the differences between Eta and EJS: - -- Eta is more lightweight. Eta weighs less than **2.5KB gzipped**, while EJS is **4.4KB gzipped** -- Eta compiles and renders templates **_much_ faster than EJS**. Check out these benchmarks: https://rawgit.com/eta-dev/eta/master/browser-tests/benchmark.html -- Eta allows left whitespace control (with `-`), something that doesn't work in EJS because EJS uses `-` on the left side to indicate that the value shouldn't be escaped. Instead, Eta uses `~` to output a raw value -- Eta gives you more flexibility with delimeters -- you could set them to `{{` and `}}`, for example, while with EJS this isn't possible -- Eta adds plugin support -- Comments in Eta use `/* ... */` which allows commenting around template tags -- Eta parses strings correctly. _Example: `<%= "%>" %>` works in Eta, while it breaks in EJS_ -- Eta exposes Typescript types and distributes a UMD build -- Eta supports custom tag-type indicators. _Example: you could change `<%=` to `<%*`_ - -
- -
- - Eta vs doT.js - - -Eta and doT.js both allow embedded JavaScript, and [both have best-in-class performance](https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html) when compared to other template engines (though Eta is slightly faster with HTML-escaped templates). Here are some of the differences between Eta and doT.js: - -- Eta allows you to control how you strip preceding and trailing whitespace after tags. -- It's much simpler to set custom delimiters with Eta than doT -- you don't have to rewrite every configuration Regular Expression -- Eta supports plugins -- Eta supports async -- Eta parses strings and multi-line comments correctly. _Example: `<%= "%>" %>` works in Eta, while the equivalent breaks in doT_ -- Eta exposes Typescript types and distributes a UMD build -- Eta supports runtime partials and file-handling. - -
- -
- - Eta vs Handlebars - - -Eta and Handlebars are very different in some ways -- Eta is an embedded template engine, while Handlebars is a logic-less template engine. Here some additional differences between Eta and Handlebars: - -- Eta is more lightweight. Eta weighs less than **2.5KB gzipped**, while Handlebars is **~22KB gzipped** -- Eta compiles and renders templates **_much_ faster than Handlebars** -- around **7x faster**. Check out these benchmarks: https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html -- Eta allows you to set custom delimiters -- Eta supports plugins -- Eta exposes Typescript types and distributes a UMD build -- Custom tag-type indicators. _Example: you could change `<%=` to `<%*`_ -- With Eta, you don't need to register tons of helpers to do simple tasks like check if one value equals another value -- Note that Eta templates run as **trusted code** -- just like any other JavaScript you write.

If you are running user-defined/created templates on your machine, server, site, etc., you probably should go with a tool built for that purpose, like Handlebars. - -
- -
- - Eta vs ES6 Template Literals - - -Template literals are a super useful tool, especially for shortening simple string concatenation. But writing complete templates using template literals can quickly get out of hand. Here's a comparison of Eta and template literals: - -- Eta compiles templates into JavaScript functions that use string concatenation and have comparable performance with template literals -- Eta lets you control preceding and trailing whitespace around tags -- Eta gives you more flexibility with delimeters -- you could set them to `{{` and `}}`, for example, or set them to `${` and `}` to mimic template literals -- Eta supports plugins -- Eta supports comments with `/* ... */` syntax, just like in regular JavaScript. Template literals require you to stick a blank string after the comment: `/* ... */""`, which is much less readable -- To write conditionals inside template literals, you have to use the ternary operator. Add more conditions or nested conditionals, and it quickly becomes a nightmarish mess of `? ... : ... ? ... : ...`. Writing conditionals in Eta is much simpler and more readable -- Eta supports partials - -
- -## Why Eta? - -Simply put, Eta is super: super lightweight, super fast, super powerful, and super simple. Like with EJS, you don't have to worry about learning an entire new templating syntax. Just write JavaScript inside your templates. - -### Where did Eta's name come from? - -"Eta" means tiny in Esperanto. Plus, it can be used as an acronym for all sorts of cool phrases: "ECMAScript Template Awesomeness", "Embedded Templating Alternative", etc.... - -Additionally, Eta is a letter of the Greek alphabet (it stands for all sorts of cool things in various mathematical fields, including efficiency) and is three letters long (perfect for a file extension). - -## Integrations - -
- - Visual Studio Code - - -[@shadowtime2000](https://github.com/shadowtime2000) created [eta-vscode](https://marketplace.visualstudio.com/items?itemName=shadowtime2000.eta-vscode). - -
- -
- - ESLint - - -[eslint-plugin-eta](https://github.com/eta-dev/eslint-plugin-eta) was created to provide an ESLint processor so you can lint your Eta templates. - -
- -
- - CLI - - -An official Eta CLI exists called [etajs-cli](https://github.com/eta-dev/etajs-cli). - -
- -
- - Webpack - - -Currently there is no official Webpack integration but [@clshortfuse](https://github.com/clshortfuse) shared the loader he uses: - -```javascript -{ - loader: 'html-loader', - options: { - preprocessor(content, loaderContext) { - return eta.render(content, {}, { filename: loaderContext.resourcePath }); - }, - }, -} -``` - -
- -
- - Node-RED - - -To operate with Eta templates in Node-RED: [@ralphwetzel/node-red-contrib-eta](https://flows.nodered.org/node/@ralphwetzel/node-red-contrib-eta) - - image - -
- -## πŸ“œ Docs - -We know nobody reads through the long and boring documentation in the ReadMe anyway, so head over to the documentation website: - -πŸ“ [https://eta.js.org](https://eta.js.org) - -## πŸ““ Examples - -### Simple Template - -```javascript -import * as Eta from "eta"; -var myTemplate = "

My favorite kind of cake is: <%= it.favoriteCake %>

"; - -Eta.render(myTemplate, { favoriteCake: "Chocolate!" }); -// Returns: '

My favorite kind of cake is: Chocolate!

' -``` - -### Conditionals - -```ejs -<% if(it.somevalue === 1) { %> -Display this -<% } else { %> -Display this instead -<% } %> -``` - -### Loops - -```ejs - -``` - -### Partials - -```ejs -<%~ include('mypartial') %> -``` - -```ejs -<%~ includeFile('./footer') %> -``` - -```ejs -<%~ include('users', {users: it.users}) %> -``` - -## βœ”οΈ Tests - -Tests can be run with `npm test`. Multiple tests check that parsing, rendering, and compiling return expected results, formatting follows guidelines, and code coverage is at the expected level. - -## Resources - -To be added - -## Projects using `eta` - -- [Docusaurus v2](https://v2.docusaurus.io): open-source documentation framework that uses Eta to generate a SSR build -- [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api): Open source typescript api codegenerator from Swagger. Uses Eta as codegenerator by templates -- [html-bundler-webpack-plugin](https://github.com/webdiscus/html-bundler-webpack-plugin): Webpack plugin make easily to bundle HTML pages from templates, source styles and scripts -- [SmartDeno](https://github.com/guildenstern70/SmartDeno): SmartDeno is an easy to setup web template using Deno & Oak -- [Add yours!](https://github.com/eta-dev/eta/edit/master/README.md) - -## Contributors - -Made with ❀ by [@nebrelbug](https://github.com/eta-dev) and all these wonderful contributors ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): - - - - - - - - - - - - - - - - - - - - - -
Ben Gubler
Ben Gubler

πŸ’» πŸ’¬ πŸ“– ⚠️
Clite Tailor
Clite Tailor

πŸ€” πŸ’»
Ioan CHIRIAC
Ioan CHIRIAC

πŸ’» πŸ€”
Craig Morten
Craig Morten

πŸ’»
Rajan Tiwari
Rajan Tiwari

πŸ’‘
shadowtime2000
shadowtime2000

πŸ’» πŸ€” ⚠️
Hamza Hamidi
Hamza Hamidi

πŸ“–
Calum Knott
Calum Knott

πŸ€”
nhaef
nhaef

πŸ’»
GΓΌn
GΓΌn

πŸ’»
- - - - - - -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! - -## Credits - -- Async support and file handling were added based on code from [EJS](https://github.com/mde/ejs), which is licensed under the Apache-2.0 license. Code was modified and refactored to some extent. -- Syntax and some parts of compilation are heavily based off EJS, Nunjucks, and doT. diff --git a/deno_dist/browser.ts b/deno_dist/browser.ts deleted file mode 100644 index 9419d96..0000000 --- a/deno_dist/browser.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Eta as EtaCore } from "./core.ts"; - -export class Eta extends EtaCore {} diff --git a/deno_dist/compile-string.ts b/deno_dist/compile-string.ts deleted file mode 100644 index fa16fa7..0000000 --- a/deno_dist/compile-string.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* TYPES */ - -import type { Options } from "./config.ts"; -import type { AstObject } from "./parse.ts"; -import type { Eta } from "./core.ts"; - -/* END TYPES */ - -/** - * Compiles a template string to a function string. Most often users just use `compile()`, which calls `compileToString` and creates a new function using the result - */ - -export function compileToString( - this: Eta, - str: string, - options?: Partial, -): string { - const config = this.config; - const isAsync = options && options.async; - - const buffer: Array = this.parse.call(this, str); - - // note: when the include function passes through options, the only parameter that matters is the filepath parameter - let res = ` -let include = (template, data) => this.render(template, data, options); -let includeAsync = (template, data) => this.renderAsync(template, data, options); - -let __eta = {res: "", e: this.escapeFunction, f: this.filterFunction}; - -function layout(path, data) { - __eta.layout = path; - __eta.layoutData = data; -} - -${config.useWith ? "with(" + config.varName + "||{}){" : ""} - -${compileBody.call(this, buffer)} - -if (__eta.layout) { - __eta.res = ${ - isAsync ? "await includeAsync" : "include" - } (__eta.layout, {body: __eta.res, ...__eta.layoutData}); -} - -${config.useWith ? "}" : ""} - -return __eta.res; -`; - - if (config.plugins) { - for (let i = 0; i < config.plugins.length; i++) { - const plugin = config.plugins[i]; - if (plugin.processFnString) { - res = plugin.processFnString(res, config); - } - } - } - - return res; -} - -/** - * Loops through the AST generated by `parse` and transform each item into JS calls - * - * **Example** - * - * ```js - * let templateAST = ['Hi ', { val: 'it.name', t: 'i' }] - * compileBody.call(Eta, templateAST) - * // => "__eta.res+='Hi '\n__eta.res+=__eta.e(it.name)\n" - * ``` - */ - -function compileBody(this: Eta, buff: Array) { - const config = this.config; - - let i = 0; - const buffLength = buff.length; - let returnStr = ""; - - for (i; i < buffLength; i++) { - const currentBlock = buff[i]; - if (typeof currentBlock === "string") { - const str = currentBlock; - - // we know string exists - returnStr += "__eta.res+='" + str + "'\n"; - } else { - const type = currentBlock.t; // "r", "e", or "i" - let content = currentBlock.val || ""; - - if (type === "r") { - // raw - - if (config.filter) { - content = "__eta.f(" + content + ")"; - } - - returnStr += "__eta.res+=" + content + "\n"; - } else if (type === "i") { - // interpolate - - if (config.filter) { - content = "__eta.f(" + content + ")"; - } - - if (config.autoEscape) { - content = "__eta.e(" + content + ")"; - } - - returnStr += "__eta.res+=" + content + "\n"; - } else if (type === "e") { - // execute - returnStr += content + "\n"; - } - } - } - - return returnStr; -} diff --git a/deno_dist/compile.ts b/deno_dist/compile.ts deleted file mode 100644 index c4550a2..0000000 --- a/deno_dist/compile.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { EtaError } from "./err.ts"; - -/* TYPES */ -import type { Eta } from "./core.ts"; -import type { EtaConfig, Options } from "./config.ts"; - -export type TemplateFunction = ( - this: Eta, - data?: object, - options?: Partial, -) => string; -/* END TYPES */ - -const AsyncFunction = async function () {}.constructor; // eslint-disable-line @typescript-eslint/no-empty-function - -/** - * Takes a template string and returns a template function that can be called with (data, config) - * - * @param str - The template string - * @param config - A custom configuration object (optional) - */ - -export function compile( - this: Eta, - str: string, - options?: Partial, -): TemplateFunction { - const config: EtaConfig = this.config; - - /* ASYNC HANDLING (modified from mde/ejs) */ - const ctor = options && options.async - ? (AsyncFunction as FunctionConstructor) - : Function; - /* END ASYNC HANDLING */ - - try { - return new ctor( - config.varName, - "options", - this.compileToString.call(this, str, options), - ) as TemplateFunction; // eslint-disable-line no-new-func - } catch (e) { - if (e instanceof SyntaxError) { - throw new EtaError( - "Bad template syntax\n\n" + - e.message + - "\n" + - Array(e.message.length + 1).join("=") + - "\n" + - this.compileToString.call(this, str, options) + - "\n", // This will put an extra newline before the callstack for extra readability - ); - } else { - throw e; - } - } -} diff --git a/deno_dist/config.ts b/deno_dist/config.ts deleted file mode 100644 index abe728f..0000000 --- a/deno_dist/config.ts +++ /dev/null @@ -1,88 +0,0 @@ -/* TYPES */ - -type trimConfig = "nl" | "slurp" | false; - -export interface Options { - /** Compile to async function */ - async?: boolean; - - /** Absolute path to template file */ - filepath?: string; -} - -export interface EtaConfig { - /** Whether or not to automatically XML-escape interpolations. Default true */ - autoEscape: boolean; - - /** Configure automatic whitespace trimming. Default `[false, 'nl']` */ - autoTrim: trimConfig | [trimConfig, trimConfig]; - - /** Whether or not to cache templates if `name` or `filename` is passed */ - cache: boolean; - - // TODO: Mention that Eta can't use "-" or "_" for config.parse since they're used for whitespace slurping. - - /** Parsing options */ - parse: { - /** Which prefix to use for evaluation. Default `""` */ - exec: string; - - /** Which prefix to use for interpolation. Default `"="` */ - interpolate: string; - - /** Which prefix to use for raw interpolation. Default `"~"` */ - raw: string; - }; - - /** Array of plugins */ - plugins: Array< - { - processFnString?: Function; - processAST?: Function; - processTemplate?: Function; - } - >; - - /** Holds cache of resolved filepaths. Set to `false` to disable. */ - filepathCache?: Record | false; - - /** Apply a filter function defined on the class to every interpolation or raw interpolation */ - filter?: boolean; - - /** Remove all safe-to-remove whitespace */ - rmWhitespace: boolean; - - /** Delimiters: by default `['<%', '%>']` */ - tags: [string, string]; - - /** Make data available on the global object instead of varName */ - useWith?: boolean; - - /** Name of the data object. Default `it` */ - varName: string; - - /** Directory that contains templates */ - views?: string; -} - -/* END TYPES */ - -/** Eta's base (global) configuration */ -const defaultConfig: EtaConfig = { - autoEscape: true, - autoTrim: [false, "nl"], - cache: false, - filepathCache: {}, - parse: { - exec: "", - interpolate: "=", - raw: "~", - }, - plugins: [], - rmWhitespace: false, - tags: ["<%", "%>"], - useWith: false, - varName: "it", -}; - -export { defaultConfig }; diff --git a/deno_dist/core.ts b/deno_dist/core.ts deleted file mode 100644 index 65d8725..0000000 --- a/deno_dist/core.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { defaultConfig } from "./config.ts"; -import { Cacher } from "./storage.ts"; -import { parse } from "./parse.ts"; -import { compile } from "./compile.ts"; -import { compileToString } from "./compile-string.ts"; -import { - render, - renderAsync, - renderString, - renderStringAsync, -} from "./render.ts"; -import { TemplateFunction } from "./compile.ts"; -import { XMLEscape } from "./utils.ts"; - -/* TYPES */ -import type { EtaConfig, Options } from "./config.ts"; -/* END TYPES */ - -export class Eta { - constructor(customConfig?: Partial) { - if (customConfig) { - this.config = { ...defaultConfig, ...customConfig }; - } else { - this.config = { ...defaultConfig }; - } - } - - config: EtaConfig; - - parse = parse; - compile = compile; - compileToString = compileToString; - render = render; - renderAsync = renderAsync; - renderString = renderString; - renderStringAsync = renderStringAsync; - - templatesSync = new Cacher({}); - templatesAsync = new Cacher({}); - - escapeFunction = XMLEscape; - filterFunction = null; - - // resolvePath takes a relative path from the "views" directory - resolvePath: - | null - | ((this: Eta, template: string, options?: Partial) => string) = - null; - readFile: null | ((this: Eta, path: string) => string) = null; - - // METHODS - - configure(customConfig: Partial) { - this.config = { ...this.config, ...customConfig }; - } - - withConfig(customConfig: Partial) { - return { ...this, config: { ...this.config, ...customConfig } }; - } - - loadTemplate( - name: string, - template: string | TemplateFunction, // template string or template function - options?: { async: boolean }, - ): void { - let templates = options && options.async - ? this.templatesAsync - : this.templatesSync; - - if (typeof template === "string") { - templates.define(name, this.compile(template, options)); - } else { - if (template.constructor.name === "AsyncFunction") { - templates = this.templatesAsync; - } - - templates.define(name, template); - } - } -} diff --git a/deno_dist/err.ts b/deno_dist/err.ts deleted file mode 100644 index 8a71c18..0000000 --- a/deno_dist/err.ts +++ /dev/null @@ -1,31 +0,0 @@ -export class EtaError extends Error { - constructor(message: string) { - super(message); - this.name = "Eta Error"; - } -} - -/** - * Throws an EtaError with a nicely formatted error and message showing where in the template the error occurred. - */ - -// TODO: make more advanced - -export function ParseErr(message: string, str: string, indx: number): void { - const whitespace = str.slice(0, indx).split(/\n/); - - const lineNo = whitespace.length; - const colNo = whitespace[lineNo - 1].length + 1; - message += " at line " + - lineNo + - " col " + - colNo + - ":\n\n" + - " " + - str.split(/\n/)[lineNo - 1] + - "\n" + - " " + - Array(colNo).join(" ") + - "^"; - throw new EtaError(message); -} diff --git a/deno_dist/file-handling.ts b/deno_dist/file-handling.ts deleted file mode 100644 index 078e5d2..0000000 --- a/deno_dist/file-handling.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { EtaError } from "./err.ts"; - -import * as path from "node:node:path"; - -import * as fs from "node:node:fs"; - -/* TYPES */ -import type { Eta as EtaCore } from "./core.ts"; -import type { Options } from "./config.ts"; -/* END TYPES */ - -export function readFile(this: EtaCore, path: string): string { - let res = ""; - - try { - res = fs.readFileSync(path, "utf8"); - // eslint-disable-line @typescript-eslint/no-explicit-any - } catch (err: any) { - if (err?.code === "ENOENT") { - throw new EtaError(`Could not find template: ${path}`); - } else { - throw err; - } - } - - return res; -} - -export function resolvePath( - this: EtaCore, - template: string, - options?: Partial, -): string { - let resolvedFilePath = ""; - - template += path.extname(template) ? "" : ".eta"; - - const views = this.config.views; - - if (!views) { - throw new EtaError("Views directory is not defined"); - } - - const baseFilePath = options && options.filepath; - - // if the file was included from another template - if (baseFilePath) { - // check the cache - if (this.config.filepathCache && this.config.filepathCache[baseFilePath]) { - return this.config.filepathCache[baseFilePath]; - } - - const absolutePathTest = absolutePathRegExp.exec(template); - - if (absolutePathTest && absolutePathTest.length) { - const formattedPath = template.replace(/^\/*/, ""); - resolvedFilePath = path.join(views, formattedPath); - } else { - resolvedFilePath = path.join(path.dirname(baseFilePath), template); - } - } else { - resolvedFilePath = path.join(views, template); - } - - if (dirIsChild(views, resolvedFilePath)) { - // add resolved path to the cache - if (baseFilePath && this.config.filepathCache) { - this.config.filepathCache[baseFilePath] = resolvedFilePath; - } - - return resolvedFilePath; - } else { - throw new EtaError(`Template '${template}' is not in the views directory`); - } -} - -function dirIsChild(parent: string, dir: string) { - const relative = path.relative(parent, dir); - return relative && !relative.startsWith("..") && !path.isAbsolute(relative); -} - -const absolutePathRegExp = /^\\|^\//; diff --git a/deno_dist/mod.ts b/deno_dist/mod.ts deleted file mode 100644 index f0104e7..0000000 --- a/deno_dist/mod.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Eta as EtaCore } from "./core.js"; -import { readFile, resolvePath } from "./file-handling.js"; - -export class Eta extends EtaCore { - readFile = readFile; - - resolvePath = resolvePath; -} diff --git a/deno_dist/parse.ts b/deno_dist/parse.ts deleted file mode 100644 index 99f24df..0000000 --- a/deno_dist/parse.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { ParseErr } from "./err.ts"; -import { trimWS } from "./utils.ts"; - -/* TYPES */ - -import type { Eta } from "./core.ts"; - -export type TagType = "r" | "e" | "i" | ""; - -export interface TemplateObject { - t: TagType; - val: string; -} - -export type AstObject = string | TemplateObject; - -/* END TYPES */ - -const templateLitReg = - /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g; - -const singleQuoteReg = /'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g; - -const doubleQuoteReg = /"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g; - -/** Escape special regular expression characters inside a string */ - -function escapeRegExp(string: string) { - // From MDN - return string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string -} - -export function parse(this: Eta, str: string): Array { - const config = this.config; - - let buffer: Array = []; - let trimLeftOfNextStr: string | false = false; - let lastIndex = 0; - const parseOptions = config.parse; - - if (config.plugins) { - for (let i = 0; i < config.plugins.length; i++) { - const plugin = config.plugins[i]; - if (plugin.processTemplate) { - str = plugin.processTemplate(str, config); - } - } - } - - /* Adding for EJS compatibility */ - if (config.rmWhitespace) { - // Code taken directly from EJS - // Have to use two separate replaces here as `^` and `$` operators don't - // work well with `\r` and empty lines don't work well with the `m` flag. - // Essentially, this replaces the whitespace at the beginning and end of - // each line and removes multiple newlines. - str = str.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, ""); - } - /* End rmWhitespace option */ - - templateLitReg.lastIndex = 0; - singleQuoteReg.lastIndex = 0; - doubleQuoteReg.lastIndex = 0; - - function pushString(strng: string, shouldTrimRightOfString?: string | false) { - if (strng) { - // if string is truthy it must be of type 'string' - - strng = trimWS( - strng, - config, - trimLeftOfNextStr, // this will only be false on the first str, the next ones will be null or undefined - shouldTrimRightOfString, - ); - - if (strng) { - // replace \ with \\, ' with \' - // we're going to convert all CRLF to LF so it doesn't take more than one replace - - strng = strng.replace(/\\|'/g, "\\$&").replace(/\r\n|\n|\r/g, "\\n"); - - buffer.push(strng); - } - } - } - - const prefixes = [ - parseOptions.exec, - parseOptions.interpolate, - parseOptions.raw, - ].reduce(function ( - accumulator, - prefix, - ) { - if (accumulator && prefix) { - return accumulator + "|" + escapeRegExp(prefix); - } else if (prefix) { - // accumulator is falsy - return escapeRegExp(prefix); - } else { - // prefix and accumulator are both falsy - return accumulator; - } - }, ""); - - const parseOpenReg = new RegExp( - escapeRegExp(config.tags[0]) + "(-|_)?\\s*(" + prefixes + ")?\\s*", - "g", - ); - - const parseCloseReg = new RegExp( - "'|\"|`|\\/\\*|(\\s*(-|_)?" + escapeRegExp(config.tags[1]) + ")", - "g", - ); - - let m; - - while ((m = parseOpenReg.exec(str))) { - const precedingString = str.slice(lastIndex, m.index); - - lastIndex = m[0].length + m.index; - - const wsLeft = m[1]; - const prefix = m[2] || ""; // by default either ~, =, or empty - - pushString(precedingString, wsLeft); - - parseCloseReg.lastIndex = lastIndex; - let closeTag; - let currentObj: AstObject | false = false; - - while ((closeTag = parseCloseReg.exec(str))) { - if (closeTag[1]) { - const content = str.slice(lastIndex, closeTag.index); - - parseOpenReg.lastIndex = lastIndex = parseCloseReg.lastIndex; - - trimLeftOfNextStr = closeTag[2]; - - const currentType: TagType = prefix === parseOptions.exec - ? "e" - : prefix === parseOptions.raw - ? "r" - : prefix === parseOptions.interpolate - ? "i" - : ""; - - currentObj = { t: currentType, val: content }; - break; - } else { - const char = closeTag[0]; - if (char === "/*") { - const commentCloseInd = str.indexOf("*/", parseCloseReg.lastIndex); - - if (commentCloseInd === -1) { - ParseErr("unclosed comment", str, closeTag.index); - } - parseCloseReg.lastIndex = commentCloseInd; - } else if (char === "'") { - singleQuoteReg.lastIndex = closeTag.index; - - const singleQuoteMatch = singleQuoteReg.exec(str); - if (singleQuoteMatch) { - parseCloseReg.lastIndex = singleQuoteReg.lastIndex; - } else { - ParseErr("unclosed string", str, closeTag.index); - } - } else if (char === '"') { - doubleQuoteReg.lastIndex = closeTag.index; - const doubleQuoteMatch = doubleQuoteReg.exec(str); - - if (doubleQuoteMatch) { - parseCloseReg.lastIndex = doubleQuoteReg.lastIndex; - } else { - ParseErr("unclosed string", str, closeTag.index); - } - } else if (char === "`") { - templateLitReg.lastIndex = closeTag.index; - const templateLitMatch = templateLitReg.exec(str); - if (templateLitMatch) { - parseCloseReg.lastIndex = templateLitReg.lastIndex; - } else { - ParseErr("unclosed string", str, closeTag.index); - } - } - } - } - if (currentObj) { - buffer.push(currentObj); - } else { - ParseErr("unclosed tag", str, m.index + precedingString.length); - } - } - - pushString(str.slice(lastIndex, str.length), false); - - if (config.plugins) { - for (let i = 0; i < config.plugins.length; i++) { - const plugin = config.plugins[i]; - if (plugin.processAST) { - buffer = plugin.processAST(buffer, config); - } - } - } - - return buffer; -} diff --git a/deno_dist/render.ts b/deno_dist/render.ts deleted file mode 100644 index f72f44b..0000000 --- a/deno_dist/render.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { EtaError } from "./err.ts"; - -/* TYPES */ -import type { Options } from "./config.ts"; -import type { TemplateFunction } from "./compile.ts"; -import type { Eta } from "./core.ts"; -/* END TYPES */ - -function handleCache( - this: Eta, - template: string, - options: Partial, -): TemplateFunction { - const templateStore = options && options.async - ? this.templatesAsync - : this.templatesSync; - - if (this.resolvePath && this.readFile && !template.startsWith("@")) { - const templatePath = options.filepath as string; - - const cachedTemplate = templateStore.get(templatePath); - - if (this.config.cache && cachedTemplate) { - return cachedTemplate; - } else { - const templateString = this.readFile(templatePath); - - const templateFn = this.compile(templateString, options); - - if (this.config.cache) templateStore.define(templatePath, templateFn); - - return templateFn; - } - } else { - const cachedTemplate = templateStore.get(template); - - if (cachedTemplate) { - return cachedTemplate; - } else { - throw new EtaError("Failed to get template '" + template + "'"); - } - } -} - -export function render( - this: Eta, - template: string | TemplateFunction, // template name or template function - data: object, - meta?: { filepath: string }, -): string { - let templateFn: TemplateFunction; - const options = { ...meta, async: false }; - - if (typeof template === "string") { - if (this.resolvePath && this.readFile && !template.startsWith("@")) { - options.filepath = this.resolvePath(template, options); - } - - templateFn = handleCache.call(this, template, options); - } else { - templateFn = template; - } - - const res = templateFn.call(this, data, options); - - return res; -} - -export function renderAsync( - this: Eta, - template: string | TemplateFunction, // template name or template function - data: object, - meta?: { filepath: string }, -): Promise { - let templateFn: TemplateFunction; - const options = { ...meta, async: true }; - - if (typeof template === "string") { - if (this.resolvePath && this.readFile && !template.startsWith("@")) { - options.filepath = this.resolvePath(template, options); - } - - templateFn = handleCache.call(this, template, options); - } else { - templateFn = template; - } - - const res = templateFn.call(this, data, options); - - // Return a promise - return new Promise(function (resolve: Function, reject: Function) { - try { - resolve(res); - } catch (err) { - reject(err); - } - }); -} - -export function renderString( - this: Eta, - template: string, - data: object, -): string { - const templateFn = this.compile(template, { async: false }); - - return render.call(this, templateFn, data); -} - -export function renderStringAsync( - this: Eta, - template: string, - data: object, -): Promise { - const templateFn = this.compile(template, { async: true }); - - return renderAsync.call(this, templateFn, data); -} diff --git a/deno_dist/storage.ts b/deno_dist/storage.ts deleted file mode 100644 index 6e740bd..0000000 --- a/deno_dist/storage.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Handles storage and accessing of values - * - * In this case, we use it to store compiled template functions - * Indexed by their `name` or `filename` - */ - -export class Cacher { - constructor(private cache: Record) {} - define(key: string, val: T): void { - this.cache[key] = val; - } - get(key: string): T { - return this.cache[key]; - } - remove(key: string): void { - delete this.cache[key]; - } - reset(): void { - this.cache = {}; - } - load(cacheObj: Record): void { - this.cache = { ...this.cache, ...cacheObj }; - } -} diff --git a/deno_dist/utils.ts b/deno_dist/utils.ts deleted file mode 100644 index 1001821..0000000 --- a/deno_dist/utils.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type { EtaConfig } from "./config.ts"; - -/** - * Takes a string within a template and trims it, based on the preceding tag's whitespace control and `config.autoTrim` - */ - -export function trimWS( - str: string, - config: EtaConfig, - wsLeft: string | false, - wsRight?: string | false, -): string { - let leftTrim; - let rightTrim; - - if (Array.isArray(config.autoTrim)) { - // Slightly confusing, - // but _}} will trim the left side of the following string - leftTrim = config.autoTrim[1]; - rightTrim = config.autoTrim[0]; - } else { - leftTrim = rightTrim = config.autoTrim; - } - - if (wsLeft || wsLeft === false) { - leftTrim = wsLeft; - } - - if (wsRight || wsRight === false) { - rightTrim = wsRight; - } - - if (!rightTrim && !leftTrim) { - return str; - } - - if (leftTrim === "slurp" && rightTrim === "slurp") { - return str.trim(); - } - - if (leftTrim === "_" || leftTrim === "slurp") { - // full slurp - str = str.trimStart(); - } else if (leftTrim === "-" || leftTrim === "nl") { - // nl trim - str = str.replace(/^(?:\r\n|\n|\r)/, ""); - } - - if (rightTrim === "_" || rightTrim === "slurp") { - // full slurp - str = str.trimEnd(); - } else if (rightTrim === "-" || rightTrim === "nl") { - // nl trim - str = str.replace(/(?:\r\n|\n|\r)$/, ""); - } - - return str; -} - -/** - * A map of special HTML characters to their XML-escaped equivalents - */ - -const escMap: { [key: string]: string } = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", -}; - -function replaceChar(s: string): string { - return escMap[s]; -} - -/** - * XML-escapes an input value after converting it to a string - * - * @param str - Input value (usually a string) - * @returns XML-escaped string - */ - -export function XMLEscape(str: unknown): string { - // To deal with XSS. Based on Escape implementations of Mustache.JS and Marko, then customized. - const newStr = String(str); - if (/[&<>"']/.test(newStr)) { - return newStr.replace(/[&<>"']/g, replaceChar); - } else { - return newStr; - } -} diff --git a/src/index.ts b/src/index.ts index 55952aa..f0104e7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,3 @@ -// @denoify-ignore - import { Eta as EtaCore } from "./core.js"; import { readFile, resolvePath } from "./file-handling.js"; diff --git a/src/mod.deno.ts b/src/mod.deno.ts deleted file mode 100644 index f0104e7..0000000 --- a/src/mod.deno.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Eta as EtaCore } from "./core.js"; -import { readFile, resolvePath } from "./file-handling.js"; - -export class Eta extends EtaCore { - readFile = readFile; - - resolvePath = resolvePath; -} diff --git a/test/deno/basic.spec.ts b/test/deno/basic.spec.ts deleted file mode 100644 index 1d24cfc..0000000 --- a/test/deno/basic.spec.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { assertEquals } from "https://deno.land/std@0.186.0/testing/asserts.ts"; -import * as eta from "../../deno_dist/mod.ts"; - -Deno.test("simple render", () => { - const t = `Hi <%=it.name%>`; - assertEquals(eta.render(t, { name: "Ben" }), "Hi Ben"); -}); diff --git a/test/deno/config.spec.ts b/test/deno/config.spec.ts deleted file mode 100644 index ff1e588..0000000 --- a/test/deno/config.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { assertEquals } from "https://deno.land/std@0.186.0/testing/asserts.ts"; -import * as eta from "../../deno_dist/mod.ts"; - -Deno.test("Renders a simple template with default env", () => { - const res = eta.render("hi <%= it.name %>", { name: "Ben" }, eta.defaultConfig); - - assertEquals(res, "hi Ben"); -}); - -Deno.test("Renders a simple template with custom tags", () => { - const res = eta.render("hi <<= it.name >>", { name: "Ben" }, { tags: ["<<", ">>"] }); - - assertEquals(res, "hi Ben"); -}); - -Deno.test("Renders a simple template without autoescaping", () => { - const res = eta.render("<%= it.html %>", { html: "

Hi

" }, { autoEscape: false }); - - assertEquals(res, "

Hi

"); // not escaped -}); diff --git a/test/deno/file-helpers.spec.ts b/test/deno/file-helpers.spec.ts deleted file mode 100644 index 02fffba..0000000 --- a/test/deno/file-helpers.spec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { assertEquals, assertThrows } from "https://deno.land/std@0.186.0/testing/asserts.ts"; -import * as path from "https://deno.land/std@0.186.0/path/mod.ts"; -const __dirname = new URL(".", import.meta.url).pathname; - -import { render, templates, compile } from "../../deno_dist/mod.ts"; - -templates.define("test-template", compile("Saluton <%=it.name%>")); - -Deno.test("include works", () => { - const renderedTemplate = render('<%~ include("test-template", it) %>', { name: "Ada" }); - - assertEquals(renderedTemplate, "Saluton Ada"); -}); - -Deno.test("includeFile works w/ filename prop", () => { - const renderedTemplate = render( - '<%~ includeFile("simple", it) %>', - { name: "Ada" }, - { filename: path.join(__dirname, "../templates/placeholder.eta") } - ); - - assertEquals(renderedTemplate, "Hi Ada"); -}); - -Deno.test('"E.includeFile" works with "views" array', () => { - const renderedTemplate = render( - '<%~ E.includeFile("randomtemplate", it) %>', - { user: "Ben" }, - { views: [path.join(__dirname, "../templates"), path.join(__dirname, "../othertemplates")] } - ); - - assertEquals(renderedTemplate, "This is a random template. Hey Ben"); -}); - -Deno.test('"includeFile" works with "views" array', () => { - const renderedTemplate = render( - '<%~ includeFile("randomtemplate", it) %>', - { user: "Ben" }, - { views: [path.join(__dirname, "../templates"), path.join(__dirname, "../othertemplates")] } - ); - - assertEquals(renderedTemplate, "This is a random template. Hey Ben"); -}); - -Deno.test('"includeFile" works with "views" string', () => { - const renderedTemplate = render( - '<%~ includeFile("randomtemplate", it) %>', - { user: "Ben" }, - { views: path.join(__dirname, "../othertemplates") } - ); - - assertEquals(renderedTemplate, "This is a random template. Hey Ben"); -}); - -Deno.test('throws if helper "includeFile" cannot find template', () => { - assertThrows( - () => { - render( - '<%~ includeFile("imaginary-template", it) %>', - { user: "Ben" }, - { views: [path.join(__dirname, "../templates"), path.join(__dirname, "../othertemplates")] } - ); - }, - Error, - `Could not find the template "imaginary-template". Paths tried: ${path.join( - __dirname, - "../templates" - )}/imaginary-template.eta,${path.join(__dirname, "../othertemplates")}/imaginary-template.eta` - ); -}); diff --git a/test/deno/helpers.spec.ts b/test/deno/helpers.spec.ts deleted file mode 100644 index 19ba6ef..0000000 --- a/test/deno/helpers.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { assertEquals, assertThrows } from "https://deno.land/std@0.186.0/testing/asserts.ts"; -import { render } from "../../deno_dist/mod.ts"; - -// SHOULD TEST COMMON ETA USAGE PATTERNS HERE - -const eachTemplate = ` -The Daugherty's have 5 kids: -
    -<% it.kids.forEach(function(kid){ %> -
  • <%= kid %>
  • -<% }) %> -
`; - -Deno.test("Loop over an array", () => { - const res = render(eachTemplate, { kids: ["Ben", "Polly", "Joel", "Phronsie", "Davie"] }); - - assertEquals( - res, - ` -The Daugherty's have 5 kids: -
    -
  • Ben
  • -
  • Polly
  • -
  • Joel
  • -
  • Phronsie
  • -
  • Davie
  • -
` - ); -}); - -Deno.test('throws if helper "include" cannot find template', () => { - assertThrows( - () => { - render('<%~ include("missing-template", it) %>', {}); - }, - Error, - 'Could not fetch template "missing-template"' - ); -});