| | 1 | | using Kestrun.Models; |
| | 2 | | using Microsoft.ClearScript.V8; |
| | 3 | | using Serilog.Events; |
| | 4 | |
|
| | 5 | | namespace Kestrun.Languages; |
| | 6 | | // --------------------------------------------------------------------------- |
| | 7 | | // Python delegate builder – now takes optional imports / references |
| | 8 | | // --------------------------------------------------------------------------- |
| | 9 | |
|
| | 10 | | internal static class JScriptDelegateBuilder |
| | 11 | | { |
| 2 | 12 | | public static bool Implemented { get; set; } |
| | 13 | | internal static RequestDelegate Build(string code, Serilog.ILogger logger) |
| | 14 | | { |
| 1 | 15 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | 16 | | { |
| 1 | 17 | | logger.Debug("Building JavaScript delegate, script length={Length}", code?.Length); |
| | 18 | | } |
| | 19 | |
|
| 1 | 20 | | if (!Implemented) |
| | 21 | | { |
| 1 | 22 | | throw new NotImplementedException("JavaScript scripting is not yet supported in Kestrun."); |
| | 23 | | } |
| | 24 | |
|
| 0 | 25 | | var engine = new V8ScriptEngine(); |
| 0 | 26 | | engine.AddHostType("KestrunResponse", typeof(KestrunResponse)); |
| 0 | 27 | | engine.Execute(code); // script defines global function handle(ctx, res) { ... } |
| | 28 | |
|
| 0 | 29 | | return async context => |
| 0 | 30 | | { |
| 0 | 31 | | var krRequest = await KestrunRequest.NewRequest(context); |
| 0 | 32 | | var krResponse = new KestrunResponse(krRequest); |
| 0 | 33 | | engine.Script.handle(context, krResponse); |
| 0 | 34 | |
|
| 0 | 35 | | if (!string.IsNullOrEmpty(krResponse.RedirectUrl)) |
| 0 | 36 | | { |
| 0 | 37 | | return; |
| 0 | 38 | | } |
| 0 | 39 | |
|
| 0 | 40 | | await krResponse.ApplyTo(context.Response); |
| 0 | 41 | | }; |
| | 42 | | } |
| | 43 | | } |