-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathevaluate.ts
More file actions
139 lines (119 loc) · 3.74 KB
/
evaluate.ts
File metadata and controls
139 lines (119 loc) · 3.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import { isEmpty, merge, toString } from "lodash-es";
import type { ScreenContextDefinition } from "../state/screen";
import type { InvokableMethods } from "../state/widget";
import { sanitizeJs, debug } from "../shared";
export const buildEvaluateFn = (
screen: Partial<ScreenContextDefinition>,
js?: string,
context?: { [key: string]: unknown },
): (() => unknown) => {
const widgets: [string, InvokableMethods | undefined][] = Object.entries(
screen.widgets ?? {},
).map(([id, state]) => {
const methods = state?.invokable.methods;
const values = state?.values;
return [id, merge({}, values, methods)];
});
const invokableObj = Object.fromEntries([
...widgets,
...Object.entries(screen.inputs ?? {}),
...Object.entries(screen.data ?? {}),
...Object.entries(screen),
...Object.entries(context ?? {}),
]);
const globalBlock = screen.model?.global;
const importedScriptBlock = screen.model?.importedScripts;
const modifiedJs = modifyJs(Object.fromEntries([...widgets]), js);
// eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
const jsFunc = new Function(
...Object.keys(invokableObj),
addScriptBlock(formatJs(modifiedJs), globalBlock, importedScriptBlock),
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return () => jsFunc(...Object.values(invokableObj));
};
const modifyJs = (
invokables: { [key: string]: InvokableMethods | undefined },
js?: string,
): string => {
if (!js || isEmpty(js)) {
return js || "";
}
// check if the code is assigning a value to a property
// eslint-disable-next-line prefer-named-capture-group
const assignmentRegex = /(\w+)\.(\w+)\s*=\s*(.*)$/gm; // matches widgetId.setter = value
let modifiedCode = js;
let match;
while ((match = assignmentRegex.exec(js))) {
const [fullMatch, widgetId, setter, value] = match;
const setterName = `set${setter.charAt(0).toUpperCase() + setter.slice(1)}`;
const originalSetter = invokables[widgetId]?.[setterName];
if (originalSetter) {
// if a setter function exists, replace the assignment with a function call
modifiedCode = modifiedCode.replace(
fullMatch,
`${widgetId}.${setterName}(${value});`,
);
}
}
return modifiedCode;
};
const formatJs = (js?: string): string => {
if (!js || isEmpty(js)) {
if (process.env.NODE_ENV === "debug") {
return "console.debug('No expression was given')";
}
return "";
}
const sanitizedJs = sanitizeJs(toString(js));
// js object
if (
(sanitizedJs.startsWith("{") && sanitizedJs.endsWith("}")) ||
(sanitizedJs.startsWith("[") && sanitizedJs.endsWith("]"))
)
return `return ${js}`;
// multiline js
if (sanitizedJs.includes("\n")) {
return `
return (function() {
${sanitizedJs}
}())
`;
}
return `return ${sanitizedJs}`;
};
const addScriptBlock = (
js: string,
globalBlock?: string,
importedScriptBlock?: string,
): string => {
let jsString = ``;
if (importedScriptBlock) {
jsString += `${importedScriptBlock}\n\n`;
}
if (globalBlock) {
jsString += `${globalBlock}\n\n`;
}
return (jsString += `${js}`);
};
/**
* @deprecated Consider using useEvaluate or createBinding which will
* optimize creating the evaluation context
*
* @param screen-the current screen state
* @param js- the javascript to evaluate
* @param context- any additional context needed for the script
* @returns the result of the evaluated expression/script
*/
export const evaluate = <T = unknown>(
screen: Partial<ScreenContextDefinition>,
js?: string,
context?: { [key: string]: unknown },
): T => {
try {
return buildEvaluateFn(screen, js, context)() as T;
} catch (e) {
debug(e);
throw e;
}
};