elsa-core/src/modules/Elsa.JavaScript/Services/JintJavaScriptEvaluator.cs

182 lines
7.8 KiB
C#
Raw Normal View History

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
2023-10-13 08:34:21 +00:00
using Elsa.Expressions.Helpers;
using Elsa.Expressions.Models;
using Elsa.Extensions;
using Elsa.JavaScript.Contracts;
using Elsa.JavaScript.Helpers;
using Elsa.JavaScript.Notifications;
using Elsa.JavaScript.Options;
using Elsa.Mediator.Contracts;
using Humanizer;
2022-01-12 10:43:46 +00:00
using Jint;
using Jint.Runtime.Interop;
2022-01-12 10:43:46 +00:00
using Microsoft.Extensions.Options;
// ReSharper disable ConvertClosureToMethodGroup
namespace Elsa.JavaScript.Services;
/// <summary>
/// Provides a JavaScript evaluator using Jint.
/// </summary>
public class JintJavaScriptEvaluator : IJavaScriptEvaluator
2022-01-12 10:43:46 +00:00
{
private readonly INotificationSender _mediator;
private readonly JintOptions _jintOptions;
2022-11-30 20:52:41 +00:00
/// <summary>
/// Constructor.
2022-11-30 20:52:41 +00:00
/// </summary>
public JintJavaScriptEvaluator(INotificationSender mediator, IOptions<JintOptions> scriptOptions)
2022-01-12 10:43:46 +00:00
{
_mediator = mediator;
_jintOptions = scriptOptions.Value;
}
2022-01-12 10:43:46 +00:00
/// <inheritdoc />
public async Task<object?> EvaluateAsync(string expression,
Type returnType,
ExpressionExecutionContext context,
ExpressionEvaluatorOptions? options = default,
Action<Engine>? configureEngine = default,
CancellationToken cancellationToken = default)
{
var engine = await GetConfiguredEngine(configureEngine, context, options, cancellationToken);
var result = ExecuteExpressionAndGetResult(engine, expression);
2023-10-13 08:34:21 +00:00
return result.ConvertTo(returnType);
}
2022-01-12 10:43:46 +00:00
private async Task<Engine> GetConfiguredEngine(Action<Engine>? configureEngine, ExpressionExecutionContext context, ExpressionEvaluatorOptions? options, CancellationToken cancellationToken)
{
options ??= new ExpressionEvaluatorOptions();
var engine = new Engine(opts =>
2022-01-12 10:43:46 +00:00
{
if (_jintOptions.AllowClrAccess)
opts.AllowClr();
// Wrap objects in ObjectWrapper instances and set their prototype to Array.prototype if they are array-like.
opts.SetWrapObjectHandler((engine, target, type) =>
{
var instance = new ObjectWrapper(engine, target);
if (ObjectArrayHelper.DetermineIfObjectIsArrayLikeClrCollection(target.GetType()))
instance.Prototype = engine.Intrinsics.Array.PrototypeObject;
return instance;
});
});
2022-01-12 10:43:46 +00:00
configureEngine?.Invoke(engine);
// Add common functions.
engine.SetValue("getWorkflowInstanceId", (Func<string>)(() => context.GetActivityExecutionContext().WorkflowExecutionContext.Id));
engine.SetValue("setCorrelationId", (Action<string?>)(value => context.GetActivityExecutionContext().WorkflowExecutionContext.CorrelationId = value));
engine.SetValue("getCorrelationId", (Func<string?>)(() => context.GetActivityExecutionContext().WorkflowExecutionContext.CorrelationId));
engine.SetValue("setVariable", (Action<string, object>)((name, value) => context.SetVariableInScope(name, value)));
engine.SetValue("getVariable", (Func<string, object?>)(name => context.GetVariableInScope(name)));
engine.SetValue("getInput", (Func<string, object?>)(name => context.GetInput(name)));
engine.SetValue("getOutputFrom", (Func<string, string?, object?>)((activityIdName, outputName) => context.GetOutput(activityIdName, outputName)));
engine.SetValue("getLastResult", (Func<object?>)(() => context.GetLastResult()));
2023-09-06 20:04:58 +00:00
// Create variable getters and setters for each variable.
CreateVariableAccessors(engine, context);
2023-09-06 20:04:58 +00:00
// Create workflow input accessors - only if the current activity is not part of a composite activity definition.
// Otherwise, the workflow input accessors will hide the composite activity input accessors which rely on variable accessors created above.
CreateWorkflowInputAccessors(engine, context);
2023-06-09 20:10:56 +00:00
// Create output getters for each activity.
2023-09-06 20:04:58 +00:00
CreateActivityOutputAccessors(engine, context);
// Create argument getters for each argument.
foreach (var argument in options.Arguments)
engine.SetValue($"get{argument.Key}", (Func<object?>)(() => argument.Value));
// Add common functions.
engine.SetValue("isNullOrWhiteSpace", (Func<string, bool>)(value => string.IsNullOrWhiteSpace(value)));
engine.SetValue("isNullOrEmpty", (Func<string, bool>)(value => string.IsNullOrEmpty(value)));
engine.SetValue("toJson", (Func<object, string>)(value => Serialize(value)));
engine.SetValue("parseGuid", (Func<string, Guid>)(value => Guid.Parse(value)));
engine.SetValue("newGuid", (Func<Guid>)(() => Guid.NewGuid()));
engine.SetValue("newGuidString", (Func<string>)(() => Guid.NewGuid().ToString()));
engine.SetValue("newShortGuid", (Func<string>)(() => Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")));
2023-09-06 20:04:58 +00:00
// Deprecated, use newGuidString instead.
engine.SetValue("getGuidString", (Func<string>)(() => Guid.NewGuid().ToString()));
2023-09-06 20:04:58 +00:00
// Deprecated, use newShortGuid instead.
engine.SetValue("getShortGuid", (Func<string>)(() => Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "")));
2022-01-12 10:43:46 +00:00
// Add common .NET types.
engine.RegisterType<DateTime>();
engine.RegisterType<DateTimeOffset>();
engine.RegisterType<TimeSpan>();
engine.RegisterType<Guid>();
2022-01-12 10:43:46 +00:00
// Invoke registered configuration callback.
_jintOptions.ConfigureEngineCallback(engine, context);
// Allow listeners invoked by the mediator to configure the engine.
await _mediator.SendAsync(new EvaluatingJavaScript(engine, context), cancellationToken);
2022-01-12 10:43:46 +00:00
return engine;
}
private void CreateWorkflowInputAccessors(Engine engine, ExpressionExecutionContext context)
{
if (context.IsInsideCompositeActivity())
return;
var inputs = context.GetWorkflowInputs().ToDictionary(x => x.Name);
if (!context.TryGetWorkflowExecutionContext(out var workflowExecutionContext))
return;
var inputDefinitions = workflowExecutionContext.Workflow.Inputs;
foreach (var inputDefinition in inputDefinitions)
{
var input = inputs.GetValueOrDefault(inputDefinition.Name);
engine.SetValue($"get{inputDefinition.Name}", (Func<object?>)(() => input?.Value));
}
}
2023-06-09 20:10:56 +00:00
private static void CreateVariableAccessors(Engine engine, ExpressionExecutionContext context)
{
var variableNames = context.GetVariableNamesInScope().ToList();
foreach (var variableName in variableNames)
2022-01-12 10:43:46 +00:00
{
var pascalName = variableName.Pascalize();
engine.SetValue($"get{pascalName}", (Func<object?>)(() => context.GetVariableInScope(variableName)));
engine.SetValue($"set{pascalName}", (Action<object?>)(value => context.SetVariableInScope(variableName, value)));
}
}
2023-09-06 20:04:58 +00:00
private static void CreateActivityOutputAccessors(Engine engine, ExpressionExecutionContext context)
2023-06-09 20:10:56 +00:00
{
var activityOutputs = context.GetActivityOutputs();
foreach (var activityOutput in activityOutputs)
foreach (var outputName in activityOutput.OutputNames)
engine.SetValue($"get{outputName}From{activityOutput.ActivityName}", (Func<object?>)(() => context.GetOutput(activityOutput.ActivityId, outputName)));
2023-06-09 20:10:56 +00:00
}
private static object? ExecuteExpressionAndGetResult(Engine engine, string expression)
{
var result = engine.Evaluate(expression);
return result.ToObject();
}
private static string Serialize(object value)
{
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());
return JsonSerializer.Serialize(value, options);
}
2022-01-12 10:43:46 +00:00
}