| | 1 | | using System.Collections.Immutable; |
| | 2 | | using System.Reflection; |
| | 3 | | using System.Text; |
| | 4 | | using Kestrun.Languages; |
| | 5 | | using Microsoft.CodeAnalysis; |
| | 6 | | using Microsoft.CodeAnalysis.CSharp; |
| | 7 | | using Microsoft.CodeAnalysis.CSharp.Scripting; |
| | 8 | | using Microsoft.CodeAnalysis.Scripting; |
| | 9 | | using Serilog.Events; |
| | 10 | | using Kestrun.Models; |
| | 11 | |
|
| | 12 | |
|
| | 13 | |
|
| | 14 | | namespace Kestrun.Hosting; |
| | 15 | |
|
| | 16 | | /// <summary> |
| | 17 | | /// Provides extension methods for validating C# scripts in the context of a KestrunHost. |
| | 18 | | /// </summary> |
| | 19 | | public static class KestrunHostScriptValidationExtensions |
| | 20 | | { |
| | 21 | | /// <summary> |
| | 22 | | /// Validates a C# script and returns compilation diagnostics without throwing exceptions. |
| | 23 | | /// Useful for testing scripts before adding routes. |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="host">The KestrunHost instance used for validation</param> |
| | 26 | | /// <param name="code">The C# script code to validate</param> |
| | 27 | | /// <param name="extraImports">Optional additional imports</param> |
| | 28 | | /// <param name="extraRefs">Optional additional assembly references</param> |
| | 29 | | /// <param name="languageVersion">C# language version to use</param> |
| | 30 | | /// <returns>Compilation diagnostics including errors and warnings</returns> |
| | 31 | | public static ImmutableArray<Diagnostic> ValidateCSharpScript( |
| | 32 | | this KestrunHost host, |
| | 33 | | string? code, |
| | 34 | | string[]? extraImports = null, |
| | 35 | | Assembly[]? extraRefs = null, |
| | 36 | | LanguageVersion languageVersion = LanguageVersion.CSharp12) |
| | 37 | | { |
| 18 | 38 | | if (host.HostLogger.IsEnabled(LogEventLevel.Debug)) |
| | 39 | | { |
| 18 | 40 | | host.HostLogger.Debug("ValidateCSharpScript() called: {@CodeLength}, imports={ImportsCount}, refs={RefsCount |
| 18 | 41 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | 42 | | } |
| | 43 | |
|
| | 44 | | try |
| | 45 | | { |
| | 46 | | // Use the same script options as BuildCsDelegate |
| 18 | 47 | | var opts = ScriptOptions.Default |
| 18 | 48 | | .WithImports("System", "System.Linq", "System.Threading.Tasks", "Microsoft.AspNetCore.Http") |
| 18 | 49 | | .WithReferences(typeof(HttpContext).Assembly, typeof(KestrunResponse).Assembly) |
| 18 | 50 | | .WithLanguageVersion(languageVersion); |
| | 51 | |
|
| 18 | 52 | | if (extraImports is { Length: > 0 }) |
| | 53 | | { |
| 1 | 54 | | opts = opts.WithImports(opts.Imports.Concat(extraImports)); |
| | 55 | | } |
| | 56 | |
|
| 18 | 57 | | if (extraRefs is { Length: > 0 }) |
| | 58 | | { |
| 0 | 59 | | opts = opts.WithReferences(opts.MetadataReferences |
| 0 | 60 | | .Concat(extraRefs.Select(r => MetadataReference.CreateFromFile(r.Location) |
| | 61 | | } |
| | 62 | |
|
| 18 | 63 | | var script = CSharpScript.Create(code, opts, typeof(CsGlobals)); |
| 17 | 64 | | return script.Compile(); |
| | 65 | | } |
| 1 | 66 | | catch (Exception ex) |
| | 67 | | { |
| | 68 | | // If there's an exception during script creation, create a synthetic diagnostic |
| 1 | 69 | | var diagnostic = Diagnostic.Create( |
| 1 | 70 | | new DiagnosticDescriptor( |
| 1 | 71 | | "KESTRUN001", |
| 1 | 72 | | "Script validation error", |
| 1 | 73 | | "Script validation failed: {0}", |
| 1 | 74 | | "Compilation", |
| 1 | 75 | | DiagnosticSeverity.Error, |
| 1 | 76 | | true), |
| 1 | 77 | | Location.None, |
| 1 | 78 | | ex.Message); |
| | 79 | |
|
| 1 | 80 | | return [diagnostic]; |
| | 81 | | } |
| 18 | 82 | | } |
| | 83 | |
|
| | 84 | | /// <summary> |
| | 85 | | /// Checks if a C# script has compilation errors. |
| | 86 | | /// </summary> |
| | 87 | | /// <param name="host">The KestrunHost instance used for validation</param> |
| | 88 | | /// <param name="code">The C# script code to check</param> |
| | 89 | | /// <param name="extraImports">Optional additional imports</param> |
| | 90 | | /// <param name="extraRefs">Optional additional assembly references</param> |
| | 91 | | /// <param name="languageVersion">C# language version to use</param> |
| | 92 | | /// <returns>True if the script compiles without errors, false otherwise</returns> |
| | 93 | | public static bool IsCSharpScriptValid( |
| | 94 | | this KestrunHost host, |
| | 95 | | string code, |
| | 96 | | string[]? extraImports = null, |
| | 97 | | Assembly[]? extraRefs = null, |
| | 98 | | LanguageVersion languageVersion = LanguageVersion.CSharp12) |
| | 99 | | { |
| 5 | 100 | | var diagnostics = host.ValidateCSharpScript(code, extraImports, extraRefs, languageVersion); |
| 7 | 101 | | return !diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); |
| | 102 | | } |
| | 103 | |
|
| | 104 | | /// <summary> |
| | 105 | | /// Gets formatted error information for a C# script. |
| | 106 | | /// </summary> |
| | 107 | | /// <param name="host">The KestrunHost instance used for validation</param> |
| | 108 | | /// <param name="code">The C# script code to check</param> |
| | 109 | | /// <param name="extraImports">Optional additional imports</param> |
| | 110 | | /// <param name="extraRefs">Optional additional assembly references</param> |
| | 111 | | /// <param name="languageVersion">C# language version to use</param> |
| | 112 | | /// <returns>Formatted error message, or null if no errors</returns> |
| | 113 | | public static string? GetCSharpScriptErrors(this KestrunHost host, |
| | 114 | | string code, |
| | 115 | | string[]? extraImports = null, |
| | 116 | | Assembly[]? extraRefs = null, |
| | 117 | | LanguageVersion languageVersion = LanguageVersion.CSharp12) |
| | 118 | | { |
| 3 | 119 | | if (host.HostLogger.IsEnabled(LogEventLevel.Debug)) |
| | 120 | | { |
| 3 | 121 | | host.HostLogger.Debug("GetCSharpScriptErrors() called: {@CodeLength}, imports={ImportsCount}, refs={RefsCoun |
| 3 | 122 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | 123 | | } |
| | 124 | |
|
| 3 | 125 | | var diagnostics = host.ValidateCSharpScript(code, extraImports, extraRefs, languageVersion); |
| 5 | 126 | | var errors = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); |
| | 127 | |
|
| 3 | 128 | | if (errors.Length == 0) |
| | 129 | | { |
| 1 | 130 | | return null; |
| | 131 | | } |
| | 132 | |
|
| | 133 | | try |
| | 134 | | { |
| | 135 | | // Create a temporary exception to format the errors |
| 2 | 136 | | var tempException = new Scripting.CompilationErrorException("Script validation errors:", diagnostics); |
| 2 | 137 | | return tempException.GetDetailedErrorMessage(); |
| | 138 | | } |
| 0 | 139 | | catch |
| | 140 | | { |
| | 141 | | // Fallback formatting if exception creation fails |
| 0 | 142 | | var sb = new StringBuilder(); |
| 0 | 143 | | _ = sb.AppendLine($"Script has {errors.Length} compilation error(s):"); |
| 0 | 144 | | for (var i = 0; i < errors.Length; i++) |
| | 145 | | { |
| 0 | 146 | | _ = sb.AppendLine($" {i + 1}. {errors[i].GetMessage()}"); |
| | 147 | | } |
| 0 | 148 | | return sb.ToString(); |
| | 149 | | } |
| 2 | 150 | | } |
| | 151 | | } |