| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Management.Automation.Internal; |
| | | 3 | | using System.Management.Automation.Language; |
| | | 4 | | using System.Text.Json.Nodes; |
| | | 5 | | using Kestrun.Hosting; |
| | | 6 | | using Kestrun.Hosting.Options; |
| | | 7 | | using Kestrun.Languages; |
| | | 8 | | using Kestrun.Utilities; |
| | | 9 | | using Microsoft.OpenApi; |
| | | 10 | | |
| | | 11 | | namespace Kestrun.OpenApi; |
| | | 12 | | |
| | | 13 | | public partial class OpenApiDocDescriptor |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Enumerates all in-session PowerShell functions in the given runspace, |
| | | 17 | | /// detects those annotated with [OpenApiPath], and maps them into the provided KestrunHost. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="cmdInfos">List of FunctionInfo objects representing PowerShell functions.</param> |
| | | 20 | | public void LoadAnnotatedFunctions(List<FunctionInfo> cmdInfos) |
| | | 21 | | { |
| | 0 | 22 | | ArgumentNullException.ThrowIfNull(cmdInfos); |
| | 0 | 23 | | var callbacks = cmdInfos |
| | 0 | 24 | | .Where(f => f.ScriptBlock.Attributes?.All(a => a is OpenApiCallbackAttribute) != false); |
| | | 25 | | |
| | 0 | 26 | | var others = cmdInfos |
| | 0 | 27 | | .Where(f => f.ScriptBlock.Attributes?.All(a => a is not OpenApiCallbackAttribute) != false); |
| | | 28 | | // (equivalent to NOT having any callback attribute) |
| | | 29 | | |
| | 0 | 30 | | foreach (var func in callbacks) |
| | | 31 | | { |
| | 0 | 32 | | ProcessFunction(func); |
| | | 33 | | } |
| | | 34 | | |
| | 0 | 35 | | BuildCallbacks(Callbacks); |
| | 0 | 36 | | foreach (var func in others) |
| | | 37 | | { |
| | 0 | 38 | | ProcessFunction(func); |
| | | 39 | | } |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Processes a single PowerShell function, extracting OpenAPI annotations and configuring the host accordingly. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <param name="func">The function information.</param> |
| | | 46 | | private void ProcessFunction(FunctionInfo func) |
| | | 47 | | { |
| | | 48 | | try |
| | | 49 | | { |
| | 0 | 50 | | var help = func.GetHelp(); |
| | 0 | 51 | | var sb = func.ScriptBlock; |
| | 0 | 52 | | if (sb is null) |
| | | 53 | | { |
| | 0 | 54 | | return; |
| | | 55 | | } |
| | | 56 | | |
| | 0 | 57 | | var attrs = sb.Attributes; |
| | 0 | 58 | | if (attrs.Count == 0) |
| | | 59 | | { |
| | 0 | 60 | | return; |
| | | 61 | | } |
| | | 62 | | // Create route options and OpenAPI metadata |
| | 0 | 63 | | var routeOptions = new MapRouteOptions(); |
| | 0 | 64 | | var openApiMetadata = new OpenAPIPathMetadata(mapOptions: routeOptions); |
| | | 65 | | // Process attributes to populate route options and OpenAPI metadata |
| | 0 | 66 | | var parsedVerb = ProcessFunctionAttributes(func, help!, attrs, routeOptions, openApiMetadata); |
| | | 67 | | |
| | 0 | 68 | | ProcessParameters(func, help!, routeOptions, openApiMetadata); |
| | | 69 | | |
| | 0 | 70 | | EnsureDefaultResponses(openApiMetadata); |
| | 0 | 71 | | FinalizeRouteOptions(func, sb, openApiMetadata, routeOptions, parsedVerb); |
| | 0 | 72 | | } |
| | 0 | 73 | | catch (Exception ex) |
| | | 74 | | { |
| | 0 | 75 | | Host.Logger.Error("Error loading OpenAPI annotated function '{funcName}': {message}", func.Name, ex.Message) |
| | 0 | 76 | | } |
| | 0 | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// Processes the OpenAPI-related attributes on the specified function. |
| | | 81 | | /// </summary> |
| | | 82 | | /// <param name="func">The function information.</param> |
| | | 83 | | /// <param name="help">The comment help information.</param> |
| | | 84 | | /// <param name="attrs">The collection of attributes applied to the function.</param> |
| | | 85 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 86 | | /// <param name="openApiMetadata">The OpenAPI metadata to populate.</param> |
| | | 87 | | /// <returns>The parsed HTTP verb for the function.</returns> |
| | | 88 | | private HttpVerb ProcessFunctionAttributes( |
| | | 89 | | FunctionInfo func, |
| | | 90 | | CommentHelpInfo help, |
| | | 91 | | IReadOnlyCollection<Attribute> attrs, |
| | | 92 | | MapRouteOptions routeOptions, |
| | | 93 | | OpenAPIPathMetadata openApiMetadata) |
| | | 94 | | { |
| | 0 | 95 | | var parsedVerb = HttpVerb.Get; |
| | | 96 | | |
| | 0 | 97 | | foreach (var attr in attrs) |
| | | 98 | | { |
| | | 99 | | try |
| | | 100 | | { |
| | | 101 | | switch (attr) |
| | | 102 | | { |
| | | 103 | | case OpenApiPathAttribute path: |
| | 0 | 104 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, path); |
| | 0 | 105 | | break; |
| | | 106 | | case OpenApiWebhookAttribute webhook: |
| | 0 | 107 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, webhook); |
| | 0 | 108 | | break; |
| | | 109 | | case OpenApiCallbackAttribute callbackOperation: |
| | 0 | 110 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, callbackO |
| | 0 | 111 | | break; |
| | | 112 | | case OpenApiExtensionAttribute extensionAttr: |
| | 0 | 113 | | ApplyExtensionAttribute(openApiMetadata, extensionAttr); |
| | 0 | 114 | | break; |
| | | 115 | | case OpenApiResponseRefAttribute responseRef: |
| | 0 | 116 | | ApplyResponseRefAttribute(openApiMetadata, responseRef); |
| | 0 | 117 | | break; |
| | | 118 | | case OpenApiResponseAttribute responseAttr: |
| | 0 | 119 | | ApplyResponseAttribute(openApiMetadata, responseAttr, routeOptions); |
| | 0 | 120 | | break; |
| | | 121 | | case OpenApiResponseExampleRefAttribute responseAttr: |
| | 0 | 122 | | ApplyResponseAttribute(openApiMetadata, responseAttr, routeOptions); |
| | 0 | 123 | | break; |
| | | 124 | | case OpenApiResponseLinkRefAttribute linkRefAttr: |
| | 0 | 125 | | ApplyResponseLinkAttribute(openApiMetadata, linkRefAttr); |
| | 0 | 126 | | break; |
| | | 127 | | case OpenApiPropertyAttribute propertyAttr: |
| | 0 | 128 | | ApplyPropertyAttribute(openApiMetadata, propertyAttr); |
| | 0 | 129 | | break; |
| | | 130 | | case OpenApiAuthorizationAttribute authAttr: |
| | 0 | 131 | | ApplyAuthorizationAttribute(routeOptions, openApiMetadata, authAttr); |
| | 0 | 132 | | break; |
| | | 133 | | case IOpenApiResponseHeaderAttribute responseHeaderAttr: |
| | 0 | 134 | | ApplyResponseHeaderAttribute(openApiMetadata, responseHeaderAttr); |
| | 0 | 135 | | break; |
| | | 136 | | case OpenApiCallbackRefAttribute callbackRefAttr: |
| | 0 | 137 | | ApplyCallbackRefAttribute(openApiMetadata, callbackRefAttr); |
| | 0 | 138 | | break; |
| | | 139 | | case KestrunAnnotation ka: |
| | 0 | 140 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 141 | | } |
| | 0 | 142 | | } |
| | 0 | 143 | | catch (InvalidOperationException ex) |
| | | 144 | | { |
| | 0 | 145 | | Host.Logger.Error(ex, "Error processing OpenApiPath attribute on function '{funcName}': {message}", func |
| | 0 | 146 | | } |
| | 0 | 147 | | catch (Exception ex) |
| | | 148 | | { |
| | 0 | 149 | | Host.Logger.Error(ex, "Error processing OpenApiPath attribute on function '{funcName}': {message}", func |
| | 0 | 150 | | } |
| | | 151 | | } |
| | | 152 | | |
| | 0 | 153 | | return parsedVerb; |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Applies the OpenApiExtension attribute to the function's OpenAPI metadata. |
| | | 158 | | /// </summary> |
| | | 159 | | /// <param name="openApiMetadata">The OpenAPI metadata to which the extension will be applied.</param> |
| | | 160 | | /// <param name="extensionAttr">The OpenApiExtension attribute containing the extension data.</param> |
| | | 161 | | private void ApplyExtensionAttribute(OpenAPIPathMetadata openApiMetadata, OpenApiExtensionAttribute extensionAttr) |
| | | 162 | | { |
| | 3 | 163 | | if (Host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 164 | | { |
| | 3 | 165 | | Host.Logger.Debug("Applying OpenApiExtension '{extensionName}' to function metadata", extensionAttr.Name); |
| | | 166 | | } |
| | 3 | 167 | | openApiMetadata.Extensions ??= []; |
| | | 168 | | |
| | | 169 | | // Parse string into a JsonNode tree. |
| | 3 | 170 | | var node = JsonNode.Parse(extensionAttr.Json); |
| | 3 | 171 | | if (node is null) |
| | | 172 | | { |
| | 1 | 173 | | Host.Logger.Error("Error parsing OpenAPI extension '{extensionName}': JSON is null", extensionAttr.Name); |
| | 1 | 174 | | return; |
| | | 175 | | } |
| | 2 | 176 | | openApiMetadata.Extensions[extensionAttr.Name] = new JsonNodeExtension(node); |
| | 2 | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Applies the OpenApiPath attribute to the function's route options and metadata. |
| | | 181 | | /// </summary> |
| | | 182 | | /// <param name="func">The function information.</param> |
| | | 183 | | /// <param name="help">The comment help information.</param> |
| | | 184 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 185 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 186 | | /// <param name="parsedVerb">The currently parsed HTTP verb.</param> |
| | | 187 | | /// <param name="oaPath">The OpenApiPath attribute instance.</param> |
| | | 188 | | /// <returns>The updated HTTP verb after processing the attribute.</returns> |
| | | 189 | | private static HttpVerb ApplyPathAttribute( |
| | | 190 | | FunctionInfo func, |
| | | 191 | | CommentHelpInfo help, |
| | | 192 | | MapRouteOptions routeOptions, |
| | | 193 | | OpenAPIPathMetadata metadata, |
| | | 194 | | HttpVerb parsedVerb, |
| | | 195 | | IOpenApiPathAttribute oaPath) |
| | | 196 | | { |
| | 0 | 197 | | var httpVerb = oaPath.HttpVerb ?? string.Empty; |
| | 0 | 198 | | if (!string.IsNullOrWhiteSpace(httpVerb)) |
| | | 199 | | { |
| | 0 | 200 | | parsedVerb = HttpVerbExtensions.FromMethodString(httpVerb); |
| | 0 | 201 | | routeOptions.HttpVerbs.Add(parsedVerb); |
| | | 202 | | } |
| | | 203 | | |
| | 0 | 204 | | var pattern = oaPath.Pattern; |
| | 0 | 205 | | if (string.IsNullOrWhiteSpace(pattern)) |
| | | 206 | | { |
| | 0 | 207 | | throw new InvalidOperationException("OpenApiPath attribute must specify a non-empty Pattern property."); |
| | | 208 | | } |
| | 0 | 209 | | var openApiPattern = pattern; |
| | 0 | 210 | | var routePattern = pattern; |
| | 0 | 211 | | if (oaPath is OpenApiPathAttribute) |
| | | 212 | | { |
| | 0 | 213 | | if (!Rfc6570PathTemplateMapper.TryMapToKestrelRoute(pattern, out var mapping, out var error)) |
| | | 214 | | { |
| | 0 | 215 | | throw new InvalidOperationException($"OpenApiPath pattern '{pattern}' is invalid: {error}"); |
| | | 216 | | } |
| | | 217 | | |
| | 0 | 218 | | openApiPattern = mapping.OpenApiPattern; |
| | 0 | 219 | | routePattern = mapping.KestrelPattern; |
| | 0 | 220 | | AddQueryParametersFromTemplate(metadata, mapping.QueryParameters); |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | // Apply pattern, summary, description, tags |
| | 0 | 224 | | routeOptions.Pattern = routePattern; |
| | 0 | 225 | | metadata.Summary = ChooseFirstNonEmpty(oaPath.Summary, help.GetSynopsis()); |
| | 0 | 226 | | metadata.Description = ChooseFirstNonEmpty(oaPath.Description, help.GetDescription()); |
| | 0 | 227 | | metadata.Tags = [.. oaPath.Tags]; |
| | | 228 | | |
| | | 229 | | // Apply deprecated flag if specified |
| | 0 | 230 | | metadata.Deprecated |= oaPath.Deprecated; |
| | | 231 | | // Apply document ID if specified |
| | 0 | 232 | | metadata.DocumentId = oaPath.DocumentId; |
| | | 233 | | switch (oaPath) |
| | | 234 | | { |
| | | 235 | | case OpenApiPathAttribute oaPathConcrete: |
| | 0 | 236 | | ApplyPathLikePath(func, routeOptions, metadata, oaPathConcrete, openApiPattern); |
| | 0 | 237 | | break; |
| | | 238 | | case OpenApiWebhookAttribute oaWebhook: |
| | 0 | 239 | | ApplyPathLikeWebhook(func, metadata, oaWebhook, pattern); |
| | 0 | 240 | | break; |
| | | 241 | | case OpenApiCallbackAttribute oaCallback: |
| | 0 | 242 | | ApplyPathLikeCallback(func, metadata, oaCallback, httpVerb, pattern); |
| | | 243 | | break; |
| | | 244 | | } |
| | | 245 | | |
| | 0 | 246 | | return parsedVerb; |
| | | 247 | | } |
| | | 248 | | |
| | | 249 | | /// <summary> |
| | | 250 | | /// Applies the OpenApiPath attribute to the function's route options and metadata for a standard path. |
| | | 251 | | /// </summary> |
| | | 252 | | /// <param name="func">The function information.</param> |
| | | 253 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 254 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 255 | | /// <param name="oaPath">The OpenApiPath attribute instance.</param> |
| | | 256 | | /// <param name="openApiPattern">The OpenAPI path pattern.</param> |
| | | 257 | | private static void ApplyPathLikePath( |
| | | 258 | | FunctionInfo func, |
| | | 259 | | MapRouteOptions routeOptions, |
| | | 260 | | OpenAPIPathMetadata metadata, |
| | | 261 | | OpenApiPathAttribute oaPath, |
| | | 262 | | string openApiPattern) |
| | | 263 | | { |
| | 0 | 264 | | metadata.Pattern = openApiPattern; |
| | 0 | 265 | | metadata.PathLikeKind = OpenApiPathLikeKind.Path; |
| | 0 | 266 | | if (!string.IsNullOrWhiteSpace(oaPath.CorsPolicy)) |
| | | 267 | | { |
| | | 268 | | // Apply Cors policy name if specified |
| | 0 | 269 | | routeOptions.CorsPolicy = oaPath.CorsPolicy; |
| | | 270 | | } |
| | | 271 | | |
| | 0 | 272 | | metadata.OperationId = oaPath.OperationId is null |
| | 0 | 273 | | ? func.Name |
| | 0 | 274 | | : string.IsNullOrWhiteSpace(oaPath.OperationId) ? metadata.OperationId : oaPath.OperationId; |
| | 0 | 275 | | } |
| | | 276 | | |
| | | 277 | | /// <summary> |
| | | 278 | | /// Adds query parameters inferred from RFC6570 query expressions. |
| | | 279 | | /// </summary> |
| | | 280 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 281 | | /// <param name="queryParameterNames">The query parameter names to add.</param> |
| | | 282 | | private static void AddQueryParametersFromTemplate( |
| | | 283 | | OpenAPIPathMetadata metadata, |
| | | 284 | | IReadOnlyList<string> queryParameterNames) |
| | | 285 | | { |
| | 0 | 286 | | if (queryParameterNames.Count == 0) |
| | | 287 | | { |
| | 0 | 288 | | return; |
| | | 289 | | } |
| | | 290 | | |
| | 0 | 291 | | metadata.Parameters ??= []; |
| | 0 | 292 | | foreach (var name in queryParameterNames.Distinct(StringComparer.OrdinalIgnoreCase)) |
| | | 293 | | { |
| | 0 | 294 | | if (metadata.Parameters.Any(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))) |
| | | 295 | | { |
| | | 296 | | continue; |
| | | 297 | | } |
| | | 298 | | |
| | 0 | 299 | | metadata.Parameters.Add(new OpenApiParameter |
| | 0 | 300 | | { |
| | 0 | 301 | | Name = name, |
| | 0 | 302 | | In = ParameterLocation.Query, |
| | 0 | 303 | | Required = false, |
| | 0 | 304 | | Schema = new OpenApiSchema { Type = JsonSchemaType.String }, |
| | 0 | 305 | | }); |
| | | 306 | | } |
| | 0 | 307 | | } |
| | | 308 | | /// <summary> |
| | | 309 | | /// Applies the OpenApiWebhook attribute to the function's OpenAPI metadata. |
| | | 310 | | /// </summary> |
| | | 311 | | /// <param name="func">The function information.</param> |
| | | 312 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 313 | | /// <param name="oaPath">The OpenApiWebhook attribute instance.</param> |
| | | 314 | | /// <param name="pattern">The route pattern.</param> |
| | | 315 | | private static void ApplyPathLikeWebhook(FunctionInfo func, OpenAPIPathMetadata metadata, OpenApiWebhookAttribute oa |
| | | 316 | | { |
| | 0 | 317 | | metadata.Pattern = pattern; |
| | 0 | 318 | | metadata.PathLikeKind = OpenApiPathLikeKind.Webhook; |
| | 0 | 319 | | metadata.OperationId = oaPath.OperationId is null |
| | 0 | 320 | | ? func.Name |
| | 0 | 321 | | : string.IsNullOrWhiteSpace(oaPath.OperationId) ? metadata.OperationId : oaPath.OperationId; |
| | 0 | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary> |
| | | 325 | | /// Applies the OpenApiCallback attribute to the function's OpenAPI metadata. |
| | | 326 | | /// </summary> |
| | | 327 | | /// <param name="func">The function information.</param> |
| | | 328 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 329 | | /// <param name="oaCallback">The OpenApiCallback attribute instance.</param> |
| | | 330 | | /// <param name="httpVerb">The HTTP verb associated with the callback.</param> |
| | | 331 | | /// <param name="callbackPattern">The callback route pattern.</param> |
| | | 332 | | /// <exception cref="InvalidOperationException">Thrown when the Expression property of the OpenApiCallback attribute |
| | | 333 | | private static void ApplyPathLikeCallback( |
| | | 334 | | FunctionInfo func, |
| | | 335 | | OpenAPIPathMetadata metadata, |
| | | 336 | | OpenApiCallbackAttribute oaCallback, |
| | | 337 | | string httpVerb, |
| | | 338 | | string callbackPattern) |
| | | 339 | | { |
| | | 340 | | // Callbacks are neither paths nor webhooks |
| | 0 | 341 | | metadata.PathLikeKind = OpenApiPathLikeKind.Callback; |
| | 0 | 342 | | if (string.IsNullOrWhiteSpace(oaCallback.Expression)) |
| | | 343 | | { |
| | 0 | 344 | | throw new InvalidOperationException("OpenApiCallback attribute must specify a non-empty Expression property. |
| | | 345 | | } |
| | | 346 | | // Callbacks must have an expression |
| | 0 | 347 | | metadata.Expression = CallbackOperationId.BuildCallbackKey(oaCallback.Expression, callbackPattern); |
| | 0 | 348 | | metadata.Inline = oaCallback.Inline; |
| | 0 | 349 | | metadata.Pattern = func.Name; |
| | 0 | 350 | | metadata.OperationId = string.IsNullOrWhiteSpace(oaCallback.OperationId) |
| | 0 | 351 | | ? CallbackOperationId.FromLastSegment(func.Name, httpVerb, oaCallback.Expression) |
| | 0 | 352 | | : oaCallback.OperationId; |
| | 0 | 353 | | } |
| | | 354 | | |
| | | 355 | | /// <summary> |
| | | 356 | | /// Chooses the first non-empty string from the provided values, normalizing newlines. |
| | | 357 | | /// </summary> |
| | | 358 | | /// <param name="values">An array of string values to evaluate.</param> |
| | | 359 | | /// <returns>The first non-empty string with normalized newlines, or null if all are null or whitespace.</returns> |
| | | 360 | | private static string? ChooseFirstNonEmpty(params string?[] values) |
| | | 361 | | { |
| | 0 | 362 | | foreach (var value in values) |
| | | 363 | | { |
| | 0 | 364 | | if (!string.IsNullOrWhiteSpace(value)) |
| | | 365 | | { |
| | 0 | 366 | | return NormalizeNewlines(value); |
| | | 367 | | } |
| | | 368 | | } |
| | | 369 | | |
| | 0 | 370 | | return null; |
| | | 371 | | } |
| | | 372 | | |
| | | 373 | | /// <summary> |
| | | 374 | | /// Normalizes newlines in the given string to use '\n' only. |
| | | 375 | | /// </summary> |
| | | 376 | | /// <param name="value">The string to normalize.</param> |
| | | 377 | | /// <returns>The normalized string.</returns> |
| | 0 | 378 | | private static string? NormalizeNewlines(string? value) => value?.Replace("\r\n", "\n"); |
| | | 379 | | |
| | | 380 | | /// <summary> |
| | | 381 | | /// Applies the OpenApiResponseRef attribute to the function's OpenAPI metadata. |
| | | 382 | | /// </summary> |
| | | 383 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 384 | | /// <param name="attribute">The OpenApiResponseRef attribute containing response reference details.</param> |
| | | 385 | | private void ApplyResponseRefAttribute(OpenAPIPathMetadata metadata, OpenApiResponseRefAttribute attribute) |
| | | 386 | | { |
| | 0 | 387 | | metadata.Responses ??= []; |
| | | 388 | | |
| | 0 | 389 | | if (!TryGetResponseItem(attribute.ReferenceId, out var response, out var inline)) |
| | | 390 | | { |
| | 0 | 391 | | throw new InvalidOperationException($"Response component with ID '{attribute.ReferenceId}' not found."); |
| | | 392 | | } |
| | | 393 | | |
| | 0 | 394 | | IOpenApiResponse iResponse = attribute.Inline || inline ? response!.Clone() : new OpenApiResponseReference(attri |
| | | 395 | | |
| | 0 | 396 | | if (attribute.Description is not null) |
| | | 397 | | { |
| | 0 | 398 | | iResponse.Description = attribute.Description; |
| | | 399 | | } |
| | | 400 | | |
| | 0 | 401 | | if (metadata.Responses.ContainsKey(attribute.StatusCode)) |
| | | 402 | | { |
| | 0 | 403 | | throw new InvalidOperationException($"Response for status code '{attribute.StatusCode}' is already defined f |
| | | 404 | | } |
| | | 405 | | |
| | 0 | 406 | | metadata.Responses.Add(attribute.StatusCode, iResponse); |
| | 0 | 407 | | } |
| | | 408 | | |
| | | 409 | | /// <summary> |
| | | 410 | | /// Applies the OpenApiResponse attribute to the function's OpenAPI metadata. |
| | | 411 | | /// </summary> |
| | | 412 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 413 | | /// <param name="attribute">The OpenApiResponse attribute containing response details.</param> |
| | | 414 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 415 | | private void ApplyResponseAttribute(OpenAPIPathMetadata metadata, IOpenApiResponseAttribute attribute, MapRouteOptio |
| | | 416 | | { |
| | 0 | 417 | | metadata.Responses ??= []; |
| | 0 | 418 | | var response = metadata.Responses.TryGetValue(attribute.StatusCode, out var value) ? value as OpenApiResponse : |
| | 0 | 419 | | if (response is not null && CreateResponseFromAttribute(attribute, response)) |
| | | 420 | | { |
| | 0 | 421 | | _ = metadata.Responses.TryAdd(attribute.StatusCode, response); |
| | 0 | 422 | | if (routeOptions.DefaultResponseContentType is null) |
| | | 423 | | { |
| | 0 | 424 | | var defaultStatusCode = SelectDefaultSuccessResponse(metadata.Responses); |
| | 0 | 425 | | if (defaultStatusCode is not null && metadata.Responses.TryGetValue(defaultStatusCode, out var defaultRe |
| | 0 | 426 | | defaultResponse.Content is not null && defaultResponse.Content.Count > 0) |
| | | 427 | | { |
| | 0 | 428 | | routeOptions.DefaultResponseContentType = |
| | 0 | 429 | | defaultResponse.Content.Keys.First(); |
| | | 430 | | } |
| | | 431 | | } |
| | | 432 | | } |
| | 0 | 433 | | } |
| | | 434 | | |
| | | 435 | | /// <summary> |
| | | 436 | | /// Selects the default success response (2xx) from the given OpenApiResponses. |
| | | 437 | | /// </summary> |
| | | 438 | | /// <param name="responses">The collection of OpenApiResponses to select from.</param> |
| | | 439 | | /// <returns>The status code of the default success response, or null if none found.</returns> |
| | | 440 | | private static string? SelectDefaultSuccessResponse(OpenApiResponses responses) |
| | | 441 | | { |
| | 0 | 442 | | return responses |
| | 0 | 443 | | .Select(kvp => new |
| | 0 | 444 | | { |
| | 0 | 445 | | StatusCode = kvp.Key, |
| | 0 | 446 | | Code = TryParseStatusCode(kvp.Key), |
| | 0 | 447 | | Response = kvp.Value |
| | 0 | 448 | | }) |
| | 0 | 449 | | .Where(x => |
| | 0 | 450 | | x.Code is >= 200 and < 300 && |
| | 0 | 451 | | HasContent(x.Response)) |
| | 0 | 452 | | .OrderBy(x => x.Code) |
| | 0 | 453 | | .Select(x => x.StatusCode) |
| | 0 | 454 | | .FirstOrDefault(); |
| | | 455 | | } |
| | | 456 | | |
| | | 457 | | /// <summary> |
| | | 458 | | /// Tries to parse the given status code string into an integer. |
| | | 459 | | /// </summary> |
| | | 460 | | /// <param name="statusCode">The status code as a string.</param> |
| | | 461 | | /// <returns>The parsed integer status code, or -1 if parsing fails.</returns> |
| | | 462 | | private static int TryParseStatusCode(string statusCode) |
| | 0 | 463 | | => int.TryParse(statusCode, out var code) ? code : -1; |
| | | 464 | | |
| | | 465 | | /// <summary> |
| | | 466 | | /// Determines if the given response has content defined. |
| | | 467 | | /// </summary> |
| | | 468 | | /// <param name="response">The OpenAPI response to check for content.</param> |
| | | 469 | | /// <returns>True if the response has content; otherwise, false.</returns> |
| | | 470 | | private static bool HasContent(IOpenApiResponse response) |
| | | 471 | | { |
| | | 472 | | // If your concrete type is OpenApiResponse (common), this is the easiest path: |
| | 0 | 473 | | if (response is OpenApiResponse r) |
| | | 474 | | { |
| | 0 | 475 | | return r.Content is not null && r.Content.Count > 0; |
| | | 476 | | } |
| | | 477 | | |
| | | 478 | | // Otherwise, we can't reliably know. Be conservative: |
| | 0 | 479 | | return false; |
| | | 480 | | } |
| | | 481 | | |
| | | 482 | | /// <summary> |
| | | 483 | | /// Applies the OpenApiProperty attribute to the function's OpenAPI metadata. |
| | | 484 | | /// </summary> |
| | | 485 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 486 | | /// <param name="attribute">The OpenApiProperty attribute containing property details.</param> |
| | | 487 | | /// <exception cref="InvalidOperationException"></exception> |
| | | 488 | | private static void ApplyPropertyAttribute(OpenAPIPathMetadata metadata, OpenApiPropertyAttribute attribute) |
| | | 489 | | { |
| | 0 | 490 | | if (attribute.StatusCode is null) |
| | | 491 | | { |
| | 0 | 492 | | return; |
| | | 493 | | } |
| | | 494 | | |
| | 0 | 495 | | if (metadata.Responses is null || !metadata.Responses.TryGetValue(attribute.StatusCode, out var res)) |
| | | 496 | | { |
| | 0 | 497 | | throw new InvalidOperationException($"Response for status code '{attribute.StatusCode}' is not defined for t |
| | | 498 | | } |
| | | 499 | | |
| | 0 | 500 | | if (res is OpenApiResponseReference) |
| | | 501 | | { |
| | 0 | 502 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute.StatusCo |
| | | 503 | | } |
| | | 504 | | |
| | 0 | 505 | | if (res is OpenApiResponse response) |
| | | 506 | | { |
| | 0 | 507 | | if (response.Content is null || response.Content.Count == 0) |
| | | 508 | | { |
| | 0 | 509 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute.Stat |
| | | 510 | | } |
| | | 511 | | |
| | 0 | 512 | | foreach (var content in response.Content.Values) |
| | | 513 | | { |
| | 0 | 514 | | if (content.Schema is null) |
| | | 515 | | { |
| | 0 | 516 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute. |
| | | 517 | | } |
| | | 518 | | |
| | 0 | 519 | | ApplySchemaAttr(attribute, content.Schema); |
| | | 520 | | } |
| | | 521 | | } |
| | 0 | 522 | | } |
| | | 523 | | |
| | | 524 | | private void ApplyAuthorizationAttribute(MapRouteOptions routeOptions, OpenAPIPathMetadata metadata, OpenApiAuthoriz |
| | | 525 | | { |
| | 0 | 526 | | metadata.SecuritySchemes ??= []; |
| | 0 | 527 | | var policyList = BuildPolicyList(attribute.Policies); |
| | 0 | 528 | | var securitySchemeList = Host.AddSecurityRequirementObject(attribute.Scheme, policyList, metadata.SecurityScheme |
| | 0 | 529 | | routeOptions.AddSecurityRequirementObject(schemes: securitySchemeList, policies: policyList); |
| | 0 | 530 | | } |
| | | 531 | | |
| | | 532 | | private static List<string> BuildPolicyList(string? policies) |
| | | 533 | | { |
| | 0 | 534 | | return [.. (string.IsNullOrWhiteSpace(policies) ? new List<string>() : [.. policies.Split(',')]) |
| | 0 | 535 | | .Where(p => !string.IsNullOrWhiteSpace(p)) |
| | 0 | 536 | | .Select(p => p.Trim())]; |
| | | 537 | | } |
| | | 538 | | |
| | | 539 | | /// <summary> |
| | | 540 | | /// Processes the parameters of the specified function, applying OpenAPI annotations as needed. |
| | | 541 | | /// </summary> |
| | | 542 | | /// <param name="func">The function information.</param> |
| | | 543 | | /// <param name="help">The comment help information.</param> |
| | | 544 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 545 | | /// <param name="openApiMetadata">The OpenAPI metadata to update.</param> |
| | | 546 | | /// <exception cref="InvalidOperationException">Thrown when an invalid operation occurs during parameter processing. |
| | | 547 | | private void ProcessParameters( |
| | | 548 | | FunctionInfo func, |
| | | 549 | | CommentHelpInfo help, |
| | | 550 | | MapRouteOptions routeOptions, |
| | | 551 | | OpenAPIPathMetadata openApiMetadata) |
| | | 552 | | { |
| | 0 | 553 | | foreach (var paramInfo in func.Parameters.Values) |
| | | 554 | | { |
| | | 555 | | // First pass for parameter and request body attributes |
| | 0 | 556 | | foreach (var attribute in paramInfo.Attributes) |
| | | 557 | | { |
| | | 558 | | switch (attribute) |
| | | 559 | | { |
| | | 560 | | case OpenApiParameterAttribute paramAttr: |
| | 0 | 561 | | ApplyParameterAttribute(func, help, routeOptions, openApiMetadata, paramInfo, paramAttr); |
| | 0 | 562 | | break; |
| | | 563 | | case OpenApiParameterRefAttribute paramRefAttr: |
| | 0 | 564 | | ApplyParameterRefAttribute(help, routeOptions, openApiMetadata, paramInfo, paramRefAttr); |
| | 0 | 565 | | break; |
| | | 566 | | case OpenApiRequestBodyRefAttribute requestBodyRefAttr: |
| | 0 | 567 | | ApplyRequestBodyRefAttribute(help, routeOptions, openApiMetadata, paramInfo, requestBodyRefAttr) |
| | 0 | 568 | | break; |
| | | 569 | | case OpenApiRequestBodyAttribute requestBodyAttr: |
| | 0 | 570 | | ApplyRequestBodyAttribute(help, routeOptions, openApiMetadata, paramInfo, requestBodyAttr); |
| | 0 | 571 | | break; |
| | | 572 | | case OpenApiRequestBodyExampleRefAttribute: |
| | | 573 | | case OpenApiParameterExampleRefAttribute: |
| | | 574 | | // Do nothing here; handled later |
| | | 575 | | break; |
| | | 576 | | case KestrunAnnotation ka: |
| | 0 | 577 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 578 | | } |
| | | 579 | | } |
| | | 580 | | // Second pass for example references |
| | 0 | 581 | | foreach (var attribute in paramInfo.Attributes) |
| | | 582 | | { |
| | | 583 | | switch (attribute) |
| | | 584 | | { |
| | | 585 | | case OpenApiParameterAttribute: |
| | | 586 | | case OpenApiParameterRefAttribute: |
| | | 587 | | case OpenApiRequestBodyRefAttribute: |
| | | 588 | | case OpenApiRequestBodyAttribute: |
| | | 589 | | // Already handled |
| | | 590 | | break; |
| | | 591 | | case OpenApiRequestBodyExampleRefAttribute requestBodyExampleRefAttr: |
| | 0 | 592 | | ApplyRequestBodyExampleRefAttribute(openApiMetadata, requestBodyExampleRefAttr); |
| | 0 | 593 | | break; |
| | | 594 | | case OpenApiParameterExampleRefAttribute parameterExampleRefAttr: |
| | 0 | 595 | | ApplyParameterExampleRefAttribute(openApiMetadata, paramInfo, parameterExampleRefAttr); |
| | 0 | 596 | | break; |
| | | 597 | | case KestrunAnnotation ka: |
| | 0 | 598 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 599 | | } |
| | | 600 | | } |
| | | 601 | | } |
| | 0 | 602 | | } |
| | | 603 | | |
| | | 604 | | #region Parameter Handlers |
| | | 605 | | /// <summary> |
| | | 606 | | /// Applies the OpenApiParameter attribute to the function's OpenAPI metadata. |
| | | 607 | | /// </summary> |
| | | 608 | | /// <param name="func">The function information.</param> |
| | | 609 | | /// <param name="help">The comment help information.</param> |
| | | 610 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 611 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 612 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 613 | | /// <param name="attribute">The OpenApiParameter attribute containing parameter details.</param> |
| | | 614 | | private void ApplyParameterAttribute( |
| | | 615 | | FunctionInfo func, |
| | | 616 | | CommentHelpInfo help, |
| | | 617 | | MapRouteOptions routeOptions, |
| | | 618 | | OpenAPIPathMetadata metadata, |
| | | 619 | | ParameterMetadata paramInfo, |
| | | 620 | | OpenApiParameterAttribute attribute) |
| | | 621 | | { |
| | 0 | 622 | | metadata.Parameters ??= []; |
| | 0 | 623 | | var parameter = new OpenApiParameter(); |
| | 0 | 624 | | if (!CreateParameterFromAttribute(attribute, parameter)) |
| | | 625 | | { |
| | 0 | 626 | | Host.Logger.Error("Error processing OpenApiParameter attribute on parameter '{paramName}' of function '{func |
| | 0 | 627 | | return; |
| | | 628 | | } |
| | | 629 | | |
| | 0 | 630 | | if (!string.IsNullOrEmpty(parameter.Name) && parameter.Name != paramInfo.Name) |
| | | 631 | | { |
| | 0 | 632 | | throw new InvalidOperationException($"Parameter name {parameter.Name} is different from variable name: '{par |
| | | 633 | | } |
| | | 634 | | |
| | 0 | 635 | | parameter.Name = paramInfo.Name; |
| | 0 | 636 | | parameter.Schema = InferPrimitiveSchema(paramInfo.ParameterType); |
| | | 637 | | |
| | 0 | 638 | | if (parameter.Schema is OpenApiSchema schema) |
| | | 639 | | { |
| | 0 | 640 | | var defaultValue = func.GetDefaultParameterValue(paramInfo.Name); |
| | 0 | 641 | | if (defaultValue is not null) |
| | | 642 | | { |
| | 0 | 643 | | schema.Default = OpenApiJsonNodeFactory.ToNode(defaultValue); |
| | | 644 | | } |
| | | 645 | | } |
| | | 646 | | |
| | 0 | 647 | | parameter.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 648 | | |
| | 0 | 649 | | foreach (var attr in paramInfo.Attributes.OfType<CmdletMetadataAttribute>()) |
| | | 650 | | { |
| | 0 | 651 | | PowerShellAttributes.ApplyPowerShellAttribute(attr, (OpenApiSchema)parameter.Schema); |
| | | 652 | | } |
| | | 653 | | |
| | 0 | 654 | | RemoveExistingParameter(metadata, paramInfo.Name); |
| | 0 | 655 | | metadata.Parameters.Add(parameter); |
| | 0 | 656 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, parameter)); |
| | 0 | 657 | | } |
| | | 658 | | |
| | | 659 | | /// <summary> |
| | | 660 | | /// Applies the OpenApiParameterRef attribute to the function's OpenAPI metadata. |
| | | 661 | | /// </summary> |
| | | 662 | | /// <param name="help">The comment help information.</param> |
| | | 663 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 664 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 665 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 666 | | /// <param name="attribute">The OpenApiParameterRef attribute containing parameter reference details.</param> |
| | | 667 | | /// <exception cref="InvalidOperationException">If the parameter name does not match the reference name when inlinin |
| | | 668 | | private void ApplyParameterRefAttribute( |
| | | 669 | | CommentHelpInfo help, |
| | | 670 | | MapRouteOptions routeOptions, |
| | | 671 | | OpenAPIPathMetadata metadata, |
| | | 672 | | ParameterMetadata paramInfo, |
| | | 673 | | OpenApiParameterRefAttribute attribute) |
| | | 674 | | { |
| | 0 | 675 | | metadata.Parameters ??= []; |
| | 0 | 676 | | routeOptions.ScriptCode.Parameters ??= []; |
| | | 677 | | |
| | 0 | 678 | | if (!TryGetParameterItem(attribute.ReferenceId, out var componentParameter, out var isInline) || |
| | 0 | 679 | | componentParameter is null) |
| | | 680 | | { |
| | 0 | 681 | | throw new InvalidOperationException($"Parameter component with ID '{attribute.ReferenceId}' not found."); |
| | | 682 | | } |
| | | 683 | | IOpenApiParameter parameter; |
| | | 684 | | |
| | 0 | 685 | | if (attribute.Inline || isInline) |
| | | 686 | | { |
| | 0 | 687 | | parameter = componentParameter.Clone(); |
| | 0 | 688 | | if (componentParameter.Name != paramInfo.Name) |
| | | 689 | | { |
| | 0 | 690 | | throw new InvalidOperationException($"Parameter name {componentParameter.Name} is different from variabl |
| | | 691 | | } |
| | | 692 | | |
| | 0 | 693 | | parameter.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 694 | | } |
| | | 695 | | else |
| | | 696 | | { |
| | 0 | 697 | | parameter = new OpenApiParameterReference(attribute.ReferenceId); |
| | | 698 | | } |
| | | 699 | | |
| | 0 | 700 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentParameter)); |
| | 0 | 701 | | RemoveExistingParameter(metadata, paramInfo.Name); |
| | 0 | 702 | | metadata.Parameters.Add(parameter); |
| | 0 | 703 | | } |
| | | 704 | | |
| | | 705 | | private void ApplyParameterExampleRefAttribute( |
| | | 706 | | OpenAPIPathMetadata metadata, |
| | | 707 | | ParameterMetadata paramInfo, |
| | | 708 | | OpenApiParameterExampleRefAttribute attribute) |
| | | 709 | | { |
| | 0 | 710 | | var parameters = metadata.Parameters |
| | 0 | 711 | | ?? throw new InvalidOperationException( |
| | 0 | 712 | | "OpenApiParameterExampleRefAttribute must follow OpenApiParameterAttribute or OpenApiParameterRefAttribute." |
| | | 713 | | |
| | 0 | 714 | | var parameter = parameters.FirstOrDefault(p => p.Name == paramInfo.Name) |
| | 0 | 715 | | ?? throw new InvalidOperationException( |
| | 0 | 716 | | $"OpenApiParameterExampleRefAttribute requires the parameter '{paramInfo.Name}' to be defined."); |
| | 0 | 717 | | if (parameter is OpenApiParameterReference) |
| | | 718 | | { |
| | 0 | 719 | | throw new InvalidOperationException( |
| | 0 | 720 | | "Cannot apply OpenApiParameterExampleRefAttribute to a parameter reference."); |
| | | 721 | | } |
| | 0 | 722 | | if (parameter is OpenApiParameter opp) |
| | | 723 | | { |
| | 0 | 724 | | opp.Examples ??= new Dictionary<string, IOpenApiExample>(); |
| | | 725 | | // Clone or reference the example |
| | 0 | 726 | | _ = TryAddExample(opp.Examples, attribute); |
| | | 727 | | } |
| | 0 | 728 | | } |
| | | 729 | | |
| | | 730 | | /// <summary> |
| | | 731 | | /// Removes any existing parameter with the specified name from the OpenAPI metadata. |
| | | 732 | | /// </summary> |
| | | 733 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 734 | | /// <param name="name">The parameter name to remove.</param> |
| | | 735 | | private static void RemoveExistingParameter(OpenAPIPathMetadata metadata, string name) |
| | | 736 | | { |
| | 0 | 737 | | if (metadata.Parameters is null) |
| | | 738 | | { |
| | 0 | 739 | | return; |
| | | 740 | | } |
| | | 741 | | |
| | 0 | 742 | | for (var i = metadata.Parameters.Count - 1; i >= 0; i--) |
| | | 743 | | { |
| | 0 | 744 | | if (string.Equals(metadata.Parameters[i].Name, name, StringComparison.OrdinalIgnoreCase)) |
| | | 745 | | { |
| | 0 | 746 | | metadata.Parameters.RemoveAt(i); |
| | | 747 | | } |
| | | 748 | | } |
| | 0 | 749 | | } |
| | | 750 | | |
| | | 751 | | #endregion |
| | | 752 | | #region Request Body Handlers |
| | | 753 | | /// <summary> |
| | | 754 | | /// Applies the OpenApiRequestBodyRef attribute to the function's OpenAPI metadata. |
| | | 755 | | /// </summary> |
| | | 756 | | /// <param name="help">The comment help information.</param> |
| | | 757 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 758 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 759 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 760 | | /// <param name="attribute">The OpenApiRequestBodyRef attribute containing request body reference details.</param> |
| | | 761 | | private void ApplyRequestBodyRefAttribute( |
| | | 762 | | CommentHelpInfo help, |
| | | 763 | | MapRouteOptions routeOptions, |
| | | 764 | | OpenAPIPathMetadata metadata, |
| | | 765 | | ParameterMetadata paramInfo, |
| | | 766 | | OpenApiRequestBodyRefAttribute attribute) |
| | | 767 | | { |
| | 0 | 768 | | var referenceId = ResolveRequestBodyReferenceId(attribute, paramInfo); |
| | 0 | 769 | | var componentRequestBody = GetRequestBody(referenceId); |
| | | 770 | | |
| | 0 | 771 | | metadata.RequestBody = attribute.Inline ? componentRequestBody.Clone() : new OpenApiRequestBodyReference(referen |
| | 0 | 772 | | metadata.RequestBody.Description = attribute.Description ?? help.GetParameterDescription(paramInfo.Name); |
| | | 773 | | |
| | 0 | 774 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentRequestBody)); |
| | 0 | 775 | | } |
| | | 776 | | |
| | | 777 | | /// <summary> |
| | | 778 | | /// Resolves the reference ID for the OpenApiRequestBodyRef attribute. |
| | | 779 | | /// </summary> |
| | | 780 | | /// <param name="attribute">The OpenApiRequestBodyRef attribute.</param> |
| | | 781 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 782 | | /// <returns>The resolved reference ID.</returns> |
| | | 783 | | /// <exception cref="InvalidOperationException"> |
| | | 784 | | /// Thrown when the ReferenceId is not specified and the parameter type is 'object', |
| | | 785 | | /// or when the ReferenceId does not match the parameter type name. |
| | | 786 | | /// </exception> |
| | | 787 | | private string ResolveRequestBodyReferenceId(OpenApiRequestBodyRefAttribute attribute, ParameterMetadata paramInfo) |
| | | 788 | | { |
| | 0 | 789 | | if (string.IsNullOrWhiteSpace(attribute.ReferenceId)) |
| | | 790 | | { |
| | 0 | 791 | | if (paramInfo.ParameterType.Name is "Object" or null) |
| | | 792 | | { |
| | 0 | 793 | | throw new InvalidOperationException("OpenApiRequestBodyRefAttribute must have a ReferenceId specified wh |
| | | 794 | | } |
| | | 795 | | |
| | 0 | 796 | | attribute.ReferenceId = paramInfo.ParameterType.Name; |
| | | 797 | | } |
| | 0 | 798 | | else if (paramInfo.ParameterType.Name != "Object" && attribute.ReferenceId != paramInfo.ParameterType.Name) |
| | | 799 | | { |
| | 0 | 800 | | return FindReferenceIdForParameter(attribute.ReferenceId, paramInfo); |
| | | 801 | | } |
| | | 802 | | // Return the reference ID as is |
| | 0 | 803 | | return attribute.ReferenceId; |
| | | 804 | | } |
| | | 805 | | |
| | | 806 | | /// <summary> |
| | | 807 | | /// Finds and validates the reference ID for a request body parameter. |
| | | 808 | | /// </summary> |
| | | 809 | | /// <param name="referenceId">The reference ID to validate.</param> |
| | | 810 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 811 | | /// <returns>The validated reference ID.</returns> |
| | | 812 | | /// <exception cref="InvalidOperationException">Thrown when the reference ID does not match the parameter type name. |
| | | 813 | | private string FindReferenceIdForParameter(string referenceId, ParameterMetadata paramInfo) |
| | | 814 | | { |
| | | 815 | | // Ensure the reference ID exists and has a schema |
| | 0 | 816 | | if (!TryGetFirstRequestBodySchema(referenceId, out var schema)) |
| | | 817 | | { |
| | 0 | 818 | | throw new InvalidOperationException( |
| | 0 | 819 | | $"Request body component with ReferenceId '{referenceId}' was not found or does not define a schema."); |
| | | 820 | | } |
| | | 821 | | // Validate that the schema matches the parameter type |
| | 0 | 822 | | if (!IsRequestBodySchemaMatchForParameter(schema, paramInfo.ParameterType)) |
| | | 823 | | { |
| | 0 | 824 | | throw new InvalidOperationException( |
| | 0 | 825 | | $"Schema for request body component '{referenceId}' does not match parameter type '{paramInfo.ParameterT |
| | | 826 | | } |
| | | 827 | | // return the validated reference ID |
| | 0 | 828 | | return referenceId; |
| | | 829 | | } |
| | | 830 | | |
| | | 831 | | /// <summary> |
| | | 832 | | /// Attempts to retrieve the first schema defined on a request body component. |
| | | 833 | | /// </summary> |
| | | 834 | | /// <param name="referenceId">The request body component reference ID.</param> |
| | | 835 | | /// <param name="schema">The extracted schema when available.</param> |
| | | 836 | | /// <returns><see langword="true"/> if a non-null schema is found; otherwise <see langword="false"/>.</returns> |
| | | 837 | | private bool TryGetFirstRequestBodySchema(string referenceId, out IOpenApiSchema schema) |
| | | 838 | | { |
| | 0 | 839 | | schema = null!; |
| | | 840 | | |
| | 0 | 841 | | if (!TryGetRequestBodyItem(referenceId, out var requestBody, out _)) |
| | | 842 | | { |
| | 0 | 843 | | return false; |
| | | 844 | | } |
| | | 845 | | |
| | 0 | 846 | | if (requestBody?.Content is null || requestBody.Content.Count == 0) |
| | | 847 | | { |
| | 0 | 848 | | return false; |
| | | 849 | | } |
| | | 850 | | |
| | 0 | 851 | | schema = requestBody.Content.First().Value.Schema!; |
| | 0 | 852 | | return schema is not null; |
| | | 853 | | } |
| | | 854 | | |
| | | 855 | | /// <summary> |
| | | 856 | | /// Determines whether a request-body schema matches a given CLR parameter type. |
| | | 857 | | /// </summary> |
| | | 858 | | /// <param name="schema">The schema declared for the request body.</param> |
| | | 859 | | /// <param name="parameterType">The CLR parameter type being validated.</param> |
| | | 860 | | /// <returns><see langword="true"/> if the schema matches the parameter type; otherwise <see langword="false"/>.</re |
| | | 861 | | private static bool IsRequestBodySchemaMatchForParameter(IOpenApiSchema schema, Type parameterType) |
| | | 862 | | { |
| | 0 | 863 | | if (schema is OpenApiSchemaReference schemaRef) |
| | | 864 | | { |
| | 0 | 865 | | return schemaRef.Reference.Id == parameterType.Name; |
| | | 866 | | } |
| | | 867 | | |
| | 0 | 868 | | if (schema is OpenApiSchema inlineSchema && PrimitiveSchemaMap.TryGetValue(parameterType, out var valueType)) |
| | | 869 | | { |
| | 0 | 870 | | var expected = valueType(); |
| | 0 | 871 | | return inlineSchema.Format == expected.Format && inlineSchema.Type == expected.Type; |
| | | 872 | | } |
| | | 873 | | |
| | 0 | 874 | | return false; |
| | | 875 | | } |
| | | 876 | | |
| | | 877 | | /// <summary> |
| | | 878 | | /// Applies the OpenApiRequestBody attribute to the function's OpenAPI metadata. |
| | | 879 | | /// </summary> |
| | | 880 | | /// <param name="help">The comment help information.</param> |
| | | 881 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 882 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 883 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 884 | | /// <param name="attribute">The OpenApiRequestBody attribute containing request body details.</param> |
| | | 885 | | private void ApplyRequestBodyAttribute( |
| | | 886 | | CommentHelpInfo help, |
| | | 887 | | MapRouteOptions routeOptions, |
| | | 888 | | OpenAPIPathMetadata metadata, |
| | | 889 | | ParameterMetadata paramInfo, |
| | | 890 | | OpenApiRequestBodyAttribute attribute) |
| | | 891 | | { |
| | 0 | 892 | | var requestBodyPreferred = ComponentRequestBodiesExists(paramInfo.ParameterType.Name); |
| | | 893 | | |
| | 0 | 894 | | if (requestBodyPreferred) |
| | | 895 | | { |
| | 0 | 896 | | ApplyPreferredRequestBody(help, routeOptions, metadata, paramInfo, attribute); |
| | 0 | 897 | | return; |
| | | 898 | | } |
| | | 899 | | |
| | 0 | 900 | | var requestBody = new OpenApiRequestBody(); |
| | 0 | 901 | | var schema = InferPrimitiveSchema(type: paramInfo.ParameterType, inline: attribute.Inline); |
| | | 902 | | |
| | 0 | 903 | | if (!CreateRequestBodyFromAttribute(attribute, requestBody, schema)) |
| | | 904 | | { |
| | 0 | 905 | | return; |
| | | 906 | | } |
| | | 907 | | |
| | 0 | 908 | | metadata.RequestBody = requestBody; |
| | 0 | 909 | | metadata.RequestBody.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | 0 | 910 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, requestBody)); |
| | 0 | 911 | | } |
| | | 912 | | |
| | | 913 | | /// <summary> |
| | | 914 | | /// Applies the OpenApiRequestBodyExampleRef attribute to the function's OpenAPI metadata. |
| | | 915 | | /// </summary> |
| | | 916 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 917 | | /// <param name="attribute">The OpenApiRequestBodyExampleRef attribute containing example reference details.</param> |
| | | 918 | | /// <exception cref="InvalidOperationException">Thrown when the request body or its content is not properly defined. |
| | | 919 | | private void ApplyRequestBodyExampleRefAttribute( |
| | | 920 | | OpenAPIPathMetadata metadata, |
| | | 921 | | OpenApiRequestBodyExampleRefAttribute attribute) |
| | | 922 | | { |
| | 0 | 923 | | var requestBody = metadata.RequestBody |
| | 0 | 924 | | ?? throw new InvalidOperationException( |
| | 0 | 925 | | "OpenApiRequestBodyExampleRefAttribute must follow OpenApiRequestBodyAttribute or OpenApiRequestBodyRefAttri |
| | | 926 | | |
| | 0 | 927 | | if (requestBody.Content is null) |
| | | 928 | | { |
| | 0 | 929 | | throw new InvalidOperationException( |
| | 0 | 930 | | "OpenApiRequestBodyExampleRefAttribute requires the request body to have content defined."); |
| | | 931 | | } |
| | | 932 | | |
| | 0 | 933 | | foreach (var oamt in requestBody.Content.Values.OfType<OpenApiMediaType>()) |
| | | 934 | | { |
| | 0 | 935 | | oamt.Examples ??= new Dictionary<string, IOpenApiExample>(); |
| | 0 | 936 | | _ = TryAddExample(oamt.Examples, attribute); |
| | | 937 | | } |
| | 0 | 938 | | } |
| | | 939 | | |
| | | 940 | | /// <summary> |
| | | 941 | | /// Applies the preferred request body from components to the function's OpenAPI metadata. |
| | | 942 | | /// </summary> |
| | | 943 | | /// <param name="help">The comment help information.</param> |
| | | 944 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 945 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 946 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 947 | | /// <param name="attribute">The OpenApiRequestBody attribute containing request body details.</param> |
| | | 948 | | private void ApplyPreferredRequestBody( |
| | | 949 | | CommentHelpInfo help, |
| | | 950 | | MapRouteOptions routeOptions, |
| | | 951 | | OpenAPIPathMetadata metadata, |
| | | 952 | | ParameterMetadata paramInfo, |
| | | 953 | | OpenApiRequestBodyAttribute attribute) |
| | | 954 | | { |
| | 0 | 955 | | var componentRequestBody = GetRequestBody(paramInfo.ParameterType.Name); |
| | | 956 | | |
| | 0 | 957 | | metadata.RequestBody = attribute.Inline |
| | 0 | 958 | | ? componentRequestBody.Clone() |
| | 0 | 959 | | : new OpenApiRequestBodyReference(paramInfo.ParameterType.Name); |
| | | 960 | | |
| | 0 | 961 | | metadata.RequestBody.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | 0 | 962 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentRequestBody)); |
| | 0 | 963 | | } |
| | | 964 | | #endregion |
| | | 965 | | |
| | | 966 | | /// <summary> |
| | | 967 | | /// Ensures that the OpenAPIPathMetadata has default responses defined. |
| | | 968 | | /// </summary> |
| | | 969 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 970 | | private static void EnsureDefaultResponses(OpenAPIPathMetadata metadata) |
| | | 971 | | { |
| | 0 | 972 | | metadata.Responses ??= []; |
| | 0 | 973 | | if (metadata.Responses.Count > 0) |
| | | 974 | | { |
| | 0 | 975 | | return; |
| | | 976 | | } |
| | 0 | 977 | | if (metadata.IsOpenApiCallback) |
| | | 978 | | { |
| | 0 | 979 | | metadata.Responses.Add("204", new OpenApiResponse { Description = "Accepted" }); |
| | | 980 | | } |
| | | 981 | | else |
| | | 982 | | { |
| | 0 | 983 | | metadata.Responses.Add("200", new OpenApiResponse { Description = "Ok" }); |
| | 0 | 984 | | metadata.Responses.Add("default", new OpenApiResponse { Description = "Unexpected error" }); |
| | | 985 | | } |
| | 0 | 986 | | } |
| | | 987 | | |
| | | 988 | | /// <summary> |
| | | 989 | | /// Finalizes the route options by adding OpenAPI metadata and configuring defaults. |
| | | 990 | | /// </summary> |
| | | 991 | | /// <param name="func">The function information.</param> |
| | | 992 | | /// <param name="sb">The script block.</param> |
| | | 993 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 994 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 995 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 996 | | private void FinalizeRouteOptions( |
| | | 997 | | FunctionInfo func, |
| | | 998 | | ScriptBlock sb, |
| | | 999 | | OpenAPIPathMetadata metadata, |
| | | 1000 | | MapRouteOptions routeOptions, |
| | | 1001 | | HttpVerb parsedVerb) |
| | | 1002 | | { |
| | 0 | 1003 | | metadata.DocumentId ??= Host.OpenApiDocumentIds; |
| | 0 | 1004 | | var documentIds = metadata.DocumentId; |
| | 0 | 1005 | | if (metadata.IsOpenApiPath) |
| | | 1006 | | { |
| | 0 | 1007 | | FinalizePathRouteOptions(func, sb, metadata, routeOptions, parsedVerb); |
| | 0 | 1008 | | return; |
| | | 1009 | | } |
| | | 1010 | | |
| | 0 | 1011 | | if (metadata.IsOpenApiWebhook) |
| | | 1012 | | { |
| | 0 | 1013 | | RegisterWebhook(func, sb, metadata, parsedVerb, documentIds); |
| | 0 | 1014 | | return; |
| | | 1015 | | } |
| | | 1016 | | |
| | 0 | 1017 | | if (metadata.IsOpenApiCallback) |
| | | 1018 | | { |
| | 0 | 1019 | | RegisterCallback(func, sb, metadata, parsedVerb, documentIds); |
| | | 1020 | | } |
| | 0 | 1021 | | } |
| | | 1022 | | |
| | | 1023 | | /// <summary> |
| | | 1024 | | /// Finalizes the route options for a standard OpenAPI path. |
| | | 1025 | | /// </summary> |
| | | 1026 | | /// <param name="func">The function information.</param> |
| | | 1027 | | /// <param name="sb">The script block.</param> |
| | | 1028 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 1029 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1030 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1031 | | private void FinalizePathRouteOptions( |
| | | 1032 | | FunctionInfo func, |
| | | 1033 | | ScriptBlock sb, |
| | | 1034 | | OpenAPIPathMetadata metadata, |
| | | 1035 | | MapRouteOptions routeOptions, |
| | | 1036 | | HttpVerb parsedVerb) |
| | | 1037 | | { |
| | 0 | 1038 | | routeOptions.OpenAPI.Add(parsedVerb, metadata); |
| | | 1039 | | |
| | 0 | 1040 | | if (string.IsNullOrWhiteSpace(routeOptions.Pattern)) |
| | | 1041 | | { |
| | 0 | 1042 | | routeOptions.Pattern = "/" + func.Name; |
| | | 1043 | | } |
| | | 1044 | | |
| | 0 | 1045 | | if (!string.IsNullOrWhiteSpace(metadata.CorsPolicy)) |
| | | 1046 | | { |
| | 0 | 1047 | | routeOptions.CorsPolicy = metadata.CorsPolicy; |
| | | 1048 | | } |
| | | 1049 | | |
| | 0 | 1050 | | routeOptions.ScriptCode.ScriptBlock = sb; |
| | 0 | 1051 | | routeOptions.DefaultResponseContentType = "application/json"; |
| | 0 | 1052 | | _ = Host.AddMapRoute(routeOptions); |
| | 0 | 1053 | | } |
| | | 1054 | | /// <summary> |
| | | 1055 | | /// Registers a webhook in the OpenAPI document descriptors. |
| | | 1056 | | /// </summary> |
| | | 1057 | | /// <param name="func">The function information.</param> |
| | | 1058 | | /// <param name="sb">The script block.</param> |
| | | 1059 | | /// <param name="metadata">The OpenAPI path metadata.</param> |
| | | 1060 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1061 | | /// <param name="documentIds">The collection of OpenAPI document IDs.</param> |
| | | 1062 | | private void RegisterWebhook(FunctionInfo func, ScriptBlock sb, OpenAPIPathMetadata metadata, HttpVerb parsedVerb, I |
| | | 1063 | | { |
| | 0 | 1064 | | EnsureParamOnlyScriptBlock(func, sb, kind: "webhook"); |
| | 0 | 1065 | | foreach (var docId in documentIds) |
| | | 1066 | | { |
| | 0 | 1067 | | var docdesc = GetDocDescriptorOrThrow(docId, attributeName: "OpenApiWebhook"); |
| | 0 | 1068 | | _ = docdesc.WebHook.TryAdd((metadata.Pattern, parsedVerb), metadata); |
| | | 1069 | | } |
| | 0 | 1070 | | } |
| | | 1071 | | /// <summary> |
| | | 1072 | | /// Registers a callback in the OpenAPI document descriptors. |
| | | 1073 | | /// </summary> |
| | | 1074 | | /// <param name="func">The function information.</param> |
| | | 1075 | | /// <param name="sb">The script block.</param> |
| | | 1076 | | /// <param name="metadata">The OpenAPI path metadata.</param> |
| | | 1077 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1078 | | /// <param name="documentIds">The collection of OpenAPI document IDs.</param> |
| | | 1079 | | private void RegisterCallback(FunctionInfo func, ScriptBlock sb, OpenAPIPathMetadata metadata, HttpVerb parsedVerb, |
| | | 1080 | | { |
| | 0 | 1081 | | EnsureParamOnlyScriptBlock(func, sb, kind: "callback"); |
| | 0 | 1082 | | foreach (var docId in documentIds) |
| | | 1083 | | { |
| | 0 | 1084 | | var docdesc = GetDocDescriptorOrThrow(docId, attributeName: "OpenApiCallback"); |
| | 0 | 1085 | | _ = docdesc.Callbacks.TryAdd((metadata.Pattern, parsedVerb), metadata); |
| | | 1086 | | } |
| | 0 | 1087 | | } |
| | | 1088 | | |
| | | 1089 | | /// <summary> |
| | | 1090 | | /// Retrieves the OpenApiDocDescriptor for the specified document ID or throws an exception if not found. |
| | | 1091 | | /// </summary> |
| | | 1092 | | /// <param name="docId">The document ID to look up.</param> |
| | | 1093 | | /// <param name="attributeName">The name of the attribute requesting the document.</param> |
| | | 1094 | | /// <returns>The corresponding OpenApiDocDescriptor.</returns> |
| | | 1095 | | private OpenApiDocDescriptor GetDocDescriptorOrThrow(string docId, string attributeName) |
| | | 1096 | | { |
| | 0 | 1097 | | return Host.OpenApiDocumentDescriptor.TryGetValue(docId, out var docdesc) |
| | 0 | 1098 | | ? docdesc |
| | 0 | 1099 | | : throw new InvalidOperationException($"The OpenAPI document ID '{docId}' specified in the {attributeName} a |
| | | 1100 | | } |
| | | 1101 | | |
| | | 1102 | | /// <summary> |
| | | 1103 | | /// Ensures that the ScriptBlock contains only a param() block with no executable statements. |
| | | 1104 | | /// </summary> |
| | | 1105 | | /// <param name="func">The function information.</param> |
| | | 1106 | | /// <param name="sb">The ScriptBlock to validate.</param> |
| | | 1107 | | /// <param name="kind">The kind of function (e.g., "webhook" or "callback").</param> |
| | | 1108 | | /// <exception cref="InvalidOperationException">Thrown if the ScriptBlock contains executable statements other than |
| | | 1109 | | private static void EnsureParamOnlyScriptBlock(FunctionInfo func, ScriptBlock sb, string kind) |
| | | 1110 | | { |
| | 0 | 1111 | | if (!PsScriptBlockValidation.IsParamLast(sb)) |
| | | 1112 | | { |
| | 0 | 1113 | | throw new InvalidOperationException($"The ScriptBlock for {kind} function '{func.Name}' must contain only a |
| | | 1114 | | } |
| | 0 | 1115 | | } |
| | | 1116 | | |
| | | 1117 | | /// <summary> |
| | | 1118 | | /// Creates a request body from the given attribute. |
| | | 1119 | | /// </summary> |
| | | 1120 | | /// <param name="attribute">The attribute containing request body information.</param> |
| | | 1121 | | /// <param name="requestBody">The OpenApiRequestBody object to populate.</param> |
| | | 1122 | | /// <param name="schema">The schema to associate with the request body.</param> |
| | | 1123 | | /// <returns>True if the request body was created successfully; otherwise, false.</returns> |
| | | 1124 | | private static bool CreateRequestBodyFromAttribute(KestrunAnnotation attribute, OpenApiRequestBody requestBody, IOpe |
| | | 1125 | | { |
| | | 1126 | | switch (attribute) |
| | | 1127 | | { |
| | | 1128 | | case OpenApiRequestBodyAttribute request: |
| | 0 | 1129 | | requestBody.Description = request.Description; |
| | 0 | 1130 | | requestBody.Required = request.Required; |
| | | 1131 | | // Content |
| | 0 | 1132 | | requestBody.Content ??= new Dictionary<string, IOpenApiMediaType>(StringComparer.Ordinal); |
| | 0 | 1133 | | var mediaType = new OpenApiMediaType(); |
| | | 1134 | | // Example |
| | 0 | 1135 | | if (request.Example is not null) |
| | | 1136 | | { |
| | 0 | 1137 | | mediaType.Example = OpenApiJsonNodeFactory.ToNode(request.Example); |
| | | 1138 | | } |
| | | 1139 | | // Schema |
| | 0 | 1140 | | mediaType.Schema = schema; |
| | 0 | 1141 | | foreach (var contentType in request.ContentType) |
| | | 1142 | | { |
| | 0 | 1143 | | requestBody.Content[contentType] = mediaType; |
| | | 1144 | | } |
| | 0 | 1145 | | return true; |
| | | 1146 | | default: |
| | 0 | 1147 | | return false; |
| | | 1148 | | } |
| | | 1149 | | } |
| | | 1150 | | } |