refactor: import rollup

This commit is contained in:
harttle
2018-08-20 23:58:41 +08:00
parent 4ece4e208f
commit bc9d8f92af
82 changed files with 8589 additions and 3963 deletions
+9 -1
View File
@@ -1,3 +1,11 @@
{ {
"presets": ["es2015"] "presets": ["es2015"],
"plugins": [
["transform-runtime", {
"helpers": false,
"polyfill": false,
"regenerator": true,
"moduleName": "babel-runtime"
}]
]
} }
+2 -1
View File
@@ -10,6 +10,7 @@
"promise" "promise"
], ],
"rules": { "rules": {
"no-var": 2 "no-var": 2,
"prefer-const": 2
} }
} }
-1
View File
@@ -1,4 +1,3 @@
/coverage /coverage
/src
/test /test
.* .*
+2 -3
View File
@@ -1,9 +1,8 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html>
<head> <head>
<meta charset="UTF-8"> <title>liquidjs for the browser</title>
<title></title>
<script src="../../dist/liquid.js"></script> <script src="../../dist/liquid.js"></script>
</head> </head>
+4 -3
View File
@@ -1,10 +1,11 @@
const Liquid = require('../..') // const Liquid = require('../..')
const Liquid = require('../../dist/liquid.common.js')
let engine = new Liquid({ const engine = new Liquid({
root: __dirname, root: __dirname,
extname: '.liquid' extname: '.liquid'
}) })
let ctx = { const ctx = {
todos: ['fork and clone', 'make it better', 'make a pull request'], todos: ['fork and clone', 'make it better', 'make a pull request'],
title: 'Welcome to liquidjs!' title: 'Welcome to liquidjs!'
} }
+3738
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+3552 -2578
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+14 -18
View File
@@ -2,16 +2,14 @@
"name": "liquidjs", "name": "liquidjs",
"version": "5.3.0-0", "version": "5.3.0-0",
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.", "description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
"main": "build/index.js", "main": "dist/liquid.common.js",
"module": "src/index.js",
"scripts": { "scripts": {
"lint": "eslint .", "lint": "eslint src/ test/",
"test": "mocha --require babel-core/register --recursive", "test": "mocha --require babel-core/register --recursive",
"coverage": "nyc report --require babel-core/register mocha test/ --recursive ", "coverage": "nyc report --require babel-core/register mocha test/ --recursive ",
"coveralls": "nyc report --reporter=text-lcov --require babel-core/register mocha test/ --recursive | coveralls", "coveralls": "nyc report --reporter=text-lcov --require babel-core/register mocha test/ --recursive | coveralls",
"dist": "npm run babelify && npm run browserify && npm run uglify", "dist": "rollup -c && ls -lh dist",
"babelify": "babel src -d build",
"browserify": "browserify src/index.js -s Liquid --ignore path -t [ babelify --presets [ es2015 ] ] > dist/liquid.js",
"uglify": "uglifyjs dist/liquid.js --compress warnings=false --mangle toplevel --output dist/liquid.min.js",
"demo:browser": "echo open http://localhost:8080/demo/browser && http-server -c-1", "demo:browser": "echo open http://localhost:8080/demo/browser && http-server -c-1",
"demo:nodejs": "node ./demo/nodejs/index.js", "demo:nodejs": "node ./demo/nodejs/index.js",
"demo:express": "cd ./demo/express/ && npm start", "demo:express": "cd ./demo/express/ && npm start",
@@ -39,21 +37,15 @@
"url": "https://github.com/harttle/liquidjs/issues" "url": "https://github.com/harttle/liquidjs/issues"
}, },
"homepage": "https://github.com/harttle/liquidjs#readme", "homepage": "https://github.com/harttle/liquidjs#readme",
"dependencies": {
"resolve-url": "^0.2.1"
},
"browser": {
"fs": false
},
"devDependencies": { "devDependencies": {
"babel-core": "^6.26.3", "babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1", "babel-preset-es2015": "^6.24.1",
"babelify": "^8.0.0",
"browserify": "^16.2.2",
"chai": "^4.1.2", "chai": "^4.1.2",
"chai-as-promised": "^7.1.1", "chai-as-promised": "^7.1.1",
"coveralls": "^3.0.0", "coveralls": "^3.0.0",
"cross-env": "^5.1.3",
"eslint": "^5.2.0", "eslint": "^5.2.0",
"eslint-config-standard": "^11.0.0", "eslint-config-standard": "^11.0.0",
"eslint-plugin-import": "^2.7.0", "eslint-plugin-import": "^2.7.0",
@@ -63,14 +55,18 @@
"eslint-plugin-standard": "^3.0.1", "eslint-plugin-standard": "^3.0.1",
"express": "^4.16.1", "express": "^4.16.1",
"http-server": "^0.11.1", "http-server": "^0.11.1",
"istanbul": "^0.4.5",
"jsdom": "^11.5.1", "jsdom": "^11.5.1",
"mocha": "^5.2.0", "mocha": "^5.2.0",
"mock-fs": "^4.4.1", "mock-fs": "^4.4.1",
"nyc": "^12.0.2", "nyc": "^12.0.2",
"regenerator-runtime": "^0.12.1",
"rollup": "^0.64.1",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-node-resolve": "^3.3.0",
"rollup-plugin-shim": "^1.0.0",
"rollup-plugin-uglify": "^4.0.0",
"sinon": "^6.1.4", "sinon": "^6.1.4",
"sinon-chai": "^3.2.0", "sinon-chai": "^3.2.0",
"supertest": "^3.0.0", "supertest": "^3.0.0"
"uglify-js": "^3.4.5"
} }
} }
+71
View File
@@ -0,0 +1,71 @@
import shim from 'rollup-plugin-shim'
import babel from 'rollup-plugin-babel'
import {uglify} from 'rollup-plugin-uglify'
import pkg from './package.json'
import nodeResolve from 'rollup-plugin-node-resolve'
const fake = {fs: `export default {}`, path: `export default {}`}
const version = process.env.VERSION || pkg.version
const sourcemap = true
const banner = `/*
* liquidjs@${version}, https://github.com/liquidjs
* (c) 2016-${new Date().getFullYear()} harttle
* Released under the MIT License.
*/`
const treeshake = {
propertyReadSideEffects: false
}
const input = 'src/index.js'
const babelConf = {
babelrc: false,
'presets': [['env', {'modules': false}]],
'plugins': ['external-helpers']
}
export default [{
output: [{
file: 'dist/liquid.common.js',
name: 'Liquid',
format: 'cjs',
sourcemap,
banner
}],
external: ['path', 'fs'],
plugins: [
nodeResolve(),
babel(babelConf)
],
treeshake,
input
}, {
output: [{
file: 'dist/liquid.js',
name: 'Liquid',
format: 'umd',
sourcemap,
banner
}],
plugins: [
shim(fake),
nodeResolve(),
babel(babelConf)
],
treeshake,
input
}, {
output: [{
file: 'dist/liquid.min.js',
name: 'Liquid',
format: 'umd',
sourcemap
}],
plugins: [
shim(fake),
nodeResolve(),
babel(babelConf),
uglify()
],
treeshake,
input
}]
+18 -18
View File
@@ -1,17 +1,17 @@
const lexical = require('./lexical.js') import * as lexical from './lexical.js'
const Syntax = require('./syntax.js') import {evalValue} from './syntax.js'
const assert = require('./util/assert.js') import assert from './util/assert.js'
const _ = require('./util/underscore.js') import {assign} from './util/underscore.js'
let valueRE = new RegExp(`${lexical.value.source}`, 'g') const valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function (options) { export default function (options) {
options = _.assign({}, options) options = assign({}, options)
let filters = {} let filters = {}
let _filterInstance = { const _filterInstance = {
render: function (output, scope) { render: function (output, scope) {
let args = this.args.map(arg => Syntax.evalValue(arg, scope)) const args = this.args.map(arg => evalValue(arg, scope))
args.unshift(output) args.unshift(output)
return this.filter.apply(null, args) return this.filter.apply(null, args)
}, },
@@ -19,9 +19,9 @@ module.exports = function (options) {
let match = lexical.filterLine.exec(str) let match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str) assert(match, 'illegal filter: ' + str)
let name = match[1] const name = match[1]
let argList = match[2] || '' const argList = match[2] || ''
let filter = filters[name] const filter = filters[name]
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
if (options.strict_filters) { if (options.strict_filters) {
throw new TypeError(`undefined filter: ${name}`) throw new TypeError(`undefined filter: ${name}`)
@@ -32,12 +32,12 @@ module.exports = function (options) {
return this return this
} }
let args = [] const args = []
while ((match = valueRE.exec(argList.trim()))) { while ((match = valueRE.exec(argList.trim()))) {
let v = match[0] const v = match[0]
let re = new RegExp(`${v}\\s*:`, 'g') const re = new RegExp(`${v}\\s*:`, 'g')
let keyMatch = re.exec(match.input) const keyMatch = re.exec(match.input)
let currentMatchIsKey = keyMatch && keyMatch.index === match.index const currentMatchIsKey = keyMatch && keyMatch.index === match.index
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v) currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
} }
@@ -50,7 +50,7 @@ module.exports = function (options) {
} }
function construct (str) { function construct (str) {
let instance = Object.create(_filterInstance) const instance = Object.create(_filterInstance)
return instance.parse(str) return instance.parse(str)
} }
+15 -17
View File
@@ -1,16 +1,15 @@
'use strict' import strftime from './util/strftime.js'
const strftime = require('./util/strftime.js') import * as _ from './util/underscore.js'
const _ = require('./util/underscore.js') import {isTruthy} from './syntax.js'
const isTruthy = require('./syntax.js').isTruthy
let escapeMap = { const escapeMap = {
'&': '&amp;', '&': '&amp;',
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;',
'"': '&#34;', '"': '&#34;',
"'": '&#39;' "'": '&#39;'
} }
let unescapeMap = { const unescapeMap = {
'&amp;': '&', '&amp;': '&',
'&lt;': '<', '&lt;': '<',
'&gt;': '>', '&gt;': '>',
@@ -18,7 +17,7 @@ let unescapeMap = {
'&#39;': "'" '&#39;': "'"
} }
let filters = { const filters = {
'abs': v => Math.abs(v), 'abs': v => Math.abs(v),
'append': (v, arg) => v + arg, 'append': (v, arg) => v + arg,
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1), 'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
@@ -57,7 +56,7 @@ let filters = {
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2), 'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
'reverse': v => v.reverse(), 'reverse': v => v.reverse(),
'round': (v, arg) => { 'round': (v, arg) => {
let amp = Math.pow(10, arg || 0) const amp = Math.pow(10, arg || 0)
return Math.round(v * amp, arg) / amp return Math.round(v * amp, arg) / amp
}, },
'rstrip': str => stringify(str).replace(/\s+$/, ''), 'rstrip': str => stringify(str).replace(/\s+$/, ''),
@@ -79,13 +78,13 @@ let filters = {
}, },
'truncatewords': (v, l, o) => { 'truncatewords': (v, l, o) => {
if (o === undefined) o = '...' if (o === undefined) o = '...'
let arr = v.split(' ') const arr = v.split(' ')
let ret = arr.slice(0, l).join(' ') let ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o if (arr.length > l) ret += o
return ret return ret
}, },
'uniq': function (arr) { 'uniq': function (arr) {
let u = {} const u = {}
return (arr || []).filter(val => { return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) { if (u.hasOwnProperty(val)) {
return false return false
@@ -107,7 +106,7 @@ function unescape (str) {
} }
function getFixed (v) { function getFixed (v) {
let p = (v + '').split('.') const p = (v + '').split('.')
return (p.length > 1) ? p[1].length : 0 return (p.length > 1) ? p[1].length : 0
} }
@@ -121,18 +120,17 @@ function stringify (obj) {
function bindFixed (cb) { function bindFixed (cb) {
return (l, r) => { return (l, r) => {
let f = getMaxFixed(l, r) const f = getMaxFixed(l, r)
return cb(l, r).toFixed(f) return cb(l, r).toFixed(f)
} }
} }
function registerAll (liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
}
function isValidDate (date) { function isValidDate (date) {
return date instanceof Date && !isNaN(date.getTime()) return date instanceof Date && !isNaN(date.getTime())
} }
export default function registerAll (liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
}
registerAll.filters = filters registerAll.filters = filters
module.exports = registerAll
+73 -90
View File
@@ -1,22 +1,24 @@
import Scope from './scope' import 'regenerator-runtime/runtime'
import _ from './util/underscore.js' import * as Scope from './scope'
import {get as httpGet} from './util/http.js'
import * as _ from './util/underscore.js'
import assert from './util/assert.js' import assert from './util/assert.js'
import tokenizer from './tokenizer.js' import * as tokenizer from './tokenizer.js'
import {statFileAsync, readFileAsync} from './util/fs.js' import {statFileAsync, readFileAsync} from './util/fs.js'
import path from 'path' import path from 'path'
import {valid as isValidUrl, extname, resolve} from './util/url.js' import {valid as isValidUrl, extname, resolve} from './util/url.js'
import lexical from './lexical.js' import * as lexical from './lexical.js'
import Render from './render.js' import Render from './render.js'
import Tag from './tag.js' import Tag from './tag.js'
import Filter from './filter.js' import Filter from './filter.js'
import Parser from './parser' import Parser from './parser'
import {isTruthy, isFalsy, evalExp, evalValue} from './syntax.js' import {isTruthy, isFalsy, evalExp, evalValue} from './syntax.js'
import tags from './tags'
import filters from './filters'
import {anySeries} from './util/promise.js' import {anySeries} from './util/promise.js'
import {ParseError, TokenizationEroor, RenderBreakError, AssertionError} from './util/error.js' import {ParseError, TokenizationError, RenderBreakError, AssertionError} from './util/error.js'
import tags from './tags/index.js'
import filters from './filters.js'
let _engine = { const _engine = {
init: function (tag, filter, options) { init: function (tag, filter, options) {
if (options.cache) { if (options.cache) {
this.cache = {} this.cache = {}
@@ -27,32 +29,31 @@ let _engine = {
this.parser = Parser(tag, filter) this.parser = Parser(tag, filter)
this.renderer = Render() this.renderer = Render()
tags(this) tags(this, Liquid)
filters(this) filters(this, Liquid)
return this return this
}, },
parse: function (html, filepath) { parse: function (html, filepath) {
let tokens = tokenizer.parse(html, filepath, this.options) const tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens) return this.parser.parse(tokens)
}, },
render: function (tpl, ctx, opts) { render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts) opts = _.assign({}, this.options, opts)
let scope = Scope.factory(ctx, opts) const scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope) return this.renderer.renderTemplates(tpl, scope)
}, },
parseAndRender: function (html, ctx, opts) { parseAndRender: async function (html, ctx, opts) {
return Promise.resolve() const tpl = await this.parse(html)
.then(() => this.parse(html)) return this.render(tpl, ctx, opts)
.then(tpl => this.render(tpl, ctx, opts))
}, },
renderFile: function (filepath, ctx, opts) { renderFile: async function (filepath, ctx, opts) {
opts = _.assign({}, opts) opts = _.assign({}, opts)
return this.getTemplate(filepath, opts.root) const templates = await this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts)) return this.render(templates, ctx, opts)
}, },
evalValue: function (str, scope) { evalValue: function (str, scope) {
let tpl = this.parser.parseValue(str.trim()) const tpl = this.parser.parseValue(str.trim())
return this.renderer.evalValue(tpl, scope) return this.renderer.evalValue(tpl, scope)
}, },
registerFilter: function (name, filter) { registerFilter: function (name, filter) {
@@ -64,39 +65,33 @@ let _engine = {
lookup: function (filepath, root) { lookup: function (filepath, root) {
root = this.options.root.concat(root || []) root = this.options.root.concat(root || [])
root = _.uniq(root) root = _.uniq(root)
let paths = root.map(root => path.resolve(root, filepath)) const paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path)) return anySeries(paths, async path => {
.catch((e) => { try {
await statFileAsync(path)
return path
} catch (e) {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}` e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e throw e
}) }
})
}, },
getTemplate: function (filepath, root) { getTemplate: function (filepath, root) {
return typeof XMLHttpRequest === 'undefined' return typeof XMLHttpRequest === 'undefined'
? this.getTemplateFromFile(filepath, root) ? this.getTemplateFromFile(filepath, root)
: this.getTemplateFromUrl(filepath, root) : this.getTemplateFromUrl(filepath, root)
}, },
getTemplateFromFile: function (filepath, root) { getTemplateFromFile: async function (filepath, root) {
if (!path.extname(filepath)) { if (!path.extname(filepath)) {
filepath += this.options.extname filepath += this.options.extname
} }
return this filepath = await this.lookup(filepath, root)
.lookup(filepath, root) return this.respectCache(filepath, async () => {
.then(filepath => { const str = await readFileAsync(filepath)
if (this.options.cache) { return this.parse(str, filepath)
let tpl = this.cache[filepath] })
if (tpl) {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
})
}, },
getTemplateFromUrl: function (filepath, root) { getTemplateFromUrl: async function (filepath, root) {
let fullUrl let fullUrl
if (isValidUrl(filepath)) { if (isValidUrl(filepath)) {
fullUrl = filepath fullUrl = filepath
@@ -106,47 +101,41 @@ let _engine = {
} }
fullUrl = resolve(root || this.options.root, filepath) fullUrl = resolve(root || this.options.root, filepath)
} }
if (this.options.cache) { return this.respectCache(
let tpl = this.cache[filepath] filepath,
if (tpl) { async () => this.parse(await httpGet(fullUrl))
return Promise.resolve(tpl) )
} },
respectCache: async function (key, getter) {
const cacheEnabled = this.options.cache
if (cacheEnabled && this.cache[key]) {
return this.cache[key]
} }
return new Promise((resolve, reject) => { const value = await getter()
let xhr = new XMLHttpRequest() if (cacheEnabled) {
xhr.onload = () => { this.cache[key] = value
if (xhr.status >= 200 && xhr.status < 300) { }
let tpl = this.parse(xhr.responseText) return value
if (this.options.cache) {
this.cache[filepath] = tpl
}
resolve(tpl)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error('An error occurred whilst sending the response.'))
}
xhr.open('GET', fullUrl)
xhr.send()
})
}, },
express: function (opts) { express: function (opts) {
opts = opts || {} opts = opts || {}
let self = this const self = this
return function (filePath, ctx, callback) { return function (filePath, ctx, cb) {
assert(Array.isArray(this.root) || _.isString(this.root), assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?') 'illegal views root, are you using express.js?')
opts.root = this.root opts.root = this.root
self.renderFile(filePath, ctx, opts) self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
.then(html => callback(null, html))
.catch(e => callback(e))
} }
} }
} }
function factory (options) { function normalizeStringArray (value) {
if (Array.isArray(value)) return value
if (_.isString(value)) return [value]
return []
}
export default function Liquid (options) {
options = _.assign({ options = _.assign({
root: ['.'], root: ['.'],
cache: false, cache: false,
@@ -162,29 +151,23 @@ function factory (options) {
}, options) }, options)
options.root = normalizeStringArray(options.root) options.root = normalizeStringArray(options.root)
let engine = Object.create(_engine) const engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options) engine.init(Tag(), Filter(options), options)
return engine return engine
} }
function normalizeStringArray (value) { Liquid.isTruthy = isTruthy
if (Array.isArray(value)) return value Liquid.isFalsy = isFalsy
if (_.isString(value)) return [value] Liquid.evalExp = evalExp
return [] Liquid.evalValue = evalValue
} Liquid.Types = {
const Types = {
ParseError, ParseError,
TokenizationEroor, TokenizationError,
RenderBreakError, RenderBreakError,
AssertionError AssertionError,
AssignScope: Object.create(null),
CaptureScope: Object.create(null),
IncrementScope: Object.create(null),
DecrementScope: Object.create(null)
} }
Liquid.lexical = lexical
factory.isTruthy = isTruthy
factory.isFalsy = isFalsy
factory.evalExp = evalExp
factory.evalValue = evalValue
factory.Types = Types
factory.lexical = lexical
module.exports = factory
+37 -67
View File
@@ -1,75 +1,75 @@
// quote related // quote related
let singleQuoted = /'[^']*'/ const singleQuoted = /'[^']*'/
let doubleQuoted = /"[^"]*"/ const doubleQuoted = /"[^"]*"/
let quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`) export const quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
let quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`) export const quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types // basic types
let integer = /-?\d+/ export const integer = /-?\d+/
let number = /-?\d+\.?\d*|\.?\d+/ export const number = /-?\d+\.?\d*|\.?\d+/
let bool = /true|false/ export const bool = /true|false/
// peoperty access // peoperty access
let identifier = /[\w-]+[?]?/ export const identifier = /[\w-]+[?]?/
let subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`) export const subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
let literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`) export const literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
let variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`) export const variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
// range related // range related
let rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`) export const rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
let range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`) export const range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
let rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`) export const rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
let value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`) export const value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
// hash related // hash related
let hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`) export const hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
let hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g') export const hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match // full match
let tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`) export const tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
let literalLine = new RegExp(`^${literal.source}$`, 'i') export const literalLine = new RegExp(`^${literal.source}$`, 'i')
let variableLine = new RegExp(`^${variable.source}$`) export const variableLine = new RegExp(`^${variable.source}$`)
let numberLine = new RegExp(`^${number.source}$`) export const numberLine = new RegExp(`^${number.source}$`)
let boolLine = new RegExp(`^${bool.source}$`, 'i') export const boolLine = new RegExp(`^${bool.source}$`, 'i')
let quotedLine = new RegExp(`^${quoted.source}$`) export const quotedLine = new RegExp(`^${quoted.source}$`)
let rangeLine = new RegExp(`^${rangeCapture.source}$`) export const rangeLine = new RegExp(`^${rangeCapture.source}$`)
let integerLine = new RegExp(`^${integer.source}$`) export const integerLine = new RegExp(`^${integer.source}$`)
// filter related // filter related
let valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`) export const valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
let valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`) export const valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
let filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g') export const filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
let filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`) export const filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
let filterLine = new RegExp(`^${filterCapture.source}$`) export const filterLine = new RegExp(`^${filterCapture.source}$`)
let operators = [ export const operators = [
/\s+or\s+/, /\s+or\s+/,
/\s+and\s+/, /\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/ /==|!=|<=|>=|<|>|\s+contains\s+/
] ]
function isInteger (str) { export function isInteger (str) {
return integerLine.test(str) return integerLine.test(str)
} }
function isLiteral (str) { export function isLiteral (str) {
return literalLine.test(str) return literalLine.test(str)
} }
function isRange (str) { export function isRange (str) {
return rangeLine.test(str) return rangeLine.test(str)
} }
function isVariable (str) { export function isVariable (str) {
return variableLine.test(str) return variableLine.test(str)
} }
function matchValue (str) { export function matchValue (str) {
return value.exec(str) return value.exec(str)
} }
function parseLiteral (str) { export function parseLiteral (str) {
let res = str.match(numberLine) let res = str.match(numberLine)
if (res) { if (res) {
return Number(str) return Number(str)
@@ -84,33 +84,3 @@ function parseLiteral (str) {
} }
throw new TypeError(`cannot parse '${str}' as literal`) throw new TypeError(`cannot parse '${str}' as literal`)
} }
module.exports = {
quoted,
number,
bool,
literal,
filter,
integer,
hash,
hashCapture,
range,
rangeCapture,
identifier,
value,
quoteBalanced,
operators,
quotedLine,
numberLine,
boolLine,
rangeLine,
literalLine,
filterLine,
tagLine,
isLiteral,
isVariable,
parseLiteral,
isRange,
matchValue,
isInteger
}
+1 -1
View File
@@ -1,4 +1,4 @@
module.exports = function (isTruthy) { export default function (isTruthy) {
return { return {
'==': (l, r) => l === r, '==': (l, r) => l === r,
'!=': (l, r) => l !== r, '!=': (l, r) => l !== r,
+11 -11
View File
@@ -1,9 +1,9 @@
const lexical = require('./lexical.js') import * as lexical from './lexical.js'
const ParseError = require('./util/error.js').ParseError import {ParseError} from './util/error.js'
const assert = require('./util/assert.js') import assert from './util/assert.js'
module.exports = function (Tag, Filter) { export default function (Tag, Filter) {
let stream = { const stream = {
init: function (tokens) { init: function (tokens) {
this.tokens = tokens this.tokens = tokens
this.handlers = {} this.handlers = {}
@@ -14,7 +14,7 @@ module.exports = function (Tag, Filter) {
return this return this
}, },
trigger: function (event, arg) { trigger: function (event, arg) {
let h = this.handlers[event] const h = this.handlers[event]
if (typeof h === 'function') { if (typeof h === 'function') {
h(arg) h(arg)
return true return true
@@ -29,7 +29,7 @@ module.exports = function (Tag, Filter) {
this.trigger(`tag:${token.name}`, token)) { this.trigger(`tag:${token.name}`, token)) {
continue continue
} }
let template = parseToken(token, this.tokens) const template = parseToken(token, this.tokens)
this.trigger('template', template) this.trigger('template', template)
} }
if (!this.stopRequested) this.trigger('end') if (!this.stopRequested) this.trigger('end')
@@ -43,7 +43,7 @@ module.exports = function (Tag, Filter) {
function parse (tokens) { function parse (tokens) {
let token let token
let templates = [] const templates = []
while ((token = tokens.shift())) { while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens)) templates.push(parseToken(token, tokens))
} }
@@ -76,10 +76,10 @@ module.exports = function (Tag, Filter) {
let match = lexical.matchValue(str) let match = lexical.matchValue(str)
assert(match, `illegal value string: ${str}`) assert(match, `illegal value string: ${str}`)
let initial = match[0] const initial = match[0]
str = str.substr(match.index + match[0].length) str = str.substr(match.index + match[0].length)
let filters = [] const filters = []
while ((match = lexical.filter.exec(str))) { while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()]) filters.push([match[0].trim()])
} }
@@ -92,7 +92,7 @@ module.exports = function (Tag, Filter) {
} }
function parseStream (tokens) { function parseStream (tokens) {
let s = Object.create(stream) const s = Object.create(stream)
return s.init(tokens) return s.init(tokens)
} }
+36 -41
View File
@@ -1,67 +1,62 @@
const Syntax = require('./syntax.js') import {evalExp} from './syntax.js'
const mapSeries = require('./util/promise.js').mapSeries import {RenderBreakError, RenderError} from './util/error.js'
const RenderBreakError = require('./util/error.js').RenderBreakError import {stringify} from './util/underscore.js'
const _ = require('./util/underscore.js') import assert from './util/assert.js'
const RenderError = require('./util/error.js').RenderError
const assert = require('./util/assert.js')
let render = { const render = {
renderTemplates: async function (templates, scope) {
renderTemplates: function (templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined') assert(scope, 'unable to evalTemplates: scope undefined')
let html = '' let html = ''
return mapSeries(templates, (tpl) => { for (const tpl of templates) {
return renderTemplate.call(this, tpl) try {
.then(partial => (html += partial)) html += await renderTemplate.call(this, tpl)
.catch(e => { } catch (e) {
if (e instanceof RenderBreakError) { if (e instanceof RenderBreakError) {
e.resolvedHTML = html e.resolvedHTML = html
throw e throw e
} }
throw new RenderError(e, tpl) throw new RenderError(e, tpl)
})
}).then(() => html)
function renderTemplate (template) {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial)
} else if (template.type === 'value') {
return this.renderValue(template, scope)
} else { // template.type === 'html'
return Promise.resolve(template.value)
} }
} }
return html
async function renderTemplate (template) {
if (template.type === 'tag') {
const partial = await this.renderTag(template, scope)
return partial === undefined ? '' : partial
}
if (template.type === 'value') {
return this.renderValue(template, scope)
}
return template.value
}
}, },
renderTag: function (template, scope) { renderTag: async function (template, scope) {
if (template.name === 'continue') { if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue')) throw new RenderBreakError('continue')
} }
if (template.name === 'break') { if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break')) throw new RenderBreakError('break')
} }
return template.render(scope) return template.render(scope)
}, },
renderValue: function (template, scope) { renderValue: async function (template, scope) {
return Promise.resolve() const partial = this.evalValue(template, scope)
.then(() => this.evalValue(template, scope)) return partial === undefined ? '' : stringify(partial)
.then(partial => partial === undefined ? '' : _.stringify(partial))
}, },
evalValue: function (template, scope) { evalValue: function (template, scope) {
assert(scope, 'unable to evalValue: scope undefined') assert(scope, 'unable to evalValue: scope undefined')
return template.filters.reduce( return template.filters.reduce(
(prev, filter) => filter.render(prev, scope), (prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope)) evalExp(template.initial, scope))
} }
} }
function factory () { export default function () {
let instance = Object.create(render) const instance = Object.create(render)
return instance return instance
} }
module.exports = factory
+14 -22
View File
@@ -1,19 +1,18 @@
'use strict' import * as _ from './util/underscore.js'
const _ = require('./util/underscore.js') import * as lexical from './lexical.js'
const lexical = require('./lexical.js') import assert from './util/assert.js'
const assert = require('./util/assert.js')
let Scope = { const Scope = {
getAll: function () { getAll: function () {
return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null)) return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
}, },
get: function (path) { get: function (path) {
let paths = this.propertyAccessSeq(path) const paths = this.propertyAccessSeq(path)
let scope = this.findContextFor(paths[0]) || _.last(this.contexts) const scope = this.findContextFor(paths[0]) || _.last(this.contexts)
return paths.reduce((value, key) => this.readProperty(value, key), scope) return paths.reduce((value, key) => this.readProperty(value, key), scope)
}, },
set: function (path, v) { set: function (path, v) {
let paths = this.propertyAccessSeq(path) const paths = this.propertyAccessSeq(path)
let scope = this.findContextFor(paths[0]) || _.last(this.contexts) let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
paths.some((key, i) => { paths.some((key, i) => {
if (!_.isObject(scope)) { if (!_.isObject(scope)) {
@@ -39,7 +38,7 @@ let Scope = {
if (!arguments.length) { if (!arguments.length) {
return this.contexts.pop() return this.contexts.pop()
} }
let i = this.contexts.findIndex(scope => scope === ctx) const i = this.contexts.findIndex(scope => scope === ctx)
if (i === -1) { if (i === -1) {
throw new TypeError('scope not found, cannot pop') throw new TypeError('scope not found, cannot pop')
} }
@@ -48,7 +47,7 @@ let Scope = {
findContextFor: function (key, filter) { findContextFor: function (key, filter) {
filter = filter || (() => true) filter = filter || (() => true)
for (let i = this.contexts.length - 1; i >= 0; i--) { for (let i = this.contexts.length - 1; i >= 0; i--) {
let candidate = this.contexts[i] const candidate = this.contexts[i]
if (!filter(candidate)) continue if (!filter(candidate)) continue
if (key in candidate) { if (key in candidate) {
return candidate return candidate
@@ -89,7 +88,7 @@ let Scope = {
*/ */
propertyAccessSeq: function (str) { propertyAccessSeq: function (str) {
str = String(str) str = String(str)
let seq = [] const seq = []
let name = '' let name = ''
let j let j
let i = 0 let i = 0
@@ -98,7 +97,7 @@ let Scope = {
case '[': case '[':
push() push()
let delemiter = str[i + 1] const delemiter = str[i + 1]
if (/['"]/.test(delemiter)) { // foo["bar"] if (/['"]/.test(delemiter)) { // foo["bar"]
j = str.indexOf(delemiter, i + 2) j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`) assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
@@ -155,23 +154,16 @@ function matchRightBracket (str, begin) {
return -1 return -1
} }
exports.factory = function (ctx, opts) { export function factory (ctx, opts) {
let defaultOptions = { const defaultOptions = {
dynamicPartials: true, dynamicPartials: true,
strict_variables: false, strict_variables: false,
strict_filters: false, strict_filters: false,
blocks: {}, blocks: {},
root: [] root: []
} }
let scope = Object.create(Scope) const scope = Object.create(Scope)
scope.opts = _.assign(defaultOptions, opts) scope.opts = _.assign(defaultOptions, opts)
scope.contexts = [ctx || {}] scope.contexts = [ctx || {}]
return scope return scope
} }
exports.types = {
AssignScope: Object.create(null),
CaptureScope: Object.create(null),
IncrementScope: Object.create(null),
DecrementScope: Object.create(null)
}
+18 -20
View File
@@ -1,26 +1,28 @@
const operators = require('./operators.js')(isTruthy) import Operators from './operators.js'
const lexical = require('./lexical.js') import * as lexical from './lexical.js'
const assert = require('./util/assert.js') import assert from './util/assert.js'
function evalExp (exp, scope) { const operators = Operators(isTruthy)
export function evalExp (exp, scope) {
assert(scope, 'unable to evalExp: scope undefined') assert(scope, 'unable to evalExp: scope undefined')
let operatorREs = lexical.operators const operatorREs = lexical.operators
let match let match
for (let i = 0; i < operatorREs.length; i++) { for (let i = 0; i < operatorREs.length; i++) {
let operatorRE = operatorREs[i] const operatorRE = operatorREs[i]
let expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`) const expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
if ((match = exp.match(expRE))) { if ((match = exp.match(expRE))) {
let l = evalExp(match[1], scope) const l = evalExp(match[1], scope)
let op = operators[match[2].trim()] const op = operators[match[2].trim()]
let r = evalExp(match[3], scope) const r = evalExp(match[3], scope)
return op(l, r) return op(l, r)
} }
} }
if ((match = exp.match(lexical.rangeLine))) { if ((match = exp.match(lexical.rangeLine))) {
let low = evalValue(match[1], scope) const low = evalValue(match[1], scope)
let high = evalValue(match[2], scope) const high = evalValue(match[2], scope)
let range = [] const range = []
for (let j = low; j <= high; j++) { for (let j = low; j <= high; j++) {
range.push(j) range.push(j)
} }
@@ -30,7 +32,7 @@ function evalExp (exp, scope) {
return evalValue(exp, scope) return evalValue(exp, scope)
} }
function evalValue (str, scope) { export function evalValue (str, scope) {
str = str && str.trim() str = str && str.trim()
if (!str) return undefined if (!str) return undefined
@@ -43,14 +45,10 @@ function evalValue (str, scope) {
throw new TypeError(`cannot eval '${str}' as value`) throw new TypeError(`cannot eval '${str}' as value`)
} }
function isTruthy (val) { export function isTruthy (val) {
return !isFalsy(val) return !isFalsy(val)
} }
function isFalsy (val) { export function isFalsy (val) {
return val === false || undefined === val || val === null return val === false || undefined === val || val === null
} }
module.exports = {
evalExp, evalValue, isTruthy, isFalsy
}
+18 -19
View File
@@ -1,38 +1,37 @@
'use strict' import {hashCapture} from './lexical.js'
const lexical = require('./lexical.js') import {evalValue} from './syntax.js'
const Syntax = require('./syntax.js') import assert from './util/assert.js'
const assert = require('./util/assert.js')
function hash (markup, scope) { function hash (markup, scope) {
let obj = {} const obj = {}
let match let match
lexical.hashCapture.lastIndex = 0 hashCapture.lastIndex = 0
while ((match = lexical.hashCapture.exec(markup))) { while ((match = hashCapture.exec(markup))) {
let k = match[1] const k = match[1]
let v = match[2] const v = match[2]
obj[k] = Syntax.evalValue(v, scope) obj[k] = evalValue(v, scope)
} }
return obj return obj
} }
module.exports = function () { export default function () {
let tagImpls = {} let tagImpls = {}
let _tagInstance = { const _tagInstance = {
render: function (scope) { render: async function (scope) {
let obj = hash(this.token.args, scope) const obj = hash(this.token.args, scope)
let impl = this.tagImpl const impl = this.tagImpl
if (typeof impl.render !== 'function') { if (typeof impl.render !== 'function') {
return Promise.resolve('') return ''
} }
return Promise.resolve().then(() => impl.render(scope, obj)) return impl.render(scope, obj)
}, },
parse: function (token, tokens) { parse: function (token, tokens) {
this.type = 'tag' this.type = 'tag'
this.token = token this.token = token
this.name = token.name this.name = token.name
let tagImpl = tagImpls[this.name] const tagImpl = tagImpls[this.name]
assert(tagImpl, `tag ${this.name} not found`) assert(tagImpl, `tag ${this.name} not found`)
this.tagImpl = Object.create(tagImpl) this.tagImpl = Object.create(tagImpl)
if (this.tagImpl.parse) { if (this.tagImpl.parse) {
@@ -46,7 +45,7 @@ module.exports = function () {
} }
function construct (token, tokens) { function construct (token, tokens) {
let instance = Object.create(_tagInstance) const instance = Object.create(_tagInstance)
instance.parse(token, tokens) instance.parse(token, tokens)
return instance return instance
} }
+6 -6
View File
@@ -1,19 +1,19 @@
import {lexical} from '../index'
import assert from '../util/assert.js' import assert from '../util/assert.js'
import {types} from '../scope'
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`) export default function (liquid, Liquid) {
const rIdentifier = Liquid.lexical.identifier
const re = new RegExp(`(${rIdentifier.source})\\s*=(.*)`)
const {AssignScope} = Liquid.Types
module.exports = function (liquid) {
liquid.registerTag('assign', { liquid.registerTag('assign', {
parse: function (token) { parse: function (token) {
let match = token.args.match(re) const match = token.args.match(re)
assert(match, `illegal token ${token.raw}`) assert(match, `illegal token ${token.raw}`)
this.key = match[1] this.key = match[1]
this.value = match[2] this.value = match[2]
}, },
render: function (scope) { render: function (scope) {
let ctx = Object.create(types.AssignScope) const ctx = Object.create(AssignScope)
ctx[this.key] = liquid.evalValue(this.value, scope) ctx[this.key] = liquid.evalValue(this.value, scope)
scope.push(ctx) scope.push(ctx)
return Promise.resolve('') return Promise.resolve('')
+13 -16
View File
@@ -1,20 +1,19 @@
'use strict' import assert from '../util/assert.js'
const Liquid = require('..')
const lexical = Liquid.lexical export default function (liquid, Liquid) {
const re = new RegExp(`(${lexical.identifier.source})`) const rIdentifier = Liquid.lexical.identifier
const assert = require('../util/assert.js') const re = new RegExp(`(${rIdentifier.source})`)
const types = require('../scope.js').types const {CaptureScope} = Liquid.Types
module.exports = function (liquid) {
liquid.registerTag('capture', { liquid.registerTag('capture', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
let match = tagToken.args.match(re) const match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`) assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1] this.variable = match[1]
this.templates = [] this.templates = []
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', token => stream.stop()) stream.on('tag:endcapture', token => stream.stop())
.on('template', tpl => this.templates.push(tpl)) .on('template', tpl => this.templates.push(tpl))
.on('end', x => { .on('end', x => {
@@ -22,13 +21,11 @@ module.exports = function (liquid) {
}) })
stream.start() stream.start()
}, },
render: function (scope, hash) { render: async function (scope, hash) {
return liquid.renderer.renderTemplates(this.templates, scope) const html = await liquid.renderer.renderTemplates(this.templates, scope)
.then((html) => { const ctx = Object.create(CaptureScope)
let ctx = Object.create(types.CaptureScope) ctx[this.variable] = html
ctx[this.variable] = html scope.push(ctx)
scope.push(ctx)
})
} }
}) })
} }
+5 -7
View File
@@ -1,6 +1,4 @@
import Liquid from '..' export default function (liquid, Liquid) {
module.exports = function (liquid) {
liquid.registerTag('case', { liquid.registerTag('case', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
@@ -9,7 +7,7 @@ module.exports = function (liquid) {
this.elseTemplates = [] this.elseTemplates = []
let p = [] let p = []
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => { .on('tag:when', token => {
this.cases.push({ this.cases.push({
val: token.args, val: token.args,
@@ -28,9 +26,9 @@ module.exports = function (liquid) {
render: function (scope, hash) { render: function (scope, hash) {
for (let i = 0; i < this.cases.length; i++) { for (let i = 0; i < this.cases.length; i++) {
let branch = this.cases[i] const branch = this.cases[i]
let val = Liquid.evalExp(branch.val, scope) const val = Liquid.evalExp(branch.val, scope)
let cond = Liquid.evalExp(this.cond, scope) const cond = Liquid.evalExp(this.cond, scope)
if (val === cond) { if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope) return liquid.renderer.renderTemplates(branch.templates, scope)
} }
+2 -2
View File
@@ -1,7 +1,7 @@
module.exports = function (liquid) { export default function (liquid) {
liquid.registerTag('comment', { liquid.registerTag('comment', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
stream stream
.on('token', token => { .on('token', token => {
if (token.name === 'endcomment') stream.stop() if (token.name === 'endcomment') stream.stop()
+12 -12
View File
@@ -1,10 +1,10 @@
const Liquid = require('..') import assert from '../util/assert.js'
const lexical = Liquid.lexical
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`) export default function (liquid, Liquid) {
const candidatesRE = new RegExp(lexical.value.source, 'g') const rValue = Liquid.lexical.value
const assert = require('../util/assert.js') const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(rValue.source, 'g')
module.exports = function (liquid) {
liquid.registerTag('cycle', { liquid.registerTag('cycle', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
@@ -12,7 +12,7 @@ module.exports = function (liquid) {
assert(match, `illegal tag: ${tagToken.raw}`) assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || '' this.group = match[1] || ''
let candidates = match[2] const candidates = match[2]
this.candidates = [] this.candidates = []
@@ -23,21 +23,21 @@ module.exports = function (liquid) {
}, },
render: function (scope, hash) { render: function (scope, hash) {
let group = Liquid.evalValue(this.group, scope) const group = Liquid.evalValue(this.group, scope)
let fingerprint = `cycle:${group}:` + this.candidates.join(',') const fingerprint = `cycle:${group}:` + this.candidates.join(',')
let groups = scope.opts.groups = scope.opts.groups || {} const groups = scope.opts.groups = scope.opts.groups || {}
let idx = groups[fingerprint] let idx = groups[fingerprint]
if (idx === undefined) { if (idx === undefined) {
idx = groups[fingerprint] = 0 idx = groups[fingerprint] = 0
} }
let candidate = this.candidates[idx] const candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx groups[fingerprint] = idx
return Promise.resolve(Liquid.evalValue(candidate, scope)) return Liquid.evalValue(candidate, scope)
} }
}) })
} }
+9 -10
View File
@@ -1,13 +1,12 @@
'use strict' import assert from '../util/assert.js'
const Liquid = require('..')
const lexical = Liquid.lexical export default function (liquid, Liquid) {
const assert = require('../util/assert.js') const lexical = Liquid.lexical
const types = require('../scope').types const {CaptureScope, AssignScope, DecrementScope} = Liquid.Types
module.exports = function (liquid) {
liquid.registerTag('decrement', { liquid.registerTag('decrement', {
parse: function (token) { parse: function (token) {
let match = token.args.match(lexical.identifier) const match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`) assert(match, `illegal identifier ${token.args}`)
this.variable = match[0] this.variable = match[0]
}, },
@@ -15,12 +14,12 @@ module.exports = function (liquid) {
let context = scope.findContextFor( let context = scope.findContextFor(
this.variable, this.variable,
ctx => { ctx => {
return Object.getPrototypeOf(ctx) !== types.CaptureScope && return Object.getPrototypeOf(ctx) !== CaptureScope &&
Object.getPrototypeOf(ctx) !== types.AssignScope Object.getPrototypeOf(ctx) !== AssignScope
} }
) )
if (!context) { if (!context) {
context = Object.create(types.DecrementScope) context = Object.create(DecrementScope)
scope.unshift(context) scope.unshift(context)
} }
if (typeof context[this.variable] !== 'number') { if (typeof context[this.variable] !== 'number') {
+82 -85
View File
@@ -1,96 +1,93 @@
import {default as Liquid, lexical} from '../index'
import {mapSeries} from '../util/promise.js' import {mapSeries} from '../util/promise.js'
import _ from '../util/underscore.js' import {isString, isObject} from '../util/underscore.js'
import assert from '../util/assert.js' import assert from '../util/assert.js'
const RenderBreakError = Liquid.Types.RenderBreakError export default function (liquid, Liquid) {
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` + const RenderBreakError = Liquid.Types.RenderBreakError
`(${lexical.value.source})` + const lexical = Liquid.lexical
`(?:\\s+${lexical.hash.source})*` + const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(?:\\s+(reversed))?` + `(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`) `(?:\\s+${lexical.hash.source})*` +
`(?:\\s+(reversed))?` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function (liquid) { liquid.registerTag('for', {parse, render})
liquid.registerTag('for', {
parse: function (tagToken, remainTokens) { function parse (tagToken, remainTokens) {
let match = re.exec(tagToken.args) const match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`) assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1] this.variable = match[1]
this.collection = match[2] this.collection = match[2]
this.reversed = !!match[3] this.reversed = !!match[3]
this.templates = [] this.templates = []
this.elseTemplates = [] this.elseTemplates = []
let p let p
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates)) .on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates)) .on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop()) .on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl)) .on('template', tpl => p.push(tpl))
.on('end', () => { .on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`) throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
let collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
collection = [collection]
} else if (_.isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
}
if (!Array.isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
let offset = hash.offset || 0
let limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
let contexts = collection.map((item, i) => {
let ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === collection.length - 1,
length: collection.length,
rindex: collection.length - i,
rindex0: collection.length - i - 1
}
return ctx
}) })
let html = '' stream.start()
return mapSeries(contexts, (context) => { }
return Promise.resolve() async function render (scope, hash) {
.then(() => scope.push(context)) let collection = Liquid.evalExp(this.collection, scope)
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
.then(partial => (html += partial)) if (!Array.isArray(collection)) {
.catch(e => { if (isString(collection) && collection.length > 0) {
if (e instanceof RenderBreakError) { collection = [collection]
html += e.resolvedHTML } else if (isObject(collection)) {
if (e.message === 'continue') return collection = Object.keys(collection).map((key) => [key, collection[key]])
} }
throw e
})
.then(() => scope.pop(context))
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return
}
throw e
}).then(() => html)
} }
}) if (!Array.isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
const contexts = collection.map((item, i) => {
const ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === collection.length - 1,
length: collection.length,
rindex: collection.length - i,
rindex0: collection.length - i - 1
}
return ctx
})
let html = ''
let finished = false
await mapSeries(contexts, async context => {
if (finished) return
scope.push(context)
try {
html += await liquid.renderer.renderTemplates(this.templates, scope)
} catch (e) {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'break') {
finished = true
}
} else throw e
}
scope.pop(context)
})
return html
}
} }
+4 -7
View File
@@ -1,6 +1,4 @@
import Liquid from '..' export default function (liquid, Liquid) {
module.exports = function (liquid) {
liquid.registerTag('if', { liquid.registerTag('if', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
@@ -8,7 +6,7 @@ module.exports = function (liquid) {
this.elseTemplates = [] this.elseTemplates = []
let p let p
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({ .on('start', () => this.branches.push({
cond: tagToken.args, cond: tagToken.args,
templates: (p = []) templates: (p = [])
@@ -30,9 +28,8 @@ module.exports = function (liquid) {
}, },
render: function (scope, hash) { render: function (scope, hash) {
for (let i = 0; i < this.branches.length; i++) { for (const branch of this.branches) {
let branch = this.branches[i] const cond = Liquid.evalExp(branch.cond, scope)
let cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) { if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope) return liquid.renderer.renderTemplates(branch.templates, scope)
} }
+28 -35
View File
@@ -1,11 +1,11 @@
'use strict' import assert from '../util/assert.js'
const Liquid = require('..')
const lexical = Liquid.lexical const staticFileRE = /[^\s,]+/
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
const staticFileRE = /[^\s,]+/ export default function (liquid, Liquid) {
const assert = require('../util/assert.js') const lexical = Liquid.lexical
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
module.exports = function (liquid) {
liquid.registerTag('include', { liquid.registerTag('include', {
parse: function (token) { parse: function (token) {
let match = staticFileRE.exec(token.args) let match = staticFileRE.exec(token.args)
@@ -23,42 +23,35 @@ module.exports = function (liquid) {
this.with = match[1] this.with = match[1]
} }
}, },
render: function (scope, hash) { render: async function (scope, hash) {
let pFilepath let filepath
if (scope.opts.dynamicPartials) { if (scope.opts.dynamicPartials) {
if (lexical.quotedLine.exec(this.value)) { if (lexical.quotedLine.exec(this.value)) {
let template = this.value.slice(1, -1) const template = this.value.slice(1, -1)
pFilepath = liquid.parseAndRender(template, scope.getAll(), scope.opts) filepath = await liquid.parseAndRender(template, scope.getAll(), scope.opts)
} else { } else {
pFilepath = Promise.resolve(Liquid.evalValue(this.value, scope)) filepath = Liquid.evalValue(this.value, scope)
} }
} else { } else {
pFilepath = Promise.resolve(this.staticValue) filepath = this.staticValue
} }
assert(filepath, `cannot include with empty filename`)
let originBlocks = scope.opts.blocks const originBlocks = scope.opts.blocks
let originBlockMode = scope.opts.blockMode const originBlockMode = scope.opts.blockMode
return pFilepath scope.opts.blocks = {}
.then(filepath => { scope.opts.blockMode = 'output'
assert(filepath, `cannot include with empty filename`) if (this.with) {
scope.opts.blocks = {} hash[filepath] = Liquid.evalValue(this.with, scope)
scope.opts.blockMode = 'output' }
if (this.with) { const templates = await liquid.getTemplate(filepath, scope.opts.root)
hash[filepath] = Liquid.evalValue(this.with, scope) scope.push(hash)
} const html = await liquid.renderer.renderTemplates(templates, scope)
return liquid.getTemplate(filepath, scope.opts.root) scope.pop(hash)
}) scope.opts.blocks = originBlocks
.then(templates => { scope.opts.blockMode = originBlockMode
scope.push(hash) return html
return liquid.renderer.renderTemplates(templates, scope)
})
.then((html) => {
scope.pop(hash)
scope.opts.blocks = originBlocks
scope.opts.blockMode = originBlockMode
return html
})
} }
}) })
} }
+10 -10
View File
@@ -1,12 +1,12 @@
const Liquid = require('../index') import assert from '../util/assert.js'
const assert = require('../util/assert.js')
const lexical = Liquid.lexical export default function (liquid, Liquid) {
const types = require('../scope').types const lexical = Liquid.lexical
const {CaptureScope, AssignScope, IncrementScope} = Liquid.Types
module.exports = function (liquid) {
liquid.registerTag('increment', { liquid.registerTag('increment', {
parse: function (token) { parse: function (token) {
let match = token.args.match(lexical.identifier) const match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`) assert(match, `illegal identifier ${token.args}`)
this.variable = match[0] this.variable = match[0]
}, },
@@ -14,18 +14,18 @@ module.exports = function (liquid) {
let context = scope.findContextFor( let context = scope.findContextFor(
this.variable, this.variable,
ctx => { ctx => {
return Object.getPrototypeOf(ctx) !== types.CaptureScope && return Object.getPrototypeOf(ctx) !== CaptureScope &&
Object.getPrototypeOf(ctx) !== types.AssignScope Object.getPrototypeOf(ctx) !== AssignScope
} }
) )
if (!context) { if (!context) {
context = Object.create(types.IncrementScope) context = Object.create(IncrementScope)
scope.unshift(context) scope.unshift(context)
} }
if (typeof context[this.variable] !== 'number') { if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0 context[this.variable] = 0
} }
let val = context[this.variable] const val = context[this.variable]
context[this.variable]++ context[this.variable]++
return val return val
} }
+30 -15
View File
@@ -1,16 +1,31 @@
module.exports = function (engine) { import For from './for.js'
require('./assign.js')(engine) import Assign from './assign.js'
require('./capture.js')(engine) import Capture from './capture.js'
require('./case.js')(engine) import Case from './case.js'
require('./comment.js')(engine) import Comment from './comment.js'
require('./cycle.js')(engine) import Include from './include.js'
require('./decrement.js')(engine) import Decrement from './decrement.js'
require('./for.js')(engine) import Cycle from './cycle.js'
require('./if.js')(engine) import If from './if.js'
require('./include.js')(engine) import Increment from './increment.js'
require('./increment.js')(engine) import Layout from './layout.js'
require('./layout.js')(engine) import Raw from './raw.js'
require('./raw.js')(engine) import Tablerow from './tablerow.js'
require('./tablerow.js')(engine) import Unless from './unless.js'
require('./unless.js')(engine)
export default function (engine, Liquid) {
Assign(engine, Liquid)
Capture(engine, Liquid)
Case(engine, Liquid)
Comment(engine, Liquid)
Cycle(engine, Liquid)
Decrement(engine, Liquid)
For(engine, Liquid)
If(engine, Liquid)
Include(engine, Liquid)
Increment(engine, Liquid)
Layout(engine, Liquid)
Raw(engine, Liquid)
Tablerow(engine, Liquid)
Unless(engine, Liquid)
} }
+33 -40
View File
@@ -1,7 +1,4 @@
const Liquid = require('..') import assert from '../util/assert.js'
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const staticFileRE = /\S+/
/* /*
* blockMode: * blockMode:
@@ -9,7 +6,10 @@ const staticFileRE = /\S+/
* * "output": output rendered html * * "output": output rendered html
*/ */
module.exports = function (liquid) { export default function (liquid, Liquid) {
const rValue = Liquid.lexical.value
const staticFileRE = /\S+/
liquid.registerTag('layout', { liquid.registerTag('layout', {
parse: function (token, remainTokens) { parse: function (token, remainTokens) {
let match = staticFileRE.exec(token.args) let match = staticFileRE.exec(token.args)
@@ -17,45 +17,41 @@ module.exports = function (liquid) {
this.staticLayout = match[0] this.staticLayout = match[0]
} }
match = lexical.value.exec(token.args) match = rValue.exec(token.args)
if (match) { if (match) {
this.layout = match[0] this.layout = match[0]
} }
this.tpls = liquid.parser.parse(remainTokens) this.tpls = liquid.parser.parse(remainTokens)
}, },
render: function (scope, hash) { render: async function (scope, hash) {
let layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout const layout = scope.opts.dynamicPartials
? Liquid.evalValue(this.layout, scope)
: this.staticLayout
assert(layout, `cannot apply layout with empty filename`) assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately // render the remaining tokens immediately
scope.opts.blockMode = 'store' scope.opts.blockMode = 'store'
return liquid.renderer.renderTemplates(this.tpls, scope) const html = await liquid.renderer.renderTemplates(this.tpls, scope)
.then(html => { if (scope.opts.blocks[''] === undefined) {
if (scope.opts.blocks[''] === undefined) { scope.opts.blocks[''] = html
scope.opts.blocks[''] = html }
} const templates = await liquid.getTemplate(layout, scope.opts.root)
return liquid.getTemplate(layout, scope.opts.root) scope.push(hash)
}) scope.opts.blockMode = 'output'
.then(templates => { const partial = await liquid.renderer.renderTemplates(templates, scope)
scope.push(hash) scope.pop(hash)
scope.opts.blockMode = 'output' return partial
return liquid.renderer.renderTemplates(templates, scope)
})
.then(partial => {
scope.pop(hash)
return partial
})
} }
}) })
liquid.registerTag('block', { liquid.registerTag('block', {
parse: function (token, remainTokens) { parse: function (token, remainTokens) {
let match = /\w+/.exec(token.args) const match = /\w+/.exec(token.args)
this.block = match ? match[0] : '' this.block = match ? match[0] : ''
this.tpls = [] this.tpls = []
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop()) .on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl)) .on('template', tpl => this.tpls.push(tpl))
.on('end', () => { .on('end', () => {
@@ -63,20 +59,17 @@ module.exports = function (liquid) {
}) })
stream.start() stream.start()
}, },
render: function (scope) { render: async function (scope) {
return Promise.resolve(scope.opts.blocks[this.block]) const childDefined = scope.opts.blocks[this.block]
.then(html => html === undefined const html = childDefined !== undefined
// render default block ? childDefined
? liquid.renderer.renderTemplates(this.tpls, scope) : await liquid.renderer.renderTemplates(this.tpls, scope)
// use child-defined block
: html) if (scope.opts.blockMode === 'store') {
.then(html => { scope.opts.blocks[this.block] = html
if (scope.opts.blockMode === 'store') { return ''
scope.opts.blocks[this.block] = html }
return '' return html
}
return html
})
} }
}) })
} }
+2 -2
View File
@@ -1,9 +1,9 @@
module.exports = function (liquid) { export default function (liquid) {
liquid.registerTag('raw', { liquid.registerTag('raw', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
this.tokens = [] this.tokens = []
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
stream stream
.on('token', token => { .on('token', token => {
if (token.name === 'endraw') stream.stop() if (token.name === 'endraw') stream.stop()
+34 -47
View File
@@ -1,17 +1,16 @@
import Liquid from '..'
import {mapSeries} from '../util/promise.js' import {mapSeries} from '../util/promise.js'
import assert from '../util/assert.js' import assert from '../util/assert.js'
const lexical = Liquid.lexical export default function (liquid, Liquid) {
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` + const lexical = Liquid.lexical
`(${lexical.value.source})` + const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(?:\\s+${lexical.hash.source})*$`) `(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function (liquid) {
liquid.registerTag('tablerow', { liquid.registerTag('tablerow', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
let match = re.exec(tagToken.args) const match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`) assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1] this.variable = match[1]
@@ -19,7 +18,7 @@ module.exports = function (liquid) {
this.templates = [] this.templates = []
let p let p
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates)) .on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop()) .on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl)) .on('template', tpl => p.push(tpl))
@@ -30,54 +29,42 @@ module.exports = function (liquid) {
stream.start() stream.start()
}, },
render: function (scope, hash) { render: async function (scope, hash) {
let collection = Liquid.evalExp(this.collection, scope) || [] let collection = Liquid.evalExp(this.collection, scope) || []
const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit
let html = ''
let offset = hash.offset || 0
let limit = (hash.limit === undefined) ? collection.length : hash.limit
let cols = hash.cols
let row
let col
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit) collection = collection.slice(offset, offset + limit)
if (!cols) cols = collection.length const cols = hash.cols || collection.length
let contexts = collection.map((item, i) => { const contexts = collection.map((item, i) => {
let ctx = {} const ctx = {}
ctx[this.variable] = item ctx[this.variable] = item
return ctx return ctx
}) })
return mapSeries(contexts, let row
(context, idx) => { let html = ''
row = Math.floor(idx / cols) + 1 await mapSeries(contexts, async (context, idx) => {
col = (idx % cols) + 1 row = Math.floor(idx / cols) + 1
if (col === 1) { const col = (idx % cols) + 1
if (row !== 1) { if (col === 1) {
html += '</tr>' if (row !== 1) {
}
html += `<tr class="row${row}">`
}
html += `<td class="col${col}">`
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
.then((partial) => {
scope.pop(context)
html += partial
html += '</td>'
return html
})
})
.then(() => {
if (row > 0) {
html += '</tr>' html += '</tr>'
} }
return html html += `<tr class="row${row}">`
}) }
html += `<td class="col${col}">`
scope.push(context)
html += await liquid.renderer.renderTemplates(this.templates, scope)
html += '</td>'
scope.pop(context)
return html
})
if (row > 0) {
html += '</tr>'
}
return html
} }
}) })
} }
+3 -5
View File
@@ -1,12 +1,10 @@
import Liquid from '../index' export default function (liquid, Liquid) {
module.exports = function (liquid) {
liquid.registerTag('unless', { liquid.registerTag('unless', {
parse: function (tagToken, remainTokens) { parse: function (tagToken, remainTokens) {
this.templates = [] this.templates = []
this.elseTemplates = [] this.elseTemplates = []
let p let p
let stream = liquid.parser.parseStream(remainTokens) const stream = liquid.parser.parseStream(remainTokens)
.on('start', x => { .on('start', x => {
p = this.templates p = this.templates
this.cond = tagToken.args this.cond = tagToken.args
@@ -22,7 +20,7 @@ module.exports = function (liquid) {
}, },
render: function (scope, hash) { render: function (scope, hash) {
let cond = Liquid.evalExp(this.cond, scope) const cond = Liquid.evalExp(this.cond, scope)
return Liquid.isFalsy(cond) return Liquid.isFalsy(cond)
? liquid.renderer.renderTemplates(this.templates, scope) ? liquid.renderer.renderTemplates(this.templates, scope)
: liquid.renderer.renderTemplates(this.elseTemplates, scope) : liquid.renderer.renderTemplates(this.elseTemplates, scope)
+15 -16
View File
@@ -1,17 +1,19 @@
const lexical = require('./lexical.js') import * as lexical from './lexical.js'
const TokenizationError = require('./util/error.js').TokenizationError import {TokenizationError} from './util/error.js'
const _ = require('./util/underscore.js') import * as _ from './util/underscore.js'
const whiteSpaceCtrl = require('./whitespace-ctrl.js') import assert from './util/assert.js'
const assert = require('./util/assert.js') import whiteSpaceCtrl from './whitespace-ctrl.js'
function parse (input, file, options) { export {default as whiteSpaceCtrl} from './whitespace-ctrl.js'
export function parse (input, file, options) {
assert(_.isString(input), 'illegal input') assert(_.isString(input), 'illegal input')
let rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g const rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
let currIndent = 0 let currIndent = 0
let lineNumber = LineNumber(input) const lineNumber = LineNumber(input)
let lastMatchEnd = 0 let lastMatchEnd = 0
let tokens = [] const tokens = []
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) { for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
if (match.index > lastMatchEnd) { if (match.index > lastMatchEnd) {
@@ -28,8 +30,8 @@ function parse (input, file, options) {
return tokens return tokens
function parseTagToken (raw, value, pos) { function parseTagToken (raw, value, pos) {
let match = value.match(lexical.tagLine) const match = value.match(lexical.tagLine)
let token = { const token = {
type: 'tag', type: 'tag',
indent: currIndent, indent: currIndent,
line: lineNumber.get(pos), line: lineNumber.get(pos),
@@ -62,7 +64,7 @@ function parse (input, file, options) {
} }
function parseHTMLToken (begin, end) { function parseHTMLToken (begin, end) {
let htmlFragment = input.slice(begin, end) const htmlFragment = input.slice(begin, end)
currIndent = _.last((htmlFragment).split('\n')).length currIndent = _.last((htmlFragment).split('\n')).length
return { return {
@@ -79,13 +81,10 @@ function LineNumber (html) {
return { return {
get: function (pos) { get: function (pos) {
let lines = html.slice(lastMatchBegin + 1, pos).split('\n') const lines = html.slice(lastMatchBegin + 1, pos).split('\n')
parsedLinesCount += lines.length - 1 parsedLinesCount += lines.length - 1
lastMatchBegin = pos lastMatchBegin = pos
return parsedLinesCount + 1 return parsedLinesCount + 1
} }
} }
} }
exports.parse = parse
exports.whiteSpaceCtrl = whiteSpaceCtrl
+2 -4
View File
@@ -1,10 +1,8 @@
const AssertionError = require('./error.js').AssertionError import {AssertionError} from './error.js'
function assert (predicate, message) { export default function (predicate, message) {
if (!predicate) { if (!predicate) {
message = message || `expect ${predicate} to be true` message = message || `expect ${predicate} to be true`
throw new AssertionError(message) throw new AssertionError(message)
} }
} }
module.exports = assert
+9 -9
View File
@@ -1,4 +1,4 @@
import _ from './underscore.js' import * as _ from './underscore.js'
function initError () { function initError () {
this.name = this.constructor.name this.name = this.constructor.name
@@ -14,7 +14,7 @@ function initLiquidError (err, token) {
this.line = token.line this.line = token.line
this.file = token.file this.file = token.file
let context = mkContext(token.input, token.line) const context = mkContext(token.input, token.line)
this.message = mkMessage(err.message, token) this.message = mkMessage(err.message, token)
this.stack = context + this.stack = context +
'\n' + (this.stack || this.message) + '\n' + (this.stack || this.message) +
@@ -64,11 +64,11 @@ AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype.constructor = AssertionError AssertionError.prototype.constructor = AssertionError
function mkContext (input, line) { function mkContext (input, line) {
let lines = input.split('\n') const lines = input.split('\n')
let begin = Math.max(line - 2, 1) const begin = Math.max(line - 2, 1)
let end = Math.min(line + 3, lines.length) const end = Math.min(line + 3, lines.length)
let context = _ const context = _
.range(begin, end + 1) .range(begin, end + 1)
.map(l => [ .map(l => [
(l === line) ? '>> ' : ' ', (l === line) ? '>> ' : ' ',
@@ -82,9 +82,9 @@ function mkContext (input, line) {
} }
function align (n, max) { function align (n, max) {
let length = (max + '').length const length = (max + '').length
let str = n + '' const str = n + ''
let blank = Array(length - str.length).join(' ') const blank = Array(length - str.length).join(' ')
return blank + str return blank + str
} }
+3 -8
View File
@@ -1,6 +1,6 @@
const fs = require('fs') import fs from 'fs'
function readFileAsync (filepath) { export function readFileAsync (filepath) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
fs.readFile(filepath, 'utf8', function (err, content) { fs.readFile(filepath, 'utf8', function (err, content) {
err ? reject(err) : resolve(content) err ? reject(err) : resolve(content)
@@ -8,13 +8,8 @@ function readFileAsync (filepath) {
}) })
}; };
function statFileAsync (path) { export function statFileAsync (path) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat)) fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
}) })
}; };
module.exports = {
readFileAsync,
statFileAsync
}
+17
View File
@@ -0,0 +1,17 @@
export function get (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error('An error occurred whilst sending the response.'))
}
xhr.open('GET', url)
xhr.send()
})
}
+3 -6
View File
@@ -4,7 +4,7 @@
* @param {Array} iteratee returns a new promise. * @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable). * The iteratee is invoked with three arguments: (value, index, iterable).
*/ */
function anySeries (iterable, iteratee) { export function anySeries (iterable, iteratee) {
let ret = Promise.reject(new Error('init')) let ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) { iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable)) ret = ret.catch(e => iteratee(item, idx, iterable))
@@ -18,9 +18,9 @@ function anySeries (iterable, iteratee) {
* @param {Array} iteratee returns a new promise. * @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable). * The iteratee is invoked with three arguments: (value, index, iterable).
*/ */
function mapSeries (iterable, iteratee) { export function mapSeries (iterable, iteratee) {
let ret = Promise.resolve('init') let ret = Promise.resolve('init')
let result = [] const result = []
iterable.forEach(function (item, idx) { iterable.forEach(function (item, idx) {
ret = ret ret = ret
.then(() => iteratee(item, idx, iterable)) .then(() => iteratee(item, idx, iterable))
@@ -28,6 +28,3 @@ function mapSeries (iterable, iteratee) {
}) })
return ret.then(() => result) return ret.then(() => result)
} }
exports.anySeries = anySeries
exports.mapSeries = mapSeries
+21 -23
View File
@@ -1,16 +1,16 @@
let monthNames = [ const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December' 'September', 'October', 'November', 'December'
] ]
let monthNamesShort = [ const monthNamesShort = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec' 'Nov', 'Dec'
] ]
let dayNames = [ const dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
] ]
let dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] const dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
let suffixes = { const suffixes = {
1: 'st', 1: 'st',
2: 'nd', 2: 'nd',
3: 'rd', 3: 'rd',
@@ -18,9 +18,9 @@ let suffixes = {
} }
// prototype extensions // prototype extensions
let _date = { const _date = {
daysInMonth: function (d) { daysInMonth: function (d) {
let feb = _date.isLeapYear(d) ? 29 : 28 const feb = _date.isLeapYear(d) ? 29 : 28
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
}, },
@@ -36,21 +36,21 @@ let _date = {
// TODO: that comment was retarted. fix it. // TODO: that comment was retarted. fix it.
getWeekOfYear: function (d, startDay) { getWeekOfYear: function (d, startDay) {
// Skip to startDay of this week // Skip to startDay of this week
let now = this.getDayOfYear(d) + (startDay - d.getDay()) const now = this.getDayOfYear(d) + (startDay - d.getDay())
// Find the first startDay of the year // Find the first startDay of the year
let jan1 = new Date(d.getFullYear(), 0, 1) const jan1 = new Date(d.getFullYear(), 0, 1)
let then = (7 - jan1.getDay() + startDay) const then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2) return _number.pad(Math.floor((now - then) / 7) + 1, 2)
}, },
isLeapYear: function (d) { isLeapYear: function (d) {
let year = d.getFullYear() const year = d.getFullYear()
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year))) return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
}, },
getSuffix: function (d) { getSuffix: function (d) {
let str = d.getDate().toString() const str = d.getDate().toString()
let index = parseInt(str.slice(-1)) const index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default'] return suffixes[index] || suffixes['default']
}, },
@@ -59,7 +59,7 @@ let _date = {
} }
} }
let _number = { const _number = {
pad: function (value, size, ch) { pad: function (value, size, ch) {
if (!ch) ch = '0' if (!ch) ch = '0'
let result = value.toString() let result = value.toString()
@@ -73,7 +73,7 @@ let _number = {
} }
} }
let formatCodes = { const formatCodes = {
a: function (d) { a: function (d) {
return dayNamesShort[d.getDay()] return dayNamesShort[d.getDay()]
}, },
@@ -162,7 +162,7 @@ let formatCodes = {
return d.getFullYear() return d.getFullYear()
}, },
z: function (d) { z: function (d) {
let tz = d.getTimezoneOffset() / 60 * 100 const tz = d.getTimezoneOffset() / 60 * 100
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4) return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
}, },
'%': function () { '%': function () {
@@ -172,13 +172,13 @@ let formatCodes = {
formatCodes.h = formatCodes.b formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L formatCodes.N = formatCodes.L
let strftime = function (d, format) { export default function (d, format) {
let output = '' let output = ''
let remaining = format let remaining = format
while (true) { while (true) {
let r = /%./g const r = /%./g
let results = r.exec(remaining) const results = r.exec(remaining)
// No more format codes. Add the remaining text and return // No more format codes. Add the remaining text and return
if (!results) { if (!results) {
@@ -190,10 +190,8 @@ let strftime = function (d, format) {
remaining = remaining.slice(r.lastIndex) remaining = remaining.slice(r.lastIndex)
// Add the format code // Add the format code
let ch = results[0].charAt(1) const ch = results[0].charAt(1)
let func = formatCodes[ch] const func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch output += func ? func.call(this, d) : '%' + ch
} }
} }
module.exports = strftime
+19 -36
View File
@@ -5,11 +5,11 @@ const toStr = Object.prototype.toString
* @param {any} value The value to check. * @param {any} value The value to check.
* @return {Boolean} Returns true if value is a string, else false. * @return {Boolean} Returns true if value is a string, else false.
*/ */
function isString (value) { export function isString (value) {
return toStr.call(value) === '[object String]' return toStr.call(value) === '[object String]'
} }
function stringify (value) { export function stringify (value) {
if (isNil(value)) { if (isNil(value)) {
return String(value) return String(value)
} }
@@ -23,7 +23,7 @@ function stringify (value) {
return value return value
} }
let cache = [] const cache = []
return JSON.stringify(value, (key, value) => { return JSON.stringify(value, (key, value) => {
if (isObject(value)) { if (isObject(value)) {
if (cache.indexOf(value) !== -1) { if (cache.indexOf(value) !== -1) {
@@ -35,17 +35,17 @@ function stringify (value) {
}) })
} }
function isNil (value) { export function isNil (value) {
return value === null || value === undefined return value === null || value === undefined
} }
function isArray (value) { export function isArray (value) {
// be compatible with IE 8 // be compatible with IE 8
return toStr.call(value) === '[object Array]' return toStr.call(value) === '[object Array]'
} }
function isError (value) { export function isError (value) {
let signature = Object.prototype.toString.call(value) const signature = Object.prototype.toString.call(value)
// [object XXXError] // [object XXXError]
return signature.substr(-6, 5) === 'Error' || return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string') (typeof value.message === 'string' && typeof value.name === 'string')
@@ -59,9 +59,9 @@ function isError (value) {
* @param {Function} iteratee The function invoked per iteration. * @param {Function} iteratee The function invoked per iteration.
* @return {Object} Returns object. * @return {Object} Returns object.
*/ */
function forOwn (object, iteratee) { export function forOwn (object, iteratee) {
object = object || {} object = object || {}
for (let k in object) { for (const k in object) {
if (object.hasOwnProperty(k)) { if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break if (iteratee(object[k], k, object) === false) break
} }
@@ -80,20 +80,20 @@ function forOwn (object, iteratee) {
* @param {...Object} sources The source objects. * @param {...Object} sources The source objects.
* @return {Object} Returns object. * @return {Object} Returns object.
*/ */
function assign (object) { export function assign (object) {
object = isObject(object) ? object : {} object = isObject(object) ? object : {}
let srcs = Array.prototype.slice.call(arguments, 1) const srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach((src) => Object.assign(object, src)) srcs.forEach((src) => Object.assign(object, src))
return object return object
} }
function last (arr) { export function last (arr) {
return arr[arr.length - 1] return arr[arr.length - 1]
} }
function uniq (arr) { export function uniq (arr) {
let u = {} const u = {}
let a = [] const a = []
for (let i = 0, l = arr.length; i < l; ++i) { for (let i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) { if (u.hasOwnProperty(arr[i])) {
continue continue
@@ -110,8 +110,8 @@ function uniq (arr) {
* @param {any} value The value to check. * @param {any} value The value to check.
* @return {Boolean} Returns true if value is an object, else false. * @return {Boolean} Returns true if value is an object, else false.
*/ */
function isObject (value) { export function isObject (value) {
let type = typeof value const type = typeof value
return value != null && (type === 'object' || type === 'function') return value != null && (type === 'object' || type === 'function')
} }
@@ -123,33 +123,16 @@ function isObject (value) {
* Note that ranges that stop before they start are considered to be zero-length instead of * Note that ranges that stop before they start are considered to be zero-length instead of
* negative if you'd like a negative range, use a negative step. * negative if you'd like a negative range, use a negative step.
*/ */
function range (start, stop, step) { export function range (start, stop, step) {
if (arguments.length === 1) { if (arguments.length === 1) {
stop = start stop = start
start = 0 start = 0
} }
step = step || 1 step = step || 1
let arr = [] const arr = []
for (let i = start; i < stop; i += step) { for (let i = start; i < stop; i += step) {
arr.push(i) arr.push(i)
} }
return arr return arr
} }
// lang
exports.isString = isString
exports.isObject = isObject
exports.isArray = isArray
exports.isNil = isNil
exports.isError = isError
// array
exports.range = range
exports.last = last
// object
exports.forOwn = forOwn
exports.assign = assign
exports.uniq = uniq
exports.stringify = stringify
+20 -4
View File
@@ -1,5 +1,4 @@
import resolveUrl from 'resolve-url' import {last, isArray} from './underscore'
import _ from './underscore'
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/ const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/ const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
@@ -15,11 +14,28 @@ export function valid (path) {
} }
export function resolve (root, path) { export function resolve (root, path) {
if (Object.prototype.toString.call(root) === '[object Array]') { if (isArray(root)) {
root = root[0] root = root[0]
} }
if (root && _.last(root) !== '/') { if (root && last(root) !== '/') {
root += '/' root += '/'
} }
return resolveUrl(root, path) return resolveUrl(root, path)
} }
function resolveUrl (root, path) {
const base = document.createElement('base')
base.href = arguments[0]
const head = document.getElementsByTagName('head')[0]
head.insertBefore(base, head.firstChild)
const a = document.createElement('a')
a.href = path
const resolved = a.href
base.href = resolved
head.removeChild(base)
return resolved
}
+5 -7
View File
@@ -1,7 +1,7 @@
const _ = require('./util/underscore.js') import {assign} from './util/underscore.js'
function whiteSpaceCtrl (tokens, options) { export default function whiteSpaceCtrl (tokens, options) {
options = _.assign({ greedy: true }, options) options = assign({ greedy: true }, options)
let inRaw = false let inRaw = false
tokens.forEach((token, i) => { tokens.forEach((token, i) => {
@@ -33,15 +33,13 @@ function shouldTrimRight (token, inRaw, options) {
function trimLeft (token, greedy) { function trimLeft (token, greedy) {
if (!token || token.type !== 'html') return if (!token || token.type !== 'html') return
let rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g const rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '') token.value = token.value.replace(rLeft, '')
} }
function trimRight (token, greedy) { function trimRight (token, greedy) {
if (!token || token.type !== 'html') return if (!token || token.type !== 'html') return
let rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g const rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '') token.value = token.value.replace(rRight, '')
} }
module.exports = whiteSpaceCtrl
+12 -9
View File
@@ -1,9 +1,12 @@
const chai = require('chai') import chai from 'chai'
import request from 'supertest'
import express from 'express'
import mock from 'mock-fs'
import Liquid from '../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect const expect = chai.expect
const mock = require('mock-fs') chai.use(chaiAsPromised)
const request = require('supertest')
const express = require('express')
const Liquid = require('../src')
describe('engine#express()', function () { describe('engine#express()', function () {
let app, engine let app, engine
@@ -36,11 +39,11 @@ describe('engine#express()', function () {
.expect(200, done) .expect(200, done)
}) })
it('should pass error when file not found', function (done) { it('should pass error when file not found', function (done) {
let view = { const view = {
root: [] root: []
} }
let file = '/not-exist.html' const file = '/not-exist.html'
let ctx = {} const ctx = {}
engine.express().call(view, file, ctx, function (err) { engine.express().call(view, file, ctx, function (err) {
try { try {
expect(err.code).to.equal('ENOENT') expect(err.code).to.equal('ENOENT')
@@ -82,7 +85,7 @@ describe('engine#express()', function () {
.expect(200, done) .expect(200, done)
}) })
it('should respect express views (Undefined) when lookup', function (done) { it('should respect express views (Undefined) when lookup', function (done) {
let files = {} const files = {}
files[process.cwd() + '/views/include.html'] = '{% include file %}' files[process.cwd() + '/views/include.html'] = '{% include file %}'
files[process.cwd() + '/views/bar.html'] = 'bar' files[process.cwd() + '/views/bar.html'] = 'bar'
mock(files) mock(files)
+16 -16
View File
@@ -1,21 +1,21 @@
const chai = require('chai') import chai from 'chai'
const sinon = require('sinon') import sinon from 'sinon'
const sinonChai = require('sinon-chai') import sinonChai from 'sinon-chai'
const expect = chai.expect import Filter from '../src/filter.js'
import {factory as scopeFactory} from '../src/scope.js'
chai.use(sinonChai) chai.use(sinonChai)
const expect = chai.expect
let filter = require('../src/filter.js')() const filter = Filter()
let Scope = require('../src/scope.js')
describe('filter', function () { describe('filter', function () {
let scope let scope
beforeEach(function () { beforeEach(function () {
filter.clear() filter.clear()
scope = Scope.factory() scope = scopeFactory()
}) })
it('should return default filter when not registered', function () { it('should return default filter when not registered', function () {
let result = filter.construct('foo') const result = filter.construct('foo')
expect(result.name).to.equal('foo') expect(result.name).to.equal('foo')
}) })
@@ -27,7 +27,7 @@ describe('filter', function () {
it('should parse argument syntax', function () { it('should parse argument syntax', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: a, "b"') const f = filter.construct('foo: a, "b"')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['a', '"b"']) expect(f.args).to.deep.equal(['a', '"b"'])
@@ -49,7 +49,7 @@ describe('filter', function () {
}) })
it('should call filter with corrct arguments', function () { it('should call filter with corrct arguments', function () {
let spy = sinon.spy() const spy = sinon.spy()
filter.register('foo', spy) filter.register('foo', spy)
filter.construct('foo: 33').render('foo', scope) filter.construct('foo: 33').render('foo', scope)
expect(spy).to.have.been.calledWith('foo', 33) expect(spy).to.have.been.calledWith('foo', 33)
@@ -57,35 +57,35 @@ describe('filter', function () {
it('should support arguments as named key/values', function () { it('should support arguments as named key/values', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: key1: "literal1", key2: value2') const f = filter.construct('foo: key1: "literal1", key2: value2')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ]) expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
}) })
it('should support arguments as named key/values with inline literals', function () { it('should support arguments as named key/values with inline literals', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: "test0", key1: "literal1", key2: value2') const f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ]) expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
}) })
it('should support arguments as named key/values with inline values', function () { it('should support arguments as named key/values with inline values', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: test0, key1: "literal1", key2: value2') const f = filter.construct('foo: test0, key1: "literal1", key2: value2')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ]) expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
}) })
it('should support argument values named same as keys', function () { it('should support argument values named same as keys', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: a: a') const f = filter.construct('foo: a: a')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', 'a']) expect(f.args).to.deep.equal(['\'a\'', 'a'])
}) })
it('should support argument literals named same as keys', function () { it('should support argument literals named same as keys', function () {
filter.register('foo', x => x) filter.register('foo', x => x)
let f = filter.construct('foo: a: "a"') const f = filter.construct('foo: a: "a"')
expect(f.name).to.equal('foo') expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', '"a"']) expect(f.args).to.deep.equal(['\'a\'', '"a"'])
}) })
+8 -8
View File
@@ -6,7 +6,7 @@ chai.use(chaiAsPromised)
const liquid = new Liquid() const liquid = new Liquid()
const expect = chai.expect const expect = chai.expect
let ctx = { const ctx = {
date: new Date(), date: new Date(),
foo: 'bar', foo: 'bar',
arr: [-2, 'a'], arr: [-2, 'a'],
@@ -85,7 +85,7 @@ describe('filters', function () {
describe('date', function () { describe('date', function () {
it('should support date: %a %b %d %Y', function () { it('should support date: %a %b %d %Y', function () {
let str = ctx.date.toDateString() const str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str) return test('{{ date | date:"%a %b %d %Y"}}', str)
}) })
it('should create a new Date when given "now"', function () { it('should create a new Date when given "now"', function () {
@@ -142,7 +142,7 @@ describe('filters', function () {
}) })
it('should support split/first', function () { it('should support split/first', function () {
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' + const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}' '{{ my_array | first }}'
return test(src, 'apples') return test(src, 'apples')
}) })
@@ -155,19 +155,19 @@ describe('filters', function () {
}) })
it('should support join', function () { it('should support join', function () {
let src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' + const src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}' '{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo') return test(src, 'John and Paul and George and Ringo')
}) })
it('should support split/last', function () { it('should support split/last', function () {
let src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' + const src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}' '{{ my_array|last }}'
return test(src, 'tiger') return test(src, 'tiger')
}) })
it('should support lstrip', function () { it('should support lstrip', function () {
let src = '{{ " So much room for activities! " | lstrip }}' const src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ') return test(src, 'So much room for activities! ')
}) })
@@ -193,12 +193,12 @@ describe('filters', function () {
}) })
it('should support string_with_newlines', function () { it('should support string_with_newlines', function () {
let src = '{% capture string_with_newlines %}\n' + const src = '{% capture string_with_newlines %}\n' +
'Hello\n' + 'Hello\n' +
'there\n' + 'there\n' +
'{% endcapture %}' + '{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}' '{{ string_with_newlines | newline_to_br }}'
let dst = '<br />' + const dst = '<br />' +
'Hello<br />' + 'Hello<br />' +
'there<br />' 'there<br />'
return test(src, dst) return test(src, dst)
+12 -10
View File
@@ -1,8 +1,10 @@
const chai = require('chai') import chai from 'chai'
import mock from 'mock-fs'
import Liquid from '../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect const expect = chai.expect
const Liquid = require('../src') chai.use(chaiAsPromised)
const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
describe('liquid', function () { describe('liquid', function () {
let engine, strictEngine, ctx let engine, strictEngine, ctx
@@ -37,7 +39,7 @@ describe('liquid', function () {
}) })
describe('Liquid', function () { describe('Liquid', function () {
it('should ignore invalid root option', function () { it('should ignore invalid root option', function () {
let liquid = Liquid({ root: /regex/ }) const liquid = Liquid({ root: /regex/ })
expect(liquid.options.root).to.deep.equal([]) expect(liquid.options.root).to.deep.equal([])
}) })
}) })
@@ -68,18 +70,18 @@ describe('liquid', function () {
}).to.not.throw() }).to.not.throw()
}) })
it('should render template multiple times', function () { it('should render template multiple times', function () {
let template = engine.parse('{{obj}}') const template = engine.parse('{{obj}}')
return engine.render(template, ctx) return engine.render(template, ctx)
.then(result => expect(result).to.equal('{"foo":"bar"}')) .then(result => expect(result).to.equal('{"foo":"bar"}'))
.then(() => engine.render(template, ctx)) .then(() => engine.render(template, ctx))
.then((result) => expect(result).to.equal('{"foo":"bar"}')) .then((result) => expect(result).to.equal('{"foo":"bar"}'))
}) })
it('should render filters', function () { it('should render filters', function () {
let template = engine.parse('<p>{{arr | join: "_"}}</p>') const template = engine.parse('<p>{{arr | join: "_"}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>') return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
}) })
it('should render accessive filters', function () { it('should render accessive filters', function () {
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' + const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}' '{{ my_array | first }}'
return expect(engine.parseAndRender(src)).to.eventually.equal('apples') return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
}) })
@@ -89,7 +91,7 @@ describe('liquid', function () {
.to.eventually.equal('foo') .to.eventually.equal('foo')
}) })
it('should find files without extname', function () { it('should find files without extname', function () {
let engine = Liquid({root: '/root'}) const engine = Liquid({root: '/root'})
return expect(engine.renderFile('/root/files/bar', ctx)) return expect(engine.renderFile('/root/files/bar', ctx))
.to.eventually.equal('bar') .to.eventually.equal('bar')
}) })
@@ -106,7 +108,7 @@ describe('liquid', function () {
.to.eventually.equal('foo') .to.eventually.equal('foo')
}) })
it('should default root to cwd', function () { it('should default root to cwd', function () {
let files = {} const files = {}
files[process.cwd() + '/foo.html'] = 'FOO' files[process.cwd() + '/foo.html'] = 'FOO'
mock(files) mock(files)
+6 -6
View File
@@ -1,7 +1,7 @@
const chai = require('chai') const chai = require('chai')
const expect = chai.expect const expect = chai.expect
let lexical = require('../src/lexical.js') const lexical = require('../src/lexical.js')
describe('lexical', function () { describe('lexical', function () {
it('should test filter syntax', function () { it('should test filter syntax', function () {
@@ -105,26 +105,26 @@ describe('lexical', function () {
}) })
it('should throw if non-literal', function () { it('should throw if non-literal', function () {
let fn = () => lexical.parseLiteral('a') const fn = () => lexical.parseLiteral('a')
expect(fn).to.throw("cannot parse 'a' as literal") expect(fn).to.throw("cannot parse 'a' as literal")
}) })
}) })
describe('.matchValue()', function () { describe('.matchValue()', function () {
it('should match -5-5', function () { it('should match -5-5', function () {
let match = lexical.matchValue('-5-5') const match = lexical.matchValue('-5-5')
expect(match && match[0]).to.equal('-5-5') expect(match && match[0]).to.equal('-5-5')
}) })
it('should match 4-3', function () { it('should match 4-3', function () {
let match = lexical.matchValue('4-3') const match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3') expect(match && match[0]).to.equal('4-3')
}) })
it('should match 4-3', function () { it('should match 4-3', function () {
let match = lexical.matchValue('4-3') const match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3') expect(match && match[0]).to.equal('4-3')
}) })
it('should match var-1', function () { it('should match var-1', function () {
let match = lexical.matchValue('var-1') const match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1') expect(match && match[0]).to.equal('var-1')
}) })
}) })
+6 -4
View File
@@ -1,8 +1,10 @@
const chai = require('chai') import chai from 'chai'
import mock from 'mock-fs'
import Liquid from '../../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect const expect = chai.expect
const mock = require('mock-fs') chai.use(chaiAsPromised)
const Liquid = require('../../src')
chai.use(require('chai-as-promised'))
describe('cache options', function () { describe('cache options', function () {
let engine let engine
+5 -5
View File
@@ -6,7 +6,7 @@ chai.use(require('chai-as-promised'))
describe('strict options', function () { describe('strict options', function () {
let engine let engine
let ctx = {} const ctx = {}
beforeEach(function () { beforeEach(function () {
engine = Liquid({ engine = Liquid({
root: '/root/', root: '/root/',
@@ -18,16 +18,16 @@ describe('strict options', function () {
.eventually.equal('beforeafter') .eventually.equal('beforeafter')
}) })
it('should throw when strict_variables true', function () { it('should throw when strict_variables true', function () {
let tpl = engine.parse('before{{notdefined}}after') const tpl = engine.parse('before{{notdefined}}after')
let opts = { const opts = {
strict_variables: true strict_variables: true
} }
return expect(engine.render(tpl, ctx, opts)).to return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/) .be.rejectedWith(/undefined variable: notdefined/)
}) })
it('should pass strict_variables to render by parseAndRender', function () { it('should pass strict_variables to render by parseAndRender', function () {
let html = 'before{{notdefined}}after' const html = 'before{{notdefined}}after'
let opts = { const opts = {
strict_variables: true strict_variables: true
} }
return expect(engine.parseAndRender(html, ctx, opts)).to return expect(engine.parseAndRender(html, ctx, opts)).to
+21 -19
View File
@@ -1,62 +1,64 @@
const chai = require('chai') import chai from 'chai'
import Liquid from '../../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect const expect = chai.expect
const Liquid = require('../../src') chai.use(chaiAsPromised)
chai.use(require('chai-as-promised'))
describe('trimming', function () { describe('trimming', function () {
let ctx = {name: 'harttle'} const ctx = {name: 'harttle'}
describe('tag trimming', function () { describe('tag trimming', function () {
it('should respect trim_tag_left', function () { it('should respect trim_tag_left', function () {
let engine = Liquid({ trim_tag_left: true }) const engine = Liquid({ trim_tag_left: true })
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} ')) return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal('foo ') .to.eventually.equal('foo ')
}) })
it('should respect trim_tag_right', function () { it('should respect trim_tag_right', function () {
let engine = Liquid({ trim_tag_right: true }) const engine = Liquid({ trim_tag_right: true })
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n')) return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo') .to.eventually.equal('\tfoo')
}) })
it('should not trim value', function () { it('should not trim value', function () {
let engine = Liquid({ trim_tag_left: true, trim_tag_right: true }) const engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx)) return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx))
.to.eventually.equal('a harttle b') .to.eventually.equal('a harttle b')
}) })
}) })
describe('value trimming', function () { describe('value trimming', function () {
it('should respect trim_value_left', function () { it('should respect trim_value_left', function () {
let engine = Liquid({ trim_value_left: true }) const engine = Liquid({ trim_value_left: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx)) return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal('harttle ') .to.eventually.equal('harttle ')
}) })
it('should respect trim_value_right', function () { it('should respect trim_value_right', function () {
let engine = Liquid({ trim_value_right: true }) const engine = Liquid({ trim_value_right: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx)) return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal(' \n \tharttle') .to.eventually.equal(' \n \tharttle')
}) })
it('should respect not trim tag', function () { it('should respect not trim tag', function () {
let engine = Liquid({ trim_value_left: true, trim_value_right: true }) const engine = Liquid({ trim_value_left: true, trim_value_right: true })
return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t')) return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t'))
.to.eventually.equal('\t aha \t') .to.eventually.equal('\t aha \t')
}) })
}) })
describe('greedy', function () { describe('greedy', function () {
let src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n ' const src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
it('should enable greedy by default', function () { it('should enable greedy by default', function () {
let engine = Liquid() const engine = Liquid()
return expect(engine.parseAndRender(src, ctx)) return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('aharttle') .to.eventually.equal('aharttle')
}) })
it('should respect to greedy:false by default', function () { it('should respect to greedy:false by default', function () {
let engine = Liquid({greedy: false}) const engine = Liquid({greedy: false})
return expect(engine.parseAndRender(src, ctx)) return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('\n a \nharttle ') .to.eventually.equal('\n a \nharttle ')
}) })
}) })
describe('markup', function () { describe('markup', function () {
it('should support trim using markup', function () { it('should support trim using markup', function () {
let engine = Liquid() const engine = Liquid()
let src = [ const src = [
'{%- assign username = "John G. Chalmers-Smith" -%}', '{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}', '{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!', ' Wow, {{ username }}, you have a long name!',
@@ -64,12 +66,12 @@ describe('trimming', function () {
' Hello there!', ' Hello there!',
'{%- endif -%}' '{%- endif -%}'
].join('\n') ].join('\n')
let dst = 'Wow, John G. Chalmers-Smith, you have a long name!' const dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst) return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should not trim when not specified', function () { it('should not trim when not specified', function () {
let engine = Liquid() const engine = Liquid()
let src = [ const src = [
'{% assign username = "John G. Chalmers-Smith" %}', '{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}', '{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!', ' Wow, {{ username }}, you have a long name!',
@@ -77,7 +79,7 @@ describe('trimming', function () {
' Hello there!', ' Hello there!',
'{% endif %}' '{% endif %}'
].join('\n') ].join('\n')
let dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n' const dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst) return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
}) })
}) })
+13 -11
View File
@@ -1,15 +1,17 @@
const chai = require('chai') import chai from 'chai'
import sinonChai from 'sinon-chai'
import Filter from '../src/filter.js'
import Tag from '../src/tag.js'
import Template from '../src/parser.js'
const expect = chai.expect const expect = chai.expect
const filter = Filter()
chai.use(require('sinon-chai')) const tag = Tag()
chai.use(sinonChai)
let filter = require('../src/filter.js')()
let tag = require('../src/tag.js')()
let Template = require('../src/parser.js')
describe('template', function () { describe('template', function () {
let template let template
let add = (l, r) => l + r const add = (l, r) => l + r
beforeEach(function () { beforeEach(function () {
filter.clear() filter.clear()
@@ -26,21 +28,21 @@ describe('template', function () {
}) })
it('should parse value string', function () { it('should parse value string', function () {
let tpl = template.parseValue('foo') const tpl = template.parseValue('foo')
expect(tpl.type).to.equal('value') expect(tpl.type).to.equal('value')
expect(tpl.initial).to.equal('foo') expect(tpl.initial).to.equal('foo')
expect(tpl.filters).to.deep.equal([]) expect(tpl.filters).to.deep.equal([])
}) })
it('should parse value string with a simple filter', function () { it('should parse value string with a simple filter', function () {
let tpl = template.parseValue('foo | add: 3, "foo"') const tpl = template.parseValue('foo | add: 3, "foo"')
expect(tpl.initial).to.equal('foo') expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(1) expect(tpl.filters.length).to.equal(1)
expect(tpl.filters[0].filter).to.equal(add) expect(tpl.filters[0].filter).to.equal(add)
}) })
it('should parse value string with filters', function () { it('should parse value string with filters', function () {
let tpl = template.parseValue('foo | add: "|" | add') const tpl = template.parseValue('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo') expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2) expect(tpl.filters.length).to.equal(2)
}) })
+32 -32
View File
@@ -1,18 +1,20 @@
'use strict' import chai from 'chai'
const chai = require('chai') import chaiAsPromised from 'chai-as-promised'
const chaiAsPromised = require('chai-as-promised') import sinonChai from 'sinon-chai'
const expect = chai.expect import sinon from 'sinon'
const sinonChai = require('sinon-chai') import Tag from '../src/tag.js'
const sinon = require('sinon') import {factory as scopeFactory} from '../src/scope.js'
import Filter from '../src/filter'
import Render from '../src/render.js'
import parser from '../src/parser.js'
chai.use(sinonChai) chai.use(sinonChai)
chai.use(chaiAsPromised) chai.use(chaiAsPromised)
let tag = require('../src/tag.js')() const expect = chai.expect
let Scope = require('../src/scope.js') const tag = Tag()
let filter = require('../src/filter')() const filter = Filter()
let Render = require('../src/render.js') const Template = parser(tag, filter)
let Template = require('../src/parser.js')(tag, filter)
let render let render
describe('render', function () { describe('render', function () {
@@ -24,43 +26,41 @@ describe('render', function () {
describe('.renderTemplates()', function () { describe('.renderTemplates()', function () {
it('should throw when scope undefined', function () { it('should throw when scope undefined', function () {
expect(function () { expect(render.renderTemplates([])).to.be.rejectedWith(/scope undefined/)
render.renderTemplates([])
}).to.throw(/scope undefined/)
}) })
it('should render html', function () { it('should render html', function () {
let scope = Scope.factory({}) const scope = scopeFactory({})
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>') return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
}) })
}) })
describe('.renderValue()', function () { describe('.renderValue()', function () {
it('should respect to .to_liquid() method', function () { it('should respect to .to_liquid() method', function () {
let scope = Scope.factory({ const scope = scopeFactory({
bar: { to_liquid: x => 'custom' } bar: { to_liquid: x => 'custom' }
}) })
let tpl = Template.parseValue('bar') const tpl = Template.parseValue('bar')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('custom') return expect(render.renderValue(tpl, scope)).to.eventually.equal('custom')
}) })
it('should stringify objects', function () { it('should stringify objects', function () {
let scope = Scope.factory({ const scope = scopeFactory({
foo: { obj: { arr: ['a', 2] } } foo: { obj: { arr: ['a', 2] } }
}) })
let tpl = Template.parseValue('foo') const tpl = Template.parseValue('foo')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"obj":{"arr":["a",2]}}') return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"obj":{"arr":["a",2]}}')
}) })
it('should skip circular property', function () { it('should skip circular property', function () {
let ctx = { foo: { num: 2 }, bar: 'bar' } const ctx = { foo: { num: 2 }, bar: 'bar' }
ctx.foo.circular = ctx ctx.foo.circular = ctx
let scope = Scope.factory(ctx) const scope = scopeFactory(ctx)
let tpl = Template.parseValue('foo') const tpl = Template.parseValue('foo')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"num":2,"circular":{"bar":"bar"}}') return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"num":2,"circular":{"bar":"bar"}}')
}) })
it('should skip function property', function () { it('should skip function property', function () {
let scope = Scope.factory({obj: {foo: 'foo', bar: x => x}}) const scope = scopeFactory({obj: {foo: 'foo', bar: x => x}})
let tpl = Template.parseValue('obj') const tpl = Template.parseValue('obj')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"foo":"foo"}') return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"foo":"foo"}')
}) })
}) })
@@ -74,24 +74,24 @@ describe('render', function () {
it('should eval value', function () { it('should eval value', function () {
filter.register('date', (l, r) => l + r) filter.register('date', (l, r) => l + r)
filter.register('time', (l, r) => l + 3 * r) filter.register('time', (l, r) => l + 3 * r)
let tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2') const tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
let scope = Scope.factory({ const scope = scopeFactory({
foo: { bar: ['a'] } foo: { bar: ['a'] }
}) })
expect(render.evalValue(tpl, scope)).to.equal('ab6') expect(render.evalValue(tpl, scope)).to.equal('ab6')
}) })
it('should reserve type', function () { it('should reserve type', function () {
filter.register('arr', () => [1]) filter.register('arr', () => [1])
let tpl = Template.parseValue('"x" | arr') const tpl = Template.parseValue('"x" | arr')
expect(render.evalValue(tpl, Scope.factory())).to.deep.equal([1]) expect(render.evalValue(tpl, scopeFactory())).to.deep.equal([1])
}) })
it('should eval filter with correct arguments', function () { it('should eval filter with correct arguments', function () {
let date = sinon.stub().returns('y') const date = sinon.stub().returns('y')
let time = sinon.spy() const time = sinon.spy()
filter.register('date', date) filter.register('date', date)
filter.register('time', time) filter.register('time', time)
let tpl = Template.parseValue('foo.bar | date: "b" | time:2') const tpl = Template.parseValue('foo.bar | date: "b" | time:2')
let scope = Scope.factory({ const scope = scopeFactory({
foo: {bar: 'bar'} foo: {bar: 'bar'}
}) })
render.evalValue(tpl, scope) render.evalValue(tpl, scope)
+8 -8
View File
@@ -1,5 +1,5 @@
import chai from 'chai' import chai from 'chai'
import Scope from '../src/scope.js' import {factory as scopeFactory} from '../src/scope.js'
const expect = chai.expect const expect = chai.expect
@@ -14,7 +14,7 @@ describe('scope', function () {
arr: ['a', 'b'] arr: ['a', 'b']
} }
} }
scope = Scope.factory(ctx) scope = scopeFactory(ctx)
}) })
describe('#propertyAccessSeq()', function () { describe('#propertyAccessSeq()', function () {
@@ -88,7 +88,7 @@ describe('scope', function () {
}) })
it('should respect to to_liquid', function () { it('should respect to to_liquid', function () {
let scope = Scope.factory({foo: { const scope = scopeFactory({foo: {
to_liquid: () => ({bar: 'BAR'}), to_liquid: () => ({bar: 'BAR'}),
bar: 'bar' bar: 'bar'
}}) }})
@@ -96,7 +96,7 @@ describe('scope', function () {
}) })
it('should respect to toLiquid', function () { it('should respect to toLiquid', function () {
let scope = Scope.factory({foo: { const scope = scopeFactory({foo: {
toLiquid: () => ({bar: 'BAR'}), toLiquid: () => ({bar: 'BAR'}),
bar: 'bar' bar: 'bar'
}}) }})
@@ -162,7 +162,7 @@ describe('scope', function () {
describe('strict_variables', function () { describe('strict_variables', function () {
let scope let scope
beforeEach(function () { beforeEach(function () {
scope = Scope.factory(ctx, { scope = scopeFactory(ctx, {
strict_variables: true strict_variables: true
}) })
}) })
@@ -227,10 +227,10 @@ describe('scope', function () {
}) })
}) })
it('should pop specified scope', function () { it('should pop specified scope', function () {
let scope1 = { const scope1 = {
foo: 'foo' foo: 'foo'
} }
let scope2 = { const scope2 = {
bar: 'bar' bar: 'bar'
} }
scope.push(scope1) scope.push(scope1)
@@ -242,7 +242,7 @@ describe('scope', function () {
expect(scope.get('bar')).to.equal('bar') expect(scope.get('bar')).to.equal('bar')
}) })
it('should throw when specified scope not found', function () { it('should throw when specified scope not found', function () {
let scope1 = { const scope1 = {
foo: 'foo' foo: 'foo'
} }
expect(() => scope.pop(scope1)).to.throw('scope not found, cannot pop') expect(() => scope.pop(scope1)).to.throw('scope not found, cannot pop')
+6 -6
View File
@@ -1,11 +1,11 @@
const chai = require('chai') const chai = require('chai')
const expect = chai.expect const expect = chai.expect
let syntax = require('../src/syntax.js') const syntax = require('../src/syntax.js')
let Scope = require('../src/scope.js') const Scope = require('../src/scope.js')
let evalExp = syntax.evalExp const evalExp = syntax.evalExp
let evalValue = syntax.evalValue const evalValue = syntax.evalValue
let isTruthy = syntax.isTruthy const isTruthy = syntax.isTruthy
describe('expression', function () { describe('expression', function () {
let scope let scope
@@ -36,7 +36,7 @@ describe('expression', function () {
}) })
it('should throw if not valid', function () { it('should throw if not valid', function () {
let fn = () => evalValue('===') const fn = () => evalValue('===')
expect(fn).to.throw("cannot eval '===' as value") expect(fn).to.throw("cannot eval '===' as value")
}) })
}) })
+41 -40
View File
@@ -1,15 +1,17 @@
const chai = require('chai') import chai from 'chai'
const sinon = require('sinon') import Tag from '../src/tag.js'
const expect = chai.expect import {factory as scopeFactory} from '../src/scope.js'
chai.use(require('sinon-chai')) import sinon from 'sinon'
import sinonChai from 'sinon-chai'
let tag = require('../src/tag.js')() chai.use(sinonChai)
let Scope = require('../src/scope.js') const expect = chai.expect
const tag = Tag()
describe('tag', function () { describe('tag', function () {
let scope let scope
before(function () { before(function () {
scope = Scope.factory({ scope = scopeFactory({
foo: 'bar', foo: 'bar',
arr: [2, 1], arr: [2, 1],
bar: { bar: {
@@ -37,19 +39,18 @@ describe('tag', function () {
}).not.throw() }).not.throw()
}) })
it('should call tag.render', function () { it('should call tag.render', async function () {
let spy = sinon.spy() const spy = sinon.spy()
tag.register('foo', { tag.register('foo', {
render: spy render: spy
}) })
return tag const token = {
.construct({ type: 'tag',
type: 'tag', value: 'foo',
value: 'foo', name: 'foo'
name: 'foo' }
}, []) await tag.construct(token, []).render(scope, {})
.render(scope, {}) expect(spy).to.have.been.called
.then(() => expect(spy).to.have.been.called)
}) })
describe('hash', function () { describe('hash', function () {
@@ -66,33 +67,33 @@ describe('tag', function () {
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo' args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
} }
}) })
it('should call tag.render with scope', function () { it('should call tag.render with scope', async function () {
return tag.construct(token, []).render(scope, {}) await tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope)) expect(spy).to.have.been.calledWithMatch(scope)
}) })
it('should resolve identifier hash', function () { it('should resolve identifier hash', async function () {
return tag.construct(token, []).render(scope, {}) await tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, { expect(spy).to.have.been.calledWithMatch({}, {
aa: 'bar' aa: 'bar'
})) })
}) })
it('should accept space between key/value', function () { it('should accept space between key/value', async function () {
return tag.construct(token, []).render(scope, {}) await tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, { expect(spy).to.have.been.calledWithMatch({}, {
bb: 2 bb: 2
})) })
}) })
it('should resolve number value hash', function () { it('should resolve number value hash', async function () {
return tag.construct(token, []).render(scope, {}) await tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, { expect(spy).to.have.been.calledWithMatch(scope, {
cc: 2.3 cc: 2.3
})) })
}) })
it('should resolve property access hash', function () { it('should resolve property access hash', async function () {
return tag.construct(token, []).render(scope, {}) await tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, { expect(spy).to.have.been.calledWithMatch(scope, {
dd: 'uoo' dd: 'uoo'
})) })
}) })
}) })
}) })
+20 -19
View File
@@ -1,29 +1,30 @@
'use strict' import Liquid from '../../src'
const Liquid = require('../../src') import chai from 'chai'
const chai = require('chai') import sinonChai from 'chai-as-promised'
chai.use(sinonChai)
const expect = chai.expect const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/assign', function () { describe('tags/assign', function () {
let liquid = Liquid() const liquid = Liquid()
it('should throw when variable expression illegal', function () { it('should throw when variable expression illegal', function () {
let src = '{% assign / %}' const src = '{% assign / %}'
let ctx = {} const ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/) return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
}) })
it('should support assign to a string', function () { it('should support assign to a string', function () {
let src = '{% assign foo="bar" %}{{foo}}' const src = '{% assign foo="bar" %}{{foo}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar') .to.eventually.equal('bar')
}) })
it('should support assign to a number', function () { it('should support assign to a number', function () {
let src = '{% assign foo=10086 %}{{foo}}' const src = '{% assign foo=10086 %}{{foo}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('10086') .to.eventually.equal('10086')
}) })
it('should shading rather than overwriting', function () { it('should shading rather than overwriting', function () {
let ctx = {foo: 'foo'} const ctx = {foo: 'foo'}
let src = '{% assign foo="FOO" %}{{foo}}' const src = '{% assign foo="FOO" %}{{foo}}'
return liquid.parseAndRender(src, ctx) return liquid.parseAndRender(src, ctx)
.then(x => { .then(x => {
expect(x).to.equal('FOO') expect(x).to.equal('FOO')
@@ -31,37 +32,37 @@ describe('tags/assign', function () {
}) })
}) })
it('should assign as array', function () { it('should assign as array', function () {
let src = '{% assign foo=(1..3) %}{{foo}}' const src = '{% assign foo=(1..3) %}{{foo}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]') .to.eventually.equal('[1,2,3]')
}) })
it('should assign as filter result', function () { it('should assign as filter result', function () {
let src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}' const src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('A') .to.eventually.equal('A')
}) })
it('should assign var-1', function () { it('should assign var-1', function () {
let src = '{% assign var-1 = 5 %}{{ var-1 }}' const src = '{% assign var-1 = 5 %}{{ var-1 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5') return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
}) })
it('should assign var-', function () { it('should assign var-', function () {
let src = '{% assign var- = 5 %}{{ var- }}' const src = '{% assign var- = 5 %}{{ var- }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5') return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
}) })
it('should assign -var', function () { it('should assign -var', function () {
let src = '{% assign -let = 5 %}{{ -let }}' const src = '{% assign -let = 5 %}{{ -let }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5') return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
}) })
it('should assign -5-5', function () { it('should assign -5-5', function () {
let src = '{% assign -5-5 = 5 %}{{ -5-5 }}' const src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5') return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
}) })
it('should assign 4-3', function () { it('should assign 4-3', function () {
let src = '{% assign 4-3 = 5 %}{{ 4-3 }}' const src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5') return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
}) })
it('should not assign -6', function () { it('should not assign -6', function () {
let src = '{% assign -6 = 5 %}{{ -6 }}' const src = '{% assign -6 = 5 %}{{ -6 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6') return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
}) })
}) })
+6 -6
View File
@@ -5,17 +5,17 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/capture', function () { describe('tags/capture', function () {
let liquid = Liquid() const liquid = Liquid()
it('should support capture', function () { it('should support capture', function () {
let src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}' const src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('A') .to.eventually.equal('A')
}) })
it('should shading rather than overwriting', function () { it('should shading rather than overwriting', function () {
let src = '{% capture var %}10{% endcapture %}{{var}}' const src = '{% capture var %}10{% endcapture %}{{var}}'
let ctx = {'var': 20} const ctx = {'var': 20}
return liquid.parseAndRender(src, ctx) return liquid.parseAndRender(src, ctx)
.then(x => { .then(x => {
expect(x).to.equal('10') expect(x).to.equal('10')
@@ -24,13 +24,13 @@ describe('tags/capture', function () {
}) })
it('should throw on invalid identifier', function () { it('should throw on invalid identifier', function () {
let src = '{% capture = %}{%endcapture%}' const src = '{% capture = %}{%endcapture%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/) .to.be.rejectedWith(/= not valid identifier/)
}) })
it('should throw when capture not closed', function () { it('should throw when capture not closed', function () {
let src = '{%capture c%}{{c}}' const src = '{%capture c%}{{c}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/) .to.be.rejectedWith(/tag .* not closed/)
}) })
+8 -8
View File
@@ -5,46 +5,46 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/case', function () { describe('tags/case', function () {
let liquid = Liquid() const liquid = Liquid()
it('should reject if not closed', function () { it('should reject if not closed', function () {
let src = '{% case "foo"%}' const src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/) .to.be.rejectedWith(/{% case "foo"%} not closed/)
}) })
it('should hit the specified case', function () { it('should hit the specified case', function () {
let src = '{% case "foo"%}' + const src = '{% case "foo"%}' +
'{% when "foo" %}foo{% when "bar"%}bar' + '{% when "foo" %}foo{% when "bar"%}bar' +
'{%endcase%}' '{%endcase%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo') .to.eventually.equal('foo')
}) })
it('should resolve empty string if not hit', function () { it('should resolve empty string if not hit', function () {
let src = '{% case empty %}' + const src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' + '{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}' '{%endcase%}'
let ctx = { const ctx = {
empty: '' empty: ''
} }
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar') .to.eventually.equal('bar')
}) })
it('should accept empty string as branch name', function () { it('should accept empty string as branch name', function () {
let src = '{% case false %}' + const src = '{% case false %}' +
'{% when "foo" %}foo{% when ""%}bar' + '{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}' '{%endcase%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('') .to.eventually.equal('')
}) })
it('should support boolean case', function () { it('should support boolean case', function () {
let src = '{% case false %}' + const src = '{% case false %}' +
'{% when "foo" %}foo{% when false%}bar' + '{% when "foo" %}foo{% when false%}bar' +
'{%endcase%}' '{%endcase%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar') .to.eventually.equal('bar')
}) })
it('should support else branch', function () { it('should support else branch', function () {
let src = '{% case "a" %}' + const src = '{% case "a" %}' +
'{% when "b" %}b{% when "c"%}c{%else %}d' + '{% when "b" %}b{% when "c"%}c{%else %}d' +
'{%endcase%}' '{%endcase%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
+6 -6
View File
@@ -5,29 +5,29 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/comment', function () { describe('tags/comment', function () {
let liquid = Liquid() const liquid = Liquid()
it('should support empty content', function () { it('should support empty content', function () {
let src = '{% comment %}{% raw%}' const src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/) .to.be.rejectedWith(/{% comment %} not closed/)
}) })
it('should ignore plain string', function () { it('should ignore plain string', function () {
let src = 'My name is {% comment %}super{% endcomment %} Shopify.' const src = 'My name is {% comment %}super{% endcomment %} Shopify.'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.') .to.eventually.equal('My name is Shopify.')
}) })
it('should ignore output tokens', function () { it('should ignore output tokens', function () {
let src = '{% comment %}\n{{ foo}} \n{% endcomment %}' const src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('') .to.eventually.equal('')
}) })
it('should ignore tag tokens', function () { it('should ignore tag tokens', function () {
let src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}' const src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('') .to.eventually.equal('')
}) })
it('should ignore un-balenced tag tokens', function () { it('should ignore un-balenced tag tokens', function () {
let src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}' const src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('') .to.eventually.equal('')
}) })
+6 -6
View File
@@ -5,10 +5,10 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/cycle', function () { describe('tags/cycle', function () {
let liquid = Liquid() const liquid = Liquid()
it('should support cycle', function () { it('should support cycle', function () {
let src = "{% cycle '1', '2', '3' %}" const src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src)) return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231') .to.eventually.equal('1231')
}) })
@@ -19,8 +19,8 @@ describe('tags/cycle', function () {
}) })
it('should support cycle in for block', function () { it('should support cycle in for block', function () {
let src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}' const src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
let ctx = { const ctx = {
one: 1 one: 1
} }
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
@@ -28,10 +28,10 @@ describe('tags/cycle', function () {
}) })
it('should support cycle group', function () { it('should support cycle group', function () {
let src = "{% cycle one: '1', '2', '3'%}" + const src = "{% cycle one: '1', '2', '3'%}" +
"{% cycle 1: '1', '2', '3'%}" + "{% cycle 1: '1', '2', '3'%}" +
"{% cycle 2: '1', '2', '3'%}" "{% cycle 2: '1', '2', '3'%}"
let ctx = { const ctx = {
one: 1 one: 1
} }
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
+11 -11
View File
@@ -5,22 +5,22 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/decrement', function () { describe('tags/decrement', function () {
let liquid = Liquid() const liquid = Liquid()
it('should throw when variable expression illegal', function () { it('should throw when variable expression illegal', function () {
let src = '{% decrement / %}{{var}}' const src = '{% decrement / %}{{var}}'
let ctx = {} const ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/) return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
}) })
it('should decrement undefined variable', function () { it('should decrement undefined variable', function () {
let src = '{% decrement var %}{% decrement var %}{% decrement var %}' const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3') .to.eventually.equal('-1-2-3')
}) })
it('should decrement defined variable', function () { it('should decrement defined variable', function () {
let src = '{% decrement var %}{% decrement var %}{% decrement var %}' const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
let ctx = {'var': 10} const ctx = {'var': 10}
return liquid.parseAndRender(src, ctx) return liquid.parseAndRender(src, ctx)
.then(x => { .then(x => {
expect(x).to.equal('987') expect(x).to.equal('987')
@@ -29,31 +29,31 @@ describe('tags/decrement', function () {
}) })
it('should be independent from assign', function () { it('should be independent from assign', function () {
let src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %}' const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3') .to.eventually.equal('-1-2-3')
}) })
it('should be independent from capture', function () { it('should be independent from capture', function () {
let src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %}' const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3') .to.eventually.equal('-1-2-3')
}) })
it('should not shading assign', function () { it('should not shading assign', function () {
let src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}' const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3 10') .to.eventually.equal('-1-2-3 10')
}) })
it('should not shading capture', function () { it('should not shading capture', function () {
let src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}' const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3 10') .to.eventually.equal('-1-2-3 10')
}) })
it('should share the same variable with increment', function () { it('should share the same variable with increment', function () {
let src = '{%increment var%}{%increment var%}{%decrement var%}{%decrement var%}{%increment var%}' const src = '{%increment var%}{%increment var%}{%decrement var%}{%decrement var%}{%increment var%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('01100') .to.eventually.equal('01100')
}) })
+28 -28
View File
@@ -23,25 +23,25 @@ describe('tags/for', function () {
} }
}) })
it('should support array', function () { it('should support array', function () {
let src = '{%for c in alpha%}{{c}}{%endfor%}' const src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc') .to.eventually.equal('abc')
}) })
it('should support object', function () { it('should support object', function () {
let src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}' const src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('foo,bar-coo,haa-') .to.eventually.equal('foo,bar-coo,haa-')
}) })
describe('scope', function () { describe('scope', function () {
it('should read super scope', function () { it('should read super scope', function () {
let src = '{%for a in (1..2)%}{{num}}{%endfor%}' const src = '{%for a in (1..2)%}{{num}}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1})) return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('11') .to.eventually.equal('11')
}) })
it('should write super scope', function () { it('should write super scope', function () {
let src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}' const src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1})) return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('12') .to.eventually.equal('12')
}) })
@@ -49,13 +49,13 @@ describe('tags/for', function () {
describe('illegal', function () { describe('illegal', function () {
it('should reject when for not closed', function () { it('should reject when for not closed', function () {
let src = '{%for c in alpha%}{{c}}' const src = '{%for c in alpha%}{{c}}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/) .to.be.rejectedWith(/tag .* not closed/)
}) })
it('should reject when inner templates rejected', function () { it('should reject when inner templates rejected', function () {
let src = '{%for c in alpha%}{%throwingTag%}{%endfor%}' const src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/intended render error/) .to.be.rejectedWith(/intended render error/)
}) })
@@ -63,51 +63,51 @@ describe('tags/for', function () {
describe('else', function () { describe('else', function () {
it('should goto else for empty array', function () { it('should goto else for empty array', function () {
let src = '{%for c in emptyArray%}a{%else%}b{%endfor%}' const src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b') .to.eventually.equal('b')
}) })
it('should treat non-empty string as one single element', function () { it('should treat non-empty string as one single element', function () {
let src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}' const src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('xabc') .to.eventually.equal('xabc')
}) })
it('should goto else for empty string', function () { it('should goto else for empty string', function () {
let src = '{%for c in ""%}a{%else%}b{%endfor%}' const src = '{%for c in ""%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b') .to.eventually.equal('b')
}) })
it('should goto else for empty string object', function () { it('should goto else for empty string object', function () {
// it should be false although `new String` is none-conform // it should be false although `new String` is none-conform
let src = '{%for c in strObj%}a{%else%}b{%endfor%}' const src = '{%for c in strObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b') .to.eventually.equal('b')
}) })
it('should goto else for empty object', function () { it('should goto else for empty object', function () {
let src = '{%for c in emptyObj%}a{%else%}b{%endfor%}' const src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b') .to.eventually.equal('b')
}) })
it('should goto else for null-prototyped object', function () { it('should goto else for null-prototyped object', function () {
let src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}' const src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b') .to.eventually.equal('b')
}) })
}) })
it('should support for with forloop', function () { it('should support for with forloop', function () {
let src = '{%for c in alpha%}' + const src = '{%for c in alpha%}' +
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' + '{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
'{{forloop.last}}.{{forloop.length}}.' + '{{forloop.last}}.{{forloop.length}}.' +
'{{forloop.rindex}}.{{forloop.rindex0}}' + '{{forloop.rindex}}.{{forloop.rindex0}}' +
'{{c}}\n' + '{{c}}\n' +
'{%endfor%}' '{%endfor%}'
let dst = 'true.1.0.false.3.3.2a\n' + const dst = 'true.1.0.false.3.3.2a\n' +
'false.2.1.false.3.2.1b\n' + 'false.2.1.false.3.2.1b\n' +
'false.3.2.true.3.1.0c\n' 'false.3.2.true.3.1.0c\n'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
@@ -115,14 +115,14 @@ describe('tags/for', function () {
}) })
it('should support for with continue', function () { it('should support for with continue', function () {
let src = '{% for i in (1..5) %}' + const src = '{% for i in (1..5) %}' +
'{{i}}{% continue %}after' + '{{i}}{% continue %}after' +
'{% endfor %}' '{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345') .to.eventually.equal('12345')
}) })
it('should support for with break', function () { it('should support for with break', function () {
let src = '{% for i in (one..5) %}' + const src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' + '{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' + '{{ i }}' +
'{% endfor %}' '{% endfor %}'
@@ -132,22 +132,22 @@ describe('tags/for', function () {
describe('limit', function () { describe('limit', function () {
it('should support for with limit', function () { it('should support for with limit', function () {
let src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}' const src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12') .to.eventually.equal('12')
}) })
it('should set forloop.last properly', function () { it('should set forloop.last properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('false true ') .to.eventually.equal('false true ')
}) })
it('should set forloop.first properly', function () { it('should set forloop.first properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('true false ') .to.eventually.equal('true false ')
}) })
it('should set forloop.length properly', function () { it('should set forloop.length properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 2 ') .to.eventually.equal('2 2 ')
}) })
@@ -155,27 +155,27 @@ describe('tags/for', function () {
describe('offset', function () { describe('offset', function () {
it('should support offset with limit', function () { it('should support offset with limit', function () {
let src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}' const src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67') .to.eventually.equal('67')
}) })
it('should set index properly', function () { it('should set index properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 2 ') .to.eventually.equal('1 2 ')
}) })
it('should set index0 properly', function () { it('should set index0 properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0 1 ') .to.eventually.equal('0 1 ')
}) })
it('should set rindex properly', function () { it('should set rindex properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 1 ') .to.eventually.equal('2 1 ')
}) })
it('should set rindex0 properly', function () { it('should set rindex0 properly', function () {
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}' const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 0 ') .to.eventually.equal('1 0 ')
}) })
@@ -183,19 +183,19 @@ describe('tags/for', function () {
describe('reverse', function () { describe('reverse', function () {
it('should support for reversed in the last position', function () { it('should support for reversed in the last position', function () {
let src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}' const src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21') .to.eventually.equal('21')
}) })
it('should support for reversed in the first position', function () { it('should support for reversed in the first position', function () {
let src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}' const src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21') .to.eventually.equal('21')
}) })
it('should support for reversed in the middle position', function () { it('should support for reversed in the middle position', function () {
let src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}' const src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('543') .to.eventually.equal('543')
}) })
+20 -20
View File
@@ -5,8 +5,8 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/if', function () { describe('tags/if', function () {
let liquid = Liquid() const liquid = Liquid()
let ctx = { const ctx = {
one: 1, one: 1,
two: 2, two: 2,
emptyString: '', emptyString: '',
@@ -14,101 +14,101 @@ describe('tags/if', function () {
} }
it('should throw if not closed', function () { it('should throw if not closed', function () {
let src = '{% if false%}yes' const src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/) .to.be.rejectedWith(/tag {% if false%} not closed/)
}) })
it('should support nested', function () { it('should support nested', function () {
let src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}' const src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('') .to.eventually.equal('')
}) })
describe('single value as condition', function () { describe('single value as condition', function () {
it('should support boolean', function () { it('should support boolean', function () {
let src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}' const src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2') .to.eventually.equal('2')
}) })
it('should treat Array truthy', function () { it('should treat Array truthy', function () {
let src = '{%if emptyArray%}a{%endif%}' const src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a') .to.eventually.equal('a')
}) })
it('should return true if empty string', function () { it('should return true if empty string', function () {
let src = '{%if emptyString%}a{%endif%}' const src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a') .to.eventually.equal('a')
}) })
}) })
describe('expression as condition', function () { describe('expression as condition', function () {
it('should support ==', function () { it('should support ==', function () {
let src = '{% if 2==3 %}yes{%else%}no{%endif%}' const src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should support >=', function () { it('should support >=', function () {
let src = '{% if 1>=2 and one<two %}a{%endif%}' const src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('') .to.eventually.equal('')
}) })
it('should support !=', function () { it('should support !=', function () {
let src = '{% if one!=two %}yes{%else%}no{%endif%}' const src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes') .to.eventually.equal('yes')
}) })
it('should support value and expression', function () { it('should support value and expression', function () {
let src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y` const src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
let ctx = { 'version': '' } const ctx = { 'version': '' }
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('XY') .to.eventually.equal('XY')
}) })
}) })
describe('comparasion to null', function () { describe('comparasion to null', function () {
it('should evaluate false for null < 10', function () { it('should evaluate false for null < 10', function () {
let src = '{% if null < 10 %}yes{% else %}no{% endif %}' const src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for null > 10', function () { it('should evaluate false for null > 10', function () {
let src = '{% if null > 10 %}yes{% else %}no{% endif %}' const src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for null <= 10', function () { it('should evaluate false for null <= 10', function () {
let src = '{% if null <= 10 %}yes{% else %}no{% endif %}' const src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for null >= 10', function () { it('should evaluate false for null >= 10', function () {
let src = '{% if null >= 10 %}yes{% else %}no{% endif %}' const src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for 10 < null', function () { it('should evaluate false for 10 < null', function () {
let src = '{% if 10 < null %}yes{% else %}no{% endif %}' const src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for 10 > null', function () { it('should evaluate false for 10 > null', function () {
let src = '{% if 10 > null %}yes{% else %}no{% endif %}' const src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for 10 <= null', function () { it('should evaluate false for 10 <= null', function () {
let src = '{% if 10 <= null %}yes{% else %}no{% endif %}' const src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should evaluate false for 10 >= null', function () { it('should evaluate false for 10 >= null', function () {
let src = '{% if 10 >= null %}yes{% else %}no{% endif %}' const src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx)) return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
+5 -5
View File
@@ -95,7 +95,7 @@ describe('tags/include', function () {
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>', '/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}' '/address.html': 'City: {{person.address.city}}'
}) })
let ctx = { const ctx = {
person: { person: {
firstName: 'Joe', firstName: 'Joe',
lastName: 'Shmoe', lastName: 'Shmoe',
@@ -114,7 +114,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include child.html color:"red" %}Y', '/parent.html': 'X{% include child.html color:"red" %}Y',
'/child.html': 'child with {{color}}' '/child.html': 'child with {{color}}'
}) })
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'}) const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY') .eventually.equal('Xchild with redY')
}) })
@@ -124,7 +124,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include bar/./../foo/child.html %}Y', '/parent.html': 'X{% include bar/./../foo/child.html %}Y',
'/foo/child.html': 'child' '/foo/child.html': 'child'
}) })
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'}) const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY') .eventually.equal('XchildY')
}) })
@@ -134,7 +134,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include foo/child.html %}Y', '/parent.html': 'X{% include foo/child.html %}Y',
'/foo/child.html': 'child' '/foo/child.html': 'child'
}) })
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'}) const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY') .eventually.equal('XchildY')
}) })
@@ -144,7 +144,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include child.html, color:"red" %}Y', '/parent.html': 'X{% include child.html, color:"red" %}Y',
'/child.html': 'child with {{color}}' '/child.html': 'child with {{color}}'
}) })
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'}) const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY') .eventually.equal('Xchild with redY')
}) })
+8 -8
View File
@@ -5,17 +5,17 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/increment', function () { describe('tags/increment', function () {
let liquid = Liquid() const liquid = Liquid()
it('should increment undefined variable', function () { it('should increment undefined variable', function () {
let src = '{% increment one %}{% increment one %}{% increment one %}' const src = '{% increment one %}{% increment one %}{% increment one %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('012') .to.eventually.equal('012')
}) })
it('should increment defined variable', function () { it('should increment defined variable', function () {
let src = '{% increment one %}{% increment one %}{% increment one %}' const src = '{% increment one %}{% increment one %}{% increment one %}'
let ctx = {one: 7} const ctx = {one: 7}
return liquid.parseAndRender(src, ctx) return liquid.parseAndRender(src, ctx)
.then(x => { .then(x => {
expect(x).to.equal('789') expect(x).to.equal('789')
@@ -24,25 +24,25 @@ describe('tags/increment', function () {
}) })
it('should be independent from assign', function () { it('should be independent from assign', function () {
let src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %}' const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('012') .to.eventually.equal('012')
}) })
it('should be independent from capture', function () { it('should be independent from capture', function () {
let src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %}' const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('012') .to.eventually.equal('012')
}) })
it('should not shading assign', function () { it('should not shading assign', function () {
let src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %} {{var}}' const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('012 10') .to.eventually.equal('012 10')
}) })
it('should not shading capture', function () { it('should not shading capture', function () {
let src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %} {{var}}' const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('012 10') .to.eventually.equal('012 10')
}) })
+8 -8
View File
@@ -21,7 +21,7 @@ describe('tags/layout', function () {
mock({ mock({
'/parent.html': 'parent' '/parent.html': 'parent'
}) })
let src = '{% layout "parent" %}{%block%}A' const src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/) .be.rejectedWith(/tag {%block%} not closed/)
}) })
@@ -39,7 +39,7 @@ describe('tags/layout', function () {
mock({ mock({
'/parent.html': 'X{%block%}{%endblock%}Y' '/parent.html': 'X{%block%}{%endblock%}Y'
}) })
let src = '{% layout "parent.html" %}{%block%}A{%endblock%}' const src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY') .eventually.equal('XAY')
}) })
@@ -47,7 +47,7 @@ describe('tags/layout', function () {
mock({ mock({
'/parent.html': 'X{%block%}{%endblock%}Y' '/parent.html': 'X{%block%}{%endblock%}Y'
}) })
let src = '{% layout "parent.html" %}A' const src = '{% layout "parent.html" %}A'
return expect(liquid.parseAndRender(src)).to return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY') .eventually.equal('XAY')
}) })
@@ -56,7 +56,7 @@ describe('tags/layout', function () {
mock({ mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z' '/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
}) })
let src = '{% layout "parent.html" %}' + const src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' + '{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}' '{%block b%}B{%endblock%}'
return expect(liquid.parseAndRender(src)).to return expect(liquid.parseAndRender(src)).to
@@ -66,7 +66,7 @@ describe('tags/layout', function () {
mock({ mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z' '/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
}) })
let src = '{% layout "parent.html" %}{%block a%}a{%endblock%}' const src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
return expect(liquid.parseAndRender(src)).to return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ') .eventually.equal('XaYBZ')
}) })
@@ -113,7 +113,7 @@ describe('tags/layout', function () {
'/parent.html': '{{color}}{%block%}{%endblock%}', '/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}' '/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}'
}) })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false }) const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA') .eventually.equal('blackA')
}) })
@@ -123,7 +123,7 @@ describe('tags/layout', function () {
'/foo/parent.html': '{{color}}{%block%}{%endblock%}', '/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}' '/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}'
}) })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false }) const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA') .eventually.equal('blackA')
}) })
@@ -133,7 +133,7 @@ describe('tags/layout', function () {
'/foo/parent.html': '{{color}}{%block%}{%endblock%}', '/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}' '/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}'
}) })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false }) const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA') .eventually.equal('blackA')
}) })
+11 -13
View File
@@ -5,21 +5,19 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/raw', function () { describe('tags/raw', function () {
let liquid = Liquid() const liquid = Liquid()
it('should support raw 1', function () { it('should support raw 1', async function () {
return expect(liquid.parseAndRender('{% raw%}')) const p = liquid.parseAndRender('{% raw%}')
.to.be.rejectedWith(/{% raw%} not closed/) return expect(p).be.rejectedWith(/{% raw%} not closed/)
}) })
it('should support raw 2', function () { it('should support raw 2', async function () {
let src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.' const src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
let dst = '{{ 5 | plus: 6 }} is equal to 11.' const dst = '{{ 5 | plus: 6 }} is equal to 11.'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
.to.eventually.equal(dst)
}) })
it('should support raw 3', function () { it('should support raw 3', function () {
let src = '{% raw %}\n{{ foo}} \n{% endraw %}' const src = '{% raw %}\n{{ foo}} \n{% endraw %}'
let dst = '\n{{ foo}} \n' const dst = '\n{{ foo}} \n'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
.to.eventually.equal(dst)
}) })
}) })
+19 -19
View File
@@ -5,52 +5,52 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/tablerow', function () { describe('tags/tablerow', function () {
let liquid = Liquid() const liquid = Liquid()
it('should support tablerow', function () { it('should support tablerow', function () {
let src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
let dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>' const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should support cols', function () { it('should support cols', function () {
let src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
let ctx = { const ctx = {
alpha: ['a', 'b', 'c'] alpha: ['a', 'b', 'c']
} }
let dst = const dst =
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' + '<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
'<tr class="row2"><td class="col1">c</td></tr>' '<tr class="row2"><td class="col1">c</td></tr>'
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
}) })
it('should support cols set to 0', function () { it('should support cols set to 0', function () {
let src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
let dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>' const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should support empty tablerow', function () { it('should support empty tablerow', function () {
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
let dst = '' const dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should support empty array', function () { it('should support empty array', function () {
let src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
let dst = '' const dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should throw when tablerow not closed', function () { it('should throw when tablerow not closed', function () {
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}' const src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/) .to.be.rejectedWith(/tag .* not closed/)
}) })
it('should support tablerow with range', function () { it('should support tablerow with range', function () {
let src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
let dst = const dst =
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' + '<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' + '<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
'<tr class="row3"><td class="col1">5</td></tr>' '<tr class="row3"><td class="col1">5</td></tr>'
@@ -58,16 +58,16 @@ describe('tags/tablerow', function () {
}) })
it('should support tablerow with limit', function () { it('should support tablerow with limit', function () {
let src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
let dst = const dst =
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' + '<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>' '<tr class="row2"><td class="col1">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
it('should support tablerow with offset', function () { it('should support tablerow with offset', function () {
let src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}' const src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
let dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' const dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst) return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
}) })
}) })
+6 -6
View File
@@ -5,31 +5,31 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
describe('tags/unless', function () { describe('tags/unless', function () {
let liquid = Liquid() const liquid = Liquid()
it('should render else when predicate yields true', function () { it('should render else when predicate yields true', function () {
// 0 is truthy // 0 is truthy
let src = '{% unless 0 %}yes{%else%}no{%endunless%}' const src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('no') .to.eventually.equal('no')
}) })
it('should render unless when predicate yields false', function () { it('should render unless when predicate yields false', function () {
let src = '{% unless false %}yes{%else%}no{%endunless%}' const src = '{% unless false %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes') .to.eventually.equal('yes')
}) })
it('should reject when tag not closed', function () { it('should reject when tag not closed', function () {
let src = '{% unless 1>2 %}yes' const src = '{% unless 1>2 %}yes'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/) .to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
}) })
it('should render unless when predicate yields false and else undefined', function () { it('should render unless when predicate yields false and else undefined', function () {
let src = '{% unless 1>2 %}yes{%endunless%}' const src = '{% unless 1>2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes') .to.eventually.equal('yes')
}) })
it('should render "" when predicate yields false and else undefined', function () { it('should render "" when predicate yields false and else undefined', function () {
let src = '{% unless 1<2 %}yes{%endunless%}' const src = '{% unless 1<2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src)) return expect(liquid.parseAndRender(src))
.to.eventually.equal('') .to.eventually.equal('')
}) })
+14 -14
View File
@@ -5,8 +5,8 @@ const expect = chai.expect
describe('tokenizer', function () { describe('tokenizer', function () {
describe('parse', function () { describe('parse', function () {
it('should handle plain HTML', function () { it('should handle plain HTML', function () {
let html = '<html><body><p>Lorem Ipsum</p></body></html>' const html = '<html><body><p>Lorem Ipsum</p></body></html>'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(1) expect(tokens.length).to.equal(1)
expect(tokens[0].value).to.equal(html) expect(tokens[0].value).to.equal(html)
@@ -18,24 +18,24 @@ describe('tokenizer', function () {
}).to.throw('illegal input') }).to.throw('illegal input')
}) })
it('should handle tag syntax', function () { it('should handle tag syntax', function () {
let html = '<p>{% for p in a[1]%}</p>' const html = '<p>{% for p in a[1]%}</p>'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(3) expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('tag') expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]') expect(tokens[1].value).to.equal('for p in a[1]')
}) })
it('should handle value syntax', function () { it('should handle value syntax', function () {
let html = '<p>{{foo | date: "%Y-%m-%d"}}</p>' const html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(3) expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('value') expect(tokens[1].type).to.equal('value')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"') expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
}) })
it('should handle consecutive value and tags', function () { it('should handle consecutive value and tags', function () {
let html = '{{foo}}{{bar}}{%foo%}{%bar%}' const html = '{{foo}}{{bar}}{%foo%}{%bar%}'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(4) expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('value') expect(tokens[0].type).to.equal('value')
@@ -45,8 +45,8 @@ describe('tokenizer', function () {
expect(tokens[2].value).to.equal('foo') expect(tokens[2].value).to.equal('foo')
}) })
it('should keep white spaces and newlines', function () { it('should keep white spaces and newlines', function () {
let html = '{%foo%}\n{%bar %} \n {%alice%}' const html = '{%foo%}\n{%bar %} \n {%alice%}'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(5) expect(tokens.length).to.equal(5)
expect(tokens[1].type).to.equal('html') expect(tokens[1].type).to.equal('html')
expect(tokens[1].raw).to.equal('\n') expect(tokens[1].raw).to.equal('\n')
@@ -54,16 +54,16 @@ describe('tokenizer', function () {
expect(tokens[3].raw).to.equal(' \n ') expect(tokens[3].raw).to.equal(' \n ')
}) })
it('should handle multiple lines tag', function () { it('should handle multiple lines tag', function () {
let html = '{%foo\na:a\nb:1.23\n%}' const html = '{%foo\na:a\nb:1.23\n%}'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(1) expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag') expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23') expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}') expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
}) })
it('should handle multiple lines value', function () { it('should handle multiple lines value', function () {
let html = '{{foo\n|date:\n"%Y-%m-%d"\n}}' const html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
let tokens = parse(html) const tokens = parse(html)
expect(tokens.length).to.equal(1) expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('value') expect(tokens[0].type).to.equal('value')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}') expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
+6 -5
View File
@@ -1,18 +1,19 @@
const chai = require('chai') import chai from 'chai'
import assert from '../../src/util/assert.js'
const expect = chai.expect const expect = chai.expect
const assert = require('../../src/util/assert.js')
describe('assert', function () { describe('assert', function () {
it('should not throw if predicate is truthy', function () { it('should not throw if predicate is truthy', function () {
let fn = () => assert('foo', 'bar') const fn = () => assert('foo', 'bar')
expect(fn).to.not.throw() expect(fn).to.not.throw()
}) })
it('should not throw if predicate is truthy', function () { it('should not throw if predicate is truthy', function () {
let fn = () => assert('', 'bar') const fn = () => assert('', 'bar')
expect(fn).to.throw(/bar/) expect(fn).to.throw(/bar/)
}) })
it('should populate default message', function () { it('should populate default message', function () {
let fn = () => assert(false) const fn = () => assert(false)
expect(fn).to.throw(/expect false to be true/) expect(fn).to.throw(/expect false to be true/)
}) })
}) })
+150 -236
View File
@@ -7,7 +7,7 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
let engine = Liquid() let engine = Liquid()
let strictEngine = Liquid({ const strictEngine = Liquid({
strict_variables: true, strict_variables: true,
strict_filters: true strict_filters: true
}) })
@@ -18,80 +18,59 @@ describe('error', function () {
}) })
describe('TokenizationError', function () { describe('TokenizationError', function () {
it('should throw TokenizationError when tag illegal', function () { it('should throw TokenizationError when tag illegal', async function () {
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually const err = await expect(engine.parseAndRender('{% . a %}', {})).be.rejected
.be.rejected expect(err.name).to.equal('TokenizationError')
.then(function (err) { expect(err.message).to.contain('illegal tag syntax')
expect(err.name).to.equal('TokenizationError')
expect(err.message).to.contain('illegal tag syntax')
})
}) })
it('should contain template content in err.message', function () { it('should contain template content in err.message', async function () {
let html = ['1st', '2nd', 'X{% . a %} Y', '4th'] const html = ['1st', '2nd', 'X{% . a %} Y', '4th']
let message = [ const message = [
' 1| 1st', ' 1| 1st',
' 2| 2nd', ' 2| 2nd',
'>> 3| X{% . a %} Y', '>> 3| X{% . a %} Y',
' 4| 4th', ' 4| 4th',
'TokenizationError' 'TokenizationError'
] ]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
.be.rejected expect(err.message).to.equal('illegal tag syntax, line:3')
.then(function (err) { expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal('illegal tag syntax, line:3') expect(err.name).to.equal('TokenizationError')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('TokenizationError')
})
}) })
it('should contain the whole template content in err.input', function () { it('should contain the whole template content in err.input', async function () {
let html = 'bar\nfoo{% . a %}\nfoo' const html = 'bar\nfoo{% . a %}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually const err = await expect(engine.parseAndRender(html)).be.rejected
.be.rejected expect(err.input).to.equal(html)
.then(function (err) {
expect(err.input).to.equal(html)
})
}) })
it('should contain line number in err.line', function () { it('should contain line number in err.line', async function () {
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually const err = await expect(engine.parseAndRender('1\n2\n{% . a %}\n4')).be.rejected
.be.rejected expect(err.name).to.equal('TokenizationError')
.then(function (err) { expect(err.line).to.equal(3)
expect(err.name).to.equal('TokenizationError')
expect(err.line).to.equal(3)
})
}) })
it('should contain stack in err.stack', function () { it('should contain stack in err.stack', async function () {
return expect(engine.parseAndRender('{% . a %}')).to.eventually const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
.be.rejected expect(err.message).to.contain('illegal tag syntax')
.then(function (err) { expect(err.stack).to.contain('at Object.parse')
expect(err.message).to.contain('illegal tag syntax')
expect(err.stack).to.contain('at Object.parse')
})
}) })
describe('captureStackTrace compatibility', function () { describe('captureStackTrace compatibility', function () {
let captureStackTrace = Error.captureStackTrace const captureStackTrace = Error.captureStackTrace
before(() => (Error.captureStackTrace = null)) before(() => (Error.captureStackTrace = null))
after(() => (Error.captureStackTrace = captureStackTrace)) after(() => (Error.captureStackTrace = captureStackTrace))
it('should use empty string if captureStackTrace not defined', function () { it('should be empty when captureStackTrace undefined', async function () {
return expect(engine.parseAndRender('{% . a %}')).to.eventually const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
.be.rejected expect(err.stack).to.contain('illegal tag syntax')
.then(function (err) { expect(err.stack).to.not.contain('at Object.parse')
expect(err.stack).to.contain('illegal tag syntax')
expect(err.stack).to.not.contain('at Object.parse')
})
}) })
}) })
it('should contain file path in err.file', function () { it('should contain file path in err.file', async function () {
let html = '<html>\n<head>\n\n{% . a %}\n\n' const html = '<html>\n<head>\n\n{% . a %}\n\n'
mock({ mock({
'/foo.html': html '/foo.html': html
}) })
return expect(engine.renderFile('/foo.html')).to.eventually const err = await expect(engine.renderFile('/foo.html')).be.rejected
.be.rejected mock.restore()
.then(function (err) { expect(err.name).to.equal('TokenizationError')
mock.restore() expect(err.file).to.equal(path.resolve('/foo.html'))
expect(err.name).to.equal('TokenizationError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
}) })
}) })
@@ -106,55 +85,43 @@ describe('error', function () {
} }
}) })
engine.registerTag('rejectingTag', { engine.registerTag('rejectingTag', {
render: function () { render: async function () {
return Promise.reject(new Error('intended render reject')) throw new Error('intended render reject')
} }
}) })
engine.registerFilter('throwingFilter', () => { engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter') throw new Error('throwed by filter')
}) })
}) })
it('should throw RenderError when tag throws', function () { it('should throw RenderError when tag throws', async function () {
let src = '{%throwingTag%}' const src = '{%throwingTag%}'
return expect(engine.parseAndRender(src)).to.eventually const err = await expect(engine.parseAndRender(src)).be.rejected
.be.rejected expect(err.name).to.equal('RenderError')
.then(function (err) { expect(err.message).to.contain('intended render error')
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render error')
})
}) })
it('should throw RenderError when tag rejects', function () { it('should throw RenderError when tag rejects', async function () {
let src = '{%rejectingTag%}' const src = '{%rejectingTag%}'
return expect(engine.parseAndRender(src)).to.eventually const err = await expect(engine.parseAndRender(src)).be.rejected
.be.rejected expect(err.name).to.equal('RenderError')
.then(function (err) { expect(err.message).to.contain('intended render reject')
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render reject')
})
}) })
it('should throw RenderError when filter throws', function () { it('should throw RenderError when filter throws', async function () {
let src = '{{1|throwingFilter}}' const src = '{{1|throwingFilter}}'
return expect(engine.parseAndRender(src)).to.eventually const err = await expect(engine.parseAndRender(src)).be.rejected
.be.rejected expect(err.name).to.equal('RenderError')
.then(function (err) { expect(err.message).to.contain('throwed by filter')
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('throwed by filter')
})
}) })
it('should not throw when variable undefined by default', function () { it('should not throw when variable undefined by default', function () {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY') return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
}) })
it('should throw RenderError when variable not defined', function () { it('should throw RenderError when variable not defined', async function () {
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually const err = await expect(strictEngine.parseAndRender('{{a}}')).be.rejected
.be.rejected expect(err).to.have.property('name', 'RenderError')
.then(function (e) { expect(err.message).to.contain('undefined variable: a')
expect(e).to.have.property('name', 'RenderError')
expect(e.message).to.contain('undefined variable: a')
})
}) })
it('should contain template context in err.stack', function () { it('should contain template context in err.stack', async function () {
let html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'] const html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
let message = [ const message = [
' 2| 2nd', ' 2| 2nd',
' 3| 3rd', ' 3| 3rd',
'>> 4| X{%throwingTag%} Y', '>> 4| X{%throwingTag%} Y',
@@ -163,15 +130,12 @@ describe('error', function () {
' 7| 7th', ' 7| 7th',
'RenderError' 'RenderError'
] ]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
.be.rejected expect(err.message).to.equal('intended render error, line:4')
.then(function (err) { expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal('intended render error, line:4') expect(err.name).to.equal('RenderError')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
}) })
it('should contain original error info for {% layout %}', function () { it('should contain original error info for {% layout %}', async function () {
mock({ mock({
'/throwing-tag.html': [ '/throwing-tag.html': [
'1st', '1st',
@@ -183,8 +147,8 @@ describe('error', function () {
'7th' '7th'
].join('\n') ].join('\n')
}) })
let html = '{%layout "throwing-tag.html"%}' const html = '{%layout "throwing-tag.html"%}'
let message = [ const message = [
' 2| 2nd', ' 2| 2nd',
' 3| 3rd', ' 3| 3rd',
'>> 4| X{%throwingTag%} Y', '>> 4| X{%throwingTag%} Y',
@@ -193,23 +157,20 @@ describe('error', function () {
' 7| 7th', ' 7| 7th',
'RenderError' 'RenderError'
] ]
return expect(engine.parseAndRender(html)).to.eventually const err = await expect(engine.parseAndRender(html)).be.rejected
.be.rejected console.log(err.message)
.then(function (err) { console.log(err.stack)
console.log(err.message) expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
console.log(err.stack) expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`) expect(err.name).to.equal('RenderError')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
}) })
it('should contain original error info for {% include %}', function () { it('should contain original error info for {% include %}', async function () {
let origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'] const origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
mock({ mock({
'/throwing-tag.html': origin.join('\n') '/throwing-tag.html': origin.join('\n')
}) })
let html = '{%include "throwing-tag.html"%}' const html = '{%include "throwing-tag.html"%}'
let message = [ const message = [
' 2| 2nd', ' 2| 2nd',
' 3| 3rd', ' 3| 3rd',
'>> 4| X{%throwingTag%} Y', '>> 4| X{%throwingTag%} Y',
@@ -218,54 +179,39 @@ describe('error', function () {
' 7| 7th', ' 7| 7th',
'RenderError' 'RenderError'
] ]
return expect(engine.parseAndRender(html)).to.eventually const err = await expect(engine.parseAndRender(html)).be.rejected
.be.rejected expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
.then(function (err) { expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`) expect(err.name).to.equal('RenderError')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
}) })
it('should contain the whole template content in err.input', function () { it('should contain the whole template content in err.input', async function () {
let html = 'bar\nfoo{%throwingTag%}\nfoo' const html = 'bar\nfoo{%throwingTag%}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually const err = await expect(engine.parseAndRender(html)).be.rejected
.be.rejected expect(err.input).to.equal(html)
.then(function (err) { expect(err.name).to.equal('RenderError')
expect(err.input).to.equal(html)
expect(err.name).to.equal('RenderError')
})
}) })
it('should contain line number in err.line', function () { it('should contain line number in err.line', async function () {
let src = '1\n2\n{{1|throwingFilter}}\n4' const src = '1\n2\n{{1|throwingFilter}}\n4'
return expect(engine.parseAndRender(src)).to.eventually const err = await expect(engine.parseAndRender(src)).be.rejected
.be.rejected expect(err.line).to.equal(3)
.then(function (err) { expect(err.name).to.equal('RenderError')
expect(err.line).to.equal(3)
expect(err.name).to.equal('RenderError')
})
}) })
it('should contain stack in err.stack', function () { it('should contain stack in err.stack', async function () {
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually const err = await expect(engine.parseAndRender('{%rejectingTag%}')).be.rejected
.be.rejected expect(err.message).to.contain('intended render reject')
.then(function (err) { expect(err.stack).to.match(/at .*:\d+:\d+/)
expect(err.message).to.contain('intended render reject')
expect(err.stack).to.match(/at .*:\d+:\d+/)
})
}) })
it('should contain file path in err.file', function () { it('should contain file path in err.file', async function () {
let html = '<html>\n<head>\n\n{% throwingTag %}\n\n' const html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
mock({ mock({
'/foo.html': html '/foo.html': html
}) })
return expect(engine.renderFile('/foo.html')).to.eventually const err = await expect(engine.renderFile('/foo.html')).be.rejected
.be.rejected mock.restore()
.then(function (err) { console.log(err, err.name)
mock.restore() expect(err.name).to.equal('RenderError')
console.log(err, err.name) expect(err.file).to.equal(path.resolve('/foo.html'))
expect(err.name).to.equal('RenderError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
}) })
}) })
@@ -278,53 +224,36 @@ describe('error', function () {
} }
}) })
}) })
it('should throw RenderError when filter not defined', function () { it('should throw RenderError when filter not defined', async function () {
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually const err = await expect(strictEngine.parseAndRender('{{1 | a}}')).be.rejected
.be.rejected expect(err).to.have.property('name', 'ParseError')
.then(function (e) { expect(err.message).to.contain('undefined filter: a')
expect(e).to.have.property('name', 'ParseError')
expect(e.message).to.contain('undefined filter: a')
})
}) })
it('should throw ParseError when tag not closed', function () { it('should throw ParseError when tag not closed', async function () {
return expect(engine.parseAndRender('{% if %}')).to.eventually const err = await expect(engine.parseAndRender('{% if %}')).be.rejected
.be.rejected expect(err.name).to.equal('ParseError')
.then(function (err) { expect(err.message).to.contain('tag {% if %} not closed')
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag {% if %} not closed')
})
}) })
it('should throw ParseError when tag parse throws', function () { it('should throw ParseError when tag parse throws', async function () {
let src = '{%throwsOnParse%}' const err = await expect(engine.parseAndRender('{%throwsOnParse%}')).be.rejected
return expect(engine.parseAndRender(src)).to.eventually expect(err.name).to.equal('ParseError')
.be.rejected expect(err.message).to.contain('intended parse error')
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('intended parse error')
})
}) })
it('should throw ParseError when tag not found', function () { it('should throw ParseError when tag not found', async function () {
let src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3' const src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
return expect(engine.parseAndRender(src)).to.eventually const err = await expect(engine.parseAndRender(src)).be.rejected
.be.rejected expect(err.name).to.equal('ParseError')
.then(function (err) { expect(err.message).to.contain('tag -a not found')
expect(err.name).to.equal('ParseError') })
expect(err.message).to.contain('tag -a not found') it('should throw ParseError when tag not exist', async function () {
}) const err = await expect(engine.parseAndRender('{% a %}')).be.rejected
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
}) })
it('should throw ParseError when tag not exist', function () { it('should contain template context in err.stack', async function () {
return expect(engine.parseAndRender('{% a %}')).to.eventually const html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
.be.rejected const message = [
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
})
})
it('should contain template context in err.stack', function () {
let html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
let message = [
' 2| 2nd', ' 2| 2nd',
' 3| 3rd', ' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y', '>> 4| X{% a %} {% enda %} Y',
@@ -333,62 +262,47 @@ describe('error', function () {
' 7| 7th', ' 7| 7th',
'ParseError: tag a not found' 'ParseError: tag a not found'
] ]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
.be.rejected expect(err.message).to.equal('tag a not found, line:4')
.then(function (err) { expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal('tag a not found, line:4') expect(err.name).to.equal('ParseError')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('ParseError')
})
}) })
it('should handle err.message when context not enough', function () { it('should handle err.message when context not enough', async function () {
let html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th'] const html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
let message = [ const message = [
' 1| 1st', ' 1| 1st',
'>> 2| X{% a %} {% enda %} Y', '>> 2| X{% a %} {% enda %} Y',
' 3| 3rd', ' 3| 3rd',
' 4| 4th', ' 4| 4th',
'ParseError: tag a not found' 'ParseError: tag a not found'
] ]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
.be.rejected expect(err.message).to.equal('tag a not found, line:2')
.then(function (err) { expect(err.stack).to.contain(message.join('\n'))
expect(err.message).to.equal('tag a not found, line:2')
expect(err.stack).to.contain(message.join('\n'))
})
}) })
it('should contain line number in err.line', function () { it('should contain line number in err.line', async function () {
let html = '<html>\n<head>\n\n{% raw %}\n\n' const html = '<html>\n<head>\n\n{% raw %}\n\n'
return expect(engine.parseAndRender(html)).to.eventually const err = await expect(engine.parseAndRender(html)).be.rejected
.be.rejected expect(err.line).to.equal(4)
.then(function (err) {
expect(err.line).to.equal(4)
})
}) })
it('should contain stack in err.stack', function () { it('should contain stack in err.stack', async function () {
return expect(engine.parseAndRender('{% -a %}')).to.eventually const err = await expect(engine.parseAndRender('{% -a %}')).be.rejected
.be.rejected expect(err.stack).to.contain('ParseError: tag -a not found')
.then(function (err) { expect(err.stack).to.match(/at .*:\d+:\d+\)/)
expect(err.stack).to.contain('ParseError: tag -a not found')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
}) })
it('should contain file path in err.file', function () { it('should contain file path in err.file', async function () {
let html = '<html>\n<head>\n\n{% raw %}\n\n' const html = '<html>\n<head>\n\n{% raw %}\n\n'
mock({ mock({
'/foo.html': html '/foo.html': html
}) })
return expect(engine.renderFile('/foo.html')).to.eventually const err = await expect(engine.renderFile('/foo.html')).be.rejected
.be.rejected mock.restore()
.then(function (err) { expect(err.name).to.equal('ParseError')
mock.restore() expect(err.file).to.equal(path.resolve('/foo.html'))
expect(err.name).to.equal('ParseError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
}) })
}) })
}) })
+11 -11
View File
@@ -4,13 +4,13 @@ const expect = chai.expect
chai.use(require('chai-as-promised')) chai.use(require('chai-as-promised'))
chai.use(require('sinon-chai')) chai.use(require('sinon-chai'))
let P = require('../../src/util/promise.js') const P = require('../../src/util/promise.js')
describe('util/promise', function () { describe('util/promise', function () {
describe('.anySeries()', function () { describe('.anySeries()', function () {
it('should resolve in series', function () { it('should resolve in series', function () {
let spy1 = sinon.spy() const spy1 = sinon.spy()
let spy2 = sinon.spy() const spy2 = sinon.spy()
return P return P
.anySeries( .anySeries(
['first', 'second'], ['first', 'second'],
@@ -28,17 +28,17 @@ describe('util/promise', function () {
.then(() => expect(spy2).to.have.been.calledAfter(spy1)) .then(() => expect(spy2).to.have.been.calledAfter(spy1))
}) })
it('should reject when all rejected', function () { it('should reject when all rejected', function () {
let p = P.anySeries(['first', 'second', 'third'], const p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item))) item => Promise.reject(new Error(item)))
return expect(p).to.be.rejectedWith('third') return expect(p).to.be.rejectedWith('third')
}) })
it('should resolve the value that first callback resolved', () => { it('should resolve the value that first callback resolved', () => {
let p = P.anySeries(['first', 'second'], const p = P.anySeries(['first', 'second'],
item => Promise.resolve(item)) item => Promise.resolve(item))
return expect(p).to.eventually.equal('first') return expect(p).to.eventually.equal('first')
}) })
it('should not call rest of callbacks once resolved', () => { it('should not call rest of callbacks once resolved', () => {
let spy = sinon.spy() const spy = sinon.spy()
return P return P
.anySeries(['first', 'second'], (item, idx) => { .anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) { if (idx > 0) {
@@ -51,18 +51,18 @@ describe('util/promise', function () {
}) })
describe('.mapSeries()', function () { describe('.mapSeries()', function () {
it('should resolve when all resolved', function () { it('should resolve when all resolved', function () {
let p = P.mapSeries(['first', 'second', 'third'], const p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item)) item => Promise.resolve(item))
return expect(p).to.eventually.deep.equal(['first', 'second', 'third']) return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
}) })
it('should reject with the error that first callback rejected', () => { it('should reject with the error that first callback rejected', () => {
let p = P.mapSeries(['first', 'second'], const p = P.mapSeries(['first', 'second'],
item => Promise.reject(item)) item => Promise.reject(item))
return expect(p).to.rejectedWith('first') return expect(p).to.rejectedWith('first')
}) })
it('should resolve in series', function () { it('should resolve in series', function () {
let spy1 = sinon.spy() const spy1 = sinon.spy()
let spy2 = sinon.spy() const spy2 = sinon.spy()
return P return P
.mapSeries( .mapSeries(
['first', 'second'], ['first', 'second'],
@@ -80,7 +80,7 @@ describe('util/promise', function () {
.then(() => expect(spy2).to.have.been.calledAfter(spy1)) .then(() => expect(spy2).to.have.been.calledAfter(spy1))
}) })
it('should not call rest of callbacks once rejected', () => { it('should not call rest of callbacks once rejected', () => {
let spy = sinon.spy() const spy = sinon.spy()
return P return P
.mapSeries(['first', 'second'], (item, idx) => { .mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) { if (idx > 0) {
+13 -13
View File
@@ -1,7 +1,7 @@
const chai = require('chai') import chai from 'chai'
const expect = chai.expect import t from '../../src/util/strftime.js'
let t = require('../../src/util/strftime.js') const expect = chai.expect
describe('util/strftime', function () { describe('util/strftime', function () {
let now let now
@@ -37,7 +37,7 @@ describe('util/strftime', function () {
expect(t(now, '%I')).to.equal('01') expect(t(now, '%I')).to.equal('01')
}) })
it('should format %I as 12 for 00:00', function () { it('should format %I as 12 for 00:00', function () {
let date = new Date('2016-01-01T00:00:00.000Z') const date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%I')).to.equal('12') expect(t(date, '%I')).to.equal('12')
}) })
describe('%j', function () { describe('%j', function () {
@@ -45,11 +45,11 @@ describe('util/strftime', function () {
expect(t(then, '%j')).to.equal('066') expect(t(then, '%j')).to.equal('066')
}) })
it('should take count of leap years', function () { it('should take count of leap years', function () {
let date = new Date('2001-03-01') const date = new Date('2001-03-01')
expect(t(date, '%j')).to.equal('060') expect(t(date, '%j')).to.equal('060')
}) })
it('should take count of leap years', function () { it('should take count of leap years', function () {
let date = new Date('2000-03-01') const date = new Date('2000-03-01')
expect(t(date, '%j')).to.equal('061') expect(t(date, '%j')).to.equal('061')
}) })
}) })
@@ -60,7 +60,7 @@ describe('util/strftime', function () {
expect(t(now, '%l')).to.equal(' 1') expect(t(now, '%l')).to.equal(' 1')
}) })
it('should format %l as 12 for 00:00', function () { it('should format %l as 12 for 00:00', function () {
let date = new Date('2016-01-01T00:00:00.000Z') const date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%l')).to.equal('12') expect(t(date, '%l')).to.equal('12')
}) })
it('should format %L as 0 padded millisecond', function () { it('should format %L as 0 padded millisecond', function () {
@@ -75,9 +75,9 @@ describe('util/strftime', function () {
expect(t(then, '%P')).to.equal('am') expect(t(then, '%P')).to.equal('am')
}) })
it('should format %q as date suffix', function () { it('should format %q as date suffix', function () {
let st = new Date('2016-03-01T03:05:03.000Z') const st = new Date('2016-03-01T03:05:03.000Z')
let nd = new Date('2016-03-02T03:05:03.000Z') const nd = new Date('2016-03-02T03:05:03.000Z')
let rd = new Date('2016-03-03T03:05:03.000Z') const rd = new Date('2016-03-03T03:05:03.000Z')
expect(t(st, '%q')).to.equal('st') expect(t(st, '%q')).to.equal('st')
expect(t(nd, '%q')).to.equal('nd') expect(t(nd, '%q')).to.equal('nd')
expect(t(rd, '%q')).to.equal('rd') expect(t(rd, '%q')).to.equal('rd')
@@ -113,7 +113,7 @@ describe('util/strftime', function () {
expect(t(now, '%z')).to.equal('+0800') expect(t(now, '%z')).to.equal('+0800')
}) })
it('should format %z as negative time zone', function () { it('should format %z as negative time zone', function () {
let date = new Date('2016-01-04T13:15:23.000Z') const date = new Date('2016-01-04T13:15:23.000Z')
date.getTimezoneOffset = () => 480 date.getTimezoneOffset = () => 480
expect(t(date, '%z')).to.equal('-0800') expect(t(date, '%z')).to.equal('-0800')
}) })
@@ -126,7 +126,7 @@ describe('util/strftime', function () {
}) })
function mockUTC () { function mockUTC () {
let p = Date.prototype const p = Date.prototype
p._getHours = p.getHours p._getHours = p.getHours
p.getHours = p.getUTCHours p.getHours = p.getUTCHours
@@ -139,7 +139,7 @@ function mockUTC () {
} }
function restoreUTC () { function restoreUTC () {
let p = Date.prototype const p = Date.prototype
p.getHours = p._getHours p.getHours = p._getHours
p.getDays = p._getDays p.getDays = p._getDays
p.getTimezoneOffset = p._getTimezoneOffset p.getTimezoneOffset = p._getTimezoneOffset
+12 -11
View File
@@ -1,10 +1,11 @@
import chai from 'chai' import chai from 'chai'
import sinonChai from 'sinon-chai'
import sinon from 'sinon' import sinon from 'sinon'
import {RenderError, RenderBreakError} from '../../src/util/error.js' import {RenderError, RenderBreakError} from '../../src/util/error.js'
import _ from '../../src/util/underscore.js' import * as _ from '../../src/util/underscore.js'
const expect = chai.expect const expect = chai.expect
chai.use(require('sinon-chai')) chai.use(sinonChai)
describe('util/underscore', function () { describe('util/underscore', function () {
describe('.isError()', function () { describe('.isError()', function () {
@@ -12,7 +13,7 @@ describe('util/underscore', function () {
expect(_.isError(new Error())).to.be.true expect(_.isError(new Error())).to.be.true
}) })
it('should return true for RenderError', function () { it('should return true for RenderError', function () {
let tpl = { const tpl = {
token: { token: {
input: 'xx' input: 'xx'
} }
@@ -53,21 +54,21 @@ describe('util/underscore', function () {
}) })
describe('.forOwn()', function () { describe('.forOwn()', function () {
it('should iterate all properties', function () { it('should iterate all properties', function () {
let spy = sinon.spy() const spy = sinon.spy()
let obj = { const obj = {
foo: 'bar' foo: 'bar'
} }
_.forOwn(obj, spy) _.forOwn(obj, spy)
expect(spy).to.have.been.calledWith('bar', 'foo', obj) expect(spy).to.have.been.calledWith('bar', 'foo', obj)
}) })
it('should default to empty object', function () { it('should default to empty object', function () {
let spy = sinon.spy() const spy = sinon.spy()
_.forOwn(undefined, spy) _.forOwn(undefined, spy)
expect(spy).to.have.not.been.called expect(spy).to.have.not.been.called
}) })
it('should not iterate over properties on prototype', function () { it('should not iterate over properties on prototype', function () {
let spy = sinon.spy() const spy = sinon.spy()
let obj = Object.create({ const obj = Object.create({
bar: 'foo' bar: 'foo'
}) })
obj.foo = 'bar' obj.foo = 'bar'
@@ -76,7 +77,7 @@ describe('util/underscore', function () {
expect(spy).to.have.been.calledWith('bar', 'foo', obj) expect(spy).to.have.been.calledWith('bar', 'foo', obj)
}) })
it('should break when returned false', function () { it('should break when returned false', function () {
let spy = sinon.stub().returns(false) const spy = sinon.stub().returns(false)
_.forOwn({ _.forOwn({
'foo': 'foo', 'foo': 'foo',
'bar': 'foo' 'bar': 'foo'
@@ -101,11 +102,11 @@ describe('util/underscore', function () {
}) })
}) })
it('should assign 2 objects', function () { it('should assign 2 objects', function () {
let src = { const src = {
foo: 'foo', foo: 'foo',
bar: 'bar' bar: 'bar'
} }
let dst = { const dst = {
foo: 'bar', foo: 'bar',
kaa: 'kaa' kaa: 'kaa'
} }
+10 -12
View File
@@ -1,4 +1,4 @@
import {resolve} from '../../src/util/url.js' import {extname, resolve} from '../../src/util/url.js'
import chai from 'chai' import chai from 'chai'
const expect = chai.expect const expect = chai.expect
@@ -22,23 +22,23 @@ describe('util/url', function () {
}) })
describe('resolve', function () { describe('resolve', function () {
describe('root', function () { describe('root', function () {
it('should support width relative path', function () { it('should support relative root', function () {
expect(resolve('./views', 'foo')) expect(resolve('./views', 'foo'))
.to.equal('https://example.com/foo/bar/views/foo') .to.equal('https://example.com/foo/bar/views/foo')
expect(resolve('./views/', 'foo')) expect(resolve('./views/', 'foo'))
.to.equal('https://example.com/foo/bar/views/foo') .to.equal('https://example.com/foo/bar/views/foo')
}) })
it('should support width absolute path', function () { it('should support absolute root', function () {
expect(resolve('/views', 'foo')) expect(resolve('/views', 'foo'))
.to.equal('https://example.com/views/foo') .to.equal('https://example.com/views/foo')
expect(resolve('/views/', 'foo')) expect(resolve('/views/', 'foo'))
.to.equal('https://example.com/views/foo') .to.equal('https://example.com/views/foo')
}) })
it('should support with empty', function () { it('should support empty root', function () {
expect(resolve('', 'page.html')) expect(resolve('', 'page.html'))
.to.equal('https://example.com/foo/bar/page.html') .to.equal('https://example.com/foo/bar/page.html')
}) })
it('should support with url', function () { it('should support full url as root', function () {
expect(resolve('https://example.com/views', 'page.html')) expect(resolve('https://example.com/views', 'page.html'))
.to.equal('https://example.com/views/page.html') .to.equal('https://example.com/views/page.html')
expect(resolve('https://example.com/views/', 'page.html')) expect(resolve('https://example.com/views/', 'page.html'))
@@ -51,14 +51,12 @@ describe('util/url', function () {
.to.equal('https://example.com/views/page.html') .to.equal('https://example.com/views/page.html')
}) })
}) })
describe('path', function () { describe('extname', function () {
it('should support width relative path', function () { it('should support relative path', function () {
expect(resolve('./views/', 'page.html')) expect(extname('./views/page.html')).to.equal('.html')
.to.equal('https://example.com/foo/bar/views/page.html')
}) })
it('should support with absolute path', function () { it('should support absolute path', function () {
expect(resolve('/views/', '/page.html')) expect(extname('/views/page.xml')).to.equal('.xml')
.to.equal('https://example.com/page.html')
}) })
}) })
}) })