MCPcopy
hub / github.com/GitbookIO/gitbook / ExpressionRuntime

Class ExpressionRuntime

packages/expr/src/runtime.ts:24–225  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

22import { formatExpressionResult } from './utils';
23
24export class ExpressionRuntime {
25 #parserOptions: AcornOptions;
26 #autocompleter: AutoComplete;
27 #logger: Logger;
28
29 constructor(logger: Logger = console) {
30 this.#parserOptions = {
31 ecmaVersion: 'latest',
32 sourceType: 'script',
33 allowHashBang: false,
34 locations: true,
35 };
36 this.#autocompleter = new AutoComplete(this, logger);
37 this.#logger = logger;
38 }
39
40 /**
41 * Evaluates an expression based on the given inputs/context.
42 */
43 public evaluate(expr: string, inputs: object): unknown {
44 try {
45 const parsed = this.parse(expr);
46
47 if (parsed.invalidNodes.length > 0) {
48 throw new ExpressionError('Invalid nodes found when parsing');
49 }
50
51 return evaluate.sync<Expression>(parsed.result, inputs, {
52 functions: true,
53 withMembers: true,
54 generate: escodegen.generate,
55 });
56 } catch (error) {
57 throw error instanceof Error
58 ? new ExpressionError(error.message)
59 : new ExpressionError('Unexpected error');
60 }
61 }
62
63 /**
64 * Evaluates an expression safely by returning the error instead of throwing when invalid.
65 */
66 public safeEvaluate(
67 expr: string,
68 inputs: object
69 ): { value: unknown; error?: undefined } | { value?: undefined; error: ExpressionError } {
70 try {
71 const value = this.evaluate(expr, inputs);
72 return {
73 value,
74 };
75 } catch (error) {
76 this.#logger.error(`Error while evaluating expression ${expr}`, error);
77
78 if (error instanceof ExpressionError) {
79 return {
80 value: undefined,
81 error,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected