| | | 1 | | using System.Collections.Immutable; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.CodeAnalysis.Scripting; |
| | | 5 | | using Microsoft.CodeAnalysis.VisualBasic; |
| | | 6 | | using Serilog.Events; |
| | | 7 | | using Microsoft.CodeAnalysis; |
| | | 8 | | using Kestrun.Utilities; |
| | | 9 | | using System.Security.Claims; |
| | | 10 | | using Kestrun.Logging; |
| | | 11 | | using Kestrun.SharedState; |
| | | 12 | | using Kestrun.Hosting; |
| | | 13 | | |
| | | 14 | | namespace Kestrun.Languages; |
| | | 15 | | |
| | | 16 | | |
| | | 17 | | internal static class VBNetDelegateBuilder |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// The marker that indicates where user code starts in the VB.NET script. |
| | | 21 | | /// This is used to ensure that the user code is correctly placed within the generated module. |
| | | 22 | | /// </summary> |
| | | 23 | | private const string StartMarker = "' ---- User code starts here ----"; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Builds a VB.NET delegate for Kestrun routes. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <remarks> |
| | | 29 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 30 | | /// </remarks> |
| | | 31 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 32 | | /// <param name="code">The VB.NET code to compile.</param> |
| | | 33 | | /// <param name="args">The arguments to pass to the script.</param> |
| | | 34 | | /// <param name="extraImports">Optional additional namespaces to import in the script.</param> |
| | | 35 | | /// <param name="extraRefs">Optional additional assemblies to reference in the script.</param> |
| | | 36 | | /// <param name="languageVersion">The VB.NET language version to use for compilation.</param> |
| | | 37 | | /// <returns>A delegate that takes CsGlobals and returns a Task.</returns> |
| | | 38 | | /// <exception cref="CompilationErrorException">Thrown if the compilation fails with errors.</exception> |
| | | 39 | | /// <remarks> |
| | | 40 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 41 | | /// </remarks> |
| | | 42 | | internal static RequestDelegate Build(KestrunHost host, |
| | | 43 | | string code, Dictionary<string, object?>? args, string[]? extraImports, |
| | | 44 | | Assembly[]? extraRefs, LanguageVersion languageVersion = LanguageVersion.VisualBasic16_9) |
| | | 45 | | { |
| | 5 | 46 | | var log = host.Logger; |
| | 5 | 47 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 48 | | { |
| | 4 | 49 | | log.Debug("Building VB.NET delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, lang= |
| | 4 | 50 | | code.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | // Validate inputs |
| | 5 | 54 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 55 | | { |
| | 1 | 56 | | throw new ArgumentNullException(nameof(code), "VB.NET code cannot be null or whitespace."); |
| | | 57 | | } |
| | | 58 | | // 1. Compile the VB.NET code into a script |
| | | 59 | | // - Use VisualBasicScript.Create() to create a script with the provided code |
| | | 60 | | // - Use ScriptOptions to specify imports, references, and language version |
| | | 61 | | // - Inject the provided arguments into the globals |
| | 4 | 62 | | var script = Compile<bool>(code, log, extraImports, extraRefs, null, languageVersion); |
| | | 63 | | |
| | | 64 | | // 2. Build the per-request delegate |
| | | 65 | | // - This delegate will be executed for each request |
| | | 66 | | // - It will create a KestrunContext and CsGlobals, then execute the script with these globals |
| | | 67 | | // - The script can access the request context and shared state store |
| | 4 | 68 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 69 | | { |
| | 3 | 70 | | log.Debug("C# delegate built successfully, script length={Length}, imports={ImportsCount}, refs={RefsCount}, |
| | 3 | 71 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 72 | | } |
| | | 73 | | |
| | 4 | 74 | | return async ctx => |
| | 4 | 75 | | { |
| | 4 | 76 | | try |
| | 4 | 77 | | { |
| | 3 | 78 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 79 | | { |
| | 2 | 80 | | log.Debug("Preparing execution for C# script at {Path}", ctx.Request.Path); |
| | 4 | 81 | | } |
| | 4 | 82 | | |
| | 3 | 83 | | var (Globals, Response, Context) = await DelegateBuilder.PrepareExecutionAsync(host, ctx, args).Configur |
| | 4 | 84 | | |
| | 4 | 85 | | // Execute the script with the current context and shared state |
| | 3 | 86 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 87 | | { |
| | 2 | 88 | | log.DebugSanitized("Executing VB.NET script for {Path}", ctx.Request.Path); |
| | 4 | 89 | | } |
| | 4 | 90 | | |
| | 3 | 91 | | _ = await script(Globals).ConfigureAwait(false); |
| | 3 | 92 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 93 | | { |
| | 2 | 94 | | log.DebugSanitized("VB.NET script executed successfully for {Path}", ctx.Request.Path); |
| | 4 | 95 | | } |
| | 4 | 96 | | |
| | 4 | 97 | | // Apply the response to the Kestrun context |
| | 3 | 98 | | await DelegateBuilder.ApplyResponseAsync(ctx, Response, log).ConfigureAwait(false); |
| | 3 | 99 | | } |
| | 4 | 100 | | finally |
| | 4 | 101 | | { |
| | 4 | 102 | | // Do not complete the response here; allow downstream middleware (e.g., StatusCodePages) |
| | 4 | 103 | | // to produce a body for status-only responses when needed. |
| | 4 | 104 | | } |
| | 7 | 105 | | }; |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | /// <summary> |
| | | 109 | | /// Decide the VB return type string that matches TResult |
| | | 110 | | /// </summary> |
| | | 111 | | /// <param name="t">The type to get the VB return type for.</param> |
| | | 112 | | /// <returns> The VB.NET return type as a string.</returns> |
| | | 113 | | private static string GetVbReturnType(Type t) |
| | | 114 | | { |
| | 13 | 115 | | if (t == typeof(bool)) |
| | | 116 | | { |
| | 8 | 117 | | return "Boolean"; |
| | | 118 | | } |
| | | 119 | | |
| | 5 | 120 | | if (t == typeof(IEnumerable<Claim>)) |
| | | 121 | | { |
| | 3 | 122 | | return "System.Collections.Generic.IEnumerable(Of System.Security.Claims.Claim)"; |
| | | 123 | | } |
| | | 124 | | |
| | | 125 | | // Fallback so it still compiles even for object / string / etc. |
| | 2 | 126 | | return "Object"; |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary> |
| | | 130 | | /// Compiles the provided VB.NET code into a delegate that can be executed with CsGlobals. |
| | | 131 | | /// </summary> |
| | | 132 | | /// <param name="code">The VB.NET code to compile.</param> |
| | | 133 | | /// <param name="log">The logger to use for logging compilation errors and warnings.</param> |
| | | 134 | | /// <param name="extraImports">Optional additional namespaces to import in the script.</param> |
| | | 135 | | /// <param name="extraRefs">Optional additional assemblies to reference in the script.</param> |
| | | 136 | | /// <param name="locals">Optional local variables to provide to the script.</param> |
| | | 137 | | /// <param name="languageVersion">The VB.NET language version to use for compilation.</param> |
| | | 138 | | /// <returns>A delegate that takes CsGlobals and returns a Task.</returns> |
| | | 139 | | /// <exception cref="CompilationErrorException">Thrown if the compilation fails with errors.</exception> |
| | | 140 | | /// <remarks> |
| | | 141 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 142 | | /// </remarks> |
| | | 143 | | internal static Func<CsGlobals, Task<TResult>> Compile<TResult>( |
| | | 144 | | string? code, Serilog.ILogger log, string[]? extraImports, |
| | | 145 | | Assembly[]? extraRefs, IReadOnlyDictionary<string, object?>? locals, LanguageVersion languageVersion |
| | | 146 | | ) |
| | | 147 | | { |
| | 13 | 148 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 149 | | { |
| | 10 | 150 | | log.Debug("Building VB.NET delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, lang= |
| | 10 | 151 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | // Validate inputs |
| | 13 | 155 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 156 | | { |
| | 0 | 157 | | throw new ArgumentNullException(nameof(code), "VB.NET code cannot be null or whitespace."); |
| | | 158 | | } |
| | | 159 | | |
| | 13 | 160 | | extraImports ??= []; |
| | 13 | 161 | | extraImports = [.. extraImports, "System.Collections.Generic", "System.Linq", "System.Security.Claims"]; |
| | | 162 | | |
| | | 163 | | // Discover dynamic namespaces from globals + locals similar to C# path |
| | 13 | 164 | | var dynamicImports = CollectDynamicImports(locals); |
| | 13 | 165 | | if (dynamicImports.Count > 0) |
| | | 166 | | { |
| | 11 | 167 | | var mergedImports = extraImports.Concat(dynamicImports) |
| | 11 | 168 | | .Distinct(StringComparer.Ordinal) |
| | 11 | 169 | | .ToArray(); |
| | 11 | 170 | | if (log.IsEnabled(LogEventLevel.Debug) && mergedImports.Length != extraImports.Length) |
| | | 171 | | { |
| | 8 | 172 | | log.Debug("Added {Count} dynamic VB imports from globals/locals.", mergedImports.Length - extraImports.L |
| | | 173 | | } |
| | 11 | 174 | | extraImports = mergedImports; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | // 🔧 1. Build a real VB file around the user snippet |
| | 13 | 178 | | var source = BuildWrappedSource(code, extraImports, vbReturnType: GetVbReturnType(typeof(TResult)), |
| | 13 | 179 | | locals: locals); |
| | | 180 | | |
| | | 181 | | // Prepares the source code for compilation. |
| | 13 | 182 | | var startLine = GetStartLineOrThrow(source, log); |
| | | 183 | | |
| | | 184 | | // Parse the source code into a syntax tree |
| | | 185 | | // This will allow us to analyze and compile the code |
| | 13 | 186 | | var tree = VisualBasicSyntaxTree.ParseText( |
| | 13 | 187 | | source, |
| | 13 | 188 | | new VisualBasicParseOptions(LanguageVersion.VisualBasic16)); |
| | | 189 | | |
| | | 190 | | // 🔧 2. References = everything already loaded + extras |
| | 13 | 191 | | var refs = BuildMetadataReferences(extraRefs); |
| | | 192 | | // 🔧 3. Normal DLL compilation |
| | 13 | 193 | | var compilation = VisualBasicCompilation.Create( |
| | 13 | 194 | | assemblyName: $"RouteScript_{Guid.NewGuid():N}", |
| | 13 | 195 | | syntaxTrees: [tree], |
| | 13 | 196 | | references: refs, |
| | 13 | 197 | | options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); |
| | | 198 | | |
| | 13 | 199 | | using var ms = new MemoryStream(); |
| | 13 | 200 | | var emitResult = compilation.Emit(ms) ?? throw new InvalidOperationException("Failed to compile VB.NET script.") |
| | | 201 | | // 🔧 4. Log the compilation result |
| | 13 | 202 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 203 | | { |
| | 10 | 204 | | log.Debug("VB.NET script compilation completed, assembly size={Size} bytes", ms.Length); |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // 🔧 5. Handle diagnostics |
| | 13 | 208 | | ThrowIfErrors(emitResult.Diagnostics, startLine, log); |
| | | 209 | | // Log any warnings from the compilation process |
| | 13 | 210 | | LogWarnings(emitResult.Diagnostics, startLine, log); |
| | | 211 | | |
| | | 212 | | // If there are no errors, log a debug message |
| | 13 | 213 | | if (emitResult.Success && log.IsEnabled(LogEventLevel.Debug)) |
| | | 214 | | { |
| | 10 | 215 | | log.Debug("VB.NET script compiled successfully with no errors."); |
| | | 216 | | } |
| | | 217 | | |
| | | 218 | | // If there are no errors, proceed to load the assembly and create the delegate |
| | 13 | 219 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 220 | | { |
| | 10 | 221 | | log.Debug("VB.NET script compiled successfully, loading assembly..."); |
| | | 222 | | } |
| | | 223 | | |
| | 13 | 224 | | ms.Position = 0; |
| | 13 | 225 | | return LoadDelegateFromAssembly<TResult>(ms.ToArray()); |
| | 13 | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Prepares the source code for compilation. |
| | | 230 | | /// </summary> |
| | | 231 | | /// <param name="source">The source code to prepare.</param> |
| | | 232 | | /// <param name="log">The logger instance.</param> |
| | | 233 | | /// <returns>The prepared source code.</returns> |
| | | 234 | | /// <exception cref="ArgumentException">Thrown when the source code is invalid.</exception> |
| | | 235 | | private static int GetStartLineOrThrow(string source, Serilog.ILogger log) |
| | | 236 | | { |
| | 13 | 237 | | var startIndex = source.IndexOf(StartMarker, StringComparison.Ordinal); |
| | 13 | 238 | | if (startIndex < 0) |
| | | 239 | | { |
| | 0 | 240 | | throw new ArgumentException($"VB.NET code must contain the marker '{StartMarker}' to indicate where user cod |
| | | 241 | | } |
| | | 242 | | |
| | 13 | 243 | | var startLine = CcUtilities.GetLineNumber(source, startIndex); |
| | 13 | 244 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 245 | | { |
| | 10 | 246 | | log.Debug("VB.NET script starts at line {LineNumber}", startLine); |
| | | 247 | | } |
| | | 248 | | |
| | 13 | 249 | | return startLine; |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | /// <summary> |
| | | 253 | | /// Prepares the metadata references for the VB.NET script. |
| | | 254 | | /// </summary> |
| | | 255 | | /// <param name="extraRefs">The extra references to include.</param> |
| | | 256 | | /// <returns>An enumerable of metadata references.</returns> |
| | | 257 | | private static IEnumerable<MetadataReference> BuildMetadataReferences(Assembly[]? extraRefs) |
| | | 258 | | { |
| | | 259 | | // NOTE: Some tests create throwaway assemblies in temp folders and then delete the folder. |
| | | 260 | | // On Windows the delete often fails (file still locked) so Assembly.Location continues to exist. |
| | | 261 | | // On Linux the delete succeeds; the Assembly remains loaded but its Location now points to a |
| | | 262 | | // non-existent path. Roslyn's MetadataReference.CreateFromFile will throw FileNotFoundException |
| | | 263 | | // in that scenario. We therefore skip any loaded assemblies whose Location no longer exists. |
| | 13 | 264 | | var baseRefs = AppDomain.CurrentDomain.GetAssemblies() |
| | 3959 | 265 | | .Where(a => !a.IsDynamic && SafeHasLocation(a)) |
| | 3379 | 266 | | .Select(a => MetadataReference.CreateFromFile(a.Location)); |
| | | 267 | | |
| | 13 | 268 | | var extras = extraRefs?.Select(r => MetadataReference.CreateFromFile(r.Location)) |
| | 13 | 269 | | ?? Enumerable.Empty<MetadataReference>(); |
| | | 270 | | |
| | | 271 | | // Always include the VB runtime explicitly then add our common baseline references. |
| | 13 | 272 | | return baseRefs |
| | 13 | 273 | | .Concat(extras) |
| | 13 | 274 | | .Append(MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.Constants).Assembly.Location)) |
| | 13 | 275 | | .Concat(DelegateBuilder.BuildBaselineReferences()); |
| | | 276 | | } |
| | | 277 | | |
| | | 278 | | /// <summary> |
| | | 279 | | /// Collects dynamic imports from the types of the provided locals and shared globals. |
| | | 280 | | /// </summary> |
| | | 281 | | /// <param name="locals">The local variables to inspect.</param> |
| | | 282 | | /// <returns>A set of unique namespace strings.</returns> |
| | | 283 | | private static HashSet<string> CollectDynamicImports(IReadOnlyDictionary<string, object?>? locals) |
| | | 284 | | { |
| | 13 | 285 | | var imports = new HashSet<string>(StringComparer.Ordinal); |
| | | 286 | | // Merge globals + locals (locals override) just for namespace harvesting |
| | 13 | 287 | | var globals = SharedStateStore.Snapshot(); |
| | 150 | 288 | | foreach (var g in globals) |
| | | 289 | | { |
| | 62 | 290 | | AddTypeNamespaces(g.Value?.GetType(), imports); |
| | | 291 | | } |
| | 13 | 292 | | if (locals is { Count: > 0 }) |
| | | 293 | | { |
| | 30 | 294 | | foreach (var l in locals) |
| | | 295 | | { |
| | 9 | 296 | | AddTypeNamespaces(l.Value?.GetType(), imports); |
| | | 297 | | } |
| | | 298 | | } |
| | 13 | 299 | | return imports; |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | private static void AddTypeNamespaces(Type? t, HashSet<string> set) |
| | | 303 | | { |
| | 89 | 304 | | if (t == null) |
| | | 305 | | { |
| | 35 | 306 | | return; |
| | | 307 | | } |
| | 54 | 308 | | if (!string.IsNullOrEmpty(t.Namespace)) |
| | | 309 | | { |
| | 54 | 310 | | _ = set.Add(t.Namespace!); |
| | | 311 | | } |
| | 54 | 312 | | if (t.IsGenericType) |
| | | 313 | | { |
| | 54 | 314 | | foreach (var ga in t.GetGenericArguments()) |
| | | 315 | | { |
| | 16 | 316 | | AddTypeNamespaces(ga, set); |
| | | 317 | | } |
| | | 318 | | } |
| | 54 | 319 | | if (t.IsArray) |
| | | 320 | | { |
| | 2 | 321 | | AddTypeNamespaces(t.GetElementType(), set); |
| | | 322 | | } |
| | 54 | 323 | | } |
| | | 324 | | private static bool SafeHasLocation(Assembly a) |
| | | 325 | | { |
| | | 326 | | try |
| | | 327 | | { |
| | 3927 | 328 | | var loc = a.Location; // may throw for some dynamic contexts |
| | 3927 | 329 | | return !string.IsNullOrEmpty(loc) && File.Exists(loc); |
| | | 330 | | } |
| | 0 | 331 | | catch |
| | | 332 | | { |
| | 0 | 333 | | return false; |
| | | 334 | | } |
| | 3927 | 335 | | } |
| | | 336 | | /// <summary> |
| | | 337 | | /// Logs any warnings from the compilation process. |
| | | 338 | | /// </summary> |
| | | 339 | | /// <param name="diagnostics">The diagnostics to check.</param> |
| | | 340 | | /// <param name="startLine">The starting line number.</param> |
| | | 341 | | /// <param name="log">The logger instance.</param> |
| | | 342 | | private static void LogWarnings(ImmutableArray<Diagnostic> diagnostics, int startLine, Serilog.ILogger log) |
| | | 343 | | { |
| | 108 | 344 | | var warnings = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | | 345 | | // If there are no warnings, log a debug message |
| | 13 | 346 | | if (warnings.Length == 0) |
| | | 347 | | { |
| | 9 | 348 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 349 | | { |
| | 8 | 350 | | log.Debug("VB.NET script compiled successfully with no warnings."); |
| | | 351 | | } |
| | | 352 | | |
| | 9 | 353 | | return; |
| | | 354 | | } |
| | | 355 | | |
| | 4 | 356 | | log.Warning($"VBNet script compilation completed with {warnings.Length} warning(s):"); |
| | 16 | 357 | | foreach (var warning in warnings) |
| | | 358 | | { |
| | 4 | 359 | | var location = warning.Location.IsInSource |
| | 4 | 360 | | ? $" at line {warning.Location.GetLineSpan().StartLinePosition.Line - startLine + 1}" |
| | 4 | 361 | | : ""; |
| | 4 | 362 | | log.Warning($" Warning [{warning.Id}]: {warning.GetMessage()}{location}"); |
| | | 363 | | } |
| | 4 | 364 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 365 | | { |
| | 2 | 366 | | log.Debug("VB.NET script compiled with warnings: {Count}", warnings.Length); |
| | | 367 | | } |
| | 4 | 368 | | } |
| | | 369 | | |
| | | 370 | | /// <summary> |
| | | 371 | | /// Throws an exception if there are compilation errors. |
| | | 372 | | /// </summary> |
| | | 373 | | /// <param name="diagnostics">The diagnostics to check.</param> |
| | | 374 | | /// <param name="startLine">The starting line number.</param> |
| | | 375 | | /// <param name="log">The logger instance.</param> |
| | | 376 | | private static void ThrowIfErrors(ImmutableArray<Diagnostic> diagnostics, int startLine, Serilog.ILogger log) |
| | | 377 | | { |
| | 108 | 378 | | var errors = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); |
| | 13 | 379 | | if (errors.Length == 0) |
| | | 380 | | { |
| | 13 | 381 | | return; |
| | | 382 | | } |
| | | 383 | | |
| | 0 | 384 | | log.Error($"VBNet script compilation completed with {errors.Length} error(s):"); |
| | 0 | 385 | | foreach (var error in errors) |
| | | 386 | | { |
| | 0 | 387 | | var location = error.Location.IsInSource |
| | 0 | 388 | | ? $" at line {error.Location.GetLineSpan().StartLinePosition.Line - startLine + 1}" |
| | 0 | 389 | | : ""; |
| | 0 | 390 | | log.Error($" Error [{error.Id}]: {error.GetMessage()}{location}"); |
| | | 391 | | } |
| | 0 | 392 | | throw new CompilationErrorException("VBNet route code compilation failed", diagnostics); |
| | | 393 | | } |
| | | 394 | | |
| | | 395 | | /// <summary> |
| | | 396 | | /// Loads a delegate from the provided assembly bytes. |
| | | 397 | | /// </summary> |
| | | 398 | | /// <typeparam name="TResult">The type of the result.</typeparam> |
| | | 399 | | /// <param name="asmBytes">The assembly bytes.</param> |
| | | 400 | | /// <returns>A delegate that can be invoked with the specified globals.</returns> |
| | | 401 | | private static Func<CsGlobals, Task<TResult>> LoadDelegateFromAssembly<TResult>(byte[] asmBytes) |
| | | 402 | | { |
| | 13 | 403 | | var asm = Assembly.Load(asmBytes); |
| | 13 | 404 | | var runMethod = asm.GetType("RouteScript")! |
| | 13 | 405 | | .GetMethod("Run", BindingFlags.Public | BindingFlags.Static)!; |
| | | 406 | | |
| | 13 | 407 | | var delegateType = typeof(Func<,>).MakeGenericType( |
| | 13 | 408 | | typeof(CsGlobals), |
| | 13 | 409 | | typeof(Task<>).MakeGenericType(typeof(TResult))); |
| | | 410 | | |
| | 13 | 411 | | return (Func<CsGlobals, Task<TResult>>)runMethod.CreateDelegate(delegateType); |
| | | 412 | | } |
| | | 413 | | |
| | | 414 | | /// <summary> |
| | | 415 | | /// Builds the wrapped source code for the VB.NET script. |
| | | 416 | | /// </summary> |
| | | 417 | | /// <param name="code">The user-provided code to wrap.</param> |
| | | 418 | | /// <param name="extraImports">Additional imports to include.</param> |
| | | 419 | | /// <param name="vbReturnType">The return type of the VB.NET function.</param> |
| | | 420 | | /// <param name="locals">Local variables to bind to the script.</param> |
| | | 421 | | /// <returns>The wrapped source code.</returns> |
| | | 422 | | private static string BuildWrappedSource(string? code, IEnumerable<string>? extraImports, |
| | | 423 | | string vbReturnType, IReadOnlyDictionary<string, object?>? locals = null |
| | | 424 | | ) |
| | | 425 | | { |
| | 13 | 426 | | var sb = new StringBuilder(); |
| | | 427 | | |
| | | 428 | | // common + caller-supplied Imports |
| | 13 | 429 | | var builtIns = new[] { |
| | 13 | 430 | | "System", "System.Threading.Tasks", |
| | 13 | 431 | | "Kestrun", "Kestrun.Models", |
| | 13 | 432 | | "Microsoft.VisualBasic", |
| | 13 | 433 | | "Kestrun.Languages" |
| | 13 | 434 | | }; |
| | | 435 | | |
| | 260 | 436 | | foreach (var ns in builtIns.Concat(extraImports ?? []) |
| | 13 | 437 | | .Distinct(StringComparer.Ordinal)) |
| | | 438 | | { |
| | 117 | 439 | | _ = sb.AppendLine($"Imports {ns}"); |
| | | 440 | | } |
| | | 441 | | |
| | 13 | 442 | | _ = sb.AppendLine($""" |
| | 13 | 443 | | Public Module RouteScript |
| | 13 | 444 | | Public Async Function Run(g As CsGlobals) As Task(Of {vbReturnType}) |
| | 13 | 445 | | Await Task.Yield() ' placeholder await |
| | 13 | 446 | | Dim Request = g.Context?.Request |
| | 13 | 447 | | Dim Response = g.Context?.Response |
| | 13 | 448 | | Dim Context = g.Context |
| | 13 | 449 | | """); |
| | | 450 | | |
| | | 451 | | // only emit these _when_ you called Compile with locals: |
| | 13 | 452 | | if (locals?.ContainsKey("username") ?? false) |
| | | 453 | | { |
| | 1 | 454 | | _ = sb.AppendLine(""" |
| | 1 | 455 | | ' only bind creds if someone passed them in |
| | 1 | 456 | | Dim username As String = CStr(g.Locals("username")) |
| | 1 | 457 | | """); |
| | | 458 | | } |
| | | 459 | | |
| | 13 | 460 | | if (locals?.ContainsKey("password") ?? false) |
| | | 461 | | { |
| | 1 | 462 | | _ = sb.AppendLine(""" |
| | 1 | 463 | | Dim password As String = CStr(g.Locals("password")) |
| | 1 | 464 | | """); |
| | | 465 | | } |
| | | 466 | | |
| | 13 | 467 | | if (locals?.ContainsKey("providedKey") == true) |
| | | 468 | | { |
| | 2 | 469 | | _ = sb.AppendLine(""" |
| | 2 | 470 | | ' only bind keys if someone passed them in |
| | 2 | 471 | | Dim providedKey As String = CStr(g.Locals("providedKey")) |
| | 2 | 472 | | """); |
| | | 473 | | } |
| | | 474 | | |
| | 13 | 475 | | if (locals?.ContainsKey("providedKeyBytes") == true) |
| | | 476 | | { |
| | 2 | 477 | | _ = sb.AppendLine(""" |
| | 2 | 478 | | Dim providedKeyBytes As Byte() = CType(g.Locals("providedKeyBytes"), Byte()) |
| | 2 | 479 | | """); |
| | | 480 | | } |
| | | 481 | | |
| | 13 | 482 | | if (locals?.ContainsKey("identity") == true) |
| | | 483 | | { |
| | 3 | 484 | | _ = sb.AppendLine(""" |
| | 3 | 485 | | Dim identity As String = CStr(g.Locals("identity")) |
| | 3 | 486 | | """); |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | // add the Marker for user code |
| | 13 | 490 | | _ = sb.AppendLine(StartMarker); |
| | | 491 | | // ---- User code starts here ---- |
| | | 492 | | |
| | 13 | 493 | | if (!string.IsNullOrEmpty(code)) |
| | | 494 | | { |
| | | 495 | | // indent the user snippet so VB is happy |
| | 13 | 496 | | _ = sb.AppendLine(string.Join( |
| | 13 | 497 | | Environment.NewLine, |
| | 28 | 498 | | code.Split('\n').Select(l => " " + l.TrimEnd('\r')))); |
| | | 499 | | } |
| | 13 | 500 | | _ = sb.AppendLine(""" |
| | 13 | 501 | | |
| | 13 | 502 | | End Function |
| | 13 | 503 | | End Module |
| | 13 | 504 | | """); |
| | 13 | 505 | | return sb.ToString(); |
| | | 506 | | } |
| | | 507 | | } |