| | | 1 | | using System.Collections; |
| | | 2 | | using System.Management.Automation; |
| | | 3 | | using System.Globalization; |
| | | 4 | | |
| | | 5 | | namespace Kestrun.Utilities.Json; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Utilities to sanitize arbitrary payloads (especially PowerShell objects) into JSON-friendly shapes |
| | | 9 | | /// for System.Text.Json/SignalR serialization without reference cycles. |
| | | 10 | | /// </summary> |
| | | 11 | | public static class PayloadSanitizer |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Returns a sanitized version of the provided value suitable for JSON serialization. |
| | | 15 | | /// - Unwraps PSObject/PSCustomObject into dictionaries |
| | | 16 | | /// - Converts IDictionary into Dictionary<string, object?> |
| | | 17 | | /// - Converts IEnumerable into List<object?> |
| | | 18 | | /// - Replaces circular references with the string "[Circular]" |
| | | 19 | | /// </summary> |
| | | 20 | | public static object? Sanitize(object? value) |
| | 5 | 21 | | => Sanitize(value, new HashSet<object>(ReferenceEqualityComparer.Instance), 0); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Internal recursive sanitizer with cycle detection. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="value">The value to sanitize.</param> |
| | | 27 | | /// <param name="visited">The set of visited objects.</param> |
| | | 28 | | /// <param name="depth">The current depth in the object graph.</param> |
| | | 29 | | /// <returns>The sanitized value.</returns> |
| | | 30 | | private static object? Sanitize(object? value, HashSet<object> visited, int depth) |
| | | 31 | | { |
| | 10 | 32 | | if (value is null) |
| | | 33 | | { |
| | 0 | 34 | | return null; |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | // Fast-path for scalars and special normalization |
| | 10 | 38 | | if (IsSimpleScalar(value, out var simple)) |
| | | 39 | | { |
| | 5 | 40 | | return simple; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | // Prevent cycles for reference types |
| | 5 | 44 | | if (!TryAddVisited(value, visited)) |
| | | 45 | | { |
| | 1 | 46 | | return "[Circular]"; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | // Handlers for common composite/PowerShell shapes |
| | 4 | 50 | | if (TryHandlePowerShellObject(value, visited, depth, out var psResult)) |
| | | 51 | | { |
| | 1 | 52 | | return psResult; |
| | | 53 | | } |
| | 3 | 54 | | if (TryHandleDictionary(value, visited, depth, out var dictResult)) |
| | | 55 | | { |
| | 1 | 56 | | return dictResult; |
| | | 57 | | } |
| | 2 | 58 | | if (TryHandleEnumerable(value, visited, depth, out var listResult)) |
| | | 59 | | { |
| | 1 | 60 | | return listResult; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | // Friendly representations for tricky types |
| | 1 | 64 | | if (TryHandleFriendlyTypes(value, out var friendly)) |
| | | 65 | | { |
| | 1 | 66 | | return friendly; |
| | | 67 | | } |
| | | 68 | | |
| | | 69 | | // Fallback: let System.Text.Json serialize public properties as-is |
| | 0 | 70 | | return value; |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | private static bool IsSimpleScalar(object value, out object? normalized) |
| | | 74 | | { |
| | | 75 | | // Treat value types and strings as simple scalars, with a special case for TimeSpan |
| | 10 | 76 | | if (value is string) |
| | | 77 | | { |
| | 1 | 78 | | normalized = value; |
| | 1 | 79 | | return true; |
| | | 80 | | } |
| | | 81 | | |
| | 9 | 82 | | var type = value.GetType(); |
| | 9 | 83 | | if (type.IsValueType) |
| | | 84 | | { |
| | 4 | 85 | | if (value is TimeSpan ts) |
| | | 86 | | { |
| | 2 | 87 | | normalized = ts.ToString("c", CultureInfo.InvariantCulture); |
| | 2 | 88 | | return true; |
| | | 89 | | } |
| | | 90 | | |
| | 2 | 91 | | normalized = value; |
| | 2 | 92 | | return true; |
| | | 93 | | } |
| | | 94 | | |
| | 5 | 95 | | normalized = null; |
| | 5 | 96 | | return false; |
| | | 97 | | } |
| | | 98 | | |
| | | 99 | | private static bool TryHandlePowerShellObject(object value, HashSet<object> visited, int depth, out object? result) |
| | | 100 | | { |
| | 4 | 101 | | if (value is PSObject pso) |
| | | 102 | | { |
| | 1 | 103 | | if (IsPSCustomObject(pso)) |
| | | 104 | | { |
| | 1 | 105 | | var dict = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | 6 | 106 | | foreach (var prop in pso.Properties) |
| | | 107 | | { |
| | 2 | 108 | | if (IsSpecialMember(prop.Name)) |
| | | 109 | | { |
| | | 110 | | continue; // Skip meta/special members that cause cycles |
| | | 111 | | } |
| | 2 | 112 | | dict[prop.Name] = Sanitize(prop.Value, visited, depth + 1); |
| | | 113 | | } |
| | 1 | 114 | | result = dict; |
| | 1 | 115 | | return true; |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | // Otherwise unwrap to base object and continue |
| | 0 | 119 | | result = Sanitize(pso.BaseObject, visited, depth + 1); |
| | 0 | 120 | | return true; |
| | | 121 | | } |
| | | 122 | | |
| | 3 | 123 | | result = null; |
| | 3 | 124 | | return false; |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | private static bool TryHandleDictionary(object value, HashSet<object> visited, int depth, out object? result) |
| | | 128 | | { |
| | 3 | 129 | | if (value is IDictionary idict) |
| | | 130 | | { |
| | 1 | 131 | | var dict = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | 4 | 132 | | foreach (DictionaryEntry entry in idict) |
| | | 133 | | { |
| | 1 | 134 | | var key = entry.Key?.ToString() ?? string.Empty; |
| | 1 | 135 | | dict[key] = Sanitize(entry.Value, visited, depth + 1); |
| | | 136 | | } |
| | 1 | 137 | | result = dict; |
| | 1 | 138 | | return true; |
| | | 139 | | } |
| | | 140 | | |
| | 2 | 141 | | result = null; |
| | 2 | 142 | | return false; |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | private static bool TryHandleEnumerable(object value, HashSet<object> visited, int depth, out object? result) |
| | | 146 | | { |
| | 2 | 147 | | if (value is IEnumerable enumerable and not string) |
| | | 148 | | { |
| | 1 | 149 | | var list = new List<object?>(); |
| | 6 | 150 | | foreach (var item in enumerable) |
| | | 151 | | { |
| | 2 | 152 | | list.Add(Sanitize(item, visited, depth + 1)); |
| | | 153 | | } |
| | 1 | 154 | | result = list; |
| | 1 | 155 | | return true; |
| | | 156 | | } |
| | | 157 | | |
| | 1 | 158 | | result = null; |
| | 1 | 159 | | return false; |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | private static bool TryHandleFriendlyTypes(object value, out object? result) |
| | | 163 | | { |
| | | 164 | | switch (value) |
| | | 165 | | { |
| | | 166 | | case Type t: |
| | 0 | 167 | | result = t.FullName; |
| | 0 | 168 | | return true; |
| | | 169 | | case Delegate del: |
| | 0 | 170 | | result = del.Method?.Name ?? del.GetType().Name; |
| | 0 | 171 | | return true; |
| | | 172 | | case Exception ex: |
| | 1 | 173 | | result = new |
| | 1 | 174 | | { |
| | 1 | 175 | | Type = ex.GetType().FullName, |
| | 1 | 176 | | ex.Message, |
| | 1 | 177 | | ex.StackTrace |
| | 1 | 178 | | }; |
| | 1 | 179 | | return true; |
| | | 180 | | default: |
| | 0 | 181 | | result = null; |
| | 0 | 182 | | return false; |
| | | 183 | | } |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private static bool TryAddVisited(object o, HashSet<object> visited) => |
| | | 187 | | // Strings and value types are safe (immutable/value) |
| | 5 | 188 | | o is string || o.GetType().IsValueType || visited.Add(o); |
| | | 189 | | |
| | | 190 | | private static bool IsPSCustomObject(PSObject pso) |
| | 1 | 191 | | => pso.BaseObject is PSCustomObject || pso.TypeNames.Contains("System.Management.Automation.PSCustomObject"); |
| | | 192 | | |
| | | 193 | | private static bool IsSpecialMember(string name) |
| | 2 | 194 | | => name is "PSObject" or "BaseObject" or "Members" or "ImmediateBaseObject" or "Properties" or "TypeNames" or "M |
| | | 195 | | } |