| | | 1 | | using System.Reflection; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Runtime; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Exports OpenAPI component classes as PowerShell class definitions. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class PowerShellOpenApiClassExporter |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Holds valid class names to be used as type in the OpenAPI function definitions. |
| | | 13 | | /// </summary> |
| | 28 | 14 | | public static List<string> ValidClassNames { get; } = []; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Exports OpenAPI component classes found in loaded assemblies |
| | | 18 | | /// as PowerShell class definitions. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="userCallbacks">Optional user-defined functions to include in the export.</param> |
| | | 21 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 22 | | public static string ExportOpenApiClasses(Dictionary<string, string>? userCallbacks) |
| | | 23 | | { |
| | 63 | 24 | | var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| | 19599 | 25 | | .Where(a => a.FullName is not null && |
| | 19599 | 26 | | a.FullName.Contains("PowerShell Class Assembly")) |
| | 63 | 27 | | .ToArray(); |
| | 63 | 28 | | return ExportOpenApiClasses(assemblies: assemblies, userCallbacks: userCallbacks); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Exports OpenAPI component classes found in the specified assemblies |
| | | 33 | | /// as PowerShell class definitions |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="assemblies">The assemblies to scan for OpenAPI component classes.</param> |
| | | 36 | | /// <param name="userCallbacks"> Optional user-defined functions to include in the export.</param> |
| | | 37 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 38 | | public static string ExportOpenApiClasses(Assembly[] assemblies, Dictionary<string, string>? userCallbacks) |
| | | 39 | | { |
| | | 40 | | // 1. Collect all component classes |
| | 67 | 41 | | var componentTypes = assemblies |
| | 67 | 42 | | .SelectMany(GetLoadableTypes) |
| | 1396 | 43 | | .Where(t => t.IsClass && !t.IsAbstract) |
| | 67 | 44 | | .Where(HasOpenApiComponentAttribute) |
| | 67 | 45 | | .ToList(); |
| | | 46 | | |
| | | 47 | | // Collect any enums required by the component graph. |
| | | 48 | | // If a class property uses an enum type constraint, that enum must exist in the session |
| | | 49 | | // before the class definition is parsed. |
| | 67 | 50 | | var enumTypes = CollectExportableEnums(componentTypes) |
| | 1 | 51 | | .OrderBy(t => t.Name, StringComparer.Ordinal) |
| | 67 | 52 | | .ToList(); |
| | | 53 | | |
| | | 54 | | // For quick lookup when choosing type names |
| | 67 | 55 | | var componentSet = new HashSet<Type>(componentTypes); |
| | | 56 | | |
| | | 57 | | // 2. Topologically sort by "uses other component as property type" |
| | 67 | 58 | | var sorted = TopologicalSortByPropertyDependencies(componentTypes, componentSet); |
| | 67 | 59 | | var hasCallbacks = userCallbacks is not null && userCallbacks.Count > 0; |
| | | 60 | | |
| | | 61 | | // nothing to export |
| | 67 | 62 | | if (sorted.Count == 0 && !hasCallbacks) |
| | | 63 | | { |
| | 63 | 64 | | return string.Empty; |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | // 3. Emit PowerShell classes (and optional callback functions) |
| | 4 | 68 | | var sb = new StringBuilder(); |
| | | 69 | | |
| | 4 | 70 | | if (enumTypes.Count > 0) |
| | | 71 | | { |
| | 1 | 72 | | _ = sb.AppendLine("# ================================================"); |
| | 1 | 73 | | _ = sb.AppendLine("# Kestrun OpenAPI Autogenerated Enum Definitions"); |
| | 1 | 74 | | _ = sb.AppendLine("# ================================================"); |
| | 1 | 75 | | _ = sb.AppendLine(); |
| | | 76 | | |
| | 4 | 77 | | foreach (var enumType in enumTypes) |
| | | 78 | | { |
| | 1 | 79 | | AppendEnum(enumType, sb); |
| | 1 | 80 | | _ = sb.AppendLine(); // blank line between enums |
| | | 81 | | } |
| | | 82 | | } |
| | | 83 | | |
| | 34 | 84 | | foreach (var type in sorted) |
| | | 85 | | { |
| | | 86 | | // Skip types without full name (should not happen) |
| | 13 | 87 | | if (type.FullName is null) |
| | | 88 | | { |
| | | 89 | | continue; |
| | | 90 | | } |
| | 13 | 91 | | if (ValidClassNames.Contains(type.FullName)) |
| | | 92 | | { |
| | | 93 | | // Already registered remove old entry |
| | 0 | 94 | | _ = ValidClassNames.Remove(type.FullName); |
| | | 95 | | } |
| | | 96 | | // Register valid class name |
| | 13 | 97 | | ValidClassNames.Add(type.FullName); |
| | | 98 | | // Emit class definition |
| | 13 | 99 | | AppendClass(type, componentSet, sb); |
| | 13 | 100 | | _ = sb.AppendLine(); // blank line between classes |
| | | 101 | | } |
| | | 102 | | |
| | 4 | 103 | | if (hasCallbacks) |
| | | 104 | | { |
| | 2 | 105 | | AppendCallback(sb, userCallbacks); |
| | | 106 | | } |
| | | 107 | | // 4. Write to temp script file |
| | 4 | 108 | | return WriteOpenApiTempScript(sb.ToString()); |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Safely retrieves loadable types from an assembly, handling partial load failures. |
| | | 113 | | /// </summary> |
| | | 114 | | /// <param name="assembly">The assembly to inspect.</param> |
| | | 115 | | /// <returns>All loadable types from the assembly.</returns> |
| | | 116 | | private static IEnumerable<Type> GetLoadableTypes(Assembly assembly) |
| | | 117 | | { |
| | | 118 | | try |
| | | 119 | | { |
| | 53 | 120 | | return assembly.GetTypes(); |
| | | 121 | | } |
| | 0 | 122 | | catch (ReflectionTypeLoadException ex) |
| | | 123 | | { |
| | 0 | 124 | | return ex.Types.Where(static t => t is not null).Cast<Type>(); |
| | | 125 | | } |
| | 0 | 126 | | catch |
| | | 127 | | { |
| | 0 | 128 | | return []; |
| | | 129 | | } |
| | 53 | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Appends user-defined callback functions to the PowerShell script. |
| | | 134 | | /// </summary> |
| | | 135 | | /// <param name="sb"> The StringBuilder to append the callback functions to. </param> |
| | | 136 | | /// <param name="userCallbacks"> The dictionary of user-defined callback functions, where the key is the function na |
| | | 137 | | private static void AppendCallback(StringBuilder sb, Dictionary<string, string>? userCallbacks) |
| | | 138 | | { |
| | 2 | 139 | | _ = sb.AppendLine("# ================================================"); |
| | 2 | 140 | | _ = sb.AppendLine("# Kestrun User Callback Functions"); |
| | 2 | 141 | | _ = sb.AppendLine("# ================================================"); |
| | 2 | 142 | | _ = sb.AppendLine(); |
| | | 143 | | |
| | 13 | 144 | | foreach (var kvp in userCallbacks!.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase)) |
| | | 145 | | { |
| | 3 | 146 | | var name = kvp.Key; |
| | 3 | 147 | | var definition = kvp.Value ?? string.Empty; |
| | | 148 | | |
| | | 149 | | // Emit a standardized callback function wrapper: |
| | | 150 | | // - keeps parameter type constraints |
| | | 151 | | // - strips OpenAPI/Parameter attributes |
| | | 152 | | // - builds $params and calls $Context.Response.AddCallbackParameters(...) |
| | 3 | 153 | | var functionScript = BuildCallbackFunctionStub(name, definition); |
| | 3 | 154 | | var normalized = NormalizeBlankLines(functionScript); |
| | 3 | 155 | | _ = sb.AppendLine(normalized); |
| | 3 | 156 | | _ = sb.AppendLine(); |
| | | 157 | | } |
| | 2 | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Normalizes blank lines in the provided PowerShell script. |
| | | 162 | | /// </summary> |
| | | 163 | | /// <param name="script">The PowerShell script as a string.</param> |
| | | 164 | | /// <returns>A string with normalized blank lines.</returns> |
| | | 165 | | private static string NormalizeBlankLines(string script) |
| | | 166 | | { |
| | 6 | 167 | | if (string.IsNullOrWhiteSpace(script)) |
| | | 168 | | { |
| | 1 | 169 | | return string.Empty; |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | // Normalize newlines first |
| | 5 | 173 | | script = script.Replace("\r\n", "\n").Replace("\r", "\n"); |
| | | 174 | | |
| | 5 | 175 | | var lines = script.Split('\n'); |
| | 5 | 176 | | var sb = new StringBuilder(script.Length); |
| | | 177 | | |
| | 174 | 178 | | for (var idx = 0; idx < lines.Length; idx++) |
| | | 179 | | { |
| | 82 | 180 | | var line = lines[idx].TrimEnd(); |
| | 82 | 181 | | var isBlank = string.IsNullOrWhiteSpace(line); |
| | | 182 | | |
| | | 183 | | // For callback function export we want compact output: |
| | | 184 | | // drop ALL whitespace-only lines (attribute stripping leaves many single blank lines). |
| | 82 | 185 | | if (!isBlank) |
| | | 186 | | { |
| | 72 | 187 | | _ = sb.AppendLine(line); |
| | | 188 | | } |
| | | 189 | | } |
| | | 190 | | |
| | | 191 | | // Trim trailing newlines |
| | 5 | 192 | | return sb.ToString().TrimEnd(); |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Builds a PowerShell function stub for a user-defined callback function. |
| | | 197 | | /// </summary> |
| | | 198 | | /// <param name="functionName"> The name of the callback function. </param> |
| | | 199 | | /// <param name="definition"> The PowerShell function definition as a string. </param> |
| | | 200 | | /// <returns>A string containing the standardized PowerShell function stub.</returns> |
| | | 201 | | private static string BuildCallbackFunctionStub(string functionName, string definition) |
| | | 202 | | { |
| | 3 | 203 | | var (paramBlock, paramNames, bodyParamName) = TryExtractParamInfo(definition); |
| | | 204 | | |
| | | 205 | | // Fall back to a no-param function if we can't parse anything. |
| | 3 | 206 | | var strippedParamBlock = StripPowerShellAttributeBlocks(paramBlock); |
| | 3 | 207 | | strippedParamBlock = NormalizeBlankLines(strippedParamBlock); |
| | | 208 | | |
| | | 209 | | // Ensure we always have a param(...) block for consistent output. |
| | 3 | 210 | | if (string.IsNullOrWhiteSpace(strippedParamBlock)) |
| | | 211 | | { |
| | 1 | 212 | | strippedParamBlock = "param()"; |
| | 1 | 213 | | paramNames = []; |
| | | 214 | | } |
| | | 215 | | |
| | 3 | 216 | | var sb = new StringBuilder(); |
| | 3 | 217 | | _ = sb.AppendLine($"function {functionName} {{"); |
| | | 218 | | |
| | | 219 | | // Normalize indentation: |
| | | 220 | | // - "param(" line: 4 spaces |
| | | 221 | | // - parameter lines: 8 spaces |
| | | 222 | | // - closing ")": 4 spaces |
| | 22 | 223 | | foreach (var rawLine in strippedParamBlock.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n')) |
| | | 224 | | { |
| | 8 | 225 | | var l = rawLine.Trim(); |
| | 8 | 226 | | if (l.Length == 0) |
| | | 227 | | { |
| | | 228 | | continue; |
| | | 229 | | } |
| | | 230 | | |
| | 8 | 231 | | if (l.Equals(")", StringComparison.Ordinal)) |
| | | 232 | | { |
| | 2 | 233 | | _ = sb.Append(" ").AppendLine(l); |
| | 2 | 234 | | continue; |
| | | 235 | | } |
| | | 236 | | |
| | 6 | 237 | | if (l.StartsWith("param", StringComparison.OrdinalIgnoreCase)) |
| | | 238 | | { |
| | 3 | 239 | | _ = sb.Append(" ").AppendLine(l); |
| | 3 | 240 | | continue; |
| | | 241 | | } |
| | | 242 | | |
| | 3 | 243 | | _ = sb.Append(" ").AppendLine(l); |
| | | 244 | | } |
| | | 245 | | |
| | 3 | 246 | | _ = sb.AppendLine(" $FunctionName = $MyInvocation.MyCommand.Name"); |
| | 3 | 247 | | _ = sb.AppendLine(" if ($null -eq $Context -or $null -eq $Context.Response) {"); |
| | 3 | 248 | | _ = sb.AppendLine(" if (Test-KrLogger) {"); |
| | 3 | 249 | | _ = sb.AppendLine(" Write-KrLog -Level Warning -Message '{function} must be called inside a route scr |
| | 3 | 250 | | _ = sb.AppendLine(" } else {"); |
| | 3 | 251 | | _ = sb.AppendLine(" Write-Warning -Message \"$FunctionName must be called inside a route script with |
| | 3 | 252 | | _ = sb.AppendLine(" }"); |
| | 3 | 253 | | _ = sb.AppendLine(" return"); |
| | 3 | 254 | | _ = sb.AppendLine(" }"); |
| | 3 | 255 | | _ = sb.AppendLine(" Write-KrLog -Level Information -Message 'Defined callback function {CallbackFunction}' -V |
| | 3 | 256 | | _ = sb.AppendLine(" $params = [System.Collections.Generic.Dictionary[string, object]]::new()"); |
| | | 257 | | |
| | 12 | 258 | | foreach (var p in paramNames) |
| | | 259 | | { |
| | | 260 | | // Use the exact casing captured from the param block; dictionary keys are case-insensitive in C#. |
| | 3 | 261 | | _ = sb.AppendLine($" $params['{p}'] = ${p}"); |
| | | 262 | | } |
| | | 263 | | |
| | 3 | 264 | | _ = sb.AppendLine(bodyParamName is { Length: > 0 } |
| | 3 | 265 | | ? $" $bodyParameterName = '{bodyParamName}'" |
| | 3 | 266 | | : " $bodyParameterName = $null"); |
| | | 267 | | |
| | 3 | 268 | | _ = sb.AppendLine(); |
| | 3 | 269 | | _ = sb.AppendLine(" $Context.Response.AddCallbackParameters("); |
| | 3 | 270 | | _ = sb.AppendLine(" $MyInvocation.MyCommand.Name,"); |
| | 3 | 271 | | _ = sb.AppendLine(" $bodyParameterName,"); |
| | 3 | 272 | | _ = sb.AppendLine(" $params)"); |
| | 3 | 273 | | _ = sb.AppendLine("}"); |
| | | 274 | | |
| | 3 | 275 | | return sb.ToString(); |
| | | 276 | | } |
| | | 277 | | |
| | | 278 | | private static (string ParamBlock, List<string> ParamNames, string? BodyParamName) TryExtractParamInfo(string defini |
| | | 279 | | { |
| | 3 | 280 | | if (string.IsNullOrWhiteSpace(definition)) |
| | | 281 | | { |
| | 0 | 282 | | return (string.Empty, [], null); |
| | | 283 | | } |
| | | 284 | | |
| | | 285 | | // Try to isolate the param(...) block from a FunctionInfo.Definition string. |
| | 3 | 286 | | var paramBlock = ExtractPowerShellParamBlock(definition); |
| | 3 | 287 | | if (string.IsNullOrWhiteSpace(paramBlock)) |
| | | 288 | | { |
| | 1 | 289 | | return (string.Empty, [], null); |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | // Identify the request body parameter name (prefer OpenApiRequestBody attribute if present) |
| | | 293 | | // Example: [OpenApiRequestBody(...)] [PaymentStatusChangedEvent]$Body |
| | 2 | 294 | | var bodyParamName = ExtractBodyParameterName(paramBlock); |
| | | 295 | | |
| | | 296 | | // Strip attribute blocks so we keep only type constraints + $paramName |
| | 2 | 297 | | var stripped = StripPowerShellAttributeBlocks(paramBlock); |
| | 2 | 298 | | var paramNames = ExtractParamNamesFromStrippedParamBlock(stripped); |
| | | 299 | | |
| | | 300 | | // If we didn't find OpenApiRequestBody, default to Body if present. |
| | 3 | 301 | | if (string.IsNullOrWhiteSpace(bodyParamName) && paramNames.Any(p => string.Equals(p, "Body", StringComparison.Or |
| | | 302 | | { |
| | 0 | 303 | | bodyParamName = paramNames.First(p => string.Equals(p, "Body", StringComparison.OrdinalIgnoreCase)); |
| | | 304 | | } |
| | | 305 | | |
| | 2 | 306 | | return (paramBlock, paramNames, bodyParamName); |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | /// <summary> |
| | | 310 | | /// States for scanning PowerShell script for quoted segments. |
| | | 311 | | /// </summary> |
| | | 312 | | private enum ScanState |
| | | 313 | | { |
| | | 314 | | /// <summary> |
| | | 315 | | /// Normal scanning state (not inside quotes). |
| | | 316 | | /// </summary> |
| | | 317 | | Normal, |
| | | 318 | | /// <summary> |
| | | 319 | | /// Inside single-quoted string segment. |
| | | 320 | | /// </summary> |
| | | 321 | | SingleQuoted, |
| | | 322 | | /// <summary> |
| | | 323 | | /// Inside double-quoted string segment. |
| | | 324 | | /// </summary> |
| | | 325 | | DoubleQuoted |
| | | 326 | | } |
| | | 327 | | |
| | | 328 | | /// <summary> |
| | | 329 | | /// Extracts the parameter block from a PowerShell function definition. |
| | | 330 | | /// </summary> |
| | | 331 | | /// <param name="definition"> The PowerShell function definition string. </param> |
| | | 332 | | /// <returns>The parameter block string including the 'param(...)' syntax; or an empty string if not found.</returns |
| | | 333 | | private static string ExtractPowerShellParamBlock(string definition) |
| | | 334 | | { |
| | 3 | 335 | | if (string.IsNullOrEmpty(definition)) |
| | | 336 | | { |
| | 0 | 337 | | return string.Empty; |
| | | 338 | | } |
| | | 339 | | |
| | 3 | 340 | | var idx = definition.IndexOf("param", StringComparison.OrdinalIgnoreCase); |
| | 3 | 341 | | if (idx < 0) |
| | | 342 | | { |
| | 0 | 343 | | return string.Empty; |
| | | 344 | | } |
| | | 345 | | |
| | 3 | 346 | | var open = definition.IndexOf('(', idx); |
| | 3 | 347 | | if (open < 0) |
| | | 348 | | { |
| | 1 | 349 | | return string.Empty; |
| | | 350 | | } |
| | | 351 | | |
| | 2 | 352 | | var depth = 0; |
| | 2 | 353 | | var state = ScanState.Normal; |
| | | 354 | | |
| | 534 | 355 | | for (var i = open; i < definition.Length; i++) |
| | | 356 | | { |
| | 267 | 357 | | if (TryConsumeQuoted(definition, ref i, ref state)) |
| | | 358 | | { |
| | | 359 | | continue; |
| | | 360 | | } |
| | | 361 | | |
| | 243 | 362 | | var ch = definition[i]; |
| | | 363 | | |
| | 243 | 364 | | if (ch == '(') |
| | | 365 | | { |
| | 5 | 366 | | depth++; |
| | 5 | 367 | | continue; |
| | | 368 | | } |
| | | 369 | | |
| | 238 | 370 | | if (ch == ')') |
| | | 371 | | { |
| | 5 | 372 | | depth--; |
| | 5 | 373 | | if (depth == 0) |
| | | 374 | | { |
| | 2 | 375 | | return definition.Substring(idx, i - idx + 1); |
| | | 376 | | } |
| | | 377 | | } |
| | | 378 | | } |
| | | 379 | | |
| | 0 | 380 | | return string.Empty; |
| | | 381 | | } |
| | | 382 | | |
| | | 383 | | /// <summary> |
| | | 384 | | /// Tries to consume a quoted segment in the PowerShell script. |
| | | 385 | | /// </summary> |
| | | 386 | | /// <param name="s"> The input string to scan. </param> |
| | | 387 | | /// <param name="i"> The current index in the string, passed by reference and updated as the quoted segment is consu |
| | | 388 | | /// <param name="state"> The current scanning state, passed by reference and updated based on quote handling. </para |
| | | 389 | | /// <returns>True if a quoted segment was consumed; otherwise, false.</returns> |
| | | 390 | | private static bool TryConsumeQuoted(string s, ref int i, ref ScanState state) |
| | | 391 | | { |
| | 267 | 392 | | var ch = s[i]; |
| | | 393 | | |
| | | 394 | | // Enter quote states |
| | 267 | 395 | | if (state == ScanState.Normal) |
| | | 396 | | { |
| | 249 | 397 | | if (ch == '\'') { state = ScanState.SingleQuoted; return true; } |
| | 243 | 398 | | if (ch == '"') { state = ScanState.DoubleQuoted; return true; } |
| | 243 | 399 | | return false; |
| | | 400 | | } |
| | | 401 | | |
| | | 402 | | // Inside single quotes: '' is an escaped single quote |
| | 22 | 403 | | if (state == ScanState.SingleQuoted) |
| | | 404 | | { |
| | 22 | 405 | | if (ch == '\'' && i + 1 < s.Length && s[i + 1] == '\'') |
| | | 406 | | { |
| | 0 | 407 | | i++; // consume second ' |
| | 0 | 408 | | return true; |
| | | 409 | | } |
| | | 410 | | |
| | 22 | 411 | | if (ch == '\'') |
| | | 412 | | { |
| | 2 | 413 | | state = ScanState.Normal; |
| | | 414 | | } |
| | | 415 | | |
| | 22 | 416 | | return true; |
| | | 417 | | } |
| | | 418 | | |
| | | 419 | | // Inside double quotes: backtick escapes the next char |
| | 0 | 420 | | if (state == ScanState.DoubleQuoted) |
| | | 421 | | { |
| | 0 | 422 | | if (ch == '`' && i + 1 < s.Length) |
| | | 423 | | { |
| | 0 | 424 | | i++; // skip escaped char |
| | 0 | 425 | | return true; |
| | | 426 | | } |
| | | 427 | | |
| | 0 | 428 | | if (ch == '"') |
| | | 429 | | { |
| | 0 | 430 | | state = ScanState.Normal; |
| | | 431 | | } |
| | | 432 | | |
| | 0 | 433 | | return true; |
| | | 434 | | } |
| | | 435 | | |
| | 0 | 436 | | return false; |
| | | 437 | | } |
| | | 438 | | |
| | | 439 | | /// <summary> |
| | | 440 | | /// Extracts the name of the body parameter from the parameter block, if annotated with [OpenApiRequestBody]. |
| | | 441 | | /// </summary> |
| | | 442 | | /// <param name="paramBlock"> The parameter block string to search within. </param> |
| | | 443 | | /// <returns>The name of the body parameter if found; otherwise, null.</returns> |
| | | 444 | | private static string? ExtractBodyParameterName(string paramBlock) |
| | | 445 | | { |
| | | 446 | | // Very targeted heuristic: if [OpenApiRequestBody(...)] is present, pick the following $name. |
| | | 447 | | // This keeps the exporter decoupled from PowerShell AST dependencies. |
| | 2 | 448 | | var marker = "OpenApiRequestBody"; |
| | 2 | 449 | | var idx = paramBlock.IndexOf(marker, StringComparison.OrdinalIgnoreCase); |
| | 2 | 450 | | if (idx < 0) |
| | | 451 | | { |
| | 1 | 452 | | return null; |
| | | 453 | | } |
| | | 454 | | |
| | | 455 | | // Search forward for '$' then capture identifier |
| | 180 | 456 | | for (var i = idx; i < paramBlock.Length; i++) |
| | | 457 | | { |
| | 90 | 458 | | if (paramBlock[i] != '$') |
| | | 459 | | { |
| | | 460 | | continue; |
| | | 461 | | } |
| | | 462 | | |
| | 1 | 463 | | var start = i + 1; |
| | 1 | 464 | | var end = start; |
| | 8 | 465 | | while (end < paramBlock.Length) |
| | | 466 | | { |
| | 8 | 467 | | var ch = paramBlock[end]; |
| | 8 | 468 | | if (!(char.IsLetterOrDigit(ch) || ch == '_')) |
| | | 469 | | { |
| | | 470 | | break; |
| | | 471 | | } |
| | 7 | 472 | | end++; |
| | | 473 | | } |
| | | 474 | | |
| | 1 | 475 | | if (end > start) |
| | | 476 | | { |
| | 1 | 477 | | return paramBlock[start..end]; |
| | | 478 | | } |
| | | 479 | | } |
| | | 480 | | |
| | 0 | 481 | | return null; |
| | | 482 | | } |
| | | 483 | | |
| | | 484 | | private static List<string> ExtractParamNamesFromStrippedParamBlock(string strippedParamBlock) |
| | | 485 | | { |
| | | 486 | | // Parse variable names only from within param(...) |
| | | 487 | | // We expect declarations like: [string]$paymentId, |
| | 2 | 488 | | if (string.IsNullOrWhiteSpace(strippedParamBlock)) |
| | | 489 | | { |
| | 0 | 490 | | return []; |
| | | 491 | | } |
| | | 492 | | |
| | 2 | 493 | | var names = new List<string>(); |
| | 2 | 494 | | var s = strippedParamBlock; |
| | | 495 | | |
| | 250 | 496 | | for (var i = 0; i < s.Length; i++) |
| | | 497 | | { |
| | 123 | 498 | | if (s[i] != '$') |
| | | 499 | | { |
| | | 500 | | continue; |
| | | 501 | | } |
| | | 502 | | |
| | 3 | 503 | | var start = i + 1; |
| | 3 | 504 | | var end = start; |
| | 3 | 505 | | if (start >= s.Length) |
| | | 506 | | { |
| | | 507 | | continue; |
| | | 508 | | } |
| | | 509 | | |
| | 3 | 510 | | if (!(char.IsLetter(s[start]) || s[start] == '_')) |
| | | 511 | | { |
| | | 512 | | continue; |
| | | 513 | | } |
| | | 514 | | |
| | 3 | 515 | | end++; |
| | 21 | 516 | | while (end < s.Length) |
| | | 517 | | { |
| | 21 | 518 | | var ch = s[end]; |
| | 21 | 519 | | if (!(char.IsLetterOrDigit(ch) || ch == '_')) |
| | | 520 | | { |
| | | 521 | | break; |
| | | 522 | | } |
| | 18 | 523 | | end++; |
| | | 524 | | } |
| | | 525 | | |
| | 3 | 526 | | var name = s[start..end]; |
| | 3 | 527 | | if (!names.Contains(name, StringComparer.OrdinalIgnoreCase)) |
| | | 528 | | { |
| | 3 | 529 | | names.Add(name); |
| | | 530 | | } |
| | | 531 | | |
| | 3 | 532 | | i = end - 1; |
| | | 533 | | } |
| | | 534 | | |
| | 2 | 535 | | return names; |
| | | 536 | | } |
| | | 537 | | |
| | | 538 | | private static string StripPowerShellAttributeBlocks(string script) |
| | | 539 | | { |
| | 5 | 540 | | if (string.IsNullOrWhiteSpace(script)) |
| | | 541 | | { |
| | 1 | 542 | | return string.Empty; |
| | | 543 | | } |
| | | 544 | | |
| | 4 | 545 | | var sb = new StringBuilder(script.Length); |
| | 4 | 546 | | var i = 0; |
| | 224 | 547 | | while (i < script.Length) |
| | | 548 | | { |
| | 220 | 549 | | var ch = script[i]; |
| | 220 | 550 | | if (ch != '[') |
| | | 551 | | { |
| | 208 | 552 | | _ = sb.Append(ch); |
| | 208 | 553 | | i++; |
| | 208 | 554 | | continue; |
| | | 555 | | } |
| | | 556 | | |
| | | 557 | | // Capture a full bracket block, handling nested [ ... ] (e.g. generic type constraints) |
| | 12 | 558 | | var start = i; |
| | 12 | 559 | | var depth = 0; |
| | 12 | 560 | | var j = i; |
| | 346 | 561 | | while (j < script.Length) |
| | | 562 | | { |
| | 346 | 563 | | var cj = script[j]; |
| | 346 | 564 | | if (cj == '[') |
| | | 565 | | { |
| | 12 | 566 | | depth++; |
| | | 567 | | } |
| | 334 | 568 | | else if (cj == ']') |
| | | 569 | | { |
| | 12 | 570 | | depth--; |
| | 12 | 571 | | if (depth == 0) |
| | | 572 | | { |
| | 12 | 573 | | j++; // include closing ']' |
| | 12 | 574 | | break; |
| | | 575 | | } |
| | | 576 | | } |
| | 334 | 577 | | j++; |
| | | 578 | | } |
| | | 579 | | |
| | | 580 | | // If unbalanced, just emit the rest |
| | 12 | 581 | | if (depth != 0) |
| | | 582 | | { |
| | 0 | 583 | | _ = sb.Append(script.AsSpan(i)); |
| | 0 | 584 | | break; |
| | | 585 | | } |
| | | 586 | | |
| | 12 | 587 | | var block = script.AsSpan(start, j - start); |
| | | 588 | | |
| | | 589 | | // Attribute blocks always include parentheses in our usage (e.g. [OpenApiPath(...)], [Parameter()]). |
| | | 590 | | // Keep type constraints like [string], [int], [MyType], [MyType[]], [List[string]]. |
| | 12 | 591 | | if (block.IndexOf('(') >= 0) |
| | | 592 | | { |
| | 6 | 593 | | i = j; |
| | 6 | 594 | | continue; |
| | | 595 | | } |
| | | 596 | | |
| | 6 | 597 | | _ = sb.Append(block); |
| | 6 | 598 | | i = j; |
| | | 599 | | } |
| | | 600 | | |
| | 4 | 601 | | return sb.ToString(); |
| | | 602 | | } |
| | | 603 | | |
| | | 604 | | /// <summary> |
| | | 605 | | /// Determines if the specified type has an OpenAPI component attribute. |
| | | 606 | | /// </summary> |
| | | 607 | | /// <param name="t">The type to inspect.</param> |
| | | 608 | | /// <returns>True if the type has an OpenAPI component attribute; otherwise, false.</returns> |
| | | 609 | | private static bool HasOpenApiComponentAttribute(Type t) |
| | | 610 | | { |
| | 992 | 611 | | return t.GetCustomAttributes(inherit: true) |
| | 799 | 612 | | .Select(a => a.GetType().Name) |
| | 992 | 613 | | .Any(n => |
| | 1791 | 614 | | n.Contains("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 615 | | } |
| | | 616 | | |
| | | 617 | | /// <summary> |
| | | 618 | | /// Appends the PowerShell class definition for the specified type to the StringBuilder. |
| | | 619 | | /// </summary> |
| | | 620 | | /// <param name="type">The type to export as a PowerShell class.</param> |
| | | 621 | | /// <param name="componentSet">The set of known component types.</param> |
| | | 622 | | /// <param name="sb">The StringBuilder to append the class definition to.</param> |
| | | 623 | | private static void AppendClass(Type type, HashSet<Type> componentSet, StringBuilder sb) |
| | | 624 | | { |
| | 13 | 625 | | var bindFormAttribute = TryBuildKrBindFormAttribute(type, out var formMaxDepth); |
| | 13 | 626 | | var requiredProperties = GetRequiredProperties(type); |
| | 13 | 627 | | var additionalPropertiesMetadata = BuildAdditionalPropertiesMetadata(type); |
| | | 628 | | |
| | 13 | 629 | | var baseClause = ResolveClassBaseClause(type, componentSet, bindFormAttribute, formMaxDepth); |
| | | 630 | | |
| | 13 | 631 | | if (bindFormAttribute is not null) |
| | | 632 | | { |
| | 1 | 633 | | _ = sb.AppendLine(bindFormAttribute); |
| | | 634 | | } |
| | | 635 | | |
| | 13 | 636 | | _ = sb.AppendLine("[NoRunspaceAffinity()]"); |
| | 13 | 637 | | _ = sb.AppendLine($"class {type.Name}{baseClause} {{"); |
| | | 638 | | |
| | | 639 | | // Only properties *declared* on this type (no inherited ones) |
| | 13 | 640 | | var props = type.GetProperties( |
| | 13 | 641 | | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); |
| | | 642 | | |
| | 13 | 643 | | AppendAdditionalPropertiesMembers(type, props, additionalPropertiesMetadata, sb); |
| | | 644 | | |
| | 13 | 645 | | if (requiredProperties.Length > 0) |
| | | 646 | | { |
| | 0 | 647 | | AppendRequiredPropertiesMetadata(requiredProperties, sb); |
| | | 648 | | } |
| | | 649 | | |
| | 106 | 650 | | foreach (var p in props) |
| | | 651 | | { |
| | 40 | 652 | | AppendValidationAttributes(p, sb); |
| | 40 | 653 | | var psType = ToPowerShellTypeName(p.PropertyType, componentSet, collapseToUnderlyingPrimitives: true); |
| | 40 | 654 | | _ = sb.AppendLine($" [{psType}]${p.Name}"); |
| | | 655 | | } |
| | | 656 | | |
| | 13 | 657 | | if (requiredProperties.Length > 0) |
| | | 658 | | { |
| | 0 | 659 | | AppendRequiredPropertiesValidationMethods(requiredProperties, sb); |
| | | 660 | | } |
| | | 661 | | |
| | | 662 | | // Add static XML metadata to guide XmlHelper without requiring PowerShell method invocation |
| | 13 | 663 | | AppendOpenApiXmlMetadataProperty(type, props, sb); |
| | | 664 | | |
| | 13 | 665 | | _ = sb.AppendLine("}"); |
| | 13 | 666 | | } |
| | | 667 | | |
| | | 668 | | /// <summary> |
| | | 669 | | /// Resolves the PowerShell class base clause for an exported OpenAPI component. |
| | | 670 | | /// </summary> |
| | | 671 | | /// <param name="type">The component type being exported.</param> |
| | | 672 | | /// <param name="componentSet">The set of known component types.</param> |
| | | 673 | | /// <param name="bindFormAttribute">The generated KrBindForm attribute text, if any.</param> |
| | | 674 | | /// <param name="formMaxDepth">The resolved KrBindForm.MaxNestingDepth value.</param> |
| | | 675 | | /// <returns>The base clause including leading colon, or an empty string when no base type is emitted.</returns> |
| | | 676 | | private static string ResolveClassBaseClause(Type type, HashSet<Type> componentSet, string? bindFormAttribute, int f |
| | | 677 | | { |
| | 13 | 678 | | if ((bindFormAttribute is null || formMaxDepth > 0) |
| | 13 | 679 | | && TryGetFormPayloadBasePsName(type, out var formBasePsName)) |
| | | 680 | | { |
| | 1 | 681 | | return $" : {formBasePsName}"; |
| | | 682 | | } |
| | | 683 | | |
| | 12 | 684 | | var baseType = type.BaseType; |
| | 12 | 685 | | if (baseType is null || baseType == typeof(object)) |
| | | 686 | | { |
| | 8 | 687 | | return string.Empty; |
| | | 688 | | } |
| | | 689 | | |
| | 4 | 690 | | var basePsName = ToPowerShellTypeName(baseType, componentSet, collapseToUnderlyingPrimitives: false); |
| | 4 | 691 | | return $" : {basePsName}"; |
| | | 692 | | } |
| | | 693 | | |
| | | 694 | | /// <summary> |
| | | 695 | | /// Appends AdditionalProperties members and metadata for a generated class when applicable. |
| | | 696 | | /// </summary> |
| | | 697 | | /// <param name="type">The component type being exported.</param> |
| | | 698 | | /// <param name="props">Declared public instance properties on the type.</param> |
| | | 699 | | /// <param name="additionalPropertiesMetadata">Prebuilt AdditionalProperties metadata block.</param> |
| | | 700 | | /// <param name="sb">The output builder.</param> |
| | | 701 | | private static void AppendAdditionalPropertiesMembers(Type type, PropertyInfo[] props, string additionalPropertiesMe |
| | | 702 | | { |
| | 13 | 703 | | if (ShouldEmitAdditionalProperties(type, props)) |
| | | 704 | | { |
| | 1 | 705 | | _ = sb.AppendLine(" [hashtable]$AdditionalProperties"); |
| | | 706 | | } |
| | | 707 | | |
| | 13 | 708 | | if (string.IsNullOrWhiteSpace(additionalPropertiesMetadata)) |
| | | 709 | | { |
| | 11 | 710 | | return; |
| | | 711 | | } |
| | | 712 | | |
| | 2 | 713 | | _ = sb.AppendLine(); |
| | 2 | 714 | | _ = sb.AppendLine(" # Static AdditionalProperties metadata for this class"); |
| | 2 | 715 | | _ = sb.AppendLine(" static [hashtable] $AdditionalPropertiesMetadata = @{"); |
| | 2 | 716 | | _ = sb.Append(additionalPropertiesMetadata); |
| | 2 | 717 | | _ = sb.AppendLine(" }"); |
| | 2 | 718 | | } |
| | | 719 | | |
| | | 720 | | /// <summary> |
| | | 721 | | /// Determines whether to emit an AdditionalProperties hashtable and metadata based on the presence of an Additional |
| | | 722 | | /// </summary> |
| | | 723 | | /// <param name="type">The type to inspect.</param> |
| | | 724 | | /// <param name="maxDepth">The maximum nesting depth for the form.</param> |
| | | 725 | | /// <returns>A string representing the KrBindForm attribute, or null if not applicable.</returns> |
| | | 726 | | private static string? TryBuildKrBindFormAttribute(Type type, out int maxDepth) |
| | | 727 | | { |
| | 13 | 728 | | maxDepth = 0; |
| | 13 | 729 | | var bindAttr = type.GetCustomAttributes(inherit: false) |
| | 38 | 730 | | .FirstOrDefault(a => a.GetType().Name.Equals("KrBindFormAttribute", StringComparison.OrdinalIgnoreCase)); |
| | | 731 | | |
| | 13 | 732 | | if (bindAttr is null) |
| | | 733 | | { |
| | 12 | 734 | | return null; |
| | | 735 | | } |
| | | 736 | | |
| | 1 | 737 | | var maxDepthProp = bindAttr.GetType().GetProperty("MaxNestingDepth"); |
| | 1 | 738 | | maxDepth = maxDepthProp?.GetValue(bindAttr) as int? ?? 0; |
| | | 739 | | |
| | 1 | 740 | | return maxDepth > 0 |
| | 1 | 741 | | ? $"[KrBindForm(MaxNestingDepth = {maxDepth})]" |
| | 1 | 742 | | : "[KrBindForm()]"; |
| | | 743 | | } |
| | | 744 | | |
| | | 745 | | /// <summary> |
| | | 746 | | /// Gets required property names from OpenApiSchemaComponent metadata on a type. |
| | | 747 | | /// </summary> |
| | | 748 | | /// <param name="type">The type to inspect.</param> |
| | | 749 | | /// <returns>An array of required property names.</returns> |
| | | 750 | | private static string[] GetRequiredProperties(Type type) |
| | | 751 | | { |
| | 13 | 752 | | var schemaAttr = type.GetCustomAttributes(inherit: false) |
| | 36 | 753 | | .FirstOrDefault(a => a.GetType().Name.Equals("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 754 | | |
| | 13 | 755 | | if (schemaAttr is null) |
| | | 756 | | { |
| | 0 | 757 | | return []; |
| | | 758 | | } |
| | | 759 | | |
| | 13 | 760 | | var requiredValues = schemaAttr.GetType().GetProperty("RequiredProperties")?.GetValue(schemaAttr) as string[]; |
| | 13 | 761 | | return requiredValues is { Length: > 0 } |
| | 0 | 762 | | ? [.. requiredValues.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct(StringComparer.OrdinalIgnoreCase)] |
| | 13 | 763 | | : []; |
| | | 764 | | } |
| | | 765 | | |
| | | 766 | | /// <summary> |
| | | 767 | | /// Appends static required-properties metadata to the generated class. |
| | | 768 | | /// </summary> |
| | | 769 | | /// <param name="requiredValues">Required property names to emit.</param> |
| | | 770 | | /// <param name="sb">The output builder.</param> |
| | | 771 | | private static void AppendRequiredPropertiesMetadata(string[] requiredValues, StringBuilder sb) |
| | | 772 | | { |
| | 0 | 773 | | if (requiredValues is not { Length: > 0 }) |
| | | 774 | | { |
| | 0 | 775 | | return; |
| | | 776 | | } |
| | | 777 | | |
| | 0 | 778 | | var requiredTuple = string.Join(", ", requiredValues.Select(v => $"'{EscapePowerShellString(v)}'")); |
| | 0 | 779 | | _ = sb.AppendLine(); |
| | 0 | 780 | | _ = sb.AppendLine(" # Static required property names for this class"); |
| | 0 | 781 | | _ = sb.AppendLine($" static [string[]] $RequiredProperties = @({requiredTuple})"); |
| | 0 | 782 | | } |
| | | 783 | | |
| | | 784 | | /// <summary> |
| | | 785 | | /// Appends instance methods that validate required properties for generated PowerShell classes. |
| | | 786 | | /// </summary> |
| | | 787 | | /// <param name="requiredProperties">The required property names.</param> |
| | | 788 | | /// <param name="sb">The output builder.</param> |
| | | 789 | | private static void AppendRequiredPropertiesValidationMethods(string[] requiredProperties, StringBuilder sb) |
| | | 790 | | { |
| | 0 | 791 | | var requiredTuple = string.Join(", ", requiredProperties.Select(v => $"'{EscapePowerShellString(v)}'")); |
| | | 792 | | |
| | 0 | 793 | | _ = sb.AppendLine(); |
| | 0 | 794 | | _ = sb.AppendLine(" [string[]] GetMissingRequiredProperties() {"); |
| | 0 | 795 | | _ = sb.AppendLine($" $required = @({requiredTuple})"); |
| | 0 | 796 | | _ = sb.AppendLine(" $missing = [System.Collections.Generic.List[string]]::new()"); |
| | 0 | 797 | | _ = sb.AppendLine(" foreach ($name in $required) {"); |
| | 0 | 798 | | _ = sb.AppendLine(" $value = $this.$name"); |
| | 0 | 799 | | _ = sb.AppendLine(" if ($null -eq $value) {"); |
| | 0 | 800 | | _ = sb.AppendLine(" $missing.Add($name)"); |
| | 0 | 801 | | _ = sb.AppendLine(" continue"); |
| | 0 | 802 | | _ = sb.AppendLine(" }"); |
| | 0 | 803 | | _ = sb.AppendLine(" if ($value -is [string] -and [string]::IsNullOrWhiteSpace([string]$value)) {"); |
| | 0 | 804 | | _ = sb.AppendLine(" $missing.Add($name)"); |
| | 0 | 805 | | _ = sb.AppendLine(" continue"); |
| | 0 | 806 | | _ = sb.AppendLine(" }"); |
| | 0 | 807 | | _ = sb.AppendLine(" if ($value -is [System.Collections.ICollection] -and $value.Count -eq 0) {"); |
| | 0 | 808 | | _ = sb.AppendLine(" $missing.Add($name)"); |
| | 0 | 809 | | _ = sb.AppendLine(" }"); |
| | 0 | 810 | | _ = sb.AppendLine(" }"); |
| | 0 | 811 | | _ = sb.AppendLine(" return $missing.ToArray()"); |
| | 0 | 812 | | _ = sb.AppendLine(" }"); |
| | | 813 | | |
| | 0 | 814 | | _ = sb.AppendLine(); |
| | 0 | 815 | | _ = sb.AppendLine(" [bool] ValidateRequiredProperties() {"); |
| | 0 | 816 | | _ = sb.AppendLine(" return $this.GetMissingRequiredProperties().Length -eq 0"); |
| | 0 | 817 | | _ = sb.AppendLine(" }"); |
| | 0 | 818 | | } |
| | | 819 | | |
| | | 820 | | private static bool ShouldEmitAdditionalProperties(Type type, PropertyInfo[] props) |
| | | 821 | | { |
| | 53 | 822 | | if (props.Any(p => string.Equals(p.Name, "AdditionalProperties", StringComparison.OrdinalIgnoreCase))) |
| | | 823 | | { |
| | 1 | 824 | | return false; |
| | | 825 | | } |
| | | 826 | | |
| | 12 | 827 | | var hasPatternProps = type.GetCustomAttributes(inherit: false) |
| | 33 | 828 | | .Any(a => a.GetType().Name.Equals("OpenApiPatternPropertiesAttribute", StringComparison.OrdinalIgnoreCase)); |
| | | 829 | | |
| | 12 | 830 | | if (hasPatternProps) |
| | | 831 | | { |
| | 0 | 832 | | return true; |
| | | 833 | | } |
| | | 834 | | |
| | 12 | 835 | | var schemaAttr = type.GetCustomAttributes(inherit: false) |
| | 32 | 836 | | .FirstOrDefault(a => a.GetType().Name.Equals("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 837 | | |
| | 12 | 838 | | if (schemaAttr is null) |
| | | 839 | | { |
| | 0 | 840 | | return false; |
| | | 841 | | } |
| | | 842 | | |
| | 12 | 843 | | var allowProp = schemaAttr.GetType().GetProperty("AdditionalPropertiesAllowed"); |
| | 12 | 844 | | return (allowProp?.GetValue(schemaAttr) as bool?) == true; |
| | | 845 | | } |
| | | 846 | | |
| | | 847 | | private static string BuildAdditionalPropertiesMetadata(Type type) |
| | | 848 | | { |
| | 13 | 849 | | var schemaAttr = type.GetCustomAttributes(inherit: false) |
| | 36 | 850 | | .FirstOrDefault(a => a.GetType().Name.Equals("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 851 | | |
| | 13 | 852 | | var additionalType = schemaAttr?.GetType().GetProperty("AdditionalProperties")?.GetValue(schemaAttr) as Type; |
| | | 853 | | |
| | 13 | 854 | | var patternAttrs = type.GetCustomAttributes(inherit: false) |
| | 25 | 855 | | .Where(a => a.GetType().Name.Equals("OpenApiPatternPropertiesAttribute", StringComparison.OrdinalIgnoreCase) |
| | 13 | 856 | | .ToArray(); |
| | | 857 | | |
| | 13 | 858 | | if (additionalType is null && patternAttrs.Length == 0) |
| | | 859 | | { |
| | 11 | 860 | | return string.Empty; |
| | | 861 | | } |
| | | 862 | | |
| | 2 | 863 | | var sb = new StringBuilder(); |
| | | 864 | | |
| | 2 | 865 | | if (additionalType is not null) |
| | | 866 | | { |
| | 1 | 867 | | _ = sb.AppendLine($" AdditionalPropertiesType = '{additionalType.FullName ?? additionalType.Name}'"); |
| | | 868 | | } |
| | | 869 | | |
| | 2 | 870 | | if (patternAttrs.Length > 0) |
| | | 871 | | { |
| | 1 | 872 | | _ = sb.AppendLine(" PatternProperties = @("); |
| | | 873 | | |
| | 4 | 874 | | foreach (var attr in patternAttrs) |
| | | 875 | | { |
| | 1 | 876 | | var keyPattern = attr.GetType().GetProperty("KeyPattern")?.GetValue(attr) as string ?? string.Empty; |
| | 1 | 877 | | var schemaType = attr.GetType().GetProperty("SchemaType")?.GetValue(attr) as Type ?? typeof(string); |
| | | 878 | | |
| | 1 | 879 | | _ = sb.AppendLine(" @{"); |
| | 1 | 880 | | _ = sb.AppendLine($" KeyPattern = '{EscapePowerShellString(keyPattern)}'"); |
| | 1 | 881 | | _ = sb.AppendLine($" SchemaType = '{schemaType.FullName ?? schemaType.Name}'"); |
| | 1 | 882 | | _ = sb.AppendLine(" }"); |
| | | 883 | | } |
| | | 884 | | |
| | 1 | 885 | | _ = sb.AppendLine(" )"); |
| | | 886 | | } |
| | | 887 | | |
| | 2 | 888 | | return sb.ToString(); |
| | | 889 | | } |
| | | 890 | | |
| | | 891 | | /// <summary> |
| | | 892 | | /// Appends a static hashtable property containing OpenApiXml metadata for the class and its properties. |
| | | 893 | | /// </summary> |
| | | 894 | | /// <remarks> |
| | | 895 | | /// This is emitted as a static property (not a PowerShell class method) so that C# reflection can read the |
| | | 896 | | /// metadata without requiring a PowerShell execution context bound to the current thread. |
| | | 897 | | /// </remarks> |
| | | 898 | | /// <param name="type">The type to extract OpenApiXml metadata from.</param> |
| | | 899 | | /// <param name="props">The properties of the type.</param> |
| | | 900 | | /// <param name="sb">The StringBuilder to append to.</param> |
| | | 901 | | private static void AppendOpenApiXmlMetadataProperty(Type type, PropertyInfo[] props, StringBuilder sb) |
| | | 902 | | { |
| | 13 | 903 | | _ = sb.AppendLine(); |
| | 13 | 904 | | _ = sb.AppendLine(" # Static OpenApiXml metadata for this class"); |
| | 13 | 905 | | _ = sb.AppendLine(" static [hashtable] $XmlMetadata = @{"); |
| | 13 | 906 | | _ = sb.AppendLine(" ClassName = '" + type.Name + "'"); |
| | | 907 | | |
| | | 908 | | // Get class-level OpenApiXml attribute |
| | 13 | 909 | | var classXmlAttr = type.GetCustomAttributes(inherit: false) |
| | 38 | 910 | | .FirstOrDefault(a => a.GetType().Name == "OpenApiXmlAttribute"); |
| | | 911 | | |
| | 13 | 912 | | if (classXmlAttr != null) |
| | | 913 | | { |
| | 0 | 914 | | var classXml = BuildXmlMetadataHashtable(classXmlAttr, indent: 12); |
| | 0 | 915 | | if (!string.IsNullOrWhiteSpace(classXml)) |
| | | 916 | | { |
| | 0 | 917 | | _ = sb.AppendLine(" ClassXml = @{"); |
| | 0 | 918 | | _ = sb.AppendLine(classXml); |
| | 0 | 919 | | _ = sb.AppendLine(" }"); |
| | | 920 | | } |
| | | 921 | | } |
| | | 922 | | |
| | | 923 | | // Get property-level OpenApiXml attributes |
| | 13 | 924 | | if (props.Length > 0) |
| | | 925 | | { |
| | 10 | 926 | | _ = sb.AppendLine(" Properties = @{"); |
| | 10 | 927 | | var hasAnyPropertyXml = false; |
| | | 928 | | |
| | 100 | 929 | | foreach (var prop in props) |
| | | 930 | | { |
| | 40 | 931 | | var propXmlAttr = prop.GetCustomAttributes(inherit: false) |
| | 52 | 932 | | .FirstOrDefault(a => a.GetType().Name == "OpenApiXmlAttribute"); |
| | | 933 | | |
| | 40 | 934 | | if (propXmlAttr != null) |
| | | 935 | | { |
| | 0 | 936 | | var propXml = BuildXmlMetadataHashtable(propXmlAttr, indent: 16); |
| | 0 | 937 | | if (!string.IsNullOrWhiteSpace(propXml)) |
| | | 938 | | { |
| | 0 | 939 | | hasAnyPropertyXml = true; |
| | 0 | 940 | | _ = sb.AppendLine($" '{prop.Name}' = @{{"); |
| | 0 | 941 | | _ = sb.AppendLine(propXml); |
| | 0 | 942 | | _ = sb.AppendLine(" }"); |
| | | 943 | | } |
| | | 944 | | } |
| | | 945 | | } |
| | | 946 | | |
| | 10 | 947 | | if (!hasAnyPropertyXml) |
| | | 948 | | { |
| | 10 | 949 | | _ = sb.AppendLine(" # No property-level XML metadata"); |
| | | 950 | | } |
| | | 951 | | |
| | 10 | 952 | | _ = sb.AppendLine(" }"); |
| | | 953 | | } |
| | | 954 | | |
| | 13 | 955 | | _ = sb.AppendLine(" }"); |
| | 13 | 956 | | } |
| | | 957 | | |
| | | 958 | | /// <summary> |
| | | 959 | | /// Builds a PowerShell hashtable representation of OpenApiXml attribute properties. |
| | | 960 | | /// </summary> |
| | | 961 | | /// <param name="xmlAttr">The OpenApiXml attribute instance.</param> |
| | | 962 | | /// <param name="indent">Number of spaces to indent.</param> |
| | | 963 | | /// <returns>PowerShell hashtable string representation.</returns> |
| | | 964 | | private static string BuildXmlMetadataHashtable(object xmlAttr, int indent) |
| | | 965 | | { |
| | 0 | 966 | | var attrType = xmlAttr.GetType(); |
| | 0 | 967 | | var sb = new StringBuilder(); |
| | 0 | 968 | | var indentStr = new string(' ', indent); |
| | | 969 | | |
| | | 970 | | // Extract properties using reflection |
| | 0 | 971 | | var nameProp = attrType.GetProperty("Name"); |
| | 0 | 972 | | var namespaceProp = attrType.GetProperty("Namespace"); |
| | 0 | 973 | | var prefixProp = attrType.GetProperty("Prefix"); |
| | 0 | 974 | | var attributeProp = attrType.GetProperty("Attribute"); |
| | 0 | 975 | | var wrappedProp = attrType.GetProperty("Wrapped"); |
| | | 976 | | |
| | 0 | 977 | | var name = nameProp?.GetValue(xmlAttr) as string; |
| | 0 | 978 | | var ns = namespaceProp?.GetValue(xmlAttr) as string; |
| | 0 | 979 | | var prefix = prefixProp?.GetValue(xmlAttr) as string; |
| | 0 | 980 | | var isAttribute = attributeProp?.GetValue(xmlAttr) is bool b && b; |
| | 0 | 981 | | var isWrapped = wrappedProp?.GetValue(xmlAttr) is bool w && w; |
| | | 982 | | |
| | 0 | 983 | | if (!string.IsNullOrWhiteSpace(name)) |
| | | 984 | | { |
| | 0 | 985 | | _ = sb.AppendLine($"{indentStr}Name = '{EscapePowerShellString(name)}'"); |
| | | 986 | | } |
| | | 987 | | |
| | 0 | 988 | | if (!string.IsNullOrWhiteSpace(ns)) |
| | | 989 | | { |
| | 0 | 990 | | _ = sb.AppendLine($"{indentStr}Namespace = '{EscapePowerShellString(ns)}'"); |
| | | 991 | | } |
| | | 992 | | |
| | 0 | 993 | | if (!string.IsNullOrWhiteSpace(prefix)) |
| | | 994 | | { |
| | 0 | 995 | | _ = sb.AppendLine($"{indentStr}Prefix = '{EscapePowerShellString(prefix)}'"); |
| | | 996 | | } |
| | | 997 | | |
| | 0 | 998 | | if (isAttribute) |
| | | 999 | | { |
| | 0 | 1000 | | _ = sb.AppendLine($"{indentStr}Attribute = $true"); |
| | | 1001 | | } |
| | | 1002 | | |
| | 0 | 1003 | | if (isWrapped) |
| | | 1004 | | { |
| | 0 | 1005 | | _ = sb.AppendLine($"{indentStr}Wrapped = $true"); |
| | | 1006 | | } |
| | | 1007 | | |
| | 0 | 1008 | | return sb.ToString().TrimEnd(); |
| | | 1009 | | } |
| | | 1010 | | |
| | | 1011 | | /// <summary> |
| | | 1012 | | /// Escapes single quotes in a string for PowerShell string literals. |
| | | 1013 | | /// </summary> |
| | | 1014 | | /// <param name="str">The string to escape.</param> |
| | | 1015 | | /// <returns>Escaped string safe for PowerShell single-quoted strings.</returns> |
| | 1 | 1016 | | private static string EscapePowerShellString(string str) => str.Replace("'", "''"); |
| | | 1017 | | |
| | | 1018 | | private static void AppendValidationAttributes(PropertyInfo property, StringBuilder sb) |
| | | 1019 | | { |
| | 40 | 1020 | | var attributes = property.GetCustomAttributes(inherit: false) |
| | 40 | 1021 | | .Select(TryFormatValidationAttribute) |
| | 12 | 1022 | | .Where(s => !string.IsNullOrWhiteSpace(s)) |
| | 40 | 1023 | | .ToList(); |
| | | 1024 | | |
| | 80 | 1025 | | foreach (var attribute in attributes) |
| | | 1026 | | { |
| | 0 | 1027 | | _ = sb.Append(" ").AppendLine(attribute); |
| | | 1028 | | } |
| | 40 | 1029 | | } |
| | | 1030 | | |
| | | 1031 | | private static string? TryFormatValidationAttribute(object attribute) |
| | | 1032 | | { |
| | 12 | 1033 | | var typeName = attribute.GetType().Name; |
| | | 1034 | | |
| | 12 | 1035 | | return typeName switch |
| | 12 | 1036 | | { |
| | 0 | 1037 | | "ValidateRangeAttribute" => FormatValidateRange(attribute), |
| | 0 | 1038 | | "ValidateLengthAttribute" => FormatValidateLength(attribute), |
| | 0 | 1039 | | "ValidateSetAttribute" => FormatValidateSet(attribute), |
| | 0 | 1040 | | "ValidatePatternAttribute" => FormatValidatePattern(attribute), |
| | 0 | 1041 | | "ValidateCountAttribute" => FormatValidateCount(attribute), |
| | 0 | 1042 | | "ValidateNotNullOrEmptyAttribute" => "[ValidateNotNullOrEmpty()]", |
| | 0 | 1043 | | "ValidateNotNullAttribute" => "[ValidateNotNull()]", |
| | 0 | 1044 | | "ValidateNotNullOrWhiteSpaceAttribute" => "[ValidateNotNullOrWhiteSpace()]", |
| | 12 | 1045 | | _ => null |
| | 12 | 1046 | | }; |
| | | 1047 | | } |
| | | 1048 | | |
| | | 1049 | | private static string? FormatValidateRange(object attribute) |
| | | 1050 | | { |
| | 0 | 1051 | | var min = attribute.GetType().GetProperty("MinRange")?.GetValue(attribute); |
| | 0 | 1052 | | var max = attribute.GetType().GetProperty("MaxRange")?.GetValue(attribute); |
| | 0 | 1053 | | return min is null || max is null ? null : $"[ValidateRange({FormatPowerShellLiteral(min)}, {FormatPowerShellLit |
| | | 1054 | | } |
| | | 1055 | | |
| | | 1056 | | private static string? FormatValidateLength(object attribute) |
| | | 1057 | | { |
| | 0 | 1058 | | var min = attribute.GetType().GetProperty("MinLength")?.GetValue(attribute); |
| | 0 | 1059 | | var max = attribute.GetType().GetProperty("MaxLength")?.GetValue(attribute); |
| | 0 | 1060 | | return min is null || max is null ? null : $"[ValidateLength({FormatPowerShellLiteral(min)}, {FormatPowerShellLi |
| | | 1061 | | } |
| | | 1062 | | |
| | | 1063 | | private static string? FormatValidateCount(object attribute) |
| | | 1064 | | { |
| | 0 | 1065 | | var min = attribute.GetType().GetProperty("MinLength")?.GetValue(attribute); |
| | 0 | 1066 | | var max = attribute.GetType().GetProperty("MaxLength")?.GetValue(attribute); |
| | 0 | 1067 | | return min is null || max is null ? null : $"[ValidateCount({FormatPowerShellLiteral(min)}, {FormatPowerShellLit |
| | | 1068 | | } |
| | | 1069 | | |
| | | 1070 | | private static string? FormatValidatePattern(object attribute) |
| | | 1071 | | { |
| | 0 | 1072 | | var pattern = attribute.GetType().GetProperty("RegexPattern")?.GetValue(attribute) as string; |
| | 0 | 1073 | | return string.IsNullOrWhiteSpace(pattern) ? null : $"[ValidatePattern('{EscapePowerShellString(pattern)}')]"; |
| | | 1074 | | } |
| | | 1075 | | |
| | | 1076 | | private static string? FormatValidateSet(object attribute) |
| | | 1077 | | { |
| | 0 | 1078 | | if (attribute.GetType().GetProperty("ValidValues")?.GetValue(attribute) is not IEnumerable<object> values) |
| | | 1079 | | { |
| | 0 | 1080 | | return null; |
| | | 1081 | | } |
| | | 1082 | | |
| | 0 | 1083 | | var formatted = values |
| | 0 | 1084 | | .Select(FormatPowerShellLiteral) |
| | 0 | 1085 | | .Where(v => !string.IsNullOrWhiteSpace(v)) |
| | 0 | 1086 | | .ToArray(); |
| | | 1087 | | |
| | 0 | 1088 | | return formatted.Length == 0 ? null : $"[ValidateSet({string.Join(", ", formatted)})]"; |
| | | 1089 | | } |
| | | 1090 | | |
| | | 1091 | | private static string? FormatPowerShellLiteral(object? value) |
| | | 1092 | | { |
| | 0 | 1093 | | return value is null |
| | 0 | 1094 | | ? "$null" |
| | 0 | 1095 | | : value switch |
| | 0 | 1096 | | { |
| | 0 | 1097 | | string s => $"'{EscapePowerShellString(s)}'", |
| | 0 | 1098 | | char c => $"'{EscapePowerShellString(c.ToString())}'", |
| | 0 | 1099 | | bool b => b ? "$true" : "$false", |
| | 0 | 1100 | | byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal => |
| | 0 | 1101 | | Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture), |
| | 0 | 1102 | | _ => $"'{EscapePowerShellString(Convert.ToString(value, System.Globalization.CultureInfo.InvariantCultur |
| | 0 | 1103 | | }; |
| | | 1104 | | } |
| | | 1105 | | |
| | | 1106 | | /// <summary> |
| | | 1107 | | /// Converts a .NET type to a PowerShell type name. |
| | | 1108 | | /// </summary> |
| | | 1109 | | /// <param name="t"></param> |
| | | 1110 | | /// <param name="componentSet"></param> |
| | | 1111 | | /// <param name="collapseToUnderlyingPrimitives">When true, types derived from OpenApiValue<T> are emitted as |
| | | 1112 | | /// <returns></returns> |
| | | 1113 | | private static string ToPowerShellTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | | 1114 | | { |
| | 56 | 1115 | | return GetNullableTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 56 | 1116 | | ?? GetOpenApiArrayWrapperTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 56 | 1117 | | ?? GetCollapsedOpenApiPrimitiveTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 56 | 1118 | | ?? GetEnumTypeName(t) |
| | 56 | 1119 | | ?? GetPrimitiveTypeName(t) |
| | 56 | 1120 | | ?? GetArrayTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 56 | 1121 | | ?? FormatComponentOrFallbackName(t, componentSet); |
| | | 1122 | | } |
| | | 1123 | | |
| | | 1124 | | /// <summary> |
| | | 1125 | | /// Produces a PowerShell nullable type constraint (e.g. <c>Nullable[int]</c>) when the input is a <c>Nullable<T& |
| | | 1126 | | /// </summary> |
| | | 1127 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1128 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1129 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 1130 | | /// <returns>The nullable type name, or <c>null</c> when <paramref name="t"/> is not nullable.</returns> |
| | | 1131 | | private static string? GetNullableTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | | 1132 | | { |
| | 56 | 1133 | | return Nullable.GetUnderlyingType(t) is Type underlying |
| | 56 | 1134 | | ? $"Nullable[{ToPowerShellTypeName(underlying, componentSet, collapseToUnderlyingPrimitives)}]" |
| | 56 | 1135 | | : null; |
| | | 1136 | | } |
| | | 1137 | | |
| | | 1138 | | /// <summary> |
| | | 1139 | | /// Produces an element-array type constraint for OpenAPI schema component array wrapper types when appropriate. |
| | | 1140 | | /// </summary> |
| | | 1141 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1142 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1143 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 1144 | | /// <returns>The array wrapper type name, or <c>null</c> when <paramref name="t"/> is not an OpenAPI array wrapper t |
| | | 1145 | | private static string? GetOpenApiArrayWrapperTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingP |
| | 54 | 1146 | | => ResolveElementArrayType(t, componentSet, collapseToUnderlyingPrimitives); |
| | | 1147 | | |
| | | 1148 | | /// <summary> |
| | | 1149 | | /// Produces the underlying primitive PowerShell type name for OpenAPI primitive wrapper types (e.g. OpenApiString/O |
| | | 1150 | | /// </summary> |
| | | 1151 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1152 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1153 | | /// <param name="collapseToUnderlyingPrimitives">Whether collapsing is enabled.</param> |
| | | 1154 | | /// <returns>The primitive name, or <c>null</c> when <paramref name="t"/> is not an OpenAPI wrapper type (or collaps |
| | | 1155 | | /// <remarks> |
| | | 1156 | | /// When <paramref name="collapseToUnderlyingPrimitives"/> is <c>true</c>, |
| | | 1157 | | /// types derived from OpenApiValue<T> are emitted as their underlying primitive (e.g., string/double/bool/lon |
| | | 1158 | | /// </remarks> |
| | | 1159 | | private static string? GetCollapsedOpenApiPrimitiveTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnder |
| | 53 | 1160 | | => collapseToUnderlyingPrimitives |
| | 53 | 1161 | | && TryGetOpenApiValueUnderlyingType(t, out var underlying) |
| | 53 | 1162 | | && underlying is not null |
| | 53 | 1163 | | ? ToPowerShellTypeName(underlying, componentSet, collapseToUnderlyingPrimitives) |
| | 53 | 1164 | | : null; |
| | | 1165 | | |
| | | 1166 | | /// <summary> |
| | | 1167 | | /// Produces the simple name for enum types so PowerShell can bind against the emitted enum definition. |
| | | 1168 | | /// </summary> |
| | | 1169 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1170 | | /// <returns>The enum name, or <c>null</c> when <paramref name="t"/> is not an enum.</returns> |
| | | 1171 | | private static string? GetEnumTypeName(Type t) |
| | 47 | 1172 | | => t.IsEnum ? t.Name : null; |
| | | 1173 | | |
| | | 1174 | | /// <summary> |
| | | 1175 | | /// Produces the PowerShell type name for well-known CLR primitives. |
| | | 1176 | | /// </summary> |
| | | 1177 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1178 | | /// <returns>The primitive name, or <c>null</c> when no primitive mapping exists.</returns> |
| | | 1179 | | private static string? GetPrimitiveTypeName(Type t) |
| | 46 | 1180 | | => ResolvePrimitiveTypeName(t); |
| | | 1181 | | |
| | | 1182 | | /// <summary> |
| | | 1183 | | /// Produces a PowerShell element-array type constraint (e.g. <c>string[]</c>) for CLR array types. |
| | | 1184 | | /// </summary> |
| | | 1185 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 1186 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1187 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 1188 | | /// <returns>The formatted array name, or <c>null</c> when <paramref name="t"/> is not an array.</returns> |
| | | 1189 | | private static string? GetArrayTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | 11 | 1190 | | => t.IsArray && t.GetElementType() is Type elementType |
| | 11 | 1191 | | ? $"{ToPowerShellTypeName(elementType, componentSet, collapseToUnderlyingPrimitives)}[]" |
| | 11 | 1192 | | : null; |
| | | 1193 | | |
| | | 1194 | | /// <summary> |
| | | 1195 | | /// Formats a component type as its simple name or falls back to full name for other reference types. |
| | | 1196 | | /// </summary> |
| | | 1197 | | /// <param name="t">The CLR type to format.</param> |
| | | 1198 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1199 | | /// <returns>A PowerShell-friendly type name.</returns> |
| | | 1200 | | private static string FormatComponentOrFallbackName(Type t, HashSet<Type> componentSet) |
| | 8 | 1201 | | => componentSet.Contains(t) || t.FullName is null |
| | 8 | 1202 | | ? t.Name |
| | 8 | 1203 | | : t.FullName; |
| | | 1204 | | |
| | | 1205 | | /// <summary> |
| | | 1206 | | /// Collects enums referenced by component properties so they can be emitted before class definitions. |
| | | 1207 | | /// </summary> |
| | | 1208 | | /// <param name="componentTypes">Component classes to scan.</param> |
| | | 1209 | | /// <returns>A de-duplicated list of enums to export.</returns> |
| | | 1210 | | private static IEnumerable<Type> CollectExportableEnums(IEnumerable<Type> componentTypes) |
| | | 1211 | | { |
| | 67 | 1212 | | var enums = new HashSet<Type>(); |
| | | 1213 | | |
| | 160 | 1214 | | foreach (var componentType in componentTypes) |
| | | 1215 | | { |
| | 106 | 1216 | | foreach (var p in componentType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Dec |
| | | 1217 | | { |
| | 82 | 1218 | | foreach (var enumType in FindEnumsInType(p.PropertyType)) |
| | | 1219 | | { |
| | 1 | 1220 | | _ = enums.Add(enumType); |
| | | 1221 | | } |
| | | 1222 | | } |
| | | 1223 | | } |
| | | 1224 | | |
| | 67 | 1225 | | return enums; |
| | | 1226 | | } |
| | | 1227 | | |
| | | 1228 | | /// <summary> |
| | | 1229 | | /// Finds any enum types within a possibly wrapped type (nullable/array/generic). |
| | | 1230 | | /// </summary> |
| | | 1231 | | /// <param name="t">Type to inspect.</param> |
| | | 1232 | | /// <returns>Zero or more enum types found.</returns> |
| | | 1233 | | private static IEnumerable<Type> FindEnumsInType(Type t) |
| | | 1234 | | { |
| | | 1235 | | // Nullable<T> |
| | 46 | 1236 | | if (Nullable.GetUnderlyingType(t) is Type underlying) |
| | | 1237 | | { |
| | 4 | 1238 | | foreach (var e in FindEnumsInType(underlying)) |
| | | 1239 | | { |
| | 0 | 1240 | | yield return e; |
| | | 1241 | | } |
| | 2 | 1242 | | yield break; |
| | | 1243 | | } |
| | | 1244 | | |
| | | 1245 | | // Arrays |
| | 44 | 1246 | | if (t.IsArray) |
| | | 1247 | | { |
| | 8 | 1248 | | foreach (var e in FindEnumsInType(t.GetElementType()!)) |
| | | 1249 | | { |
| | 0 | 1250 | | yield return e; |
| | | 1251 | | } |
| | 4 | 1252 | | yield break; |
| | | 1253 | | } |
| | | 1254 | | |
| | | 1255 | | // Generic arguments |
| | 40 | 1256 | | if (t.IsGenericType) |
| | | 1257 | | { |
| | 0 | 1258 | | foreach (var arg in t.GetGenericArguments()) |
| | | 1259 | | { |
| | 0 | 1260 | | foreach (var e in FindEnumsInType(arg)) |
| | | 1261 | | { |
| | 0 | 1262 | | yield return e; |
| | | 1263 | | } |
| | | 1264 | | } |
| | | 1265 | | } |
| | | 1266 | | |
| | 40 | 1267 | | if (t.IsEnum) |
| | | 1268 | | { |
| | 1 | 1269 | | yield return t; |
| | | 1270 | | } |
| | 40 | 1271 | | } |
| | | 1272 | | |
| | | 1273 | | /// <summary> |
| | | 1274 | | /// Appends a PowerShell enum definition for the specified .NET enum type. |
| | | 1275 | | /// </summary> |
| | | 1276 | | /// <param name="enumType">Enum type to emit.</param> |
| | | 1277 | | /// <param name="sb">Output StringBuilder.</param> |
| | | 1278 | | private static void AppendEnum(Type enumType, StringBuilder sb) |
| | | 1279 | | { |
| | 1 | 1280 | | if (!enumType.IsEnum) |
| | | 1281 | | { |
| | 0 | 1282 | | return; |
| | | 1283 | | } |
| | | 1284 | | |
| | 1 | 1285 | | var underlying = Enum.GetUnderlyingType(enumType); |
| | 1 | 1286 | | var psUnderlying = ResolvePrimitiveTypeName(underlying) ?? underlying.FullName ?? "int"; |
| | | 1287 | | |
| | 1 | 1288 | | _ = sb.AppendLine($"enum {enumType.Name} {{"); |
| | | 1289 | | |
| | 8 | 1290 | | foreach (var name in Enum.GetNames(enumType)) |
| | | 1291 | | { |
| | 3 | 1292 | | var rawValue = Enum.Parse(enumType, name); |
| | 3 | 1293 | | var numericValue = Convert.ChangeType(rawValue, underlying, provider: System.Globalization.CultureInfo.Invar |
| | | 1294 | | |
| | | 1295 | | // Always emit explicit values to preserve non-sequential enums. |
| | 3 | 1296 | | _ = sb.AppendLine($" {name} = [{psUnderlying}]{numericValue}"); |
| | | 1297 | | } |
| | | 1298 | | |
| | 1 | 1299 | | _ = sb.AppendLine("}"); |
| | 1 | 1300 | | } |
| | | 1301 | | |
| | | 1302 | | /// <summary> |
| | | 1303 | | /// Resolves the PowerShell type name for OpenAPI array wrapper components. |
| | | 1304 | | /// </summary> |
| | | 1305 | | /// <param name="t">The .NET type to resolve.</param> |
| | | 1306 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 1307 | | /// <param name="collapseToUnderlyingPrimitives">When true, types derived from OpenApiValue<T> are emitted as |
| | | 1308 | | /// <returns>The PowerShell type name for the array element if applicable; otherwise, null.</returns> |
| | | 1309 | | private static string? ResolveElementArrayType(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitiv |
| | | 1310 | | { |
| | | 1311 | | // OpenAPI schema component array wrappers: |
| | | 1312 | | // Some PowerShell OpenAPI schemas are modeled as a component class with Array=$true, |
| | | 1313 | | // typically inheriting from the element schema type (e.g. EventDates : Date). |
| | | 1314 | | // When referenced as a property type, we want the PowerShell type constraint to be |
| | | 1315 | | // the element array (e.g. [Date[]]) instead of the wrapper class ([EventDates]). |
| | | 1316 | | // IMPORTANT: this must run before OpenApiValue<T> collapsing so wrappers don't lose their array-ness. |
| | 54 | 1317 | | if (collapseToUnderlyingPrimitives && componentSet.Contains(t) && TryGetArrayComponentElementType(t, out var ele |
| | | 1318 | | { |
| | | 1319 | | // Guard against pathological self-references. |
| | 1 | 1320 | | if (elementType == t) |
| | | 1321 | | { |
| | 0 | 1322 | | return t.Name; |
| | | 1323 | | } |
| | | 1324 | | |
| | 1 | 1325 | | var elementPsName = ToPowerShellTypeName(elementType, componentSet, collapseToUnderlyingPrimitives); |
| | 1 | 1326 | | return $"{elementPsName}[]"; |
| | | 1327 | | } |
| | 53 | 1328 | | return null; |
| | | 1329 | | } |
| | | 1330 | | |
| | | 1331 | | // Mapping of .NET primitive types to PowerShell type names. |
| | 1 | 1332 | | private static readonly Dictionary<Type, string> PrimitiveTypeAliases = |
| | 1 | 1333 | | new() |
| | 1 | 1334 | | { |
| | 1 | 1335 | | [typeof(bool)] = "bool", |
| | 1 | 1336 | | [typeof(byte)] = "byte", |
| | 1 | 1337 | | [typeof(sbyte)] = "sbyte", |
| | 1 | 1338 | | [typeof(short)] = "short", |
| | 1 | 1339 | | [typeof(ushort)] = "ushort", |
| | 1 | 1340 | | [typeof(int)] = "int", |
| | 1 | 1341 | | [typeof(uint)] = "uint", |
| | 1 | 1342 | | [typeof(long)] = "long", |
| | 1 | 1343 | | [typeof(ulong)] = "ulong", |
| | 1 | 1344 | | [typeof(float)] = "float", |
| | 1 | 1345 | | [typeof(double)] = "double", |
| | 1 | 1346 | | [typeof(decimal)] = "decimal", |
| | 1 | 1347 | | [typeof(char)] = "char", |
| | 1 | 1348 | | [typeof(string)] = "string", |
| | 1 | 1349 | | [typeof(object)] = "object", |
| | 1 | 1350 | | [typeof(DateTime)] = "datetime", |
| | 1 | 1351 | | [typeof(Guid)] = "guid", |
| | 1 | 1352 | | [typeof(byte[])] = "byte[]" |
| | 1 | 1353 | | }; |
| | | 1354 | | |
| | | 1355 | | /// <summary> |
| | | 1356 | | /// Resolves the PowerShell type name for common .NET primitive types. |
| | | 1357 | | /// </summary> |
| | | 1358 | | /// <param name="t">The .NET type to resolve.</param> |
| | | 1359 | | /// <returns>The PowerShell type name if the type is a recognized primitive; otherwise, null.</returns> |
| | | 1360 | | private static string? ResolvePrimitiveTypeName(Type t) |
| | | 1361 | | { |
| | | 1362 | | // unwrap nullable if needed |
| | 47 | 1363 | | t = Nullable.GetUnderlyingType(t) ?? t; |
| | | 1364 | | |
| | 47 | 1365 | | return PrimitiveTypeAliases.TryGetValue(t, out var alias) ? alias : null; |
| | | 1366 | | } |
| | | 1367 | | |
| | | 1368 | | private static bool TryGetOpenApiValueUnderlyingType(Type t, out Type? underlyingType) |
| | | 1369 | | { |
| | 49 | 1370 | | underlyingType = null; |
| | | 1371 | | |
| | | 1372 | | // Walk base types looking for OpenApiScalar<T> (preferred) or OpenApiValue<T> (legacy) |
| | | 1373 | | // by name to avoid hard coupling. |
| | | 1374 | | // OpenApiScalar<T> lives in Kestrun.Annotations and is in the global namespace. |
| | 49 | 1375 | | var current = t; |
| | | 1376 | | |
| | 127 | 1377 | | while (current is not null && current != typeof(object)) |
| | | 1378 | | { |
| | 84 | 1379 | | if (current.IsGenericType) |
| | | 1380 | | { |
| | 6 | 1381 | | var def = current.GetGenericTypeDefinition(); |
| | 6 | 1382 | | if (string.Equals(def.Name, "OpenApiScalar`1", StringComparison.Ordinal) || |
| | 6 | 1383 | | string.Equals(def.Name, "OpenApiValue`1", StringComparison.Ordinal)) |
| | | 1384 | | { |
| | 6 | 1385 | | underlyingType = current.GetGenericArguments()[0]; |
| | 6 | 1386 | | return true; |
| | | 1387 | | } |
| | | 1388 | | } |
| | | 1389 | | |
| | 78 | 1390 | | current = current.BaseType; |
| | | 1391 | | } |
| | | 1392 | | |
| | 43 | 1393 | | return false; |
| | | 1394 | | } |
| | | 1395 | | |
| | | 1396 | | private static bool TryGetArrayComponentElementType(Type componentType, out Type? elementType) |
| | | 1397 | | { |
| | 6 | 1398 | | elementType = null; |
| | | 1399 | | |
| | | 1400 | | // We don't take a hard dependency on the annotation type here; this exporter |
| | | 1401 | | // may reflect PowerShell-generated assemblies. We detect the attribute by name |
| | | 1402 | | // and then read common properties via reflection. |
| | 6 | 1403 | | var attr = componentType |
| | 6 | 1404 | | .GetCustomAttributes(inherit: false) |
| | 15 | 1405 | | .FirstOrDefault(a => a.GetType().Name.Contains("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase) |
| | | 1406 | | |
| | 6 | 1407 | | if (attr is null) |
| | | 1408 | | { |
| | 0 | 1409 | | return false; |
| | | 1410 | | } |
| | | 1411 | | |
| | 6 | 1412 | | var attrType = attr.GetType(); |
| | 6 | 1413 | | var arrayProp = attrType.GetProperty("Array"); |
| | 6 | 1414 | | if (arrayProp?.GetValue(attr) is not bool isArray || !isArray) |
| | | 1415 | | { |
| | 5 | 1416 | | return false; |
| | | 1417 | | } |
| | | 1418 | | |
| | | 1419 | | // Prefer explicit ItemsType if provided. |
| | 1 | 1420 | | var itemsTypeProp = attrType.GetProperty("ItemsType"); |
| | 1 | 1421 | | if (itemsTypeProp?.GetValue(attr) is Type itemsType) |
| | | 1422 | | { |
| | 0 | 1423 | | elementType = itemsType; |
| | 0 | 1424 | | return true; |
| | | 1425 | | } |
| | | 1426 | | |
| | | 1427 | | // Common PowerShell pattern: wrapper inherits from element schema. |
| | 1 | 1428 | | var baseType = componentType.BaseType; |
| | 1 | 1429 | | if (baseType is not null && baseType != typeof(object)) |
| | | 1430 | | { |
| | 1 | 1431 | | elementType = baseType; |
| | 1 | 1432 | | return true; |
| | | 1433 | | } |
| | | 1434 | | |
| | 0 | 1435 | | return false; |
| | | 1436 | | } |
| | | 1437 | | |
| | | 1438 | | /// <summary> |
| | | 1439 | | /// Topologically sort types so that dependencies (property types) |
| | | 1440 | | /// appear before the types that reference them. |
| | | 1441 | | /// </summary> |
| | | 1442 | | /// <param name="types">The list of types to sort.</param> |
| | | 1443 | | /// <param name="componentSet">Set of component types for quick lookup.</param> |
| | | 1444 | | /// <returns>The sorted list of types.</returns> |
| | | 1445 | | private static List<Type> TopologicalSortByPropertyDependencies( |
| | | 1446 | | List<Type> types, |
| | | 1447 | | HashSet<Type> componentSet) |
| | | 1448 | | { |
| | 67 | 1449 | | var result = new List<Type>(); |
| | 67 | 1450 | | var visited = new Dictionary<Type, bool>(); // false = temp-mark, true = perm-mark |
| | | 1451 | | |
| | 160 | 1452 | | foreach (var t in types) |
| | | 1453 | | { |
| | 13 | 1454 | | Visit(t, componentSet, visited, result); |
| | | 1455 | | } |
| | | 1456 | | |
| | 67 | 1457 | | return result; |
| | | 1458 | | } |
| | | 1459 | | |
| | | 1460 | | /// <summary> |
| | | 1461 | | /// Visits the type and its dependencies recursively for topological sorting. |
| | | 1462 | | /// </summary> |
| | | 1463 | | /// <param name="t">Type to visit</param> |
| | | 1464 | | /// <param name="componentSet">Set of component types</param> |
| | | 1465 | | /// <param name="visited">Dictionary tracking visited types and their mark status</param> |
| | | 1466 | | /// <param name="result">List to accumulate the sorted types</param> |
| | | 1467 | | private static void Visit( |
| | | 1468 | | Type t, |
| | | 1469 | | HashSet<Type> componentSet, |
| | | 1470 | | Dictionary<Type, bool> visited, |
| | | 1471 | | List<Type> result) |
| | | 1472 | | { |
| | 20 | 1473 | | if (visited.TryGetValue(t, out var perm)) |
| | | 1474 | | { |
| | 7 | 1475 | | if (!perm) |
| | | 1476 | | { |
| | | 1477 | | // cycle; ignore for now |
| | 7 | 1478 | | return; |
| | | 1479 | | } |
| | | 1480 | | return; |
| | | 1481 | | } |
| | | 1482 | | |
| | | 1483 | | // temp-mark |
| | 13 | 1484 | | visited[t] = false; |
| | | 1485 | | |
| | 13 | 1486 | | var deps = new List<Type>(); |
| | | 1487 | | |
| | | 1488 | | // 1) Dependencies via property types (component properties) |
| | 13 | 1489 | | var propDeps = t.GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| | 47 | 1490 | | .Select(p => GetComponentDependencyType(p.PropertyType, componentSet)) |
| | 47 | 1491 | | .Where(dep => dep is not null) |
| | 5 | 1492 | | .Select(dep => dep!) |
| | 13 | 1493 | | .Distinct(); |
| | | 1494 | | |
| | 13 | 1495 | | deps.AddRange(propDeps); |
| | | 1496 | | |
| | | 1497 | | // 2) Dependency via base type (parenting) |
| | 13 | 1498 | | var baseType = t.BaseType; |
| | 13 | 1499 | | if (baseType != null && componentSet.Contains(baseType)) |
| | | 1500 | | { |
| | 2 | 1501 | | deps.Add(baseType); |
| | | 1502 | | } |
| | | 1503 | | |
| | 40 | 1504 | | foreach (var dep in deps.Distinct()) |
| | | 1505 | | { |
| | 7 | 1506 | | Visit(dep, componentSet, visited, result); |
| | | 1507 | | } |
| | | 1508 | | |
| | | 1509 | | // perm-mark |
| | 13 | 1510 | | visited[t] = true; |
| | 13 | 1511 | | result.Add(t); |
| | 13 | 1512 | | } |
| | | 1513 | | |
| | | 1514 | | private static Type? GetComponentDependencyType(Type propertyType, HashSet<Type> componentSet) |
| | | 1515 | | { |
| | | 1516 | | // Unwrap Nullable |
| | 47 | 1517 | | if (Nullable.GetUnderlyingType(propertyType) is Type underlying) |
| | | 1518 | | { |
| | 2 | 1519 | | propertyType = underlying; |
| | | 1520 | | } |
| | | 1521 | | |
| | | 1522 | | // Unwrap arrays |
| | 47 | 1523 | | if (propertyType.IsArray) |
| | | 1524 | | { |
| | 4 | 1525 | | propertyType = propertyType.GetElementType()!; |
| | | 1526 | | } |
| | | 1527 | | |
| | 47 | 1528 | | return componentSet.Contains(propertyType) ? propertyType : null; |
| | | 1529 | | } |
| | | 1530 | | |
| | | 1531 | | /// <summary> |
| | | 1532 | | /// Determines the PowerShell base type for form payload exports based on KrBindForm.MaxNestingDepth. |
| | | 1533 | | /// </summary> |
| | | 1534 | | /// <param name="type">The OpenAPI component type.</param> |
| | | 1535 | | /// <param name="basePsName">The resolved PowerShell base type name.</param> |
| | | 1536 | | /// <returns>True if a form payload base should be applied; otherwise false.</returns> |
| | | 1537 | | private static bool TryGetFormPayloadBasePsName(Type type, out string? basePsName) |
| | | 1538 | | { |
| | 13 | 1539 | | basePsName = null; |
| | | 1540 | | |
| | 13 | 1541 | | var bindAttr = type.GetCustomAttributes(inherit: false) |
| | 38 | 1542 | | .FirstOrDefault(a => a.GetType().Name.Equals("KrBindFormAttribute", StringComparison.OrdinalIgnoreCase)); |
| | | 1543 | | |
| | 13 | 1544 | | if (bindAttr is null) |
| | | 1545 | | { |
| | 12 | 1546 | | return false; |
| | | 1547 | | } |
| | | 1548 | | |
| | 1 | 1549 | | var maxDepthProp = bindAttr.GetType().GetProperty("MaxNestingDepth"); |
| | 1 | 1550 | | var maxDepth = maxDepthProp?.GetValue(bindAttr) as int?; |
| | | 1551 | | |
| | | 1552 | | // If MaxNestingDepth > 0, treat as multipart; otherwise form data. |
| | 1 | 1553 | | basePsName = (maxDepth.GetValueOrDefault(0) > 0) |
| | 1 | 1554 | | ? "Kestrun.Forms.KrMultipart" |
| | 1 | 1555 | | : "Kestrun.Forms.KrFormData"; |
| | 1 | 1556 | | return true; |
| | | 1557 | | } |
| | | 1558 | | |
| | | 1559 | | /// <summary> |
| | | 1560 | | /// Writes the OpenAPI class definitions to a temporary PowerShell script file. |
| | | 1561 | | /// </summary> |
| | | 1562 | | /// <param name="openApiClasses">The OpenAPI class definitions as a string.</param> |
| | | 1563 | | /// <returns>The path to the temporary PowerShell script file.</returns> |
| | | 1564 | | public static string WriteOpenApiTempScript(string openApiClasses) |
| | | 1565 | | { |
| | | 1566 | | // Use a stable file name so multiple runspaces share the same script |
| | 4 | 1567 | | var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".ps1"); |
| | | 1568 | | |
| | | 1569 | | // Ensure directory exists |
| | 4 | 1570 | | _ = Directory.CreateDirectory(Path.GetDirectoryName(tempPath)!); |
| | | 1571 | | |
| | | 1572 | | // Build content with header |
| | 4 | 1573 | | var sb = new StringBuilder() |
| | 4 | 1574 | | .AppendLine("# ================================================") |
| | 4 | 1575 | | .AppendLine("# Kestrun OpenAPI Autogenerated Class Definitions") |
| | 4 | 1576 | | .AppendLine("# DO NOT EDIT - generated at runtime") |
| | 4 | 1577 | | .Append("# Timestamp: ").Append(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")).Append('Z').AppendLine() |
| | 4 | 1578 | | .AppendLine("# ================================================") |
| | 4 | 1579 | | .AppendLine() |
| | 4 | 1580 | | .AppendLine("[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSProvideCommentHelp', '')]") |
| | 4 | 1581 | | .AppendLine("param()") |
| | 4 | 1582 | | .AppendLine(openApiClasses); |
| | | 1583 | | |
| | | 1584 | | // Save using UTF-8 without BOM |
| | 4 | 1585 | | File.WriteAllText(tempPath, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); |
| | | 1586 | | |
| | 4 | 1587 | | return tempPath; |
| | | 1588 | | } |
| | | 1589 | | } |