-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathevaluate.ts
More file actions
304 lines (262 loc) · 8.8 KB
/
Copy pathevaluate.ts
File metadata and controls
304 lines (262 loc) · 8.8 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { isEmpty, merge, toString } from "lodash-es";
import { parse as acornParse } from "acorn";
import type { ScreenContextDefinition } from "../state/screen";
import type { InvokableMethods, WidgetState } from "../state/widget";
import {
sanitizeJs,
debug,
visitExpressions,
type EnsembleScreenModel,
replace,
} from "../shared";
/**
* Cache of compiled global / imported scripts keyed by the full script string.
* Each entry stores the symbol names and their corresponding values so that we
* can inject them as parameters when evaluating bindings, removing the need to
* re-parse the same script for every binding.
*/
interface CachedScriptEntry {
symbols: string[];
// compiled function that, given a context, returns an object of exports
fn: (ctx: { [key: string]: unknown }) => { [key: string]: unknown };
}
const globalScriptCache = new Map<string, CachedScriptEntry>();
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument */
const parseScriptSymbols = (script: string): string[] => {
const symbols = new Set<string>();
try {
const ast: any = acornParse(script, {
ecmaVersion: 2020,
sourceType: "script",
});
ast.body?.forEach((node: any) => {
if (node.type === "FunctionDeclaration" && node.id) {
symbols.add(node.id.name);
}
if (node.type === "VariableDeclaration") {
node.declarations.forEach((decl: any) => {
if (decl.id?.type === "Identifier") {
symbols.add(decl.id.name);
}
});
}
});
} catch (e) {
debug(e);
}
return Array.from(symbols);
};
/* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument */
const getCachedGlobals = (
script: string,
ctx: { [key: string]: unknown },
): { symbols: string[]; values: unknown[] } => {
if (isEmpty(script.trim())) return { symbols: [], values: [] };
let entry = globalScriptCache.get(script);
const symbols = parseScriptSymbols(script);
// build a function that executes the script within the provided context using `with`
// and returns an object containing the exported symbols
// eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
const compiled = new Function(
"ctx",
`with (ctx) {\n${script}\nreturn { ${symbols.join(", ")} };\n}`,
) as CachedScriptEntry["fn"];
entry = { symbols, fn: compiled };
globalScriptCache.set(script, entry);
const exportsObj = entry.fn(ctx);
const values = entry.symbols.map((name) => exportsObj[name]);
return { symbols: entry.symbols, values };
};
export const widgetStatesToInvokables = (widgets: {
[key: string]: WidgetState | undefined;
}): [string, InvokableMethods | undefined][] => {
return Object.entries(widgets).map(([id, state]) => {
const methods = state?.invokable?.methods;
const values = state?.values;
return [id, merge({}, values, methods)];
});
};
export const buildEvaluateFn = (
screen: Partial<ScreenContextDefinition>,
js?: string,
context?: { [key: string]: unknown },
): (() => unknown) => {
const widgets: [string, InvokableMethods | undefined][] = screen.widgets
? widgetStatesToInvokables(screen.widgets)
: [];
const invokableObj = Object.fromEntries(
[
...widgets,
...Object.entries(screen.inputs ?? {}),
...Object.entries(screen.data ?? {}),
...Object.entries(screen),
...Object.entries(context ?? {}),
// Need to filter out invalid JS identifiers
].filter(([key, _]) => !key.includes(".")),
);
const globalBlock = screen.model?.global ?? "";
const importedScriptBlock = screen.model?.importedScripts ?? "";
// 1️⃣ cache/compile the IMPORT block (shared across screens)
const importResult = getCachedGlobals(
importedScriptBlock,
merge({}, context, invokableObj),
);
// build an object of import exports so the global block can access them
const importExportsObj = Object.fromEntries(
importResult.symbols.map((s, i) => [s, importResult.values[i]]),
);
// 2️⃣ cache/compile the GLOBAL block (per screen) with import exports in scope
const globalResult = getCachedGlobals(
globalBlock,
merge({}, context, invokableObj, importExportsObj),
);
// 3️⃣ merge symbols and values (global overrides import if duplicate)
const symbolValueMap = new Map<string, unknown>();
importResult.symbols.forEach((sym, idx) => {
symbolValueMap.set(sym, importResult.values[idx]);
});
globalResult.symbols.forEach((sym, idx) => {
symbolValueMap.set(sym, globalResult.values[idx]);
});
const allSymbols = Array.from(symbolValueMap.keys());
const allValues = Array.from(symbolValueMap.values());
// eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
const jsFunc = new Function(
...Object.keys(invokableObj),
// addScriptBlock(formatJs(js), globalBlock, importedScriptBlock),
...allSymbols,
formatJs(js),
);
// return () => jsFunc(...Object.values(invokableObj)) as unknown;
return () => jsFunc(...Object.values(invokableObj), ...allValues) as unknown;
};
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));
if (
(sanitizedJs.startsWith("{") && sanitizedJs.endsWith("}")) ||
(sanitizedJs.startsWith("[") && sanitizedJs.endsWith("]"))
) {
return `return ${sanitizedJs}`;
}
// multiline js
if (sanitizedJs.includes("\n")) {
if (sanitizedJs.includes("await ")) {
return `
return (async function() {
${sanitizedJs}
}())
`;
}
return `
return (function() {
${sanitizedJs}
}())
`;
}
if (sanitizedJs.includes("await ")) {
return `
return (async function() {
return ${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}`);
};
// map to store binding evaluation statistics keyed by sanitized expression label
interface BindingStats {
count: number;
total: number;
max: number;
min: number;
}
// in-memory cache for quick inspection in dev builds (not used in production)
const bindingEvaluationStats = new Map<string, BindingStats>();
const timestamp = (): number => {
// use high-resolution timer when available
if (
typeof performance !== "undefined" &&
typeof performance.now === "function"
) {
return performance.now();
}
// Date.now fallback – millisecond precision
return Date.now();
};
const recordBindingEvaluation = (
expr: string | undefined,
duration: number,
): void => {
if (!expr) return;
// keep label concise for easy reading; remove surrounding `${}` if present
const label = sanitizeJs(toString(expr)).slice(0, 100);
const existing = bindingEvaluationStats.get(label) ?? {
count: 0,
total: 0,
max: 0,
min: Number.POSITIVE_INFINITY,
};
existing.count += 1;
existing.total += duration;
existing.max = Math.max(existing.max, duration);
existing.min = Math.min(existing.min, duration);
bindingEvaluationStats.set(label, existing);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(globalThis as any).__bindingEvaluationStats = bindingEvaluationStats;
/**
* @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 {
const start = timestamp();
const result = buildEvaluateFn(screen, js, context)() as T;
const duration = timestamp() - start;
recordBindingEvaluation(js, duration);
return result;
} catch (e) {
debug(e);
throw e;
}
};
export const evaluateDeep = (
inputs: { [key: string]: unknown },
model?: EnsembleScreenModel,
context?: { [key: string]: unknown },
): { [key: string]: unknown } => {
const resolvedInputs = visitExpressions(
inputs,
replace((expr) => evaluate({ model }, expr, context)),
);
return resolvedInputs as { [key: string]: unknown };
};
export const testGetScriptCacheSize = (): number => globalScriptCache.size;