fix: throws on invalid arguments for prepend/append, fixes #208

This commit is contained in:
harttle
2020-03-24 23:57:26 +08:00
parent 60c14ba057
commit 479c63350a
13 changed files with 163 additions and 113 deletions
+12 -19
View File
@@ -1,42 +1,35 @@
import { isArray, last } from '../../util/underscore' import { isArray, last as arrayLast } from '../../util/underscore'
import { isTruthy } from '../../render/boolean' import { isTruthy } from '../../render/boolean'
import { FilterImpl } from '../../template/filter/filter-impl' import { FilterImpl } from '../../template/filter/filter-impl'
export default { export const join = (v: any[], arg: string) => v.join(arg === undefined ? ' ' : arg)
'join': (v: any[], arg: string) => v.join(arg === undefined ? ' ' : arg), export const last = (v: any) => isArray(v) ? arrayLast(v) : ''
'last': (v: any) => isArray(v) ? last(v) : '', export const first = (v: any) => isArray(v) ? v[0] : ''
'first': (v: any) => isArray(v) ? v[0] : '', export const reverse = (v: any[]) => [...v].reverse()
'map': map, export const sort = <T>(v: T[], arg: (lhs: T, rhs: T) => number) => v.sort(arg)
'reverse': (v: any[]) => [...v].reverse(), export const size = (v: string | any[]) => (v && v.length) || 0
'sort': <T>(v: T[], arg: (lhs: T, rhs: T) => number) => v.sort(arg),
'size': (v: string | any[]) => (v && v.length) || 0,
'concat': concat,
'slice': slice,
'uniq': uniq,
'where': where
}
function map<T1, T2> (arr: {[key: string]: T1}[], arg: string): T1[] { export function map<T1, T2> (arr: {[key: string]: T1}[], arg: string): T1[] {
return arr.map(v => v[arg]) return arr.map(v => v[arg])
} }
function concat<T1, T2> (v: T1[], arg: T2[] | T2): (T1 | T2)[] { export function concat<T1, T2> (v: T1[], arg: T2[] | T2): (T1 | T2)[] {
return Array.prototype.concat.call(v, arg) return Array.prototype.concat.call(v, arg)
} }
function slice<T> (v: T[], begin: number, length = 1): T[] { export function slice<T> (v: T[], begin: number, length = 1): T[] {
begin = begin < 0 ? v.length + begin : begin begin = begin < 0 ? v.length + begin : begin
return v.slice(begin, begin + length) return v.slice(begin, begin + length)
} }
function where<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): T[] { export function where<T extends object> (this: FilterImpl, arr: T[], property: string, expected?: any): T[] {
return arr.filter(obj => { return arr.filter(obj => {
const value = this.context.getFromScope(obj, property.split('.')) const value = this.context.getFromScope(obj, property.split('.'))
return expected === undefined ? isTruthy(value) : value === expected return expected === undefined ? isTruthy(value) : value === expected
}) })
} }
function uniq<T> (arr: T[]): T[] { export function uniq<T> (arr: T[]): T[] {
const u = {} const u = {}
return (arr || []).filter(val => { return (arr || []).filter(val => {
if (u.hasOwnProperty(String(val))) return false if (u.hasOwnProperty(String(val))) return false
+9 -11
View File
@@ -1,18 +1,16 @@
import strftime from '../../util/strftime' import strftime from '../../util/strftime'
import { isString, isNumber } from '../../util/underscore' import { isString, isNumber } from '../../util/underscore'
export default { export function date (v: string | Date, arg: string) {
'date': (v: string | Date, arg: string) => { let date = v
let date = v if (v === 'now' || v === 'today') {
if (v === 'now' || v === 'today') { date = new Date()
date = new Date() } else if (isNumber(v)) {
} else if (isNumber(v)) { date = new Date(v * 1000)
date = new Date(v * 1000) } else if (isString(v)) {
} else if (isString(v)) { date = /^\d+$/.test(v) ? new Date(+v * 1000) : new Date(v)
date = /^\d+$/.test(v) ? new Date(+v * 1000) : new Date(v)
}
return isValidDate(date) ? strftime(date, arg) : v
} }
return isValidDate(date) ? strftime(date, arg) : v
} }
function isValidDate (date: any): date is Date { function isValidDate (date: any): date is Date {
+11 -6
View File
@@ -15,7 +15,7 @@ const unescapeMap = {
'&#39;': "'" '&#39;': "'"
} }
function escape (str: string) { export function escape (str: string) {
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m]) return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
} }
@@ -23,9 +23,14 @@ function unescape (str: string) {
return String(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m]) return String(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
} }
export default { export function escapeOnce (str: string) {
'escape': escape, return escape(unescape(str))
'escape_once': (str: string) => escape(unescape(str)), }
'newline_to_br': (v: string) => v.replace(/\n/g, '<br />'),
'strip_html': (v: string) => v.replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, '') export function newlineToBr (v: string) {
return v.replace(/\n/g, '<br />')
}
export function stripHtml (v: string) {
return v.replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, '')
} }
+7 -9
View File
@@ -1,9 +1,7 @@
import html from './html' export * from './html'
import str from './string' export * from './math'
import math from './math' export * from './url'
import url from './url' export * from './array'
import array from './array' export * from './date'
import date from './date' export * from './object'
import obj from './object' export * from './string'
export default { ...html, ...str, ...math, ...url, ...date, ...obj, ...array }
+18 -17
View File
@@ -1,24 +1,25 @@
import { caseInsensitiveCompare } from '../../util/underscore' import { caseInsensitiveCompare } from '../../util/underscore'
export default { export const abs = Math.abs
'abs': (v: number) => Math.abs(v), export const atLeast = Math.max
'at_least': (v: number, n: number) => Math.max(v, n), export const atMost = Math.min
'at_most': (v: number, n: number) => Math.min(v, n), export const ceil = Math.ceil
'ceil': (v: number) => Math.ceil(v), export const dividedBy = (v: number, arg: number) => v / arg
'divided_by': (v: number, arg: number) => v / arg, export const floor = Math.floor
'floor': (v: number) => Math.floor(v), export const minus = (v: number, arg: number) => v - arg
'minus': (v: number, arg: number) => v - arg, export const modulo = (v: number, arg: number) => v % arg
'modulo': (v: number, arg: number) => v % arg, export const times = (v: number, arg: number) => v * arg
'round': (v: number, arg = 0) => {
const amp = Math.pow(10, arg) export function round (v: number, arg = 0) {
return Math.round(v * amp) / amp const amp = Math.pow(10, arg)
}, return Math.round(v * amp) / amp
'plus': (v: number, arg: number) => Number(v) + Number(arg),
'sort_natural': sortNatural,
'times': (v: number, arg: number) => v * arg
} }
function sortNatural (input: any[], property?: string) { export function plus (v: number, arg: number) {
return Number(v) + Number(arg)
}
export function sortNatural (input: any[], property?: string) {
if (!input || !input.sort) return [] if (!input || !input.sort) return []
if (property !== undefined) { if (property !== undefined) {
return [...input].sort( return [...input].sort(
+5 -7
View File
@@ -1,11 +1,9 @@
import { isFalsy } from '../../render/boolean' import { isFalsy } from '../../render/boolean'
import { toValue } from '../../util/underscore' import { toValue } from '../../util/underscore'
export default { export function Default<T1, T2> (v: string | T1, arg: T2): string | T1 | T2 {
'default': function<T1, T2> (v: string | T1, arg: T2): string | T1 | T2 { return isFalsy(toValue(v)) || v === '' ? arg : v
return isFalsy(toValue(v)) || v === '' ? arg : v }
}, export function json (v: any) {
'json': function (v: any) { return JSON.stringify(v)
return JSON.stringify(v)
}
} }
+50 -22
View File
@@ -4,46 +4,74 @@
* * prefer stringify() to String() since `undefined`, `null` should eval '' * * prefer stringify() to String() since `undefined`, `null` should eval ''
*/ */
import { stringify } from '../../util/underscore' import { stringify } from '../../util/underscore'
import { assert } from '../../util/assert'
export default { export function append (v: string, arg: string) {
'append': (v: string, arg: string) => stringify(v) + stringify(arg), assert(arg !== undefined, () => 'append expect 2 arguments')
'prepend': (v: string, arg: string) => stringify(arg) + stringify(v), return stringify(v) + stringify(arg)
'capitalize': capitalize,
'lstrip': (v: string) => stringify(v).replace(/^\s+/, ''),
'downcase': (v: string) => stringify(v).toLowerCase(),
'upcase': (str: string) => stringify(str).toUpperCase(),
'remove': (v: string, arg: string) => stringify(v).split(arg).join(''),
'remove_first': (v: string, l: string) => stringify(v).replace(l, ''),
'replace': replace,
'replace_first': replaceFirst,
'rstrip': (str: string) => stringify(str).replace(/\s+$/, ''),
'split': (v: string, arg: string) => stringify(v).split(arg),
'strip': (v: string) => stringify(v).trim(),
'strip_newlines': (v: string) => stringify(v).replace(/\n/g, ''),
'truncate': truncate,
'truncatewords': truncateWords
} }
function capitalize (str: string) { export function prepend (v: string, arg: string) {
assert(arg !== undefined, () => 'prepend expect 2 arguments')
return stringify(arg) + stringify(v)
}
export function lstrip (v: string) {
return stringify(v).replace(/^\s+/, '')
}
export function downcase (v: string) {
return stringify(v).toLowerCase()
}
export function upcase (str: string) {
return stringify(str).toUpperCase()
}
export function remove (v: string, arg: string) {
return stringify(v).split(arg).join('')
}
export function removeFirst (v: string, l: string) {
return stringify(v).replace(l, '')
}
export function rstrip (str: string) {
return stringify(str).replace(/\s+$/, '')
}
export function split (v: string, arg: string) {
return stringify(v).split(arg)
}
export function strip (v: string) {
return stringify(v).trim()
}
export function stripNewlines (v: string) {
return stringify(v).replace(/\n/g, '')
}
export function capitalize (str: string) {
str = stringify(str) str = stringify(str)
return str.charAt(0).toUpperCase() + str.slice(1) return str.charAt(0).toUpperCase() + str.slice(1)
} }
function replace (v: string, pattern: string, replacement: string) { export function replace (v: string, pattern: string, replacement: string) {
return stringify(v).split(pattern).join(replacement) return stringify(v).split(pattern).join(replacement)
} }
function replaceFirst (v: string, arg1: string, arg2: string) { export function replaceFirst (v: string, arg1: string, arg2: string) {
return stringify(v).replace(arg1, arg2) return stringify(v).replace(arg1, arg2)
} }
function truncate (v: string, l = 50, o = '...') { export function truncate (v: string, l = 50, o = '...') {
v = stringify(v) v = stringify(v)
if (v.length <= l) return v if (v.length <= l) return v
return v.substr(0, l - o.length) + o return v.substr(0, l - o.length) + o
} }
function truncateWords (v: string, l = 15, o = '...') { export function truncatewords (v: string, l = 15, o = '...') {
const arr = v.split(/\s+/) const arr = v.split(/\s+/)
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
+2 -4
View File
@@ -1,4 +1,2 @@
export default { export const urlDecode = (x: string) => x.split('+').map(decodeURIComponent).join(' ')
'url_decode': (x: string) => x.split('+').map(decodeURIComponent).join(' '), export const urlEncode = (x: string) => x.split(' ').map(encodeURIComponent).join('+')
'url_encode': (x: string) => x.split(' ').map(encodeURIComponent).join('+')
}
+4 -4
View File
@@ -1,6 +1,6 @@
import { Context } from './context/context' import { Context } from './context/context'
import * as fs from './fs/node' import * as fs from './fs/node'
import * as _ from './util/underscore' import { forOwn, snakeCase } from './util/underscore'
import { Template } from './template/template' import { Template } from './template/template'
import { Tokenizer } from './parser/tokenizer' import { Tokenizer } from './parser/tokenizer'
import { Render } from './render/render' import { Render } from './render/render'
@@ -8,7 +8,7 @@ import Parser from './parser/parser'
import { TagImplOptions } from './template/tag/tag-impl-options' import { TagImplOptions } from './template/tag/tag-impl-options'
import { Value } from './template/value' import { Value } from './template/value'
import builtinTags from './builtin/tags' import builtinTags from './builtin/tags'
import builtinFilters from './builtin/filters' import * as builtinFilters from './builtin/filters'
import { TagMap } from './template/tag/tag-map' import { TagMap } from './template/tag/tag-map'
import { FilterMap } from './template/filter/filter-map' import { FilterMap } from './template/filter/filter-map'
import { LiquidOptions, normalizeStringArray, NormalizedFullOptions, applyDefault, normalize } from './liquid-options' import { LiquidOptions, normalizeStringArray, NormalizedFullOptions, applyDefault, normalize } from './liquid-options'
@@ -34,8 +34,8 @@ export class Liquid {
this.filters = new FilterMap(this.options.strictFilters) this.filters = new FilterMap(this.options.strictFilters)
this.tags = new TagMap() this.tags = new TagMap()
_.forOwn(builtinTags, (conf, name) => this.registerTag(name, conf)) forOwn(builtinTags, (conf, name) => this.registerTag(snakeCase(name), conf))
_.forOwn(builtinFilters, (handler, name) => this.registerFilter(name, handler)) forOwn(builtinFilters, (handler, name) => this.registerFilter(snakeCase(name), handler))
} }
public parse (html: string, filepath?: string): Template[] { public parse (html: string, filepath?: string): Template[] {
const tokenizer = new Tokenizer(html, filepath) const tokenizer = new Tokenizer(html, filepath)
+7
View File
@@ -120,6 +120,13 @@ export function identify<T> (val: T): T {
return val return val
} }
export function snakeCase (str: string) {
return str.replace(
/(\w?)([A-Z])/g,
(_, a, b) => (a ? a + '_' : '') + b.toLowerCase()
)
}
export function changeCase (str: string): string { export function changeCase (str: string): string {
const hasLowerCase = [...str].some(ch => ch >= 'a' && ch <= 'z') const hasLowerCase = [...str].some(ch => ch >= 'a' && ch <= 'z')
return hasLowerCase ? str.toUpperCase() : str.toLowerCase() return hasLowerCase ? str.toUpperCase() : str.toLowerCase()
+13
View File
@@ -22,6 +22,19 @@ describe('filters/html', function () {
it('should not escape twice', it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3')) () => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
}) })
describe('newline_to_br', function () {
it('should support string_with_newlines', function () {
const src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}'
const dst = '<br />' +
'Hello<br />' +
'there<br />'
return test(src, dst)
})
})
describe('strip_html', function () { describe('strip_html', function () {
it('should strip all tags', function () { it('should strip all tags', function () {
return test('{{ "Have <em>you</em> read <cite><a href=&quot;https://en.wikipedia.org/wiki/Ulysses_(novel)&quot;>Ulysses</a></cite>?" | strip_html }}', return test('{{ "Have <em>you</em> read <cite><a href=&quot;https://en.wikipedia.org/wiki/Ulysses_(novel)&quot;>Ulysses</a></cite>?" | strip_html }}',
+16 -14
View File
@@ -1,6 +1,9 @@
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, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
use(chaiAsPromised)
describe('filters/string', function () { describe('filters/string', function () {
let liquid: Liquid let liquid: Liquid
@@ -11,14 +14,24 @@ describe('filters/string', function () {
it('should return "-3abc" for -3, "abc"', it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc')) () => test('{{ -3 | append: "abc" }}', '-3abc'))
it('should return "abar" for "a", foo', () => test('{{ "a" | append: foo }}', 'abar')) it('should return "abar" for "a", foo', () => test('{{ "a" | append: foo }}', 'abar'))
it('should return "abc" for "abc", undefined', () => test('{{ "abc" | append: undefinedVar }}', 'abc')) it('should throw if second argument undefined', () => {
return expect(test('{{ "abc" | append: undefinedVar }}', 'abc')).to.be.rejectedWith(/2 arguments/)
})
it('should throw if second argument not set', () => {
return expect(test('{{ "abc" | append }}', 'abc')).to.be.rejectedWith(/2 arguments/)
})
it('should return "abcfalse" for "abc", false', () => test('{{ "abc" | append: false }}', 'abcfalse')) it('should return "abcfalse" for "abc", false', () => test('{{ "abc" | append: false }}', 'abcfalse'))
}) })
describe('prepend', function () { describe('prepend', function () {
it('should return "-3abc" for -3, "abc"', it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | prepend: "abc" }}', 'abc-3')) () => test('{{ -3 | prepend: "abc" }}', 'abc-3'))
it('should return "abar" for "a", foo', () => test('{{ "a" | prepend: foo }}', 'bara')) it('should return "abar" for "a", foo', () => test('{{ "a" | prepend: foo }}', 'bara'))
it('should return "abc" for "abc", undefined', () => test('{{ "abc" | prepend: undefinedVar }}', 'abc')) it('should throw if second argument undefined', () => {
return expect(test('{{ "abc" | prepend: undefinedVar }}', 'abc')).to.be.rejectedWith(/2 arguments/)
})
it('should throw if second argument not set', () => {
return expect(test('{{ "abc" | prepend }}', 'abc')).to.be.rejectedWith(/2 arguments/)
})
it('should return "falseabc" for "abc", false', () => test('{{ "abc" | prepend: false }}', 'falseabc')) it('should return "falseabc" for "abc", false', () => test('{{ "abc" | prepend: false }}', 'falseabc'))
}) })
describe('capitalize', function () { describe('capitalize', function () {
@@ -105,17 +118,6 @@ describe('filters/string', function () {
const 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! ')
}) })
it('should support string_with_newlines', function () {
const src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}'
const dst = '<br />' +
'Hello<br />' +
'there<br />'
return test(src, dst)
})
it('should support prepend', function () { it('should support prepend', function () {
return test('{% assign url = "liquidmarkup.com" %}' + return test('{% assign url = "liquidmarkup.com" %}' +
'{{ "/index.html" | prepend: url }}', '{{ "/index.html" | prepend: url }}',
+9
View File
@@ -7,6 +7,15 @@ const expect = chai.expect
chai.use(sinonChai) chai.use(sinonChai)
describe('util/underscore', function () { describe('util/underscore', function () {
describe('.camel2snake()', function () {
it('should convert camelCase to snakeCase', function () {
expect(_.snakeCase('fooBarCoo')).to.equal('foo_bar_coo')
})
it('should convert empty string to empty string', function () {
expect(_.snakeCase('')).to.equal('')
})
})
describe('.isString()', function () { describe('.isString()', function () {
it('should return true for literal string', function () { it('should return true for literal string', function () {
expect(_.isString('foo')).to.be.true expect(_.isString('foo')).to.be.true