using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using XFEWorkflow.Abstractions; namespace XFEWorkflow.Infrastructure.Compilation; /// Produces SDK-only method adapters; implementation assemblies are never referenced. public static class PluginMethodBindings { public static string Identifier(string name) => "_" + Regex.Replace(name, "[^\\p{L}\\p{Nd}_]", "_"); public static string MethodName(CapabilityDescriptor capability) => Identifier(capability.Id[(capability.PluginId.Length + 1)..]) + "Async"; public static string CallName(CapabilityDescriptor capability) => "XfePlugins." + Identifier(capability.PluginId) + "." + MethodName(capability); private static string Type(PortDefinition port) => port.Type switch { WorkflowValueType.String or WorkflowValueType.Resource => "string?", WorkflowValueType.Number => "double?", WorkflowValueType.Boolean => "bool?", WorkflowValueType.Object => "JsonObject?", WorkflowValueType.Array => "JsonArray?", _ => "JsonNode?" }; public static string Generate(IEnumerable capabilities) { var source = new StringBuilder("#nullable enable\nusing System; using System.Threading; using System.Threading.Tasks; using System.Text.Json; using System.Text.Json.Nodes; using XFEWorkflow.Abstractions;\nnamespace XfePlugins {\n"); foreach (var group in capabilities.Where(x => !x.IsTrigger && x.PluginId != "core").GroupBy(x => x.PluginId).OrderBy(x => x.Key)) { source.Append("public static class ").Append(Identifier(group.Key)).Append(" {\n"); foreach (var capability in group.OrderBy(x => x.Id)) { var outputs = capability.Outputs; var resultType = outputs.Count switch { 0 => "", 1 => "<" + Type(outputs[0]) + ">", _ => "<(" + string.Join(", ", outputs.Select(x => Type(x) + " " + Identifier(x.Name))) + ")>" }; source.Append("public static async ValueTask").Append(resultType).Append(' ').Append(MethodName(capability)).Append("(IWorkflowContext context"); foreach (var input in capability.Inputs) source.Append(", ").Append(Type(input)).Append(' ').Append(Identifier(input.Name)); source.Append(", CancellationToken cancellationToken = default) {\nvar args = new JsonObject();\n"); foreach (var input in capability.Inputs) source.Append("args[").Append(JsonSerializer.Serialize(input.Name)).Append("] = JsonSerializer.SerializeToNode(").Append(Identifier(input.Name)).Append(");\n"); source.Append("var result = await context.InvokeAsync(").Append(JsonSerializer.Serialize(capability.Id)).Append(", args, cancellationToken);\n"); var expressions = outputs.Select(x => "result[" + JsonSerializer.Serialize(x.Name) + "]?.Deserialize<" + Type(x) + ">()" ).ToList(); if (outputs.Count > 0) source.Append("return ").Append(outputs.Count == 1 ? expressions[0] : "(" + string.Join(", ", expressions) + ")").Append(';'); source.Append("\n}\n"); } source.Append("}\n"); } return source.Append("}\n").ToString(); } }