private static HttpRequestMessage CreateRequest(string url, JsValue?headers) { if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { throw new ArgumentException("Url must be an absolute URL"); } var request = new HttpRequestMessage(HttpMethod.Get, uri); if (headers != null && headers.Type == Types.Object) { var obj = headers.AsObject(); foreach (var(key, property) in obj.GetOwnProperties()) { var value = TypeConverter.ToString(property.Value); if (!string.IsNullOrWhiteSpace(key)) { request.Headers.TryAddWithoutValidation(key, value ?? string.Empty); } } } return(request); }
public Completion(string type, JsValue?value, string identifier, Exception ex = null, Jint.Parser.Ast.Statement stmt = null) { Type = type; Value = value; Identifier = identifier; statement = stmt; ExceptionLocation = ex; }
static string?AsString(JsValue?value, JsonInstance json, bool formatForRaw) { return(value switch { JsBoolean b => b.AsBoolean() ? "true" : "false", JsString s => formatForRaw ? $"\"{s.AsString()}\"": s.AsString(), JsNumber n => n.AsNumber().ToString(CultureInfo.InvariantCulture), JsNull => null, JsUndefined => null, { } v => json.Stringify(JsValue.Undefined, new[] { v }).AsString(), _ => null });
string?AsString(JsValue?value) { return(value switch { JsBoolean b => b.AsBoolean() ? "true" : "false", JsString s => s.AsString(), JsNumber n => n.AsNumber().ToString(CultureInfo.InvariantCulture), JsNull => null, JsUndefined => null, { } v => _json.Stringify(JsValue.Undefined, new[] { v }).AsString(), _ => null });
public PropertyDescriptor(JsValue?get, JsValue?set, bool?enumerable = null, bool?configurable = null) { Get = get; Set = set; if (enumerable.HasValue) { Enumerable = enumerable.Value; } if (configurable.HasValue) { Configurable = configurable.Value; } }
public PropertyDescriptor(JsValue?value, bool?writable, bool?enumerable, bool?configurable) { Value = value; if (writable.HasValue) { Writable = writable.Value; } if (enumerable.HasValue) { Enumerable = enumerable.Value; } if (configurable.HasValue) { Configurable = configurable.Value; } }
public static List <DomainId> ToIds(this JsValue?value) { var ids = new List <DomainId>(); if (value?.IsString() == true) { ids.Add(DomainId.Create(value.ToString())); } else if (value?.IsArray() == true) { foreach (var item in value.AsArray()) { if (item.IsString()) { ids.Add(DomainId.Create(item.ToString())); } } } return(ids); }
private async Task GetJsonAsync(ExecutionContext context, string url, Action <JsValue> callback, JsValue?headers) { context.MarkAsync(); try { using (var httpClient = httpClientFactory.CreateClient()) { var request = CreateRequest(url, headers); var response = await httpClient.SendAsync(request, context.CancellationToken); response.EnsureSuccessStatusCode(); var responseObject = await ParseResponse(context, response); context.Engine.ResetTimeoutTicks(); callback(responseObject); } } catch (Exception ex) { context.Fail(ex); } }
private void GetJson(ExecutionContext context, string url, Action <JsValue> callback, JsValue?headers) { GetJsonAsync(context, url, callback, headers).Forget(); }
private async Task GetJsonAsync(ExecutionContext context, string url, Action <JsValue> callback, JsValue?headers) { if (callback == null) { context.Fail(new JavaScriptException("Callback cannot be null.")); return; } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { context.Fail(new JavaScriptException("URL is not valid.")); return; } context.MarkAsync(); try { using (var httpClient = httpClientFactory.CreateClient()) { using (var request = CreateRequest(url, headers)) { using (var response = await httpClient.SendAsync(request, context.CancellationToken)) { response.EnsureSuccessStatusCode(); var responseObject = await ParseResponse(context, response); context.Engine.ResetConstraints(); callback(responseObject); } } } } catch (Exception ex) { context.Fail(ex); } }
public static IJsonValue Map(JsValue?value) { if (value == null || value.IsNull() || value.IsUndefined()) { return(JsonValue.Null); } if (value.IsString()) { return(JsonValue.Create(value.AsString())); } if (value.IsBoolean()) { return(JsonValue.Create(value.AsBoolean())); } if (value.IsNumber()) { return(JsonValue.Create(value.AsNumber())); } if (value.IsDate()) { return(JsonValue.Create(value.AsDate().ToString())); } if (value.IsRegExp()) { return(JsonValue.Create(value.AsRegExp().Value?.ToString())); } if (value.IsArray()) { var arr = value.AsArray(); var result = JsonValue.Array(); for (var i = 0; i < arr.Length; i++) { result.Add(Map(arr.Get(i.ToString(CultureInfo.InvariantCulture)))); } return(result); } if (value.IsObject()) { var obj = value.AsObject(); var result = JsonValue.Object(); foreach (var(key, propertyDescriptor) in obj.GetOwnProperties()) { result[key.AsString()] = Map(propertyDescriptor.Value); } return(result); } throw new ArgumentException("Invalid json type.", nameof(value)); }
private static HttpRequestMessage CreateRequest(ScriptExecutionContext context, HttpMethod method, Uri uri, JsValue?body, JsValue?headers) { var request = new HttpRequestMessage(method, uri); if (body != null) { var serializer = new JsonSerializer(context.Engine); var json = serializer.Serialize(body, JsValue.Undefined, JsValue.Undefined)?.ToString(); if (json != null) { request.Content = new StringContent(json, Encoding.UTF8, "text/json"); } } if (headers != null && headers.Type == Types.Object) { var obj = headers.AsObject(); foreach (var(key, property) in obj.GetOwnProperties()) { var value = TypeConverter.ToString(property.Value); var keyString = key.AsString(); if (!string.IsNullOrWhiteSpace(keyString)) { request.Headers.TryAddWithoutValidation(keyString, value ?? string.Empty); } } } return(request); }
public Completion(string type, JsValue?value, string identifier) { Type = type; Value = value; Identifier = identifier; }
private void GetBlurHash(ScriptExecutionContext context, JsValue input, Action <JsValue> callback, JsValue?componentX, JsValue?componentY) { Guard.NotNull(callback); context.Schedule(async(scheduler, ct) => { if (input is not ObjectWrapper objectWrapper) { scheduler.Run(callback, JsValue.FromObject(context.Engine, "ErrorNoAsset")); return; } async Task ResolveHashAsync(AssetRef asset) { if (asset.FileSize > 512_000 || asset.Type != AssetType.Image) { scheduler.Run(callback, JsValue.Null); return; } var options = new BlurOptions(); if (componentX?.IsNumber() == true) { options.ComponentX = (int)componentX.AsNumber(); } if (componentY?.IsNumber() == true) { options.ComponentX = (int)componentX.AsNumber(); } var assetThumbnailGenerator = serviceProvider.GetRequiredService <IAssetThumbnailGenerator>(); var assetFileStore = serviceProvider.GetRequiredService <IAssetFileStore>(); try { var hash = await asset.GetBlurHashAsync(options, assetFileStore, assetThumbnailGenerator, ct); scheduler.Run(callback, JsValue.FromObject(context.Engine, hash)); } catch { scheduler.Run(callback, JsValue.Null); } } switch (objectWrapper.Target) { case IAssetEntity asset: await ResolveHashAsync(asset.ToRef()); break; case EnrichedAssetEvent @event: await ResolveHashAsync(@event.ToRef()); break; default: scheduler.Run(callback, JsValue.FromObject(context.Engine, "ErrorNoAsset")); break; } }); }
private void GetText(ScriptExecutionContext context, JsValue input, Action <JsValue> callback, JsValue?encoding) { Guard.NotNull(callback); context.Schedule(async(scheduler, ct) => { if (input is not ObjectWrapper objectWrapper) { scheduler.Run(callback, JsValue.FromObject(context.Engine, "ErrorNoAsset")); return; } async Task ResolveAssetText(AssetRef asset) { if (asset.FileSize > 256_000) { scheduler.Run(callback, JsValue.FromObject(context.Engine, "ErrorTooBig")); return; } var assetFileStore = serviceProvider.GetRequiredService <IAssetFileStore>(); try { var text = await asset.GetTextAsync(encoding?.ToString(), assetFileStore, ct); scheduler.Run(callback, JsValue.FromObject(context.Engine, text)); } catch { scheduler.Run(callback, JsValue.Null); } } switch (objectWrapper.Target) { case IAssetEntity asset: await ResolveAssetText(asset.ToRef()); break; case EnrichedAssetEvent e: await ResolveAssetText(e.ToRef()); break; default: scheduler.Run(callback, JsValue.FromObject(context.Engine, "ErrorNoAsset")); break; } }); }
public Completion(string type, JsValue? value, string identifier) { _type = type; _value = value; _identifier = identifier; }
private async Task RequestAsync(ScriptExecutionContext context, HttpMethod method, string url, JsValue?body, Action <JsValue> callback, JsValue?headers) { if (callback == null) { context.Fail(new JavaScriptException("Callback cannot be null.")); return; } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { context.Fail(new JavaScriptException("URL is not valid.")); return; } context.MarkAsync(); try { using (var httpClient = httpClientFactory.CreateClient()) { using (var request = CreateRequest(context, method, uri, body, headers)) { using (var response = await httpClient.SendAsync(request, context.CancellationToken)) { response.EnsureSuccessStatusCode(); var responseObject = await ParseResponse(context, response); // Reset the time contraints and other constraints so that our awaiting does not count as script time. context.Engine.ResetConstraints(); callback(responseObject); } } } } catch (Exception ex) { context.Fail(ex); } }
static Object Clr(this JsValue?arg) { return(arg.HasValue ? arg.Value.ToObject() : null); }
private void Request(ScriptExecutionContext context, HttpMethod method, string url, JsValue?body, Action <JsValue> callback, JsValue?headers) { context.Schedule(async(scheduler, ct) => { if (callback == null) { throw new JavaScriptException("Callback cannot be null."); } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { throw new JavaScriptException("URL is not valid."); } using (var httpClient = httpClientFactory.CreateClient()) { using (var request = CreateRequest(context, method, uri, body, headers)) { using (var response = await httpClient.SendAsync(request, ct)) { response.EnsureSuccessStatusCode(); var responseObject = await ParseResponseasync(context, response, ct); scheduler.Run(callback, responseObject); } } } }); }