vendor: amis 6.13.0 base (fork root)
This commit is contained in:
3
packages/amis-formula/.gitignore
vendored
Normal file
3
packages/amis-formula/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/coverage
|
||||
/lib
|
||||
/esm
|
||||
21
packages/amis-formula/LICENSE
Normal file
21
packages/amis-formula/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 百度智能云爱速搭
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
5
packages/amis-formula/README.md
Normal file
5
packages/amis-formula/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# amis-formula
|
||||
|
||||
负责 amis 里面的表达式、公式及模板的实现
|
||||
|
||||
属于 [amis](https://github.com/baidu/amis) 子项目
|
||||
@@ -0,0 +1,56 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`lexer:filter 1`] = `
|
||||
[
|
||||
"<Raw> $abc is ",
|
||||
"<OpenScript> \${",
|
||||
"<Identifier> abc",
|
||||
"<OpenFilter> |",
|
||||
"<Char> ",
|
||||
"<Identifier> date",
|
||||
"<Punctuator> :",
|
||||
"<Char> ",
|
||||
"<Identifier> YYYY",
|
||||
"<Punctuator> -",
|
||||
"<Identifier> MM",
|
||||
"<Punctuator> -",
|
||||
"<Identifier> DD",
|
||||
"<Char> ",
|
||||
"<Identifier> HH:mm:ss",
|
||||
"<CloseScript> }",
|
||||
"<EOF> undefined",
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`lexer:filter 2`] = `
|
||||
[
|
||||
"<Raw> $abc is ",
|
||||
"<OpenScript> \${",
|
||||
"<Identifier> abc",
|
||||
"<OpenFilter> |",
|
||||
"<Char> ",
|
||||
"<Identifier> isTrue",
|
||||
"<Char> ",
|
||||
"<Punctuator> :",
|
||||
"<Char> ",
|
||||
"<Identifier> trueValue",
|
||||
"<Char> ",
|
||||
"<Punctuator> :",
|
||||
"<Char> ",
|
||||
"<Identifier> falseValue",
|
||||
"<CloseScript> }",
|
||||
"<EOF> undefined",
|
||||
]
|
||||
`;
|
||||
|
||||
exports[`lexer:simple 1`] = `
|
||||
[
|
||||
"<Raw> expression result is ",
|
||||
"<OpenScript> \${",
|
||||
"<Identifier> a",
|
||||
"<Punctuator> +",
|
||||
"<Identifier> b",
|
||||
"<CloseScript> }",
|
||||
"<EOF> undefined",
|
||||
]
|
||||
`;
|
||||
2325
packages/amis-formula/__tests__/__snapshots__/parser.test.ts.snap
Normal file
2325
packages/amis-formula/__tests__/__snapshots__/parser.test.ts.snap
Normal file
File diff suppressed because it is too large
Load Diff
629
packages/amis-formula/__tests__/async-evalute.test.ts
Normal file
629
packages/amis-formula/__tests__/async-evalute.test.ts
Normal file
@@ -0,0 +1,629 @@
|
||||
import {evaluateForAsync, parse} from '../src';
|
||||
|
||||
test('evalute:simple', async () => {
|
||||
expect(
|
||||
await evaluateForAsync('a is ${a}', {
|
||||
a: 123
|
||||
})
|
||||
).toBe('a is 123');
|
||||
});
|
||||
|
||||
test('evalute:filter', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${a | abc}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
abc(input: any) {
|
||||
return `${input}456`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123456');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${a | concat:233}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, arg: string) {
|
||||
return `${input}${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123233');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${concat(a, a)}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, arg: string) {
|
||||
return `${input}${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123123');
|
||||
});
|
||||
|
||||
test('evalute:filter2', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${[1, 2, 3] | concat:4 | join}',
|
||||
{},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,4');
|
||||
});
|
||||
|
||||
test('evalute:filter3', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${[1, 2, 3] | concat:"4" | join}',
|
||||
{},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,4');
|
||||
});
|
||||
|
||||
test('evalute:filter4', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'a is ${[1, 2, 3] | concat:${a + 3} | join}',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,7');
|
||||
});
|
||||
|
||||
test('evalute:oldVariable', async () => {
|
||||
expect(
|
||||
await evaluateForAsync('a is $a', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('a is 4');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('b is $b', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('b is ');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('a.b is $a.b', {
|
||||
a: {
|
||||
b: 233
|
||||
}
|
||||
})
|
||||
).toBe('a.b is 233');
|
||||
});
|
||||
|
||||
test('evalute:ariable2', async () => {
|
||||
expect(
|
||||
await evaluateForAsync('a is $$', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('a is [object Object]');
|
||||
});
|
||||
|
||||
test('evalute:ariable3', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'$$',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toMatchObject({
|
||||
a: 4
|
||||
});
|
||||
});
|
||||
|
||||
test('evalute:object-variable', async () => {
|
||||
const data = {
|
||||
key: 'x',
|
||||
obj: {
|
||||
x: 1,
|
||||
y: 2
|
||||
}
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('a is ${obj.x}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj[x]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj[`x`]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj["x"]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj[key]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj[`${key}`]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${obj[${key}]}', data)).toBe('a is 1');
|
||||
});
|
||||
|
||||
test('evalute:literal-variable', async () => {
|
||||
const data = {
|
||||
key: 'x',
|
||||
index: 0,
|
||||
obj: {
|
||||
x: 1,
|
||||
y: 2
|
||||
}
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('a is ${({x: 1})["x"]}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${({x: 1}).x}', data)).toBe('a is 1');
|
||||
expect(await evaluateForAsync('a is ${(["a", "b"])[index]}', data)).toBe(
|
||||
'a is a'
|
||||
);
|
||||
expect(await evaluateForAsync('a is ${(["a", "b"])[1]}', data)).toBe(
|
||||
'a is b'
|
||||
);
|
||||
expect(await evaluateForAsync('a is ${(["a", "b"]).0}', data)).toBe('a is a');
|
||||
});
|
||||
|
||||
test('evalute:tempalte', async () => {
|
||||
const data = {
|
||||
key: 'x'
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('abc${`11${3}22`}xyz', data)).toBe(
|
||||
'abc11322xyz'
|
||||
);
|
||||
expect(await evaluateForAsync('abc${`${3}22`}xyz', data)).toBe('abc322xyz');
|
||||
expect(await evaluateForAsync('abc${`11${3}`}xyz', data)).toBe('abc113xyz');
|
||||
expect(await evaluateForAsync('abc${`${3}`}xyz', data)).toBe('abc3xyz');
|
||||
expect(await evaluateForAsync('abc${`${key}`}xyz', data)).toBe('abcxxyz');
|
||||
});
|
||||
|
||||
test('evalute:literal', async () => {
|
||||
const data = {
|
||||
dynamicKey: 'alpha'
|
||||
};
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${{a: 1, 0: 2, "3": 3}}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${{a: 1, 0: 2, "3": 3, [`4`]: 4}}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3,
|
||||
4: 4
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${{a: 1, 0: 2, "3": 3, [`${dynamicKey}233`]: 4}}',
|
||||
data,
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3,
|
||||
alpha233: 4
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${[1, 2, `2${dynamicKey}2`, {a: 1, 0: 2, [`2`]: "3"}]}',
|
||||
data,
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toMatchObject([1, 2, `2alpha2`, {a: 1, 0: 2, [`2`]: '3'}]);
|
||||
});
|
||||
|
||||
test('evalute:variableName', async () => {
|
||||
const data = {
|
||||
'a_b': 'c',
|
||||
'222': 10222,
|
||||
'222_221': 233,
|
||||
'222_abcde': 'abcde',
|
||||
'222-221': 333
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('${a_b}', data)).toBe('c');
|
||||
expect(await evaluateForAsync('${222}', data)).toBe(222);
|
||||
expect(await evaluateForAsync('${222_221}', data)).toBe('233');
|
||||
expect(await evaluateForAsync('${222-221}', data)).toBe(1);
|
||||
expect(await evaluateForAsync('${222_abcde}', data)).toBe('abcde');
|
||||
expect(
|
||||
await evaluateForAsync('${&["222-221"]}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toBe(333);
|
||||
expect(
|
||||
await evaluateForAsync('222', data, {
|
||||
variableMode: true
|
||||
})
|
||||
).toBe(10222);
|
||||
});
|
||||
|
||||
test('evalute:3-1', async () => {
|
||||
const data = {};
|
||||
|
||||
expect(await evaluateForAsync('${3-1}', data)).toBe(2);
|
||||
expect(await evaluateForAsync('${-1 + 2.5 + 3}', data)).toBe(4.5);
|
||||
expect(await evaluateForAsync('${-1 + -1}', data)).toBe(-2);
|
||||
expect(await evaluateForAsync('${3 * -1}', data)).toBe(-3);
|
||||
|
||||
expect(await evaluateForAsync('${3 + +1}', data)).toBe(4);
|
||||
});
|
||||
|
||||
test('evalate:0.1+0.2', async () => {
|
||||
expect(await evaluateForAsync('${0.1 + 0.2}', {})).toBe(0.3);
|
||||
});
|
||||
|
||||
test('evalute:variable:com.xxx.xx', async () => {
|
||||
const data = {
|
||||
'com.xxx.xx': 'abc',
|
||||
'com xxx%xx': 'cde',
|
||||
'com[xxx]': 'eee'
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('${com\\.xxx\\.xx}', data)).toBe('abc');
|
||||
expect(await evaluateForAsync('${com\\ xxx\\%xx}', data)).toBe('cde');
|
||||
expect(await evaluateForAsync('${com\\[xxx\\]}', data)).toBe('eee');
|
||||
});
|
||||
|
||||
test('evalute:anonymous:function', async () => {
|
||||
const data = {
|
||||
arr: [1, 2, 3],
|
||||
arr2: [
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
{
|
||||
a: 2
|
||||
},
|
||||
{
|
||||
a: 3
|
||||
}
|
||||
],
|
||||
outter: 4
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('${() => 233}', data)).toMatchObject({
|
||||
args: [],
|
||||
return: {type: 'literal', value: 233},
|
||||
type: 'anonymous_function'
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYMAP(arr, () => 1)}', data)
|
||||
).toMatchObject([1, 1, 1]);
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYMAP(arr, item => item)}', data)
|
||||
).toMatchObject([1, 2, 3]);
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYMAP(arr, item => item * 2)}', data)
|
||||
).toMatchObject([2, 4, 6]);
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYMAP(arr2, (item, index) => `a${item.a}${index}`)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject(['a10', 'a21', 'a32']);
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYMAP(arr2, (item, index) => `a${item.a}${index}${outter}`)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject(['a104', 'a214', 'a324']);
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYMAP(arr2, (item, index) => {x: item.a, index: index})}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([
|
||||
{
|
||||
x: 1,
|
||||
index: 0
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
index: 1
|
||||
},
|
||||
{
|
||||
x: 3,
|
||||
index: 2
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:anonymous:function2', async () => {
|
||||
const data = {
|
||||
arr: [1, 2, 3],
|
||||
arr2: [
|
||||
{
|
||||
x: 1,
|
||||
y: [
|
||||
{
|
||||
z: 1
|
||||
},
|
||||
{
|
||||
z: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
y: [
|
||||
{
|
||||
z: 2
|
||||
},
|
||||
{
|
||||
z: 2
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYMAP(ARRAYMAP(arr, item => item * 2), item => item + 2)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([4, 6, 8]);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYMAP(arr2, item => ARRAYMAP(item.y, i => i.z))}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([
|
||||
[1, 1],
|
||||
[2, 2]
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:array:func', async () => {
|
||||
const data = {
|
||||
arr1: [0, 1, false, 2, '', 3],
|
||||
arr2: ['a', 'b', 'c'],
|
||||
arr3: [1, 2, 3],
|
||||
arr4: [2, 4, 6],
|
||||
arr5: [
|
||||
{
|
||||
id: 1.1
|
||||
},
|
||||
{
|
||||
id: 2.2
|
||||
},
|
||||
{
|
||||
id: 1.1,
|
||||
name: 1.3
|
||||
}
|
||||
],
|
||||
obj1: {
|
||||
p1: 'name',
|
||||
p2: 'age',
|
||||
p3: 'obj',
|
||||
p4: [
|
||||
{
|
||||
p41: 'Tom',
|
||||
p42: 'Jerry'
|
||||
},
|
||||
{
|
||||
p41: 'baidu',
|
||||
p42: 'amis'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
expect(await evaluateForAsync('${COMPACT(arr1)}', data)).toMatchObject([
|
||||
1, 2, 3
|
||||
]);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync("${COMPACT([0, 1, false, 2, '', 3])}", data)
|
||||
).toMatchObject([1, 2, 3]);
|
||||
|
||||
expect(await evaluateForAsync('${JOIN(arr2, "~")}', data)).toMatch('a~b~c');
|
||||
|
||||
expect(await evaluateForAsync('${SUM(arr3)}', data)).toBe(6);
|
||||
|
||||
expect(await evaluateForAsync('${AVG(arr4)}', data)).toBe(4);
|
||||
|
||||
expect(await evaluateForAsync('${MIN(arr4)}', data)).toBe(2);
|
||||
|
||||
expect(await evaluateForAsync('${MAX(arr4)}', data)).toBe(6);
|
||||
|
||||
expect(await evaluateForAsync('${CONCAT(arr3, arr4)}', data)).toMatchObject([
|
||||
1, 2, 3, 2, 4, 6
|
||||
]);
|
||||
|
||||
expect(await evaluateForAsync('${CONCAT(arr, arr4)}', data)).toMatchObject([
|
||||
2, 4, 6
|
||||
]);
|
||||
|
||||
expect(await evaluateForAsync('${UNIQ(arr5)}', data)).toMatchObject(
|
||||
data.arr5
|
||||
);
|
||||
|
||||
expect(await evaluateForAsync('${UNIQ(arr5, "id")}', data)).toMatchObject([
|
||||
{id: 1.1},
|
||||
{id: 2.2}
|
||||
]);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYFILTER(arr1, item => item)}', data)
|
||||
).toMatchObject([1, 2, 3]);
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYFILTER(arr1, item => item && item >=2)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([2, 3]);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYFINDINDEX(arr3, item => item === 2)}', data)
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYFINDINDEX(arr3, item => item !== 1)}', data)
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYFIND(arr5, item => item.name === 1.3)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject({
|
||||
id: 1.1,
|
||||
name: 1.3
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync('${ARRAYFIND(arr5, item => item.id !== 1.1)}', data)
|
||||
).toMatchObject({
|
||||
id: 2.2
|
||||
});
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYSOME(arr5, item => item.name === 1.3)}',
|
||||
data
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${ARRAYEVERY(arr5, item => item.name === 1.3)}',
|
||||
data
|
||||
)
|
||||
).toBe(false);
|
||||
|
||||
expect(await evaluateForAsync('${ARRAYINCLUDES(arr1, false)}', data)).toBe(
|
||||
true
|
||||
);
|
||||
|
||||
expect(await evaluateForAsync('${GET(arr1, 2)}', data)).toBe(false);
|
||||
expect(await evaluateForAsync('${GET(arr1, 6, "not-found")}', data)).toBe(
|
||||
'not-found'
|
||||
);
|
||||
expect(await evaluateForAsync('${GET(arr5, "[2].name")}', data)).toBe(1.3);
|
||||
expect(await evaluateForAsync('${GET(arr5, "2.name")}', data)).toBe(1.3);
|
||||
expect(await evaluateForAsync('${GET(obj1, "p2")}', data)).toBe('age');
|
||||
expect(await evaluateForAsync('${GET(obj1, "p4.1.p42")}', data)).toBe('amis');
|
||||
expect(await evaluateForAsync('${GET(obj1, "p4[1].p42")}', data)).toBe(
|
||||
'amis'
|
||||
);
|
||||
|
||||
expect(await evaluateForAsync('${ENCODEJSON(obj1)}', data)).toBe(
|
||||
JSON.stringify(data.obj1)
|
||||
);
|
||||
expect(
|
||||
await evaluateForAsync('${DECODEJSON("{\\"name\\":\\"amis\\"}")}', data)
|
||||
).toMatchObject(JSON.parse('{"name":"amis"}'));
|
||||
});
|
||||
|
||||
test('evalute:ISTYPE', async () => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: 'string',
|
||||
c: null,
|
||||
d: undefined,
|
||||
e: [1, 2],
|
||||
f: {a: 1, b: 2},
|
||||
g: new Date()
|
||||
};
|
||||
expect(await evaluateForAsync('${ISTYPE(a, "number")}', data)).toBe(true);
|
||||
expect(await evaluateForAsync('${ISTYPE(b, "number")}', data)).toBe(false);
|
||||
expect(await evaluateForAsync('${ISTYPE(b, "string")}', data)).toBe(true);
|
||||
expect(await evaluateForAsync('${ISTYPE(c, "nil")}', data)).toBe(true);
|
||||
expect(await evaluateForAsync('${ISTYPE(d, "nil")}', data)).toBe(true);
|
||||
expect(await evaluateForAsync('${ISTYPE(e, "array")}', data)).toBe(true);
|
||||
expect(await evaluateForAsync('${ISTYPE(f, "array")}', data)).toBe(false);
|
||||
expect(await evaluateForAsync('${ISTYPE(f, "plain-object")}', data)).toBe(
|
||||
true
|
||||
);
|
||||
expect(await evaluateForAsync('${ISTYPE(g, "date")}', data)).toBe(true);
|
||||
});
|
||||
|
||||
test('async-evalute:namespace', async () => {
|
||||
localStorage.setItem('a', '1');
|
||||
localStorage.setItem('b', '2');
|
||||
localStorage.setItem('c', '{"a": 1, "b": 2, "c": {"d": 4}}');
|
||||
localStorage.setItem('key', 'c');
|
||||
localStorage.setItem('spec-var-name', 'you are right');
|
||||
|
||||
expect(await evaluateForAsync('${ls: a}', {})).toBe(1);
|
||||
expect(await evaluateForAsync('${ls: b}', {})).toBe(2);
|
||||
expect(await evaluateForAsync('${ls: c}', {})).toMatchObject({
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: {d: 4}
|
||||
});
|
||||
// 被认为是减操作
|
||||
expect(await evaluateForAsync('${ls: spec-var-name}', {})).toBe(0);
|
||||
expect(await evaluateForAsync('${ls: spec\\-var\\-name}', {})).toBe(
|
||||
'you are right'
|
||||
);
|
||||
expect(await evaluateForAsync('${ls: &["spec-var-name"]}', {})).toBe(
|
||||
'you are right'
|
||||
);
|
||||
expect(await evaluateForAsync('${ls: &["c"]["c"]}', {})).toMatchObject({
|
||||
d: 4
|
||||
});
|
||||
expect(await evaluateForAsync('${ls: &["c"][key]}', {})).toMatchObject({
|
||||
d: 4
|
||||
});
|
||||
});
|
||||
396
packages/amis-formula/__tests__/async-fomula.test.ts
Normal file
396
packages/amis-formula/__tests__/async-fomula.test.ts
Normal file
@@ -0,0 +1,396 @@
|
||||
import moment from 'moment';
|
||||
import {evaluateForAsync, registerFunction} from '../src';
|
||||
|
||||
const defaultContext = {
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: 3,
|
||||
d: 4,
|
||||
e: 5
|
||||
};
|
||||
|
||||
async function evalFormual(expression: string, data: any = defaultContext) {
|
||||
return evaluateForAsync(expression, data, {
|
||||
evalMode: true
|
||||
});
|
||||
}
|
||||
|
||||
test('formula:expression', async () => {
|
||||
expect(await evalFormual('a + 3')).toBe(4);
|
||||
expect(await evalFormual('b * 3')).toBe(6);
|
||||
expect(await evalFormual('b * 3 + 4')).toBe(10);
|
||||
expect(await evalFormual('c * (3 + 4)')).toBe(21);
|
||||
expect(await evalFormual('d / (a + 1)')).toBe(2);
|
||||
expect(await evalFormual('5 % 3')).toBe(2);
|
||||
expect(await evalFormual('3 | 4')).toBe(7);
|
||||
expect(await evalFormual('4 ^ 4')).toBe(0);
|
||||
expect(await evalFormual('4 ^ 4')).toBe(0);
|
||||
expect(await evalFormual('4 & 4')).toBe(4);
|
||||
expect(await evalFormual('4 & 3')).toBe(0);
|
||||
expect(await evalFormual('~-1')).toBe(0);
|
||||
expect(await evalFormual('!!1')).toBe(true);
|
||||
expect(await evalFormual('!!""')).toBe(false);
|
||||
expect(await evalFormual('1 || 2')).toBe(1);
|
||||
expect(await evalFormual('1 && 2')).toBe(2);
|
||||
expect(await evalFormual('1 && 2 || 3')).toBe(2);
|
||||
expect(await evalFormual('1 || 2 || 3')).toBe(1);
|
||||
expect(await evalFormual('1 || 2 && 3')).toBe(1);
|
||||
expect(await evalFormual('(1 || 2) && 3')).toBe(3);
|
||||
expect(await evalFormual('1 == "1"')).toBe(true);
|
||||
expect(await evalFormual('1 === "1"')).toBe(false);
|
||||
expect(await evalFormual('1 < 1')).toBe(false);
|
||||
expect(await evalFormual('1 <= 1')).toBe(true);
|
||||
expect(await evalFormual('1 > 1')).toBe(false);
|
||||
expect(await evalFormual('1 >= 1')).toBe(true);
|
||||
expect(await evalFormual('3 >> 1')).toBe(1);
|
||||
expect(await evalFormual('3 << 1')).toBe(6);
|
||||
expect(await evalFormual('10 ** 3')).toBe(1000);
|
||||
|
||||
expect(await evalFormual('10 ? 3 : 2')).toBe(3);
|
||||
expect(await evalFormual('0 ? 3 : 2')).toBe(2);
|
||||
});
|
||||
|
||||
test('formula:expression2', async () => {
|
||||
expect(await evalFormual('a[0]', {a: [1, 2, 3]})).toBe(1);
|
||||
expect(await evalFormual('a[b]', {a: [1, 2, 3], b: 1})).toBe(2);
|
||||
expect(await evalFormual('a[b - 1]', {a: [1, 2, 3], b: 1})).toBe(1);
|
||||
expect(await evalFormual('a[b ? 1 : 2]', {a: [1, 2, 3], b: 1})).toBe(2);
|
||||
expect(await evalFormual('a[c ? 1 : 2]', {a: [1, 2, 3], b: 1})).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:expression3', async () => {
|
||||
// expect(await evalFormual('${a} === "b"', {a: 'b'})).toBe(true);
|
||||
expect(await evalFormual('b === "b"')).toBe(false);
|
||||
// expect(await evalFormual('${a}', {a: 'b'})).toBe('b');
|
||||
|
||||
expect(await evalFormual('obj.x.a', {obj: {x: {a: 1}}})).toBe(1);
|
||||
expect(await evalFormual('obj.y.a', {obj: {x: {a: 1}}})).toBe(undefined);
|
||||
});
|
||||
|
||||
test('formula:if', async () => {
|
||||
expect(await evalFormual('IF(true, 2, 3)')).toBe(2);
|
||||
expect(await evalFormual('IF(false, 2, 3)')).toBe(3);
|
||||
expect(await evalFormual('IF(false, 2, IF(true, 3, 4))')).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:and', async () => {
|
||||
expect(!!(await evalFormual('AND(0, 1)'))).toBe(false);
|
||||
expect(!!(await evalFormual('AND(1, 1)'))).toBe(true);
|
||||
expect(!!(await evalFormual('AND(1, 1, 1, 0)'))).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:or', async () => {
|
||||
expect(!!(await evalFormual('OR(0, 1)'))).toBe(true);
|
||||
expect(!!(await evalFormual('OR(1, 1)'))).toBe(true);
|
||||
expect(!!(await evalFormual('OR(1, 1, 1, 0)'))).toBe(true);
|
||||
expect(!!(await evalFormual('OR(0, 0, 0, 0)'))).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:xor', async () => {
|
||||
expect(await evalFormual('XOR(0, 1)')).toBe(true);
|
||||
expect(await evalFormual('XOR(1, 0)')).toBe(true);
|
||||
expect(await evalFormual('XOR(1, 1)')).toBe(false);
|
||||
expect(await evalFormual('XOR(0, 0)')).toBe(false);
|
||||
|
||||
expect(await evalFormual('XOR(0, 0, 1)')).toBe(true);
|
||||
expect(await evalFormual('XOR(0, 1, 1)')).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:ifs', async () => {
|
||||
expect(!!(await evalFormual('IFS(0, 1, 2)'))).toBe(true);
|
||||
expect(!!(await evalFormual('IFS(0, 1, 2, 2, 3)'))).toBe(true);
|
||||
expect(!!(await evalFormual('IFS(0, 1, 0, 2, 0)'))).toBe(false);
|
||||
expect(await evalFormual('IFS(0, 1, 2, 2)')).toBe(2);
|
||||
expect(await evalFormual('IFS(0, 1, 0, 2)')).toBe(undefined);
|
||||
});
|
||||
|
||||
test('formula:math', async () => {
|
||||
expect(await evalFormual('ABS(1)')).toBe(1);
|
||||
expect(await evalFormual('ABS(-1)')).toBe(1);
|
||||
expect(await evalFormual('ABS(0)')).toBe(0);
|
||||
|
||||
expect(await evalFormual('MAX(1, -1, 2, 3, 5, -9)')).toBe(5);
|
||||
expect(await evalFormual('MIN(1, -1, 2, 3, 5, -9)')).toBe(-9);
|
||||
|
||||
expect(await evalFormual('MOD(3, 2)')).toBe(1);
|
||||
|
||||
expect(await evalFormual('PI()')).toBe(Math.PI);
|
||||
|
||||
expect(await evalFormual('ROUND(3.55)')).toBe(3.55);
|
||||
expect(await evalFormual('ROUND(3.45)')).toBe(3.45);
|
||||
|
||||
expect(await evalFormual('ROUND(3.456789, 2)')).toBe(3.46);
|
||||
expect(await evalFormual('CEIL(3.456789)')).toBe(3.46);
|
||||
expect(await evalFormual('FLOOR(3.456789)')).toBe(3.45);
|
||||
|
||||
expect(await evalFormual('SQRT(4)')).toBe(2);
|
||||
expect(await evalFormual('AVG(4, 6, 10, 10, 10)')).toBe(8);
|
||||
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/devsq-%E5%87%BD%E6%95%B0-8b739616-8376-4df5-8bd0-cfe0a6caf444
|
||||
expect(await evalFormual('DEVSQ(4,5,8,7,11,4,3)')).toBe(48);
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/avedev-%E5%87%BD%E6%95%B0-58fe8d65-2a84-4dc7-8052-f3f87b5c6639
|
||||
expect(await evalFormual('ROUND(AVEDEV(4,5,6,7,5,4,3), 2)')).toBe(1.02);
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/harmean-%E5%87%BD%E6%95%B0-5efd9184-fab5-42f9-b1d3-57883a1d3bc6
|
||||
expect(await evalFormual('ROUND(HARMEAN(4,5,8,7,11,4,3), 3)')).toBe(5.028);
|
||||
|
||||
expect(await evalFormual('LARGE([1,3,5,4,7,6], 3)')).toBe(5);
|
||||
expect(await evalFormual('LARGE([1,3,5,4,7,6], 1)')).toBe(7);
|
||||
|
||||
expect(await evalFormual('UPPERMONEY(7682.01)')).toBe('柒仟陆佰捌拾贰元壹分');
|
||||
expect(await evalFormual('UPPERMONEY(7682)')).toBe('柒仟陆佰捌拾贰元整');
|
||||
|
||||
expect(await evalFormual('POW(2,3)')).toBe(8);
|
||||
expect(await evalFormual('POW(4,2)')).toBe(16);
|
||||
|
||||
// 非数字类型转换是否正常?
|
||||
expect(await evalFormual('"3" + "3"')).toBe(6);
|
||||
expect(await evalFormual('"3" - "3"')).toBe(0);
|
||||
expect(await evalFormual('AVG(4, "6", "10", 10, 10)')).toBe(8);
|
||||
expect(await evalFormual('MAX(4, "6", "10", 2, 3)')).toBe(10);
|
||||
expect(await evalFormual('POW("2","3")')).toBe(8);
|
||||
expect(await evalFormual('POW("22.3",2)')).toBe(497.29);
|
||||
expect(await evalFormual('POW("word2",2)')).toBe('word2');
|
||||
|
||||
expect(await evalFormual('"a" + "b"')).toBe('ab');
|
||||
});
|
||||
|
||||
test('formula:text', async () => {
|
||||
expect(await evalFormual('LEFT("abcdefg", 2)')).toBe('ab');
|
||||
expect(await evalFormual('RIGHT("abcdefg", 2)')).toBe('fg');
|
||||
expect(await evalFormual('LENGTH("abcdefg")')).toBe(7);
|
||||
expect(await evalFormual('LEN("abcdefg")')).toBe(7);
|
||||
expect(await evalFormual('ISEMPTY("abcdefg")')).toBe(false);
|
||||
expect(await evalFormual('ISEMPTY("")')).toBe(true);
|
||||
expect(await evalFormual('CONCATENATE("a", "b", "c", "d")')).toBe('abcd');
|
||||
expect(await evalFormual('CHAR(97)')).toBe('a');
|
||||
expect(await evalFormual('LOWER("AB")')).toBe('ab');
|
||||
expect(await evalFormual('UPPER("ab")')).toBe('AB');
|
||||
expect(await evalFormual('SPLIT("a,b,c")')).toMatchObject(['a', 'b', 'c']);
|
||||
expect(await evalFormual('TRIM(" ab ")')).toBe('ab');
|
||||
expect(await evalFormual('STARTSWITH("xab", "ab")')).toBe(false);
|
||||
expect(await evalFormual('STARTSWITH("xab", "x")')).toBe(true);
|
||||
expect(await evalFormual('ENDSWITH("xab", "x")')).toBe(false);
|
||||
expect(await evalFormual('ENDSWITH("xab", "b")')).toBe(true);
|
||||
expect(await evalFormual('UPPERFIRST("xab")')).toBe('Xab');
|
||||
expect(await evalFormual('PADSTART("5", 3, "0")')).toBe('005');
|
||||
expect(await evalFormual('PADSTART(5, 3, 0)')).toBe('005');
|
||||
expect(await evalFormual('CAPITALIZE("star")')).toBe('Star');
|
||||
expect(await evalFormual('ESCAPE("&")')).toBe('&');
|
||||
expect(await evalFormual('TRUNCATE("amis.baidu.com", 7)')).toBe('amis...');
|
||||
expect(await evalFormual('BEFORELAST("amis.baidu.com", ".")')).toBe(
|
||||
'amis.baidu'
|
||||
);
|
||||
expect(await evalFormual('BEFORELAST("amis", ".")')).toBe('amis');
|
||||
expect(await evalFormual('STRIPTAG("<b>amis</b>")')).toBe('amis');
|
||||
expect(await evalFormual('LINEBREAK("am\nis")')).toBe('am<br/>is');
|
||||
expect(await evalFormual('CONTAINS("xab", "x")')).toBe(true);
|
||||
expect(await evalFormual('CONTAINS("xab", "b")')).toBe(true);
|
||||
expect(await evalFormual('REPLACE("xabab", "ab", "cd")')).toBe('xcdcd');
|
||||
expect(await evalFormual('SEARCH("xabab", "ab")')).toBe(1);
|
||||
expect(await evalFormual('SEARCH("xabab", "cd")')).toBe(-1);
|
||||
expect(await evalFormual('SEARCH("xabab", "ab", 2)')).toBe(3);
|
||||
expect(await evalFormual('MID("xabab", 2, 2)')).toBe('ba');
|
||||
});
|
||||
|
||||
test('formula:date', async () => {
|
||||
expect(await evalFormual('TIMESTAMP(DATE(2021, 11, 21, 0, 0, 0), "x")')).toBe(
|
||||
new Date(2021, 11, 21, 0, 0, 0).getTime()
|
||||
);
|
||||
expect(
|
||||
await evalFormual('DATETOSTR(DATE(2021, 11, 21, 0, 0, 0), "YYYY-MM-DD")')
|
||||
).toBe('2021-12-21');
|
||||
expect(await evalFormual('DATETOSTR(DATE("2021-12-21"), "YYYY-MM-DD")')).toBe(
|
||||
'2021-12-21'
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR(TODAY(), "YYYY-MM-DD")')).toBe(
|
||||
moment().format('YYYY-MM-DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR(NOW(), "YYYY-MM-DD")')).toBe(
|
||||
moment().format('YYYY-MM-DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR(1676563200, "YYYY-MM-DD")')).toBe(
|
||||
moment(1676563200, 'X').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR(1676563200000, "YYYY-MM-DD")')).toBe(
|
||||
moment(1676563200000, 'x').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR("12/25/2022", "YYYY-MM-DD")')).toBe(
|
||||
moment('12/25/2022').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR("12-25-2022", "YYYY/MM/DD")')).toBe(
|
||||
moment('12-25-2022').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR("2022年12月25日", "YYYY/MM/DD")')).toBe(
|
||||
moment('2022年12月25日', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATETOSTR("2022年12月25日 14时23分56秒", "YYYY/MM/DD HH:mm:ss")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2022年12月25日 14时23分56秒', 'YYYY-MM-DD HH:mm:ss').format(
|
||||
'YYYY/MM/DD HH:mm:ss'
|
||||
)
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR("20230105", "YYYY/MM/DD")')).toBe(
|
||||
moment('20230105', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(await evalFormual('DATETOSTR("2023.01.05", "YYYY/MM/DD")')).toBe(
|
||||
moment('2023.01.05', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATETOSTR("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z")'
|
||||
)
|
||||
).toBe(moment('2010-10-20 4:30 +0000').format('YYYY-MM-DD HH:mm Z'));
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATETOSTR("2013-02-04T10:35:24-08:00", "YYYY-MM-DD HH:mm:ss")'
|
||||
)
|
||||
).toBe(moment('2013-02-04T10:35:24-08:00').format('YYYY-MM-DD HH:mm:ss'));
|
||||
expect(await evalFormual('YEAR(STRTODATE("2021-10-24 10:10:10"))')).toBe(
|
||||
2021
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", undefined, "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toEqual(['2023.02.17 12:00:00', '2023.02.18 11:59:59']);
|
||||
expect(await evalFormual('DATERANGESPLIT("1676563200,1676735999", 0)')).toBe(
|
||||
'1676563200'
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", 0 , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.17 12:00:00');
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", "start" , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.17 12:00:00');
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", 1 , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.18 11:59:59');
|
||||
expect(
|
||||
await evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", "end" , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.18 11:59:59');
|
||||
expect(await evalFormual('WEEKDAY("2023-02-27")')).toBe(
|
||||
moment('2023-02-27').weekday()
|
||||
);
|
||||
expect(await evalFormual('WEEKDAY("2023-02-27", 2)')).toBe(
|
||||
moment('2023-02-27').isoWeekday()
|
||||
);
|
||||
expect(await evalFormual('WEEK("2023-03-05")')).toBe(
|
||||
moment('2023-03-05').week()
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-03-08", ["2023-03-01", "2024-04-07"], "year")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-03-08').isBetween('2023-03-01', '2024-04-07', 'year', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2022-03-08", ["2023-03-01", "2024-04-07"], "year")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2022-03-08').isBetween('2023-03-01', '2024-04-07', 'year', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-03-08", ["2023-03-01", "2023-04-07"], "month")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-03-08').isBetween('2023-03-01', '2023-04-07', 'month', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-05-08", ["2023-03-01", "2023-04-07", "month"])'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-05-08').isBetween('2023-03-01', '2023-04-07', 'month', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-03-06", ["2023-03-01", "2023-05-07"])'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-03-06').isBetween('2023-03-01', '2023-05-07', 'day', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-05-08", ["2023-03-01", "2023-05-07"])'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-05-08').isBetween('2023-03-01', '2023-05-07', 'day', '[]')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'BETWEENRANGE("2023-05-07", ["2023-03-01", "2023-05-07"], "day", "()")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-05-07').isBetween('2023-03-01', '2023-05-07', 'day', '()')
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day"), "," ,ENDOF("2023-02-28", "day"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28').startOf('day').format()},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format()}`
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day", "YYYY-MM-DD HH:mm:ss"), ",", ENDOF("2023-02-28", "day", "YYYY-MM-DD HH:mm:ss"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28')
|
||||
.startOf('day')
|
||||
.format('YYYY-MM-DD HH:mm:ss')},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format('YYYY-MM-DD HH:mm:ss')}`
|
||||
);
|
||||
expect(
|
||||
await evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day", "X"), "," ,ENDOF("2023-02-28", "day", "X"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28').startOf('day').format('X')},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format('X')}`
|
||||
);
|
||||
});
|
||||
|
||||
test('formula:last', async () => {
|
||||
expect(await evalFormual('LAST([1, 2, 3])')).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:basename', async () => {
|
||||
expect(await evalFormual('BASENAME("/home/amis/a.json")')).toBe('a.json');
|
||||
});
|
||||
|
||||
test('formula:customFunction', async () => {
|
||||
registerFunction('ASYNCFUNCTION', async input => {
|
||||
const response = await Promise.resolve({
|
||||
status: 0,
|
||||
data: {
|
||||
name: 'amis'
|
||||
}
|
||||
});
|
||||
return response;
|
||||
});
|
||||
|
||||
expect(await evalFormual('ASYNCFUNCTION()')).toMatchObject({
|
||||
status: 0,
|
||||
data: {
|
||||
name: 'amis'
|
||||
}
|
||||
});
|
||||
});
|
||||
617
packages/amis-formula/__tests__/evalute.test.ts
Normal file
617
packages/amis-formula/__tests__/evalute.test.ts
Normal file
@@ -0,0 +1,617 @@
|
||||
import {evaluate, parse} from '../src';
|
||||
|
||||
test('evalute:simple', () => {
|
||||
expect(
|
||||
evaluate('a is ${a}', {
|
||||
a: 123
|
||||
})
|
||||
).toBe('a is 123');
|
||||
});
|
||||
|
||||
test('evalute:filter', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${a | abc}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
abc(input: any) {
|
||||
return `${input}456`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123456');
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${a | concat:233}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, arg: string) {
|
||||
return `${input}${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123233');
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${concat(a, a)}',
|
||||
{
|
||||
a: 123
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, arg: string) {
|
||||
return `${input}${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 123123');
|
||||
});
|
||||
|
||||
test('evalute:filter2', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${[1, 2, 3] | concat:4 | join}',
|
||||
{},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,4');
|
||||
});
|
||||
|
||||
test('evalute:filter3', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${[1, 2, 3] | concat:"4" | join}',
|
||||
{},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,4');
|
||||
});
|
||||
|
||||
test('evalute:filter4', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'a is ${[1, 2, 3] | concat:${a + 3} | join}',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
filters: {
|
||||
concat(input: any, ...args: Array<any>) {
|
||||
return input.concat.apply(input, args);
|
||||
},
|
||||
join(input: any) {
|
||||
return input.join(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
).toBe('a is 1,2,3,7');
|
||||
});
|
||||
|
||||
test('evalute:keywords', () => {
|
||||
expect(evaluate('a is ${JOIN([1, 2, 3], "|")}', {})).toBe('a is 1|2|3');
|
||||
});
|
||||
|
||||
test('evalute:oldVariable', () => {
|
||||
expect(
|
||||
evaluate('a is $a', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('a is 4');
|
||||
|
||||
expect(
|
||||
evaluate('b is $b', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('b is ');
|
||||
|
||||
expect(
|
||||
evaluate('a.b is $a.b', {
|
||||
a: {
|
||||
b: 233
|
||||
}
|
||||
})
|
||||
).toBe('a.b is 233');
|
||||
});
|
||||
|
||||
test('evalute:ariable2', () => {
|
||||
expect(
|
||||
evaluate('a is $$', {
|
||||
a: 4
|
||||
})
|
||||
).toBe('a is [object Object]');
|
||||
});
|
||||
|
||||
test('evalute:ariable3', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'$$',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toMatchObject({
|
||||
a: 4
|
||||
});
|
||||
});
|
||||
|
||||
test('evalute:object-variable', () => {
|
||||
const data = {
|
||||
key: 'x',
|
||||
obj: {
|
||||
x: 1,
|
||||
y: 2
|
||||
}
|
||||
};
|
||||
|
||||
expect(evaluate('a is ${obj.x}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj[x]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj[`x`]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj["x"]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj[key]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj[`${key}`]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${obj[${key}]}', data)).toBe('a is 1');
|
||||
});
|
||||
|
||||
test('evalute:literal-variable', () => {
|
||||
const data = {
|
||||
key: 'x',
|
||||
index: 0,
|
||||
obj: {
|
||||
x: 1,
|
||||
y: 2
|
||||
}
|
||||
};
|
||||
|
||||
expect(evaluate('a is ${({x: 1})["x"]}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${({x: 1}).x}', data)).toBe('a is 1');
|
||||
expect(evaluate('a is ${(["a", "b"])[index]}', data)).toBe('a is a');
|
||||
expect(evaluate('a is ${(["a", "b"])[1]}', data)).toBe('a is b');
|
||||
expect(evaluate('a is ${(["a", "b"]).0}', data)).toBe('a is a');
|
||||
});
|
||||
|
||||
test('evalute:tempalte', () => {
|
||||
const data = {
|
||||
key: 'x'
|
||||
};
|
||||
|
||||
expect(evaluate('abc${`11${3}22`}xyz', data)).toBe('abc11322xyz');
|
||||
expect(evaluate('abc${`${3}22`}xyz', data)).toBe('abc322xyz');
|
||||
expect(evaluate('abc${`11${3}`}xyz', data)).toBe('abc113xyz');
|
||||
expect(evaluate('abc${`${3}`}xyz', data)).toBe('abc3xyz');
|
||||
expect(evaluate('abc${`${key}`}xyz', data)).toBe('abcxxyz');
|
||||
});
|
||||
|
||||
test('evalute:literal', () => {
|
||||
const data = {
|
||||
dynamicKey: 'alpha'
|
||||
};
|
||||
|
||||
expect(
|
||||
evaluate('${{a: 1, 0: 2, "3": 3}}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluate('${{a: 1, 0: 2, "3": 3, [`4`]: 4}}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3,
|
||||
4: 4
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluate('${{a: 1, 0: 2, "3": 3, [`${dynamicKey}233`]: 4}}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject({
|
||||
a: 1,
|
||||
0: 2,
|
||||
3: 3,
|
||||
alpha233: 4
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluate('${[1, 2, `2${dynamicKey}2`, {a: 1, 0: 2, [`2`]: "3"}]}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toMatchObject([1, 2, `2alpha2`, {a: 1, 0: 2, [`2`]: '3'}]);
|
||||
});
|
||||
|
||||
test('evalute:variableName', () => {
|
||||
const data = {
|
||||
'a_b': 'c',
|
||||
'222': 10222,
|
||||
'222_221': 233,
|
||||
'222_abcde': 'abcde',
|
||||
'222-221': 333
|
||||
};
|
||||
|
||||
expect(evaluate('${a_b}', data)).toBe('c');
|
||||
expect(evaluate('${222}', data)).toBe(222);
|
||||
expect(evaluate('${222_221}', data)).toBe('233');
|
||||
expect(evaluate('${222-221}', data)).toBe(1);
|
||||
expect(evaluate('${222_abcde}', data)).toBe('abcde');
|
||||
expect(
|
||||
evaluate('${&["222-221"]}', data, {
|
||||
defaultFilter: 'raw'
|
||||
})
|
||||
).toBe(333);
|
||||
expect(
|
||||
evaluate('222', data, {
|
||||
variableMode: true
|
||||
})
|
||||
).toBe(10222);
|
||||
});
|
||||
|
||||
test('evalute:3-1', () => {
|
||||
const data = {};
|
||||
|
||||
expect(evaluate('${3-1}', data)).toBe(2);
|
||||
expect(evaluate('${-1 + 2.5 + 3}', data)).toBe(4.5);
|
||||
expect(evaluate('${-1 + -1}', data)).toBe(-2);
|
||||
expect(evaluate('${3 * -1}', data)).toBe(-3);
|
||||
|
||||
expect(evaluate('${3 + +1}', data)).toBe(4);
|
||||
});
|
||||
|
||||
test('evalate:0.1+0.2', () => {
|
||||
expect(evaluate('${0.1 + 0.2}', {})).toBe(0.3);
|
||||
});
|
||||
|
||||
test('evalute:variable:com.xxx.xx', () => {
|
||||
const data = {
|
||||
'com.xxx.xx': 'abc',
|
||||
'com xxx%xx': 'cde',
|
||||
'com[xxx]': 'eee'
|
||||
};
|
||||
|
||||
expect(evaluate('${com\\.xxx\\.xx}', data)).toBe('abc');
|
||||
expect(evaluate('${com\\ xxx\\%xx}', data)).toBe('cde');
|
||||
expect(evaluate('${com\\[xxx\\]}', data)).toBe('eee');
|
||||
});
|
||||
|
||||
test('evalute:anonymous:function', () => {
|
||||
const data = {
|
||||
arr: [1, 2, 3],
|
||||
arr2: [
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
{
|
||||
a: 2
|
||||
},
|
||||
{
|
||||
a: 3
|
||||
}
|
||||
],
|
||||
outter: 4
|
||||
};
|
||||
|
||||
expect(evaluate('${() => 233}', data)).toMatchObject({
|
||||
args: [],
|
||||
return: {type: 'literal', value: 233},
|
||||
type: 'anonymous_function'
|
||||
});
|
||||
|
||||
expect(evaluate('${ARRAYMAP(arr, () => 1)}', data)).toMatchObject([1, 1, 1]);
|
||||
expect(evaluate('${ARRAYMAP(arr, item => item)}', data)).toMatchObject([
|
||||
1, 2, 3
|
||||
]);
|
||||
expect(evaluate('${ARRAYMAP(arr, item => item * 2)}', data)).toMatchObject([
|
||||
2, 4, 6
|
||||
]);
|
||||
expect(
|
||||
evaluate('${ARRAYMAP(arr2, (item, index) => `a${item.a}${index}`)}', data)
|
||||
).toMatchObject(['a10', 'a21', 'a32']);
|
||||
expect(
|
||||
evaluate(
|
||||
'${ARRAYMAP(arr2, (item, index) => `a${item.a}${index}${outter}`)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject(['a104', 'a214', 'a324']);
|
||||
expect(
|
||||
evaluate(
|
||||
'${ARRAYMAP(arr2, (item, index) => {x: item.a, index: index})}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([
|
||||
{
|
||||
x: 1,
|
||||
index: 0
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
index: 1
|
||||
},
|
||||
{
|
||||
x: 3,
|
||||
index: 2
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:anonymous:function2', () => {
|
||||
const data = {
|
||||
arr: [1, 2, 3],
|
||||
arr2: [
|
||||
{
|
||||
x: 1,
|
||||
y: [
|
||||
{
|
||||
z: 1
|
||||
},
|
||||
{
|
||||
z: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
x: 2,
|
||||
y: [
|
||||
{
|
||||
z: 2
|
||||
},
|
||||
{
|
||||
z: 2
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${ARRAYMAP(ARRAYMAP(arr, item => item * 2), item => item + 2)}',
|
||||
data
|
||||
)
|
||||
).toMatchObject([4, 6, 8]);
|
||||
|
||||
expect(
|
||||
evaluate('${ARRAYMAP(arr2, item => ARRAYMAP(item.y, i => i.z))}', data)
|
||||
).toMatchObject([
|
||||
[1, 1],
|
||||
[2, 2]
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:array:func', () => {
|
||||
const data = {
|
||||
arr1: [0, 1, false, 2, '', 3],
|
||||
arr2: ['a', 'b', 'c'],
|
||||
arr3: [1, 2, 3],
|
||||
arr4: [2, 4, 6],
|
||||
arr5: [
|
||||
{
|
||||
id: 1.1
|
||||
},
|
||||
{
|
||||
id: 2.2
|
||||
},
|
||||
{
|
||||
id: 1.1,
|
||||
name: 1.3
|
||||
}
|
||||
],
|
||||
obj1: {
|
||||
p1: 'name',
|
||||
p2: 'age',
|
||||
p3: 'obj',
|
||||
p4: [
|
||||
{
|
||||
p41: 'Tom',
|
||||
p42: 'Jerry'
|
||||
},
|
||||
{
|
||||
p41: 'baidu',
|
||||
p42: 'amis'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
expect(evaluate('${COMPACT(arr1)}', data)).toMatchObject([1, 2, 3]);
|
||||
|
||||
expect(evaluate("${COMPACT([0, 1, false, 2, '', 3])}", data)).toMatchObject([
|
||||
1, 2, 3
|
||||
]);
|
||||
|
||||
expect(evaluate('${JOIN(arr2, "~")}', data)).toMatch('a~b~c');
|
||||
|
||||
expect(evaluate('${SUM(arr3)}', data)).toBe(6);
|
||||
|
||||
expect(evaluate('${AVG(arr4)}', data)).toBe(4);
|
||||
|
||||
expect(evaluate('${MIN(arr4)}', data)).toBe(2);
|
||||
|
||||
expect(evaluate('${MAX(arr4)}', data)).toBe(6);
|
||||
|
||||
expect(evaluate('${CONCAT(arr3, arr4)}', data)).toMatchObject([
|
||||
1, 2, 3, 2, 4, 6
|
||||
]);
|
||||
|
||||
expect(evaluate('${CONCAT(arr, arr4)}', data)).toMatchObject([2, 4, 6]);
|
||||
|
||||
expect(evaluate('${UNIQ(arr5)}', data)).toMatchObject(data.arr5);
|
||||
|
||||
expect(evaluate('${UNIQ(arr5, "id")}', data)).toMatchObject([
|
||||
{id: 1.1},
|
||||
{id: 2.2}
|
||||
]);
|
||||
|
||||
expect(evaluate('${ARRAYFILTER(arr1, item => item)}', data)).toMatchObject([
|
||||
1, 2, 3
|
||||
]);
|
||||
expect(
|
||||
evaluate('${ARRAYFILTER(arr1, item => item && item >=2)}', data)
|
||||
).toMatchObject([2, 3]);
|
||||
|
||||
expect(evaluate('${ARRAYFINDINDEX(arr3, item => item === 2)}', data)).toBe(1);
|
||||
|
||||
expect(evaluate('${ARRAYFINDINDEX(arr3, item => item !== 1)}', data)).toBe(1);
|
||||
|
||||
expect(
|
||||
evaluate('${ARRAYFIND(arr5, item => item.name === 1.3)}', data)
|
||||
).toMatchObject({
|
||||
id: 1.1,
|
||||
name: 1.3
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluate('${ARRAYFIND(arr5, item => item.id !== 1.1)}', data)
|
||||
).toMatchObject({
|
||||
id: 2.2
|
||||
});
|
||||
|
||||
expect(evaluate('${ARRAYSOME(arr5, item => item.name === 1.3)}', data)).toBe(
|
||||
true
|
||||
);
|
||||
|
||||
expect(evaluate('${ARRAYEVERY(arr5, item => item.name === 1.3)}', data)).toBe(
|
||||
false
|
||||
);
|
||||
|
||||
expect(evaluate('${ARRAYINCLUDES(arr1, false)}', data)).toBe(true);
|
||||
|
||||
expect(evaluate('${GET(arr1, 2)}', data)).toBe(false);
|
||||
expect(evaluate('${GET(arr1, 6, "not-found")}', data)).toBe('not-found');
|
||||
expect(evaluate('${GET(arr5, "[2].name")}', data)).toBe(1.3);
|
||||
expect(evaluate('${GET(arr5, "2.name")}', data)).toBe(1.3);
|
||||
expect(evaluate('${GET(obj1, "p2")}', data)).toBe('age');
|
||||
expect(evaluate('${GET(obj1, "p4.1.p42")}', data)).toBe('amis');
|
||||
expect(evaluate('${GET(obj1, "p4[1].p42")}', data)).toBe('amis');
|
||||
|
||||
expect(evaluate('${ENCODEJSON(obj1)}', data)).toBe(JSON.stringify(data.obj1));
|
||||
expect(
|
||||
evaluate('${DECODEJSON("{\\"name\\":\\"amis\\"}")}', data)
|
||||
).toMatchObject(JSON.parse('{"name":"amis"}'));
|
||||
});
|
||||
|
||||
test('evalute:ISTYPE', () => {
|
||||
const data = {
|
||||
a: 1,
|
||||
b: 'string',
|
||||
c: null,
|
||||
d: undefined,
|
||||
e: [1, 2],
|
||||
f: {a: 1, b: 2},
|
||||
g: new Date()
|
||||
};
|
||||
expect(evaluate('${ISTYPE(a, "number")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(b, "number")}', data)).toBe(false);
|
||||
expect(evaluate('${ISTYPE(b, "string")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(c, "nil")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(d, "nil")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(e, "array")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(f, "array")}', data)).toBe(false);
|
||||
expect(evaluate('${ISTYPE(f, "plain-object")}', data)).toBe(true);
|
||||
expect(evaluate('${ISTYPE(g, "date")}', data)).toBe(true);
|
||||
});
|
||||
|
||||
test('evalute:Math', () => {
|
||||
const data = {
|
||||
float: 0.5,
|
||||
integer1: 2,
|
||||
integer2: 4,
|
||||
negativeInteger: -2,
|
||||
array: [1, 2, 3],
|
||||
infinity: Infinity
|
||||
};
|
||||
|
||||
expect(evaluate('${POW(integer1, integer2)}', data)).toBe(16);
|
||||
expect(evaluate('${POW(integer2, 0.5)}', data)).toBe(2);
|
||||
expect(evaluate('${POW(integer1, -2)}', data)).toBe(0.25);
|
||||
/** 计算结果不合法,则返回NaN */
|
||||
expect(evaluate('${POW(negativeInteger, 0.5)}', data)).toBe(NaN);
|
||||
/** 参数值不合法,则返回基数本身*/
|
||||
expect(evaluate('${POW(array, 2)}', data)).toBe(data.array);
|
||||
/** 测试Infinity */
|
||||
expect(evaluate('${POW(infinity, 2)}', data)).toBe(data.infinity);
|
||||
expect(evaluate('${POW(1, infinity)}', data)).toBe(NaN);
|
||||
expect(evaluate('${POW(2, infinity)}', data)).toBe(data.infinity);
|
||||
});
|
||||
|
||||
test('evalute:UUID', () => {
|
||||
function isUUIDv4(value: string) {
|
||||
return /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(
|
||||
value
|
||||
);
|
||||
}
|
||||
|
||||
expect(isUUIDv4(evaluate('${UUID()}', {}))).toBe(true);
|
||||
expect(evaluate('${UUID()}', {}).length).toBe(36);
|
||||
expect(evaluate('${UUID(8)}', {}).length).toBe(8);
|
||||
});
|
||||
|
||||
test('evalute:namespace', () => {
|
||||
localStorage.setItem('a', '1');
|
||||
localStorage.setItem('b', '2');
|
||||
localStorage.setItem('c', '{"a": 1, "b": 2, "c": {"d": 4}}');
|
||||
localStorage.setItem('key', 'c');
|
||||
localStorage.setItem('spec-var-name', 'you are right');
|
||||
|
||||
expect(evaluate('${ls: a}', {})).toBe(1);
|
||||
expect(evaluate('${ls: b}', {})).toBe(2);
|
||||
expect(evaluate('${ls: c}', {})).toMatchObject({a: 1, b: 2, c: {d: 4}});
|
||||
// 被认为是减操作
|
||||
expect(evaluate('${ls: spec-var-name}', {})).toBe(0);
|
||||
expect(evaluate('${ls: spec\\-var\\-name}', {})).toBe('you are right');
|
||||
expect(evaluate('${ls: &["spec-var-name"]}', {})).toBe('you are right');
|
||||
expect(evaluate('${ls: &["c"]["c"]}', {})).toMatchObject({d: 4});
|
||||
expect(evaluate('${ls: &["c"][key]}', {})).toMatchObject({d: 4});
|
||||
});
|
||||
|
||||
test('evalute:speical characters', () => {
|
||||
// 优先识别成位运算,而不是过滤器
|
||||
expect(evaluate('${1 | 2}', {})).toBe(3);
|
||||
expect(evaluate('${1 | abc}', {abc: 2})).toBe(3);
|
||||
});
|
||||
|
||||
test('evalute:replace', () => {
|
||||
const data = {};
|
||||
expect(evaluate('${REPLACE("abcdefg", "abc", "cbd")}', data)).toBe('cbddefg');
|
||||
expect(evaluate('${REPLACE("abcdefg", "efg", "efg")}', data)).toBe('abcdefg');
|
||||
expect(evaluate('${REPLACE("abcdefg", "abc", "abcabc")}', data)).toBe(
|
||||
'abcabcdefg'
|
||||
);
|
||||
});
|
||||
362
packages/amis-formula/__tests__/fomula.test.ts
Normal file
362
packages/amis-formula/__tests__/fomula.test.ts
Normal file
@@ -0,0 +1,362 @@
|
||||
import moment from 'moment';
|
||||
import {evaluate, parse, registerFunction} from '../src';
|
||||
|
||||
const defaultContext = {
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: 3,
|
||||
d: 4,
|
||||
e: 5
|
||||
};
|
||||
|
||||
function evalFormual(expression: string, data: any = defaultContext) {
|
||||
return evaluate(expression, data, {
|
||||
evalMode: true
|
||||
});
|
||||
}
|
||||
|
||||
test('formula:expression', () => {
|
||||
expect(evalFormual('a + 3')).toBe(4);
|
||||
expect(evalFormual('b * 3')).toBe(6);
|
||||
expect(evalFormual('b * 3 + 4')).toBe(10);
|
||||
expect(evalFormual('c * (3 + 4)')).toBe(21);
|
||||
expect(evalFormual('d / (a + 1)')).toBe(2);
|
||||
expect(evalFormual('5 % 3')).toBe(2);
|
||||
expect(evalFormual('3 | 4')).toBe(7);
|
||||
expect(evalFormual('4 ^ 4')).toBe(0);
|
||||
expect(evalFormual('4 ^ 4')).toBe(0);
|
||||
expect(evalFormual('4 & 4')).toBe(4);
|
||||
expect(evalFormual('4 & 3')).toBe(0);
|
||||
expect(evalFormual('~-1')).toBe(0);
|
||||
expect(evalFormual('!!1')).toBe(true);
|
||||
expect(evalFormual('!!""')).toBe(false);
|
||||
expect(evalFormual('1 || 2')).toBe(1);
|
||||
expect(evalFormual('1 && 2')).toBe(2);
|
||||
expect(evalFormual('1 && 2 || 3')).toBe(2);
|
||||
expect(evalFormual('1 || 2 || 3')).toBe(1);
|
||||
expect(evalFormual('1 || 2 && 3')).toBe(1);
|
||||
expect(evalFormual('(1 || 2) && 3')).toBe(3);
|
||||
expect(evalFormual('1 == "1"')).toBe(true);
|
||||
expect(evalFormual('1 === "1"')).toBe(false);
|
||||
expect(evalFormual('1 < 1')).toBe(false);
|
||||
expect(evalFormual('1 <= 1')).toBe(true);
|
||||
expect(evalFormual('1 > 1')).toBe(false);
|
||||
expect(evalFormual('1 >= 1')).toBe(true);
|
||||
expect(evalFormual('3 >> 1')).toBe(1);
|
||||
expect(evalFormual('3 << 1')).toBe(6);
|
||||
expect(evalFormual('10 ** 3')).toBe(1000);
|
||||
|
||||
expect(evalFormual('10 ? 3 : 2')).toBe(3);
|
||||
expect(evalFormual('0 ? 3 : 2')).toBe(2);
|
||||
});
|
||||
|
||||
test('formula:expression2', () => {
|
||||
expect(evalFormual('a[0]', {a: [1, 2, 3]})).toBe(1);
|
||||
expect(evalFormual('a[b]', {a: [1, 2, 3], b: 1})).toBe(2);
|
||||
expect(evalFormual('a[b - 1]', {a: [1, 2, 3], b: 1})).toBe(1);
|
||||
expect(evalFormual('a[b ? 1 : 2]', {a: [1, 2, 3], b: 1})).toBe(2);
|
||||
expect(evalFormual('a[c ? 1 : 2]', {a: [1, 2, 3], b: 1})).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:expression3', () => {
|
||||
// expect(evalFormual('${a} === "b"', {a: 'b'})).toBe(true);
|
||||
expect(evalFormual('b === "b"')).toBe(false);
|
||||
// expect(evalFormual('${a}', {a: 'b'})).toBe('b');
|
||||
|
||||
expect(evalFormual('obj.x.a', {obj: {x: {a: 1}}})).toBe(1);
|
||||
expect(evalFormual('obj.y.a', {obj: {x: {a: 1}}})).toBe(undefined);
|
||||
});
|
||||
|
||||
test('formula:if', () => {
|
||||
expect(evalFormual('IF(true, 2, 3)')).toBe(2);
|
||||
expect(evalFormual('IF(false, 2, 3)')).toBe(3);
|
||||
expect(evalFormual('IF(false, 2, IF(true, 3, 4))')).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:and', () => {
|
||||
expect(!!evalFormual('AND(0, 1)')).toBe(false);
|
||||
expect(!!evalFormual('AND(1, 1)')).toBe(true);
|
||||
expect(!!evalFormual('AND(1, 1, 1, 0)')).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:or', () => {
|
||||
expect(!!evalFormual('OR(0, 1)')).toBe(true);
|
||||
expect(!!evalFormual('OR(1, 1)')).toBe(true);
|
||||
expect(!!evalFormual('OR(1, 1, 1, 0)')).toBe(true);
|
||||
expect(!!evalFormual('OR(0, 0, 0, 0)')).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:xor', () => {
|
||||
expect(evalFormual('XOR(0, 1)')).toBe(true);
|
||||
expect(evalFormual('XOR(1, 0)')).toBe(true);
|
||||
expect(evalFormual('XOR(1, 1)')).toBe(false);
|
||||
expect(evalFormual('XOR(0, 0)')).toBe(false);
|
||||
|
||||
expect(evalFormual('XOR(0, 0, 1)')).toBe(true);
|
||||
expect(evalFormual('XOR(0, 1, 1)')).toBe(false);
|
||||
});
|
||||
|
||||
test('formula:ifs', () => {
|
||||
expect(!!evalFormual('IFS(0, 1, 2)')).toBe(true);
|
||||
expect(!!evalFormual('IFS(0, 1, 2, 2, 3)')).toBe(true);
|
||||
expect(!!evalFormual('IFS(0, 1, 0, 2, 0)')).toBe(false);
|
||||
expect(evalFormual('IFS(0, 1, 2, 2)')).toBe(2);
|
||||
expect(evalFormual('IFS(0, 1, 0, 2)')).toBe(undefined);
|
||||
});
|
||||
|
||||
test('formula:math', () => {
|
||||
expect(evalFormual('ABS(1)')).toBe(1);
|
||||
expect(evalFormual('ABS(-1)')).toBe(1);
|
||||
expect(evalFormual('ABS(0)')).toBe(0);
|
||||
|
||||
expect(evalFormual('MAX(1, -1, 2, 3, 5, -9)')).toBe(5);
|
||||
expect(evalFormual('MIN(1, -1, 2, 3, 5, -9)')).toBe(-9);
|
||||
|
||||
expect(evalFormual('MOD(3, 2)')).toBe(1);
|
||||
|
||||
expect(evalFormual('PI()')).toBe(Math.PI);
|
||||
|
||||
expect(evalFormual('ROUND(3.55)')).toBe(3.55);
|
||||
expect(evalFormual('ROUND(3.45)')).toBe(3.45);
|
||||
|
||||
expect(evalFormual('ROUND(3.456789, 2)')).toBe(3.46);
|
||||
expect(evalFormual('CEIL(3.456789)')).toBe(3.46);
|
||||
expect(evalFormual('FLOOR(3.456789)')).toBe(3.45);
|
||||
|
||||
expect(evalFormual('SQRT(4)')).toBe(2);
|
||||
expect(evalFormual('AVG(4, 6, 10, 10, 10)')).toBe(8);
|
||||
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/devsq-%E5%87%BD%E6%95%B0-8b739616-8376-4df5-8bd0-cfe0a6caf444
|
||||
expect(evalFormual('DEVSQ(4,5,8,7,11,4,3)')).toBe(48);
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/avedev-%E5%87%BD%E6%95%B0-58fe8d65-2a84-4dc7-8052-f3f87b5c6639
|
||||
expect(evalFormual('ROUND(AVEDEV(4,5,6,7,5,4,3), 2)')).toBe(1.02);
|
||||
// 示例来自 https://support.microsoft.com/zh-cn/office/harmean-%E5%87%BD%E6%95%B0-5efd9184-fab5-42f9-b1d3-57883a1d3bc6
|
||||
expect(evalFormual('ROUND(HARMEAN(4,5,8,7,11,4,3), 3)')).toBe(5.028);
|
||||
|
||||
expect(evalFormual('LARGE([1,3,5,4,7,6], 3)')).toBe(5);
|
||||
expect(evalFormual('LARGE([1,3,5,4,7,6], 1)')).toBe(7);
|
||||
|
||||
expect(evalFormual('UPPERMONEY(7682.01)')).toBe('柒仟陆佰捌拾贰元壹分');
|
||||
expect(evalFormual('UPPERMONEY(7682)')).toBe('柒仟陆佰捌拾贰元整');
|
||||
|
||||
// 非数字类型转换是否正常?
|
||||
expect(evalFormual('"3" + "3"')).toBe(6);
|
||||
expect(evalFormual('"3" - "3"')).toBe(0);
|
||||
expect(evalFormual('AVG(4, "6", "10", 10, 10)')).toBe(8);
|
||||
expect(evalFormual('MAX(4, "6", "10", 2, 3)')).toBe(10);
|
||||
|
||||
expect(evalFormual('"a" + "b"')).toBe('ab');
|
||||
});
|
||||
|
||||
test('formula:text', () => {
|
||||
expect(evalFormual('LEFT("abcdefg", 2)')).toBe('ab');
|
||||
expect(evalFormual('RIGHT("abcdefg", 2)')).toBe('fg');
|
||||
expect(evalFormual('LENGTH("abcdefg")')).toBe(7);
|
||||
expect(evalFormual('LEN("abcdefg")')).toBe(7);
|
||||
expect(evalFormual('ISEMPTY("abcdefg")')).toBe(false);
|
||||
expect(evalFormual('ISEMPTY("")')).toBe(true);
|
||||
expect(evalFormual('CONCATENATE("a", "b", "c", "d")')).toBe('abcd');
|
||||
expect(evalFormual('CHAR(97)')).toBe('a');
|
||||
expect(evalFormual('LOWER("AB")')).toBe('ab');
|
||||
expect(evalFormual('UPPER("ab")')).toBe('AB');
|
||||
expect(evalFormual('SPLIT("a,b,c")')).toMatchObject(['a', 'b', 'c']);
|
||||
expect(evalFormual('TRIM(" ab ")')).toBe('ab');
|
||||
expect(evalFormual('STARTSWITH("xab", "ab")')).toBe(false);
|
||||
expect(evalFormual('STARTSWITH("xab", "x")')).toBe(true);
|
||||
expect(evalFormual('ENDSWITH("xab", "x")')).toBe(false);
|
||||
expect(evalFormual('ENDSWITH("xab", "b")')).toBe(true);
|
||||
expect(evalFormual('UPPERFIRST("xab")')).toBe('Xab');
|
||||
expect(evalFormual('PADSTART("5", 3, "0")')).toBe('005');
|
||||
expect(evalFormual('PADSTART(5, 3, 0)')).toBe('005');
|
||||
expect(evalFormual('CAPITALIZE("star")')).toBe('Star');
|
||||
expect(evalFormual('ESCAPE("&")')).toBe('&');
|
||||
expect(evalFormual('TRUNCATE("amis.baidu.com", 7)')).toBe('amis...');
|
||||
expect(evalFormual('BEFORELAST("amis.baidu.com", ".")')).toBe('amis.baidu');
|
||||
expect(evalFormual('BEFORELAST("amis", ".")')).toBe('amis');
|
||||
expect(evalFormual('STRIPTAG("<b>amis</b>")')).toBe('amis');
|
||||
expect(evalFormual('LINEBREAK("am\nis")')).toBe('am<br/>is');
|
||||
expect(evalFormual('CONTAINS("xab", "x")')).toBe(true);
|
||||
expect(evalFormual('CONTAINS("xab", "b")')).toBe(true);
|
||||
expect(evalFormual('REPLACE("xabab", "ab", "cd")')).toBe('xcdcd');
|
||||
expect(evalFormual('SEARCH("xabab", "ab")')).toBe(1);
|
||||
expect(evalFormual('SEARCH("xabab", "cd")')).toBe(-1);
|
||||
expect(evalFormual('SEARCH("xabab", "ab", 2)')).toBe(3);
|
||||
expect(evalFormual('MID("xabab", 2, 2)')).toBe('ba');
|
||||
});
|
||||
|
||||
test('formula:date', () => {
|
||||
expect(evalFormual('TIMESTAMP(DATE(2021, 11, 21, 0, 0, 0), "x")')).toBe(
|
||||
new Date(2021, 11, 21, 0, 0, 0).getTime()
|
||||
);
|
||||
expect(
|
||||
evalFormual('DATETOSTR(DATE(2021, 11, 21, 0, 0, 0), "YYYY-MM-DD")')
|
||||
).toBe('2021-12-21');
|
||||
expect(evalFormual('DATETOSTR(DATE("2021-12-21"), "YYYY-MM-DD")')).toBe(
|
||||
'2021-12-21'
|
||||
);
|
||||
expect(evalFormual('DATETOSTR(TODAY(), "YYYY-MM-DD")')).toBe(
|
||||
moment().format('YYYY-MM-DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR(NOW(), "YYYY-MM-DD")')).toBe(
|
||||
moment().format('YYYY-MM-DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR(1676563200, "YYYY-MM-DD")')).toBe(
|
||||
moment(1676563200, 'X').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR(1676563200000, "YYYY-MM-DD")')).toBe(
|
||||
moment(1676563200000, 'x').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR("12/25/2022", "YYYY-MM-DD")')).toBe(
|
||||
moment('12/25/2022').format('YYYY-MM-DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR("12-25-2022", "YYYY/MM/DD")')).toBe(
|
||||
moment('12-25-2022').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR("2022年12月25日", "YYYY/MM/DD")')).toBe(
|
||||
moment('2022年12月25日', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATETOSTR("2022年12月25日 14时23分56秒", "YYYY/MM/DD HH:mm:ss")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2022年12月25日 14时23分56秒', 'YYYY-MM-DD HH:mm:ss').format(
|
||||
'YYYY/MM/DD HH:mm:ss'
|
||||
)
|
||||
);
|
||||
expect(evalFormual('DATETOSTR("20230105", "YYYY/MM/DD")')).toBe(
|
||||
moment('20230105', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(evalFormual('DATETOSTR("2023.01.05", "YYYY/MM/DD")')).toBe(
|
||||
moment('2023.01.05', 'YYYY-MM-DD').format('YYYY/MM/DD')
|
||||
);
|
||||
expect(
|
||||
evalFormual('DATETOSTR("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z")')
|
||||
).toBe(moment('2010-10-20 4:30 +0000').format('YYYY-MM-DD HH:mm Z'));
|
||||
expect(
|
||||
evalFormual('DATETOSTR("2013-02-04T10:35:24-08:00", "YYYY-MM-DD HH:mm:ss")')
|
||||
).toBe(moment('2013-02-04T10:35:24-08:00').format('YYYY-MM-DD HH:mm:ss'));
|
||||
expect(evalFormual('YEAR(STRTODATE("2021-10-24 10:10:10"))')).toBe(2021);
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", undefined, "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toEqual(['2023.02.17 12:00:00', '2023.02.18 11:59:59']);
|
||||
expect(evalFormual('DATERANGESPLIT("1676563200,1676735999", 0)')).toBe(
|
||||
'1676563200'
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", 0 , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.17 12:00:00');
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", "start" , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.17 12:00:00');
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", 1 , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.18 11:59:59');
|
||||
expect(
|
||||
evalFormual(
|
||||
'DATERANGESPLIT("1676563200,1676735999", "end" , "YYYY.MM.DD hh:mm:ss")'
|
||||
)
|
||||
).toBe('2023.02.18 11:59:59');
|
||||
expect(evalFormual('WEEKDAY("2023-02-27")')).toBe(
|
||||
moment('2023-02-27').weekday()
|
||||
);
|
||||
expect(evalFormual('WEEKDAY("2023-02-27", 2)')).toBe(
|
||||
moment('2023-02-27').isoWeekday()
|
||||
);
|
||||
expect(evalFormual('WEEK("2023-03-05")')).toBe(moment('2023-03-05').week());
|
||||
expect(
|
||||
evalFormual(
|
||||
'BETWEENRANGE("2023-03-08", ["2023-03-01", "2024-04-07"], "year")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-03-08').isBetween('2023-03-01', '2024-04-07', 'year', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'BETWEENRANGE("2022-03-08", ["2023-03-01", "2024-04-07"], "year")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2022-03-08').isBetween('2023-03-01', '2024-04-07', 'year', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'BETWEENRANGE("2023-03-08", ["2023-03-01", "2023-04-07"], "month")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-03-08').isBetween('2023-03-01', '2023-04-07', 'month', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'BETWEENRANGE("2023-05-08", ["2023-03-01", "2023-04-07", "month"])'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-05-08').isBetween('2023-03-01', '2023-04-07', 'month', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual('BETWEENRANGE("2023-03-06", ["2023-03-01", "2023-05-07"])')
|
||||
).toBe(
|
||||
moment('2023-03-06').isBetween('2023-03-01', '2023-05-07', 'day', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual('BETWEENRANGE("2023-05-08", ["2023-03-01", "2023-05-07"])')
|
||||
).toBe(
|
||||
moment('2023-05-08').isBetween('2023-03-01', '2023-05-07', 'day', '[]')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'BETWEENRANGE("2023-05-07", ["2023-03-01", "2023-05-07"], "day", "()")'
|
||||
)
|
||||
).toBe(
|
||||
moment('2023-05-07').isBetween('2023-03-01', '2023-05-07', 'day', '()')
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day"), "," ,ENDOF("2023-02-28", "day"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28').startOf('day').format()},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format()}`
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day", "YYYY-MM-DD HH:mm:ss"), ",", ENDOF("2023-02-28", "day", "YYYY-MM-DD HH:mm:ss"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28')
|
||||
.startOf('day')
|
||||
.format('YYYY-MM-DD HH:mm:ss')},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format('YYYY-MM-DD HH:mm:ss')}`
|
||||
);
|
||||
expect(
|
||||
evalFormual(
|
||||
'CONCATENATE(STARTOF("2023-02-28", "day", "X"), "," ,ENDOF("2023-02-28", "day", "X"))'
|
||||
)
|
||||
).toBe(
|
||||
`${moment('2023-02-28').startOf('day').format('X')},${moment('2023-02-28')
|
||||
.endOf('day')
|
||||
.format('X')}`
|
||||
);
|
||||
});
|
||||
|
||||
test('formula:last', () => {
|
||||
expect(evalFormual('LAST([1, 2, 3])')).toBe(3);
|
||||
});
|
||||
|
||||
test('formula:basename', () => {
|
||||
expect(evalFormual('BASENAME("/home/amis/a.json")')).toBe('a.json');
|
||||
});
|
||||
|
||||
test('formula:customFunction', () => {
|
||||
registerFunction('CUSTOMFUNCTION', input => input);
|
||||
expect(evalFormual('CUSTOMFUNCTION("func")')).toBe('func');
|
||||
});
|
||||
22
packages/amis-formula/__tests__/jest.setup.js
Normal file
22
packages/amis-formula/__tests__/jest.setup.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const originalWarn = console.warn.bind(console.warn);
|
||||
|
||||
require('moment-timezone');
|
||||
const moment = require('moment');
|
||||
moment.tz.setDefault('Asia/Shanghai');
|
||||
|
||||
global.beforeAll(() => {
|
||||
console.warn = msg => {
|
||||
// warning 先关了,实在太吵。
|
||||
// const str = msg.toString();
|
||||
// if (
|
||||
// str.includes('componentWillMount') ||
|
||||
// str.includes('componentWillReceiveProps')
|
||||
// ) {
|
||||
// return;
|
||||
// }
|
||||
// originalWarn(msg);
|
||||
};
|
||||
});
|
||||
global.afterAll(() => {
|
||||
console.warn = originalWarn;
|
||||
});
|
||||
70
packages/amis-formula/__tests__/lexer.test.ts
Normal file
70
packages/amis-formula/__tests__/lexer.test.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import {lexer as createLexer, parse} from '../src';
|
||||
|
||||
function getTokens(input: string, options?: any) {
|
||||
const lexer = createLexer(input, options);
|
||||
const tokens: Array<any> = [];
|
||||
|
||||
while (true) {
|
||||
const token = lexer.next();
|
||||
if (token) {
|
||||
tokens.push(token);
|
||||
|
||||
if (token.type === 'EOF') {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return tokens.map(token => `<${token.type}> ${token.value}`);
|
||||
}
|
||||
|
||||
test('lexer:simple', () => {
|
||||
expect(
|
||||
getTokens('expression result is ${a + b}', {
|
||||
evalMode: false
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('lexer:filter', () => {
|
||||
expect(
|
||||
getTokens('\\$abc is ${abc | date: YYYY-MM-DD HH\\:mm\\:ss}', {
|
||||
evalMode: false,
|
||||
filters: {
|
||||
date() {}
|
||||
}
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
getTokens('\\$abc is ${abc | isTrue : trueValue : falseValue}', {
|
||||
evalMode: false,
|
||||
filters: {
|
||||
isTrue() {}
|
||||
}
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
// test('lexer:test', () => {
|
||||
// console.log(getTokens("{a: 1, 'b': 2, `c`: 3, d: {}}", {evalMode: true}));
|
||||
// });
|
||||
|
||||
test('lexer:exception', () => {
|
||||
expect(() =>
|
||||
getTokens('\\aabc is ', {
|
||||
evalMode: false
|
||||
})
|
||||
).toThrow('Unexpected token a in 1:3');
|
||||
|
||||
expect(() =>
|
||||
getTokens('${a | filter: \\x2}', {
|
||||
evalMode: false,
|
||||
filters: {
|
||||
filter() {}
|
||||
}
|
||||
})
|
||||
).toThrow('Unexpected token x in 1:17');
|
||||
});
|
||||
213
packages/amis-formula/__tests__/parser.test.ts
Normal file
213
packages/amis-formula/__tests__/parser.test.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import moment from 'moment';
|
||||
import {parse} from '../src/index';
|
||||
|
||||
test('parser:simple', () => {
|
||||
expect(
|
||||
parse('expression result is ${a + b}', {
|
||||
evalMode: false
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:complex', () => {
|
||||
expect(
|
||||
parse('raw content ${`es tempalte ${`deeper${a + 3}`}`}', {
|
||||
evalMode: false
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:evalMode', () => {
|
||||
expect(
|
||||
parse('a + b', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:template', () => {
|
||||
expect(
|
||||
parse('`abc${a + b}`', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:string', () => {
|
||||
expect(
|
||||
parse('"string literall, escape \\""', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('"string literall, escape \\" \\\\ \\/ \\b \\f \\n \\r \\t"', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:number', () => {
|
||||
expect(
|
||||
parse('-1 + 2.5 + 3', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:single-string', () => {
|
||||
expect(
|
||||
parse("'string'", {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:object-literall', () => {
|
||||
expect(
|
||||
parse("{a: 1, 'b': 2, [`c`]: 3, d: {}}", {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:array-literall', () => {
|
||||
expect(
|
||||
parse('[a, b, 1, 2, {a: 1}]', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:variable-geter', () => {
|
||||
expect(
|
||||
parse('doAction(a.b, a[b], a["c"], a[`d`])', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:variable-geter2', () => {
|
||||
expect(
|
||||
parse('a[b]["c"][d][`x`]', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('a[b]["c"].d[`x`]', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
test('parser:multi-expression', () => {
|
||||
expect(
|
||||
parse('(a.b, a[b], a["c"], a[`d`])', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:functionCall', () => {
|
||||
expect(
|
||||
parse('doAction(a, doAction(b))', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:filter', () => {
|
||||
expect(
|
||||
parse('\\$abc is ${abc | html}', {
|
||||
evalMode: false
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:filter-escape', () => {
|
||||
expect(
|
||||
parse('\\$abc is ${abc | date: YYYY-MM-DD HH\\:mm\\:ss}', {
|
||||
evalMode: false,
|
||||
filters: {
|
||||
date: (input: any, format = 'LLL', inputFormat = 'X') =>
|
||||
moment(input, inputFormat).format(format)
|
||||
}
|
||||
} as any)
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:conditional', () => {
|
||||
expect(
|
||||
parse('a ? b : c', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:binary-expression', () => {
|
||||
expect(
|
||||
parse('a && b && c', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('a && b || c', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('a || b && c', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('a !== b === c', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:group-expression', () => {
|
||||
expect(
|
||||
parse('a && (b && c)', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:unary-expression', () => {
|
||||
expect(
|
||||
parse('!!a', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('parser:anonymous-function', () => {
|
||||
expect(
|
||||
parse('() => 1', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('() => "string"', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
|
||||
expect(
|
||||
parse('(a) => `${a.a}---${a.b}`', {
|
||||
evalMode: true
|
||||
})
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
// test('parser:test', () => {
|
||||
// console.log(JSON.stringify(parse('ARRAYMAP(arr, (item) => item.abc)', {
|
||||
// evalMode: true
|
||||
// }), null, 2));
|
||||
// });
|
||||
117
packages/amis-formula/package.json
Normal file
117
packages/amis-formula/package.json
Normal file
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"name": "amis-formula",
|
||||
"version": "6.13.0",
|
||||
"description": "负责 amis 里面的表达式实现,内置公式,编辑器等",
|
||||
"main": "lib/index.js",
|
||||
"module": "esm/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "npm run clean-dist && npm run genDoc && cross-env NODE_ENV=production rollup -c && cp src/doc.md lib/doc.md && cp src/doc.md esm/doc.md",
|
||||
"build-esm": "npm run clean-dist && cross-env NODE_ENV=production rollup -c rollup.esm.config.js",
|
||||
"lib": "npm run clean-dist && cross-env NODE_ENV=production IS_LIB=1 rollup -c",
|
||||
"clean-dist": "rimraf lib/**",
|
||||
"declaration": "tsc --project tsconfig-for-declaration.json --allowJs --declaration --emitDeclarationOnly --declarationDir ./lib --rootDir ./src",
|
||||
"test": "jest",
|
||||
"update-snapshot": "jest --updateSnapshot",
|
||||
"coverage": "jest --coverage",
|
||||
"genDoc": "ts-node ./scripts/genDoc.ts"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"require": "./lib/index.js",
|
||||
"import": "./esm/index.js"
|
||||
},
|
||||
"./lib/*": {
|
||||
"require": "./lib/*.js",
|
||||
"import": "./esm/*.js"
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/aisuda/amis-tpl.git"
|
||||
},
|
||||
"keywords": [
|
||||
"amis",
|
||||
"tpl",
|
||||
"parser",
|
||||
"formula"
|
||||
],
|
||||
"files": [
|
||||
"lib",
|
||||
"esm"
|
||||
],
|
||||
"author": "fex",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/aisuda/amis-tpl/issues"
|
||||
},
|
||||
"homepage": "https://github.com/aisuda/amis-tpl#readme",
|
||||
"dependencies": {
|
||||
"lodash": "^4.17.15",
|
||||
"moment": "^2.19.4",
|
||||
"tslib": "^2.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^22.0.2",
|
||||
"@rollup/plugin-json": "^4.1.0",
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@rollup/plugin-typescript": "^8.3.4",
|
||||
"@types/doctrine": "0.0.5",
|
||||
"@types/jest": "^28.1.0",
|
||||
"@types/lodash": "^4.14.175",
|
||||
"cross-env": "^7.0.3",
|
||||
"doctrine": "^3.0.0",
|
||||
"jest": "^29.0.3",
|
||||
"jest-canvas-mock": "^2.3.0",
|
||||
"jest-environment-jsdom": "^29.0.3",
|
||||
"mini-css-extract-plugin": "^2.4.5",
|
||||
"moment-timezone": "^0.5.33",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.60.2",
|
||||
"rollup-plugin-license": "^2.6.0",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"sass": "^1.54.9",
|
||||
"sass-loader": "^12.1.0",
|
||||
"style-loader": "^3.2.1",
|
||||
"stylelint": "^13.0.0",
|
||||
"ts-jest": "^29.0.2",
|
||||
"ts-loader": "^9.2.3",
|
||||
"ts-node": "^10.4.0",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"browserslist": "IE >= 11",
|
||||
"jest": {
|
||||
"testEnvironment": "jsdom",
|
||||
"coverageReporters": [
|
||||
"text",
|
||||
"cobertura"
|
||||
],
|
||||
"collectCoverageFrom": [
|
||||
"src/**/*"
|
||||
],
|
||||
"moduleFileExtensions": [
|
||||
"ts",
|
||||
"tsx",
|
||||
"js"
|
||||
],
|
||||
"transform": {
|
||||
"^.+\\.(t|j)sx?$": "@swc/jest"
|
||||
},
|
||||
"setupFiles": [
|
||||
"jest-canvas-mock"
|
||||
],
|
||||
"testRegex": "/.*\\.test\\.(ts|tsx|js)$",
|
||||
"moduleNameMapper": {
|
||||
"\\.(css|less|sass|scss)$": "<rootDir>/../__mocks__/styleMock.js",
|
||||
"\\.(svg)$": "<rootDir>/../__mocks__/svgMock.js"
|
||||
},
|
||||
"setupFilesAfterEnv": [
|
||||
"<rootDir>/__tests__/jest.setup.js"
|
||||
],
|
||||
"snapshotFormat": {
|
||||
"escapeString": false,
|
||||
"printBasicPrototype": false
|
||||
}
|
||||
},
|
||||
"gitHead": "37d23b4a8eb1c663bc38e8dd9040889ea1526ec4"
|
||||
}
|
||||
140
packages/amis-formula/rollup.config.js
Normal file
140
packages/amis-formula/rollup.config.js
Normal file
@@ -0,0 +1,140 @@
|
||||
// rollup.config.js
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import json from '@rollup/plugin-json';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import license from 'rollup-plugin-license';
|
||||
import {
|
||||
name,
|
||||
version,
|
||||
main,
|
||||
module,
|
||||
author,
|
||||
dependencies
|
||||
} from './package.json';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
const settings = {
|
||||
globals: {}
|
||||
};
|
||||
|
||||
const pkgs = [];
|
||||
// 读取所有的node_modules目录,获取所有的包名
|
||||
[
|
||||
path.join(__dirname, './node_modules'),
|
||||
path.join(__dirname, '../../node_modules')
|
||||
].forEach(dir => {
|
||||
if (fs.existsSync(dir)) {
|
||||
fs.readdirSync(dir).forEach(item => {
|
||||
if (item.startsWith('.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.startsWith('@')) {
|
||||
fs.readdirSync(path.join(dir, item)).forEach(subItem => {
|
||||
pkgs.push(item + '/' + subItem);
|
||||
});
|
||||
}
|
||||
|
||||
return pkgs.push(item);
|
||||
});
|
||||
}
|
||||
});
|
||||
const external = id =>
|
||||
pkgs.some(pkg => id.startsWith(pkg) || ~id.indexOf(`node_modules/${pkg}`));
|
||||
|
||||
export default [
|
||||
{
|
||||
input: ['./src/index.ts'],
|
||||
output: [
|
||||
{
|
||||
...settings,
|
||||
dir: path.dirname(main),
|
||||
format: 'cjs',
|
||||
exports: 'named',
|
||||
preserveModulesRoot: './src',
|
||||
preserveModules: true // Keep directory structure and files
|
||||
}
|
||||
],
|
||||
external: external,
|
||||
plugins: getPlugins('cjs')
|
||||
},
|
||||
{
|
||||
input: ['./src/index.ts'],
|
||||
output: [
|
||||
{
|
||||
...settings,
|
||||
dir: path.dirname(module),
|
||||
format: 'esm',
|
||||
exports: 'named',
|
||||
preserveModulesRoot: './src',
|
||||
preserveModules: true // Keep directory structure and files
|
||||
}
|
||||
],
|
||||
external: external,
|
||||
plugins: getPlugins('esm')
|
||||
}
|
||||
];
|
||||
|
||||
function transpileDynamicImportForCJS(options) {
|
||||
return {
|
||||
name: 'transpile-dynamic-import-for-cjs',
|
||||
renderDynamicImport({format, targetModuleId}) {
|
||||
if (format !== 'cjs') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
left: 'Promise.resolve().then(function() {return new Promise(function(fullfill) {require([',
|
||||
right:
|
||||
', "tslib"], function(mod, tslib) {fullfill(tslib.__importStar(mod))})})})'
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getPlugins(format = 'esm') {
|
||||
const typeScriptOptions = {
|
||||
typescript: require('typescript'),
|
||||
sourceMap: false,
|
||||
outputToFilesystem: true,
|
||||
|
||||
...(format === 'esm'
|
||||
? {
|
||||
compilerOptions: {
|
||||
rootDir: './src',
|
||||
outDir: path.dirname(module)
|
||||
}
|
||||
}
|
||||
: {
|
||||
compilerOptions: {
|
||||
rootDir: './src',
|
||||
outDir: path.dirname(main)
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
return [
|
||||
transpileDynamicImportForCJS(),
|
||||
json(),
|
||||
resolve({
|
||||
jsnext: true,
|
||||
main: true,
|
||||
browser: true
|
||||
}),
|
||||
typescript(typeScriptOptions),
|
||||
commonjs({
|
||||
include: 'node_modules/**',
|
||||
extensions: ['.js'],
|
||||
ignoreGlobal: false,
|
||||
sourceMap: false
|
||||
}),
|
||||
license({
|
||||
banner: `
|
||||
${name} v${version}
|
||||
Copyright 2021<%= moment().format('YYYY') > 2021 ? '-' + moment().format('YYYY') : null %> ${author}
|
||||
`
|
||||
})
|
||||
];
|
||||
}
|
||||
5
packages/amis-formula/rollup.esm.config.js
Normal file
5
packages/amis-formula/rollup.esm.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
import config from "./rollup.config";
|
||||
|
||||
const esmConfig = config[1];
|
||||
|
||||
export default esmConfig;
|
||||
142
packages/amis-formula/scripts/genDoc.ts
Normal file
142
packages/amis-formula/scripts/genDoc.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import doctrine from 'doctrine';
|
||||
|
||||
const workDir = path.resolve(path.dirname(__dirname));
|
||||
const jsFile = path.join(workDir, 'src/evalutor.ts');
|
||||
const outputFile = path.join(workDir, 'src/doc.ts');
|
||||
const outputMD = path.join(workDir, 'src/doc.md');
|
||||
|
||||
function getFormulaComments(contents: string) {
|
||||
const comments: Array<{
|
||||
fnName: string;
|
||||
comments: string;
|
||||
}> = [];
|
||||
|
||||
contents.replace(/\/\*[\s\S]+?\*\//g, (_, index, input) => {
|
||||
const pos = index + _.length;
|
||||
const following = input.substring(pos, pos + 200);
|
||||
|
||||
if (/^\s*fn(\w+)\(/.test(following)) {
|
||||
comments.push({
|
||||
fnName: RegExp.$1,
|
||||
comments: _
|
||||
});
|
||||
}
|
||||
|
||||
return _;
|
||||
});
|
||||
|
||||
return comments;
|
||||
}
|
||||
|
||||
function formatType(tag: any): string {
|
||||
// console.log(tag);
|
||||
if (tag.type === 'RestType') {
|
||||
return `...${formatType(tag.expression)}`;
|
||||
} else if (tag.type === 'TypeApplication') {
|
||||
return `Array<${tag.applications
|
||||
.map((item: any) => formatType(item))
|
||||
.join(',')}>`;
|
||||
}
|
||||
|
||||
return tag.name;
|
||||
}
|
||||
|
||||
async function main(...params: Array<any>) {
|
||||
const contents = fs.readFileSync(jsFile, 'utf8');
|
||||
|
||||
const comments = getFormulaComments(contents);
|
||||
const result = comments.map(item => {
|
||||
const ast = doctrine.parse(item.comments, {
|
||||
unwrap: true
|
||||
});
|
||||
const result: any = {
|
||||
name: item.fnName,
|
||||
description: ast.description
|
||||
};
|
||||
|
||||
let example = '';
|
||||
let params: Array<any> = [];
|
||||
let returns: any = undefined;
|
||||
let namespace = '';
|
||||
ast.tags.forEach(tag => {
|
||||
if (tag.title === 'example') {
|
||||
example = tag.description!;
|
||||
} else if (tag.title === 'namespace') {
|
||||
namespace = tag.name!;
|
||||
} else if (tag.title === 'param') {
|
||||
params.push({
|
||||
type: formatType(tag.type),
|
||||
name: tag.name,
|
||||
description: tag.description
|
||||
});
|
||||
} else if (tag.title === 'returns') {
|
||||
returns = {
|
||||
type: formatType(tag.type),
|
||||
description: tag.description
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
result.example = example;
|
||||
result.params = params;
|
||||
result.returns = returns;
|
||||
result.namespace = namespace;
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
outputFile,
|
||||
`/**\n * 公式文档 请运行 \`npm run genDoc\` 自动生成\n */\n
|
||||
import {bulkRegisterFunctionDoc} from './function';
|
||||
|
||||
bulkRegisterFunctionDoc(${JSON.stringify(result, null, 2).replace(
|
||||
/\"(\w+)\"\:/g,
|
||||
(_, key) => `${key}:`
|
||||
)});
|
||||
`,
|
||||
'utf8'
|
||||
);
|
||||
console.log(`公式文档生成 > ${outputFile}`);
|
||||
|
||||
const grouped: any = {};
|
||||
result.forEach((item: any) => {
|
||||
const scope = item.namespace || '其他';
|
||||
const arr = grouped[scope] || (grouped[scope] = []);
|
||||
|
||||
arr.push(item);
|
||||
});
|
||||
|
||||
let md = '';
|
||||
Object.keys(grouped).forEach(key => {
|
||||
md += `## ${key}\n\n`;
|
||||
|
||||
grouped[key].forEach((item: any) => {
|
||||
md += `### ${item.name}\n\n`;
|
||||
|
||||
md += `用法:\`${item.example}\`\n\n`;
|
||||
|
||||
if (item.params.length) {
|
||||
// md += `参数:\n`;
|
||||
|
||||
item.params.forEach((param: any) => {
|
||||
md += ` * \`${param.name}:${param.type}\` ${param.description}\n`;
|
||||
});
|
||||
|
||||
if (item.returns) {
|
||||
md += `\n返回:\`${item.returns.type}\` ${
|
||||
item.returns.description || ''
|
||||
}\n\n`;
|
||||
}
|
||||
}
|
||||
|
||||
md += `${item.description}\n\n`;
|
||||
});
|
||||
});
|
||||
fs.writeFileSync(outputMD, md, 'utf8');
|
||||
console.log(`公式md生成 > ${outputMD}`);
|
||||
}
|
||||
|
||||
main().catch(e => console.error(e));
|
||||
55
packages/amis-formula/scripts/lib.ts
Normal file
55
packages/amis-formula/scripts/lib.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {parse, evaluate} from '../src';
|
||||
import moment from 'moment';
|
||||
|
||||
// 来自 https://vanillajstoolkit.com/polyfills/arrayfind/
|
||||
if (!Array.prototype.find) {
|
||||
Array.prototype.find = function (callback: any) {
|
||||
// 1. Let O be ? ToObject(this value).
|
||||
if (this == null) {
|
||||
throw new TypeError('"this" is null or not defined');
|
||||
}
|
||||
|
||||
var o = Object(this);
|
||||
|
||||
// 2. Let len be ? ToLength(? Get(O, "length")).
|
||||
var len = o.length >>> 0;
|
||||
|
||||
// 3. If IsCallable(callback) is false, throw a TypeError exception.
|
||||
if (typeof callback !== 'function') {
|
||||
throw new TypeError('callback must be a function');
|
||||
}
|
||||
|
||||
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
|
||||
var thisArg = arguments[1];
|
||||
|
||||
// 5. Let k be 0.
|
||||
var k = 0;
|
||||
|
||||
// 6. Repeat, while k < len
|
||||
while (k < len) {
|
||||
// a. Let Pk be ! ToString(k).
|
||||
// b. Let kValue be ? Get(O, Pk).
|
||||
// c. Let testResult be ToBoolean(? Call(callback, T, « kValue, k, O »)).
|
||||
// d. If testResult is true, return kValue.
|
||||
var kValue = o[k];
|
||||
if (callback.call(thisArg, kValue, k, o)) {
|
||||
return kValue;
|
||||
}
|
||||
// e. Increase k by 1.
|
||||
k++;
|
||||
}
|
||||
|
||||
// 7. Return undefined.
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export function momentFormat(
|
||||
input: any,
|
||||
inputFormat: string,
|
||||
outputFormat: string
|
||||
) {
|
||||
return moment(input, inputFormat).format(outputFormat);
|
||||
}
|
||||
|
||||
export {parse, evaluate, moment};
|
||||
1178
packages/amis-formula/src/doc.md
Normal file
1178
packages/amis-formula/src/doc.md
Normal file
File diff suppressed because it is too large
Load Diff
1975
packages/amis-formula/src/doc.ts
Normal file
1975
packages/amis-formula/src/doc.ts
Normal file
File diff suppressed because it is too large
Load Diff
10
packages/amis-formula/src/error.ts
Normal file
10
packages/amis-formula/src/error.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 表达式解析错误
|
||||
*/
|
||||
|
||||
export class FormulaEvalError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'FormulaEvalError';
|
||||
}
|
||||
}
|
||||
2494
packages/amis-formula/src/evalutor.ts
Normal file
2494
packages/amis-formula/src/evalutor.ts
Normal file
File diff suppressed because it is too large
Load Diff
655
packages/amis-formula/src/evalutorForAsync.ts
Normal file
655
packages/amis-formula/src/evalutorForAsync.ts
Normal file
@@ -0,0 +1,655 @@
|
||||
/**
|
||||
* @file 公式内置函数
|
||||
*/
|
||||
import {FilterContext} from './types';
|
||||
import {createObject, Evaluator, stripNumber} from './evalutor';
|
||||
import {FormulaEvalError} from './error';
|
||||
|
||||
export async function runSequence<T, U>(
|
||||
arr: Array<T>,
|
||||
fn: (item: T, index: number) => Promise<U>
|
||||
) {
|
||||
const result: Array<U> = [];
|
||||
|
||||
await arr.reduce(async (promise, item: T, index: number) => {
|
||||
await promise;
|
||||
result.push(await fn(item, index));
|
||||
}, Promise.resolve());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export class AsyncEvaluator extends (Evaluator as any) {
|
||||
constructor(data: any, options?: any) {
|
||||
super(data, options);
|
||||
}
|
||||
|
||||
async document(ast: {type: 'document'; body: Array<any>}) {
|
||||
if (!ast.body.length) {
|
||||
return undefined;
|
||||
}
|
||||
const isString = ast.body.length > 1;
|
||||
const content = await runSequence(ast.body, async item => {
|
||||
let result = this.evalute(item);
|
||||
|
||||
if (isString && result == null) {
|
||||
// 不要出现 undefined, null 之类的文案
|
||||
return '';
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
return content.length === 1 ? content[0] : content.join('');
|
||||
}
|
||||
|
||||
async filter(ast: {
|
||||
type: 'filter';
|
||||
input: any;
|
||||
filters: Array<{name: string; args: Array<any>}>;
|
||||
}) {
|
||||
let input = await this.evalute(ast.input);
|
||||
const filters = ast.filters.concat();
|
||||
const context: FilterContext = {
|
||||
filter: undefined,
|
||||
data: this.context,
|
||||
restFilters: filters
|
||||
};
|
||||
|
||||
while (filters.length) {
|
||||
const filter = filters.shift()!;
|
||||
const fn = this.filters[filter.name];
|
||||
|
||||
if (!fn) {
|
||||
throw new Error(`filter \`${filter.name}\` not exists.`);
|
||||
}
|
||||
context.filter = filter;
|
||||
|
||||
const argsRes = await runSequence(filter.args, async item => {
|
||||
if (item?.type === 'mixed') {
|
||||
const res = await runSequence(item.body, item =>
|
||||
typeof item === 'string' ? item : this.evalute(item)
|
||||
);
|
||||
|
||||
return res.join('');
|
||||
} else if (item.type) {
|
||||
return this.evalute(item);
|
||||
}
|
||||
return item;
|
||||
});
|
||||
|
||||
input = fn.apply(context, [input].concat(argsRes));
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
async template(ast: {type: 'template'; body: Array<any>}) {
|
||||
const args = await runSequence(ast.body, arg => this.evalute(arg));
|
||||
return args.join('');
|
||||
}
|
||||
|
||||
// 下标获取
|
||||
async getter(ast: {host: any; key: any}) {
|
||||
const host = await this.evalute(ast.host);
|
||||
let key = await this.evalute(ast.key);
|
||||
if (typeof key === 'undefined' && ast.key?.type === 'variable') {
|
||||
key = ast.key.name;
|
||||
}
|
||||
return host?.[key];
|
||||
}
|
||||
|
||||
// 位操作如 +2 ~3 !
|
||||
async unary(ast: {op: '+' | '-' | '~' | '!'; value: any}) {
|
||||
let value = await this.evalute(ast.value);
|
||||
|
||||
switch (ast.op) {
|
||||
case '+':
|
||||
return +value;
|
||||
case '-':
|
||||
return -value;
|
||||
case '~':
|
||||
return ~value;
|
||||
case '!':
|
||||
return !value;
|
||||
}
|
||||
}
|
||||
|
||||
async power(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
return Math.pow(this.formatNumber(left), this.formatNumber(right));
|
||||
}
|
||||
|
||||
async multiply(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
return stripNumber(this.formatNumber(left) * this.formatNumber(right));
|
||||
}
|
||||
|
||||
async divide(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
return stripNumber(this.formatNumber(left) / this.formatNumber(right));
|
||||
}
|
||||
|
||||
async remainder(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
return this.formatNumber(left) % this.formatNumber(right);
|
||||
}
|
||||
|
||||
async add(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
// 如果有一个不是数字就变成字符串拼接
|
||||
if (isNaN(left) || isNaN(right)) {
|
||||
return left + right;
|
||||
}
|
||||
return stripNumber(this.formatNumber(left) + this.formatNumber(right));
|
||||
}
|
||||
|
||||
async minus(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
return stripNumber(this.formatNumber(left) - this.formatNumber(right));
|
||||
}
|
||||
|
||||
async shift(ast: {op: '<<' | '>>' | '>>>'; left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.formatNumber(this.evalute(ast.right), true);
|
||||
|
||||
if (ast.op === '<<') {
|
||||
return left << right;
|
||||
} else if (ast.op == '>>') {
|
||||
return left >> right;
|
||||
} else {
|
||||
return left >>> right;
|
||||
}
|
||||
}
|
||||
|
||||
async lt(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left < right;
|
||||
}
|
||||
|
||||
async gt(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
return left > right;
|
||||
}
|
||||
|
||||
async le(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left <= right;
|
||||
}
|
||||
|
||||
async ge(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left >= right;
|
||||
}
|
||||
|
||||
async eq(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left == right;
|
||||
}
|
||||
|
||||
async ne(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left != right;
|
||||
}
|
||||
|
||||
async streq(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left === right;
|
||||
}
|
||||
|
||||
async strneq(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
// todo 如果是日期的对比,这个地方可以优化一下。
|
||||
|
||||
return left !== right;
|
||||
}
|
||||
|
||||
async binary(ast: {op: '&' | '^' | '|'; left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
const right = await this.evalute(ast.right);
|
||||
|
||||
if (ast.op === '&') {
|
||||
return left & right;
|
||||
} else if (ast.op === '^') {
|
||||
return left ^ right;
|
||||
} else {
|
||||
return left | right;
|
||||
}
|
||||
}
|
||||
|
||||
async and(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
return left && this.evalute(ast.right);
|
||||
}
|
||||
|
||||
async or(ast: {left: any; right: any}) {
|
||||
const left = await this.evalute(ast.left);
|
||||
return left || this.evalute(ast.right);
|
||||
}
|
||||
|
||||
array(ast: {type: 'array'; members: Array<any>}) {
|
||||
return runSequence(ast.members, member => this.evalute(member));
|
||||
}
|
||||
|
||||
async object(ast: {members: Array<{key: string; value: any}>}) {
|
||||
let object: any = {};
|
||||
await ast.members.reduce(
|
||||
async (promise: any, {key, value}: any, index: number) => {
|
||||
await promise;
|
||||
const objKey = await this.evalute(key);
|
||||
const objVal = await this.evalute(value);
|
||||
object[objKey] = objVal;
|
||||
},
|
||||
Promise.resolve()
|
||||
);
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
async conditional(ast: {
|
||||
type: 'conditional';
|
||||
test: any;
|
||||
consequent: any;
|
||||
alternate: any;
|
||||
}) {
|
||||
return (await this.evalute(ast.test))
|
||||
? await this.evalute(ast.consequent)
|
||||
: await this.evalute(ast.alternate);
|
||||
}
|
||||
|
||||
async funcCall(this: any, ast: {identifier: string; args: Array<any>}) {
|
||||
const fnName = `fn${ast.identifier}`;
|
||||
const fn =
|
||||
this.functions[fnName] ||
|
||||
this[fnName] ||
|
||||
(this.filters.hasOwnProperty(ast.identifier) &&
|
||||
this.filters[ast.identifier]);
|
||||
|
||||
if (!fn) {
|
||||
throw new FormulaEvalError(`${ast.identifier}函数没有定义`);
|
||||
}
|
||||
|
||||
let args: Array<any> = ast.args;
|
||||
|
||||
// 逻辑函数特殊处理,因为有时候有些运算是可以跳过的。
|
||||
if (~['IF', 'AND', 'OR', 'XOR', 'IFS'].indexOf(ast.identifier)) {
|
||||
args = args.map(a => () => this.evalute(a));
|
||||
} else {
|
||||
args = await runSequence(args, a => this.evalute(a));
|
||||
}
|
||||
|
||||
return fn.apply(this, args);
|
||||
}
|
||||
|
||||
async callAnonymousFunction(
|
||||
ast: {
|
||||
args: any[];
|
||||
return: any;
|
||||
},
|
||||
args: Array<any>
|
||||
) {
|
||||
const ctx: any = createObject(
|
||||
this.contextStack[this.contextStack.length - 1]('&') || {},
|
||||
{}
|
||||
);
|
||||
ast.args.forEach((arg: any) => {
|
||||
if (arg.type !== 'variable') {
|
||||
throw new Error('expected a variable as argument');
|
||||
}
|
||||
ctx[arg.name] = args.shift();
|
||||
});
|
||||
this.contextStack.push((varName: string) =>
|
||||
varName === '&' ? ctx : ctx[varName]
|
||||
);
|
||||
const result = await this.evalute(ast.return);
|
||||
this.contextStack.pop();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 示例:IF(A, B, C)
|
||||
*
|
||||
* 如果满足条件A,则返回B,否则返回C,支持多层嵌套IF函数。
|
||||
*
|
||||
* 也可以用表达式如:A ? B : C
|
||||
*
|
||||
* @example IF(condition, consequent, alternate)
|
||||
* @param {expression} condition - 条件表达式.
|
||||
* @param {any} consequent 条件判断通过的返回结果
|
||||
* @param {any} alternate 条件判断不通过的返回结果
|
||||
* @namespace 逻辑函数
|
||||
*
|
||||
* @returns {any} 根据条件返回不同的结果
|
||||
*/
|
||||
async fnIF(
|
||||
condition: () => any,
|
||||
trueValue: () => any,
|
||||
falseValue: () => any
|
||||
) {
|
||||
return (await condition()) ? await trueValue() : await falseValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 条件全部符合,返回 true,否则返回 false
|
||||
*
|
||||
* 示例:AND(语文成绩>80, 数学成绩>80)
|
||||
*
|
||||
* 语文成绩和数学成绩都大于 80,则返回 true,否则返回 false
|
||||
*
|
||||
* 也可以直接用表达式如:语文成绩>80 && 数学成绩>80
|
||||
*
|
||||
* @example AND(expression1, expression2, ...expressionN)
|
||||
* @param {...expression} conditions - 条件表达式.
|
||||
* @namespace 逻辑函数
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
async fnAND(...condtions: Array<() => any>) {
|
||||
if (!condtions.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return condtions.reduce(async (promise, c) => {
|
||||
const result = await promise;
|
||||
if (result) {
|
||||
return c();
|
||||
}
|
||||
return result;
|
||||
}, Promise.resolve(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* 条件任意一个满足条件,返回 true,否则返回 false
|
||||
*
|
||||
* 示例:OR(语文成绩>80, 数学成绩>80)
|
||||
*
|
||||
* 语文成绩和数学成绩任意一个大于 80,则返回 true,否则返回 false
|
||||
*
|
||||
* 也可以直接用表达式如:语文成绩>80 || 数学成绩>80
|
||||
*
|
||||
* @example OR(expression1, expression2, ...expressionN)
|
||||
* @param {...expression} conditions - 条件表达式.
|
||||
* @namespace 逻辑函数
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
async fnOR(...condtions: Array<() => any>) {
|
||||
if (!condtions.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return condtions.reduce(async (promise, c) => {
|
||||
const result = await promise;
|
||||
if (result) {
|
||||
return true;
|
||||
}
|
||||
return c();
|
||||
}, Promise.resolve(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* 异或处理,多个表达式组中存在奇数个真时认为真。
|
||||
*
|
||||
* @example XOR(condition1, condition2)
|
||||
* @param {expression} condition1 - 条件表达式1
|
||||
* @param {expression} condition2 - 条件表达式2
|
||||
* @namespace 逻辑函数
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
async fnXOR(...condtions: Array<() => any>) {
|
||||
if (!condtions.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !!(
|
||||
(await runSequence(condtions, c => c())).filter(item => item).length % 2
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断函数集合,相当于多个 else if 合并成一个。
|
||||
*
|
||||
* 示例:IFS(语文成绩 > 80, "优秀", 语文成绩 > 60, "良", "继续努力")
|
||||
*
|
||||
* 如果语文成绩大于 80,则返回优秀,否则判断大于 60 分,则返回良,否则返回继续努力。
|
||||
*
|
||||
* @example IFS(condition1, result1, condition2, result2,...conditionN, resultN)
|
||||
* @param {...any} args - 条件,返回值集合
|
||||
* @namespace 逻辑函数
|
||||
* @returns {any} 第一个满足条件的结果,没有命中的返回 false。
|
||||
*/
|
||||
async fnIFS(...args: Array<() => any>) {
|
||||
if (args.length % 2) {
|
||||
args.splice(args.length - 1, 0, () => true);
|
||||
}
|
||||
|
||||
while (args.length) {
|
||||
const c = args.shift()!;
|
||||
const v = args.shift()!;
|
||||
|
||||
if (await c()) {
|
||||
return await v();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数组做数据转换,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYMAP(arr, item => item)
|
||||
* @returns {boolean} 结果
|
||||
*/
|
||||
fnARRAYMAP(value: any, iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
return (Array.isArray(value) ? value : []).reduce(
|
||||
async (promise, item, index) => {
|
||||
const arr = await promise;
|
||||
arr.push(await this.callAnonymousFunction(iterator, [item, index]));
|
||||
return arr;
|
||||
},
|
||||
Promise.resolve([])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据做数据过滤,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
* 将第二个箭头函数返回为 false 的成员过滤掉。
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYFILTER(arr, item => item)
|
||||
* @returns {boolean} 结果
|
||||
*/
|
||||
async fnARRAYFILTER(value: any, iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
return await (Array.isArray(value) ? value : []).reduce(
|
||||
async (promise, item, index) => {
|
||||
let arr = await promise;
|
||||
const hit = await this.callAnonymousFunction(iterator, [item, index]);
|
||||
|
||||
if (hit) {
|
||||
arr.push(item);
|
||||
}
|
||||
|
||||
return arr;
|
||||
},
|
||||
Promise.resolve([])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据做数据查找,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
* 找出第二个箭头函数返回为 true 的成员的索引。
|
||||
*
|
||||
* 示例:
|
||||
*
|
||||
* ARRAYFINDINDEX([0, 2, false], item => item === 2) 得到 1
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYFINDINDEX(arr, item => item === 2)
|
||||
* @returns {number} 结果
|
||||
*/
|
||||
async fnARRAYFINDINDEX(arr: any[], iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
let hitIndex = -1;
|
||||
const items = Array.isArray(arr) ? arr : [];
|
||||
|
||||
for (const [index, item] of items.entries()) {
|
||||
const hit = await this.callAnonymousFunction(iterator, [item, index]);
|
||||
if (hit) {
|
||||
hitIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return hitIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据做数据查找,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
* 找出第二个箭头函数返回为 true 的成员。
|
||||
*
|
||||
* 示例:
|
||||
*
|
||||
* ARRAYFIND([0, 2, false], item => item === 2) 得到 2
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYFIND(arr, item => item === 2)
|
||||
* @returns {any} 结果
|
||||
*/
|
||||
async fnARRAYFIND(arr: any[], iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
let hitItem = undefined;
|
||||
const items = Array.isArray(arr) ? arr : [];
|
||||
|
||||
for (const [index, item] of items.entries()) {
|
||||
const hit = await this.callAnonymousFunction(iterator, [item, index]);
|
||||
if (hit) {
|
||||
hitItem = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return hitItem;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据做数据遍历判断,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
* 判断第二个箭头函数是否存在返回为 true 的成员。
|
||||
*
|
||||
* 示例:
|
||||
*
|
||||
* ARRAYSOME([0, 2, false], item => item === 2) 得到 true
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYSOME(arr, item => item === 2)
|
||||
* @returns {boolean} 结果
|
||||
*/
|
||||
async fnARRAYSOME(arr: any[], iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
let result = await (Array.isArray(arr) ? arr : []).reduce(
|
||||
async (promise: any, item: any, index: number) => {
|
||||
const prev = await promise;
|
||||
const hit = await this.callAnonymousFunction(iterator, [item, index]);
|
||||
return prev || hit;
|
||||
},
|
||||
Promise.resolve(false)
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据做数据遍历判断,需要搭配箭头函数一起使用,注意箭头函数只支持单表达式用法。
|
||||
* 判断第二个箭头函数返回是否都为 true。
|
||||
*
|
||||
* 示例:
|
||||
*
|
||||
* ARRAYEVERY([0, 2, false], item => item === 2) 得到 false
|
||||
*
|
||||
* @param {Array<any>} arr 数组
|
||||
* @param {Function<any>} iterator 箭头函数
|
||||
* @namespace 数组
|
||||
* @example ARRAYEVERY(arr, item => item === 2)
|
||||
* @returns {boolean} 结果
|
||||
*/
|
||||
async fnARRAYEVERY(arr: any[], iterator: any) {
|
||||
if (!iterator || iterator.type !== 'anonymous_function') {
|
||||
throw new Error('expected an anonymous function get ' + iterator);
|
||||
}
|
||||
|
||||
let result = await (Array.isArray(arr) ? arr : []).reduce(
|
||||
async (promise: any, item: any, index: number) => {
|
||||
const prev = await promise;
|
||||
const hit = await this.callAnonymousFunction(iterator, [item, index]);
|
||||
|
||||
return prev && hit;
|
||||
},
|
||||
Promise.resolve(true)
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
46
packages/amis-formula/src/filter.ts
Normal file
46
packages/amis-formula/src/filter.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import {Evaluator} from './evalutor';
|
||||
import {FilterMap} from './types';
|
||||
|
||||
const entityMap: any = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/'
|
||||
};
|
||||
const escapeHtml = (str: string) =>
|
||||
String(str).replace(/[&<>"'\/]/g, function (s) {
|
||||
return entityMap[s];
|
||||
});
|
||||
|
||||
/**
|
||||
* filter 是历史包袱,不建议使用。因为这是之前的语法,所以在公式解析里面做了兼容。
|
||||
* 建议用 ${ LEFT(xxx) } 这种函数调用语法。
|
||||
*/
|
||||
export const filters: FilterMap = {
|
||||
raw: input => input,
|
||||
html: (input: string) => {
|
||||
if (input == null) {
|
||||
return input;
|
||||
}
|
||||
return escapeHtml(input);
|
||||
}
|
||||
};
|
||||
|
||||
export function registerFilter(
|
||||
name: string,
|
||||
fn: (input: any, ...args: any[]) => any
|
||||
): void {
|
||||
filters[name] = fn;
|
||||
Evaluator.extendDefaultFilters(filters);
|
||||
}
|
||||
|
||||
export function extendsFilters(value: FilterMap) {
|
||||
Object.assign(filters, value);
|
||||
Evaluator.extendDefaultFilters(filters);
|
||||
}
|
||||
|
||||
export function getFilters() {
|
||||
return filters;
|
||||
}
|
||||
56
packages/amis-formula/src/function.ts
Normal file
56
packages/amis-formula/src/function.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import {Evaluator} from './evalutor';
|
||||
import {FunctionDocMap, FunctionDocItem} from './types';
|
||||
|
||||
export function registerFunction(
|
||||
name: string,
|
||||
fn: (this: Evaluator, ...args: Array<any>) => any
|
||||
): void {
|
||||
Evaluator.extendDefaultFunctions({
|
||||
[`fn${name}`]: fn
|
||||
});
|
||||
}
|
||||
|
||||
export const functionDocs: FunctionDocMap = {};
|
||||
|
||||
export function registerFunctionDoc(groupName: string, item: FunctionDocItem) {
|
||||
if (functionDocs[groupName]) {
|
||||
functionDocs[groupName].push(item);
|
||||
} else {
|
||||
functionDocs[groupName] = [item];
|
||||
}
|
||||
}
|
||||
|
||||
export function bulkRegisterFunctionDoc(
|
||||
fnDocs: {
|
||||
name: string;
|
||||
description: string;
|
||||
example: string;
|
||||
params: {
|
||||
type: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
}[];
|
||||
returns: {
|
||||
type: string;
|
||||
description: string | null;
|
||||
};
|
||||
namespace: string;
|
||||
}[]
|
||||
) {
|
||||
fnDocs.forEach(item => registerFunctionDoc(item.namespace || 'Others', item));
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册公式,并同时注册公式说明
|
||||
* @param name
|
||||
* @param fn
|
||||
* @param fnInfo
|
||||
*/
|
||||
export function registerFormula(
|
||||
name: string,
|
||||
fn: (this: Evaluator, ...args: Array<any>) => any,
|
||||
fnInfo?: FunctionDocItem
|
||||
) {
|
||||
registerFunction(name, fn);
|
||||
fnInfo && registerFunctionDoc(fnInfo.namespace || 'Others', fnInfo);
|
||||
}
|
||||
71
packages/amis-formula/src/index.ts
Normal file
71
packages/amis-formula/src/index.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import {Evaluator} from './evalutor';
|
||||
import {AsyncEvaluator} from './evalutorForAsync';
|
||||
import {parse} from './parser';
|
||||
import {lexer} from './lexer';
|
||||
import {registerFilter, filters, getFilters, extendsFilters} from './filter';
|
||||
import {
|
||||
registerFunction,
|
||||
registerFunctionDoc,
|
||||
functionDocs,
|
||||
registerFormula
|
||||
} from './function';
|
||||
import type {
|
||||
FilterContext,
|
||||
ASTNode,
|
||||
ParserOptions,
|
||||
EvaluatorOptions
|
||||
} from './types';
|
||||
export {
|
||||
parse,
|
||||
lexer,
|
||||
Evaluator,
|
||||
AsyncEvaluator,
|
||||
FilterContext,
|
||||
filters,
|
||||
getFilters,
|
||||
registerFilter,
|
||||
registerFormula,
|
||||
registerFunction,
|
||||
registerFunctionDoc,
|
||||
extendsFilters
|
||||
};
|
||||
|
||||
export * from './types';
|
||||
|
||||
export function evaluate(
|
||||
astOrString: string | ASTNode,
|
||||
data: any,
|
||||
options?: ParserOptions & EvaluatorOptions
|
||||
) {
|
||||
let ast: ASTNode = astOrString as ASTNode;
|
||||
if (typeof astOrString === 'string') {
|
||||
ast = parse(astOrString, options);
|
||||
}
|
||||
|
||||
return new Evaluator(data, options).evalute(ast);
|
||||
}
|
||||
|
||||
export async function evaluateForAsync(
|
||||
astOrString: string | ASTNode,
|
||||
data: any,
|
||||
options?: ParserOptions & EvaluatorOptions
|
||||
) {
|
||||
let ast: ASTNode = astOrString as ASTNode;
|
||||
if (typeof astOrString === 'string') {
|
||||
ast = parse(astOrString, options);
|
||||
}
|
||||
|
||||
return new AsyncEvaluator(data, options).evalute(ast);
|
||||
}
|
||||
|
||||
Evaluator.extendDefaultFilters(getFilters());
|
||||
AsyncEvaluator.setDefaultFilters(getFilters());
|
||||
|
||||
export async function getFunctionsDoc() {
|
||||
await import('./doc');
|
||||
|
||||
return Object.entries(functionDocs).map(([k, items]) => ({
|
||||
groupName: k,
|
||||
items
|
||||
}));
|
||||
}
|
||||
812
packages/amis-formula/src/lexer.ts
Normal file
812
packages/amis-formula/src/lexer.ts
Normal file
@@ -0,0 +1,812 @@
|
||||
import {getFilters} from './filter';
|
||||
import {LexerOptions, Token, TokenTypeName} from './types';
|
||||
|
||||
export const enum TokenEnum {
|
||||
BooleanLiteral = 1,
|
||||
RAW,
|
||||
Variable,
|
||||
OpenScript,
|
||||
CloseScript,
|
||||
EOF,
|
||||
Identifier,
|
||||
Literal,
|
||||
NumericLiteral,
|
||||
Punctuator,
|
||||
StringLiteral,
|
||||
RegularExpression,
|
||||
TemplateRaw,
|
||||
TemplateLeftBrace,
|
||||
TemplateRightBrace,
|
||||
OpenFilter,
|
||||
Char
|
||||
}
|
||||
|
||||
export const TokenName: {
|
||||
[propName: string]: TokenTypeName;
|
||||
} = {};
|
||||
TokenName[TokenEnum.BooleanLiteral] = 'Boolean';
|
||||
TokenName[TokenEnum.RAW] = 'Raw';
|
||||
TokenName[TokenEnum.Variable] = 'Variable';
|
||||
TokenName[TokenEnum.OpenScript] = 'OpenScript';
|
||||
TokenName[TokenEnum.CloseScript] = 'CloseScript';
|
||||
TokenName[TokenEnum.EOF] = 'EOF';
|
||||
TokenName[TokenEnum.Identifier] = 'Identifier';
|
||||
TokenName[TokenEnum.Literal] = 'Literal';
|
||||
TokenName[TokenEnum.NumericLiteral] = 'Numeric';
|
||||
TokenName[TokenEnum.Punctuator] = 'Punctuator';
|
||||
TokenName[TokenEnum.StringLiteral] = 'String';
|
||||
TokenName[TokenEnum.RegularExpression] = 'RegularExpression';
|
||||
TokenName[TokenEnum.TemplateRaw] = 'TemplateRaw';
|
||||
TokenName[TokenEnum.TemplateLeftBrace] = 'TemplateLeftBrace';
|
||||
TokenName[TokenEnum.TemplateRightBrace] = 'TemplateRightBrace';
|
||||
TokenName[TokenEnum.OpenFilter] = 'OpenFilter';
|
||||
TokenName[TokenEnum.Char] = 'Char';
|
||||
|
||||
const mainStates = {
|
||||
START: 0,
|
||||
SCRIPT: 1,
|
||||
EXPRESSION: 2,
|
||||
BLOCK: 3,
|
||||
Template: 4,
|
||||
Filter: 5
|
||||
};
|
||||
|
||||
const rawStates = {
|
||||
START: 0,
|
||||
ESCAPE: 1
|
||||
};
|
||||
|
||||
const numberStates = {
|
||||
START: 0,
|
||||
ZERO: 1,
|
||||
DIGIT: 2,
|
||||
POINT: 3,
|
||||
DIGIT_FRACTION: 4,
|
||||
EXP: 5
|
||||
};
|
||||
|
||||
const stringStates = {
|
||||
START: 0,
|
||||
START_QUOTE_OR_CHAR: 1,
|
||||
ESCAPE: 2
|
||||
};
|
||||
|
||||
const filterStates = {
|
||||
START: 0,
|
||||
Func: 1,
|
||||
SEP: 2,
|
||||
ESCAPE: 3
|
||||
};
|
||||
|
||||
const punctuatorList = [
|
||||
'===',
|
||||
'!==',
|
||||
'>>>',
|
||||
'==',
|
||||
'!=',
|
||||
'<>',
|
||||
'<=',
|
||||
'>=',
|
||||
'||',
|
||||
'&&',
|
||||
'++',
|
||||
'--',
|
||||
'<<',
|
||||
'>>',
|
||||
'**',
|
||||
'+=',
|
||||
'*=',
|
||||
'/=',
|
||||
'<',
|
||||
'>',
|
||||
'=',
|
||||
'*',
|
||||
'/',
|
||||
'-',
|
||||
'+',
|
||||
'^',
|
||||
'!',
|
||||
'~',
|
||||
'%',
|
||||
'&',
|
||||
'|',
|
||||
'(',
|
||||
')',
|
||||
'[',
|
||||
']',
|
||||
'{',
|
||||
'}',
|
||||
'?',
|
||||
':',
|
||||
';',
|
||||
',',
|
||||
'.',
|
||||
'$'
|
||||
];
|
||||
|
||||
const escapes = {
|
||||
'"': 0, // Quotation mask
|
||||
'\\': 1, // Reverse solidus
|
||||
'/': 2, // Solidus
|
||||
'b': 3, // Backspace
|
||||
'f': 4, // Form feed
|
||||
'n': 5, // New line
|
||||
'r': 6, // Carriage return
|
||||
't': 7, // Horizontal tab
|
||||
'u': 8 // 4 hexadecimal digits
|
||||
};
|
||||
|
||||
function isDigit1to9(char: string) {
|
||||
return char >= '1' && char <= '9';
|
||||
}
|
||||
|
||||
function isDigit(char: string) {
|
||||
return char >= '0' && char <= '9';
|
||||
}
|
||||
|
||||
function isExp(char: string) {
|
||||
return char === 'e' || char === 'E';
|
||||
}
|
||||
|
||||
function escapeString(text: string, allowedLetter: Array<string> = []) {
|
||||
return text.replace(/\\(.)/g, function (_, text) {
|
||||
return text === 'b'
|
||||
? '\b'
|
||||
: text === 'f'
|
||||
? '\f'
|
||||
: text === 'n'
|
||||
? '\n'
|
||||
: text === 'r'
|
||||
? '\r'
|
||||
: text === 't'
|
||||
? '\t'
|
||||
: text === 'v'
|
||||
? '\v'
|
||||
: text === '\\'
|
||||
? '\\'
|
||||
: text === '/'
|
||||
? '/'
|
||||
: ~allowedLetter.indexOf(text)
|
||||
? text
|
||||
: _;
|
||||
});
|
||||
}
|
||||
|
||||
function formatNumber(value: string) {
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
export function lexer(input: string, options: LexerOptions = {}) {
|
||||
let line = 1;
|
||||
let column = 1;
|
||||
let index = 0;
|
||||
let mainState = mainStates.START;
|
||||
const states: Array<any> = [mainState];
|
||||
let tokenCache: Array<Token> = [];
|
||||
options = {...options};
|
||||
const allowFilter = options.allowFilter !== false;
|
||||
|
||||
if (!options.isFilter) {
|
||||
const filterKeys = Object.keys(getFilters());
|
||||
if ((options as any).filters) {
|
||||
filterKeys.push(...Object.keys((options as any).filters));
|
||||
}
|
||||
options.isFilter = (name: string) => filterKeys.includes(name);
|
||||
}
|
||||
|
||||
if (options.evalMode || options.variableMode) {
|
||||
pushState(mainStates.EXPRESSION);
|
||||
}
|
||||
|
||||
function pushState(state: any) {
|
||||
states.push((mainState = state));
|
||||
}
|
||||
function popState() {
|
||||
states.pop();
|
||||
mainState = states[states.length - 1];
|
||||
}
|
||||
|
||||
function position(value?: string) {
|
||||
if (value && typeof value === 'string') {
|
||||
const lines = value.split(/[\r\n]+/);
|
||||
return {
|
||||
index: index + value.length,
|
||||
line: line + lines.length - 1,
|
||||
column: column + lines[lines.length - 1].length
|
||||
};
|
||||
}
|
||||
|
||||
return {index: index, line, column};
|
||||
}
|
||||
|
||||
function eof(): Token | void | null {
|
||||
if (index >= input.length) {
|
||||
return {
|
||||
type: TokenName[TokenEnum.EOF],
|
||||
value: undefined,
|
||||
start: position(),
|
||||
end: position()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function raw(): Token | void | null {
|
||||
if (mainState !== mainStates.START) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let buffer = '';
|
||||
let state = rawStates.START;
|
||||
let i = index;
|
||||
|
||||
while (i < input.length) {
|
||||
const ch = input[i];
|
||||
|
||||
if (state === rawStates.ESCAPE) {
|
||||
if (escapes.hasOwnProperty(ch) || ch === '$') {
|
||||
buffer += ch;
|
||||
i++;
|
||||
state = rawStates.START;
|
||||
} else {
|
||||
const pos = position(buffer + ch);
|
||||
throw new SyntaxError(
|
||||
`Unexpected token ${ch} in ${pos.line}:${pos.column}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (ch === '\\') {
|
||||
buffer += ch;
|
||||
i++;
|
||||
state = rawStates.ESCAPE;
|
||||
continue;
|
||||
} else if (ch === '$') {
|
||||
const nextCh = input[i + 1];
|
||||
if (nextCh === '{') {
|
||||
break;
|
||||
} else if (nextCh === '$') {
|
||||
// $$ 用法兼容
|
||||
tokenCache.push({
|
||||
type: TokenName[TokenEnum.Variable],
|
||||
value: '&',
|
||||
raw: '$$',
|
||||
start: position(input.substring(index, i)),
|
||||
end: position(input.substring(index, i + 2))
|
||||
});
|
||||
break;
|
||||
} else {
|
||||
// 支持旧的 $varName 的取值方法
|
||||
const match = /^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*/.exec(
|
||||
input.substring(i + 1)
|
||||
);
|
||||
if (match) {
|
||||
tokenCache.push({
|
||||
type: TokenName[TokenEnum.Variable],
|
||||
value: match[0],
|
||||
raw: match[0],
|
||||
start: position(input.substring(index, i)),
|
||||
end: position(input.substring(index, i + 1 + match[0].length))
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
i++;
|
||||
buffer += ch;
|
||||
}
|
||||
}
|
||||
|
||||
if (i > index) {
|
||||
return {
|
||||
type: TokenName[TokenEnum.RAW],
|
||||
value: escapeString(buffer, ['`', '$']),
|
||||
raw: buffer,
|
||||
start: position(),
|
||||
end: position(buffer)
|
||||
};
|
||||
}
|
||||
return tokenCache.length ? tokenCache.shift() : null;
|
||||
}
|
||||
|
||||
function openScript() {
|
||||
if (
|
||||
mainState === mainStates.Template ||
|
||||
mainState === mainStates.EXPRESSION
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ch = input[index];
|
||||
if (ch === '$') {
|
||||
const nextCh = input[index + 1];
|
||||
if (nextCh === '{') {
|
||||
pushState(mainStates.SCRIPT);
|
||||
const value = input.substring(index, index + 2);
|
||||
return {
|
||||
type: TokenName[TokenEnum.OpenScript],
|
||||
value,
|
||||
start: position(),
|
||||
end: position(value)
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function expression() {
|
||||
if (
|
||||
mainState !== mainStates.SCRIPT &&
|
||||
mainState !== mainStates.EXPRESSION &&
|
||||
mainState !== mainStates.BLOCK &&
|
||||
mainState !== mainStates.Filter
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const token =
|
||||
literal() ||
|
||||
identifier() ||
|
||||
numberLiteral() ||
|
||||
stringLiteral() ||
|
||||
punctuator() ||
|
||||
char();
|
||||
|
||||
if (token?.value === '{' && token.type == 'Punctuator') {
|
||||
pushState(mainStates.BLOCK);
|
||||
} else if (token?.value === '}' && token.type == 'Punctuator') {
|
||||
if (mainState === mainStates.Filter) {
|
||||
popState();
|
||||
}
|
||||
|
||||
const prevState = mainState;
|
||||
popState();
|
||||
|
||||
if (
|
||||
prevState === mainStates.SCRIPT ||
|
||||
prevState === mainStates.EXPRESSION
|
||||
) {
|
||||
return {
|
||||
type: TokenName[
|
||||
prevState === mainStates.EXPRESSION
|
||||
? TokenEnum.TemplateRightBrace
|
||||
: TokenEnum.CloseScript
|
||||
],
|
||||
value: token!.value,
|
||||
start: position(),
|
||||
end: position(token!.value)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// filter 过滤器部分需要特殊处理
|
||||
if (
|
||||
mainState === mainStates.SCRIPT &&
|
||||
token?.type == 'Punctuator' &&
|
||||
token.value === '|' &&
|
||||
allowFilter
|
||||
) {
|
||||
// 怎么区分是过滤还是位运算呢?
|
||||
// 靠外面反馈吧
|
||||
if (options?.isFilter) {
|
||||
const restInput = input.substring(token.start.index + 1).trim();
|
||||
const m = /^[A-Za-z0-9_$@][A-Za-z0-9_\-$@]*/.exec(restInput);
|
||||
if (!m || !options.isFilter(m[0])) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
pushState(mainStates.Filter);
|
||||
return {
|
||||
type: TokenName[TokenEnum.OpenFilter],
|
||||
value: '|',
|
||||
start: position(),
|
||||
end: position('|')
|
||||
};
|
||||
} else if (
|
||||
mainState === mainStates.Filter &&
|
||||
token?.value === '|' &&
|
||||
token.type == 'Punctuator'
|
||||
) {
|
||||
return {
|
||||
type: TokenName[TokenEnum.OpenFilter],
|
||||
value: '|',
|
||||
start: position(),
|
||||
end: position('|')
|
||||
};
|
||||
}
|
||||
|
||||
if (!token && input[index] === '`') {
|
||||
pushState(mainStates.Template);
|
||||
return {
|
||||
type: TokenName[TokenEnum.Punctuator],
|
||||
value: '`',
|
||||
start: position(),
|
||||
end: position('`')
|
||||
};
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
function char() {
|
||||
if (mainState !== mainStates.Filter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let i = index;
|
||||
let ch = input[i];
|
||||
if (ch === '\\') {
|
||||
const nextCh = input[i + 1];
|
||||
|
||||
if (
|
||||
nextCh === '$' ||
|
||||
~punctuatorList.indexOf(nextCh) ||
|
||||
escapes.hasOwnProperty(nextCh)
|
||||
) {
|
||||
i++;
|
||||
ch =
|
||||
nextCh === 'b'
|
||||
? '\b'
|
||||
: nextCh === 'f'
|
||||
? '\f'
|
||||
: nextCh === 'n'
|
||||
? '\n'
|
||||
: nextCh === 'r'
|
||||
? '\r'
|
||||
: nextCh === 't'
|
||||
? '\t'
|
||||
: nextCh === 'v'
|
||||
? '\v'
|
||||
: nextCh;
|
||||
} else {
|
||||
const pos = position(input.substring(index, index + 2));
|
||||
throw new SyntaxError(
|
||||
`Unexpected token ${nextCh} in ${pos.line}:${pos.column}`
|
||||
);
|
||||
}
|
||||
}
|
||||
const token = {
|
||||
type: TokenName[TokenEnum.Char],
|
||||
value: ch,
|
||||
start: position(),
|
||||
end: position(input.substring(index, i + 1))
|
||||
};
|
||||
return token;
|
||||
}
|
||||
|
||||
function template(): Token | void | null {
|
||||
if (mainState !== mainStates.Template) {
|
||||
return null;
|
||||
}
|
||||
let state = stringStates.START;
|
||||
let i = index;
|
||||
while (i < input.length) {
|
||||
const ch = input[i];
|
||||
|
||||
if (state === stringStates.ESCAPE) {
|
||||
if (escapes.hasOwnProperty(ch) || ch === '`' || ch === '$') {
|
||||
i++;
|
||||
state = stringStates.START_QUOTE_OR_CHAR;
|
||||
} else {
|
||||
const pos = position(input.substring(index, i + 1));
|
||||
throw new SyntaxError(
|
||||
`Unexpected token ${ch} in ${pos.line}:${pos.column}`
|
||||
);
|
||||
}
|
||||
} else if (ch === '\\') {
|
||||
i++;
|
||||
state = stringStates.ESCAPE;
|
||||
} else if (ch === '`') {
|
||||
popState();
|
||||
tokenCache.push({
|
||||
type: TokenName[TokenEnum.Punctuator],
|
||||
value: '`',
|
||||
start: position(input.substring(index, i)),
|
||||
end: position(input.substring(index, i + 1))
|
||||
});
|
||||
break;
|
||||
} else if (ch === '$') {
|
||||
const nextCh = input[i + 1];
|
||||
if (nextCh === '{') {
|
||||
pushState(mainStates.EXPRESSION);
|
||||
tokenCache.push({
|
||||
type: TokenName[TokenEnum.TemplateLeftBrace],
|
||||
value: '${',
|
||||
start: position(input.substring(index, i)),
|
||||
end: position(input.substring(index, i + 2))
|
||||
});
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (i > index) {
|
||||
const value = input.substring(index, i);
|
||||
return {
|
||||
type: TokenName[TokenEnum.TemplateRaw],
|
||||
value: escapeString(value, ['`', '$']),
|
||||
raw: value,
|
||||
start: position(),
|
||||
end: position(value)
|
||||
};
|
||||
}
|
||||
return tokenCache.length ? tokenCache.shift() : null;
|
||||
}
|
||||
|
||||
function skipWhiteSpace() {
|
||||
while (index < input.length) {
|
||||
const ch = input[index];
|
||||
if (ch === '\r') {
|
||||
// CR (Unix)
|
||||
index++;
|
||||
line++;
|
||||
column = 1;
|
||||
if (input.charAt(index) === '\n') {
|
||||
// CRLF (Windows)
|
||||
index++;
|
||||
}
|
||||
} else if (ch === '\n') {
|
||||
// LF (MacOS)
|
||||
index++;
|
||||
line++;
|
||||
column = 1;
|
||||
} else if (ch === '\t' || ch === ' ') {
|
||||
index++;
|
||||
column++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function punctuator() {
|
||||
const find = punctuatorList.find(
|
||||
punctuator =>
|
||||
input.substring(index, index + punctuator.length) === punctuator
|
||||
);
|
||||
if (find) {
|
||||
return {
|
||||
type: TokenName[TokenEnum.Punctuator],
|
||||
value: find,
|
||||
start: position(),
|
||||
end: position(find)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// substring(index, index + 4) 在某些情况会匹配错误
|
||||
// 比如变量名称为 trueValue
|
||||
// ${value2|isTrue:trueValue:falseValue}
|
||||
function literal() {
|
||||
// {4,10} 匹配长度就足够判断 ("true").length <= targetLength <= ("undefined").length + 1
|
||||
const match = input.substring(index).match(/^\w{4,10}/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let keyword = match[0].toLowerCase();
|
||||
let value: any = keyword;
|
||||
let isLiteral = false;
|
||||
|
||||
if (keyword === 'true' || keyword === 'null') {
|
||||
isLiteral = true;
|
||||
value = keyword === 'true' ? true : null;
|
||||
} else if (keyword === 'false') {
|
||||
isLiteral = true;
|
||||
value = false;
|
||||
} else if (keyword === 'undefined') {
|
||||
isLiteral = true;
|
||||
value = undefined;
|
||||
}
|
||||
|
||||
if (isLiteral) {
|
||||
return {
|
||||
type:
|
||||
value === true || value === false
|
||||
? TokenName[TokenEnum.BooleanLiteral]
|
||||
: TokenName[TokenEnum.Literal],
|
||||
value,
|
||||
raw: keyword,
|
||||
start: position(),
|
||||
end: position(keyword)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function numberLiteral() {
|
||||
let i = index;
|
||||
|
||||
let passedValueIndex = i;
|
||||
let state = numberStates.START;
|
||||
|
||||
iterator: while (i < input.length) {
|
||||
const char = input.charAt(i);
|
||||
|
||||
switch (state) {
|
||||
case numberStates.START: {
|
||||
if (char === '0') {
|
||||
passedValueIndex = i + 1;
|
||||
state = numberStates.ZERO;
|
||||
} else if (isDigit1to9(char)) {
|
||||
passedValueIndex = i + 1;
|
||||
state = numberStates.DIGIT;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case numberStates.ZERO: {
|
||||
if (char === '.') {
|
||||
state = numberStates.POINT;
|
||||
} else if (isExp(char)) {
|
||||
state = numberStates.EXP;
|
||||
} else {
|
||||
break iterator;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case numberStates.DIGIT: {
|
||||
if (isDigit(char)) {
|
||||
passedValueIndex = i + 1;
|
||||
} else if (char === '.') {
|
||||
state = numberStates.POINT;
|
||||
} else if (isExp(char)) {
|
||||
state = numberStates.EXP;
|
||||
} else {
|
||||
break iterator;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case numberStates.POINT: {
|
||||
if (isDigit(char)) {
|
||||
passedValueIndex = i + 1;
|
||||
state = numberStates.DIGIT_FRACTION;
|
||||
} else {
|
||||
break iterator;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case numberStates.DIGIT_FRACTION: {
|
||||
if (isDigit(char)) {
|
||||
passedValueIndex = i + 1;
|
||||
} else if (isExp(char)) {
|
||||
state = numberStates.EXP;
|
||||
} else {
|
||||
break iterator;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
if (passedValueIndex > 0) {
|
||||
const value = input.slice(index, passedValueIndex);
|
||||
return {
|
||||
type: TokenName[TokenEnum.NumericLiteral],
|
||||
value: formatNumber(value),
|
||||
raw: value,
|
||||
start: position(),
|
||||
end: position(value)
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function stringLiteral() {
|
||||
let startQuote = '"';
|
||||
let state = stringStates.START;
|
||||
let i = index;
|
||||
while (i < input.length) {
|
||||
const ch = input[i];
|
||||
|
||||
if (state === stringStates.START) {
|
||||
if (ch === '"' || ch === "'") {
|
||||
startQuote = ch;
|
||||
i++;
|
||||
state = stringStates.START_QUOTE_OR_CHAR;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else if (state === stringStates.ESCAPE) {
|
||||
if (escapes.hasOwnProperty(ch) || ch === startQuote) {
|
||||
i++;
|
||||
state = stringStates.START_QUOTE_OR_CHAR;
|
||||
} else {
|
||||
const pos = position(input.substring(index, i + 1));
|
||||
throw new SyntaxError(
|
||||
`Unexpected token ${ch} in ${pos.line}:${pos.column}`
|
||||
);
|
||||
}
|
||||
} else if (ch === '\\') {
|
||||
i++;
|
||||
state = stringStates.ESCAPE;
|
||||
} else if (ch === startQuote) {
|
||||
i++;
|
||||
break;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (i > index) {
|
||||
const value = input.substring(index, i);
|
||||
return {
|
||||
type: TokenName[TokenEnum.StringLiteral],
|
||||
value: escapeString(value.substring(1, value.length - 1), [startQuote]),
|
||||
raw: value,
|
||||
start: position(),
|
||||
end: position(value)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function identifier() {
|
||||
// 变量模式是 resolveVariable 的时候使用的
|
||||
// 这个纯变量获取模式,不支持其他什么表达式
|
||||
// 仅仅支持 xxx.xxx 或者 xxx[ exression ] 这类语法
|
||||
// 所以纯变量模式支持纯数字作为变量名
|
||||
const reg = options?.variableMode
|
||||
? /^[\u4e00-\u9fa5A-Za-z0-9_$@][\u4e00-\u9fa5A-Za-z0-9_\-$@]*/
|
||||
: /^(?:[\u4e00-\u9fa5A-Za-z_$@]([\u4e00-\u9fa5A-Za-z0-9_$@]|\\(?:\.|\[|\]|\(|\)|\{|\}|\s|=|!|>|<|\||&|\+|-|\*|\/|\^|~|%|&|\?|:|;|,))*|\d+[\u4e00-\u9fa5A-Za-z_$@](?:[\u4e00-\u9fa5A-Za-z0-9_$@]|\\(?:\.|\[|\]|\(|\)|\{|\}|\s|=|!|>|<|\||&|\+|-|\*|\/|\^|~|%|&|\?|:|;|,))*)/;
|
||||
|
||||
const match = reg.exec(
|
||||
input.substring(index, index + 256) // 变量长度不能超过 256
|
||||
);
|
||||
if (match) {
|
||||
return {
|
||||
type: TokenName[TokenEnum.Identifier],
|
||||
value: match[0].replace(
|
||||
/\\(\.|\[|\]|\(|\)|\{|\}|\s|=|!|>|<|\||&|\+|-|\*|\/|\^|~|%|&|\?|:|;|,)/g,
|
||||
(_, v) => v
|
||||
),
|
||||
start: position(),
|
||||
end: position(match[0])
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getNextToken(): Token | void | null {
|
||||
if (tokenCache.length) {
|
||||
return tokenCache.shift()!;
|
||||
}
|
||||
|
||||
if (
|
||||
mainState === mainStates.SCRIPT ||
|
||||
mainState === mainStates.EXPRESSION ||
|
||||
mainState === mainStates.BLOCK
|
||||
) {
|
||||
skipWhiteSpace();
|
||||
}
|
||||
|
||||
return eof() || raw() || openScript() || expression() || template();
|
||||
}
|
||||
|
||||
return {
|
||||
next: function () {
|
||||
const token = getNextToken();
|
||||
|
||||
if (token) {
|
||||
index = token.end.index;
|
||||
line = token.end.line;
|
||||
column = token.end.column;
|
||||
return token;
|
||||
}
|
||||
|
||||
const pos = position();
|
||||
throw new SyntaxError(
|
||||
`unexpected character "${input[index]}" at ${pos.line}:${pos.column}`
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
875
packages/amis-formula/src/parser.ts
Normal file
875
packages/amis-formula/src/parser.ts
Normal file
@@ -0,0 +1,875 @@
|
||||
import {lexer as createLexer, TokenEnum, TokenName} from './lexer';
|
||||
import {ParserOptions, ASTNode, Token, ASTNodeOrNull, Position} from './types';
|
||||
|
||||
const argListStates = {
|
||||
START: 0,
|
||||
COMMA: 1,
|
||||
SET: 2
|
||||
};
|
||||
|
||||
const tempalteStates = {
|
||||
START: 0,
|
||||
SCRIPTING: 1
|
||||
};
|
||||
|
||||
const objectStates = {
|
||||
START: 0,
|
||||
KEY: 1,
|
||||
COLON: 2,
|
||||
VALUE: 3,
|
||||
COMMA: 4
|
||||
};
|
||||
|
||||
export function parse(input: string, options?: ParserOptions): ASTNode {
|
||||
let token: Token;
|
||||
const lexer = createLexer(input, options);
|
||||
const tokens: Array<Token> = [];
|
||||
const tokenChunk: Array<Token> = [];
|
||||
|
||||
// 允许的变量名字空间
|
||||
let variableNamespaces: Array<string> = options?.variableNamespaces ?? [
|
||||
'window',
|
||||
'cookie',
|
||||
'ls',
|
||||
'ss'
|
||||
];
|
||||
if (!Array.isArray(variableNamespaces)) {
|
||||
variableNamespaces = [];
|
||||
}
|
||||
|
||||
function next() {
|
||||
token = tokenChunk.length ? tokenChunk.shift()! : lexer.next();
|
||||
|
||||
if (!token) {
|
||||
throw new TypeError('next token is undefined');
|
||||
}
|
||||
tokens.push(token);
|
||||
}
|
||||
|
||||
function back() {
|
||||
tokenChunk.unshift(tokens.pop()!);
|
||||
token = tokens[tokens.length - 1];
|
||||
}
|
||||
|
||||
function matchPunctuator(operator: string | Array<string>) {
|
||||
return (
|
||||
token.type === TokenName[TokenEnum.Punctuator] &&
|
||||
(Array.isArray(operator)
|
||||
? ~operator.indexOf(token.value!)
|
||||
: token.value === operator)
|
||||
);
|
||||
}
|
||||
|
||||
function fatal() {
|
||||
throw TypeError(
|
||||
`Unexpected token ${token!.value || token.type} in ${token!.start.line}:${
|
||||
token!.start.column
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
||||
function assert(result: any) {
|
||||
if (!result) {
|
||||
fatal();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function expression(): ASTNodeOrNull {
|
||||
return assignmentExpression();
|
||||
}
|
||||
|
||||
function skipWhiteSpaceChar() {
|
||||
while (
|
||||
token.type === TokenName[TokenEnum.Char] &&
|
||||
/^\s+$/m.test(token.value)
|
||||
) {
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
function collectFilterArg() {
|
||||
const arg: Array<any> = [];
|
||||
while (
|
||||
!matchPunctuator(':') &&
|
||||
token.type !== TokenName[TokenEnum.OpenFilter] &&
|
||||
token.type !== TokenName[TokenEnum.CloseScript]
|
||||
) {
|
||||
const item =
|
||||
literal() ||
|
||||
numberLiteral() ||
|
||||
stringLiteral() ||
|
||||
template() ||
|
||||
arrayLiteral() ||
|
||||
rawScript() ||
|
||||
objectLiteral();
|
||||
|
||||
if (item) {
|
||||
arg.push(item);
|
||||
} else {
|
||||
assert(
|
||||
~[
|
||||
TokenName[TokenEnum.Identifier],
|
||||
TokenName[TokenEnum.Punctuator],
|
||||
TokenName[TokenEnum.Char]
|
||||
].indexOf(token.type)
|
||||
);
|
||||
|
||||
// 其他的都当字符处理
|
||||
if (arg.length && typeof arg[arg.length - 1] === 'string') {
|
||||
arg[arg.length - 1] += token.raw || token.value;
|
||||
} else {
|
||||
arg.push(token.raw || token.value);
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
if (arg.length && typeof arg[arg.length - 1] === 'string') {
|
||||
arg[arg.length - 1] = arg[arg.length - 1].replace(/\s+$/, '');
|
||||
if (!arg[arg.length - 1]) {
|
||||
arg.pop();
|
||||
}
|
||||
}
|
||||
return arg;
|
||||
}
|
||||
|
||||
function complexExpression(): ASTNodeOrNull {
|
||||
let ast = expression();
|
||||
|
||||
const filters: Array<any> = [];
|
||||
while (token.type === TokenName[TokenEnum.OpenFilter]) {
|
||||
next();
|
||||
|
||||
skipWhiteSpaceChar();
|
||||
const name = assert(identifier());
|
||||
const fnName = name.name;
|
||||
const args = [];
|
||||
|
||||
skipWhiteSpaceChar();
|
||||
while (matchPunctuator(':')) {
|
||||
next();
|
||||
skipWhiteSpaceChar();
|
||||
|
||||
let argContents: any = collectFilterArg();
|
||||
if (argContents.length === 1) {
|
||||
argContents = argContents[0];
|
||||
} else if (!argContents.length) {
|
||||
argContents = '';
|
||||
}
|
||||
|
||||
args.push(
|
||||
Array.isArray(argContents)
|
||||
? {
|
||||
type: 'mixed',
|
||||
body: argContents
|
||||
}
|
||||
: argContents
|
||||
);
|
||||
}
|
||||
filters.push({
|
||||
name: fnName,
|
||||
args
|
||||
});
|
||||
}
|
||||
|
||||
if (filters.length) {
|
||||
ast = {
|
||||
type: 'filter',
|
||||
input: ast,
|
||||
filters,
|
||||
start: ast!.start,
|
||||
end: filters[filters.length - 1].end
|
||||
};
|
||||
}
|
||||
|
||||
return ast;
|
||||
}
|
||||
|
||||
function arrowFunction(): ASTNodeOrNull {
|
||||
let ast: any = argList() || variable();
|
||||
let args: Array<any> = [];
|
||||
let start: Position;
|
||||
|
||||
if (ast?.type === 'variable') {
|
||||
args = [ast];
|
||||
start = ast.start;
|
||||
} else if (ast?.type === 'arg-list') {
|
||||
start = ast.start;
|
||||
args = ast.body;
|
||||
}
|
||||
|
||||
if (Array.isArray(args) && matchPunctuator('=')) {
|
||||
next();
|
||||
if (matchPunctuator('>')) {
|
||||
next();
|
||||
const body = assert(expression());
|
||||
return {
|
||||
type: 'anonymous_function',
|
||||
args: args,
|
||||
return: body,
|
||||
start: start!,
|
||||
end: body.end
|
||||
};
|
||||
} else {
|
||||
back();
|
||||
}
|
||||
}
|
||||
|
||||
return ast;
|
||||
}
|
||||
|
||||
function conditionalExpression(): ASTNodeOrNull {
|
||||
const ast = logicalOrExpression();
|
||||
|
||||
if (!ast) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (matchPunctuator('?')) {
|
||||
next();
|
||||
let consequent = assignmentExpression();
|
||||
assert(consequent);
|
||||
assert(matchPunctuator(':'));
|
||||
|
||||
next();
|
||||
let alternate = assignmentExpression();
|
||||
assert(alternate);
|
||||
|
||||
return {
|
||||
type: 'conditional',
|
||||
test: ast,
|
||||
consequent: consequent,
|
||||
alternate: alternate,
|
||||
start: ast.start,
|
||||
end: alternate!.end
|
||||
};
|
||||
}
|
||||
|
||||
return ast;
|
||||
}
|
||||
|
||||
function binaryExpressionParser(
|
||||
type: string,
|
||||
operator: string,
|
||||
parseFunction: () => any,
|
||||
rightParseFunction = parseFunction,
|
||||
leftKey = 'left',
|
||||
rightKey = 'right'
|
||||
) {
|
||||
let ast = parseFunction();
|
||||
if (!ast) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (matchPunctuator(operator)) {
|
||||
while (matchPunctuator(operator)) {
|
||||
next();
|
||||
const right = assert(rightParseFunction());
|
||||
|
||||
ast = {
|
||||
type: type,
|
||||
op: operator,
|
||||
[leftKey]: ast,
|
||||
[rightKey]: right,
|
||||
start: ast.start,
|
||||
end: right.end
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return ast;
|
||||
}
|
||||
|
||||
function logicalOrExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('or', '||', logicalAndExpression);
|
||||
}
|
||||
|
||||
function logicalAndExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('and', '&&', bitwiseOrExpression);
|
||||
}
|
||||
|
||||
function bitwiseOrExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('binary', '|', bitwiseXOrExpression);
|
||||
}
|
||||
|
||||
function bitwiseXOrExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('binary', '^', bitwiseAndExpression);
|
||||
}
|
||||
|
||||
function bitwiseAndExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('binary', '&', equalityExpression);
|
||||
}
|
||||
|
||||
function equalityExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('eq', '==', () =>
|
||||
binaryExpressionParser('ne', '!=', () =>
|
||||
binaryExpressionParser('streq', '===', () =>
|
||||
binaryExpressionParser('strneq', '!==', relationalExpression)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function relationalExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('lt', '<', () =>
|
||||
binaryExpressionParser('gt', '>', () =>
|
||||
binaryExpressionParser('le', '<=', () =>
|
||||
binaryExpressionParser('ge', '>=', shiftExpression)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function shiftExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('shift', '<<', () =>
|
||||
binaryExpressionParser('shift', '>>', () =>
|
||||
binaryExpressionParser('shift', '>>>', additiveExpression)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function additiveExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('add', '+', () =>
|
||||
binaryExpressionParser('minus', '-', multiplicativeExpression)
|
||||
);
|
||||
}
|
||||
|
||||
function multiplicativeExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('multiply', '*', () =>
|
||||
binaryExpressionParser('divide', '/', () =>
|
||||
binaryExpressionParser('remainder', '%', powerExpression)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function powerExpression(): ASTNodeOrNull {
|
||||
return binaryExpressionParser('power', '**', unaryExpression);
|
||||
}
|
||||
|
||||
function unaryExpression(): ASTNodeOrNull {
|
||||
const unaryOperators = ['+', '-', '~', '!'];
|
||||
const stack: Array<any> = [];
|
||||
while (matchPunctuator(unaryOperators)) {
|
||||
stack.push(token);
|
||||
next();
|
||||
}
|
||||
let ast: any = postfixExpression();
|
||||
assert(!stack.length || ast);
|
||||
while (stack.length) {
|
||||
const op = stack.pop();
|
||||
|
||||
ast = {
|
||||
type: 'unary',
|
||||
op: op.value,
|
||||
value: ast,
|
||||
start: op.start,
|
||||
end: op.end
|
||||
};
|
||||
}
|
||||
return ast;
|
||||
}
|
||||
|
||||
function postfixExpression(
|
||||
parseFunction: () => any = leftHandSideExpression
|
||||
): ASTNodeOrNull {
|
||||
let ast = parseFunction();
|
||||
if (!ast) {
|
||||
return null;
|
||||
}
|
||||
|
||||
while (matchPunctuator('[') || matchPunctuator('.')) {
|
||||
const isDot = matchPunctuator('.');
|
||||
next();
|
||||
const right = assert(
|
||||
isDot ? identifier() || numberLiteral() || rawScript() : expression()
|
||||
);
|
||||
|
||||
if (!isDot) {
|
||||
assert(matchPunctuator(']'));
|
||||
next();
|
||||
}
|
||||
|
||||
ast = {
|
||||
type: 'getter',
|
||||
host: ast,
|
||||
key: right,
|
||||
start: ast.start,
|
||||
end: right.end
|
||||
};
|
||||
}
|
||||
|
||||
return ast;
|
||||
}
|
||||
|
||||
function leftHandSideExpression(): ASTNodeOrNull {
|
||||
return functionCall() || arrowFunction() || primaryExpression();
|
||||
}
|
||||
|
||||
function varibleKey(allowVariable = false, inObject = false): ASTNodeOrNull {
|
||||
return (
|
||||
(allowVariable ? variable() : identifier()) ||
|
||||
stringLiteral() ||
|
||||
numberLiteral() ||
|
||||
(inObject ? objectTemplateKey() : template())
|
||||
);
|
||||
}
|
||||
|
||||
function objectTemplateKey(): ASTNodeOrNull {
|
||||
if (matchPunctuator('[')) {
|
||||
next();
|
||||
const key = assert(template());
|
||||
assert(matchPunctuator(']'));
|
||||
next();
|
||||
return key;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function stringLiteral(): ASTNodeOrNull {
|
||||
if (token.type === TokenName[TokenEnum.StringLiteral]) {
|
||||
const cToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'string',
|
||||
value: cToken.value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function numberLiteral(): ASTNodeOrNull {
|
||||
if (token.type === TokenName[TokenEnum.NumericLiteral]) {
|
||||
const value = token.value;
|
||||
const cToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'literal',
|
||||
value: value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function template(): ASTNodeOrNull {
|
||||
if (matchPunctuator('`')) {
|
||||
const start = token;
|
||||
let end = start;
|
||||
next();
|
||||
let state = tempalteStates.START;
|
||||
const ast: ASTNode = {
|
||||
type: 'template',
|
||||
body: [],
|
||||
start: start.start,
|
||||
end: start.end
|
||||
};
|
||||
while (true) {
|
||||
if (state === tempalteStates.SCRIPTING) {
|
||||
const exp = assert(expression());
|
||||
ast.body.push(exp);
|
||||
assert(token.type === TokenName[TokenEnum.TemplateRightBrace]);
|
||||
next();
|
||||
state = tempalteStates.START;
|
||||
} else {
|
||||
if (matchPunctuator('`')) {
|
||||
end = token;
|
||||
next();
|
||||
break;
|
||||
} else if (token.type === TokenName[TokenEnum.TemplateLeftBrace]) {
|
||||
next();
|
||||
state = tempalteStates.SCRIPTING;
|
||||
} else if (token.type === TokenName[TokenEnum.TemplateRaw]) {
|
||||
ast.body.push({
|
||||
type: 'template_raw',
|
||||
value: token.value,
|
||||
start: token.start,
|
||||
end: token.end
|
||||
});
|
||||
next();
|
||||
} else {
|
||||
fatal();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ast.end = end.end;
|
||||
return ast;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function identifier(): ASTNodeOrNull {
|
||||
if (token.type === TokenName[TokenEnum.Identifier]) {
|
||||
const cToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'identifier',
|
||||
name: cToken.value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function primaryExpression(): ASTNodeOrNull {
|
||||
return (
|
||||
variable() ||
|
||||
literal() ||
|
||||
numberLiteral() ||
|
||||
stringLiteral() ||
|
||||
template() ||
|
||||
arrayLiteral() ||
|
||||
objectLiteral() ||
|
||||
(() => {
|
||||
const ast = expressionList();
|
||||
|
||||
if (ast?.body.length === 1) {
|
||||
return ast.body[0];
|
||||
}
|
||||
|
||||
return ast;
|
||||
})() ||
|
||||
rawScript()
|
||||
);
|
||||
}
|
||||
|
||||
function literal(): ASTNodeOrNull {
|
||||
if (
|
||||
token.type === TokenName[TokenEnum.Literal] ||
|
||||
token.type === TokenName[TokenEnum.BooleanLiteral]
|
||||
) {
|
||||
const value = token.value;
|
||||
const cToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'literal',
|
||||
value: value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function functionCall(): ASTNodeOrNull {
|
||||
if (token.type === TokenName[TokenEnum.Identifier]) {
|
||||
const id = token;
|
||||
next();
|
||||
if (matchPunctuator('(')) {
|
||||
const argList = expressionList();
|
||||
assert(argList);
|
||||
return {
|
||||
type: 'func_call',
|
||||
identifier: id.value,
|
||||
args: argList?.body,
|
||||
start: id.start,
|
||||
end: argList!.end
|
||||
};
|
||||
} else {
|
||||
back();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function arrayLiteral(): ASTNodeOrNull {
|
||||
if (matchPunctuator('[')) {
|
||||
const argList = expressionList('[', ']');
|
||||
assert(argList);
|
||||
return {
|
||||
type: 'array',
|
||||
members: argList?.body,
|
||||
start: argList!.start,
|
||||
end: argList!.end
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function expressionList(startOP = '(', endOp = ')'): ASTNodeOrNull {
|
||||
if (matchPunctuator(startOP)) {
|
||||
const start = token;
|
||||
let end: Token;
|
||||
next();
|
||||
const args: Array<any> = [];
|
||||
let state = argListStates.START;
|
||||
|
||||
while (true) {
|
||||
if (state === argListStates.COMMA || !matchPunctuator(endOp)) {
|
||||
const arg = assert(expression());
|
||||
args.push(arg);
|
||||
state = argListStates.START;
|
||||
|
||||
if (matchPunctuator(',')) {
|
||||
next();
|
||||
state = argListStates.COMMA;
|
||||
}
|
||||
} else if (matchPunctuator(endOp)) {
|
||||
end = token;
|
||||
next();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'expression-list',
|
||||
body: args,
|
||||
start: start.start,
|
||||
end: end!.end
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function argList(startOP = '(', endOp = ')'): ASTNodeOrNull {
|
||||
let count = 0;
|
||||
let rollback = () => {
|
||||
while (count-- > 0) {
|
||||
back();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
if (matchPunctuator(startOP)) {
|
||||
const start = token;
|
||||
let end: Token = start;
|
||||
next();
|
||||
count++;
|
||||
const args: Array<any> = [];
|
||||
let state = argListStates.START;
|
||||
|
||||
while (!matchPunctuator(endOp)) {
|
||||
if (state === argListStates.COMMA || state === argListStates.START) {
|
||||
const arg = variable(false);
|
||||
|
||||
if (!arg) {
|
||||
return rollback();
|
||||
}
|
||||
|
||||
count++;
|
||||
args.push(arg);
|
||||
state = argListStates.SET;
|
||||
} else if (state === argListStates.SET && matchPunctuator(',')) {
|
||||
next();
|
||||
count++;
|
||||
state = argListStates.COMMA;
|
||||
} else {
|
||||
return rollback();
|
||||
}
|
||||
}
|
||||
|
||||
if (matchPunctuator(endOp)) {
|
||||
end = token;
|
||||
next();
|
||||
return {
|
||||
type: 'arg-list',
|
||||
body: args,
|
||||
start: start.start,
|
||||
end: end.end
|
||||
};
|
||||
} else {
|
||||
return rollback();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function objectLiteral(): ASTNodeOrNull {
|
||||
if (matchPunctuator('{')) {
|
||||
const start = token;
|
||||
let end = start;
|
||||
next();
|
||||
let ast: ASTNode = {
|
||||
type: 'object',
|
||||
members: [],
|
||||
start: start.start,
|
||||
end: start.end
|
||||
};
|
||||
let state = objectStates.START;
|
||||
let key: any, value: any;
|
||||
while (true) {
|
||||
if (state === objectStates.KEY) {
|
||||
assert(matchPunctuator(':'));
|
||||
next();
|
||||
state = objectStates.COLON;
|
||||
} else if (state === objectStates.COLON) {
|
||||
value = assert(expression());
|
||||
ast.members.push({
|
||||
key,
|
||||
value
|
||||
});
|
||||
state = objectStates.VALUE;
|
||||
} else if (state === objectStates.VALUE) {
|
||||
if (matchPunctuator(',')) {
|
||||
next();
|
||||
state = objectStates.COMMA;
|
||||
} else if (matchPunctuator('}')) {
|
||||
end = token;
|
||||
next();
|
||||
break;
|
||||
} else {
|
||||
fatal();
|
||||
}
|
||||
} else {
|
||||
if (state != objectStates.COMMA && matchPunctuator('}')) {
|
||||
end = token;
|
||||
next();
|
||||
break;
|
||||
}
|
||||
|
||||
key = assert(varibleKey(false, true));
|
||||
state = objectStates.KEY;
|
||||
}
|
||||
}
|
||||
|
||||
ast.end = end.end;
|
||||
return ast;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function assignmentExpression(): ASTNodeOrNull {
|
||||
return conditionalExpression();
|
||||
}
|
||||
|
||||
function contents(): ASTNodeOrNull {
|
||||
const node: ASTNode = {
|
||||
type: 'document',
|
||||
body: [],
|
||||
start: token.start,
|
||||
end: token.end
|
||||
};
|
||||
while (token.type !== TokenName[TokenEnum.EOF]) {
|
||||
const ast = raw() || rawScript() || oldVariable();
|
||||
|
||||
if (!ast) {
|
||||
break;
|
||||
}
|
||||
node.body.push(ast);
|
||||
}
|
||||
if (node.body.length) {
|
||||
node.end = node.body[node.body.length - 1].end;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function raw(): ASTNodeOrNull {
|
||||
if (token.type !== TokenName[TokenEnum.RAW]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'raw',
|
||||
value: cToken.value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
}
|
||||
|
||||
function rawScript(): ASTNodeOrNull {
|
||||
if (token.type !== TokenName[TokenEnum.OpenScript]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const start = token;
|
||||
let end = start;
|
||||
next();
|
||||
const exp = assert(complexExpression());
|
||||
assert(token.type === TokenName[TokenEnum.CloseScript]);
|
||||
end = token;
|
||||
next();
|
||||
|
||||
return {
|
||||
type: 'script',
|
||||
body: exp,
|
||||
start: start.start,
|
||||
end: end.end
|
||||
};
|
||||
}
|
||||
|
||||
function variable(allowNameSpace = true): ASTNodeOrNull {
|
||||
if (token.type === TokenName[TokenEnum.Identifier]) {
|
||||
const cToken = token;
|
||||
next();
|
||||
|
||||
if (
|
||||
allowNameSpace &&
|
||||
matchPunctuator(':') &&
|
||||
~variableNamespaces.indexOf(cToken.value)
|
||||
) {
|
||||
next();
|
||||
const body = assert(postfixExpression());
|
||||
return {
|
||||
type: 'ns-variable',
|
||||
namespace: cToken.value,
|
||||
body,
|
||||
start: cToken.start,
|
||||
end: body.end
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'variable',
|
||||
name: cToken.value,
|
||||
start: cToken.start,
|
||||
end: cToken.end
|
||||
};
|
||||
} else if (matchPunctuator('&')) {
|
||||
const v = token;
|
||||
next();
|
||||
return {
|
||||
type: 'variable',
|
||||
name: '&',
|
||||
start: v.start,
|
||||
end: v.end
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function oldVariable(): ASTNodeOrNull {
|
||||
if (token.type !== TokenName[TokenEnum.Variable]) {
|
||||
return null;
|
||||
}
|
||||
const prevToken = token;
|
||||
next();
|
||||
return {
|
||||
type: 'script',
|
||||
body: prevToken.value.split('.').reduce((prev: any, key: string) => {
|
||||
return prev
|
||||
? {
|
||||
type: 'getter',
|
||||
host: prev,
|
||||
key,
|
||||
start: prevToken.start,
|
||||
end: prevToken.end
|
||||
}
|
||||
: {
|
||||
type: 'variable',
|
||||
name: key,
|
||||
start: prevToken.start,
|
||||
end: prevToken.end
|
||||
};
|
||||
}, null),
|
||||
start: prevToken.start,
|
||||
end: prevToken.end
|
||||
};
|
||||
}
|
||||
|
||||
next();
|
||||
const ast = options?.variableMode
|
||||
? postfixExpression(variable)
|
||||
: options?.evalMode
|
||||
? expression()
|
||||
: contents();
|
||||
|
||||
assert(token!?.type === TokenName[TokenEnum.EOF]);
|
||||
|
||||
return ast!;
|
||||
}
|
||||
132
packages/amis-formula/src/types.ts
Normal file
132
packages/amis-formula/src/types.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import {Evaluator} from './evalutor';
|
||||
|
||||
export interface FilterMap {
|
||||
[propName: string]: (this: FilterContext, input: any, ...args: any[]) => any;
|
||||
}
|
||||
|
||||
export interface FunctionMap {
|
||||
[propName: string]: (this: Evaluator, ...args: Array<any>) => any;
|
||||
}
|
||||
|
||||
export interface FunctionDocItem {
|
||||
name: string; // 函数名
|
||||
example?: string; // 示例
|
||||
description?: string; // 描述
|
||||
namespace?: string;
|
||||
[propName: string]: any;
|
||||
}
|
||||
export interface FunctionDocMap {
|
||||
[propName: string]: FunctionDocItem[];
|
||||
}
|
||||
|
||||
export interface FilterContext {
|
||||
data: Object;
|
||||
filter?: {
|
||||
name: string;
|
||||
args: Array<any>;
|
||||
};
|
||||
restFilters: Array<{
|
||||
name: string;
|
||||
args: Array<any>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface EvaluatorOptions {
|
||||
/**
|
||||
* 可以外部传入 ast 节点处理器,定制或者扩充自定义函数
|
||||
*/
|
||||
functions?: FunctionMap;
|
||||
|
||||
/**
|
||||
* 可以外部扩充 filter
|
||||
*/
|
||||
filters?: FilterMap;
|
||||
|
||||
defaultFilter?: string;
|
||||
}
|
||||
|
||||
export interface LexerOptions {
|
||||
/**
|
||||
* 直接是运算表达式?还是从模板开始 ${} 里面才算运算表达式
|
||||
*/
|
||||
evalMode?: boolean;
|
||||
|
||||
/**
|
||||
* 只支持取变量。
|
||||
*/
|
||||
variableMode?: boolean;
|
||||
|
||||
/**
|
||||
* 是否允许 filter 语法,比如:
|
||||
*
|
||||
* ${abc | html}
|
||||
*/
|
||||
allowFilter?: boolean;
|
||||
|
||||
isFilter?: (name: string) => boolean;
|
||||
}
|
||||
|
||||
export type TokenTypeName =
|
||||
| 'Boolean'
|
||||
| 'Raw'
|
||||
| 'Variable'
|
||||
| 'OpenScript'
|
||||
| 'CloseScript'
|
||||
| 'EOF'
|
||||
| 'Identifier'
|
||||
| 'Literal'
|
||||
| 'Numeric'
|
||||
| 'Punctuator'
|
||||
| 'String'
|
||||
| 'RegularExpression'
|
||||
| 'TemplateRaw'
|
||||
| 'TemplateLeftBrace'
|
||||
| 'TemplateRightBrace'
|
||||
| 'OpenFilter'
|
||||
| 'Char';
|
||||
|
||||
export interface Position {
|
||||
index: number;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
export interface Token {
|
||||
type: TokenTypeName;
|
||||
value: any;
|
||||
raw?: string;
|
||||
start: Position;
|
||||
end: Position;
|
||||
}
|
||||
|
||||
export type NodeType = 'content' | 'raw' | 'conditional';
|
||||
|
||||
export interface ParserOptions {
|
||||
/**
|
||||
* 直接是运算表达式?还是从模板开始 ${} 里面才算运算表达式
|
||||
*/
|
||||
evalMode?: boolean;
|
||||
|
||||
/**
|
||||
* 只支持取变量。
|
||||
*/
|
||||
variableMode?: boolean;
|
||||
|
||||
/**
|
||||
* 是否允许 filter 语法,比如:
|
||||
*
|
||||
* ${abc | html}
|
||||
*/
|
||||
allowFilter?: boolean;
|
||||
|
||||
variableNamespaces?: Array<string>;
|
||||
}
|
||||
|
||||
export interface ASTNode {
|
||||
type: string;
|
||||
start: Position;
|
||||
end: Position;
|
||||
[propname: string]: any;
|
||||
}
|
||||
|
||||
export type ASTNodeOrNull = ASTNode | null;
|
||||
36
packages/amis-formula/tsconfig-for-declaration.json
Normal file
36
packages/amis-formula/tsconfig-for-declaration.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"outDir": "lib/",
|
||||
"module": "commonjs",
|
||||
"target": "es5",
|
||||
"lib": ["es6", "dom", "ES2015"],
|
||||
"sourceMap": true,
|
||||
"jsx": "react",
|
||||
"moduleResolution": "node",
|
||||
"rootDir": "",
|
||||
"importHelpers": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"sourceRoot": "src",
|
||||
"noImplicitReturns": true,
|
||||
"noImplicitThis": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"skipLibCheck": true,
|
||||
"skipDefaultLibCheck": true,
|
||||
"allowJs": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"build",
|
||||
"scripts",
|
||||
"acceptance-tests",
|
||||
"webpack",
|
||||
"jest",
|
||||
"src/setupTests.ts"
|
||||
],
|
||||
"types": ["typePatches"]
|
||||
}
|
||||
17
packages/amis-formula/tsconfig.json
Normal file
17
packages/amis-formula/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "./",
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"typeRoots": [
|
||||
"../../types",
|
||||
"./node_modules/@types",
|
||||
"../../node_modules/@types"
|
||||
],
|
||||
"paths": {}
|
||||
},
|
||||
"include": ["src/**/*", "scripts/**/*"],
|
||||
"references": []
|
||||
}
|
||||
Reference in New Issue
Block a user