Skip to content

Commit

Permalink
fix(utils): use empty string for reference error in interpolation
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jun 21, 2021
1 parent 90d9dc8 commit 0426a86
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/koishi-utils/src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,17 @@ export function capitalize(source: string) {

// eslint-disable-next-line no-new-func
export const interpolate = new Function('template', 'context', `
with (context) {
return template.replace(/\\{\\{[\\s\\S]+?\\}\\}/g, (sub) => {
const expr = sub.substring(2, sub.length - 2)
return eval(expr)
try {
with (context) {
return eval(expr)
}
} catch {
return ''
}
})
}`) as ((template: string, context: object) => string)
`) as ((template: string, context: object) => string)

export function escapeRegExp(source: string) {
return source
Expand Down
1 change: 1 addition & 0 deletions packages/koishi-utils/tests/string.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe('String Manipulations', () => {

it('interpolate', () => {
expect(interpolate('foo{{ bar }}foo', { bar: 'baz' })).to.equal('foobazfoo')
expect(interpolate('foo{{ bar }}foo', {})).to.equal('foofoo')
})

it('escape regexp', () => {
Expand Down

0 comments on commit 0426a86

Please sign in to comment.