namespace XFEEDToolBox.Plugin; /// Explicit JSON nodes keep the wire format independent of reflection and AOT trimming. internal static class JsonWire { internal static JsonObject Obj(params (string Key, JsonNode? Value)[] values) { var result = new JsonObject(); foreach (var (key, value) in values) result.Add(key, Normalize(value)); return result; } internal static JsonArray Arr(params JsonNode?[] values) => new(values.Select(Normalize).ToArray()); private static JsonNode? Normalize(JsonNode? value) { // nlohmann/json emits null for non-finite telemetry. Preserve that wire // behavior without enabling non-standard JSON floating-point literals. if (value is JsonValue scalar && (scalar.TryGetValue(out var number) && !double.IsFinite(number) || scalar.TryGetValue(out var single) && !float.IsFinite(single))) return null; return value; } internal static JsonElement Required(this JsonElement value, string name) => value.GetProperty(name); internal static string Str(this JsonElement value, string name, string fallback = "") => value.TryGetProperty(name, out var found) ? found.GetString() ?? throw new InvalidDataException("Expected string: " + name) : fallback; internal static ulong U64(this JsonElement value, string name, ulong fallback = 0) => value.TryGetProperty(name, out var found) ? found.GetUInt64() : fallback; internal static long I64(this JsonElement value, string name, long fallback = 0) => value.TryGetProperty(name, out var found) ? found.GetInt64() : fallback; internal static int Int(this JsonElement value, string name, int fallback = 0) => value.TryGetProperty(name, out var found) ? found.GetInt32() : fallback; internal static double Num(this JsonElement value, string name, double fallback = 0) => value.TryGetProperty(name, out var found) ? found.GetDouble() : fallback; internal static bool Bool(this JsonElement value, string name, bool fallback = false) => value.TryGetProperty(name, out var found) ? found.GetBoolean() : fallback; }