fix: break/continue omitting output before them, #123

BREAKING CHANGE: remove default export, now should be used like import
{Liquid} from 'liquidjs'
This commit is contained in:
harttle
2019-08-26 10:15:43 -05:00
committed by Jun Yang
parent 854e12ba53
commit ae45c4622e
99 changed files with 373 additions and 407 deletions
+3 -5
View File
@@ -1,7 +1,5 @@
import * as Benchmark from 'benchmark' import * as Benchmark from 'benchmark'
import Liquid from '../src/liquid' import { Context, TagToken, Liquid } from '../src/liquid'
import TagToken from '../src/parser/tag-token'
import Context from '../src/context/context'
const engine = new Liquid({ const engine = new Liquid({
root: __dirname, root: __dirname,
@@ -34,13 +32,13 @@ const template = `
</ul> </ul>
` `
export default function () { export function demo () {
console.log('--- demo ---') console.log('--- demo ---')
return new Promise(resolve => { return new Promise(resolve => {
new Benchmark.Suite('demo') new Benchmark.Suite('demo')
.add('demo', { .add('demo', {
defer: true, defer: true,
fn: (d: any) => engine.parseAndRender(template, ctx).then(x => d.resolve(x)) fn: (d: any) => engine.parseAndRender(template, ctx).then((x: any) => d.resolve(x))
}) })
.on('cycle', (event: any) => console.log(String(event.target))) .on('cycle', (event: any) => console.log(String(event.target)))
.on('complete', resolve) .on('complete', resolve)
+4 -4
View File
@@ -1,7 +1,7 @@
import output from './output' import { output } from './output'
import tag from './tag' import { tag } from './tag'
import demo from './demo' import { demo } from './demo'
import layout from './layout' import { layout } from './layout'
async function main () { async function main () {
await output() await output()
+3 -3
View File
@@ -17,17 +17,17 @@ const template = `
{% block body %}a small body{% endblock %} {% block body %}a small body{% endblock %}
` `
export default function () { export function layout () {
console.log('--- layout ---') console.log('--- layout ---')
return new Promise(resolve => { return new Promise(resolve => {
new Benchmark.Suite('layout') new Benchmark.Suite('layout')
.add('cache=false', { .add('cache=false', {
defer: true, defer: true,
fn: (d: any) => engine.parseAndRender(template, {}).then(x => d.resolve(x)) fn: (d: any) => engine.parseAndRender(template, {}).then((x: any) => d.resolve(x))
}) })
.add('cache=true', { .add('cache=true', {
defer: true, defer: true,
fn: (d: any) => cachingEngine.parseAndRender(template, {}).then(x => d.resolve(x)) fn: (d: any) => cachingEngine.parseAndRender(template, {}).then((x: any) => d.resolve(x))
}) })
.on('cycle', (event: any) => console.log(String(event.target))) .on('cycle', (event: any) => console.log(String(event.target)))
.on('complete', resolve) .on('complete', resolve)
+2 -2
View File
@@ -3,7 +3,7 @@ import Liquid from '../src/liquid'
const liquid = new Liquid() const liquid = new Liquid()
export default function () { export function output () {
console.log('--- output ---') console.log('--- output ---')
return new Promise(resolve => { return new Promise(resolve => {
new Benchmark.Suite('output') new Benchmark.Suite('output')
@@ -21,6 +21,6 @@ export default function () {
function test (str: string) { function test (str: string) {
return { return {
defer: true, defer: true,
fn: (d: any) => liquid.parseAndRender(str).then(x => d.resolve(x)) fn: (d: any) => liquid.parseAndRender(str).then((x: any) => d.resolve(x))
} }
} }
+2 -2
View File
@@ -3,7 +3,7 @@ import Liquid from '../src/liquid'
const liquid = new Liquid() const liquid = new Liquid()
export default function () { export function tag () {
console.log('--- tag ---') console.log('--- tag ---')
return new Promise(resolve => { return new Promise(resolve => {
new Benchmark.Suite('tag') new Benchmark.Suite('tag')
@@ -25,6 +25,6 @@ export default function () {
function test (str: string) { function test (str: string) {
return { return {
defer: true, defer: true,
fn: (d: any) => liquid.parseAndRender(str).then(x => d.resolve(x)) fn: (d: any) => liquid.parseAndRender(str).then((x: any) => d.resolve(x))
} }
} }
+2 -1
View File
@@ -8,7 +8,8 @@
<body> <body>
<script> <script>
var engine = new window.Liquid({ var Liquid = window.liquidjs.Liquid
var engine = new Liquid({
extname: '.html', extname: '.html',
cache: true cache: true
}); });
+1 -1
View File
@@ -1,5 +1,5 @@
const express = require('express') const express = require('express')
const Liquid = require('../..') const { Liquid } = require('liquidjs')
const app = express() const app = express()
const engine = new Liquid({ const engine = new Liquid({
+1 -1
View File
@@ -1,4 +1,4 @@
const Liquid = require('liquidjs') const { Liquid } = require('liquidjs')
const engine = new Liquid({ const engine = new Liquid({
root: __dirname, root: __dirname,
+4 -4
View File
@@ -1,4 +1,4 @@
import Liquid from 'liquidjs' import { Liquid, TagToken, Hash, Context } from 'liquidjs'
const engine = new Liquid({ const engine = new Liquid({
root: __dirname, root: __dirname,
@@ -6,12 +6,12 @@ const engine = new Liquid({
}) })
engine.registerTag('header', { engine.registerTag('header', {
parse: function (token) { parse: function (token: TagToken) {
const [key, val] = token.args.split(':') const [key, val] = token.args.split(':')
this[key] = val this[key] = val
}, },
render: function (scope, hash) { render: function (context: Context, hash: Hash) {
const title = this.liquid.evalValue(this['content'], scope) const title = this.liquid.evalValue(this['content'], context)
return `<h1>${title}</h1>` return `<h1>${title}</h1>`
} }
}) })
+2 -3
View File
@@ -18,7 +18,6 @@ const input = './src/liquid.ts'
const cjs = { const cjs = {
output: [{ output: [{
file: 'dist/liquid.common.js', file: 'dist/liquid.common.js',
name: 'Liquid',
format: 'cjs', format: 'cjs',
sourcemap, sourcemap,
banner banner
@@ -41,7 +40,7 @@ const cjs = {
const umd = { const umd = {
output: [{ output: [{
file: 'dist/liquid.js', file: 'dist/liquid.js',
name: 'Liquid', name: 'liquidjs',
format: 'umd', format: 'umd',
sourcemap, sourcemap,
banner banner
@@ -70,7 +69,7 @@ const umd = {
const min = { const min = {
output: [{ output: [{
file: 'dist/liquid.min.js', file: 'dist/liquid.min.js',
name: 'Liquid', name: 'liquidjs',
format: 'umd', format: 'umd',
sourcemap sourcemap
}], }],
+4 -4
View File
@@ -1,8 +1,8 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { identifier } from '../../parser/lexical' import { identifier } from '../../parser/lexical'
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Context from '../../context/context' import { Context } from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
const re = new RegExp(`(${identifier.source})\\s*=([^]*)`) const re = new RegExp(`(${identifier.source})\\s*=([^]*)`)
+6 -6
View File
@@ -1,10 +1,10 @@
import BlockMode from '../../context/block-mode' import BlockMode from '../../context/block-mode'
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Token from '../../parser/token' import { Token } from '../../parser/token'
import ITemplate from '../../template/itemplate' import { ITemplate } from '../../template/itemplate'
import Context from '../../context/context' import { Context } from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream' import { ParseStream } from '../../parser/parse-stream'
export default { export default {
parse: function (token: TagToken, remainTokens: Token[]) { parse: function (token: TagToken, remainTokens: Token[]) {
+3 -6
View File
@@ -1,9 +1,6 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { identifier } from '../../parser/lexical' import { identifier } from '../../parser/lexical'
import TagToken from '../../parser/tag-token' import { ITemplate, Context, ITagImplOptions, TagToken, Token } from '../../types'
import Token from '../../parser/token'
import Context from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options'
const re = new RegExp(`(${identifier.source})`) const re = new RegExp(`(${identifier.source})`)
@@ -17,7 +14,7 @@ export default {
const stream = this.liquid.parser.parseStream(remainTokens) const stream = this.liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', () => stream.stop()) stream.on('tag:endcapture', () => stream.stop())
.on('template', (tpl) => this.templates.push(tpl)) .on('template', (tpl: ITemplate) => this.templates.push(tpl))
.on('end', () => { .on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`) throw new Error(`tag ${tagToken.raw} not closed`)
}) })
+5 -9
View File
@@ -1,10 +1,5 @@
import { Hash, Emitter, TagToken, Token, Context, ITemplate, ITagImplOptions, ParseStream } from '../../types'
import { evalExp } from '../../render/syntax' import { evalExp } from '../../render/syntax'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
import Context from '../../context/context'
import ITemplate from '../../template/itemplate'
import ITagImplOptions from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream'
export default { export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) { parse: function (tagToken: TagToken, remainTokens: Token[]) {
@@ -30,15 +25,16 @@ export default {
stream.start() stream.start()
}, },
render: async function (ctx: Context) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
for (let i = 0; i < this.cases.length; i++) { for (let i = 0; i < this.cases.length; i++) {
const branch = this.cases[i] const branch = this.cases[i]
const val = await evalExp(branch.val, ctx) const val = await evalExp(branch.val, ctx)
const cond = await evalExp(this.cond, ctx) const cond = await evalExp(this.cond, ctx)
if (val === cond) { if (val === cond) {
return this.liquid.renderer.renderTemplates(branch.templates, ctx) this.liquid.renderer.renderTemplates(branch.templates, ctx, emitter)
return
} }
} }
return this.liquid.renderer.renderTemplates(this.elseTemplates, ctx) this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
} }
} as ITagImplOptions } as ITagImplOptions
+3 -3
View File
@@ -1,6 +1,6 @@
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Token from '../../parser/token' import { Token } from '../../parser/token'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
export default { export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) { parse: function (tagToken: TagToken, remainTokens: Token[]) {
+4 -4
View File
@@ -1,9 +1,9 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { value as rValue } from '../../parser/lexical' import { value as rValue } from '../../parser/lexical'
import { evalValue } from '../../render/syntax' import { evalValue } from '../../render/syntax'
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Context from '../../context/context' import { Context } from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`) const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(rValue.source, 'g') const candidatesRE = new RegExp(rValue.source, 'g')
+4 -4
View File
@@ -1,8 +1,8 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { identifier } from '../../parser/lexical' import { identifier } from '../../parser/lexical'
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Context from '../../context/context' import { Context } from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
import { isNumber } from '../../util/underscore' import { isNumber } from '../../util/underscore'
export default { export default {
+7 -16
View File
@@ -1,15 +1,10 @@
import { Emitter, TagToken, Token, Context, ITemplate, ITagImplOptions, ParseStream } from '../../types'
import { isString, isObject, isArray } from '../../util/underscore' import { isString, isObject, isArray } from '../../util/underscore'
import { parseExp } from '../../render/syntax' import { parseExp } from '../../render/syntax'
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { identifier, value, hash } from '../../parser/lexical' import { identifier, value, hash } from '../../parser/lexical'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
import Context from '../../context/context'
import Hash from '../../template/tag/hash'
import ITemplate from '../../template/itemplate'
import ITagImplOptions from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream'
import { ForloopDrop } from '../../drop/forloop-drop' import { ForloopDrop } from '../../drop/forloop-drop'
import { Hash } from '../../template/tag/hash'
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` + const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` + `(${value.source})` +
@@ -41,7 +36,7 @@ export default {
stream.start() stream.start()
}, },
render: async function (ctx: Context, hash: Hash) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
let collection = await parseExp(this.collection, ctx) let collection = await parseExp(this.collection, ctx)
if (!isArray(collection)) { if (!isArray(collection)) {
@@ -63,20 +58,16 @@ export default {
const context = { forloop: new ForloopDrop(collection.length) } const context = { forloop: new ForloopDrop(collection.length) }
ctx.push(context) ctx.push(context)
let html = ''
for (const item of collection) { for (const item of collection) {
context[this.variable] = item context[this.variable] = item
try { try {
html += await this.liquid.renderer.renderTemplates(this.templates, ctx) await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
} catch (e) { } catch (e) {
if (e.name === 'RenderBreakError') { if (e.name !== 'RenderBreakError') throw e
html += e.resolvedHTML if (e.message === 'break') break
if (e.message === 'break') break
} else throw e
} }
context.forloop.next() context.forloop.next()
} }
ctx.pop() ctx.pop()
return html
} }
} as ITagImplOptions } as ITagImplOptions
+5 -10
View File
@@ -1,10 +1,4 @@
import { evalExp, isTruthy } from '../../render/syntax' import { Hash, Emitter, evalExp, isTruthy, TagToken, Token, Context, ITemplate, ITagImplOptions, ParseStream } from '../../types'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
import Context from '../../context/context'
import ITemplate from '../../template/itemplate'
import ITagImplOptions from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream'
export default { export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) { parse: function (tagToken: TagToken, remainTokens: Token[]) {
@@ -33,13 +27,14 @@ export default {
stream.start() stream.start()
}, },
render: async function (ctx: Context) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
for (const branch of this.branches) { for (const branch of this.branches) {
const cond = await evalExp(branch.cond, ctx) const cond = await evalExp(branch.cond, ctx)
if (isTruthy(cond)) { if (isTruthy(cond)) {
return this.liquid.renderer.renderTemplates(branch.templates, ctx) await this.liquid.renderer.renderTemplates(branch.templates, ctx, emitter)
return
} }
} }
return this.liquid.renderer.renderTemplates(this.elseTemplates, ctx) await this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
} }
} as ITagImplOptions } as ITagImplOptions
+4 -8
View File
@@ -1,11 +1,8 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { Hash, Emitter, TagToken, Context, ITagImplOptions } from '../../types'
import { value, quotedLine } from '../../parser/lexical' import { value, quotedLine } from '../../parser/lexical'
import { evalValue, parseValue } from '../../render/syntax' import { evalValue, parseValue } from '../../render/syntax'
import BlockMode from '../../context/block-mode' import BlockMode from '../../context/block-mode'
import TagToken from '../../parser/tag-token'
import Context from '../../context/context'
import Hash from '../../template/tag/hash'
import ITagImplOptions from '../../template/tag/itag-impl-options'
const staticFileRE = /[^\s,]+/ const staticFileRE = /[^\s,]+/
const withRE = new RegExp(`with\\s+(${value.source})`) const withRE = new RegExp(`with\\s+(${value.source})`)
@@ -21,7 +18,7 @@ export default {
match = withRE.exec(token.args) match = withRE.exec(token.args)
if (match) this.with = match[1] if (match) this.with = match[1]
}, },
render: async function (ctx: Context, hash: Hash) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
let filepath let filepath
if (ctx.opts.dynamicPartials) { if (ctx.opts.dynamicPartials) {
if (quotedLine.exec(this.value)) { if (quotedLine.exec(this.value)) {
@@ -45,10 +42,9 @@ export default {
} }
const templates = await this.liquid.getTemplate(filepath, ctx.opts) const templates = await this.liquid.getTemplate(filepath, ctx.opts)
ctx.push(hash) ctx.push(hash)
const html = await this.liquid.renderer.renderTemplates(templates, ctx) await this.liquid.renderer.renderTemplates(templates, ctx, emitter)
ctx.pop() ctx.pop()
ctx.setRegister('blocks', originBlocks) ctx.setRegister('blocks', originBlocks)
ctx.setRegister('blockMode', originBlockMode) ctx.setRegister('blockMode', originBlockMode)
return html
} }
} as ITagImplOptions } as ITagImplOptions
+2 -2
View File
@@ -1,7 +1,7 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { identifier } from '../../parser/lexical' import { identifier } from '../../parser/lexical'
import { isNumber } from '../../util/underscore' import { isNumber } from '../../util/underscore'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
export default { export default {
parse: function (token) { parse: function (token) {
+1 -1
View File
@@ -15,7 +15,7 @@ import tablerow from './tablerow'
import unless from './unless' import unless from './unless'
import Break from './break' import Break from './break'
import Continue from './continue' import Continue from './continue'
import ITagImplOptions from '../../template/tag/itag-impl-options' import { ITagImplOptions } from '../../template/tag/itag-impl-options'
const tags: { [key: string]: ITagImplOptions } = { const tags: { [key: string]: ITagImplOptions } = {
assign, 'for': For, capture, 'case': Case, comment, include, decrement, increment, cycle, 'if': If, layout, block, raw, tablerow, unless, 'break': Break, 'continue': Continue assign, 'for': For, capture, 'case': Case, comment, include, decrement, increment, cycle, 'if': If, layout, block, raw, tablerow, unless, 'break': Break, 'continue': Continue
+3 -6
View File
@@ -1,12 +1,9 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { value as rValue } from '../../parser/lexical' import { value as rValue } from '../../parser/lexical'
import { evalValue } from '../../render/syntax' import { evalValue } from '../../render/syntax'
import { TagToken, Token, Context, ITagImplOptions } from '../../types'
import BlockMode from '../../context/block-mode' import BlockMode from '../../context/block-mode'
import TagToken from '../../parser/tag-token' import { Hash } from '../../template/tag/hash'
import Token from '../../parser/token'
import Context from '../../context/context'
import Hash from '../../template/tag/hash'
import ITagImplOptions from '../../template/tag/itag-impl-options'
const staticFileRE = /\S+/ const staticFileRE = /\S+/
+1 -3
View File
@@ -1,6 +1,4 @@
import TagToken from '../../parser/tag-token' import { TagToken, Token, ITagImplOptions } from '../../types'
import Token from '../../parser/token'
import ITagImplOptions from '../../template/tag/itag-impl-options'
export default { export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) { parse: function (tagToken: TagToken, remainTokens: Token[]) {
+9 -18
View File
@@ -1,13 +1,6 @@
import assert from '../../util/assert' import { assert } from '../../util/assert'
import { evalExp } from '../../render/syntax' import { evalExp, Emitter, Hash, TagToken, Token, Context, ITemplate, ITagImplOptions, ParseStream } from '../../types'
import { identifier, value, hash } from '../../parser/lexical' import { identifier, value, hash } from '../../parser/lexical'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
import ITemplate from '../../template/itemplate'
import Context from '../../context/context'
import Hash from '../../template/tag/hash'
import ITagImplOptions from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream'
import { TablerowloopDrop } from '../../drop/tablerowloop-drop' import { TablerowloopDrop } from '../../drop/tablerowloop-drop'
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` + const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
@@ -35,7 +28,7 @@ export default {
stream.start() stream.start()
}, },
render: async function (ctx: Context, hash: Hash) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
let collection = await evalExp(this.collection, ctx) || [] let collection = await evalExp(this.collection, ctx) || []
const offset = hash.offset || 0 const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit const limit = (hash.limit === undefined) ? collection.length : hash.limit
@@ -47,19 +40,17 @@ export default {
const scope = { tablerowloop } const scope = { tablerowloop }
ctx.push(scope) ctx.push(scope)
let html = ''
for (let idx = 0; idx < collection.length; idx++, tablerowloop.next()) { for (let idx = 0; idx < collection.length; idx++, tablerowloop.next()) {
scope[this.variable] = collection[idx] scope[this.variable] = collection[idx]
if (tablerowloop.col0() === 0) { if (tablerowloop.col0() === 0) {
if (tablerowloop.row() !== 1) html += '</tr>' if (tablerowloop.row() !== 1) emitter.write('</tr>')
html += `<tr class="row${tablerowloop.row()}">` emitter.write(`<tr class="row${tablerowloop.row()}">`)
} }
html += `<td class="col${tablerowloop.col()}">` emitter.write(`<td class="col${tablerowloop.col()}">`)
html += await this.liquid.renderer.renderTemplates(this.templates, ctx) await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
html += '</td>' emitter.write('</td>')
} }
if (collection.length) html += '</tr>' if (collection.length) emitter.write('</tr>')
ctx.pop() ctx.pop()
return html
} }
} as ITagImplOptions } as ITagImplOptions
+5 -10
View File
@@ -1,9 +1,4 @@
import { evalExp, isFalsy } from '../../render/syntax' import { Emitter, evalExp, isFalsy, ParseStream, Context, ITagImplOptions, Token, Hash , TagToken } from '../../types'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
import Context from '../../context/context'
import ITagImplOptions from '../../template/tag/itag-impl-options'
import ParseStream from '../../parser/parse-stream'
export default { export default {
parse: function (tagToken: TagToken, remainTokens: Token[]) { parse: function (tagToken: TagToken, remainTokens: Token[]) {
@@ -25,10 +20,10 @@ export default {
stream.start() stream.start()
}, },
render: async function (ctx: Context) { render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
const cond = await evalExp(this.cond, ctx) const cond = await evalExp(this.cond, ctx)
return isFalsy(cond) isFalsy(cond)
? this.liquid.renderer.renderTemplates(this.templates, ctx) ? await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
: this.liquid.renderer.renderTemplates(this.elseTemplates, ctx) : await this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
} }
} as ITagImplOptions } as ITagImplOptions
+6 -6
View File
@@ -1,11 +1,11 @@
import * as _ from '../util/underscore' import * as _ from '../util/underscore'
import { Drop } from '../drop/drop' import { Drop } from '../drop/drop'
import { __assign } from 'tslib' import { __assign } from 'tslib'
import assert from '../util/assert' import { assert } from '../util/assert'
import { NormalizedFullOptions, applyDefault } from '../liquid-options' import { NormalizedFullOptions, applyDefault } from '../liquid-options'
import { Scope } from './scope' import { Scope } from './scope'
export default class Context { export class Context {
private scopes: Scope[] = [{}] private scopes: Scope[] = [{}]
private registers = {} private registers = {}
public environments: Scope public environments: Scope
@@ -24,8 +24,8 @@ export default class Context {
return [this.environments, ...this.scopes] return [this.environments, ...this.scopes]
.reduce((ctx, val) => __assign(ctx, val), {}) .reduce((ctx, val) => __assign(ctx, val), {})
} }
public async get (path: string) { public get (path: string) {
const paths = await this.parseProp(path) const paths = this.parseProp(path)
let ctx = this.findScope(paths[0]) || this.environments let ctx = this.findScope(paths[0]) || this.environments
for (const path of paths) { for (const path of paths) {
ctx = readProperty(ctx, path) ctx = readProperty(ctx, path)
@@ -62,7 +62,7 @@ export default class Context {
* accessSeq("foo['b]r']") // ['foo', 'b]r'] * accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar' * accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/ */
private async parseProp (str: string) { private parseProp (str: string) {
str = String(str) str = String(str)
const seq: string[] = [] const seq: string[] = []
let name = '' let name = ''
@@ -85,7 +85,7 @@ export default class Context {
assert(j !== -1, `unbalanced []: ${str}`) assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j) name = str.slice(i + 1, j)
if (!/^[+-]?\d+$/.test(name)) { // foo[bar] vs. foo[1] if (!/^[+-]?\d+$/.test(name)) { // foo[bar] vs. foo[1]
name = String(await this.get(name)) name = String(this.get(name))
} }
push() push()
i = j + 1 i = j + 1
+13 -19
View File
@@ -1,23 +1,22 @@
import Context from './context/context' import { Context } from './context/context'
import * as Types from './types'
import fs from './fs/node' import fs from './fs/node'
import * as _ from './util/underscore' import * as _ from './util/underscore'
import ITemplate from './template/itemplate' import { ITemplate } from './template/itemplate'
import Tokenizer from './parser/tokenizer' import { Tokenizer } from './parser/tokenizer'
import Render from './render/render' import { Render } from './render/render'
import Tag from './template/tag/tag' import { Tag } from './template/tag/tag'
import { Filter } from './template/filter/filter' import { Filter } from './template/filter/filter'
import Parser from './parser/parser' import Parser from './parser/parser'
import ITagImplOptions from './template/tag/itag-impl-options' import { ITagImplOptions } from './template/tag/itag-impl-options'
import Value from './template/value' import { Value } from './template/value'
import { isTruthy, isFalsy, evalExp, evalValue } from './render/syntax'
import builtinTags from './builtin/tags' import builtinTags from './builtin/tags'
import builtinFilters from './builtin/filters' import builtinFilters from './builtin/filters'
import { LiquidOptions, NormalizedFullOptions, applyDefault, normalize } from './liquid-options' import { LiquidOptions, NormalizedFullOptions, applyDefault, normalize } from './liquid-options'
import { FilterImplOptions } from './template/filter/filter-impl-options' import { FilterImplOptions } from './template/filter/filter-impl-options'
import IFS from './fs/ifs' import IFS from './fs/ifs'
export * from './types'
export default class Liquid { export class Liquid {
public options: NormalizedFullOptions public options: NormalizedFullOptions
public renderer: Render public renderer: Render
public parser: Parser public parser: Parser
@@ -39,10 +38,10 @@ export default class Liquid {
const tokens = this.tokenizer.tokenize(html, filepath) const tokens = this.tokenizer.tokenize(html, filepath)
return this.parser.parse(tokens) return this.parser.parse(tokens)
} }
public render (tpl: ITemplate[], ctx?: object, opts?: LiquidOptions) { public render (tpl: ITemplate[], scope?: object, opts?: LiquidOptions) {
const options = { ...this.options, ...normalize(opts) } const options = { ...this.options, ...normalize(opts) }
const scope = new Context(ctx, options) const ctx = new Context(scope, options)
return this.renderer.renderTemplates(tpl, scope) return this.renderer.renderTemplates(tpl, ctx)
} }
public async parseAndRender (html: string, ctx?: object, opts?: LiquidOptions) { public async parseAndRender (html: string, ctx?: object, opts?: LiquidOptions) {
const tpl = await this.parse(html) const tpl = await this.parse(html)
@@ -92,10 +91,5 @@ export default class Liquid {
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb) self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
} }
} }
public static default = Liquid public static default = Liquid // compatible to import { Liquid } from 'liquidjs'
public static isTruthy = isTruthy
public static isFalsy = isFalsy
public static evalExp = evalExp
public static evalValue = evalValue
public static Types = Types
} }
+2 -2
View File
@@ -1,7 +1,7 @@
import Token from './token' import { Token } from './token'
import { last } from '../util/underscore' import { last } from '../util/underscore'
export default class DelimitedToken extends Token { export class DelimitedToken extends Token {
public constructor ( public constructor (
raw: string, raw: string,
value: string, value: string,
+2 -2
View File
@@ -1,6 +1,6 @@
import Token from './token' import { Token } from './token'
export default class HTMLToken extends Token { export class HTMLToken extends Token {
public constructor (str: string, input: string, line: number, col: number, file?: string) { public constructor (str: string, input: string, line: number, col: number, file?: string) {
super(str, input, line, col, file) super(str, input, line, col, file)
this.type = 'html' this.type = 'html'
+3 -3
View File
@@ -1,8 +1,8 @@
import DelimitedToken from './delimited-token' import { DelimitedToken } from './delimited-token'
import Token from './token' import { Token } from './token'
import { NormalizedFullOptions } from '../liquid-options' import { NormalizedFullOptions } from '../liquid-options'
export default class OutputToken extends DelimitedToken { export class OutputToken extends DelimitedToken {
public constructor ( public constructor (
raw: string, raw: string,
value: string, value: string,
+4 -4
View File
@@ -1,10 +1,10 @@
import Token from '../parser/token' import { Token } from '../parser/token'
import ITemplate from '../template/itemplate' import { ITemplate } from '../template/itemplate'
import TagToken from './tag-token' import { TagToken } from './tag-token'
type ParseToken = ((token: Token, remainTokens: Token[]) => ITemplate) type ParseToken = ((token: Token, remainTokens: Token[]) => ITemplate)
export default class ParseStream { export class ParseStream {
private tokens: Token[] private tokens: Token[]
private handlers: {[key: string]: (arg: any) => void} = {} private handlers: {[key: string]: (arg: any) => void} = {}
private stopRequested: boolean = false private stopRequested: boolean = false
+9 -9
View File
@@ -1,13 +1,13 @@
import { ParseError } from '../util/error' import { ParseError } from '../util/error'
import Liquid from '../liquid' import { Liquid } from '../liquid'
import ParseStream from './parse-stream' import { ParseStream } from './parse-stream'
import Token from './token' import { Token } from './token'
import TagToken from './tag-token' import { TagToken } from './tag-token'
import OutputToken from './output-token' import { OutputToken } from './output-token'
import Tag from '../template/tag/tag' import { Tag } from '../template/tag/tag'
import Output from '../template/output' import { Output } from '../template/output'
import HTML from '../template/html' import { HTML } from '../template/html'
import ITemplate from '../template/itemplate' import { ITemplate } from '../template/itemplate'
export default class Parser { export default class Parser {
private liquid: Liquid private liquid: Liquid
+3 -3
View File
@@ -1,10 +1,10 @@
import DelimitedToken from './delimited-token' import { DelimitedToken } from './delimited-token'
import Token from './token' import { Token } from './token'
import { TokenizationError } from '../util/error' import { TokenizationError } from '../util/error'
import * as lexical from './lexical' import * as lexical from './lexical'
import { NormalizedFullOptions } from '../liquid-options' import { NormalizedFullOptions } from '../liquid-options'
export default class TagToken extends DelimitedToken { export class TagToken extends DelimitedToken {
public name: string public name: string
public args: string public args: string
public constructor ( public constructor (
+1 -1
View File
@@ -1,4 +1,4 @@
export default class Token { export class Token {
public trimLeft: boolean = false public trimLeft: boolean = false
public trimRight: boolean = false public trimRight: boolean = false
public type: string = 'notset' public type: string = 'notset'
+6 -6
View File
@@ -1,14 +1,14 @@
import whiteSpaceCtrl from './whitespace-ctrl' import { whiteSpaceCtrl } from './whitespace-ctrl'
import HTMLToken from './html-token' import { HTMLToken } from './html-token'
import TagToken from './tag-token' import { TagToken } from './tag-token'
import Token from './token' import { Token } from './token'
import OutputToken from './output-token' import { OutputToken } from './output-token'
import { TokenizationError } from '../util/error' import { TokenizationError } from '../util/error'
import { NormalizedFullOptions, applyDefault } from '../liquid-options' import { NormalizedFullOptions, applyDefault } from '../liquid-options'
enum ParseState { HTML, OUTPUT, TAG } enum ParseState { HTML, OUTPUT, TAG }
export default class Tokenizer { export class Tokenizer {
private options: NormalizedFullOptions private options: NormalizedFullOptions
public constructor (options?: NormalizedFullOptions) { public constructor (options?: NormalizedFullOptions) {
this.options = applyDefault(options) this.options = applyDefault(options)
+4 -4
View File
@@ -1,9 +1,9 @@
import Token from '../parser/token' import { Token } from '../parser/token'
import TagToken from '../parser/tag-token' import { TagToken } from '../parser/tag-token'
import HTMLToken from '../parser/html-token' import { HTMLToken } from '../parser/html-token'
import { NormalizedFullOptions } from '../liquid-options' import { NormalizedFullOptions } from '../liquid-options'
export default function whiteSpaceCtrl (tokens: Token[], options: NormalizedFullOptions) { export function whiteSpaceCtrl (tokens: Token[], options: NormalizedFullOptions) {
options = { greedy: true, ...options } options = { greedy: true, ...options }
let inRaw = false let inRaw = false
+6 -13
View File
@@ -1,22 +1,15 @@
import { RenderError } from '../util/error' import { RenderError } from '../util/error'
import assert from '../util/assert' import { Context } from '../context/context'
import Context from '../context/context' import { ITemplate } from '../template/itemplate'
import ITemplate from '../template/itemplate'
import { Emitter } from './emitter' import { Emitter } from './emitter'
export default class Render { export class Render {
public async renderTemplates (templates: ITemplate[], ctx: Context) { public async renderTemplates (templates: ITemplate[], ctx: Context, emitter = new Emitter()) {
assert(ctx, 'unable to evalTemplates: context undefined')
const emitter = new Emitter()
for (const tpl of templates) { for (const tpl of templates) {
try { try {
emitter.write(await tpl.render(ctx, emitter)) await tpl.render(ctx, emitter)
} catch (e) { } catch (e) {
if (e.name === 'RenderBreakError') { if (e.name === 'RenderBreakError') throw e
e.resolvedHTML = emitter.html
throw e
}
throw e.name === 'RenderError' ? e : new RenderError(e, tpl) throw e.name === 'RenderError' ? e : new RenderError(e, tpl)
} }
} }
+12 -12
View File
@@ -1,6 +1,6 @@
import * as lexical from '../parser/lexical' import * as lexical from '../parser/lexical'
import assert from '../util/assert' import { assert } from '../util/assert'
import Context from '../context/context' import { Context } from '../context/context'
import { range, last, isFunction, toValue } from '../util/underscore' import { range, last, isFunction, toValue } from '../util/underscore'
import { isComparable } from '../drop/icomparable' import { isComparable } from '../drop/icomparable'
import { NullDrop } from '../drop/null-drop' import { NullDrop } from '../drop/null-drop'
@@ -45,7 +45,7 @@ const binaryOperators: {[key: string]: (lhs: any, rhs: any) => boolean} = {
'or': (l: any, r: any) => isTruthy(l) || isTruthy(r) 'or': (l: any, r: any) => isTruthy(l) || isTruthy(r)
} }
export async function parseExp (exp: string, ctx: Context): Promise<any> { export function parseExp (exp: string, ctx: Context): any {
assert(ctx, 'unable to parseExp: scope undefined') assert(ctx, 'unable to parseExp: scope undefined')
const operatorREs = lexical.operators const operatorREs = lexical.operators
let match let match
@@ -53,27 +53,27 @@ export async function parseExp (exp: string, ctx: Context): Promise<any> {
const operatorRE = operatorREs[i] const operatorRE = operatorREs[i]
const 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))) {
const l = await parseExp(match[1], ctx) const l = parseExp(match[1], ctx)
const op = binaryOperators[match[2].trim()] const op = binaryOperators[match[2].trim()]
const r = await parseExp(match[3], ctx) const r = parseExp(match[3], ctx)
return op(l, r) return op(l, r)
} }
} }
if ((match = exp.match(lexical.rangeLine))) { if ((match = exp.match(lexical.rangeLine))) {
const low = await evalValue(match[1], ctx) const low = evalValue(match[1], ctx)
const high = await evalValue(match[2], ctx) const high = evalValue(match[2], ctx)
return range(+low, +high + 1) return range(+low, +high + 1)
} }
return parseValue(exp, ctx) return parseValue(exp, ctx)
} }
export async function evalExp (str: string, ctx: Context): Promise<any> { export function evalExp (str: string, ctx: Context): any {
return toValue(await parseExp(str, ctx)) return toValue(parseExp(str, ctx))
} }
export async function parseValue (str: string | undefined, ctx: Context): Promise<any> { export function parseValue (str: string | undefined, ctx: Context): any {
if (!str) return null if (!str) return null
str = str.trim() str = str.trim()
@@ -87,8 +87,8 @@ export async function parseValue (str: string | undefined, ctx: Context): Promis
return ctx.get(str) return ctx.get(str)
} }
export async function evalValue (str: string | undefined, ctx: Context) { export function evalValue (str: string | undefined, ctx: Context) {
return toValue(await parseValue(str, ctx)) return toValue(parseValue(str, ctx))
} }
export function isTruthy (val: any): boolean { export function isTruthy (val: any): boolean {
+1 -1
View File
@@ -1,4 +1,4 @@
import Context from '../../context/context' import { Context } from '../../context/context'
export interface FilterImpl { export interface FilterImpl {
context: Context; context: Context;
+4 -4
View File
@@ -1,5 +1,5 @@
import { parseValue } from '../../render/syntax' import { parseValue } from '../../render/syntax'
import Context from '../../context/context' import { Context } from '../../context/context'
import { isArray } from '../../util/underscore' import { isArray } from '../../util/underscore'
import { FilterImplOptions } from './filter-impl-options' import { FilterImplOptions } from './filter-impl-options'
@@ -21,11 +21,11 @@ export class Filter {
this.impl = impl || (x => x) this.impl = impl || (x => x)
this.args = args this.args = args
} }
public async render (value: any, context: Context) { public render (value: any, context: Context) {
const argv: any[] = [] const argv: any[] = []
for (const arg of this.args) { for (const arg of this.args) {
if (isKeyValuePair(arg)) argv.push([arg[0], await parseValue(arg[1], context)]) if (isKeyValuePair(arg)) argv.push([arg[0], parseValue(arg[1], context)])
else argv.push(await parseValue(arg, context)) else argv.push(parseValue(arg, context))
} }
return this.impl.apply({ context }, [value, ...argv]) return this.impl.apply({ context }, [value, ...argv])
} }
+8 -6
View File
@@ -1,14 +1,16 @@
import Template from '../template/template' import { Template } from '../template/template'
import ITemplate from '../template/itemplate' import { ITemplate } from '../template/itemplate'
import HTMLToken from '../parser/html-token' import { HTMLToken } from '../parser/html-token'
import { Context } from '../context/context'
import { Emitter } from '../render/emitter'
export default class extends Template<HTMLToken> implements ITemplate { export class HTML extends Template<HTMLToken> implements ITemplate {
private str: string private str: string
public constructor (token: HTMLToken) { public constructor (token: HTMLToken) {
super(token) super(token)
this.str = token.value this.str = token.value
} }
public async render (): Promise<string> { public render (ctx: Context, emitter: Emitter) {
return this.str emitter.write(this.str)
} }
} }
+4 -4
View File
@@ -1,8 +1,8 @@
import Context from '../context/context' import { Context } from '../context/context'
import Token from '../parser/token' import { Token } from '../parser/token'
import { Emitter } from '../render/emitter' import { Emitter } from '../render/emitter'
export default interface ITemplate { export interface ITemplate {
token: Token; token: Token;
render(ctx: Context, emitter: Emitter): Promise<string>; render(ctx: Context, emitter: Emitter): Promise<void> | void;
} }
+9 -8
View File
@@ -1,18 +1,19 @@
import Value from './value' import { Value } from './value'
import { stringify, toValue } from '../util/underscore' import { stringify, toValue } from '../util/underscore'
import Template from '../template/template' import { Template } from '../template/template'
import ITemplate from '../template/itemplate' import { ITemplate } from '../template/itemplate'
import Context from '../context/context' import { Context } from '../context/context'
import OutputToken from '../parser/output-token' import { Emitter } from '../render/emitter'
import { OutputToken } from '../parser/output-token'
export default class Output extends Template<OutputToken> implements ITemplate { export class Output extends Template<OutputToken> implements ITemplate {
private value: Value private value: Value
public constructor (token: OutputToken, strictFilters: boolean) { public constructor (token: OutputToken, strictFilters: boolean) {
super(token) super(token)
this.value = new Value(token.value, strictFilters) this.value = new Value(token.value, strictFilters)
} }
public async render (ctx: Context): Promise<string> { public async render (ctx: Context, emitter: Emitter) {
const val = await this.value.value(ctx) const val = await this.value.value(ctx)
return stringify(toValue(val)) emitter.write(stringify(toValue(val)))
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
import { hashCapture } from '../../parser/lexical' import { hashCapture } from '../../parser/lexical'
import { parseValue } from '../../render/syntax' import { parseValue } from '../../render/syntax'
import Context from '../../context/context' import { Context } from '../../context/context'
/** /**
* Key-Value Pairs Representing Tag Arguments * Key-Value Pairs Representing Tag Arguments
@@ -8,7 +8,7 @@ import Context from '../../context/context'
* For the markup `{% include 'head.html' foo='bar' %}`, * For the markup `{% include 'head.html' foo='bar' %}`,
* hash['foo'] === 'bar' * hash['foo'] === 'bar'
*/ */
export default class Hash { export class Hash {
[key: string]: any [key: string]: any
public static async create (markup: string, ctx: Context) { public static async create (markup: string, ctx: Context) {
const instance = new Hash() const instance = new Hash()
+8 -7
View File
@@ -1,10 +1,11 @@
import Context from '../../context/context' import { Context } from '../../context/context'
import TagToken from '../../parser/tag-token' import { TagToken } from '../../parser/tag-token'
import Token from '../../parser/token' import { Token } from '../../parser/token'
import Hash from '../../template/tag/hash' import { ITagImpl } from './itag-impl'
import ITagImpl from './itag-impl' import { Hash } from '../../template/tag/hash'
import { Emitter } from '../../render/emitter'
export default interface ITagImplOptions { export interface ITagImplOptions {
parse?: (this: ITagImpl, token: TagToken, remainingTokens: Token[]) => void; parse?: (this: ITagImpl, token: TagToken, remainingTokens: Token[]) => void;
render?: (this: ITagImpl, ctx: Context, hash: Hash) => any | Promise<any>; render: (this: ITagImpl, ctx: Context, hash: Hash, emitter: Emitter) => void;
} }
+3 -3
View File
@@ -1,7 +1,7 @@
import Liquid from '../../liquid' import { Liquid } from '../../liquid'
import ITagImplOptions from './itag-impl-options' import { ITagImplOptions } from './itag-impl-options'
export default interface ITagImpl extends ITagImplOptions { export interface ITagImpl extends ITagImplOptions {
liquid: Liquid; liquid: Liquid;
[key: string]: any; [key: string]: any;
} }
+9 -13
View File
@@ -1,16 +1,11 @@
import { stringify, isFunction } from '../../util/underscore' import { stringify, isFunction } from '../../util/underscore'
import assert from '../../util/assert' import { assert } from '../../util/assert'
import Context from '../../context/context' import { Liquid } from '../../liquid'
import ITagImpl from './itag-impl' import { Template } from '../../template/template'
import ITagImplOptions from './itag-impl-options' import { Emitter, Hash, Context, ITagImplOptions, TagToken, ITemplate, Token } from '../../types'
import Liquid from '../../liquid' import { ITagImpl } from './itag-impl'
import Hash from './hash'
import Template from '../../template/template'
import ITemplate from '../../template/itemplate'
import TagToken from '../../parser/tag-token'
import Token from '../../parser/token'
export default class Tag extends Template<TagToken> implements ITemplate { export class Tag extends Template<TagToken> implements ITemplate {
public name: string public name: string
private impl: ITagImpl private impl: ITagImpl
private static impls: { [key: string]: ITagImplOptions } = {} private static impls: { [key: string]: ITagImplOptions } = {}
@@ -28,10 +23,11 @@ export default class Tag extends Template<TagToken> implements ITemplate {
this.impl.parse(token, tokens) this.impl.parse(token, tokens)
} }
} }
public async render (ctx: Context) { public async render (ctx: Context, emitter: Emitter) {
const hash = await Hash.create(this.token.args, ctx) const hash = await Hash.create(this.token.args, ctx)
const impl = this.impl const impl = this.impl
return isFunction(impl.render) ? stringify(await impl.render(ctx, hash)) : '' const html = isFunction(impl.render) ? stringify(await impl.render(ctx, hash, emitter)) : ''
html && emitter.write(html)
} }
public static register (name: string, tag: ITagImplOptions) { public static register (name: string, tag: ITagImplOptions) {
Tag.impls[name] = tag Tag.impls[name] = tag
+1 -1
View File
@@ -1,4 +1,4 @@
export default abstract class Template<T> { export abstract class Template<T> {
public token: T; public token: T;
public constructor (token: T) { public constructor (token: T) {
this.token = token this.token = token
+5 -5
View File
@@ -1,8 +1,8 @@
import { parseExp } from '../render/syntax' import { parseExp } from '../render/syntax'
import { FilterArgs, Filter } from './filter/filter' import { FilterArgs, Filter } from './filter/filter'
import Context from '../context/context' import { Context } from '../context/context'
export default class Value { export class Value {
private strictFilters: boolean private strictFilters: boolean
private initial: string private initial: string
private filters: Filter[] = [] private filters: Filter[] = []
@@ -47,10 +47,10 @@ export default class Value {
} }
this.filters.push(new Filter(name, args, this.strictFilters)) this.filters.push(new Filter(name, args, this.strictFilters))
} }
public async value (ctx: Context) { public value (ctx: Context) {
let val = await parseExp(this.initial, ctx) let val = parseExp(this.initial, ctx)
for (const filter of this.filters) { for (const filter of this.filters) {
val = await filter.render(val, ctx) val = filter.render(val, ctx)
} }
return val return val
} }
+9
View File
@@ -1,2 +1,11 @@
export { ParseError, TokenizationError, RenderBreakError, AssertionError } from './util/error' export { ParseError, TokenizationError, RenderBreakError, AssertionError } from './util/error'
export { Drop } from './drop/drop' export { Drop } from './drop/drop'
export { Emitter } from './render/emitter'
export { isTruthy, isFalsy, evalExp, evalValue } from './render/syntax'
export { TagToken } from './parser/tag-token'
export { Context } from './context/context'
export { ITemplate } from './template/itemplate'
export { ITagImplOptions } from './template/tag/itag-impl-options'
export { ParseStream } from './parser/parse-stream'
export { Token } from './parser/token'
export { Hash } from './template/tag/hash'
+1 -1
View File
@@ -1,6 +1,6 @@
import { AssertionError } from './error' import { AssertionError } from './error'
export default function<T> (predicate: T | null | undefined, message?: string) { export function assert <T> (predicate: T | null | undefined, message?: string) {
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)
+2 -2
View File
@@ -1,6 +1,6 @@
import * as _ from './underscore' import * as _ from './underscore'
import Token from '../parser/token' import { Token } from '../parser/token'
import ITemplate from '../template/itemplate' import { ITemplate } from '../template/itemplate'
abstract class LiquidError extends Error { abstract class LiquidError extends Error {
private token: Token private token: Token
+2 -2
View File
@@ -1,10 +1,10 @@
import Liquid from '../..' import { Liquid, Drop } from '../..'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
use(chaiAsPromised) use(chaiAsPromised)
class SettingsDrop extends Liquid.Types.Drop { class SettingsDrop extends Drop {
private foo: string = 'FOO' private foo: string = 'FOO'
public bar () { public bar () {
return 'BAR' return 'BAR'
+2 -2
View File
@@ -1,11 +1,11 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../..' import { Liquid } from '../..'
describe('.evalValue()', function () { describe('.evalValue()', function () {
var engine: Liquid var engine: Liquid
beforeEach(() => { engine = new Liquid() }) beforeEach(() => { engine = new Liquid() })
it('should throw when scope undefined', async function () { it('should throw when scope undefined', async function () {
return expect(engine.evalValue('{{"foo"}}', null as any)).to.be.rejectedWith(/scope undefined/) return expect(() => engine.evalValue('{{"foo"}}', null as any)).to.throw(/scope undefined/)
}) })
}) })
+1 -1
View File
@@ -2,7 +2,7 @@ import { expect } from 'chai'
import * as request from 'supertest' import * as request from 'supertest'
import * as express from 'express' import * as express from 'express'
import { resolve } from 'path' import { resolve } from 'path'
import Liquid from '../..' import { Liquid } from '../..'
describe('express()', function () { describe('express()', function () {
const root = resolve(__dirname, '../stub/root') const root = resolve(__dirname, '../stub/root')
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../..' import { Liquid } from '../..'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../..' import { Liquid } from '../..'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
import { resolve } from 'path' import { resolve } from 'path'
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../..' import { Liquid } from '../..'
const liquid = new Liquid() const liquid = new Liquid()
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../dist/liquid.js' import { Liquid } from '../../dist/liquid.js'
import * as sinon from 'sinon' import * as sinon from 'sinon'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import { JSDOM } from 'jsdom' import { JSDOM } from 'jsdom'
+1 -1
View File
@@ -1,5 +1,5 @@
import { test } from '../../../stub/render' import { test } from '../../../stub/render'
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('filters/array', function () { describe('filters/array', function () {
+1 -1
View File
@@ -1,6 +1,6 @@
import { test, ctx } from '../../../stub/render' import { test, ctx } from '../../../stub/render'
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
describe('filters/date', function () { describe('filters/date', function () {
let liquid: Liquid let liquid: Liquid
+1 -1
View File
@@ -1,6 +1,6 @@
import { expect } from 'chai' import { expect } from 'chai'
import { test, liquid } from '../../../stub/render' import { test, liquid } from '../../../stub/render'
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
describe('filters/math', function () { describe('filters/math', function () {
const l = new Liquid() const l = new Liquid()
+1 -1
View File
@@ -1,5 +1,5 @@
import { test } from '../../../stub/render' import { test } from '../../../stub/render'
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('filters/string', function () { describe('filters/string', function () {
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+17 -7
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
import { Scope } from '../../../../src/context/scope' import { Scope } from '../../../../src/context/scope'
@@ -106,12 +106,22 @@ describe('tags/for', function () {
return expect(html).to.equal(dst) return expect(html).to.equal(dst)
}) })
it('should support for with continue', async function () { describe('continue', function () {
const src = '{% for i in (1..5) %}' + it('should support for with continue', async function () {
'{{i}}{% continue %}after' + const src = '{% for i in (1..5) %}' +
'{% endfor %}' '{% if i == 4 %}continue{% continue %}{% endif %}{{i}}' +
const html = await liquid.parseAndRender(src, ctx) '{% endfor %}'
return expect(html).to.equal('12345') const html = await liquid.parseAndRender(src, ctx)
return expect(html).to.equal('123continue5')
})
it('should output contents before continue', async function () {
const src = '{% for i in (1..5) %}' +
'{% if i == 4 %}continue{% continue %}{% endif %}' +
'{{ i }}' +
'{% endfor %}'
const html = await liquid.parseAndRender(src, ctx)
return expect(html).to.equal('123continue5')
})
}) })
describe('break', function () { describe('break', function () {
it('should support break', async function () { it('should support break', async function () {
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('tags/if', function () { describe('tags/if', function () {
+5 -5
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid, Drop } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
import { mock, restore } from '../../../stub/mockfs' import { mock, restore } from '../../../stub/mockfs'
@@ -83,8 +83,8 @@ describe('tags/include', function () {
const html = await liquid.renderFile('with.html') const html = await liquid.renderFile('with.html')
return expect(html).to.equal('color:red, shape:rect') return expect(html).to.equal('color:red, shape:rect')
}) })
it('should support include: with as Liquid Drop', async function () { it('should support include: with as Drop', async function () {
class ColorDrop extends Liquid.Types.Drop { class ColorDrop extends Drop {
public valueOf (): string { public valueOf (): string {
return 'red!' return 'red!'
} }
@@ -96,8 +96,8 @@ describe('tags/include', function () {
const html = await liquid.renderFile('with.html', { color: new ColorDrop() }) const html = await liquid.renderFile('with.html', { color: new ColorDrop() })
expect(html).to.equal('color:red!') expect(html).to.equal('color:red!')
}) })
it('should support include: with passed as Liquid Drop', async function () { it('should support include: with passed as Drop', async function () {
class ColorDrop extends Liquid.Types.Drop { class ColorDrop extends Drop {
public valueOf (): string { public valueOf (): string {
return 'red!' return 'red!'
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
import { mock, restore } from '../../../stub/mockfs' import { mock, restore } from '../../../stub/mockfs'
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('tags/raw', function () { describe('tags/raw', function () {
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('tags/tablerow', function () { describe('tags/tablerow', function () {
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../../src/liquid' import { Liquid } from '../../../../src/liquid'
import { expect, use } from 'chai' import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('drop/blank-drop', function () { describe('drop/blank-drop', function () {
let liquid: Liquid let liquid: Liquid
+3 -3
View File
@@ -1,11 +1,11 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid, Drop } from '../../../src/liquid'
describe('drop/drop', function () { describe('drop/drop', function () {
let liquid: Liquid let liquid: Liquid
before(() => (liquid = new Liquid())) before(() => (liquid = new Liquid()))
class CustomDrop extends Liquid.Types.Drop { class CustomDrop extends Drop {
private name: string = 'NAME' private name: string = 'NAME'
public getName () { public getName () {
return 'GET NAME' return 'GET NAME'
@@ -16,7 +16,7 @@ describe('drop/drop', function () {
return key.toUpperCase() return key.toUpperCase()
} }
} }
class PromiseDrop extends Liquid.Types.Drop { class PromiseDrop extends Drop {
private name = Promise.resolve('NAME') private name = Promise.resolve('NAME')
public async getName () { public async getName () {
return 'GET NAME' return 'GET NAME'
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('drop/empty-drop', function () { describe('drop/empty-drop', function () {
let liquid: Liquid let liquid: Liquid
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('drop/null-drop', function () { describe('drop/null-drop', function () {
let liquid: Liquid let liquid: Liquid
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
import { mock, restore } from '../../stub/mockfs' import { mock, restore } from '../../stub/mockfs'
describe('LiquidOptions#cache', function () { describe('LiquidOptions#cache', function () {
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('LiquidOptions#*_delimiter_*', function () { describe('LiquidOptions#*_delimiter_*', function () {
it('should respect tag_delimiter_*', async function () { it('should respect tag_delimiter_*', async function () {
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('LiquidOptions#fs', function () { describe('LiquidOptions#fs', function () {
let engine: Liquid let engine: Liquid
+2 -2
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../src/liquid' import { Liquid, isFalsy } from '../../../src/liquid'
import * as chai from 'chai' import * as chai from 'chai'
import { mock, restore } from '../../stub/mockfs' import { mock, restore } from '../../stub/mockfs'
import * as chaiAsPromised from 'chai-as-promised' import * as chaiAsPromised from 'chai-as-promised'
@@ -19,7 +19,7 @@ describe('Liquid', function () {
it('should call plugin with Liquid', async function () { it('should call plugin with Liquid', async function () {
const engine = new Liquid() const engine = new Liquid()
engine.plugin(function (Liquid) { engine.plugin(function (Liquid) {
this.registerFilter('t', x => Liquid.isFalsy(x)) this.registerFilter('t', x => isFalsy(x))
}) })
const html = await engine.parseAndRender('{{false|t}}') const html = await engine.parseAndRender('{{false|t}}')
expect(html).to.equal('true') expect(html).to.equal('true')
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
describe('LiquidOptions#strict*', function () { describe('LiquidOptions#strict*', function () {
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
describe('LiquidOptions#trimming', function () { describe('LiquidOptions#trimming', function () {
const ctx = { name: 'harttle' } const ctx = { name: 'harttle' }
+3 -2
View File
@@ -1,5 +1,5 @@
import { expect } from 'chai' import { expect } from 'chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
import * as path from 'path' import * as path from 'path'
import { mock, restore } from '../../stub/mockfs' import { mock, restore } from '../../stub/mockfs'
@@ -190,7 +190,8 @@ describe('error', function () {
engine.registerTag('throwsOnParse', { engine.registerTag('throwsOnParse', {
parse: function () { parse: function () {
throw new Error('intended parse error') throw new Error('intended parse error')
} },
render: () => ''
}) })
}) })
it('should throw ParseError when filter not defined', async function () { it('should throw ParseError when filter not defined', async function () {
+1 -1
View File
@@ -1,4 +1,4 @@
import Liquid from '../../src/liquid' import { Liquid } from '../../src/liquid'
import { expect } from 'chai' import { expect } from 'chai'
export const liquid = new Liquid() export const liquid = new Liquid()
+39 -40
View File
@@ -1,10 +1,10 @@
import * as chai from 'chai' import * as chai from 'chai'
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import { Scope } from '../../../src/context/scope' import { Scope } from '../../../src/context/scope'
const expect = chai.expect const expect = chai.expect
describe('scope', function () { describe('Context', function () {
let ctx: any, scope: Scope let ctx: any, scope: Scope
beforeEach(function () { beforeEach(function () {
scope = { scope = {
@@ -22,108 +22,107 @@ describe('scope', function () {
describe('#propertyAccessSeq()', function () { describe('#propertyAccessSeq()', function () {
it('should handle dot syntax', async function () { it('should handle dot syntax', async function () {
expect(await ctx.parseProp('foo.bar')) expect(ctx.parseProp('foo.bar'))
.to.deep.equal(['foo', 'bar']) .to.deep.equal(['foo', 'bar'])
}) })
it('should handle [<String>] syntax', async function () { it('should handle [<String>] syntax', async function () {
expect(await ctx.parseProp('foo["bar"]')) expect(ctx.parseProp('foo["bar"]'))
.to.deep.equal(['foo', 'bar']) .to.deep.equal(['foo', 'bar'])
}) })
it('should handle [<Identifier>] syntax', async function () { it('should handle [<Identifier>] syntax', async function () {
expect(await ctx.parseProp('foo[foo]')) expect(ctx.parseProp('foo[foo]'))
.to.deep.equal(['foo', 'zoo']) .to.deep.equal(['foo', 'zoo'])
}) })
it('should handle nested access 1', async function () { it('should handle nested access 1', async function () {
expect(await ctx.parseProp('foo[bar.zoo]')) expect(ctx.parseProp('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']) .to.deep.equal(['foo', 'coo'])
}) })
it('should handle nested access 2', async function () { it('should handle nested access 2', async function () {
expect(await ctx.parseProp('foo[bar["zoo"]]')) expect(ctx.parseProp('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']) .to.deep.equal(['foo', 'coo'])
}) })
it('should handle nested access 3', async function () { it('should handle nested access 3', async function () {
expect(await ctx.parseProp('bar["foo"].zoo')) expect(ctx.parseProp('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo']) .to.deep.equal(['bar', 'foo', 'zoo'])
}) })
it('should handle nested access 4', async function () { it('should handle nested access 4', async function () {
expect(await ctx.parseProp('foo[0].bar')) expect(ctx.parseProp('foo[0].bar'))
.to.deep.equal(['foo', '0', 'bar']) .to.deep.equal(['foo', '0', 'bar'])
}) })
it('should handle nested access 5', async function () { it('should handle nested access 5', async function () {
expect(await ctx.parseProp('foo[one].bar')) expect(ctx.parseProp('foo[one].bar'))
.to.deep.equal(['foo', '1', 'bar']) .to.deep.equal(['foo', '1', 'bar'])
}) })
it('should handle nested access 6', async function () { it('should handle nested access 6', async function () {
expect(await ctx.parseProp('foo[two].bar')) expect(ctx.parseProp('foo[two].bar'))
.to.deep.equal(['foo', 'undefined', 'bar']) .to.deep.equal(['foo', 'undefined', 'bar'])
}) })
}) })
describe('#get()', function () { describe('#get()', function () {
it('should get direct property', async function () { it('should get direct property', async function () {
expect(await await ctx.get('foo')).equal('zoo') expect(ctx.get('foo')).equal('zoo')
}) })
it('undefined property should yield undefined', async function () { it('undefined property should yield undefined', async function () {
expect(ctx.get('notdefined')).to.be.rejected expect(ctx.get('notdefined')).to.equal(undefined)
expect(await ctx.get('notdefined')).to.equal(undefined) expect(ctx.get(false as any)).to.equal(undefined)
expect(await ctx.get(false as any)).to.equal(undefined)
}) })
it('should throw for invalid path', async function () { it('should throw for invalid path', async function () {
expect(ctx.get('')).to.be.rejectedWith('invalid path:""') expect(() => ctx.get('')).to.throw('invalid path:""')
}) })
it('should throw when [] unbalanced', async function () { it('should throw when [] unbalanced', async function () {
expect(ctx.get('foo[bar')).to.be.rejectedWith(/unbalanced \[\]/) expect(() => ctx.get('foo[bar')).to.throw(/unbalanced \[\]/)
}) })
it('should throw when "" unbalanced', async function () { it('should throw when "" unbalanced', async function () {
expect(ctx.get('foo["bar]')).to.be.rejectedWith(/unbalanced "/) expect(() => ctx.get('foo["bar]')).to.throw(/unbalanced "/)
}) })
it("should throw when '' unbalanced", async function () { it("should throw when '' unbalanced", async function () {
expect(ctx.get("foo['bar]")).to.be.rejectedWith(/unbalanced '/) expect(() => ctx.get("foo['bar]")).to.throw(/unbalanced '/)
}) })
it('should respect to toLiquid', async function () { it('should respect to toLiquid', async function () {
const scope = new Context({ foo: { const scope = new Context({ foo: {
toLiquid: () => ({ bar: 'BAR' }), toLiquid: () => ({ bar: 'BAR' }),
bar: 'bar' bar: 'bar'
} }) } })
expect(await scope.get('foo.bar')).to.equal('BAR') expect(scope.get('foo.bar')).to.equal('BAR')
}) })
it('should access child property via dot syntax', async function () { it('should access child property via dot syntax', async function () {
expect(await ctx.get('bar.zoo')).to.equal('coo') expect(ctx.get('bar.zoo')).to.equal('coo')
expect(await ctx.get('bar.arr')).to.deep.equal(['a', 'b']) expect(ctx.get('bar.arr')).to.deep.equal(['a', 'b'])
}) })
it('should access child property via [<String>] syntax', async function () { it('should access child property via [<String>] syntax', async function () {
expect(await ctx.get('bar["zoo"]')).to.equal('coo') expect(ctx.get('bar["zoo"]')).to.equal('coo')
}) })
it('should access child property via [<Number>] syntax', async function () { it('should access child property via [<Number>] syntax', async function () {
expect(await ctx.get('bar.arr[0]')).to.equal('a') expect(ctx.get('bar.arr[0]')).to.equal('a')
}) })
it('should access child property via [<Identifier>] syntax', async function () { it('should access child property via [<Identifier>] syntax', async function () {
expect(await ctx.get('bar[foo]')).to.equal('coo') expect(ctx.get('bar[foo]')).to.equal('coo')
}) })
it('should return undefined when not exist', async function () { it('should return undefined when not exist', async function () {
expect(await ctx.get('foo.foo.foo')).to.be.undefined expect(ctx.get('foo.foo.foo')).to.be.undefined
}) })
it('should return string length as size', async function () { it('should return string length as size', async function () {
expect(await ctx.get('foo.size')).to.equal(3) expect(ctx.get('foo.size')).to.equal(3)
}) })
it('should return array length as size', async function () { it('should return array length as size', async function () {
expect(await ctx.get('bar.arr.size')).to.equal(2) expect(ctx.get('bar.arr.size')).to.equal(2)
}) })
it('should return size property if exists', async function () { it('should return size property if exists', async function () {
expect(await ctx.get('zoo.size')).to.equal(4) expect(ctx.get('zoo.size')).to.equal(4)
}) })
it('should return undefined if do not have size and length', async function () { it('should return undefined if do not have size and length', async function () {
expect(await ctx.get('one.size')).to.equal(undefined) expect(ctx.get('one.size')).to.equal(undefined)
}) })
}) })
describe('strictVariables', async function () { describe('strictVariables', async function () {
@@ -134,28 +133,28 @@ describe('scope', function () {
} as any) } as any)
}) })
it('should throw when variable not defined', function () { it('should throw when variable not defined', function () {
return expect(ctx.get('notdefined')).to.be.rejectedWith(/undefined variable: notdefined/) return expect(() => ctx.get('notdefined')).to.throw(/undefined variable: notdefined/)
}) })
it('should throw when deep variable not exist', async function () { it('should throw when deep variable not exist', async function () {
ctx.push({ foo: 'FOO' }) ctx.push({ foo: 'FOO' })
return expect(ctx.get('foo.bar.not.defined')).to.be.rejectedWith(/undefined variable: bar/) return expect(() => ctx.get('foo.bar.not.defined')).to.throw(/undefined variable: bar/)
}) })
it('should throw when itself not defined', async function () { it('should throw when itself not defined', async function () {
ctx.push({ foo: 'FOO' }) ctx.push({ foo: 'FOO' })
return expect(ctx.get('foo.BAR')).to.be.rejectedWith(/undefined variable: BAR/) return expect(() => ctx.get('foo.BAR')).to.throw(/undefined variable: BAR/)
}) })
it('should find variable in parent scope', async function () { it('should find variable in parent scope', async function () {
ctx.push({ 'foo': 'foo' }) ctx.push({ 'foo': 'foo' })
ctx.push({ ctx.push({
'bar': 'bar' 'bar': 'bar'
}) })
expect(await ctx.get('foo')).to.equal('foo') expect(ctx.get('foo')).to.equal('foo')
}) })
}) })
describe('.getAll()', function () { describe('.getAll()', function () {
it('should get all properties when arguments empty', async function () { it('should get all properties when arguments empty', async function () {
expect(await ctx.getAll()).deep.equal(scope) expect(ctx.getAll()).deep.equal(scope)
}) })
}) })
@@ -165,14 +164,14 @@ describe('scope', function () {
ctx.push({ ctx.push({
foo: 'foo' foo: 'foo'
}) })
expect(await ctx.get('foo')).to.equal('foo') expect(ctx.get('foo')).to.equal('foo')
expect(await ctx.get('bar')).to.equal('bar') expect(ctx.get('bar')).to.equal('bar')
}) })
it('should hide deep properties by push', async function () { it('should hide deep properties by push', async function () {
ctx.push({ bar: { bar: 'bar' } }) ctx.push({ bar: { bar: 'bar' } })
ctx.push({ bar: { foo: 'foo' } }) ctx.push({ bar: { foo: 'foo' } })
expect(await ctx.get('bar.foo')).to.equal('foo') expect(ctx.get('bar.foo')).to.equal('foo')
expect(await ctx.get('bar.bar')).to.equal(undefined) expect(ctx.get('bar.bar')).to.equal(undefined)
}) })
}) })
describe('.pop()', function () { describe('.pop()', function () {
@@ -181,7 +180,7 @@ describe('scope', function () {
foo: 'foo' foo: 'foo'
}) })
ctx.pop() ctx.pop()
expect(await ctx.get('foo')).to.equal('zoo') expect(ctx.get('foo')).to.equal('zoo')
}) })
}) })
}) })
+4 -4
View File
@@ -1,8 +1,8 @@
import { expect } from 'chai' import { expect } from 'chai'
import Tokenizer from '../../../src/parser/tokenizer' import { Tokenizer } from '../../../src/parser/tokenizer'
import TagToken from '../../../src/parser/tag-token' import { TagToken } from '../../../src/parser/tag-token'
import OutputToken from '../../../src/parser/output-token' import { OutputToken } from '../../../src/parser/output-token'
import HTMLToken from '../../../src/parser/html-token' import { HTMLToken } from '../../../src/parser/html-token'
describe('tokenizer', function () { describe('tokenizer', function () {
const tokenizer = new Tokenizer() const tokenizer = new Tokenizer()
+5 -5
View File
@@ -1,10 +1,10 @@
import { expect } from 'chai' import { expect } from 'chai'
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import Token from '../../../src/parser/token' import { Token } from '../../../src/parser/token'
import Tag from '../../../src/template/tag/tag' import { Tag } from '../../../src/template/tag/tag'
import { Filter } from '../../../src/template/filter/filter' import { Filter } from '../../../src/template/filter/filter'
import Render from '../../../src/render/render' import { Render } from '../../../src/render/render'
import HTML from '../../../src/template/html' import { HTML } from '../../../src/template/html'
describe('render', function () { describe('render', function () {
let render: Render let render: Render
+2 -2
View File
@@ -1,4 +1,4 @@
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import { expect } from 'chai' import { expect } from 'chai'
import { evalExp, evalValue, isTruthy } from '../../../src/render/syntax' import { evalExp, evalValue, isTruthy } from '../../../src/render/syntax'
@@ -62,7 +62,7 @@ describe('render/syntax', function () {
describe('.evalExp()', function () { describe('.evalExp()', function () {
it('should throw when scope undefined', async function () { it('should throw when scope undefined', async function () {
return expect((evalExp as any)('')).to.be.rejectedWith(/scope undefined/) return expect(() => (evalExp as any)('')).to.throw(/scope undefined/)
}) })
it('should eval simple expression', async function () { it('should eval simple expression', async function () {
+2 -2
View File
@@ -2,7 +2,7 @@ import * as chai from 'chai'
import * as sinon from 'sinon' import * as sinon from 'sinon'
import * as sinonChai from 'sinon-chai' import * as sinonChai from 'sinon-chai'
import { Filter } from '../../../../src/template/filter/filter' import { Filter } from '../../../../src/template/filter/filter'
import Context from '../../../../src/context/context' import { Context } from '../../../../src/context/context'
chai.use(sinonChai) chai.use(sinonChai)
const expect = chai.expect const expect = chai.expect
@@ -14,7 +14,7 @@ describe('filter', function () {
ctx = new Context() ctx = new Context()
}) })
it('should create default filter if not registered', async function () { it('should create default filter if not registered', async function () {
const result = new Filter('foo', [], false) const result = new Filter('foo', [], false) as any
expect(result.name).to.equal('foo') expect(result.name).to.equal('foo')
}) })
+13 -11
View File
@@ -1,14 +1,16 @@
import * as chai from 'chai' import * as chai from 'chai'
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import Output from '../../../src/template/output' import { Output } from '../../../src/template/output'
import OutputToken from '../../../src/parser/output-token' import { OutputToken } from '../../../src/parser/output-token'
import { Filter } from '../../../src/template/filter/filter' import { Filter } from '../../../src/template/filter/filter'
const expect = chai.expect const expect = chai.expect
describe('Output', function () { describe('Output', function () {
const emitter = { write: (html: string) => (emitter.html += html), html: '' }
beforeEach(function () { beforeEach(function () {
Filter.clear() Filter.clear()
emitter.html = ''
}) })
it('should stringify objects', async function () { it('should stringify objects', async function () {
@@ -16,25 +18,25 @@ describe('Output', function () {
foo: { obj: { arr: ['a', 2] } } foo: { obj: { arr: ['a', 2] } }
}) })
const output = new Output({ value: 'foo' } as OutputToken, false) const output = new Output({ value: 'foo' } as OutputToken, false)
const html = await output.render(scope) await output.render(scope, emitter)
return expect(html).to.equal('[object Object]') return expect(emitter.html).to.equal('[object Object]')
}) })
it('should skip function property', async function () { it('should skip function property', async function () {
const scope = new Context({ obj: { foo: 'foo', bar: (x: any) => x } }) const scope = new Context({ obj: { foo: 'foo', bar: (x: any) => x } })
const output = new Output({ value: 'obj' } as OutputToken, false) const output = new Output({ value: 'obj' } as OutputToken, false)
const html = await output.render(scope) await output.render(scope, emitter)
return expect(html).to.equal('[object Object]') return expect(emitter.html).to.equal('[object Object]')
}) })
it('should respect to .toString()', async () => { it('should respect to .toString()', async () => {
const scope = new Context({ obj: { toString: () => 'FOO' } }) const scope = new Context({ obj: { toString: () => 'FOO' } })
const output = new Output({ value: 'obj' } as OutputToken, false) const output = new Output({ value: 'obj' } as OutputToken, false)
const str = await output.render(scope) await output.render(scope, emitter)
return expect(str).to.equal('FOO') return expect(emitter.html).to.equal('FOO')
}) })
it('should respect to .toString()', async () => { it('should respect to .toString()', async () => {
const scope = new Context({ obj: { toString: () => 'FOO' } }) const scope = new Context({ obj: { toString: () => 'FOO' } })
const output = new Output({ value: 'obj' } as OutputToken, false) const output = new Output({ value: 'obj' } as OutputToken, false)
const str = await output.render(scope) await output.render(scope, emitter)
return expect(str).to.equal('FOO') return expect(emitter.html).to.equal('FOO')
}) })
}) })
+14 -10
View File
@@ -1,10 +1,10 @@
import * as chai from 'chai' import * as chai from 'chai'
import Tag from '../../../src/template/tag/tag' import { Tag } from '../../../src/template/tag/tag'
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import * as sinon from 'sinon' import * as sinon from 'sinon'
import * as sinonChai from 'sinon-chai' import * as sinonChai from 'sinon-chai'
import Liquid from '../../../src/liquid' import { Liquid } from '../../../src/liquid'
import TagToken from '../../../src/parser/tag-token' import { TagToken } from '../../../src/parser/tag-token'
chai.use(sinonChai) chai.use(sinonChai)
const expect = chai.expect const expect = chai.expect
@@ -12,6 +12,7 @@ const liquid = new Liquid()
describe('tag', function () { describe('tag', function () {
let ctx: Context let ctx: Context
const emitter = { write: (html: string) => (emitter.html += html), html: '' }
before(function () { before(function () {
ctx = new Context({ ctx = new Context({
foo: 'bar', foo: 'bar',
@@ -22,6 +23,9 @@ describe('tag', function () {
}) })
Tag.clear() Tag.clear()
}) })
beforeEach(function () {
emitter.html = ''
})
it('should throw when not registered', function () { it('should throw when not registered', function () {
expect(function () { expect(function () {
@@ -51,7 +55,7 @@ describe('tag', function () {
value: 'foo', value: 'foo',
name: 'foo' name: 'foo'
} as TagToken } as TagToken
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.called expect(spy).to.have.been.called
}) })
@@ -70,29 +74,29 @@ describe('tag', function () {
} as TagToken } as TagToken
}) })
it('should call tag.render with scope', async function () { it('should call tag.render with scope', async function () {
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.calledWithMatch(ctx) expect(spy).to.have.been.calledWithMatch(ctx)
}) })
it('should resolve identifier hash', async function () { it('should resolve identifier hash', async function () {
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.calledWithMatch({}, { expect(spy).to.have.been.calledWithMatch({}, {
aa: 'bar' aa: 'bar'
}) })
}) })
it('should accept space between key/value', async function () { it('should accept space between key/value', async function () {
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.calledWithMatch({}, { expect(spy).to.have.been.calledWithMatch({}, {
bb: 2 bb: 2
}) })
}) })
it('should resolve number value hash', async function () { it('should resolve number value hash', async function () {
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.calledWithMatch(ctx, { expect(spy).to.have.been.calledWithMatch(ctx, {
cc: 2.3 cc: 2.3
}) })
}) })
it('should resolve property access hash', async function () { it('should resolve property access hash', async function () {
await new Tag(token, [], liquid).render(ctx) await new Tag(token, [], liquid).render(ctx, emitter)
expect(spy).to.have.been.calledWithMatch(ctx, { expect(spy).to.have.been.calledWithMatch(ctx, {
dd: 'uoo' dd: 'uoo'
}) })
+2 -2
View File
@@ -1,9 +1,9 @@
import * as chai from 'chai' import * as chai from 'chai'
import * as sinonChai from 'sinon-chai' import * as sinonChai from 'sinon-chai'
import * as sinon from 'sinon' import * as sinon from 'sinon'
import Context from '../../../src/context/context' import { Context } from '../../../src/context/context'
import { Filter } from '../../../src/template/filter/filter' import { Filter } from '../../../src/template/filter/filter'
import Value from '../../../src/template/value' import { Value } from '../../../src/template/value'
chai.use(sinonChai) chai.use(sinonChai)
+1 -1
View File
@@ -1,5 +1,5 @@
import * as chai from 'chai' import * as chai from 'chai'
import assert from '../../../src/util/assert' import { assert } from '../../../src/util/assert'
const expect = chai.expect const expect = chai.expect