using System.Collections; using System.Globalization; using System.Text.Json.Nodes; namespace w4c_workflows.Services.Nodes; /// /// Converts the loosely-typed values YamlDotNet produces (scalars, nested /// Dictionary<object, object> mappings and List<object> /// sequences) into , so node parameters keep their YAML /// types and can be interpolated by the shared engine. /// public static class NodeParameterReader { /// Builds a JSON object from a YAML mapping (null-safe). public static JsonObject ToJsonObject(Dictionary? mapping) { var result = new JsonObject(); if (mapping == null) return result; foreach (var (key, value) in mapping) result[key] = ToJsonNode(value); return result; } /// Converts a single YamlDotNet value into a JSON node. public static JsonNode? ToJsonNode(object? value) => value switch { null => null, JsonNode node => node.DeepClone(), string text => JsonValue.Create(text), bool flag => JsonValue.Create(flag), char ch => JsonValue.Create(ch.ToString()), sbyte or byte or short or ushort or int or uint or long => JsonValue.Create(Convert.ToInt64(value, CultureInfo.InvariantCulture)), ulong unsigned => JsonValue.Create(unsigned), float or double or decimal => JsonValue.Create(Convert.ToDecimal(value, CultureInfo.InvariantCulture)), DateTime dateTime => JsonValue.Create(dateTime.ToString("O", CultureInfo.InvariantCulture)), DateTimeOffset offset => JsonValue.Create(offset.ToString("O", CultureInfo.InvariantCulture)), IDictionary dictionary => FromDictionary(dictionary), IEnumerable sequence => FromSequence(sequence), _ => JsonValue.Create(value.ToString()), }; private static JsonObject FromDictionary(IDictionary dictionary) { var result = new JsonObject(); foreach (DictionaryEntry entry in dictionary) { var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(key)) continue; result[key] = ToJsonNode(entry.Value); } return result; } private static JsonArray FromSequence(IEnumerable sequence) { var result = new JsonArray(); foreach (var element in sequence) result.Add(ToJsonNode(element)); return result; } }