| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Management.Automation.Internal; |
| | | 4 | | using System.Management.Automation.Language; |
| | | 5 | | using System.Text.Json.Nodes; |
| | | 6 | | using Kestrun.Forms; |
| | | 7 | | using Kestrun.Hosting; |
| | | 8 | | using Kestrun.Hosting.Options; |
| | | 9 | | using Kestrun.Languages; |
| | | 10 | | using Kestrun.Utilities; |
| | | 11 | | using Microsoft.OpenApi; |
| | | 12 | | |
| | | 13 | | namespace Kestrun.OpenApi; |
| | | 14 | | |
| | | 15 | | public partial class OpenApiDocDescriptor |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Enumerates all in-session PowerShell functions in the given runspace, |
| | | 19 | | /// detects those annotated with [OpenApiPath], and maps them into the provided KestrunHost. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="cmdInfos">List of FunctionInfo objects representing PowerShell functions.</param> |
| | | 22 | | public void LoadAnnotatedFunctions(List<FunctionInfo> cmdInfos) |
| | | 23 | | { |
| | 0 | 24 | | ArgumentNullException.ThrowIfNull(cmdInfos); |
| | 0 | 25 | | var callbacks = cmdInfos |
| | 0 | 26 | | .Where(f => f.ScriptBlock.Attributes?.All(a => a is OpenApiCallbackAttribute) != false); |
| | | 27 | | |
| | 0 | 28 | | var others = cmdInfos |
| | 0 | 29 | | .Where(f => f.ScriptBlock.Attributes?.All(a => a is not OpenApiCallbackAttribute) != false); |
| | | 30 | | // (equivalent to NOT having any callback attribute) |
| | | 31 | | |
| | 0 | 32 | | foreach (var func in callbacks) |
| | | 33 | | { |
| | 0 | 34 | | ProcessFunction(func); |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | BuildCallbacks(Callbacks); |
| | 0 | 38 | | foreach (var func in others) |
| | | 39 | | { |
| | 0 | 40 | | ProcessFunction(func); |
| | | 41 | | } |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Processes a single PowerShell function, extracting OpenAPI annotations and configuring the host accordingly. |
| | | 46 | | /// </summary> |
| | | 47 | | /// <param name="func">The function information.</param> |
| | | 48 | | private void ProcessFunction(FunctionInfo func) |
| | | 49 | | { |
| | | 50 | | try |
| | | 51 | | { |
| | 0 | 52 | | var help = func.GetHelp(); |
| | 0 | 53 | | var sb = func.ScriptBlock; |
| | 0 | 54 | | if (sb is null) |
| | | 55 | | { |
| | 0 | 56 | | return; |
| | | 57 | | } |
| | | 58 | | |
| | 0 | 59 | | var attrs = sb.Attributes; |
| | 0 | 60 | | if (attrs.Count == 0) |
| | | 61 | | { |
| | 0 | 62 | | return; |
| | | 63 | | } |
| | | 64 | | // Create route options and OpenAPI metadata |
| | 0 | 65 | | var routeOptions = new MapRouteOptions |
| | 0 | 66 | | { |
| | 0 | 67 | | // Seed defaults up-front so response attributes can safely add per-status entries |
| | 0 | 68 | | // without losing the host-level 'default' fallback. |
| | 0 | 69 | | DefaultResponseContentType = new Dictionary<string, ICollection<ContentTypeWithSchema>>(Host.Options.Def |
| | 0 | 70 | | }; |
| | 0 | 71 | | var openApiMetadata = new OpenAPIPathMetadata(mapOptions: routeOptions); |
| | | 72 | | // Process attributes to populate route options and OpenAPI metadata |
| | 0 | 73 | | var parsedVerb = ProcessFunctionAttributes(func, help!, attrs, routeOptions, openApiMetadata); |
| | | 74 | | |
| | 0 | 75 | | ProcessParameters(func, help!, routeOptions, openApiMetadata); |
| | | 76 | | |
| | 0 | 77 | | EnsureDefaultResponses(openApiMetadata); |
| | 0 | 78 | | FinalizeRouteOptions(func, sb, openApiMetadata, routeOptions, parsedVerb); |
| | 0 | 79 | | } |
| | 0 | 80 | | catch (Exception ex) |
| | | 81 | | { |
| | 0 | 82 | | Host.Logger.Error("Error loading OpenAPI annotated function '{funcName}': {message}", func.Name, ex.Message) |
| | 0 | 83 | | } |
| | 0 | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <summary> |
| | | 87 | | /// Processes the OpenAPI-related attributes on the specified function. |
| | | 88 | | /// </summary> |
| | | 89 | | /// <param name="func">The function information.</param> |
| | | 90 | | /// <param name="help">The comment help information.</param> |
| | | 91 | | /// <param name="attrs">The collection of attributes applied to the function.</param> |
| | | 92 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 93 | | /// <param name="openApiMetadata">The OpenAPI metadata to populate.</param> |
| | | 94 | | /// <returns>The parsed HTTP verb for the function.</returns> |
| | | 95 | | private HttpVerb ProcessFunctionAttributes( |
| | | 96 | | FunctionInfo func, |
| | | 97 | | CommentHelpInfo help, |
| | | 98 | | IReadOnlyCollection<Attribute> attrs, |
| | | 99 | | MapRouteOptions routeOptions, |
| | | 100 | | OpenAPIPathMetadata openApiMetadata) |
| | | 101 | | { |
| | 0 | 102 | | var parsedVerb = HttpVerb.Get; |
| | | 103 | | |
| | 0 | 104 | | foreach (var attr in attrs) |
| | | 105 | | { |
| | | 106 | | try |
| | | 107 | | { |
| | | 108 | | switch (attr) |
| | | 109 | | { |
| | | 110 | | case OpenApiPathAttribute path: |
| | 0 | 111 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, path); |
| | 0 | 112 | | break; |
| | | 113 | | case OpenApiWebhookAttribute webhook: |
| | 0 | 114 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, webhook); |
| | 0 | 115 | | break; |
| | | 116 | | case OpenApiCallbackAttribute callbackOperation: |
| | 0 | 117 | | parsedVerb = ApplyPathAttribute(func, help, routeOptions, openApiMetadata, parsedVerb, callbackO |
| | 0 | 118 | | break; |
| | | 119 | | case OpenApiExtensionAttribute extensionAttr: |
| | 0 | 120 | | ApplyExtensionAttribute(openApiMetadata, extensionAttr); |
| | 0 | 121 | | break; |
| | | 122 | | case OpenApiResponseRefAttribute responseRef: |
| | 0 | 123 | | ApplyResponseRefAttribute(openApiMetadata, responseRef, routeOptions); |
| | 0 | 124 | | break; |
| | | 125 | | case OpenApiResponseAttribute responseAttr: |
| | 0 | 126 | | ApplyResponseAttribute(openApiMetadata, responseAttr, routeOptions); |
| | 0 | 127 | | break; |
| | | 128 | | case OpenApiResponseExampleRefAttribute responseAttr: |
| | 0 | 129 | | ApplyResponseAttribute(openApiMetadata, responseAttr, routeOptions); |
| | 0 | 130 | | break; |
| | | 131 | | case OpenApiResponseLinkRefAttribute linkRefAttr: |
| | 0 | 132 | | ApplyResponseLinkAttribute(openApiMetadata, linkRefAttr); |
| | 0 | 133 | | break; |
| | | 134 | | case OpenApiPropertyAttribute propertyAttr: |
| | 0 | 135 | | ApplyPropertyAttribute(openApiMetadata, propertyAttr); |
| | 0 | 136 | | break; |
| | | 137 | | case OpenApiAuthorizationAttribute authAttr: |
| | 0 | 138 | | ApplyAuthorizationAttribute(routeOptions, openApiMetadata, authAttr); |
| | 0 | 139 | | break; |
| | | 140 | | case IOpenApiResponseHeaderAttribute responseHeaderAttr: |
| | 0 | 141 | | ApplyResponseHeaderAttribute(openApiMetadata, responseHeaderAttr); |
| | 0 | 142 | | break; |
| | | 143 | | case OpenApiCallbackRefAttribute callbackRefAttr: |
| | 0 | 144 | | ApplyCallbackRefAttribute(openApiMetadata, callbackRefAttr); |
| | 0 | 145 | | break; |
| | | 146 | | case KrBindFormAttribute formAttr: |
| | 0 | 147 | | ApplyFormBindingAttribute(routeOptions, formAttr); |
| | 0 | 148 | | break; |
| | | 149 | | case KestrunAnnotation ka: |
| | 0 | 150 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 151 | | } |
| | 0 | 152 | | } |
| | 0 | 153 | | catch (InvalidOperationException ex) |
| | | 154 | | { |
| | 0 | 155 | | Host.Logger.Error(ex, "Error processing OpenApiPath attribute on function '{funcName}': {message}", func |
| | 0 | 156 | | } |
| | 0 | 157 | | catch (Exception ex) |
| | | 158 | | { |
| | 0 | 159 | | Host.Logger.Error(ex, "Error processing OpenApiPath attribute on function '{funcName}': {message}", func |
| | 0 | 160 | | } |
| | | 161 | | } |
| | | 162 | | |
| | 0 | 163 | | return parsedVerb; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | private void ApplyFormBindingAttribute(MapRouteOptions routeOptions, KrBindFormAttribute formAttr) |
| | | 167 | | { |
| | 0 | 168 | | if (formAttr.Template is not null) |
| | | 169 | | { |
| | 0 | 170 | | if (!Host.Runtime.FormOptions.TryGetValue(formAttr.Template, out var template)) |
| | | 171 | | { |
| | 0 | 172 | | throw new InvalidOperationException($"Form options template '{formAttr.Template}' not found."); |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | // Clone the template to avoid modifying the original |
| | 0 | 176 | | routeOptions.FormOptions = new KrFormOptions(template); |
| | 0 | 177 | | return; |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | // If no template is specified, apply the attribute properties directly |
| | 0 | 181 | | var formOptions = FormHelper.ApplyKrPartAttributes(formAttr); |
| | | 182 | | |
| | | 183 | | // Assign the form options to the route options |
| | 0 | 184 | | routeOptions.FormOptions = formOptions; |
| | 0 | 185 | | } |
| | | 186 | | |
| | | 187 | | /// <summary> |
| | | 188 | | /// Applies the OpenApiExtension attribute to the function's OpenAPI metadata. |
| | | 189 | | /// </summary> |
| | | 190 | | /// <param name="openApiMetadata">The OpenAPI metadata to which the extension will be applied.</param> |
| | | 191 | | /// <param name="extensionAttr">The OpenApiExtension attribute containing the extension data.</param> |
| | | 192 | | private void ApplyExtensionAttribute(OpenAPIPathMetadata openApiMetadata, OpenApiExtensionAttribute extensionAttr) |
| | | 193 | | { |
| | 3 | 194 | | if (Host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 195 | | { |
| | 3 | 196 | | Host.Logger.Debug("Applying OpenApiExtension '{extensionName}' to function metadata", extensionAttr.Name); |
| | | 197 | | } |
| | 3 | 198 | | openApiMetadata.Extensions ??= []; |
| | | 199 | | |
| | | 200 | | // Parse string into a JsonNode tree. |
| | 3 | 201 | | var node = JsonNode.Parse(extensionAttr.Json); |
| | 3 | 202 | | if (node is null) |
| | | 203 | | { |
| | 1 | 204 | | Host.Logger.Error("Error parsing OpenAPI extension '{extensionName}': JSON is null", extensionAttr.Name); |
| | 1 | 205 | | return; |
| | | 206 | | } |
| | 2 | 207 | | openApiMetadata.Extensions[extensionAttr.Name] = new JsonNodeExtension(node); |
| | 2 | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Applies the OpenApiPath attribute to the function's route options and metadata. |
| | | 212 | | /// </summary> |
| | | 213 | | /// <param name="func">The function information.</param> |
| | | 214 | | /// <param name="help">The comment help information.</param> |
| | | 215 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 216 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 217 | | /// <param name="parsedVerb">The currently parsed HTTP verb.</param> |
| | | 218 | | /// <param name="oaPath">The OpenApiPath attribute instance.</param> |
| | | 219 | | /// <returns>The updated HTTP verb after processing the attribute.</returns> |
| | | 220 | | private static HttpVerb ApplyPathAttribute( |
| | | 221 | | FunctionInfo func, |
| | | 222 | | CommentHelpInfo help, |
| | | 223 | | MapRouteOptions routeOptions, |
| | | 224 | | OpenAPIPathMetadata metadata, |
| | | 225 | | HttpVerb parsedVerb, |
| | | 226 | | IOpenApiPathAttribute oaPath) |
| | | 227 | | { |
| | 0 | 228 | | var httpVerb = oaPath.HttpVerb ?? string.Empty; |
| | 0 | 229 | | if (!string.IsNullOrWhiteSpace(httpVerb)) |
| | | 230 | | { |
| | 0 | 231 | | parsedVerb = HttpVerbExtensions.FromMethodString(httpVerb); |
| | 0 | 232 | | routeOptions.HttpVerbs.Add(parsedVerb); |
| | | 233 | | } |
| | | 234 | | |
| | 0 | 235 | | var pattern = oaPath.Pattern; |
| | 0 | 236 | | if (string.IsNullOrWhiteSpace(pattern)) |
| | | 237 | | { |
| | 0 | 238 | | throw new InvalidOperationException("OpenApiPath attribute must specify a non-empty Pattern property."); |
| | | 239 | | } |
| | 0 | 240 | | var openApiPattern = pattern; |
| | 0 | 241 | | var routePattern = pattern; |
| | 0 | 242 | | if (oaPath is OpenApiPathAttribute) |
| | | 243 | | { |
| | 0 | 244 | | if (!Rfc6570PathTemplateMapper.TryMapToKestrelRoute(pattern, out var mapping, out var error)) |
| | | 245 | | { |
| | 0 | 246 | | throw new InvalidOperationException($"OpenApiPath pattern '{pattern}' is invalid: {error}"); |
| | | 247 | | } |
| | | 248 | | |
| | 0 | 249 | | openApiPattern = mapping.OpenApiPattern; |
| | 0 | 250 | | routePattern = mapping.KestrelPattern; |
| | 0 | 251 | | AddQueryParametersFromTemplate(metadata, mapping.QueryParameters); |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | // Apply pattern, summary, description, tags |
| | 0 | 255 | | routeOptions.Pattern = routePattern; |
| | 0 | 256 | | metadata.Summary = ChooseFirstNonEmpty(oaPath.Summary, help.GetSynopsis()); |
| | 0 | 257 | | metadata.Description = ChooseFirstNonEmpty(oaPath.Description, help.GetDescription()); |
| | 0 | 258 | | metadata.Tags = [.. oaPath.Tags]; |
| | | 259 | | |
| | | 260 | | // Apply deprecated flag if specified |
| | 0 | 261 | | metadata.Deprecated |= oaPath.Deprecated; |
| | | 262 | | // Apply document ID if specified |
| | 0 | 263 | | metadata.DocumentId = oaPath.DocumentId; |
| | | 264 | | switch (oaPath) |
| | | 265 | | { |
| | | 266 | | case OpenApiPathAttribute oaPathConcrete: |
| | 0 | 267 | | ApplyPathLikePath(func, routeOptions, metadata, oaPathConcrete, openApiPattern); |
| | 0 | 268 | | break; |
| | | 269 | | case OpenApiWebhookAttribute oaWebhook: |
| | 0 | 270 | | ApplyPathLikeWebhook(func, metadata, oaWebhook, pattern); |
| | 0 | 271 | | break; |
| | | 272 | | case OpenApiCallbackAttribute oaCallback: |
| | 0 | 273 | | ApplyPathLikeCallback(func, metadata, oaCallback, httpVerb, pattern); |
| | | 274 | | break; |
| | | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | return parsedVerb; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | /// <summary> |
| | | 281 | | /// Applies the OpenApiPath attribute to the function's route options and metadata for a standard path. |
| | | 282 | | /// </summary> |
| | | 283 | | /// <param name="func">The function information.</param> |
| | | 284 | | /// <param name="routeOptions">The route options to configure.</param> |
| | | 285 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 286 | | /// <param name="oaPath">The OpenApiPath attribute instance.</param> |
| | | 287 | | /// <param name="openApiPattern">The OpenAPI path pattern.</param> |
| | | 288 | | private static void ApplyPathLikePath( |
| | | 289 | | FunctionInfo func, |
| | | 290 | | MapRouteOptions routeOptions, |
| | | 291 | | OpenAPIPathMetadata metadata, |
| | | 292 | | OpenApiPathAttribute oaPath, |
| | | 293 | | string openApiPattern) |
| | | 294 | | { |
| | 0 | 295 | | metadata.Pattern = openApiPattern; |
| | 0 | 296 | | metadata.PathLikeKind = OpenApiPathLikeKind.Path; |
| | 0 | 297 | | if (!string.IsNullOrWhiteSpace(oaPath.CorsPolicy)) |
| | | 298 | | { |
| | | 299 | | // Apply Cors policy name if specified |
| | 0 | 300 | | routeOptions.CorsPolicy = oaPath.CorsPolicy; |
| | | 301 | | } |
| | | 302 | | |
| | 0 | 303 | | metadata.OperationId = oaPath.OperationId is null |
| | 0 | 304 | | ? func.Name |
| | 0 | 305 | | : string.IsNullOrWhiteSpace(oaPath.OperationId) ? metadata.OperationId : oaPath.OperationId; |
| | 0 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <summary> |
| | | 309 | | /// Adds query parameters inferred from RFC6570 query expressions. |
| | | 310 | | /// </summary> |
| | | 311 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 312 | | /// <param name="queryParameterNames">The query parameter names to add.</param> |
| | | 313 | | private static void AddQueryParametersFromTemplate( |
| | | 314 | | OpenAPIPathMetadata metadata, |
| | | 315 | | IReadOnlyList<string> queryParameterNames) |
| | | 316 | | { |
| | 0 | 317 | | if (queryParameterNames.Count == 0) |
| | | 318 | | { |
| | 0 | 319 | | return; |
| | | 320 | | } |
| | | 321 | | |
| | 0 | 322 | | metadata.Parameters ??= []; |
| | 0 | 323 | | foreach (var name in queryParameterNames.Distinct(StringComparer.OrdinalIgnoreCase)) |
| | | 324 | | { |
| | 0 | 325 | | if (metadata.Parameters.Any(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))) |
| | | 326 | | { |
| | | 327 | | continue; |
| | | 328 | | } |
| | | 329 | | |
| | 0 | 330 | | metadata.Parameters.Add(new OpenApiParameter |
| | 0 | 331 | | { |
| | 0 | 332 | | Name = name, |
| | 0 | 333 | | In = ParameterLocation.Query, |
| | 0 | 334 | | Required = false, |
| | 0 | 335 | | Schema = new OpenApiSchema { Type = JsonSchemaType.String }, |
| | 0 | 336 | | }); |
| | | 337 | | } |
| | 0 | 338 | | } |
| | | 339 | | /// <summary> |
| | | 340 | | /// Applies the OpenApiWebhook attribute to the function's OpenAPI metadata. |
| | | 341 | | /// </summary> |
| | | 342 | | /// <param name="func">The function information.</param> |
| | | 343 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 344 | | /// <param name="oaPath">The OpenApiWebhook attribute instance.</param> |
| | | 345 | | /// <param name="pattern">The route pattern.</param> |
| | | 346 | | private static void ApplyPathLikeWebhook(FunctionInfo func, OpenAPIPathMetadata metadata, OpenApiWebhookAttribute oa |
| | | 347 | | { |
| | 0 | 348 | | metadata.Pattern = pattern; |
| | 0 | 349 | | metadata.PathLikeKind = OpenApiPathLikeKind.Webhook; |
| | 0 | 350 | | metadata.OperationId = oaPath.OperationId is null |
| | 0 | 351 | | ? func.Name |
| | 0 | 352 | | : string.IsNullOrWhiteSpace(oaPath.OperationId) ? metadata.OperationId : oaPath.OperationId; |
| | 0 | 353 | | } |
| | | 354 | | |
| | | 355 | | /// <summary> |
| | | 356 | | /// Applies the OpenApiCallback attribute to the function's OpenAPI metadata. |
| | | 357 | | /// </summary> |
| | | 358 | | /// <param name="func">The function information.</param> |
| | | 359 | | /// <param name="metadata">The OpenAPI metadata to populate.</param> |
| | | 360 | | /// <param name="oaCallback">The OpenApiCallback attribute instance.</param> |
| | | 361 | | /// <param name="httpVerb">The HTTP verb associated with the callback.</param> |
| | | 362 | | /// <param name="callbackPattern">The callback route pattern.</param> |
| | | 363 | | /// <exception cref="InvalidOperationException">Thrown when the Expression property of the OpenApiCallback attribute |
| | | 364 | | private static void ApplyPathLikeCallback( |
| | | 365 | | FunctionInfo func, |
| | | 366 | | OpenAPIPathMetadata metadata, |
| | | 367 | | OpenApiCallbackAttribute oaCallback, |
| | | 368 | | string httpVerb, |
| | | 369 | | string callbackPattern) |
| | | 370 | | { |
| | | 371 | | // Callbacks are neither paths nor webhooks |
| | 0 | 372 | | metadata.PathLikeKind = OpenApiPathLikeKind.Callback; |
| | 0 | 373 | | if (string.IsNullOrWhiteSpace(oaCallback.Expression)) |
| | | 374 | | { |
| | 0 | 375 | | throw new InvalidOperationException("OpenApiCallback attribute must specify a non-empty Expression property. |
| | | 376 | | } |
| | | 377 | | // Callbacks must have an expression |
| | 0 | 378 | | metadata.Expression = CallbackOperationId.BuildCallbackKey(oaCallback.Expression, callbackPattern); |
| | 0 | 379 | | metadata.Inline = oaCallback.Inline; |
| | 0 | 380 | | metadata.Pattern = func.Name; |
| | 0 | 381 | | metadata.OperationId = string.IsNullOrWhiteSpace(oaCallback.OperationId) |
| | 0 | 382 | | ? CallbackOperationId.FromLastSegment(func.Name, httpVerb, oaCallback.Expression) |
| | 0 | 383 | | : oaCallback.OperationId; |
| | 0 | 384 | | } |
| | | 385 | | |
| | | 386 | | /// <summary> |
| | | 387 | | /// Chooses the first non-empty string from the provided values, normalizing newlines. |
| | | 388 | | /// </summary> |
| | | 389 | | /// <param name="values">An array of string values to evaluate.</param> |
| | | 390 | | /// <returns>The first non-empty string with normalized newlines, or null if all are null or whitespace.</returns> |
| | | 391 | | private static string? ChooseFirstNonEmpty(params string?[] values) |
| | | 392 | | { |
| | 0 | 393 | | foreach (var value in values) |
| | | 394 | | { |
| | 0 | 395 | | if (!string.IsNullOrWhiteSpace(value)) |
| | | 396 | | { |
| | 0 | 397 | | return NormalizeNewlines(value); |
| | | 398 | | } |
| | | 399 | | } |
| | | 400 | | |
| | 0 | 401 | | return null; |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | /// <summary> |
| | | 405 | | /// Normalizes newlines in the given string to use '\n' only. |
| | | 406 | | /// </summary> |
| | | 407 | | /// <param name="value">The string to normalize.</param> |
| | | 408 | | /// <returns>The normalized string.</returns> |
| | 0 | 409 | | private static string? NormalizeNewlines(string? value) => value?.Replace("\r\n", "\n"); |
| | | 410 | | |
| | | 411 | | /// <summary> |
| | | 412 | | /// Applies the OpenApiResponseRef attribute to the function's OpenAPI metadata. |
| | | 413 | | /// </summary> |
| | | 414 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 415 | | /// <param name="attribute">The OpenApiResponseRef attribute containing response reference details.</param> |
| | | 416 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 417 | | private void ApplyResponseRefAttribute(OpenAPIPathMetadata metadata, OpenApiResponseRefAttribute attribute, MapRoute |
| | | 418 | | { |
| | 0 | 419 | | metadata.Responses ??= []; |
| | | 420 | | |
| | 0 | 421 | | if (!TryGetResponseItem(attribute.ReferenceId, out var response, out var inline)) |
| | | 422 | | { |
| | 0 | 423 | | throw new InvalidOperationException($"Response component with ID '{attribute.ReferenceId}' not found."); |
| | | 424 | | } |
| | | 425 | | |
| | 0 | 426 | | IOpenApiResponse iResponse = attribute.Inline || inline ? response!.Clone() : new OpenApiResponseReference(attri |
| | | 427 | | |
| | 0 | 428 | | if (attribute.Description is not null) |
| | | 429 | | { |
| | 0 | 430 | | iResponse.Description = attribute.Description; |
| | | 431 | | } |
| | | 432 | | |
| | 0 | 433 | | if (metadata.Responses.ContainsKey(attribute.StatusCode)) |
| | | 434 | | { |
| | 0 | 435 | | throw new InvalidOperationException($"Response for status code '{attribute.StatusCode}' is already defined f |
| | | 436 | | } |
| | | 437 | | |
| | 0 | 438 | | metadata.Responses.Add(attribute.StatusCode, iResponse); |
| | 0 | 439 | | routeOptions.DefaultResponseContentType ??= new Dictionary<string, ICollection<ContentTypeWithSchema>>(StringCom |
| | | 440 | | |
| | 0 | 441 | | if (response?.Content is not { Count: > 0 }) |
| | | 442 | | { |
| | 0 | 443 | | routeOptions.DefaultResponseContentType[attribute.StatusCode] = []; |
| | 0 | 444 | | return; |
| | | 445 | | } |
| | | 446 | | |
| | | 447 | | // Note: if the existing response is a reference, we still apply the new response details to it. |
| | | 448 | | // This allows attributes to override referenced responses without needing to define new references for each var |
| | | 449 | | // if (CreateResponseFromAttribute(attribute, response)) |
| | | 450 | | // { |
| | | 451 | | // SetDefaultResponseContentType(metadata.Responses, routeOptions, attribute.StatusCode); |
| | | 452 | | // Merge into existing dictionary instead of overwriting so we preserve host defaults |
| | | 453 | | // and can add multiple entries (e.g., 201 + 4XX). |
| | | 454 | | |
| | | 455 | | // Materialize keys to avoid OpenAPI collections being mutated later. |
| | | 456 | | // Also capture the schema CLR type (best-effort) to enable runtime negotiation/serialization decisions. |
| | 0 | 457 | | routeOptions.DefaultResponseContentType[attribute.StatusCode] = |
| | 0 | 458 | | [ |
| | 0 | 459 | | .. response.Content.Select(kvp => |
| | 0 | 460 | | new ContentTypeWithSchema(kvp.Key, kvp.Value.Schema!.Id)) |
| | 0 | 461 | | ]; |
| | | 462 | | //} |
| | 0 | 463 | | } |
| | | 464 | | |
| | | 465 | | /// <summary> |
| | | 466 | | /// Applies the OpenApiResponse attribute to the function's OpenAPI metadata. |
| | | 467 | | /// </summary> |
| | | 468 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 469 | | /// <param name="attribute">The OpenApiResponse attribute containing response details.</param> |
| | | 470 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 471 | | private void ApplyResponseAttribute(OpenAPIPathMetadata metadata, IOpenApiResponseAttribute attribute, MapRouteOptio |
| | | 472 | | { |
| | 1 | 473 | | metadata.Responses ??= []; |
| | | 474 | | OpenApiResponse response; |
| | 1 | 475 | | if (!metadata.Responses.TryGetValue(attribute.StatusCode, out var existing)) |
| | | 476 | | { |
| | 0 | 477 | | response = new OpenApiResponse(); |
| | 0 | 478 | | metadata.Responses.Add(attribute.StatusCode, response); |
| | | 479 | | } |
| | 1 | 480 | | else if (existing is OpenApiResponse existingResponse) |
| | | 481 | | { |
| | 0 | 482 | | response = existingResponse; |
| | | 483 | | } |
| | | 484 | | else |
| | | 485 | | { |
| | 1 | 486 | | response = new OpenApiResponse(); |
| | 1 | 487 | | metadata.Responses[attribute.StatusCode] = response; |
| | | 488 | | } |
| | | 489 | | |
| | | 490 | | // Note: if the existing response is a reference, we still apply the new response details to it. |
| | | 491 | | // This allows attributes to override referenced responses without needing to define new references for each var |
| | 1 | 492 | | if (CreateResponseFromAttribute(attribute, response)) |
| | | 493 | | { |
| | 1 | 494 | | var schema = (attribute is OpenApiResponseAttribute concreteAttr && concreteAttr.Schema is not null) ? concr |
| | 1 | 495 | | SetDefaultResponseContentType(metadata.Responses, routeOptions, attribute.StatusCode, schema); |
| | | 496 | | } |
| | 1 | 497 | | } |
| | | 498 | | |
| | | 499 | | /// <summary> |
| | | 500 | | /// Updates <see cref="MapRouteOptions.DefaultResponseContentType"/> with the response content types for the provide |
| | | 501 | | /// This enables runtime content negotiation in <c>Write-KrResponse</c> for exact codes (e.g. <c>400</c>) and OpenAP |
| | | 502 | | /// </summary> |
| | | 503 | | /// <param name="responses">The collection of OpenAPI responses to check and update.</param> |
| | | 504 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 505 | | /// <param name="newStatusCode">The status code of the new response that was just added.</param> |
| | | 506 | | /// <param name="schema">The schema type associated with the response content type.</param> |
| | | 507 | | private static void SetDefaultResponseContentType(OpenApiResponses responses, MapRouteOptions routeOptions, string n |
| | | 508 | | { |
| | 1 | 509 | | ArgumentNullException.ThrowIfNull(responses); |
| | 1 | 510 | | ArgumentNullException.ThrowIfNull(routeOptions); |
| | 1 | 511 | | if (string.IsNullOrWhiteSpace(newStatusCode)) |
| | | 512 | | { |
| | 0 | 513 | | return; |
| | | 514 | | } |
| | | 515 | | |
| | 1 | 516 | | if (!responses.TryGetValue(newStatusCode, out var newResponse)) |
| | | 517 | | { |
| | 0 | 518 | | return; |
| | | 519 | | } |
| | | 520 | | |
| | | 521 | | // Merge into existing dictionary instead of overwriting so we preserve host defaults |
| | | 522 | | // and can add multiple entries (e.g., 201 + 4XX). |
| | 1 | 523 | | routeOptions.DefaultResponseContentType ??= new Dictionary<string, ICollection<ContentTypeWithSchema>>(StringCom |
| | | 524 | | |
| | 1 | 525 | | if (newResponse.Content is null || newResponse.Content.Count == 0) |
| | | 526 | | { |
| | 0 | 527 | | routeOptions.DefaultResponseContentType[newStatusCode] = []; |
| | 0 | 528 | | return; |
| | | 529 | | } |
| | | 530 | | |
| | | 531 | | // Materialize keys to avoid OpenAPI collections being mutated later. |
| | 1 | 532 | | routeOptions.DefaultResponseContentType[newStatusCode] = |
| | 1 | 533 | | [ |
| | 1 | 534 | | .. newResponse.Content.Select(kvp => |
| | 1 | 535 | | new ContentTypeWithSchema(kvp.Key, schema)) |
| | 1 | 536 | | ]; |
| | 1 | 537 | | } |
| | | 538 | | |
| | | 539 | | /// <summary> |
| | | 540 | | /// Attempts to infer a reasonable CLR <see cref="Type"/> from an OpenAPI schema. |
| | | 541 | | /// This is best-effort only; reference/complex schemas will typically map to <see cref="object"/>. |
| | | 542 | | /// </summary> |
| | | 543 | | /// <param name="schema">The OpenAPI schema.</param> |
| | | 544 | | /// <returns>The inferred CLR type, or null when unknown.</returns> |
| | | 545 | | private static Type? TryInferClrTypeFromSchema(IOpenApiSchema? schema) |
| | | 546 | | { |
| | 0 | 547 | | if (schema is null) |
| | | 548 | | { |
| | 0 | 549 | | return null; |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | // References (components) can represent arbitrary shapes. |
| | 0 | 553 | | if (schema is OpenApiSchemaReference) |
| | | 554 | | { |
| | 0 | 555 | | return typeof(object); |
| | | 556 | | } |
| | | 557 | | |
| | 0 | 558 | | if (schema is not OpenApiSchema s) |
| | | 559 | | { |
| | 0 | 560 | | return typeof(object); |
| | | 561 | | } |
| | | 562 | | |
| | | 563 | | // Ignore nullability bit; we only capture the underlying CLR type. |
| | 0 | 564 | | var type = (s.Type ?? JsonSchemaType.Object) & ~JsonSchemaType.Null; |
| | | 565 | | |
| | 0 | 566 | | if ((type & JsonSchemaType.Array) != 0) |
| | | 567 | | { |
| | 0 | 568 | | var itemType = TryInferClrTypeFromSchema(s.Items); |
| | 0 | 569 | | return itemType is null ? typeof(object[]) : itemType.MakeArrayType(); |
| | | 570 | | } |
| | | 571 | | |
| | 0 | 572 | | return InferNonArrayClrType(s, type); |
| | | 573 | | } |
| | | 574 | | |
| | | 575 | | /// <summary> |
| | | 576 | | /// Infers a CLR type for non-array OpenAPI schema kinds. |
| | | 577 | | /// </summary> |
| | | 578 | | /// <param name="schema">The concrete OpenAPI schema.</param> |
| | | 579 | | /// <param name="type">The normalized OpenAPI schema type flags.</param> |
| | | 580 | | /// <returns>The inferred CLR type.</returns> |
| | | 581 | | private static Type InferNonArrayClrType(OpenApiSchema schema, JsonSchemaType type) |
| | | 582 | | { |
| | | 583 | | // For objects, we have no better information to go on, so we default to object. |
| | 0 | 584 | | if ((type & JsonSchemaType.Object) != 0) |
| | | 585 | | { |
| | 0 | 586 | | return typeof(object); |
| | | 587 | | } |
| | | 588 | | // For booleans, we can directly map to bool. |
| | 0 | 589 | | if ((type & JsonSchemaType.Boolean) != 0) |
| | | 590 | | { |
| | 0 | 591 | | return typeof(bool); |
| | | 592 | | } |
| | | 593 | | // For integers, we attempt to infer more specific types based on the format, but if the format is unrecognized, |
| | 0 | 594 | | if ((type & JsonSchemaType.Integer) != 0) |
| | | 595 | | { |
| | 0 | 596 | | return InferIntegerClrType(schema.Format); |
| | | 597 | | } |
| | | 598 | | // For numbers, we attempt to infer more specific types based on the format, but if the format is unrecognized, |
| | 0 | 599 | | if ((type & JsonSchemaType.Number) != 0) |
| | | 600 | | { |
| | 0 | 601 | | return InferNumberClrType(schema.Format); |
| | | 602 | | } |
| | | 603 | | // For strings, we can attempt to infer more specific types based on the format, but if the format is unrecogniz |
| | 0 | 604 | | if ((type & JsonSchemaType.String) != 0) |
| | | 605 | | { |
| | 0 | 606 | | return InferStringClrType(schema.Format); |
| | | 607 | | } |
| | | 608 | | // If we have no type or an unrecognized type, default to object. This is a best-effort inference and may not be |
| | 0 | 609 | | return (type & JsonSchemaType.Null) != 0 ? typeof(void) : typeof(object); |
| | | 610 | | } |
| | | 611 | | |
| | | 612 | | /// <summary> |
| | | 613 | | /// Infers the CLR integer type from an OpenAPI integer format. |
| | | 614 | | /// </summary> |
| | | 615 | | /// <param name="format">The OpenAPI schema format value.</param> |
| | | 616 | | /// <returns>The inferred CLR integer type.</returns> |
| | | 617 | | private static Type InferIntegerClrType(string? format) |
| | 0 | 618 | | => string.Equals(format, "int64", StringComparison.OrdinalIgnoreCase) ? typeof(long) : typeof(int); |
| | | 619 | | |
| | | 620 | | /// <summary> |
| | | 621 | | /// Infers the CLR numeric type from an OpenAPI number format. |
| | | 622 | | /// </summary> |
| | | 623 | | /// <param name="format">The OpenAPI schema format value.</param> |
| | | 624 | | /// <returns>The inferred CLR number type.</returns> |
| | | 625 | | private static Type InferNumberClrType(string? format) |
| | 0 | 626 | | => string.Equals(format, "float", StringComparison.OrdinalIgnoreCase) ? typeof(float) : typeof(double); |
| | | 627 | | |
| | | 628 | | /// <summary> |
| | | 629 | | /// Infers the CLR string-like type from an OpenAPI string format. |
| | | 630 | | /// </summary> |
| | | 631 | | /// <param name="format">The OpenAPI schema format value.</param> |
| | | 632 | | /// <returns>The inferred CLR type for the string format.</returns> |
| | | 633 | | private static Type InferStringClrType(string? format) |
| | 0 | 634 | | => format?.ToLowerInvariant() switch |
| | 0 | 635 | | { |
| | 0 | 636 | | "binary" => typeof(byte[]), |
| | 0 | 637 | | "uuid" => typeof(Guid), |
| | 0 | 638 | | "uri" => typeof(Uri), |
| | 0 | 639 | | "duration" => typeof(TimeSpan), |
| | 0 | 640 | | "date-time" => typeof(DateTimeOffset), |
| | 0 | 641 | | _ => typeof(string) |
| | 0 | 642 | | }; |
| | | 643 | | |
| | | 644 | | /// <summary> |
| | | 645 | | /// Selects the default success response (2xx) from the given OpenApiResponses. |
| | | 646 | | /// </summary> |
| | | 647 | | /// <param name="responses">The collection of OpenApiResponses to select from.</param> |
| | | 648 | | /// <returns>The status code of the default success response, or null if none found.</returns> |
| | | 649 | | private static string? SelectDefaultSuccessResponse(OpenApiResponses responses) |
| | | 650 | | { |
| | 0 | 651 | | return responses |
| | 0 | 652 | | .Select(kvp => new |
| | 0 | 653 | | { |
| | 0 | 654 | | StatusCode = kvp.Key, |
| | 0 | 655 | | Code = TryParseStatusCode(kvp.Key), |
| | 0 | 656 | | Response = kvp.Value |
| | 0 | 657 | | }) |
| | 0 | 658 | | .Where(x => |
| | 0 | 659 | | x.Code is >= 200 and < 300 && |
| | 0 | 660 | | HasContent(x.Response)) |
| | 0 | 661 | | .OrderBy(x => x.Code) |
| | 0 | 662 | | .Select(x => x.StatusCode) |
| | 0 | 663 | | .FirstOrDefault(); |
| | | 664 | | } |
| | | 665 | | |
| | | 666 | | /// <summary> |
| | | 667 | | /// Tries to parse the given status code string into an integer. |
| | | 668 | | /// </summary> |
| | | 669 | | /// <param name="statusCode">The status code as a string.</param> |
| | | 670 | | /// <returns>The parsed integer status code, or -1 if parsing fails.</returns> |
| | | 671 | | private static int TryParseStatusCode(string statusCode) |
| | 0 | 672 | | => int.TryParse(statusCode, out var code) ? code : -1; |
| | | 673 | | |
| | | 674 | | /// <summary> |
| | | 675 | | /// Determines if the given response has content defined. |
| | | 676 | | /// </summary> |
| | | 677 | | /// <param name="response">The OpenAPI response to check for content.</param> |
| | | 678 | | /// <returns>True if the response has content; otherwise, false.</returns> |
| | | 679 | | private static bool HasContent(IOpenApiResponse response) |
| | | 680 | | { |
| | | 681 | | // If your concrete type is OpenApiResponse (common), this is the easiest path: |
| | 0 | 682 | | if (response is OpenApiResponse r) |
| | | 683 | | { |
| | 0 | 684 | | return r.Content is not null && r.Content.Count > 0; |
| | | 685 | | } |
| | | 686 | | |
| | | 687 | | // Otherwise, we can't reliably know. Be conservative: |
| | 0 | 688 | | return false; |
| | | 689 | | } |
| | | 690 | | |
| | | 691 | | /// <summary> |
| | | 692 | | /// Applies the OpenApiProperty attribute to the function's OpenAPI metadata. |
| | | 693 | | /// </summary> |
| | | 694 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 695 | | /// <param name="attribute">The OpenApiProperty attribute containing property details.</param> |
| | | 696 | | /// <exception cref="InvalidOperationException"></exception> |
| | | 697 | | private void ApplyPropertyAttribute(OpenAPIPathMetadata metadata, OpenApiPropertyAttribute attribute) |
| | | 698 | | { |
| | 0 | 699 | | if (attribute.StatusCode is null) |
| | | 700 | | { |
| | 0 | 701 | | return; |
| | | 702 | | } |
| | | 703 | | |
| | 0 | 704 | | if (metadata.Responses is null || !metadata.Responses.TryGetValue(attribute.StatusCode, out var res)) |
| | | 705 | | { |
| | 0 | 706 | | throw new InvalidOperationException($"Response for status code '{attribute.StatusCode}' is not defined for t |
| | | 707 | | } |
| | | 708 | | // Note: if the existing response is a reference, we still apply the new response details to it. This allows att |
| | 0 | 709 | | if (res is OpenApiResponseReference) |
| | | 710 | | { |
| | 0 | 711 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute.StatusCo |
| | | 712 | | } |
| | | 713 | | // We have to be able to modify the response content to apply the property attribute, so we require a concrete O |
| | 0 | 714 | | if (res is OpenApiResponse response) |
| | | 715 | | { |
| | 0 | 716 | | if (response.Content is null || response.Content.Count == 0) |
| | | 717 | | { |
| | 0 | 718 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute.Stat |
| | | 719 | | } |
| | | 720 | | |
| | 0 | 721 | | foreach (var content in response.Content.Values) |
| | | 722 | | { |
| | 0 | 723 | | if (content.Schema is null) |
| | | 724 | | { |
| | 0 | 725 | | throw new InvalidOperationException($"Cannot apply OpenApiPropertyAttribute to response '{attribute. |
| | | 726 | | } |
| | | 727 | | |
| | 0 | 728 | | ApplySchemaAttr(attribute, content.Schema); |
| | | 729 | | } |
| | | 730 | | } |
| | 0 | 731 | | } |
| | | 732 | | |
| | | 733 | | private void ApplyAuthorizationAttribute(MapRouteOptions routeOptions, OpenAPIPathMetadata metadata, OpenApiAuthoriz |
| | | 734 | | { |
| | 0 | 735 | | metadata.SecuritySchemes ??= []; |
| | 0 | 736 | | var policyList = BuildPolicyList(attribute.Policies); |
| | 0 | 737 | | var securitySchemeList = Host.AddSecurityRequirementObject(attribute.Scheme, policyList, metadata.SecurityScheme |
| | 0 | 738 | | routeOptions.AddSecurityRequirementObject(schemes: securitySchemeList, policies: policyList); |
| | 0 | 739 | | } |
| | | 740 | | |
| | | 741 | | private static List<string> BuildPolicyList(string? policies) |
| | | 742 | | { |
| | 0 | 743 | | return [.. (string.IsNullOrWhiteSpace(policies) ? new List<string>() : [.. policies.Split(',')]) |
| | 0 | 744 | | .Where(p => !string.IsNullOrWhiteSpace(p)) |
| | 0 | 745 | | .Select(p => p.Trim())]; |
| | | 746 | | } |
| | | 747 | | |
| | | 748 | | /// <summary> |
| | | 749 | | /// Processes the parameters of the specified function, applying OpenAPI annotations as needed. |
| | | 750 | | /// </summary> |
| | | 751 | | /// <param name="func">The function information.</param> |
| | | 752 | | /// <param name="help">The comment help information.</param> |
| | | 753 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 754 | | /// <param name="openApiMetadata">The OpenAPI metadata to update.</param> |
| | | 755 | | /// <exception cref="InvalidOperationException">Thrown when an invalid operation occurs during parameter processing. |
| | | 756 | | private void ProcessParameters( |
| | | 757 | | FunctionInfo func, |
| | | 758 | | CommentHelpInfo help, |
| | | 759 | | MapRouteOptions routeOptions, |
| | | 760 | | OpenAPIPathMetadata openApiMetadata) |
| | | 761 | | { |
| | 0 | 762 | | foreach (var paramInfo in func.Parameters.Values) |
| | | 763 | | { |
| | | 764 | | // First pass for parameter and request body attributes |
| | 0 | 765 | | foreach (var attribute in paramInfo.Attributes) |
| | | 766 | | { |
| | | 767 | | switch (attribute) |
| | | 768 | | { |
| | | 769 | | case OpenApiParameterAttribute paramAttr: |
| | 0 | 770 | | ApplyParameterAttribute(func, help, routeOptions, openApiMetadata, paramInfo, paramAttr); |
| | 0 | 771 | | break; |
| | | 772 | | case OpenApiParameterRefAttribute paramRefAttr: |
| | 0 | 773 | | ApplyParameterRefAttribute(help, routeOptions, openApiMetadata, paramInfo, paramRefAttr); |
| | 0 | 774 | | break; |
| | | 775 | | case OpenApiRequestBodyRefAttribute requestBodyRefAttr: |
| | 0 | 776 | | ApplyRequestBodyRefAttribute(help, routeOptions, openApiMetadata, paramInfo, requestBodyRefAttr) |
| | 0 | 777 | | break; |
| | | 778 | | case OpenApiRequestBodyAttribute requestBodyAttr: |
| | 0 | 779 | | ApplyRequestBodyAttribute(help, routeOptions, openApiMetadata, paramInfo, requestBodyAttr); |
| | 0 | 780 | | break; |
| | | 781 | | case OpenApiRequestBodyExampleRefAttribute: |
| | | 782 | | case OpenApiParameterExampleRefAttribute: |
| | | 783 | | // Do nothing here; handled later |
| | | 784 | | break; |
| | | 785 | | case KestrunAnnotation ka: |
| | 0 | 786 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 787 | | } |
| | | 788 | | } |
| | | 789 | | // Second pass for example references |
| | 0 | 790 | | foreach (var attribute in paramInfo.Attributes) |
| | | 791 | | { |
| | | 792 | | switch (attribute) |
| | | 793 | | { |
| | | 794 | | case OpenApiParameterAttribute: |
| | | 795 | | case OpenApiParameterRefAttribute: |
| | | 796 | | case OpenApiRequestBodyRefAttribute: |
| | | 797 | | case OpenApiRequestBodyAttribute: |
| | | 798 | | // Already handled |
| | | 799 | | break; |
| | | 800 | | case OpenApiRequestBodyExampleRefAttribute requestBodyExampleRefAttr: |
| | 0 | 801 | | ApplyRequestBodyExampleRefAttribute(openApiMetadata, requestBodyExampleRefAttr); |
| | 0 | 802 | | break; |
| | | 803 | | case OpenApiParameterExampleRefAttribute parameterExampleRefAttr: |
| | 0 | 804 | | ApplyParameterExampleRefAttribute(openApiMetadata, paramInfo, parameterExampleRefAttr); |
| | 0 | 805 | | break; |
| | | 806 | | case KestrunAnnotation ka: |
| | 0 | 807 | | throw new InvalidOperationException($"Unhandled Kestrun annotation: {ka.GetType().Name}"); |
| | | 808 | | } |
| | | 809 | | } |
| | | 810 | | } |
| | 0 | 811 | | } |
| | | 812 | | |
| | | 813 | | #region Parameter Handlers |
| | | 814 | | /// <summary> |
| | | 815 | | /// Applies the OpenApiParameter attribute to the function's OpenAPI metadata. |
| | | 816 | | /// </summary> |
| | | 817 | | /// <param name="func">The function information.</param> |
| | | 818 | | /// <param name="help">The comment help information.</param> |
| | | 819 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 820 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 821 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 822 | | /// <param name="attribute">The OpenApiParameter attribute containing parameter details.</param> |
| | | 823 | | private void ApplyParameterAttribute( |
| | | 824 | | FunctionInfo func, |
| | | 825 | | CommentHelpInfo help, |
| | | 826 | | MapRouteOptions routeOptions, |
| | | 827 | | OpenAPIPathMetadata metadata, |
| | | 828 | | ParameterMetadata paramInfo, |
| | | 829 | | OpenApiParameterAttribute attribute) |
| | | 830 | | { |
| | 0 | 831 | | metadata.Parameters ??= []; |
| | 0 | 832 | | var parameter = new OpenApiParameter(); |
| | 0 | 833 | | if (!CreateParameterFromAttribute(attribute, parameter)) |
| | | 834 | | { |
| | 0 | 835 | | Host.Logger.Error("Error processing OpenApiParameter attribute on parameter '{paramName}' of function '{func |
| | 0 | 836 | | return; |
| | | 837 | | } |
| | | 838 | | |
| | 0 | 839 | | if (!string.IsNullOrEmpty(parameter.Name) && parameter.Name != paramInfo.Name) |
| | | 840 | | { |
| | 0 | 841 | | throw new InvalidOperationException($"Parameter name {parameter.Name} is different from variable name: '{par |
| | | 842 | | } |
| | | 843 | | |
| | 0 | 844 | | parameter.Name = paramInfo.Name; |
| | 0 | 845 | | parameter.Schema = InferPrimitiveSchema(paramInfo.ParameterType); |
| | | 846 | | |
| | 0 | 847 | | if (parameter.Schema is OpenApiSchema schema) |
| | | 848 | | { |
| | 0 | 849 | | var defaultValue = func.GetDefaultParameterValue(paramInfo.Name); |
| | 0 | 850 | | if (defaultValue is not null) |
| | | 851 | | { |
| | 0 | 852 | | schema.Default = OpenApiJsonNodeFactory.ToNode(defaultValue); |
| | | 853 | | } |
| | | 854 | | } |
| | | 855 | | |
| | 0 | 856 | | parameter.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 857 | | |
| | 0 | 858 | | foreach (var attr in paramInfo.Attributes.OfType<CmdletMetadataAttribute>()) |
| | | 859 | | { |
| | 0 | 860 | | PowerShellAttributes.ApplyPowerShellAttribute(attr, (OpenApiSchema)parameter.Schema); |
| | | 861 | | } |
| | | 862 | | |
| | 0 | 863 | | RemoveExistingParameter(metadata, paramInfo.Name); |
| | 0 | 864 | | metadata.Parameters.Add(parameter); |
| | 0 | 865 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, parameter)); |
| | 0 | 866 | | } |
| | | 867 | | |
| | | 868 | | /// <summary> |
| | | 869 | | /// Applies the OpenApiParameterRef attribute to the function's OpenAPI metadata. |
| | | 870 | | /// </summary> |
| | | 871 | | /// <param name="help">The comment help information.</param> |
| | | 872 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 873 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 874 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 875 | | /// <param name="attribute">The OpenApiParameterRef attribute containing parameter reference details.</param> |
| | | 876 | | /// <exception cref="InvalidOperationException">If the parameter name does not match the reference name when inlinin |
| | | 877 | | private void ApplyParameterRefAttribute( |
| | | 878 | | CommentHelpInfo help, |
| | | 879 | | MapRouteOptions routeOptions, |
| | | 880 | | OpenAPIPathMetadata metadata, |
| | | 881 | | ParameterMetadata paramInfo, |
| | | 882 | | OpenApiParameterRefAttribute attribute) |
| | | 883 | | { |
| | 0 | 884 | | metadata.Parameters ??= []; |
| | 0 | 885 | | routeOptions.ScriptCode.Parameters ??= []; |
| | | 886 | | |
| | 0 | 887 | | if (!TryGetParameterItem(attribute.ReferenceId, out var componentParameter, out var isInline) || |
| | 0 | 888 | | componentParameter is null) |
| | | 889 | | { |
| | 0 | 890 | | throw new InvalidOperationException($"Parameter component with ID '{attribute.ReferenceId}' not found."); |
| | | 891 | | } |
| | | 892 | | IOpenApiParameter parameter; |
| | | 893 | | |
| | 0 | 894 | | if (attribute.Inline || isInline) |
| | | 895 | | { |
| | 0 | 896 | | parameter = componentParameter.Clone(); |
| | 0 | 897 | | if (componentParameter.Name != paramInfo.Name) |
| | | 898 | | { |
| | 0 | 899 | | throw new InvalidOperationException($"Parameter name {componentParameter.Name} is different from variabl |
| | | 900 | | } |
| | | 901 | | |
| | 0 | 902 | | parameter.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 903 | | } |
| | | 904 | | else |
| | | 905 | | { |
| | 0 | 906 | | parameter = new OpenApiParameterReference(attribute.ReferenceId); |
| | | 907 | | } |
| | | 908 | | |
| | 0 | 909 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentParameter)); |
| | 0 | 910 | | RemoveExistingParameter(metadata, paramInfo.Name); |
| | 0 | 911 | | metadata.Parameters.Add(parameter); |
| | 0 | 912 | | } |
| | | 913 | | |
| | | 914 | | private void ApplyParameterExampleRefAttribute( |
| | | 915 | | OpenAPIPathMetadata metadata, |
| | | 916 | | ParameterMetadata paramInfo, |
| | | 917 | | OpenApiParameterExampleRefAttribute attribute) |
| | | 918 | | { |
| | 0 | 919 | | var parameters = metadata.Parameters |
| | 0 | 920 | | ?? throw new InvalidOperationException( |
| | 0 | 921 | | "OpenApiParameterExampleRefAttribute must follow OpenApiParameterAttribute or OpenApiParameterRefAttribute." |
| | | 922 | | |
| | 0 | 923 | | var parameter = parameters.FirstOrDefault(p => p.Name == paramInfo.Name) |
| | 0 | 924 | | ?? throw new InvalidOperationException( |
| | 0 | 925 | | $"OpenApiParameterExampleRefAttribute requires the parameter '{paramInfo.Name}' to be defined."); |
| | 0 | 926 | | if (parameter is OpenApiParameterReference) |
| | | 927 | | { |
| | 0 | 928 | | throw new InvalidOperationException( |
| | 0 | 929 | | "Cannot apply OpenApiParameterExampleRefAttribute to a parameter reference."); |
| | | 930 | | } |
| | 0 | 931 | | if (parameter is OpenApiParameter opp) |
| | | 932 | | { |
| | 0 | 933 | | opp.Examples ??= new Dictionary<string, IOpenApiExample>(); |
| | | 934 | | // Clone or reference the example |
| | 0 | 935 | | _ = TryAddExample(opp.Examples, attribute); |
| | | 936 | | } |
| | 0 | 937 | | } |
| | | 938 | | |
| | | 939 | | /// <summary> |
| | | 940 | | /// Removes any existing parameter with the specified name from the OpenAPI metadata. |
| | | 941 | | /// </summary> |
| | | 942 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 943 | | /// <param name="name">The parameter name to remove.</param> |
| | | 944 | | private static void RemoveExistingParameter(OpenAPIPathMetadata metadata, string name) |
| | | 945 | | { |
| | 0 | 946 | | if (metadata.Parameters is null) |
| | | 947 | | { |
| | 0 | 948 | | return; |
| | | 949 | | } |
| | | 950 | | |
| | 0 | 951 | | for (var i = metadata.Parameters.Count - 1; i >= 0; i--) |
| | | 952 | | { |
| | 0 | 953 | | if (string.Equals(metadata.Parameters[i].Name, name, StringComparison.OrdinalIgnoreCase)) |
| | | 954 | | { |
| | 0 | 955 | | metadata.Parameters.RemoveAt(i); |
| | | 956 | | } |
| | | 957 | | } |
| | 0 | 958 | | } |
| | | 959 | | |
| | | 960 | | #endregion |
| | | 961 | | #region Request Body Handlers |
| | | 962 | | /// <summary> |
| | | 963 | | /// Applies the OpenApiRequestBodyRef attribute to the function's OpenAPI metadata. |
| | | 964 | | /// </summary> |
| | | 965 | | /// <param name="help">The comment help information.</param> |
| | | 966 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 967 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 968 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 969 | | /// <param name="attribute">The OpenApiRequestBodyRef attribute containing request body reference details.</param> |
| | | 970 | | private void ApplyRequestBodyRefAttribute( |
| | | 971 | | CommentHelpInfo help, |
| | | 972 | | MapRouteOptions routeOptions, |
| | | 973 | | OpenAPIPathMetadata metadata, |
| | | 974 | | ParameterMetadata paramInfo, |
| | | 975 | | OpenApiRequestBodyRefAttribute attribute) |
| | | 976 | | { |
| | 0 | 977 | | var referenceId = ResolveRequestBodyReferenceId(attribute, paramInfo); |
| | 0 | 978 | | var componentRequestBody = GetRequestBody(referenceId); |
| | | 979 | | |
| | 0 | 980 | | metadata.RequestBody = attribute.Inline ? componentRequestBody.Clone() : new OpenApiRequestBodyReference(referen |
| | 0 | 981 | | metadata.RequestBody.Description = attribute.Description ?? help.GetParameterDescription(paramInfo.Name); |
| | | 982 | | |
| | 0 | 983 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentRequestBody, routeOptio |
| | 0 | 984 | | } |
| | | 985 | | |
| | | 986 | | /// <summary> |
| | | 987 | | /// Resolves the reference ID for the OpenApiRequestBodyRef attribute. |
| | | 988 | | /// </summary> |
| | | 989 | | /// <param name="attribute">The OpenApiRequestBodyRef attribute.</param> |
| | | 990 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 991 | | /// <returns>The resolved reference ID.</returns> |
| | | 992 | | /// <exception cref="InvalidOperationException"> |
| | | 993 | | /// Thrown when the ReferenceId is not specified and the parameter type is 'object', |
| | | 994 | | /// or when the ReferenceId does not match the parameter type name. |
| | | 995 | | /// </exception> |
| | | 996 | | private string ResolveRequestBodyReferenceId(OpenApiRequestBodyRefAttribute attribute, ParameterMetadata paramInfo) |
| | | 997 | | { |
| | 0 | 998 | | if (string.IsNullOrWhiteSpace(attribute.ReferenceId)) |
| | | 999 | | { |
| | 0 | 1000 | | if (paramInfo.ParameterType.Name is "Object" or null) |
| | | 1001 | | { |
| | 0 | 1002 | | throw new InvalidOperationException("OpenApiRequestBodyRefAttribute must have a ReferenceId specified wh |
| | | 1003 | | } |
| | | 1004 | | |
| | 0 | 1005 | | attribute.ReferenceId = paramInfo.ParameterType.Name; |
| | | 1006 | | } |
| | 0 | 1007 | | else if (paramInfo.ParameterType.Name != "Object" && attribute.ReferenceId != paramInfo.ParameterType.Name) |
| | | 1008 | | { |
| | 0 | 1009 | | return FindReferenceIdForParameter(attribute.ReferenceId, paramInfo); |
| | | 1010 | | } |
| | | 1011 | | // Return the reference ID as is |
| | 0 | 1012 | | return attribute.ReferenceId; |
| | | 1013 | | } |
| | | 1014 | | |
| | | 1015 | | /// <summary> |
| | | 1016 | | /// Finds and validates the reference ID for a request body parameter. |
| | | 1017 | | /// </summary> |
| | | 1018 | | /// <param name="referenceId">The reference ID to validate.</param> |
| | | 1019 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 1020 | | /// <returns>The validated reference ID.</returns> |
| | | 1021 | | /// <exception cref="InvalidOperationException">Thrown when the reference ID does not match the parameter type name. |
| | | 1022 | | private string FindReferenceIdForParameter(string referenceId, ParameterMetadata paramInfo) |
| | | 1023 | | { |
| | | 1024 | | // Ensure the reference ID exists and has a schema |
| | 0 | 1025 | | if (!TryGetFirstRequestBodySchema(referenceId, out var schema)) |
| | | 1026 | | { |
| | 0 | 1027 | | throw new InvalidOperationException( |
| | 0 | 1028 | | $"Request body component with ReferenceId '{referenceId}' was not found or does not define a schema."); |
| | | 1029 | | } |
| | | 1030 | | // Validate that the schema matches the parameter type |
| | 0 | 1031 | | if (!IsRequestBodySchemaMatchForParameter(schema, paramInfo.ParameterType)) |
| | | 1032 | | { |
| | 0 | 1033 | | throw new InvalidOperationException( |
| | 0 | 1034 | | $"Schema for request body component '{referenceId}' does not match parameter type '{paramInfo.ParameterT |
| | | 1035 | | } |
| | | 1036 | | // return the validated reference ID |
| | 0 | 1037 | | return referenceId; |
| | | 1038 | | } |
| | | 1039 | | |
| | | 1040 | | /// <summary> |
| | | 1041 | | /// Attempts to retrieve the first schema defined on a request body component. |
| | | 1042 | | /// </summary> |
| | | 1043 | | /// <param name="referenceId">The request body component reference ID.</param> |
| | | 1044 | | /// <param name="schema">The extracted schema when available.</param> |
| | | 1045 | | /// <returns><see langword="true"/> if a non-null schema is found; otherwise <see langword="false"/>.</returns> |
| | | 1046 | | private bool TryGetFirstRequestBodySchema(string referenceId, out IOpenApiSchema schema) |
| | | 1047 | | { |
| | 0 | 1048 | | schema = null!; |
| | | 1049 | | |
| | 0 | 1050 | | if (!TryGetRequestBodyItem(referenceId, out var requestBody, out _)) |
| | | 1051 | | { |
| | 0 | 1052 | | return false; |
| | | 1053 | | } |
| | | 1054 | | |
| | 0 | 1055 | | if (requestBody?.Content is null || requestBody.Content.Count == 0) |
| | | 1056 | | { |
| | 0 | 1057 | | return false; |
| | | 1058 | | } |
| | | 1059 | | |
| | 0 | 1060 | | schema = requestBody.Content.First().Value.Schema!; |
| | 0 | 1061 | | return schema is not null; |
| | | 1062 | | } |
| | | 1063 | | |
| | | 1064 | | /// <summary> |
| | | 1065 | | /// Determines whether a request-body schema matches a given CLR parameter type. |
| | | 1066 | | /// </summary> |
| | | 1067 | | /// <param name="schema">The schema declared for the request body.</param> |
| | | 1068 | | /// <param name="parameterType">The CLR parameter type being validated.</param> |
| | | 1069 | | /// <returns><see langword="true"/> if the schema matches the parameter type; otherwise <see langword="false"/>.</re |
| | | 1070 | | private static bool IsRequestBodySchemaMatchForParameter(IOpenApiSchema schema, Type parameterType) |
| | | 1071 | | { |
| | 0 | 1072 | | if (schema is OpenApiSchemaReference schemaRef) |
| | | 1073 | | { |
| | 0 | 1074 | | return schemaRef.Reference.Id == parameterType.Name; |
| | | 1075 | | } |
| | | 1076 | | |
| | 0 | 1077 | | if (schema is OpenApiSchema inlineSchema && PrimitiveSchemaMap.TryGetValue(parameterType, out var valueType)) |
| | | 1078 | | { |
| | 0 | 1079 | | var expected = valueType(); |
| | 0 | 1080 | | return inlineSchema.Format == expected.Format && inlineSchema.Type == expected.Type; |
| | | 1081 | | } |
| | | 1082 | | |
| | 0 | 1083 | | return false; |
| | | 1084 | | } |
| | | 1085 | | |
| | | 1086 | | /// <summary> |
| | | 1087 | | /// Applies the OpenApiRequestBody attribute to the function's OpenAPI metadata. |
| | | 1088 | | /// </summary> |
| | | 1089 | | /// <param name="help">The comment help information.</param> |
| | | 1090 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1091 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 1092 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 1093 | | /// <param name="attribute">The OpenApiRequestBody attribute containing request body details.</param> |
| | | 1094 | | private void ApplyRequestBodyAttribute( |
| | | 1095 | | CommentHelpInfo help, |
| | | 1096 | | MapRouteOptions routeOptions, |
| | | 1097 | | OpenAPIPathMetadata metadata, |
| | | 1098 | | ParameterMetadata paramInfo, |
| | | 1099 | | OpenApiRequestBodyAttribute attribute) |
| | | 1100 | | { |
| | 0 | 1101 | | ResolveFormOptions(routeOptions, paramInfo); |
| | | 1102 | | |
| | | 1103 | | // Special handling for form payloads |
| | 0 | 1104 | | if (routeOptions.FormOptions is not null) |
| | | 1105 | | // && (paramInfo.ParameterType == typeof(KrFormData) || paramInfo.ParameterType == typeof(KrFormPayload))) |
| | | 1106 | | { |
| | 0 | 1107 | | ApplyFormRequestBody(help, routeOptions, metadata, paramInfo, attribute); |
| | 0 | 1108 | | return; |
| | | 1109 | | } |
| | | 1110 | | // Check for preferred request body in components |
| | 0 | 1111 | | var requestBodyPreferred = ComponentRequestBodiesExists(paramInfo.ParameterType.Name); |
| | 0 | 1112 | | if (requestBodyPreferred) |
| | | 1113 | | { |
| | 0 | 1114 | | ApplyPreferredRequestBody(help, routeOptions, metadata, paramInfo, attribute); |
| | 0 | 1115 | | return; |
| | | 1116 | | } |
| | | 1117 | | |
| | 0 | 1118 | | var requestBody = new OpenApiRequestBody(); |
| | 0 | 1119 | | var schema = InferPrimitiveSchema(type: paramInfo.ParameterType, inline: attribute.Inline); |
| | | 1120 | | |
| | 0 | 1121 | | if (!CreateRequestBodyFromAttribute(attribute, requestBody, schema)) |
| | | 1122 | | { |
| | 0 | 1123 | | return; |
| | | 1124 | | } |
| | | 1125 | | |
| | 0 | 1126 | | metadata.RequestBody = requestBody; |
| | 0 | 1127 | | metadata.RequestBody.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 1128 | | |
| | 0 | 1129 | | if (routeOptions.FormOptions is not null && requestBody.Content?.Keys.Count > 0) |
| | | 1130 | | { |
| | 0 | 1131 | | routeOptions.FormOptions.AllowedContentTypes.Clear(); |
| | 0 | 1132 | | routeOptions.FormOptions.AllowedContentTypes.AddRange(requestBody.Content?.Keys ?? []); |
| | | 1133 | | } |
| | | 1134 | | // If the request body defines content types, use them as allowed content types for the route and form options |
| | 0 | 1135 | | routeOptions.AllowedRequestContentTypes.Clear(); |
| | 0 | 1136 | | routeOptions.AllowedRequestContentTypes.AddRange(requestBody.Content?.Keys ?? []); |
| | | 1137 | | |
| | | 1138 | | // Add the parameter for injection |
| | 0 | 1139 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, requestBody, routeOptions.FormOp |
| | 0 | 1140 | | } |
| | | 1141 | | |
| | | 1142 | | /// <summary> |
| | | 1143 | | /// Resolves form options for the request body parameter when form binding is configured. |
| | | 1144 | | /// </summary> |
| | | 1145 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1146 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 1147 | | private void ResolveFormOptions(MapRouteOptions routeOptions, ParameterMetadata paramInfo) |
| | | 1148 | | { |
| | 0 | 1149 | | if (routeOptions.FormOptions is not null) |
| | | 1150 | | { |
| | 0 | 1151 | | return; |
| | | 1152 | | } |
| | | 1153 | | |
| | 0 | 1154 | | if (Host.Runtime.FormOptions.TryGetValue(paramInfo.ParameterType.Name, out var formOptionsValue)) |
| | | 1155 | | { |
| | 0 | 1156 | | routeOptions.FormOptions = new KrFormOptions(formOptionsValue); |
| | 0 | 1157 | | return; |
| | | 1158 | | } |
| | | 1159 | | |
| | 0 | 1160 | | var formAttr = paramInfo.ParameterType.GetCustomAttribute<KrBindFormAttribute>(inherit: true); |
| | 0 | 1161 | | if (formAttr is null) |
| | | 1162 | | { |
| | 0 | 1163 | | return; |
| | | 1164 | | } |
| | | 1165 | | |
| | 0 | 1166 | | var formOptions = FormHelper.ApplyKrPartAttributes(formAttr); |
| | 0 | 1167 | | formOptions.Name = paramInfo.ParameterType.FullName ?? paramInfo.ParameterType.Name; |
| | | 1168 | | |
| | 0 | 1169 | | var rules = FormHelper.BuildFormPartRulesFromType(paramInfo.ParameterType); |
| | 0 | 1170 | | AddFormPartRules(formOptions, rules); |
| | | 1171 | | |
| | 0 | 1172 | | routeOptions.FormOptions = formOptions; |
| | 0 | 1173 | | } |
| | | 1174 | | |
| | | 1175 | | /// <summary> |
| | | 1176 | | /// Applies request body metadata for form payload parameters. |
| | | 1177 | | /// </summary> |
| | | 1178 | | /// <param name="help">The comment help information.</param> |
| | | 1179 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1180 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 1181 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 1182 | | /// <param name="attribute">The OpenApiRequestBody attribute containing request body details.</param> |
| | | 1183 | | private void ApplyFormRequestBody( |
| | | 1184 | | CommentHelpInfo help, |
| | | 1185 | | MapRouteOptions routeOptions, |
| | | 1186 | | OpenAPIPathMetadata metadata, |
| | | 1187 | | ParameterMetadata paramInfo, |
| | | 1188 | | OpenApiRequestBodyAttribute attribute) |
| | | 1189 | | { |
| | 0 | 1190 | | var contentTypes = ResolveFormContentTypes(attribute, routeOptions.FormOptions!); |
| | 0 | 1191 | | routeOptions.FormOptions!.AllowedContentTypes.Clear(); |
| | 0 | 1192 | | routeOptions.FormOptions.AllowedContentTypes.AddRange(contentTypes); |
| | | 1193 | | |
| | 0 | 1194 | | var formSchema = InferPrimitiveSchema(type: paramInfo.ParameterType, inline: attribute.Inline); |
| | 0 | 1195 | | var requestBodyContent = BuildFormRequestBodyWithSchema(formSchema, contentTypes, routeOptions.FormOptions, attr |
| | 0 | 1196 | | metadata.RequestBody = requestBodyContent; |
| | 0 | 1197 | | metadata.RequestBody.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | | 1198 | | // Add the parameter for injection |
| | 0 | 1199 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, requestBodyContent, routeOptions |
| | 0 | 1200 | | } |
| | | 1201 | | |
| | | 1202 | | /// <summary> |
| | | 1203 | | /// Applies the OpenApiRequestBodyExampleRef attribute to the function's OpenAPI metadata. |
| | | 1204 | | /// </summary> |
| | | 1205 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 1206 | | /// <param name="attribute">The OpenApiRequestBodyExampleRef attribute containing example reference details.</param> |
| | | 1207 | | /// <exception cref="InvalidOperationException">Thrown when the request body or its content is not properly defined. |
| | | 1208 | | private void ApplyRequestBodyExampleRefAttribute( |
| | | 1209 | | OpenAPIPathMetadata metadata, |
| | | 1210 | | OpenApiRequestBodyExampleRefAttribute attribute) |
| | | 1211 | | { |
| | 0 | 1212 | | var requestBody = metadata.RequestBody |
| | 0 | 1213 | | ?? throw new InvalidOperationException( |
| | 0 | 1214 | | "OpenApiRequestBodyExampleRefAttribute must follow OpenApiRequestBodyAttribute or OpenApiRequestBodyRefAttri |
| | | 1215 | | |
| | 0 | 1216 | | if (requestBody.Content is null) |
| | | 1217 | | { |
| | 0 | 1218 | | throw new InvalidOperationException( |
| | 0 | 1219 | | "OpenApiRequestBodyExampleRefAttribute requires the request body to have content defined."); |
| | | 1220 | | } |
| | | 1221 | | |
| | 0 | 1222 | | foreach (var oamt in requestBody.Content.Values.OfType<OpenApiMediaType>()) |
| | | 1223 | | { |
| | 0 | 1224 | | oamt.Examples ??= new Dictionary<string, IOpenApiExample>(); |
| | 0 | 1225 | | _ = TryAddExample(oamt.Examples, attribute); |
| | | 1226 | | } |
| | 0 | 1227 | | } |
| | | 1228 | | |
| | | 1229 | | private static OpenApiRequestBody BuildFormRequestBodyWithSchema( |
| | | 1230 | | IOpenApiSchema schema, |
| | | 1231 | | string[] contentTypes, |
| | | 1232 | | KrFormOptions options, |
| | | 1233 | | OpenApiRequestBodyAttribute attribute) |
| | | 1234 | | { |
| | 0 | 1235 | | var requestBody = new OpenApiRequestBody |
| | 0 | 1236 | | { |
| | 0 | 1237 | | Description = attribute.Description, |
| | 0 | 1238 | | Required = attribute.Required, |
| | 0 | 1239 | | Content = new Dictionary<string, IOpenApiMediaType>(StringComparer.OrdinalIgnoreCase) |
| | 0 | 1240 | | }; |
| | | 1241 | | |
| | 0 | 1242 | | var encoding = BuildMultipartEncoding(options); |
| | | 1243 | | |
| | 0 | 1244 | | foreach (var contentType in contentTypes) |
| | | 1245 | | { |
| | 0 | 1246 | | if (string.IsNullOrWhiteSpace(contentType)) |
| | | 1247 | | { |
| | | 1248 | | continue; |
| | | 1249 | | } |
| | | 1250 | | |
| | 0 | 1251 | | var mediaType = new OpenApiMediaType |
| | 0 | 1252 | | { |
| | 0 | 1253 | | Schema = schema |
| | 0 | 1254 | | }; |
| | | 1255 | | |
| | 0 | 1256 | | if (IsMultipartContentType(contentType) && encoding is not null) |
| | | 1257 | | { |
| | 0 | 1258 | | mediaType.Encoding = encoding; |
| | | 1259 | | } |
| | | 1260 | | |
| | 0 | 1261 | | requestBody.Content[contentType] = mediaType; |
| | | 1262 | | } |
| | | 1263 | | |
| | 0 | 1264 | | return requestBody; |
| | | 1265 | | } |
| | | 1266 | | |
| | | 1267 | | /// <summary> |
| | | 1268 | | /// Resolves the content types for a form request body based on the attribute and form options. |
| | | 1269 | | /// </summary> |
| | | 1270 | | /// <param name="attribute">The OpenApiRequestBodyAttribute containing request body details.</param> |
| | | 1271 | | /// <param name="options">The KrFormOptions specifying allowed content types.</param> |
| | | 1272 | | /// <returns>An array of content type strings to be used for the form request body.</returns> |
| | | 1273 | | private static string[] ResolveFormContentTypes(OpenApiRequestBodyAttribute attribute, KrFormOptions options) |
| | | 1274 | | { |
| | | 1275 | | // if content type is specified on the attribute, use that |
| | 0 | 1276 | | if (attribute.ContentType is { Length: > 0 }) |
| | | 1277 | | { |
| | 0 | 1278 | | return attribute.ContentType; |
| | | 1279 | | } |
| | | 1280 | | |
| | | 1281 | | // if allowed content types are specified, use those |
| | 0 | 1282 | | if (options.AllowedContentTypes.Count > 0) |
| | | 1283 | | { |
| | 0 | 1284 | | return [.. options.AllowedContentTypes]; |
| | | 1285 | | } |
| | | 1286 | | // default to multipart/form-data |
| | 0 | 1287 | | return ["multipart/form-data"]; |
| | | 1288 | | } |
| | | 1289 | | |
| | | 1290 | | private static bool IsMultipartContentType(string contentType) |
| | 0 | 1291 | | => contentType.StartsWith("multipart/", StringComparison.OrdinalIgnoreCase); |
| | | 1292 | | |
| | | 1293 | | private static Dictionary<string, OpenApiEncoding>? BuildMultipartEncoding(KrFormOptions options) |
| | | 1294 | | { |
| | 0 | 1295 | | var encoding = new Dictionary<string, OpenApiEncoding>(StringComparer.Ordinal); |
| | | 1296 | | |
| | 0 | 1297 | | foreach (var rule in options.Rules) |
| | | 1298 | | { |
| | 0 | 1299 | | if (string.IsNullOrWhiteSpace(rule.Name)) |
| | | 1300 | | { |
| | | 1301 | | continue; |
| | | 1302 | | } |
| | | 1303 | | |
| | 0 | 1304 | | if (!IsProbablyFileRule(rule)) |
| | | 1305 | | { |
| | | 1306 | | continue; |
| | | 1307 | | } |
| | | 1308 | | |
| | 0 | 1309 | | if (rule.AllowedContentTypes.Count == 0) |
| | | 1310 | | { |
| | | 1311 | | continue; |
| | | 1312 | | } |
| | | 1313 | | |
| | 0 | 1314 | | encoding[rule.Name] = new OpenApiEncoding |
| | 0 | 1315 | | { |
| | 0 | 1316 | | ContentType = string.Join(", ", rule.AllowedContentTypes) |
| | 0 | 1317 | | }; |
| | | 1318 | | } |
| | | 1319 | | |
| | 0 | 1320 | | return encoding.Count > 0 ? encoding : null; |
| | | 1321 | | } |
| | | 1322 | | |
| | | 1323 | | private static bool IsProbablyFileRule(KrFormPartRule rule) |
| | | 1324 | | { |
| | 0 | 1325 | | if (rule.StoreToDisk) |
| | | 1326 | | { |
| | 0 | 1327 | | return true; |
| | | 1328 | | } |
| | | 1329 | | |
| | 0 | 1330 | | if (rule.AllowedExtensions.Count > 0) |
| | | 1331 | | { |
| | 0 | 1332 | | return true; |
| | | 1333 | | } |
| | | 1334 | | |
| | 0 | 1335 | | foreach (var ct in rule.AllowedContentTypes) |
| | | 1336 | | { |
| | 0 | 1337 | | if (string.IsNullOrWhiteSpace(ct)) |
| | | 1338 | | { |
| | | 1339 | | continue; |
| | | 1340 | | } |
| | | 1341 | | |
| | 0 | 1342 | | if (!ct.StartsWith("text/", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1343 | | && !ct.Equals("application/json", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1344 | | && !ct.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) |
| | | 1345 | | { |
| | 0 | 1346 | | return true; |
| | | 1347 | | } |
| | | 1348 | | } |
| | | 1349 | | |
| | 0 | 1350 | | return false; |
| | 0 | 1351 | | } |
| | | 1352 | | |
| | | 1353 | | /// <summary> |
| | | 1354 | | /// Applies the preferred request body from components to the function's OpenAPI metadata. |
| | | 1355 | | /// </summary> |
| | | 1356 | | /// <param name="help">The comment help information.</param> |
| | | 1357 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1358 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 1359 | | /// <param name="paramInfo">The parameter information.</param> |
| | | 1360 | | /// <param name="attribute">The OpenApiRequestBody attribute containing request body details.</param> |
| | | 1361 | | private void ApplyPreferredRequestBody( |
| | | 1362 | | CommentHelpInfo help, |
| | | 1363 | | MapRouteOptions routeOptions, |
| | | 1364 | | OpenAPIPathMetadata metadata, |
| | | 1365 | | ParameterMetadata paramInfo, |
| | | 1366 | | OpenApiRequestBodyAttribute attribute) |
| | | 1367 | | { |
| | 0 | 1368 | | var componentRequestBody = GetRequestBody(paramInfo.ParameterType.Name); |
| | | 1369 | | |
| | 0 | 1370 | | metadata.RequestBody = attribute.Inline |
| | 0 | 1371 | | ? componentRequestBody.Clone() |
| | 0 | 1372 | | : new OpenApiRequestBodyReference(paramInfo.ParameterType.Name); |
| | | 1373 | | |
| | 0 | 1374 | | metadata.RequestBody.Description ??= help.GetParameterDescription(paramInfo.Name); |
| | 0 | 1375 | | routeOptions.ScriptCode.Parameters.Add(new ParameterForInjectionInfo(paramInfo, componentRequestBody, routeOptio |
| | 0 | 1376 | | } |
| | | 1377 | | #endregion |
| | | 1378 | | |
| | | 1379 | | /// <summary> |
| | | 1380 | | /// Ensures that the OpenAPIPathMetadata has default responses defined. |
| | | 1381 | | /// </summary> |
| | | 1382 | | /// <param name="metadata">The OpenAPI metadata to update.</param> |
| | | 1383 | | private static void EnsureDefaultResponses(OpenAPIPathMetadata metadata) |
| | | 1384 | | { |
| | 0 | 1385 | | metadata.Responses ??= []; |
| | 0 | 1386 | | if (metadata.Responses.Count > 0) |
| | | 1387 | | { |
| | 0 | 1388 | | return; |
| | | 1389 | | } |
| | 0 | 1390 | | if (metadata.IsOpenApiCallback) |
| | | 1391 | | { |
| | 0 | 1392 | | metadata.Responses.Add("204", new OpenApiResponse { Description = "Accepted" }); |
| | | 1393 | | } |
| | | 1394 | | else |
| | | 1395 | | { |
| | 0 | 1396 | | metadata.Responses.Add("200", new OpenApiResponse { Description = "Ok" }); |
| | 0 | 1397 | | metadata.Responses.Add("default", new OpenApiResponse { Description = "Unexpected error" }); |
| | | 1398 | | } |
| | 0 | 1399 | | } |
| | | 1400 | | |
| | | 1401 | | /// <summary> |
| | | 1402 | | /// Finalizes the route options by adding OpenAPI metadata and configuring defaults. |
| | | 1403 | | /// </summary> |
| | | 1404 | | /// <param name="func">The function information.</param> |
| | | 1405 | | /// <param name="sb">The script block.</param> |
| | | 1406 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 1407 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1408 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1409 | | private void FinalizeRouteOptions( |
| | | 1410 | | FunctionInfo func, |
| | | 1411 | | ScriptBlock sb, |
| | | 1412 | | OpenAPIPathMetadata metadata, |
| | | 1413 | | MapRouteOptions routeOptions, |
| | | 1414 | | HttpVerb parsedVerb) |
| | | 1415 | | { |
| | 0 | 1416 | | metadata.DocumentId ??= Host.OpenApiDocumentIds; |
| | 0 | 1417 | | var documentIds = metadata.DocumentId; |
| | 0 | 1418 | | if (metadata.IsOpenApiPath) |
| | | 1419 | | { |
| | 0 | 1420 | | FinalizePathRouteOptions(func, sb, metadata, routeOptions, parsedVerb); |
| | 0 | 1421 | | return; |
| | | 1422 | | } |
| | | 1423 | | |
| | 0 | 1424 | | if (metadata.IsOpenApiWebhook) |
| | | 1425 | | { |
| | 0 | 1426 | | RegisterWebhook(func, sb, metadata, parsedVerb, documentIds); |
| | 0 | 1427 | | return; |
| | | 1428 | | } |
| | | 1429 | | |
| | 0 | 1430 | | if (metadata.IsOpenApiCallback) |
| | | 1431 | | { |
| | 0 | 1432 | | RegisterCallback(func, sb, metadata, parsedVerb, documentIds); |
| | | 1433 | | } |
| | 0 | 1434 | | } |
| | | 1435 | | |
| | | 1436 | | /// <summary> |
| | | 1437 | | /// Finalizes the route options for a standard OpenAPI path. |
| | | 1438 | | /// </summary> |
| | | 1439 | | /// <param name="func">The function information.</param> |
| | | 1440 | | /// <param name="sb">The script block.</param> |
| | | 1441 | | /// <param name="metadata">The OpenAPI metadata.</param> |
| | | 1442 | | /// <param name="routeOptions">The route options to update.</param> |
| | | 1443 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1444 | | private void FinalizePathRouteOptions( |
| | | 1445 | | FunctionInfo func, |
| | | 1446 | | ScriptBlock sb, |
| | | 1447 | | OpenAPIPathMetadata metadata, |
| | | 1448 | | MapRouteOptions routeOptions, |
| | | 1449 | | HttpVerb parsedVerb) |
| | | 1450 | | { |
| | 0 | 1451 | | routeOptions.OpenAPI.Add(parsedVerb, metadata); |
| | | 1452 | | |
| | 0 | 1453 | | if (string.IsNullOrWhiteSpace(routeOptions.Pattern)) |
| | | 1454 | | { |
| | 0 | 1455 | | routeOptions.Pattern = "/" + func.Name; |
| | | 1456 | | } |
| | | 1457 | | |
| | 0 | 1458 | | if (!string.IsNullOrWhiteSpace(metadata.CorsPolicy)) |
| | | 1459 | | { |
| | 0 | 1460 | | routeOptions.CorsPolicy = metadata.CorsPolicy; |
| | | 1461 | | } |
| | | 1462 | | |
| | | 1463 | | // Set the script block or wrap for form options |
| | 0 | 1464 | | routeOptions.ScriptCode.ScriptBlock = sb; |
| | 0 | 1465 | | routeOptions.IsOpenApiAnnotatedFunctionRoute = true; |
| | 0 | 1466 | | routeOptions.DefaultResponseContentType ??= new Dictionary<string, ICollection<ContentTypeWithSchema>>(Host.Opti |
| | 0 | 1467 | | _ = Host.AddMapRoute(routeOptions); |
| | 0 | 1468 | | } |
| | | 1469 | | |
| | | 1470 | | /// <summary> |
| | | 1471 | | /// Registers a webhook in the OpenAPI document descriptors. |
| | | 1472 | | /// </summary> |
| | | 1473 | | /// <param name="func">The function information.</param> |
| | | 1474 | | /// <param name="sb">The script block.</param> |
| | | 1475 | | /// <param name="metadata">The OpenAPI path metadata.</param> |
| | | 1476 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1477 | | /// <param name="documentIds">The collection of OpenAPI document IDs.</param> |
| | | 1478 | | private void RegisterWebhook(FunctionInfo func, ScriptBlock sb, OpenAPIPathMetadata metadata, HttpVerb parsedVerb, I |
| | | 1479 | | { |
| | 0 | 1480 | | EnsureParamOnlyScriptBlock(func, sb, kind: "webhook"); |
| | 0 | 1481 | | foreach (var docId in documentIds) |
| | | 1482 | | { |
| | 0 | 1483 | | var docdesc = GetDocDescriptorOrThrow(docId, attributeName: "OpenApiWebhook"); |
| | 0 | 1484 | | _ = docdesc.WebHook.TryAdd((metadata.Pattern, parsedVerb), metadata); |
| | | 1485 | | } |
| | 0 | 1486 | | } |
| | | 1487 | | /// <summary> |
| | | 1488 | | /// Registers a callback in the OpenAPI document descriptors. |
| | | 1489 | | /// </summary> |
| | | 1490 | | /// <param name="func">The function information.</param> |
| | | 1491 | | /// <param name="sb">The script block.</param> |
| | | 1492 | | /// <param name="metadata">The OpenAPI path metadata.</param> |
| | | 1493 | | /// <param name="parsedVerb">The HTTP verb parsed from the function.</param> |
| | | 1494 | | /// <param name="documentIds">The collection of OpenAPI document IDs.</param> |
| | | 1495 | | private void RegisterCallback(FunctionInfo func, ScriptBlock sb, OpenAPIPathMetadata metadata, HttpVerb parsedVerb, |
| | | 1496 | | { |
| | 0 | 1497 | | EnsureParamOnlyScriptBlock(func, sb, kind: "callback"); |
| | 0 | 1498 | | foreach (var docId in documentIds) |
| | | 1499 | | { |
| | 0 | 1500 | | var docdesc = GetDocDescriptorOrThrow(docId, attributeName: "OpenApiCallback"); |
| | 0 | 1501 | | _ = docdesc.Callbacks.TryAdd((metadata.Pattern, parsedVerb), metadata); |
| | | 1502 | | } |
| | 0 | 1503 | | } |
| | | 1504 | | |
| | | 1505 | | /// <summary> |
| | | 1506 | | /// Retrieves the OpenApiDocDescriptor for the specified document ID or throws an exception if not found. |
| | | 1507 | | /// </summary> |
| | | 1508 | | /// <param name="docId">The document ID to look up.</param> |
| | | 1509 | | /// <param name="attributeName">The name of the attribute requesting the document.</param> |
| | | 1510 | | /// <returns>The corresponding OpenApiDocDescriptor.</returns> |
| | | 1511 | | private OpenApiDocDescriptor GetDocDescriptorOrThrow(string docId, string attributeName) |
| | | 1512 | | { |
| | 0 | 1513 | | return Host.OpenApiDocumentDescriptor.TryGetValue(docId, out var docdesc) |
| | 0 | 1514 | | ? docdesc |
| | 0 | 1515 | | : throw new InvalidOperationException($"The OpenAPI document ID '{docId}' specified in the {attributeName} a |
| | | 1516 | | } |
| | | 1517 | | |
| | | 1518 | | /// <summary> |
| | | 1519 | | /// Ensures that the ScriptBlock contains only a param() block with no executable statements. |
| | | 1520 | | /// </summary> |
| | | 1521 | | /// <param name="func">The function information.</param> |
| | | 1522 | | /// <param name="sb">The ScriptBlock to validate.</param> |
| | | 1523 | | /// <param name="kind">The kind of function (e.g., "webhook" or "callback").</param> |
| | | 1524 | | /// <exception cref="InvalidOperationException">Thrown if the ScriptBlock contains executable statements other than |
| | | 1525 | | private static void EnsureParamOnlyScriptBlock(FunctionInfo func, ScriptBlock sb, string kind) |
| | | 1526 | | { |
| | 0 | 1527 | | if (!PsScriptBlockValidation.IsParamLast(sb)) |
| | | 1528 | | { |
| | 0 | 1529 | | throw new InvalidOperationException($"The ScriptBlock for {kind} function '{func.Name}' must contain only a |
| | | 1530 | | } |
| | 0 | 1531 | | } |
| | | 1532 | | |
| | | 1533 | | /// <summary> |
| | | 1534 | | /// Creates a request body from the given attribute. |
| | | 1535 | | /// </summary> |
| | | 1536 | | /// <param name="attribute">The attribute containing request body information.</param> |
| | | 1537 | | /// <param name="requestBody">The OpenApiRequestBody object to populate.</param> |
| | | 1538 | | /// <param name="schema">The schema to associate with the request body.</param> |
| | | 1539 | | /// <returns>True if the request body was created successfully; otherwise, false.</returns> |
| | | 1540 | | private static bool CreateRequestBodyFromAttribute(KestrunAnnotation attribute, OpenApiRequestBody requestBody, IOpe |
| | | 1541 | | { |
| | | 1542 | | switch (attribute) |
| | | 1543 | | { |
| | | 1544 | | case OpenApiRequestBodyAttribute request: |
| | 0 | 1545 | | requestBody.Description = request.Description; |
| | 0 | 1546 | | requestBody.Required = request.Required; |
| | | 1547 | | // Content |
| | 0 | 1548 | | requestBody.Content ??= new Dictionary<string, IOpenApiMediaType>(StringComparer.Ordinal); |
| | 0 | 1549 | | var mediaType = new OpenApiMediaType(); |
| | | 1550 | | // Example |
| | 0 | 1551 | | if (request.Example is not null) |
| | | 1552 | | { |
| | 0 | 1553 | | mediaType.Example = OpenApiJsonNodeFactory.ToNode(request.Example); |
| | | 1554 | | } |
| | | 1555 | | // Schema |
| | 0 | 1556 | | mediaType.Schema = schema; |
| | 0 | 1557 | | foreach (var contentType in request.ContentType) |
| | | 1558 | | { |
| | 0 | 1559 | | requestBody.Content[contentType] = mediaType; |
| | | 1560 | | } |
| | 0 | 1561 | | return true; |
| | | 1562 | | default: |
| | 0 | 1563 | | return false; |
| | | 1564 | | } |
| | | 1565 | | } |
| | | 1566 | | } |